Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

refactor(claude): parse each API body once; keep ci exec callers' Claude settings

Kyle Elliott8424782c15dd
diff --git a/cli/beacon/internal/ci/harness.go b/cli/beacon/internal/ci/harness.go
index 65df04ae..a99c90f2 100644
--- a/cli/beacon/internal/ci/harness.go
+++ b/cli/beacon/internal/ci/harness.go
@@ -40,13 +40,18 @@ func ClaudeEnv(base []string, endpoint string) []string {
delete(env, "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT")
env["OTEL_LOG_TOOL_DETAILS"] = "1"
env["OTEL_LOG_USER_PROMPTS"] = "1"
- // The same WebFetch page capture an endpoint install enables; ci exec runs the same
- // collector config, so its claude_api_body processor drops every other body. A value the
- // caller set (0, or file:<dir>) is theirs.
- if _, configured := env["OTEL_LOG_RAW_API_BODIES"]; !configured {
- env["OTEL_LOG_RAW_API_BODIES"] = "1"
+ for key, value := range claudeEnvDefaults {
+ if strings.TrimSpace(env[key]) == "" {
+ env[key] = value
+ }
}
+ return flattenEnv(env)
+}
+// claudeEnvDefaults are set only when the caller has not set them. Someone who has deliberately
+// tuned these has a reason, and this is a wrapper around their session rather than an owner of
+// their telemetry configuration.
+var claudeEnvDefaults = map[string]string{
// Export on a timer that fits the session, instead of relying on the flush at shutdown.
//
// The OpenTelemetry default metric interval is 60 seconds, and `ci exec` wraps sessions that
@@ -58,22 +63,16 @@ func ClaudeEnv(base []string, endpoint string) []string {
//
// A shutdown flush is still the backstop and still has to work. This just stops it being the only
// thing between a captured session and an empty log.
- //
- // Set only when the caller has not. Someone who has deliberately tuned these has a reason, and
- // this is a wrapper around their session rather than an owner of their telemetry configuration.
- for key, value := range map[string]string{
- "OTEL_METRIC_EXPORT_INTERVAL": "5000",
- // The batch processors default to 1s and 5s respectively, which is already inside a short
- // session -- pinned anyway so the whole pipeline's timing is stated in one place rather than
- // inherited from three different SDK defaults.
- "OTEL_BLRP_SCHEDULE_DELAY": "1000",
- "OTEL_BSP_SCHEDULE_DELAY": "1000",
- } {
- if strings.TrimSpace(env[key]) == "" {
- env[key] = value
- }
- }
- return flattenEnv(env)
+ "OTEL_METRIC_EXPORT_INTERVAL": "5000",
+ // The batch processors default to 1s and 5s respectively, which is already inside a short
+ // session -- pinned anyway so the whole pipeline's timing is stated in one place rather than
+ // inherited from three different SDK defaults.
+ "OTEL_BLRP_SCHEDULE_DELAY": "1000",
+ "OTEL_BSP_SCHEDULE_DELAY": "1000",
+ // The same WebFetch page capture an endpoint install enables. ci exec writes the same collector
+ // config, so its claude_api_body processor drops every other body. 0 or file:<dir> is the
+ // caller's.
+ "OTEL_LOG_RAW_API_BODIES": "1",
}
func BuildHarnessConfig(base []string, harnessList, grpcEndpoint, baseDir string, run *schema.RunInfo) (HarnessConfig, error) {
@@ -90,6 +89,13 @@ func BuildHarnessConfig(base []string, harnessList, grpcEndpoint, baseDir string
for _, harness := range harnesses {
switch harness {
case HarnessClaude:
+ // ClaudeEnv keeps a caller's value for these, so it has to be given the caller's.
+ // RunChild lays this env over the caller's own, so leaving them out would overwrite it.
+ for key := range claudeEnvDefaults {
+ if value := baseEnv[key]; strings.TrimSpace(value) != "" {
+ env[key] = value
+ }
+ }
env = envMap(ClaudeEnv(flattenEnv(env), grpcEndpoint))
case HarnessCodex:
codexHome := filepath.Join(baseDir, "codex-home")
diff --git a/cli/beacon/internal/ci/harness_test.go b/cli/beacon/internal/ci/harness_test.go
index ac6cd1a0..8cbc5aa7 100644
--- a/cli/beacon/internal/ci/harness_test.go
+++ b/cli/beacon/internal/ci/harness_test.go
@@ -23,12 +23,34 @@ func TestClaudeEnvIncludesDetailedToolAndPromptLogging(t *testing.T) {
}
}
-func TestClaudeEnvKeepsTheCallersRawBodyPolicy(t *testing.T) {
+// ci exec builds the child's env through BuildHarnessConfig and lays it over the caller's own, so a
+// value the caller set survives only if BuildHarnessConfig hands it to ClaudeEnv.
+func TestBuildHarnessConfigKeepsTheCallersClaudeDefaults(t *testing.T) {
for _, policy := range []string{"0", "file:/tmp/claude-bodies"} {
- env := envMap(ClaudeEnv([]string{"OTEL_LOG_RAW_API_BODIES=" + policy}, "http://127.0.0.1:4317"))
- if got := env["OTEL_LOG_RAW_API_BODIES"]; got != policy {
+ base := []string{"OTEL_LOG_RAW_API_BODIES=" + policy, "OTEL_METRIC_EXPORT_INTERVAL=30000", "SECRET_TOKEN=not-copied"}
+ cfg, err := BuildHarnessConfig(base, "claude", "http://127.0.0.1:4317", t.TempDir(), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := cfg.Env["OTEL_LOG_RAW_API_BODIES"]; got != policy {
t.Fatalf("OTEL_LOG_RAW_API_BODIES = %q, want the caller's %q", got, policy)
}
+ if got := cfg.Env["OTEL_METRIC_EXPORT_INTERVAL"]; got != "30000" {
+ t.Fatalf("OTEL_METRIC_EXPORT_INTERVAL = %q, want the caller's 30000", got)
+ }
+ if got := cfg.Env["OTEL_BSP_SCHEDULE_DELAY"]; got != "1000" {
+ t.Fatalf("OTEL_BSP_SCHEDULE_DELAY = %q, want the default for a key the caller left unset", got)
+ }
+ if _, copied := cfg.Env["SECRET_TOKEN"]; copied {
+ t.Fatal("BuildHarnessConfig copied the caller's whole environment")
+ }
+ }
+ cfg, err := BuildHarnessConfig(nil, "claude", "http://127.0.0.1:4317", t.TempDir(), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := cfg.Env["OTEL_LOG_RAW_API_BODIES"]; got != "1" {
+ t.Fatalf("OTEL_LOG_RAW_API_BODIES = %q, want 1 by default", got)
}
}
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/claude_api_body.go b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/claude_api_body.go
index c44cb280..6deb7e40 100644
--- a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/claude_api_body.go
+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/claude_api_body.go
@@ -28,92 +28,87 @@ const (
claudeWebFetchToolName = "WebFetch"
)
-// SanitizeClaudeAPIBody applies Beacon's policy for Claude Code's API body events
-// (OTEL_LOG_RAW_API_BODIES) to attrs in place, and reports whether the record is dropped. It is
-// keyed on the event name, never the harness name, so the Agent SDK or anything else that emits
-// these events under another service name is held to the same policy.
+// Beacon's policy for Claude Code's API body events (OTEL_LOG_RAW_API_BODIES) is keyed on the
+// event name, never the harness name, so the Agent SDK or anything else that emits these events
+// under another service name is held to it too.
//
// A body can carry the system prompt, the whole conversation, tool schemas and tool results. The
// one Beacon keeps is the WebFetch summarizer request, the only model call that carries the
-// fetched page: its user-role text moves to ClaudeWebFetchInputAttr, and body and body_ref are
-// removed. Every other body event, request or response, is dropped -- claude_code.api_request
-// already records the call -- and so is a summarizer request with no text left to keep.
-//
-// It is idempotent: a record the claude_api_body processor already rewrote passes through
-// unchanged.
-func SanitizeClaudeAPIBody(attrs map[string]interface{}, recordBody string) (drop bool) {
- name := ClaudeLogEventName(attrs, recordBody)
- if name != ClaudeAPIRequestBody && name != ClaudeAPIResponseBody {
- return false
+// fetched page, and of that only its user-role text. Every other body event, request or response,
+// is dropped -- claude_code.api_request already records the call -- and so is a summarizer request
+// with no text left to keep.
+
+func isClaudeAPIBody(eventName string) bool {
+ return eventName == ClaudeAPIRequestBody || eventName == ClaudeAPIResponseBody
+}
+
+func isClaudeWebFetchSummarizerRequest(eventName, querySource string) bool {
+ return eventName == ClaudeAPIRequestBody && querySource == claudeWebFetchApplyQuerySource
+}
+
+type claudeWebFetchInput struct {
+ text string
+ truncated bool
+}
+
+// takeClaudeAPIBody removes the body, body_ref and summarizer input of a Claude Code API body
+// event from attrs, and returns the text Beacon keeps: the summarizer request's user text, or
+// nothing. isBody reports whether eventName is a body event at all. A record the claude_api_body
+// processor already rewrote carries the text in ClaudeWebFetchInputAttr, so its body is not
+// parsed again.
+func takeClaudeAPIBody(attrs map[string]interface{}, eventName string) (input claudeWebFetchInput, isBody bool) {
+ if !isClaudeAPIBody(eventName) {
+ return claudeWebFetchInput{}, false
}
body, _ := attrs["body"].(string)
- delete(attrs, "body")
- delete(attrs, "body_ref")
- if name != ClaudeAPIRequestBody || FirstString(attrs, "query_source") != claudeWebFetchApplyQuerySource {
- return true
+ input.text, _ = attrs[ClaudeWebFetchInputAttr].(string)
+ input.truncated, _ = BoolAttr(attrs, ClaudeWebFetchInputTruncatedAttr)
+ for _, key := range []string{"body", "body_ref", ClaudeWebFetchInputAttr, ClaudeWebFetchInputTruncatedAttr} {
+ delete(attrs, key)
}
- if text, _ := attrs[ClaudeWebFetchInputAttr].(string); text != "" {
- return false
+ if !isClaudeWebFetchSummarizerRequest(eventName, FirstString(attrs, "query_source")) {
+ return claudeWebFetchInput{}, true
}
- truncated, _ := BoolAttr(attrs, "body_truncated")
- text, partial, ok := claudeUserText(body, truncated)
- if !ok || text == "" {
- return true
+ if input.text != "" {
+ return input, true
}
- attrs[ClaudeWebFetchInputAttr] = text
- if partial {
- attrs[ClaudeWebFetchInputTruncatedAttr] = true
+ bodyTruncated, _ := BoolAttr(attrs, "body_truncated")
+ text, partial, ok := claudeUserText(body, bodyTruncated)
+ if !ok {
+ return claudeWebFetchInput{}, true
}
- return false
+ return claudeWebFetchInput{text: text, truncated: partial}, true
}
-// SanitizeClaudeAPIBodyRecord is SanitizeClaudeAPIBody on a log record. The claude_api_body
-// processor calls it so the policy holds before any exporter sees the record, including ones such
-// as splunk_hec that forward OTLP attributes as they arrive.
+// SanitizeClaudeAPIBodyRecord applies the API body policy to a log record in place, and reports
+// whether the record is dropped. A kept summarizer request leaves with its text in
+// ClaudeWebFetchInputAttr in place of body and body_ref. The claude_api_body processor calls it so
+// the policy holds before any exporter sees the record, including ones such as splunk_hec that
+// forward OTLP attributes as they arrive.
func SanitizeClaudeAPIBodyRecord(record plog.LogRecord) (drop bool) {
attrs := record.Attributes()
- name := map[string]interface{}{}
+ eventName := ""
if value, ok := attrs.Get("event.name"); ok {
- name["event.name"] = value.AsString()
+ eventName = value.AsString()
}
- switch ClaudeLogEventName(name, record.Body().AsString()) {
- case ClaudeAPIRequestBody, ClaudeAPIResponseBody:
- default:
+ name := claudeLogEventName(eventName, record.Body().AsString())
+ if !isClaudeAPIBody(name) {
return false
}
- sanitized := AttrsToMap(attrs)
- if SanitizeClaudeAPIBody(sanitized, record.Body().AsString()) {
+ input, _ := takeClaudeAPIBody(AttrsToMap(attrs), name)
+ if input.text == "" {
return true
}
- attrs.Remove("body")
- attrs.Remove("body_ref")
- if text, ok := sanitized[ClaudeWebFetchInputAttr].(string); ok {
- attrs.PutStr(ClaudeWebFetchInputAttr, text)
+ for _, key := range []string{"body", "body_ref", ClaudeWebFetchInputTruncatedAttr} {
+ attrs.Remove(key)
}
- if truncated, _ := BoolAttr(sanitized, ClaudeWebFetchInputTruncatedAttr); truncated {
+ attrs.PutStr(ClaudeWebFetchInputAttr, input.text)
+ if input.truncated {
attrs.PutBool(ClaudeWebFetchInputTruncatedAttr, true)
}
return false
}
-type claudeWebFetchInput struct {
- text string
- truncated bool
-}
-
-// takeClaudeWebFetchInput removes the summarizer input from attrs so that raw.attributes does not
-// hold a second copy of the page beside gen_ai.tool.call.result.
-func takeClaudeWebFetchInput(attrs map[string]interface{}, recordBody string) claudeWebFetchInput {
- if ClaudeLogEventName(attrs, recordBody) != ClaudeAPIRequestBody {
- return claudeWebFetchInput{}
- }
- text, _ := attrs[ClaudeWebFetchInputAttr].(string)
- truncated, _ := BoolAttr(attrs, ClaudeWebFetchInputTruncatedAttr)
- delete(attrs, ClaudeWebFetchInputAttr)
- delete(attrs, ClaudeWebFetchInputTruncatedAttr)
- return claudeWebFetchInput{text: text, truncated: truncated}
-}
-
// normalizeClaudeWebFetchInput records the summarizer input as what it is: content the WebFetch
// tool brought into the agent's context. It is third-party text, not something the user typed, so
// it goes to gen_ai.tool.call.result under the WebFetch tool name -- where
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/claude_api_body_test.go b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/claude_api_body_test.go
index 6fb3a8c6..df89d443 100644
--- a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/claude_api_body_test.go
+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/claude_api_body_test.go
@@ -19,7 +19,7 @@ var privateBodyParts = []string{"system-private", "assistant-private", "file-pri
func claudeBodyRecord(eventName, querySource, body string) plog.LogRecord {
record := plog.NewLogRecord()
record.Body().SetStr("claude_code." + eventName)
- record.SetTimestamp(pcommonTimestamp(1700000000))
+ record.SetTimestamp(pcommon.NewTimestampFromTime(time.Unix(1700000000, 0).UTC()))
attrs := record.Attributes()
attrs.PutStr("service.name", "claude-code")
attrs.PutStr("service.version", "2.1.291")
@@ -37,6 +37,14 @@ func claudeBodyRecord(eventName, querySource, body string) plog.LogRecord {
return record
}
+// convertedLog runs record through EventsFromLogs, the path the exporters take, and reports whether
+// it survived as an event.
+func convertedLog(record plog.LogRecord) bool {
+ logs := plog.NewLogs()
+ record.CopyTo(logs.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty())
+ return len(NewConverter(Options{}).EventsFromLogs(logs)) == 1
+}
+
func encodedEvent(t *testing.T, event Event) string {
t.Helper()
encoded, err := json.Marshal(event)
@@ -48,7 +56,7 @@ func encodedEvent(t *testing.T, event Event) string {
func TestClaudeWebFetchSummarizerInputIsRecordedAsAWebFetchResult(t *testing.T) {
record := claudeBodyRecord("api_request_body", claudeWebFetchApplyQuerySource, summarizerBody)
- if ShouldDropLog(nil, record) {
+ if !convertedLog(record) {
t.Fatal("the WebFetch summarizer request was dropped")
}
event := NewConverter(Options{}).EventFromLog(nil, record)
@@ -110,12 +118,15 @@ func TestClaudeAPIBodiesOtherThanTheSummarizerRequestAreDropped(t *testing.T) {
"summarizer, top-level array": claudeBodyRecord("api_request_body", claudeWebFetchApplyQuerySource, `[{"role":"user","content":"x"}]`),
"summarizer, empty text block": claudeBodyRecord("api_request_body", claudeWebFetchApplyQuerySource, `{"messages":[{"role":"user","content":[{"type":"text","text":""}]}]}`),
}
+ claimed := claudeBodyRecord("api_request_body", "sdk", "")
+ claimed.Attributes().PutStr(ClaudeWebFetchInputAttr, "PAGE-CANARY")
+ cases["main request claiming processed input"] = claimed
for name, record := range cases {
t.Run(name, func(t *testing.T) {
- if !ShouldDropLog(nil, record) {
+ if convertedLog(record) {
t.Fatal("body event was kept")
}
- // A caller that converts without asking ShouldDropLog still gets no body.
+ // A caller that converts one record directly still gets no body.
encoded := encodedEvent(t, NewConverter(Options{}).EventFromLog(nil, record))
for _, forbidden := range append(privateBodyParts, "private-body", "PARTIAL-PAGE", "PAGE-CANARY", "/private/body.json") {
if strings.Contains(encoded, forbidden) {
@@ -135,7 +146,7 @@ func TestClaudeAPIBodyPolicyIsKeyedOnTheEventName(t *testing.T) {
record.Attributes().Remove("event.name")
return record
}
- if !ShouldDropLog(nil, sdk("sdk")) {
+ if convertedLog(sdk("sdk")) {
t.Fatal("an Agent SDK main-loop body was kept")
}
event := NewConverter(Options{}).EventFromLog(nil, sdk(claudeWebFetchApplyQuerySource))
@@ -166,7 +177,7 @@ func TestClaudeTruncatedSummarizerBodyKeepsTheReadablePrefix(t *testing.T) {
t.Run(name, func(t *testing.T) {
record := claudeBodyRecord("api_request_body", claudeWebFetchApplyQuerySource, body)
record.Attributes().PutStr("body_truncated", "true")
- if ShouldDropLog(nil, record) {
+ if !convertedLog(record) {
t.Fatal("a truncated summarizer request was dropped with its page prefix")
}
event := NewConverter(Options{}).EventFromLog(nil, record)
@@ -184,7 +195,7 @@ func TestClaudeTruncatedSummarizerBodyKeepsTheReadablePrefix(t *testing.T) {
}
cutBeforeText := claudeBodyRecord("api_request_body", claudeWebFetchApplyQuerySource, full[:strings.Index(full, `"text":"Web`)])
cutBeforeText.Attributes().PutBool("body_truncated", true)
- if !ShouldDropLog(nil, cutBeforeText) {
+ if convertedLog(cutBeforeText) {
t.Fatal("a body cut before any user text was kept")
}
}
@@ -238,7 +249,3 @@ func TestSanitizeClaudeAPIBodyRecordMatchesTheConverter(t *testing.T) {
t.Fatal("the processor changed a record that is not an API body")
}
}
-
-func pcommonTimestamp(seconds int64) pcommon.Timestamp {
- return pcommon.Timestamp(uint64(time.Unix(seconds, 0).UnixNano()))
-}
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go
index 9b7ea6b3..4cea8ca5 100644
--- a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go
+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go
@@ -111,7 +111,9 @@ func (c Converter) EventsFromLogs(logs plog.Logs) []Event {
if ShouldDropLog(resourceAttrs, record) {
continue
}
- events = append(events, c.EventFromLog(resourceAttrs, record))
+ if event, keep := c.eventFromLog(resourceAttrs, record); keep {
+ events = append(events, event)
+ }
}
}
}
@@ -158,8 +160,9 @@ func (c Converter) EventsFromMetrics(metrics pmetric.Metrics) []Event {
func ShouldDropLog(resourceAttrs map[string]interface{}, record plog.LogRecord) bool {
attrs := MergeMaps(resourceAttrs, AttrsToMap(record.Attributes()))
- if SanitizeClaudeAPIBody(attrs, record.Body().AsString()) {
- return true
+ if name := ClaudeLogEventName(attrs, record.Body().AsString()); isClaudeAPIBody(name) {
+ // A summarizer request is decided once its body is parsed, in eventFromLog.
+ return !isClaudeWebFetchSummarizerRequest(name, FirstString(attrs, "query_source"))
}
harness := HarnessName(attrs, record.Body().AsString())
if isCodexHarness(harness) {
@@ -305,10 +308,16 @@ func shouldDropCopilotMetric(resourceAttrs map[string]interface{}, name string,
}
func (c Converter) EventFromLog(resourceAttrs map[string]interface{}, record plog.LogRecord) Event {
+ event, _ := c.eventFromLog(resourceAttrs, record)
+ return event
+}
+
+// eventFromLog converts a log record, and reports whether the event is worth keeping: it is not
+// for a Claude Code API body event that leaves no text behind once its body is removed.
+func (c Converter) eventFromLog(resourceAttrs map[string]interface{}, record plog.LogRecord) (Event, bool) {
attrs := MergeMaps(resourceAttrs, AttrsToMap(record.Attributes()))
body := record.Body().AsString()
- SanitizeClaudeAPIBody(attrs, body)
- webFetchInput := takeClaudeWebFetchInput(attrs, body)
+ webFetchInput, isAPIBody := takeClaudeAPIBody(attrs, ClaudeLogEventName(attrs, body))
ts := Timestamp(record.Timestamp().AsTime())
// An action the record states outright is observed by definition; only the fallback has to
// account for how it got there.
@@ -339,7 +348,7 @@ func (c Converter) EventFromLog(resourceAttrs map[string]interface{}, record plo
// Last, so it sees the action and category the normalizers settled on rather
// than the ones InferAction guessed.
c.PromoteRetainedContent(&event, attrs, body)
- return event
+ return event, !isAPIBody || webFetchInput.text != ""
}
func (c Converter) EventFromSpan(resourceAttrs map[string]interface{}, span ptrace.Span) Event {
@@ -652,10 +661,14 @@ func (c Converter) NormalizeClaudeLogEvent(event *Event, attrs map[string]interf
}
func ClaudeLogEventName(attrs map[string]interface{}, body string) string {
+ return claudeLogEventName(FirstString(attrs, "event.name"), body)
+}
+
+func claudeLogEventName(eventName, body string) string {
if normalized := strings.ToLower(strings.TrimSpace(body)); strings.HasPrefix(normalized, "claude_code.") {
return normalized
}
- normalized := strings.ToLower(strings.TrimSpace(FirstString(attrs, "event.name")))
+ normalized := strings.ToLower(strings.TrimSpace(eventName))
if strings.HasPrefix(normalized, "claude_code.") {
return normalized
}