Skip to content

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

fix(hermes): key a cloned profile's event ids by its home

Saurav Singh10aec3253fd5
diff --git a/cli/beacon/internal/hermessession/collect.go b/cli/beacon/internal/hermessession/collect.go
index 90351005..b0774955 100644
--- a/cli/beacon/internal/hermessession/collect.go
+++ b/cli/beacon/internal/hermessession/collect.go
@@ -54,7 +54,10 @@ type State struct {
}
type CollectOptions struct {
- DBPath string
+ DBPath string
+ // StatePath is this home's cursor file. The session home file beside it (SessionHomesPath) is
+ // shared by every home whose cursor sits in the same directory, and decides which of them keys a
+ // session's event ids by home. Without a StatePath no ids are keyed.
StatePath string
Write bool
LogPath string
@@ -220,6 +223,9 @@ func CollectOnce(opts CollectOptions) (summary Summary, err error) {
if err != nil {
return summary, err
}
+ if err := assignEventIDHomes(SessionHomesPath(opts.StatePath), canonicalHome(filepath.Dir(store.Path())), sessions, state); err != nil {
+ return summary, fmt.Errorf("assign Hermes event id homes: %w", err)
+ }
defer func() {
if saveErr := state.Save(opts.StatePath); saveErr != nil && err == nil {
err = fmt.Errorf("save Hermes collector state: %w", saveErr)
diff --git a/cli/beacon/internal/hermessession/event_id_test.go b/cli/beacon/internal/hermessession/event_id_test.go
index f4c8c4d5..f0c6130b 100644
--- a/cli/beacon/internal/hermessession/event_id_test.go
+++ b/cli/beacon/internal/hermessession/event_id_test.go
@@ -105,32 +105,3 @@ func TestMapSessionKeysEventIDsByHome(t *testing.T) {
}
}
}
-
-// A cursor marked KeyedByHome keeps keying the session's ids by its home on every sweep, so events
-// written later in the session never fall back to the unkeyed ids another home writes.
-func TestCollectOnceKeysEventIDsForACursorMarkedKeyed(t *testing.T) {
- dir := t.TempDir()
- dbPath := filepath.Join(dir, "state.db")
- createHermesFixtureDB(t, dbPath)
- statePath := filepath.Join(dir, "hermes-state.json")
- state := &State{Version: StateVersion, Sessions: map[string]*Cursor{"hermes-session-1": {KeyedByHome: true}}}
- if err := state.Save(statePath); err != nil {
- t.Fatal(err)
- }
- logPath := filepath.Join(dir, "runtime.jsonl")
- if _, err := CollectOnce(CollectOptions{DBPath: dbPath, StatePath: statePath, LogPath: logPath, Write: true, UserMode: true}); err != nil {
- t.Fatal(err)
- }
- for _, ev := range readEvents(t, logPath) {
- if ev.Event.ID == fixtureEventIDs[ev.Event.Action] {
- t.Fatalf("%s kept the unkeyed id %s", ev.Event.Action, ev.Event.ID)
- }
- }
- saved, err := LoadState(statePath)
- if err != nil {
- t.Fatal(err)
- }
- if cursor := saved.Sessions["hermes-session-1"]; cursor == nil || !cursor.KeyedByHome || !cursor.Started {
- t.Fatalf("cursor = %#v, want it collected and still keyed by home", cursor)
- }
-}
diff --git a/cli/beacon/internal/hermessession/session_homes.go b/cli/beacon/internal/hermessession/session_homes.go
new file mode 100644
index 00000000..d3bef0d2
--- /dev/null
+++ b/cli/beacon/internal/hermessession/session_homes.go
@@ -0,0 +1,76 @@
+package hermessession
+
+import (
+ "path/filepath"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionsync"
+)
+
+// SessionHomesFileName is the file, beside the cursor files, that records which Hermes home holds
+// the unkeyed event ids of each session id.
+const SessionHomesFileName = "hermes-session-homes.json"
+
+const sessionHomesVersion = 1
+
+// sessionHomes maps a Hermes session id to the canonical path of the home whose sweeps write that
+// session's unkeyed event ids. Every home a sweep of one cursor directory reads shares it, so the
+// first home to collect a session id keeps the ids Beacon has always derived, and any other home
+// that later finds the same id, as a cloned profile does, keys its ids by its own path instead.
+type sessionHomes struct {
+ Version int `json:"version"`
+ Sessions map[string]string `json:"sessions"`
+}
+
+var sessionHomesFile = sessionsync.StateFile[sessionHomes]{
+ Name: "Hermes session home",
+ New: func() *sessionHomes {
+ return &sessionHomes{Version: sessionHomesVersion, Sessions: map[string]string{}}
+ },
+ Valid: func(s *sessionHomes) bool { return s.Version == sessionHomesVersion && s.Sessions != nil },
+ Stamp: func(s *sessionHomes) { s.Version = sessionHomesVersion },
+}
+
+// SessionHomesPath is the session home file for the cursor at statePath, or empty when there is no
+// cursor file, as for --print.
+func SessionHomesPath(statePath string) string {
+ if statePath == "" {
+ return ""
+ }
+ return filepath.Join(filepath.Dir(statePath), SessionHomesFileName)
+}
+
+// assignEventIDHomes decides, for each session this sweep reads, whether its event ids are keyed by
+// home, and records the decision on its cursor. It claims a session id for home when no home holds
+// it yet, so the common case, a session id only one home has, keeps its unkeyed ids.
+//
+// A cursor that has already collected events keeps the ids it wrote: a session a home collected
+// before this file existed stays unkeyed, and is claimed for that home when no other home was first.
+// Only a session's first sweep can be keyed, so ids never change part way through a session.
+//
+// path is the shared session home file; an empty path decides nothing, leaving every id unkeyed.
+func assignEventIDHomes(path, home string, sessions []Session, state *State) error {
+ if path == "" || len(sessions) == 0 {
+ return nil
+ }
+ return sessionHomesFile.Update(path, func(homes *sessionHomes) bool {
+ changed := false
+ for _, session := range sessions {
+ cursor := state.cursor(session.ID)
+ owner, claimed := homes.Sessions[session.ID]
+ switch {
+ case cursor.Started || cursor.LastMessageID > 0:
+ if !claimed && !cursor.KeyedByHome {
+ homes.Sessions[session.ID] = home
+ changed = true
+ }
+ case !claimed:
+ homes.Sessions[session.ID] = home
+ changed = true
+ cursor.KeyedByHome = false
+ default:
+ cursor.KeyedByHome = owner != home
+ }
+ }
+ return changed
+ })
+}
diff --git a/cli/beacon/internal/hermessession/session_homes_test.go b/cli/beacon/internal/hermessession/session_homes_test.go
new file mode 100644
index 00000000..c80f5d4a
--- /dev/null
+++ b/cli/beacon/internal/hermessession/session_homes_test.go
@@ -0,0 +1,143 @@
+package hermessession
+
+import (
+ "database/sql"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
+)
+
+// clonedHermesHomes makes the native root and a profile cloned from it: both hold the fixture
+// session under the same id, as `hermes profile create --clone` leaves them. Each home syncs into
+// its own log, because the writer drops an event that repeats another session's action at the same
+// moment, which the clone's copied history does, and these tests are about ids rather than that.
+func clonedHermesHomes(t *testing.T) (root, profile string) {
+ t.Helper()
+ home := t.TempDir()
+ testenv.SetHome(t, home)
+ root = filepath.Join(home, ".hermes")
+ profile = filepath.Join(root, "profiles", "work")
+ for _, dir := range []string{root, profile} {
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ createHermesFixtureDB(t, filepath.Join(dir, "state.db"))
+ }
+ return root, profile
+}
+
+// homeLog is the runtime log a test syncs dir into.
+func homeLog(dir string) string { return filepath.Join(dir, "runtime.jsonl") }
+
+func syncHermesHome(t *testing.T, dir string) Summary {
+ t.Helper()
+ summary, err := CollectOnce(CollectOptions{DBPath: filepath.Join(dir, "state.db"), StatePath: DefaultStatePath(dir), LogPath: homeLog(dir), Write: true, UserMode: true})
+ if err != nil {
+ t.Fatalf("sync %s: %v", dir, err)
+ }
+ return summary
+}
+
+// addHermesPrompt appends a user message to the fixture session, the way each copy of a cloned
+// profile goes on independently: both stores give the new row the same message id.
+func addHermesPrompt(t *testing.T, dir, text string) {
+ t.Helper()
+ db, err := sql.Open("sqlite", filepath.Join(dir, "state.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ if _, err := db.Exec(`INSERT INTO messages (id, session_id, role, content, timestamp, active) VALUES (4, 'hermes-session-1', 'user', ?, 1780633000.0, 1)`, text); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func loadCursor(t *testing.T, dir string) *Cursor {
+ t.Helper()
+ state, err := LoadState(DefaultStatePath(dir))
+ if err != nil {
+ t.Fatal(err)
+ }
+ cursor := state.Sessions["hermes-session-1"]
+ if cursor == nil {
+ t.Fatalf("no cursor for the fixture session in %s", DefaultStatePath(dir))
+ }
+ return cursor
+}
+
+func eventIDsByAction(t *testing.T, dir string) map[string]string {
+ t.Helper()
+ out := map[string]string{}
+ for _, ev := range readEvents(t, homeLog(dir)) {
+ out[ev.Event.Action] = ev.Event.ID
+ }
+ return out
+}
+
+// assertNoSharedEventIDs fails when two events the homes wrote carry one id, which is what ingest,
+// the backfill restage and share upsert would collapse into a single event.
+func assertNoSharedEventIDs(t *testing.T, dirs ...string) {
+ t.Helper()
+ seen := map[string]schema.Event{}
+ for _, dir := range dirs {
+ for _, ev := range readEvents(t, homeLog(dir)) {
+ if first, dup := seen[ev.Event.ID]; dup {
+ a, _ := json.Marshal(first)
+ b, _ := json.Marshal(ev)
+ t.Fatalf("event id %s names two events:\n%s\n%s", ev.Event.ID, a, b)
+ }
+ seen[ev.Event.ID] = ev
+ }
+ }
+}
+
+// Issue #974: a cloned profile starts with a copy of state.db, so it holds the same session id as
+// the home it was cloned from, and the copies' message ids count up independently once they
+// diverge. The first home to sync the session keeps the unkeyed ids; the clone keys its own.
+func TestCollectOnceKeysEventIDsOfAClonedProfile(t *testing.T) {
+ root, profile := clonedHermesHomes(t)
+ syncHermesHome(t, root)
+ syncHermesHome(t, profile)
+
+ assertFixtureEventIDs(t, eventIDsByAction(t, root))
+ if got := len(readEvents(t, homeLog(profile))); got != len(fixtureEventIDs) {
+ t.Fatalf("clone wrote %d events, want %d", got, len(fixtureEventIDs))
+ }
+ assertNoSharedEventIDs(t, root, profile)
+ if loadCursor(t, root).KeyedByHome || !loadCursor(t, profile).KeyedByHome {
+ t.Fatalf("root keyed = %v, clone keyed = %v, want only the clone keyed", loadCursor(t, root).KeyedByHome, loadCursor(t, profile).KeyedByHome)
+ }
+
+ // Both copies go on with a different message 4.
+ addHermesPrompt(t, root, "deploy to staging")
+ addHermesPrompt(t, profile, "rewrite the readme")
+ if s := syncHermesHome(t, root); s.EventsEmitted != 1 {
+ t.Fatalf("root's second sync wrote %d events, want the new prompt", s.EventsEmitted)
+ }
+ if s := syncHermesHome(t, profile); s.EventsEmitted != 1 {
+ t.Fatalf("clone's second sync wrote %d events, want the new prompt", s.EventsEmitted)
+ }
+ assertNoSharedEventIDs(t, root, profile)
+
+ if s := syncHermesHome(t, profile); s.EventsEmitted != 0 {
+ t.Fatalf("clone's third sync wrote %d events, want none", s.EventsEmitted)
+ }
+}
+
+// Whichever home syncs a session first keeps the unkeyed ids, so a clone synced before the home it
+// came from is the one that keeps them.
+func TestCollectOnceKeysTheSecondHomeToSyncASession(t *testing.T) {
+ root, profile := clonedHermesHomes(t)
+ syncHermesHome(t, profile)
+ syncHermesHome(t, root)
+
+ assertFixtureEventIDs(t, eventIDsByAction(t, profile))
+ assertNoSharedEventIDs(t, root, profile)
+ if !loadCursor(t, root).KeyedByHome || loadCursor(t, profile).KeyedByHome {
+ t.Fatal("want only the home synced second keyed")
+ }
+}