The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
add claude backfill support
Justin D'Souza0c77cf2cda50
diff --git a/cli/beacon/cmd/endpoint_claude.go b/cli/beacon/cmd/endpoint_claude.gonew file mode 100644index 00000000..b867688e--- /dev/null+++ b/cli/beacon/cmd/endpoint_claude.go@@ -0,0 +1,226 @@+package cmd++import (+ "context"+ "encoding/json"+ "fmt"+ "path/filepath"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/claudesession"+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"+ "github.com/spf13/cobra"+)++var endpointClaudeCmd = &cobra.Command{+ Use: "claude",+ Short: "Collect telemetry from Claude Code session files",+ Long: `Collect endpoint telemetry from Claude Code's local session transcripts.++Beacon's normal Claude Code integration uses hooks and OpenTelemetry for live capture.+This command reads Claude's committed JSONL session files under ~/.claude/projects so+historical sessions and sessions that ran without Beacon hooks can still be represented+in the local endpoint log. Every emitted event is marked harness.collection_method=poll:+Beacon sees what Claude already wrote, so nothing here can hold or deny a tool call.`,+}++var endpointClaudeSyncCmd = &cobra.Command{+ Use: "sync",+ Short: "Read new Claude Code session records into the runtime log",+ SilenceUsage: true,+ RunE: runEndpointClaudeSync,+}++var endpointClaudeStatusCmd = &cobra.Command{+ Use: "status",+ Short: "Show Claude Code sessions on this machine and how much Beacon collected",+ SilenceUsage: true,+ RunE: runEndpointClaudeStatus,+}++var endpointClaudeOpts struct {+ projectsDir string+ statePath string+ logPath string+ print bool+ watch bool+ interval time.Duration+}++func init() {+ endpointCmd.AddCommand(endpointClaudeCmd)+ endpointClaudeCmd.AddCommand(endpointClaudeSyncCmd)+ endpointClaudeCmd.AddCommand(endpointClaudeStatusCmd)++ for _, c := range []*cobra.Command{endpointClaudeSyncCmd, endpointClaudeStatusCmd} {+ f := c.Flags()+ f.StringVar(&endpointClaudeOpts.projectsDir, "projects-dir", "", "Claude projects directory (default ~/.claude/projects)")+ f.StringVar(&endpointClaudeOpts.statePath, "state", "", "Collector cursor file (default ~/.beacon/endpoint/state/claude.json)")+ f.BoolVar(&endpointOpts.jsonOutput, "json", false, "Print the result as JSON")+ f.BoolVar(&endpointOpts.userMode, "user", true, "Use per-user endpoint paths")+ f.BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths")+ }++ sync := endpointClaudeSyncCmd.Flags()+ sync.StringVar(&endpointClaudeOpts.logPath, "log-path", "", "Runtime JSONL log path (default resolved endpoint log)")+ sync.BoolVar(&endpointClaudeOpts.print, "print", false, "Print mapped events as JSON without writing them or advancing the cursor (dry run)")+ sync.BoolVar(&endpointClaudeOpts.watch, "watch", false, "Sweep continuously on --interval (default: one sweep then exit)")+ sync.DurationVar(&endpointClaudeOpts.interval, "interval", time.Minute, "Sweep interval for --watch")+}++func runEndpointClaudeSync(cmd *cobra.Command, args []string) error {+ userMode := endpointUserMode()+ opts := claudesession.CollectOptions{+ ProjectsDir: endpointClaudeOpts.projectsDir,+ Print: endpointClaudeOpts.print,+ Out: cmd.OutOrStdout(),+ Write: !endpointClaudeOpts.print,+ UserMode: userMode,+ }+ if !endpointClaudeOpts.print {+ opts.StatePath = resolveClaudeStatePath(endpointClaudeOpts.statePath, userMode)+ opts.LogPath = lifecycle.ResolveRuntimeLog(userMode, endpointClaudeOpts.logPath).EffectiveLogPath+ }++ ctx := cmd.Context()+ if ctx == nil {+ ctx = context.Background()+ }+ if endpointClaudeOpts.watch && !endpointClaudeOpts.print {+ return watchClaude(ctx, cmd, opts)+ }++ summary, err := claudesession.CollectOnce(opts)+ reportClaudeSweep(cmd, summary)+ return err+}++func watchClaude(ctx context.Context, cmd *cobra.Command, opts claudesession.CollectOptions) error {+ interval := endpointClaudeOpts.interval+ if interval < 5*time.Second {+ interval = 5 * time.Second+ }+ for {+ summary, err := claudesession.CollectOnce(opts)+ if err != nil {+ fmt.Fprintf(cmd.ErrOrStderr(), "claude sync error: %v\n", err)+ }+ reportClaudeSweep(cmd, summary)+ select {+ case <-ctx.Done():+ return nil+ case <-time.After(interval):+ }+ }+}++func reportClaudeSweep(cmd *cobra.Command, summary claudesession.Summary) {+ if endpointClaudeOpts.print {+ return+ }+ if endpointOpts.jsonOutput {+ _ = json.NewEncoder(cmd.OutOrStdout()).Encode(summary)+ return+ }+ fmt.Fprintf(cmd.OutOrStdout(), "claude sync: %d sessions, %d changed, %d events, %d errors\n",+ summary.Sessions, summary.SessionsChanged, summary.EventsEmitted, summary.Errors)+ if summary.MalformedLines > 0 {+ fmt.Fprintf(cmd.OutOrStdout(), " %d unreadable line(s) in Claude session logs\n", summary.MalformedLines)+ }+ if summary.PartialSessions > 0 {+ fmt.Fprintf(cmd.OutOrStdout(), " %d session(s) had a partly written record; it will be read on the next sweep\n", summary.PartialSessions)+ }+}++type claudeSessionStatus struct {+ SessionID string `json:"session_id"`+ Path string `json:"path"`+ Workspace string `json:"workspace,omitempty"`+ UpdatedAt string `json:"updated_at,omitempty"`+ CollectedLine int `json:"collected_line"`+ Collected bool `json:"collected"`+ SizeBytes int64 `json:"size_bytes"`+ IsSidechain bool `json:"is_sidechain,omitempty"`+ ParentSession string `json:"parent_session_id,omitempty"`+}++type claudeStatusReport struct {+ ProjectsDir string `json:"projects_dir"`+ Present bool `json:"present"`+ StatePath string `json:"state_path,omitempty"`+ Sessions []claudeSessionStatus `json:"sessions"`+}++func runEndpointClaudeStatus(cmd *cobra.Command, args []string) error {+ store, err := claudesession.NewStore(endpointClaudeOpts.projectsDir)+ if err != nil {+ return err+ }+ statePath := resolveClaudeStatePath(endpointClaudeOpts.statePath, endpointUserMode())+ state, err := claudesession.LoadState(statePath)+ if err != nil {+ return err+ }+ refs, err := store.List()+ if err != nil {+ return err+ }+ report := claudeStatusReport{+ ProjectsDir: store.ProjectsDir,+ Present: store.Exists(),+ StatePath: statePath,+ Sessions: make([]claudeSessionStatus, 0, len(refs)),+ }+ for _, ref := range refs {+ status := claudeSessionStatus{+ SessionID: ref.ID,+ Path: ref.Path,+ Workspace: ref.ProjectPath,+ SizeBytes: ref.SizeBytes,+ IsSidechain: ref.IsSidechain,+ ParentSession: ref.ParentSessionID,+ }+ if ref.ModTimeUnixMS > 0 {+ status.UpdatedAt = time.UnixMilli(ref.ModTimeUnixMS).UTC().Format(time.RFC3339)+ }+ if cursor := state.Files[ref.Path]; cursor != nil {+ status.CollectedLine = cursor.LastLine+ status.Collected = cursor.SizeBytes == ref.SizeBytes && cursor.ModTimeUnixMS == ref.ModTimeUnixMS+ }+ report.Sessions = append(report.Sessions, status)+ }+ if endpointOpts.jsonOutput {+ return json.NewEncoder(cmd.OutOrStdout()).Encode(report)+ }+ fmt.Fprintf(cmd.OutOrStdout(), "Claude projects: %s\n", report.ProjectsDir)+ if !report.Present {+ fmt.Fprintln(cmd.OutOrStdout(), "No Claude Code session directory found.")+ return nil+ }+ fmt.Fprintf(cmd.OutOrStdout(), "Collector state: %s\n", report.StatePath)+ fmt.Fprintf(cmd.OutOrStdout(), "Sessions: %d\n", len(report.Sessions))+ for _, session := range report.Sessions {+ marker := "pending"+ if session.Collected {+ marker = "collected"+ }+ sidechain := ""+ if session.IsSidechain {+ sidechain = " sidechain"+ }+ fmt.Fprintf(cmd.OutOrStdout(), " %s %s%s line=%d size=%d workspace=%s\n",+ marker, session.SessionID, sidechain, session.CollectedLine, session.SizeBytes, session.Workspace)+ }+ return nil+}++func resolveClaudeStatePath(override string, userMode bool) string {+ if override != "" {+ return override+ }+ if userMode {+ return claudesession.DefaultStatePath()+ }+ return filepath.Join(endpointconfig.BaseDir(false), "state", "claude.json")+}diff --git a/cli/beacon/internal/claudesession/claudesession_test.go b/cli/beacon/internal/claudesession/claudesession_test.gonew file mode 100644index 00000000..b9c51694--- /dev/null+++ b/cli/beacon/internal/claudesession/claudesession_test.go@@ -0,0 +1,211 @@+package claudesession++import (+ "encoding/json"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+)++func TestListFindsClaudeSessionsAndSubagents(t *testing.T) {+ root := t.TempDir()+ project := filepath.Join(root, "-tmp-repo")+ mainPath := filepath.Join(project, "sess-1.jsonl")+ writeFile(t, mainPath, userLine("sess-1", "u1", "ship it")+"\n")+ writeFile(t, filepath.Join(project, "sessions-index.json"), `{"version":1,"entries":[{"sessionId":"sess-1","fullPath":`+quote(mainPath)+`,"projectPath":"/tmp/repo","gitBranch":"main"}]}`)++ subPath := filepath.Join(project, "sess-1", "subagents", "agent-a.jsonl")+ writeFile(t, subPath, userLine("sess-1", "su1", "inspect")+"\n")+ writeFile(t, strings.TrimSuffix(subPath, ".jsonl")+".meta.json", `{"agentType":"Explore","description":"inspect files","toolUseId":"toolu_sub"}`)++ store := &Store{ProjectsDir: root}+ refs, err := store.List()+ if err != nil {+ t.Fatalf("List: %v", err)+ }+ if len(refs) != 2 {+ t.Fatalf("List returned %d refs, want 2: %+v", len(refs), refs)+ }+ if refs[0].ProjectPath != "/tmp/repo" {+ t.Fatalf("project path = %q, want index value", refs[0].ProjectPath)+ }+ if !refs[1].IsSidechain || refs[1].ParentSessionID != "sess-1" || refs[1].Meta == nil || refs[1].Meta.AgentType != "Explore" {+ t.Fatalf("subagent ref not populated: %+v", refs[1])+ }+}++func TestMapClaudeTranscriptProducesEndpointEvents(t *testing.T) {+ ref := SessionRef{ID: "sess-1", Path: "/tmp/sess-1.jsonl", ProjectPath: "/tmp/repo"}+ records := decodeFixture(t, []string{+ userLine("sess-1", "u1", "add a health endpoint"),+ assistantLine("sess-1", "a1"),+ toolResultLine("sess-1", "r1", "toolu_bash", "ok", false),+ })++ mapped := MapSession(ref, records, MapOptions{})+ got := actions(mapped)+ want := []string{"session.started", "prompt.submitted", "tool.invoked", "agent.message", "token.usage", "command.executed"}+ if strings.Join(got, ",") != strings.Join(want, ",") {+ t.Fatalf("actions = %v, want %v", got, want)+ }+ for _, item := range mapped {+ ev := item.Event+ if ev.Harness.Name != Harness || ev.Harness.CollectionMethod != schema.CollectionMethodPoll {+ t.Fatalf("%s harness = %+v, want Claude poll", ev.Event.Action, ev.Harness)+ }+ if ev.Origin != schema.OriginLocal {+ t.Fatalf("%s origin = %q, want local", ev.Event.Action, ev.Origin)+ }+ if ev.Event.ID == "" {+ t.Fatalf("%s missing deterministic event id", ev.Event.Action)+ }+ if err := ev.Validate(); err != nil {+ t.Fatalf("%s failed validation: %v", ev.Event.Action, err)+ }+ }+ command := findAction(t, mapped, "command.executed")+ if command.Command == nil || command.Command.Command != "npm test" || command.Command.Output != "ok" {+ t.Fatalf("command = %+v, want npm test with output", command.Command)+ }+ usage := findAction(t, mapped, "token.usage")+ if usage.GenAI == nil || usage.GenAI.Usage == nil || usage.GenAI.Usage.InputTokens == nil || *usage.GenAI.Usage.InputTokens != 10 {+ t.Fatalf("usage = %+v, want input tokens", usage.GenAI)+ }+}++func TestCollectOnceUsesCursorAndPrintDoesNotAdvance(t *testing.T) {+ dir := t.TempDir()+ projects := filepath.Join(dir, "projects")+ sessionPath := filepath.Join(projects, "-tmp-repo", "sess-1.jsonl")+ writeFile(t, sessionPath, userLine("sess-1", "u1", "first")+"\n")+ statePath := filepath.Join(dir, "state", "claude.json")+ logPath := filepath.Join(dir, "runtime.jsonl")++ opts := CollectOptions{ProjectsDir: projects, StatePath: statePath, LogPath: logPath, Write: true, UserMode: true}+ first, err := CollectOnce(opts)+ if err != nil {+ t.Fatalf("first CollectOnce: %v", err)+ }+ if first.EventsEmitted == 0 {+ t.Fatal("first sweep emitted no events")+ }+ before := readLog(t, logPath)+ second, err := CollectOnce(opts)+ if err != nil {+ t.Fatalf("second CollectOnce: %v", err)+ }+ if second.EventsEmitted != 0 {+ t.Fatalf("second sweep emitted %d events, want 0", second.EventsEmitted)+ }+ if after := readLog(t, logPath); len(after) != len(before) {+ t.Fatalf("log grew from %d to %d events with unchanged cursor", len(before), len(after))+ }++ writeFile(t, sessionPath, userLine("sess-1", "u1", "first")+"\n"+userLine("sess-1", "u2", "second")+"\n")+ var printed strings.Builder+ printSummary, err := CollectOnce(CollectOptions{ProjectsDir: projects, Print: true, Out: &printed})+ if err != nil {+ t.Fatalf("print CollectOnce: %v", err)+ }+ if printSummary.EventsEmitted == 0 || printed.Len() == 0 {+ t.Fatalf("print sweep emitted nothing: summary=%+v output=%q", printSummary, printed.String())+ }+ realSummary, err := CollectOnce(opts)+ if err != nil {+ t.Fatalf("real CollectOnce after print: %v", err)+ }+ if realSummary.EventsEmitted == 0 {+ t.Fatal("--print advanced the cursor; real sweep had nothing left")+ }+}++func decodeFixture(t *testing.T, lines []string) []Record {+ t.Helper()+ records, stats, err := decodeRecords(strings.NewReader(strings.Join(lines, "\n") + "\n"))+ if err != nil {+ t.Fatalf("decodeRecords: %v", err)+ }+ if stats.Malformed != 0 {+ t.Fatalf("malformed fixture: %+v", stats)+ }+ return records+}++func actions(mapped []MappedEvent) []string {+ out := make([]string, 0, len(mapped))+ for _, item := range mapped {+ out = append(out, item.Event.Event.Action)+ }+ return out+}++func findAction(t *testing.T, mapped []MappedEvent, action string) schema.Event {+ t.Helper()+ for _, item := range mapped {+ if item.Event.Event.Action == action {+ return item.Event+ }+ }+ t.Fatalf("no %s in %v", action, actions(mapped))+ return schema.Event{}+}++func readLog(t *testing.T, path string) []schema.Event {+ t.Helper()+ data, err := os.ReadFile(path)+ if err != nil {+ if os.IsNotExist(err) {+ return nil+ }+ t.Fatal(err)+ }+ var out []schema.Event+ for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") {+ if line == "" {+ continue+ }+ var ev schema.Event+ if err := json.Unmarshal([]byte(line), &ev); err != nil {+ t.Fatalf("decode log line: %v", err)+ }+ out = append(out, ev)+ }+ return out+}++func writeFile(t *testing.T, path, content string) {+ t.Helper()+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, []byte(content), 0o600); err != nil {+ t.Fatal(err)+ }+}++func userLine(sessionID, uuid, text string) string {+ return `{"parentUuid":null,"isSidechain":false,"type":"user","message":{"role":"user","content":` + quote(text) + `},"uuid":` + quote(uuid) + `,"timestamp":"2026-09-19T22:00:00.000Z","cwd":"/tmp/repo","sessionId":` + quote(sessionID) + `,"version":"2.1.154","gitBranch":"main"}`+}++func assistantLine(sessionID, uuid string) string {+ return `{"parentUuid":"u1","isSidechain":false,"type":"assistant","message":{"model":"claude-sonnet-4-5","id":"msg_1","role":"assistant","content":[{"type":"text","text":"I'll run tests."},{"type":"tool_use","id":"toolu_bash","name":"Bash","input":{"command":"npm test"}}],"usage":{"input_tokens":10,"output_tokens":4,"cache_read_input_tokens":2}},"uuid":` + quote(uuid) + `,"timestamp":"2026-09-19T22:00:01.000Z","cwd":"/tmp/repo","sessionId":` + quote(sessionID) + `,"version":"2.1.154","gitBranch":"main"}`+}++func toolResultLine(sessionID, uuid, toolUseID, output string, isError bool) string {+ return `{"parentUuid":"a1","isSidechain":false,"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":` + quote(toolUseID) + `,"content":` + quote(output) + `,"is_error":` + boolString(isError) + `}]},"uuid":` + quote(uuid) + `,"timestamp":"2026-09-19T22:00:02.000Z","cwd":"/tmp/repo","sessionId":` + quote(sessionID) + `,"version":"2.1.154","gitBranch":"main"}`+}++func quote(s string) string {+ data, _ := json.Marshal(s)+ return string(data)+}++func boolString(v bool) string {+ if v {+ return "true"+ }+ return "false"+}diff --git a/cli/beacon/internal/claudesession/collect.go b/cli/beacon/internal/claudesession/collect.gonew file mode 100644index 00000000..3d1b2aeb--- /dev/null+++ b/cli/beacon/internal/claudesession/collect.go@@ -0,0 +1,209 @@+package claudesession++import (+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "os"+ "path/filepath"+ "strings"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"+)++const StateVersion = 1++type Cursor struct {+ LastLine int `json:"last_line"`+ SizeBytes int64 `json:"size_bytes,omitempty"`+ ModTimeUnixMS int64 `json:"mtime_unix_ms,omitempty"`+ Started bool `json:"started,omitempty"`+}++type State struct {+ Version int `json:"version"`+ Files map[string]*Cursor `json:"files"`+}++type CollectOptions struct {+ ProjectsDir string+ StatePath string+ Write bool+ LogPath string+ UserMode bool+ Print bool+ Out io.Writer+}++type Summary struct {+ Sessions int `json:"sessions"`+ SessionsChanged int `json:"sessions_changed"`+ EventsEmitted int `json:"events_emitted"`+ Errors int `json:"errors"`+ MalformedLines int `json:"malformed_lines"`+ PartialSessions int `json:"partial_sessions"`+}++func DefaultStatePath() string {+ base := filepath.Join(os.TempDir(), "beacon")+ if home, err := os.UserHomeDir(); err == nil && strings.TrimSpace(home) != "" {+ base = filepath.Join(home, ".beacon")+ }+ return filepath.Join(base, "endpoint", "state", "claude.json")+}++func LoadState(path string) (*State, error) {+ state := &State{Version: StateVersion, Files: map[string]*Cursor{}}+ if path == "" {+ return state, nil+ }+ data, err := os.ReadFile(path)+ if err != nil {+ if errors.Is(err, os.ErrNotExist) {+ return state, nil+ }+ return nil, err+ }+ var stored State+ if err := json.Unmarshal(data, &stored); err != nil {+ return nil, fmt.Errorf("read Claude collector state %s: %w", path, err)+ }+ if stored.Version != StateVersion || stored.Files == nil {+ return state, nil+ }+ state.Files = stored.Files+ return state, nil+}++func (s *State) Save(path string) error {+ if path == "" {+ return nil+ }+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ return err+ }+ s.Version = StateVersion+ data, err := json.MarshalIndent(s, "", " ")+ if err != nil {+ return err+ }+ tmp := path + ".tmp"+ if err := os.WriteFile(tmp, data, 0o600); err != nil {+ return err+ }+ return os.Rename(tmp, path)+}++func (s *State) cursor(path string) *Cursor {+ if s.Files == nil {+ s.Files = map[string]*Cursor{}+ }+ c := s.Files[path]+ if c == nil {+ c = &Cursor{}+ s.Files[path] = c+ }+ return c+}++func CollectOnce(opts CollectOptions) (summary Summary, err error) {+ store, err := NewStore(opts.ProjectsDir)+ if err != nil {+ return summary, err+ }+ refs, err := store.List()+ if err != nil {+ return summary, err+ }+ summary.Sessions = len(refs)+ if len(refs) == 0 {+ return summary, nil+ }+ state, err := LoadState(opts.StatePath)+ if err != nil {+ return summary, err+ }+ defer func() {+ if saveErr := state.Save(opts.StatePath); saveErr != nil && err == nil {+ err = fmt.Errorf("save Claude collector state: %w", saveErr)+ }+ }()++ var errs []error+ for _, ref := range refs {+ changed, collectErr := collectSession(store, ref, state, opts, &summary)+ if collectErr != nil {+ summary.Errors+++ errs = append(errs, fmt.Errorf("Claude session %s: %w", ref.ID, collectErr))+ continue+ }+ if changed {+ summary.SessionsChanged+++ }+ }+ if len(errs) > 0 {+ return summary, errors.Join(errs...)+ }+ return summary, nil+}++func collectSession(store *Store, ref SessionRef, state *State, opts CollectOptions, summary *Summary) (bool, error) {+ cursor := state.cursor(ref.Path)+ if ref.SizeBytes < cursor.SizeBytes {+ cursor.LastLine = 0+ cursor.Started = false+ }+ if ref.SizeBytes == cursor.SizeBytes && ref.ModTimeUnixMS == cursor.ModTimeUnixMS {+ return false, nil+ }+ records, stats, err := store.Read(ref)+ summary.MalformedLines += stats.Malformed+ if stats.PartialTail {+ summary.PartialSessions+++ }+ if err != nil {+ return false, err+ }+ mapped := MapSession(ref, records, MapOptions{MinLine: cursor.LastLine, SkipSessionStarted: cursor.Started})+ if len(mapped) == 0 {+ advanceCursor(cursor, ref, stats.Lines)+ return false, nil+ }+ for i, item := range mapped {+ if err := emit(item.Event, opts); err != nil {+ if i > 0 {+ cursor.LastLine = mapped[i-1].SourceLine+ }+ return true, err+ }+ summary.EventsEmitted+++ if item.Event.Event.Action == "session.started" {+ cursor.Started = true+ }+ }+ advanceCursor(cursor, ref, stats.Lines)+ return true, nil+}++func advanceCursor(cursor *Cursor, ref SessionRef, lines int) {+ cursor.LastLine = lines+ cursor.SizeBytes = ref.SizeBytes+ cursor.ModTimeUnixMS = ref.ModTimeUnixMS+}++func emit(event schema.Event, opts CollectOptions) error {+ if opts.Print {+ out := opts.Out+ if out == nil {+ out = io.Discard+ }+ return json.NewEncoder(out).Encode(event)+ }+ if !opts.Write {+ return nil+ }+ _, err := writer.AppendEvent(event, writer.Options{Path: opts.LogPath, UserMode: opts.UserMode})+ return err+}diff --git a/cli/beacon/internal/claudesession/mapper.go b/cli/beacon/internal/claudesession/mapper.gonew file mode 100644index 00000000..163bab32--- /dev/null+++ b/cli/beacon/internal/claudesession/mapper.go@@ -0,0 +1,627 @@+package claudesession++import (+ "crypto/sha1"+ "encoding/hex"+ "encoding/json"+ "fmt"+ "io"+ "path/filepath"+ "strings"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+)++type MappedEvent struct {+ DedupID string+ SourceLine int+ Event schema.Event+}++type MapOptions struct {+ MinLine int+ SkipSessionStarted bool+}++type toolCall struct {+ ID string+ Name string+ Input map[string]interface{}+}++type mapper struct {+ ref SessionRef+ opts MapOptions+ out []MappedEvent+ tools map[string]toolCall+}++func MapSession(ref SessionRef, records []Record, opts MapOptions) []MappedEvent {+ m := &mapper{ref: ref, opts: opts, tools: map[string]toolCall{}}+ for i := range records {+ m.consume(records[i])+ }+ return m.out+}++func (m *mapper) consume(record Record) {+ entry := record.Entry+ emit := record.Line > m.opts.MinLine+ if emit && !m.opts.SkipSessionStarted && len(m.out) == 0 && entry.SessionID != "" {+ m.emitSessionStarted(record)+ }++ switch entry.Type {+ case "user":+ m.consumeUser(record, emit)+ case "assistant":+ m.consumeAssistant(record, emit)+ case "summary":+ if emit {+ m.emitSummary(record)+ }+ }+}++func (m *mapper) consumeUser(record Record, emit bool) {+ entry := record.Entry+ if entry.IsMeta {+ return+ }+ content := entry.Message["content"]+ if text, ok := content.(string); ok {+ text = cleanUserText(text)+ if emit && text != "" {+ m.emitPrompt(record, text)+ }+ return+ }+ blocks, ok := content.([]interface{})+ if !ok {+ return+ }+ var textParts []string+ for i, raw := range blocks {+ block, ok := raw.(map[string]interface{})+ if !ok {+ continue+ }+ switch stringValue(block["type"]) {+ case "text":+ if text := cleanUserText(stringValue(block["text"])); text != "" {+ textParts = append(textParts, text)+ }+ case "tool_result":+ if emit {+ m.emitToolResult(record, i, block)+ }+ }+ }+ if emit {+ if text := strings.TrimSpace(strings.Join(textParts, "\n")); text != "" {+ m.emitPrompt(record, text)+ }+ }+}++func (m *mapper) consumeAssistant(record Record, emit bool) {+ entry := record.Entry+ blocks, _ := entry.Message["content"].([]interface{})+ var textParts []string+ var reasoningParts []string+ for i, raw := range blocks {+ block, ok := raw.(map[string]interface{})+ if !ok {+ continue+ }+ switch stringValue(block["type"]) {+ case "text":+ if text := strings.TrimSpace(stringValue(block["text"])); text != "" {+ textParts = append(textParts, text)+ }+ case "thinking":+ if text := strings.TrimSpace(firstString(block, "thinking", "text")); text != "" {+ reasoningParts = append(reasoningParts, text)+ }+ case "tool_use":+ call := toolCall{+ ID: stringValue(block["id"]),+ Name: stringValue(block["name"]),+ Input: mapValue(block["input"]),+ }+ if call.ID != "" {+ m.tools[call.ID] = call+ }+ if emit {+ m.emitToolInvoked(record, i, call)+ }+ }+ }+ if emit {+ if text := strings.TrimSpace(strings.Join(textParts, "\n")); text != "" {+ m.emitAgentMessage(record, text)+ }+ if text := strings.TrimSpace(strings.Join(reasoningParts, "\n")); text != "" {+ m.emitAgentReasoning(record, text)+ }+ if usage := usageFromMessage(entry.Message); usage != nil {+ m.emitUsage(record, usage)+ }+ }+}++func (m *mapper) emitSessionStarted(record Record) {+ ev := m.base(record, "session.started", "session", schema.SeverityInfo, schema.FidelityObserved, "Claude Code session started")+ ev.Raw = map[string]interface{}{"claude_session": m.raw(record)}+ m.append(record, "session.started", ev)+}++func (m *mapper) emitPrompt(record Record, text string) {+ ev := m.base(record, "prompt.submitted", "prompt", schema.SeverityInfo, schema.FidelityObserved, "Prompt submitted to Claude Code")+ ev.Prompt = &schema.PromptInfo{Text: text}+ ev.Content = contentMarker(text)+ ev.GenAI = mergeGenAI(ev.GenAI, &schema.GenAIInfo{Input: &schema.GenAIInputInfo{Messages: asymptoteobserve.TextInputMessages(text)}})+ m.append(record, "prompt", ev)+}++func (m *mapper) emitAgentMessage(record Record, text string) {+ ev := m.base(record, "agent.message", "agent", schema.SeverityInfo, schema.FidelityObserved, "Claude Code assistant message")+ ev.Content = contentMarker(text)+ ev.GenAI = mergeGenAI(ev.GenAI, &schema.GenAIInfo{Output: &schema.GenAIOutputInfo{Messages: asymptoteobserve.TextOutputMessages(text)}})+ m.applyResponse(&ev, record.Entry)+ m.append(record, "agent.message", ev)+}++func (m *mapper) emitAgentReasoning(record Record, text string) {+ ev := m.base(record, "agent.reasoning", "agent", schema.SeverityInfo, schema.FidelityObserved, "Claude Code reasoning observed")+ ev.Content = contentMarker(text)+ ev.GenAI = mergeGenAI(ev.GenAI, &schema.GenAIInfo{Output: &schema.GenAIOutputInfo{Messages: asymptoteobserve.ReasoningOutputMessages(text)}})+ m.applyResponse(&ev, record.Entry)+ m.append(record, "agent.reasoning", ev)+}++func (m *mapper) emitToolInvoked(record Record, block int, call toolCall) {+ if call.Name == "" {+ return+ }+ action, category := "tool.invoked", "tool"+ ev := m.base(record, action, category, schema.SeverityInfo, schema.FidelityObserved, "Claude Code tool invocation observed")+ ev.Tool = &schema.ToolInfo{Name: call.Name}+ ev.GenAI = mergeGenAI(ev.GenAI, &schema.GenAIInfo{Tool: &schema.GenAIToolInfo{Name: call.Name, Call: &schema.GenAIToolCallInfo{ID: call.ID, Arguments: call.Input}}})+ if command := commandFromTool(call); command != "" {+ ev.Tool.Command = command+ }+ if path := pathFromTool(call); path != "" {+ ev.Tool.Path = path+ }+ if server, tool := mcpFromToolName(call.Name); server != "" || tool != "" {+ ev.Event.Action = "mcp.tool_invoked"+ ev.Event.Category = "mcp"+ ev.MCP = &schema.MCPInfo{Server: server, Tool: tool}+ }+ m.append(record, "tool.invoked."+itoa(block), ev)+}++func (m *mapper) emitToolResult(record Record, block int, result map[string]interface{}) {+ callID := stringValue(result["tool_use_id"])+ call := m.tools[callID]+ if call.ID == "" {+ call.ID = callID+ }+ content := toolResultText(result["content"])+ isError, _ := result["is_error"].(bool)+ switch {+ case isCommandTool(call):+ ev := m.base(record, "command.executed", "command", severityForError(isError), schema.FidelityObserved, "Claude Code command completed")+ ev.Command = &schema.CommandInfo{Command: commandFromTool(call), Output: content}+ ev.Tool = &schema.ToolInfo{Name: call.Name, Command: commandFromTool(call)}+ ev.GenAI = toolResultGenAI(call, content)+ m.append(record, "tool.result."+itoa(block), ev)+ case isFileTool(call):+ ev := m.base(record, fileAction(call), "file", severityForError(isError), schema.FidelityObserved, "Claude Code file activity observed")+ ev.File = &schema.FileInfo{Path: pathFromTool(call), Operation: fileOperation(call), Language: languageForPath(pathFromTool(call))}+ ev.Tool = &schema.ToolInfo{Name: call.Name, Path: pathFromTool(call)}+ ev.GenAI = toolResultGenAI(call, content)+ m.append(record, "tool.result."+itoa(block), ev)+ default:+ action := "tool.completed"+ if isError {+ action = "tool.failed"+ }+ ev := m.base(record, action, "tool", severityForError(isError), schema.FidelityObserved, "Claude Code tool completed")+ ev.Tool = &schema.ToolInfo{Name: call.Name}+ ev.GenAI = toolResultGenAI(call, content)+ m.append(record, "tool.result."+itoa(block), ev)+ }+}++func (m *mapper) emitUsage(record Record, usage *schema.GenAIUsageInfo) {+ ev := m.base(record, "token.usage", "metric", schema.SeverityInfo, schema.FidelityObserved, "Claude Code token usage observed")+ ev.GenAI = mergeGenAI(ev.GenAI, &schema.GenAIInfo{Usage: usage})+ m.applyResponse(&ev, record.Entry)+ m.append(record, "usage", ev)+}++func (m *mapper) emitSummary(record Record) {+ summary := firstString(record.Entry.Message, "summary", "content")+ if summary == "" {+ return+ }+ ev := m.base(record, "session.summary", "session", schema.SeverityInfo, schema.FidelityObserved, "Claude Code session summary observed")+ ev.Content = contentMarker(summary)+ ev.Raw = map[string]interface{}{"claude_session": map[string]interface{}{"summary": summary}}+ m.append(record, "summary", ev)+}++func (m *mapper) base(record Record, action, category string, severity schema.Severity, fidelity, message string) schema.Event {+ entry := record.Entry+ ev := schema.NewEvent(schema.NewEventOptions{+ Action: action,+ Category: category,+ Severity: severity,+ Fidelity: fidelity,+ Message: message,+ Origin: schema.OriginLocal,+ Harness: schema.HarnessInfo{Name: Harness, CollectionMethod: schema.CollectionMethodPoll},+ })+ if ts := parseTimestamp(entry.Timestamp); ts != "" {+ ev.Timestamp = ts+ }+ sessionID := entry.SessionID+ if sessionID == "" {+ sessionID = m.ref.ID+ }+ workspace := entry.CWD+ if workspace == "" {+ workspace = m.ref.ProjectPath+ }+ ev.Session = &schema.SessionInfo{ID: sessionID, WorkingDirectory: workspace}+ if workspace != "" {+ ev.Repository = workspace+ }+ if branch := firstNonEmpty(entry.GitBranch, indexBranch(m.ref)); branch != "" {+ ev.Branch = branch+ }+ if model := stringValue(entry.Message["model"]); model != "" {+ ev.Model = asymptoteobserve.NormalizeModelName(model)+ }+ if entry.IsSidechain || m.ref.IsSidechain {+ ev.GenAI = mergeGenAI(ev.GenAI, &schema.GenAIInfo{Agent: m.agentInfo(entry)})+ }+ return ev+}++func (m *mapper) append(record Record, suffix string, ev schema.Event) {+ coordinate := firstNonEmpty(record.Entry.UUID, m.ref.Path+":"+itoa(record.Line)) + ":" + suffix+ ev.Event.ID = claudeEventID(coordinate)+ m.out = append(m.out, MappedEvent{DedupID: ev.Event.ID, SourceLine: record.Line, Event: ev})+}++func (m *mapper) raw(record Record) map[string]interface{} {+ raw := map[string]interface{}{+ "source_path": recordSourcePath(m.ref),+ "line": record.Line,+ "version": record.Entry.Version,+ "entrypoint": record.Entry.Entrypoint,+ "user_type": record.Entry.UserType,+ "is_sidechain": record.Entry.IsSidechain || m.ref.IsSidechain,+ }+ if m.ref.ParentSessionID != "" {+ raw["parent_session_id"] = m.ref.ParentSessionID+ }+ return raw+}++func (m *mapper) agentInfo(entry Entry) *schema.GenAIAgentInfo {+ agent := &schema.GenAIAgentInfo{ID: firstNonEmpty(entry.AgentID, m.ref.ID)}+ if m.ref.Meta != nil {+ agent.Name = m.ref.Meta.AgentType+ agent.Description = m.ref.Meta.Description+ }+ if entry.AttributionAgent != "" && agent.Name == "" {+ agent.Name = entry.AttributionAgent+ }+ return agent+}++func (m *mapper) applyResponse(ev *schema.Event, entry Entry) {+ if ev.GenAI == nil {+ ev.GenAI = &schema.GenAIInfo{}+ }+ if id := stringValue(entry.Message["id"]); id != "" {+ ev.GenAI.Response = &schema.GenAIResponseInfo{ID: id, Model: stringValue(entry.Message["model"])}+ }+}++func contentMarker(text string) *schema.ContentInfo {+ return asymptoteobserve.RetainedContent(text, asymptoteobserve.DefaultRawStringLimit)+}++func usageFromMessage(message map[string]interface{}) *schema.GenAIUsageInfo {+ raw := mapValue(message["usage"])+ if len(raw) == 0 {+ return nil+ }+ usage := &schema.GenAIUsageInfo{}+ if v, ok := int64Value(raw["input_tokens"]); ok {+ usage.InputTokens = &v+ }+ if v, ok := int64Value(raw["output_tokens"]); ok {+ usage.OutputTokens = &v+ }+ if v, ok := int64Value(firstValue(raw, "cache_creation_input_tokens", "cache_creation_tokens")); ok {+ usage.CacheCreation = &schema.GenAIUsageCacheCreationInfo{InputTokens: &v}+ }+ if v, ok := int64Value(firstValue(raw, "cache_read_input_tokens", "cache_read_tokens")); ok {+ usage.CacheRead = &schema.GenAIUsageCacheReadInfo{InputTokens: &v}+ }+ if v, ok := int64Value(firstValue(raw, "reasoning_output_tokens")); ok {+ usage.Reasoning = &schema.GenAIUsageReasoningInfo{OutputTokens: &v}+ }+ if usage.InputTokens == nil && usage.OutputTokens == nil && usage.CacheCreation == nil && usage.CacheRead == nil && usage.Reasoning == nil {+ return nil+ }+ return usage+}++func toolResultGenAI(call toolCall, result string) *schema.GenAIInfo {+ return &schema.GenAIInfo{Tool: &schema.GenAIToolInfo{Name: call.Name, Call: &schema.GenAIToolCallInfo{ID: call.ID, Arguments: call.Input, Result: result}}}+}++func mergeGenAI(base, next *schema.GenAIInfo) *schema.GenAIInfo {+ if base == nil {+ return next+ }+ if next == nil {+ return base+ }+ if next.Agent != nil {+ base.Agent = next.Agent+ }+ if next.Input != nil {+ base.Input = next.Input+ }+ if next.Output != nil {+ base.Output = next.Output+ }+ if next.Response != nil {+ base.Response = next.Response+ }+ if next.Tool != nil {+ base.Tool = next.Tool+ }+ if next.Usage != nil {+ base.Usage = next.Usage+ }+ return base+}++func parseTimestamp(value string) string {+ if strings.TrimSpace(value) == "" {+ return ""+ }+ if ts, err := time.Parse(time.RFC3339Nano, value); err == nil {+ return schema.FormatTimestamp(ts.UTC())+ }+ return ""+}++func cleanUserText(text string) string {+ text = strings.TrimSpace(text)+ if strings.Contains(text, "<local-command-caveat>") || strings.Contains(text, "<command-name>") {+ return ""+ }+ return text+}++func toolResultText(value interface{}) string {+ switch v := value.(type) {+ case string:+ return v+ case []interface{}:+ var parts []string+ for _, raw := range v {+ block, ok := raw.(map[string]interface{})+ if !ok {+ continue+ }+ if text := firstString(block, "text", "content"); text != "" {+ parts = append(parts, text)+ }+ }+ return strings.TrimSpace(strings.Join(parts, "\n"))+ default:+ if value == nil {+ return ""+ }+ data, _ := json.Marshal(value)+ return string(data)+ }+}++func isCommandTool(call toolCall) bool {+ switch strings.ToLower(call.Name) {+ case "bash", "shell", "terminal":+ return true+ default:+ return false+ }+}++func isFileTool(call toolCall) bool {+ switch strings.ToLower(call.Name) {+ case "read", "write", "edit", "multiedit", "notebookread", "notebookedit":+ return pathFromTool(call) != ""+ default:+ return false+ }+}++func commandFromTool(call toolCall) string {+ return firstString(call.Input, "command", "cmd", "shell_command")+}++func pathFromTool(call toolCall) string {+ return firstString(call.Input, "file_path", "filePath", "path", "notebook_path")+}++func fileAction(call toolCall) string {+ if strings.EqualFold(call.Name, "Read") || strings.EqualFold(call.Name, "NotebookRead") {+ return "file.read"+ }+ return "file.modified"+}++func fileOperation(call toolCall) string {+ switch strings.ToLower(call.Name) {+ case "read", "notebookread":+ return "read"+ case "write":+ return "create"+ default:+ return "modify"+ }+}++func languageForPath(path string) string {+ ext := strings.TrimPrefix(filepath.Ext(path), ".")+ return ext+}++func severityForError(isError bool) schema.Severity {+ if isError {+ return schema.SeverityMedium+ }+ return schema.SeverityInfo+}++func mcpFromToolName(name string) (string, string) {+ if !strings.HasPrefix(name, "mcp__") {+ return "", ""+ }+ rest := strings.TrimPrefix(name, "mcp__")+ if server, tool, ok := strings.Cut(rest, "__"); ok {+ return server, tool+ }+ server, tool, ok := strings.Cut(rest, "_")+ if !ok {+ return "", ""+ }+ return server, tool+}++func recordSourcePath(ref SessionRef) string {+ if ref.Path == "" {+ return ""+ }+ return ref.Path+}++func indexBranch(ref SessionRef) string {+ if ref.Index == nil {+ return ""+ }+ return ref.Index.GitBranch+}++func mapValue(value interface{}) map[string]interface{} {+ if value == nil {+ return nil+ }+ if m, ok := value.(map[string]interface{}); ok {+ return m+ }+ return nil+}++func stringValue(value interface{}) string {+ if s, ok := value.(string); ok {+ return s+ }+ return ""+}++func firstString(m map[string]interface{}, keys ...string) string {+ for _, key := range keys {+ if value := stringValue(m[key]); value != "" {+ return value+ }+ }+ return ""+}++func firstValue(m map[string]interface{}, keys ...string) interface{} {+ for _, key := range keys {+ if value, ok := m[key]; ok {+ return value+ }+ }+ return nil+}++func firstNonEmpty(values ...string) string {+ for _, value := range values {+ if strings.TrimSpace(value) != "" {+ return value+ }+ }+ return ""+}++func int64Value(value interface{}) (int64, bool) {+ switch v := value.(type) {+ case int64:+ return v, true+ case int:+ return int64(v), true+ case float64:+ return int64(v), true+ case json.Number:+ n, err := v.Int64()+ return n, err == nil+ default:+ return 0, false+ }+}++func itoa(n int) string {+ if n == 0 {+ return "0"+ }+ var buf [20]byte+ i := len(buf)+ neg := n < 0+ if neg {+ n = -n+ }+ for n > 0 {+ i--+ buf[i] = byte('0' + n%10)+ n /= 10+ }+ if neg {+ i--+ buf[i] = '-'+ }+ return string(buf[i:])+}++var claudeIDNamespace = [16]byte{+ 0x61, 0x2f, 0x2d, 0x8a, 0x09, 0x9f, 0x44, 0x6a,+ 0x93, 0x31, 0x86, 0x17, 0x55, 0x28, 0xcd, 0x42,+}++func claudeEventID(dedupID string) string {+ digest := sha1.New()+ digest.Write(claudeIDNamespace[:])+ io.WriteString(digest, dedupID)+ var id [16]byte+ copy(id[:], digest.Sum(nil))+ id[6] = (id[6] & 0x0f) | 0x50+ id[8] = (id[8] & 0x3f) | 0x80+ out := make([]byte, 32)+ hex.Encode(out, id[:])+ return fmt.Sprintf("%s-%s-%s-%s-%s", out[0:8], out[8:12], out[12:16], out[16:20], out[20:32])+}diff --git a/cli/beacon/internal/claudesession/store.go b/cli/beacon/internal/claudesession/store.gonew file mode 100644index 00000000..a2d2e3b6--- /dev/null+++ b/cli/beacon/internal/claudesession/store.go@@ -0,0 +1,224 @@+package claudesession++import (+ "bufio"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "io/fs"+ "os"+ "path/filepath"+ "sort"+ "strings"+)++const (+ MaxLineBytes = 8 * 1024 * 1024+)++type SessionRef struct {+ ID string+ Path string+ ProjectDir string+ ProjectPath string+ ModTimeUnixMS int64+ SizeBytes int64+ IsSidechain bool+ ParentSessionID string+ Meta *SubagentMeta+ Index *IndexEntry+}++type Store struct {+ ProjectsDir string+}++type Stats struct {+ Lines int+ Decoded int+ Malformed int+ PartialTail bool+ FirstError error+}++func DefaultProjectsDir() (string, error) {+ home, err := os.UserHomeDir()+ if err != nil {+ return "", fmt.Errorf("resolve home directory: %w", err)+ }+ if strings.TrimSpace(home) == "" {+ return "", errors.New("home directory is empty")+ }+ return filepath.Join(home, ".claude", "projects"), nil+}++func NewStore(dir string) (*Store, error) {+ if strings.TrimSpace(dir) != "" {+ return &Store{ProjectsDir: dir}, nil+ }+ def, err := DefaultProjectsDir()+ if err != nil {+ return nil, err+ }+ return &Store{ProjectsDir: def}, nil+}++func (s *Store) Exists() bool {+ info, err := os.Stat(s.ProjectsDir)+ return err == nil && info.IsDir()+}++func (s *Store) List() ([]SessionRef, error) {+ entries, err := os.ReadDir(s.ProjectsDir)+ if err != nil {+ if errors.Is(err, fs.ErrNotExist) {+ return nil, nil+ }+ return nil, fmt.Errorf("read Claude projects directory: %w", err)+ }++ var refs []SessionRef+ for _, entry := range entries {+ if !entry.IsDir() {+ continue+ }+ projectDir := filepath.Join(s.ProjectsDir, entry.Name())+ index := readIndex(projectDir)+ if err := filepath.WalkDir(projectDir, func(path string, d fs.DirEntry, walkErr error) error {+ if walkErr != nil {+ return nil+ }+ if d.IsDir() {+ return nil+ }+ if filepath.Ext(path) != ".jsonl" {+ return nil+ }+ info, err := d.Info()+ if err != nil || info.IsDir() {+ return nil+ }+ ref := SessionRef{+ ID: strings.TrimSuffix(filepath.Base(path), ".jsonl"),+ Path: path,+ ProjectDir: projectDir,+ ProjectPath: projectPathFromDir(projectDir),+ ModTimeUnixMS: info.ModTime().UnixMilli(),+ SizeBytes: info.Size(),+ }+ if idx := index[path]; idx != nil {+ ref.Index = idx+ if idx.ProjectPath != "" {+ ref.ProjectPath = idx.ProjectPath+ }+ if idx.SessionID != "" {+ ref.ID = idx.SessionID+ }+ ref.IsSidechain = idx.IsSidechain+ }+ if filepath.Base(filepath.Dir(path)) == "subagents" {+ ref.IsSidechain = true+ ref.ParentSessionID = filepath.Base(filepath.Dir(filepath.Dir(path)))+ ref.Meta = readSubagentMeta(strings.TrimSuffix(path, ".jsonl") + ".meta.json")+ }+ refs = append(refs, ref)+ return nil+ }); err != nil {+ return nil, err+ }+ }+ sort.SliceStable(refs, func(i, j int) bool {+ if refs[i].ModTimeUnixMS != refs[j].ModTimeUnixMS {+ return refs[i].ModTimeUnixMS < refs[j].ModTimeUnixMS+ }+ return refs[i].Path < refs[j].Path+ })+ return refs, nil+}++func (s *Store) Read(ref SessionRef) ([]Record, Stats, error) {+ f, err := os.Open(ref.Path)+ if err != nil {+ return nil, Stats{}, err+ }+ defer f.Close()+ return decodeRecords(f)+}++func decodeRecords(r io.Reader) ([]Record, Stats, error) {+ scanner := bufio.NewScanner(r)+ scanner.Buffer(make([]byte, 0, 64*1024), MaxLineBytes)+ var records []Record+ var stats Stats+ lineNo := 0+ for scanner.Scan() {+ lineNo+++ stats.Lines = lineNo+ line := scanner.Bytes()+ if len(strings.TrimSpace(string(line))) == 0 {+ continue+ }+ entry, err := decodeEntry(line)+ if err != nil {+ stats.Malformed+++ if stats.FirstError == nil {+ stats.FirstError = err+ }+ continue+ }+ stats.Decoded+++ records = append(records, Record{Line: lineNo, Entry: *entry})+ }+ if err := scanner.Err(); err != nil {+ if errors.Is(err, bufio.ErrTooLong) {+ stats.Malformed+++ if stats.FirstError == nil {+ stats.FirstError = fmt.Errorf("claude session line exceeds %d bytes", MaxLineBytes)+ }+ return records, stats, nil+ }+ return records, stats, err+ }+ return records, stats, nil+}++func readIndex(projectDir string) map[string]*IndexEntry {+ data, err := os.ReadFile(filepath.Join(projectDir, "sessions-index.json"))+ if err != nil {+ return nil+ }+ var index SessionIndex+ if err := json.Unmarshal(data, &index); err != nil {+ return nil+ }+ out := make(map[string]*IndexEntry, len(index.Entries))+ for i := range index.Entries {+ entry := index.Entries[i]+ if entry.FullPath == "" {+ continue+ }+ out[entry.FullPath] = &entry+ }+ return out+}++func readSubagentMeta(path string) *SubagentMeta {+ data, err := os.ReadFile(path)+ if err != nil {+ return nil+ }+ var meta SubagentMeta+ if err := json.Unmarshal(data, &meta); err != nil {+ return nil+ }+ return &meta+}++func projectPathFromDir(projectDir string) string {+ base := filepath.Base(projectDir)+ if !strings.HasPrefix(base, "-") {+ return ""+ }+ return string(filepath.Separator) + strings.ReplaceAll(strings.TrimPrefix(base, "-"), "-", string(filepath.Separator))+}diff --git a/cli/beacon/internal/claudesession/types.go b/cli/beacon/internal/claudesession/types.gonew file mode 100644index 00000000..9bfad28a--- /dev/null+++ b/cli/beacon/internal/claudesession/types.go@@ -0,0 +1,79 @@+// Package claudesession reads Claude Code's local session transcripts and turns them into+// Beacon endpoint telemetry.+//+// This is an after-the-fact collection path. Claude has already committed the JSONL row before+// Beacon sees it, so every mapped event carries harness.collection_method=poll. That is+// deliberately different from the Claude hook adapter, which observes hooks as they fire and can+// participate in the optional policy seam.+package claudesession++import (+ "encoding/json"+ "fmt"+)++const Harness = "claude_code"++type Entry struct {+ ParentUUID string `json:"parentUuid,omitempty"`+ IsSidechain bool `json:"isSidechain,omitempty"`+ PromptID string `json:"promptId,omitempty"`+ Type string `json:"type"`+ Subtype string `json:"subtype,omitempty"`+ UUID string `json:"uuid,omitempty"`+ Timestamp string `json:"timestamp,omitempty"`+ UserType string `json:"userType,omitempty"`+ Entrypoint string `json:"entrypoint,omitempty"`+ CWD string `json:"cwd,omitempty"`+ SessionID string `json:"sessionId,omitempty"`+ Version string `json:"version,omitempty"`+ GitBranch string `json:"gitBranch,omitempty"`+ IsMeta bool `json:"isMeta,omitempty"`+ Message map[string]interface{} `json:"message,omitempty"`+ Attachment map[string]interface{} `json:"attachment,omitempty"`+ RequestID string `json:"requestId,omitempty"`+ AttributionAgent string `json:"attributionAgent,omitempty"`+ AgentID string `json:"agentId,omitempty"`+}++type Record struct {+ Line int+ Entry Entry+}++type SubagentMeta struct {+ AgentType string `json:"agentType,omitempty"`+ Description string `json:"description,omitempty"`+ ToolUseID string `json:"toolUseId,omitempty"`+}++type SessionIndex struct {+ Version int `json:"version"`+ Entries []IndexEntry `json:"entries"`+ OriginalPath string `json:"originalPath"`+}++type IndexEntry struct {+ SessionID string `json:"sessionId"`+ FullPath string `json:"fullPath"`+ FileMtime int64 `json:"fileMtime"`+ FirstPrompt string `json:"firstPrompt"`+ Summary string `json:"summary"`+ MessageCount int `json:"messageCount"`+ Created string `json:"created"`+ Modified string `json:"modified"`+ GitBranch string `json:"gitBranch"`+ ProjectPath string `json:"projectPath"`+ IsSidechain bool `json:"isSidechain"`+}++func decodeEntry(line []byte) (*Entry, error) {+ var entry Entry+ if err := json.Unmarshal(line, &entry); err != nil {+ return nil, fmt.Errorf("claude session entry: %w", err)+ }+ if entry.Type == "" {+ return nil, fmt.Errorf("claude session entry: missing type")+ }+ return &entry, nil+}