Skip to content

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

add hermes session sync

Justin D'Souza3e973f6371e6
diff --git a/cli/beacon/cmd/endpoint_hermes.go b/cli/beacon/cmd/endpoint_hermes.go
new file mode 100644
index 00000000..69099ad6
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_hermes.go
@@ -0,0 +1,224 @@
+package cmd
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/hermessession"
+ "github.com/spf13/cobra"
+)
+
+// `beacon endpoint hermes` complements the live Hermes hook integration.
+//
+// Hermes also keeps committed session history in ~/.hermes/state.db. Reading that store is a local,
+// offline poll path: useful for backfill and transcript coverage, but unable to approve, deny, or
+// delay tool calls. Live hooks remain the real-time path.
+var endpointHermesCmd = &cobra.Command{
+ Use: "hermes",
+ Short: "Collect telemetry from Hermes Agent sessions",
+ Long: `Collect endpoint telemetry from Hermes Agent's local session database.
+
+Hermes hooks remain the real-time integration. This command reads the committed
+SQLite session store at ~/.hermes/state.db and converts historical or missed rows
+into endpoint events marked harness.collection_method=poll.`,
+}
+
+var endpointHermesSyncCmd = &cobra.Command{
+ Use: "sync",
+ Short: "Read new Hermes session rows into the runtime log",
+ SilenceUsage: true,
+ RunE: runEndpointHermesSync,
+}
+
+var endpointHermesStatusCmd = &cobra.Command{
+ Use: "status",
+ Short: "Show Hermes sessions on this machine and how much has been collected",
+ SilenceUsage: true,
+ RunE: runEndpointHermesStatus,
+}
+
+var endpointHermesOpts struct {
+ dbPath string
+ statePath string
+ logPath string
+ print bool
+ watch bool
+ interval time.Duration
+}
+
+func init() {
+ endpointCmd.AddCommand(endpointHermesCmd)
+ endpointHermesCmd.AddCommand(endpointHermesSyncCmd)
+ endpointHermesCmd.AddCommand(endpointHermesStatusCmd)
+
+ for _, c := range []*cobra.Command{endpointHermesSyncCmd, endpointHermesStatusCmd} {
+ f := c.Flags()
+ f.StringVar(&endpointHermesOpts.dbPath, "db", "", "Hermes state database (default ~/.hermes/state.db)")
+ f.StringVar(&endpointHermesOpts.statePath, "state", "", "Collector cursor file (default ~/.beacon/endpoint/state/hermes.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 := endpointHermesSyncCmd.Flags()
+ sync.StringVar(&endpointHermesOpts.logPath, "log-path", "", "Runtime JSONL log path (default resolved endpoint log)")
+ sync.BoolVar(&endpointHermesOpts.print, "print", false, "Print mapped events as JSON without writing them or advancing the cursor (dry run)")
+ sync.BoolVar(&endpointHermesOpts.watch, "watch", false, "Sweep continuously on --interval (default: one sweep then exit)")
+ sync.DurationVar(&endpointHermesOpts.interval, "interval", time.Minute, "Sweep interval for --watch")
+}
+
+func runEndpointHermesSync(cmd *cobra.Command, args []string) error {
+ userMode := endpointUserMode()
+ opts := hermessession.CollectOptions{
+ DBPath: endpointHermesOpts.dbPath,
+ Print: endpointHermesOpts.print,
+ Out: cmd.OutOrStdout(),
+ Write: !endpointHermesOpts.print,
+ UserMode: userMode,
+ }
+ if !endpointHermesOpts.print {
+ opts.StatePath = resolveHermesStatePath(endpointHermesOpts.statePath)
+ opts.LogPath = lifecycle.ResolveRuntimeLog(userMode, endpointHermesOpts.logPath).EffectiveLogPath
+ }
+
+ ctx := cmd.Context()
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ if endpointHermesOpts.watch && !endpointHermesOpts.print {
+ return watchHermes(ctx, cmd, opts)
+ }
+ summary, err := hermessession.CollectOnce(opts)
+ reportHermesSweep(cmd, summary)
+ return err
+}
+
+func watchHermes(ctx context.Context, cmd *cobra.Command, opts hermessession.CollectOptions) error {
+ interval := endpointHermesOpts.interval
+ if interval < 5*time.Second {
+ interval = 5 * time.Second
+ }
+ for {
+ summary, err := hermessession.CollectOnce(opts)
+ if err != nil {
+ fmt.Fprintf(cmd.ErrOrStderr(), "Hermes sync error: %v\n", err)
+ }
+ reportHermesSweep(cmd, summary)
+ select {
+ case <-ctx.Done():
+ return nil
+ case <-time.After(interval):
+ }
+ }
+}
+
+func reportHermesSweep(cmd *cobra.Command, summary hermessession.Summary) {
+ if endpointHermesOpts.print {
+ return
+ }
+ if endpointOpts.jsonOutput {
+ _ = json.NewEncoder(cmd.OutOrStdout()).Encode(summary)
+ return
+ }
+ fmt.Fprintf(cmd.OutOrStdout(), "Hermes sync: %d sessions, %d changed, %d events, %d errors\n",
+ summary.Sessions, summary.SessionsChanged, summary.EventsEmitted, summary.Errors)
+}
+
+type hermesSessionStatus struct {
+ SessionID string `json:"session_id"`
+ Title string `json:"title,omitempty"`
+ WorkingDirectory string `json:"working_directory,omitempty"`
+ StartedAt string `json:"started_at,omitempty"`
+ EndedAt string `json:"ended_at,omitempty"`
+ LastMessageID int64 `json:"last_message_id"`
+ CollectedMessageID int64 `json:"collected_message_id"`
+ Collected bool `json:"collected"`
+}
+
+type hermesStatusReport struct {
+ DBPath string `json:"db_path"`
+ Present bool `json:"present"`
+ StatePath string `json:"state_path,omitempty"`
+ Sessions []hermesSessionStatus `json:"sessions"`
+}
+
+func runEndpointHermesStatus(cmd *cobra.Command, args []string) error {
+ dbPath := endpointHermesOpts.dbPath
+ if dbPath == "" {
+ dbPath = hermessession.DefaultDBPath()
+ }
+ statePath := resolveHermesStatePath(endpointHermesOpts.statePath)
+ report := hermesStatusReport{DBPath: dbPath, StatePath: statePath}
+
+ store, err := hermessession.OpenStore(dbPath)
+ if err != nil {
+ if endpointOpts.jsonOutput {
+ _ = json.NewEncoder(cmd.OutOrStdout()).Encode(report)
+ return nil
+ }
+ fmt.Fprintf(cmd.OutOrStdout(), "Hermes state database not found or unreadable: %s\n", dbPath)
+ return nil
+ }
+ defer store.Close()
+ report.Present = true
+
+ state, err := hermessession.LoadState(statePath)
+ if err != nil {
+ return err
+ }
+ sessions, err := store.ListSessions()
+ if err != nil {
+ return err
+ }
+ for _, session := range sessions {
+ lastID, err := store.LastMessageID(session.ID)
+ if err != nil {
+ return err
+ }
+ status := hermesSessionStatus{
+ SessionID: session.ID,
+ Title: session.Title,
+ WorkingDirectory: session.CWD,
+ LastMessageID: lastID,
+ }
+ if session.StartedAtMS > 0 {
+ status.StartedAt = time.UnixMilli(session.StartedAtMS).UTC().Format(time.RFC3339)
+ }
+ if session.EndedAtMS > 0 {
+ status.EndedAt = time.UnixMilli(session.EndedAtMS).UTC().Format(time.RFC3339)
+ }
+ if cursor := state.Sessions[session.ID]; cursor != nil {
+ status.CollectedMessageID = cursor.LastMessageID
+ status.Collected = cursor.Started && cursor.LastMessageID >= lastID && (session.EndedAtMS == 0 || cursor.EndedAtMS == session.EndedAtMS)
+ }
+ report.Sessions = append(report.Sessions, status)
+ }
+ if endpointOpts.jsonOutput {
+ return json.NewEncoder(cmd.OutOrStdout()).Encode(report)
+ }
+ fmt.Fprintf(cmd.OutOrStdout(), "Hermes state database: %s\n", report.DBPath)
+ fmt.Fprintf(cmd.OutOrStdout(), "Collector state: %s\n", report.StatePath)
+ if len(report.Sessions) == 0 {
+ fmt.Fprintln(cmd.OutOrStdout(), "No Hermes sessions found.")
+ return nil
+ }
+ for _, session := range report.Sessions {
+ mark := "pending"
+ if session.Collected {
+ mark = "collected"
+ }
+ fmt.Fprintf(cmd.OutOrStdout(), "- %s [%s] messages %d/%d %s\n",
+ session.SessionID, mark, session.CollectedMessageID, session.LastMessageID, session.Title)
+ }
+ return nil
+}
+
+func resolveHermesStatePath(path string) string {
+ if path != "" {
+ return path
+ }
+ return hermessession.DefaultStatePath()
+}
diff --git a/cli/beacon/internal/hermessession/collect.go b/cli/beacon/internal/hermessession/collect.go
new file mode 100644
index 00000000..f082be18
--- /dev/null
+++ b/cli/beacon/internal/hermessession/collect.go
@@ -0,0 +1,928 @@
+package hermessession
+
+import (
+ "crypto/sha1"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+ _ "modernc.org/sqlite"
+)
+
+const (
+ Harness = "hermes"
+ StateVersion = 1
+)
+
+type Cursor struct {
+ LastMessageID int64 `json:"last_message_id"`
+ Started bool `json:"started"`
+ EndedAtMS int64 `json:"ended_at_ms,omitempty"`
+ InputTokens int64 `json:"input_tokens,omitempty"`
+ OutputTokens int64 `json:"output_tokens,omitempty"`
+ CacheReadTokens int64 `json:"cache_read_tokens,omitempty"`
+ CacheWriteTokens int64 `json:"cache_write_tokens,omitempty"`
+ ReasoningTokens int64 `json:"reasoning_tokens,omitempty"`
+ CostUSD float64 `json:"cost_usd,omitempty"`
+}
+
+type State struct {
+ Version int `json:"version"`
+ Sessions map[string]*Cursor `json:"sessions"`
+}
+
+type CollectOptions struct {
+ DBPath 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"`
+}
+
+type Session struct {
+ ID string
+ Source string
+ Model string
+ CWD string
+ Title string
+ ParentSessionID string
+ StartedAtMS int64
+ EndedAtMS int64
+ EndReason string
+ MessageCount int64
+ ToolCallCount int64
+ InputTokens int64
+ OutputTokens int64
+ CacheReadTokens int64
+ CacheWriteTokens int64
+ ReasoningTokens int64
+ EstimatedCostUSD float64
+ ActualCostUSD float64
+ CostStatus string
+ CostSource string
+}
+
+type Message struct {
+ ID int64
+ SessionID string
+ Role string
+ Content string
+ ToolCallID string
+ ToolCalls string
+ ToolName string
+ TimestampMS int64
+ TokenCount int64
+ FinishReason string
+ Reasoning string
+ ReasoningContent string
+ ReasoningDetails string
+ PlatformMessageID string
+ Observed bool
+ Active bool
+}
+
+type MappedEvent struct {
+ SourceMessageID int64
+ Event schema.Event
+}
+
+func DefaultDBPath() string {
+ if home, err := os.UserHomeDir(); err == nil && strings.TrimSpace(home) != "" {
+ return filepath.Join(home, ".hermes", "state.db")
+ }
+ return filepath.Join(os.TempDir(), "hermes", "state.db")
+}
+
+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", "hermes.json")
+}
+
+func LoadState(path string) (*State, error) {
+ state := &State{Version: StateVersion, Sessions: 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 Hermes collector state %s: %w", path, err)
+ }
+ if stored.Version != StateVersion || stored.Sessions == nil {
+ return state, nil
+ }
+ state.Sessions = stored.Sessions
+ 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(sessionID string) *Cursor {
+ if s.Sessions == nil {
+ s.Sessions = map[string]*Cursor{}
+ }
+ cursor := s.Sessions[sessionID]
+ if cursor == nil {
+ cursor = &Cursor{}
+ s.Sessions[sessionID] = cursor
+ }
+ return cursor
+}
+
+func CollectOnce(opts CollectOptions) (summary Summary, err error) {
+ dbPath := opts.DBPath
+ if dbPath == "" {
+ dbPath = DefaultDBPath()
+ }
+ if _, statErr := os.Stat(dbPath); statErr != nil {
+ if os.IsNotExist(statErr) {
+ return summary, nil
+ }
+ return summary, statErr
+ }
+ store, err := OpenStore(dbPath)
+ if err != nil {
+ return summary, err
+ }
+ defer store.Close()
+ sessions, err := store.ListSessions()
+ if err != nil {
+ return summary, err
+ }
+ summary.Sessions = len(sessions)
+ 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 Hermes collector state: %w", saveErr)
+ }
+ }()
+ var errs []error
+ for _, session := range sessions {
+ changed, collectErr := collectSession(store, session, state, opts, &summary)
+ if collectErr != nil {
+ summary.Errors++
+ errs = append(errs, fmt.Errorf("Hermes session %s: %w", session.ID, collectErr))
+ continue
+ }
+ if changed {
+ summary.SessionsChanged++
+ }
+ }
+ if len(errs) > 0 {
+ return summary, errors.Join(errs...)
+ }
+ return summary, nil
+}
+
+func collectSession(store *Store, session Session, state *State, opts CollectOptions, summary *Summary) (bool, error) {
+ cursor := state.cursor(session.ID)
+ messages, err := store.ReadMessages(session.ID, cursor.LastMessageID)
+ if err != nil {
+ return false, err
+ }
+ mapped := MapSession(session, messages, cursor)
+ if len(mapped) == 0 {
+ advanceCursorMessages(cursor, messages)
+ updateCursorTotals(cursor, session)
+ return false, nil
+ }
+ for _, item := range mapped {
+ if err := emit(item.Event, opts); err != nil {
+ return true, err
+ }
+ summary.EventsEmitted++
+ if item.SourceMessageID > cursor.LastMessageID {
+ cursor.LastMessageID = item.SourceMessageID
+ }
+ switch item.Event.Event.Action {
+ case "session.started":
+ cursor.Started = true
+ case "session.ended":
+ cursor.EndedAtMS = session.EndedAtMS
+ case "token.usage":
+ updateCursorTotals(cursor, session)
+ }
+ }
+ advanceCursorMessages(cursor, messages)
+ updateCursorTotals(cursor, session)
+ return true, nil
+}
+
+func advanceCursorMessages(cursor *Cursor, messages []Message) {
+ for _, message := range messages {
+ if message.ID > cursor.LastMessageID {
+ cursor.LastMessageID = message.ID
+ }
+ }
+}
+
+func updateCursorTotals(cursor *Cursor, session Session) {
+ if session.InputTokens > cursor.InputTokens {
+ cursor.InputTokens = session.InputTokens
+ }
+ if session.OutputTokens > cursor.OutputTokens {
+ cursor.OutputTokens = session.OutputTokens
+ }
+ if session.CacheReadTokens > cursor.CacheReadTokens {
+ cursor.CacheReadTokens = session.CacheReadTokens
+ }
+ if session.CacheWriteTokens > cursor.CacheWriteTokens {
+ cursor.CacheWriteTokens = session.CacheWriteTokens
+ }
+ if session.ReasoningTokens > cursor.ReasoningTokens {
+ cursor.ReasoningTokens = session.ReasoningTokens
+ }
+ if cost := sessionCost(session); cost > cursor.CostUSD {
+ cursor.CostUSD = cost
+ }
+ if session.EndedAtMS > 0 && cursor.EndedAtMS == 0 {
+ cursor.EndedAtMS = session.EndedAtMS
+ }
+}
+
+func emit(event schema.Event, opts CollectOptions) error {
+ if opts.Print && opts.Out != nil {
+ data, err := json.Marshal(event)
+ if err != nil {
+ return err
+ }
+ if _, err := opts.Out.Write(append(data, '\n')); err != nil {
+ return err
+ }
+ }
+ if opts.Write {
+ if _, err := writer.AppendEvent(event, writer.Options{Path: opts.LogPath, UserMode: opts.UserMode}); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+type Store struct {
+ path string
+ db *sql.DB
+}
+
+func OpenStore(path string) (*Store, error) {
+ db, err := openSQLiteReadOnly(path)
+ if err != nil {
+ return nil, err
+ }
+ if err := db.Ping(); err != nil {
+ _ = db.Close()
+ return nil, err
+ }
+ return &Store{path: path, db: db}, nil
+}
+
+func (s *Store) Close() error { return s.db.Close() }
+
+func (s *Store) Path() string { return s.path }
+
+func (s *Store) ListSessions() ([]Session, error) {
+ rows, err := s.db.Query(`
+SELECT id, source, model, cwd, title, parent_session_id, started_at, ended_at, end_reason,
+ message_count, tool_call_count, input_tokens, output_tokens, cache_read_tokens,
+ cache_write_tokens, reasoning_tokens, estimated_cost_usd, actual_cost_usd,
+ cost_status, cost_source
+FROM sessions
+WHERE archived = 0
+ORDER BY started_at, id`)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []Session
+ for rows.Next() {
+ var s Session
+ var model, cwd, title, parent, endReason, costStatus, costSource sql.NullString
+ var started, ended sql.NullFloat64
+ var msgCount, toolCount, input, output, cacheRead, cacheWrite, reasoning sql.NullInt64
+ var estimatedCost, actualCost sql.NullFloat64
+ if err := rows.Scan(&s.ID, &s.Source, &model, &cwd, &title, &parent, &started, &ended, &endReason,
+ &msgCount, &toolCount, &input, &output, &cacheRead, &cacheWrite, &reasoning,
+ &estimatedCost, &actualCost, &costStatus, &costSource); err != nil {
+ return nil, err
+ }
+ s.Model = model.String
+ s.CWD = cwd.String
+ s.Title = title.String
+ s.ParentSessionID = parent.String
+ s.StartedAtMS = secondsToMillis(started)
+ s.EndedAtMS = secondsToMillis(ended)
+ s.EndReason = endReason.String
+ s.MessageCount = msgCount.Int64
+ s.ToolCallCount = toolCount.Int64
+ s.InputTokens = input.Int64
+ s.OutputTokens = output.Int64
+ s.CacheReadTokens = cacheRead.Int64
+ s.CacheWriteTokens = cacheWrite.Int64
+ s.ReasoningTokens = reasoning.Int64
+ s.EstimatedCostUSD = estimatedCost.Float64
+ s.ActualCostUSD = actualCost.Float64
+ s.CostStatus = costStatus.String
+ s.CostSource = costSource.String
+ out = append(out, s)
+ }
+ return out, rows.Err()
+}
+
+func (s *Store) ReadMessages(sessionID string, afterID int64) ([]Message, error) {
+ rows, err := s.db.Query(`
+SELECT id, session_id, role, content, tool_call_id, tool_calls, tool_name, timestamp,
+ token_count, finish_reason, reasoning, reasoning_content, reasoning_details,
+ platform_message_id, observed, active
+FROM messages
+WHERE session_id = ? AND active = 1 AND id > ?
+ORDER BY id`, sessionID, afterID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []Message
+ for rows.Next() {
+ var m Message
+ var content, callID, calls, toolName, finish, reasoning, reasoningContent, reasoningDetails, platformID sql.NullString
+ var ts sql.NullFloat64
+ var token sql.NullInt64
+ var observed, active sql.NullInt64
+ if err := rows.Scan(&m.ID, &m.SessionID, &m.Role, &content, &callID, &calls, &toolName, &ts, &token, &finish,
+ &reasoning, &reasoningContent, &reasoningDetails, &platformID, &observed, &active); err != nil {
+ return nil, err
+ }
+ m.Content = content.String
+ m.ToolCallID = callID.String
+ m.ToolCalls = calls.String
+ m.ToolName = toolName.String
+ m.TimestampMS = secondsToMillis(ts)
+ m.TokenCount = token.Int64
+ m.FinishReason = finish.String
+ m.Reasoning = reasoning.String
+ m.ReasoningContent = reasoningContent.String
+ m.ReasoningDetails = reasoningDetails.String
+ m.PlatformMessageID = platformID.String
+ m.Observed = observed.Int64 != 0
+ m.Active = active.Int64 != 0
+ out = append(out, m)
+ }
+ return out, rows.Err()
+}
+
+func (s *Store) LastMessageID(sessionID string) (int64, error) {
+ var last sql.NullInt64
+ if err := s.db.QueryRow(`SELECT max(id) FROM messages WHERE session_id = ? AND active = 1`, sessionID).Scan(&last); err != nil {
+ return 0, err
+ }
+ return last.Int64, nil
+}
+
+func openSQLiteReadOnly(path string) (*sql.DB, error) {
+ uriPath := filepath.ToSlash(path)
+ if !strings.HasPrefix(uriPath, "/") {
+ uriPath = "/" + uriPath
+ }
+ u := url.URL{Scheme: "file", Path: uriPath}
+ q := u.Query()
+ q.Set("mode", "ro")
+ q.Set("_pragma", "busy_timeout(1000)")
+ u.RawQuery = q.Encode()
+ return sql.Open("sqlite", u.String())
+}
+
+func MapSession(session Session, messages []Message, cursor *Cursor) []MappedEvent {
+ m := &mapper{session: session, cursor: cursor, calls: map[string]toolCall{}}
+ m.mapSession()
+ for _, message := range messages {
+ m.mapMessage(message)
+ }
+ m.mapUsage()
+ m.mapSessionEnd()
+ return m.out
+}
+
+type mapper struct {
+ session Session
+ cursor *Cursor
+ out []MappedEvent
+ calls map[string]toolCall
+ lastTimestampMS int64
+}
+
+type toolCall struct {
+ ID string
+ Name string
+ Arguments map[string]interface{}
+}
+
+func (m *mapper) mapSession() {
+ if m.cursor != nil && m.cursor.Started {
+ return
+ }
+ ev := m.base(m.session.StartedAtMS, "session.started", "session", schema.SeverityInfo, "Hermes session started")
+ ev.Raw = map[string]interface{}{"hermes": map[string]interface{}{
+ "source": m.session.Source,
+ "title": m.session.Title,
+ "parent_session_id": m.session.ParentSessionID,
+ }}
+ m.append(0, "session.started", ev)
+}
+
+func (m *mapper) mapSessionEnd() {
+ if m.session.EndedAtMS == 0 || (m.cursor != nil && m.cursor.EndedAtMS == m.session.EndedAtMS) {
+ return
+ }
+ ev := m.base(m.session.EndedAtMS, "session.ended", "session", schema.SeverityInfo, "Hermes session ended")
+ ev.Raw = map[string]interface{}{"hermes": map[string]interface{}{
+ "end_reason": m.session.EndReason,
+ }}
+ m.append(0, fmt.Sprintf("session.ended.%d", m.session.EndedAtMS), ev)
+}
+
+func (m *mapper) mapUsage() {
+ if m.cursor == nil {
+ return
+ }
+ usage := &schema.GenAIUsageInfo{}
+ if delta := m.session.InputTokens - m.cursor.InputTokens; delta > 0 {
+ usage.InputTokens = &delta
+ }
+ if delta := m.session.OutputTokens - m.cursor.OutputTokens; delta > 0 {
+ usage.OutputTokens = &delta
+ }
+ if delta := m.session.CacheReadTokens - m.cursor.CacheReadTokens; delta > 0 {
+ usage.CacheRead = &schema.GenAIUsageCacheReadInfo{InputTokens: &delta}
+ }
+ if delta := m.session.CacheWriteTokens - m.cursor.CacheWriteTokens; delta > 0 {
+ usage.CacheCreation = &schema.GenAIUsageCacheCreationInfo{InputTokens: &delta}
+ }
+ if delta := m.session.ReasoningTokens - m.cursor.ReasoningTokens; delta > 0 {
+ usage.Reasoning = &schema.GenAIUsageReasoningInfo{OutputTokens: &delta}
+ }
+ cost := sessionCost(m.session)
+ if delta := cost - m.cursor.CostUSD; delta > 0 {
+ usage.CostUSD = &delta
+ }
+ if usage.InputTokens == nil && usage.OutputTokens == nil && usage.CacheRead == nil && usage.CacheCreation == nil && usage.Reasoning == nil && usage.CostUSD == nil {
+ return
+ }
+ ts := m.session.EndedAtMS
+ if ts == 0 {
+ ts = m.lastTimestampMS
+ }
+ if ts == 0 {
+ ts = m.session.StartedAtMS
+ }
+ if ts == 0 {
+ ts = time.Now().UnixMilli()
+ }
+ ev := m.base(ts, "token.usage", "metric", schema.SeverityInfo, "Hermes token usage")
+ ev.GenAI = m.withGenAI(ev.GenAI, func(genAI *schema.GenAIInfo) { genAI.Usage = usage })
+ ev.Raw = map[string]interface{}{"hermes": map[string]interface{}{
+ "token_source": "session_totals_delta",
+ "cost_status": m.session.CostStatus,
+ "cost_source": m.session.CostSource,
+ }}
+ m.append(0, fmt.Sprintf("token.usage.%d.%d.%d.%d.%d.%g",
+ m.session.InputTokens,
+ m.session.OutputTokens,
+ m.session.CacheReadTokens,
+ m.session.CacheWriteTokens,
+ m.session.ReasoningTokens,
+ cost,
+ ), ev)
+}
+
+func (m *mapper) mapMessage(message Message) {
+ if message.TimestampMS > m.lastTimestampMS {
+ m.lastTimestampMS = message.TimestampMS
+ }
+ role := strings.ToLower(strings.TrimSpace(message.Role))
+ switch role {
+ case "user":
+ if text := strings.TrimSpace(message.Content); text != "" {
+ ev := m.base(message.TimestampMS, "prompt.submitted", "prompt", schema.SeverityInfo, "Hermes prompt submitted")
+ ev.Prompt = &schema.PromptInfo{Text: text}
+ ev.Content = asymptoteobserve.RetainedContent(text, asymptoteobserve.DefaultStringLimit)
+ m.append(message.ID, "prompt.submitted", ev)
+ }
+ case "assistant":
+ for idx, text := range reasoningParts(message) {
+ ev := m.base(message.TimestampMS, "agent.reasoning", "session", schema.SeverityInfo, "Hermes agent reasoning")
+ ev.Content = asymptoteobserve.RetainedContent(text, asymptoteobserve.DefaultStringLimit)
+ ev.GenAI = m.withGenAI(ev.GenAI, func(genAI *schema.GenAIInfo) {
+ genAI.Output = &schema.GenAIOutputInfo{Messages: []map[string]interface{}{{"role": "assistant", "content": text, "type": "reasoning"}}}
+ })
+ ev.Raw = map[string]interface{}{"hermes": map[string]interface{}{"reasoning_part": idx}}
+ m.append(message.ID, fmt.Sprintf("reasoning.%d", idx), ev)
+ }
+ if text := strings.TrimSpace(message.Content); text != "" {
+ ev := m.base(message.TimestampMS, "agent.message", "agent", schema.SeverityInfo, "Hermes assistant message")
+ ev.Content = asymptoteobserve.RetainedContent(text, asymptoteobserve.DefaultStringLimit)
+ ev.GenAI = m.withGenAI(ev.GenAI, func(genAI *schema.GenAIInfo) {
+ genAI.Output = &schema.GenAIOutputInfo{Messages: []map[string]interface{}{{"role": "assistant", "content": text}}}
+ })
+ m.append(message.ID, "agent.message", ev)
+ }
+ for idx, call := range parseToolCalls(message.ToolCalls) {
+ m.calls[call.ID] = call
+ ev := m.toolEvent(message.TimestampMS, call, "tool.invoked", "tool", schema.SeverityInfo, "Hermes tool invoked")
+ m.append(message.ID, fmt.Sprintf("tool_call.%d", idx), ev)
+ }
+ case "tool":
+ call := m.calls[message.ToolCallID]
+ if call.ID == "" {
+ call = toolCall{ID: message.ToolCallID, Name: message.ToolName}
+ }
+ if call.Name == "" {
+ call.Name = message.ToolName
+ }
+ m.mapToolResult(message, call)
+ }
+}
+
+func (m *mapper) mapToolResult(message Message, call toolCall) {
+ result := decodeJSONObject(message.Content)
+ action, category, severity, msg := classifyTool(call.Name, call.Arguments, result)
+ ev := m.toolEvent(message.TimestampMS, call, action, category, severity, msg)
+ if output := firstString(result, "output", "stdout", "stderr", "result", "content"); output != "" {
+ ev.Content = asymptoteobserve.RetainedContent(output, asymptoteobserve.DefaultStringLimit)
+ }
+ switch action {
+ case "command.executed":
+ ev.Command = &schema.CommandInfo{Command: stringArg(call.Arguments, "command", "cmd")}
+ if output := firstString(result, "output", "stdout", "stderr", "result"); output != "" {
+ ev.Command.Output = output
+ }
+ if code, ok := intArg(result, "exit_code", "exitCode", "code"); ok {
+ ev.Command.ExitCode = &code
+ if code != 0 {
+ ev.Error = &schema.ErrorInfo{Type: "command_failed"}
+ }
+ }
+ case "file.read", "file.created", "file.modified":
+ path := stringArg(call.Arguments, "path", "file_path", "target_path")
+ ev.File = &schema.FileInfo{Path: path, Operation: fileOperationForAction(action)}
+ if path != "" {
+ ev.File.Language = strings.TrimPrefix(filepath.Ext(path), ".")
+ }
+ if diff := firstString(call.Arguments, "diff", "patch"); diff != "" {
+ ev.File.Diff = diff
+ ev.File.DiffBytes = len(diff)
+ ev.File.DiffHash = sha256String(diff)
+ ev.Content = asymptoteobserve.RetainedContent(diff, asymptoteobserve.DefaultStringLimit)
+ }
+ case "mcp.tool_invoked":
+ ev.MCP = &schema.MCPInfo{Tool: call.Name}
+ }
+ if errorText := firstString(result, "error"); errorText != "" && ev.Error == nil {
+ ev.Error = &schema.ErrorInfo{Type: "tool_error"}
+ }
+ ev.Raw = mergeRaw(ev.Raw, map[string]interface{}{"hermes": map[string]interface{}{
+ "tool_result": result,
+ }})
+ m.append(message.ID, "tool_result", ev)
+}
+
+func (m *mapper) base(timestampMS int64, action, category string, severity schema.Severity, message string) schema.Event {
+ ev := schema.NewEvent(schema.NewEventOptions{
+ Action: action,
+ Category: category,
+ Severity: severity,
+ Message: message,
+ Origin: schema.OriginLocal,
+ Fidelity: schema.FidelityObserved,
+ Harness: schema.HarnessInfo{
+ Name: Harness,
+ CollectionMethod: schema.CollectionMethodPoll,
+ },
+ })
+ if timestampMS > 0 {
+ ev.Timestamp = schema.FormatTimestamp(time.UnixMilli(timestampMS))
+ }
+ ev.Session = &schema.SessionInfo{ID: m.session.ID, WorkingDirectory: m.session.CWD}
+ if m.session.Model != "" {
+ ev.Model = asymptoteobserve.NormalizeModelName(m.session.Model)
+ ev.GenAI = m.withGenAI(ev.GenAI, func(genAI *schema.GenAIInfo) {
+ genAI.Request = &schema.GenAIRequestInfo{Model: ev.Model}
+ })
+ }
+ return ev
+}
+
+func (m *mapper) toolEvent(timestampMS int64, call toolCall, action, category string, severity schema.Severity, message string) schema.Event {
+ ev := m.base(timestampMS, action, category, severity, message)
+ ev.Tool = &schema.ToolInfo{Name: call.Name}
+ if command := stringArg(call.Arguments, "command", "cmd"); command != "" {
+ ev.Tool.Command = command
+ }
+ if path := stringArg(call.Arguments, "path", "file_path", "target_path"); path != "" {
+ ev.Tool.Path = path
+ }
+ ev.GenAI = m.withGenAI(ev.GenAI, func(genAI *schema.GenAIInfo) {
+ genAI.Operation = &schema.GenAIOperationInfo{Name: "execute_tool"}
+ genAI.Tool = &schema.GenAIToolInfo{
+ Name: call.Name,
+ Call: &schema.GenAIToolCallInfo{
+ ID: call.ID,
+ Arguments: call.Arguments,
+ },
+ }
+ })
+ return ev
+}
+
+func (m *mapper) append(sourceMessageID int64, suffix string, ev schema.Event) {
+ ev.Event.ID = hermesEventID(fmt.Sprintf("%s:%d:%s", m.session.ID, sourceMessageID, suffix))
+ m.out = append(m.out, MappedEvent{SourceMessageID: sourceMessageID, Event: ev})
+}
+
+func (m *mapper) withGenAI(genAI *schema.GenAIInfo, edit func(*schema.GenAIInfo)) *schema.GenAIInfo {
+ if genAI == nil {
+ genAI = &schema.GenAIInfo{}
+ }
+ edit(genAI)
+ return genAI
+}
+
+func parseToolCalls(raw string) []toolCall {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return nil
+ }
+ var items []map[string]interface{}
+ if err := json.Unmarshal([]byte(raw), &items); err != nil {
+ return nil
+ }
+ out := make([]toolCall, 0, len(items))
+ for _, item := range items {
+ id := firstString(item, "id", "call_id")
+ fn := asMap(item["function"])
+ name := firstString(item, "name", "tool_name")
+ args := map[string]interface{}{}
+ if fn != nil {
+ name = firstNonEmpty(name, firstString(fn, "name"))
+ args = decodeArguments(fn["arguments"])
+ } else {
+ args = decodeArguments(item["arguments"])
+ }
+ if id == "" {
+ id = firstString(item, "tool_call_id")
+ }
+ out = append(out, toolCall{ID: id, Name: name, Arguments: args})
+ }
+ return out
+}
+
+func classifyTool(name string, args, result map[string]interface{}) (string, string, schema.Severity, string) {
+ lower := strings.ToLower(strings.TrimSpace(name))
+ failed := firstString(result, "error") != "" || boolArg(result, "error") || boolArg(result, "failed")
+ if lower == "terminal" || strings.Contains(lower, "shell") || strings.Contains(lower, "bash") || stringArg(args, "command", "cmd") != "" {
+ return "command.executed", "command", schema.SeverityInfo, "Hermes command executed"
+ }
+ if isFileReadTool(lower) {
+ return "file.read", "file", schema.SeverityInfo, "Hermes file read"
+ }
+ if isFileCreateTool(lower) {
+ return "file.created", "file", schema.SeverityInfo, "Hermes file created"
+ }
+ if isFileEditTool(lower) {
+ return "file.modified", "file", schema.SeverityInfo, "Hermes file modified"
+ }
+ if strings.Contains(lower, "__") || strings.HasPrefix(lower, "mcp_") {
+ return "mcp.tool_invoked", "mcp", schema.SeverityInfo, "Hermes MCP tool invoked"
+ }
+ if failed {
+ return "tool.failed", "tool", schema.SeverityHigh, "Hermes tool failed"
+ }
+ return "tool.completed", "tool", schema.SeverityInfo, "Hermes tool completed"
+}
+
+func isFileReadTool(lower string) bool {
+ return strings.Contains(lower, "read") || strings.Contains(lower, "grep") || strings.Contains(lower, "search") || strings.Contains(lower, "list") || strings.Contains(lower, "find")
+}
+
+func isFileCreateTool(lower string) bool {
+ return strings.Contains(lower, "create") || strings.Contains(lower, "write")
+}
+
+func isFileEditTool(lower string) bool {
+ return strings.Contains(lower, "edit") || strings.Contains(lower, "patch") || strings.Contains(lower, "replace")
+}
+
+func fileOperationForAction(action string) string {
+ switch action {
+ case "file.read":
+ return "read"
+ case "file.created":
+ return "create"
+ case "file.modified":
+ return "modify"
+ default:
+ return ""
+ }
+}
+
+func reasoningParts(message Message) []string {
+ seen := map[string]bool{}
+ var out []string
+ for _, text := range []string{message.Reasoning, message.ReasoningContent, message.ReasoningDetails} {
+ text = strings.TrimSpace(text)
+ if text == "" || seen[text] {
+ continue
+ }
+ seen[text] = true
+ out = append(out, text)
+ }
+ return out
+}
+
+func decodeArguments(value interface{}) map[string]interface{} {
+ switch typed := value.(type) {
+ case string:
+ return decodeJSONObject(typed)
+ case map[string]interface{}:
+ return typed
+ default:
+ return map[string]interface{}{}
+ }
+}
+
+func decodeJSONObject(raw string) map[string]interface{} {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return map[string]interface{}{}
+ }
+ var out map[string]interface{}
+ if err := json.Unmarshal([]byte(raw), &out); err != nil {
+ return map[string]interface{}{"result": raw}
+ }
+ return out
+}
+
+func asMap(value interface{}) map[string]interface{} {
+ if m, ok := value.(map[string]interface{}); ok {
+ return m
+ }
+ return nil
+}
+
+func stringArg(m map[string]interface{}, keys ...string) string {
+ return firstString(m, keys...)
+}
+
+func firstString(m map[string]interface{}, keys ...string) string {
+ for _, key := range keys {
+ switch v := m[key].(type) {
+ case string:
+ if strings.TrimSpace(v) != "" {
+ return v
+ }
+ case fmt.Stringer:
+ if strings.TrimSpace(v.String()) != "" {
+ return v.String()
+ }
+ case float64:
+ return strconv.FormatFloat(v, 'f', -1, 64)
+ case int:
+ return strconv.Itoa(v)
+ case int64:
+ return strconv.FormatInt(v, 10)
+ }
+ }
+ return ""
+}
+
+func firstNonEmpty(values ...string) string {
+ for _, value := range values {
+ if strings.TrimSpace(value) != "" {
+ return value
+ }
+ }
+ return ""
+}
+
+func intArg(m map[string]interface{}, keys ...string) (int, bool) {
+ for _, key := range keys {
+ switch v := m[key].(type) {
+ case float64:
+ return int(v), true
+ case int:
+ return v, true
+ case int64:
+ return int(v), true
+ case string:
+ if n, err := strconv.Atoi(strings.TrimSpace(v)); err == nil {
+ return n, true
+ }
+ }
+ }
+ return 0, false
+}
+
+func boolArg(m map[string]interface{}, keys ...string) bool {
+ for _, key := range keys {
+ v, ok := m[key].(bool)
+ if ok && v {
+ return true
+ }
+ }
+ return false
+}
+
+func mergeRaw(raw map[string]interface{}, next map[string]interface{}) map[string]interface{} {
+ if raw == nil {
+ raw = map[string]interface{}{}
+ }
+ for k, v := range next {
+ raw[k] = v
+ }
+ return raw
+}
+
+func secondsToMillis(value sql.NullFloat64) int64 {
+ if !value.Valid || value.Float64 <= 0 {
+ return 0
+ }
+ return int64(value.Float64 * 1000)
+}
+
+func sessionCost(session Session) float64 {
+ if session.ActualCostUSD > 0 {
+ return session.ActualCostUSD
+ }
+ return session.EstimatedCostUSD
+}
+
+func sha256String(value string) string {
+ sum := sha256.Sum256([]byte(value))
+ return hex.EncodeToString(sum[:])
+}
+
+var hermesIDNamespace = [16]byte{
+ 0x58, 0x24, 0x3d, 0x29, 0x5e, 0xa1, 0x4b, 0xbe,
+ 0x85, 0xa7, 0x49, 0x11, 0xa7, 0x18, 0xdb, 0x0c,
+}
+
+func hermesEventID(dedupID string) string {
+ digest := sha1.New()
+ digest.Write(hermesIDNamespace[:])
+ 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/hermessession/collect_test.go b/cli/beacon/internal/hermessession/collect_test.go
new file mode 100644
index 00000000..4c049da1
--- /dev/null
+++ b/cli/beacon/internal/hermessession/collect_test.go
@@ -0,0 +1,253 @@
+package hermessession
+
+import (
+ "bufio"
+ "database/sql"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+)
+
+func TestCollectOnceMapsHermesStateDBAndAdvancesCursor(t *testing.T) {
+ dir := t.TempDir()
+ dbPath := filepath.Join(dir, "state.db")
+ createHermesFixtureDB(t, dbPath)
+ logPath := filepath.Join(dir, "runtime.jsonl")
+ statePath := filepath.Join(dir, "hermes-state.json")
+
+ summary, err := CollectOnce(CollectOptions{
+ DBPath: dbPath,
+ StatePath: statePath,
+ LogPath: logPath,
+ Write: true,
+ UserMode: true,
+ })
+ if err != nil {
+ t.Fatalf("CollectOnce returned error: %v", err)
+ }
+ if summary.Sessions != 1 || summary.SessionsChanged != 1 || summary.EventsEmitted == 0 || summary.Errors != 0 {
+ t.Fatalf("summary = %#v, want one changed session with events and no errors", summary)
+ }
+
+ events := readEvents(t, logPath)
+ actions := eventActions(events)
+ want := []string{
+ "session.started",
+ "prompt.submitted",
+ "agent.reasoning",
+ "tool.invoked",
+ "command.executed",
+ "token.usage",
+ "session.ended",
+ }
+ if strings.Join(actions, ",") != strings.Join(want, ",") {
+ t.Fatalf("actions = %v, want %v", actions, want)
+ }
+
+ command := findAction(t, events, "command.executed")
+ if command.Command == nil || command.Command.Command != "go test ./..." {
+ t.Fatalf("command event = %#v, want command.command", command.Command)
+ }
+ if command.Command.ExitCode == nil || *command.Command.ExitCode != 0 {
+ t.Fatalf("exit code = %#v, want 0", command.Command.ExitCode)
+ }
+ if command.Harness.CollectionMethod != schema.CollectionMethodPoll {
+ t.Fatalf("collection method = %q, want poll", command.Harness.CollectionMethod)
+ }
+ if command.Event.Fidelity != schema.FidelityObserved {
+ t.Fatalf("fidelity = %q, want observed", command.Event.Fidelity)
+ }
+
+ state, err := LoadState(statePath)
+ if err != nil {
+ t.Fatalf("LoadState returned error: %v", err)
+ }
+ cursor := state.Sessions["hermes-session-1"]
+ if cursor == nil || cursor.LastMessageID != 3 || !cursor.Started || cursor.EndedAtMS == 0 {
+ t.Fatalf("cursor = %#v, want collected through message 3 and ended", cursor)
+ }
+
+ second, err := CollectOnce(CollectOptions{
+ DBPath: dbPath,
+ StatePath: statePath,
+ LogPath: logPath,
+ Write: true,
+ UserMode: true,
+ })
+ if err != nil {
+ t.Fatalf("second CollectOnce returned error: %v", err)
+ }
+ if second.EventsEmitted != 0 || second.SessionsChanged != 0 {
+ t.Fatalf("second summary = %#v, want no new events", second)
+ }
+ if got := len(readEvents(t, logPath)); got != len(events) {
+ t.Fatalf("event count after second run = %d, want %d", got, len(events))
+ }
+}
+
+func TestMapSessionClassifiesFileTool(t *testing.T) {
+ session := Session{ID: "s1", Model: "anthropic/claude-opus-4.6", CWD: "/repo", StartedAtMS: 1000}
+ messages := []Message{
+ {
+ ID: 1,
+ SessionID: "s1",
+ Role: "assistant",
+ TimestampMS: 2000,
+ ToolCalls: `[{"id":"call_read","function":{"name":"read_file","arguments":"{\"path\":\"README.md\"}"}}]`,
+ },
+ {
+ ID: 2,
+ SessionID: "s1",
+ Role: "tool",
+ ToolCallID: "call_read",
+ ToolName: "read_file",
+ TimestampMS: 3000,
+ Content: `{"content":"hello"}`,
+ },
+ }
+
+ mapped := MapSession(session, messages, &Cursor{Started: true})
+ fileEvent := findMappedAction(t, mapped, "file.read")
+ if fileEvent.File == nil || fileEvent.File.Path != "README.md" || fileEvent.File.Operation != "read" {
+ t.Fatalf("file event = %#v, want README.md read", fileEvent.File)
+ }
+ if fileEvent.Model != "claude-opus-4.6" {
+ t.Fatalf("model = %q, want normalized model", fileEvent.Model)
+ }
+}
+
+func createHermesFixtureDB(t *testing.T, path string) {
+ t.Helper()
+ db, err := sql.Open("sqlite", path)
+ if err != nil {
+ t.Fatalf("open sqlite: %v", err)
+ }
+ defer db.Close()
+ schemaSQL := `
+CREATE TABLE sessions (
+ id TEXT PRIMARY KEY,
+ source TEXT NOT NULL,
+ user_id TEXT,
+ model TEXT,
+ model_config TEXT,
+ system_prompt TEXT,
+ parent_session_id TEXT,
+ started_at REAL NOT NULL,
+ ended_at REAL,
+ end_reason TEXT,
+ message_count INTEGER DEFAULT 0,
+ tool_call_count INTEGER DEFAULT 0,
+ input_tokens INTEGER DEFAULT 0,
+ output_tokens INTEGER DEFAULT 0,
+ cache_read_tokens INTEGER DEFAULT 0,
+ cache_write_tokens INTEGER DEFAULT 0,
+ reasoning_tokens INTEGER DEFAULT 0,
+ cwd TEXT,
+ billing_provider TEXT,
+ billing_base_url TEXT,
+ billing_mode TEXT,
+ estimated_cost_usd REAL,
+ actual_cost_usd REAL,
+ cost_status TEXT,
+ cost_source TEXT,
+ pricing_version TEXT,
+ title TEXT,
+ api_call_count INTEGER DEFAULT 0,
+ handoff_state TEXT,
+ handoff_platform TEXT,
+ handoff_error TEXT,
+ rewind_count INTEGER NOT NULL DEFAULT 0,
+ archived INTEGER NOT NULL DEFAULT 0
+);
+CREATE TABLE messages (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ session_id TEXT NOT NULL REFERENCES sessions(id),
+ role TEXT NOT NULL,
+ content TEXT,
+ tool_call_id TEXT,
+ tool_calls TEXT,
+ tool_name TEXT,
+ timestamp REAL NOT NULL,
+ token_count INTEGER,
+ finish_reason TEXT,
+ reasoning TEXT,
+ reasoning_content TEXT,
+ reasoning_details TEXT,
+ codex_reasoning_items TEXT,
+ codex_message_items TEXT,
+ platform_message_id TEXT,
+ observed INTEGER DEFAULT 0,
+ active INTEGER NOT NULL DEFAULT 1
+);`
+ if _, err := db.Exec(schemaSQL); err != nil {
+ t.Fatalf("create schema: %v", err)
+ }
+ if _, err := db.Exec(`
+INSERT INTO sessions (id, source, model, cwd, started_at, ended_at, end_reason, message_count, tool_call_count, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, reasoning_tokens, estimated_cost_usd, title)
+VALUES ('hermes-session-1', 'cli', 'anthropic/claude-opus-4.6', '/repo', 1780632830.5, 1780632999.25, 'cli_close', 3, 1, 100, 20, 7, 3, 5, 0.01, 'fixture');
+INSERT INTO messages (id, session_id, role, content, timestamp, active)
+VALUES (1, 'hermes-session-1', 'user', 'run tests', 1780632831.0, 1);
+INSERT INTO messages (id, session_id, role, tool_calls, timestamp, reasoning_content, finish_reason, active)
+VALUES (2, 'hermes-session-1', 'assistant', '[{"id":"call_terminal","call_id":"call_terminal","function":{"name":"terminal","arguments":"{\"command\":\"go test ./...\",\"workdir\":\"/repo\"}"}}]', 1780632832.0, 'I should run the tests.', 'tool_calls', 1);
+INSERT INTO messages (id, session_id, role, tool_call_id, tool_name, content, timestamp, active)
+VALUES (3, 'hermes-session-1', 'tool', 'call_terminal', 'terminal', '{"output":"ok","exit_code":0,"error":null}', 1780632833.0, 1);
+`); err != nil {
+ t.Fatalf("insert fixture rows: %v", err)
+ }
+}
+
+func readEvents(t *testing.T, path string) []schema.Event {
+ t.Helper()
+ f, err := os.Open(path)
+ if err != nil {
+ t.Fatalf("open log: %v", err)
+ }
+ defer f.Close()
+ var out []schema.Event
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ var ev schema.Event
+ if err := json.Unmarshal(scanner.Bytes(), &ev); err != nil {
+ t.Fatalf("decode event: %v", err)
+ }
+ out = append(out, ev)
+ }
+ if err := scanner.Err(); err != nil {
+ t.Fatalf("scan log: %v", err)
+ }
+ return out
+}
+
+func eventActions(events []schema.Event) []string {
+ out := make([]string, 0, len(events))
+ for _, event := range events {
+ out = append(out, event.Event.Action)
+ }
+ return out
+}
+
+func findAction(t *testing.T, events []schema.Event, action string) schema.Event {
+ t.Helper()
+ for _, event := range events {
+ if event.Event.Action == action {
+ return event
+ }
+ }
+ t.Fatalf("action %q not found in %v", action, eventActions(events))
+ return schema.Event{}
+}
+
+func findMappedAction(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("action %q not found in mapped events", action)
+ return schema.Event{}
+}