Skip to content

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

fix(claude): retain live Bash output

Kyle Elliottbfd75fc7dc6a
diff --git a/cli/beacon-hooks/cmd/endpoint_events.go b/cli/beacon-hooks/cmd/endpoint_events.go
index 0a9780c4..7d4126ef 100644
--- a/cli/beacon-hooks/cmd/endpoint_events.go
+++ b/cli/beacon-hooks/cmd/endpoint_events.go
@@ -7,6 +7,7 @@ import (
"fmt"
"os"
"path/filepath"
+ "regexp"
"strconv"
"strings"
"time"
@@ -436,6 +437,69 @@ func applyIngestedToolResult(fields map[string]interface{}, action, toolName str
}
}
+// claudeBashExitLine is the first line Claude Code writes into a failed Bash call's `error` when
+// the command ran and exited. Its absence means the shell itself could not be started.
+var claudeBashExitLine = regexp.MustCompile(`^Exit code (-?\d+)$`)
+
+// applyClaudeBashResult maps the result of Claude Code's Bash tool onto the command field, and
+// reports whether the payload is a failure of a command that ran and exited.
+//
+// The two outcomes arrive in different shapes. A success (`PostToolUse`) carries `tool_response`
+// with `stdout` and `stderr` as separate strings and no exit code. They are stored stdout first,
+// then stderr, so the order in which the command interleaved them is lost. A failure
+// (`PostToolUseFailure`) carries no tool response, only a top-level `error`: a first line
+// `Exit code N`, then the output with both streams interleaved as Claude saw it. That line is
+// the only exit code Claude reports, so it is parsed rather than synthesized. An `error` without
+// it is a shell that never started; that is a message, not command output, and is not recorded.
+//
+// Claude reports an interrupted command as a success with `interrupted` set, or as a failure with
+// `is_interrupt`, and its output is partial either way, so that is recorded beside it.
+func applyClaudeBashResult(fields, input map[string]interface{}, toolName string, toolResponse map[string]interface{}) bool {
+ if !strings.EqualFold(strings.TrimSpace(toolName), "bash") {
+ return false
+ }
+ var output string
+ var exitCode int
+ exited := false
+ if errText := getFirstStr(input, "error"); errText != "" {
+ firstLine, rest, _ := strings.Cut(errText, "\n")
+ match := claudeBashExitLine.FindStringSubmatch(strings.TrimSpace(firstLine))
+ if match == nil {
+ return false
+ }
+ code, err := strconv.Atoi(match[1])
+ if err != nil {
+ return false
+ }
+ output, exitCode, exited = rest, code, true
+ } else if toolResponse != nil {
+ output = getFirstStr(toolResponse, "stdout")
+ if stderr := getFirstStr(toolResponse, "stderr"); stderr != "" {
+ if output != "" && !strings.HasSuffix(output, "\n") {
+ output += "\n"
+ }
+ output += stderr
+ }
+ }
+ command := mutableChild(fields["command"])
+ if exited {
+ command["exit_code"] = exitCode
+ }
+ if output != "" {
+ command["output"] = output
+ if _, exists := fields["content"]; !exists {
+ fields["content"] = retainedContentFields(output)
+ }
+ }
+ if len(command) > 0 {
+ fields["command"] = command
+ }
+ if interrupted, _ := toolResponse["interrupted"].(bool); interrupted || input["is_interrupt"] == true {
+ fields["raw"] = mergeNested(fields["raw"], map[string]interface{}{"claude_interrupted": true})
+ }
+ return exited
+}
+
// toolCallIDFromEnvelope reads the runtime's own identifier for one tool
// invocation out of a hook payload's top level.
//
diff --git a/cli/beacon-hooks/cmd/post_tool.go b/cli/beacon-hooks/cmd/post_tool.go
index 6e00878d..780d95fd 100644
--- a/cli/beacon-hooks/cmd/post_tool.go
+++ b/cli/beacon-hooks/cmd/post_tool.go
@@ -433,6 +433,13 @@ func emitPostToolObserved(logger *logging.Logger, input map[string]interface{})
for key, value := range toolFieldsWithResponse(toolName, toolInput, toolResponse) {
fields[key] = value
}
+ // A Bash command that ran and exited non-zero is recorded the way the OTLP and transcript paths
+ // record the same call: command.executed, high severity. As tool.failed it would never match
+ // their copies, and each copy would keep the command's output in the log.
+ if platformFlag == "claude" && applyClaudeBashResult(fields, input, toolName, toolResponse) {
+ emitHookEvent(logger, "command.executed", "command", "high", "Shell command failed", input, fields)
+ return
+ }
// Kimi Code's result is read before the shared failure branch below, unlike every other
// runtime's, and the ordering is the whole point. Kimi Code reports a failure by sending
// `PostToolUseFailure` -- the exact spelling that branch matches -- so it is the branch that
diff --git a/cli/beacon-hooks/cmd/post_tool_claude_bash_test.go b/cli/beacon-hooks/cmd/post_tool_claude_bash_test.go
new file mode 100644
index 00000000..721fc8e5
--- /dev/null
+++ b/cli/beacon-hooks/cmd/post_tool_claude_bash_test.go
@@ -0,0 +1,224 @@
+package cmd
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+// claudeBashFailurePayload is the PostToolUseFailure payload Claude Code's hook documentation
+// gives for a failed Bash command: no tool_response, and the exit status and output in `error`.
+func claudeBashFailurePayload(errText string) map[string]interface{} {
+ return map[string]interface{}{
+ "session_id": "s-743",
+ "cwd": "/repo",
+ "permission_mode": "default",
+ "hook_event_name": "PostToolUseFailure",
+ "tool_name": "Bash",
+ "tool_input": map[string]interface{}{"command": "npm test", "description": "Run test suite"},
+ "tool_use_id": "toolu_743",
+ "error": errText,
+ "is_interrupt": false,
+ "duration_ms": float64(4187),
+ }
+}
+
+// runClaudePostTool runs one Claude payload through the post-tool command against a log that
+// already holds the given lines, and returns the log's path and every event in it.
+func runClaudePostTool(t *testing.T, payload map[string]interface{}, existing ...string) (string, []map[string]interface{}) {
+ t.Helper()
+ setupHookConfigDirs(t)
+ platformFlag = "claude"
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)
+ if len(existing) > 0 {
+ var data []byte
+ for _, line := range existing {
+ data = append(data, line+"\n"...)
+ }
+ if err := os.WriteFile(logPath, data, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ runHookWithInput(t, runPostTool, payload)
+ return logPath, endpointEvents(t, logPath)
+}
+
+// claudeCommandLine is a command.executed line for the call in claudeBashFailurePayload, in the
+// shape another capture path writes it.
+func claudeCommandLine(t *testing.T, fields map[string]interface{}) string {
+ t.Helper()
+ event := map[string]interface{}{
+ "timestamp": time.Now().UTC().Format(time.RFC3339Nano),
+ "vendor": "beacon",
+ "product": "endpoint-agent",
+ "schema_version": "1.0",
+ "event": map[string]interface{}{"action": "command.executed", "category": "command"},
+ "tool": map[string]interface{}{"name": "Bash", "command": "npm test"},
+ "gen_ai": map[string]interface{}{"tool": map[string]interface{}{"call": map[string]interface{}{"id": "toolu_743"}, "name": "Bash"}},
+ }
+ for key, value := range fields {
+ event[key] = value
+ }
+ data, err := json.Marshal(event)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(data)
+}
+
+func TestClaudeBashPostToolCapturesTypedResult(t *testing.T) {
+ payload := postToolPayload("Bash", map[string]interface{}{"command": "sh scripts/probe.sh"},
+ map[string]interface{}{"stdout": "Shell output marker.\n", "stderr": "warning\n", "interrupted": false, "isImage": false})
+ payload["tool_use_id"] = "toolu_live_bash_1"
+ raw, event := runPostToolOnce(t, "claude", payload)
+
+ if event.Event.Action != "command.executed" || event.Severity != "info" {
+ t.Fatalf("event = %s/%s, want info command.executed", event.Event.Action, event.Severity)
+ }
+ if event.Command == nil || event.Command.Command != "sh scripts/probe.sh" ||
+ event.Command.Output != "Shell output marker.\nwarning\n" {
+ t.Fatalf("command = %+v, want command and captured stdout/stderr", event.Command)
+ }
+ if event.Command.ExitCode != nil {
+ t.Fatalf("command.exit_code = %v, want absent because a success reports no exit code", *event.Command.ExitCode)
+ }
+ if toolCallResult(event) != nil {
+ t.Fatalf("gen_ai.tool.call.result = %#v, want no duplicate of command.output", toolCallResult(event))
+ }
+ if event.GenAI == nil || event.GenAI.Tool == nil || event.GenAI.Tool.Call == nil || event.GenAI.Tool.Call.ID != "toolu_live_bash_1" {
+ t.Fatalf("gen_ai = %+v, want Claude's tool_use_id as the call id", event.GenAI)
+ }
+ if _, ok := raw["raw"]; ok {
+ t.Fatalf("raw = %v, want none for a command that was not interrupted", raw["raw"])
+ }
+}
+
+// stdout and stderr arrive as separate strings; they are stored stdout first, joined by one
+// newline when stdout does not already end in one.
+func TestClaudeBashPostToolJoinsStreams(t *testing.T) {
+ cases := []struct {
+ name, stdout, stderr, want string
+ }{
+ {"stdout without a trailing newline", "out", "err", "out\nerr"},
+ {"stdout with a trailing newline", "out\n", "err\n", "out\nerr\n"},
+ {"stderr only", "", "err\n", "err\n"},
+ {"stdout only", "out", "", "out"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ _, event := runPostToolOnce(t, "claude", postToolPayload("Bash",
+ map[string]interface{}{"command": "sh scripts/probe.sh"},
+ map[string]interface{}{"stdout": tc.stdout, "stderr": tc.stderr, "interrupted": false}))
+ if event.Command == nil || event.Command.Output != tc.want {
+ t.Fatalf("command = %+v, want output %q", event.Command, tc.want)
+ }
+ })
+ }
+}
+
+// A failed command reaches the hook with its exit status and interleaved output in `error`. It is
+// recorded as the command execution it was, with the exit code Claude reported, rather than as a
+// tool failure carrying nothing.
+func TestClaudeBashFailureRecordsExitCodeAndOutput(t *testing.T) {
+ _, event := runPostToolOnce(t, "claude", claudeBashFailurePayload("Exit code 1\nError: Cannot find module 'express'"))
+
+ if event.Event.Action != "command.executed" || event.Severity != "high" {
+ t.Fatalf("event = %s/%s, want high-severity command.executed", event.Event.Action, event.Severity)
+ }
+ if event.Command == nil || event.Command.Command != "npm test" || event.Command.Output != "Error: Cannot find module 'express'" {
+ t.Fatalf("command = %+v, want the command and its output without the exit line", event.Command)
+ }
+ if event.Command.ExitCode == nil || *event.Command.ExitCode != 1 {
+ t.Fatalf("command.exit_code = %v, want 1 from Claude's exit line", event.Command.ExitCode)
+ }
+ if event.Content == nil || !event.Content.Included || event.Content.Bytes != len("Error: Cannot find module 'express'") {
+ t.Fatalf("content = %+v, want a marker describing the retained output", event.Content)
+ }
+}
+
+// Without an `Exit code N` line the shell never started, so there is no command output to keep.
+func TestClaudeBashFailureWithoutExitLineStaysAToolFailure(t *testing.T) {
+ _, event := runPostToolOnce(t, "claude", claudeBashFailurePayload("spawn /bin/zsh ENOENT"))
+
+ if event.Event.Action != "tool.failed" || event.Severity != "high" {
+ t.Fatalf("event = %s/%s, want high-severity tool.failed", event.Event.Action, event.Severity)
+ }
+ if event.Command != nil && (event.Command.Output != "" || event.Command.ExitCode != nil) {
+ t.Fatalf("command = %+v, want no output or exit code for a shell that never started", event.Command)
+ }
+}
+
+// An interrupted command's output is partial, which a reader has to be told.
+func TestClaudeBashInterruptedOutputIsMarked(t *testing.T) {
+ t.Run("success with interrupted", func(t *testing.T) {
+ raw, event := runPostToolOnce(t, "claude", postToolPayload("Bash",
+ map[string]interface{}{"command": "sleep 60"},
+ map[string]interface{}{"stdout": "partial", "stderr": "", "interrupted": true}))
+ if event.Event.Action != "command.executed" || event.Command == nil || event.Command.Output != "partial" {
+ t.Fatalf("event = %s command = %+v, want command.executed with the partial output", event.Event.Action, event.Command)
+ }
+ if got := nested(t, raw, "raw")["claude_interrupted"]; got != true {
+ t.Fatalf("raw.claude_interrupted = %v, want true", got)
+ }
+ })
+ t.Run("failure with is_interrupt", func(t *testing.T) {
+ payload := claudeBashFailurePayload("Exit code 130\npartial")
+ payload["is_interrupt"] = true
+ raw, _ := runPostToolOnce(t, "claude", payload)
+ if got := nested(t, raw, "raw")["claude_interrupted"]; got != true {
+ t.Fatalf("raw.claude_interrupted = %v, want true", got)
+ }
+ })
+}
+
+// Claude Code's OTLP tool_result for the same call carries no output. Whichever report is written
+// first, the hook's output must reach the log.
+func TestClaudeBashOutputSurvivesAnEarlierCollectorReport(t *testing.T) {
+ payload := postToolPayload("Bash", map[string]interface{}{"command": "npm test"},
+ map[string]interface{}{"stdout": "ok\n", "stderr": "", "interrupted": false})
+ otlp := map[string]interface{}{
+ "harness": map[string]interface{}{"name": "claude_code", "collection_method": "otlp"},
+ "command": map[string]interface{}{"command": "npm test", "duration_ms": 24},
+ }
+ cases := []struct {
+ name string
+ session map[string]interface{}
+ }{
+ // The collector does not populate the working directory for Claude Code today.
+ {"as the collector writes it", map[string]interface{}{"id": "s-743"}},
+ {"with the hook's working directory", map[string]interface{}{"id": "s-743", "working_directory": "/repo"}},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ otlp["session"] = tc.session
+ _, events := runClaudePostTool(t, payload, claudeCommandLine(t, otlp))
+ if len(events) != 2 {
+ t.Fatalf("events = %d, want the collector's report and the hook's", len(events))
+ }
+ if got := nested(t, events[1], "command")["output"]; got != "ok\n" {
+ t.Fatalf("hook command.output = %v, want the output kept", got)
+ }
+ })
+ }
+}
+
+// The transcript copy of a failed command is command.executed with the same call id and output. The
+// hook's copy matches it, so `claude sync` does not store the output a second time.
+func TestClaudeBashFailureMatchesTheTranscriptCopy(t *testing.T) {
+ logPath, _ := runClaudePostTool(t, claudeBashFailurePayload("Exit code 1\nError: Cannot find module 'express'"))
+ poll := claudeCommandLine(t, map[string]interface{}{
+ "severity": "high",
+ "harness": map[string]interface{}{"name": "claude_code", "collection_method": "poll"},
+ "session": map[string]interface{}{"id": "s-743", "working_directory": "/repo"},
+ "repository": "/repo",
+ "command": map[string]interface{}{"command": "npm test", "output": "Exit code 1\nError: Cannot find module 'express'"},
+ })
+ if !asymptoteobserve.IsDuplicateEndpointEvent(logPath, []byte(poll), asymptoteobserve.EndpointDuplicateWindow) {
+ t.Fatal("the transcript copy of a failed command should be suppressed by the hook's")
+ }
+}
diff --git a/cli/beacon-hooks/cmd/post_tool_ingested_result_test.go b/cli/beacon-hooks/cmd/post_tool_ingested_result_test.go
index 8fe19d2c..803f9f2d 100644
--- a/cli/beacon-hooks/cmd/post_tool_ingested_result_test.go
+++ b/cli/beacon-hooks/cmd/post_tool_ingested_result_test.go
@@ -128,7 +128,6 @@ func TestPostToolDoesNotRecordResultsForOtherTools(t *testing.T) {
name, tool, action string
input, response map[string]interface{}
}{
- {"Bash", "Bash", "command.executed", map[string]interface{}{"command": "cat NOTES.md"}, map[string]interface{}{"stdout": ingestedInjection}},
{"Write", "Write", "file.modified", map[string]interface{}{"file_path": "/repo/OUT.md", "content": ingestedInjection}, map[string]interface{}{"type": "create", "content": ingestedInjection}},
{"TodoWrite", "TodoWrite", "tool.invoked", map[string]interface{}{"todos": []interface{}{}}, map[string]interface{}{"newTodos": []interface{}{ingestedInjection}}},
{"Task", "Task", "tool.invoked", map[string]interface{}{"prompt": "x"}, map[string]interface{}{"content": ingestedInjection}},
@@ -241,3 +240,35 @@ func TestPostToolIngestedResultIsRedactedAndBounded(t *testing.T) {
}
})
}
+
+func TestClaudeBashOutputIsRedactedAndBounded(t *testing.T) {
+ const secret = "sk-abcdefghijklmnopqrstuvwxyz0123"
+ t.Run("redacted", func(t *testing.T) {
+ raw, event := runPostToolOnce(t, "claude", postToolPayload("Bash",
+ map[string]interface{}{"command": "printf secret"},
+ map[string]interface{}{"stdout": "api_key=" + secret}))
+ data, _ := json.Marshal(raw)
+ if strings.Contains(string(data), secret) {
+ t.Fatalf("secret reached the log: %s", data)
+ }
+ if event.Command == nil || !strings.Contains(event.Command.Output, "[REDACTED]") {
+ t.Fatalf("command = %+v, want redacted output", event.Command)
+ }
+ if event.Content == nil || !event.Content.Redacted {
+ t.Fatalf("content = %+v, want redacted=true", event.Content)
+ }
+ })
+ t.Run("per-string limit", func(t *testing.T) {
+ long := strings.Repeat("a", asymptoteobserve.DefaultStringLimit*2)
+ _, event := runPostToolOnce(t, "claude", postToolPayload("Bash",
+ map[string]interface{}{"command": "printf long"},
+ map[string]interface{}{"stdout": long}))
+ if event.Command == nil || len(event.Command.Output) > asymptoteobserve.DefaultStringLimit ||
+ !strings.HasSuffix(event.Command.Output, "...[truncated]") {
+ t.Fatalf("command.output length=%d, want <= %d and marked truncated", len(event.Command.Output), asymptoteobserve.DefaultStringLimit)
+ }
+ if event.Content == nil || !event.Content.Truncated || event.Content.Bytes != len(long) {
+ t.Fatalf("content = %+v, want truncated with original byte count", event.Content)
+ }
+ })
+}
diff --git a/docs/runtimes/claude-code.mdx b/docs/runtimes/claude-code.mdx
index 2e85c51c..03b8322d 100644
--- a/docs/runtimes/claude-code.mdx
+++ b/docs/runtimes/claude-code.mdx
@@ -76,7 +76,7 @@ Beacon detects Claude Code through the `claude` executable and Claude settings p
|------|---------|
| Prompt telemetry | Supported when emitted through Claude Code OTLP or hooks |
| Turn identity | Supported. Claude Code's `prompt.id` is kept as `prompt.id` on OTLP events; hook events after the prompt read the same id from the session transcript, and `beacon endpoint claude sync` reads it from `promptId`. The hook-recorded prompt itself takes its id from the OTLP `user_prompt` event, because the hook runs before Claude Code records the prompt |
-| Command, tool, and file telemetry | Supported through Claude Code OTLP with detailed tool inputs enabled |
+| Command, tool, and file telemetry | Supported through Claude Code OTLP with detailed tool inputs enabled; with hooks installed, Bash results also carry command output and, for a failed command, its exit code |
| Token usage and cost | Supported through OTLP token and cost metrics, with per-model and per-session attribution |
| Hook lifecycle and tool telemetry | Optional through `beacon endpoint hooks install --harness claude` |
| Historical session sync | Supported through `beacon endpoint claude sync`; marked as poll collection |
@@ -113,9 +113,26 @@ attributes remain under `raw.attributes`, subject to the configured redaction
and event-size controls. Future full-body `claude_code.*` lifecycle records
default to `session.activity` until Beacon assigns a more specific mapping.
-Optional hook events are an additional telemetry source. A hook pre-tool
-observation can appear as `tool.invoked`; the completed OTLP `tool_result` is
-the record that supplies the canonical command or file action.
+Optional hook events complement OTLP. Pre-tool observations can appear as
+`tool.invoked`. A Bash `PostToolUse` records `tool_response.stdout` followed by
+`tool_response.stderr` in `command.output`; Claude reports the two streams
+separately, so the order in which the command interleaved them is not kept, and
+no exit code is reported for a success. A failed Bash command arrives as
+`PostToolUseFailure` with no tool response, only an `error` whose first line is
+`Exit code N`, followed by the output with both streams interleaved. Beacon
+records it as a high-severity `command.executed` with `command.exit_code` set to
+N and the remaining text in `command.output`. Claude may middle-truncate long
+output or add lines of its own, such as a timeout notice. An `error` without that
+line means the shell never started; it is recorded as `tool.failed` without
+output. An interrupted command's partial output is marked
+`raw.claude_interrupted: true`. Retained output is subject to Beacon's local
+redaction and size limits.
+
+The hook event carries Claude's tool call ID, so the later `claude sync` copy of
+the same call, which has the same output, is suppressed as a duplicate. The OTLP
+`command.executed` for the call has no output and no working directory, so it is
+kept as a separate event. If a report without output is ever written first, the
+hook event is still kept, so the output is not lost.
Detailed tool inputs can contain sensitive command arguments, paths, URLs, search terms, and MCP request data. Beacon sends this telemetry only to the configured local collector during normal endpoint execution; apply the same access, retention, and redaction controls used for other retained prompt and tool data.
diff --git a/pkg/asymptoteobserve/dedupe.go b/pkg/asymptoteobserve/dedupe.go
index e42585a7..b18f6ceb 100644
--- a/pkg/asymptoteobserve/dedupe.go
+++ b/pkg/asymptoteobserve/dedupe.go
@@ -17,11 +17,13 @@ const (
)
type endpointDedupeEvent struct {
- action string
- harness string
- key string
- callID string
- ts time.Time
+ action string
+ harness string
+ key string
+ callID string
+ hasOutput bool
+ polled bool
+ ts time.Time
}
// IsDuplicateEndpointEvent reports whether candidateLine duplicates a recently
@@ -89,8 +91,14 @@ func duplicateEndpointEvents(existing, candidate endpointDedupeEvent, effectiveW
// runs and the collector writes when its batch flushes, so the two reports
// of one call routinely land five seconds apart -- past the two-second
// window that is the only thing that ever collapsed them.
+ //
+ // The one exception is a live report that retains command output the earlier one lacks. The
+ // log is append-only, so the earlier line cannot be completed; suppressing the later one would
+ // silently lose the output whenever a path that has none -- Claude Code's OTLP tool_result --
+ // happened to be written first. A polled copy is backfill and stays suppressed: keeping it
+ // would put every command an install without hooks ran into the log twice.
if existing.callID != "" && existing.callID == candidate.callID {
- return true
+ return existing.hasOutput || !candidate.hasOutput || candidate.polled
}
// Without matching IDs, only the timing heuristic is left, and only across
// capture paths: two adjacent calls from one path can legitimately touch the
@@ -170,7 +178,12 @@ func endpointDedupeCandidate(line []byte) (endpointDedupeEvent, bool) {
strings.ToLower(workspace),
target,
}, "\x00")
- return endpointDedupeEvent{action: strings.ToLower(action), harness: harness, key: key, callID: callID, ts: ts.UTC()}, true
+ return endpointDedupeEvent{
+ action: strings.ToLower(action), harness: harness, key: key, callID: callID,
+ hasOutput: nestedString(event, "command", "output") != "",
+ polled: nestedString(event, "harness", "collection_method") == CollectionMethodPoll,
+ ts: ts.UTC(),
+ }, true
}
func endpointDedupeWindow(action string, fallback time.Duration) time.Duration {
diff --git a/pkg/asymptoteobserve/dedupe_test.go b/pkg/asymptoteobserve/dedupe_test.go
index ee77d4fd..5bc284ad 100644
--- a/pkg/asymptoteobserve/dedupe_test.go
+++ b/pkg/asymptoteobserve/dedupe_test.go
@@ -136,6 +136,41 @@ func TestIsDuplicateEndpointEventCollapsesNormalizedHarnessOnCallID(t *testing.T
}
}
+// The log is append-only, so when two reports of one call land in the "wrong" order the line
+// written first cannot be completed. A live report carrying command output the earlier one lacks
+// is therefore kept; a report that adds nothing, or a polled backfill copy, is still suppressed.
+func TestIsDuplicateEndpointEventKeepsALaterReportThatAddsCommandOutput(t *testing.T) {
+ line := func(ts, method, output string) string {
+ command := `{"command":"echo hi"}`
+ if output != "" {
+ command = `{"command":"echo hi","output":"` + output + `"}`
+ }
+ return `{"timestamp":"` + ts + `","event":{"action":"command.executed"},"harness":{"name":"claude_code","collection_method":"` + method + `"},` +
+ `"session":{"id":"s1","working_directory":"/repo"},"command":` + command + `,"tool":{"name":"Bash","command":"echo hi"},"gen_ai":{"tool":{"call":{"id":"toolu_1"}}}}`
+ }
+ cases := []struct {
+ name string
+ existing, candidate string
+ duplicate bool
+ }{
+ {"live output after a report without it", line("2026-08-21T18:00:01Z", "otlp", ""), line("2026-08-21T18:00:02Z", "hook", "hi"), false},
+ {"report without output after one with it", line("2026-08-21T18:00:01Z", "hook", "hi"), line("2026-08-21T18:00:07Z", "otlp", ""), true},
+ {"both carry output", line("2026-08-21T18:00:01Z", "hook", "hi"), line("2026-08-21T18:00:09Z", "poll", "hi"), true},
+ {"polled output after a report without it", line("2026-08-21T18:00:01Z", "otlp", ""), line("2026-08-21T18:00:09Z", "poll", "hi"), true},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "runtime.jsonl")
+ if err := os.WriteFile(path, []byte(tc.existing+"\n"), 0644); err != nil {
+ t.Fatalf("write existing event: %v", err)
+ }
+ if got := IsDuplicateEndpointEvent(path, []byte(tc.candidate), EndpointDuplicateWindow); got != tc.duplicate {
+ t.Fatalf("duplicate = %t, want %t", got, tc.duplicate)
+ }
+ })
+ }
+}
+
// A Claude Code Write reaches the hook through diffFields, which records
// file.operation "modify", and reaches the collector as "create" -- two words
// for one action. While the target included the operation, the pair could not