@osfactory/otel-hook 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1020 -0
  3. package/dist/adapter-DIgRACtL.d.ts +303 -0
  4. package/dist/cli.js +12607 -0
  5. package/dist/cli.js.map +1 -0
  6. package/dist/config.d.ts +233 -0
  7. package/dist/config.js +996 -0
  8. package/dist/config.js.map +1 -0
  9. package/dist/content-CoB7aNP1.d.ts +118 -0
  10. package/dist/diagnostics.d.ts +58 -0
  11. package/dist/diagnostics.js +46 -0
  12. package/dist/diagnostics.js.map +1 -0
  13. package/dist/errors.d.ts +91 -0
  14. package/dist/errors.js +322 -0
  15. package/dist/errors.js.map +1 -0
  16. package/dist/events-VxBnDFaO.d.ts +2044 -0
  17. package/dist/filesystem-store-J8jjDMTh.d.ts +65 -0
  18. package/dist/hook-CGpo-vks.d.ts +292 -0
  19. package/dist/identity-BrVBs901.d.ts +227 -0
  20. package/dist/index.d.ts +44 -0
  21. package/dist/index.js +11798 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/install.d.ts +1021 -0
  24. package/dist/install.js +3271 -0
  25. package/dist/install.js.map +1 -0
  26. package/dist/integration.d.ts +303 -0
  27. package/dist/integration.js +5942 -0
  28. package/dist/integration.js.map +1 -0
  29. package/dist/keys-Dej5bN3L.d.ts +7 -0
  30. package/dist/lifecycle.d.ts +428 -0
  31. package/dist/lifecycle.js +1077 -0
  32. package/dist/lifecycle.js.map +1 -0
  33. package/dist/memory-DXVBc8V9.d.ts +94 -0
  34. package/dist/model.d.ts +45 -0
  35. package/dist/model.js +1023 -0
  36. package/dist/model.js.map +1 -0
  37. package/dist/otlp-log-sink-CeIFDDpn.d.ts +457 -0
  38. package/dist/payload-CHr53E_v.d.ts +201 -0
  39. package/dist/policy-D1CrlYn3.d.ts +73 -0
  40. package/dist/ports-Q8x0ODhs.d.ts +200 -0
  41. package/dist/primitives-CJ8-rn-f.d.ts +75 -0
  42. package/dist/privacy.d.ts +51 -0
  43. package/dist/privacy.js +633 -0
  44. package/dist/privacy.js.map +1 -0
  45. package/dist/providers.d.ts +257 -0
  46. package/dist/providers.js +4398 -0
  47. package/dist/providers.js.map +1 -0
  48. package/dist/registry-BzYmC9OC.d.ts +49 -0
  49. package/dist/runtime.d.ts +32 -0
  50. package/dist/runtime.js +2907 -0
  51. package/dist/runtime.js.map +1 -0
  52. package/dist/schema-Cn0-xz8L.d.ts +224 -0
  53. package/dist/semconv-Baoz-0OI.d.ts +188 -0
  54. package/dist/service-j4jEO6cZ.d.ts +68 -0
  55. package/dist/state.d.ts +36 -0
  56. package/dist/state.js +710 -0
  57. package/dist/state.js.map +1 -0
  58. package/dist/taxonomy-DwhTtuWd.d.ts +87 -0
  59. package/dist/telemetry.d.ts +77 -0
  60. package/dist/telemetry.js +2294 -0
  61. package/dist/telemetry.js.map +1 -0
  62. package/dist/testing.d.ts +155 -0
  63. package/dist/testing.js +6513 -0
  64. package/dist/testing.js.map +1 -0
  65. package/package.json +124 -0
