Skip to content

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

Share traces as beacon.trace.v1 and derive the chat view from the bundle

Clauded816303f52a3
diff --git a/pkg/asymptoteobserve/share.go b/pkg/asymptoteobserve/share.go
index f2a204ad..bcd134ad 100644
--- a/pkg/asymptoteobserve/share.go
+++ b/pkg/asymptoteobserve/share.go
@@ -9,20 +9,21 @@ import (
"sort"
"strings"
"time"
- "unicode/utf8"
)
-// This file is the CLI half of the shared-trace wire contract, beacon.share.v1: the request and
-// response bodies `beacon share` exchanges with beacon.sh, and the projection of one session's
-// endpoint events into the messages a shared trace is made of.
+// This file is the CLI half of the shared-trace wire contract: the request and response bodies
+// `beacon share` exchanges with beacon.sh, and BuildShareBundle, which turns one session's endpoint
+// events into the trace that is published.
//
-// A shared trace is a snapshot a person chose to publish, so the projection is conservative about
-// what leaves the machine: every event goes through SanitizeEvent first, local paths are rewritten
-// relative to the session's directory or the home directory, and Beacon's own bookkeeping events
-// (heartbeats, metric datapoints, the session.shared record itself) are left out.
-
-// ShareSchemaVersion names the wire contract.
-const ShareSchemaVersion = "beacon.share.v1"
+// A shared trace IS a beacon.trace.v1 trace (trace.go), projected by the same code the local
+// dashboard uses (tracebuild.go), so a shared trace and the local one read the same and every
+// lens runs on both. The chat view beacon.sh shows is derived from the bundle with TraceMessages;
+// it is never uploaded.
+//
+// A shared trace is a snapshot a person chose to publish, so the build is conservative about what
+// leaves the machine: every event goes through SanitizeEvent and then has local paths rewritten
+// relative to the session's directory or the home directory before it is projected, and Beacon's
+// own bookkeeping and status telemetry are left out (ShareProjects).
// Visibility levels of a shared trace. Direct is the default: anyone with the link.
const (
@@ -40,188 +41,63 @@ func ValidShareVisibility(value string) bool {
return false
}
-// Message roles.
-const (
- ShareRoleUser = "user"
- ShareRoleAssistant = "assistant"
- ShareRoleSystem = "system"
-)
-
-// Part types.
-const (
- SharePartText = "text"
- SharePartThinking = "thinking"
- SharePartToolCall = "tool_call"
- SharePartToolResult = "tool_result"
- SharePartError = "error"
- SharePartSystemEvent = "system_event"
-)
-
-// Tool kinds, the toolKind of a tool_call part.
-const (
- ShareToolKindTerminalCommand = "terminal_command"
- ShareToolKindRead = "read"
- ShareToolKindEdit = "edit"
- ShareToolKindWrite = "write"
- ShareToolKindDelete = "delete"
- ShareToolKindGrep = "grep"
- ShareToolKindGlob = "glob"
- ShareToolKindWebSearch = "web_search"
- ShareToolKindWebFetch = "web_fetch"
- ShareToolKindTask = "task"
- ShareToolKindTodo = "todo"
- ShareToolKindMCP = "mcp"
- ShareToolKindOther = "other"
-)
-
-// Tool result statuses.
-const (
- ShareStatusSuccess = "success"
- ShareStatusError = "error"
-)
-
-// Relationship types of related_to.
-const (
- ShareRelationshipSubagent = "subagent"
- ShareRelationshipResume = "resume"
-)
-
-// ShareSourceCLI is the source the CLI reports for traces it uploads.
+// ShareSourceCLI is the source the CLI reports for traces it uploads, and the provenance source of
+// the bundles it builds.
const ShareSourceCLI = "cli"
-// ShareMaxMessagesPerBatch is the most messages one batch request may carry.
-const ShareMaxMessagesPerBatch = 1000
+// ShareMaxEventsPerBatch is the most events one batch request may carry.
+const ShareMaxEventsPerBatch = 1000
// ShareTitleMaxRunes bounds a title derived from the first prompt.
const ShareTitleMaxRunes = 80
-// ShareTokenUsageV1 is a token count in the contract's flat shape. Every field is written, zero
-// included, because the contract defines all five.
-type ShareTokenUsageV1 struct {
- InputTokens int64 `json:"input_tokens"`
- OutputTokens int64 `json:"output_tokens"`
- CacheReadInputTokens int64 `json:"cache_read_input_tokens"`
- CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
- ReasoningOutputTokens int64 `json:"reasoning_output_tokens"`
-}
-
-// IsZero reports whether no count is set.
-func (u ShareTokenUsageV1) IsZero() bool {
- return u == ShareTokenUsageV1{}
-}
-
-// ShareTraceV1 is the body of PUT /v1/traces/{external_id}: the trace's metadata. There is
-// deliberately no local path field; ProjectName is a name, never a directory.
+// ShareTraceV1 is the body of PUT /v1/traces/{external_id}: the trace's summary and how it is
+// shared. SchemaVersion is TraceSchemaVersion. The server owns the summary's sharing block and
+// ignores it on input.
type ShareTraceV1 struct {
- SchemaVersion string `json:"schema_version"`
- AgentID string `json:"agent_id"`
- Title string `json:"title,omitempty"`
- Visibility string `json:"visibility,omitempty"`
- Model string `json:"model,omitempty"`
- ProjectName string `json:"project_name,omitempty"`
- GitRemoteURL string `json:"git_remote_url,omitempty"`
- GitBranch string `json:"git_branch,omitempty"`
- GitRef string `json:"git_ref,omitempty"`
- TokenUsage *ShareTokenUsageV1 `json:"token_usage,omitempty"`
- CostUSD *float64 `json:"cost_usd,omitempty"`
- SourceSessionID string `json:"source_session_id,omitempty"`
- SourceCreatedAt string `json:"source_created_at,omitempty"`
- SourceUpdatedAt string `json:"source_updated_at,omitempty"`
- RelatedTo string `json:"related_to,omitempty"`
- RelationshipType string `json:"relationship_type,omitempty"`
- Source string `json:"source,omitempty"`
+ SchemaVersion string `json:"schema_version"`
+ Summary TraceSummaryV1 `json:"summary"`
+ Visibility string `json:"visibility,omitempty"`
+ Title string `json:"title,omitempty"`
+ Source string `json:"source,omitempty"`
+ Provenance TraceProvenanceV1 `json:"provenance"`
}
// ShareTraceResultV1 is the response of PUT /v1/traces/{external_id}.
type ShareTraceResultV1 struct {
- ID string `json:"id"`
- ExternalID string `json:"external_id"`
- URL string `json:"url"`
- Visibility string `json:"visibility"`
- MessageCount int `json:"message_count"`
- Created bool `json:"created"`
+ ID string `json:"id"`
+ ExternalID string `json:"external_id"`
+ URL string `json:"url"`
+ Visibility string `json:"visibility"`
+ EventCount int `json:"event_count"`
+ Created bool `json:"created"`
}
-// ShareTraceStateV1 is the owner's view of a trace from GET /v1/traces/{external_id}: enough of
-// the trace metadata to report on, and the message watermark a refresh continues from.
+// ShareTraceStateV1 is the owner's view of a trace from GET /v1/traces/{external_id}: enough to
+// report on, and the event watermark a refresh continues from.
type ShareTraceStateV1 struct {
- ID string `json:"id"`
- ExternalID string `json:"external_id,omitempty"`
- URL string `json:"url"`
- Title string `json:"title,omitempty"`
- AgentID string `json:"agent_id,omitempty"`
- Model string `json:"model,omitempty"`
- Visibility string `json:"visibility"`
- TokenUsage *ShareTokenUsageV1 `json:"token_usage,omitempty"`
- MessageCount int `json:"message_count"`
- LastMessageID string `json:"last_message_id,omitempty"`
- MaxOrder int `json:"max_order"`
- CreatedAt string `json:"created_at,omitempty"`
- UpdatedAt string `json:"updated_at,omitempty"`
+ ID string `json:"id"`
+ ExternalID string `json:"external_id,omitempty"`
+ URL string `json:"url"`
+ Title string `json:"title,omitempty"`
+ Visibility string `json:"visibility"`
+ EventCount int `json:"event_count"`
+ LastEventID string `json:"last_event_id,omitempty"`
+ MaxNumber int `json:"max_number"`
+ CreatedAt string `json:"created_at,omitempty"`
+ UpdatedAt string `json:"updated_at,omitempty"`
}
-// ShareMessagesBatchV1 is the body of POST /v1/traces/{external_id}/messages/batch.
-type ShareMessagesBatchV1 struct {
- Messages []ShareMessageV1 `json:"messages"`
+// ShareEventsBatchV1 is the body of POST /v1/traces/{external_id}/events/batch. Events are upserted
+// by ID, which is stable across uploads, so re-sending a batch is idempotent.
+type ShareEventsBatchV1 struct {
+ Events []TraceEventV1 `json:"events"`
}
-// ShareBatchResultV1 is the response of a message batch.
+// ShareBatchResultV1 is the response of an event batch.
type ShareBatchResultV1 struct {
- Accepted int `json:"accepted"`
- MessageCount int `json:"message_count"`
-}
-
-// ShareMessageV1 is one message of a shared trace. ID is stable across uploads, which is what makes
-// re-sending a batch an idempotent upsert.
-type ShareMessageV1 struct {
- ID string `json:"id"`
- Order int `json:"order"`
- Role string `json:"role"`
- Timestamp string `json:"timestamp"`
- Model string `json:"model,omitempty"`
- Text string `json:"text"`
- Parts []SharePartV1 `json:"parts"`
- TokenUsage *ShareTokenUsageV1 `json:"token_usage,omitempty"`
-}
-
-// SharePartV1 is one part of a message. Content is one of the Share*Content types below, or a
-// map[string]interface{} of small scalars for a system_event.
-type SharePartV1 struct {
- Type string `json:"type"`
- Order int `json:"order"`
- Content interface{} `json:"content"`
-}
-
-// ShareTextContent is the content of a text or thinking part.
-type ShareTextContent struct {
- Text string `json:"text"`
-}
-
-// ShareToolCallContent is the content of a tool_call part. Diff is the edit's retained diff when the
-// runtime reported one; it lives on the call because the contract's tool_result has no diff.
-type ShareToolCallContent struct {
- CallID string `json:"callId"`
- ToolName string `json:"toolName"`
- ToolKind string `json:"toolKind"`
- Args map[string]interface{} `json:"args"`
- Command string `json:"command,omitempty"`
- FilePath string `json:"filePath,omitempty"`
- Diff string `json:"diff,omitempty"`
-}
-
-// ShareToolResultContent is the content of a tool_result part.
-type ShareToolResultContent struct {
- CallID string `json:"callId"`
- ToolName string `json:"toolName"`
- Output string `json:"output"`
- Status string `json:"status"`
- ExitCode *int `json:"exitCode,omitempty"`
- DurationMS *int64 `json:"durationMs,omitempty"`
-}
-
-// ShareErrorContent is the content of an error part.
-type ShareErrorContent struct {
- Message string `json:"message"`
+ Upserted int `json:"upserted"`
+ EventCount int `json:"event_count"`
}
var shareExternalIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$`)
@@ -249,134 +125,8 @@ func ShareExternalID(harness, sessionID string) string {
return name + ":sha256-" + hex.EncodeToString(sum[:])[:32]
}
-// ShareToolKind classifies a tool for the contract's toolKind, from the tool's own name first --
-// every runtime names its tools differently, so the table covers each supported runtime's
-// spellings -- and then from what Beacon recorded about the call (an MCP server, a command, a file
-// operation). Anything else is "other".
-func ShareToolKind(toolName, action, category string, isMCP bool) string {
- name := normalizeToolName(toolName)
- if kind, ok := shareToolKindsByName[name]; ok {
- return kind
- }
- lowerAction := strings.ToLower(strings.TrimSpace(action))
- lowerCategory := strings.ToLower(strings.TrimSpace(category))
- rawLower := strings.ToLower(strings.TrimSpace(toolName))
- switch {
- case isMCP || lowerCategory == "mcp" || strings.HasPrefix(lowerAction, "mcp.") ||
- strings.HasPrefix(rawLower, "mcp__") || strings.HasPrefix(rawLower, "mcp_") || strings.HasPrefix(rawLower, "mcp."):
- return ShareToolKindMCP
- case strings.HasPrefix(lowerAction, "command.") || lowerCategory == "command":
- return ShareToolKindTerminalCommand
- case lowerAction == "file.read":
- return ShareToolKindRead
- case lowerAction == "file.created":
- return ShareToolKindWrite
- case lowerAction == "file.deleted":
- return ShareToolKindDelete
- case lowerAction == "file.modified" || lowerAction == "file.edited":
- return ShareToolKindEdit
- }
- switch {
- case name == "":
- return ShareToolKindOther
- case strings.Contains(name, "bash") || strings.Contains(name, "shell") || strings.Contains(name, "terminal"):
- return ShareToolKindTerminalCommand
- case strings.Contains(name, "websearch"):
- return ShareToolKindWebSearch
- case strings.Contains(name, "webfetch") || strings.Contains(name, "fetchurl"):
- return ShareToolKindWebFetch
- case strings.Contains(name, "todo"):
- return ShareToolKindTodo
- case strings.Contains(name, "grep"):
- return ShareToolKindGrep
- case strings.Contains(name, "glob"):
- return ShareToolKindGlob
- case strings.Contains(name, "read"):
- return ShareToolKindRead
- case strings.Contains(name, "edit") || strings.Contains(name, "patch") || strings.Contains(name, "replace"):
- return ShareToolKindEdit
- case strings.Contains(name, "write") || strings.Contains(name, "create"):
- return ShareToolKindWrite
- case strings.Contains(name, "delete"):
- return ShareToolKindDelete
- }
- return ShareToolKindOther
-}
-
-// normalizeToolName lowercases a tool name and drops separators, so exec_command, execCommand and
-// exec-command compare equal. A namespace prefix some runtimes add ("functions.", "default_api:")
-// is dropped first.
-func normalizeToolName(name string) string {
- name = strings.ToLower(strings.TrimSpace(name))
- for _, prefix := range []string{"functions.", "default_api:", "default_api."} {
- name = strings.TrimPrefix(name, prefix)
- }
- var b strings.Builder
- for _, r := range name {
- if r == '_' || r == '-' || r == ' ' || r == '.' {
- continue
- }
- b.WriteRune(r)
- }
- return b.String()
-}
-
-// shareToolKindsByName maps normalized tool names to kinds: Claude Code, Codex CLI, Cursor, Gemini
-// CLI, Qwen Code, OpenCode, Cline, the Pi family, Copilot, Kiro, OpenHands, Antigravity, DeepSeek
-// Harness, Grok Build and fx spellings.
-var shareToolKindsByName = func() map[string]string {
- table := map[string][]string{
- ShareToolKindTerminalCommand: {
- "bash", "shell", "execcommand", "exec", "localshell", "runterminalcmd", "runterminalcommand",
- "runcommand", "runshellcommand", "executebash", "executecommand", "terminal", "command",
- "bashoutput", "killshell", "killbash", "terminalsend", "ipython", "powershell", "cmd",
- },
- ShareToolKindRead: {
- "read", "view", "readfile", "viewfile", "cat", "notebookread", "readmanyfiles", "openfile",
- "fsread", "readimage",
- },
- ShareToolKindEdit: {
- "edit", "multiedit", "applypatch", "strreplace", "strreplaceeditor", "strreplacebasededittool",
- "searchreplace", "editfile", "replace", "notebookedit", "patch", "replaceinfile", "editnotebook",
- "fswrite",
- },
- ShareToolKindWrite: {
- "write", "create", "writefile", "createfile", "writetofile", "newfile",
- },
- ShareToolKindDelete: {
- "delete", "deletefile", "remove", "removefile", "rm",
- },
- ShareToolKindGrep: {
- "grep", "grepsearch", "search", "rg", "ripgrep", "searchfilecontent", "codebasesearch",
- "searchfiles",
- },
- ShareToolKindGlob: {
- "glob", "find", "filesearch", "findbyname", "ls", "listdir", "listdirectory", "listfiles",
- },
- ShareToolKindWebSearch: {
- "websearch", "googlesearch", "googlewebsearch", "searchweb",
- },
- ShareToolKindWebFetch: {
- "webfetch", "fetch", "fetchurl", "readurl", "urlfetch", "browse",
- },
- ShareToolKindTask: {
- "task", "agent", "subagent", "spawnagent", "dispatchagent", "delegate", "newtask", "runsubagent",
- },
- ShareToolKindTodo: {
- "todowrite", "todoread", "todo", "updateplan", "writetodos", "updatetodos", "todolist",
- },
- }
- out := map[string]string{}
- for kind, names := range table {
- for _, name := range names {
- out[name] = kind
- }
- }
- return out
-}()
-
-// ShareOptions tunes the projection. The zero value is what BuildShareMessages uses: the working
-// directory comes from the events and the home directory from the environment.
+// ShareOptions tunes BuildShareBundle. The zero value takes the working directory from the events,
+// the home directory from the environment, and stamps the bundle with the current time.
type ShareOptions struct {
// WorkingDirectory is the session's directory. Paths under it are written relative to it.
WorkingDirectory string
@@ -384,32 +134,72 @@ type ShareOptions struct {
HomeDirectory string
// NoHomeLookup leaves HomeDirectory empty rather than reading it from the environment.
NoHomeLookup bool
+ // BeaconVersion is recorded in the bundle's provenance.
+ BeaconVersion string
+ // GeneratedAt is the provenance timestamp; zero means now.
+ GeneratedAt time.Time
+}
+
+// ShareProjects reports whether a shared trace carries event: false for Beacon's bookkeeping about
+// the session (session.shared, session.share_requested, session.commit_linked), for Beacon's own
+// telemetry and runtime status pings (heartbeats, inventory, destination health, idle/activity
+// status, MCP tool listings, runtime detection), for metric datapoints that carry no token usage,
+// and for an event with no action. It is the one definition of what a share publishes, so a local
+// view can tell when a shared trace is behind the session: an event ShareProjects accepts that is
+// newer than the share.
+func ShareProjects(event Event) bool {
+ NormalizeTraceEvent(&event)
+ action := strings.ToLower(strings.TrimSpace(event.Event.Action))
+ category := strings.ToLower(strings.TrimSpace(event.Event.Category))
+ switch {
+ case action == "" || shareBookkeepingActions[action] || traceNoise(action, category):
+ return false
+ case category == "metric" || strings.HasPrefix(action, "token.") || strings.HasPrefix(action, "metric."):
+ // Usage is the only part of a datapoint a trace has use for.
+ return event.GenAI != nil && event.GenAI.Usage != nil
+ }
+ return true
}
-// BuildShareMessages projects one session's events into shared-trace messages.
-//
-// Events are sanitized (SanitizeEvent), ordered by timestamp with the event id as tie-breaker, and
-// mapped as follows:
-//
-// - a prompt is a user message with a text part;
-// - assistant text and reasoning are assistant messages with a text or thinking part;
-// - a tool invocation is an assistant message with a tool_call part, and its completion is a
-// separate message with a tool_result part carrying the same callId. Hook runtimes report one
-// call twice (before and after); the two are paired by gen_ai.tool.call.id, or, when the
-// runtime names no call id, by tool name with the most recent unanswered invocation. A call or
-// result reported twice (a hook and an OTLP copy of one action) is written once, with the
-// second copy only filling fields the first lacked. A completion with no invocation gets a
-// tool_call message of its own just before it, so every result has a call;
-// - approvals, policy decisions and session lifecycle are system messages with a system_event
-// part; failures that are not a tool's are system messages with an error part.
-//
-// Heartbeats, inventory, metric datapoints and the session.shared record are not messages.
-func BuildShareMessages(events []Event) []ShareMessageV1 {
- return BuildShareMessagesWithOptions(events, ShareOptions{})
+// ShareEventID is the stable id of the trace event an endpoint event becomes: its event.id when it
+// has one, otherwise the id the runtime log writer would derive for it (EventIDForLine over the
+// event as the writer stamps it), so a session read from its runtime's store names its events the
+// same way on every upload.
+func ShareEventID(event Event) string {
+ if id := strings.TrimSpace(event.Event.ID); id != "" {
+ return id
+ }
+ event.Event.ID = ""
+ AttachDerivedTrace(&event)
+ event = SanitizeEvent(cloneEvent(event), 64*1024)
+ data, err := json.Marshal(event)
+ if err != nil {
+ return eventUUID("share", event.Timestamp+"\x00"+event.Event.Action+"\x00"+event.Message)
+ }
+ return EventIDForLine(data)
}
-// BuildShareMessagesWithOptions is BuildShareMessages with explicit options.
-func BuildShareMessagesWithOptions(events []Event, opts ShareOptions) []ShareMessageV1 {
+// BuildShareBundle builds the trace a person publishes from one session's events: a
+// beacon.trace.v1 bundle projected by TraceEventFromEvent and TraceBuilder, the code the local
+// dashboard uses.
+//
+// Before projection every event is sanitized (SanitizeEvent) and has local paths rewritten -- the
+// session's directory becomes ".", the home directory "~" -- in every field the projection reads:
+// the message, prompt text, retained assistant output, command line and output, file path and diff,
+// tool command, path, arguments and result, MCP fields, approval and policy reasons, error, the
+// working directory and the repository. Events ShareProjects rejects are left out. The rest are
+// ordered by timestamp, then with tool invocations ahead of everything else at one instant (a
+// pre-tool and a post-tool hook can share a timestamp), then by ID; events that cannot be timed keep
+// their input order after every timed one. An event that appears twice (the same ID) is carried
+// once. Each event's ID is ShareEventID, so re-sharing upserts rather than duplicates.
+//
+// The summary is folded from the carried events, as the dashboard folds a trace, with these
+// differences for publication: session.working_directory is dropped, repository.path is the
+// project's directory name rather than a path (never the home directory's name, which is the local
+// account's), and repository.remote_url and ref come from the session's commit links and CI run,
+// with credentials removed (ShareRemoteURL). Token usage is the plain sum of the carried events'
+// usage, as in the local view.
+func BuildShareBundle(events []Event, opts ShareOptions) TraceBundleV1 {
if opts.WorkingDirectory == "" {
for _, event := range events {
if event.Session != nil && strings.TrimSpace(event.Session.WorkingDirectory) != "" {
@@ -423,55 +213,36 @@ func BuildShareMessagesWithOptions(events []Event, opts ShareOptions) []ShareMes
opts.HomeDirectory = home
}
}
- b := &shareBuilder{
- scrub: newPathScrubber(opts.WorkingDirectory, opts.HomeDirectory),
- seen: map[string]bool{},
- calls: map[string]*ShareToolCallContent{},
- results: map[string]*ShareToolResultContent{},
- callMessage: map[string]*ShareMessageV1{},
- prompts: map[string]*ShareMessageV1{},
- lastPrompt: map[string]*sharePromptRef{},
- }
- for _, item := range orderShareEvents(events) {
- b.add(item)
- }
- out := make([]ShareMessageV1, 0, len(b.messages))
- for i, message := range b.messages {
- message.Order = i + 1
- out = append(out, *message)
- }
- return out
-}
+ scrub := newPathScrubber(opts.WorkingDirectory, opts.HomeDirectory)
-type shareEvent struct {
- event Event
- id string
- ts time.Time
- hasTS bool
- rank int
-}
-
-// orderShareEvents sanitizes events, gives each its message id, and sorts them by timestamp, then
-// with invocations ahead of everything else at one instant (a pre-tool and a post-tool hook can
-// share a timestamp), then by id. Events that cannot be timed keep their input position relative
-// to each other, after every timed event.
-func orderShareEvents(events []Event) []shareEvent {
- items := make([]shareEvent, 0, len(events))
- for _, event := range events {
- id := ShareMessageID(event)
- event = SanitizeEvent(event, 1<<30)
- item := shareEvent{event: event, id: id}
- if ts, err := ParseTimestamp(event.Timestamp); err == nil {
- item.ts, item.hasTS = ts, true
- } else if ts, err := time.Parse(time.RFC3339Nano, event.Timestamp); err == nil {
- item.ts, item.hasTS = ts, true
+ type item struct {
+ event Event
+ te TraceEventV1
+ ts time.Time
+ hasTS bool
+ rank int
+ }
+ items := make([]item, 0, len(events))
+ for _, original := range events {
+ if !ShareProjects(original) {
+ continue
}
- if isShareInvocation(event) {
- item.rank = 0
- } else {
- item.rank = 1
+ id := ShareEventID(original)
+ event := scrub.event(SanitizeEvent(cloneEvent(original), 1<<30))
+ NormalizeTraceEvent(&event)
+ te := TraceEventFromEvent(event, id, 0)
+ if te.Tool != nil && te.Tool.Arguments == nil {
+ // A hook keeps the tool's input in raw when the runtime gave it no gen_ai call.
+ if args := rawToolArgs(event.Raw); args != nil {
+ te.Tool.Arguments = args
+ }
+ }
+ it := item{event: event, te: te, rank: 1}
+ it.ts, it.hasTS = traceEventTime(te)
+ if traceToolInvocation(te) {
+ it.rank = 0
}
- items = append(items, item)
+ items = append(items, it)
}
sort.SliceStable(items, func(i, j int) bool {
a, b := items[i], items[j]
@@ -487,783 +258,171 @@ func orderShareEvents(events []Event) []shareEvent {
if a.rank != b.rank {
return a.rank < b.rank
}
- return a.id < b.id
+ return a.te.ID < b.te.ID
})
- return items
-}
-// ShareMessageID is the stable id of the message an event becomes: its event.id when it has one,
-// otherwise the id the runtime log writer would derive for it (EventIDForLine over the event as the
-// writer stamps it), so a session read from its runtime's store names its messages the same way on
-// every upload.
-func ShareMessageID(event Event) string {
- if id := strings.TrimSpace(event.Event.ID); id != "" {
- return id
+ provenance := TraceProvenanceV1{Source: ShareSourceCLI, BeaconVersion: opts.BeaconVersion}
+ generated := opts.GeneratedAt
+ if generated.IsZero() {
+ generated = time.Now()
}
- event.Event.ID = ""
- AttachDerivedTrace(&event)
- event = SanitizeEvent(event, 64*1024)
- data, err := json.Marshal(event)
- if err != nil {
- return eventUUID("share", event.Timestamp+"\x00"+event.Event.Action+"\x00"+event.Message)
- }
- return EventIDForLine(data)
-}
-
-type shareBuilder struct {
- scrub pathScrubber
- messages []*ShareMessageV1
- seen map[string]bool
- // calls, results and callMessage are keyed by callId.
- calls map[string]*ShareToolCallContent
- results map[string]*ShareToolResultContent
- callMessage map[string]*ShareMessageV1
- // pending holds call ids of invocations that named no runtime call id, newest last, waiting for
- // a completion to pair with by tool name.
- pending []string
- // prompts holds user messages by harness, session and prompt.id, so one prompt captured by two
- // paths (a hook and the OTLP export) is written once. lastPrompt holds the newest user message
- // per harness and session, for the copy that carries no prompt.id (Claude Code's
- // UserPromptSubmit hook runs before the prompt is recorded, so it has none).
- prompts map[string]*ShareMessageV1
- lastPrompt map[string]*sharePromptRef
-}
-
-type sharePromptRef struct {
- message *ShareMessageV1
- keyed bool
- ts time.Time
- hasTS bool
-}
-
-// sharePromptPairWindow is how far apart two captures of one prompt may be. The hook and the
-// export record the same submission within moments of each other.
-const sharePromptPairWindow = 10 * time.Second
-
-type shareEventClass int
-
-const (
- shareSkip shareEventClass = iota
- sharePrompt
- shareAgentText
- shareThinking
- shareTool
- shareApproval
- shareSystem
- shareError
-)
+ provenance.GeneratedAt = FormatTimestamp(generated)
-func classifyShareEvent(event Event) shareEventClass {
- action := strings.ToLower(strings.TrimSpace(event.Event.Action))
- category := strings.ToLower(strings.TrimSpace(event.Event.Category))
- switch {
- case action == "" || action == "session.shared":
- return shareSkip
- case category == "metric" || category == "inventory" || category == "health" || category == "telemetry" ||
- strings.HasPrefix(action, "endpoint.") || strings.HasPrefix(action, "telemetry.") ||
- strings.HasPrefix(action, "inventory.") || strings.HasPrefix(action, "token.") ||
- strings.HasPrefix(action, "destination.") || strings.HasPrefix(action, "health."):
- return shareSkip
- case action == "session.activity" || action == "session.idle" || action == "session.status" ||
- action == "session.lock" || action == "mcp.tool_listed" || action == "agent.detected":
- return shareSkip
- case category == "prompt" || strings.HasPrefix(action, "prompt."):
- return sharePrompt
- case strings.Contains(action, "reasoning") || strings.Contains(action, "thinking"):
- return shareThinking
- case action == "agent.message" || action == "assistant.message" || action == "agent.response" ||
- action == "agent.response.completed" || action == "agent.plan":
- return shareAgentText
- case category == "approval" || strings.HasPrefix(action, "approval.") || strings.HasPrefix(action, "policy."):
- return shareApproval
- case strings.HasPrefix(action, "tool.") || strings.HasPrefix(action, "command.") ||
- strings.HasPrefix(action, "file.") || action == "mcp.tool_invoked" || action == "mcp.tool_call" ||
- category == "tool" || category == "command" || category == "file":
- return shareTool
- case action == "session.error" || action == "agent.error" || strings.HasPrefix(action, "error.") ||
- category == "error":
- return shareError
- }
- return shareSystem
-}
-
-// isShareInvocation reports an event that names a tool call before it runs.
-func isShareInvocation(event Event) bool {
- switch strings.ToLower(strings.TrimSpace(event.Event.Action)) {
- case "tool.invoked", "tool.started", "tool.call", "tool.execute.before", "tool.execution_start",
- "command.invoked", "command.execute.before", "mcp.tool_call":
- // The hook adapter also labels a post-tool event tool.invoked for tools it has no more
- // specific action for (WebFetch, Task, Grep, ...). That event carries the finished call's
- // result, and is a completion.
- return !hasShareCompletionEvidence(event)
- }
- return false
-}
-
-// isShareCompletion reports an event that says a tool call finished: its action says so, or it
-// carries what only a finished call has (a result, output, an exit code, a diff, an error).
-func isShareCompletion(event Event) bool {
- switch strings.ToLower(strings.TrimSpace(event.Event.Action)) {
- case "tool.completed", "tool.failed", "tool.execute.after", "tool.execution_complete", "tool.result":
- return true
- }
- if event.File != nil && event.File.Diff != "" {
- return true
- }
- return hasShareCompletionEvidence(event)
-}
-
-// hasShareCompletionEvidence reports an event that carries what only a finished call has: a
-// result, command output or exit code, or an error. A diff is not evidence on its own, because an
-// edit's invocation can carry the patch it is about to apply.
-func hasShareCompletionEvidence(event Event) bool {
- if event.GenAI != nil && event.GenAI.Tool != nil && event.GenAI.Tool.Call != nil && event.GenAI.Tool.Call.Result != nil {
- return true
- }
- if event.Command != nil && (event.Command.Output != "" || event.Command.ExitCode != nil || event.Command.DurationMS > 0) {
- return true
- }
- return event.Error != nil && event.Error.Type != ""
-}
-
-func (b *shareBuilder) add(item shareEvent) {
- if b.seen[item.id] {
- return
- }
- event := item.event
- class := classifyShareEvent(event)
- if class == shareSkip {
- return
- }
- b.seen[item.id] = true
- switch class {
- case sharePrompt:
- text := sharePromptText(event)
- key := sharePromptKey(event)
- if existing := b.samePrompt(item, key, text); existing != nil {
- // The same prompt from a second capture path: fill in the text if the first copy
- // had none, and write nothing new.
- if existing.Text == sharePromptNotRetained && text != "" {
- text = b.scrub.text(text)
- existing.Text = text
- existing.Parts = []SharePartV1{{Type: SharePartText, Order: 1, Content: ShareTextContent{Text: text}}}
- }
- return
- }
- if text == "" {
- text = sharePromptNotRetained
- }
- b.appendText(item, ShareRoleUser, SharePartText, text)
- message := b.messages[len(b.messages)-1]
- if key != "" {
- b.prompts[key] = message
- }
- b.lastPrompt[sharePromptScope(event)] = &sharePromptRef{message: message, keyed: key != "", ts: item.ts, hasTS: item.hasTS}
- case shareAgentText:
- text := shareAssistantText(event, GenAIPartTypeText)
- if text == "" {
- return
+ var builder *TraceBuilder
+ seen := map[string]bool{}
+ for _, it := range items {
+ if seen[it.te.ID] {
+ continue
}
- b.appendText(item, ShareRoleAssistant, SharePartText, text)
- case shareThinking:
- text := shareAssistantText(event, GenAIPartTypeReasoning)
- if text == "" {
- return
+ seen[it.te.ID] = true
+ if builder == nil {
+ builder = NewTraceBuilder(shareTraceID(it.event), it.event)
}
- b.appendText(item, ShareRoleAssistant, SharePartThinking, text)
- case shareTool:
- b.addTool(item)
- case shareApproval:
- b.addApproval(item)
- case shareError:
- msg := b.scrub.text(firstNonEmptyString(event.Message, errorType(event), event.Event.Action))
- b.append(item, ShareRoleSystem, msg, SharePartV1{Type: SharePartError, Content: ShareErrorContent{Message: msg}})
- default:
- b.addSystem(item)
+ builder.Add(it.event, it.te)
}
-}
-
-const sharePromptNotRetained = "(prompt text not retained)"
-
-// samePrompt finds the user message an earlier capture of this prompt wrote. A prompt.id match is
-// exact. Without one, the newest prompt in the session counts as the same submission only when
-// exactly one of the two copies carries a prompt.id (they came from different capture paths), they
-// are within sharePromptPairWindow, and their texts agree or one of them retained none.
-func (b *shareBuilder) samePrompt(item shareEvent, key, text string) *ShareMessageV1 {
- if key != "" {
- if existing := b.prompts[key]; existing != nil {
- return existing
- }
- }
- last := b.lastPrompt[sharePromptScope(item.event)]
- if last == nil || last.keyed == (key != "") || !last.hasTS || !item.hasTS {
- return nil
+ if builder == nil {
+ builder = NewTraceBuilder(shareTraceID(Event{}), Event{})
}
- gap := item.ts.Sub(last.ts)
- if gap < 0 {
- gap = -gap
+ bundle := builder.Bundle(provenance)
+ bundle.Range = nil
+ if bundle.Events == nil {
+ bundle.Events = []TraceEventV1{}
}
- if gap > sharePromptPairWindow {
- return nil
- }
- if text != "" && last.message.Text != sharePromptNotRetained && b.scrub.text(text) != last.message.Text {
- return nil
- }
- if key != "" {
- b.prompts[key] = last.message
- }
- last.keyed = true
- return last.message
-}
-
-func sharePromptScope(event Event) string {
- session := ""
- if event.Session != nil {
- session = event.Session.ID
- }
- return NormalizeHarnessName(event.Harness.Name) + "\x00" + session
-}
-
-// sharePromptKey names one user prompt across capture paths: prompt.id is the runtime's own id for
-// the turn, which a hook and the OTLP export both carry.
-func sharePromptKey(event Event) string {
- if event.Prompt == nil || strings.TrimSpace(event.Prompt.ID) == "" {
- return ""
- }
- session := ""
- if event.Session != nil {
- session = event.Session.ID
- }
- return NormalizeHarnessName(event.Harness.Name) + "\x00" + session + "\x00" + strings.TrimSpace(event.Prompt.ID)
-}
-
-func (b *shareBuilder) newMessage(item shareEvent, id, role, text string, parts ...SharePartV1) *ShareMessageV1 {
- for i := range parts {
- parts[i].Order = i + 1
- }
- message := &ShareMessageV1{
- ID: id,
- Role: role,
- Timestamp: shareTimestamp(item),
- Model: shareModel(item.event),
- Text: text,
- Parts: parts,
- }
- if usage := shareUsage(item.event); usage != nil {
- message.TokenUsage = usage
- }
- return message
-}
-
-func (b *shareBuilder) append(item shareEvent, role, text string, parts ...SharePartV1) *ShareMessageV1 {
- message := b.newMessage(item, item.id, role, text, parts...)
- b.messages = append(b.messages, message)
- return message
+ shareSummaryForPublication(&bundle.Summary, events, opts)
+ return bundle
}
-func (b *shareBuilder) appendText(item shareEvent, role, partType, text string) {
- text = b.scrub.text(text)
- b.append(item, role, text, SharePartV1{Type: partType, Content: ShareTextContent{Text: text}})
-}
-
-func (b *shareBuilder) addTool(item shareEvent) {
- event := item.event
- callID := ToolCallID(&event)
- toolName := shareToolName(event)
- invocation := isShareInvocation(event)
- explicit := invocation
- completion := !invocation && isShareCompletion(event)
-
- if !invocation && !completion {
- // Neither phase is explicit (a file read a hook observed, an MCP call a transcript recorded).
- // It completes a call already on the trace, and is a call of its own otherwise.
- if callID != "" && b.calls[callID] != nil {
- completion = true
- } else if callID == "" {
- if paired := b.pairPending(event, toolName); paired != "" {
- callID = paired
- completion = true
- }
- }
- if !completion {
- invocation = true
- }
- }
-
- if invocation {
- if callID != "" && b.calls[callID] != nil {
- mergeToolCall(b.calls[callID], b.toolCallContent(event, callID, toolName))
- return
+// shareTraceID names the shared bundle the way the dashboard names a session's trace.
+func shareTraceID(event Event) string {
+ if event.Session != nil && strings.TrimSpace(event.Session.ID) != "" {
+ harness := NormalizeHarnessName(event.Harness.Name)
+ if harness == "" {
+ harness = strings.TrimSpace(event.Harness.Name)
}
- named := callID != ""
- if !named {
- callID = item.id
- }
- call := b.toolCallContent(event, callID, toolName)
- message := b.append(item, ShareRoleAssistant, shareToolCallText(call), SharePartV1{Type: SharePartToolCall, Content: call})
- b.calls[callID] = call
- b.callMessage[callID] = message
- // Only an explicit invocation waits for a result. A phase-less event promoted to a call
- // is already whole; queuing it would turn the next read of the same file into its result.
- if !named && explicit {
- b.pending = append(b.pending, callID)
- }
- return
- }
-
- // A completion.
- if callID == "" {
- callID = b.pairPending(event, toolName)
- }
- if callID != "" && b.results[callID] != nil {
- mergeToolResult(b.results[callID], b.toolResultContent(event, callID, toolName))
- if call := b.calls[callID]; call != nil {
- mergeToolCall(call, b.toolCallContent(event, callID, toolName))
- }
- return
- }
- if callID == "" || b.calls[callID] == nil {
- // No invocation on the trace: the runtime reported only the finished call (a poll backfill,
- // a post-tool hook alone). Write the call just ahead of its result.
- if callID == "" {
- callID = item.id
- }
- call := b.toolCallContent(event, callID, toolName)
- message := b.newMessage(item, eventUUID("share-call", item.id), ShareRoleAssistant, shareToolCallText(call), SharePartV1{Type: SharePartToolCall, Content: call})
- message.TokenUsage = nil
- b.messages = append(b.messages, message)
- b.calls[callID] = call
- b.callMessage[callID] = message
- } else {
- // The completion often carries what the invocation did not: the diff, the command line.
- mergeToolCall(b.calls[callID], b.toolCallContent(event, callID, toolName))
+ return "session:" + harness + ":" + strings.TrimSpace(event.Session.ID)
}
- if toolName == "" {
- toolName = b.calls[callID].ToolName
- }
- result := b.toolResultContent(event, callID, toolName)
- b.append(item, ShareRoleAssistant, shareToolResultText(result), SharePartV1{Type: SharePartToolResult, Content: result})
- b.results[callID] = result
+ return TraceProjectionID(event)
}
-// pairPending finds the most recent unanswered invocation without a runtime call id for the same
-// tool, removes it from the queue and returns its call id.
-func (b *shareBuilder) pairPending(event Event, toolName string) string {
- command, path := shareCommand(event), shareFilePath(event)
- for i := len(b.pending) - 1; i >= 0; i-- {
- id := b.pending[i]
- call := b.calls[id]
- if call == nil || b.results[id] != nil {
- continue
- }
- if normalizeToolName(call.ToolName) != normalizeToolName(toolName) {
- continue
- }
- if command != "" && call.Command != "" && b.scrub.text(command) != call.Command {
- continue
- }
- if path != "" && call.FilePath != "" && b.scrub.path(path) != call.FilePath {
- continue
- }
- b.pending = append(b.pending[:i], b.pending[i+1:]...)
- return id
+// shareSummaryForPublication replaces the summary's local paths with what a reader elsewhere can
+// use, from the session's original (unscrubbed) events.
+func shareSummaryForPublication(summary *TraceSummaryV1, events []Event, opts ShareOptions) {
+ if summary.Session != nil {
+ summary.Session.WorkingDirectory = ""
}
- return ""
-}
-
-func (b *shareBuilder) toolCallContent(event Event, callID, toolName string) *ShareToolCallContent {
- call := &ShareToolCallContent{
- CallID: callID,
- ToolName: toolName,
- ToolKind: ShareToolKind(toolName, event.Event.Action, event.Event.Category, event.MCP != nil),
- Args: b.scrub.args(shareToolArgs(event)),
- Command: b.scrub.text(shareCommand(event)),
- FilePath: b.scrub.path(shareFilePath(event)),
- }
- if event.File != nil {
- call.Diff = b.scrub.text(event.File.Diff)
- }
- if call.Args == nil {
- call.Args = map[string]interface{}{}
- }
- return call
-}
-
-func (b *shareBuilder) toolResultContent(event Event, callID, toolName string) *ShareToolResultContent {
- result := &ShareToolResultContent{
- CallID: callID,
- ToolName: toolName,
- Output: b.scrub.text(shareToolOutput(event)),
- Status: ShareStatusSuccess,
- }
- if event.Command != nil {
- if event.Command.ExitCode != nil {
- code := *event.Command.ExitCode
- result.ExitCode = &code
- }
- if event.Command.DurationMS > 0 {
- ms := event.Command.DurationMS
- result.DurationMS = &ms
+ home := opts.HomeDirectory
+ var remote, branch, ref, project, workDir string
+ for _, event := range events {
+ if workDir == "" && event.Session != nil {
+ workDir = strings.TrimSpace(event.Session.WorkingDirectory)
}
- }
- if shareFailed(event) {
- result.Status = ShareStatusError
- }
- return result
-}
-
-func mergeToolCall(dst, src *ShareToolCallContent) {
- if dst.ToolName == "" {
- dst.ToolName = src.ToolName
- }
- if dst.ToolKind == "" || dst.ToolKind == ShareToolKindOther {
- dst.ToolKind = src.ToolKind
- }
- if len(dst.Args) == 0 && len(src.Args) > 0 {
- dst.Args = src.Args
- }
- if dst.Command == "" {
- dst.Command = src.Command
- }
- if dst.FilePath == "" {
- dst.FilePath = src.FilePath
- }
- if dst.Diff == "" {
- dst.Diff = src.Diff
- }
-}
-
-func mergeToolResult(dst, src *ShareToolResultContent) {
- if dst.ToolName == "" {
- dst.ToolName = src.ToolName
- }
- if dst.Output == "" {
- dst.Output = src.Output
- }
- if dst.ExitCode == nil {
- dst.ExitCode = src.ExitCode
- }
- if dst.DurationMS == nil {
- dst.DurationMS = src.DurationMS
- }
- if src.Status == ShareStatusError {
- dst.Status = ShareStatusError
- }
-}
-
-func (b *shareBuilder) addApproval(item shareEvent) {
- event := item.event
- content := map[string]interface{}{}
- action := strings.ToLower(event.Event.Action)
- subtype := "approval"
- if strings.HasPrefix(action, "policy.") || (event.Policy != nil && event.Approval == nil) {
- subtype = "policy"
- }
- content["subtype"] = subtype
- content["action"] = event.Event.Action
- if event.Approval != nil {
- putString(content, "decision", event.Approval.Decision)
- putString(content, "reason", b.scrub.text(event.Approval.Reason))
- if event.Approval.Required {
- content["required"] = true
+ if event.VCS != nil {
+ if event.VCS.Repository != nil && event.VCS.Repository.URL != nil && remote == "" {
+ remote = ShareRemoteURL(event.VCS.Repository.URL.Full)
+ }
+ if event.VCS.Ref != nil && event.VCS.Ref.Head != nil {
+ if branch == "" {
+ branch = ShareBranch(event.VCS.Ref.Head.Name)
+ }
+ // The newest commit wins: a session that made several is described by the last.
+ if event.VCS.Ref.Head.Revision != "" {
+ ref = event.VCS.Ref.Head.Revision
+ }
+ }
}
- }
- if event.Policy != nil {
- putString(content, "policyDecision", event.Policy.Decision)
- putString(content, "enforcement", event.Policy.Enforcement)
- putString(content, "policyName", event.Policy.Name)
- if _, ok := content["reason"]; !ok {
- putString(content, "reason", b.scrub.text(event.Policy.Reason))
+ if event.Run != nil {
+ if ref == "" {
+ ref = event.Run.Commit
+ }
+ if branch == "" {
+ branch = ShareBranch(event.Run.Branch)
+ }
+ if project == "" {
+ project = shareProjectName(event.Run.Repository, home)
+ }
}
- }
- putString(content, "toolName", shareToolName(event))
- putString(content, "callId", ToolCallID(&event))
- putString(content, "command", b.scrub.text(shareCommand(event)))
- putString(content, "fidelity", event.Event.Fidelity)
- text := strings.TrimSpace(strings.Join(nonEmpty(event.Event.Action, stringField(content, "toolName"), stringField(content, "decision")), " "))
- b.append(item, ShareRoleSystem, text, SharePartV1{Type: SharePartSystemEvent, Content: content})
-}
-
-func (b *shareBuilder) addSystem(item shareEvent) {
- event := item.event
- content := map[string]interface{}{"subtype": event.Event.Action}
- if event.Handoff != nil {
- putString(content, "sourceHarness", event.Handoff.SourceHarness)
- putString(content, "sourceSessionId", event.Handoff.SourceSessionID)
- }
- if event.VCS != nil && event.VCS.Ref != nil && event.VCS.Ref.Head != nil {
- putString(content, "commit", event.VCS.Ref.Head.Revision)
- putString(content, "branch", event.VCS.Ref.Head.Name)
- }
- if event.SystemContext != nil {
- putString(content, "contextKind", event.SystemContext.Kind)
- }
- putString(content, "fidelity", event.Event.Fidelity)
- summary := b.scrub.text(TruncateString(strings.TrimSpace(event.Message), 500))
- putString(content, "summary", summary)
- b.append(item, ShareRoleSystem, firstNonEmptyString(summary, event.Event.Action), SharePartV1{Type: SharePartSystemEvent, Content: content})
-}
-
-func sharePromptText(event Event) string {
- if event.Prompt != nil && strings.TrimSpace(event.Prompt.Text) != "" {
- return strings.TrimSpace(event.Prompt.Text)
- }
- if event.GenAI != nil && event.GenAI.Input != nil {
- if parts := GenAIText(event.GenAI.Input.Messages, RoleUser, GenAIPartTypeText); len(parts) > 0 {
- return boundShareText(strings.Join(parts, "\n\n"))
+ if project == "" {
+ project = shareProjectName(event.Repository, home)
}
}
- return ""
-}
-
-// shareAssistantText reads retained assistant text of partType from gen_ai.output.messages. The
-// event message is used only when it is not one of the fixed labels writers put there.
-func shareAssistantText(event Event, partType string) string {
- if event.GenAI != nil && event.GenAI.Output != nil {
- if parts := GenAIText(event.GenAI.Output.Messages, RoleAssistant, partType); len(parts) > 0 {
- return boundShareText(strings.Join(parts, "\n\n"))
- }
+ if project == "" && remote != "" {
+ project = strings.TrimSuffix(lastPathSegment(remote), ".git")
}
- if event.Content != nil && event.Content.Included && strings.TrimSpace(event.Message) != "" && !looksLikeLabel(event.Message) {
- return strings.TrimSpace(event.Message)
+ if project == "" {
+ project = shareProjectName(workDir, home)
}
- return ""
-}
-
-// looksLikeLabel recognizes the fixed descriptions writers put in event.message ("Codex assistant
-// message", "Claude Code reasoning observed"), which are not what the assistant said.
-func looksLikeLabel(message string) bool {
- lower := strings.ToLower(strings.TrimSpace(message))
- for _, suffix := range []string{" observed", " message", " reasoning", " response", " completed"} {
- if strings.HasSuffix(lower, suffix) && utf8.RuneCountInString(lower) < 60 {
- return true
- }
+ repo := summary.Repository
+ if repo == nil {
+ repo = &TraceRepositoryV1{}
}
- return false
-}
-
-// boundShareText holds text joined from several stored parts to the limit one part is stored at,
-// and redacts it again, as the dashboard does for the same joined text.
-func boundShareText(text string) string {
- return RedactString(TruncateString(text, DefaultStringLimit))
-}
-
-func shareToolName(event Event) string {
- if event.Tool != nil && strings.TrimSpace(event.Tool.Name) != "" {
- return strings.TrimSpace(event.Tool.Name)
+ repo.Path = project
+ repo.Branch = ShareBranch(repo.Branch)
+ if repo.Branch == "" {
+ repo.Branch = branch
}
- if event.GenAI != nil && event.GenAI.Tool != nil && strings.TrimSpace(event.GenAI.Tool.Name) != "" {
- return strings.TrimSpace(event.GenAI.Tool.Name)
+ if repo.RemoteURL == "" {
+ repo.RemoteURL = remote
}
- if event.MCP != nil && strings.TrimSpace(event.MCP.Tool) != "" {
- if event.MCP.Server != "" {
- return "mcp__" + event.MCP.Server + "__" + event.MCP.Tool
- }
- return event.MCP.Tool
+ if repo.Ref == "" {
+ repo.Ref = ref
}
- switch {
- case event.Command != nil && event.Command.Command != "":
- return "shell"
- case event.File != nil:
- switch strings.ToLower(event.Event.Action) {
- case "file.read":
- return "read"
- case "file.created":
- return "write"
- case "file.deleted":
- return "delete"
- default:
- return "edit"
- }
+ if *repo == (TraceRepositoryV1{}) {
+ summary.Repository = nil
+ } else {
+ summary.Repository = repo
}
- return ""
}
-func shareCommand(event Event) string {
- if event.Command != nil && strings.TrimSpace(event.Command.Command) != "" {
- return strings.TrimSpace(event.Command.Command)
- }
- if event.Tool != nil {
- return strings.TrimSpace(event.Tool.Command)
+// shareProjectName is the last segment of a directory or repository name, unless it is the home
+// directory, whose name is the local account's.
+func shareProjectName(value, home string) string {
+ value = strings.TrimSpace(value)
+ if value == "" || samePath(value, home) {
+ return ""
}
- return ""
+ return lastPathSegment(value)
}
-func shareFilePath(event Event) string {
- if event.File != nil && strings.TrimSpace(event.File.Path) != "" {
- return strings.TrimSpace(event.File.Path)
+// NewShareTrace is the PUT body for a bundle built by BuildShareBundle: its summary, the requested
+// visibility, a title from its first prompt (ShareTitle), and its provenance.
+func NewShareTrace(bundle TraceBundleV1, visibility string) ShareTraceV1 {
+ trace := ShareTraceV1{
+ SchemaVersion: TraceSchemaVersion,
+ Summary: bundle.Summary,
+ Visibility: visibility,
+ Source: ShareSourceCLI,
+ Provenance: bundle.Provenance,
}
- if event.Tool != nil {
- return strings.TrimSpace(event.Tool.Path)
+ trace.Summary.Sharing = TraceSharingV1{State: "shared", Visibility: visibility}
+ for _, event := range bundle.Events {
+ if event.Type == "user_message" && event.Content != nil && strings.TrimSpace(event.Content.Text) != "" {
+ trace.Title = ShareTitle(event.Content.Text)
+ break
+ }
}
- return ""
+ return trace
}
-// shareToolArgs returns the call's arguments: gen_ai.tool.call.arguments when it is an object (or
-// a JSON object in a string), otherwise the tool input a hook kept in raw.
-func shareToolArgs(event Event) map[string]interface{} {
- if event.GenAI != nil && event.GenAI.Tool != nil && event.GenAI.Tool.Call != nil {
- if args := objectValue(event.GenAI.Tool.Call.Arguments); args != nil {
- return args
- }
- }
+// rawToolArgs is the tool input a hook kept in raw, when it is an object.
+func rawToolArgs(raw map[string]interface{}) map[string]interface{} {
for _, key := range []string{"tool_input", "toolInput", "arguments", "args", "input"} {
- if args := objectValue(event.Raw[key]); args != nil {
+ if args := objectValue(raw[key]); args != nil {
return args
}
}
return nil
}
-func objectValue(value interface{}) map[string]interface{} {
- switch typed := value.(type) {
- case map[string]interface{}:
- if len(typed) == 0 {
- return nil
- }
- return typed
- case string:
- trimmed := strings.TrimSpace(typed)
- if !strings.HasPrefix(trimmed, "{") {
- return nil
- }
- var out map[string]interface{}
- if json.Unmarshal([]byte(trimmed), &out) == nil && len(out) > 0 {
- return SanitizeMap(out, PrivacyOptions{RedactSecrets: true, StringLimit: DefaultRawStringLimit})
- }
- case nil:
- return nil
- default:
- data, err := json.Marshal(typed)
- if err != nil {
- return nil
- }
- var out map[string]interface{}
- if json.Unmarshal(data, &out) == nil && len(out) > 0 {
- return out
- }
- }
- return nil
-}
-
-func shareToolOutput(event Event) string {
- if event.Command != nil && strings.TrimSpace(event.Command.Output) != "" {
- return event.Command.Output
- }
- if event.GenAI != nil && event.GenAI.Tool != nil && event.GenAI.Tool.Call != nil && event.GenAI.Tool.Call.Result != nil {
- return boundShareText(ToolResultPlainText(event.GenAI.Tool.Call.Result))
- }
- return ""
-}
-
-func shareFailed(event Event) bool {
- action := strings.ToLower(event.Event.Action)
- if strings.Contains(action, "fail") || strings.Contains(action, "error") || strings.Contains(action, "denied") {
- return true
- }
- if event.Error != nil && event.Error.Type != "" {
- return true
- }
- return event.Command != nil && event.Command.ExitCode != nil && *event.Command.ExitCode != 0
-}
-
-func errorType(event Event) string {
- if event.Error != nil {
- return event.Error.Type
- }
- return ""
-}
-
-func shareToolCallText(call *ShareToolCallContent) string {
- detail := firstNonEmptyString(call.Command, call.FilePath)
- if detail == "" {
- return call.ToolName
- }
- if call.ToolName == "" {
- return TruncateString(detail, 1024)
- }
- return TruncateString(call.ToolName+": "+detail, 1024)
-}
-
-func shareToolResultText(result *ShareToolResultContent) string {
- if result.Output != "" {
- return TruncateString(result.Output, 1024)
- }
- return strings.TrimSpace(result.ToolName + " " + result.Status)
-}
-
-func shareTimestamp(item shareEvent) string {
- if item.hasTS {
- return item.ts.UTC().Format(time.RFC3339Nano)
- }
- return item.event.Timestamp
-}
-
-func shareModel(event Event) string {
- model := event.Model
- if model == "" && event.GenAI != nil {
- if event.GenAI.Response != nil && event.GenAI.Response.Model != "" {
- model = event.GenAI.Response.Model
- } else if event.GenAI.Request != nil {
- model = event.GenAI.Request.Model
- }
- }
- return NormalizeModelName(model)
-}
-
-func shareUsage(event Event) *ShareTokenUsageV1 {
- if event.GenAI == nil || event.GenAI.Usage == nil {
- return nil
- }
- usage := ShareTokenUsageFromGenAI(event.GenAI.Usage)
- if usage.IsZero() {
- return nil
- }
- return &usage
-}
-
-// ShareTokenUsageFromGenAI flattens one gen_ai.usage block. The one-hour cache-write subset is a
-// breakdown of cache_creation and has no field of its own in the contract.
-func ShareTokenUsageFromGenAI(usage *GenAIUsageInfo) ShareTokenUsageV1 {
- var out ShareTokenUsageV1
- if usage == nil {
- return out
- }
- if usage.InputTokens != nil {
- out.InputTokens = *usage.InputTokens
- }
- if usage.OutputTokens != nil {
- out.OutputTokens = *usage.OutputTokens
- }
- if usage.CacheRead != nil && usage.CacheRead.InputTokens != nil {
- out.CacheReadInputTokens = *usage.CacheRead.InputTokens
- }
- if usage.CacheCreation != nil && usage.CacheCreation.InputTokens != nil {
- out.CacheCreationInputTokens = *usage.CacheCreation.InputTokens
- }
- if usage.Reasoning != nil && usage.Reasoning.OutputTokens != nil {
- out.ReasoningOutputTokens = *usage.Reasoning.OutputTokens
- }
- return out
-}
-
-func putString(m map[string]interface{}, key, value string) {
- if value = strings.TrimSpace(value); value != "" {
- m[key] = value
+// cloneEvent deep-copies an event through its JSON form, so sanitizing and scrubbing never write
+// into the caller's events.
+func cloneEvent(event Event) Event {
+ data, err := json.Marshal(event)
+ if err != nil {
+ return event
}
-}
-
-func stringField(m map[string]interface{}, key string) string {
- value, _ := m[key].(string)
- return value
-}
-
-func nonEmpty(values ...string) []string {
- out := values[:0:0]
- for _, value := range values {
- if strings.TrimSpace(value) != "" {
- out = append(out, value)
- }
+ var out Event
+ if err := json.Unmarshal(data, &out); err != nil {
+ return event
}
return out
}
@@ -1399,136 +558,91 @@ func (s pathScrubber) value(value interface{}) interface{} {
return value
}
-// ShareMetadataFromEvents derives a trace's metadata from its events: the agent, a title from the
-// first prompt, the model used most, repository context, summed token usage and runtime-reported
-// cost, and the source session's first and last timestamps. Visibility is left for the caller.
-//
-// Token usage here is a plain sum of every event's gen_ai.usage. That is right for span and
-// per-request usage and wrong for cumulative metric series and for a session captured both live
-// and by a poll backfill; a caller with the CLI's token aggregator (cli/beacon/internal/tokens,
-// which resolves both) should replace TokenUsage and CostUSD with its totals.
-func ShareMetadataFromEvents(events []Event) ShareTraceV1 {
- return ShareMetadataFromEventsWithOptions(events, ShareOptions{})
-}
-
-// ShareMetadataFromEventsWithOptions is ShareMetadataFromEvents with the path options the title is
-// scrubbed with.
-func ShareMetadataFromEventsWithOptions(events []Event, opts ShareOptions) ShareTraceV1 {
- meta := ShareTraceV1{SchemaVersion: ShareSchemaVersion, Source: ShareSourceCLI}
- items := orderShareEvents(events)
- models := map[string]int{}
- var modelOrder []string
- var usage ShareTokenUsageV1
- var cost float64
- var hasCost bool
- var workDir, firstPrompt string
- seen := map[string]bool{}
- for _, item := range items {
- event := item.event
- if strings.EqualFold(event.Event.Action, "session.shared") {
- continue
- }
- if meta.AgentID == "" {
- meta.AgentID = NormalizeHarnessName(event.Harness.Name)
- }
- if meta.SourceSessionID == "" && event.Session != nil {
- meta.SourceSessionID = strings.TrimSpace(event.Session.ID)
- }
- if workDir == "" && event.Session != nil {
- workDir = strings.TrimSpace(event.Session.WorkingDirectory)
- }
- if item.hasTS {
- ts := item.ts.UTC().Format(time.RFC3339Nano)
- if meta.SourceCreatedAt == "" {
- meta.SourceCreatedAt = ts
- }
- meta.SourceUpdatedAt = ts
- }
- if firstPrompt == "" && classifyShareEvent(event) == sharePrompt {
- firstPrompt = sharePromptText(event)
- }
- if model := shareModel(event); model != "" {
- if models[model] == 0 {
- modelOrder = append(modelOrder, model)
- }
- models[model]++
- }
- if !seen[item.id] && event.GenAI != nil && event.GenAI.Usage != nil {
- seen[item.id] = true
- u := ShareTokenUsageFromGenAI(event.GenAI.Usage)
- usage.InputTokens += u.InputTokens
- usage.OutputTokens += u.OutputTokens
- usage.CacheReadInputTokens += u.CacheReadInputTokens
- usage.CacheCreationInputTokens += u.CacheCreationInputTokens
- usage.ReasoningOutputTokens += u.ReasoningOutputTokens
- if event.GenAI.Usage.CostUSD != nil {
- cost += *event.GenAI.Usage.CostUSD
- hasCost = true
- }
- }
- if event.VCS != nil {
- if event.VCS.Repository != nil && event.VCS.Repository.URL != nil && meta.GitRemoteURL == "" {
- meta.GitRemoteURL = ShareRemoteURL(event.VCS.Repository.URL.Full)
- }
- if event.VCS.Ref != nil && event.VCS.Ref.Head != nil {
- if ShareBranch(event.VCS.Ref.Head.Name) != "" && meta.GitBranch == "" {
- meta.GitBranch = ShareBranch(event.VCS.Ref.Head.Name)
- }
- // The newest commit wins: a session that made several is described by the last.
- if event.VCS.Ref.Head.Revision != "" {
- meta.GitRef = event.VCS.Ref.Head.Revision
- }
- }
- }
- if event.Run != nil {
- if meta.GitRef == "" {
- meta.GitRef = event.Run.Commit
- }
- if meta.GitBranch == "" {
- meta.GitBranch = ShareBranch(event.Run.Branch)
- }
- if meta.ProjectName == "" {
- meta.ProjectName = lastPathSegment(event.Run.Repository)
- }
- }
- if meta.GitBranch == "" {
- meta.GitBranch = ShareBranch(event.Branch)
- }
- if meta.ProjectName == "" && strings.TrimSpace(event.Repository) != "" {
- meta.ProjectName = lastPathSegment(event.Repository)
- }
- if meta.RelatedTo == "" && event.Handoff != nil && event.Handoff.SourceSessionID != "" && event.Handoff.SourceHarness != "" {
- meta.RelatedTo = ShareExternalID(event.Handoff.SourceHarness, event.Handoff.SourceSessionID)
- meta.RelationshipType = ShareRelationshipResume
- }
- }
- home := opts.HomeDirectory
- if home == "" && !opts.NoHomeLookup {
- home, _ = os.UserHomeDir()
- }
- if firstPrompt != "" {
- meta.Title = ShareTitle(newPathScrubber(firstNonEmptyString(opts.WorkingDirectory, workDir), home).text(firstPrompt))
- }
- best := 0
- for _, model := range modelOrder {
- if models[model] > best {
- meta.Model, best = model, models[model]
- }
+// event rewrites local paths in every field of an event the trace projection reads, on copies, so
+// the caller's event is unchanged. Paths (file, tool path, working directory, repository) are
+// written relative to the working directory; free text (messages, prompts, command lines and
+// output, diffs, reasons) has whole-path occurrences replaced; structured blocks (gen_ai with its
+// retained messages and tool arguments and results, MCP, errors, VCS, CI run, system context, raw)
+// have every string value treated as free text.
+func (s pathScrubber) event(e Event) Event {
+ e.Message = s.text(e.Message)
+ e.Repository = s.path(e.Repository)
+ if e.Session != nil {
+ c := *e.Session
+ c.WorkingDirectory = s.path(c.WorkingDirectory)
+ e.Session = &c
+ }
+ if e.Prompt != nil {
+ c := *e.Prompt
+ c.Text = s.text(c.Text)
+ e.Prompt = &c
+ }
+ if e.Tool != nil {
+ c := *e.Tool
+ c.Name = s.text(c.Name)
+ c.Command = s.text(c.Command)
+ c.Path = s.path(c.Path)
+ e.Tool = &c
+ }
+ if e.Command != nil {
+ c := *e.Command
+ c.Command = s.text(c.Command)
+ c.Output = s.text(c.Output)
+ e.Command = &c
+ }
+ if e.File != nil {
+ c := *e.File
+ c.Path = s.path(c.Path)
+ c.Diff = s.text(c.Diff)
+ e.File = &c
+ }
+ if e.Approval != nil {
+ c := *e.Approval
+ c.Reason = s.text(c.Reason)
+ e.Approval = &c
+ }
+ if e.Policy != nil {
+ c := *e.Policy
+ c.Name = s.text(c.Name)
+ c.Reason = s.text(c.Reason)
+ e.Policy = &c
+ }
+ e.Error = scrubTyped(s, e.Error)
+ e.MCP = scrubTyped(s, e.MCP)
+ e.GenAI = scrubTyped(s, e.GenAI)
+ e.VCS = scrubTyped(s, e.VCS)
+ e.Run = scrubTyped(s, e.Run)
+ e.SystemContext = scrubTyped(s, e.SystemContext)
+ e.Handoff = scrubTyped(s, e.Handoff)
+ if e.Raw != nil {
+ e.Raw = s.args(e.Raw)
+ }
+ return e
+}
+
+// scrubTyped rewrites every string in a structured block as free text, through its JSON form. A
+// block that does not survive the round trip is dropped rather than published unscrubbed.
+func scrubTyped[T any](s pathScrubber, input *T) *T {
+ if input == nil {
+ return nil
}
- if meta.ProjectName == "" && meta.GitRemoteURL != "" {
- meta.ProjectName = strings.TrimSuffix(lastPathSegment(meta.GitRemoteURL), ".git")
+ data, err := json.Marshal(input)
+ if err != nil {
+ return nil
}
- // The directory's own name, unless it is the home directory, whose name is the local account's.
- if meta.ProjectName == "" && workDir != "" && !samePath(workDir, home) && !samePath(workDir, opts.HomeDirectory) {
- meta.ProjectName = lastPathSegment(workDir)
+ var generic interface{}
+ if err := json.Unmarshal(data, &generic); err != nil {
+ return nil
}
- if !usage.IsZero() {
- meta.TokenUsage = &usage
+ data, err = json.Marshal(s.value(generic))
+ if err != nil {
+ return nil
}
- if hasCost {
- meta.CostUSD = &cost
+ out := new(T)
+ if err := json.Unmarshal(data, out); err != nil {
+ return nil
}
- return meta
+ return out
}
// ShareTitle is a one-line title of at most ShareTitleMaxRunes runes from prompt text, without the
diff --git a/pkg/asymptoteobserve/share_test.go b/pkg/asymptoteobserve/share_test.go
index edb8200f..6373c47a 100644
--- a/pkg/asymptoteobserve/share_test.go
+++ b/pkg/asymptoteobserve/share_test.go
@@ -3,8 +3,10 @@ package asymptoteobserve
import (
"encoding/json"
"fmt"
+ "reflect"
"strings"
"testing"
+ "time"
)
func shareEventAt(ts, harness, method, action, category string) Event {
@@ -32,9 +34,15 @@ func withCall(e Event, id, name string, args interface{}, result interface{}) Ev
return e
}
-var shareTestOpts = ShareOptions{HomeDirectory: "/home/dev"}
+var shareTestOpts = ShareOptions{HomeDirectory: "/home/dev", NoHomeLookup: true}
-func partsOf(t *testing.T, messages []ShareMessageV1) []string {
+// shareMessages is the chat view of the shared bundle built from events: the path every message a
+// shared trace shows goes through.
+func shareMessages(events []Event, opts ShareOptions) []TraceMessageV1 {
+ return TraceMessages(BuildShareBundle(events, opts))
+}
+
+func partsOf(t *testing.T, messages []TraceMessageV1) []string {
t.Helper()
var out []string
for _, m := range messages {
@@ -45,7 +53,7 @@ func partsOf(t *testing.T, messages []ShareMessageV1) []string {
return out
}
-func TestBuildShareMessagesPairsClaudeHookPreAndPost(t *testing.T) {
+func TestShareMessagesPairsClaudeHookPreAndPost(t *testing.T) {
prompt := shareEventAt("2026-10-01T10:00:00.000000000Z", "claude_code", CollectionMethodHook, "prompt.submitted", "prompt")
prompt.Event.ID = "e-prompt"
prompt.Prompt = &PromptInfo{Text: "List the files in /home/dev/src/app please"}
@@ -78,7 +86,7 @@ func TestBuildShareMessagesPairsClaudeHookPreAndPost(t *testing.T) {
// Given out of order, and with the session.shared record that must never become a message.
shared := shareEventAt("2026-10-01T11:00:00.000000000Z", "claude_code", "", "session.shared", "session")
- messages := BuildShareMessagesWithOptions([]Event{answer, otlp, shared, post, usage, pre, prompt}, shareTestOpts)
+ messages := shareMessages([]Event{answer, otlp, shared, post, usage, pre, prompt}, shareTestOpts)
got := partsOf(t, messages)
want := []string{"user/text", "assistant/tool_call", "assistant/tool_result", "assistant/text"}
@@ -96,15 +104,15 @@ func TestBuildShareMessagesPairsClaudeHookPreAndPost(t *testing.T) {
if text := messages[0].Text; text != "List the files in . please" {
t.Fatalf("prompt text not scrubbed: %q", text)
}
- call := messages[1].Parts[0].Content.(*ShareToolCallContent)
- if call.CallID != "toolu_1" || call.ToolKind != ShareToolKindTerminalCommand || call.Command != "ls -la ./cmd" {
+ call := messages[1].Parts[0].Content.(*TraceToolCallContentV1)
+ if call.CallID != "toolu_1" || call.ToolKind != TraceToolKindTerminalCommand || call.Command != "ls -la ./cmd" {
t.Fatalf("call = %+v", call)
}
if call.Args["command"] != "ls -la ./cmd" {
t.Fatalf("args = %+v", call.Args)
}
- result := messages[2].Parts[0].Content.(*ShareToolResultContent)
- if result.CallID != "toolu_1" || result.Output != "main.go\n" || result.Status != ShareStatusSuccess {
+ result := messages[2].Parts[0].Content.(*TraceToolResultContentV1)
+ if result.CallID != "toolu_1" || result.Output != "main.go\n" || result.Status != TraceToolStatusSuccess {
t.Fatalf("result = %+v", result)
}
if result.ExitCode == nil || *result.ExitCode != 0 || result.DurationMS == nil || *result.DurationMS != 42 {
@@ -115,34 +123,34 @@ func TestBuildShareMessagesPairsClaudeHookPreAndPost(t *testing.T) {
}
}
-func TestBuildShareMessagesSynthesizesCallForPollCompletion(t *testing.T) {
+func TestShareMessagesSynthesizesCallForPollCompletion(t *testing.T) {
cmd := shareEventAt("2026-10-01T10:00:00Z", "codex", CollectionMethodPoll, "command.executed", "command")
cmd.Event.ID = "e-cmd"
cmd = withCall(cmd, "call_9", "exec_command", map[string]interface{}{"cmd": "go test ./..."}, nil)
cmd.Command = &CommandInfo{Command: "go test ./...", ExitCode: intPtr(1), Output: "FAIL"}
- messages := BuildShareMessagesWithOptions([]Event{cmd}, shareTestOpts)
+ messages := shareMessages([]Event{cmd}, shareTestOpts)
if got := partsOf(t, messages); strings.Join(got, ",") != "assistant/tool_call,assistant/tool_result" {
t.Fatalf("parts = %v", got)
}
if messages[0].ID == "e-cmd" || messages[1].ID != "e-cmd" {
t.Fatalf("ids = %s %s", messages[0].ID, messages[1].ID)
}
- again := BuildShareMessagesWithOptions([]Event{cmd}, shareTestOpts)
+ again := shareMessages([]Event{cmd}, shareTestOpts)
if again[0].ID != messages[0].ID {
t.Fatalf("synthesized call id is not stable: %s vs %s", again[0].ID, messages[0].ID)
}
- call := messages[0].Parts[0].Content.(*ShareToolCallContent)
- if call.CallID != "call_9" || call.ToolKind != ShareToolKindTerminalCommand || call.Args["cmd"] != "go test ./..." {
+ call := messages[0].Parts[0].Content.(*TraceToolCallContentV1)
+ if call.CallID != "call_9" || call.ToolKind != TraceToolKindTerminalCommand || call.Args["cmd"] != "go test ./..." {
t.Fatalf("call = %+v", call)
}
- result := messages[1].Parts[0].Content.(*ShareToolResultContent)
- if result.Status != ShareStatusError || result.ExitCode == nil || *result.ExitCode != 1 {
+ result := messages[1].Parts[0].Content.(*TraceToolResultContentV1)
+ if result.Status != TraceToolStatusError || result.ExitCode == nil || *result.ExitCode != 1 {
t.Fatalf("result = %+v", result)
}
}
-func TestBuildShareMessagesPairsCallsWithoutRuntimeIDs(t *testing.T) {
+func TestShareMessagesPairsCallsWithoutRuntimeIDs(t *testing.T) {
// Cursor-shaped: no tool call id on either hook. The edit's diff arrives on the completion and
// belongs on the call.
before := shareEventAt("2026-10-01T10:00:00Z", "cursor", CollectionMethodHook, "tool.invoked", "tool")
@@ -160,27 +168,27 @@ func TestBuildShareMessagesPairsCallsWithoutRuntimeIDs(t *testing.T) {
read.Event.ID = "c-read"
read.File = &FileInfo{Path: "/home/dev/notes.txt", Operation: "read"}
- messages := BuildShareMessagesWithOptions([]Event{before, after, edit, read}, shareTestOpts)
+ messages := shareMessages([]Event{before, after, edit, read}, shareTestOpts)
want := "assistant/tool_call,assistant/tool_result,assistant/tool_call,assistant/tool_result,assistant/tool_call"
if got := partsOf(t, messages); strings.Join(got, ",") != want {
t.Fatalf("parts = %v", got)
}
- call := messages[0].Parts[0].Content.(*ShareToolCallContent)
- result := messages[1].Parts[0].Content.(*ShareToolResultContent)
+ call := messages[0].Parts[0].Content.(*TraceToolCallContentV1)
+ result := messages[1].Parts[0].Content.(*TraceToolResultContentV1)
if result.CallID != call.CallID || call.CallID != "c-before" {
t.Fatalf("not paired: call %q result %q", call.CallID, result.CallID)
}
- editCall := messages[2].Parts[0].Content.(*ShareToolCallContent)
- if editCall.FilePath != "main.go" || editCall.ToolKind != ShareToolKindEdit || editCall.Diff == "" {
+ editCall := messages[2].Parts[0].Content.(*TraceToolCallContentV1)
+ if editCall.FilePath != "main.go" || editCall.ToolKind != TraceToolKindEdit || editCall.Diff == "" {
t.Fatalf("edit call = %+v", editCall)
}
- readCall := messages[4].Parts[0].Content.(*ShareToolCallContent)
- if readCall.FilePath != "~/notes.txt" || readCall.ToolKind != ShareToolKindRead {
+ readCall := messages[4].Parts[0].Content.(*TraceToolCallContentV1)
+ if readCall.FilePath != "~/notes.txt" || readCall.ToolKind != TraceToolKindRead {
t.Fatalf("read call = %+v", readCall)
}
}
-func TestBuildShareMessagesTranscriptMCPAndApproval(t *testing.T) {
+func TestShareMessagesTranscriptMCPAndApproval(t *testing.T) {
invoke := shareEventAt("2026-10-01T10:00:00Z", "claude_code", CollectionMethodPoll, "mcp.tool_invoked", "mcp")
invoke.Event.ID = "m-invoke"
invoke = withCall(invoke, "toolu_m", "mcp__github__search", map[string]interface{}{"q": "beacon"}, nil)
@@ -201,34 +209,34 @@ func TestBuildShareMessagesTranscriptMCPAndApproval(t *testing.T) {
reasoning.Event.ID = "m-think"
reasoning.GenAI = &GenAIInfo{Output: &GenAIOutputInfo{Messages: ReasoningOutputMessages("Consider the cache.")}}
- messages := BuildShareMessagesWithOptions([]Event{invoke, done, approval, start, failure, reasoning}, shareTestOpts)
+ messages := shareMessages([]Event{invoke, done, approval, start, failure, reasoning}, shareTestOpts)
want := "system/system_event,assistant/tool_call,assistant/tool_result,system/system_event,system/error,assistant/thinking"
if got := partsOf(t, messages); strings.Join(got, ",") != want {
t.Fatalf("parts = %v", got)
}
- call := messages[1].Parts[0].Content.(*ShareToolCallContent)
- if call.ToolKind != ShareToolKindMCP || call.Args["q"] != "beacon" {
+ call := messages[1].Parts[0].Content.(*TraceToolCallContentV1)
+ if call.ToolKind != TraceToolKindMCP || call.Args["q"] != "beacon" {
t.Fatalf("mcp call = %+v", call)
}
- if result := messages[2].Parts[0].Content.(*ShareToolResultContent); result.Output != "3 results" || result.CallID != "toolu_m" {
+ if result := messages[2].Parts[0].Content.(*TraceToolResultContentV1); result.Output != "3 results" || result.CallID != "toolu_m" {
t.Fatalf("mcp result = %+v", result)
}
ev := messages[3].Parts[0].Content.(map[string]interface{})
if ev["subtype"] != "approval" || ev["decision"] != "deny" || ev["toolName"] != "bash" {
t.Fatalf("approval = %+v", ev)
}
- if messages[4].Parts[0].Content.(ShareErrorContent).Message != "provider returned 500" {
+ if messages[4].Parts[0].Content.(TraceErrorContentV1).Message != "provider returned 500" {
t.Fatalf("error = %+v", messages[4])
}
}
-func TestBuildShareMessagesSanitizesContent(t *testing.T) {
+func TestShareMessagesSanitizesContent(t *testing.T) {
prompt := shareEventAt("2026-10-01T10:00:00Z", "codex", CollectionMethodHook, "prompt.submitted", "prompt")
prompt.Prompt = &PromptInfo{Text: "use api_key=supersecretvalue123 to call it"}
cmd := shareEventAt("2026-10-01T10:00:01Z", "codex", CollectionMethodHook, "command.executed", "command")
cmd.Command = &CommandInfo{Command: "curl -H 'Authorization: Bearer abc.def.ghi' x", Output: "token=zzzzzzzzzzzz"}
- messages := BuildShareMessagesWithOptions([]Event{prompt, cmd}, shareTestOpts)
+ messages := shareMessages([]Event{prompt, cmd}, shareTestOpts)
data, err := json.Marshal(messages)
if err != nil {
t.Fatal(err)
@@ -238,64 +246,64 @@ func TestBuildShareMessagesSanitizesContent(t *testing.T) {
t.Fatalf("secret %q reached the payload: %s", secret, data)
}
}
- if messages[0].ID == "" || messages[0].ID != ShareMessageID(prompt) {
+ if messages[0].ID == "" || messages[0].ID != ShareEventID(prompt) {
t.Fatalf("derived id %q does not match ShareMessageID", messages[0].ID)
}
}
-func TestBuildShareMessagesIsDeterministic(t *testing.T) {
+func TestShareMessagesIsDeterministic(t *testing.T) {
a := shareEventAt("2026-10-01T10:00:00Z", "codex", CollectionMethodHook, "prompt.submitted", "prompt")
a.Event.ID = "b"
a.Prompt = &PromptInfo{Text: "one"}
b := shareEventAt("2026-10-01T10:00:00Z", "codex", CollectionMethodHook, "prompt.submitted", "prompt")
b.Event.ID = "a"
b.Prompt = &PromptInfo{Text: "two"}
- first, _ := json.Marshal(BuildShareMessagesWithOptions([]Event{a, b}, shareTestOpts))
- second, _ := json.Marshal(BuildShareMessagesWithOptions([]Event{b, a}, shareTestOpts))
+ first, _ := json.Marshal(shareMessages([]Event{a, b}, shareTestOpts))
+ second, _ := json.Marshal(shareMessages([]Event{b, a}, shareTestOpts))
if string(first) != string(second) {
t.Fatalf("order depends on input:\n%s\n%s", first, second)
}
- if !strings.Contains(string(first), `"id":"a","order":1`) {
+ if messages := shareMessages([]Event{a, b}, shareTestOpts); messages[0].ID != "a" || messages[0].Order != 1 {
t.Fatalf("ties are not broken by id: %s", first)
}
}
-func TestShareToolKind(t *testing.T) {
+func TestTraceToolKind(t *testing.T) {
cases := []struct {
name, action, category string
mcp bool
want string
}{
- {"Bash", "tool.invoked", "tool", false, ShareToolKindTerminalCommand},
- {"exec_command", "", "", false, ShareToolKindTerminalCommand},
- {"run_terminal_cmd", "", "", false, ShareToolKindTerminalCommand},
- {"shell", "", "", false, ShareToolKindTerminalCommand},
- {"Read", "", "", false, ShareToolKindRead},
- {"view", "", "", false, ShareToolKindRead},
- {"read_file", "", "", false, ShareToolKindRead},
- {"Edit", "", "", false, ShareToolKindEdit},
- {"MultiEdit", "", "", false, ShareToolKindEdit},
- {"apply_patch", "", "", false, ShareToolKindEdit},
- {"str_replace_editor", "", "", false, ShareToolKindEdit},
- {"Write", "", "", false, ShareToolKindWrite},
- {"create_file", "", "", false, ShareToolKindWrite},
- {"Grep", "", "", false, ShareToolKindGrep},
- {"Glob", "", "", false, ShareToolKindGlob},
- {"WebSearch", "", "", false, ShareToolKindWebSearch},
- {"WebFetch", "", "", false, ShareToolKindWebFetch},
- {"Task", "", "", false, ShareToolKindTask},
- {"TodoWrite", "", "", false, ShareToolKindTodo},
- {"update_plan", "", "", false, ShareToolKindTodo},
- {"mcp__github__search", "", "", false, ShareToolKindMCP},
- {"search_issues", "mcp.tool_invoked", "mcp", true, ShareToolKindMCP},
- {"", "file.read", "file", false, ShareToolKindRead},
- {"", "file.created", "file", false, ShareToolKindWrite},
- {"", "command.executed", "command", false, ShareToolKindTerminalCommand},
- {"frobnicate", "tool.invoked", "tool", false, ShareToolKindOther},
+ {"Bash", "tool.invoked", "tool", false, TraceToolKindTerminalCommand},
+ {"exec_command", "", "", false, TraceToolKindTerminalCommand},
+ {"run_terminal_cmd", "", "", false, TraceToolKindTerminalCommand},
+ {"shell", "", "", false, TraceToolKindTerminalCommand},
+ {"Read", "", "", false, TraceToolKindRead},
+ {"view", "", "", false, TraceToolKindRead},
+ {"read_file", "", "", false, TraceToolKindRead},
+ {"Edit", "", "", false, TraceToolKindEdit},
+ {"MultiEdit", "", "", false, TraceToolKindEdit},
+ {"apply_patch", "", "", false, TraceToolKindEdit},
+ {"str_replace_editor", "", "", false, TraceToolKindEdit},
+ {"Write", "", "", false, TraceToolKindWrite},
+ {"create_file", "", "", false, TraceToolKindWrite},
+ {"Grep", "", "", false, TraceToolKindGrep},
+ {"Glob", "", "", false, TraceToolKindGlob},
+ {"WebSearch", "", "", false, TraceToolKindWebSearch},
+ {"WebFetch", "", "", false, TraceToolKindWebFetch},
+ {"Task", "", "", false, TraceToolKindTask},
+ {"TodoWrite", "", "", false, TraceToolKindTodo},
+ {"update_plan", "", "", false, TraceToolKindTodo},
+ {"mcp__github__search", "", "", false, TraceToolKindMCP},
+ {"search_issues", "mcp.tool_invoked", "mcp", true, TraceToolKindMCP},
+ {"", "file.read", "file", false, TraceToolKindRead},
+ {"", "file.created", "file", false, TraceToolKindWrite},
+ {"", "command.executed", "command", false, TraceToolKindTerminalCommand},
+ {"frobnicate", "tool.invoked", "tool", false, TraceToolKindOther},
}
for _, tc := range cases {
- if got := ShareToolKind(tc.name, tc.action, tc.category, tc.mcp); got != tc.want {
- t.Errorf("ShareToolKind(%q, %q) = %q, want %q", tc.name, tc.action, got, tc.want)
+ if got := TraceToolKind(tc.name, tc.action, tc.category, tc.mcp); got != tc.want {
+ t.Errorf("TraceToolKind(%q, %q) = %q, want %q", tc.name, tc.action, got, tc.want)
}
}
}
@@ -325,7 +333,7 @@ func TestShareExternalID(t *testing.T) {
}
}
-func TestShareMetadataFromEvents(t *testing.T) {
+func TestShareBundleSummary(t *testing.T) {
start := shareEventAt("2026-10-01T10:00:00Z", "claude", CollectionMethodHook, "session.started", "session")
start.Branch = "main"
prompt := shareEventAt("2026-10-01T10:00:01Z", "claude", CollectionMethodHook, "prompt.submitted", "prompt")
@@ -347,34 +355,54 @@ func TestShareMetadataFromEvents(t *testing.T) {
handoff := shareEventAt("2026-10-01T10:00:01Z", "claude", CollectionMethodHook, "session.handoff", "session")
handoff.Handoff = &HandoffInfo{SourceHarness: "codex", SourceSessionID: "abc123"}
- meta := ShareMetadataFromEventsWithOptions([]Event{link, m3, m2, m1, prompt, handoff, start}, shareTestOpts)
- if meta.SchemaVersion != ShareSchemaVersion || meta.AgentID != "claude_code" || meta.Source != ShareSourceCLI {
- t.Fatalf("identity = %+v", meta)
+ opts := shareTestOpts
+ opts.BeaconVersion = "v0.0.99"
+ opts.GeneratedAt = time.Date(2026, 10, 2, 0, 0, 0, 0, time.UTC)
+ bundle := BuildShareBundle([]Event{link, m3, m2, m1, prompt, handoff, start}, opts)
+ summary := bundle.Summary
+ if bundle.SchemaVersion != TraceSchemaVersion || bundle.ID != "session:claude_code:sess-1" || summary.ID != bundle.ID {
+ t.Fatalf("identity = %q %q", bundle.SchemaVersion, bundle.ID)
}
- if meta.Title != "Fix the flaky login test in ./login_test.go, it fails about one run in ten on C…" {
- t.Fatalf("title = %q", meta.Title)
+ if bundle.Provenance != (TraceProvenanceV1{Source: ShareSourceCLI, GeneratedAt: "2026-10-02T00:00:00.000000000Z", BeaconVersion: "v0.0.99"}) {
+ t.Fatalf("provenance = %+v", bundle.Provenance)
}
- if n := len([]rune(meta.Title)); n > ShareTitleMaxRunes {
- t.Fatalf("title has %d runes", n)
+ // The commit link is bookkeeping: it is not an event of the shared trace, but it names the commit.
+ if summary.EventCount != 6 || len(bundle.Events) != 6 {
+ t.Fatalf("event count = %d, events = %d", summary.EventCount, len(bundle.Events))
}
- if meta.Model != "claude-sonnet-5-5" {
- t.Fatalf("model = %q", meta.Model)
+ if summary.Model == nil || len(summary.Model.Names) != 2 {
+ t.Fatalf("model = %+v", summary.Model)
}
- want := ShareTokenUsageV1{InputTokens: 150, OutputTokens: 20, CacheReadInputTokens: 5, ReasoningOutputTokens: 7}
- if meta.TokenUsage == nil || *meta.TokenUsage != want || meta.CostUSD == nil || *meta.CostUSD != 0.25 {
- t.Fatalf("usage = %+v cost = %v", meta.TokenUsage, meta.CostUSD)
+ want := TraceUsageV1{InputTokens: 150, OutputTokens: 20, CacheReadInputTokens: 5, ReasoningOutputTokens: 7, CostUSD: 0.25}
+ if summary.TokenUsage == nil || *summary.TokenUsage != want {
+ t.Fatalf("usage = %+v", summary.TokenUsage)
}
- if meta.GitRemoteURL != "https://github.com/acme/repo.git" || meta.GitBranch != "main" || meta.GitRef != "abc123def" {
- t.Fatalf("git = %q %q %q", meta.GitRemoteURL, meta.GitBranch, meta.GitRef)
+ wantRepo := TraceRepositoryV1{RemoteURL: "https://github.com/acme/repo.git", Branch: "main", Ref: "abc123def", Path: "repo"}
+ if summary.Repository == nil || *summary.Repository != wantRepo {
+ t.Fatalf("repository = %+v", summary.Repository)
}
- if meta.ProjectName != "repo" {
- t.Fatalf("project = %q", meta.ProjectName)
+ if summary.Session == nil || summary.Session.ID != "sess-1" || summary.Session.WorkingDirectory != "" {
+ t.Fatalf("session = %+v", summary.Session)
}
- if meta.SourceSessionID != "sess-1" || meta.SourceCreatedAt != "2026-10-01T10:00:00Z" || meta.SourceUpdatedAt != "2026-10-01T10:00:05Z" {
- t.Fatalf("source = %+v", meta)
+ if summary.StartedAt != "2026-10-01T10:00:00Z" || summary.EndedAt != "2026-10-01T10:00:04Z" {
+ t.Fatalf("range = %s .. %s", summary.StartedAt, summary.EndedAt)
}
- if meta.RelatedTo != "codex_cli:abc123" || meta.RelationshipType != ShareRelationshipResume {
- t.Fatalf("related = %q %q", meta.RelatedTo, meta.RelationshipType)
+ if summary.Harness.Name != "claude" || strings.Join(summary.Harness.CollectionMethods, ",") != "hook,otlp" {
+ t.Fatalf("harness = %+v", summary.Harness)
+ }
+
+ trace := NewShareTrace(bundle, ShareVisibilityDirect)
+ if trace.SchemaVersion != TraceSchemaVersion || trace.Source != ShareSourceCLI || trace.Visibility != ShareVisibilityDirect {
+ t.Fatalf("trace = %+v", trace)
+ }
+ if trace.Title != "Fix the flaky login test in ./login_test.go, it fails about one run in ten on C…" {
+ t.Fatalf("title = %q", trace.Title)
+ }
+ if n := len([]rune(trace.Title)); n > ShareTitleMaxRunes {
+ t.Fatalf("title has %d runes", n)
+ }
+ if trace.Summary.Sharing.Visibility != ShareVisibilityDirect || trace.Provenance != bundle.Provenance {
+ t.Fatalf("sharing = %+v, provenance = %+v", trace.Summary.Sharing, trace.Provenance)
}
}
@@ -400,80 +428,100 @@ func TestShareRemoteURL(t *testing.T) {
}
}
-// TestShareWireShape pins the JSON field names and shapes of the beacon.share.v1 contract, so a
-// rename here cannot drift from what beacon.sh accepts.
+// TestShareWireShape pins the JSON field names and shapes of the shared-trace contract, so a rename
+// here cannot drift from what beacon.sh accepts.
func TestShareWireShape(t *testing.T) {
- message := ShareMessageV1{
- ID: "m1", Order: 1, Role: ShareRoleAssistant, Timestamp: "2026-10-01T10:00:00Z", Model: "m", Text: "t",
- Parts: []SharePartV1{
- {Type: SharePartToolCall, Order: 1, Content: &ShareToolCallContent{CallID: "c", ToolName: "Bash", ToolKind: ShareToolKindTerminalCommand, Args: map[string]interface{}{}, Command: "ls", FilePath: "a", Diff: "d"}},
- {Type: SharePartToolResult, Order: 2, Content: &ShareToolResultContent{CallID: "c", ToolName: "Bash", Output: "o", Status: ShareStatusSuccess, ExitCode: intPtr(0), DurationMS: int64Ptr(3)}},
- {Type: SharePartText, Order: 3, Content: ShareTextContent{Text: "x"}},
- {Type: SharePartError, Order: 4, Content: ShareErrorContent{Message: "e"}},
- {Type: SharePartSystemEvent, Order: 5, Content: map[string]interface{}{"subtype": "session.started"}},
- },
- TokenUsage: &ShareTokenUsageV1{InputTokens: 1},
- }
- got, err := json.Marshal(message)
+ trace := ShareTraceV1{
+ SchemaVersion: TraceSchemaVersion,
+ Summary: TraceSummaryV1{ID: "session:claude_code:s", EventCount: 1, Harness: TraceHarnessV1{Name: "claude_code"}, Content: TraceContentSummaryV1{Retention: "full"}, Sharing: TraceSharingV1{State: "shared", Visibility: "direct"}},
+ Visibility: ShareVisibilityDirect,
+ Title: "t",
+ Source: ShareSourceCLI,
+ Provenance: TraceProvenanceV1{Source: "cli", GeneratedAt: "g"},
+ }
+ got, err := json.Marshal(trace)
if err != nil {
t.Fatal(err)
}
- want := `{"id":"m1","order":1,"role":"assistant","timestamp":"2026-10-01T10:00:00Z","model":"m","text":"t","parts":[` +
- `{"type":"tool_call","order":1,"content":{"callId":"c","toolName":"Bash","toolKind":"terminal_command","args":{},"command":"ls","filePath":"a","diff":"d"}},` +
- `{"type":"tool_result","order":2,"content":{"callId":"c","toolName":"Bash","output":"o","status":"success","exitCode":0,"durationMs":3}},` +
- `{"type":"text","order":3,"content":{"text":"x"}},` +
- `{"type":"error","order":4,"content":{"message":"e"}},` +
- `{"type":"system_event","order":5,"content":{"subtype":"session.started"}}],` +
- `"token_usage":{"input_tokens":1,"output_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"reasoning_output_tokens":0}}`
+ want := `{"schema_version":"beacon.trace.v1","summary":{"id":"session:claude_code:s","event_count":1,"harness":{"name":"claude_code"},` +
+ `"content":{"retention":"full","has_redactions":false,"has_truncations":false},"sharing":{"state":"shared","visibility":"direct"}},` +
+ `"visibility":"direct","title":"t","source":"cli","provenance":{"source":"cli","generated_at":"g"}}`
if string(got) != want {
- t.Fatalf("message JSON drifted:\n got %s\nwant %s", got, want)
+ t.Fatalf("trace JSON drifted:\n got %s\nwant %s", got, want)
}
- trace := ShareTraceV1{
- SchemaVersion: ShareSchemaVersion, AgentID: "claude_code", Title: "t", Visibility: ShareVisibilityDirect, Model: "m",
- ProjectName: "p", GitRemoteURL: "u", GitBranch: "b", GitRef: "r", TokenUsage: &ShareTokenUsageV1{}, CostUSD: float64Ptr(0),
- SourceSessionID: "s", SourceCreatedAt: "c", SourceUpdatedAt: "d", RelatedTo: "x", RelationshipType: ShareRelationshipSubagent, Source: ShareSourceCLI,
- }
- got, err = json.Marshal(trace)
+ batch := ShareEventsBatchV1{Events: []TraceEventV1{{ID: "e1", Number: 1, Timestamp: "ts", Type: "command", Action: "command.executed", PromptID: "p", SourceEventID: "e1",
+ Command: &TraceCommandV1{Command: "ls", ExitCode: intPtr(0)}}}}
+ got, err = json.Marshal(batch)
if err != nil {
t.Fatal(err)
}
- want = `{"schema_version":"beacon.share.v1","agent_id":"claude_code","title":"t","visibility":"direct","model":"m",` +
- `"project_name":"p","git_remote_url":"u","git_branch":"b","git_ref":"r",` +
- `"token_usage":{"input_tokens":0,"output_tokens":0,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"reasoning_output_tokens":0},` +
- `"cost_usd":0,"source_session_id":"s","source_created_at":"c","source_updated_at":"d","related_to":"x","relationship_type":"subagent","source":"cli"}`
+ want = `{"events":[{"id":"e1","number":1,"timestamp":"ts","type":"command","action":"command.executed","prompt_id":"p","command":{"command":"ls","exit_code":0},"source_event_id":"e1"}]}`
if string(got) != want {
- t.Fatalf("trace JSON drifted:\n got %s\nwant %s", got, want)
+ t.Fatalf("batch JSON drifted:\n got %s\nwant %s", got, want)
}
var state ShareTraceStateV1
- if err := json.Unmarshal([]byte(`{"id":"k3x","url":"https://beacon.sh/s/k3x","visibility":"direct","message_count":4,"last_message_id":"m4","max_order":4}`), &state); err != nil {
+ if err := json.Unmarshal([]byte(`{"id":"k3x","external_id":"claude_code:abc","url":"https://beacon.sh/s/k3x","title":"t","visibility":"direct","event_count":4,"last_event_id":"e4","max_number":4,"created_at":"c","updated_at":"u"}`), &state); err != nil {
t.Fatal(err)
}
- if state.LastMessageID != "m4" || state.MaxOrder != 4 || state.MessageCount != 4 {
+ if state != (ShareTraceStateV1{ID: "k3x", ExternalID: "claude_code:abc", URL: "https://beacon.sh/s/k3x", Title: "t", Visibility: "direct", EventCount: 4, LastEventID: "e4", MaxNumber: 4, CreatedAt: "c", UpdatedAt: "u"}) {
t.Fatalf("state = %+v", state)
}
var put ShareTraceResultV1
- if err := json.Unmarshal([]byte(`{"id":"k3x","external_id":"claude_code:abc","url":"https://beacon.sh/s/k3x","visibility":"direct","message_count":0,"created":true}`), &put); err != nil {
+ if err := json.Unmarshal([]byte(`{"id":"k3x","external_id":"claude_code:abc","url":"https://beacon.sh/s/k3x","visibility":"direct","event_count":0,"created":true}`), &put); err != nil {
t.Fatal(err)
}
- if !put.Created || put.ExternalID != "claude_code:abc" {
+ if put != (ShareTraceResultV1{ID: "k3x", ExternalID: "claude_code:abc", URL: "https://beacon.sh/s/k3x", Visibility: "direct", Created: true}) {
t.Fatalf("put = %+v", put)
}
+ var result ShareBatchResultV1
+ if err := json.Unmarshal([]byte(`{"upserted":2,"event_count":6}`), &result); err != nil || result != (ShareBatchResultV1{Upserted: 2, EventCount: 6}) {
+ t.Fatalf("batch result = %+v, %v", result, err)
+ }
+}
+
+// The wire types survive a JSON round trip unchanged, so what the CLI sends is what beacon.sh
+// stores and serves back.
+func TestShareWireTypesRoundTrip(t *testing.T) {
+ events := shareFieldEvents()
+ bundle := BuildShareBundle(events, shareTestOpts)
+ for name, value := range map[string]interface{}{
+ "trace": NewShareTrace(bundle, ShareVisibilityPublic),
+ "batch": ShareEventsBatchV1{Events: bundle.Events},
+ "bundle": bundle,
+ } {
+ data, err := json.Marshal(value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ decoded := reflect.New(reflect.TypeOf(value))
+ if err := json.Unmarshal(data, decoded.Interface()); err != nil {
+ t.Fatalf("%s: %v", name, err)
+ }
+ again, err := json.Marshal(decoded.Elem().Interface())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(again) != string(data) {
+ t.Fatalf("%s changed in a round trip:\n%s\n%s", name, data, again)
+ }
+ }
}
-func TestShareMetadataLeavesOutDetachedHeadAndTheHomeDirectoryName(t *testing.T) {
+func TestShareSummaryLeavesOutDetachedHeadAndTheHomeDirectoryName(t *testing.T) {
event := shareEventAt("2026-10-01T10:00:00Z", "claude_code", CollectionMethodPoll, "prompt.submitted", "prompt")
event.Session.WorkingDirectory = "/home/dev"
+ event.Repository = "/home/dev"
event.Branch = "HEAD"
event.Prompt = &PromptInfo{Text: "hi"}
- meta := ShareMetadataFromEventsWithOptions([]Event{event}, shareTestOpts)
- if meta.GitBranch != "" || meta.ProjectName != "" {
- t.Fatalf("branch = %q, project = %q", meta.GitBranch, meta.ProjectName)
+ if repo := BuildShareBundle([]Event{event}, shareTestOpts).Summary.Repository; repo != nil {
+ t.Fatalf("repository = %+v", repo)
}
event.Session.WorkingDirectory = "/home/dev/src/app"
- if meta := ShareMetadataFromEventsWithOptions([]Event{event}, shareTestOpts); meta.ProjectName != "app" {
- t.Fatalf("project = %q", meta.ProjectName)
+ event.Repository = "/home/dev/src/app"
+ if repo := BuildShareBundle([]Event{event}, shareTestOpts).Summary.Repository; repo == nil || repo.Path != "app" || repo.Branch != "" {
+ t.Fatalf("repository = %+v", repo)
}
}
@@ -508,7 +556,7 @@ func TestPathScrubberReplacesWholePathsOnly(t *testing.T) {
}
}
-func TestBuildShareMessagesKeepsRepeatedPhaselessCallsApart(t *testing.T) {
+func TestShareMessagesKeepsRepeatedPhaselessCallsApart(t *testing.T) {
// Cursor's beforeReadFile records file.read with a path and nothing else. Reading the same file
// twice is two calls, not a call and its result.
var events []Event
@@ -518,23 +566,24 @@ func TestBuildShareMessagesKeepsRepeatedPhaselessCallsApart(t *testing.T) {
read.File = &FileInfo{Path: "/home/dev/src/app/main.go", Operation: "read"}
events = append(events, read)
}
- messages := BuildShareMessagesWithOptions(events, shareTestOpts)
+ messages := shareMessages(events, shareTestOpts)
want := "assistant/tool_call,assistant/tool_call,assistant/tool_call"
if got := partsOf(t, messages); strings.Join(got, ",") != want {
t.Fatalf("parts = %v", got)
}
}
-func TestShareMetadataUsesExplicitHomeWithoutLookup(t *testing.T) {
+func TestShareTitleUsesExplicitHomeWithoutLookup(t *testing.T) {
prompt := shareEventAt("2026-10-01T10:00:00Z", "claude_code", CollectionMethodHook, "prompt.submitted", "prompt")
+ prompt.Session.WorkingDirectory = ""
prompt.Prompt = &PromptInfo{Text: "look at /home/al/secret"}
- meta := ShareMetadataFromEventsWithOptions([]Event{prompt}, ShareOptions{HomeDirectory: "/home/al", NoHomeLookup: true})
- if meta.Title != "look at ~/secret" {
- t.Fatalf("title = %q", meta.Title)
+ trace := NewShareTrace(BuildShareBundle([]Event{prompt}, ShareOptions{HomeDirectory: "/home/al", NoHomeLookup: true}), ShareVisibilityDirect)
+ if trace.Title != "look at ~/secret" {
+ t.Fatalf("title = %q", trace.Title)
}
}
-func TestBuildShareMessagesTreatsAPostToolInvokedEventAsTheResult(t *testing.T) {
+func TestShareMessagesTreatsAPostToolInvokedEventAsTheResult(t *testing.T) {
// The hook adapter labels a PostToolUse for tools without a more specific action (WebFetch,
// Grep, Task, ...) tool.invoked, carrying the result. With a PreToolUse tool.invoked for the
// same call (Kimi Code, Muse Code) it must still produce a result.
@@ -549,18 +598,18 @@ func TestBuildShareMessagesTreatsAPostToolInvokedEventAsTheResult(t *testing.T)
lone.Event.ID = "c-post"
lone = withCall(lone, "toolu_9", "Grep", map[string]interface{}{"pattern": "x"}, "3 matches")
- messages := BuildShareMessagesWithOptions([]Event{pre, post, lone}, shareTestOpts)
+ messages := shareMessages([]Event{pre, post, lone}, shareTestOpts)
want := "assistant/tool_call,assistant/tool_result,assistant/tool_call,assistant/tool_result"
if got := partsOf(t, messages); strings.Join(got, ",") != want {
t.Fatalf("parts = %v", got)
}
- result := messages[1].Parts[0].Content.(*ShareToolResultContent)
+ result := messages[1].Parts[0].Content.(*TraceToolResultContentV1)
if result.CallID != "call_1" || !strings.Contains(fmt.Sprint(result.Output), "page body") {
t.Fatalf("result = %+v", result)
}
}
-func TestBuildShareMessagesWritesAPromptCapturedTwiceOnce(t *testing.T) {
+func TestShareMessagesWritesAPromptCapturedTwiceOnce(t *testing.T) {
// Claude Code logs each prompt from the UserPromptSubmit hook and from the OTLP export, with
// different event ids and the same prompt.id. The export copy may carry no text.
otlp := shareEventAt("2026-10-01T10:00:00Z", "claude_code", CollectionMethodOTLP, "prompt.submitted", "prompt")
@@ -573,7 +622,7 @@ func TestBuildShareMessagesWritesAPromptCapturedTwiceOnce(t *testing.T) {
next.Event.ID = "p-next"
next.Prompt = &PromptInfo{ID: "prompt-2", Text: "fix the test"}
- messages := BuildShareMessagesWithOptions([]Event{otlp, hook, next}, shareTestOpts)
+ messages := shareMessages([]Event{otlp, hook, next}, shareTestOpts)
if len(messages) != 2 {
t.Fatalf("messages = %d, want 2: %+v", len(messages), messages)
}
@@ -582,7 +631,7 @@ func TestBuildShareMessagesWritesAPromptCapturedTwiceOnce(t *testing.T) {
}
}
-func TestBuildShareMessagesPairsPromptCapturesOnlyAcrossPaths(t *testing.T) {
+func TestShareMessagesPairsPromptCapturesOnlyAcrossPaths(t *testing.T) {
prompt := func(id, ts, method, promptID, text string) Event {
e := shareEventAt(ts, "claude_code", method, "prompt.submitted", "prompt")
e.Event.ID = id
@@ -590,7 +639,7 @@ func TestBuildShareMessagesPairsPromptCapturesOnlyAcrossPaths(t *testing.T) {
return e
}
// Hook first, export second: one message.
- got := BuildShareMessagesWithOptions([]Event{
+ got := shareMessages([]Event{
prompt("h1", "2026-10-01T10:00:00Z", CollectionMethodHook, "", "continue"),
prompt("o1", "2026-10-01T10:00:01Z", CollectionMethodOTLP, "p-1", ""),
}, shareTestOpts)
@@ -598,7 +647,7 @@ func TestBuildShareMessagesPairsPromptCapturesOnlyAcrossPaths(t *testing.T) {
t.Fatalf("hook then export = %+v", got)
}
// Two hook prompts with the same text moments apart are two submissions.
- got = BuildShareMessagesWithOptions([]Event{
+ got = shareMessages([]Event{
prompt("h1", "2026-10-01T10:00:00Z", CollectionMethodHook, "", "continue"),
prompt("h2", "2026-10-01T10:00:03Z", CollectionMethodHook, "", "continue"),
}, shareTestOpts)
@@ -606,7 +655,7 @@ func TestBuildShareMessagesPairsPromptCapturesOnlyAcrossPaths(t *testing.T) {
t.Fatalf("two hook prompts = %+v", got)
}
// A keyless copy far from the keyed one, or with different text, stays separate.
- got = BuildShareMessagesWithOptions([]Event{
+ got = shareMessages([]Event{
prompt("o1", "2026-10-01T10:00:00Z", CollectionMethodOTLP, "p-1", "first"),
prompt("h1", "2026-10-01T10:05:00Z", CollectionMethodHook, "", "first"),
prompt("o2", "2026-10-01T10:06:00Z", CollectionMethodOTLP, "p-2", "second"),
@@ -616,3 +665,281 @@ func TestBuildShareMessagesPairsPromptCapturesOnlyAcrossPaths(t *testing.T) {
t.Fatalf("unrelated prompts merged: %+v", got)
}
}
+
+// shareFieldEvents is one session whose events put the sharer's home directory in every kind of
+// field the trace projection reads.
+func shareFieldEvents() []Event {
+ prompt := shareEventAt("2026-10-01T10:00:00Z", "claude_code", CollectionMethodHook, "prompt.submitted", "prompt")
+ prompt.Event.ID = "f-prompt"
+ prompt.Prompt = &PromptInfo{ID: "p1", Text: "read /home/dev/notes/todo.md"}
+ prompt.Repository = "/home/dev/src/app"
+
+ cmd := shareEventAt("2026-10-01T10:00:01Z", "claude_code", CollectionMethodHook, "command.executed", "command")
+ cmd.Event.ID = "f-cmd"
+ cmd = withCall(cmd, "toolu_c", "Bash", map[string]interface{}{"command": "cat /home/dev/.config/app.toml"}, nil)
+ cmd.Tool.Command = "cat /home/dev/.config/app.toml"
+ cmd.Command = &CommandInfo{Command: "cat /home/dev/.config/app.toml", ExitCode: intPtr(1), Output: "cat: /home/dev/.config/app.toml: No such file"}
+ cmd.Message = "ran cat /home/dev/.config/app.toml"
+
+ edit := shareEventAt("2026-10-01T10:00:02Z", "claude_code", CollectionMethodHook, "file.modified", "file")
+ edit.Event.ID = "f-edit"
+ edit = withCall(edit, "toolu_e", "Edit", map[string]interface{}{"file_path": "/home/dev/src/app/main.go", "nested": []interface{}{map[string]interface{}{"p": "/home/dev/x"}}}, map[string]interface{}{"path": "/home/dev/src/app/main.go"})
+ edit.Tool.Path = "/home/dev/src/app/main.go"
+ edit.File = &FileInfo{Path: "/home/dev/src/app/main.go", Operation: "modify", Diff: "--- /home/dev/src/app/main.go\n+++ /home/dev/src/app/main.go\n"}
+
+ mcp := shareEventAt("2026-10-01T10:00:03Z", "claude_code", CollectionMethodHook, "mcp.tool_invoked", "mcp")
+ mcp.Event.ID = "f-mcp"
+ mcp = withCall(mcp, "toolu_m", "mcp__fs__read", map[string]interface{}{"path": "/home/dev/secret.txt"}, []interface{}{map[string]interface{}{"type": "text", "text": "from /home/dev/secret.txt"}})
+ mcp.MCP = &MCPInfo{Server: "fs", Tool: "read", Resource: &MCPResourceInfo{URI: "file:///home/dev/secret.txt"}}
+
+ approval := shareEventAt("2026-10-01T10:00:04Z", "claude_code", CollectionMethodHook, "approval.denied", "approval")
+ approval.Event.ID = "f-approval"
+ approval.Approval = &ApprovalInfo{Required: true, Decision: "deny", Reason: "writes to /home/dev/.ssh"}
+ approval.Policy = &PolicyInfo{Name: "home /home/dev guard", Decision: "deny", Reason: "path /home/dev/.ssh is protected"}
+
+ failure := shareEventAt("2026-10-01T10:00:05Z", "claude_code", CollectionMethodHook, "session.error", "session")
+ failure.Event.ID = "f-error"
+ failure.Message = "open /home/dev/src/app/go.mod: permission denied"
+ failure.Error = &ErrorInfo{Type: "/home/dev/bin/tool exited"}
+
+ answer := shareEventAt("2026-10-01T10:00:06Z", "claude_code", CollectionMethodHook, "agent.message", "agent")
+ answer.Event.ID = "f-answer"
+ answer.GenAI = &GenAIInfo{Output: &GenAIOutputInfo{Messages: TextOutputMessages("I changed /home/dev/src/app/main.go")}}
+ answer.Raw = map[string]interface{}{"cwd": "/home/dev/src/app"}
+
+ return []Event{prompt, cmd, edit, mcp, approval, failure, answer}
+}
+
+// Every field the shared bundle carries is scrubbed of the sharer's home and session directory:
+// command lines and output, file paths and diffs, tool arguments and results, MCP fields, approval
+// and policy text, errors, retained text, the working directory and the repository.
+func TestShareBundleScrubsEveryFieldType(t *testing.T) {
+ events := shareFieldEvents()
+ bundle := BuildShareBundle(events, shareTestOpts)
+ data, err := json.Marshal(bundle)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(string(data), "/home/dev") {
+ t.Fatalf("a local path reached the bundle: %s", data)
+ }
+ messages, err := json.Marshal(TraceMessages(bundle))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(string(messages), "/home/dev") {
+ t.Fatalf("a local path reached the messages: %s", messages)
+ }
+ byID := map[string]TraceEventV1{}
+ for _, event := range bundle.Events {
+ byID[event.ID] = event
+ }
+ checks := map[string]string{
+ "prompt": byID["f-prompt"].Content.Text,
+ "command": byID["f-cmd"].Command.Command,
+ "command output": byID["f-cmd"].Command.Output.Text,
+ "tool command": byID["f-cmd"].Tool.Command,
+ "tool argument": fmt.Sprint(byID["f-cmd"].Tool.Arguments),
+ "message": byID["f-cmd"].Summary,
+ "file path": byID["f-edit"].File.Path,
+ "file title": byID["f-edit"].Title,
+ "tool path": byID["f-edit"].Tool.Path,
+ "diff": byID["f-edit"].File.Diff.Text,
+ "nested argument": fmt.Sprint(byID["f-edit"].Tool.Arguments),
+ "tool result": fmt.Sprint(byID["f-edit"].Tool.Result),
+ "mcp argument": fmt.Sprint(byID["f-mcp"].Tool.Arguments),
+ "mcp result": fmt.Sprint(byID["f-mcp"].Tool.Result),
+ "mcp resource": byID["f-mcp"].MCP.ResourceURI,
+ "approval reason": byID["f-approval"].Approval.Reason,
+ "policy name": byID["f-approval"].Policy.Name,
+ "policy reason": byID["f-approval"].Policy.Reason,
+ "error message": byID["f-error"].Summary,
+ "error type": byID["f-error"].Error.Type,
+ "assistant text": byID["f-answer"].Content.Text,
+ }
+ want := map[string]string{
+ "prompt": "read ~/notes/todo.md",
+ "command": "cat ~/.config/app.toml",
+ "command output": "cat: ~/.config/app.toml: No such file",
+ "file path": "main.go",
+ "tool path": "main.go",
+ "mcp resource": "file://~/secret.txt",
+ "error message": "open ./go.mod: permission denied",
+ "approval reason": "writes to ~/.ssh",
+ "assistant text": "I changed ./main.go",
+ }
+ for name, got := range checks {
+ if strings.Contains(got, "/home/dev") || got == "" {
+ t.Errorf("%s = %q", name, got)
+ }
+ if w, ok := want[name]; ok && got != w {
+ t.Errorf("%s = %q, want %q", name, got, w)
+ }
+ }
+ if repo := bundle.Summary.Repository; repo == nil || repo.Path != "app" {
+ t.Errorf("repository = %+v", repo)
+ }
+ // The caller's events are not rewritten.
+ if events[1].Command.Command != "cat /home/dev/.config/app.toml" || events[2].File.Path != "/home/dev/src/app/main.go" ||
+ events[3].GenAI.Tool.Call.Arguments.(map[string]interface{})["path"] != "/home/dev/secret.txt" {
+ t.Fatal("BuildShareBundle changed the caller's events")
+ }
+}
+
+func TestShareProjects(t *testing.T) {
+ event := func(action, category string) Event {
+ return shareEventAt("2026-10-01T10:00:00Z", "claude_code", CollectionMethodHook, action, category)
+ }
+ usage := event("token.usage", "metric")
+ usage.GenAI = &GenAIInfo{Usage: &GenAIUsageInfo{InputTokens: int64Ptr(3)}}
+ metricWithoutUsage := event("", "metric")
+ metricWithoutUsage.Raw = map[string]interface{}{"metric_name": "claude_code.lines_of_code.count"}
+ cases := []struct {
+ name string
+ event Event
+ want bool
+ }{
+ {"prompt", event("prompt.submitted", "prompt"), true},
+ {"tool", event("tool.invoked", "tool"), true},
+ {"command", event("command.executed", ""), true},
+ {"session start", event("session.started", "session"), true},
+ {"handoff", event("session.handoff", "session"), true},
+ {"reasoning", event("agent.reasoning", "agent"), true},
+ {"token usage", usage, true},
+ {"metric without usage", metricWithoutUsage, false},
+ {"shared record", event("session.shared", "session"), false},
+ {"share request", event("session.share_requested", "session"), false},
+ {"commit link", event("session.commit_linked", "session"), false},
+ {"heartbeat", event("endpoint.heartbeat", "health"), false},
+ {"inventory", event("inventory.snapshot", "inventory"), false},
+ {"idle", event("session.idle", "session"), false},
+ {"tool listing", event("mcp.tool_listed", "mcp"), false},
+ {"no action", event("", ""), false},
+ }
+ for _, tc := range cases {
+ if got := ShareProjects(tc.event); got != tc.want {
+ t.Errorf("ShareProjects(%s) = %v, want %v", tc.name, got, tc.want)
+ }
+ }
+ // The bundle carries exactly what ShareProjects accepts.
+ var events []Event
+ accepted := 0
+ for i, tc := range cases {
+ e := tc.event
+ e.Event.ID = fmt.Sprintf("e-%02d", i)
+ events = append(events, e)
+ if tc.want {
+ accepted++
+ }
+ }
+ if bundle := BuildShareBundle(events, shareTestOpts); len(bundle.Events) != accepted || bundle.Summary.EventCount != accepted {
+ t.Fatalf("bundle carries %d events (summary %d), ShareProjects accepts %d", len(bundle.Events), bundle.Summary.EventCount, accepted)
+ }
+}
+
+func TestShareBundleOrdersNumbersAndDeduplicates(t *testing.T) {
+ pre := shareEventAt("2026-10-01T10:00:01Z", "claude_code", CollectionMethodHook, "tool.invoked", "tool")
+ pre.Event.ID = "z-pre"
+ pre = withCall(pre, "toolu_1", "Bash", map[string]interface{}{"command": "ls"}, nil)
+ post := shareEventAt("2026-10-01T10:00:01Z", "claude_code", CollectionMethodHook, "command.executed", "command")
+ post.Event.ID = "a-post"
+ post = withCall(post, "toolu_1", "Bash", nil, nil)
+ post.Command = &CommandInfo{Command: "ls", ExitCode: intPtr(0)}
+ prompt := shareEventAt("2026-10-01T10:00:00Z", "claude_code", CollectionMethodHook, "prompt.submitted", "prompt")
+ prompt.Prompt = &PromptInfo{Text: "list"}
+ untimed := shareEventAt("not a time", "claude_code", CollectionMethodHook, "session.ended", "session")
+ untimed.Event.ID = "u"
+
+ bundle := BuildShareBundle([]Event{untimed, post, pre, prompt, post}, shareTestOpts)
+ var got []string
+ for i, event := range bundle.Events {
+ if event.Number != i+1 {
+ t.Fatalf("event %d is numbered %d", i, event.Number)
+ }
+ got = append(got, event.ID)
+ }
+ // The invocation sorts ahead of its completion at one instant, the duplicate is carried once,
+ // and the untimed event comes last.
+ if want := ShareEventID(prompt) + ",z-pre,a-post,u"; strings.Join(got, ",") != want {
+ t.Fatalf("events = %v, want %s", got, want)
+ }
+ if bundle.Spans != nil && len(bundle.Spans) != 0 {
+ t.Fatalf("spans = %+v", bundle.Spans)
+ }
+ if again := BuildShareBundle([]Event{untimed, post, pre, prompt, post}, ShareOptions{HomeDirectory: "/home/dev", NoHomeLookup: true, GeneratedAt: time.Unix(0, 0)}); again.Events[0].ID != got[0] {
+ t.Fatal("derived event id is not stable")
+ }
+ if empty := BuildShareBundle(nil, shareTestOpts); empty.Events == nil || len(empty.Events) != 0 || empty.Summary.EventCount != 0 {
+ t.Fatalf("empty bundle = %+v", empty)
+ }
+}
+
+// TraceMessages reads any bundle, including the local dashboard's, which still holds bookkeeping
+// and status events: they are never messages.
+func TestTraceMessagesSkipsBookkeepingInALocalBundle(t *testing.T) {
+ builder := NewTraceBuilder("session:claude_code:sess-1", Event{})
+ for i, e := range []Event{
+ shareEventAt("2026-10-01T10:00:00Z", "claude_code", "", "session.shared", "session"),
+ shareEventAt("2026-10-01T10:00:01Z", "claude_code", "", "session.share_requested", "session"),
+ shareEventAt("2026-10-01T10:00:02Z", "claude_code", "", "session.commit_linked", "session"),
+ shareEventAt("2026-10-01T10:00:03Z", "claude_code", CollectionMethodOTLP, "token.usage", "metric"),
+ shareEventAt("2026-10-01T10:00:04Z", "claude_code", CollectionMethodHook, "session.started", "session"),
+ } {
+ builder.Add(e, TraceEventFromEvent(e, fmt.Sprintf("line-%d", i), 0))
+ }
+ messages := TraceMessages(builder.Bundle(TraceProvenanceV1{}))
+ if got := partsOf(t, messages); strings.Join(got, ",") != "system/system_event" || messages[0].Kind != TraceMessageKindSystem {
+ t.Fatalf("parts = %v", got)
+ }
+}
+
+func TestTraceMessageRoundTrip(t *testing.T) {
+ messages := TraceMessages(BuildShareBundle(shareFieldEvents(), shareTestOpts))
+ kinds := map[string]bool{}
+ for _, m := range messages {
+ kinds[m.Kind] = true
+ }
+ for _, kind := range []string{TraceMessageKindPrompt, TraceMessageKindToolCall, TraceMessageKindToolResult, TraceMessageKindApproval, TraceMessageKindError, TraceMessageKindAssistant} {
+ if !kinds[kind] {
+ t.Fatalf("no %s message in %+v", kind, messages)
+ }
+ }
+ data, err := json.Marshal(messages)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var decoded []TraceMessageV1
+ if err := json.Unmarshal(data, &decoded); err != nil {
+ t.Fatal(err)
+ }
+ again, err := json.Marshal(decoded)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(again) != string(data) {
+ t.Fatalf("messages changed in a round trip:\n%s\n%s", data, again)
+ }
+ if _, ok := decoded[1].Parts[0].Content.(*TraceToolCallContentV1); !ok {
+ t.Fatalf("tool call decoded as %T", decoded[1].Parts[0].Content)
+ }
+ want := `{"id":"m1","role":"assistant","kind":"tool_call","order":1,"timestamp":"t","model":"m","text":"x","parts":[` +
+ `{"type":"tool_call","order":1,"content":{"callId":"c","toolName":"Bash","toolKind":"terminal_command","args":{},"command":"ls","filePath":"a","diff":"d"}},` +
+ `{"type":"tool_result","order":2,"content":{"callId":"c","toolName":"Bash","output":"o","status":"success","exitCode":0,"durationMs":3}},` +
+ `{"type":"text","order":3,"content":{"text":"x"}},` +
+ `{"type":"error","order":4,"content":{"message":"e"}},` +
+ `{"type":"system_event","order":5,"content":{"subtype":"session.started"}}],` +
+ `"token_usage":{"input_tokens":1}}`
+ pinned := TraceMessageV1{ID: "m1", Role: TraceRoleAssistant, Kind: TraceMessageKindToolCall, Order: 1, Timestamp: "t", Model: "m", Text: "x",
+ Parts: []TraceMessagePartV1{
+ {Type: TracePartToolCall, Order: 1, Content: &TraceToolCallContentV1{CallID: "c", ToolName: "Bash", ToolKind: TraceToolKindTerminalCommand, Args: map[string]interface{}{}, Command: "ls", FilePath: "a", Diff: "d"}},
+ {Type: TracePartToolResult, Order: 2, Content: &TraceToolResultContentV1{CallID: "c", ToolName: "Bash", Output: "o", Status: TraceToolStatusSuccess, ExitCode: intPtr(0), DurationMS: int64Ptr(3)}},
+ {Type: TracePartText, Order: 3, Content: TraceTextContentV1{Text: "x"}},
+ {Type: TracePartError, Order: 4, Content: TraceErrorContentV1{Message: "e"}},
+ {Type: TracePartSystemEvent, Order: 5, Content: map[string]interface{}{"subtype": "session.started"}},
+ },
+ TokenUsage: &TraceUsageV1{InputTokens: 1},
+ }
+ if got, _ := json.Marshal(pinned); string(got) != want {
+ t.Fatalf("message JSON drifted:\n got %s\nwant %s", got, want)
+ }
+}
diff --git a/pkg/asymptoteobserve/tracemessages.go b/pkg/asymptoteobserve/tracemessages.go
new file mode 100644
index 00000000..575efcc4
--- /dev/null
+++ b/pkg/asymptoteobserve/tracemessages.go
@@ -0,0 +1,1009 @@
+package asymptoteobserve
+
+import (
+ "encoding/json"
+ "sort"
+ "strings"
+ "time"
+ "unicode/utf8"
+)
+
+// This file derives the chat view of a trace: TraceMessages turns a beacon.trace.v1 bundle's events
+// into the messages a reader scrolls through -- what the user asked, what the assistant said and
+// thought, each tool call paired with its result, approvals and lifecycle as system notes. It is
+// derived from the bundle and never stored or uploaded, so the local dashboard, beacon.sh and
+// anything else that holds a bundle show one trace as the same conversation.
+
+// Message roles.
+const (
+ TraceRoleUser = "user"
+ TraceRoleAssistant = "assistant"
+ TraceRoleSystem = "system"
+)
+
+// Message kinds: what one message is, at a glance.
+const (
+ TraceMessageKindPrompt = "prompt"
+ TraceMessageKindAssistant = "assistant_text"
+ TraceMessageKindThinking = "thinking"
+ TraceMessageKindToolCall = "tool_call"
+ TraceMessageKindToolResult = "tool_result"
+ TraceMessageKindApproval = "approval"
+ TraceMessageKindSystem = "system"
+ TraceMessageKindError = "error"
+)
+
+// Part types.
+const (
+ TracePartText = "text"
+ TracePartThinking = "thinking"
+ TracePartToolCall = "tool_call"
+ TracePartToolResult = "tool_result"
+ TracePartError = "error"
+ TracePartSystemEvent = "system_event"
+)
+
+// Tool kinds, the toolKind of a tool_call part.
+const (
+ TraceToolKindTerminalCommand = "terminal_command"
+ TraceToolKindRead = "read"
+ TraceToolKindEdit = "edit"
+ TraceToolKindWrite = "write"
+ TraceToolKindDelete = "delete"
+ TraceToolKindGrep = "grep"
+ TraceToolKindGlob = "glob"
+ TraceToolKindWebSearch = "web_search"
+ TraceToolKindWebFetch = "web_fetch"
+ TraceToolKindTask = "task"
+ TraceToolKindTodo = "todo"
+ TraceToolKindMCP = "mcp"
+ TraceToolKindOther = "other"
+)
+
+// Tool result statuses.
+const (
+ TraceToolStatusSuccess = "success"
+ TraceToolStatusError = "error"
+)
+
+// TraceMessageV1 is one message of a trace's chat view. ID is the ID of the event it came from (a
+// synthesized tool call has an ID derived from its result's), so it is stable across derivations.
+type TraceMessageV1 struct {
+ ID string `json:"id"`
+ Role string `json:"role"`
+ Kind string `json:"kind"`
+ Order int `json:"order"`
+ Timestamp string `json:"timestamp"`
+ Model string `json:"model,omitempty"`
+ Text string `json:"text"`
+ Parts []TraceMessagePartV1 `json:"parts"`
+ TokenUsage *TraceUsageV1 `json:"token_usage,omitempty"`
+}
+
+// TraceMessagePartV1 is one part of a message. Content is TraceTextContentV1 (text, thinking),
+// *TraceToolCallContentV1, *TraceToolResultContentV1, TraceErrorContentV1, or a
+// map[string]interface{} of small scalars for a system_event.
+type TraceMessagePartV1 struct {
+ Type string `json:"type"`
+ Order int `json:"order"`
+ Content interface{} `json:"content"`
+}
+
+// UnmarshalJSON decodes Content into the type its part type names, so a message survives a JSON
+// round trip unchanged.
+func (p *TraceMessagePartV1) UnmarshalJSON(data []byte) error {
+ var wire struct {
+ Type string `json:"type"`
+ Order int `json:"order"`
+ Content json.RawMessage `json:"content"`
+ }
+ if err := json.Unmarshal(data, &wire); err != nil {
+ return err
+ }
+ p.Type, p.Order, p.Content = wire.Type, wire.Order, nil
+ if len(wire.Content) == 0 || string(wire.Content) == "null" {
+ return nil
+ }
+ var err error
+ switch wire.Type {
+ case TracePartText, TracePartThinking:
+ var c TraceTextContentV1
+ err = json.Unmarshal(wire.Content, &c)
+ p.Content = c
+ case TracePartToolCall:
+ c := &TraceToolCallContentV1{}
+ err = json.Unmarshal(wire.Content, c)
+ p.Content = c
+ case TracePartToolResult:
+ c := &TraceToolResultContentV1{}
+ err = json.Unmarshal(wire.Content, c)
+ p.Content = c
+ case TracePartError:
+ var c TraceErrorContentV1
+ err = json.Unmarshal(wire.Content, &c)
+ p.Content = c
+ default:
+ var c interface{}
+ err = json.Unmarshal(wire.Content, &c)
+ p.Content = c
+ }
+ return err
+}
+
+// TraceTextContentV1 is the content of a text or thinking part.
+type TraceTextContentV1 struct {
+ Text string `json:"text"`
+}
+
+// TraceToolCallContentV1 is the content of a tool_call part. Diff is the edit's retained diff when
+// the runtime reported one; it lives on the call because a tool_result has no diff.
+type TraceToolCallContentV1 struct {
+ CallID string `json:"callId"`
+ ToolName string `json:"toolName"`
+ ToolKind string `json:"toolKind"`
+ Args map[string]interface{} `json:"args"`
+ Command string `json:"command,omitempty"`
+ FilePath string `json:"filePath,omitempty"`
+ Diff string `json:"diff,omitempty"`
+}
+
+// TraceToolResultContentV1 is the content of a tool_result part.
+type TraceToolResultContentV1 struct {
+ CallID string `json:"callId"`
+ ToolName string `json:"toolName"`
+ Output string `json:"output"`
+ Status string `json:"status"`
+ ExitCode *int `json:"exitCode,omitempty"`
+ DurationMS *int64 `json:"durationMs,omitempty"`
+}
+
+// TraceErrorContentV1 is the content of an error part.
+type TraceErrorContentV1 struct {
+ Message string `json:"message"`
+}
+
+// TraceMessages derives the chat view of a trace from its events, in event order (Number, then the
+// order given):
+//
+// - a prompt is a user message with a text part;
+// - assistant text and reasoning are assistant messages with a text or thinking part;
+// - a tool invocation is an assistant message with a tool_call part, and its completion is a
+// separate message with a tool_result part carrying the same callId. Hook runtimes report one
+// call twice (before and after); the two are paired by tool_call_id, or, when the runtime names
+// no call id, by tool name with the most recent unanswered invocation. A call or result
+// reported twice (a hook and an OTLP copy of one action) is written once, with the second copy
+// only filling fields the first lacked. A completion with no invocation gets a tool_call
+// message of its own just before it, so every result has a call;
+// - one prompt captured by two paths (a hook and the OTLP export) is written once;
+// - approvals, policy decisions and session lifecycle are system messages with a system_event
+// part; failures that are not a tool's are system messages with an error part.
+//
+// Heartbeats, inventory, metric datapoints and Beacon's own bookkeeping are not messages. The
+// bundle is read as it is: privacy (sanitizing, path scrubbing) is applied when the bundle is built,
+// by BuildShareBundle for a shared trace.
+func TraceMessages(bundle TraceBundleV1) []TraceMessageV1 {
+ events := append([]TraceEventV1(nil), bundle.Events...)
+ sort.SliceStable(events, func(i, j int) bool { return events[i].Number < events[j].Number })
+ b := &traceMessageBuilder{
+ seen: map[string]bool{},
+ calls: map[string]*TraceToolCallContentV1{},
+ results: map[string]*TraceToolResultContentV1{},
+ callMessage: map[string]*TraceMessageV1{},
+ prompts: map[string]*TraceMessageV1{},
+ }
+ for _, event := range events {
+ b.add(event)
+ }
+ out := make([]TraceMessageV1, 0, len(b.messages))
+ for i, message := range b.messages {
+ message.Order = i + 1
+ out = append(out, *message)
+ }
+ return out
+}
+
+type traceMessageBuilder struct {
+ messages []*TraceMessageV1
+ seen map[string]bool
+ // calls, results and callMessage are keyed by callId.
+ calls map[string]*TraceToolCallContentV1
+ results map[string]*TraceToolResultContentV1
+ callMessage map[string]*TraceMessageV1
+ // pending holds call ids of invocations that named no runtime call id, newest last, waiting for
+ // a completion to pair with by tool name.
+ pending []string
+ // prompts holds user messages by prompt id, so one prompt captured by two paths (a hook and the
+ // OTLP export) is written once. lastPrompt is the newest user message, for the copy that carries
+ // no prompt id (Claude Code's UserPromptSubmit hook runs before the prompt is recorded, so it
+ // has none).
+ prompts map[string]*TraceMessageV1
+ lastPrompt *tracePromptRef
+}
+
+type tracePromptRef struct {
+ message *TraceMessageV1
+ keyed bool
+ ts time.Time
+ hasTS bool
+}
+
+// tracePromptPairWindow is how far apart two captures of one prompt may be. The hook and the
+// export record the same submission within moments of each other.
+const tracePromptPairWindow = 10 * time.Second
+
+const tracePromptNotRetained = "(prompt text not retained)"
+
+type traceMessageClass int
+
+const (
+ traceMessageSkip traceMessageClass = iota
+ traceMessagePrompt
+ traceMessageAgentText
+ traceMessageThinking
+ traceMessageTool
+ traceMessageApproval
+ traceMessageSystem
+ traceMessageError
+)
+
+// shareBookkeepingActions are the events Beacon writes about a session rather than the session's
+// own activity: the record of a share, an auto-share request, and a commit link.
+var shareBookkeepingActions = map[string]bool{
+ "session.shared": true,
+ "session.share_requested": true,
+ "session.commit_linked": true,
+}
+
+// traceNoise reports Beacon's own telemetry and runtime status pings: heartbeats, inventory,
+// destination health, idle/activity status, MCP tool listings and runtime detection. None of it is
+// something the agent did.
+func traceNoise(action, category string) bool {
+ switch {
+ case category == "inventory" || category == "health" || category == "telemetry" ||
+ strings.HasPrefix(action, "endpoint.") || strings.HasPrefix(action, "telemetry.") ||
+ strings.HasPrefix(action, "inventory.") || strings.HasPrefix(action, "destination.") ||
+ strings.HasPrefix(action, "health."):
+ return true
+ case action == "session.activity" || action == "session.idle" || action == "session.status" ||
+ action == "session.lock" || action == "mcp.tool_listed" || action == "agent.detected":
+ return true
+ }
+ return false
+}
+
+func classifyTraceMessage(event TraceEventV1) traceMessageClass {
+ action := strings.ToLower(strings.TrimSpace(event.Action))
+ category := strings.ToLower(strings.TrimSpace(event.Category))
+ switch {
+ case action == "" || shareBookkeepingActions[action] || traceNoise(action, category):
+ return traceMessageSkip
+ case category == "metric" || strings.HasPrefix(action, "token.") || strings.HasPrefix(action, "metric."):
+ return traceMessageSkip
+ case category == "prompt" || strings.HasPrefix(action, "prompt."):
+ return traceMessagePrompt
+ case strings.Contains(action, "reasoning") || strings.Contains(action, "thinking"):
+ return traceMessageThinking
+ case action == "agent.message" || action == "assistant.message" || action == "agent.response" ||
+ action == "agent.response.completed" || action == "agent.plan":
+ return traceMessageAgentText
+ case category == "approval" || strings.HasPrefix(action, "approval.") || strings.HasPrefix(action, "policy."):
+ return traceMessageApproval
+ case strings.HasPrefix(action, "tool.") || strings.HasPrefix(action, "command.") ||
+ strings.HasPrefix(action, "file.") || action == "mcp.tool_invoked" || action == "mcp.tool_call" ||
+ category == "tool" || category == "command" || category == "file":
+ return traceMessageTool
+ case action == "session.error" || action == "agent.error" || strings.HasPrefix(action, "error.") ||
+ category == "error":
+ return traceMessageError
+ }
+ return traceMessageSystem
+}
+
+// traceToolInvocation reports an event that names a tool call before it runs.
+func traceToolInvocation(event TraceEventV1) bool {
+ switch strings.ToLower(strings.TrimSpace(event.Action)) {
+ case "tool.invoked", "tool.started", "tool.call", "tool.execute.before", "tool.execution_start",
+ "command.invoked", "command.execute.before", "mcp.tool_call":
+ // The hook adapter also labels a post-tool event tool.invoked for tools it has no more
+ // specific action for (WebFetch, Task, Grep, ...). That event carries the finished call's
+ // result, and is a completion.
+ return !traceCompletionEvidence(event)
+ }
+ return false
+}
+
+// traceToolCompletion reports an event that says a tool call finished: its action says so, or it
+// carries what only a finished call has (a result, output, an exit code, a diff, an error).
+func traceToolCompletion(event TraceEventV1) bool {
+ switch strings.ToLower(strings.TrimSpace(event.Action)) {
+ case "tool.completed", "tool.failed", "tool.execute.after", "tool.execution_complete", "tool.result":
+ return true
+ }
+ if event.File != nil && event.File.Diff != nil && event.File.Diff.Text != "" {
+ return true
+ }
+ return traceCompletionEvidence(event)
+}
+
+// traceCompletionEvidence reports an event that carries what only a finished call has: a result,
+// command output or exit code, or an error. A diff is not evidence on its own, because an edit's
+// invocation can carry the patch it is about to apply.
+func traceCompletionEvidence(event TraceEventV1) bool {
+ if event.Tool != nil && event.Tool.Result != nil {
+ return true
+ }
+ if event.Command != nil && ((event.Command.Output != nil && event.Command.Output.Text != "") || event.Command.ExitCode != nil || event.Command.DurationMS > 0) {
+ return true
+ }
+ return event.Error != nil && event.Error.Type != ""
+}
+
+func (b *traceMessageBuilder) add(event TraceEventV1) {
+ if b.seen[event.ID] {
+ return
+ }
+ class := classifyTraceMessage(event)
+ if class == traceMessageSkip {
+ return
+ }
+ b.seen[event.ID] = true
+ switch class {
+ case traceMessagePrompt:
+ text := tracePromptText(event)
+ key := strings.TrimSpace(event.PromptID)
+ if existing := b.samePrompt(event, key, text); existing != nil {
+ // The same prompt from a second capture path: fill in the text if the first copy had
+ // none, and write nothing new.
+ if existing.Text == tracePromptNotRetained && text != "" {
+ existing.Text = text
+ existing.Parts = []TraceMessagePartV1{{Type: TracePartText, Order: 1, Content: TraceTextContentV1{Text: text}}}
+ }
+ return
+ }
+ if text == "" {
+ text = tracePromptNotRetained
+ }
+ message := b.appendText(event, TraceRoleUser, TraceMessageKindPrompt, TracePartText, text)
+ if key != "" {
+ b.prompts[key] = message
+ }
+ ts, hasTS := traceEventTime(event)
+ b.lastPrompt = &tracePromptRef{message: message, keyed: key != "", ts: ts, hasTS: hasTS}
+ case traceMessageAgentText:
+ if text := traceAssistantText(event, "agent_message"); text != "" {
+ b.appendText(event, TraceRoleAssistant, TraceMessageKindAssistant, TracePartText, text)
+ }
+ case traceMessageThinking:
+ if text := traceAssistantText(event, "agent_reasoning"); text != "" {
+ b.appendText(event, TraceRoleAssistant, TraceMessageKindThinking, TracePartThinking, text)
+ }
+ case traceMessageTool:
+ b.addTool(event)
+ case traceMessageApproval:
+ b.addApproval(event)
+ case traceMessageError:
+ msg := traceFirstNonEmpty(event.Summary, traceErrorType(event), event.Action)
+ b.append(event, TraceRoleSystem, TraceMessageKindError, msg, TraceMessagePartV1{Type: TracePartError, Content: TraceErrorContentV1{Message: msg}})
+ default:
+ b.addSystem(event)
+ }
+}
+
+// samePrompt finds the user message an earlier capture of this prompt wrote. A prompt id match is
+// exact. Without one, the newest prompt counts as the same submission only when exactly one of the
+// two copies carries a prompt id (they came from different capture paths), they are within
+// tracePromptPairWindow, and their texts agree or one of them retained none.
+func (b *traceMessageBuilder) samePrompt(event TraceEventV1, key, text string) *TraceMessageV1 {
+ if key != "" {
+ if existing := b.prompts[key]; existing != nil {
+ return existing
+ }
+ }
+ last := b.lastPrompt
+ ts, hasTS := traceEventTime(event)
+ if last == nil || last.keyed == (key != "") || !last.hasTS || !hasTS {
+ return nil
+ }
+ gap := ts.Sub(last.ts)
+ if gap < 0 {
+ gap = -gap
+ }
+ if gap > tracePromptPairWindow {
+ return nil
+ }
+ if text != "" && last.message.Text != tracePromptNotRetained && text != last.message.Text {
+ return nil
+ }
+ if key != "" {
+ b.prompts[key] = last.message
+ }
+ last.keyed = true
+ return last.message
+}
+
+func (b *traceMessageBuilder) newMessage(event TraceEventV1, id, role, kind, text string, parts ...TraceMessagePartV1) *TraceMessageV1 {
+ for i := range parts {
+ parts[i].Order = i + 1
+ }
+ message := &TraceMessageV1{
+ ID: id,
+ Role: role,
+ Kind: kind,
+ Timestamp: traceMessageTimestamp(event),
+ Model: event.Model,
+ Text: text,
+ Parts: parts,
+ }
+ if event.Usage != nil && !traceUsageEmpty(*event.Usage) {
+ usage := *event.Usage
+ message.TokenUsage = &usage
+ }
+ return message
+}
+
+func (b *traceMessageBuilder) append(event TraceEventV1, role, kind, text string, parts ...TraceMessagePartV1) *TraceMessageV1 {
+ message := b.newMessage(event, event.ID, role, kind, text, parts...)
+ b.messages = append(b.messages, message)
+ return message
+}
+
+func (b *traceMessageBuilder) appendText(event TraceEventV1, role, kind, partType, text string) *TraceMessageV1 {
+ return b.append(event, role, kind, text, TraceMessagePartV1{Type: partType, Content: TraceTextContentV1{Text: text}})
+}
+
+func (b *traceMessageBuilder) addTool(event TraceEventV1) {
+ callID := strings.TrimSpace(event.ToolCallID)
+ toolName := traceMessageToolName(event)
+ invocation := traceToolInvocation(event)
+ explicit := invocation
+ completion := !invocation && traceToolCompletion(event)
+
+ if !invocation && !completion {
+ // Neither phase is explicit (a file read a hook observed, an MCP call a transcript recorded).
+ // It completes a call already on the trace, and is a call of its own otherwise.
+ if callID != "" && b.calls[callID] != nil {
+ completion = true
+ } else if callID == "" {
+ if paired := b.pairPending(event, toolName); paired != "" {
+ callID = paired
+ completion = true
+ }
+ }
+ if !completion {
+ invocation = true
+ }
+ }
+
+ if invocation {
+ if callID != "" && b.calls[callID] != nil {
+ mergeTraceToolCall(b.calls[callID], traceToolCallContent(event, callID, toolName))
+ return
+ }
+ named := callID != ""
+ if !named {
+ callID = event.ID
+ }
+ call := traceToolCallContent(event, callID, toolName)
+ message := b.append(event, TraceRoleAssistant, TraceMessageKindToolCall, traceToolCallText(call), TraceMessagePartV1{Type: TracePartToolCall, Content: call})
+ b.calls[callID] = call
+ b.callMessage[callID] = message
+ // Only an explicit invocation waits for a result. A phase-less event promoted to a call is
+ // already whole; queuing it would turn the next read of the same file into its result.
+ if !named && explicit {
+ b.pending = append(b.pending, callID)
+ }
+ return
+ }
+
+ // A completion.
+ if callID == "" {
+ callID = b.pairPending(event, toolName)
+ }
+ if callID != "" && b.results[callID] != nil {
+ mergeTraceToolResult(b.results[callID], traceToolResultContent(event, callID, toolName))
+ if call := b.calls[callID]; call != nil {
+ mergeTraceToolCall(call, traceToolCallContent(event, callID, toolName))
+ }
+ return
+ }
+ if callID == "" || b.calls[callID] == nil {
+ // No invocation on the trace: the runtime reported only the finished call (a poll backfill,
+ // a post-tool hook alone). Write the call just ahead of its result.
+ if callID == "" {
+ callID = event.ID
+ }
+ call := traceToolCallContent(event, callID, toolName)
+ message := b.newMessage(event, eventUUID("trace-call", event.ID), TraceRoleAssistant, TraceMessageKindToolCall, traceToolCallText(call), TraceMessagePartV1{Type: TracePartToolCall, Content: call})
+ message.TokenUsage = nil
+ b.messages = append(b.messages, message)
+ b.calls[callID] = call
+ b.callMessage[callID] = message
+ } else {
+ // The completion often carries what the invocation did not: the diff, the command line.
+ mergeTraceToolCall(b.calls[callID], traceToolCallContent(event, callID, toolName))
+ }
+ if toolName == "" {
+ toolName = b.calls[callID].ToolName
+ }
+ result := traceToolResultContent(event, callID, toolName)
+ b.append(event, TraceRoleAssistant, TraceMessageKindToolResult, traceToolResultText(result), TraceMessagePartV1{Type: TracePartToolResult, Content: result})
+ b.results[callID] = result
+}
+
+// pairPending finds the most recent unanswered invocation without a runtime call id for the same
+// tool, removes it from the queue and returns its call id.
+func (b *traceMessageBuilder) pairPending(event TraceEventV1, toolName string) string {
+ command, path := traceMessageCommand(event), traceMessageFilePath(event)
+ for i := len(b.pending) - 1; i >= 0; i-- {
+ id := b.pending[i]
+ call := b.calls[id]
+ if call == nil || b.results[id] != nil {
+ continue
+ }
+ if normalizeToolName(call.ToolName) != normalizeToolName(toolName) {
+ continue
+ }
+ if command != "" && call.Command != "" && command != call.Command {
+ continue
+ }
+ if path != "" && call.FilePath != "" && path != call.FilePath {
+ continue
+ }
+ b.pending = append(b.pending[:i], b.pending[i+1:]...)
+ return id
+ }
+ return ""
+}
+
+func traceToolCallContent(event TraceEventV1, callID, toolName string) *TraceToolCallContentV1 {
+ call := &TraceToolCallContentV1{
+ CallID: callID,
+ ToolName: toolName,
+ ToolKind: TraceToolKind(toolName, event.Action, event.Category, event.MCP != nil),
+ Args: traceToolArgs(event),
+ Command: traceMessageCommand(event),
+ FilePath: traceMessageFilePath(event),
+ }
+ if event.File != nil && event.File.Diff != nil {
+ call.Diff = event.File.Diff.Text
+ }
+ if call.Args == nil {
+ call.Args = map[string]interface{}{}
+ }
+ return call
+}
+
+func traceToolResultContent(event TraceEventV1, callID, toolName string) *TraceToolResultContentV1 {
+ result := &TraceToolResultContentV1{
+ CallID: callID,
+ ToolName: toolName,
+ Output: traceToolOutput(event),
+ Status: TraceToolStatusSuccess,
+ }
+ if event.Command != nil {
+ if event.Command.ExitCode != nil {
+ code := *event.Command.ExitCode
+ result.ExitCode = &code
+ }
+ if event.Command.DurationMS > 0 {
+ ms := event.Command.DurationMS
+ result.DurationMS = &ms
+ }
+ }
+ if traceToolFailed(event) {
+ result.Status = TraceToolStatusError
+ }
+ return result
+}
+
+func mergeTraceToolCall(dst, src *TraceToolCallContentV1) {
+ if dst.ToolName == "" {
+ dst.ToolName = src.ToolName
+ }
+ if dst.ToolKind == "" || dst.ToolKind == TraceToolKindOther {
+ dst.ToolKind = src.ToolKind
+ }
+ if len(dst.Args) == 0 && len(src.Args) > 0 {
+ dst.Args = src.Args
+ }
+ if dst.Command == "" {
+ dst.Command = src.Command
+ }
+ if dst.FilePath == "" {
+ dst.FilePath = src.FilePath
+ }
+ if dst.Diff == "" {
+ dst.Diff = src.Diff
+ }
+}
+
+func mergeTraceToolResult(dst, src *TraceToolResultContentV1) {
+ if dst.ToolName == "" {
+ dst.ToolName = src.ToolName
+ }
+ if dst.Output == "" {
+ dst.Output = src.Output
+ }
+ if dst.ExitCode == nil {
+ dst.ExitCode = src.ExitCode
+ }
+ if dst.DurationMS == nil {
+ dst.DurationMS = src.DurationMS
+ }
+ if src.Status == TraceToolStatusError {
+ dst.Status = TraceToolStatusError
+ }
+}
+
+func (b *traceMessageBuilder) addApproval(event TraceEventV1) {
+ content := map[string]interface{}{}
+ action := strings.ToLower(event.Action)
+ subtype := "approval"
+ if strings.HasPrefix(action, "policy.") || (event.Policy != nil && event.Approval == nil) {
+ subtype = "policy"
+ }
+ content["subtype"] = subtype
+ content["action"] = event.Action
+ if event.Approval != nil {
+ putString(content, "decision", event.Approval.Decision)
+ putString(content, "reason", event.Approval.Reason)
+ if event.Approval.Required {
+ content["required"] = true
+ }
+ }
+ if event.Policy != nil {
+ putString(content, "policyDecision", event.Policy.Decision)
+ putString(content, "enforcement", event.Policy.Enforcement)
+ putString(content, "policyName", event.Policy.Name)
+ if _, ok := content["reason"]; !ok {
+ putString(content, "reason", event.Policy.Reason)
+ }
+ }
+ putString(content, "toolName", traceMessageToolName(event))
+ putString(content, "callId", event.ToolCallID)
+ putString(content, "command", traceMessageCommand(event))
+ putString(content, "fidelity", event.Fidelity)
+ text := strings.TrimSpace(strings.Join(nonEmpty(event.Action, stringField(content, "toolName"), stringField(content, "decision")), " "))
+ b.append(event, TraceRoleSystem, TraceMessageKindApproval, text, TraceMessagePartV1{Type: TracePartSystemEvent, Content: content})
+}
+
+func (b *traceMessageBuilder) addSystem(event TraceEventV1) {
+ content := map[string]interface{}{"subtype": event.Action}
+ putString(content, "fidelity", event.Fidelity)
+ summary := TruncateString(strings.TrimSpace(event.Summary), 500)
+ putString(content, "summary", summary)
+ b.append(event, TraceRoleSystem, TraceMessageKindSystem, traceFirstNonEmpty(summary, event.Action), TraceMessagePartV1{Type: TracePartSystemEvent, Content: content})
+}
+
+func tracePromptText(event TraceEventV1) string {
+ if event.Content != nil {
+ return strings.TrimSpace(event.Content.Text)
+ }
+ return ""
+}
+
+// traceAssistantText is the retained assistant text of an event the projection typed eventType.
+// When nothing was retained the projection falls back to the event's message, which writers
+// usually fill with a fixed label ("Codex assistant message"); a label is not what the assistant
+// said, so it is not text.
+func traceAssistantText(event TraceEventV1, eventType string) string {
+ if event.Type != eventType || event.Content == nil {
+ return ""
+ }
+ text := strings.TrimSpace(event.Content.Text)
+ if text != "" && text == strings.TrimSpace(event.Summary) && looksLikeLabel(text) {
+ return ""
+ }
+ return text
+}
+
+// looksLikeLabel recognizes the fixed descriptions writers put in event.message ("Codex assistant
+// message", "Claude Code reasoning observed"), which are not what the assistant said.
+func looksLikeLabel(message string) bool {
+ lower := strings.ToLower(strings.TrimSpace(message))
+ for _, suffix := range []string{" observed", " message", " reasoning", " response", " completed", " captured"} {
+ if strings.HasSuffix(lower, suffix) && utf8.RuneCountInString(lower) < 60 {
+ return true
+ }
+ }
+ return false
+}
+
+func traceMessageToolName(event TraceEventV1) string {
+ if event.Tool != nil && strings.TrimSpace(event.Tool.Name) != "" {
+ return strings.TrimSpace(event.Tool.Name)
+ }
+ if event.MCP != nil && strings.TrimSpace(event.MCP.Tool) != "" {
+ if event.MCP.Server != "" {
+ return "mcp__" + event.MCP.Server + "__" + event.MCP.Tool
+ }
+ return event.MCP.Tool
+ }
+ switch {
+ case event.Command != nil && event.Command.Command != "":
+ return "shell"
+ case event.File != nil:
+ switch strings.ToLower(event.Action) {
+ case "file.read":
+ return "read"
+ case "file.created":
+ return "write"
+ case "file.deleted":
+ return "delete"
+ default:
+ return "edit"
+ }
+ }
+ return ""
+}
+
+func traceMessageCommand(event TraceEventV1) string {
+ if event.Command != nil && strings.TrimSpace(event.Command.Command) != "" {
+ return strings.TrimSpace(event.Command.Command)
+ }
+ if event.Tool != nil {
+ return strings.TrimSpace(event.Tool.Command)
+ }
+ return ""
+}
+
+func traceMessageFilePath(event TraceEventV1) string {
+ if event.File != nil && strings.TrimSpace(event.File.Path) != "" {
+ return strings.TrimSpace(event.File.Path)
+ }
+ if event.Tool != nil {
+ return strings.TrimSpace(event.Tool.Path)
+ }
+ return ""
+}
+
+// traceToolArgs returns the call's arguments when they are an object (or a JSON object in a
+// string).
+func traceToolArgs(event TraceEventV1) map[string]interface{} {
+ if event.Tool == nil {
+ return nil
+ }
+ return objectValue(event.Tool.Arguments)
+}
+
+func objectValue(value interface{}) map[string]interface{} {
+ switch typed := value.(type) {
+ case map[string]interface{}:
+ if len(typed) == 0 {
+ return nil
+ }
+ return typed
+ case string:
+ trimmed := strings.TrimSpace(typed)
+ if !strings.HasPrefix(trimmed, "{") {
+ return nil
+ }
+ var out map[string]interface{}
+ if json.Unmarshal([]byte(trimmed), &out) == nil && len(out) > 0 {
+ return SanitizeMap(out, PrivacyOptions{RedactSecrets: true, StringLimit: DefaultRawStringLimit})
+ }
+ case nil:
+ return nil
+ default:
+ data, err := json.Marshal(typed)
+ if err != nil {
+ return nil
+ }
+ var out map[string]interface{}
+ if json.Unmarshal(data, &out) == nil && len(out) > 0 {
+ return out
+ }
+ }
+ return nil
+}
+
+func traceToolOutput(event TraceEventV1) string {
+ if event.Command != nil && event.Command.Output != nil && strings.TrimSpace(event.Command.Output.Text) != "" {
+ return event.Command.Output.Text
+ }
+ if event.Tool != nil && event.Tool.Result != nil {
+ return RedactString(TruncateString(ToolResultPlainText(event.Tool.Result), DefaultStringLimit))
+ }
+ return ""
+}
+
+func traceToolFailed(event TraceEventV1) bool {
+ action := strings.ToLower(event.Action)
+ if strings.Contains(action, "fail") || strings.Contains(action, "error") || strings.Contains(action, "denied") {
+ return true
+ }
+ if event.Error != nil && event.Error.Type != "" {
+ return true
+ }
+ return event.Command != nil && event.Command.ExitCode != nil && *event.Command.ExitCode != 0
+}
+
+func traceErrorType(event TraceEventV1) string {
+ if event.Error != nil {
+ return event.Error.Type
+ }
+ return ""
+}
+
+func traceToolCallText(call *TraceToolCallContentV1) string {
+ detail := traceFirstNonEmpty(call.Command, call.FilePath)
+ if detail == "" {
+ return call.ToolName
+ }
+ if call.ToolName == "" {
+ return TruncateString(detail, 1024)
+ }
+ return TruncateString(call.ToolName+": "+detail, 1024)
+}
+
+func traceToolResultText(result *TraceToolResultContentV1) string {
+ if result.Output != "" {
+ return TruncateString(result.Output, 1024)
+ }
+ return strings.TrimSpace(result.ToolName + " " + result.Status)
+}
+
+// traceEventTime parses an event's timestamp.
+func traceEventTime(event TraceEventV1) (time.Time, bool) {
+ if ts, err := ParseTimestamp(event.Timestamp); err == nil {
+ return ts, true
+ }
+ if ts, err := time.Parse(time.RFC3339Nano, event.Timestamp); err == nil {
+ return ts, true
+ }
+ return time.Time{}, false
+}
+
+func traceMessageTimestamp(event TraceEventV1) string {
+ if ts, ok := traceEventTime(event); ok {
+ return ts.UTC().Format(time.RFC3339Nano)
+ }
+ return event.Timestamp
+}
+
+// TraceToolKind classifies a tool for a tool_call part's toolKind, from the tool's own name first
+// -- every runtime names its tools differently, so the table covers each supported runtime's
+// spellings -- and then from what Beacon recorded about the call (an MCP server, a command, a file
+// operation). Anything else is "other".
+func TraceToolKind(toolName, action, category string, isMCP bool) string {
+ name := normalizeToolName(toolName)
+ if kind, ok := traceToolKindsByName[name]; ok {
+ return kind
+ }
+ lowerAction := strings.ToLower(strings.TrimSpace(action))
+ lowerCategory := strings.ToLower(strings.TrimSpace(category))
+ rawLower := strings.ToLower(strings.TrimSpace(toolName))
+ switch {
+ case isMCP || lowerCategory == "mcp" || strings.HasPrefix(lowerAction, "mcp.") ||
+ strings.HasPrefix(rawLower, "mcp__") || strings.HasPrefix(rawLower, "mcp_") || strings.HasPrefix(rawLower, "mcp."):
+ return TraceToolKindMCP
+ case strings.HasPrefix(lowerAction, "command.") || lowerCategory == "command":
+ return TraceToolKindTerminalCommand
+ case lowerAction == "file.read":
+ return TraceToolKindRead
+ case lowerAction == "file.created":
+ return TraceToolKindWrite
+ case lowerAction == "file.deleted":
+ return TraceToolKindDelete
+ case lowerAction == "file.modified" || lowerAction == "file.edited":
+ return TraceToolKindEdit
+ }
+ switch {
+ case name == "":
+ return TraceToolKindOther
+ case strings.Contains(name, "bash") || strings.Contains(name, "shell") || strings.Contains(name, "terminal"):
+ return TraceToolKindTerminalCommand
+ case strings.Contains(name, "websearch"):
+ return TraceToolKindWebSearch
+ case strings.Contains(name, "webfetch") || strings.Contains(name, "fetchurl"):
+ return TraceToolKindWebFetch
+ case strings.Contains(name, "todo"):
+ return TraceToolKindTodo
+ case strings.Contains(name, "grep"):
+ return TraceToolKindGrep
+ case strings.Contains(name, "glob"):
+ return TraceToolKindGlob
+ case strings.Contains(name, "read"):
+ return TraceToolKindRead
+ case strings.Contains(name, "edit") || strings.Contains(name, "patch") || strings.Contains(name, "replace"):
+ return TraceToolKindEdit
+ case strings.Contains(name, "write") || strings.Contains(name, "create"):
+ return TraceToolKindWrite
+ case strings.Contains(name, "delete"):
+ return TraceToolKindDelete
+ }
+ return TraceToolKindOther
+}
+
+// normalizeToolName lowercases a tool name and drops separators, so exec_command, execCommand and
+// exec-command compare equal. A namespace prefix some runtimes add ("functions.", "default_api:")
+// is dropped first.
+func normalizeToolName(name string) string {
+ name = strings.ToLower(strings.TrimSpace(name))
+ for _, prefix := range []string{"functions.", "default_api:", "default_api."} {
+ name = strings.TrimPrefix(name, prefix)
+ }
+ var b strings.Builder
+ for _, r := range name {
+ if r == '_' || r == '-' || r == ' ' || r == '.' {
+ continue
+ }
+ b.WriteRune(r)
+ }
+ return b.String()
+}
+
+// traceToolKindsByName maps normalized tool names to kinds: Claude Code, Codex CLI, Cursor, Gemini
+// CLI, Qwen Code, OpenCode, Cline, the Pi family, Copilot, Kiro, OpenHands, Antigravity, DeepSeek
+// Harness, Grok Build and fx spellings.
+var traceToolKindsByName = func() map[string]string {
+ table := map[string][]string{
+ TraceToolKindTerminalCommand: {
+ "bash", "shell", "execcommand", "exec", "localshell", "runterminalcmd", "runterminalcommand",
+ "runcommand", "runshellcommand", "executebash", "executecommand", "terminal", "command",
+ "bashoutput", "killshell", "killbash", "terminalsend", "ipython", "powershell", "cmd",
+ },
+ TraceToolKindRead: {
+ "read", "view", "readfile", "viewfile", "cat", "notebookread", "readmanyfiles", "openfile",
+ "fsread", "readimage",
+ },
+ TraceToolKindEdit: {
+ "edit", "multiedit", "applypatch", "strreplace", "strreplaceeditor", "strreplacebasededittool",
+ "searchreplace", "editfile", "replace", "notebookedit", "patch", "replaceinfile", "editnotebook",
+ "fswrite",
+ },
+ TraceToolKindWrite: {
+ "write", "create", "writefile", "createfile", "writetofile", "newfile",
+ },
+ TraceToolKindDelete: {
+ "delete", "deletefile", "remove", "removefile", "rm",
+ },
+ TraceToolKindGrep: {
+ "grep", "grepsearch", "search", "rg", "ripgrep", "searchfilecontent", "codebasesearch",
+ "searchfiles",
+ },
+ TraceToolKindGlob: {
+ "glob", "find", "filesearch", "findbyname", "ls", "listdir", "listdirectory", "listfiles",
+ },
+ TraceToolKindWebSearch: {
+ "websearch", "googlesearch", "googlewebsearch", "searchweb",
+ },
+ TraceToolKindWebFetch: {
+ "webfetch", "fetch", "fetchurl", "readurl", "urlfetch", "browse",
+ },
+ TraceToolKindTask: {
+ "task", "agent", "subagent", "spawnagent", "dispatchagent", "delegate", "newtask", "runsubagent",
+ },
+ TraceToolKindTodo: {
+ "todowrite", "todoread", "todo", "updateplan", "writetodos", "updatetodos", "todolist",
+ },
+ }
+ out := map[string]string{}
+ for kind, names := range table {
+ for _, name := range names {
+ out[name] = kind
+ }
+ }
+ return out
+}()
+
+func putString(m map[string]interface{}, key, value string) {
+ if value = strings.TrimSpace(value); value != "" {
+ m[key] = value
+ }
+}
+
+func stringField(m map[string]interface{}, key string) string {
+ value, _ := m[key].(string)
+ return value
+}
+
+func nonEmpty(values ...string) []string {
+ out := values[:0:0]
+ for _, value := range values {
+ if strings.TrimSpace(value) != "" {
+ out = append(out, value)
+ }
+ }
+ return out
+}