feat(gateway): chat memory read path (unification slice 3) (#887)
Wires the durable-memory engine into the chat turn: prepareTurn resolves a
per-channel Subject (BotUser as AgentID, TurnRunnerConfig.UserIdentity for
the user), runs a scope-only Query over Subject.Scopes(), and renders the
result into a new <memory purpose="durable_context" trust="data"> block
between <tools> and <env>, following the same untrusted-data framing as
those two blocks. The read is synchronous, total, and never surfaces an
error: a nil engine, a failing Query, or a panicking provider all degrade to
no memory block (recovered in gateway.renderMemory).
UserIdentity is supplied per channel by the composition
(userIdentityResolver in internal/app/archied): telegram and email resolve
their native SenderID, the dashboard ("web") and webhook resolve nothing, so
a webhook's route-path SenderID can never become a user identity and the
dashboard's shared bearer token can never impersonate a person.
Fixes the composition-ordering bug that left every turn runner holding a nil
memory engine: setupMemoryAll now runs before setupGateways in main.go, and
before setupGatewayChat in gateway.go's startGatewayRuntime, so
boot.memoryStore() has a live engine at every turn-runner construction site.
Named constants bound the read: memoryRecordsPerScope per scope, and
memoryBlockByteCap on the rendered block, which drops (and logs) trailing
records rather than truncating one mid-line.
This commit is contained in:
1 parent
d5026f1a49
commit
c8f88c84b2
14 files changed
+699
-6
No files matched your search
@@ -688,7 +688,8 @@ func (b *boot) setupGateways(ctx context.Context, cfgPath, overlayPath string) b
|
||||
Bus: b.bus,
|
||||
Log: log,
|
||||
ChannelManager: b.channelManager, AgentStatus: b.agentStatus,
|
||||
RateLimiter: b.rateLimiter,
|
||||
RateLimiter: b.rateLimiter,
|
||||
MemoryEngine: b.memoryStore(),
|
||||
})
|
||||
if !ok {
|
||||
return false
|
||||
@@ -1156,6 +1157,27 @@ func (b *boot) setupMemoryAll() error {
|
||||
return b.setupMemoryEngine()
|
||||
}
|
||||
|
||||
// memoryStore resolves the active memory engine (the same one
|
||||
// setupMemoryEngine registered under cfg.Memory.Engine) as the narrow read
|
||||
// surface a chat turn runner needs. Nil when the registry was never set up
|
||||
// or the configured engine is not registered -- both cases the turn runner
|
||||
// already treats as "no memory block" (gateway.renderMemory), so a chat
|
||||
// turn degrades instead of failing.
|
||||
func (b *boot) memoryStore() gateway.MemoryStore {
|
||||
if b.memEngines == nil {
|
||||
return nil
|
||||
}
|
||||
name := b.cfg.Memory.Engine
|
||||
if name == "" {
|
||||
name = infraMemory.EngineName
|
||||
}
|
||||
engine, ok := b.memEngines.Get(name)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return engine
|
||||
}
|
||||
|
||||
// setupCurators wires the curator engine family. The registry owns
|
||||
// curator registration, lifecycle and shutdown ordering. The runtime
|
||||
// loop (archie-core-89x) and the reference curators (archie-core-i7i,
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/memory"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// userIdentityResolver returns the gateway.TurnRunnerConfig.UserIdentity
|
||||
// function for one channel, per docs/prds/memory-engine-unification.md §3:
|
||||
// resolution is supplied per channel by the composition, never inferred by
|
||||
// the engine or guessed from a channel-neutral "channel:SenderID"
|
||||
// concatenation.
|
||||
//
|
||||
// Telegram and email carry a native per-person sender id (a Telegram numeric
|
||||
// user id, an SMTP from address). The dashboard ("web") has one bearer
|
||||
// token, not users, and a webhook's SenderID is the configured route path
|
||||
// (internal/channels/webhook/webhook.go), not a person -- treating either as
|
||||
// an identity would give a URL or a shared token the same standing as a
|
||||
// real user, which the read path's isolation guarantee depends on never
|
||||
// happening. Both resolve nothing, so a turn on either channel gets global
|
||||
// and agent scopes only (Subject.WritableScopes' fail-closed behaviour).
|
||||
func userIdentityResolver(channel string) func(messaging.Message) (memory.IdentityID, bool) {
|
||||
switch channel {
|
||||
case "telegram", "email":
|
||||
return senderIDIdentity
|
||||
default:
|
||||
return noUserIdentity
|
||||
}
|
||||
}
|
||||
|
||||
// senderIDIdentity resolves a channel's own SenderID as the user's identity.
|
||||
// Empty means the channel carries no per-person identity for this message.
|
||||
func senderIDIdentity(msg messaging.Message) (memory.IdentityID, bool) {
|
||||
if msg.SenderID == "" {
|
||||
return "", false
|
||||
}
|
||||
return memory.IdentityID(msg.SenderID), true
|
||||
}
|
||||
|
||||
// noUserIdentity resolves nothing: the channel it is wired to (the
|
||||
// dashboard, a webhook) carries no per-person identity at all.
|
||||
func noUserIdentity(messaging.Message) (memory.IdentityID, bool) {
|
||||
return "", false
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// TestWebhookUserIdentityNeverReturnsTheRoutePath guards
|
||||
// docs/prds/memory-engine-unification.md §3 and §4's specific webhook
|
||||
// requirement: internal/channels/webhook/webhook.go sets SenderID to the
|
||||
// configured route path (RouteConfig.Path), and that must never surface as
|
||||
// a user identity, however plausible it looks as one.
|
||||
func TestWebhookUserIdentityNeverReturnsTheRoutePath(t *testing.T) {
|
||||
resolver := userIdentityResolver("webhook")
|
||||
id, ok := resolver(messaging.Message{SenderID: "/github", Sender: "webhook"})
|
||||
if ok || id != "" {
|
||||
t.Fatalf("webhook resolver = (%q, %v), want (\"\", false)", id, ok)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUserIdentityResolverPerChannel documents the composition's per-channel
|
||||
// choice: telegram and email carry a native sender id, the dashboard ("web")
|
||||
// and webhook do not.
|
||||
func TestUserIdentityResolverPerChannel(t *testing.T) {
|
||||
tests := []struct {
|
||||
channel string
|
||||
senderID string
|
||||
wantOK bool
|
||||
}{
|
||||
{"telegram", "12345", true},
|
||||
{"email", "person@example.com", true},
|
||||
{"web", "anything", false},
|
||||
{"webhook", "/github", false},
|
||||
{"unknown-future-channel", "anything", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.channel, func(t *testing.T) {
|
||||
resolver := userIdentityResolver(tt.channel)
|
||||
id, ok := resolver(messaging.Message{SenderID: tt.senderID})
|
||||
if ok != tt.wantOK {
|
||||
t.Fatalf("%s resolver ok = %v, want %v", tt.channel, ok, tt.wantOK)
|
||||
}
|
||||
if ok && string(id) != tt.senderID {
|
||||
t.Fatalf("%s resolver id = %q, want %q", tt.channel, id, tt.senderID)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestSenderIDIdentityFailsClosedOnEmptySenderID guards §3's "fail closed":
|
||||
// an empty SenderID (a channel that carries no per-caller id for this
|
||||
// particular message) must resolve to no identity, never an empty-string
|
||||
// identity that Subject would treat as present.
|
||||
func TestSenderIDIdentityFailsClosedOnEmptySenderID(t *testing.T) {
|
||||
id, ok := senderIDIdentity(messaging.Message{SenderID: ""})
|
||||
if ok || id != "" {
|
||||
t.Fatalf("senderIDIdentity(empty) = (%q, %v), want (\"\", false)", id, ok)
|
||||
}
|
||||
}
|
||||
@@ -33,3 +33,51 @@ func TestRunBuildsWorktreeManagerBeforeGateways(t *testing.T) {
|
||||
t.Fatal("Run wires the gateways before buildTreesAndIdentities; prReviewer captures b.trees, so review_pr would be dropped instead of advertised")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunSetsUpMemoryBeforeGateways pins the ordering
|
||||
// docs/prds/memory-engine-unification.md §4's "Prerequisite" note requires:
|
||||
// setupGateways constructs every chat turn runner (setupGatewayChat,
|
||||
// setupTelegramGateway), and a turn runner captures b.memEngines at
|
||||
// construction time via boot.memoryStore(). Built the other way round, every
|
||||
// turn runner captures a nil engine and the chat <memory> block never
|
||||
// appears, silently, because renderMemory treats a nil engine the same as a
|
||||
// failed read. Nothing at runtime observes the order, so it is asserted by
|
||||
// source position, the same way TestRunBuildsWorktreeManagerBeforeGateways
|
||||
// pins the worktree-manager ordering above.
|
||||
func TestRunSetsUpMemoryBeforeGateways(t *testing.T) {
|
||||
fileset := token.NewFileSet()
|
||||
file, err := parser.ParseFile(fileset, "main.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run := methodBody(t, file, "Run")
|
||||
memoryAll := methodCallPosition(run, "setupMemoryAll")
|
||||
gateways := methodCallPosition(run, "setupGateways")
|
||||
if memoryAll == token.NoPos || gateways == token.NoPos {
|
||||
t.Fatalf("Run call positions: setupMemoryAll=%v setupGateways=%v, want both present", memoryAll, gateways)
|
||||
}
|
||||
if gateways < memoryAll {
|
||||
t.Fatal("Run wires the gateways before setupMemoryAll; every turn runner would capture a nil memory engine")
|
||||
}
|
||||
}
|
||||
|
||||
// TestStartGatewayRuntimeSetsUpMemoryBeforeGatewayChat is the standalone
|
||||
// Gateway process's half of the same prerequisite: startGatewayRuntime
|
||||
// (gateway.go) constructs the turn runner via setupGatewayChat, which must
|
||||
// see a non-nil b.memEngines already.
|
||||
func TestStartGatewayRuntimeSetsUpMemoryBeforeGatewayChat(t *testing.T) {
|
||||
fileset := token.NewFileSet()
|
||||
file, err := parser.ParseFile(fileset, "gateway.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run := methodBody(t, file, "startGatewayRuntime")
|
||||
memoryAll := methodCallPosition(run, "setupMemoryAll")
|
||||
chat := methodCallPosition(run, "setupGatewayChat")
|
||||
if memoryAll == token.NoPos || chat == token.NoPos {
|
||||
t.Fatalf("startGatewayRuntime call positions: setupMemoryAll=%v setupGatewayChat=%v, want both present", memoryAll, chat)
|
||||
}
|
||||
if chat < memoryAll {
|
||||
t.Fatal("startGatewayRuntime wires setupGatewayChat before setupMemoryAll; the turn runner would capture a nil memory engine")
|
||||
}
|
||||
}
|
||||
@@ -125,14 +125,17 @@ func (b *boot) startGatewayRuntime(ctx context.Context, actor gateway.ChatTaskAc
|
||||
b.bus = events.NewBus()
|
||||
b.addCleanup(b.bus.Close)
|
||||
b.capabilityHost = plugin.NewHost()
|
||||
contract := b.setupGatewayChat(ctx, actor)
|
||||
// setupMemoryAll must run before setupGatewayChat: setupGatewayChat
|
||||
// constructs the turn runner, which captures b.memEngines at
|
||||
// construction time (see the identical ordering note in main.go's Run).
|
||||
// Memory is opened with its own long-lived context inside (matching the
|
||||
// daemon path via setupMemoryAll): shutdown of the file-backed provider
|
||||
// outlives the boot context by design, so the legacy manager wires itself
|
||||
// with a background context rather than the gateway's boot ctx.
|
||||
if err := b.setupMemory(); err != nil { //nolint:contextcheck // setupMemory owns its lifecycle contexts, matching the daemon's setupMemoryAll
|
||||
if err := b.setupMemoryAll(); err != nil { //nolint:contextcheck // setupMemory owns its lifecycle contexts, matching the daemon's setupMemoryAll
|
||||
return nil, err
|
||||
}
|
||||
contract := b.setupGatewayChat(ctx, actor)
|
||||
if err := b.registerTools(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -67,6 +67,7 @@ func (b *boot) setupGatewayChat(ctx context.Context, actor gateway.ChatTaskActor
|
||||
ChatTaskActor: actor, ChatPRReviewer: b.prReviewer(),
|
||||
DefaultChatIdentity: b.defaultChatIdentity, SessionStore: b.chatSessionStore,
|
||||
Bus: b.bus, Log: b.log, Secrets: b.secrets,
|
||||
MemoryEngine: b.memoryStore(),
|
||||
}
|
||||
router.LLM, router.LLMStream = makeChatLLMResponder(ctx, "web", setup, b.chatSessionStore, router)
|
||||
router.Titles = newChatTitleGenerator(setup)
|
||||
|
||||
@@ -411,6 +411,15 @@ func Run() int { //nolint:cyclop // the composition root's setup sequence is del
|
||||
if err := b.buildTreesAndIdentities(ctx); err != nil {
|
||||
return 1
|
||||
}
|
||||
// setupMemoryAll must run before setupGateways: setupGateways constructs
|
||||
// every chat turn runner (setupGatewayChat / setupTelegramGateway), and a
|
||||
// turn runner captures b.memEngines at construction time. Built the other
|
||||
// way round, every turn runner would capture a nil engine and the chat
|
||||
// read path (docs/prds/memory-engine-unification.md §4) would silently
|
||||
// never see a record.
|
||||
if err := b.setupMemoryAll(); err != nil {
|
||||
return 1
|
||||
}
|
||||
if !b.setupGateways(ctx, args.cfgPath, args.overlayPath) {
|
||||
return 1
|
||||
}
|
||||
@@ -425,9 +434,6 @@ func Run() int { //nolint:cyclop // the composition root's setup sequence is del
|
||||
if err := b.registerNATSRPC(); err != nil {
|
||||
return 1
|
||||
}
|
||||
if err := b.setupMemoryAll(); err != nil {
|
||||
return 1
|
||||
}
|
||||
b.setupCurators(ctx)
|
||||
|
||||
if err := b.setupScheduling(); err != nil {
|
||||
|
||||
@@ -68,6 +68,10 @@ type telegramSetup struct {
|
||||
// RateLimiter budgets inbound messages per sender when set. Nil
|
||||
// leaves rate limiting off.
|
||||
RateLimiter *ratelimit.Limiter
|
||||
// MemoryEngine is the durable-memory read surface (b.memEngines' active
|
||||
// engine, resolved by cfg.Memory.Engine). Nil disables the chat <memory>
|
||||
// block for every turn runner built from this setup.
|
||||
MemoryEngine gateway.MemoryStore
|
||||
}
|
||||
|
||||
// telegramValidateConfigMap builds the map Gateway.ValidateConfig expects
|
||||
@@ -355,6 +359,8 @@ func newChatTurnRunner(
|
||||
Operator: cfg.Chat.Operator,
|
||||
Workspace: cfg.Chat.Workspace,
|
||||
Repos: chatRepoEnv(cfg, s.DefaultChatIdentity),
|
||||
MemoryEngine: s.MemoryEngine,
|
||||
UserIdentity: userIdentityResolver(channel),
|
||||
Log: s.Log,
|
||||
})
|
||||
if err := runner.Recover(ctx); err != nil && s.Log != nil {
|
||||
|
||||
@@ -64,6 +64,13 @@ type SystemPromptConfig struct {
|
||||
// (chat.operator). Rendered so the agent knows the identity context it
|
||||
// serves under; empty means unconfigured and must be said explicitly.
|
||||
Operator string
|
||||
// Memory is the pre-rendered <memory> block body: the durable records the
|
||||
// read path recalled for this turn's resolved subject, already bounded by
|
||||
// the per-scope record limit and the render byte cap. Empty when there is
|
||||
// nothing to recall, or when the read degraded (engine failure, panic,
|
||||
// unresolved identity beyond global/agent scope) -- the template omits
|
||||
// the block entirely in that case, exactly like Tools.
|
||||
Memory string
|
||||
}
|
||||
|
||||
// promptData is the template execution context. It exists so the template
|
||||
@@ -105,6 +112,7 @@ func BuildSystemPrompt(cfg SystemPromptConfig) string {
|
||||
Workspace: cfg.Workspace,
|
||||
Repos: cfg.Repos,
|
||||
Operator: cfg.Operator,
|
||||
Memory: cfg.Memory,
|
||||
}
|
||||
var buf strings.Builder
|
||||
if err := archiePromptTemplate.Execute(&buf, data); err != nil {
|
||||
|
||||
@@ -46,6 +46,11 @@ The `<soul>` block above, when present, supplies identity and communication styl
|
||||
{{- else}}
|
||||
Right now no tools are available to you, so you can only answer from the conversation and your own knowledge. Say that directly when asked to act on files, systems or the network.
|
||||
{{- end}}
|
||||
{{if .Memory}}
|
||||
<memory purpose="durable_context" trust="data">
|
||||
{{xml .Memory}}
|
||||
</memory>
|
||||
{{- end}}
|
||||
|
||||
<env purpose="runtime_metadata" trust="data">
|
||||
Today's date: {{xml .Date}}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/memory"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
@@ -99,6 +100,17 @@ type TurnRunnerConfig struct {
|
||||
// default branch, rendered into the prompt's <env> block.
|
||||
Repos []RepoEnv
|
||||
Log *slog.Logger
|
||||
// MemoryEngine is the durable-memory read surface consulted once per turn
|
||||
// in prepareTurn. Nil disables the <memory> block entirely (renderMemory
|
||||
// treats a nil store the same as a failed read).
|
||||
MemoryEngine MemoryStore
|
||||
// UserIdentity resolves the initiating user's identity for one inbound
|
||||
// message, per channel. False (or a nil UserIdentity) means the channel
|
||||
// carries no per-person identity -- the dashboard's one bearer token, or a
|
||||
// webhook's route path, which must never be treated as a person -- and
|
||||
// the turn's memory Subject gets no UserID, so its read is agent and
|
||||
// global scope only (docs/prds/memory-engine-unification.md §3, §4).
|
||||
UserIdentity func(msg messaging.Message) (memory.IdentityID, bool)
|
||||
}
|
||||
|
||||
// TurnRunner owns one chat turn from session resolution through model
|
||||
@@ -314,6 +326,7 @@ func (r *TurnRunner) prepareTurn(ctx context.Context, sessionID string, in Inbou
|
||||
if r.Personas != nil {
|
||||
persona = r.Personas.GetActive(sessionID)
|
||||
}
|
||||
memoryBlock := renderMemory(ctx, r.MemoryEngine, r.resolveSubject(in.Message), r.Log)
|
||||
systemPrompt := BuildSystemPrompt(SystemPromptConfig{
|
||||
Persona: persona,
|
||||
Tools: prepared.ToolSummaries(),
|
||||
@@ -325,6 +338,7 @@ func (r *TurnRunner) prepareTurn(ctx context.Context, sessionID string, in Inbou
|
||||
Workspace: r.Workspace,
|
||||
Repos: r.Repos,
|
||||
Operator: r.Operator,
|
||||
Memory: memoryBlock,
|
||||
})
|
||||
compression, err := CompressionConfigForModel(
|
||||
modelDetails,
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
domainmemory "github.com/samcharles93/archie-core/internal/domain/memory"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
)
|
||||
|
||||
// memoryRecordsPerScope bounds how many records of each scope the read path
|
||||
// asks the engine for. It is a per-scope limit, not a total: Subject.Scopes()
|
||||
// returns at most four scopes, so the worst case is four times this many
|
||||
// records before the byte cap below trims further.
|
||||
const memoryRecordsPerScope = 20
|
||||
|
||||
// memoryBlockByteCap bounds the rendered <memory> block's size. This is a
|
||||
// size guard, not a timeout: the read is local and synchronous, and nothing
|
||||
// here waits on the network. A record that would push the block over the cap
|
||||
// is dropped (not truncated mid-record) and the drop is logged, so the block
|
||||
// stays valid content rather than silently corrupted output.
|
||||
const memoryBlockByteCap = 8192
|
||||
|
||||
// MemoryStore is the read surface prepareTurn needs from a memory engine: a
|
||||
// scope-only Query, nothing else. Narrowed from domainmemory.Store (which
|
||||
// also carries the write operations slice 4 uses) so this package's read
|
||||
// path cannot accidentally reach for Create/Update/Forget.
|
||||
type MemoryStore interface {
|
||||
Query(ctx context.Context, q domainmemory.Query) ([]domainmemory.Record, error)
|
||||
}
|
||||
|
||||
// renderMemory builds the turn's <memory> block body: a scope-only Query over
|
||||
// subject.Scopes() (most specific first, per Subject.Scopes' own doc), bounded
|
||||
// by memoryRecordsPerScope per scope and memoryBlockByteCap overall.
|
||||
//
|
||||
// This is synchronous, total, and never returns an error: docs/prds/
|
||||
// memory-engine-unification.md §4 requires the chat read path to degrade to
|
||||
// an empty block on any engine failure, including a panic, rather than fail
|
||||
// the turn -- a memory read is an enhancement to the prompt, never a
|
||||
// precondition for answering. The recover here is that contract's only
|
||||
// enforcement point; every caller below runs inside it.
|
||||
func renderMemory(ctx context.Context, store MemoryStore, subject domainmemory.Subject, log *slog.Logger) (block string) {
|
||||
if store == nil {
|
||||
return ""
|
||||
}
|
||||
defer func() {
|
||||
if p := recover(); p != nil {
|
||||
if log != nil {
|
||||
log.Warn("chat memory read panicked; continuing without a memory block", "panic", p)
|
||||
}
|
||||
block = ""
|
||||
}
|
||||
}()
|
||||
|
||||
records, err := store.Query(ctx, domainmemory.Query{
|
||||
Scopes: subject.Scopes(),
|
||||
Limit: memoryRecordsPerScope * len(subject.Scopes()),
|
||||
})
|
||||
if err != nil {
|
||||
if log != nil {
|
||||
log.Warn("chat memory read failed; continuing without a memory block", "err", err)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
return renderMemoryRecords(records, log)
|
||||
}
|
||||
|
||||
// renderMemoryRecords formats records as one line each, addressed by the
|
||||
// record's own id -- the same id the write path (slice 4) will take a
|
||||
// memory_edit call by, so the read and write directions share one source of
|
||||
// truth for addressing. A record whose line would push the block past
|
||||
// memoryBlockByteCap is dropped and logged rather than truncated mid-line,
|
||||
// so a partial block is never mistaken for a complete or a corrupted one.
|
||||
func renderMemoryRecords(records []domainmemory.Record, log *slog.Logger) string {
|
||||
var b strings.Builder
|
||||
dropped := 0
|
||||
for _, record := range records {
|
||||
line := fmt.Sprintf("- [%s] (%s, %s) %s\n", record.ID, record.Scope.Kind, record.Kind, record.Content)
|
||||
if b.Len()+len(line) > memoryBlockByteCap {
|
||||
dropped++
|
||||
continue
|
||||
}
|
||||
b.WriteString(line)
|
||||
}
|
||||
if dropped > 0 && log != nil {
|
||||
log.Warn("chat memory block exceeded its render cap; some records were dropped",
|
||||
"cap_bytes", memoryBlockByteCap, "dropped", dropped, "rendered", len(records)-dropped)
|
||||
}
|
||||
return strings.TrimRight(b.String(), "\n")
|
||||
}
|
||||
|
||||
// resolveSubject builds a turn's memory Subject from the runner's agent
|
||||
// identity (BotUser, the closest thing to an Agent id the tree records today
|
||||
// -- see sessioncurator.Adapter) and the channel's UserIdentity resolver. A
|
||||
// nil resolver, or one that returns false, yields UserID "" -- Subject.Scopes
|
||||
// then names only agent and global, never a wider fallback
|
||||
// (docs/prds/memory-engine-unification.md §3, "fail closed").
|
||||
func (r *TurnRunner) resolveSubject(msg messaging.Message) domainmemory.Subject {
|
||||
subject := domainmemory.Subject{AgentID: domainmemory.AgentID(r.BotUser)}
|
||||
if r.UserIdentity == nil {
|
||||
return subject
|
||||
}
|
||||
if id, ok := r.UserIdentity(msg); ok {
|
||||
subject.UserID = id
|
||||
}
|
||||
return subject
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
domainmemory "github.com/samcharles93/archie-core/internal/domain/memory"
|
||||
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
||||
infraMemory "github.com/samcharles93/archie-core/internal/infrastructure/memory"
|
||||
)
|
||||
|
||||
// newMemoryTestEngine builds a real builtin engine so these tests exercise
|
||||
// the actual scope-key isolation, not a fake that might not mirror it.
|
||||
func newMemoryTestEngine(t *testing.T) *infraMemory.BuiltinEngine {
|
||||
t.Helper()
|
||||
return infraMemory.NewBuiltinEngine(t.TempDir(), 0)
|
||||
}
|
||||
|
||||
func telegramIdentity(msg messaging.Message) (domainmemory.IdentityID, bool) {
|
||||
if msg.SenderID == "" {
|
||||
return "", false
|
||||
}
|
||||
return domainmemory.IdentityID(msg.SenderID), true
|
||||
}
|
||||
|
||||
func chatMsg(sourceID, channelID, senderID, text string) Inbound {
|
||||
return Inbound{Message: messaging.Message{
|
||||
SourceID: sourceID,
|
||||
ConversationID: messaging.ConversationID{ChannelID: channelID},
|
||||
Sender: "user",
|
||||
SenderID: senderID,
|
||||
Role: messaging.RoleUser,
|
||||
Text: text,
|
||||
}}
|
||||
}
|
||||
|
||||
func newMemoryTestRunner(t *testing.T, engine MemoryStore, userIdentity func(messaging.Message) (domainmemory.IdentityID, bool), botUser string) (*TurnRunner, *turnTestPreparedModel) {
|
||||
t.Helper()
|
||||
store := NewSessionStoreMemory()
|
||||
router := NewRouter(nil, nil, "telegram")
|
||||
router.Identity = botUser
|
||||
router.InitSessions(store)
|
||||
prepared := &turnTestPreparedModel{reply: "ok"}
|
||||
runner := NewTurnRunner(TurnRunnerConfig{
|
||||
Router: router,
|
||||
Sessions: store,
|
||||
Models: &fakeModelManager{models: []string{"test/model"}, activeModel: "test/model"},
|
||||
Personas: NewPersonaRegistry(DefaultPersonas()),
|
||||
Model: &turnTestModel{prepared: prepared},
|
||||
BotUser: botUser,
|
||||
Channel: "telegram",
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
MemoryEngine: engine,
|
||||
UserIdentity: userIdentity,
|
||||
})
|
||||
return runner, prepared
|
||||
}
|
||||
|
||||
// lastSystemPrompt returns the system-prompt message content the model saw
|
||||
// on its most recent Generate call.
|
||||
func lastSystemPrompt(prepared *turnTestPreparedModel) string {
|
||||
for _, m := range prepared.lastRequest.Messages {
|
||||
if m.Role == "system" {
|
||||
return m.Content
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// TestTurnMemoryReadPathAppearsNextTurn is acceptance criterion 1: a record
|
||||
// created directly through the engine's Store appears in a later turn's
|
||||
// prompt, with its id.
|
||||
func TestTurnMemoryReadPathAppearsNextTurn(t *testing.T) {
|
||||
engine := newMemoryTestEngine(t)
|
||||
runner, prepared := newMemoryTestRunner(t, engine, telegramIdentity, "archie")
|
||||
|
||||
rec, err := engine.Create(context.Background(), domainmemory.NewRecord{
|
||||
Scope: domainmemory.Scope{Kind: domainmemory.ScopeAgentUser, Agent: "archie", User: "alice"},
|
||||
Kind: "note",
|
||||
Content: "alice prefers dark roast coffee",
|
||||
Author: "test",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Create() error = %v", err)
|
||||
}
|
||||
|
||||
if _, err := runner.Run(context.Background(), chatMsg("s1", "chat-1", "alice", "hi"), nil); err != nil {
|
||||
t.Fatalf("Run() error = %v", err)
|
||||
}
|
||||
|
||||
prompt := lastSystemPrompt(prepared)
|
||||
if !strings.Contains(prompt, "alice prefers dark roast coffee") {
|
||||
t.Fatalf("prompt missing planted record content, prompt = %q", prompt)
|
||||
}
|
||||
if !strings.Contains(prompt, string(rec.ID)) {
|
||||
t.Fatalf("prompt missing record id %q, prompt = %q", rec.ID, prompt)
|
||||
}
|
||||
if !strings.Contains(prompt, `<memory purpose="durable_context" trust="data">`) {
|
||||
t.Fatalf("prompt missing memory block wrapper, prompt = %q", prompt)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTurnMemoryIsolatesByUser is acceptance criterion 2: an agent-user
|
||||
// record for one user is absent from a different user's prompt on the same
|
||||
// channel and agent, asserted end to end through the turn path.
|
||||
func TestTurnMemoryIsolatesByUser(t *testing.T) {
|
||||
engine := newMemoryTestEngine(t)
|
||||
runner, prepared := newMemoryTestRunner(t, engine, telegramIdentity, "archie")
|
||||
|
||||
if _, err := engine.Create(context.Background(), domainmemory.NewRecord{
|
||||
Scope: domainmemory.Scope{Kind: domainmemory.ScopeAgentUser, Agent: "archie", User: "alice"},
|
||||
Kind: "note",
|
||||
Content: "alice's secret project is codename phoenix",
|
||||
Author: "test",
|
||||
}); err != nil {
|
||||
t.Fatalf("Create() error = %v", err)
|
||||
}
|
||||
|
||||
if _, err := runner.Run(context.Background(), chatMsg("s1", "chat-bob", "bob", "hi"), nil); err != nil {
|
||||
t.Fatalf("Run() error = %v", err)
|
||||
}
|
||||
|
||||
prompt := lastSystemPrompt(prepared)
|
||||
if strings.Contains(prompt, "codename phoenix") {
|
||||
t.Fatalf("bob's prompt leaked alice's agent-user record, prompt = %q", prompt)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTurnMemoryScopeSharing is acceptance criterion 3: agent-scope records
|
||||
// are visible to both of that agent's users, a global record is visible to a
|
||||
// second agent, and an agent-user record is not shared.
|
||||
func TestTurnMemoryScopeSharing(t *testing.T) {
|
||||
engine := newMemoryTestEngine(t)
|
||||
ctx := context.Background()
|
||||
|
||||
if _, err := engine.Create(ctx, domainmemory.NewRecord{
|
||||
Scope: domainmemory.Scope{Kind: domainmemory.ScopeAgent, Agent: "archie"}, Kind: "note",
|
||||
Content: "agent-wide fact about archie", Author: "test",
|
||||
}); err != nil {
|
||||
t.Fatalf("Create(agent) error = %v", err)
|
||||
}
|
||||
if _, err := engine.Create(ctx, domainmemory.NewRecord{
|
||||
Scope: domainmemory.Scope{Kind: domainmemory.ScopeGlobal}, Kind: "note",
|
||||
Content: "global fact for every agent", Author: "test",
|
||||
}); err != nil {
|
||||
t.Fatalf("Create(global) error = %v", err)
|
||||
}
|
||||
if _, err := engine.Create(ctx, domainmemory.NewRecord{
|
||||
Scope: domainmemory.Scope{Kind: domainmemory.ScopeAgentUser, Agent: "archie", User: "alice"}, Kind: "note",
|
||||
Content: "relationship-only fact about alice and archie", Author: "test",
|
||||
}); err != nil {
|
||||
t.Fatalf("Create(agent-user) error = %v", err)
|
||||
}
|
||||
|
||||
// alice and bob both talk to archie: both see the agent-wide fact, only
|
||||
// alice sees the agent-user fact.
|
||||
archieRunner, archiePrepared := newMemoryTestRunner(t, engine, telegramIdentity, "archie")
|
||||
if _, err := archieRunner.Run(ctx, chatMsg("s-alice", "chat-alice", "alice", "hi"), nil); err != nil {
|
||||
t.Fatalf("Run(alice) error = %v", err)
|
||||
}
|
||||
alicePrompt := lastSystemPrompt(archiePrepared)
|
||||
if !strings.Contains(alicePrompt, "agent-wide fact about archie") {
|
||||
t.Fatalf("alice's prompt missing agent-wide fact, prompt = %q", alicePrompt)
|
||||
}
|
||||
if !strings.Contains(alicePrompt, "relationship-only fact about alice and archie") {
|
||||
t.Fatalf("alice's prompt missing her own agent-user fact, prompt = %q", alicePrompt)
|
||||
}
|
||||
|
||||
if _, err := archieRunner.Run(ctx, chatMsg("s-bob", "chat-bob", "bob", "hi"), nil); err != nil {
|
||||
t.Fatalf("Run(bob) error = %v", err)
|
||||
}
|
||||
bobPrompt := lastSystemPrompt(archiePrepared)
|
||||
if !strings.Contains(bobPrompt, "agent-wide fact about archie") {
|
||||
t.Fatalf("bob's prompt missing agent-wide fact, prompt = %q", bobPrompt)
|
||||
}
|
||||
if strings.Contains(bobPrompt, "relationship-only fact about alice and archie") {
|
||||
t.Fatalf("bob's prompt leaked alice's agent-user fact, prompt = %q", bobPrompt)
|
||||
}
|
||||
|
||||
// A second agent sees the global fact but not the first agent's
|
||||
// agent-scope fact.
|
||||
otherRunner, otherPrepared := newMemoryTestRunner(t, engine, telegramIdentity, "other-agent")
|
||||
if _, err := otherRunner.Run(ctx, chatMsg("s-carol", "chat-carol", "carol", "hi"), nil); err != nil {
|
||||
t.Fatalf("Run(other agent) error = %v", err)
|
||||
}
|
||||
otherPrompt := lastSystemPrompt(otherPrepared)
|
||||
if !strings.Contains(otherPrompt, "global fact for every agent") {
|
||||
t.Fatalf("second agent's prompt missing global fact, prompt = %q", otherPrompt)
|
||||
}
|
||||
if strings.Contains(otherPrompt, "agent-wide fact about archie") {
|
||||
t.Fatalf("second agent's prompt leaked the first agent's agent-scope fact, prompt = %q", otherPrompt)
|
||||
}
|
||||
}
|
||||
|
||||
// failingMemoryStore always errors.
|
||||
type failingMemoryStore struct{}
|
||||
|
||||
func (failingMemoryStore) Query(context.Context, domainmemory.Query) ([]domainmemory.Record, error) {
|
||||
return nil, errors.New("engine unavailable")
|
||||
}
|
||||
|
||||
// panickingMemoryStore always panics.
|
||||
type panickingMemoryStore struct{}
|
||||
|
||||
func (panickingMemoryStore) Query(context.Context, domainmemory.Query) ([]domainmemory.Record, error) {
|
||||
panic("boom")
|
||||
}
|
||||
|
||||
// TestTurnMemoryFailingEngineDegradesSilently is acceptance criterion 6 (the
|
||||
// failing half): a failing engine completes the turn with no memory block
|
||||
// and no surfaced error.
|
||||
func TestTurnMemoryFailingEngineDegradesSilently(t *testing.T) {
|
||||
runner, prepared := newMemoryTestRunner(t, failingMemoryStore{}, telegramIdentity, "archie")
|
||||
|
||||
reply, err := runner.Run(context.Background(), chatMsg("s1", "chat-1", "alice", "hi"), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Run() error = %v, want turn to complete despite the engine failure", err)
|
||||
}
|
||||
if reply != "ok" {
|
||||
t.Fatalf("reply = %q, want ok", reply)
|
||||
}
|
||||
if strings.Contains(lastSystemPrompt(prepared), "<memory ") {
|
||||
t.Fatalf("prompt has a memory block despite a failing engine, prompt = %q", lastSystemPrompt(prepared))
|
||||
}
|
||||
}
|
||||
|
||||
// TestTurnMemoryPanickingEngineDegradesSilently is acceptance criterion 6
|
||||
// (the panic half): a panicking engine/provider completes the turn with no
|
||||
// memory block and no surfaced error or crash.
|
||||
func TestTurnMemoryPanickingEngineDegradesSilently(t *testing.T) {
|
||||
runner, prepared := newMemoryTestRunner(t, panickingMemoryStore{}, telegramIdentity, "archie")
|
||||
|
||||
reply, err := runner.Run(context.Background(), chatMsg("s1", "chat-1", "alice", "hi"), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Run() error = %v, want turn to complete despite the engine panic", err)
|
||||
}
|
||||
if reply != "ok" {
|
||||
t.Fatalf("reply = %q, want ok", reply)
|
||||
}
|
||||
if strings.Contains(lastSystemPrompt(prepared), "<memory ") {
|
||||
t.Fatalf("prompt has a memory block despite a panicking engine, prompt = %q", lastSystemPrompt(prepared))
|
||||
}
|
||||
}
|
||||
|
||||
// TestTurnMemoryNoResolvableUserGetsGlobalAndAgentOnly is acceptance
|
||||
// criterion 7 (the fail-closed half): a channel whose UserIdentity resolver
|
||||
// is nil (the dashboard/"web" channel) renders only global and agent scopes,
|
||||
// never a user-scoped or agent-user record.
|
||||
func TestTurnMemoryNoResolvableUserGetsGlobalAndAgentOnly(t *testing.T) {
|
||||
engine := newMemoryTestEngine(t)
|
||||
ctx := context.Background()
|
||||
if _, err := engine.Create(ctx, domainmemory.NewRecord{
|
||||
Scope: domainmemory.Scope{Kind: domainmemory.ScopeAgent, Agent: "archie"}, Kind: "note",
|
||||
Content: "agent-scope fact", Author: "test",
|
||||
}); err != nil {
|
||||
t.Fatalf("Create(agent) error = %v", err)
|
||||
}
|
||||
if _, err := engine.Create(ctx, domainmemory.NewRecord{
|
||||
Scope: domainmemory.Scope{Kind: domainmemory.ScopeGlobal}, Kind: "note",
|
||||
Content: "global-scope fact", Author: "test",
|
||||
}); err != nil {
|
||||
t.Fatalf("Create(global) error = %v", err)
|
||||
}
|
||||
if _, err := engine.Create(ctx, domainmemory.NewRecord{
|
||||
Scope: domainmemory.Scope{Kind: domainmemory.ScopeUser, User: "webhook-user"}, Kind: "note",
|
||||
Content: "user-scope fact that must never leak to a resolverless channel", Author: "test",
|
||||
}); err != nil {
|
||||
t.Fatalf("Create(user) error = %v", err)
|
||||
}
|
||||
|
||||
// nil UserIdentity: exactly what the dashboard/"web" channel wires.
|
||||
runner, prepared := newMemoryTestRunner(t, engine, nil, "archie")
|
||||
msg := chatMsg("s1", "chat-1", "webhook-user", "hi")
|
||||
if _, err := runner.Run(ctx, msg, nil); err != nil {
|
||||
t.Fatalf("Run() error = %v", err)
|
||||
}
|
||||
prompt := lastSystemPrompt(prepared)
|
||||
if !strings.Contains(prompt, "agent-scope fact") || !strings.Contains(prompt, "global-scope fact") {
|
||||
t.Fatalf("prompt missing agent/global scope facts, prompt = %q", prompt)
|
||||
}
|
||||
if strings.Contains(prompt, "user-scope fact that must never leak") {
|
||||
t.Fatalf("prompt leaked a user-scope record despite no resolvable user identity, prompt = %q", prompt)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRenderMemoryRecordsCapsLoudly is acceptance criterion 8's read-side
|
||||
// analogue: a set of records whose rendering would exceed the byte cap is
|
||||
// bounded, not silently corrupted -- some records are dropped and a warning
|
||||
// is logged, rather than the block being cut off mid-line.
|
||||
func TestRenderMemoryRecordsCapsLoudly(t *testing.T) {
|
||||
var records []domainmemory.Record
|
||||
for i := range 500 {
|
||||
records = append(records, domainmemory.Record{
|
||||
ID: domainmemory.RecordID(fmt.Sprintf("rec-%d", i)),
|
||||
Scope: domainmemory.Scope{Kind: domainmemory.ScopeGlobal},
|
||||
Kind: "note",
|
||||
Content: strings.Repeat("x", 100),
|
||||
})
|
||||
}
|
||||
|
||||
var logged strings.Builder
|
||||
log := slog.New(slog.NewTextHandler(&logged, nil))
|
||||
got := renderMemoryRecords(records, log)
|
||||
|
||||
if len(got) > memoryBlockByteCap {
|
||||
t.Fatalf("rendered block = %d bytes, want <= %d", len(got), memoryBlockByteCap)
|
||||
}
|
||||
if !strings.Contains(logged.String(), "exceeded its render cap") {
|
||||
t.Fatalf("expected a loud log line on cap overflow, got %q", logged.String())
|
||||
}
|
||||
// Every rendered line must be complete: no record content cut off
|
||||
// mid-line, which would be silent corruption rather than a bounded drop.
|
||||
for line := range strings.SplitSeq(got, "\n") {
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
if !strings.HasSuffix(line, strings.Repeat("x", 100)) {
|
||||
t.Fatalf("rendered line looks truncated mid-record: %q", line)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestRenderMemoryNilStoreIsANoOp guards the nil-engine composition case
|
||||
// (setupMemoryEngine failed or was never reached): a nil MemoryEngine must
|
||||
// not panic prepareTurn.
|
||||
func TestRenderMemoryNilStoreIsANoOp(t *testing.T) {
|
||||
got := renderMemory(context.Background(), nil, domainmemory.Subject{AgentID: "archie"}, slog.New(slog.DiscardHandler))
|
||||
if got != "" {
|
||||
t.Fatalf("renderMemory(nil store) = %q, want empty", got)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user