package/README.md ADDED
@@ -0,0 +1,1020 @@
1
+ # @osfactory/otel-hook
2
+
3
+ Provider-neutral coding-agent hooks for OpenTelemetry.
4
+
5
+ `otel-hook` is a CLI you register as a hook in a coding agent, and a TypeScript
6
+ library you can embed. Provider adapters normalize each agent's hook protocol
7
+ into a versioned canonical event model, which is then screened for privacy,
8
+ accounted for usage, and exported over OTLP.
9
+
10
+ ## Status
11
+
12
+ **Published as `0.1.0`.** Install with `npm install -g @osfactory/otel-hook` or
13
+ `npx @osfactory/otel-hook`. See [docs/release-checklist.md](docs/release-checklist.md)
14
+ and [Known limitations](#known-limitations) for what this release intentionally
15
+ does and does not claim.
16
+
17
+ ## Principles
18
+
19
+ - Independent of any telemetry consumer
20
+ - Explicit, immutable per-invocation identity; no ambient session state
21
+ - Provider-specific protocol adapters behind one contract
22
+ - Fail-open hook execution, fail-closed attribution
23
+ - No conversation or tool content by default
24
+ - Replay-safe usage accounting, no daemon
25
+
26
+ ## Supported providers
27
+
28
+ `otel-hook providers` prints this table for your installed version, with the full
29
+ capability matrix. Adapter behaviour is *declared* rather than inferred, because
30
+ "this provider reports no cached tokens" and "this session used no cache" are
31
+ indistinguishable in the data.
32
+
33
+ | Provider id | Agent | Maturity | stdout protocol | Usage temporality | Registration |
34
+ | ------------- | ------------------ | ------------ | --------------- | ----------------- | ---------------------------- |
35
+ | `claude-code` | Claude Code | stable | silent | delta | `setup` (global and project) |
36
+ | `codex` | OpenAI Codex CLI | stable | silent | cumulative[^1] | `setup` (global and project) |
37
+ | `cursor` | Cursor | stable | provider JSON | delta | `setup` (global and project) |
38
+ | `gemini-cli` | Gemini CLI | stable | silent | cumulative | `setup` (global and project) |
39
+ | `antigravity` | Google Antigravity | experimental | silent | delta | `setup --settings-file` |
40
+
41
+ [^1]: Codex's counters are cumulative over the **whole session**, not per turn:
42
+ every usage-bearing hook stamps the rollout's running `total_token_usage`.
43
+ Deltas are therefore diffed against the session's previous snapshot rather
44
+ than per `turn_id`, which is what keeps a three-turn session from billing its
45
+ first turn three times. `otel-hook providers` prints this as
46
+ `usage temporality cumulative (series: session-lifetime)`; see
47
+ [docs/usage-semantics.md](docs/usage-semantics.md#which-series-a-cumulative-report-continues).
48
+
49
+ `antigravity` is registered but marked `experimental`: parts of its field and
50
+ lifecycle mapping are reconstructions pending confirmation against real captures.
51
+ Selecting it logs a warning to stderr, `providers` reports its open promotion
52
+ gates, and `--no-experimental` excludes it entirely.
53
+
54
+ ## CLI
55
+
56
+ ```bash
57
+ otel-hook run [--provider <id>] [options] # process one hook payload from stdin
58
+ otel-hook doctor [--json] # configuration and delivery health
59
+ otel-hook providers [--json] # adapters and their capabilities
60
+ otel-hook setup --provider <id> [options] # register this hook in a provider's config
61
+ otel-hook diagnose [--json] # report what is registered where
62
+ otel-hook uninstall --provider <id> # remove this hook from a provider's config
63
+ otel-hook --version
64
+ ```
65
+
66
+ ### `run`
67
+
68
+ Reads **exactly one** JSON value from stdin, bounded by `--max-input-bytes`
69
+ (default 1 MiB). Writes to stdout **only** what the selected provider's protocol
70
+ requires — for four of the five providers, nothing at all. Every diagnostic goes
71
+ to stderr as one JSON object per line.
72
+
73
+ **`run` always exits 0.** Unreadable stdin, malformed JSON, an unknown provider,
74
+ an ambiguous detection, conflicting identity, an unreachable collector, an
75
+ unwritable state directory: all become stderr diagnostics
76
+ ([ADR 0004](docs/adr/0004-stdout-and-fail-open.md)). A telemetry hook that can
77
+ fail its host agent is a liability.
78
+
79
+ ```bash
80
+ # Register this as the hook command; the payload arrives on stdin.
81
+ otel-hook run --provider claude-code \
82
+ --endpoint https://collector.example/v1/traces \
83
+ --header "authorization=Bearer $COLLECTOR_TOKEN"
84
+ ```
85
+
86
+ Provider selection:
87
+
88
+ - `--provider <id>` is **preferred and recommended.** It is the only way to reach
89
+ `exact` detection confidence for a payload with no self-identifying provider
90
+ field, and it makes ambiguity structurally impossible.
91
+ - Without it, auto-detection requires a **unique** recognizer: if more than one
92
+ registered adapter recognizes the payload, the invocation is refused with a
93
+ diagnostic naming the candidates. There is no default provider and no tie-break
94
+ by registration order.
95
+
96
+ This matters in practice. Claude Code, the Codex CLI, and the Gemini CLI share a
97
+ PascalCase hook vocabulary (`SessionStart`, `PreToolUse`, `PostToolUse`, `Stop`,
98
+ `PreCompact`, `SubagentStop`). Measured against this repository's own fixtures, a
99
+ real Claude Code `SessionStart` payload is claimed by the Gemini adapter at
100
+ `exact` and by the Codex adapter at `strong`. Confidence is self-reported per
101
+ adapter and is *not* comparable across providers, so taking the highest score
102
+ would file one agent's telemetry under another's id. Cursor payloads, whose
103
+ `hook_event_name` values are camelCase (`preToolUse`, `beforeSubmitPrompt`), and
104
+ Antigravity's camelCase envelope both auto-detect cleanly.
105
+
106
+ Invocation identity — immutable, per invocation, never from the environment
107
+ ([ADR 0001](docs/adr/0001-invocation-identity-isolation.md)):
108
+
109
+ ```
110
+ --session-id --invocation-id --parent-invocation-id --root-session-id
111
+ --agent-instance-id --identity-file <path>
112
+ ```
113
+
114
+ `--identity-file` accepts a JSON object with any of those fields plus `startedAt`
115
+ and a `workspace` identity, validated strictly. Flags and the file are *separate*
116
+ claims at equal confidence, so if they disagree — or if either disagrees with the
117
+ provider payload — the result is an identity **conflict**: attribution is declined
118
+ and nothing is exported, rather than one assertion silently winning.
119
+
120
+ No environment variable sets identity. The `OTEL_HOOK_*` variables and the
121
+ standard `OTEL_EXPORTER_OTLP_ENDPOINT`, `OTEL_SERVICE_NAME`, and
122
+ `OTEL_RESOURCE_ATTRIBUTES` configure the exporter, privacy, detection, and
123
+ logging only.
124
+
125
+ Exporter and runtime policy (never identity):
126
+
127
+ ```
128
+ --config-file --endpoint --protocol --service-name --service-namespace
129
+ --timeout-ms --no-export --content-mode --log-level --header name=value
130
+ --resource-attr key=value --state-dir --installation-id --no-spool
131
+ --flush-timeout-ms --max-input-bytes --attr key=value --transport
132
+ ```
133
+
134
+ Only header *names* enter the resolved-config snapshot that is logged and
135
+ reported; the values go straight to the exporter, so a snapshot cannot leak a
136
+ credential.
137
+
138
+ `--resource-attr` and `--attr` are different channels and never mix.
139
+ `--resource-attr` sets an OTLP **resource** attribute — a fact about this
140
+ deployment, attached to every exported span. `--attr` sets an opaque
141
+ **consumer** attribute carried on one invocation's identity. See
142
+ [Resource attributes](#resource-attributes).
143
+
144
+ Delivery deduplication suppresses a redelivered callback across process restarts,
145
+ because the identity it keys on is recomputed from durable inputs rather than
146
+ remembered in memory. Two identities can carry it.
147
+
148
+ **It is at-least-once, not exactly-once, and cannot be made exactly-once.** The
149
+ collector is a separate system: a batch is accepted over HTTP and the claim is then
150
+ committed to local state, and there is no transaction spanning those two. A process
151
+ killed in between leaves a callback the collector has *taken* and local state still
152
+ records as unclaimed, so a redelivery re-exports it. The re-export is **labelled,
153
+ not silent**: it lands in the same trace and carries
154
+ `otelhook.span.orphan="already-closed"`, because the span correlator finds the scope
155
+ already closed and refuses to republish under the accepted span's id. That is the
156
+ recovery this design offers instead of a guarantee it cannot keep. See
157
+ [Crash semantics](#crash-semantics-and-what-deduplication-does-not-cover).
158
+
159
+ A host-supplied delivery id, unique by construction because only the host knows
160
+ it:
161
+
162
+ ```bash
163
+ otel-hook run --provider cursor --callback-id "$HOST_DELIVERY_ID"
164
+ ```
165
+
166
+ Or, with no flag at all, one normalized from payload fields the selected adapter
167
+ vouches for — a `tool_use_id`, a `turn_id`, a `generation_id`, a
168
+ provider-recorded timestamp:
169
+
170
+ ```bash
171
+ otel-hook run --provider cursor # redelivered tool callbacks dedupe
172
+ otel-hook providers --json # per-adapter "deliveryIdentifier"
173
+ ```
174
+
175
+ Either way, a redelivery suppresses duplicate *telemetry* while still producing
176
+ the provider's protocol response, because a redelivered callback still expects
177
+ one. Deduplication is scoped by provider, installation, and the provider's own
178
+ session, and the pair that reaches state is a digest — a provider's session id or
179
+ tool-call id is never written to disk or logged as a side effect of deduplicating
180
+ on it. Adapters report identifier-shaped *components*, never content: prose and
181
+ filesystem paths cannot satisfy the contract's component guard, so a delivery id
182
+ derived from a prompt or a home directory is a rejected claim rather than a
183
+ privacy incident.
184
+
185
+ No adapter identifies *every* callback. Coverage is declared per provider
186
+ (`deliveryIdentifier: none | partial | all`) rather than left to be inferred, and
187
+ `--require-callback-id` reports each callback that could not be deduplicated —
188
+ naming the **callback**, not only the provider, because the provider id and the
189
+ capability are identical for every callback of that provider and so identify
190
+ nothing an operator can act on:
191
+
192
+ ```bash
193
+ otel-hook run --provider claude-code --require-callback-id
194
+ # stderr: delivery-identifier-unavailable "provider.delivery_identifier":"partial"
195
+ # "delivery.reason":"callback-not-identifiable"
196
+ # "delivery.source_event_name":"Stop"
197
+ # prompt_id is not a delivery identity here: Claude Code can fire Stop
198
+ # more than once per prompt when a hook continues the turn
199
+ ```
200
+
201
+ The explanation comes from the adapter's own gap table, so it names the protocol
202
+ field whose absence is the gap — which is the one thing a host or a provider owner
203
+ can actually change. Gap reasons are validated on the way out like any other
204
+ adapter output: a reason carrying a filesystem path or a newline is dropped rather
205
+ than printed.
206
+
207
+ A suppressed redelivery is parsed but changes nothing: no export, no advance of
208
+ the session sequence counter, and no rewrite of a cumulative usage baseline. Both
209
+ of those are canonical state — the sequence seeds every event's derived id — so
210
+ advancing them for a callback that is not a new observation would renumber the
211
+ next genuine event and change its id.
212
+
213
+ A claim is committed only once the batch is somewhere durable, and the test is
214
+ **any** rather than **all** — `outcome.ingest.durability`:
215
+
216
+ | Fate | Meaning | Claim |
217
+ | --- | --- | --- |
218
+ | `nothing-to-deliver` | Suppressed, or no events to export | committed |
219
+ | `delivered` | Every span reached the collector or the spool | committed |
220
+ | `partial` | Some reached it, some did not | committed, `delivery.partialLoss` set |
221
+ | `lost` | Nothing reached it | released, `delivery.retryable` set |
222
+
223
+ A successful spool enqueue counts as delivered, because a later invocation drains
224
+ it. `lost` releases the claim, so redelivering retries instead of being suppressed
225
+ — committing there would be an at-most-*zero* guarantee: the telemetry gone and
226
+ the claim saying never to try again.
227
+
228
+ `partial` is **terminal**: it is not retried. Retrying would re-export every span
229
+ the collector already accepted, turning a reported loss into a silent double-count,
230
+ and a duplicated span corrupts a total nobody can reconstruct while a reported loss
231
+ is a number somebody can act on.
232
+
233
+ Usage accounting is part of that commit, not of parsing. Deltas are derived and the
234
+ cumulative baseline advanced **after** delivery is known and only for a committed
235
+ callback, so a lost callback leaves the baseline exactly where its retry needs it —
236
+ otherwise the retry would diff the advanced snapshot against itself and report zero.
237
+ Sequence numbers are the one thing reserved up front, so a failed callback leaves a
238
+ harmless gap in the numbering rather than a reused number.
239
+
240
+ Rollup application is **idempotent by delivery identity**. It is the one piece of
241
+ accounting outside `ingest`'s own transaction — the accumulator takes the same
242
+ non-reentrant session lock, so it runs in a second critical section — which makes it
243
+ the only place a reclaimed or superseded delivery could apply its numbers twice.
244
+ That matters most for a delta-reporting provider: a delta needs no baseline, so a
245
+ retry has nothing to diff against and would simply add the same tokens again. The
246
+ marker naming the last delivery folded in rides *inside* the rollup record, so the
247
+ check and the write are one atomic operation and no multi-key pseudo-transaction is
248
+ invented. Only the most recent delivery per rollup key is recognizable, which is the
249
+ retry window and nothing beyond it.
250
+
251
+ `staleClaimMillis` — how long an uncommitted claim is respected before a later
252
+ delivery may assume the holder died — is raised automatically to cover this
253
+ installation's own worst-case work (state lock wait + every permitted export
254
+ attempt + the bounded flush). A window shorter than that is not a smaller
255
+ guarantee but the opposite of one: a peer would declare a *live* process abandoned
256
+ and export the same callback twice. Raising it is logged.
257
+
258
+ Retention defers to the same window. `deliveryRetentionMillis` expires *handled*
259
+ callbacks, but the sweep will not drop an uncommitted claim until it is older than
260
+ the effective `staleClaimMillis` too —
261
+ otherwise tightening retention would delete a claim while its holder is still
262
+ exporting, and the concurrent redelivery would see a *fresh* callback. Records kept
263
+ back for that reason are reported as `cleanup.dedup.retainedInFlight`, and a
264
+ retention shorter than the stale window is logged. An abandoned claim is still
265
+ reclaimed once past both, so a crash costs a delayed export rather than a permanent
266
+ one.
267
+
268
+ It stays fail-open: an unidentifiable callback is still exported and still
269
+ accounted. Losing a real observation is unrecoverable, exporting a possible
270
+ duplicate is not. `--no-derive-callback-id` opts out of derivation entirely and
271
+ deduplicates only against `--callback-id`. See
272
+ [Known limitations](#known-limitations) for what each adapter cannot identify.
273
+
274
+ ### `doctor`
275
+
276
+ ```bash
277
+ otel-hook doctor --json
278
+ ```
279
+
280
+ Reports the version, an attribute-safe configuration snapshot, a real
281
+ write/read/delete probe of the state directory, spool depth, exporter
282
+ configuration, privacy mode, and the adapter count. Exits 1 when any check fails,
283
+ so CI can gate on it. Every check is local: `doctor` never sends a span.
284
+
285
+ ### `setup`, `diagnose`, `uninstall`
286
+
287
+ ```bash
288
+ otel-hook setup --provider claude-code --dry-run # exactly what would be written
289
+ otel-hook setup --provider claude-code # project scope: .claude/settings.json
290
+ otel-hook setup --provider codex --scope global # ~/.codex/hooks.json
291
+ otel-hook diagnose --json # what is registered, in both scopes
292
+ otel-hook uninstall --provider claude-code
293
+ ```
294
+
295
+ `setup` writes into a configuration file this project does not own, so it is
296
+ conservative by construction:
297
+
298
+ - **Idempotent.** Re-running with the same options rewrites nothing — byte for
299
+ byte, not merely semantically.
300
+ - **Upgrade-safe.** A registration written by an *earlier* version (recognized by
301
+ the `--managed-marker` substring, `otel-hook` by default) is rewritten in place
302
+ rather than duplicated, and pre-existing duplicates are collapsed. Two
303
+ registrations of one hook means two spans per event.
304
+ - **Reversible.** `uninstall` removes exactly what `setup` added, including the
305
+ structure it created, so a document that had no `hooks` key before has none
306
+ after. Asserted byte for byte in `tests/install/lifecycle.test.ts`.
307
+ - **Non-destructive.** Other tools' hooks, matchers a developer narrowed by hand,
308
+ unrelated settings keys, and the file's own indentation, line endings, and
309
+ trailing newline all survive. A document that does not parse, or whose `hooks`
310
+ value is not the documented shape, is **reported and left untouched** — never
311
+ overwritten to make the installer succeed.
312
+ - **Atomic and locked.** Writes land through a temp file plus `rename` (atomic on
313
+ POSIX and on Windows), and the read-merge-write sequence holds a lock file
314
+ beside the target, so two concurrent setups cannot lose each other's work. A
315
+ lock left behind by a crashed process is reclaimed after 30s.
316
+ - **Read-only when it says so.** `diagnose` and `--dry-run` take no lock and
317
+ create no directories; `--dry-run` prints the exact bytes a real run would
318
+ write.
319
+
320
+ `--scope` is `project` by default for `setup` and `uninstall` (writing into a home
321
+ directory is the surprising choice) and `all` for `diagnose`. Only events the
322
+ adapter turns into telemetry are registered; `--event` overrides that.
323
+
324
+ `diagnose` exits 1 on anything an operator should act on — a partial
325
+ registration, duplicate entries, an unparseable document — so CI can gate on
326
+ `otel-hook diagnose --json`.
327
+
328
+ Which providers this works for, and why not the others, is recorded in
329
+ [docs/registration-evidence.md](docs/registration-evidence.md).
330
+
331
+ ## Library
332
+
333
+ ```ts
334
+ import { createHookRuntime } from "@osfactory/otel-hook/integration";
335
+ import { createDefaultProviderRegistry } from "@osfactory/otel-hook/providers";
336
+ import { DEFAULT_CONFIG } from "@osfactory/otel-hook/config";
337
+
338
+ const runtime = createHookRuntime({
339
+ config: { ...DEFAULT_CONFIG, exporter: { ...DEFAULT_CONFIG.exporter, endpoint } },
340
+ registry: createDefaultProviderRegistry({ includeExperimental: false }),
341
+ stateRootDir: "/var/lib/otel-hook",
342
+ installationId: "prod",
343
+ providerNamespace: "claude-code",
344
+ });
345
+
346
+ const outcome = await runtime.process({
347
+ payload,
348
+ transport: "hook-stdin",
349
+ providerHint: "claude-code",
350
+ // Optional. Omit it and the adapter's own replay-stable identifier is used
351
+ // where the payload carries one.
352
+ delivery: { callbackId: hostDeliveryId },
353
+ });
354
+
355
+ // Bounded: returns within flushTimeoutMillis even if the collector hangs.
356
+ await runtime.shutdown();
357
+ ```
358
+
359
+ `process` never throws and `outcome.ingest.ok` is always `true`; inspect
360
+ `attribution`, `diagnostics`, and `usageRollups` to learn what happened, and
361
+ `outcome.delivery` to learn whether deduplication actually applied
362
+ (`deduplicated`, `origin`, `outcome`, and — when it did not — `reason` and the
363
+ adapter's declared `capability`). For the
364
+ lower-level orchestrator without the filesystem and lifecycle wiring, use
365
+ `createOtelHook` from `@osfactory/otel-hook/runtime`.
366
+
367
+ ### Entry points
368
+
369
+ | Import | Contents |
370
+ | ---------------------------------- | ----------------------------------------------------------------------------- |
371
+ | `@osfactory/otel-hook` | Everything below, re-exported |
372
+ | `@osfactory/otel-hook/model` | Canonical events, identity, usage, content facts, extensions |
373
+ | `@osfactory/otel-hook/providers` | Adapter contract, event factory, registry, the five adapters, default factory |
374
+ | `@osfactory/otel-hook/privacy` | Privacy policy, privacy service, workspace derivation |
375
+ | `@osfactory/otel-hook/config` | Typed configuration, precedence, environment parsing |
376
+ | `@osfactory/otel-hook/errors` | Error taxonomy, error info, attribution outcomes |
377
+ | `@osfactory/otel-hook/runtime` | `OtelHook`, ports, clock, ids, logger, in-memory implementations |
378
+ | `@osfactory/otel-hook/lifecycle` | Span correlator, callback deduplicator, usage accumulator, janitor |
379
+ | `@osfactory/otel-hook/state` | Filesystem and bounded-memory state stores, session locking |
380
+ | `@osfactory/otel-hook/telemetry` | OTLP trace and log sinks, durable spools, canonical-event-to-span and -to-log mappings |
381
+ | `@osfactory/otel-hook/diagnostics` | Delivery health tracking and summaries |
382
+ | `@osfactory/otel-hook/integration` | `createHookRuntime`: state + lifecycle + OTLP wired for short-lived hooks |
383
+ | `@osfactory/otel-hook/install` | Pure hook-registration planners, plus the locked/atomic apply lifecycle |
384
+ | `@osfactory/otel-hook/testing` | Test doubles, harness, synthetic reference adapter |
385
+
386
+ The subpaths are curated, not raw module barrels: on-disk key derivation, the
387
+ in-process lock, and span re-assembly are omitted so the state layout and the
388
+ canonical-event boundary stay free to change. A test asserts they stay out.
389
+
390
+ ## Registration planners
391
+
392
+ `@osfactory/otel-hook/install` is two layers. The **planners** are pure: they take
393
+ the parsed contents of a provider's configuration document and return the
394
+ document to write back, plus what changed. Reading and writing the file is the
395
+ caller's job ([ADR 0003](docs/adr/0003-provider-adapter-boundary.md)), and
396
+ re-running with the same options is a no-op.
397
+
398
+ ```ts
399
+ import { planProviderRegistration } from "@osfactory/otel-hook/install";
400
+
401
+ const plan = planProviderRegistration({
402
+ providerId: "claude-code",
403
+ existing: JSON.parse(await readFile(settingsPath, "utf8")),
404
+ options: { command: "otel-hook run --provider claude-code" },
405
+ });
406
+ if (plan.status === "planned" && plan.changed) {
407
+ await writeFile(settingsPath, `${JSON.stringify(plan.document, null, 2)}\n`);
408
+ }
409
+ ```
410
+
411
+ A plan can also come back `conflict` (the document is not the shape the provider
412
+ documents — do not write), `invalid` (the options cannot produce a registration),
413
+ or `unsupported`.
414
+
415
+ The **lifecycle** layer — `runRegistrationLifecycle`, what the CLI's `setup`,
416
+ `diagnose`, and `uninstall` call — does the file handling described above:
417
+ locking, formatting preservation, atomic writes, and refusing rather than
418
+ clobbering.
419
+
420
+ Planners exist for `claude-code`, `codex`, `cursor`, `gemini-cli`, and
421
+ `antigravity`. Cursor's `hooks.json` is the one *flat* document among them —
422
+ `{ version: 1, hooks: { "<event>": [{ command }] } }` — and its default event set
423
+ deliberately omits `beforeShellExecution`/`afterShellExecution` and the MCP pair,
424
+ because one shell call fires those *and* `preToolUse`/`postToolUse`, and only the
425
+ generic pair carries a `tool_use_id` to correlate the two edges. `antigravity` is
426
+ the remaining gap, and it is a *location* gap rather than a shape one: `setup`
427
+ requires `--settings-file`. `PROVIDER_REGISTRATION_SUPPORT` carries the reason and
428
+ the `evidenceBlocker` per provider;
429
+ [docs/registration-evidence.md](docs/registration-evidence.md) is the long form.
430
+
431
+ ## Canonical model
432
+
433
+ Every event carries `schemaVersion` (`CANONICAL_SCHEMA_VERSION`), identity,
434
+ provenance, workspace, a per-session `sequence`, and a timestamp:
435
+
436
+ ```text
437
+ session.start session.end
438
+ prompt.submitted
439
+ generation.start generation.end
440
+ tool.start tool.end
441
+ subagent.start subagent.end
442
+ compaction.performed
443
+ error.raised
444
+ ```
445
+
446
+ Canonical event types are provider-neutral; the provider's own name for an event
447
+ is preserved separately in `provenance.sourceEventName` and never translated into
448
+ another provider's vocabulary. Usage is explicit about inclusive totals, subsets,
449
+ cache-creation accounting, provider totals, and delta/cumulative temporality —
450
+ see [docs/usage-semantics.md](docs/usage-semantics.md).
451
+
452
+ ## Spans and cross-process correlation
453
+
454
+ A coding-agent hook fires once per lifecycle edge, usually as a separate
455
+ short-lived process for the `*.start` and for the `*.end`. Spans are therefore
456
+ built from *derived* identity rather than in-process context:
457
+
458
+ - `traceId = H(providerId, sessionId)` — one trace per session per provider, so
459
+ an end emitted minutes later joins its start's trace, and two providers that
460
+ reuse a session id never merge.
461
+ - `spanId = H(providerId, sessionId, family, scopeKey)` — stable across
462
+ processes and idempotent under redelivery, so the process that closes a span
463
+ computes the same id the process that opened it would have.
464
+ - Parents are recorded at start time, so an end process that never saw the
465
+ generation id still hangs its tool span in the same place.
466
+
467
+ **One OTLP record per span.** Because the span id is derived from the scope, a
468
+ `*.start` edge and its later `*.end` edge compute the *same* id — and OTLP has no
469
+ notion of updating a span, so exporting on both edges would put two records with
470
+ one identity on the wire, which collectors variously drop, keep the older of, or
471
+ show twice. So a `*.start` with no end in its batch exports **nothing**: it is
472
+ recorded in the state store, and the end edge exports the single completed span
473
+ with a real duration. The two cases where a second record is legitimate get their
474
+ own span id, derived with an extra discriminator rather than colliding:
475
+
476
+ - a second, *distinct* end for a scope already closed
477
+ (`otelhook.span.orphan=already-closed`).
478
+
479
+ The consequence worth knowing: **a span whose end never arrives is never
480
+ exported.** That is standard OpenTelemetry behaviour for a span that never ends,
481
+ and the alternative — inventing an end time — would report a wrong duration
482
+ instead of no duration. The state record expires on the retention window, and the
483
+ sweep counts what it dropped, so the cost is visible rather than silent:
484
+ `lifecycle.expired_open_spans` in the janitor's report and a warning on the log.
485
+
486
+ The end process recovers the start time, duration, parent, and start-only
487
+ attributes (tool kind, requested model, delegation depth, agent name) from the
488
+ state store. Whether that succeeded is always explicit on the span:
489
+
490
+ | Attribute | Values |
491
+ | ------------------------ | ------------------------------------------------------------- |
492
+ | `otelhook.span.paired` | `true` when both edges are known |
493
+ | `otelhook.span.pairing` | `in-batch` \| `cross-process` \| `unpaired` |
494
+ | `otelhook.span.orphan` | `none` \| `missing-start` \| `missing-end` \| `expired-start` \| `already-closed` \| `provider-mismatch` \| `state-incompatible` \| `state-corrupt` \| `state-unavailable` |
495
+
496
+ Correlation is an enrichment, never a precondition: unreadable, locked, or
497
+ absent state costs a span its pairing, never the export. Retention, bounds, and
498
+ what happens when the record shape changes are in
499
+ [docs/state-retention.md](docs/state-retention.md).
500
+
501
+ ## Logs
502
+
503
+ A span reports that a tool call happened and whether it failed. It cannot report
504
+ what was *in* it — span attributes are a flat bounded map, one record per span. A
505
+ conversation turn is a sequence of distinct pieces of content, each with its own
506
+ role, length, and disclosure decision, so there is an optional OTLP logs pipeline
507
+ alongside the traces one.
508
+
509
+ **Off by default.** An installation that upgrades must not silently start sending a
510
+ second stream to a collector whose receivers and quotas were sized for traces:
511
+
512
+ ```bash
513
+ otel-hook run --provider claude-code --endpoint http://localhost:4318/v1/traces --logs
514
+ # or: OTEL_HOOK_LOGS_ENABLED=1
515
+ ```
516
+
517
+ One record per content fact, plus one per event that carries none, keyed by
518
+ `otelhook.log.signal`:
519
+
520
+ ```text
521
+ session prompt response reasoning
522
+ tool shell file-operation mcp delegation
523
+ compaction error
524
+ ```
525
+
526
+ Which signals a provider can populate is *derived* from the `lifecycleEvents` it
527
+ already declares, not maintained as a second list — a stale capability declaration
528
+ is worse than none, because a consumer cannot tell "reports no tool output" from
529
+ "nobody updated it". The mapping is versioned (`LOG_MAPPING_VERSION`, carried on
530
+ every record as `otelhook.log.mapping_version`).
531
+
532
+ Records carry the same identity attributes as spans and the **same derived trace and
533
+ span ids**, so a record lands in its span's trace without either signal knowing about
534
+ the other. Both ids come from the event's own `(providerId, sessionId)`, so two
535
+ sessions in one batch derive two trace ids — cross-session contamination is
536
+ structurally impossible rather than checked for. A record on a `*.start` edge points
537
+ *forward* to the span id the end edge will publish, since that edge exports no span
538
+ at all.
539
+
540
+ **Content is disabled by default, behind three gates.** All three must be open for a
541
+ body to appear:
542
+
543
+ | Gate | Default |
544
+ | --- | --- |
545
+ | `privacy.contentMode` ≠ `omit` | `omit` |
546
+ | `exporter.logs.includeContent` (`--logs-content`) | `false` |
547
+ | `privacy.allowRawContent`, for `raw` only | `false` |
548
+
549
+ `includeContent` is a separate switch because spans carry no content in *any* mode:
550
+ an installation that set `contentMode` to get a hash and a length has never had
551
+ content on the wire, and reusing that setting to also mean "publish prompts" would
552
+ change what an existing configuration discloses without anybody editing it. A
553
+ withheld body says which gate stopped it (`otelhook.content.withheld`:
554
+ `privacy-policy` | `logs-content-disabled` | `raw-not-permitted`) rather than being
555
+ a bare absence. The measurable description — length, byte length, salted hash,
556
+ secrets-redacted count — is present in every mode.
557
+
558
+ Delivery mirrors the trace sink: HTTP/protobuf, bounded batching, retries, bounded
559
+ flush, idempotent shutdown, and a **separate** durable spool at
560
+ `spool-logs`, so a logs outage cannot consume the capacity the primary signal's
561
+ retries need. The endpoint is derived from `--endpoint` (a trailing `/v1/traces`
562
+ becomes `/v1/logs`) unless `--logs-endpoint` states one. Health is reported per
563
+ signal, because a collector with no logs receiver leaves traces perfectly healthy.
564
+
565
+ The full mapping table, attribute vocabulary, bounds, and durability matrix are in
566
+ [docs/canonical-log-mapping.md](docs/canonical-log-mapping.md).
567
+
568
+ ## Privacy
569
+
570
+ Content is omitted by default; only lengths and a stable salted hash are
571
+ recorded. `mask` and `redact` modes exist, and `raw` additionally requires
572
+ `allowRawContent`. `WorkspaceIdentity` has no path field at all, so a filesystem
573
+ path cannot reach an event regardless of content mode. Secret-looking keys are
574
+ replaced recursively at every depth, and depth, string, array, object, and
575
+ per-invocation event counts are bounded
576
+ ([ADR 0005](docs/adr/0005-central-privacy-service.md)).
577
+
578
+ Spans carry no content in any content mode. The only pipeline that can carry it is
579
+ the optional [logs](#logs) one, and only with its own `includeContent` switch also
580
+ set — one policy, one privacy service, two gates.
581
+
582
+ The CLI additionally narrows the environment adapters can observe to an
583
+ allow-list of `OTEL_*` and agent-specific prefixes, minus the OTLP `*_HEADERS`
584
+ variables that carry credentials — a hook inherits the developer's whole
585
+ environment, and the adapter contract would otherwise hand all of it to every
586
+ adapter.
587
+
588
+ ## Writing a provider adapter
589
+
590
+ ```ts
591
+ import {
592
+ createEventFactory,
593
+ providerDetectionSchema,
594
+ SILENT_HOOK_RESPONSE,
595
+ type ProviderAdapter,
596
+ } from "@osfactory/otel-hook/providers";
597
+
598
+ export const createAcmeAdapter = (): ProviderAdapter => ({
599
+ id: asProviderId("acme"),
600
+ version: "1.0.0",
601
+ capabilities: {
602
+ /* declare what the provider actually reports */
603
+ },
604
+
605
+ // Cheap, side-effect free. Return `none` rather than guessing.
606
+ detect: (input) => providerDetectionSchema.parse({ ... }),
607
+
608
+ // Contribute claims; the core arbitrates and may decline attribution.
609
+ identify: (input, context) => [ ... ],
610
+
611
+ // The only place that reads the payload.
612
+ parse: (input, context) => {
613
+ const factory = createEventFactory({
614
+ identity: input.identity,
615
+ sequenceBase: input.sequenceBase,
616
+ context,
617
+ });
618
+ factory.build({ type: "session.start", sessionKind: "interactive" });
619
+ return { status: "parsed", events: factory.events() };
620
+ },
621
+
622
+ hookResponse: () => SILENT_HOOK_RESPONSE,
623
+ });
624
+ ```
625
+
626
+ Rules the core enforces, not just documents:
627
+
628
+ - Raw payloads must not escape `parse`. Extensions and attributes accept only
629
+ primitives, so a nested payload cannot be attached.
630
+ - Content must be described through `context.privacy`. Events whose disclosure
631
+ does not match the resolved policy are dropped with a diagnostic.
632
+ - Sequences must be consecutive from `input.sequenceBase`; `createEventFactory`
633
+ handles this, along with derived, replay-safe event ids.
634
+ - Events must carry the identity the core resolved. Mismatches are dropped.
635
+ - Adapters get no filesystem and no network, and must hold no cross-invocation
636
+ state.
637
+
638
+ Pass the adapter to `createDefaultProviderRegistry({ additional: [...] })` to use
639
+ it alongside the built-ins.
640
+
641
+ ## Testing an adapter
642
+
643
+ ```ts
644
+ import { createTestHook, findDisclosureViolations, batchContains } from "@osfactory/otel-hook/testing";
645
+
646
+ const harness = createTestHook({ adapters: [createAcmeAdapter()] });
647
+ const outcome = await harness.hook.ingest({ payload, transport: "hook-stdin" });
648
+
649
+ expect(outcome.attribution).toBe("attributed");
650
+ expect(findDisclosureViolations(harness.sink.events())).toEqual([]);
651
+ expect(batchContains(harness.sink.events(), "a prompt fragment")).toBe(false);
652
+ ```
653
+
654
+ The harness wires a deterministic clock and ids, an in-memory state store and
655
+ recording sink (both with fault injection), and a recording logger. Nothing reads
656
+ the wall clock, the environment, or the filesystem.
657
+
658
+ ## Configuration
659
+
660
+ Precedence, lowest to highest: `defaults` → `file` → `environment` →
661
+ `inline-override`, merged per leaf field with per-field provenance. An unusable
662
+ layer is rejected rather than partially applied, and the CLI then falls back to
663
+ `DEFAULT_CONFIG` with a diagnostic rather than exiting.
664
+
665
+ ### The logs signal
666
+
667
+ `exporter.logs` is its own sub-object, merged per leaf like everything else, so a
668
+ file may enable the signal while the environment sets only the endpoint:
669
+
670
+ | Field | Default | Flag | Variable |
671
+ | --- | --- | --- | --- |
672
+ | `enabled` | `false` | `--logs` / `--no-logs` | `OTEL_HOOK_LOGS_ENABLED` |
673
+ | `endpoint` | derived from `endpoint` | `--logs-endpoint` | `OTEL_HOOK_LOGS_ENDPOINT`, then `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` |
674
+ | `includeContent` | `false` | `--logs-content` | `OTEL_HOOK_LOGS_INCLUDE_CONTENT` |
675
+ | `maxBatchSize` | `128` | — | — |
676
+
677
+ Everything else — protocol, headers, timeout, service identity, resource
678
+ attributes — is shared with the traces signal, which is why `logs` is nested under
679
+ `exporter` rather than being a second top-level section that could drift.
680
+
681
+ Two combinations are reported as notes rather than errors, because both are things
682
+ an operator lands on by setting one switch and forgetting the other: logs enabled
683
+ with no endpoint and none derivable, and `includeContent` set while `contentMode` is
684
+ `omit` (so there is nothing disclosed to carry — the symptom, every body withheld,
685
+ otherwise looks like a bug).
686
+
687
+ ### Resource attributes
688
+
689
+ `exporter.resourceAttributes` adds custom attributes to the OTLP Resource every
690
+ exported span carries. Three sources feed it, merged **per attribute key** with
691
+ the usual precedence:
692
+
693
+ | Source | Layer |
694
+ | ----------------------------------------- | ----------------- |
695
+ | `"exporter": {"resourceAttributes": {…}}` | `file` |
696
+ | `OTEL_RESOURCE_ATTRIBUTES` | `environment` |
697
+ | `--resource-attr key=value` (repeatable) | `inline-override` |
698
+
699
+ ```bash
700
+ export OTEL_RESOURCE_ATTRIBUTES="deployment.environment=staging,deployment.note=a%2Cb"
701
+ otel-hook run --provider claude-code --resource-attr team.name=core
702
+ ```
703
+
704
+ Each key is its own leaf, so the union of all three layers is exported and the
705
+ highest layer wins only the keys it names. Precedence is an override relation,
706
+ not a replacement one: a higher layer cannot *remove* a key a lower layer set.
707
+
708
+ `OTEL_RESOURCE_ATTRIBUTES` is parsed as the specification defines it — W3C
709
+ Baggage. Comma-separated `key=value` pairs, optional surrounding whitespace, an
710
+ ignored `;`-delimited metadata suffix, optional surrounding quotes, and
711
+ **percent-encoded values**, so `deployment.note=a%2Cb` is one attribute whose
712
+ value is `a,b` rather than two malformed entries. An unusable entry is reported
713
+ and skipped; the rest of the variable still applies.
714
+
715
+ Bounds and refusals, all enforced in every layer:
716
+
717
+ - at most 64 attributes, keys ≤ 255 characters, values ≤ 2048 characters;
718
+ - keys must start with a letter and use only letters, digits, and `_ . - /`;
719
+ - values are a single string, number, or boolean — never an array, which no
720
+ environment variable can express;
721
+ - a key matching the privacy policy's secret-name patterns (`api_key`,
722
+ `*.token`, `authorization`, …) is dropped. A resource attribute rides on
723
+ *every* span, so this would be the most durable possible leak.
724
+
725
+ **`service.name` is never set by a resource attribute.** It is typed exporter
726
+ policy with its own precedence, so a map that could also write it would make the
727
+ winner depend on merge order inside the exporter. `--resource-attr
728
+ service.name=…` and a `service.name` key in a config file are refused outright,
729
+ naming `--service-name` instead. A `service.name` (or `service.namespace`) inside
730
+ `OTEL_RESOURCE_ATTRIBUTES` — the shape a migrating deployment already has — is
731
+ honoured, but as the *weakest* source of that field:
732
+
733
+ ```
734
+ OTEL_HOOK_SERVICE_NAME > OTEL_SERVICE_NAME > service.name in OTEL_RESOURCE_ATTRIBUTES
735
+ ```
736
+
737
+ A disagreement between those variables is warned about, naming the variables and
738
+ not their values.
739
+
740
+ Attributes survive the durable retry spool: the whole resolved resource is
741
+ persisted with the batch and replayed as recorded, because it describes the
742
+ invocation that made the observation rather than the one that drained the spool.
743
+ Custom attributes are re-checked on the way out, so a hand-edited spool file
744
+ cannot inject one the live path would have refused.
745
+
746
+ Diagnostics report resource attribute **names** only — `doctor --json` shows
747
+ `exporter.resource_attribute_names`. A name is already on the wire in every
748
+ exported resource; a value is not disclosed anywhere a name would do.
749
+
750
+ ## Crash semantics, and what deduplication does not cover
751
+
752
+ Two systems are involved and only one of them is transactional. Local state — the
753
+ sequence counter, the usage baseline, the delivery claim — lives in a filesystem
754
+ store this package controls. The collector does not. There is no protocol that
755
+ commits an OTLP export and a local state write together, so every ordering leaves a
756
+ window:
757
+
758
+ | Order | Crash window | Consequence |
759
+ | --- | --- | --- |
760
+ | export, then commit (**chosen**) | accepted by the collector, claim not yet committed | a redelivery **re-exports**: at-least-once |
761
+ | commit, then export | claim committed, export never happened | the observation is **lost**, silently |
762
+
763
+ The first is chosen deliberately. A duplicate is *identifiable*; a silent loss is
764
+ neither identifiable nor recoverable — nothing downstream can tell that an
765
+ observation was supposed to exist. Precisely how identifiable is worth being exact
766
+ about, because there are two cases and only one of them is droppable by span id:
767
+
768
+ | Re-export | When | What the collector sees |
769
+ | --- | --- | --- |
770
+ | byte-identical | the redelivery derives the **same** event id | the same trace and span id; the span correlator replays the facts already on disk, so a backend drops or overwrites |
771
+ | labelled duplicate | the redelivery derives a **different** event id | the same trace, a discriminated span id, and `otelhook.span.orphan="already-closed"` with `otelhook.span.paired=false` |
772
+
773
+ The second is the common case for a reclaimed claim, because most adapters seed each
774
+ hook firing with a distinct invocation — so the re-export cannot reuse the accepted
775
+ span's id without overwriting a published observation, and it is classified instead.
776
+ That attribute does not *prove* duplication (a genuine second close of one scope
777
+ carries it too), but it does mean the duplicate never arrives indistinguishable from
778
+ a first observation, which is what makes at-least-once survivable downstream. Both
779
+ paths are pinned in `tests/integration/delivery-dedup.test.ts`.
780
+
781
+ So, precisely:
782
+
783
+ - **Export is at-least-once.** A callback whose telemetry the collector accepted may
784
+ be exported again if this process dies before committing the claim.
785
+ - **Local accounting is at-most-once**, because it is committed under the same lock
786
+ as the claim it depends on, and the rollup — the one part outside that lock — is
787
+ idempotent by delivery identity.
788
+ - **A partial batch is terminal**, and its loss is reported rather than retried.
789
+ - **`staleClaimMillis` is a floor, not a proof.** If a real installation exceeds it,
790
+ a peer reclaims a live claim; the commit then detects the mismatched owner token,
791
+ refuses, and raises `delivery-claim-superseded` rather than silently double
792
+ counting. That diagnostic means the window needs raising.
793
+
794
+ Usage rollups are applied in a second critical section after the baseline advance,
795
+ because the accumulator takes the same non-reentrant session lock. Two windows sit
796
+ there and they are not the same shape:
797
+
798
+ - **Double-application is closed.** The record carries the last delivery folded into
799
+ it, so a reclaimed or superseded delivery re-applying its own delta is a no-op.
800
+ This lives in one key rather than being simulated across two, which is what makes
801
+ it a real atomic check instead of a pseudo-transaction.
802
+ - **Under-application stays open.** A crash *between* the baseline advance and the
803
+ rollup write loses one rollup increment. The baseline is correct, so the next
804
+ observation is unaffected, and baseline-first is chosen precisely so this window
805
+ under-counts a rollup rather than letting the next diff over-count.
806
+
807
+ This is why known limitation 2 stays open: deduplication is a real suppression
808
+ mechanism with a real gap, not an exactly-once guarantee.
809
+
810
+ ## Known limitations
811
+
812
+ Release blockers are marked. Each limitation is asserted by a named test, so
813
+ fixing one means updating that test rather than discovering a silent change.
814
+
815
+ 1. **Auto-detection cannot separate the PascalCase provider family.** Claude
816
+ Code, Codex, and Gemini CLI payloads are refused by auto-detection whenever
817
+ more than one adapter recognizes them; `--provider` is required for those
818
+ agents. Asserted in `tests/cli/detection.test.ts` and `tests/e2e/cli.test.ts`.
819
+ 2. **Delivery deduplication is incomplete, and is at-least-once (release blocker).**
820
+ Two separate gaps, both open:
821
+
822
+ *Crash window.* OTLP export and local state cannot be committed together, so a
823
+ process killed after the collector accepted a batch but before the claim was
824
+ committed re-exports on redelivery. The re-export is labelled rather than silent —
825
+ `otelhook.span.orphan="already-closed"`, or byte-identical when the redelivery
826
+ derives the same event id — which is the mitigation; it is not a guarantee. See
827
+ [Crash semantics](#crash-semantics-and-what-deduplication-does-not-cover).
828
+
829
+ *Coverage.* No adapter identifies every callback, and the Gemini CLI identifies
830
+ none. Each refuses the callbacks
831
+ where a stable-looking field would suppress a *genuine* second firing rather
832
+ than a redelivery. `--require-callback-id` reports these per callback — naming the
833
+ callback and the protocol field whose absence is the gap — and a host-supplied
834
+ `--callback-id` closes any of them. Neither `invocationId` nor
835
+ `eventId` can substitute: some adapters seed the former with a clock reading,
836
+ and the latter is seeded with a session sequence number that has already
837
+ advanced by the time a redelivery arrives. What each adapter cannot identify:
838
+ - **Claude Code** — `StopFailure`, `SessionStart`, `SessionEnd`, `PreCompact`,
839
+ `PostCompact`, plus any `Stop` or `SubagentStop` that fired because a hook
840
+ continued the turn. Claude Code can fire `Stop` more than once per prompt, so
841
+ `prompt_id` alone is not a delivery identity; the `stop_hook_active` flag
842
+ separates the once-per-prompt stop (`false`, deduplicated — it carries the
843
+ turn's usage) from a continuation (`true`, deliberately left unidentifiable,
844
+ because two continuations are indistinguishable and suppressing one would lose
845
+ real tokens).
846
+ - **Codex** — `SessionStart`, `PreCompact`, `PostCompact`, and any tool
847
+ callback whose optional `tool_call_id` is absent (`tool_name` is not a
848
+ substitute: two calls to the same tool in one turn would collapse into one).
849
+ - **Cursor** — `preCompact`, `afterAgentResponse`, `afterAgentThought`, both
850
+ subagent callbacks, and the dedicated shell, MCP, file-edit, and file-read
851
+ callbacks, none of which carry a `tool_use_id` at all: the only remaining
852
+ distinguishing fields are the command line and the file path, and
853
+ `generation_id` would be worse than nothing, since one generation runs many
854
+ shell commands.
855
+ - **Gemini CLI** — *everything*, declared `deliveryIdentifier: "none"`. The
856
+ protocol carries no request, turn, or tool-call id at all. The only candidate
857
+ is the provider-recorded `timestamp`, and a millisecond reading repeats on
858
+ redelivery without *separating* two genuine firings. `session_id` does not
859
+ rescue the session edges either: `SessionStart` carries
860
+ `source: "startup" | "resume" | "clear"` and fires again under the *same*
861
+ `session_id` on resume and clear, so keying on it would suppress every restart
862
+ after the first. `--callback-id` is the only deduplication available for this
863
+ provider.
864
+ - **Antigravity** — `Stop` only. The invocation and tool edges are identified
865
+ from `invocationNum` and `stepIdx`, both on the verified field list. `Stop` can
866
+ fire twice per invocation (idle, then fully idle), and the only field separating
867
+ those firings (`fullyIdle`) is an unconfirmed reconstruction — so keying it on
868
+ `invocationNum` would suppress the second, *real* firing rather than a
869
+ redelivery.
870
+
871
+ A process killed between claiming a callback and completing it leaves an
872
+ uncommitted claim; a later delivery reclaims it once `staleClaimMillis`
873
+ (default 60,000ms) has passed, so a crash costs a delayed export rather than a
874
+ permanently lost one, and the sweep will not expire such a claim before then
875
+ however short retention is set. Asserted in
876
+ `tests/integration/delivery-dedup.test.ts`,
877
+ `tests/providers/delivery-identity.test.ts`,
878
+ `tests/runtime/lifecycle-dedup.test.ts`,
879
+ `tests/runtime/lifecycle-usage-accumulator.test.ts`, and
880
+ `tests/integration/hook-runtime.test.ts`.
881
+ 3. **Cross-process span pairing needs a shared, durable state root.** A `*.end`
882
+ fired as its own process carries its start time, duration, parent, and
883
+ start-only attributes because the `SpanCorrelator` read them back from the
884
+ state store. Point two invocations at different `--state-dir`s, disable the
885
+ exporter, or let the record age past the retention window, and the end is
886
+ exported as an explicitly classified orphan
887
+ (`otelhook.span.orphan=missing-start` / `expired-start`) rather than merged
888
+ on a guess. Asserted in `tests/e2e/cli.test.ts` and
889
+ `tests/integration/span-correlation.test.ts`; see
890
+ [docs/state-retention.md](docs/state-retention.md).
891
+ 4. **Claude Code hook field aliases are normalized at the adapter boundary.**
892
+ Current `reason` / `trigger` fields and legacy `end_reason` /
893
+ `compact_trigger` wrappers map to the same canonical session and compaction
894
+ events.
895
+ 5. **Claude Code reports no reasoning-token counter and no provider total.**
896
+ Confirmed against real captures at 2.1.220 — 0 of 4,999 `usage` objects carried
897
+ either — so `reportsReasoningOutput: false` and `reportsProviderTotal: false`
898
+ are settled exclusions rather than open questions, and a consumer can tell
899
+ "this provider does not report reasoning tokens" from "this turn used none".
900
+ Cache read and cache creation *are* reported, at
901
+ `usage.cache_read_input_tokens` and `usage.cache_creation_input_tokens` (whose
902
+ TTL split is a breakdown, reconciled and never added). No hook callback carries
903
+ a token counter at all, so `usage` is read only when a wrapping harness
904
+ attaches it. A harness that attaches an excluded counter anyway is told which
905
+ field was declined. `ADAPTER-NOTE-001`; see
906
+ [docs/claude-code-usage-contract.md](docs/claude-code-usage-contract.md).
907
+ 6. **`contextTokensBefore` is an explicit exclusion for Claude Code.** Neither
908
+ compaction callback reports a context size upstream (`PreCompact` carries
909
+ `trigger` and `custom_instructions`; `PostCompact` carries `trigger` and
910
+ `compact_summary`), so there is no provider-stated figure for injected state to
911
+ carry across the boundary. Both figures are emitted when one harness attaches
912
+ them to `PostCompact`, which carries both ends in a single callback; a
913
+ `context_tokens_before` on `PreCompact` alone is declined explicitly rather
914
+ than dropped silently. `compact_summary` is never read — it is conversation
915
+ content. `ADAPTER-NOTE-002`.
916
+ 7. **Cursor sends no timestamp, and four of its facts rest on capture rather than
917
+ documentation.** The contract is derived from Cursor's published hooks
918
+ reference plus four real redacted capture runs (Cursor IDE 3.12.17 and CLI
919
+ 2026.07.17); `src/providers/cursor/payload.ts` cites both, and
920
+ `tests/parity/cursor.parity.test.ts` replays the fixture bytes through the
921
+ shipped adapter with no envelope bridge — which is what retired
922
+ `ADAPTER-NOTE-005`. Four residual limits, each a consequence of what Cursor
923
+ does or does not send:
924
+ - **No timestamp field exists** on any Cursor hook, in the reference or in any
925
+ captured payload's key list, so `occurredAt` is a clock reading. Replay
926
+ stability comes from `deliveryIdentity` instead, not from `invocationId`.
927
+ - **Token accounting is partly undocumented.** `input_tokens`,
928
+ `output_tokens`, `cache_read_tokens`, and `cache_write_tokens` appear on
929
+ `stop` and `afterAgentResponse` in capture and nowhere in the reference.
930
+ `input_tokens` is read as the canonical *inclusive* total with
931
+ `cache_read_tokens` as a subset — the reading all three captured samples are
932
+ consistent with — and a payload that contradicts it loses the breakdown
933
+ rather than being reinterpreted. `cache_write_tokens` is not mapped at all:
934
+ canonical usage needs an explicit cache-creation accounting, and nothing
935
+ establishes whether Cursor bills those tokens inside or beside
936
+ `input_tokens`, so a non-zero value produces a warning instead of a guess.
937
+ See `CURSOR_USAGE_INCLUSIVITY_NOTE`.
938
+ - **Two callbacks report no outcome.** `afterShellExecution` and
939
+ `afterMCPExecution` carry no exit code and no status field, so their
940
+ `tool.end` reports `outcome: "unknown"` rather than assuming success. The
941
+ generic `postToolUse`/`postToolUseFailure` pair does distinguish the two,
942
+ which is why it is the pair `setup` registers.
943
+ - **Subagents and compaction are partial.** `subagentStop` carries no subagent
944
+ id — the reference gives `subagent_id` to `subagentStart` only — so both are
945
+ ignored rather than emitting a delegation that never closes, and
946
+ `emitsSubagentEvents` is `false`. Cursor exposes no post-compaction
947
+ callback, so `compaction.performed` carries `contextTokensBefore` and never
948
+ `contextTokensAfter`.
949
+
950
+ Delivery also differs by surface: `stop` and `afterAgentResponse` fired in the
951
+ captured IDE runs and in neither CLI run, while `sessionEnd` fired in both CLI
952
+ runs and in neither IDE run — from the same `hooks.json`. See
953
+ [docs/registration-evidence.md](docs/registration-evidence.md).
954
+ 8. **Antigravity is experimental (release blocker for that provider).** It maps
955
+ only `tool.start`/`tool.end`; `PreInvocation`, `PostInvocation`, and `Stop` are
956
+ ignored rather than mapped to invented session or generation identities. Its
957
+ open promotion gates are printed by `otel-hook providers`. Its hook-file
958
+ *shape* is recorded but no install *path* has been verified, so `setup`
959
+ requires an explicit `--settings-file` and `diagnose` does not sweep it.
960
+ 9. **No Python parity is claimed for Codex or Gemini CLI.** The pinned
961
+ `opentelemetry-hooks==0.14.0` reference rewrites Gemini's `BeforeTool` into
962
+ Claude Code's `PreToolUse` (`DIVERGENCE-007`), and reads Codex's
963
+ `gen_ai.client.version` from whichever `codex` binary is on the *host's* PATH
964
+ rather than from the payload's own `codex_version` — host-dependent, and wrong
965
+ for a replayed payload (`DIVERGENCE-010`).
966
+ `tests/parity/codex-gemini.parity.test.ts` establishes our own semantics and
967
+ pins both divergences instead of asserting agreement.
968
+ 10. **Only OTLP HTTP/protobuf is exported, for traces and logs.** `http/json` falls
969
+ back to a disabled sink with a warning, and there is no metrics pipeline. The
970
+ logs pipeline is off by default; see [Logs](#logs).
971
+ 11. **Gemini CLI cache and reasoning tokens never reach a hook.** The CLI's hook
972
+ translator rebuilds `usageMetadata` as exactly
973
+ `{ promptTokenCount, candidatesTokenCount, totalTokenCount }`, so
974
+ `cachedContentTokenCount` and `thoughtsTokenCount` — both present on the SDK
975
+ response it reads — are dropped before any hook runs. The adapter declares
976
+ `reportsCachedInput: false` and `reportsReasoningOutput: false` accordingly,
977
+ and still maps both counters in case a later translator version stops
978
+ stripping them. Unblocking this needs a change upstream, not here.
979
+
980
+ Relatedly, `AfterModel` fires once **per streaming chunk**, and a chunk's
981
+ counters are a snapshot of the response so far rather than that chunk's
982
+ increment — the CLI's own `loggingStreamWrapper` keeps `lastUsageMetadata`
983
+ and never sums. The adapter therefore reports `cumulative` temporality, so
984
+ several usage-bearing chunks of one stream diff against a single
985
+ generation-scoped baseline and are billed once in total. Asserted in
986
+ `tests/providers/gemini/usage.test.ts`,
987
+ `tests/providers/gemini/integration.test.ts`, and
988
+ `tests/parity/codex-gemini.parity.test.ts`.
989
+ 12. **MCP tool calls are recognized by a naming convention, not a declared fact.**
990
+ The `mcp` log signal is assigned when a canonical tool name matches `mcp__…`,
991
+ which is the shape Claude Code, Codex, and Gemini CLI payloads carry. Cursor's
992
+ dedicated MCP callbacks produce `<server>:<tool>` names and therefore classify as
993
+ `tool` — under-reporting, never a wrong claim. Fixing it properly needs a
994
+ canonical field an adapter can populate from a *verified* contract, which is
995
+ blocked on the same Cursor evidence gap as limitation 7. Asserted in
996
+ `tests/runtime/telemetry-log-records.test.ts`.
997
+ 13. **A `tool.end` log record cannot refine past `tool`.** Only the start edge
998
+ carries `toolKind`, so the same `Bash` call is signal `shell` on its start and
999
+ `tool` on its end. The span for that scope *does* carry the kind, recovered from
1000
+ state by the correlator, so the detail is available — just not on that record.
1001
+
1002
+ ## Architecture decisions
1003
+
1004
+ See [docs/adr](docs/adr/README.md), and `AGENT.md` for the dependency direction
1005
+ and safety rules contributors are held to.
1006
+
1007
+ ## Development
1008
+
1009
+ ```bash
1010
+ npm install
1011
+ npm run check # typecheck, lint, build, full test suite, fixture validation
1012
+ npm run test:e2e # drive the built CLI binary as a child process
1013
+ npm run test:parity # differential suite against the pinned Python reference
1014
+ npm run test:packaging # pack, install into a scratch consumer, exercise every export
1015
+ ```
1016
+
1017
+ The parity suite builds a cached virtualenv under the OS temp directory on first
1018
+ run and skips itself if no Python interpreter is available.
1019
+
1020
+ Licensed under MIT.