record

package
v0.7.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package record turns one proxied call into the forms the recorder writes.

The record of truth is WIRE (wire.go): the raw request and response, redacted, in the format Inference-Perf replays directly. With --record-otlp each turn is also sent live as an OTLP span (otlp.go) for Phoenix and other collectors. This file defines the translated span both of those views are built from, in the flat claude-record shape (span name `chat <model>`, flat attributes, ISO times), which stays the reference for what a turn carries.

Index

Constants

View Source
const (
	// SpanDerivedTurn is the span name for a reconstructed human turn.
	SpanDerivedTurn = "cg.turn.derived"

	AttrTurnDerived   = "cg.turn.derived"  // always true on these spans
	AttrTurnSequence  = "cg.turn.sequence" // DERIVED ordering, 1-based within a root
	AttrTurnPrompt    = "cg.turn.prompt"   // the recovered human text
	AttrTurnPromptLen = "cg.turn.prompt_length"
	AttrTurnRoot      = "cg.turn.conversation_root"
	AttrTurnMethod    = "cg.turn.method" // how it was recovered, for auditability

	// AttrTurnPrior is true on a turn that was already history in the first call observed for
	// its conversation: a resumed session's earlier turns, or turns from before recording began.
	// Count a session's own turns as those where this is false. See ReconTurn.Prior.
	AttrTurnPrior = "cg.turn.prior_to_observation"

	// TurnMethodBodyRecon names the only method there is today. Spelled out in the data so a
	// consumer can tell a reconstruction from an observation without reading this file.
	TurnMethodBodyRecon = "request_body_reconstruction"

	// Tool-call attributes lifted from the body. Same spelling as claude-record's, because
	// the point is that existing queries keep working.
	AttrToolName   = "tool_name"
	AttrToolArgs   = "full_command"
	AttrToolCallID = "gen_ai.tool.call.id"
	AttrToolLifted = "cg.tool.from_body" // true: read out of the message body, not observed
)

Derived-data attribute keys. All cg.* -- additive, and namespaced so nothing mistakes them for either standard gen_ai semconv or claude-record's observed claude_code.* keys.

View Source
const (
	RedactedName     = "«redacted:name»"
	RedactedUsername = "«redacted:username»"
	RedactedEmail    = "«redacted:email»"
	RedactedTerm     = "«redacted:term»"
	RedactedOwner    = "«redacted:owner»"
	RedactedRepo     = "«redacted:repo»"
)

Markers for removed identity. Placeholder's «» family, with the category kept so a reader can tell a removed name from a removed key.

View Source
const (
	PartText         = "text"
	PartToolCall     = "tool_call"
	PartToolResponse = "tool_call_response"
)

Part type values, spelled as the corpus spells them. Note tool_call, NOT Anthropic's tool_use: the translation below is the whole point of this file.

View Source
const (
	StatusOK    = 1
	StatusError = 2
)

