Skip to content

Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster by executing routine tasks, explaining complex code, and handling git workflows - all through natural language commands.

TypeScript

telemetry: complete rows gathered through $, sent in batches, serving built-in plugins only (#95618)

Alice T'Poteat4564326dcaa6
diff --git a/mods/README.md b/mods/README.md
index f80ba955..ede3e373 100644
--- a/mods/README.md
+++ b/mods/README.md
@@ -9,7 +9,7 @@ source, published as it is built into the binary.
| --- | --- | --- |
| [`sec-default`](sec-default) | Keeps an organization's classic hooks, prompt content, managed settings and tool policy out of reach of the plugins a person installs; adds no policy of its own. | Outermost, on a machine with managed settings or for a Team or Enterprise organization, unless managed `prependPlugins` says otherwise |
| [`diff`](diff) | `/diff`: the session's uncommitted changes in a pane beside the transcript, file by file with their hunks, refreshed as Claude edits files and runs commands. | Built in |
-| [`telemetry`](telemetry) | Adds `$.telemetry` (`log`, `mark`) in the `engine.create` fold so a plugin can record an event as a first-party analytics row; sends nothing wherever Claude Code's analytics are off. | Built in |
+| [`telemetry`](telemetry) | Adds `$.telemetry` (`log`, `mark`) in the `engine.create` fold so a built-in plugin can record an event as a first-party analytics row, sent in batches; refuses installed plugins; sends nothing wherever Claude Code's analytics are off. | Built in |
| [`agents-md`](agents-md) | `AGENTS.md` as project instructions, by one option: loaded where the project has no `CLAUDE.md` of its own (`claude-md-or-agents-md`, the default) or beside it (`claude-md-and-agents-md`), placed and framed exactly as the engine places `CLAUDE.md`, nested ones on a `Read`; or the project's and the person's instruction files dropped and the organization's kept (`managed-only`); or `CLAUDE.md` alone, as the engine reads it (`claude-md`). | Built in |
Each folder is a complete plugin: `.claude-plugin/plugin.json`, a
diff --git a/mods/telemetry/.claude-plugin/plugin.json b/mods/telemetry/.claude-plugin/plugin.json
index f7861584..a65a3c2a 100644
--- a/mods/telemetry/.claude-plugin/plugin.json
+++ b/mods/telemetry/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "telemetry",
"version": "0.1.0",
- "description": "Plugin analytics: adds $.telemetry in the engine.create fold, so a plugin logs an event or marks a feature's use as one first-party row per call, sent with the session's own credential.",
+ "description": "Plugin analytics: adds $.telemetry in the engine.create fold, so a plugin logs an event or marks a feature's use as a first-party row, sent in batches with the session's own credential.",
"author": {
"name": "Anthropic"
},
diff --git a/mods/telemetry/README.md b/mods/telemetry/README.md
index 38c936a6..5bd450ab 100644
--- a/mods/telemetry/README.md
+++ b/mods/telemetry/README.md
@@ -1,32 +1,55 @@
# telemetry
Plugin analytics as a plugin: one `engine.create` step adds `$.telemetry` to
-the engine interface every plugin above it is handed, built over the
-`$.session` and `$.http` nouns beneath. `$.telemetry.log({ event, props })`
-sends one event as one first-party row, `tengu_plugin_<event>`;
-`$.telemetry.mark({ feature, kind, reason?, props? })` marks one use of a
-feature as the CLI's own feature events do, `tengu_feature_<kind>` with a
-`feature_name` and the mark's properties beside it. Each call is one POST to
-the event-logging ingest with the session's own credential
-(`$.session.authorize()`, resolved at each call), one attempt, nothing
-batched; a session with no first-party credential, or an ingest that
-refuses, rejects the caller's promise.
+the engine interface every plugin above it is handed, built over the nouns
+beneath, and a hook on its own two events serves the plugins built into
+Claude Code alone: a call from a plugin a person installed or an
+administrator listed is refused with a reason (the host stamps every call
+with the plugin that raised it, `next.origin`, and the gate reads its tier).
+`$.telemetry.log({ event, props })` queues one event as one first-party
+row, `tengu_plugin_<event>`; `$.telemetry.mark({ feature, kind, reason?,
+props? })` marks one use of a feature as the CLI's own feature events do,
+`tengu_feature_<kind>` with a `feature_name` and the mark's properties
+beside it. Both resolve once the row is queued. Rows go out in batches: one
+POST to the event-logging ingest with the session's own credential
+(`$.session.authorize()`, resolved for each batch) a few seconds after the
+first row was queued, at once when a hundred wait, and when the session
+ends; a batch the ingest refuses with a server error, a timeout or a rate
+limit is tried once more. A session with no first-party credential, or an
+ingest that still refuses, drops the batch; each outcome is one line in the
+debug log.
+
+Each row carries what the CLI's own rows carry, gathered through `$` once
+a session: an event id, the install's device id and the signed-in account's
+ids from the CLI's global config, the session's id, model, client type,
+entrypoint and interactivity, and an `env` block (platform and
+architecture from one `uname` probe, terminal, shell, package managers and
+runtimes, CI and GitHub Actions, the remote container, the deployment, the
+Linux distribution and kernel, WSL, the working directory's version
+control), with the repository's remote hash beside the row's properties.
+What the engine alone knows (its version and build time, its runtime's
+version, the process's memory, the request's betas, the subscription tier,
+the calling agent) is not on `$`, and those columns stay empty.
It sends nothing wherever the CLI's own analytics are off: under
`DISABLE_TELEMETRY`, `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` or
-`DO_NOT_TRACK`, on any third-party provider (Bedrock, Vertex, Foundry and
-kin), and on a deployment with its own OAuth URL. Each is read through
-`$.env` at every call, rows go one after another, and the credential is
-authorized afresh right before each POST, so a session that has since moved
-to a third-party provider or a cloud gateway sends nothing more. The row's
-`user_type` is `ant` when `USER_TYPE` says so, else `external`.
+`DO_NOT_TRACK`, in a test run, on any third-party provider (Bedrock,
+Vertex, Foundry and kin) the host does not manage, on a cloud gateway
+(the environment's switch or the managed policy's login pins), and on a
+deployment with its own OAuth URL. Each is read through `$.env` and
+`$.settings` before every batch, so a session that has since moved to a
+third-party provider or a gateway sends nothing more; when the switches
+cannot be read, nothing is sent either. The row's `user_type` is `ant`
+when `USER_TYPE` says so, else `external`.
Nothing free-form reaches a row. An event name and every property key is a
snake_case token; a value is a finite number, a boolean, or a Choice (a
string named together with the list it is chosen from), under `log` and
`mark` alike; `mark` takes `ok`, `sad` or `bad`, with a `reason` required on
the last two and refused on the first. An entry that breaks a rule is
-refused before anything is sent.
+refused before anything is queued. Of the environment, a variable whose
+value is a secret, or names a person or a host, is read for whether it is
+set and nothing more; a shell is its basename from a closed list.
`hooks/register.ts` is the module; `types/index.d.ts` is the noun's contract,
the one declaration of `$.telemetry` that this mod's hooks, a mod calling the
@@ -35,20 +58,26 @@ noun and a test answering it all read.
## What it hooks
`engine.create`: `{ ...await next(e), telemetry }`, so the noun is added and
-nothing beneath is replaced.
+nothing beneath is replaced. `telemetry.*`, the gate: a caller in the
+built-in tier (or the engine) goes on, any other is refused, and a gate
+that throws refuses too. `session.start`, to learn whether a person is at
+the prompt; `session.end`, to send what still waits.
## What it calls on `$`
-`session.authorize`, `session.id`, `session.model`, `http.fetch`, `env.get`
-(the switches above and `USER_TYPE`, by literal name), each on the
-interface the fold handed it.
+`session.authorize`, `session.id`, `session.model`, `session.surfaces`,
+`session.cwd`, `session.repo`, `settings.read`, `env.get` (the switches and
+the describing variables, by literal name), `fs.read`, `fs.list`,
+`fs.exists`, `process.run` (one `sh -c` of `uname` and `command -v`),
+`clock.after`, `clock.sleep`, `http.fetch` and `ui.log` (to the debug log),
+each on the interface the fold handed it.
-## Where it runs
+## Where it runs, whom it serves
-This plugin is seated by the CLI itself, on internal builds whose own
-analytics are on, and nowhere else: `session.authorize` exists only there,
-and the rows it writes join tables only the CLI's own events reach. It is
-not meant to be installed or loaded with `--plugin-dir`; the folder has a
-manifest so it reads like every other plugin, not so it can stand alone. A
-plugin that calls `$.telemetry` where this one is absent finds no such noun
-and should treat that as "no analytics here".
+This plugin is seated by the CLI itself, on every build whose own analytics
+are on, and nowhere else; it serves the plugins bundled with the CLI and
+refuses every other caller. It is not meant to be installed or loaded with
+`--plugin-dir`; the folder has a manifest so it reads like every other
+plugin, not so it can stand alone. A built-in that calls `$.telemetry`
+where this one is absent finds no such noun and should treat that as "no
+analytics here".
diff --git a/mods/telemetry/hooks/batching/batch-rows/batch-rows.ts b/mods/telemetry/hooks/batching/batch-rows/batch-rows.ts
new file mode 100644
index 00000000..244aa38a
--- /dev/null
+++ b/mods/telemetry/hooks/batching/batch-rows/batch-rows.ts
@@ -0,0 +1,5 @@
+/**
+ * The most rows one batch carries: a queue this full goes out at once
+ * rather than on the timer.
+ */
+export const BATCH_ROWS = 100
diff --git a/mods/telemetry/hooks/batching/batch-rows/index.ts b/mods/telemetry/hooks/batching/batch-rows/index.ts
new file mode 100644
index 00000000..a56e2c1a
--- /dev/null
+++ b/mods/telemetry/hooks/batching/batch-rows/index.ts
@@ -0,0 +1,3 @@
+export * from './batch-rows.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/batching/batch-window-ms/batch-window-ms.ts b/mods/telemetry/hooks/batching/batch-window-ms/batch-window-ms.ts
new file mode 100644
index 00000000..23f57558
--- /dev/null
+++ b/mods/telemetry/hooks/batching/batch-window-ms/batch-window-ms.ts
@@ -0,0 +1,5 @@
+/**
+ * How long a queued row waits for company before its batch goes out, in
+ * milliseconds; a session that ends sooner sends what waits then.
+ */
+export const BATCH_WINDOW_MS = 5000
diff --git a/mods/telemetry/hooks/batching/batch-window-ms/index.ts b/mods/telemetry/hooks/batching/batch-window-ms/index.ts
new file mode 100644
index 00000000..84d82363
--- /dev/null
+++ b/mods/telemetry/hooks/batching/batch-window-ms/index.ts
@@ -0,0 +1,3 @@
+export * from './batch-window-ms.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/batching/index.ts b/mods/telemetry/hooks/batching/index.ts
new file mode 100644
index 00000000..c328a18d
--- /dev/null
+++ b/mods/telemetry/hooks/batching/index.ts
@@ -0,0 +1,8 @@
+export * from './batch-rows'
+export * from './batch-window-ms'
+export * from './is-retriable'
+export * from './message-of'
+export * from './pending-row'
+export * from './retry-delay-ms'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/batching/is-retriable/index.ts b/mods/telemetry/hooks/batching/is-retriable/index.ts
new file mode 100644
index 00000000..19e4adcd
--- /dev/null
+++ b/mods/telemetry/hooks/batching/is-retriable/index.ts
@@ -0,0 +1,6 @@
+export * from './is-retriable.js'
+export * from './status-request-timeout'
+export * from './status-server-error'
+export * from './status-too-many-requests'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/batching/is-retriable/is-retriable.ts b/mods/telemetry/hooks/batching/is-retriable/is-retriable.ts
new file mode 100644
index 00000000..dc438950
--- /dev/null
+++ b/mods/telemetry/hooks/batching/is-retriable/is-retriable.ts
@@ -0,0 +1,15 @@
+import { STATUS_REQUEST_TIMEOUT } from './status-request-timeout'
+import { STATUS_SERVER_ERROR } from './status-server-error'
+import { STATUS_TOO_MANY_REQUESTS } from './status-too-many-requests'
+
+/**
+ * Whether an answer from the ingest is worth the one retry: a server error,
+ * a timeout or a rate limit; anything else it refused stays refused.
+ *
+ * @param status the HTTP status the ingest answered
+ * @returns true for 5xx, 408 and 429
+ */
+export const isRetriable = (status: number) =>
+ status >= STATUS_SERVER_ERROR ||
+ status === STATUS_REQUEST_TIMEOUT ||
+ status === STATUS_TOO_MANY_REQUESTS
diff --git a/mods/telemetry/hooks/batching/is-retriable/status-request-timeout/index.ts b/mods/telemetry/hooks/batching/is-retriable/status-request-timeout/index.ts
new file mode 100644
index 00000000..aa2595a8
--- /dev/null
+++ b/mods/telemetry/hooks/batching/is-retriable/status-request-timeout/index.ts
@@ -0,0 +1,3 @@
+export * from './status-request-timeout.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/batching/is-retriable/status-request-timeout/status-request-timeout.ts b/mods/telemetry/hooks/batching/is-retriable/status-request-timeout/status-request-timeout.ts
new file mode 100644
index 00000000..fd1b1414
--- /dev/null
+++ b/mods/telemetry/hooks/batching/is-retriable/status-request-timeout/status-request-timeout.ts
@@ -0,0 +1,4 @@
+/**
+ * HTTP 408: the ingest gave up waiting for the request; worth the one retry.
+ */
+export const STATUS_REQUEST_TIMEOUT = 408
diff --git a/mods/telemetry/hooks/batching/is-retriable/status-server-error/index.ts b/mods/telemetry/hooks/batching/is-retriable/status-server-error/index.ts
new file mode 100644
index 00000000..3584ce31
--- /dev/null
+++ b/mods/telemetry/hooks/batching/is-retriable/status-server-error/index.ts
@@ -0,0 +1,3 @@
+export * from './status-server-error.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/batching/is-retriable/status-server-error/status-server-error.ts b/mods/telemetry/hooks/batching/is-retriable/status-server-error/status-server-error.ts
new file mode 100644
index 00000000..5e34ea01
--- /dev/null
+++ b/mods/telemetry/hooks/batching/is-retriable/status-server-error/status-server-error.ts
@@ -0,0 +1,5 @@
+/**
+ * HTTP 500, the first server-side status: it and everything above is the
+ * ingest's own failure and worth the one retry.
+ */
+export const STATUS_SERVER_ERROR = 500
diff --git a/mods/telemetry/hooks/batching/is-retriable/status-too-many-requests/index.ts b/mods/telemetry/hooks/batching/is-retriable/status-too-many-requests/index.ts
new file mode 100644
index 00000000..2b3dc142
--- /dev/null
+++ b/mods/telemetry/hooks/batching/is-retriable/status-too-many-requests/index.ts
@@ -0,0 +1,3 @@
+export * from './status-too-many-requests.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/batching/is-retriable/status-too-many-requests/status-too-many-requests.ts b/mods/telemetry/hooks/batching/is-retriable/status-too-many-requests/status-too-many-requests.ts
new file mode 100644
index 00000000..731d5ed3
--- /dev/null
+++ b/mods/telemetry/hooks/batching/is-retriable/status-too-many-requests/status-too-many-requests.ts
@@ -0,0 +1,4 @@
+/**
+ * HTTP 429: the ingest is shedding load; worth the one retry after a pause.
+ */
+export const STATUS_TOO_MANY_REQUESTS = 429
diff --git a/mods/telemetry/hooks/batching/message-of/index.ts b/mods/telemetry/hooks/batching/message-of/index.ts
new file mode 100644
index 00000000..1de1dae4
--- /dev/null
+++ b/mods/telemetry/hooks/batching/message-of/index.ts
@@ -0,0 +1,3 @@
+export * from './message-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/batching/message-of/message-of.ts b/mods/telemetry/hooks/batching/message-of/message-of.ts
new file mode 100644
index 00000000..38b0174a
--- /dev/null
+++ b/mods/telemetry/hooks/batching/message-of/message-of.ts
@@ -0,0 +1,9 @@
+/**
+ * What a batch's failure says, for the refusal each of its rows rejects
+ * with: the error's own message, or the value as text.
+ *
+ * @param error what sending the batch threw
+ * @returns the message
+ */
+export const messageOf = (error: unknown) =>
+ error instanceof Error ? error.message : String(error)
diff --git a/mods/telemetry/hooks/batching/pending-row/index.ts b/mods/telemetry/hooks/batching/pending-row/index.ts
new file mode 100644
index 00000000..d521cabe
--- /dev/null
+++ b/mods/telemetry/hooks/batching/pending-row/index.ts
@@ -0,0 +1,3 @@
+export type * from './pending-row.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/batching/pending-row/pending-row.ts b/mods/telemetry/hooks/batching/pending-row/pending-row.ts
new file mode 100644
index 00000000..7e4f3476
--- /dev/null
+++ b/mods/telemetry/hooks/batching/pending-row/pending-row.ts
@@ -0,0 +1,11 @@
+import type Entries from '../../entries'
+
+/**
+ * One row waiting for its batch: the checked fields, and the id and time
+ * it was logged with.
+ */
+export type PendingRow = {
+ fields: Entries.Fields
+ eventId: string
+ loggedAt: string
+}
diff --git a/mods/telemetry/hooks/batching/retry-delay-ms/index.ts b/mods/telemetry/hooks/batching/retry-delay-ms/index.ts
new file mode 100644
index 00000000..4e238007
--- /dev/null
+++ b/mods/telemetry/hooks/batching/retry-delay-ms/index.ts
@@ -0,0 +1,3 @@
+export * from './retry-delay-ms.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/batching/retry-delay-ms/retry-delay-ms.ts b/mods/telemetry/hooks/batching/retry-delay-ms/retry-delay-ms.ts
new file mode 100644
index 00000000..4f443652
--- /dev/null
+++ b/mods/telemetry/hooks/batching/retry-delay-ms/retry-delay-ms.ts
@@ -0,0 +1,5 @@
+/**
+ * How long the one retry waits after a POST that failed or was answered with
+ * a status worth retrying, in milliseconds.
+ */
+export const RETRY_DELAY_MS = 500
diff --git a/mods/telemetry/hooks/config-location/config-location.ts b/mods/telemetry/hooks/config-location/config-location.ts
new file mode 100644
index 00000000..70acbc78
--- /dev/null
+++ b/mods/telemetry/hooks/config-location/config-location.ts
@@ -0,0 +1,12 @@
+/**
+ * Where the CLI's global config file is, read off the environment; read to
+ * find the file, never sent.
+ *
+ * The config directory when one is named, else the home directory (the
+ * profile directory on Windows).
+ */
+export type ConfigLocation = {
+ readonly configDir: string | undefined
+ readonly home: string | undefined
+ readonly userProfile: string | undefined
+}
diff --git a/mods/telemetry/hooks/config-location/index.ts b/mods/telemetry/hooks/config-location/index.ts
new file mode 100644
index 00000000..bccfc1b6
--- /dev/null
+++ b/mods/telemetry/hooks/config-location/index.ts
@@ -0,0 +1,3 @@
+export type * from './config-location.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/client-type-of/client-type-by-entrypoint/client-type-by-entrypoint.ts b/mods/telemetry/hooks/context/client-type-of/client-type-by-entrypoint/client-type-by-entrypoint.ts
new file mode 100644
index 00000000..495fa243
--- /dev/null
+++ b/mods/telemetry/hooks/context/client-type-of/client-type-by-entrypoint/client-type-by-entrypoint.ts
@@ -0,0 +1,12 @@
+/**
+ * The client types the CLI names by entrypoint alone: the SDKs, the VS Code
+ * and desktop hosts, and the local agent.
+ */
+export const CLIENT_TYPE_BY_ENTRYPOINT: Readonly<Record<string, string>> = {
+ 'sdk-ts': 'sdk-typescript',
+ 'sdk-py': 'sdk-python',
+ 'sdk-cli': 'sdk-cli',
+ 'claude-vscode': 'claude-vscode',
+ 'local-agent': 'local-agent',
+ 'claude-desktop': 'claude-desktop',
+}
diff --git a/mods/telemetry/hooks/context/client-type-of/client-type-by-entrypoint/index.ts b/mods/telemetry/hooks/context/client-type-of/client-type-by-entrypoint/index.ts
new file mode 100644
index 00000000..14b71b34
--- /dev/null
+++ b/mods/telemetry/hooks/context/client-type-of/client-type-by-entrypoint/index.ts
@@ -0,0 +1,3 @@
+export * from './client-type-by-entrypoint.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/client-type-of/client-type-of.ts b/mods/telemetry/hooks/context/client-type-of/client-type-of.ts
new file mode 100644
index 00000000..2b02db90
--- /dev/null
+++ b/mods/telemetry/hooks/context/client-type-of/client-type-of.ts
@@ -0,0 +1,26 @@
+import type { Facts } from '../../facts'
+import IsAnalyticsOff from '../../is-analytics-off'
+import { CLIENT_TYPE_BY_ENTRYPOINT } from './client-type-by-entrypoint'
+
+/**
+ * The row's `client_type` as the CLI decides it at start: a GitHub Action,
+ * an SDK or host by entrypoint, `remote` with an ingress token, else `cli`.
+ *
+ * @param facts the variables as read once for the session
+ * @returns the client type
+ */
+export function clientTypeOf(facts: Facts) {
+ const isRemote =
+ facts.entrypoint === 'remote' ||
+ facts.hasSessionAccessToken ||
+ facts.hasSessionIngressTokenFile ||
+ facts.hasWebsocketAuthFileDescriptor ||
+ IsAnalyticsOff.isEnvTruthy(facts.claudeCodeRemote)
+
+ const isGithubAction = IsAnalyticsOff.isEnvTruthy(facts.githubActions)
+
+ return isGithubAction
+ ? 'github-action'
+ : (CLIENT_TYPE_BY_ENTRYPOINT[facts.entrypoint ?? ''] ??
+ (isRemote ? 'remote' : 'cli'))
+}
diff --git a/mods/telemetry/hooks/context/client-type-of/index.ts b/mods/telemetry/hooks/context/client-type-of/index.ts
new file mode 100644
index 00000000..46e82a1e
--- /dev/null
+++ b/mods/telemetry/hooks/context/client-type-of/index.ts
@@ -0,0 +1,4 @@
+export * from './client-type-by-entrypoint'
+export * from './client-type-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/context-of.ts b/mods/telemetry/hooks/context/context-of.ts
new file mode 100644
index 00000000..51ac26dc
--- /dev/null
+++ b/mods/telemetry/hooks/context/context-of.ts
@@ -0,0 +1,30 @@
+import type { TelemetryDeps } from '../telemetry-deps'
+import type { Context } from './context'
+import { environmentFieldsOf } from './environment-fields-of'
+import { probeOf } from './probe-of'
+import { sessionFieldsOf } from './session-fields-of'
+
+/**
+ * Gathers and shapes what holds for the whole session, once: who the rows
+ * are from, the session's fields, its `env` block and the remote hash.
+ *
+ * Nothing in it is a secret or a path: every field is the closed value the
+ * CLI's own column holds.
+ *
+ * @param deps the calls on the nouns beneath
+ * @param isInteractive whether a person is at the prompt
+ * @returns the session's context for every batch after
+ */
+export async function contextOf(
+ deps: TelemetryDeps,
+ isInteractive: boolean,
+): Promise<Context> {
+ const probe = await probeOf(deps, isInteractive)
+
+ return {
+ identity: probe.identity,
+ session: sessionFieldsOf(probe.facts),
+ environment: environmentFieldsOf(probe),
+ remoteHash: probe.remoteHash,
+ }
+}
diff --git a/mods/telemetry/hooks/context/context/context.ts b/mods/telemetry/hooks/context/context/context.ts
new file mode 100644
index 00000000..07ae0bbf
--- /dev/null
+++ b/mods/telemetry/hooks/context/context/context.ts
@@ -0,0 +1,17 @@
+import type { EnvironmentFields } from '../environment-fields'
+import type { Identity } from '../identity'
+import type { SessionFields } from '../session-fields'
+
+/**
+ * Everything a row carries that holds for the whole session, gathered once
+ * before the first batch.
+ *
+ * Who it is from, the session's constant fields, its `env` block, and the
+ * repository's remote hash for the metadata.
+ */
+export type Context = {
+ readonly identity: Identity
+ readonly session: SessionFields
+ readonly environment: EnvironmentFields
+ readonly remoteHash: string | undefined
+}
diff --git a/mods/telemetry/hooks/context/context/index.ts b/mods/telemetry/hooks/context/context/index.ts
new file mode 100644
index 00000000..9a92dbdf
--- /dev/null
+++ b/mods/telemetry/hooks/context/context/index.ts
@@ -0,0 +1,3 @@
+export type * from './context.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/entrypoint-of/entrypoint-of.ts b/mods/telemetry/hooks/context/entrypoint-of/entrypoint-of.ts
new file mode 100644
index 00000000..ad67093a
--- /dev/null
+++ b/mods/telemetry/hooks/context/entrypoint-of/entrypoint-of.ts
@@ -0,0 +1,13 @@
+/**
+ * The row's `entrypoint` field: the variable as the CLI or its host set it
+ * when spelled like one (a short lowercase token), else `other`.
+ *
+ * @param variable CLAUDE_CODE_ENTRYPOINT as read; undefined stays so
+ * @returns the field, or undefined
+ */
+export function entrypointOf(variable: string | undefined) {
+ const isSpelled =
+ variable === undefined || /^[a-z][a-z0-9_-]{0,39}$/.test(variable)
+
+ return isSpelled ? variable : 'other'
+}
diff --git a/mods/telemetry/hooks/context/entrypoint-of/index.ts b/mods/telemetry/hooks/context/entrypoint-of/index.ts
new file mode 100644
index 00000000..408a1b7a
--- /dev/null
+++ b/mods/telemetry/hooks/context/entrypoint-of/index.ts
@@ -0,0 +1,3 @@
+export * from './entrypoint-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/environment-fields-of/action-ref-of/action-ref-of.ts b/mods/telemetry/hooks/context/environment-fields-of/action-ref-of/action-ref-of.ts
new file mode 100644
index 00000000..4799bd4f
--- /dev/null
+++ b/mods/telemetry/hooks/context/environment-fields-of/action-ref-of/action-ref-of.ts
@@ -0,0 +1,11 @@
+/**
+ * The row's `github_action_ref`: what follows `claude-code-action/` in the
+ * action's path, as the CLI reads it; undefined when the path names none.
+ *
+ * @param actionPath GITHUB_ACTION_PATH as read
+ * @returns the ref, or undefined
+ */
+export const actionRefOf = (actionPath: string | undefined) =>
+ actionPath?.includes('claude-code-action/')
+ ? actionPath.split('claude-code-action/')[1]
+ : undefined
diff --git a/mods/telemetry/hooks/context/environment-fields-of/action-ref-of/index.ts b/mods/telemetry/hooks/context/environment-fields-of/action-ref-of/index.ts
new file mode 100644
index 00000000..4cd3ed6d
--- /dev/null
+++ b/mods/telemetry/hooks/context/environment-fields-of/action-ref-of/index.ts
@@ -0,0 +1,3 @@
+export * from './action-ref-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/environment-fields-of/environment-fields-of.ts b/mods/telemetry/hooks/context/environment-fields-of/environment-fields-of.ts
new file mode 100644
index 00000000..3ab180dc
--- /dev/null
+++ b/mods/telemetry/hooks/context/environment-fields-of/environment-fields-of.ts
@@ -0,0 +1,60 @@
+import Deployment from '../../deployment'
+import IsAnalyticsOff from '../../is-analytics-off'
+import type { EnvironmentFields } from '../environment-fields'
+import type { Probe } from '../probe'
+import { shellOf } from '../shell-of'
+import { terminalOf } from '../terminal-of'
+import { actionRefOf } from './action-ref-of'
+import { githubActionsFieldsOf } from './github-actions-fields-of'
+import { tagsOf } from './tags-of'
+
+/**
+ * The rows' `env` block from what was probed, valued as the CLI's own is;
+ * the GitHub Actions fields only inside a workflow, the Linux ones on Linux.
+ *
+ * @param probe what was gathered for the session
+ * @returns the block
+ */
+export function environmentFieldsOf(probe: Probe): EnvironmentFields {
+ const { facts, machine, platform } = probe
+ const isGithubAction = IsAnalyticsOff.isEnvTruthy(facts.githubActions)
+ const isLinux = machine.platformRaw === 'linux'
+
+ return {
+ platform,
+ platformRaw: machine.platformRaw,
+ arch: machine.arch,
+ terminal: terminalOf(facts, platform, probe.isInteractive),
+ shell: shellOf(facts.shellPath),
+ packageManagers: machine.packageManagers,
+ runtimes: machine.runtimes,
+ isCi: IsAnalyticsOff.isEnvTruthy(facts.ci),
+ isClaubbit: IsAnalyticsOff.isEnvTruthy(facts.claubbit),
+ isGithubAction,
+ isClaudeCodeAction: IsAnalyticsOff.isEnvTruthy(facts.claudeCodeAction),
+ isClaudeCodeRemote: IsAnalyticsOff.isEnvTruthy(facts.claudeCodeRemote),
+ isLocalAgentMode: facts.entrypoint === 'local-agent',
+ isConductor: facts.bundleIdentifier === 'com.conductor.app',
+ deploymentEnvironment: Deployment.deploymentOf(probe.signals, platform),
+ remoteEnvironmentType: facts.remoteEnvironmentType,
+ claudeCodeContainerId: facts.containerId,
+ claudeCodeRemoteSessionId: facts.remoteSessionId,
+ tags: tagsOf(facts.tags),
+ githubEventName: isGithubAction ? facts.githubEventName : undefined,
+ githubActionsRunnerEnvironment: isGithubAction
+ ? facts.runnerEnvironment
+ : undefined,
+ githubActionsRunnerOs: isGithubAction ? facts.runnerOs : undefined,
+ githubActionRef: isGithubAction
+ ? actionRefOf(facts.githubActionPath)
+ : undefined,
+ githubActionsMetadata: isGithubAction
+ ? githubActionsFieldsOf(facts)
+ : undefined,
+ wslVersion: probe.wslVersion,
+ linuxDistroId: probe.distro.id,
+ linuxDistroVersion: probe.distro.version,
+ linuxKernel: isLinux ? machine.kernel : undefined,
+ vcs: probe.vcs,
+ }
+}
diff --git a/mods/telemetry/hooks/context/environment-fields-of/github-actions-fields-of/github-actions-fields-of.ts b/mods/telemetry/hooks/context/environment-fields-of/github-actions-fields-of/github-actions-fields-of.ts
new file mode 100644
index 00000000..f7de54a4
--- /dev/null
+++ b/mods/telemetry/hooks/context/environment-fields-of/github-actions-fields-of/github-actions-fields-of.ts
@@ -0,0 +1,26 @@
+import type { Facts } from '../../../facts'
+import type EnvironmentFields from '../../environment-fields'
+
+/**
+ * The GitHub Actions ids for the row's `env` block; undefined when the
+ * workflow names none of the three.
+ *
+ * @param facts the variables as read once for the session
+ * @returns the ids, or undefined
+ */
+export function githubActionsFieldsOf(
+ facts: Facts,
+): EnvironmentFields.GithubActionsFields | undefined {
+ const hasAny =
+ facts.githubActorId !== undefined ||
+ facts.githubRepositoryId !== undefined ||
+ facts.githubRepositoryOwnerId !== undefined
+
+ return hasAny
+ ? {
+ actorId: facts.githubActorId,
+ repositoryId: facts.githubRepositoryId,
+ repositoryOwnerId: facts.githubRepositoryOwnerId,
+ }
+ : undefined
+}
diff --git a/mods/telemetry/hooks/context/environment-fields-of/github-actions-fields-of/index.ts b/mods/telemetry/hooks/context/environment-fields-of/github-actions-fields-of/index.ts
new file mode 100644
index 00000000..e192abe4
--- /dev/null
+++ b/mods/telemetry/hooks/context/environment-fields-of/github-actions-fields-of/index.ts
@@ -0,0 +1,3 @@
+export * from './github-actions-fields-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/environment-fields-of/index.ts b/mods/telemetry/hooks/context/environment-fields-of/index.ts
new file mode 100644
index 00000000..f4b1daf4
--- /dev/null
+++ b/mods/telemetry/hooks/context/environment-fields-of/index.ts
@@ -0,0 +1,6 @@
+export * from './action-ref-of'
+export * from './environment-fields-of.js'
+export * from './github-actions-fields-of'
+export * from './tags-of'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/environment-fields-of/tags-of/index.ts b/mods/telemetry/hooks/context/environment-fields-of/tags-of/index.ts
new file mode 100644
index 00000000..29eb5b98
--- /dev/null
+++ b/mods/telemetry/hooks/context/environment-fields-of/tags-of/index.ts
@@ -0,0 +1,3 @@
+export * from './tags-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/environment-fields-of/tags-of/tags-of.ts b/mods/telemetry/hooks/context/environment-fields-of/tags-of/tags-of.ts
new file mode 100644
index 00000000..859484f7
--- /dev/null
+++ b/mods/telemetry/hooks/context/environment-fields-of/tags-of/tags-of.ts
@@ -0,0 +1,15 @@
+/**
+ * The row's `tags` field: the variable split on commas and trimmed, or
+ * undefined when it names none.
+ *
+ * @param variable CLAUDE_CODE_TAGS as read
+ * @returns the field, or undefined
+ */
+export function tagsOf(variable: string | undefined) {
+ const listed = (variable ?? '')
+ .split(',')
+ .map(tag => tag.trim())
+ .filter(Boolean)
+
+ return listed.length > 0 ? listed : undefined
+}
diff --git a/mods/telemetry/hooks/context/environment-fields/environment-fields.ts b/mods/telemetry/hooks/context/environment-fields/environment-fields.ts
new file mode 100644
index 00000000..41e22e1d
--- /dev/null
+++ b/mods/telemetry/hooks/context/environment-fields/environment-fields.ts
@@ -0,0 +1,41 @@
+import type { GithubActionsFields } from './github-actions-fields'
+
+/**
+ * The `env` block every row of the session carries, as the CLI's own rows
+ * carry it, before its keys are spelled for the wire (Entries.wireOf).
+ *
+ * The machine, the terminal and shell, CI and GitHub Actions, the remote
+ * container, the deployment. `isClaudeAiAuth` follows the credential each
+ * batch is sent with and joins these then; an absent field is undefined.
+ */
+export type EnvironmentFields = {
+ readonly platform: string
+ readonly platformRaw: string
+ readonly arch: string
+ readonly terminal: string
+ readonly shell: string
+ readonly packageManagers: string
+ readonly runtimes: string
+ readonly isCi: boolean
+ readonly isClaubbit: boolean
+ readonly isGithubAction: boolean
+ readonly isClaudeCodeAction: boolean
+ readonly isClaudeCodeRemote: boolean
+ readonly isLocalAgentMode: boolean
+ readonly isConductor: boolean
+ readonly deploymentEnvironment: string
+ readonly remoteEnvironmentType: string | undefined
+ readonly claudeCodeContainerId: string | undefined
+ readonly claudeCodeRemoteSessionId: string | undefined
+ readonly tags: readonly string[] | undefined
+ readonly githubEventName: string | undefined
+ readonly githubActionsRunnerEnvironment: string | undefined
+ readonly githubActionsRunnerOs: string | undefined
+ readonly githubActionRef: string | undefined
+ readonly githubActionsMetadata: GithubActionsFields | undefined
+ readonly wslVersion: string | undefined
+ readonly linuxDistroId: string | undefined
+ readonly linuxDistroVersion: string | undefined
+ readonly linuxKernel: string | undefined
+ readonly vcs: string | undefined
+}
diff --git a/mods/telemetry/hooks/context/environment-fields/github-actions-fields/github-actions-fields.ts b/mods/telemetry/hooks/context/environment-fields/github-actions-fields/github-actions-fields.ts
new file mode 100644
index 00000000..23cfa699
--- /dev/null
+++ b/mods/telemetry/hooks/context/environment-fields/github-actions-fields/github-actions-fields.ts
@@ -0,0 +1,9 @@
+/**
+ * The GitHub Actions ids a row's `env` block carries when the session runs
+ * in a workflow: the actor, the repository and its owner, by number.
+ */
+export type GithubActionsFields = {
+ readonly actorId: string | undefined
+ readonly repositoryId: string | undefined
+ readonly repositoryOwnerId: string | undefined
+}
diff --git a/mods/telemetry/hooks/context/environment-fields/github-actions-fields/index.ts b/mods/telemetry/hooks/context/environment-fields/github-actions-fields/index.ts
new file mode 100644
index 00000000..270aa04d
--- /dev/null
+++ b/mods/telemetry/hooks/context/environment-fields/github-actions-fields/index.ts
@@ -0,0 +1,3 @@
+export type * from './github-actions-fields.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/environment-fields/index.ts b/mods/telemetry/hooks/context/environment-fields/index.ts
new file mode 100644
index 00000000..a6b29102
--- /dev/null
+++ b/mods/telemetry/hooks/context/environment-fields/index.ts
@@ -0,0 +1,4 @@
+export type * from './environment-fields.js'
+export * from './github-actions-fields'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/identity/global-config-path/global-config-path.ts b/mods/telemetry/hooks/context/identity/global-config-path/global-config-path.ts
new file mode 100644
index 00000000..1cfa26dc
--- /dev/null
+++ b/mods/telemetry/hooks/context/identity/global-config-path/global-config-path.ts
@@ -0,0 +1,19 @@
+import type { ConfigLocation } from '../../../config-location'
+
+/**
+ * Where the CLI keeps its global config: `.claude.json` under the config
+ * directory when one is named, else under the home or profile directory.
+ *
+ * @param location the three variables as read
+ * @returns the file's path, or undefined when no directory is named
+ */
+export function globalConfigPath(location: ConfigLocation): string | undefined {
+ const directory = location.configDir || location.home || location.userProfile
+
+ const separator =
+ directory?.includes('\\') && !directory.includes('/') ? '\\' : '/'
+
+ return directory
+ ? `${directory.replace(/[\\/]+$/, '')}${separator}.claude.json`
+ : undefined
+}
diff --git a/mods/telemetry/hooks/context/identity/global-config-path/index.ts b/mods/telemetry/hooks/context/identity/global-config-path/index.ts
new file mode 100644
index 00000000..dda1c31a
--- /dev/null
+++ b/mods/telemetry/hooks/context/identity/global-config-path/index.ts
@@ -0,0 +1,3 @@
+export * from './global-config-path.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/identity/identity-of.ts b/mods/telemetry/hooks/context/identity/identity-of.ts
new file mode 100644
index 00000000..16aabb06
--- /dev/null
+++ b/mods/telemetry/hooks/context/identity/identity-of.ts
@@ -0,0 +1,54 @@
+import type { ConfigLocation } from '../../config-location'
+import Entries from '../../entries'
+import { globalConfigPath } from './global-config-path'
+import type { Identity } from './identity'
+import { plausibleUuid } from './plausible-uuid'
+
+/**
+ * Reads the identity the CLI's global config records: the device id it
+ * minted for this install, and the account it is signed in to.
+ *
+ * A config that is missing, unreadable or not JSON yields an identity with
+ * nothing in it; the address is kept on an internal build alone.
+ *
+ * @param read reads a file as text
+ * @param location where the config is
+ * @param isInternal whether this is an internal build
+ * @returns the identity, each field undefined unless the config has it
+ */
+export async function identityOf(
+ read: (path: string) => Promise<string>,
+ location: ConfigLocation,
+ isInternal: boolean,
+): Promise<Identity> {
+ const path = globalConfigPath(location)
+
+ let config: unknown
+
+ try {
+ config = path === undefined ? undefined : JSON.parse(await read(path))
+ } catch {
+ config = undefined
+ }
+
+ const record = Entries.isRecord(config) ? config : {}
+
+ const account = Entries.isRecord(record.oauthAccount)
+ ? record.oauthAccount
+ : {}
+
+ const deviceId = record.userID
+ const email = account.emailAddress
+
+ const isDeviceId =
+ typeof deviceId === 'string' && /^[A-Za-z0-9_-]{8,128}$/.test(deviceId)
+
+ const isEmailKept = isInternal && typeof email === 'string' && email !== ''
+
+ return {
+ deviceId: isDeviceId ? deviceId : undefined,
+ accountUuid: plausibleUuid(account.accountUuid),
+ organizationUuid: plausibleUuid(account.organizationUuid),
+ email: isEmailKept ? email : undefined,
+ }
+}
diff --git a/mods/telemetry/hooks/context/identity/identity/identity.ts b/mods/telemetry/hooks/context/identity/identity/identity.ts
new file mode 100644
index 00000000..22dcbaaa
--- /dev/null
+++ b/mods/telemetry/hooks/context/identity/identity/identity.ts
@@ -0,0 +1,13 @@
+/**
+ * Who the rows are from, as the CLI's global config records it: the
+ * install's device id, and the signed-in account's ids and address.
+ *
+ * Each is undefined when the config has none or cannot be read; the address
+ * rides only on an internal build's rows, as the CLI's own does.
+ */
+export type Identity = {
+ readonly deviceId: string | undefined
+ readonly accountUuid: string | undefined
+ readonly organizationUuid: string | undefined
+ readonly email: string | undefined
+}
diff --git a/mods/telemetry/hooks/context/identity/identity/index.ts b/mods/telemetry/hooks/context/identity/identity/index.ts
new file mode 100644
index 00000000..794483fa
--- /dev/null
+++ b/mods/telemetry/hooks/context/identity/identity/index.ts
@@ -0,0 +1,3 @@
+export type * from './identity.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/identity/index.ts b/mods/telemetry/hooks/context/identity/index.ts
new file mode 100644
index 00000000..920ad8b3
--- /dev/null
+++ b/mods/telemetry/hooks/context/identity/index.ts
@@ -0,0 +1,6 @@
+export * from './global-config-path'
+export * from './identity'
+export * from './identity-of.js'
+export * from './plausible-uuid'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/identity/plausible-uuid/index.ts b/mods/telemetry/hooks/context/identity/plausible-uuid/index.ts
new file mode 100644
index 00000000..ddcb331c
--- /dev/null
+++ b/mods/telemetry/hooks/context/identity/plausible-uuid/index.ts
@@ -0,0 +1,5 @@
+export * from './plausible-uuid.js'
+export * from './uuid-length-floor'
+export * from './uuid-length-limit'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/identity/plausible-uuid/plausible-uuid.ts b/mods/telemetry/hooks/context/identity/plausible-uuid/plausible-uuid.ts
new file mode 100644
index 00000000..39f06c25
--- /dev/null
+++ b/mods/telemetry/hooks/context/identity/plausible-uuid/plausible-uuid.ts
@@ -0,0 +1,18 @@
+import { UUID_LENGTH_FLOOR } from './uuid-length-floor'
+import { UUID_LENGTH_LIMIT } from './uuid-length-limit'
+
+/**
+ * A value the config holds as an account or organization id, when it is a
+ * string long enough to be one; a number or a trivial string is dropped.
+ *
+ * @param value what the config holds under the key
+ * @returns the id, or undefined
+ */
+export function plausibleUuid(value: unknown): string | undefined {
+ const isPlausible =
+ typeof value === 'string' &&
+ value.length >= UUID_LENGTH_FLOOR &&
+ value.length <= UUID_LENGTH_LIMIT
+
+ return isPlausible ? value : undefined
+}
diff --git a/mods/telemetry/hooks/context/identity/plausible-uuid/uuid-length-floor/index.ts b/mods/telemetry/hooks/context/identity/plausible-uuid/uuid-length-floor/index.ts
new file mode 100644
index 00000000..b5a6f5aa
--- /dev/null
+++ b/mods/telemetry/hooks/context/identity/plausible-uuid/uuid-length-floor/index.ts
@@ -0,0 +1,3 @@
+export * from './uuid-length-floor.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/identity/plausible-uuid/uuid-length-floor/uuid-length-floor.ts b/mods/telemetry/hooks/context/identity/plausible-uuid/uuid-length-floor/uuid-length-floor.ts
new file mode 100644
index 00000000..a4e8acf0
--- /dev/null
+++ b/mods/telemetry/hooks/context/identity/plausible-uuid/uuid-length-floor/uuid-length-floor.ts
@@ -0,0 +1,5 @@
+/**
+ * The shortest string taken for an account or organization id, the CLI's
+ * own floor: long enough to sweep trivial junk, no format assumed.
+ */
+export const UUID_LENGTH_FLOOR = 8
diff --git a/mods/telemetry/hooks/context/identity/plausible-uuid/uuid-length-limit/index.ts b/mods/telemetry/hooks/context/identity/plausible-uuid/uuid-length-limit/index.ts
new file mode 100644
index 00000000..6477202e
--- /dev/null
+++ b/mods/telemetry/hooks/context/identity/plausible-uuid/uuid-length-limit/index.ts
@@ -0,0 +1,3 @@
+export * from './uuid-length-limit.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/identity/plausible-uuid/uuid-length-limit/uuid-length-limit.ts b/mods/telemetry/hooks/context/identity/plausible-uuid/uuid-length-limit/uuid-length-limit.ts
new file mode 100644
index 00000000..2051459e
--- /dev/null
+++ b/mods/telemetry/hooks/context/identity/plausible-uuid/uuid-length-limit/uuid-length-limit.ts
@@ -0,0 +1,5 @@
+/**
+ * The longest string taken for an account or organization id or a device
+ * id; anything longer is not an id and is dropped.
+ */
+export const UUID_LENGTH_LIMIT = 128
diff --git a/mods/telemetry/hooks/context/index.ts b/mods/telemetry/hooks/context/index.ts
new file mode 100644
index 00000000..244123e1
--- /dev/null
+++ b/mods/telemetry/hooks/context/index.ts
@@ -0,0 +1,21 @@
+export * from './client-type-of'
+export * from './context'
+export * from './context-of.js'
+export * from './entrypoint-of'
+export * from './environment-fields'
+export * from './environment-fields-of'
+export * from './identity'
+export * from './linux-distro-of'
+export * from './machine'
+export * from './probe'
+export * from './probe-of'
+export * from './remote-hash-of'
+export * from './session-fields'
+export * from './session-fields-of'
+export * from './shell-of'
+export * from './terminal-of'
+export * from './vcs-of'
+export * from './version-of'
+export * from './wsl-version-of'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/linux-distro-of/index.ts b/mods/telemetry/hooks/context/linux-distro-of/index.ts
new file mode 100644
index 00000000..ce3b467e
--- /dev/null
+++ b/mods/telemetry/hooks/context/linux-distro-of/index.ts
@@ -0,0 +1,5 @@
+export * from './linux-distro'
+export * from './linux-distro-of.js'
+export * from './os-release-value'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/linux-distro-of/linux-distro-of.ts b/mods/telemetry/hooks/context/linux-distro-of/linux-distro-of.ts
new file mode 100644
index 00000000..6014c139
--- /dev/null
+++ b/mods/telemetry/hooks/context/linux-distro-of/linux-distro-of.ts
@@ -0,0 +1,26 @@
+import type { LinuxDistro } from './linux-distro'
+import { osReleaseValue } from './os-release-value'
+
+/**
+ * Reads the distribution's id and version off `/etc/os-release`, as the
+ * CLI's own rows do; a file that is missing or unreadable yields neither.
+ *
+ * @param readOsRelease reads `/etc/os-release` as text
+ * @returns the distribution
+ */
+export async function linuxDistroOf(
+ readOsRelease: () => Promise<string>,
+): Promise<LinuxDistro> {
+ let content: string
+
+ try {
+ content = await readOsRelease()
+ } catch {
+ content = ''
+ }
+
+ return {
+ id: osReleaseValue(content, 'ID'),
+ version: osReleaseValue(content, 'VERSION_ID'),
+ }
+}
diff --git a/mods/telemetry/hooks/context/linux-distro-of/linux-distro/index.ts b/mods/telemetry/hooks/context/linux-distro-of/linux-distro/index.ts
new file mode 100644
index 00000000..47399088
--- /dev/null
+++ b/mods/telemetry/hooks/context/linux-distro-of/linux-distro/index.ts
@@ -0,0 +1,3 @@
+export type * from './linux-distro.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/linux-distro-of/linux-distro/linux-distro.ts b/mods/telemetry/hooks/context/linux-distro-of/linux-distro/linux-distro.ts
new file mode 100644
index 00000000..e86b8282
--- /dev/null
+++ b/mods/telemetry/hooks/context/linux-distro-of/linux-distro/linux-distro.ts
@@ -0,0 +1,8 @@
+/**
+ * What `/etc/os-release` says of a Linux machine for the row: the
+ * distribution's `ID` and `VERSION_ID`, undefined when absent or unread.
+ */
+export type LinuxDistro = {
+ readonly id: string | undefined
+ readonly version: string | undefined
+}
diff --git a/mods/telemetry/hooks/context/linux-distro-of/os-release-value/index.ts b/mods/telemetry/hooks/context/linux-distro-of/os-release-value/index.ts
new file mode 100644
index 00000000..46ad821e
--- /dev/null
+++ b/mods/telemetry/hooks/context/linux-distro-of/os-release-value/index.ts
@@ -0,0 +1,3 @@
+export * from './os-release-value.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/linux-distro-of/os-release-value/os-release-value.ts b/mods/telemetry/hooks/context/linux-distro-of/os-release-value/os-release-value.ts
new file mode 100644
index 00000000..a93986d7
--- /dev/null
+++ b/mods/telemetry/hooks/context/linux-distro-of/os-release-value/os-release-value.ts
@@ -0,0 +1,14 @@
+/**
+ * One key's value in an os-release file, unquoted; undefined when the file
+ * has no such line.
+ *
+ * @param content the file's text
+ * @param key the key
+ * @returns the value, or undefined
+ */
+export const osReleaseValue = (content: string, key: 'ID' | 'VERSION_ID') =>
+ content
+ .split('\n')
+ .map(line => /^(ID|VERSION_ID)=(.*)$/.exec(line))
+ .find(match => match?.[1] === key)?.[2]
+ ?.replace(/^"|"$/g, '')
diff --git a/mods/telemetry/hooks/context/machine/arch-of/arch-of.ts b/mods/telemetry/hooks/context/machine/arch-of/arch-of.ts
new file mode 100644
index 00000000..20614532
--- /dev/null
+++ b/mods/telemetry/hooks/context/machine/arch-of/arch-of.ts
@@ -0,0 +1,18 @@
+/**
+ * The architecture as the CLI's runtime names it, from what `uname -m` or
+ * Windows' PROCESSOR_ARCHITECTURE says: `x64`, `arm64`, `ia32`, else as is.
+ *
+ * @param machine the architecture as the system spells it
+ * @returns the runtime's spelling
+ */
+export function archOf(machine: string) {
+ const spelled = machine.trim().toLowerCase()
+
+ const named: readonly (readonly [boolean, string])[] = [
+ [spelled === 'x86_64' || spelled === 'amd64', 'x64'],
+ [spelled === 'aarch64' || spelled === 'arm64', 'arm64'],
+ [spelled === 'x86' || /^i[3-6]86$/.test(spelled), 'ia32'],
+ ]
+
+ return named.find(([isIt]) => isIt)?.[1] ?? (spelled || 'unknown')
+}
diff --git a/mods/telemetry/hooks/context/machine/arch-of/index.ts b/mods/telemetry/hooks/context/machine/arch-of/index.ts
new file mode 100644
index 00000000..e0414845
--- /dev/null
+++ b/mods/telemetry/hooks/context/machine/arch-of/index.ts
@@ -0,0 +1,3 @@
+export * from './arch-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/machine/index.ts b/mods/telemetry/hooks/context/machine/index.ts
new file mode 100644
index 00000000..ad84770c
--- /dev/null
+++ b/mods/telemetry/hooks/context/machine/index.ts
@@ -0,0 +1,8 @@
+export * from './arch-of'
+export * from './machine'
+export * from './machine-of.js'
+export * from './platform-of'
+export * from './probe-script'
+export * from './probe-timeout-ms'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/machine/machine-of.ts b/mods/telemetry/hooks/context/machine/machine-of.ts
new file mode 100644
index 00000000..69b37ab4
--- /dev/null
+++ b/mods/telemetry/hooks/context/machine/machine-of.ts
@@ -0,0 +1,53 @@
+import type { ProcessRunResult } from 'claude-code'
+
+import type { Facts } from '../../facts'
+import { archOf } from './arch-of'
+import type { Machine } from './machine'
+import { PROBE_SCRIPT } from './probe-script'
+
+/**
+ * Probes the machine once: on Windows (the `OS` variable says so) from the
+ * environment alone, elsewhere with one `sh` run of PROBE_SCRIPT.
+ *
+ * A probe that fails or exits non-zero leaves the system unnamed
+ * (`unknown`) and the lists empty; nothing is retried.
+ *
+ * @param run runs one program to its end
+ * @param facts the variables as read, for the Windows answer
+ * @returns the machine as probed
+ */
+export async function machineOf(
+ run: (argv: readonly string[]) => Promise<ProcessRunResult>,
+ facts: Facts,
+): Promise<Machine> {
+ if (facts.os === 'Windows_NT') {
+ return {
+ platformRaw: 'win32',
+ arch: archOf(facts.processorArchitecture ?? ''),
+ kernel: undefined,
+ packageManagers: '',
+ runtimes: '',
+ }
+ }
+
+ let result: ProcessRunResult | undefined
+
+ try {
+ result = await run(['sh', '-c', PROBE_SCRIPT])
+ } catch {
+ result = undefined
+ }
+
+ const [system = '', kernel = '', machine = '', managers = '', runtimes = ''] =
+ (result?.exitCode === 0 ? result.stdout.split('\n') : []).map(line =>
+ line.trim(),
+ )
+
+ return {
+ platformRaw: system.toLowerCase() || 'unknown',
+ arch: archOf(machine),
+ kernel: kernel || undefined,
+ packageManagers: managers.replace(/,$/, ''),
+ runtimes: runtimes.replace(/,$/, ''),
+ }
+}
diff --git a/mods/telemetry/hooks/context/machine/machine/index.ts b/mods/telemetry/hooks/context/machine/machine/index.ts
new file mode 100644
index 00000000..d96fc83d
--- /dev/null
+++ b/mods/telemetry/hooks/context/machine/machine/index.ts
@@ -0,0 +1,3 @@
+export type * from './machine.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/machine/machine/machine.ts b/mods/telemetry/hooks/context/machine/machine/machine.ts
new file mode 100644
index 00000000..53dc96c5
--- /dev/null
+++ b/mods/telemetry/hooks/context/machine/machine/machine.ts
@@ -0,0 +1,15 @@
+/**
+ * What one probe of the machine answers for the rows' `env` block: the
+ * system's own name, the architecture, the kernel, and what is on the PATH.
+ *
+ * `platformRaw` is the system's name lowercased (`darwin`, `linux`,
+ * `freebsd`, `win32`); the package managers and runtimes are comma-joined,
+ * an empty string for none.
+ */
+export type Machine = {
+ readonly platformRaw: string
+ readonly arch: string
+ readonly kernel: string | undefined
+ readonly packageManagers: string
+ readonly runtimes: string
+}
diff --git a/mods/telemetry/hooks/context/machine/platform-of/index.ts b/mods/telemetry/hooks/context/machine/platform-of/index.ts
new file mode 100644
index 00000000..8787b8a0
--- /dev/null
+++ b/mods/telemetry/hooks/context/machine/platform-of/index.ts
@@ -0,0 +1,3 @@
+export * from './platform-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/machine/platform-of/platform-of.ts b/mods/telemetry/hooks/context/machine/platform-of/platform-of.ts
new file mode 100644
index 00000000..dadf4528
--- /dev/null
+++ b/mods/telemetry/hooks/context/machine/platform-of/platform-of.ts
@@ -0,0 +1,17 @@
+/**
+ * The row's `platform` as the CLI's own rows have it: the host platform the
+ * environment names when it is one of the three, else by the system's name.
+ *
+ * @param hostPlatform CLAUDE_CODE_HOST_PLATFORM, when set
+ * @param platformRaw the system's own name lowercased
+ * @returns `win32`, `darwin`, or `linux` for anything else
+ */
+export function platformOf(
+ hostPlatform: string | undefined,
+ platformRaw: string,
+) {
+ const named = ['win32', 'darwin', 'linux'].find(one => one === hostPlatform)
+ const isOwnName = platformRaw === 'win32' || platformRaw === 'darwin'
+
+ return named ?? (isOwnName ? platformRaw : 'linux')
+}
diff --git a/mods/telemetry/hooks/context/machine/probe-script/index.ts b/mods/telemetry/hooks/context/machine/probe-script/index.ts
new file mode 100644
index 00000000..296c9ed4
--- /dev/null
+++ b/mods/telemetry/hooks/context/machine/probe-script/index.ts
@@ -0,0 +1,3 @@
+export * from './probe-script.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/machine/probe-script/probe-script.ts b/mods/telemetry/hooks/context/machine/probe-script/probe-script.ts
new file mode 100644
index 00000000..25e1eb77
--- /dev/null
+++ b/mods/telemetry/hooks/context/machine/probe-script/probe-script.ts
@@ -0,0 +1,17 @@
+/**
+ * The one shell script the plugin runs, once a session, anywhere but
+ * Windows; five lines come back.
+ *
+ * `uname -s`, `uname -r`, `uname -m`, then the package managers found of
+ * npm, yarn and pnpm comma-joined, then the runtimes found of bun, deno and
+ * node.
+ */
+export const PROBE_SCRIPT = [
+ 'uname -s',
+ 'uname -r',
+ 'uname -m',
+ 'for c in npm yarn pnpm; do command -v "$c" >/dev/null 2>&1 && ' +
+ 'printf "%s," "$c"; done; echo',
+ 'for c in bun deno node; do command -v "$c" >/dev/null 2>&1 && ' +
+ 'printf "%s," "$c"; done; echo',
+].join('\n')
diff --git a/mods/telemetry/hooks/context/machine/probe-timeout-ms/index.ts b/mods/telemetry/hooks/context/machine/probe-timeout-ms/index.ts
new file mode 100644
index 00000000..f26c4197
--- /dev/null
+++ b/mods/telemetry/hooks/context/machine/probe-timeout-ms/index.ts
@@ -0,0 +1,3 @@
+export * from './probe-timeout-ms.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/machine/probe-timeout-ms/probe-timeout-ms.ts b/mods/telemetry/hooks/context/machine/probe-timeout-ms/probe-timeout-ms.ts
new file mode 100644
index 00000000..8626edc4
--- /dev/null
+++ b/mods/telemetry/hooks/context/machine/probe-timeout-ms/probe-timeout-ms.ts
@@ -0,0 +1,5 @@
+/**
+ * How long the one machine probe may run before the host stops it, in
+ * milliseconds; a stopped probe leaves the machine unnamed.
+ */
+export const PROBE_TIMEOUT_MS = 5000
diff --git a/mods/telemetry/hooks/context/probe-of/index.ts b/mods/telemetry/hooks/context/probe-of/index.ts
new file mode 100644
index 00000000..d9446372
--- /dev/null
+++ b/mods/telemetry/hooks/context/probe-of/index.ts
@@ -0,0 +1,5 @@
+export * from './linux-files'
+export * from './linux-files-of'
+export * from './probe-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/probe-of/linux-files-of/index.ts b/mods/telemetry/hooks/context/probe-of/linux-files-of/index.ts
new file mode 100644
index 00000000..550598d2
--- /dev/null
+++ b/mods/telemetry/hooks/context/probe-of/linux-files-of/index.ts
@@ -0,0 +1,3 @@
+export * from './linux-files-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/probe-of/linux-files-of/linux-files-of.ts b/mods/telemetry/hooks/context/probe-of/linux-files-of/linux-files-of.ts
new file mode 100644
index 00000000..ca1bf7b4
--- /dev/null
+++ b/mods/telemetry/hooks/context/probe-of/linux-files-of/linux-files-of.ts
@@ -0,0 +1,40 @@
+import type { TelemetryDeps } from '../../../telemetry-deps'
+import { linuxDistroOf } from '../../linux-distro-of'
+import { wslVersionOf } from '../../wsl-version-of'
+import type { LinuxFiles } from '../linux-files'
+
+/**
+ * Reads the four Linux files the rows draw on, on Linux alone; elsewhere,
+ * and for each file that cannot be read, the answer is empty.
+ *
+ * @param deps the calls on the nouns beneath
+ * @param isLinux whether the machine named itself Linux
+ * @returns what the files say
+ */
+export async function linuxFilesOf(
+ deps: TelemetryDeps,
+ isLinux: boolean,
+): Promise<LinuxFiles> {
+ const [distro, wslVersion, isEc2, isDocker] = await Promise.all([
+ isLinux
+ ? linuxDistroOf(() => deps.read('/etc/os-release'))
+ : { id: undefined, version: undefined },
+ isLinux ? wslVersionOf(() => deps.read('/proc/version')) : undefined,
+ isLinux
+ ? deps.read('/sys/hypervisor/uuid').then(
+ uuid => uuid.startsWith('ec2'),
+ () => false,
+ )
+ : false,
+ isLinux ? deps.exists('/.dockerenv').catch(() => false) : false,
+ ])
+
+ return {
+ distro,
+ wslVersion,
+ fileSignals: [
+ ['aws-ec2', isEc2],
+ ['docker', isDocker],
+ ],
+ }
+}
diff --git a/mods/telemetry/hooks/context/probe-of/linux-files/index.ts b/mods/telemetry/hooks/context/probe-of/linux-files/index.ts
new file mode 100644
index 00000000..bc9ee85b
--- /dev/null
+++ b/mods/telemetry/hooks/context/probe-of/linux-files/index.ts
@@ -0,0 +1,3 @@
+export type * from './linux-files.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/probe-of/linux-files/linux-files.ts b/mods/telemetry/hooks/context/probe-of/linux-files/linux-files.ts
new file mode 100644
index 00000000..f8551e55
--- /dev/null
+++ b/mods/telemetry/hooks/context/probe-of/linux-files/linux-files.ts
@@ -0,0 +1,12 @@
+import type Deployment from '../../../deployment'
+import type { LinuxDistro } from '../../linux-distro-of'
+
+/**
+ * What the Linux files say for the rows: the distribution, the WSL release,
+ * and the two deployments whose signal is a file (EC2, Docker).
+ */
+export type LinuxFiles = {
+ readonly distro: LinuxDistro
+ readonly wslVersion: string | undefined
+ readonly fileSignals: readonly Deployment.DeploymentSignal[]
+}
diff --git a/mods/telemetry/hooks/context/probe-of/probe-of.ts b/mods/telemetry/hooks/context/probe-of/probe-of.ts
new file mode 100644
index 00000000..8231cd28
--- /dev/null
+++ b/mods/telemetry/hooks/context/probe-of/probe-of.ts
@@ -0,0 +1,54 @@
+import type { TelemetryDeps } from '../../telemetry-deps'
+import Identity from '../identity'
+import Machine from '../machine'
+import type { Probe } from '../probe'
+import { remoteHashOf } from '../remote-hash-of'
+import { vcsOf } from '../vcs-of'
+import { linuxFilesOf } from './linux-files-of'
+
+/**
+ * Gathers what holds for the whole session through the nouns beneath: the
+ * variables, the global config, one machine probe, the directory, the remote.
+ *
+ * Each read that fails leaves its part empty; the Linux files are read on
+ * Linux alone.
+ *
+ * @param deps the calls on the nouns beneath
+ * @param isInteractive whether a person is at the prompt
+ * @returns what was gathered, for context-of to shape
+ */
+export async function probeOf(
+ deps: TelemetryDeps,
+ isInteractive: boolean,
+): Promise<Probe> {
+ const [facts, signals, location, environment, cwd, repo] = await Promise.all([
+ deps.facts(),
+ deps.deployment(),
+ deps.configLocation(),
+ deps.environment(),
+ deps.cwd().catch(() => undefined),
+ deps.repo().catch(() => null),
+ ])
+
+ const [identity, machine, vcs, remoteHash] = await Promise.all([
+ Identity.identityOf(deps.read, location, environment.userType === 'ant'),
+ Machine.machineOf(deps.run, facts),
+ cwd === undefined ? undefined : vcsOf(deps.list, cwd, facts.hasP4Port),
+ remoteHashOf(repo?.remote),
+ ])
+
+ const files = await linuxFilesOf(deps, machine.platformRaw === 'linux')
+
+ return {
+ facts,
+ signals: [...signals, ...files.fileSignals],
+ identity,
+ machine,
+ platform: Machine.platformOf(facts.hostPlatform, machine.platformRaw),
+ isInteractive,
+ distro: files.distro,
+ wslVersion: files.wslVersion,
+ vcs,
+ remoteHash,
+ }
+}
diff --git a/mods/telemetry/hooks/context/probe/index.ts b/mods/telemetry/hooks/context/probe/index.ts
new file mode 100644
index 00000000..d374442e
--- /dev/null
+++ b/mods/telemetry/hooks/context/probe/index.ts
@@ -0,0 +1,3 @@
+export type * from './probe.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/probe/probe.ts b/mods/telemetry/hooks/context/probe/probe.ts
new file mode 100644
index 00000000..fcc8061d
--- /dev/null
+++ b/mods/telemetry/hooks/context/probe/probe.ts
@@ -0,0 +1,22 @@
+import type Deployment from '../../deployment'
+import type { Facts } from '../../facts'
+import type { Identity } from '../identity'
+import type { LinuxDistro } from '../linux-distro-of'
+import type { Machine } from '../machine'
+
+/**
+ * Everything gathered for the session's context before it is shaped: the
+ * variables, the identity, the machine, the Linux files and the directory.
+ */
+export type Probe = {
+ readonly facts: Facts
+ readonly signals: readonly Deployment.DeploymentSignal[]
+ readonly identity: Identity
+ readonly machine: Machine
+ readonly platform: string
+ readonly isInteractive: boolean
+ readonly distro: LinuxDistro
+ readonly wslVersion: string | undefined
+ readonly vcs: string | undefined
+ readonly remoteHash: string | undefined
+}
diff --git a/mods/telemetry/hooks/context/remote-hash-of/hex-of/hex-of.ts b/mods/telemetry/hooks/context/remote-hash-of/hex-of/hex-of.ts
new file mode 100644
index 00000000..4a3fd6c3
--- /dev/null
+++ b/mods/telemetry/hooks/context/remote-hash-of/hex-of/hex-of.ts
@@ -0,0 +1,12 @@
+import { HEX_RADIX } from './hex-radix'
+
+/**
+ * A buffer's bytes as lowercase hex, two digits each.
+ *
+ * @param buffer the bytes
+ * @returns the hex text
+ */
+export const hexOf = (buffer: ArrayBuffer) =>
+ [...new Uint8Array(buffer)]
+ .map(byte => byte.toString(HEX_RADIX).padStart(2, '0'))
+ .join('')
diff --git a/mods/telemetry/hooks/context/remote-hash-of/hex-of/hex-radix/hex-radix.ts b/mods/telemetry/hooks/context/remote-hash-of/hex-of/hex-radix/hex-radix.ts
new file mode 100644
index 00000000..31af0603
--- /dev/null
+++ b/mods/telemetry/hooks/context/remote-hash-of/hex-of/hex-radix/hex-radix.ts
@@ -0,0 +1,4 @@
+/**
+ * Sixteen: the radix a byte is written in as two hex digits.
+ */
+export const HEX_RADIX = 16
diff --git a/mods/telemetry/hooks/context/remote-hash-of/hex-of/hex-radix/index.ts b/mods/telemetry/hooks/context/remote-hash-of/hex-of/hex-radix/index.ts
new file mode 100644
index 00000000..5b9c6ab2
--- /dev/null
+++ b/mods/telemetry/hooks/context/remote-hash-of/hex-of/hex-radix/index.ts
@@ -0,0 +1,3 @@
+export * from './hex-radix.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/remote-hash-of/hex-of/index.ts b/mods/telemetry/hooks/context/remote-hash-of/hex-of/index.ts
new file mode 100644
index 00000000..e2e11088
--- /dev/null
+++ b/mods/telemetry/hooks/context/remote-hash-of/hex-of/index.ts
@@ -0,0 +1,4 @@
+export * from './hex-of.js'
+export * from './hex-radix'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/remote-hash-of/index.ts b/mods/telemetry/hooks/context/remote-hash-of/index.ts
new file mode 100644
index 00000000..2df06685
--- /dev/null
+++ b/mods/telemetry/hooks/context/remote-hash-of/index.ts
@@ -0,0 +1,6 @@
+export * from './hex-of'
+export * from './normalized-remote-of'
+export * from './remote-hash-length'
+export * from './remote-hash-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/remote-hash-of/normalized-remote-of/index.ts b/mods/telemetry/hooks/context/remote-hash-of/normalized-remote-of/index.ts
new file mode 100644
index 00000000..e118b325
--- /dev/null
+++ b/mods/telemetry/hooks/context/remote-hash-of/normalized-remote-of/index.ts
@@ -0,0 +1,3 @@
+export * from './normalized-remote-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/remote-hash-of/normalized-remote-of/normalized-remote-of.ts b/mods/telemetry/hooks/context/remote-hash-of/normalized-remote-of/normalized-remote-of.ts
new file mode 100644
index 00000000..95212248
--- /dev/null
+++ b/mods/telemetry/hooks/context/remote-hash-of/normalized-remote-of/normalized-remote-of.ts
@@ -0,0 +1,24 @@
+/**
+ * A git remote URL as the CLI normalizes it before hashing: `host/path`
+ * lowercased, the user and a trailing `.git` dropped.
+ *
+ * The scp form (`git@host:owner/repo`) and the URL form (`https://` or
+ * `ssh://`) alike; undefined for anything else.
+ *
+ * @param remote the remote URL as `$.session.repo()` answers it
+ * @returns the normalized remote, or undefined
+ */
+export function normalizedRemoteOf(remote: string): string | undefined {
+ const trimmed = remote.trim()
+
+ const [, host, path] =
+ /^git@([^:/@]+):(.+?)(?:\.git)?$/.exec(trimmed) ??
+ /^(?:https?|ssh):\/\/(?:[^@/?#]*@)?([^/?#@]+)\/(.+?)(?:\.git)?$/.exec(
+ trimmed,
+ ) ??
+ []
+
+ const isRecognized = host !== undefined && path !== undefined
+
+ return isRecognized ? `${host}/${path}`.toLowerCase() : undefined
+}
diff --git a/mods/telemetry/hooks/context/remote-hash-of/remote-hash-length/index.ts b/mods/telemetry/hooks/context/remote-hash-of/remote-hash-length/index.ts
new file mode 100644
index 00000000..1c30ca3a
--- /dev/null
+++ b/mods/telemetry/hooks/context/remote-hash-of/remote-hash-length/index.ts
@@ -0,0 +1,3 @@
+export * from './remote-hash-length.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/remote-hash-of/remote-hash-length/remote-hash-length.ts b/mods/telemetry/hooks/context/remote-hash-of/remote-hash-length/remote-hash-length.ts
new file mode 100644
index 00000000..305b91cc
--- /dev/null
+++ b/mods/telemetry/hooks/context/remote-hash-of/remote-hash-length/remote-hash-length.ts
@@ -0,0 +1,5 @@
+/**
+ * How many hex digits of the remote's SHA-256 a row carries as `rh`: the
+ * CLI's own sixteen, so the plugin's rows join where the CLI's do.
+ */
+export const REMOTE_HASH_LENGTH = 16
diff --git a/mods/telemetry/hooks/context/remote-hash-of/remote-hash-of.ts b/mods/telemetry/hooks/context/remote-hash-of/remote-hash-of.ts
new file mode 100644
index 00000000..1847c282
--- /dev/null
+++ b/mods/telemetry/hooks/context/remote-hash-of/remote-hash-of.ts
@@ -0,0 +1,24 @@
+import { hexOf } from './hex-of'
+import { normalizedRemoteOf } from './normalized-remote-of'
+import { REMOTE_HASH_LENGTH } from './remote-hash-length'
+
+/**
+ * The rows' `rh`: the first hex digits of the SHA-256 of the session's
+ * normalized origin remote, the key the CLI's own rows join a repository by.
+ *
+ * @param remote the origin remote as `$.session.repo()` answers it
+ * @returns the hash, or undefined outside a recognized remote
+ */
+export async function remoteHashOf(
+ remote: string | null | undefined,
+): Promise<string | undefined> {
+ const normalized = remote ? normalizedRemoteOf(remote) : undefined
+
+ if (normalized === undefined) {
+ return undefined
+ }
+
+ return hexOf(
+ await crypto.subtle.digest('SHA-256', new TextEncoder().encode(normalized)),
+ ).slice(0, REMOTE_HASH_LENGTH)
+}
diff --git a/mods/telemetry/hooks/context/session-fields-of/index.ts b/mods/telemetry/hooks/context/session-fields-of/index.ts
new file mode 100644
index 00000000..c6d7bf2a
--- /dev/null
+++ b/mods/telemetry/hooks/context/session-fields-of/index.ts
@@ -0,0 +1,3 @@
+export * from './session-fields-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/session-fields-of/session-fields-of.ts b/mods/telemetry/hooks/context/session-fields-of/session-fields-of.ts
new file mode 100644
index 00000000..26e1aa09
--- /dev/null
+++ b/mods/telemetry/hooks/context/session-fields-of/session-fields-of.ts
@@ -0,0 +1,21 @@
+import type { Facts } from '../../facts'
+import { clientTypeOf } from '../client-type-of'
+import { entrypointOf } from '../entrypoint-of'
+import type { SessionFields } from '../session-fields'
+import { versionOf } from '../version-of'
+
+/**
+ * The session's constant row fields from the variables as read: the client,
+ * the entrypoint, the SDK's version and a benchmark run's ids.
+ *
+ * @param facts the variables as read once for the session
+ * @returns the fields
+ */
+export const sessionFieldsOf = (facts: Facts): SessionFields => ({
+ clientType: clientTypeOf(facts),
+ entrypoint: entrypointOf(facts.entrypoint),
+ agentSdkVersion: versionOf(facts.agentSdkVersion),
+ sweBenchRunId: facts.sweBenchRunId || undefined,
+ sweBenchInstanceId: facts.sweBenchInstanceId || undefined,
+ sweBenchTaskId: facts.sweBenchTaskId || undefined,
+})
diff --git a/mods/telemetry/hooks/context/session-fields/index.ts b/mods/telemetry/hooks/context/session-fields/index.ts
new file mode 100644
index 00000000..767f7129
--- /dev/null
+++ b/mods/telemetry/hooks/context/session-fields/index.ts
@@ -0,0 +1,3 @@
+export type * from './session-fields.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/session-fields/session-fields.ts b/mods/telemetry/hooks/context/session-fields/session-fields.ts
new file mode 100644
index 00000000..1f529b8a
--- /dev/null
+++ b/mods/telemetry/hooks/context/session-fields/session-fields.ts
@@ -0,0 +1,15 @@
+/**
+ * The row fields that are the session's for its whole life, before their
+ * keys are spelled for the wire.
+ *
+ * The client, the entrypoint, the SDK and a benchmark run's ids, each
+ * undefined when the environment names none.
+ */
+export type SessionFields = {
+ readonly clientType: string
+ readonly entrypoint: string | undefined
+ readonly agentSdkVersion: string | undefined
+ readonly sweBenchRunId: string | undefined
+ readonly sweBenchInstanceId: string | undefined
+ readonly sweBenchTaskId: string | undefined
+}
diff --git a/mods/telemetry/hooks/context/shell-of/index.ts b/mods/telemetry/hooks/context/shell-of/index.ts
new file mode 100644
index 00000000..5e40c92a
--- /dev/null
+++ b/mods/telemetry/hooks/context/shell-of/index.ts
@@ -0,0 +1,4 @@
+export * from './known-shells'
+export * from './shell-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/shell-of/known-shells/index.ts b/mods/telemetry/hooks/context/shell-of/known-shells/index.ts
new file mode 100644
index 00000000..f01e8e03
--- /dev/null
+++ b/mods/telemetry/hooks/context/shell-of/known-shells/index.ts
@@ -0,0 +1,3 @@
+export * from './known-shells.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/shell-of/known-shells/known-shells.ts b/mods/telemetry/hooks/context/shell-of/known-shells/known-shells.ts
new file mode 100644
index 00000000..b5a97f40
--- /dev/null
+++ b/mods/telemetry/hooks/context/shell-of/known-shells/known-shells.ts
@@ -0,0 +1,23 @@
+/**
+ * The shell names a row may carry, the CLI's own list: the login shell's
+ * basename when it is one of these, else `other`; `none` when unset.
+ */
+export const KNOWN_SHELLS: readonly string[] = [
+ 'zsh',
+ 'bash',
+ 'fish',
+ 'sh',
+ 'dash',
+ 'ash',
+ 'ksh',
+ 'tcsh',
+ 'csh',
+ 'nu',
+ 'nushell',
+ 'pwsh',
+ 'powershell',
+ 'cmd',
+ 'elvish',
+ 'xonsh',
+ 'ion',
+]
diff --git a/mods/telemetry/hooks/context/shell-of/shell-of.ts b/mods/telemetry/hooks/context/shell-of/shell-of.ts
new file mode 100644
index 00000000..cf39eeb5
--- /dev/null
+++ b/mods/telemetry/hooks/context/shell-of/shell-of.ts
@@ -0,0 +1,24 @@
+import { KNOWN_SHELLS } from './known-shells'
+
+/**
+ * The row's `shell`: the login shell's basename when the CLI's list knows
+ * it, `other` when it does not, `none` when no shell is set.
+ *
+ * The path itself, which can name a person, never reaches a row.
+ *
+ * @param shellPath SHELL (or COMSPEC on Windows) as read
+ * @returns the shell's name from the closed list
+ */
+export function shellOf(shellPath: string | undefined) {
+ const base = (shellPath ?? '')
+ .split(/[/\\]/)
+ .at(-1)
+ ?.toLowerCase()
+ .replace(/\.exe$/, '')
+
+ if (!shellPath) {
+ return 'none'
+ }
+
+ return base !== undefined && KNOWN_SHELLS.includes(base) ? base : 'other'
+}
diff --git a/mods/telemetry/hooks/context/terminal-of/index.ts b/mods/telemetry/hooks/context/terminal-of/index.ts
new file mode 100644
index 00000000..25c7047a
--- /dev/null
+++ b/mods/telemetry/hooks/context/terminal-of/index.ts
@@ -0,0 +1,4 @@
+export * from './jetbrains-ides'
+export * from './terminal-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/terminal-of/jetbrains-ides/index.ts b/mods/telemetry/hooks/context/terminal-of/jetbrains-ides/index.ts
new file mode 100644
index 00000000..c6555a51
--- /dev/null
+++ b/mods/telemetry/hooks/context/terminal-of/jetbrains-ides/index.ts
@@ -0,0 +1,3 @@
+export * from './jetbrains-ides.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/terminal-of/jetbrains-ides/jetbrains-ides.ts b/mods/telemetry/hooks/context/terminal-of/jetbrains-ides/jetbrains-ides.ts
new file mode 100644
index 00000000..c7454f04
--- /dev/null
+++ b/mods/telemetry/hooks/context/terminal-of/jetbrains-ides/jetbrains-ides.ts
@@ -0,0 +1,22 @@
+/**
+ * The JetBrains IDEs the CLI tells apart by the terminal's bundle
+ * identifier, in the order it tries them.
+ */
+export const JETBRAINS_IDES: readonly string[] = [
+ 'pycharm',
+ 'intellij',
+ 'webstorm',
+ 'phpstorm',
+ 'rubymine',
+ 'clion',
+ 'goland',
+ 'rider',
+ 'datagrip',
+ 'appcode',
+ 'dataspell',
+ 'aqua',
+ 'gateway',
+ 'fleet',
+ 'jetbrains',
+ 'androidstudio',
+]
diff --git a/mods/telemetry/hooks/context/terminal-of/terminal-of.ts b/mods/telemetry/hooks/context/terminal-of/terminal-of.ts
new file mode 100644
index 00000000..266fd749
--- /dev/null
+++ b/mods/telemetry/hooks/context/terminal-of/terminal-of.ts
@@ -0,0 +1,74 @@
+import type { Facts } from '../../facts'
+import { JETBRAINS_IDES } from './jetbrains-ides'
+
+/**
+ * The row's `terminal` as the CLI names the terminal it runs in, read off
+ * the same variables in the same order.
+ *
+ * The IDE hosts first, then TERM and TERM_PROGRAM, the multiplexers, the
+ * Linux and Windows terminals, WSL, an ssh session, and what TERM still
+ * tells; `non-interactive` with no person at the prompt, else `unknown`.
+ *
+ * @param facts the variables as read once for the session
+ * @param platform the row's platform (the JetBrains check differs on darwin)
+ * @param isInteractive whether a person is at the prompt
+ * @returns the terminal's name
+ */
+export function terminalOf(
+ facts: Facts,
+ platform: string,
+ isInteractive: boolean,
+) {
+ const askpass = (facts.vscodeGitAskpassMain ?? '').toLowerCase()
+ const bundle = (facts.bundleIdentifier ?? '').toLowerCase()
+ const term = facts.term ?? ''
+ const termProgram = facts.termProgram ?? ''
+ const isJediTerm = facts.terminalEmulator === 'JetBrains-JediTerm'
+ const jetbrains = JETBRAINS_IDES.find(ide => bundle.includes(ide))
+
+ const candidates: readonly (readonly [boolean, string])[] = [
+ [isJediTerm && platform !== 'darwin', 'pycharm'],
+ [facts.hasCursorTraceId || askpass.includes('cursor'), 'cursor'],
+ [askpass.includes('windsurf'), 'windsurf'],
+ [askpass.includes('antigravity'), 'antigravity'],
+ [bundle.includes('vscodium'), 'codium'],
+ [bundle.includes('windsurf') || bundle.includes('devin'), 'windsurf'],
+ [bundle.includes('com.google.android.studio'), 'androidstudio'],
+ [jetbrains !== undefined, jetbrains ?? ''],
+ [facts.hasVisualStudioVersion, 'visualstudio'],
+ [isJediTerm, 'pycharm'],
+ [term === 'xterm-ghostty', 'ghostty'],
+ [term.includes('kitty'), 'kitty'],
+ [/^devin([ -]desktop)?$/i.test(termProgram), 'windsurf'],
+ [termProgram !== '', termProgram],
+ [facts.hasTmux, 'tmux'],
+ [facts.hasSty, 'screen'],
+ [facts.hasKonsoleVersion, 'konsole'],
+ [facts.hasGnomeTerminalService, 'gnome-terminal'],
+ [facts.hasXtermVersion, 'xterm'],
+ [facts.hasVteVersion, 'vte-based'],
+ [facts.hasTerminatorUuid, 'terminator'],
+ [facts.hasKittyWindowId, 'kitty'],
+ [facts.hasAlacrittyLog, 'alacritty'],
+ [facts.hasTilixId, 'tilix'],
+ [facts.hasWtSession, 'windows-terminal'],
+ [facts.hasSessionName && term === 'cygwin', 'cygwin'],
+ [facts.msystem !== undefined, (facts.msystem ?? '').toLowerCase()],
+ [
+ facts.hasConEmuAnsi || facts.hasConEmuPid || facts.hasConEmuTask,
+ 'conemu',
+ ],
+ [facts.wslDistroName !== undefined, `wsl-${facts.wslDistroName}`],
+ [
+ facts.hasSshConnection || facts.hasSshClient || facts.hasSshTty,
+ 'ssh-session',
+ ],
+ [term.includes('alacritty'), 'alacritty'],
+ [term.includes('rxvt'), 'rxvt'],
+ [term.includes('termite'), 'termite'],
+ [term !== '', term],
+ [!isInteractive, 'non-interactive'],
+ ]
+
+ return candidates.find(([isHeld]) => isHeld)?.[1] ?? 'unknown'
+}
diff --git a/mods/telemetry/hooks/context/vcs-of/distinct/distinct.ts b/mods/telemetry/hooks/context/vcs-of/distinct/distinct.ts
new file mode 100644
index 00000000..d49b6f80
--- /dev/null
+++ b/mods/telemetry/hooks/context/vcs-of/distinct/distinct.ts
@@ -0,0 +1,17 @@
+/**
+ * The list with each value once, first occurrence kept, order kept.
+ *
+ * @param values the list
+ * @returns the distinct values
+ */
+export function distinct(values: readonly string[]): string[] {
+ const seen = new Set<string>()
+
+ return values.filter(value => {
+ const isSeen = seen.has(value)
+
+ seen.add(value)
+
+ return !isSeen
+ })
+}
diff --git a/mods/telemetry/hooks/context/vcs-of/distinct/index.ts b/mods/telemetry/hooks/context/vcs-of/distinct/index.ts
new file mode 100644
index 00000000..049f2fd8
--- /dev/null
+++ b/mods/telemetry/hooks/context/vcs-of/distinct/index.ts
@@ -0,0 +1,3 @@
+export * from './distinct.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/vcs-of/index.ts b/mods/telemetry/hooks/context/vcs-of/index.ts
new file mode 100644
index 00000000..60cf1adf
--- /dev/null
+++ b/mods/telemetry/hooks/context/vcs-of/index.ts
@@ -0,0 +1,5 @@
+export * from './distinct'
+export * from './vcs-markers'
+export * from './vcs-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/vcs-of/vcs-markers/index.ts b/mods/telemetry/hooks/context/vcs-of/vcs-markers/index.ts
new file mode 100644
index 00000000..6464d2d5
--- /dev/null
+++ b/mods/telemetry/hooks/context/vcs-of/vcs-markers/index.ts
@@ -0,0 +1,3 @@
+export * from './vcs-markers.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/vcs-of/vcs-markers/vcs-markers.ts b/mods/telemetry/hooks/context/vcs-of/vcs-markers/vcs-markers.ts
new file mode 100644
index 00000000..a3cdb2f4
--- /dev/null
+++ b/mods/telemetry/hooks/context/vcs-of/vcs-markers/vcs-markers.ts
@@ -0,0 +1,14 @@
+/**
+ * The entries that mark a working directory as a version-control checkout,
+ * each with the system it names, in the CLI's own order.
+ */
+export const VCS_MARKERS: readonly (readonly [string, string])[] = [
+ ['.git', 'git'],
+ ['.hg', 'mercurial'],
+ ['.svn', 'svn'],
+ ['.p4config', 'perforce'],
+ ['$tf', 'tfs'],
+ ['.tfvc', 'tfs'],
+ ['.jj', 'jujutsu'],
+ ['.sl', 'sapling'],
+]
diff --git a/mods/telemetry/hooks/context/vcs-of/vcs-of.ts b/mods/telemetry/hooks/context/vcs-of/vcs-of.ts
new file mode 100644
index 00000000..2a2a9285
--- /dev/null
+++ b/mods/telemetry/hooks/context/vcs-of/vcs-of.ts
@@ -0,0 +1,38 @@
+import type { FsEntry } from 'claude-code'
+
+import { distinct } from './distinct'
+import { VCS_MARKERS } from './vcs-markers'
+
+/**
+ * The row's `vcs`: the version-control systems whose marker is in the
+ * session's directory, Perforce too when P4PORT is set, comma-joined.
+ *
+ * @param list lists a directory
+ * @param cwd the session's directory
+ * @param hasP4Port whether P4PORT is set
+ * @returns the systems found, or undefined for none or an unlistable directory
+ */
+export async function vcsOf(
+ list: (path: string) => Promise<readonly FsEntry[]>,
+ cwd: string,
+ hasP4Port: boolean,
+): Promise<string | undefined> {
+ let entries: readonly FsEntry[]
+
+ try {
+ entries = await list(cwd)
+ } catch {
+ entries = []
+ }
+
+ const names = new Set(entries.map(entry => entry.name))
+
+ const found = distinct([
+ ...(hasP4Port ? ['perforce'] : []),
+ ...VCS_MARKERS.flatMap(([marker, system]) =>
+ names.has(marker) ? [system] : [],
+ ),
+ ])
+
+ return found.length > 0 ? found.join(',') : undefined
+}
diff --git a/mods/telemetry/hooks/context/version-of/index.ts b/mods/telemetry/hooks/context/version-of/index.ts
new file mode 100644
index 00000000..e115d6d3
--- /dev/null
+++ b/mods/telemetry/hooks/context/version-of/index.ts
@@ -0,0 +1,3 @@
+export * from './version-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/version-of/version-of.ts b/mods/telemetry/hooks/context/version-of/version-of.ts
new file mode 100644
index 00000000..605e7e00
--- /dev/null
+++ b/mods/telemetry/hooks/context/version-of/version-of.ts
@@ -0,0 +1,13 @@
+/**
+ * A version string reduced to what a row may carry, as the CLI reduces the
+ * Agent SDK's: its semver core, `unknown` as said, else `other`.
+ *
+ * @param version the variable as read; undefined stays undefined
+ * @returns the version for the row, or undefined
+ */
+export function versionOf(version: string | undefined) {
+ const isKept = version === undefined || version === 'unknown'
+ const core = /^\d{1,8}\.\d{1,8}\.\d{1,8}(?!\d)/.exec(version ?? '')?.[0]
+
+ return isKept ? version : (core ?? 'other')
+}
diff --git a/mods/telemetry/hooks/context/wsl-version-of/index.ts b/mods/telemetry/hooks/context/wsl-version-of/index.ts
new file mode 100644
index 00000000..b3aa27e5
--- /dev/null
+++ b/mods/telemetry/hooks/context/wsl-version-of/index.ts
@@ -0,0 +1,3 @@
+export * from './wsl-version-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/context/wsl-version-of/wsl-version-of.ts b/mods/telemetry/hooks/context/wsl-version-of/wsl-version-of.ts
new file mode 100644
index 00000000..6dfcd83e
--- /dev/null
+++ b/mods/telemetry/hooks/context/wsl-version-of/wsl-version-of.ts
@@ -0,0 +1,22 @@
+/**
+ * The WSL release a Linux kernel string names, as the CLI reads
+ * `/proc/version`: the digit after `WSL`, `1` for the `Microsoft` kernels.
+ *
+ * @param readProcVersion reads `/proc/version` as text
+ * @returns the WSL version, or undefined off WSL or when the file is unread
+ */
+export async function wslVersionOf(
+ readProcVersion: () => Promise<string>,
+): Promise<string | undefined> {
+ let kernel: string
+
+ try {
+ kernel = (await readProcVersion()).toLowerCase()
+ } catch {
+ return undefined
+ }
+
+ const isMicrosoft = kernel.includes('microsoft')
+
+ return /wsl(\d+)/.exec(kernel)?.[1] ?? (isMicrosoft ? '1' : undefined)
+}
diff --git a/mods/telemetry/hooks/deployment/deployment-name/deployment-name.ts b/mods/telemetry/hooks/deployment/deployment-name/deployment-name.ts
new file mode 100644
index 00000000..537ad3ea
--- /dev/null
+++ b/mods/telemetry/hooks/deployment/deployment-name/deployment-name.ts
@@ -0,0 +1,6 @@
+import type { DEPLOYMENTS } from '../deployments'
+
+/**
+ * One of the deployments a row can name (DEPLOYMENTS).
+ */
+export type DeploymentName = (typeof DEPLOYMENTS)[number]
diff --git a/mods/telemetry/hooks/deployment/deployment-name/index.ts b/mods/telemetry/hooks/deployment/deployment-name/index.ts
new file mode 100644
index 00000000..deafbf71
--- /dev/null
+++ b/mods/telemetry/hooks/deployment/deployment-name/index.ts
@@ -0,0 +1,3 @@
+export type * from './deployment-name.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/deployment/deployment-of.ts b/mods/telemetry/hooks/deployment/deployment-of.ts
new file mode 100644
index 00000000..885948cc
--- /dev/null
+++ b/mods/telemetry/hooks/deployment/deployment-of.ts
@@ -0,0 +1,18 @@
+import type { DeploymentSignal } from './deployment-signal'
+import { DEPLOYMENTS } from './deployments'
+
+/**
+ * The row's `deployment_environment`: the first deployment in the CLI's
+ * order whose signal holds, else `unknown-<platform>` as it names none.
+ *
+ * @param signals each deployment read, with whether its signal holds
+ * @param platform the row's platform, for the fallback
+ * @returns the deployment's name
+ */
+export const deploymentOf = (
+ signals: readonly DeploymentSignal[],
+ platform: string,
+) =>
+ DEPLOYMENTS.find(deployment =>
+ signals.some(([name, isHeld]) => isHeld && name === deployment),
+ ) ?? `unknown-${platform}`
diff --git a/mods/telemetry/hooks/deployment/deployment-signal/deployment-signal.ts b/mods/telemetry/hooks/deployment/deployment-signal/deployment-signal.ts
new file mode 100644
index 00000000..744eec50
--- /dev/null
+++ b/mods/telemetry/hooks/deployment/deployment-signal/deployment-signal.ts
@@ -0,0 +1,7 @@
+import type { DeploymentName } from '../deployment-name'
+
+/**
+ * One deployment and whether its signal holds: a variable set, on, or
+ * holding the value the CLI looks for, or one of the two marker files.
+ */
+export type DeploymentSignal = readonly [DeploymentName, boolean]
diff --git a/mods/telemetry/hooks/deployment/deployment-signal/index.ts b/mods/telemetry/hooks/deployment/deployment-signal/index.ts
new file mode 100644
index 00000000..2bc82862
--- /dev/null
+++ b/mods/telemetry/hooks/deployment/deployment-signal/index.ts
@@ -0,0 +1,3 @@
+export type * from './deployment-signal.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/deployment/deployments/deployments.ts b/mods/telemetry/hooks/deployment/deployments/deployments.ts
new file mode 100644
index 00000000..e474e2fc
--- /dev/null
+++ b/mods/telemetry/hooks/deployment/deployments/deployments.ts
@@ -0,0 +1,43 @@
+/**
+ * Every deployment a row can name, in the order the CLI's own detection
+ * tries them; the first whose signal holds names the row.
+ *
+ * Cloud development environments, then cloud platforms, CI, and container
+ * orchestration last.
+ */
+export const DEPLOYMENTS = [
+ 'codespaces',
+ 'gitpod',
+ 'coder',
+ 'devpod',
+ 'daytona',
+ 'gcp-cloud-workstations',
+ 'aws-cloud9',
+ 'replit',
+ 'glitch',
+ 'vercel',
+ 'railway',
+ 'render',
+ 'netlify',
+ 'heroku',
+ 'fly.io',
+ 'cloudflare-pages',
+ 'deno-deploy',
+ 'aws-lambda',
+ 'aws-fargate',
+ 'aws-ecs',
+ 'aws-ec2',
+ 'gcp-cloud-run',
+ 'gcp',
+ 'azure-app-service',
+ 'azure-functions',
+ 'digitalocean-app-platform',
+ 'huggingface-spaces',
+ 'github-actions',
+ 'gitlab-ci',
+ 'circleci',
+ 'buildkite',
+ 'ci',
+ 'kubernetes',
+ 'docker',
+] as const
diff --git a/mods/telemetry/hooks/deployment/deployments/index.ts b/mods/telemetry/hooks/deployment/deployments/index.ts
new file mode 100644
index 00000000..e7ac5a12
--- /dev/null
+++ b/mods/telemetry/hooks/deployment/deployments/index.ts
@@ -0,0 +1,3 @@
+export * from './deployments.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/deployment/index.ts b/mods/telemetry/hooks/deployment/index.ts
new file mode 100644
index 00000000..97f2f9d2
--- /dev/null
+++ b/mods/telemetry/hooks/deployment/index.ts
@@ -0,0 +1,6 @@
+export * from './deployment-name'
+export * from './deployment-of.js'
+export * from './deployment-signal'
+export * from './deployments'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/entries/batch-of.ts b/mods/telemetry/hooks/entries/batch-of.ts
index a8a1c919..8e8ec74d 100644
--- a/mods/telemetry/hooks/entries/batch-of.ts
+++ b/mods/telemetry/hooks/entries/batch-of.ts
@@ -1,34 +1,23 @@
-import type { Fields } from './fields'
-import type { RowSession } from './row-session'
+import type Batching from '../batching'
+import type { BatchStamp } from './batch-stamp'
+import { eventDataOf } from './event-data-of'
+import { wireOf } from './wire-of'
/**
- * The first-party event batch for one entry, shaped as the CLI's own
- * event exporter shapes its batches.
+ * The first-party event batch for the queued rows, shaped as the CLI's own
+ * event exporter shapes its batches: one ClaudeCodeInternalEvent per row.
*
- * The ClaudeCodeInternalEvent JSON, one event per batch; the properties ride
- * as base64 JSON in `additional_metadata`, the field the exporter uses;
- * `user_type` is what the environment's USER_TYPE says of the build.
- *
- * @param fields the entry as checked
- * @param session the session's id and model, and the build's user type
- * @returns the batch's JSON text, ready to send to the exporter
+ * @param rows the rows as they were queued, oldest first
+ * @param stamp what the batch stamps on every row
+ * @returns the batch's JSON text, ready to POST to the ingest
*/
-export function batchOf(fields: Fields, session: RowSession) {
- const metadata = JSON.stringify(fields.props)
-
- return JSON.stringify({
- events: [
- {
- event_type: 'ClaudeCodeInternalEvent',
- event_data: {
- event_name: fields.name,
- client_timestamp: new Date().toISOString(),
- session_id: session.sessionId,
- model: session.model,
- user_type: session.userType,
- additional_metadata: btoa(metadata),
- },
- },
- ],
+export const batchOf = (
+ rows: readonly Batching.PendingRow[],
+ stamp: BatchStamp,
+) =>
+ JSON.stringify({
+ events: rows.map(row => ({
+ event_type: 'ClaudeCodeInternalEvent',
+ event_data: wireOf(eventDataOf(row, stamp)),
+ })),
})
-}
diff --git a/mods/telemetry/hooks/entries/batch-stamp/batch-stamp.ts b/mods/telemetry/hooks/entries/batch-stamp/batch-stamp.ts
new file mode 100644
index 00000000..d6df9bdc
--- /dev/null
+++ b/mods/telemetry/hooks/entries/batch-stamp/batch-stamp.ts
@@ -0,0 +1,17 @@
+import type { Context } from '../../context'
+
+/**
+ * What one batch stamps on each of its rows beside the row's own fields:
+ * the session as read when the batch went out, and its context.
+ *
+ * `userType` is `ant` or `external` as USER_TYPE says of the build;
+ * `isClaudeAiAuth` follows the credential the batch is sent with.
+ */
+export type BatchStamp = {
+ readonly sessionId: string
+ readonly model: string
+ readonly userType: string
+ readonly isInteractive: boolean
+ readonly isClaudeAiAuth: boolean
+ readonly context: Context
+}
diff --git a/mods/telemetry/hooks/entries/batch-stamp/index.ts b/mods/telemetry/hooks/entries/batch-stamp/index.ts
new file mode 100644
index 00000000..4d3534c4
--- /dev/null
+++ b/mods/telemetry/hooks/entries/batch-stamp/index.ts
@@ -0,0 +1,3 @@
+export type * from './batch-stamp.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/entries/event-data-of/auth-of/auth-of.ts b/mods/telemetry/hooks/entries/event-data-of/auth-of/auth-of.ts
new file mode 100644
index 00000000..2080ee72
--- /dev/null
+++ b/mods/telemetry/hooks/entries/event-data-of/auth-of/auth-of.ts
@@ -0,0 +1,21 @@
+import type { Context } from '../../../context'
+
+/**
+ * The row's `auth`: the signed-in account's and organization's ids, or
+ * undefined when the identity holds neither (an API key, no login).
+ *
+ * @param identity who the rows are from
+ * @returns the ids, or undefined
+ */
+export function authOf(identity: Context['identity']) {
+ const hasEither =
+ identity.accountUuid !== undefined ||
+ identity.organizationUuid !== undefined
+
+ return hasEither
+ ? {
+ accountUuid: identity.accountUuid,
+ organizationUuid: identity.organizationUuid,
+ }
+ : undefined
+}
diff --git a/mods/telemetry/hooks/entries/event-data-of/auth-of/index.ts b/mods/telemetry/hooks/entries/event-data-of/auth-of/index.ts
new file mode 100644
index 00000000..5a2692d6
--- /dev/null
+++ b/mods/telemetry/hooks/entries/event-data-of/auth-of/index.ts
@@ -0,0 +1,3 @@
+export * from './auth-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/entries/event-data-of/event-data-of.ts b/mods/telemetry/hooks/entries/event-data-of/event-data-of.ts
new file mode 100644
index 00000000..09099f52
--- /dev/null
+++ b/mods/telemetry/hooks/entries/event-data-of/event-data-of.ts
@@ -0,0 +1,31 @@
+import type Batching from '../../batching'
+import type { BatchStamp } from '../batch-stamp'
+import { authOf } from './auth-of'
+import { metadataOf } from './metadata-of'
+
+/**
+ * One row as a ClaudeCodeInternalEvent, keyed as the plugin builds it;
+ * wireOf spells it for the ingest.
+ *
+ * Its id, name and time, who and where it is from, the session's fields,
+ * its `env` block, and its properties in `additionalMetadata`.
+ *
+ * @param row the row as it was queued
+ * @param stamp what the batch stamps on every row
+ * @returns the event's data
+ */
+export const eventDataOf = (row: Batching.PendingRow, stamp: BatchStamp) => ({
+ eventId: row.eventId,
+ eventName: row.fields.name,
+ clientTimestamp: row.loggedAt,
+ deviceId: stamp.context.identity.deviceId,
+ email: stamp.context.identity.email,
+ auth: authOf(stamp.context.identity),
+ sessionId: stamp.sessionId,
+ model: stamp.model,
+ userType: stamp.userType,
+ isInteractive: stamp.isInteractive,
+ ...stamp.context.session,
+ env: { ...stamp.context.environment, isClaudeAiAuth: stamp.isClaudeAiAuth },
+ additionalMetadata: metadataOf(row, stamp.context.remoteHash),
+})
diff --git a/mods/telemetry/hooks/entries/event-data-of/index.ts b/mods/telemetry/hooks/entries/event-data-of/index.ts
new file mode 100644
index 00000000..07c613d1
--- /dev/null
+++ b/mods/telemetry/hooks/entries/event-data-of/index.ts
@@ -0,0 +1,5 @@
+export * from './auth-of'
+export * from './event-data-of.js'
+export * from './metadata-of'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/entries/event-data-of/metadata-of/index.ts b/mods/telemetry/hooks/entries/event-data-of/metadata-of/index.ts
new file mode 100644
index 00000000..90f09c46
--- /dev/null
+++ b/mods/telemetry/hooks/entries/event-data-of/metadata-of/index.ts
@@ -0,0 +1,3 @@
+export * from './metadata-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/entries/event-data-of/metadata-of/metadata-of.ts b/mods/telemetry/hooks/entries/event-data-of/metadata-of/metadata-of.ts
new file mode 100644
index 00000000..49317f95
--- /dev/null
+++ b/mods/telemetry/hooks/entries/event-data-of/metadata-of/metadata-of.ts
@@ -0,0 +1,14 @@
+import type Batching from '../../../batching'
+
+/**
+ * The row's `additional_metadata`: its properties as base64 JSON, the
+ * repository's remote hash beside them as the CLI's own rows carry it.
+ *
+ * @param row the row as it was queued
+ * @param remoteHash the session's remote hash, when it is in a repository
+ * @returns the base64 text
+ */
+export const metadataOf = (
+ row: Batching.PendingRow,
+ remoteHash: string | undefined,
+) => btoa(JSON.stringify({ rh: remoteHash, ...row.fields.props }))
diff --git a/mods/telemetry/hooks/entries/index.ts b/mods/telemetry/hooks/entries/index.ts
index 101dfc4b..ae8dcfb3 100644
--- a/mods/telemetry/hooks/entries/index.ts
+++ b/mods/telemetry/hooks/entries/index.ts
@@ -1,4 +1,5 @@
export * from './batch-of.js'
+export * from './batch-stamp'
export * from './checked-fields.js'
export * from './checked-mark.js'
export * from './checked-props'
@@ -6,6 +7,7 @@ export * from './checked-value'
export * from './choice-token'
export * from './choices-limit'
export * from './core-event-prefix'
+export * from './event-data-of'
export * from './event-prefix'
export * from './feature-prefix'
export * from './fields'
@@ -19,7 +21,7 @@ export * from './mark-kinds'
export * from './method'
export * from './prop-limit'
export * from './refusal'
-export * from './row-session'
export * from './token'
+export * from './wire-of'
export * as default from '.'
diff --git a/mods/telemetry/hooks/entries/row-session/index.ts b/mods/telemetry/hooks/entries/row-session/index.ts
deleted file mode 100644
index 32704bf4..00000000
--- a/mods/telemetry/hooks/entries/row-session/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export type * from './row-session.js'
-
-export * as default from '.'
diff --git a/mods/telemetry/hooks/entries/row-session/row-session.ts b/mods/telemetry/hooks/entries/row-session/row-session.ts
deleted file mode 100644
index f7065c28..00000000
--- a/mods/telemetry/hooks/entries/row-session/row-session.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * What one row says of the session that sent it: its id, its model, and
- * the build's user type (`ant` or `external`) as the environment names it.
- */
-export type RowSession = {
- sessionId: string
- model: string
- userType: string
-}
diff --git a/mods/telemetry/hooks/entries/wire-of/index.ts b/mods/telemetry/hooks/entries/wire-of/index.ts
new file mode 100644
index 00000000..057757d2
--- /dev/null
+++ b/mods/telemetry/hooks/entries/wire-of/index.ts
@@ -0,0 +1,3 @@
+export * from './wire-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/entries/wire-of/wire-of.ts b/mods/telemetry/hooks/entries/wire-of/wire-of.ts
new file mode 100644
index 00000000..5556464e
--- /dev/null
+++ b/mods/telemetry/hooks/entries/wire-of/wire-of.ts
@@ -0,0 +1,24 @@
+import { isRecord } from '../is-record'
+
+/**
+ * A value with every object key respelled for the event-logging ingest:
+ * `platformRaw` as `platform_raw`, all the way down; arrays and leaves kept.
+ *
+ * @param value the row, or a part of it, keyed as the plugin builds it
+ * @returns the same value keyed as the ingest reads it
+ */
+export function wireOf(value: unknown): unknown {
+ const isList = Array.isArray(value)
+ const isObject = isRecord(value)
+
+ return isList
+ ? value.map(wireOf)
+ : isObject
+ ? Object.fromEntries(
+ Object.entries(value).map(([key, member]) => [
+ key.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`),
+ wireOf(member),
+ ]),
+ )
+ : value
+}
diff --git a/mods/telemetry/hooks/environment/environment.ts b/mods/telemetry/hooks/environment/environment.ts
index 0596a320..56d36a76 100644
--- a/mods/telemetry/hooks/environment/environment.ts
+++ b/mods/telemetry/hooks/environment/environment.ts
@@ -1,16 +1,19 @@
/**
- * What the plugin reads of the environment before each row: the
+ * What the plugin reads of the environment before each batch: the
* build's user type and every switch that turns the CLI's analytics off.
*
* Each field is the variable's value as `$.env.get` answers it, undefined
- * when unset; analytics-off/ decides what they mean together.
+ * when unset; is-analytics-off/ decides what they mean together.
*/
export type Environment = {
readonly userType: string | undefined
+ readonly nodeEnv: string | undefined
readonly disableTelemetry: string | undefined
readonly disableNonessentialTraffic: string | undefined
readonly doNotTrack: string | undefined
readonly customOauthUrl: string | undefined
+ readonly useGateway: string | undefined
+ readonly providerManagedByHost: string | undefined
readonly useBedrock: string | undefined
readonly useVertex: string | undefined
readonly useFoundry: string | undefined
diff --git a/mods/telemetry/hooks/facts/facts.ts b/mods/telemetry/hooks/facts/facts.ts
new file mode 100644
index 00000000..814ce2ac
--- /dev/null
+++ b/mods/telemetry/hooks/facts/facts.ts
@@ -0,0 +1,66 @@
+/**
+ * What the plugin reads of the environment once a session to describe it in
+ * every row, as the CLI's own rows describe theirs.
+ *
+ * Each field is one variable as `$.env.get` answers it, undefined when
+ * unset, or only whether it is set where its value is a secret or names a
+ * person or a host; context/ reduces each to the value the CLI's column has.
+ */
+export type Facts = {
+ readonly entrypoint: string | undefined
+ readonly agentSdkVersion: string | undefined
+ readonly hostPlatform: string | undefined
+ readonly os: string | undefined
+ readonly processorArchitecture: string | undefined
+ readonly shellPath: string | undefined
+ readonly ci: string | undefined
+ readonly claubbit: string | undefined
+ readonly githubActions: string | undefined
+ readonly claudeCodeAction: string | undefined
+ readonly claudeCodeRemote: string | undefined
+ readonly remoteEnvironmentType: string | undefined
+ readonly containerId: string | undefined
+ readonly remoteSessionId: string | undefined
+ readonly tags: string | undefined
+ readonly hasSessionAccessToken: boolean
+ readonly hasSessionIngressTokenFile: boolean
+ readonly hasWebsocketAuthFileDescriptor: boolean
+ readonly githubEventName: string | undefined
+ readonly runnerEnvironment: string | undefined
+ readonly runnerOs: string | undefined
+ readonly githubActionPath: string | undefined
+ readonly githubActorId: string | undefined
+ readonly githubRepositoryId: string | undefined
+ readonly githubRepositoryOwnerId: string | undefined
+ readonly sweBenchRunId: string | undefined
+ readonly sweBenchInstanceId: string | undefined
+ readonly sweBenchTaskId: string | undefined
+ readonly hasP4Port: boolean
+ readonly wslDistroName: string | undefined
+ readonly hasCursorTraceId: boolean
+ readonly vscodeGitAskpassMain: string | undefined
+ readonly bundleIdentifier: string | undefined
+ readonly hasVisualStudioVersion: boolean
+ readonly terminalEmulator: string | undefined
+ readonly term: string | undefined
+ readonly termProgram: string | undefined
+ readonly hasTmux: boolean
+ readonly hasSty: boolean
+ readonly hasKonsoleVersion: boolean
+ readonly hasGnomeTerminalService: boolean
+ readonly hasXtermVersion: boolean
+ readonly hasVteVersion: boolean
+ readonly hasTerminatorUuid: boolean
+ readonly hasKittyWindowId: boolean
+ readonly hasAlacrittyLog: boolean
+ readonly hasTilixId: boolean
+ readonly hasWtSession: boolean
+ readonly hasSessionName: boolean
+ readonly msystem: string | undefined
+ readonly hasConEmuAnsi: boolean
+ readonly hasConEmuPid: boolean
+ readonly hasConEmuTask: boolean
+ readonly hasSshConnection: boolean
+ readonly hasSshClient: boolean
+ readonly hasSshTty: boolean
+}
diff --git a/mods/telemetry/hooks/facts/index.ts b/mods/telemetry/hooks/facts/index.ts
new file mode 100644
index 00000000..00a6f44b
--- /dev/null
+++ b/mods/telemetry/hooks/facts/index.ts
@@ -0,0 +1,3 @@
+export type * from './facts.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/gate/caught/caught.ts b/mods/telemetry/hooks/gate/caught/caught.ts
new file mode 100644
index 00000000..6070a207
--- /dev/null
+++ b/mods/telemetry/hooks/gate/caught/caught.ts
@@ -0,0 +1,14 @@
+import type { Caught } from 'claude-code'
+
+import { REFUSED } from '../refused'
+
+/**
+ * The gate's `.catch`: a gate that threw before going on refuses the call;
+ * a refusal from beneath (a malformed entry) is passed up as it is.
+ *
+ * @param e the entry as the caller passed it
+ * @param next the replay-safe continuation the catch is handed
+ * @returns beneath's own answer replayed, or the refusal
+ */
+export const caught = <E, R>(e: E, next: ((e: E) => R) & Caught) =>
+ next.called ? next(e) : REFUSED
diff --git a/mods/telemetry/hooks/gate/caught/index.ts b/mods/telemetry/hooks/gate/caught/index.ts
new file mode 100644
index 00000000..78e73759
--- /dev/null
+++ b/mods/telemetry/hooks/gate/caught/index.ts
@@ -0,0 +1,3 @@
+export * from './caught.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/gate/gate-next/gate-next.ts b/mods/telemetry/hooks/gate/gate-next/gate-next.ts
new file mode 100644
index 00000000..abd1dd04
--- /dev/null
+++ b/mods/telemetry/hooks/gate/gate-next/gate-next.ts
@@ -0,0 +1,7 @@
+import type { Origin } from 'claude-code'
+
+/**
+ * What the gate reads of the continuation it is handed: the hooks beneath
+ * to go on to, and who raised the call, as the host stamped it.
+ */
+export type GateNext<E, R> = ((e: E) => R) & { readonly origin?: Origin }
diff --git a/mods/telemetry/hooks/gate/gate-next/index.ts b/mods/telemetry/hooks/gate/gate-next/index.ts
new file mode 100644
index 00000000..5fa988cb
--- /dev/null
+++ b/mods/telemetry/hooks/gate/gate-next/index.ts
@@ -0,0 +1,3 @@
+export type * from './gate-next.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/gate/index.ts b/mods/telemetry/hooks/gate/index.ts
new file mode 100644
index 00000000..3606b1ed
--- /dev/null
+++ b/mods/telemetry/hooks/gate/index.ts
@@ -0,0 +1,7 @@
+export * from './caught'
+export * from './gate-next'
+export * from './refused'
+export * from './served'
+export * from './served-tiers'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/gate/refused/index.ts b/mods/telemetry/hooks/gate/refused/index.ts
new file mode 100644
index 00000000..bf42c557
--- /dev/null
+++ b/mods/telemetry/hooks/gate/refused/index.ts
@@ -0,0 +1,3 @@
+export * from './refused.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/gate/refused/refused.ts b/mods/telemetry/hooks/gate/refused/refused.ts
new file mode 100644
index 00000000..80c712f4
--- /dev/null
+++ b/mods/telemetry/hooks/gate/refused/refused.ts
@@ -0,0 +1,7 @@
+/**
+ * The answer a caller outside the served tiers gets from `$.telemetry`: its
+ * promise rejects with this, and the host notes it in the debug log.
+ */
+export const REFUSED = {
+ deny: '$.telemetry serves the plugins built into Claude Code alone',
+} as const
diff --git a/mods/telemetry/hooks/gate/served-tiers/index.ts b/mods/telemetry/hooks/gate/served-tiers/index.ts
new file mode 100644
index 00000000..abde6a41
--- /dev/null
+++ b/mods/telemetry/hooks/gate/served-tiers/index.ts
@@ -0,0 +1,3 @@
+export * from './served-tiers.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/gate/served-tiers/served-tiers.ts b/mods/telemetry/hooks/gate/served-tiers/served-tiers.ts
new file mode 100644
index 00000000..b91264b6
--- /dev/null
+++ b/mods/telemetry/hooks/gate/served-tiers/served-tiers.ts
@@ -0,0 +1,5 @@
+/**
+ * The tiers `$.telemetry` serves: the plugins bundled in the binary, and the
+ * engine itself. A caller seated anywhere else is refused, on every build.
+ */
+export const SERVED_TIERS: readonly string[] = ['builtin', 'core']
diff --git a/mods/telemetry/hooks/gate/served/index.ts b/mods/telemetry/hooks/gate/served/index.ts
new file mode 100644
index 00000000..8840c3af
--- /dev/null
+++ b/mods/telemetry/hooks/gate/served/index.ts
@@ -0,0 +1,3 @@
+export * from './served.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/gate/served/served.ts b/mods/telemetry/hooks/gate/served/served.ts
new file mode 100644
index 00000000..e27ada84
--- /dev/null
+++ b/mods/telemetry/hooks/gate/served/served.ts
@@ -0,0 +1,19 @@
+import type { GateNext } from '../gate-next'
+import { REFUSED } from '../refused'
+import { SERVED_TIERS } from '../served-tiers'
+
+/**
+ * The gate on `telemetry.log` and `telemetry.mark`: a caller seated in
+ * SERVED_TIERS goes on beneath, any other is REFUSED; no origin throws.
+ *
+ * @param e the entry as the caller passed it
+ * @param next the hooks beneath, carrying who raised the call
+ * @returns what beneath answers, or the refusal
+ */
+export function served<E, R>(e: E, next: GateNext<E, R>): R | typeof REFUSED {
+ if (next.origin?.tier === undefined) {
+ throw new Error('$.telemetry: the call names no origin')
+ }
+
+ return SERVED_TIERS.includes(next.origin.tier) ? next(e) : REFUSED
+}
diff --git a/mods/telemetry/hooks/hooks.json b/mods/telemetry/hooks/hooks.json
index dd92650e..95b8d78b 100644
--- a/mods/telemetry/hooks/hooks.json
+++ b/mods/telemetry/hooks/hooks.json
@@ -1,4 +1,6 @@
{
- "description": "Plugin analytics: an engine.create step adds $.telemetry (log, mark) over $.session, $.http and $.env beneath; sends nothing wherever the CLI's analytics are off",
- "modules": ["./register.ts"]
+ "description": "Plugin analytics: an engine.create step adds $.telemetry (log, mark) over $.session, $.env, $.settings, $.fs, $.process, $.clock and $.http beneath; rows go out in batches; sends nothing wherever the CLI's analytics are off",
+ "modules": [
+ "./register.ts"
+ ]
}
diff --git a/mods/telemetry/hooks/index.ts b/mods/telemetry/hooks/index.ts
index ced13e86..afc3469e 100644
--- a/mods/telemetry/hooks/index.ts
+++ b/mods/telemetry/hooks/index.ts
@@ -1,7 +1,15 @@
+export * from './batching'
+export * from './config-location'
+export * from './context'
+export * from './deployment'
export * from './entries'
export * from './environment'
+export * from './facts'
+export * from './gate'
export * from './is-analytics-off'
+export * from './policy-pins'
export * from './register.js'
+export * from './sender'
export * from './telemetry-deps'
export * from './telemetry-of'
diff --git a/mods/telemetry/hooks/is-analytics-off/is-analytics-off.ts b/mods/telemetry/hooks/is-analytics-off/is-analytics-off.ts
index 911a8f52..7d86dd2a 100644
--- a/mods/telemetry/hooks/is-analytics-off/is-analytics-off.ts
+++ b/mods/telemetry/hooks/is-analytics-off/is-analytics-off.ts
@@ -1,34 +1,44 @@
import type { Environment } from '../environment'
+import type { PolicyPins } from '../policy-pins'
import { isEnvSet } from './is-env-set'
import { isEnvTruthy } from './is-env-truthy'
/**
* Whether the CLI's own analytics would be off here, read off the
- * environment alone: then the plugin sends nothing either.
+ * environment and the managed policy: then the plugin sends nothing either.
*
- * Off when DISABLE_TELEMETRY or the nonessential-traffic switch is set at
- * all or DO_NOT_TRACK is on, on any third-party provider (no first-party
- * credential rides there), and on a deployment with its own OAuth URL.
+ * Off under test, when DISABLE_TELEMETRY or the nonessential-traffic switch
+ * is set at all or DO_NOT_TRACK is on, on a third-party provider the host
+ * does not manage, on a gateway, and on a deployment with its own OAuth URL.
*
- * @param environment the variables as read once for the session
+ * @param environment the switches as read for this batch
+ * @param policy the managed settings' gateway pins
* @returns true when no row may be sent
*/
-export function isAnalyticsOff(environment: Environment) {
+export function isAnalyticsOff(environment: Environment, policy: PolicyPins) {
const isPrivate =
+ environment.nodeEnv === 'test' ||
isEnvSet(environment.disableTelemetry) ||
isEnvSet(environment.disableNonessentialTraffic) ||
isEnvTruthy(environment.doNotTrack)
- const isThirdParty = [
- environment.useBedrock,
- environment.useVertex,
- environment.useFoundry,
- environment.useAnthropicAws,
- environment.useAnthropicGoogleCloud,
- environment.useMantle,
- ].some(isEnvTruthy)
+ const isThirdParty =
+ !isEnvTruthy(environment.providerManagedByHost) &&
+ [
+ environment.useBedrock,
+ environment.useVertex,
+ environment.useFoundry,
+ environment.useAnthropicAws,
+ environment.useAnthropicGoogleCloud,
+ environment.useMantle,
+ ].some(isEnvTruthy)
+
+ const isGateway =
+ isEnvTruthy(environment.useGateway) ||
+ policy.forceLoginMethod === 'gateway' ||
+ policy.forceLoginGatewayUrl !== undefined
const isCustomDeployment = isEnvSet(environment.customOauthUrl?.trim())
- return isPrivate || isThirdParty || isCustomDeployment
+ return isPrivate || isThirdParty || isGateway || isCustomDeployment
}
diff --git a/mods/telemetry/hooks/policy-pins/index.ts b/mods/telemetry/hooks/policy-pins/index.ts
new file mode 100644
index 00000000..ff9853ac
--- /dev/null
+++ b/mods/telemetry/hooks/policy-pins/index.ts
@@ -0,0 +1,3 @@
+export type * from './policy-pins.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/policy-pins/policy-pins.ts b/mods/telemetry/hooks/policy-pins/policy-pins.ts
new file mode 100644
index 00000000..60d103a5
--- /dev/null
+++ b/mods/telemetry/hooks/policy-pins/policy-pins.ts
@@ -0,0 +1,10 @@
+/**
+ * The two managed-settings keys that pin a session to a cloud gateway, as
+ * `$.settings.read({ source: "policy" })` answers them.
+ *
+ * A session so pinned sends its rows nowhere, as the CLI's own analytics do.
+ */
+export type PolicyPins = {
+ readonly forceLoginMethod?: unknown
+ readonly forceLoginGatewayUrl?: unknown
+}
diff --git a/mods/telemetry/hooks/register.ts b/mods/telemetry/hooks/register.ts
index 275bf0c5..1e78659d 100644
--- a/mods/telemetry/hooks/register.ts
+++ b/mods/telemetry/hooks/register.ts
@@ -1,32 +1,64 @@
import type { EngineInterface, On } from 'claude-code'
+import Context from './context'
+import Gate from './gate'
+import IsAnalyticsOff from './is-analytics-off'
+import type { Sender } from './sender'
import { telemetryOf } from './telemetry-of'
/**
- * Registers the plugin's one hook: its engine.create step adds
- * `$.telemetry` over the nouns beneath, the plugin's own `$` as core built.
+ * Registers the plugin's hooks: its engine.create step adds `$.telemetry`
+ * over the nouns beneath; session.start and session.end feed and flush it.
*
- * `log` runs after the fold, reaching `$.session` and `$.http` through the
- * nouns beneath; each is one call on them.
+ * `log` and `mark` queue a row for a built-in caller and refuse any other;
+ * a gate that throws refuses too, a refusal from beneath stays as it is. A
+ * batch goes out on a timer, when full, and when the session ends.
*
* @param on the engine's registrar
*/
export function register(on: On) {
- on('engine.create', async ($, e, next) => {
+ let sender: Sender | undefined
+ let isInteractive: boolean | undefined
+
+ on('telemetry.*', (_$, e, next) => Gate.served(e, next)).catch(
+ (_$, e, next) => Gate.caught(e, next),
+ )
+
+ on('session.start', (_$, e, next) => {
+ isInteractive = e.isInteractive
+
+ return next(e)
+ })
+
+ on('session.end', async (_$, e, next) => {
+ await sender?.flush()
+
+ return next(e)
+ })
+
+ on('engine.create', async (_$, e, next) => {
const beneath = await next(e)
- const telemetry: EngineInterface['telemetry'] = telemetryOf({
+ sender = telemetryOf({
authorize: () => beneath.session.authorize(),
id: () => beneath.session.id(),
model: () => beneath.session.model(),
+ isInteractive: async () =>
+ isInteractive ??
+ (await beneath.session.surfaces()).includes('terminal'),
environment: async () => ({
userType: await beneath.env.get('USER_TYPE'),
+ nodeEnv: await beneath.env.get('NODE_ENV'),
disableTelemetry: await beneath.env.get('DISABLE_TELEMETRY'),
disableNonessentialTraffic: await beneath.env.get(
'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC',
),
doNotTrack: await beneath.env.get('DO_NOT_TRACK'),
customOauthUrl: await beneath.env.get('CLAUDE_CODE_CUSTOM_OAUTH_URL'),
+ useGateway: await beneath.env.get('CLAUDE_CODE_USE_GATEWAY'),
+ providerManagedByHost: await beneath.env.get(
+ 'CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST',
+ ),
useBedrock: await beneath.env.get('CLAUDE_CODE_USE_BEDROCK'),
useVertex: await beneath.env.get('CLAUDE_CODE_USE_VERTEX'),
useFoundry: await beneath.env.get('CLAUDE_CODE_USE_FOUNDRY'),
@@ -36,9 +68,286 @@ export function register(on: On) {
),
useMantle: await beneath.env.get('CLAUDE_CODE_USE_MANTLE'),
}),
+ policy: () => beneath.settings.read({ source: 'policy' }),
+ facts: async () => ({
+ entrypoint: await beneath.env.get('CLAUDE_CODE_ENTRYPOINT'),
+ agentSdkVersion: await beneath.env.get('CLAUDE_AGENT_SDK_VERSION'),
+ hostPlatform: await beneath.env.get('CLAUDE_CODE_HOST_PLATFORM'),
+ os: await beneath.env.get('OS'),
+ processorArchitecture: await beneath.env.get('PROCESSOR_ARCHITECTURE'),
+ shellPath:
+ (await beneath.env.get('SHELL')) ??
+ (await beneath.env.get('COMSPEC')),
+ ci: await beneath.env.get('CI'),
+ claubbit: await beneath.env.get('CLAUBBIT'),
+ githubActions: await beneath.env.get('GITHUB_ACTIONS'),
+ claudeCodeAction: await beneath.env.get('CLAUDE_CODE_ACTION'),
+ claudeCodeRemote: await beneath.env.get('CLAUDE_CODE_REMOTE'),
+ remoteEnvironmentType: await beneath.env.get(
+ 'CLAUDE_CODE_REMOTE_ENVIRONMENT_TYPE',
+ ),
+ containerId: await beneath.env.get('CLAUDE_CODE_CONTAINER_ID'),
+ remoteSessionId: await beneath.env.get('CLAUDE_CODE_REMOTE_SESSION_ID'),
+ tags: await beneath.env.get('CLAUDE_CODE_TAGS'),
+ hasSessionAccessToken: IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('CLAUDE_CODE_SESSION_ACCESS_TOKEN'),
+ ),
+ hasSessionIngressTokenFile: IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('CLAUDE_SESSION_INGRESS_TOKEN_FILE'),
+ ),
+ hasWebsocketAuthFileDescriptor: IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR'),
+ ),
+ githubEventName: await beneath.env.get('GITHUB_EVENT_NAME'),
+ runnerEnvironment: await beneath.env.get('RUNNER_ENVIRONMENT'),
+ runnerOs: await beneath.env.get('RUNNER_OS'),
+ githubActionPath: await beneath.env.get('GITHUB_ACTION_PATH'),
+ githubActorId: await beneath.env.get('GITHUB_ACTOR_ID'),
+ githubRepositoryId: await beneath.env.get('GITHUB_REPOSITORY_ID'),
+ githubRepositoryOwnerId: await beneath.env.get(
+ 'GITHUB_REPOSITORY_OWNER_ID',
+ ),
+ sweBenchRunId: await beneath.env.get('SWE_BENCH_RUN_ID'),
+ sweBenchInstanceId: await beneath.env.get('SWE_BENCH_INSTANCE_ID'),
+ sweBenchTaskId: await beneath.env.get('SWE_BENCH_TASK_ID'),
+ hasP4Port: IsAnalyticsOff.isEnvSet(await beneath.env.get('P4PORT')),
+ wslDistroName: await beneath.env.get('WSL_DISTRO_NAME'),
+ hasCursorTraceId: IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('CURSOR_TRACE_ID'),
+ ),
+ vscodeGitAskpassMain: await beneath.env.get('VSCODE_GIT_ASKPASS_MAIN'),
+ bundleIdentifier: await beneath.env.get('__CFBundleIdentifier'),
+ hasVisualStudioVersion: IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('VisualStudioVersion'),
+ ),
+ terminalEmulator: await beneath.env.get('TERMINAL_EMULATOR'),
+ term: await beneath.env.get('TERM'),
+ termProgram: await beneath.env.get('TERM_PROGRAM'),
+ hasTmux: IsAnalyticsOff.isEnvSet(await beneath.env.get('TMUX')),
+ hasSty: IsAnalyticsOff.isEnvSet(await beneath.env.get('STY')),
+ hasKonsoleVersion: IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('KONSOLE_VERSION'),
+ ),
+ hasGnomeTerminalService: IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('GNOME_TERMINAL_SERVICE'),
+ ),
+ hasXtermVersion: IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('XTERM_VERSION'),
+ ),
+ hasVteVersion: IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('VTE_VERSION'),
+ ),
+ hasTerminatorUuid: IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('TERMINATOR_UUID'),
+ ),
+ hasKittyWindowId: IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('KITTY_WINDOW_ID'),
+ ),
+ hasAlacrittyLog: IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('ALACRITTY_LOG'),
+ ),
+ hasTilixId: IsAnalyticsOff.isEnvSet(await beneath.env.get('TILIX_ID')),
+ hasWtSession: IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('WT_SESSION'),
+ ),
+ hasSessionName: IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('SESSIONNAME'),
+ ),
+ msystem: await beneath.env.get('MSYSTEM'),
+ hasConEmuAnsi: IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('ConEmuANSI'),
+ ),
+ hasConEmuPid: IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('ConEmuPID'),
+ ),
+ hasConEmuTask: IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('ConEmuTask'),
+ ),
+ hasSshConnection: IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('SSH_CONNECTION'),
+ ),
+ hasSshClient: IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('SSH_CLIENT'),
+ ),
+ hasSshTty: IsAnalyticsOff.isEnvSet(await beneath.env.get('SSH_TTY')),
+ }),
+ deployment: async () => [
+ [
+ 'codespaces',
+ IsAnalyticsOff.isEnvTruthy(await beneath.env.get('CODESPACES')),
+ ],
+ [
+ 'gitpod',
+ IsAnalyticsOff.isEnvSet(await beneath.env.get('GITPOD_WORKSPACE_ID')),
+ ],
+ ['coder', IsAnalyticsOff.isEnvTruthy(await beneath.env.get('CODER'))],
+ [
+ 'coder',
+ IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('CODER_WORKSPACE_NAME'),
+ ),
+ ],
+ ['devpod', IsAnalyticsOff.isEnvTruthy(await beneath.env.get('DEVPOD'))],
+ [
+ 'devpod',
+ IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('DEVPOD_WORKSPACE_UID'),
+ ),
+ ],
+ [
+ 'daytona',
+ IsAnalyticsOff.isEnvSet(await beneath.env.get('DAYTONA_WS_ID')),
+ ],
+ [
+ 'gcp-cloud-workstations',
+ IsAnalyticsOff.isEnvTruthy(
+ await beneath.env.get('GOOGLE_CLOUD_WORKSTATIONS'),
+ ),
+ ],
+ [
+ 'aws-cloud9',
+ IsAnalyticsOff.isEnvSet(await beneath.env.get('C9_PID')),
+ ],
+ [
+ 'aws-cloud9',
+ IsAnalyticsOff.isEnvSet(await beneath.env.get('C9_USER')),
+ ],
+ ['replit', IsAnalyticsOff.isEnvSet(await beneath.env.get('REPL_ID'))],
+ ['replit', IsAnalyticsOff.isEnvSet(await beneath.env.get('REPL_SLUG'))],
+ [
+ 'glitch',
+ IsAnalyticsOff.isEnvSet(await beneath.env.get('PROJECT_DOMAIN')),
+ ],
+ ['vercel', IsAnalyticsOff.isEnvTruthy(await beneath.env.get('VERCEL'))],
+ [
+ 'railway',
+ IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('RAILWAY_ENVIRONMENT_NAME'),
+ ),
+ ],
+ [
+ 'railway',
+ IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('RAILWAY_SERVICE_NAME'),
+ ),
+ ],
+ ['render', IsAnalyticsOff.isEnvTruthy(await beneath.env.get('RENDER'))],
+ [
+ 'netlify',
+ IsAnalyticsOff.isEnvTruthy(await beneath.env.get('NETLIFY')),
+ ],
+ ['heroku', IsAnalyticsOff.isEnvSet(await beneath.env.get('DYNO'))],
+ [
+ 'fly.io',
+ IsAnalyticsOff.isEnvSet(await beneath.env.get('FLY_APP_NAME')),
+ ],
+ [
+ 'fly.io',
+ IsAnalyticsOff.isEnvSet(await beneath.env.get('FLY_MACHINE_ID')),
+ ],
+ [
+ 'cloudflare-pages',
+ IsAnalyticsOff.isEnvTruthy(await beneath.env.get('CF_PAGES')),
+ ],
+ [
+ 'deno-deploy',
+ IsAnalyticsOff.isEnvSet(await beneath.env.get('DENO_DEPLOYMENT_ID')),
+ ],
+ [
+ 'aws-lambda',
+ IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('AWS_LAMBDA_FUNCTION_NAME'),
+ ),
+ ],
+ [
+ 'aws-fargate',
+ (await beneath.env.get('AWS_EXECUTION_ENV')) === 'AWS_ECS_FARGATE',
+ ],
+ [
+ 'aws-ecs',
+ (await beneath.env.get('AWS_EXECUTION_ENV')) === 'AWS_ECS_EC2',
+ ],
+ [
+ 'gcp-cloud-run',
+ IsAnalyticsOff.isEnvSet(await beneath.env.get('K_SERVICE')),
+ ],
+ [
+ 'gcp',
+ IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('GOOGLE_CLOUD_PROJECT'),
+ ),
+ ],
+ [
+ 'azure-app-service',
+ IsAnalyticsOff.isEnvSet(await beneath.env.get('WEBSITE_SITE_NAME')),
+ ],
+ [
+ 'azure-app-service',
+ IsAnalyticsOff.isEnvSet(await beneath.env.get('WEBSITE_SKU')),
+ ],
+ [
+ 'azure-functions',
+ IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('AZURE_FUNCTIONS_ENVIRONMENT'),
+ ),
+ ],
+ [
+ 'digitalocean-app-platform',
+ IsAnalyticsOff.isEnvSet(await beneath.env.get('APP_URL')) &&
+ String(await beneath.env.get('APP_URL')).includes(
+ 'ondigitalocean.app',
+ ),
+ ],
+ [
+ 'huggingface-spaces',
+ IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('SPACE_CREATOR_USER_ID'),
+ ),
+ ],
+ [
+ 'github-actions',
+ IsAnalyticsOff.isEnvTruthy(await beneath.env.get('GITHUB_ACTIONS')),
+ ],
+ [
+ 'gitlab-ci',
+ IsAnalyticsOff.isEnvTruthy(await beneath.env.get('GITLAB_CI')),
+ ],
+ [
+ 'circleci',
+ IsAnalyticsOff.isEnvSet(await beneath.env.get('CIRCLECI')),
+ ],
+ [
+ 'buildkite',
+ IsAnalyticsOff.isEnvSet(await beneath.env.get('BUILDKITE')),
+ ],
+ ['ci', IsAnalyticsOff.isEnvTruthy(await beneath.env.get('CI'))],
+ [
+ 'kubernetes',
+ IsAnalyticsOff.isEnvSet(
+ await beneath.env.get('KUBERNETES_SERVICE_HOST'),
+ ),
+ ],
+ ],
+ configLocation: async () => ({
+ configDir: await beneath.env.get('CLAUDE_CONFIG_DIR'),
+ home: await beneath.env.get('HOME'),
+ userProfile: await beneath.env.get('USERPROFILE'),
+ }),
+ cwd: () => beneath.session.cwd(),
+ repo: () => beneath.session.repo(),
+ read: path => beneath.fs.read(path),
+ list: path => beneath.fs.list(path),
+ exists: path => beneath.fs.exists(path),
+ run: argv =>
+ beneath.process.run(argv, { timeoutMs: Context.PROBE_TIMEOUT_MS }),
fetch: (url, init) => beneath.http.fetch(url, init),
+ after: (ms, fn) => beneath.clock.after(ms, fn),
+ sleep: ms => beneath.clock.sleep(ms),
+ debug: text => beneath.ui.log(text, { to: 'debug' }),
})
+ const telemetry: EngineInterface['telemetry'] = sender.telemetry
+
return { ...beneath, telemetry }
})
}
diff --git a/mods/telemetry/hooks/sender/index.ts b/mods/telemetry/hooks/sender/index.ts
new file mode 100644
index 00000000..0441d047
--- /dev/null
+++ b/mods/telemetry/hooks/sender/index.ts
@@ -0,0 +1,3 @@
+export type * from './sender.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/hooks/sender/sender.ts b/mods/telemetry/hooks/sender/sender.ts
new file mode 100644
index 00000000..941c3710
--- /dev/null
+++ b/mods/telemetry/hooks/sender/sender.ts
@@ -0,0 +1,14 @@
+import type { Telemetry } from '../../types'
+
+/**
+ * What `telemetryOf` builds: the `$.telemetry` noun, and the flush the
+ * plugin's session.end hook calls to send what still waits.
+ */
+export type Sender = {
+ telemetry: Telemetry
+
+ /**
+ * Sends every queued row now, in one batch; resolves once it settled.
+ */
+ flush: () => Promise<void>
+}
diff --git a/mods/telemetry/hooks/telemetry-deps/telemetry-deps.ts b/mods/telemetry/hooks/telemetry-deps/telemetry-deps.ts
index 28f87372..7c1573e0 100644
--- a/mods/telemetry/hooks/telemetry-deps/telemetry-deps.ts
+++ b/mods/telemetry/hooks/telemetry-deps/telemetry-deps.ts
@@ -1,10 +1,25 @@
-import type { HttpInit, HttpResponse, SessionAuthorization } from 'claude-code'
+import type {
+ FsEntry,
+ HttpInit,
+ HttpResponse,
+ ProcessRunResult,
+ SessionAuthorization,
+ SessionRepo,
+ Timer,
+} from 'claude-code'
+import type { ConfigLocation } from '../config-location'
+import type Deployment from '../deployment'
import type { Environment } from '../environment'
+import type { Facts } from '../facts'
+import type { PolicyPins } from '../policy-pins'
/**
- * What `telemetryOf` reaches on the nouns beneath: the session's authorize
- * and reads, and one fetch. Each is a call on the plugin's own `$`.
+ * What `telemetryOf` reaches on the nouns beneath, each a call on the
+ * plugin's own `$`.
+ *
+ * The session, the environment, files, one process, the clock, one fetch
+ * and the debug log.
*/
export type TelemetryDeps = {
/**
@@ -13,23 +28,94 @@ export type TelemetryDeps = {
authorize: () => Promise<SessionAuthorization>
/**
- * The session's id, for the row.
+ * The session's id, for the batch.
*/
id: () => Promise<string>
/**
- * The session's model, for the row.
+ * The session's model, for the batch.
*/
model: () => Promise<string>
/**
- * Reads, at each call, what the row and the off switch need of the
- * environment: the build's user type and every analytics-off variable.
+ * Whether a person is at the prompt: what `session.start` said, else
+ * whether the session draws on a terminal.
+ */
+ isInteractive: () => Promise<boolean>
+
+ /**
+ * Reads, before each batch, the build's user type and every analytics-off
+ * variable.
*/
environment: () => Promise<Environment>
/**
- * Posts the batch to the ingest with the credential handle.
+ * Reads the managed policy's gateway pins.
+ */
+ policy: () => Promise<PolicyPins>
+
+ /**
+ * Reads, once a session, the variables that describe it in a row.
+ */
+ facts: () => Promise<Facts>
+
+ /**
+ * Reads, once a session, whether each deployment's variable holds.
+ */
+ deployment: () => Promise<readonly Deployment.DeploymentSignal[]>
+
+ /**
+ * Reads where the CLI's global config file is.
+ */
+ configLocation: () => Promise<ConfigLocation>
+
+ /**
+ * The directory the session runs in.
+ */
+ cwd: () => Promise<string>
+
+ /**
+ * The repository the session runs in, or null.
+ */
+ repo: () => Promise<SessionRepo | null>
+
+ /**
+ * Reads a file as text; rejects when it cannot be read.
+ */
+ read: (path: string) => Promise<string>
+
+ /**
+ * Lists a directory; rejects when it cannot be listed.
+ */
+ list: (path: string) => Promise<readonly FsEntry[]>
+
+ /**
+ * Whether a path exists.
+ */
+ exists: (path: string) => Promise<boolean>
+
+ /**
+ * Runs one program to its end.
+ */
+ run: (argv: readonly string[]) => Promise<ProcessRunResult>
+
+ /**
+ * Posts a batch to the ingest with the credential handle.
*/
fetch: (url: string, init: HttpInit) => Promise<HttpResponse>
+
+ /**
+ * Calls `fn` once after `ms` milliseconds.
+ */
+ after: (ms: number, fn: () => void) => Timer
+
+ /**
+ * Resolves after `ms` milliseconds.
+ */
+ sleep: (ms: number) => Promise<void>
+
+ /**
+ * Writes one line to the debug log.
+ */
+ debug: (text: string) => void
}
diff --git a/mods/telemetry/hooks/telemetry-of/telemetry-of.ts b/mods/telemetry/hooks/telemetry-of/telemetry-of.ts
index 70395f1b..3ae6479c 100644
--- a/mods/telemetry/hooks/telemetry-of/telemetry-of.ts
+++ b/mods/telemetry/hooks/telemetry-of/telemetry-of.ts
@@ -1,74 +1,191 @@
+import type { HttpResponse, Timer } from 'claude-code'
+
import type { Telemetry } from '../../types'
+import Batching from '../batching'
+import Context from '../context'
import Entries from '../entries'
+import type { Environment } from '../environment'
import { isAnalyticsOff } from '../is-analytics-off'
+import type { Sender } from '../sender'
import type { TelemetryDeps } from '../telemetry-deps'
/**
- * Builds `$.telemetry`: `log` and `mark` check the entry, read the environment
- * and authorize afresh, build the first-party row and POST it to the ingest.
+ * Builds `$.telemetry` and its flush: `log` and `mark` check the entry and
+ * queue a row; a batch goes out on a timer, when full, or when flushed.
*
- * One POST per call, rows one after another, nothing kept between them: a
- * session that has moved to a third-party provider or a gateway, or turned
- * analytics off, sends nothing more; no credential or a refusal rejects.
+ * Each batch reads the switches afresh: analytics off, or unreadable, sends
+ * nothing; no credential, or an ingest that refuses after one retry, drops
+ * the batch. Each outcome is one debug line; the context is gathered once.
*
* @param deps the calls on the nouns beneath
- * @returns the `$.telemetry` interface, `log` and `mark`
+ * @returns the noun and its flush
*/
-export function telemetryOf(deps: TelemetryDeps): Telemetry {
- let queue: Promise<unknown> = Promise.resolve()
+export function telemetryOf(deps: TelemetryDeps): Sender {
+ let pending: Batching.PendingRow[] = []
+ let timer: Timer | undefined
+ let context: Promise<Context.Context> | undefined
+ let priming: Promise<void> | undefined
+ let sending: Promise<void> = Promise.resolve()
- async function post(
- fields: Entries.Fields,
- method: Entries.Method,
- ): Promise<void> {
- const environment = await deps.environment()
+ function gathered(): Promise<Context.Context> {
+ const gathering =
+ context ??
+ deps
+ .isInteractive()
+ .then(isInteractive => Context.contextOf(deps, isInteractive))
+ .catch((error: unknown) => {
+ context = undefined
+ throw error
+ })
- if (isAnalyticsOff(environment)) {
- return
- }
+ context = gathering
- const body = Entries.batchOf(fields, {
- sessionId: await deps.id(),
- model: await deps.model(),
- userType: environment.userType === 'ant' ? 'ant' : 'external',
- })
+ return gathering
+ }
- const auth = await deps.authorize()
+ async function sendingEnvironment(): Promise<Environment | undefined> {
+ try {
+ const [environment, policy] = await Promise.all([
+ deps.environment(),
+ deps.policy(),
+ ])
- if (!auth) {
- throw Entries.refusal(
- 'this session has no first-party credential to authorize',
- method,
+ return isAnalyticsOff(environment, policy) ? undefined : environment
+ } catch (error) {
+ deps.debug(
+ 'telemetry: the analytics switches could not be read, so nothing ' +
+ `is sent (${Batching.messageOf(error)})`,
)
+
+ return undefined
}
+ }
+
+ async function primed(): Promise<void> {
+ const environment = await sendingEnvironment()
+
+ if (environment) {
+ await gathered()
+ }
+ }
- const response = await deps.fetch(Entries.INGEST_URL, {
+ const post = (body: string, auth: string): Promise<HttpResponse> =>
+ deps.fetch(Entries.INGEST_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-service-name': 'claude-code',
},
- auth: auth.handle,
+ auth,
body,
})
+ async function postedWithRetry(
+ body: string,
+ auth: string,
+ ): Promise<HttpResponse> {
+ let first: HttpResponse | undefined
+
+ try {
+ first = await post(body, auth)
+ } catch {
+ first = undefined
+ }
+
+ const isSettled =
+ first !== undefined && (first.ok || !Batching.isRetriable(first.status))
+
+ if (first !== undefined && isSettled) {
+ return first
+ }
+
+ await deps.sleep(Batching.RETRY_DELAY_MS)
+
+ return post(body, auth)
+ }
+
+ async function send(rows: readonly Batching.PendingRow[]): Promise<void> {
+ const environment = await sendingEnvironment()
+
+ if (!environment) {
+ return
+ }
+
+ const authorization = await deps.authorize()
+
+ if (!authorization) {
+ throw new Error('this session has no first-party credential to authorize')
+ }
+
+ const settled = await gathered()
+
+ const response = await postedWithRetry(
+ Entries.batchOf(rows, {
+ sessionId: await deps.id(),
+ model: await deps.model(),
+ userType: environment.userType === 'ant' ? 'ant' : 'external',
+ isInteractive: await deps.isInteractive(),
+ isClaudeAiAuth:
+ authorization.kind === 'bearer' &&
+ settled.identity.accountUuid !== undefined,
+ context: settled,
+ }),
+ authorization.handle,
+ )
+
if (!response.ok) {
- throw Entries.refusal(`the ingest answered ${response.status}`, method)
+ throw new Error(`the ingest answered ${response.status}`)
+ }
+
+ deps.debug(`telemetry: sent ${rows.length} row(s)`)
+ }
+
+ function flush(): Promise<void> {
+ timer?.cancel()
+ timer = undefined
+
+ const rows = pending
+
+ pending = []
+
+ if (rows.length === 0) {
+ return sending
}
+
+ sending = sending.then(() =>
+ send(rows).catch((error: unknown) => {
+ deps.debug(
+ `telemetry: ${rows.length} row(s) not sent: ` +
+ Batching.messageOf(error),
+ )
+ }),
+ )
+
+ return sending
}
- function queued(
- fields: Entries.Fields,
- method: Entries.Method,
- ): Promise<void> {
- const turn = queue.then(() => post(fields, method))
- queue = turn.catch(() => undefined)
+ function queued(fields: Entries.Fields) {
+ priming ??= primed().catch(() => undefined)
+
+ pending.push({
+ fields,
+ eventId: crypto.randomUUID(),
+ loggedAt: new Date().toISOString(),
+ })
- return turn
+ if (pending.length >= Batching.BATCH_ROWS) {
+ void flush()
+
+ return
+ }
+
+ timer ??= deps.after(Batching.BATCH_WINDOW_MS, () => void flush())
}
- return {
- log: async entry => queued(Entries.checkedFields(entry), 'log'),
- mark: async entry => queued(Entries.checkedMark(entry), 'mark'),
+ const telemetry: Telemetry = {
+ log: async entry => queued(Entries.checkedFields(entry)),
+ mark: async entry => queued(Entries.checkedMark(entry)),
}
+
+ return { telemetry, flush }
}
diff --git a/mods/telemetry/tests/fixtures/config-path.ts b/mods/telemetry/tests/fixtures/config-path.ts
new file mode 100644
index 00000000..1017d7ed
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/config-path.ts
@@ -0,0 +1,4 @@
+/**
+ * Where the CLI's global config is under SENDING_ENV's HOME.
+ */
+export const CONFIG_PATH = '/Users/person/.claude.json'
diff --git a/mods/telemetry/tests/fixtures/deaf-telemetry.ts b/mods/telemetry/tests/fixtures/deaf-telemetry.ts
new file mode 100644
index 00000000..875a4471
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/deaf-telemetry.ts
@@ -0,0 +1,10 @@
+import type { Telemetry } from '../../types'
+
+/**
+ * A `telemetry` that takes every entry and does nothing with it: what the
+ * replacing plugin tries to hand up in place of the real one.
+ */
+export const DEAF_TELEMETRY: Telemetry = {
+ log: async () => undefined,
+ mark: async () => undefined,
+}
diff --git a/mods/telemetry/tests/fixtures/device-id.ts b/mods/telemetry/tests/fixtures/device-id.ts
new file mode 100644
index 00000000..3fed020f
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/device-id.ts
@@ -0,0 +1,5 @@
+/**
+ * What the global config records as this install's device id.
+ */
+export const DEVICE_ID =
+ 'ab01ab01ab01ab01ab01ab01ab01ab01ab01ab01ab01ab01ab01ab01ab01ab01'
diff --git a/mods/telemetry/tests/fixtures/ended.ts b/mods/telemetry/tests/fixtures/ended.ts
new file mode 100644
index 00000000..3c51c9e4
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/ended.ts
@@ -0,0 +1,10 @@
+import type { SessionEndInput } from 'claude-code'
+
+/**
+ * The session as it ends: the person left.
+ */
+export const ENDED: SessionEndInput = {
+ reason: 'prompt_input_exit',
+ sessionId: 'the-session',
+ resume: { id: 'the-session' },
+}
diff --git a/mods/telemetry/tests/fixtures/analytics-off-environments.ts b/mods/telemetry/tests/fixtures/environments/analytics-off-environments.ts
similarity index 91%
rename from mods/telemetry/tests/fixtures/analytics-off-environments.ts
rename to mods/telemetry/tests/fixtures/environments/analytics-off-environments.ts
index 9dc78410..27da083e 100644
--- a/mods/telemetry/tests/fixtures/analytics-off-environments.ts
+++ b/mods/telemetry/tests/fixtures/environments/analytics-off-environments.ts
@@ -8,6 +8,8 @@ export const ANALYTICS_OFF_ENVIRONMENTS: readonly Readonly<
{ DISABLE_TELEMETRY: '0' },
{ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1' },
{ DO_NOT_TRACK: 'true' },
+ { NODE_ENV: 'test' },
+ { CLAUDE_CODE_USE_GATEWAY: '1' },
{ CLAUDE_CODE_USE_BEDROCK: '1' },
{ CLAUDE_CODE_USE_VERTEX: 'yes' },
{ CLAUDE_CODE_USE_FOUNDRY: 'on' },
diff --git a/mods/telemetry/tests/fixtures/environments/github-action-env.ts b/mods/telemetry/tests/fixtures/environments/github-action-env.ts
new file mode 100644
index 00000000..d10f2ba8
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/environments/github-action-env.ts
@@ -0,0 +1,20 @@
+import { SENDING_ENV } from './sending-env.js'
+
+/**
+ * SENDING_ENV inside a GitHub Actions workflow running the Claude Code
+ * action from a pull request.
+ */
+export const GITHUB_ACTION_ENV: Readonly<Record<string, string>> = {
+ ...SENDING_ENV,
+ CI: 'true',
+ GITHUB_ACTIONS: 'true',
+ GITHUB_EVENT_NAME: 'pull_request',
+ RUNNER_OS: 'Linux',
+ RUNNER_ENVIRONMENT: 'github-hosted',
+ GITHUB_ACTION_PATH: '/runner/_actions/anthropics/claude-code-action/v1',
+ GITHUB_ACTOR_ID: '11',
+ GITHUB_REPOSITORY_ID: '22',
+ GITHUB_REPOSITORY_OWNER_ID: '33',
+ CLAUDE_CODE_ENTRYPOINT: 'claude-code-github-action',
+ CLAUDE_CODE_ACTION: '1',
+}
diff --git a/mods/telemetry/tests/fixtures/environments/host-managed-bedrock-env.ts b/mods/telemetry/tests/fixtures/environments/host-managed-bedrock-env.ts
new file mode 100644
index 00000000..d925f075
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/environments/host-managed-bedrock-env.ts
@@ -0,0 +1,11 @@
+import { SENDING_ENV } from './sending-env.js'
+
+/**
+ * SENDING_ENV on Bedrock under a host that manages the provider: the CLI's
+ * analytics stay on there unless DISABLE_TELEMETRY says otherwise.
+ */
+export const HOST_MANAGED_BEDROCK_ENV: Readonly<Record<string, string>> = {
+ ...SENDING_ENV,
+ CLAUDE_CODE_USE_BEDROCK: '1',
+ CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST: '1',
+}
diff --git a/mods/telemetry/tests/fixtures/environments/index.ts b/mods/telemetry/tests/fixtures/environments/index.ts
new file mode 100644
index 00000000..bd94161b
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/environments/index.ts
@@ -0,0 +1,9 @@
+export * from './analytics-off-environments.js'
+export * from './github-action-env.js'
+export * from './host-managed-bedrock-env.js'
+export * from './linux-files.js'
+export * from './linux-probed.js'
+export * from './sending-env.js'
+export * from './windows-env.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/tests/fixtures/environments/linux-files.ts b/mods/telemetry/tests/fixtures/environments/linux-files.ts
new file mode 100644
index 00000000..f5182c4c
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/environments/linux-files.ts
@@ -0,0 +1,9 @@
+/**
+ * The files an Ubuntu machine under WSL2 on EC2 holds where the plugin
+ * reads the distribution, the kernel and the hypervisor.
+ */
+export const LINUX_FILES: Readonly<Record<string, string>> = {
+ '/etc/os-release': 'NAME="Ubuntu"\nID=ubuntu\nVERSION_ID="24.04"\n',
+ '/proc/version': 'Linux version 6.6.87.2-microsoft-standard-WSL2',
+ '/sys/hypervisor/uuid': 'ec2e1916-9099-7caf-fd21-012345abcdef',
+}
diff --git a/mods/telemetry/tests/fixtures/environments/linux-probed.ts b/mods/telemetry/tests/fixtures/environments/linux-probed.ts
new file mode 100644
index 00000000..6c7f33a7
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/environments/linux-probed.ts
@@ -0,0 +1,6 @@
+/**
+ * What the one machine probe prints on that Linux machine: x86_64, npm and
+ * node on the PATH.
+ */
+export const LINUX_PROBED =
+ 'Linux\n6.6.87.2-microsoft-standard-WSL2\nx86_64\nnpm,\nnode,\n'
diff --git a/mods/telemetry/tests/fixtures/environments/sending-env.ts b/mods/telemetry/tests/fixtures/environments/sending-env.ts
new file mode 100644
index 00000000..43451bcf
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/environments/sending-env.ts
@@ -0,0 +1,11 @@
+/**
+ * The environment of an internal build's session on a Mac, in Ghostty under
+ * zsh, signed in, its config under HOME: every switch clear, so rows go.
+ */
+export const SENDING_ENV: Readonly<Record<string, string>> = {
+ USER_TYPE: 'ant',
+ CLAUDE_CODE_ENTRYPOINT: 'cli',
+ TERM_PROGRAM: 'ghostty',
+ SHELL: '/bin/zsh',
+ HOME: '/Users/person',
+}
diff --git a/mods/telemetry/tests/fixtures/environments/windows-env.ts b/mods/telemetry/tests/fixtures/environments/windows-env.ts
new file mode 100644
index 00000000..4d6a485a
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/environments/windows-env.ts
@@ -0,0 +1,12 @@
+/**
+ * The environment of an external build's session on Windows, in Windows
+ * Terminal under cmd, its config under USERPROFILE.
+ */
+export const WINDOWS_ENV: Readonly<Record<string, string>> = {
+ USER_TYPE: 'external',
+ OS: 'Windows_NT',
+ PROCESSOR_ARCHITECTURE: 'AMD64',
+ COMSPEC: 'C:\\Windows\\System32\\cmd.exe',
+ USERPROFILE: 'C:\\Users\\person',
+ WT_SESSION: '1',
+}
diff --git a/mods/telemetry/tests/fixtures/expected-row.ts b/mods/telemetry/tests/fixtures/expected-row.ts
new file mode 100644
index 00000000..9e4442e7
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/expected-row.ts
@@ -0,0 +1,42 @@
+import { DEVICE_ID } from './device-id.js'
+import { REMOTE_HASH } from './remote-hash.js'
+
+/**
+ * The survey answer's row as SENDING_ENV's session sends it, complete: the
+ * shape rowOf reads back, every column the plugin can fill filled.
+ */
+export const EXPECTED_ROW = {
+ event_type: 'ClaudeCodeInternalEvent',
+ hasEventId: true,
+ hasTimestamp: true,
+ event_name: 'tengu_plugin_survey_answered',
+ device_id: DEVICE_ID,
+ email: '[email protected]',
+ auth: { account_uuid: 'acc-1111-2222', organization_uuid: 'org-3333-4444' },
+ session_id: 'the-session',
+ model: 'the-model',
+ user_type: 'ant',
+ is_interactive: true,
+ client_type: 'cli',
+ entrypoint: 'cli',
+ env: {
+ platform: 'darwin',
+ platform_raw: 'darwin',
+ arch: 'arm64',
+ terminal: 'ghostty',
+ shell: 'zsh',
+ package_managers: 'npm,pnpm',
+ runtimes: 'bun,node',
+ is_ci: false,
+ is_claubbit: false,
+ is_github_action: false,
+ is_claude_code_action: false,
+ is_claude_code_remote: false,
+ is_local_agent_mode: false,
+ is_conductor: false,
+ deployment_environment: 'unknown-darwin',
+ vcs: 'git',
+ is_claude_ai_auth: true,
+ },
+ metadata: { rh: REMOTE_HASH, answer: 2, page: 'ready', seen: true },
+}
diff --git a/mods/telemetry/tests/fixtures/first-party-session.ts b/mods/telemetry/tests/fixtures/first-party-session.ts
index 0af68256..cb828b25 100644
--- a/mods/telemetry/tests/fixtures/first-party-session.ts
+++ b/mods/telemetry/tests/fixtures/first-party-session.ts
@@ -1,33 +1,112 @@
-import type { Args, HttpResponse, On, SessionAuthorization } from 'claude-code'
+import type { Args, On } from 'claude-code'
+import { mock } from 'claude-code/testing'
import { ACCEPTED } from './accepted.js'
import { BEARER } from './bearer.js'
+import { CONFIG_PATH } from './config-path.js'
+import { GLOBAL_CONFIG } from './global-config.js'
+import { LISTING } from './listing.js'
+import { PROBED } from './probed.js'
+import { REPO } from './repo.js'
+import type { SentSession } from './sent-session.js'
+import type { SessionOptions } from './session-options.js'
/**
- * Answers what the telemetry plugin reads of a session signed in first
- * party, and keeps each post the ingest accepts.
+ * Answers, beneath the plugins, everything the telemetry plugin reads of a
+ * session signed in first party on a Mac in a git checkout, on a mock clock.
+ *
+ * Keeps what the plugin did: each post, file read, program run and debug
+ * line, as it does it.
*
* @param on the test's `on`
- * @param authorization the credential the session holds
- * @param answer what the ingest answers each post; accepted by default
- * @returns each post, as it was made
+ * @param options how this session differs from the plain one
+ * @returns what the plugin did, and the clock
*/
export function firstPartySession(
on: On,
- authorization: SessionAuthorization = BEARER,
- answer: HttpResponse = ACCEPTED,
-) {
+ options: SessionOptions = {},
+): SentSession {
const posts: Args<'http.fetch'>[] = []
+ const reads: string[] = []
+ const runs: Args<'process.run'>[] = []
+ const lines: string[] = []
+ const clock = mock.clock(on)
+
+ const files: Readonly<Record<string, string>> = {
+ [CONFIG_PATH]: GLOBAL_CONFIG,
+ ...options.files,
+ }
+
+ const answers = options.answers ?? [ACCEPTED]
+ const authorizations = options.authorizations ?? [BEARER]
+ let authorizeCalls = 0
+
+ const isPolicyUnreadable = options.policy?.kind === 'unreadable'
+
+ on('session.start', ($, e) => ({ cwd: e.cwd }))
+ on('session.end', ($, e) => ({ sessionId: e.sessionId }))
on('session.id', () => ({ value: 'the-session' }))
on('session.model', () => ({ value: 'the-model' }))
- on('session.authorize', () => ({ value: authorization }))
+ on('session.surfaces', () => ({ value: ['terminal'] }))
+ on('session.cwd', () => ({ value: '/work' }))
+ on('session.repo', () => ({ value: REPO }))
+ on('fs.list', () => ({ value: LISTING }))
+
+ on('session.authorize', () => {
+ authorizeCalls += 1
+
+ const answer =
+ authorizations[Math.min(authorizeCalls, authorizations.length) - 1]
+
+ const isRefused = answer === 'refused'
+
+ return isRefused
+ ? { deny: 'the credential store is locked' }
+ : { value: answer === undefined ? BEARER : answer }
+ })
+
+ on('settings.read', () =>
+ isPolicyUnreadable
+ ? { deny: 'the managed settings file is unreadable' }
+ : { value: options.policy?.settings ?? {} },
+ )
+
+ on('fs.read', ($, e) => {
+ reads.push(e.path)
+
+ const text = files[e.path]
+
+ return text === undefined ? { deny: `ENOENT: ${e.path}` } : { value: text }
+ })
+
+ on('fs.exists', ($, e) => ({
+ value: (options.existing ?? []).includes(e.path),
+ }))
+
+ const probed = { ...PROBED, stdout: options.probeOutput ?? PROBED.stdout }
+
+ on('process.run', ($, e) => {
+ runs.push(e)
+
+ return { value: probed }
+ })
on('http.fetch', ($, e) => {
posts.push(e)
- return { value: answer }
+ return {
+ value: answers[Math.min(posts.length, answers.length) - 1] ?? ACCEPTED,
+ }
+ })
+
+ on('ui.log', ($, e) => {
+ if (e.to === 'debug') {
+ lines.push(e.text)
+ }
+
+ return { value: undefined }
})
- return posts
+ return { posts, reads, runs, lines, clock }
}
diff --git a/mods/telemetry/tests/fixtures/gate/failing-next.ts b/mods/telemetry/tests/fixtures/gate/failing-next.ts
new file mode 100644
index 00000000..1b9802c0
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/gate/failing-next.ts
@@ -0,0 +1,14 @@
+/**
+ * A continuation as the gate's catch is handed it after a failure: going
+ * on throws what beneath refused with.
+ *
+ * @param isCalled whether the failed hook had called next before it failed
+ * @returns the continuation
+ */
+export const failingNext = (isCalled: boolean) =>
+ Object.assign(
+ () => {
+ throw new Error('beneath refused the entry')
+ },
+ { called: isCalled, error: { kind: 'throw' as const, budget: 0 } },
+ )
diff --git a/mods/telemetry/tests/fixtures/gate/index.ts b/mods/telemetry/tests/fixtures/gate/index.ts
new file mode 100644
index 00000000..9a708078
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/gate/index.ts
@@ -0,0 +1,4 @@
+export * from './failing-next.js'
+export * from './next-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/tests/fixtures/gate/next-of.ts b/mods/telemetry/tests/fixtures/gate/next-of.ts
new file mode 100644
index 00000000..a24704a7
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/gate/next-of.ts
@@ -0,0 +1,13 @@
+import type { Tier } from 'claude-code'
+
+/**
+ * A continuation as the gate is handed it: answers `served` when gone on
+ * to, stamped with a caller in the tier given, or with no origin at all.
+ *
+ * @param tier the caller's tier; undefined for a call that names no origin
+ * @returns the continuation
+ */
+export const nextOf = (tier: Tier | undefined) =>
+ Object.assign(() => 'served', {
+ origin: tier === undefined ? undefined : { plugin: 'caller', tier },
+ })
diff --git a/mods/telemetry/tests/fixtures/global-config.ts b/mods/telemetry/tests/fixtures/global-config.ts
new file mode 100644
index 00000000..221dc8cb
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/global-config.ts
@@ -0,0 +1,16 @@
+import { DEVICE_ID } from './device-id.js'
+
+/**
+ * The CLI's global config as the session's machine holds it: the install's
+ * device id and the signed-in account, among keys the plugin never reads.
+ */
+export const GLOBAL_CONFIG = JSON.stringify({
+ autoUpdates: true,
+ userID: DEVICE_ID,
+ oauthAccount: {
+ accountUuid: 'acc-1111-2222',
+ organizationUuid: 'org-3333-4444',
+ emailAddress: '[email protected]',
+ },
+ projects: { '/work': {} },
+})
diff --git a/mods/telemetry/tests/fixtures/held.ts b/mods/telemetry/tests/fixtures/held.ts
new file mode 100644
index 00000000..f4b2d74c
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/held.ts
@@ -0,0 +1,6 @@
+import type { Telemetry } from '../../types'
+
+/**
+ * What the holding plugin keeps of the table it was handed: the noun.
+ */
+export type Held = { telemetry: Telemetry }
diff --git a/mods/telemetry/tests/fixtures/index.ts b/mods/telemetry/tests/fixtures/index.ts
index df60764d..7515e935 100644
--- a/mods/telemetry/tests/fixtures/index.ts
+++ b/mods/telemetry/tests/fixtures/index.ts
@@ -1,20 +1,32 @@
export * from './accepted.js'
-export * from './analytics-off-environments.js'
-export * from './base64-alphabet.js'
-export * from './base64-decoded.js'
-export * from './base64-digit-bits.js'
-export * from './batch-of.js'
export * from './bearer.js'
+export * from './config-path.js'
+export * from './deaf-telemetry.js'
+export * from './device-id.js'
+export * from './ended.js'
+export * from './environments'
+export * from './expected-row.js'
export * from './first-party-session.js'
export * from './fullscreen.js'
-export type * from './ingest-batch.js'
-export type * from './ingest-event.js'
+export * from './gate'
+export * from './global-config.js'
+export type * from './held.js'
+export * from './listing.js'
export * from './mark.js'
-export * from './marking.js'
+export * from './plugins'
+export type * from './policy-option.js'
+export * from './probed.js'
+export * from './read-tool.js'
export * from './record.js'
-export * from './recording.js'
export * from './refused.js'
-export * from './row-of.js'
+export * from './rejected.js'
+export * from './remote-hash.js'
+export * from './repo.js'
+export type * from './sent-session.js'
+export type * from './session-options.js'
+export * from './started.js'
export * from './survey-answer.js'
+export * from './typed.js'
+export * from './wire'
export * as default from '.'
diff --git a/mods/telemetry/tests/fixtures/listing.ts b/mods/telemetry/tests/fixtures/listing.ts
new file mode 100644
index 00000000..ce527daa
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/listing.ts
@@ -0,0 +1,8 @@
+import type { FsEntry } from 'claude-code'
+
+/**
+ * What the session's working directory lists: a git checkout.
+ */
+export const LISTING: FsEntry[] = [
+ { name: '.git', kind: 'dir', size: 0, isLink: false },
+]
diff --git a/mods/telemetry/tests/fixtures/plugins/holding.ts b/mods/telemetry/tests/fixtures/plugins/holding.ts
new file mode 100644
index 00000000..e7017aad
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/plugins/holding.ts
@@ -0,0 +1,29 @@
+import type { Plugin } from 'claude-code/testing'
+
+import type { Held } from '../held.js'
+
+/**
+ * A plugin a person installed that keeps the table its engine.create step
+ * is handed, to call `telemetry.log` off it later; the scan refuses it.
+ */
+export const holding: Plugin = {
+ name: 'holding',
+ tier: 'user',
+ register(on) {
+ let held: Held | null = null
+
+ on('engine.create', async (_$, e, next) => {
+ const beneath = await next(e)
+
+ held = beneath
+
+ return beneath
+ })
+
+ on('command.run', { command: 'hold' }, async () => {
+ await held?.telemetry.log({ event: 'held' })
+
+ return { text: 'served' }
+ })
+ },
+}
diff --git a/mods/telemetry/tests/fixtures/plugins/index.ts b/mods/telemetry/tests/fixtures/plugins/index.ts
new file mode 100644
index 00000000..58491083
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/plugins/index.ts
@@ -0,0 +1,11 @@
+export * from './holding.js'
+export * from './managing.js'
+export * from './marking.js'
+export * from './meddling.js'
+export * from './reaching.js'
+export * from './recording.js'
+export * from './replacing.js'
+export * from './swallowing.js'
+export * from './visiting.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/tests/fixtures/plugins/managing.ts b/mods/telemetry/tests/fixtures/plugins/managing.ts
new file mode 100644
index 00000000..61b6f3bf
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/plugins/managing.ts
@@ -0,0 +1,18 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin an administrator prepended whose `/manage <entry>` marks the
+ * entry through `$.telemetry`, answering "queued", or why it was refused.
+ */
+export const managing: Plugin = {
+ name: 'managing',
+ tier: 'prepend',
+ register(on) {
+ on('command.run', { command: 'manage' }, ($, e) =>
+ $.telemetry.mark(JSON.parse(e.args)).then(
+ () => ({ text: 'queued' }),
+ (error: unknown) => ({ text: String(error) }),
+ ),
+ )
+ },
+}
diff --git a/mods/telemetry/tests/fixtures/marking.ts b/mods/telemetry/tests/fixtures/plugins/marking.ts
similarity index 61%
rename from mods/telemetry/tests/fixtures/marking.ts
rename to mods/telemetry/tests/fixtures/plugins/marking.ts
index 9599e93c..7cc1a142 100644
--- a/mods/telemetry/tests/fixtures/marking.ts
+++ b/mods/telemetry/tests/fixtures/plugins/marking.ts
@@ -1,15 +1,16 @@
import type { Plugin } from 'claude-code/testing'
/**
- * A plugin whose `/mark <entry>` marks the entry through `$.telemetry`,
- * answering "sent", or why the mark was refused.
+ * A built-in plugin whose `/mark <entry>` marks the entry through
+ * `$.telemetry`, answering "queued", or why the mark was refused.
*/
export const marking: Plugin = {
name: 'marking',
+ tier: 'builtin',
register(on) {
on('command.run', { command: 'mark' }, ($, e) =>
$.telemetry.mark(JSON.parse(e.args)).then(
- () => ({ text: 'sent' }),
+ () => ({ text: 'queued' }),
(error: unknown) => ({ text: String(error) }),
),
)
diff --git a/mods/telemetry/tests/fixtures/plugins/meddling.ts b/mods/telemetry/tests/fixtures/plugins/meddling.ts
new file mode 100644
index 00000000..8c19d26e
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/plugins/meddling.ts
@@ -0,0 +1,20 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin a person installed that hooks `telemetry.log` above the gate to
+ * rename every row, and logs one of its own through `/meddle`.
+ */
+export const meddling: Plugin = {
+ name: 'meddling',
+ tier: 'user',
+ register(on) {
+ on('telemetry.log', (_$, e, next) => next({ ...e, event: 'renamed' }))
+
+ on('command.run', { command: 'meddle' }, $ =>
+ $.telemetry.log({ event: 'mine' }).then(
+ () => ({ text: 'served' }),
+ (error: unknown) => ({ text: String(error) }),
+ ),
+ )
+ },
+}
diff --git a/mods/telemetry/tests/fixtures/plugins/reaching.ts b/mods/telemetry/tests/fixtures/plugins/reaching.ts
new file mode 100644
index 00000000..542900db
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/plugins/reaching.ts
@@ -0,0 +1,49 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin a person installed that reaches for `$.telemetry` every way it
+ * can; `/reach` says how the first went, the debug log the other two.
+ *
+ * On the table its engine.create step is handed, from a timer its
+ * session.start sets, and from a tool.call hook.
+ */
+export const reaching: Plugin = {
+ name: 'reaching',
+ tier: 'user',
+ register(on) {
+ let during = 'not called'
+
+ on('engine.create', async (_$, e, next) => {
+ const beneath = await next(e)
+
+ during = await beneath.telemetry
+ .log({ event: 'during_create' })
+ .then(() => 'served', String)
+
+ return beneath
+ })
+
+ on('session.start', ($, e, next) => {
+ $.clock.after(1, () => {
+ void $.telemetry
+ .log({ event: 'from_timer' })
+ .then(() => 'served', String)
+ .then(outcome => $.ui.log(`timer: ${outcome}`, { to: 'debug' }))
+ })
+
+ return next(e)
+ })
+
+ on('tool.call', { tool: 'Read' }, async ($, e, next) => {
+ const outcome = await $.telemetry
+ .log({ event: 'from_tool' })
+ .then(() => 'served', String)
+
+ await $.ui.log(`tool: ${outcome}`, { to: 'debug' })
+
+ return next(e)
+ })
+
+ on('command.run', { command: 'reach' }, () => ({ text: during }))
+ },
+}
diff --git a/mods/telemetry/tests/fixtures/recording.ts b/mods/telemetry/tests/fixtures/plugins/recording.ts
similarity index 62%
rename from mods/telemetry/tests/fixtures/recording.ts
rename to mods/telemetry/tests/fixtures/plugins/recording.ts
index ed6ec560..28c279ab 100644
--- a/mods/telemetry/tests/fixtures/recording.ts
+++ b/mods/telemetry/tests/fixtures/plugins/recording.ts
@@ -1,15 +1,16 @@
import type { Plugin } from 'claude-code/testing'
/**
- * A plugin whose `/record <entry>` logs the entry through `$.telemetry`,
- * answering "sent", or why the row was refused.
+ * A built-in plugin whose `/record <entry>` logs the entry through
+ * `$.telemetry`, answering "queued", or why the row was refused.
*/
export const recording: Plugin = {
name: 'recording',
+ tier: 'builtin',
register(on) {
on('command.run', { command: 'record' }, ($, e) =>
$.telemetry.log(JSON.parse(e.args)).then(
- () => ({ text: 'sent' }),
+ () => ({ text: 'queued' }),
(error: unknown) => ({ text: String(error) }),
),
)
diff --git a/mods/telemetry/tests/fixtures/plugins/replacing.ts b/mods/telemetry/tests/fixtures/plugins/replacing.ts
new file mode 100644
index 00000000..d52d5941
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/plugins/replacing.ts
@@ -0,0 +1,25 @@
+import type { Plugin } from 'claude-code/testing'
+
+import { DEAF_TELEMETRY } from '../deaf-telemetry.js'
+
+/**
+ * A plugin a person installed whose engine.create step hands up its own
+ * `telemetry` in place of the one beneath, then logs through `/replace`.
+ */
+export const replacing: Plugin = {
+ name: 'replacing',
+ tier: 'user',
+ register(on) {
+ on('engine.create', async (_$, e, next) => ({
+ ...(await next(e)),
+ telemetry: DEAF_TELEMETRY,
+ }))
+
+ on('command.run', { command: 'replace' }, $ =>
+ $.telemetry.log({ event: 'mine' }).then(
+ () => ({ text: 'served' }),
+ (error: unknown) => ({ text: String(error) }),
+ ),
+ )
+ },
+}
diff --git a/mods/telemetry/tests/fixtures/plugins/swallowing.ts b/mods/telemetry/tests/fixtures/plugins/swallowing.ts
new file mode 100644
index 00000000..af9be34c
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/plugins/swallowing.ts
@@ -0,0 +1,13 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin a person installed that answers `telemetry.log` above the gate
+ * without going on beneath: the rows of everyone beneath it stop there.
+ */
+export const swallowing: Plugin = {
+ name: 'swallowing',
+ tier: 'user',
+ register(on) {
+ on('telemetry.log', () => ({ value: undefined }))
+ },
+}
diff --git a/mods/telemetry/tests/fixtures/plugins/visiting.ts b/mods/telemetry/tests/fixtures/plugins/visiting.ts
new file mode 100644
index 00000000..7ce60d89
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/plugins/visiting.ts
@@ -0,0 +1,18 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin a person installed whose `/visit <entry>` logs the entry through
+ * `$.telemetry`, answering "queued", or why the row was refused.
+ */
+export const visiting: Plugin = {
+ name: 'visiting',
+ tier: 'user',
+ register(on) {
+ on('command.run', { command: 'visit' }, ($, e) =>
+ $.telemetry.log(JSON.parse(e.args)).then(
+ () => ({ text: 'queued' }),
+ (error: unknown) => ({ text: String(error) }),
+ ),
+ )
+ },
+}
diff --git a/mods/telemetry/tests/fixtures/policy-option.ts b/mods/telemetry/tests/fixtures/policy-option.ts
new file mode 100644
index 00000000..26b4759e
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/policy-option.ts
@@ -0,0 +1,10 @@
+/**
+ * The managed policy a test's session reads: the settings' keys, or the
+ * word `unreadable` when the settings cannot be read at all.
+ */
+export type PolicyOption =
+ | {
+ readonly kind: 'settings'
+ readonly settings: Readonly<Record<string, unknown>>
+ }
+ | { readonly kind: 'unreadable' }
diff --git a/mods/telemetry/tests/fixtures/probed.ts b/mods/telemetry/tests/fixtures/probed.ts
new file mode 100644
index 00000000..262c0649
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/probed.ts
@@ -0,0 +1,11 @@
+import type { ProcessRunResult } from 'claude-code'
+
+/**
+ * What the one machine probe prints on the session's Mac: Darwin on arm64,
+ * npm and pnpm on the PATH, bun and node too.
+ */
+export const PROBED: ProcessRunResult = {
+ exitCode: 0,
+ stdout: 'Darwin\n25.6.0\narm64\nnpm,pnpm,\nbun,node,\n',
+ stderr: '',
+}
diff --git a/mods/telemetry/tests/fixtures/read-tool.ts b/mods/telemetry/tests/fixtures/read-tool.ts
new file mode 100644
index 00000000..7136fe7c
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/read-tool.ts
@@ -0,0 +1,6 @@
+import type { ToolCallArgs } from 'claude-code'
+
+/**
+ * A Read the model asks for, for the reaching plugin's tool.call hook.
+ */
+export const READ_TOOL: ToolCallArgs = { tool: 'Read', file_path: '/work/a' }
diff --git a/mods/telemetry/tests/fixtures/refused.ts b/mods/telemetry/tests/fixtures/refused.ts
index 334f1aba..2420b829 100644
--- a/mods/telemetry/tests/fixtures/refused.ts
+++ b/mods/telemetry/tests/fixtures/refused.ts
@@ -1,7 +1,7 @@
import type { HttpResponse } from 'claude-code'
/**
- * The ingest's answer while it is down.
+ * The ingest's answer while it is down: worth the one retry.
*/
export const REFUSED: HttpResponse = {
status: 500,
diff --git a/mods/telemetry/tests/fixtures/rejected.ts b/mods/telemetry/tests/fixtures/rejected.ts
new file mode 100644
index 00000000..db308337
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/rejected.ts
@@ -0,0 +1,11 @@
+import type { HttpResponse } from 'claude-code'
+
+/**
+ * The ingest's answer to a batch it will never take: not retried.
+ */
+export const REJECTED: HttpResponse = {
+ status: 400,
+ ok: false,
+ headers: {},
+ text: '',
+}
diff --git a/mods/telemetry/tests/fixtures/remote-hash.ts b/mods/telemetry/tests/fixtures/remote-hash.ts
new file mode 100644
index 00000000..8600d0cf
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/remote-hash.ts
@@ -0,0 +1,5 @@
+/**
+ * The first sixteen hex digits of the SHA-256 of REPO's remote normalized
+ * (`github.com/anthropics/claude-code`): what the rows carry as `rh`.
+ */
+export const REMOTE_HASH = 'd900cba35dcd6960'
diff --git a/mods/telemetry/tests/fixtures/repo.ts b/mods/telemetry/tests/fixtures/repo.ts
new file mode 100644
index 00000000..fac2f210
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/repo.ts
@@ -0,0 +1,11 @@
+import type { SessionRepo } from 'claude-code'
+
+/**
+ * The repository the session runs in: a GitHub remote over ssh.
+ */
+export const REPO: SessionRepo = {
+ root: '/work',
+ remote: '[email protected]:anthropics/claude-code.git',
+ internal: false,
+ name: null,
+}
diff --git a/mods/telemetry/tests/fixtures/row-of.ts b/mods/telemetry/tests/fixtures/row-of.ts
deleted file mode 100644
index 22f06885..00000000
--- a/mods/telemetry/tests/fixtures/row-of.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import type { Args } from 'claude-code'
-
-import { base64Decoded } from './base64-decoded.js'
-import { batchOf } from './batch-of.js'
-
-/**
- * The one row a post to the ingest carries, held steady for a test: its
- * random id and timestamp dropped, `hasTimestamp` and `metadata` decoded.
- *
- * @param post the `http.fetch` the plugin made
- * @returns the row's type, whether it was stamped, its fields and metadata
- */
-export function rowOf(post: Args<'http.fetch'>): unknown {
- const [event] = batchOf(post).events
-
- const {
- event_id: _eventId,
- client_timestamp,
- additional_metadata,
- ...rest
- } = event?.event_data ?? {}
-
- return {
- event_type: event?.event_type,
- hasTimestamp: typeof client_timestamp === 'string',
- ...rest,
- metadata: JSON.parse(base64Decoded(String(additional_metadata))),
- }
-}
diff --git a/mods/telemetry/tests/fixtures/sent-session.ts b/mods/telemetry/tests/fixtures/sent-session.ts
new file mode 100644
index 00000000..38a06ba8
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/sent-session.ts
@@ -0,0 +1,14 @@
+import type { Args } from 'claude-code'
+import type { MockClock } from 'claude-code/testing'
+
+/**
+ * What a test reads back of its session: each post to the ingest, each file
+ * read and program run the plugin made, each debug line, and the clock.
+ */
+export type SentSession = {
+ readonly posts: Args<'http.fetch'>[]
+ readonly reads: string[]
+ readonly runs: Args<'process.run'>[]
+ readonly lines: string[]
+ readonly clock: MockClock
+}
diff --git a/mods/telemetry/tests/fixtures/session-options.ts b/mods/telemetry/tests/fixtures/session-options.ts
new file mode 100644
index 00000000..95bff654
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/session-options.ts
@@ -0,0 +1,19 @@
+import type { HttpResponse, SessionAuthorization } from 'claude-code'
+
+import type { PolicyOption } from './policy-option.js'
+
+/**
+ * How a test's session differs from the plain one.
+ *
+ * What `authorize` and the ingest answer in turn (`refused`: the store will
+ * not open; the last repeats), the managed policy (`unreadable` when it
+ * cannot be read), and the machine's files, markers and probe output.
+ */
+export type SessionOptions = {
+ readonly authorizations?: readonly (SessionAuthorization | 'refused')[]
+ readonly answers?: readonly HttpResponse[]
+ readonly policy?: PolicyOption
+ readonly files?: Readonly<Record<string, string>>
+ readonly existing?: readonly string[]
+ readonly probeOutput?: string
+}
diff --git a/mods/telemetry/tests/fixtures/started.ts b/mods/telemetry/tests/fixtures/started.ts
new file mode 100644
index 00000000..2e6e2914
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/started.ts
@@ -0,0 +1,10 @@
+import type { SessionStartInput } from 'claude-code'
+
+/**
+ * The session as it starts: a person at the prompt in the checkout.
+ */
+export const STARTED: SessionStartInput = {
+ cwd: '/work',
+ surface: 'terminal',
+ isInteractive: true,
+}
diff --git a/mods/telemetry/tests/fixtures/typed.ts b/mods/telemetry/tests/fixtures/typed.ts
new file mode 100644
index 00000000..d705b23a
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/typed.ts
@@ -0,0 +1,17 @@
+import type { CommandRunInput } from 'claude-code'
+
+import { FULLSCREEN } from './fullscreen.js'
+
+/**
+ * A command typed at the prompt with an entry as its argument.
+ *
+ * @param command the command's name
+ * @param entry what it carries
+ * @returns the command as the person would run it
+ */
+export const typed = (command: string, entry: unknown): CommandRunInput => ({
+ command,
+ args: JSON.stringify(entry),
+ origin: { kind: 'composer' },
+ presentation: FULLSCREEN,
+})
diff --git a/mods/telemetry/tests/fixtures/base64-alphabet.ts b/mods/telemetry/tests/fixtures/wire/base64-alphabet.ts
similarity index 100%
rename from mods/telemetry/tests/fixtures/base64-alphabet.ts
rename to mods/telemetry/tests/fixtures/wire/base64-alphabet.ts
diff --git a/mods/telemetry/tests/fixtures/base64-decoded.ts b/mods/telemetry/tests/fixtures/wire/base64-decoded.ts
similarity index 91%
rename from mods/telemetry/tests/fixtures/base64-decoded.ts
rename to mods/telemetry/tests/fixtures/wire/base64-decoded.ts
index 8e83a7f1..5de0ce17 100644
--- a/mods/telemetry/tests/fixtures/base64-decoded.ts
+++ b/mods/telemetry/tests/fixtures/wire/base64-decoded.ts
@@ -8,7 +8,7 @@ import { BASE64_DIGIT_BITS } from './base64-digit-bits.js'
* @param encoded the base64 text
* @returns the decoded text
*/
-export const base64Decoded = (encoded: string): string =>
+export const base64Decoded = (encoded: string) =>
(
[...encoded.replace(/=+$/, '')]
.map(digit =>
diff --git a/mods/telemetry/tests/fixtures/base64-digit-bits.ts b/mods/telemetry/tests/fixtures/wire/base64-digit-bits.ts
similarity index 100%
rename from mods/telemetry/tests/fixtures/base64-digit-bits.ts
rename to mods/telemetry/tests/fixtures/wire/base64-digit-bits.ts
diff --git a/mods/telemetry/tests/fixtures/batch-of.ts b/mods/telemetry/tests/fixtures/wire/batch-of.ts
similarity index 100%
rename from mods/telemetry/tests/fixtures/batch-of.ts
rename to mods/telemetry/tests/fixtures/wire/batch-of.ts
diff --git a/mods/telemetry/tests/fixtures/wire/event-name-of.ts b/mods/telemetry/tests/fixtures/wire/event-name-of.ts
new file mode 100644
index 00000000..3452b7ab
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/wire/event-name-of.ts
@@ -0,0 +1,12 @@
+/**
+ * The name a row was sent under, as rowsOf reads the row back; undefined
+ * for a value that is no row.
+ *
+ * @param row one of rowsOf's rows
+ * @returns the name the row was sent under
+ */
+export function eventNameOf(row: unknown): unknown {
+ const isRow = typeof row === 'object' && row !== null && 'event_name' in row
+
+ return isRow ? row.event_name : undefined
+}
diff --git a/mods/telemetry/tests/fixtures/wire/index.ts b/mods/telemetry/tests/fixtures/wire/index.ts
new file mode 100644
index 00000000..bfe10ed5
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/wire/index.ts
@@ -0,0 +1,10 @@
+export * from './base64-alphabet.js'
+export * from './base64-decoded.js'
+export * from './base64-digit-bits.js'
+export * from './batch-of.js'
+export * from './event-name-of.js'
+export type * from './ingest-batch.js'
+export type * from './ingest-event.js'
+export * from './rows-of.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/tests/fixtures/ingest-batch.ts b/mods/telemetry/tests/fixtures/wire/ingest-batch.ts
similarity index 100%
rename from mods/telemetry/tests/fixtures/ingest-batch.ts
rename to mods/telemetry/tests/fixtures/wire/ingest-batch.ts
diff --git a/mods/telemetry/tests/fixtures/ingest-event.ts b/mods/telemetry/tests/fixtures/wire/ingest-event.ts
similarity index 100%
rename from mods/telemetry/tests/fixtures/ingest-event.ts
rename to mods/telemetry/tests/fixtures/wire/ingest-event.ts
diff --git a/mods/telemetry/tests/fixtures/wire/rows-of.ts b/mods/telemetry/tests/fixtures/wire/rows-of.ts
new file mode 100644
index 00000000..15d44e4e
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/wire/rows-of.ts
@@ -0,0 +1,27 @@
+import type { SentSession } from '../sent-session.js'
+import { base64Decoded } from './base64-decoded.js'
+import { batchOf } from './batch-of.js'
+
+/**
+ * Every row the session's posts carried, in order, held steady for a test:
+ * a row's random id and timestamp told as present, its metadata decoded.
+ *
+ * @param session what the plugin did
+ * @returns each row's type and fields, with `metadata` decoded
+ */
+export const rowsOf = (session: SentSession): unknown[] =>
+ session.posts.flatMap(post =>
+ batchOf(post).events.map(event => {
+ const { event_id, client_timestamp, additional_metadata, ...rest } =
+ event.event_data
+
+ return {
+ event_type: event.event_type,
+ hasEventId:
+ typeof event_id === 'string' && /^[0-9a-f-]{36}$/.test(event_id),
+ hasTimestamp: typeof client_timestamp === 'string',
+ ...rest,
+ metadata: JSON.parse(base64Decoded(String(additional_metadata))),
+ }
+ }),
+ )
diff --git a/mods/telemetry/tests/gate.test.ts b/mods/telemetry/tests/gate.test.ts
new file mode 100644
index 00000000..f348b1ce
--- /dev/null
+++ b/mods/telemetry/tests/gate.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, mock, test, tier } from 'claude-code/testing'
+
+import Hooks from '../hooks'
+import Fixtures from './fixtures'
+
+tier('builtin')
+
+const refusal = `HooksError: reaching: $.telemetry.log: ${Hooks.REFUSED.deny}`
+
+describe('gate', () => {
+ test(
+ 'the table an engine.create step is handed serves no one above either',
+ { plugins: [Fixtures.recording, Fixtures.reaching] },
+ async ($, on) => {
+ mock.env(on, Fixtures.SENDING_ENV)
+
+ const session = Fixtures.firstPartySession(on)
+
+ on('tool.call', () => ({ result: 'read' }))
+
+ await $.session.start(Fixtures.STARTED)
+ await session.clock.advance(1)
+ await $.tool.call(Fixtures.READ_TOOL)
+
+ const during = (await $.command.run(Fixtures.typed('reach', {}))).text
+
+ await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+
+ expect({
+ isServedDuringCreate: during === 'served',
+ later: session.lines.filter(line => !line.startsWith('telemetry: ')),
+ rows: Fixtures.rowsOf(session).map(Fixtures.eventNameOf),
+ }).toEqual({
+ isServedDuringCreate: false,
+ later: [`timer: ${refusal}`, `tool: ${refusal}`],
+ rows: ['tengu_plugin_survey_answered'],
+ })
+ },
+ )
+
+ test(
+ 'a module that keeps the table to call later never loads',
+ { plugins: [Fixtures.holding] },
+ async ($, on) => {
+ mock.env(on, Fixtures.SENDING_ENV)
+
+ const session = Fixtures.firstPartySession(on)
+
+ const held = await $.command
+ .run(Fixtures.typed('hold', {}))
+ .then(result => result.text, String)
+
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+
+ expect({
+ isLoaded: !String(held).includes('did not load'),
+ posts: session.posts,
+ }).toEqual({ isLoaded: false, posts: [] })
+ },
+ )
+
+ test(
+ 'a hook above may rename a row a built-in sends, never send its own',
+ { plugins: [Fixtures.recording, Fixtures.meddling] },
+ async ($, on) => {
+ mock.env(on, Fixtures.SENDING_ENV)
+
+ const session = Fixtures.firstPartySession(on)
+ const own = (await $.command.run(Fixtures.typed('meddle', {}))).text
+
+ await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+
+ expect({
+ own,
+ rows: Fixtures.rowsOf(session).map(Fixtures.eventNameOf),
+ }).toEqual({
+ own: `HooksError: meddling: $.telemetry.log: ${Hooks.REFUSED.deny}`,
+ rows: ['tengu_plugin_renamed'],
+ })
+ },
+ )
+
+ test(
+ 'a hook above that answers without going on sends nothing at all',
+ { plugins: [Fixtures.recording, Fixtures.swallowing] },
+ async ($, on) => {
+ mock.env(on, Fixtures.SENDING_ENV)
+
+ const session = Fixtures.firstPartySession(on)
+
+ const answer = (
+ await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))
+ ).text
+
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+
+ expect({ answer, posts: session.posts }).toEqual({
+ answer: 'queued',
+ posts: [],
+ })
+ },
+ )
+
+ test(
+ 'a step above cannot hand up its own telemetry in place of this one',
+ { plugins: [Fixtures.recording, Fixtures.replacing] },
+ async ($, on) => {
+ mock.env(on, Fixtures.SENDING_ENV)
+
+ const session = Fixtures.firstPartySession(on)
+ const own = (await $.command.run(Fixtures.typed('replace', {}))).text
+
+ await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+
+ expect({
+ own,
+ rows: Fixtures.rowsOf(session).map(Fixtures.eventNameOf),
+ }).toEqual({
+ own: `HooksError: replacing: $.telemetry.log: ${Hooks.REFUSED.deny}`,
+ rows: ['tengu_plugin_survey_answered'],
+ })
+ },
+ )
+})
diff --git a/mods/telemetry/tests/register.test.ts b/mods/telemetry/tests/register.test.ts
index b3a92e9a..1fca2e42 100644
--- a/mods/telemetry/tests/register.test.ts
+++ b/mods/telemetry/tests/register.test.ts
@@ -1,54 +1,107 @@
-import type { Args } from 'claude-code'
import { describe, expect, mock, test, tier } from 'claude-code/testing'
+import Hooks from '../hooks'
import Fixtures from './fixtures'
tier('builtin')
+const tiers = ['builtin', 'core', 'user', 'prepend', 'append'] as const
+
describe('register', () => {
test(
- 'a $.telemetry.log call from a plugin posts one first-party row',
+ 'rows queued through $.telemetry.log go out as one complete batch',
{ plugins: [Fixtures.recording] },
async ($, on) => {
- mock.env(on, { USER_TYPE: 'ant' })
+ mock.env(on, Fixtures.SENDING_ENV)
- const posts = Fixtures.firstPartySession(on)
+ const session = Fixtures.firstPartySession(on)
- expect(
- await $.command.run(Fixtures.record(Fixtures.surveyAnswer())),
- ).toEqual({ text: 'sent' })
+ await $.session.start(Fixtures.STARTED)
+
+ const first = await $.command.run(
+ Fixtures.record(Fixtures.surveyAnswer()),
+ )
+
+ await $.command.run(Fixtures.record({ event: 'again', props: { n: 1 } }))
+
+ expect(first).toEqual({ text: 'queued' })
+ expect(session.posts, 'nothing before the window passes').toEqual([])
+
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
expect(
- posts.map(post => [post.url, post.init?.method, post.init?.auth]),
+ session.posts.map(post => [
+ post.url,
+ post.init?.method,
+ post.init?.auth,
+ post.init?.headers,
+ ]),
).toEqual([
[
'https://api.anthropic.com/api/event_logging/v2/batch',
'POST',
'the-handle',
+ {
+ 'Content-Type': 'application/json',
+ 'x-service-name': 'claude-code',
+ },
],
])
- expect(posts.map(Fixtures.rowOf)).toEqual([
- {
- event_type: 'ClaudeCodeInternalEvent',
- hasTimestamp: true,
- event_name: 'tengu_plugin_survey_answered',
- session_id: 'the-session',
- model: 'the-model',
- user_type: 'ant',
- metadata: { answer: 2, page: 'ready', seen: true },
- },
- ])
+ expect(Fixtures.rowsOf(session)).toHaveLength(2)
+ expect(Fixtures.rowsOf(session)[0]).toEqual(Fixtures.EXPECTED_ROW)
+
+ expect(Fixtures.rowsOf(session)[1]).toMatchObject({
+ event_name: 'tengu_plugin_again',
+ metadata: { rh: Fixtures.REMOTE_HASH, n: 1 },
+ })
+
+ expect(session.lines).toEqual(['telemetry: sent 2 row(s)'])
},
)
test(
- 'a row already named tengu_ is sent under its own name',
+ 'a full queue goes out at once, before the window',
{ plugins: [Fixtures.recording] },
async ($, on) => {
- mock.env(on, {})
+ mock.env(on, Fixtures.SENDING_ENV)
+
+ const session = Fixtures.firstPartySession(on)
+
+ for (let row = 0; row < Hooks.BATCH_ROWS; row++) {
+ await $.command.run(Fixtures.record({ event: 'x', props: { row } }))
+ }
- const posts = Fixtures.firstPartySession(on)
+ await session.clock.settle()
+
+ expect(session.posts).toHaveLength(1)
+ expect(Fixtures.rowsOf(session)).toHaveLength(Hooks.BATCH_ROWS)
+ },
+ )
+
+ test(
+ 'the end of the session sends what still waits',
+ { plugins: [Fixtures.recording] },
+ async ($, on) => {
+ mock.env(on, Fixtures.SENDING_ENV)
+
+ const session = Fixtures.firstPartySession(on)
+
+ await $.session.start(Fixtures.STARTED)
+ await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))
+ await $.session.end(Fixtures.ENDED)
+
+ expect(Fixtures.rowsOf(session)).toEqual([Fixtures.EXPECTED_ROW])
+ },
+ )
+
+ test(
+ 'a tengu_ name is kept; an external build sends no address',
+ { plugins: [Fixtures.recording] },
+ async ($, on) => {
+ mock.env(on, { ...Fixtures.SENDING_ENV, USER_TYPE: 'external' })
+
+ const session = Fixtures.firstPartySession(on)
await $.command.run(
Fixtures.record({
@@ -57,18 +110,15 @@ describe('register', () => {
}),
)
- expect(posts.map(Fixtures.batchOf)).toMatchObject([
- {
- events: [
- {
- event_data: {
- event_name: 'tengu_repl_diff_panel_shown',
- user_type: 'external',
- },
- },
- ],
- },
- ])
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+
+ expect(Fixtures.rowsOf(session)[0]).toMatchObject({
+ event_name: 'tengu_repl_diff_panel_shown',
+ user_type: 'external',
+ device_id: Fixtures.DEVICE_ID,
+ })
+
+ expect(Fixtures.rowsOf(session)[0]).not.toHaveProperty('email')
},
)
@@ -80,58 +130,120 @@ describe('register', () => {
on('env.get', ($, e) => ({ value: environment[e.name] }))
- const posts = Fixtures.firstPartySession(on)
+ const session = Fixtures.firstPartySession(on)
const answers: (string | undefined)[] = []
for (const off of Fixtures.ANALYTICS_OFF_ENVIRONMENTS) {
- environment = { USER_TYPE: 'ant', ...off }
+ environment = { ...Fixtures.SENDING_ENV, ...off }
answers.push(
(await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))).text,
)
+
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
}
- const withheld = posts.length
+ const withheld = session.posts.length
- environment = { USER_TYPE: 'ant' }
+ environment = Fixtures.SENDING_ENV
await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
expect(answers).toEqual(
- Fixtures.ANALYTICS_OFF_ENVIRONMENTS.map(() => 'sent'),
+ Fixtures.ANALYTICS_OFF_ENVIRONMENTS.map(() => 'queued'),
)
expect(withheld, 'nothing posted while any switch was off').toBe(0)
- expect(posts, 'then one row once every switch is clear').toHaveLength(1)
+
+ expect(
+ session.posts,
+ 'one batch once every switch is clear',
+ ).toHaveLength(1)
},
)
test(
- 'a third-party provider the host manages sends nothing too',
+ 'a gateway the managed policy pins sends nothing',
{ plugins: [Fixtures.recording] },
async ($, on) => {
- mock.env(on, {
- CLAUDE_CODE_USE_BEDROCK: '1',
- CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST: '1',
+ mock.env(on, Fixtures.SENDING_ENV)
+
+ const session = Fixtures.firstPartySession(on, {
+ policy: { kind: 'settings', settings: { forceLoginMethod: 'gateway' } },
})
- const posts = Fixtures.firstPartySession(on)
+ await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+
+ expect(session.posts).toEqual([])
+ },
+ )
+
+ test(
+ 'unreadable switches send nothing, and the debug log says why',
+ { plugins: [Fixtures.recording] },
+ async ($, on) => {
+ mock.env(on, Fixtures.SENDING_ENV)
+
+ const session = Fixtures.firstPartySession(on, {
+ policy: { kind: 'unreadable' },
+ })
const { text } = await $.command.run(
Fixtures.record(Fixtures.surveyAnswer()),
)
- expect({ text, posts }).toEqual({ text: 'sent', posts: [] })
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+
+ expect({ text, posts: session.posts }).toEqual({
+ text: 'queued',
+ posts: [],
+ })
+
+ expect(session.reads, 'nothing of the machine is read either').toEqual([])
+
+ expect(session.lines.at(-1)).toStartWith(
+ 'telemetry: the analytics switches could not be read, so nothing is ' +
+ 'sent (',
+ )
},
)
test(
- 'a $.telemetry.mark call posts the feature row by its own name',
+ 'a host-managed third-party provider follows DISABLE_TELEMETRY',
+ { plugins: [Fixtures.recording] },
+ async ($, on) => {
+ let environment = Fixtures.HOST_MANAGED_BEDROCK_ENV
+
+ on('env.get', ($, e) => ({ value: environment[e.name] }))
+
+ const session = Fixtures.firstPartySession(on)
+
+ await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+
+ const managed = session.posts.length
+
+ environment = { ...environment, DISABLE_TELEMETRY: '1' }
+
+ await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+
+ expect({ managed, afterOptOut: session.posts.length }).toEqual({
+ managed: 1,
+ afterOptOut: 1,
+ })
+ },
+ )
+
+ test(
+ 'marks go out as the feature events, by their own names',
{ plugins: [Fixtures.marking] },
async ($, on) => {
- mock.env(on, { USER_TYPE: 'ant' })
+ mock.env(on, Fixtures.SENDING_ENV)
- const posts = Fixtures.firstPartySession(on)
+ const session = Fixtures.firstPartySession(on)
const answers: (string | undefined)[] = []
for (const entry of [
@@ -142,11 +254,13 @@ describe('register', () => {
answers.push((await $.command.run(Fixtures.mark(entry))).text)
}
- expect(answers).toEqual(['sent', 'sent', 'sent'])
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+
+ expect(answers).toEqual(['queued', 'queued', 'queued'])
expect(
- posts.map(Fixtures.rowOf),
- 'the feature events by their own names, no plugin prefix',
+ Fixtures.rowsOf(session),
+ 'one batch, the feature events by their own names, no plugin prefix',
).toMatchObject([
{
event_name: 'tengu_feature_ok',
@@ -168,12 +282,12 @@ describe('register', () => {
)
test(
- 'a mark with a bad kind or a wrong reason is refused, nothing sent',
+ 'a mark with a bad kind or a wrong reason is refused, nothing queued',
{ plugins: [Fixtures.marking] },
async ($, on) => {
- mock.env(on, { USER_TYPE: 'ant' })
+ mock.env(on, Fixtures.SENDING_ENV)
- const posts = Fixtures.firstPartySession(on)
+ const session = Fixtures.firstPartySession(on)
const refusalFor = async (entry: unknown) =>
(await $.command.run(Fixtures.mark(entry))).text
@@ -196,63 +310,114 @@ describe('register', () => {
'$.telemetry.mark: takes a feature name, a snake_case token',
)
- expect(await refusalFor('x')).toEndWith(
- '$.telemetry.mark: takes one entry, { feature, kind, reason?, props? }',
- )
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
- expect(posts).toEqual([])
+ expect(session.posts).toEqual([])
},
)
test(
- 'a session with no first-party credential is refused, nothing sent',
+ 'with no first-party credential nothing is sent, and the debug log says so',
{ plugins: [Fixtures.recording] },
async ($, on) => {
- mock.env(on, {})
+ mock.env(on, Fixtures.SENDING_ENV)
- const posts = Fixtures.firstPartySession(on, null)
+ const session = Fixtures.firstPartySession(on, {
+ authorizations: [null],
+ })
const { text } = await $.command.run(
Fixtures.record(Fixtures.surveyAnswer()),
)
- expect(text).toEndWith(
- '$.telemetry.log: this session has no first-party credential to ' +
- 'authorize',
- )
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
- expect(posts).toEqual([])
+ expect({ text, posts: session.posts }).toEqual({
+ text: 'queued',
+ posts: [],
+ })
+
+ expect(session.lines.at(-1)).toBe(
+ 'telemetry: 1 row(s) not sent: this session has no first-party ' +
+ 'credential to authorize',
+ )
},
)
test(
- "the ingest's refusal rejects the caller's promise",
+ 'a server error is tried once more; a second one drops the batch',
{ plugins: [Fixtures.recording] },
async ($, on) => {
- mock.env(on, {})
+ mock.env(on, Fixtures.SENDING_ENV)
- const posts = Fixtures.firstPartySession(
- on,
- Fixtures.BEARER,
- Fixtures.REFUSED,
- )
+ const session = Fixtures.firstPartySession(on, {
+ answers: [Fixtures.REFUSED, Fixtures.REFUSED],
+ })
- const { text } = await $.command.run(
- Fixtures.record(Fixtures.surveyAnswer()),
+ await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+ await session.clock.advance(Hooks.RETRY_DELAY_MS)
+
+ expect(session.posts).toHaveLength(2)
+
+ expect(session.lines.at(-1)).toBe(
+ 'telemetry: 1 row(s) not sent: the ingest answered 500',
)
+ },
+ )
- expect(text).toEndWith('$.telemetry.log: the ingest answered 500')
- expect(posts).toHaveLength(1)
+ test(
+ 'a server error then an acceptance sends the batch',
+ { plugins: [Fixtures.recording] },
+ async ($, on) => {
+ mock.env(on, Fixtures.SENDING_ENV)
+
+ const session = Fixtures.firstPartySession(on, {
+ answers: [Fixtures.REFUSED, Fixtures.ACCEPTED],
+ })
+
+ await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+ await session.clock.advance(Hooks.RETRY_DELAY_MS)
+
+ expect(session.posts.map(post => post.init?.body)).toEqual([
+ session.posts[0]?.init?.body,
+ session.posts[0]?.init?.body,
+ ])
+
+ expect(session.lines.at(-1)).toBe('telemetry: sent 1 row(s)')
+ },
+ )
+
+ test(
+ 'a client error is not retried',
+ { plugins: [Fixtures.recording] },
+ async ($, on) => {
+ mock.env(on, Fixtures.SENDING_ENV)
+
+ const session = Fixtures.firstPartySession(on, {
+ answers: [Fixtures.REJECTED],
+ })
+
+ await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+ await session.clock.advance(Hooks.RETRY_DELAY_MS)
+
+ expect(session.posts).toHaveLength(1)
+
+ expect(session.lines.at(-1)).toBe(
+ 'telemetry: 1 row(s) not sent: the ingest answered 400',
+ )
},
)
test(
- 'free text and a malformed entry are refused, nothing sent',
+ 'free text and a malformed entry are refused, nothing queued',
{ plugins: [Fixtures.recording] },
async ($, on) => {
- mock.env(on, {})
+ mock.env(on, Fixtures.SENDING_ENV)
- const posts = Fixtures.firstPartySession(on)
+ const session = Fixtures.firstPartySession(on)
const refusalFor = async (entry: unknown) =>
(
@@ -286,24 +451,23 @@ describe('register', () => {
await refusalFor({ event: 'x', props: { 'a path': 1 } }),
).toEndWith('$.telemetry.log: props: every key is a snake_case token')
- expect(await refusalFor('x')).toEndWith(
- '$.telemetry.log: takes one entry, { event, props? }',
- )
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
- expect(posts).toEqual([])
+ expect(session.posts).toEqual([])
},
)
test(
- 'a number that is not finite is refused, nothing sent',
+ 'a number that is not finite is refused, nothing queued',
{
plugins: [
{
name: 'counting',
+ tier: 'builtin',
register(on) {
on('command.run', { command: 'count' }, $ =>
$.telemetry.log({ event: 'x', props: { n: Number.NaN } }).then(
- () => ({ text: 'sent' }),
+ () => ({ text: 'queued' }),
(error: unknown) => ({ text: String(error) }),
),
)
@@ -312,9 +476,9 @@ describe('register', () => {
],
},
async ($, on) => {
- mock.env(on, {})
+ mock.env(on, Fixtures.SENDING_ENV)
- const posts = Fixtures.firstPartySession(on)
+ const session = Fixtures.firstPartySession(on)
const { text } = await $.command.run({
command: 'count',
@@ -323,47 +487,215 @@ describe('register', () => {
presentation: Fixtures.FULLSCREEN,
})
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+
expect(text).toEndWith('$.telemetry.log: props.n: a number is finite')
- expect(posts).toEqual([])
+ expect(session.posts).toEqual([])
},
)
test(
- 'a failed authorize is not memoized; a retry sends',
+ 'the config, the machine and the variables are read once a session',
{ plugins: [Fixtures.recording] },
async ($, on) => {
- const posts: Args<'http.fetch'>[] = []
+ mock.env(on, Fixtures.SENDING_ENV)
- let authorizations = 0
+ const session = Fixtures.firstPartySession(on)
- mock.env(on, {})
- on('session.id', () => ({ value: 'the-session' }))
- on('session.model', () => ({ value: 'the-model' }))
+ await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+ await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+
+ expect({
+ posts: session.posts.length,
+ configReads: session.reads.filter(path => path === Fixtures.CONFIG_PATH)
+ .length,
+ runs: session.runs.map(run => run.argv.slice(0, 2)),
+ }).toEqual({ posts: 2, configReads: 1, runs: [['sh', '-c']] })
+ },
+ )
- on('session.authorize', () => {
- authorizations += 1
+ test(
+ 'on Windows the platform is read off the environment and no program runs',
+ { plugins: [Fixtures.recording] },
+ async ($, on) => {
+ mock.env(on, Fixtures.WINDOWS_ENV)
- const isFirstAuthorization = authorizations === 1
+ const session = Fixtures.firstPartySession(on)
- return isFirstAuthorization
- ? { deny: 'transient' }
- : { value: Fixtures.BEARER }
+ await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+
+ expect(Fixtures.rowsOf(session)[0]).toMatchObject({
+ env: {
+ platform: 'win32',
+ platform_raw: 'win32',
+ arch: 'x64',
+ shell: 'cmd',
+ terminal: 'windows-terminal',
+ deployment_environment: 'unknown-win32',
+ },
})
- on('http.fetch', ($, e) => {
- posts.push(e)
+ expect(session.runs).toEqual([])
+ },
+ )
- return { value: Fixtures.ACCEPTED }
+ test(
+ 'on Linux the distribution, kernel, WSL and EC2 come from their files',
+ { plugins: [Fixtures.recording] },
+ async ($, on) => {
+ mock.env(on, { ...Fixtures.SENDING_ENV, WSL_DISTRO_NAME: 'Ubuntu' })
+
+ const session = Fixtures.firstPartySession(on, {
+ probeOutput: Fixtures.LINUX_PROBED,
+ files: Fixtures.LINUX_FILES,
+ existing: ['/.dockerenv'],
})
- const first = await $.command.run(Fixtures.record({ event: 'x' }))
- const postsAfterFirst = posts.length
- const second = await $.command.run(Fixtures.record({ event: 'x' }))
+ await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+
+ expect(Fixtures.rowsOf(session)[0]).toMatchObject({
+ env: {
+ platform: 'linux',
+ platform_raw: 'linux',
+ arch: 'x64',
+ terminal: 'ghostty',
+ package_managers: 'npm',
+ runtimes: 'node',
+ linux_distro_id: 'ubuntu',
+ linux_distro_version: '24.04',
+ linux_kernel: '6.6.87.2-microsoft-standard-WSL2',
+ wsl_version: '2',
+ deployment_environment: 'aws-ec2',
+ },
+ })
+ },
+ )
- expect(first.text).toContain('transient')
- expect(postsAfterFirst).toBe(0)
- expect(second.text).toBe('sent')
- expect(posts).toHaveLength(1)
+ test(
+ 'in a GitHub Actions run the client and the workflow ids ride along',
+ { plugins: [Fixtures.recording] },
+ async ($, on) => {
+ mock.env(on, Fixtures.GITHUB_ACTION_ENV)
+
+ const session = Fixtures.firstPartySession(on)
+
+ await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+
+ expect(Fixtures.rowsOf(session)[0]).toMatchObject({
+ client_type: 'github-action',
+ entrypoint: 'claude-code-github-action',
+ env: {
+ is_ci: true,
+ is_github_action: true,
+ is_claude_code_action: true,
+ deployment_environment: 'github-actions',
+ github_event_name: 'pull_request',
+ github_actions_runner_os: 'Linux',
+ github_actions_runner_environment: 'github-hosted',
+ github_action_ref: 'v1',
+ github_actions_metadata: {
+ actor_id: '11',
+ repository_id: '22',
+ repository_owner_id: '33',
+ },
+ },
+ })
+ },
+ )
+
+ test(
+ 'a failed authorize is not held against the next batch',
+ { plugins: [Fixtures.recording] },
+ async ($, on) => {
+ mock.env(on, Fixtures.SENDING_ENV)
+
+ const session = Fixtures.firstPartySession(on, {
+ authorizations: ['refused', Fixtures.BEARER],
+ })
+
+ await $.command.run(Fixtures.record({ event: 'x' }))
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+
+ const postsAfterFirst = session.posts.length
+
+ await $.command.run(Fixtures.record({ event: 'x' }))
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+
+ expect({ postsAfterFirst, posts: session.posts.length }).toEqual({
+ postsAfterFirst: 0,
+ posts: 1,
+ })
+
+ expect(session.lines[0]).toContain('the credential store is locked')
+ },
+ )
+
+ test(
+ 'a plugin a person installed is refused, and its own hook carries on',
+ { plugins: [Fixtures.visiting] },
+ async ($, on) => {
+ mock.env(on, Fixtures.SENDING_ENV)
+
+ const session = Fixtures.firstPartySession(on)
+
+ const { text } = await $.command.run(
+ Fixtures.typed('visit', Fixtures.surveyAnswer()),
+ )
+
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+
+ expect({ text, posts: session.posts }).toEqual({
+ text: `HooksError: visiting: $.telemetry.log: ${Hooks.REFUSED.deny}`,
+ posts: [],
+ })
},
)
+
+ test(
+ 'a plugin an administrator prepended is refused too',
+ { plugins: [Fixtures.managing] },
+ async ($, on) => {
+ mock.env(on, Fixtures.SENDING_ENV)
+
+ const session = Fixtures.firstPartySession(on)
+
+ const { text } = await $.command.run(
+ Fixtures.typed('manage', { feature: 'learn_page', kind: 'ok' }),
+ )
+
+ await session.clock.advance(Hooks.BATCH_WINDOW_MS)
+
+ expect({ text, posts: session.posts }).toEqual({
+ text: `HooksError: managing: $.telemetry.mark: ${Hooks.REFUSED.deny}`,
+ posts: [],
+ })
+ },
+ )
+
+ test('the gate serves built-ins and core, throws on no origin', () => {
+ expect(tiers.map(tier => Hooks.served({}, Fixtures.nextOf(tier)))).toEqual([
+ 'served',
+ 'served',
+ Hooks.REFUSED,
+ Hooks.REFUSED,
+ Hooks.REFUSED,
+ ])
+
+ expect(() => Hooks.served({}, Fixtures.nextOf(undefined))).toThrow(
+ '$.telemetry: the call names no origin',
+ )
+ })
+
+ test('a gate that threw refuses; a refusal from beneath passes up', () => {
+ expect(Hooks.caught({}, Fixtures.failingNext(false))).toEqual(Hooks.REFUSED)
+
+ expect(() => Hooks.caught({}, Fixtures.failingNext(true))).toThrow(
+ 'beneath refused the entry',
+ )
+ })
})
diff --git a/mods/telemetry/types/index.d.ts b/mods/telemetry/types/index.d.ts
index 6527f970..0e7b8564 100644
--- a/mods/telemetry/types/index.d.ts
+++ b/mods/telemetry/types/index.d.ts
@@ -10,21 +10,22 @@
*/
/**
- * A plugin's analytics, sent one event at a time through `$.telemetry`.
+ * A plugin's analytics, queued through `$.telemetry` and sent in batches.
*
- * Internal builds alone: the telemetry mod adds the noun in the
- * `engine.create` fold, so a plugin on an external build, or one where the
- * mod is off, finds no `$.telemetry` and its call throws.
+ * The telemetry mod adds the noun in the `engine.create` fold wherever the
+ * CLI seats it, which is every build whose own analytics are on, and serves
+ * the plugins built into the CLI alone: a call from an installed plugin
+ * rejects. Where the mod is off or absent there is no `$.telemetry`.
*/
export type Telemetry = {
/**
- * Sends one event, `tengu_plugin_<event>`, as one first-party row;
- * resolves once the ingest accepted it.
+ * Queues one event, `tengu_plugin_<event>`, as one first-party row, sent
+ * with the next batch; resolves once queued, rejects a malformed entry.
*
* The calling mod names itself in `event`; one already named `tengu_…` is
* sent as named. A value is a finite number, a boolean or a
* TelemetryChoice; free text is refused. One input, as every op on `$`
- * takes.
+ * takes. Whether a batch went out is a line in the debug log.
*
* @param entry the event's name, a snake_case token, and its properties by
* snake_case key
@@ -41,7 +42,8 @@ export type Telemetry = {
/**
* Marks one use of a feature as the CLI's own feature events do, one
- * `tengu_feature_<kind>` row; resolves once the ingest accepted it.
+ * `tengu_feature_<kind>` row queued for the next batch; resolves once
+ * queued, rejects a malformed entry.
*
* The row carries `feature_name`, `error_code` on sad or bad (`reason`,
* required there and refused on ok) and the entry's `props`, checked as
@@ -108,8 +110,8 @@ export type TelemetryChoice = { value: string; of: readonly string[] }
declare module 'claude-code' {
interface EngineInterface {
/**
- * A plugin's analytics, one first-party row per call; present only where
- * the telemetry mod is seated (internal builds), absent everywhere else.
+ * A built-in plugin's analytics, first-party rows sent in batches;
+ * present where the telemetry mod is seated, refused to installed plugins.
*/
telemetry: Telemetry
}