fix(gateway): stamp the session platform from the channel that carried the message

One Router serves every channel and named itself "web", so Source.Platform -- the
FIRST component of the session natural key, and the platform GetByChannel filters
on -- was a constant, true of no channel but the dashboard. Two consequences
followed: the per-user identity policy was real code that no production call site
reached with a real channel name, and a curator pass's write to agent-user memory
could not be read back by the turn that wrote it, because that turn resolved no
UserID.

The channel now travels with the message. Frontends name the channel they carry
(pb.Message.platform: telegram, email, webhook, web), and the Gateway stamps the
session from it, falling back to its own name when a sender names none -- which is
what every existing row holds and what a frontend that does not participate keeps
doing.

Identity resolution reads the platform off the inbound rather than closing over a
channel name, so carriesPersonIdentity finally decides something in production:
telegram and email resolve a person, the dashboard and a webhook resolve nothing,
and an unknown platform fails closed.

Deliberately NOT changed, because it is where this could quietly widen scope:
TurnRunnerConfig.Channel still keys tool availability, so no channel gains or
loses a tool here. Only session lookup and identity follow the message's platform.

Consequence the maintainer accepted: a chat whose active session came from /new or
/branch re-resolves once, since GetByChannel now filters on the channel's name. A
chat with no /new re-resolves onto the same deterministic session id and heals
silently.

Verified: gateway, archied, gatewayrpc, messaging, webui, channels and cmd suites,
go vet ./..., go build ./..., golangci-lint run ./... (0 issues), docs:check.
New contracts: TestResolveSessionKeyStampsTheMessagesPlatform, the per-platform
identity table, and the transport-context wire round trip.
This commit is contained in:
sam committed 2026-09-22 04:30:15 +10:00
1 parent 84450ac96c
commit 3cdaba2509
18 files changed
+259 -108

No files matched your search

