Plan: OpenTelemetry export of permission decisions and helper runs
Closes: #272. Branch: feat/otel-decisions. Status: Done (2026-11-01) — landed with a live check against a local collector
Erratum (2026-11-01): the version attribute is gadhs.pi_modes.version, the emitting pi-modes' version; pi-modes cannot read @gadhs/pi’s own version reliably, and `gadhs.pi.version suggested it.
Erratum (2026-11-01): the recordVerdict wiring test went in test/judge-wiring-callback.test.ts, where recordVerdict’s other tests live, not `test/judge-wiring.test.ts.
Design
What the operator decided (2026-11-01)
The export is wanted even with no agency collector today. Hand-rolled: the
official OpenTelemetry JS SDK is too complex for the need (10+ packages, the
exporters still at 0.x, Node >=22.15, one SDK per process), and the existing
pi OTel extensions have one maintainer each and dependencies a major version
behind (pi-otel 0.3.0: 17 stars, last commit 2026-09-13, OTel 0.57/1.30
against current 0.300/3.0). The OTLP/HTTP JSON encoding is part of the
stable OTLP specification (1.11), which an OpenTelemetry Collector’s OTLP
receiver accepts as shipped, so a small sender is a bounded job. pi-modes
registers no global OpenTelemetry SDK, so pi-otel or another extension can
run beside it and send LLM traces to the same collector.
What is emitted
Two kinds of span, both from pi-modes:
A decision span per gated tool call: recordVerdict in judge-wiring.ts
already receives everything needed. The span starts at the gate’s
startedAt and ends at decidedAt (a host’s wait excluded, as the status
line’s latency is). Name execute_tool <tool>, kind INTERNAL, attributes:
| Attribute | Value |
|---|---|
|
|
|
the ask’s |
|
the ask’s |
|
|
|
the verdict’s |
|
|
|
the rule pattern, when a rule decided |
|
the mode id |
|
|
|
the command or path, only with content capture on |
The GenAI conventions are at Development status; the plan pins what it
emits to semantic-conventions-genai as read on 2026-11-01 (execute_tool,
invoke_agent, the gen_ai. names above) and records that in the module’s
doc comment. Permission has no convention, so those attributes are ours,
under gadhs.permission.. The verdict’s reason text is never sent: it can
quote the command.
A helper span per helper run, emitted by HelperRuns (helper-runs.ts),
the one object every run’s lifecycle passes through: started (the
start time), backgrounded, yielded, and ended(id, at, failed, priced),
which subagent-wiring.ts calls for a foreground run at its result (line
751) and for a background run when its report is fetched (line 531). The
span is emitted at ended, from run.startedAt to at: name
invoke_agent <agent>, attributes gen_ai.operation.name=invoke_agent,
gen_ai.agent.name, gadhs.helper.outcome = failed when failed, else
done; gadhs.helper.background=true when the run’s state was
background before it ended; gadhs.helper.yielded=true when yielded
was called for it; gadhs.helper.model when the run has one. A run that
never ends (pi quits first) emits no span. Never the task text or the
yield’s content: HelperRuns passes the exporter only the fields named
here, and the contract test’s expectation lists every attribute key, so a
new key fails it.
Every span carries the resource service.name (pi, or OTEL_SERVICE_NAME)
and the attributes session.id (pi’s session id) and gadhs.pi.version.
The exporter is built once, in index.ts at load, from process.env; the
session id it stamps is read lazily through a getter over
refs.sessionId (SessionRefs in session-wiring.ts, set at each
session_start), so a span before the first session start carries no
session.id, and a /new changes it. Trace ids: one per pi session (the
session id’s 32 hex characters when it is a UUID without its dashes, else
16 random bytes), derived from that same getter and cached per id; span
ids 8 random bytes.
The decision span’s attributes come from the ask as recordVerdict
receives it. Its two callers differ: judgeCommand passes the ask it
built, adjudicateAsk passes the raw args[0], whose toolName may be
absent for a write/edit (the surface is under accessIntent, which
normalizeAsk resolves). So recordVerdict gains a parameter: the
normalized ask, which both callers already hold, and the exporter reads
toolName, surface, agentName and forwarded from it. A decision span of a forwarded
ask carries no parent: the helper’s own session is another trace. No
traceparent is read or propagated; that is #272’s follow-up if the agency
wants cross-process joins.
Switching on, and off
Off unless one of OTEL_EXPORTER_OTLP_TRACES_ENDPOINT or
OTEL_EXPORTER_OTLP_ENDPOINT is set (read once at session start). The
traces URL follows the specification: the traces variable as given; the
generic one with /v1/traces appended. OTEL_EXPORTER_OTLP_HEADERS
(k=v,k2=v2, URL-decoded) is sent on every request, and its values never
appear in any log line or error. OTEL_EXPORTER_OTLP_TRACES_PROTOCOL or
OTEL_EXPORTER_OTLP_PROTOCOL other than http/json (or unset): the
exporter refuses to start, one otel.refused diagnostics line names the
protocol, and nothing is sent. OTEL_SDK_DISABLED=true turns it off.
Content capture (gen_ai.tool.call.arguments) is on only with
OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT set to a value other than
false/empty, the GenAI conventions' own variable. No overlay setting: the
collector is the box’s business, not the mode’s.
Delivery
A module otel-export.ts: a bounded queue (512 spans; past it the oldest is
dropped and counted), flushed by a timer every 5 s or at 64 spans, each flush
one POST of one ExportTraceServiceRequest in OTLP JSON (hex ids,
lowerCamelCase keys, integer enums, timeUnixNano as decimal strings) with
a 10 s timeout through fetch and AbortSignal.timeout. A failed POST drops
that batch: one otel.export_failed diagnostics line per distinct status or
error, not per batch. session_shutdown flushes once more, bounded by the
same timeout; a quit does not wait past it. Nothing here runs on the gate’s
path: recording a span is a push onto the queue.
Failure modes
-
No endpoint,
OTEL_SDK_DISABLED, or an unsupported protocol: fail closed, silent for the first two, one diagnostics line for the third.startOtelExportreturnsundefined; every caller’sotel?.is a no-op; no timer, no fetch. Tested: no fetch and no timer with the env unset. -
A failed or timed-out POST: fail open, loud once. The batch is dropped; a
otel.export_failedline per distinct status or error text, never per batch, and never carrying a header value (the line names the URL’s host and the status only). pi’s work is unaffected. Tested with the fake collector answering 503, and with a closed port. -
Queue overflow: fail open, counted. Past 512 queued spans the oldest is dropped; the count of dropped spans is an attribute (
gadhs.otel.dropped) on the next batch’s first span, and oneotel.droppeddiagnostics line per session. Tested by queueing 600 with the collector stalled. -
Shutdown racing the timer: at most one flush of each span.
shutdown()clears the timer first, then flushes what is queued once, bounded by the POST timeout; a flush already in flight is awaited, not repeated. A quit that outlasts the timeout proceeds; the batch is lost and nothing is logged (the process is leaving). Concurrency test: a timer flush in flight against the fake collector whenshutdown()is called; the collector receives every span exactly once. -
Header values: never in any log.
OTEL_EXPORTER_OTLP_HEADERSis parsed into a map used only on the request; the diagnostics lines are built from a fixed set of fields. Tested: a failure with a header set leaves no trace of its value in the diagnostics log.
Where it lives
-
otel-export.ts(new): the env reading, the queue, the encoding, the sender; exportsstartOtelExport(env, deps)withdeps = { sessionId: () ⇒ string | undefined, piVersion: string, now: () ⇒ number, fetch, log }, returning{ decision(…), helper(…), shutdown() } | undefined. The GenAI convention names it emits, and the date they were read (2026-11-01,open-telemetry/semantic-conventions-genai, status Development), are in its header comment. -
judge-wiring.tsrecordVerdict: gains the normalized ask as a parameter (both callers, lines 1016 and 1050, pass theirs) and makes one call todeps.otel?.decision(normalized, verdict, span, modeId);JudgeDepsgainsotel?, set byregisterJudgefrom a new argument. -
helper-runs.tsHelperRuns: constructed with an optionalotel?.helpersink (subagent-wiring.tsline 229 passes it);endedemits the helper span;yieldedandbackgroundedset the flags it reads. -
index.ts: builds the exporter fromprocess.envat load and hands it toregisterJudgeandwireSubagents;session-wiring.ts’s `session_shutdownhandler (line 483) callsshutdown()afterdeps.judge.onShutdown(). -
modes.adocgains a sectionOpenTelemetry exportunder Diagnostics (line 3634’s[#diagnostics]);CHANGELOG.adocan Added entry under== Unreleased. -
The MR’s description says
Closes #272; after the merge, one note on #272 with the merge SHA, and this plan’s status set to Done.
Scope
In
-
The module, its wiring, the two span kinds, the environment contract above.
-
Tests,
test/otel-export.test.ts, by category:-
Contract (wire format): the exact OTLP JSON of one decision span and one helper span against a fixed expectation that lists every attribute key, so an added key (a reason, a task) fails it;
timeUnixNanoas decimal strings; hex ids of 32 and 16 characters. -
Behaviour, against a fake collector (
node:http): batching at 64 spans and at the 5 s timer (fake timers);OTEL_EXPORTER_OTLP_HEADERSsent, URL-decoded; the URL rule for the generic and the traces variable; a 503 drops the batch and logs once for repeated 503s; overflow at 512 counts; content capture off by default and on with the variable; a header value absent from the diagnostics log after a failure. -
Fail-closed: no fetch and no timer with no endpoint, with
OTEL_SDK_DISABLED=true, and withgrpc/http/protobuf(oneotel.refusedline). -
Concurrency:
shutdown()during an in-flight timer flush delivers every span exactly once. -
Property (fast-check): any ask/verdict pair, with arbitrary strings in every text field, encodes without a throw, to valid JSON, with no text field’s content present unless capture is on.
-
-
test/judge-wiring.test.ts:recordVerdictpasses the exporter the normalized ask, the gate’s two times and the verdict’s source and kind, for ajudgeCommandcall and anadjudicateAskcall. -
test/subagent-wiring.test.ts: a foreground run and a background run each reach the exporter once at their end, the background one withbackground=true; a run that never ends emits nothing. -
test/session-wiring.test.ts:session_shutdowncallsshutdown().