diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 683f6219a..bdf3f02a0 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -1011,8 +1011,12 @@ func (b *boot) setupCurators(ctx context.Context) { // doesn't declare Manifest.Skills, per curator not per instance. Skills: skillcurator.NewStore(skillsRoot), // Conversations backs the session-memory curator; b.chatSessionStore - // is opened by openChatSessions before setupCurators. - Conversations: sessioncurator.NewAdapter(b.chatSessionStore), + // is opened by openChatSessions before setupCurators. The agent every + // curator write is addressed to is the deployment's bot user: the same + // value the turn runner reads agent-scope memory with + // (TurnRunnerConfig.BotUser), so a fact written here is a fact a later + // turn reaches. + Conversations: sessioncurator.NewAdapter(b.chatSessionStore, b.cfg.BotUser), LLM: curatorLLMRunner{rt: b.llm, outcomes: b.providerOutcomes}, // b.chatModels.ActiveModel() is the same source sendChatTurn uses // for a real chat turn (telegram_setup.go) -- not diff --git a/internal/infrastructure/sessioncurator/adapter.go b/internal/infrastructure/sessioncurator/adapter.go index 6bb724303..a00c4e219 100644 --- a/internal/infrastructure/sessioncurator/adapter.go +++ b/internal/infrastructure/sessioncurator/adapter.go @@ -19,18 +19,26 @@ import ( // curator needs -- never the full session CRUD/branch/search surface a // chat gateway exposes. See docs/prds/session-memory-curator.md. type Adapter struct { - store gateway.SessionStore + store gateway.SessionStore + agentID string } -// NewAdapter builds an Adapter. Roles come from the canonical records the +// NewAdapter builds an Adapter that reports agentID as the agent owning +// every session it returns, so the curator addresses agent-user memory to +// the same agent a chat turn reads it back from (the composition's +// configured bot user, the value gateway.TurnRunnerConfig.BotUser carries). +// A session record's own Source.BotUser is deliberately not used for this: +// it is the router's session-resolution match key, and empty in a +// single-identity deployment. Roles come from the canonical records the // store returns, so no bot identity is needed to derive them. -func NewAdapter(store gateway.SessionStore) *Adapter { - return &Adapter{store: store} +func NewAdapter(store gateway.SessionStore, agentID string) *Adapter { + return &Adapter{store: store, agentID: agentID} } // RecentSessions returns sessions active at or after since, newest first. -// AgentID is the session's bot identity, the closest thing to an Agent the -// tree records today (see docs/architecture/identity.md). +// AgentID is the agent every session's memory is addressed by -- the +// composition's configured bot user, the same value a chat turn addresses +// its own reads with (see docs/architecture/identity.md). func (a *Adapter) RecentSessions(ctx context.Context, since time.Time) ([]curator.SessionSummary, error) { sessions, err := a.store.List(ctx) if err != nil { @@ -41,7 +49,7 @@ func (a *Adapter) RecentSessions(ctx context.Context, since time.Time) ([]curato if s.LastActiveAt.Before(since) { continue } - out = append(out, curator.SessionSummary{ID: s.SessionID, AgentID: s.Source.BotUser, LastActive: s.LastActiveAt}) + out = append(out, curator.SessionSummary{ID: s.SessionID, AgentID: a.agentID, LastActive: s.LastActiveAt}) } return out, nil } diff --git a/internal/infrastructure/sessioncurator/adapter_test.go b/internal/infrastructure/sessioncurator/adapter_test.go index 0514db2be..f639592e6 100644 --- a/internal/infrastructure/sessioncurator/adapter_test.go +++ b/internal/infrastructure/sessioncurator/adapter_test.go @@ -30,7 +30,7 @@ func TestAdapterRecentSessionsFiltersByActivity(t *testing.T) { t.Fatalf("Save(recent) = %v", err) } - a := NewAdapter(store) + a := NewAdapter(store, "archie-bot") got, err := a.RecentSessions(ctx, time.Unix(1000, 0)) if err != nil { t.Fatalf("RecentSessions() = %v, want nil", err) @@ -64,7 +64,7 @@ func TestAdapterMessagesReadsRoleFromRecords(t *testing.T) { t.Fatalf("SaveMessage(bare) = %v", err) } - a := NewAdapter(store) + a := NewAdapter(store, "archie-bot") got, err := a.Messages(ctx, "s1", 10) if err != nil { t.Fatalf("Messages() = %v, want nil", err) @@ -83,9 +83,11 @@ func TestAdapterMessagesReadsRoleFromRecords(t *testing.T) { } } -// TestAdapterRecentSessionsCarriesAgentID pins that a session's agent reaches -// the curator contract, so an agent-user scope can be addressed without -// recovering the agent from the session id. +// TestAdapterRecentSessionsCarriesAgentID pins that the agent a session's +// memory is addressed to comes from the composition, not from the record's +// own BotUser: BotUser is the router's session-resolution key +// (gateway/session_commands.go), which is empty in a single-identity +// deployment -- an addressing component, never a match key. func TestAdapterRecentSessionsCarriesAgentID(t *testing.T) { t.Parallel() store := newTestStore(t) @@ -93,19 +95,19 @@ func TestAdapterRecentSessionsCarriesAgentID(t *testing.T) { sess := gateway.SessionContext{ SessionID: "s1", - Source: messaging.SessionSource{Platform: "telegram", BotUser: "winter", ChannelID: "chat-1"}, + Source: messaging.SessionSource{Platform: "telegram", BotUser: "primary", ChannelID: "chat-1"}, LastActiveAt: time.Unix(2000, 0), } if err := store.Save(ctx, sess); err != nil { t.Fatalf("Save() = %v", err) } - got, err := NewAdapter(store).RecentSessions(ctx, time.Unix(1000, 0)) + got, err := NewAdapter(store, "archie-bot").RecentSessions(ctx, time.Unix(1000, 0)) if err != nil { t.Fatalf("RecentSessions() = %v, want nil", err) } - if len(got) != 1 || got[0].AgentID != "winter" { - t.Fatalf("RecentSessions() = %+v, want one session with AgentID winter", got) + if len(got) != 1 || got[0].AgentID != "archie-bot" { + t.Fatalf("RecentSessions() = %+v, want one session whose AgentID is the composition's %q", got, "archie-bot") } } @@ -129,7 +131,7 @@ func TestAdapterMessagesCarriesSenderID(t *testing.T) { } } - got, err := NewAdapter(store).Messages(ctx, "s1", 10) + got, err := NewAdapter(store, "archie-bot").Messages(ctx, "s1", 10) if err != nil { t.Fatalf("Messages() = %v, want nil", err) } diff --git a/internal/infrastructure/sessioncurator/sessioncurator.go b/internal/infrastructure/sessioncurator/sessioncurator.go index e718922b8..e2a3b0fde 100644 --- a/internal/infrastructure/sessioncurator/sessioncurator.go +++ b/internal/infrastructure/sessioncurator/sessioncurator.go @@ -18,12 +18,13 @@ const Name = "session-memory" // written. const ActionExtracted = "memory.extracted" -// ActionSkipped records a session the pass could not attribute to exactly -// one participant, so nothing was written for it. The reason names how many -// distinct senders were found (zero for a dashboard or webhook session, -// more than one for a group chat), and how many user messages carried no -// sender at all -- unknown provenance rules a session out on its own, beside -// any number of identified senders. +// ActionSkipped records a session the pass could not address, so nothing was +// written for it. The reason names what was missing: an agent id (the +// deployment's bot user, empty when the composition resolved none), how many +// distinct senders were found (zero for a dashboard or webhook session, more +// than one for a group chat), and how many user messages carried no sender at +// all -- unknown provenance rules a session out on its own, beside any number +// of identified senders. const ActionSkipped = "memory.skipped" // DefaultInterval is the check-in cadence used when nothing more @@ -137,9 +138,9 @@ func effectiveSince(since, now time.Time) time.Time { // writes them through engine as agent-user memory for the session's single // participant. Returns nil (no Action) when nothing was extracted -- // matching the skill curator's "a pass with nothing to report is not an -// error" -- or when the session carries no messages at all. A session that -// cannot be attributed to one participant is skipped with an Action saying -// so. +// error" -- or when the session carries no messages at all. A session the +// pass cannot address -- no agent, or no single participant -- is skipped +// with an Action saying why. func (c *Curator) reviewOne(ctx context.Context, engine domainmemory.MemoryEngine, sess curator.SessionSummary) (*curator.Action, error) { msgs, err := c.host.Conversations.Messages(ctx, sess.ID, messageTailSize) if err != nil { @@ -149,10 +150,26 @@ func (c *Curator) reviewOne(ctx context.Context, engine domainmemory.MemoryEngin return nil, nil } - // Resolve the participant before spending a model call: an - // unattributable session has nowhere addressable to write, so there is - // nothing a model response could add. ScopeAgentUser is addressed by - // both ids, and a guess would file one person's facts under another's. + // Resolve the address before spending a model call: an unaddressable + // session has nowhere to write, so there is nothing a model response + // could add. ScopeAgentUser is addressed by both ids, and a guess would + // file one person's facts under another's. + // + // An empty agent id is the composition having resolved no bot user for + // this deployment -- the session's own record cannot supply one (see + // Adapter). The engine would refuse the scope, which is the right + // refusal for a write with no address: what is wrong is writing it at + // all, so the skip belongs here, at the point the scope is produced, and + // not as a Pass error that abandons every other session's work. + if sess.AgentID == "" { + return &curator.Action{ + At: c.host.Clock.Now(), + Type: ActionSkipped, + Detail: sess.ID, + Reason: "no agent id: agent-user memory needs an agent and a user", + }, nil + } + participant, reason := sessionParticipant(msgs) if participant == "" { return &curator.Action{ diff --git a/internal/infrastructure/sessioncurator/sessioncurator_test.go b/internal/infrastructure/sessioncurator/sessioncurator_test.go index 40548ed22..8b3391411 100644 --- a/internal/infrastructure/sessioncurator/sessioncurator_test.go +++ b/internal/infrastructure/sessioncurator/sessioncurator_test.go @@ -4,11 +4,13 @@ import ( "context" "errors" "fmt" + "os" "testing" "time" "github.com/samcharles93/archie-core/internal/domain/curator" domainmemory "github.com/samcharles93/archie-core/internal/domain/memory" + infraMemory "github.com/samcharles93/archie-core/internal/infrastructure/memory" ) // --- fakes ------------------------------------------------------------- @@ -136,6 +138,47 @@ func (f fakeEngineSource) Get(name string) (domainmemory.MemoryEngine, bool) { return f.engine, true } +// engineSource adapts one memory engine under the name the curator is built +// with, so a case can bind the real builtin engine where the fake's refusal +// behaviour would hide what the engine actually validates. +type engineSource struct{ engine domainmemory.MemoryEngine } + +func (s engineSource) Get(name string) (domainmemory.MemoryEngine, bool) { + if name != "builtin" { + return nil, false + } + return s.engine, true +} + +func newTestCuratorWithEngine(t *testing.T, conv curator.ConversationSource, llm curator.LLMRunner, engine domainmemory.MemoryEngine) *Curator { + t.Helper() + c := New(time.Hour, "builtin") + c.Bind(curator.Registrar{ + Conversations: conv, + LLM: llm, + MemoryEngines: engineSource{engine: engine}, + Clock: testClock{now: time.Unix(1000, 0)}, + }) + return c +} + +// engineScopeDirs names the per-scope directories a real engine has written +// to. It persists one directory per scope it has ever written, so an empty +// root is an engine holding no records at all -- the only root-wide view the +// engine's scope-addressed read surface can't give a test. +func engineScopeDirs(t *testing.T, root string) []string { + t.Helper() + entries, err := os.ReadDir(root) + if err != nil { + t.Fatalf("ReadDir(%s) = %v", root, err) + } + names := make([]string, 0, len(entries)) + for _, e := range entries { + names = append(names, e.Name()) + } + return names +} + type testClock struct{ now time.Time } func (c testClock) Now() time.Time { return c.now } @@ -502,6 +545,125 @@ func TestPassReviewsMultipleSessionsIndependently(t *testing.T) { } } +// TestPassSkipsASessionWithNoAgentID drives the real builtin engine, whose +// Create validates the scope it is handed. A session with no agent id is the +// address the tree has for an agent-user record without an agent: it has no +// scope, so it must be skipped and its reason recorded, never turned into a +// Pass error that takes every other session's actions down with it. +func TestPassSkipsASessionWithNoAgentID(t *testing.T) { + t.Parallel() + root := t.TempDir() + engine := infraMemory.NewBuiltinEngine(root, 0) + conv := &fakeConversations{ + sessions: map[string]time.Time{"s1": time.Unix(1000, 0)}, + agents: map[string]string{"s1": ""}, + messages: map[string][]curator.ConversationMessage{ + "s1": {{Role: "user", SenderID: "u-42", Content: "I prefer tabs"}}, + }, + } + c := newTestCuratorWithEngine(t, conv, &fakeLLM{responses: []string{`["prefers tabs over spaces"]`}}, engine) + + res, err := c.Pass(context.Background(), curator.PassInput{}) + if err != nil { + t.Fatalf("Pass() = %v, want nil: a session with no agent id is skipped, not a pass failure", err) + } + if len(res.Actions) != 1 { + t.Fatalf("Actions = %#v, want exactly one skip", res.Actions) + } + got := res.Actions[0] + if got.Type != ActionSkipped { + t.Errorf("Actions[0].Type = %q, want %q", got.Type, ActionSkipped) + } + if got.Detail != "s1" { + t.Errorf("Actions[0].Detail = %q, want the session id %q", got.Detail, "s1") + } + if want := "no agent id: agent-user memory needs an agent and a user"; got.Reason != want { + t.Errorf("Actions[0].Reason = %q, want %q", got.Reason, want) + } + if dirs := engineScopeDirs(t, root); len(dirs) != 0 { + t.Errorf("engine scope directories = %v, want none: the pass wrote for a session it could not address", dirs) + } +} + +// TestPassWritesThroughTheRealEngineForAnAddressableSession is the companion +// to the skip above: it holds the same real engine, the same extractable +// message, and an agent id, so the skip cannot pass for a reason unrelated to +// the agent id -- such as an engine that refuses every write. +func TestPassWritesThroughTheRealEngineForAnAddressableSession(t *testing.T) { + t.Parallel() + root := t.TempDir() + engine := infraMemory.NewBuiltinEngine(root, 0) + conv := &fakeConversations{ + sessions: map[string]time.Time{"s1": time.Unix(1000, 0)}, + agents: map[string]string{"s1": "archie-bot"}, + messages: map[string][]curator.ConversationMessage{ + "s1": {{Role: "user", SenderID: "u-42", Content: "I prefer tabs"}}, + }, + } + c := newTestCuratorWithEngine(t, conv, &fakeLLM{responses: []string{`["prefers tabs over spaces"]`}}, engine) + + res, err := c.Pass(context.Background(), curator.PassInput{}) + if err != nil { + t.Fatalf("Pass() = %v, want nil", err) + } + if len(res.Actions) != 1 || res.Actions[0].Type != ActionExtracted { + t.Fatalf("Actions = %#v, want one %s", res.Actions, ActionExtracted) + } + scope := domainmemory.Scope{Kind: domainmemory.ScopeAgentUser, Agent: "archie-bot", User: "u-42"} + records, err := engine.List(context.Background(), scope) + if err != nil { + t.Fatalf("List(%v) = %v, want nil", scope, err) + } + if len(records) != 1 { + t.Fatalf("List(%v) = %#v, want the one extracted record", scope, records) + } + if records[0].Content != "prefers tabs over spaces" { + t.Errorf("Content = %q, want the extracted fact verbatim", records[0].Content) + } +} + +// TestPassContinuesPastAnUnattributableSession pins that a session the pass +// cannot address costs the pass that session and nothing else. Both sessions +// here are unattributable, so an abort on the first would drop the second's +// action as well. +func TestPassContinuesPastAnUnattributableSession(t *testing.T) { + t.Parallel() + root := t.TempDir() + engine := infraMemory.NewBuiltinEngine(root, 0) + conv := &fakeConversations{ + sessions: map[string]time.Time{"s1": time.Unix(1000, 0), "s2": time.Unix(1000, 0)}, + agents: map[string]string{"s1": "", "s2": ""}, + messages: map[string][]curator.ConversationMessage{ + "s1": {{Role: "user", SenderID: "u-1", Content: "fact for s1"}}, + "s2": {{Role: "user", SenderID: "u-2", Content: "fact for s2"}}, + }, + } + c := newTestCuratorWithEngine(t, conv, &fakeLLM{responses: []string{`["a fact worth keeping"]`}}, engine) + + res, err := c.Pass(context.Background(), curator.PassInput{}) + if err != nil { + t.Fatalf("Pass() = %v, want nil: one unattributable session must not abort the pass", err) + } + if len(res.Actions) != 2 { + t.Fatalf("Actions = %#v, want one action per session", res.Actions) + } + seen := make(map[string]string, len(res.Actions)) + for _, a := range res.Actions { + if a.Type != ActionSkipped { + t.Errorf("Actions = %#v, want every action to be %s", res.Actions, ActionSkipped) + } + seen[a.Detail] = a.Type + } + for _, session := range []string{"s1", "s2"} { + if _, ok := seen[session]; !ok { + t.Errorf("no action recorded for %s: a session the pass could not address took the whole pass down with it", session) + } + } + if dirs := engineScopeDirs(t, root); len(dirs) != 0 { + t.Errorf("engine scope directories = %v, want none", dirs) + } +} + func TestPassUnknownEngineIsAnError(t *testing.T) { t.Parallel() c := New(time.Hour, "does-not-exist")