+32 -29
View File
@@ -5,42 +5,45 @@ import (
"github.com/samcharles93/archie-core/internal/domain/messaging" "github.com/samcharles93/archie-core/internal/domain/messaging"
) )
// userIdentityResolver returns the gateway.TurnRunnerConfig.UserIdentity // carriesPersonIdentity reports whether a platform's SenderID names a person,
// function for one channel, per docs/prds/memory-engine-unification.md §3: // per docs/prds/memory-engine-unification.md §3: resolution is supplied per
// resolution is supplied per channel by the composition, never inferred by // channel by the composition, never inferred by the engine or guessed from a
// the engine or guessed from a channel-neutral "channel:SenderID" // channel-neutral "channel:SenderID" concatenation.
// concatenation.
// //
// Telegram and email carry a native per-person sender id (a Telegram numeric // 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 // user id, an SMTP from address). The dashboard ("web") has one bearer token,
// token, not users, and a webhook carries no per-caller identity at all: its // not users, and a webhook carries no per-caller identity at all: its route path
// route path is a source, not a person, and never enters SenderID // is a source, not a person, and never enters SenderID
// (internal/channels/webhook/webhook.go -- it travels in the transport-only // (internal/channels/webhook/webhook.go -- it travels in the transport-only
// Inbound.BudgetKey instead). Treating a URL or a shared token as an // Inbound.BudgetKey instead). Treating a URL or a shared token as an identity
// identity would give it the same standing as a real user, which the read // would give it the same standing as a real user, which the read path's
// path's isolation guarantee depends on never happening. Both resolve // isolation guarantee depends on never happening.
// nothing, so a turn on either channel gets global and agent scopes only //
// (Subject.WritableScopes' fail-closed behaviour). // An unknown platform fails closed, so a channel added later gets global and
func userIdentityResolver(channel string) func(messaging.Message) (memory.IdentityID, bool) { // agent scopes only until someone decides deliberately that it carries people.
switch channel { func carriesPersonIdentity(platform string) bool {
switch platform {
case "telegram", "email": case "telegram", "email":
return senderIDIdentity return true
default: default:
return noUserIdentity return false
} }
} }
// senderIDIdentity resolves a channel's own SenderID as the user's identity. // userIdentityResolver is the composition's identity policy for a turn, keyed on
// Empty means the channel carries no per-person identity for this message. // the platform the message itself names rather than on the process that serves
func senderIDIdentity(msg messaging.Message) (memory.IdentityID, bool) { // it.
if msg.SenderID == "" { //
return "", false // It was closed over a single channel name, and one Gateway Router serves every
// channel, so that name was "web" even for a Telegram turn: the allowlist above
// was real code no production call site reached with a real channel name, and
// Subject.UserID was always empty (archie-core-c1qx). Reading the platform off
// the inbound is what makes the policy reachable.
func userIdentityResolver() func(messaging.Inbound) (memory.IdentityID, bool) {
return func(in messaging.Inbound) (memory.IdentityID, bool) {
if !carriesPersonIdentity(in.Platform) || in.Message.SenderID == "" {
return "", false
}
return memory.IdentityID(in.Message.SenderID), true
} }
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
} }
+31 -22
View File
@@ -8,23 +8,30 @@ import (
// TestWebhookUserIdentityNeverReturnsTheRoutePath guards // TestWebhookUserIdentityNeverReturnsTheRoutePath guards
// docs/prds/memory-engine-unification.md §3 and §4's specific webhook // docs/prds/memory-engine-unification.md §3 and §4's specific webhook
// requirement: internal/channels/webhook/webhook.go sets SenderID to the // requirement: internal/channels/webhook/webhook.go carries the configured route
// configured route path (RouteConfig.Path), and that must never surface as // path in Inbound.BudgetKey, never in SenderID, and no platform may turn one into
// a user identity, however plausible it looks as one. // a user identity however plausible it looks as one.
func TestWebhookUserIdentityNeverReturnsTheRoutePath(t *testing.T) { func TestWebhookUserIdentityNeverReturnsTheRoutePath(t *testing.T) {
resolver := userIdentityResolver("webhook") resolver := userIdentityResolver()
id, ok := resolver(messaging.Message{SenderID: "/github", Sender: "webhook"}) id, ok := resolver(messaging.Inbound{
Platform: "webhook",
Message: messaging.Message{SenderID: "/github", Sender: "webhook"},
})
if ok || id != "" { if ok || id != "" {
t.Fatalf("webhook resolver = (%q, %v), want (\"\", false)", id, ok) t.Fatalf("webhook resolver = (%q, %v), want (\"\", false)", id, ok)
} }
} }
// TestUserIdentityResolverPerChannel documents the composition's per-channel // TestUserIdentityResolverPerPlatform documents the composition's per-platform
// choice: telegram and email carry a native sender id, the dashboard ("web") // choice: telegram and email carry a native sender id, the dashboard ("web") and
// and webhook do not. // webhook do not, and a platform nobody has decided about fails closed.
func TestUserIdentityResolverPerChannel(t *testing.T) { //
// It is keyed on the message's platform rather than a resolver per channel,
// because one Gateway Router serves every channel: closing over a channel name
// resolved every turn as "web" (archie-core-c1qx).
func TestUserIdentityResolverPerPlatform(t *testing.T) {
tests := []struct { tests := []struct {
channel string platform string
senderID string senderID string
wantOK bool wantOK bool
}{ }{
@@ -33,28 +40,30 @@ func TestUserIdentityResolverPerChannel(t *testing.T) {
{"web", "anything", false}, {"web", "anything", false},
{"webhook", "/github", false}, {"webhook", "/github", false},
{"unknown-future-channel", "anything", false}, {"unknown-future-channel", "anything", false},
{"", "anything", false},
} }
resolver := userIdentityResolver()
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.channel, func(t *testing.T) { t.Run(tt.platform, func(t *testing.T) {
resolver := userIdentityResolver(tt.channel) id, ok := resolver(messaging.Inbound{Platform: tt.platform, Message: messaging.Message{SenderID: tt.senderID}})
id, ok := resolver(messaging.Message{SenderID: tt.senderID})
if ok != tt.wantOK { if ok != tt.wantOK {
t.Fatalf("%s resolver ok = %v, want %v", tt.channel, ok, tt.wantOK) t.Fatalf("%s resolver ok = %v, want %v", tt.platform, ok, tt.wantOK)
} }
if ok && string(id) != tt.senderID { if ok && string(id) != tt.senderID {
t.Fatalf("%s resolver id = %q, want %q", tt.channel, id, tt.senderID) t.Fatalf("%s resolver id = %q, want %q", tt.platform, id, tt.senderID)
} }
}) })
} }
} }
// TestSenderIDIdentityFailsClosedOnEmptySenderID guards §3's "fail closed": // TestUserIdentityResolverFailsClosedOnEmptySenderID guards §3's "fail closed":
// an empty SenderID (a channel that carries no per-caller id for this // an empty SenderID (a channel that carries no per-caller id for this particular
// particular message) must resolve to no identity, never an empty-string // message) must resolve to no identity, never an empty-string identity that
// identity that Subject would treat as present. // Subject would treat as present.
func TestSenderIDIdentityFailsClosedOnEmptySenderID(t *testing.T) { func TestUserIdentityResolverFailsClosedOnEmptySenderID(t *testing.T) {
id, ok := senderIDIdentity(messaging.Message{SenderID: ""}) resolver := userIdentityResolver()
id, ok := resolver(messaging.Inbound{Platform: "telegram", Message: messaging.Message{SenderID: ""}})
if ok || id != "" { if ok || id != "" {
t.Fatalf("senderIDIdentity(empty) = (%q, %v), want (\"\", false)", id, ok) t.Fatalf("telegram resolver with no sender id = (%q, %v), want (\"\", false)", id, ok)
} }
} }
+1 -1
View File
@@ -196,7 +196,7 @@ func newChatTurnRunner(
Repos: chatRepoEnv(cfg, s.DefaultChatIdentity), Repos: chatRepoEnv(cfg, s.DefaultChatIdentity),
MemoryEngine: s.MemoryEngine, MemoryEngine: s.MemoryEngine,
MemoryWriter: s.MemoryWriter, MemoryWriter: s.MemoryWriter,
UserIdentity: userIdentityResolver(channel), UserIdentity: userIdentityResolver(),
Log: s.Log, Log: s.Log,
}) })
if err := runner.Recover(ctx); err != nil && s.Log != nil { if err := runner.Recover(ctx); err != nil && s.Log != nil {
+12 -7
View File
@@ -201,13 +201,18 @@ func (g *Gateway) processMessage(ctx context.Context, from, to, raw string) {
// following Content-Type or headers. // following Content-Type or headers.
text := extractBody(raw) text := extractBody(raw)
msg := messaging.Inbound{Message: messaging.Message{ msg := messaging.Inbound{
ConversationID: messaging.ConversationID{ChannelID: to}, Message: messaging.Message{
Sender: from, ConversationID: messaging.ConversationID{ChannelID: to},
SenderID: from, Sender: from,
Role: messaging.RoleUser, SenderID: from,
Text: text, Role: messaging.RoleUser,
}} Text: text,
},
// The frontend names the channel it carries, which is how the Gateway
// learns it is serving email rather than whatever it calls itself.
Platform: "email",
}
reply, err := client.Route(ctx, msg) reply, err := client.Route(ctx, msg)
if err != nil { if err != nil {
g.log.Error("email route", "err", err, "from", from) g.log.Error("email route", "err", err, "from", from)
+3 -3
View File
@@ -412,7 +412,7 @@ func (g *Gateway) resumeHandler(client messaging.ChatContract) bot.HandlerFunc {
if !ok { if !ok {
return return
} }
reply, err := client.Route(ctx, messaging.Inbound{Message: messaging.Message{ reply, err := client.Route(ctx, messaging.Inbound{Platform: "telegram", Message: messaging.Message{
ConversationID: conversationID(msg), ConversationID: conversationID(msg),
Sender: msg.From.Username, Sender: msg.From.Username,
Role: messaging.RoleUser, Role: messaging.RoleUser,
@@ -434,7 +434,7 @@ func (g *Gateway) routeCmdHandler(client messaging.ChatContract, cmd string) bot
if !ok { if !ok {
return return
} }
reply, err := client.Route(ctx, messaging.Inbound{Message: messaging.Message{ reply, err := client.Route(ctx, messaging.Inbound{Platform: "telegram", Message: messaging.Message{
ConversationID: conversationID(msg), ConversationID: conversationID(msg),
Sender: msg.From.Username, Sender: msg.From.Username,
Role: messaging.RoleUser, Role: messaging.RoleUser,
@@ -565,7 +565,7 @@ func (g *Gateway) handleCallback(ctx context.Context, b *bot.Bot, update *models
// /stop meant to cancel it, which would sit unread until the turn it was // /stop meant to cancel it, which would sit unread until the turn it was
// aimed at had already finished. // aimed at had already finished.
func (g *Gateway) submitTurn(ctx context.Context, b *bot.Bot, msg *models.Message, client messaging.ChatContract) { func (g *Gateway) submitTurn(ctx context.Context, b *bot.Bot, msg *models.Message, client messaging.ChatContract) {
gm := messaging.Inbound{Message: messaging.Message{ gm := messaging.Inbound{Platform: "telegram", Message: messaging.Message{
// Telegram's message ID makes persistence idempotent: the store // Telegram's message ID makes persistence idempotent: the store
// derives a canonical ID from it, so a redelivered update is a // derives a canonical ID from it, so a redelivered update is a
// no-op rather than appending a duplicate or overwriting the // no-op rather than appending a duplicate or overwriting the
+1
View File
@@ -186,6 +186,7 @@ func (g *Gateway) handleWebhook(route *RouteConfig) http.HandlerFunc {
// limiting, so it travels in the transport-only BudgetKey // limiting, so it travels in the transport-only BudgetKey
// rather than borrowing the identity field. // rather than borrowing the identity field.
BudgetKey: route.Path, BudgetKey: route.Path,
Platform: "webhook",
} }
reply, err := client.Route(r.Context(), msg) reply, err := client.Route(r.Context(), msg)
if err != nil { if err != nil {
+19 -3
View File
@@ -154,7 +154,14 @@ type Message struct {
// -- a webhook's configured route path. Transport-only: a channel frontend // -- a webhook's configured route path. Transport-only: a channel frontend
// sets it on inbound and it is never persisted, exactly like page. Empty // sets it on inbound and it is never persisted, exactly like page. Empty
// means the message is not rate limited. // means the message is not rate limited.
BudgetKey string `protobuf:"bytes,9,opt,name=budget_key,json=budgetKey,proto3" json:"budget_key,omitempty"` BudgetKey string `protobuf:"bytes,9,opt,name=budget_key,json=budgetKey,proto3" json:"budget_key,omitempty"`
// platform is the channel that carried this message ("telegram", "email",
// "webhook", "web"), as the frontend that owns that channel knows it. It is
// how the Gateway learns which channel it is serving: one Router serves every
// channel, so its own name is "web" even for a Telegram turn, which made
// Source.Platform -- the first component of the session natural key -- a
// constant. Transport-only, never persisted: the session record keeps it.
Platform string `protobuf:"bytes,10,opt,name=platform,proto3" json:"platform,omitempty"`
unknownFields protoimpl.UnknownFields unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache sizeCache protoimpl.SizeCache
} }
@@ -252,6 +259,13 @@ func (x *Message) GetBudgetKey() string {
return "" return ""
} }
func (x *Message) GetPlatform() string {
if x != nil {
return x.Platform
}
return ""
}
type ToolCall struct { type ToolCall struct {
state protoimpl.MessageState `protogen:"open.v1"` state protoimpl.MessageState `protogen:"open.v1"`
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
@@ -2772,7 +2786,7 @@ const file_gateway_v1_chat_proto_rawDesc = "" +
"\n" + "\n" +
"created_at\x18\t \x01(\v2\x1a.google.protobuf.TimestampR\tcreatedAt\x12@\n" + "created_at\x18\t \x01(\v2\x1a.google.protobuf.TimestampR\tcreatedAt\x12@\n" +
"\x0elast_active_at\x18\n" + "\x0elast_active_at\x18\n" +
" \x01(\v2\x1a.google.protobuf.TimestampR\flastActiveAt\"\x88\x02\n" + " \x01(\v2\x1a.google.protobuf.TimestampR\flastActiveAt\"\xa4\x02\n" +
"\aMessage\x12\x1d\n" + "\aMessage\x12\x1d\n" +
"\n" + "\n" +
"message_id\x18\x01 \x01(\tR\tmessageId\x12\x1b\n" + "message_id\x18\x01 \x01(\tR\tmessageId\x12\x1b\n" +
@@ -2785,7 +2799,9 @@ const file_gateway_v1_chat_proto_rawDesc = "" +
"\x04page\x18\a \x01(\tR\x04page\x12*\n" + "\x04page\x18\a \x01(\tR\x04page\x12*\n" +
"\x02at\x18\b \x01(\v2\x1a.google.protobuf.TimestampR\x02at\x12\x1d\n" + "\x02at\x18\b \x01(\v2\x1a.google.protobuf.TimestampR\x02at\x12\x1d\n" +
"\n" + "\n" +
"budget_key\x18\t \x01(\tR\tbudgetKey\"|\n" + "budget_key\x18\t \x01(\tR\tbudgetKey\x12\x1a\n" +
"\bplatform\x18\n" +
" \x01(\tR\bplatform\"|\n" +
"\bToolCall\x12\x0e\n" + "\bToolCall\x12\x0e\n" +
"\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" + "\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" +
"\x04name\x18\x02 \x01(\tR\x04name\x12\x1e\n" + "\x04name\x18\x02 \x01(\tR\x04name\x12\x1e\n" +
+11
View File
@@ -35,6 +35,17 @@ type Inbound struct {
// rate limited, which is correct for a source with no stable key of // rate limited, which is correct for a source with no stable key of
// its own (the dashboard). // its own (the dashboard).
BudgetKey string BudgetKey string
// Platform is the channel that carried this message ("telegram",
// "email", "webhook", "web"), named by the frontend that owns that
// channel. It is how the Gateway learns which channel it is serving:
// one Router serves all of them, so its own name is "web" even for a
// Telegram turn, which made SessionSource.Platform -- the first
// component of the session natural key -- a constant, and left the
// per-user identity policy unreachable with a real channel name
// (archie-core-c1qx). Transport-only and never persisted: the session
// record keeps the platform. Empty means the sender did not name its
// channel, and the Gateway falls back to its own name.
Platform string
} }
// SpawnRequest is a chat-originated task creation request. Repo and // SpawnRequest is a chat-originated task creation request. Repo and
+9 -9
View File
@@ -282,7 +282,7 @@ func (r *Router) route(ctx context.Context, in Inbound) (string, error) {
text := strings.TrimSpace(in.Message.Text) text := strings.TrimSpace(in.Message.Text)
cmd, _ := parseCmd(text, r.gatewayName) cmd, _ := parseCmd(text, r.gatewayName)
if reply, handled, err := r.dispatchLocal(ctx, in.Message, text, cmd); handled { if reply, handled, err := r.dispatchLocal(ctx, in.Message, r.sessionPlatform(in), text, cmd); handled {
return reply, err return reply, err
} }
@@ -301,7 +301,7 @@ func (r *Router) route(ctx context.Context, in Inbound) (string, error) {
// dispatchLocal handles recognized local commands. Returns (reply, // dispatchLocal handles recognized local commands. Returns (reply,
// true) when the command was recognized and handled. // true) when the command was recognized and handled.
func (r *Router) dispatchLocal(ctx context.Context, msg messaging.Message, text, cmd string) (string, bool, error) { func (r *Router) dispatchLocal(ctx context.Context, msg messaging.Message, platform, text, cmd string) (string, bool, error) {
rest := restAfter(text, cmd, r.gatewayName) rest := restAfter(text, cmd, r.gatewayName)
switch cmd { switch cmd {
@@ -336,13 +336,13 @@ func (r *Router) dispatchLocal(ctx context.Context, msg messaging.Message, text,
reply, err := r.handleProfile() reply, err := r.handleProfile()
return reply, true, err return reply, true, err
} }
return r.dispatchLocalMisc(ctx, msg, cmd, rest) return r.dispatchLocalMisc(ctx, msg, platform, cmd, rest)
} }
// dispatchLocalMisc handles the remaining recognized local commands not // dispatchLocalMisc handles the remaining recognized local commands not
// covered by dispatchLocal's first switch. Split out to keep cyclomatic // covered by dispatchLocal's first switch. Split out to keep cyclomatic
// complexity down. // complexity down.
func (r *Router) dispatchLocalMisc(ctx context.Context, msg messaging.Message, cmd, rest string) (string, bool, error) { func (r *Router) dispatchLocalMisc(ctx context.Context, msg messaging.Message, platform, cmd, rest string) (string, bool, error) {
switch cmd { switch cmd {
case "/sessions": case "/sessions":
reply, err := r.handleSessions(ctx, msg) reply, err := r.handleSessions(ctx, msg)
@@ -365,7 +365,7 @@ func (r *Router) dispatchLocalMisc(ctx context.Context, msg messaging.Message, c
case "/restart": case "/restart":
return r.handleRestartAdapter(ctx), true, nil return r.handleRestartAdapter(ctx), true, nil
} }
return r.dispatchSessionCommand(ctx, msg, cmd, rest) return r.dispatchSessionCommand(ctx, msg, platform, cmd, rest)
} }
// handleVersion reports the configured build version. // handleVersion reports the configured build version.
@@ -403,13 +403,13 @@ func (r *Router) handleRestartAdapter(ctx context.Context) string {
// (/new, /topic, /retry, /undo, /title, /branch, /compress and their // (/new, /topic, /retry, /undo, /title, /branch, /compress and their
// aliases). Split out from dispatchLocal to keep cyclomatic complexity // aliases). Split out from dispatchLocal to keep cyclomatic complexity
// down. // down.
func (r *Router) dispatchSessionCommand(ctx context.Context, msg messaging.Message, cmd, rest string) (string, bool, error) { func (r *Router) dispatchSessionCommand(ctx context.Context, msg messaging.Message, platform, cmd, rest string) (string, bool, error) {
switch cmd { switch cmd {
case "/new", "/reset": case "/new", "/reset":
reply, err := r.handleNew(ctx, msg, rest) reply, err := r.handleNew(ctx, msg, platform, rest)
return reply, true, err return reply, true, err
case "/topic": case "/topic":
reply, err := r.handleTopic(ctx, msg, rest) reply, err := r.handleTopic(ctx, msg, platform, rest)
return reply, true, err return reply, true, err
case "/retry": case "/retry":
reply, err := r.handleRetry(ctx, msg) reply, err := r.handleRetry(ctx, msg)
@@ -421,7 +421,7 @@ func (r *Router) dispatchSessionCommand(ctx context.Context, msg messaging.Messa
reply, err := r.handleTitle(ctx, msg, rest) reply, err := r.handleTitle(ctx, msg, rest)
return reply, true, err return reply, true, err
case "/branch", "/fork": case "/branch", "/fork":
reply, err := r.handleBranch(ctx, msg, rest) reply, err := r.handleBranch(ctx, msg, platform, rest)
return reply, true, err return reply, true, err
case "/compress", "/compact": case "/compress", "/compact":
reply, err := r.handleCompress(ctx, msg, rest) reply, err := r.handleCompress(ctx, msg, rest)
+25 -12
View File
@@ -264,6 +264,19 @@ func sessionTrackerKey(channelID, threadID string) string {
return channelID + ":" + threadID return channelID + ":" + threadID
} }
// sessionPlatform is the platform a session for this inbound belongs to: the
// channel that carried the message when the frontend named itself, else the
// Gateway's own name. Naming it is what makes SessionSource.Platform truthful --
// one Router serves every channel, so its own name is "web" even for a Telegram
// turn, which made the platform a constant and left the per-user identity policy
// unreachable with a real channel name (archie-core-c1qx).
func (r *Router) sessionPlatform(in Inbound) string {
if in.Platform != "" {
return in.Platform
}
return r.gatewayName
}
// ResolveSessionKey resolves or creates a session for a message and // ResolveSessionKey resolves or creates a session for a message and
// returns the session ID. This is the entry point the LLM responder // returns the session ID. This is the entry point the LLM responder
// in main.go should call instead of its inline sessionKey helper. // in main.go should call instead of its inline sessionKey helper.
@@ -272,7 +285,7 @@ func (r *Router) ResolveSessionKey(ctx context.Context, in Inbound) (string, err
if r.sessionTracker == nil { if r.sessionTracker == nil {
return sessionKeyFromFields(conv.ChannelID, conv.ThreadID), nil return sessionKeyFromFields(conv.ChannelID, conv.ThreadID), nil
} }
return r.sessionTracker.resolve(ctx, r.gatewayName, r.Identity, conv.ChannelID, conv.ThreadID) return r.sessionTracker.resolve(ctx, r.sessionPlatform(in), r.Identity, conv.ChannelID, conv.ThreadID)
} }
// ── Router session command handlers ──────────────────────────────────────── // ── Router session command handlers ────────────────────────────────────────
@@ -284,7 +297,7 @@ func (r *Router) handleStart() (string, error) {
// handleNew creates a fresh session for the current channel+thread, // handleNew creates a fresh session for the current channel+thread,
// optionally setting a title. // optionally setting a title.
func (r *Router) handleNew(ctx context.Context, msg messaging.Message, rest string) (string, error) { func (r *Router) handleNew(ctx context.Context, msg messaging.Message, platform, rest string) (string, error) {
if r.sessionTracker == nil { if r.sessionTracker == nil {
return "Session management is not configured.", nil return "Session management is not configured.", nil
} }
@@ -296,7 +309,7 @@ func (r *Router) handleNew(ctx context.Context, msg messaging.Message, rest stri
sc := SessionContext{ sc := SessionContext{
SessionID: id, SessionID: id,
Source: SessionSource{ Source: SessionSource{
Platform: r.gatewayName, Platform: platform,
BotUser: r.Identity, BotUser: r.Identity,
ChannelID: msg.ConversationID.ChannelID, ChannelID: msg.ConversationID.ChannelID,
ThreadID: msg.ConversationID.ThreadID, ThreadID: msg.ConversationID.ThreadID,
@@ -319,7 +332,7 @@ func (r *Router) handleNew(ctx context.Context, msg messaging.Message, rest stri
// handleTopic manages topic/session switching for threaded conversations. // handleTopic manages topic/session switching for threaded conversations.
// "off" disables topic routing (reverts to flat), "help" shows info, // "off" disables topic routing (reverts to flat), "help" shows info,
// and a session-id switches to that session. // and a session-id switches to that session.
func (r *Router) handleTopic(ctx context.Context, msg messaging.Message, rest string) (string, error) { func (r *Router) handleTopic(ctx context.Context, msg messaging.Message, platform, rest string) (string, error) {
if r.sessionTracker == nil { if r.sessionTracker == nil {
return "Session management is not configured.", nil return "Session management is not configured.", nil
} }
@@ -331,9 +344,9 @@ func (r *Router) handleTopic(ctx context.Context, msg messaging.Message, rest st
case "help": case "help":
return topicHelpText(), nil return topicHelpText(), nil
case "": case "":
return r.topicListSessions(ctx, msg) return r.topicListSessions(ctx, msg, platform)
default: default:
return r.topicSwitchSession(ctx, msg, rest) return r.topicSwitchSession(ctx, msg, platform, rest)
} }
} }
@@ -344,9 +357,9 @@ func topicHelpText() string {
" <session-id> — switch to a session by the ID shown in /topic" " <session-id> — switch to a session by the ID shown in /topic"
} }
func (r *Router) topicListSessions(ctx context.Context, msg messaging.Message) (string, error) { func (r *Router) topicListSessions(ctx context.Context, msg messaging.Message, platform string) (string, error) {
active := r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID) active := r.sessionTracker.getActive(msg.ConversationID.ChannelID, msg.ConversationID.ThreadID)
sessions, err := r.sessionTracker.sessions.GetByChannel(ctx, r.gatewayName, msg.ConversationID.ChannelID) sessions, err := r.sessionTracker.sessions.GetByChannel(ctx, platform, msg.ConversationID.ChannelID)
if err != nil { if err != nil {
return "", fmt.Errorf("list sessions: %w", err) return "", fmt.Errorf("list sessions: %w", err)
} }
@@ -367,8 +380,8 @@ func (r *Router) topicListSessions(ctx context.Context, msg messaging.Message) (
return b.String(), nil return b.String(), nil
} }
func (r *Router) topicSwitchSession(ctx context.Context, msg messaging.Message, rest string) (string, error) { func (r *Router) topicSwitchSession(ctx context.Context, msg messaging.Message, platform, rest string) (string, error) {
sessions, err := r.sessionTracker.sessions.GetByChannel(ctx, r.gatewayName, msg.ConversationID.ChannelID) sessions, err := r.sessionTracker.sessions.GetByChannel(ctx, platform, msg.ConversationID.ChannelID)
if err != nil { if err != nil {
return "", fmt.Errorf("list sessions: %w", err) return "", fmt.Errorf("list sessions: %w", err)
} }
@@ -507,7 +520,7 @@ func (r *Router) handleTitle(ctx context.Context, msg messaging.Message, rest st
// handleBranch creates a new child session that inherits the current // handleBranch creates a new child session that inherits the current
// session's history. The new session becomes the active session. // session's history. The new session becomes the active session.
func (r *Router) handleBranch(ctx context.Context, msg messaging.Message, rest string) (string, error) { func (r *Router) handleBranch(ctx context.Context, msg messaging.Message, platform, rest string) (string, error) {
if r.sessionTracker == nil { if r.sessionTracker == nil {
return "Session management is not configured.", nil return "Session management is not configured.", nil
} }
@@ -545,7 +558,7 @@ func (r *Router) handleBranch(ctx context.Context, msg messaging.Message, rest s
sc := SessionContext{ sc := SessionContext{
SessionID: id, SessionID: id,
Source: SessionSource{ Source: SessionSource{
Platform: r.gatewayName, Platform: platform,
BotUser: r.Identity, BotUser: r.Identity,
ChannelID: channelID, ChannelID: channelID,
ThreadID: threadID, ThreadID: threadID,
+72
View File
@@ -0,0 +1,72 @@
package gateway
import (
"context"
"testing"
"github.com/samcharles93/archie-core/internal/domain/messaging"
)
// TestResolveSessionKeyStampsTheMessagesPlatform is archie-core-c1qx's contract:
// a session's platform is the channel that carried the message, not the
// Gateway's own name. One Router serves every channel, so its own name is "web"
// even for a Telegram turn, which made Source.Platform -- the first component of
// the session natural key -- a constant, and left the per-user identity policy
// unreachable with a real channel name.
func TestResolveSessionKeyStampsTheMessagesPlatform(t *testing.T) {
store := NewSessionStoreMemory()
t.Cleanup(func() { _ = store.Close() })
router := NewRouter(nil, nil, "web")
router.Identity = "archie"
router.InitSessions(store)
ctx := context.Background()
telegram := Inbound{Platform: "telegram", Message: messaging.Message{
ConversationID: messaging.ConversationID{ChannelID: "-100123"},
SenderID: "42",
Role: messaging.RoleUser,
Text: "hello",
}}
id, err := router.ResolveSessionKey(ctx, telegram)
if err != nil {
t.Fatalf("ResolveSessionKey: %v", err)
}
session, err := store.Get(ctx, id)
if err != nil {
t.Fatalf("Get: %v", err)
}
if session.Source.Platform != "telegram" {
t.Errorf("Source.Platform = %q, want %q: the channel that carried the message, not the Gateway's own name",
session.Source.Platform, "telegram")
}
// The platform is the first component of the session lookup key, so a lookup
// under the channel's name is what a later message in the same chat resolves
// through. Under the Gateway's name it would miss and start a second session.
found, err := store.GetByChannel(ctx, "telegram", "-100123")
if err != nil {
t.Fatalf("GetByChannel: %v", err)
}
if len(found) != 1 || found[0].SessionID != id {
t.Errorf("GetByChannel(telegram, -100123) = %+v, want the session just resolved", found)
}
// A frontend that does not name its channel keeps the Gateway's own name,
// which is the behaviour every existing session row has.
plain := Inbound{Message: messaging.Message{
ConversationID: messaging.ConversationID{ChannelID: "-100999"},
Role: messaging.RoleUser,
Text: "no platform",
}}
plainID, err := router.ResolveSessionKey(ctx, plain)
if err != nil {
t.Fatalf("ResolveSessionKey(no platform): %v", err)
}
plainSession, err := store.Get(ctx, plainID)
if err != nil {
t.Fatalf("Get: %v", err)
}
if plainSession.Source.Platform != "web" {
t.Errorf("Source.Platform = %q, want the Gateway's own name %q when the sender names none",
plainSession.Source.Platform, "web")
}
}
+13 -8
View File
@@ -110,12 +110,17 @@ type TurnRunnerConfig struct {
// same as a subject with no writable scope: no tools registered). // same as a subject with no writable scope: no tools registered).
MemoryWriter MemoryWriteStore MemoryWriter MemoryWriteStore
// UserIdentity resolves the initiating user's identity for one inbound // UserIdentity resolves the initiating user's identity for one inbound
// message, per channel. False (or a nil UserIdentity) means the channel // message, per platform. It reads the platform off the inbound rather than
// carries no per-person identity -- the dashboard's one bearer token, or a // closing over one, because a single Router serves every channel: a resolver
// webhook's route path, which must never be treated as a person -- and // bound to a channel name received "web" for a Telegram turn, which left
// the turn's memory Subject gets no UserID, so its read is agent and // Subject.UserID always empty in production (archie-core-c1qx).
// global scope only (docs/prds/memory-engine-unification.md §3, §4). //
UserIdentity func(msg messaging.Message) (memory.IdentityID, bool) // False (or a nil UserIdentity) means the platform carries no per-person
// identity -- the dashboard's one bearer token, or a webhook 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(in Inbound) (memory.IdentityID, bool)
} }
// TurnRunner owns one chat turn from session resolution through model // TurnRunner owns one chat turn from session resolution through model
@@ -304,10 +309,10 @@ type preparedTurn struct {
// runs the session-level compression trigger, since that needs the same // runs the session-level compression trigger, since that needs the same
// model-derived budget the view is built against. // model-derived budget the view is built against.
func (r *TurnRunner) prepareTurn(ctx context.Context, sessionID string, in Inbound, history []messaging.Message) (preparedTurn, error) { func (r *TurnRunner) prepareTurn(ctx context.Context, sessionID string, in Inbound, history []messaging.Message) (preparedTurn, error) {
subject := r.resolveSubject(in.Message) subject := r.resolveSubject(in)
extraTools := append( extraTools := append(
TaskTools(r.TaskLister, r.Tasks, r.TaskLogs, r.TaskActor, r.TaskIdentity), TaskTools(r.TaskLister, r.Tasks, r.TaskLogs, r.TaskActor, r.TaskIdentity),
SessionTools(r.Sessions, r.Router.SessionTracker(), r.Channel, in.Message)..., SessionTools(r.Sessions, r.Router.SessionTracker(), r.Router.sessionPlatform(in), in.Message)...,
) )
extraTools = append(extraTools, ReviewTools(r.PRReviewer, r.TaskIdentity)...) extraTools = append(extraTools, ReviewTools(r.PRReviewer, r.TaskIdentity)...)
// The dashboard tools (page_index, dashboard_navigate) belong to the web // The dashboard tools (page_index, dashboard_navigate) belong to the web
+6 -4
View File
@@ -7,7 +7,6 @@ import (
"strings" "strings"
domainmemory "github.com/samcharles93/archie-core/internal/domain/memory" 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 // memoryRecordsPerScope bounds how many records of each scope the read path
@@ -113,16 +112,19 @@ func renderMemoryRecords(records []domainmemory.Record, log *slog.Logger) string
// resolveSubject builds a turn's memory Subject from the runner's agent // 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 // identity (BotUser, the closest thing to an Agent id the tree records today
// -- see sessioncurator.Adapter) and the channel's UserIdentity resolver. A // -- see sessioncurator.Adapter) and the session's UserIdentity resolver. A
// nil resolver, or one that returns false, yields UserID "" -- Subject.Scopes // nil resolver, or one that returns false, yields UserID "" -- Subject.Scopes
// then names only agent and global, never a wider fallback // then names only agent and global, never a wider fallback
// (docs/prds/memory-engine-unification.md §3, "fail closed"). // (docs/prds/memory-engine-unification.md §3, "fail closed").
func (r *TurnRunner) resolveSubject(msg messaging.Message) domainmemory.Subject { //
// It takes the whole inbound rather than its message because the resolver needs
// the platform the message arrived on (archie-core-c1qx).
func (r *TurnRunner) resolveSubject(in Inbound) domainmemory.Subject {
subject := domainmemory.Subject{AgentID: domainmemory.AgentID(r.BotUser)} subject := domainmemory.Subject{AgentID: domainmemory.AgentID(r.BotUser)}
if r.UserIdentity == nil { if r.UserIdentity == nil {
return subject return subject
} }
if id, ok := r.UserIdentity(msg); ok { if id, ok := r.UserIdentity(in); ok {
subject.UserID = id subject.UserID = id
} }
return subject return subject
+4 -4
View File
@@ -20,11 +20,11 @@ func newMemoryTestEngine(t *testing.T) *infraMemory.BuiltinEngine {
return infraMemory.NewBuiltinEngine(t.TempDir(), 0) return infraMemory.NewBuiltinEngine(t.TempDir(), 0)
} }
func telegramIdentity(msg messaging.Message) (domainmemory.IdentityID, bool) { func telegramIdentity(in Inbound) (domainmemory.IdentityID, bool) {
if msg.SenderID == "" { if in.Message.SenderID == "" {
return "", false return "", false
} }
return domainmemory.IdentityID(msg.SenderID), true return domainmemory.IdentityID(in.Message.SenderID), true
} }
func chatMsg(sourceID, channelID, senderID, text string) Inbound { func chatMsg(sourceID, channelID, senderID, text string) Inbound {
@@ -38,7 +38,7 @@ func chatMsg(sourceID, channelID, senderID, text string) Inbound {
}} }}
} }
func newMemoryTestRunner(t *testing.T, engine MemoryStore, userIdentity func(messaging.Message) (domainmemory.IdentityID, bool), botUser string) (*TurnRunner, *turnTestPreparedModel) { func newMemoryTestRunner(t *testing.T, engine MemoryStore, userIdentity func(Inbound) (domainmemory.IdentityID, bool), botUser string) (*TurnRunner, *turnTestPreparedModel) {
t.Helper() t.Helper()
store := NewSessionStoreMemory() store := NewSessionStoreMemory()
router := NewRouter(nil, nil, "telegram") router := NewRouter(nil, nil, "telegram")
@@ -117,13 +117,16 @@ func TestWireValuesPreserveHistoryAndMedia(t *testing.T) {
t.Fatalf("event round trip: %+v", got) t.Fatalf("event round trip: %+v", got)
} }
// Transport-only inbound context rides alongside the record and must // Transport-only inbound context rides alongside the record and must
// survive the hop: Page reaches the system prompt, and BudgetKey is what // survive the hop: Page reaches the system prompt, BudgetKey is what the
// the Gateway charges the message against when the channel has no // Gateway charges the message against when the channel has no per-person
// per-person SenderID to charge (a webhook route). // SenderID to charge (a webhook route), and Platform is how the Gateway
// learns which channel it is serving -- one Router serves all of them
// (archie-core-c1qx).
in := gateway.Inbound{ in := gateway.Inbound{
Message: messaging.Message{ConversationID: messaging.ConversationID{ChannelID: "/hook"}, Role: messaging.RoleUser, Text: "hi"}, Message: messaging.Message{ConversationID: messaging.ConversationID{ChannelID: "/hook"}, Role: messaging.RoleUser, Text: "hi"},
Page: "/tasks", Page: "/tasks",
BudgetKey: "/hook", BudgetKey: "/hook",
Platform: "webhook",
} }
if got := inboundValue(inboundProto(in)); !reflect.DeepEqual(got, in) { if got := inboundValue(inboundProto(in)); !reflect.DeepEqual(got, in) {
t.Fatalf("inbound round trip = %+v, want %+v", got, in) t.Fatalf("inbound round trip = %+v, want %+v", got, in)
+4 -3
View File
@@ -55,12 +55,13 @@ func storedValue(v *pb.Message) messaging.Message {
} }
// inboundProto renders a channel message and its transport context in wire // inboundProto renders a channel message and its transport context in wire
// shape. Page and BudgetKey ride along; the record's role does not, for the // shape. Page, BudgetKey and Platform ride along; the record's role does not, for
// reason storedProto gives. // the reason storedProto gives.
func inboundProto(v messaging.Inbound) *pb.Message { func inboundProto(v messaging.Inbound) *pb.Message {
m := storedProto(v.Message) m := storedProto(v.Message)
m.Page = v.Page m.Page = v.Page
m.BudgetKey = v.BudgetKey m.BudgetKey = v.BudgetKey
m.Platform = v.Platform
return m return m
} }
@@ -74,7 +75,7 @@ func inboundValue(v *pb.Message) messaging.Inbound {
} }
msg := storedValue(v) msg := storedValue(v)
msg.Role = messaging.RoleUser msg.Role = messaging.RoleUser
return messaging.Inbound{Message: msg, Page: v.Page, BudgetKey: v.BudgetKey} return messaging.Inbound{Message: msg, Page: v.Page, BudgetKey: v.BudgetKey, Platform: v.Platform}
} }
func toolProto(v messaging.ToolCallEvent) *pb.ToolCall { func toolProto(v messaging.ToolCallEvent) *pb.ToolCall {
+3
View File
@@ -258,6 +258,9 @@ func (s *Server) decodeChatMessage(w http.ResponseWriter, r *http.Request) (mess
Text: req.Text, Text: req.Text,
}, },
Page: req.Page, Page: req.Page,
// The dashboard names the channel it carries; see the platform field's
// note in internal/domain/messaging/inbound.go.
Platform: "web",
}, true }, true
} }
+7
View File
@@ -56,6 +56,13 @@ message Message {
// sets it on inbound and it is never persisted, exactly like page. Empty // sets it on inbound and it is never persisted, exactly like page. Empty
// means the message is not rate limited. // means the message is not rate limited.
string budget_key = 9; string budget_key = 9;
// platform is the channel that carried this message ("telegram", "email",
// "webhook", "web"), as the frontend that owns that channel knows it. It is
// how the Gateway learns which channel it is serving: one Router serves every
// channel, so its own name is "web" even for a Telegram turn, which made
// Source.Platform -- the first component of the session natural key -- a
// constant. Transport-only, never persisted: the session record keeps it.
string platform = 10;
} }
message ToolCall { message ToolCall {
string id = 1; string id = 1;