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
fix(hermes): pin the sweep cursor to the batch it actually wrote
Clauded7c3af038a3d
diff --git a/cli/beacon/cmd/endpoint_hermes.go b/cli/beacon/cmd/endpoint_hermes.goindex d7c01145..19e1c9bc 100644--- a/cli/beacon/cmd/endpoint_hermes.go+++ b/cli/beacon/cmd/endpoint_hermes.go@@ -5,6 +5,7 @@ import ("encoding/json""fmt""path/filepath"+ "strings""time""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"@@ -217,8 +218,12 @@ func runEndpointHermesStatus(cmd *cobra.Command, args []string) error {return nil}+// resolveHermesStatePath keeps the cursor beside the log the sweep writes to. A system-mode sweep+// collects on behalf of the machine, so its cursor belongs next to the system runtime log rather+// than in whichever home the operator happened to run from; everything else uses the per-user+// default in hermessession.DefaultStatePath.func resolveHermesStatePath(path string, userMode bool) string {- if path != "" {+ if strings.TrimSpace(path) != "" {return path}if !userMode {diff --git a/cli/beacon/cmd/endpoint_hermes_test.go b/cli/beacon/cmd/endpoint_hermes_test.gonew file mode 100644index 00000000..e40a4b22--- /dev/null+++ b/cli/beacon/cmd/endpoint_hermes_test.go@@ -0,0 +1,40 @@+package cmd++import (+ "path/filepath"+ "strings"+ "testing"+)++// The cursor is what keeps a scheduled sweep from re-appending every Hermes session's whole+// history, so it has to land beside the log that sweep writes to. A system-mode sweep that stores+// its cursor under the operator's home lets a later user-mode run skip sessions the user log never+// received, and vice versa.+func TestHermesStatePathFollowsTheSweepItBelongsTo(t *testing.T) {+ if got := resolveHermesStatePath("/explicit/path.json", true); got != "/explicit/path.json" {+ t.Errorf("an explicit --state was overridden: %q", got)+ }+ if got := resolveHermesStatePath("/explicit/path.json", false); got != "/explicit/path.json" {+ t.Errorf("an explicit --state was overridden in system mode: %q", got)+ }++ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)++ user := resolveHermesStatePath("", true)+ if want := filepath.Join(home, ".beacon", "endpoint", "state", "hermes.json"); user != want {+ t.Errorf("user cursor = %q, want %q", user, want)+ }++ system := resolveHermesStatePath("", false)+ if !filepath.IsAbs(system) {+ t.Errorf("system cursor = %q, which is not somewhere a sweep can reliably write", system)+ }+ if strings.HasPrefix(system, home) {+ t.Errorf("a system sweep put its cursor in the operator's home: %q", system)+ }+ if system == user {+ t.Errorf("system and user sweeps share one cursor at %q", system)+ }+}diff --git a/cli/beacon/internal/hermessession/collect.go b/cli/beacon/internal/hermessession/collect.goindex 9c33207c..e6c1ce30 100644--- a/cli/beacon/internal/hermessession/collect.go+++ b/cli/beacon/internal/hermessession/collect.go@@ -232,8 +232,9 @@ func collectSession(store *Store, session Session, state *State, opts CollectOptif err != nil {return false, err}- mapped := MapSession(session, messages, cursor)+ mapped, pending := MapSession(session, messages, cursor)if len(mapped) == 0 {+ cursor.PendingCalls = pendingadvanceCursorMessages(cursor, messages)updateCursorTotals(cursor, session)return false, nil@@ -244,6 +245,9 @@ func collectSession(store *Store, session Session, state *State, opts CollectOpt}summary.EventsEmitted++}+ // The cursor only moves once the whole batch is on disk. CollectOnce saves the state even when a+ // session fails, so advancing while emitting would skip the events the failed sweep never wrote.+ cursor.PendingCalls = pendingfor _, item := range mapped {if item.SourceMessageID > cursor.LastMessageID {cursor.LastMessageID = item.SourceMessageID@@ -441,7 +445,15 @@ func openSQLiteReadOnly(path string) (*sql.DB, error) {return sql.Open("sqlite", u.String())}-func MapSession(session Session, messages []Message, cursor *Cursor) []MappedEvent {+// MapSession maps one session's new messages into endpoint events. It also returns the tool calls+// that are still waiting for their result, because Hermes writes a call's arguments on the+// assistant row and the result on a later one: without carrying them across sweeps, a result+// collected after its call would be classified with no command or path.+//+// The pending calls are returned rather than written onto the cursor so the caller can persist them+// only once every event in the batch is written. Recording them earlier would drop a call's+// arguments when a later emit fails and the sweep retries the same messages.+func MapSession(session Session, messages []Message, cursor *Cursor) ([]MappedEvent, map[string]json.RawMessage) {m := &mapper{session: session, cursor: cursor, calls: map[string]toolCall{}}if cursor != nil {for id, raw := range cursor.PendingCalls {@@ -457,19 +469,25 @@ func MapSession(session Session, messages []Message, cursor *Cursor) []MappedEve}m.mapUsage()m.mapSessionEnd()- if cursor != nil {- if len(m.calls) > 0 {- cursor.PendingCalls = make(map[string]json.RawMessage, len(m.calls))- for id, call := range m.calls {- if data, err := json.Marshal(call); err == nil {- cursor.PendingCalls[id] = data- }- }- } else {- cursor.PendingCalls = nil+ return m.out, encodePendingCalls(m.calls)+}++func encodePendingCalls(calls map[string]toolCall) map[string]json.RawMessage {+ if len(calls) == 0 {+ return nil+ }+ out := make(map[string]json.RawMessage, len(calls))+ for id, call := range calls {+ data, err := json.Marshal(call)+ if err != nil {+ continue}+ out[id] = data}- return m.out+ if len(out) == 0 {+ return nil+ }+ return out}type mapper struct {diff --git a/cli/beacon/internal/hermessession/collect_test.go b/cli/beacon/internal/hermessession/collect_test.goindex 4c049da1..61887e19 100644--- a/cli/beacon/internal/hermessession/collect_test.go+++ b/cli/beacon/internal/hermessession/collect_test.go@@ -4,6 +4,7 @@ import ("bufio""database/sql""encoding/json"+ "errors""os""path/filepath""strings"@@ -110,7 +111,7 @@ func TestMapSessionClassifiesFileTool(t *testing.T) {},}- mapped := MapSession(session, messages, &Cursor{Started: true})+ 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)@@ -251,3 +252,133 @@ func findMappedAction(t *testing.T, mapped []MappedEvent, action string) schema.t.Fatalf("action %q not found in mapped events", action)return schema.Event{}}++// CollectOnce saves the collector state even when a session fails part way through, so the cursor+// must not move until every event in the batch is on disk. Advancing it inside the emit loop lost+// the rest of the batch: the next sweep read past those messages and never wrote them.+func TestCollectOnceKeepsCursorWhenAnEmitFails(t *testing.T) {+ dir := t.TempDir()+ dbPath := filepath.Join(dir, "state.db")+ createHermesFixtureDB(t, dbPath)+ statePath := filepath.Join(dir, "hermes-state.json")++ failing := &writerFailingAfter{limit: 3}+ if _, err := CollectOnce(CollectOptions{+ DBPath: dbPath,+ StatePath: statePath,+ Print: true,+ Out: failing,+ }); err == nil {+ t.Fatal("CollectOnce returned no error although the writer failed mid-batch")+ }++ state, err := LoadState(statePath)+ if err != nil {+ t.Fatalf("LoadState returned error: %v", err)+ }+ if cursor := state.Sessions["hermes-session-1"]; cursor != nil {+ if cursor.LastMessageID != 0 || cursor.Started || cursor.EndedAtMS != 0 {+ t.Fatalf("cursor = %#v, want no progress recorded for a batch that was not written", cursor)+ }+ }++ logPath := filepath.Join(dir, "runtime.jsonl")+ if _, err := CollectOnce(CollectOptions{+ DBPath: dbPath,+ StatePath: statePath,+ LogPath: logPath,+ Write: true,+ UserMode: true,+ }); err != nil {+ t.Fatalf("second CollectOnce returned error: %v", err)+ }+ actions := eventActions(readEvents(t, logPath))+ 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 after retry = %v, want the whole batch %v", actions, want)+ }+}++// Hermes writes a tool call's arguments on the assistant row and the result on a later one, which+// can land in a different sweep. The unresolved call rides on the cursor so the result is still+// classified with the command it ran.+func TestCollectOnceCarriesToolArgumentsAcrossSweeps(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")++ db, err := sql.Open("sqlite", dbPath)+ if err != nil {+ t.Fatalf("open sqlite: %v", err)+ }+ // Drop the tool result and the session end so the first sweep sees a call with no result yet,+ // the way a sweep that runs while Hermes is still working does.+ if _, err := db.Exec(`DELETE FROM messages WHERE id = 3;+UPDATE sessions SET ended_at = NULL, end_reason = NULL WHERE id = 'hermes-session-1';`); err != nil {+ t.Fatalf("trim fixture rows: %v", err)+ }++ opts := CollectOptions{DBPath: dbPath, StatePath: statePath, LogPath: logPath, Write: true, UserMode: true}+ if _, err := CollectOnce(opts); err != nil {+ db.Close()+ t.Fatalf("first CollectOnce returned error: %v", err)+ }+ state, err := LoadState(statePath)+ if err != nil {+ db.Close()+ t.Fatalf("LoadState returned error: %v", err)+ }+ cursor := state.Sessions["hermes-session-1"]+ if cursor == nil || len(cursor.PendingCalls) != 1 {+ db.Close()+ t.Fatalf("cursor = %#v, want the unresolved call carried on the cursor", cursor)+ }++ if _, err := db.Exec(`+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);+UPDATE sessions SET ended_at = 1780632999.25, end_reason = 'cli_close' WHERE id = 'hermes-session-1';`); err != nil {+ db.Close()+ t.Fatalf("insert tool result: %v", err)+ }+ db.Close()++ if _, err := CollectOnce(opts); err != nil {+ t.Fatalf("second CollectOnce returned error: %v", err)+ }+ command := findAction(t, readEvents(t, logPath), "command.executed")+ if command.Command == nil || command.Command.Command != "go test ./..." {+ t.Fatalf("command event = %#v, want the command from the earlier sweep's tool call", command.Command)+ }++ state, err = LoadState(statePath)+ if err != nil {+ t.Fatalf("LoadState returned error: %v", err)+ }+ if cursor := state.Sessions["hermes-session-1"]; cursor == nil || len(cursor.PendingCalls) != 0 {+ t.Fatalf("cursor = %#v, want the resolved call dropped from the cursor", cursor)+ }+}++type writerFailingAfter struct {+ limit int+ writes int+}++func (w *writerFailingAfter) Write(p []byte) (int, error) {+ w.writes+++ if w.writes > w.limit {+ return 0, errors.New("destination unavailable")+ }+ return len(p), nil+}