Status codes as the corpus uses them: 1 = OK, 2 = ERROR. (OTel's own OK is 1 and ERROR is 2, so these agree; the corpus just stores the integer.)

View Source
const (
	IncompleteNone      = ""                 // the whole turn was captured
	IncompleteTeeCap    = "tee_cap_reached"  // response longer than the record cap
	IncompleteRetainCap = "retain_bound"     // CG's 16 MB retain bound; body never materialised
	IncompleteTruncated = "rounds_truncated" // continuation exit, both rounds truncated
	IncompleteNoBody    = "no_body_on_path"  // a terminal path that never buffers a body
	// IncompleteNoUsage: the response's usage block was absent or unparseable, so the
	// cache-split values on this span are zeros that were never measured. Needed because
	// ToSpan emits those keys unconditionally -- deliberately, since a genuine zero is data --
	// which leaves "no cache activity" and "unknown" indistinguishable without this marker.
	IncompleteNoUsage = "no_usage_on_response"
)

Incompleteness reasons. Exported so the proxy and the analysis side name them identically rather than by matching strings by eye.

View Source
const (
	AttrOperation    = "gen_ai.operation.name"
	AttrSystem       = "gen_ai.system"
	AttrModel        = "gen_ai.request.model"
	AttrMaxTokens    = "gen_ai.request.max_tokens"
	AttrEffort       = "gen_ai.request.effort"
	AttrOutputSchema = "gen_ai.request.output_schema"
	AttrOutputType   = "gen_ai.output.type"
	AttrInputMsgs    = "gen_ai.input.messages"
	AttrOutputMsgs   = "gen_ai.output.messages"
	AttrToolDefs     = "gen_ai.tool.definitions"
	AttrInputTokens  = "gen_ai.usage.input_tokens"
	AttrOutputTokens = "gen_ai.usage.output_tokens"

	// The cache split, under the GenAI semconv names claude-record also writes since 0.1.5
	// (collector #34). Both are already counted in AttrInputTokens, as the semconv says.
	AttrCacheRead  = "gen_ai.usage.cache_read.input_tokens"
	AttrCacheWrite = "gen_ai.usage.cache_creation.input_tokens"

	// CG-only. Semconv has no name for the uncached remainder.
	AttrFreshInput   = "cg.usage.fresh_input_tokens"
	AttrStopReason   = "cg.response.stop_reason"
	AttrUpstreamMS   = "cg.upstream_ms"
	AttrFirstByteMS  = "cg.first_byte_ms"
	AttrRounds       = "cg.upstream_rounds"
	AttrIncomplete   = "cg.incomplete"
	AttrResponseSize = "cg.response_bytes"
	AttrRecordedBy   = "cg.recorded_by"
)

Attribute keys. Every one the existing corpus uses is spelled here exactly as the corpus spells it, because a typo is a silently-missing column in someone's analysis. The cg.* keys are ADDITIVE -- new information claude-record never had -- and namespaced so nothing can mistake them for standard gen_ai semconv.

View Source
const (
	AttrProviderName = "gen_ai.provider.name"
	AttrSessionID    = "session.id"

	// OpenInference (Arize Phoenix). See github.com/Arize-ai/openinference, semantic conventions.
	AttrOISpanKind       = "openinference.span.kind"
	AttrOIModelName      = "llm.model_name"
	AttrOIProvider       = "llm.provider"
	AttrOITokenPrompt    = "llm.token_count.prompt"
	AttrOITokenComplete  = "llm.token_count.completion"
	AttrOITokenTotal     = "llm.token_count.total"
	AttrOITokenCacheRead = "llm.token_count.prompt_details.cache_read"
	AttrOITokenCacheNew  = "llm.token_count.prompt_details.cache_write"
	AttrOIInputValue     = "input.value"
	AttrOIInputMime      = "input.mime_type"
	AttrOIOutputValue    = "output.value"
	AttrOIOutputMime     = "output.mime_type"

	OISpanKindLLM   = "LLM"
	OISpanKindChain = "CHAIN"

	// Resource attributes.
	ResService       = "service.name"
	ResServiceVer    = "service.version"
	ResClient        = "cg.client.name"
	ResTenant        = "cg.tenant.id"
	ServiceNameProxy = "context-guru-proxy"
)

OTLP and OpenInference attribute keys added on the exported spans.

View Source
const CollectorVersion = "cg-record/0.2.0"

CollectorVersion identifies the producer in every file written. It is deliberately DISTINCT from claude-record's own version string: a corpus that mixes two producers must be able to say which rows came from which, or every coverage difference between them becomes unattributable at analysis time.

0.2.0: identity redaction (identity.go). Files from 0.1.0 still name the person recording.

View Source
const MinRootCalls = 3

MinRootCalls floors RootShare for short sessions, where 5% of a handful of calls would admit every subagent.

View Source
const Placeholder = redact.Redacted

Placeholder marks a removed value. It reuses internal/redact's visible-by-design placeholder so a reader sees one convention, not two.

View Source
const RootShare = 0.05

RootShare is the fraction of a session's calls a conversation root must hold to count as a real conversation rather than a subagent. Measured: 64 of 66 sessions have exactly one root above this line; 2 have two, both genuine (a /clear mid-session starts a second conversation). Subagent roots sit far below it -- typically one to four calls each. Measured sweep on 100 sessions: raising it to 0.10/0.20/0.30 shaves over-count but costs real recall (92.7% -> 92.3% -> 91.4% -> 91.3%), trading good turns for bad at about 1:3. 0.05 is the measured optimum, not a guess.

View Source
const SpanKindClient = "SPAN_KIND_CLIENT"

SpanKindClient is the only kind this package emits: a proxied model call is an outbound request. Spelled as the corpus spells it.

Variables

This section is empty.

Functions

func CapContent

func CapContent(s string, cap int) (string, bool)

CapContent applies a size cap AFTER scrubbing, and reports whether it bit.

Separate from Content on purpose. internal/redact.Content folds the cap in and appends a human-readable truncation note, which is right for a dashboard field. For a trace the truncation is a fact about the TURN: it belongs in Turn.Incomplete where an analysis can filter on it, not buried in the body text where it can only be found by a substring search. Callers that cap must set Incomplete accordingly.

func Content

func Content(s string) string

Content scrubs credentials, and the identity of the person recording, from arbitrary recorded text.

Order is deliberate: identity first (see identity.go), then internal/redact.Content (it owns the vocabulary and handles the submatch-preserving URL and header rules), then the extra shapes, then the base64 pass. cap<=0 means no cap, and the cap is NOT applied here -- see CapContent -- because a recorded trace wants the whole turn, and truncation for a trace is an incompleteness fact that belongs on the span (Turn.Incomplete), not a silent trim inside a redactor.

func ContentJSON

func ContentJSON(s string) string

ContentJSON scrubs a JSON document by scrubbing the STRINGS INSIDE IT, never its encoded text, and splices back only the strings that changed.

WHY, measured on the first full day of recordings (2026-10-07): Content run over encoded JSON corrupted 63 of 314 bodies. The assignment rule's value class `[^\s"',;}]` admits a backslash, so in `?token=XYZ\"` the match took the `\` of the escaped quote with it and left a bare `"` behind -- invalid JSON. Turn reconstruction parses these bodies, so the first broken string silently ended turn derivation for the rest of the session (2 of 7 turns found). Decoded text has no escapes for a pattern to eat, and a re-encoded string is always a valid literal, so the document stays valid whatever the patterns do.

What the encoded pass caught ACROSS literals is kept: an object member is also checked as `"key": value`, the exact shape internal/redact's JSON-assignment rule exists for, and its value is replaced whole when that pair would have been scrubbed. Bytes outside a changed literal -- key order, whitespace, `<`-style escapes -- are untouched, so a body with nothing to redact comes back identical.

Text that is not valid JSON falls back to Content: a capped or otherwise partial body is still scrubbed, just without the structure guarantee.

func ConversationRoot

func ConversationRoot(msgs []Message) string

ConversationRoot identifies which conversation a model call belongs to, from the set of tools the call advertises.

WHY TOOL DEFINITIONS AND NOT THE FIRST MESSAGE

The obvious anchor is the conversation's first human turn: the main thread replays it on every call, each subagent has its own. That was tried and it FAILS on long sessions, measured. Once a conversation passes compaction the earliest turn drops out of the replayed window, so the same conversation silently acquires a new identity mid-session and its turns fragment across several "conversations". On the worst measured session it produced 32 roots for one session, five of them above any sensible threshold, and reconstructed 29 turns where 31 happened.

The advertised tool list does not scroll out of the window, so it survives compaction. It also separates the threads that matter: the main agent advertises the full tool set, a subagent gets a restricted one (Explore has no Write or Edit), and a WebFetch-fed thread advertises none. Measured over 66 sessions: 2 to 5 distinct sets per session, the dominant set holding 83% of calls on average and never less than 50%.

Returns "" when a call advertises no tools at all. That is the signature of a helper call -- a WebFetch-fed thread, or Claude Code's own session-title generator -- and such calls are dropped. Measured: adopting them into the dominant conversation instead adds 13 turns of which only 2 are real, so it buys 1.7 points of apparent coverage by readmitting 11 non-turns.

func FormatTime

func FormatTime(t time.Time) string

FormatTime renders t the way the corpus stores timestamps: UTC, microseconds, +00:00.

func HumanText

func HumanText(content string) string

HumanText returns the human-authored text of one role:user text part, or "" if the part is framework-injected. This is the filter the "with work" column is about.

func MarshalMessages

func MarshalMessages(msgs []Message) (string, error)

MarshalMessages renders a message list as the attribute value: a JSON string, because that is what the corpus stores and what the scripts json.loads.

func OTLPMessages

func OTLPMessages(corpus string) string

OTLPMessages converts the corpus message list (a JSON string) to the semconv message schema. The only difference is that a tool_call's arguments become a JSON value instead of a string. Input that does not parse is returned as is: a trace with a malformed message attribute is still a trace.

func RedactSSE

func RedactSSE(raw string) string

RedactSSE returns the stream with credentials and identity removed, across event boundaries.

func SafeFileName

func SafeFileName(id string) string

SafeFileName makes a session id safe as a file name on every platform, NTFS included: a ":" there silently creates an alternate data stream instead of a file.

func SetIdentity

func SetIdentity(id Identity)

SetIdentity replaces the identity Content removes. The proxy never needs it -- the local identity is loaded on first use -- but tests do, so a result never depends on who runs them.

func SpanName

func SpanName(model string) string

SpanName builds the `chat <model>` name the analysis scripts match on. One place, so the `chat ` prefix cannot be lost.

func ToolCallAttrs

func ToolCallAttrs(u ToolUse) map[string]any

ToolCallAttrs renders one lifted tool call as span attributes, using claude-record's own key names so existing queries resolve.

cg.tool.from_body marks the provenance: these values were read out of a message body rather than observed at execution time. Present so that a mixed corpus stays interpretable.

func ToolDefinitions

func ToolDefinitions(requestBody []byte) (string, error)

ToolDefinitions renders gen_ai.tool.definitions, present on 5,037 of the 5,680 corpus chat spans and the thing that makes a tool_call interpretable: the call names a tool whose parameter schema lives only here.

The array is RESHAPED, not passed through. converter.py rewrites each Anthropic tool {name, description, input_schema} into {type:"function", name, description, parameters}, so the corpus stores the OpenAI-flavoured spelling. Forwarding the Anthropic shape would put `input_schema` where every consumer reads `parameters`.

func ToolResults

func ToolResults(msgs []Message) map[string]string

ToolResults maps call id -> result text, read from role:tool messages.

func TraceIDFor

func TraceIDFor(sessionKey string) string

TraceIDFor maps a session key to a 16-byte OTLP trace id, as 32 hex characters.

A UUID is used as is, without its dashes, so a session's trace id in Phoenix reads as its Claude Code session id. Any other key is hashed: it is stable, so every call of one session gets the same trace id, and two sessions never collide in practice.

func UsageFromResponse

func UsageFromResponse(responseBody []byte) (fresh, cacheRead, cacheWrite, output int, stopReason string, err error)

UsageFromResponse pulls the token split out of a response body. This is the mooncake unblock arriving in one place: Anthropic reports cache_read_input_tokens and cache_creation_input_tokens on every response, and `input_tokens` is the FRESH prefix only -- the under-reporting that claude-record inherits as issue #17.

func Wire

func Wire(c WireCall, bodyCap int) ([]byte, error)

Wire renders one call as a redacted JSONL line, newline included.

bodyCap > 0 caps each body after redaction (see the file comment for what a cut body means).

Types

type Call

type Call struct {
	Order    string // sort key: span start time, or span id -- caller's choice, must be consistent
	Messages []Message

	// ToolDefs is the call's advertised tool schema, verbatim (gen_ai.tool.definitions). It is
	// the conversation anchor -- see ConversationRoot for why the first message is not.
	ToolDefs string
}

Call is one observed model call, as the reconstruction needs it: the translated input messages plus a stable ordering key.

type File

type File struct {
	TraceID          string `json:"trace_id"`
	SpanCount        int    `json:"span_count"`
	CollectedAt      string `json:"collected_at"`
	Spans            []Span `json:"spans"`
	CollectorVersion string `json:"collector_version"`
}

File is one session's worth of spans: the unit claude-record writes and the analysis scripts load.

func NewFile

func NewFile(traceID string, spans []Span, collectedAt time.Time) File

NewFile assembles a session file. collectedAt is passed in rather than read from the clock so the result is testable.

func (File) Marshal

func (f File) Marshal() ([]byte, error)

Marshal renders the file as the corpus stores it: indented, trailing newline.

type Identity

type Identity struct {
	Usernames []string // local OS login names
	Names     []string // personal names, e.g. the git user.name
	Emails    []string // addresses always removed, even ones the generic rule would keep
	Terms     []string // anything else, e.g. GitHub logins
}

Identity is who to remove from a recording. The zero value removes emails and repo URLs only.

func LocalIdentity

func LocalIdentity() Identity

LocalIdentity reads the identity of the person running the proxy: the OS login and home directory names, the git user.name and user.email, and the extra-terms list.

type Message

type Message struct {
	Role         string `json:"role"`
	FinishReason string `json:"finish_reason,omitempty"` // output messages only
	Content      string `json:"content,omitempty"`       // the string-form system message
	Parts        []Part `json:"parts,omitempty"`
}

Message is one entry in gen_ai.input.messages / gen_ai.output.messages.

Content and Parts are both present because the corpus uses both: 1,952 system messages carry a plain `content` string rather than parts. Round-tripping that difference keeps a recorded file byte-comparable with a collected one instead of merely equivalent.

func InputMessages

func InputMessages(requestBody []byte) ([]Message, error)

InputMessages translates an Anthropic request body into the corpus's input-message list.

The system prompt becomes a leading role=system message, which is how the corpus carries it: there is no separate system attribute, and an analysis asking "was a system prompt present" looks for that message.

func OutputMessages

func OutputMessages(responseBody []byte) ([]Message, error)

OutputMessages translates a non-streaming Anthropic response into the corpus output-message list: always exactly one assistant message, mirroring convert_response_to_otel.

Two details are copied rather than improved on. The finish_reason falls back to "stop" when the response carries no stop_reason (the corpus default, not part of the Anthropic vocabulary), and role is the literal "assistant" rather than whatever the body claims -- converter.py hardcodes it, and a response claiming another role would otherwise produce a row no analysis expects.

type Meta

type Meta struct {
	Model        string
	MaxTokens    int
	Temperature  *float64
	Effort       string
	OutputType   string
	OutputSchema string
	Stream       bool
}

Meta is the non-message request side of a span. A struct rather than six return values because the list was already at the length where callers start transposing arguments.

func RequestMeta

func RequestMeta(requestBody []byte) (Meta, error)

RequestMeta pulls the request-side span attributes that are not messages.

effort comes from req.output_config.effort VERBATIM -- it is not derived. An earlier version of this function inferred it from the thinking budget on three tiers (low/medium/high), which was wrong in a way worth recording: the corpus contains only "high" (4,965) and "xhigh" (698), max_tokens is a constant 64000 on every span and so carries no signal, and "low"/"medium" appear nowhere at all. A derived value would have invented data the corpus has never held. Claude Code sends the effort it was configured with; this passes it through.

OutputType mirrors the same block: "json" when output_config.format is present, "text" when output_config exists without one, and EMPTY when there is no output_config at all -- the three-way distinction converter.py makes, where absent means "this request did not say".

type OTLPSpan

type OTLPSpan struct {
	TraceID      string // 32 hex
	SpanID       string // 16 hex
	ParentSpanID string // 16 hex, or ""
	Name         string
	Start, End   time.Time
	Attributes   map[string]any
	StatusError  string // "" = OK
}

OTLPSpan is one span ready for export: everything an OTLP exporter needs, with no SDK types, so this package stays free of I/O and unit-testable on values alone. The proxy turns it into an SDK span.

type Part

type Part struct {
	Type      string `json:"type"`
	Content   string `json:"content,omitempty"`   // text
	ID        string `json:"id,omitempty"`        // tool_call, tool_call_response
	Name      string `json:"name,omitempty"`      // tool_call
	Arguments string `json:"arguments,omitempty"` // tool_call: JSON, as a STRING
	Response  string `json:"response,omitempty"`  // tool_call_response: a STRING
}

Part is one piece of a message: text, a tool call, or a tool result.

Fields are omitempty so each part serialises to exactly the key set the corpus uses for its type -- a text part has no `id`, a tool_call has no `response`. An always-present empty key would be a new shape for every consumer to skip.

type ReconTurn

type ReconTurn struct {
	// Sequence is 1-based over the turns recovered for one conversation, in the order the
	// bodies carried them. DERIVED: it is an ordering, and it equals claude-record's
	// interaction.sequence only when no turn was missed at either end.
	Sequence int

	// Text is the human's prompt, wrappers stripped, whitespace-normalised.
	Text string

	// FirstSeen identifies the model call whose body first carried this turn -- the ordering
	// key, and the closest thing to a timestamp a reconstruction has. Set by the caller to
	// the span id or start time it is working from.
	FirstSeen string

	// Root is the conversation this turn belongs to (see ConversationRoot). Turns from
	// different roots are different conversations and must not be merged into one sequence.
	Root string

	// Prior marks a turn that was already HISTORY in the first call observed for its root:
	// it sits before that call's last assistant message, so it was typed before the proxy saw
	// the conversation. Live, that is a resumed session -- Claude Code gives a resume a new
	// session id, and its first request replays the old conversation, so without this mark
	// every resume re-counts the earlier session's turns (a second developer's corpus: one prompt chain
	// replayed across three session files). It is also what a session started before
	// recording began looks like, and, offline, a session whose early calls were lost.
	// The proxy cannot tell those apart, so the turn is MARKED, not dropped.
	Prior bool
}

ReconTurn is one recovered human turn.

func ReconstructTurns

func ReconstructTurns(calls []Call) []ReconTurn

ReconstructTurns recovers the human turns from a session's model calls.

Calls need not be sorted; they are ordered by Call.Order here. Turns are de-duplicated by text within a conversation root, because every subsequent call replays them.

Roots holding fewer than max(MinRootCalls, RootShare*len(calls)) calls are dropped as subagent traffic. Each surviving root is numbered independently from 1.

type Span

type Span struct {
	TraceID      string         `json:"trace_id"`
	SpanID       string         `json:"span_id"`
	ParentSpanID string         `json:"parent_span_id"`
	Name         string         `json:"name"`
	Kind         string         `json:"kind"`
	StartTime    string         `json:"start_time"`
	EndTime      string         `json:"end_time"`
	Attributes   map[string]any `json:"attributes"`
	ResourceAttr map[string]any `json:"resource_attributes"`
	Status       Status         `json:"status"`
}

Span is one recorded turn, shaped for the existing corpus. Field order in the struct is the field order in the JSON, which keeps a hand-diff against a corpus file readable.

func DerivedTurnSpan

func DerivedTurnSpan(sessionID, spanID, parentID string, t ReconTurn, start time.Time) Span

DerivedTurnSpan renders one reconstructed turn as a span.

start is the start time of the model call whose body first carried the turn -- the earliest moment the proxy can prove the turn existed by. It is NOT when the human typed, and the span carries no end time for exactly that reason: a zero-length span is honest about knowing one instant, where a fabricated duration would not be.

func WithDerivedTurns

func WithDerivedTurns(sessionID string, spans []Span) (out []Span)

WithDerivedTurns returns a session's observed spans followed by one derived span per human turn rebuilt from their request bodies. Wire does not store turns; this is how a reader of wire gets them, with the same reconstruction the proxy used to run inline.

Turn ids come from the session, the conversation root and the sequence number, so rebuilding a session twice gives the same ids. Fails open: if reconstruction panics, the observed spans are returned unchanged.

type Status

type Status struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

Status is a span's outcome.

type ToolUse

type ToolUse struct {
	CallID    string
	Name      string
	Arguments string // JSON, as a string -- same shape as the body carries it
}

ToolUse is one tool call lifted out of an assistant message body.

func ToolCalls

func ToolCalls(msgs []Message) []ToolUse

ToolCalls extracts every tool call from a translated output-message list.

The join key (gen_ai.tool.call.id, the toolu_bdrk_... value) is what makes this useful: the same id appears on claude-record's tool spans and in every later request body, so a reconstruction and an observation can be matched call-for-call.

type Turn

type Turn struct {
	SessionID string // becomes trace_id
	SpanID    string
	ParentID  string

	Model     string
	System    string // "anthropic" | "openai"
	Start     time.Time
	End       time.Time
	MaxTokens int
	Effort    string
	OutputTy  string // "json" | "text"

	// Bodies, already redacted by the caller. RequestBody is the PRISTINE client request
	// (pre-pipeline): a corpus of what the agent actually sent is the thing that is
	// reconstructable, and CG is the only place that still has it after compaction.
	RequestBody  string
	ResponseBody string
	OutputSchema string
	// ToolDefs is the tool schema the client advertised on this request. Present on 5,037
	// of the corpus's 5,680 chat spans -- the second-commonest body attribute after the
	// messages -- and it is what makes a turn interpretable: a tool_use block in the
	// response names a tool whose parameters live only here. CG has it for free, in the
	// same pristine request body.
	ToolDefs string

	// Usage. The three components are what claude-record cannot PRESERVE: it reads them from
	// Jaeger tags, sums them into gen_ai.usage.input_tokens, and keeps no column for the
	// split, so no corpus file can answer a cache question after the fact. CG has them at the
	// source. The sum stays identical either way (see InputTokens); the split is the addition,
	// and it is the one mooncake needs.
	FreshInput int
	CacheRead  int
	CacheWrite int
	Output     int
	StopReason string

	// Timing that only a proxy knows.
	UpstreamMS  int64
	FirstByteMS int64
	Rounds      int

	// Incompleteness. THIS IS LOAD-BEARING: two CG response paths (past the 16 MB retain
	// bound, and a continuation where both rounds truncated) yield no body at all, and the
	// stream tee is capped. A turn that quietly carries an empty response body is a corpus
	// defect nobody discovers until analysis; a turn that SAYS it is incomplete is data.
	// Never leave this empty to mean "fine" -- see IncompleteNone.
	Incomplete   string
	ResponseSize int

	Err string
}

Turn is everything this package needs to know about one proxied request. It is a plain data struct on purpose: the proxy fills it, the recorder writes it, and nothing in between needs a live handler. That is what makes the recorder unit-testable without standing up a proxy.

func (Turn) InputTokens

func (t Turn) InputTokens() int

InputTokens is what goes in gen_ai.usage.input_tokens: fresh + cache_read + cache_write.

THIS MATCHES claude-record EXACTLY, and it is worth writing down because an earlier version of this comment claimed the opposite. claude-record's converter.py has a total_input_tokens() helper that sums all three components for precisely the OTel-semconv reason -- Anthropic reports input_tokens as the uncached remainder only, so the full prompt size is the sum. The collector already does the right thing here.

So this column IS bit-comparable between the two recorders, which is a stronger parity claim than the one previously recorded here. Issue #17 is about a different layer: Claude Code's OTel metrics export, not this conversion.

The SPLIT is what mooncake needs, not the total. claude-record before 0.1.5 kept only the sum in the OTel file, so the split is not recoverable from those corpus files; since 0.1.5 both recorders write it under the same semconv names. CG has it at the source, on every turn.

func (*Turn) MarkIncomplete

func (t *Turn) MarkIncomplete(reason string)

MarkIncomplete is markIncomplete for the proxy, which fills a Turn from another package.

It exists because Turn.Incomplete is not a plain assignment: a turn can be incomplete for several reasons at once (a retain bound AND a multi-round continuation), the FIRST reason is the most specific and must survive, and later distinct reasons append comma-separated so an analysis can search for any one of them. A caller setting the field directly would have to reimplement that rule, and would eventually get it wrong in a way no test here would catch.

func (*Turn) Redact

func (t *Turn) Redact(bodyCap int)

Redact scrubs every free-text field on the turn in place, and records a cap hit as incompleteness rather than letting it pass silently.

Idempotent, so a double call cannot corrupt a turn.

GOROUTINE PLACEMENT IS THE SECURITY PROPERTY, and it is not this function's choice: this must be called on the WRITER goroutine, immediately before the bytes are written, never on the request goroutine. dash/event.go measured the cost of getting this wrong at ~53 ms, about 25% of a request, paid by the next request on a keep-alive connection. The ordering against the write is what guarantees no unscrubbed byte ever reaches disk.

func (Turn) ToOTLP

func (t Turn) ToOTLP() OTLPSpan

ToOTLP renders the turn for export. It starts from ToSpan, so the two renderings cannot drift on any attribute they share, and adds what OTLP and Phoenix need.

func (Turn) ToSpan

func (t Turn) ToSpan() Span

ToSpan renders the turn. Bodies must already be redacted; see Redact.

type WireCall

type WireCall struct {
	Path        string
	Headers     http.Header // as the client sent them; Wire removes credentials
	Request     []byte
	Response    []byte
	ResponseSSE bool
	Status      int
	Start, End  time.Time
}

WireCall is one proxied call, as the proxy hands it over. Bodies are RAW; Wire redacts them.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL