fix(chat): operator name from config, session wiring, prompt rules

Three defects found from a real Telegram transcript.

1. The operator's name was compiled into the prompt.

internal/gateway/persona.go and prompt.go both hardcoded "Sam's" into the
default persona and the fallback prompt. The persona renders first into
every system prompt, so a personal name was sent to the model provider on
every turn, and any other deployment got an assistant that believed it
worked for someone else. There was nowhere to put it: Repo.Owner is a repo
owner and config.Config had no operator concept.

ChatConfig.Operator now carries it, rendered in the prompt's <env> block as
runtime metadata and omitted entirely when unset. config.example.toml
documents that setting it sends the name to the model provider.

2. /new claimed to clear history that it had not cleared.

The chat responder keyed history by channel id through a local sessionKey
helper, while the session commands operate on tracked session ids.
sessionTracker.resolve mints deterministic ids so the two agree -- until
/new, /branch or /resume assigns a generated id, after which they address
different histories permanently. /new reported "Conversation history has
been cleared" while the next turn still saw everything, and /undo,
/compress, /resume and /sessions acted on a namespace the conversation
never read.

gateway.Router.ResolveSessionKey already existed for this, and
session_commands.go:104 said outright that main.go should call it instead of
its inline helper. It never got wired. The responder now resolves through
the router and the dead helper is deleted so it cannot come back.

buildTelegramRouter constructs the router before the responder so the
dependency is visible rather than captured by reference.

3. Prompt rules for two behaviours the transcript showed.

The agent offered to accept shell access it has no tool to use, which is
both unhonourable and a request for the user's secrets. It also opened
mid-conversation replies with a greeting, and described its own manner
("no fluff") in stock phrasing. Added core rule 7 and three communication
rules covering greetings, self-description and register.

Note the memory claim in that transcript was NOT a fabrication: the
memory_edit tool's own description names MEMORY.md and USER.md, and tool
descriptions are part of the prompt.

Also added chat-turn logging (session id, channel, thread, history depth).
Chat turns were entirely unlogged, so a report of lost context had no
evidence to check: 76 log lines covered two days and none of them was a
conversation. A separate report of mid-conversation amnesia remains
undiagnosed -- single process, 43h uptime, compression untriggered at three
messages -- and this is what makes it diagnosable next time.

Regression tests: prompt renders/omits the operator and carries no personal
name; the responder resolves via ResolveSessionKey and defines no local
session key helper.

Verified: go build, go vet, gofmt clean; full suite passes.
This commit is contained in:
sam committed 2026-07-29 15:17:23 +10:00
1 parent 9d5040fd65
commit bf5a7618e6
9 files changed
+158 -17

No files matched your search

-7
View File
@@ -713,13 +713,6 @@ func parseListenAddr(addr, defaultHost string, defaultPort int) (string, int) {
// sessionKey builds a deterministic session identifier from a gateway
// message's routing fields. Platform + channel + thread uniquely identify
// a conversation for session persistence and history retrieval.
func sessionKey(msg gateway.Message) string {
if msg.ThreadID != "" {
return msg.ChannelID + ":" + msg.ThreadID
}
return msg.ChannelID
}
func executionProviders(cfg config.Config) map[string]agentexec.Provider {
return agentexec.ProvidersFromConfig(cfg.Providers)
}
+54
View File
@@ -0,0 +1,54 @@
package main
import (
"os"
"strings"
"testing"
)
// TestChatResponderResolvesSessionsThroughRouter guards the wiring that ties
// chat history to the session lifecycle commands.
//
// The responder must resolve a session through Router.ResolveSessionKey, which
// consults the session tracker. A local channel-keyed helper agrees with the
// tracker only until /new, /branch or /resume assigns a session a generated
// id; from then on the commands and the conversation address different
// histories, so /new reported "Conversation history has been cleared" while
// the next turn still saw every earlier message.
//
// This is asserted against the source, in the style of
// internal/tools/provider/contract_test.go, because the wiring is what
// matters and it has no return value to inspect.
func TestChatResponderResolvesSessionsThroughRouter(t *testing.T) {
t.Parallel()
source, err := os.ReadFile("telegram_setup.go")
if err != nil {
t.Fatalf("read telegram_setup.go: %v", err)
}
text := string(source)
if !strings.Contains(text, "router.ResolveSessionKey(ctx, msg)") {
t.Error("the chat responder must resolve sessions via router.ResolveSessionKey, " +
"so /new, /resume, /undo and /compress act on the history the conversation reads")
}
if strings.Contains(text, "sessionKey(msg)") {
t.Error("the chat responder must not key history by channel id directly; " +
"that bypasses the session tracker and desynchronises the session commands")
}
}
// TestNoInlineSessionKeyHelper keeps the removed helper from returning. It
// looked harmless and quietly reintroduced the split namespace.
func TestNoInlineSessionKeyHelper(t *testing.T) {
t.Parallel()
source, err := os.ReadFile("main.go")
if err != nil {
t.Fatalf("read main.go: %v", err)
}
if strings.Contains(string(source), "func sessionKey(") {
t.Error("main.go redefines a local sessionKey helper; " +
"gateway.Router.ResolveSessionKey is the single session resolver")
}
}
+27 -8
View File
@@ -128,24 +128,33 @@ func makeTelegramSessionStore(s telegramSetup) gateway.SessionStore {
}
func buildTelegramRouter(ctx context.Context, tg *telegram.Gateway, s telegramSetup, sessionStore gateway.SessionStore) *gateway.Router {
llmResponder, llmStream := makeTelegramLLMResponder(ctx, tg, s, sessionStore)
router := gateway.NewRouter(s.St, llmResponder, "telegram")
router.LLMStream = llmStream
// The router is built before the responder so the responder can resolve
// sessions through it. Both orderings work at runtime -- the responder is
// a closure -- but this way the dependency is visible rather than
// captured by reference.
router := gateway.NewRouter(s.St, nil, "telegram")
router.Models = s.ChatModels
router.InitSessions(sessionStore)
configureTaskCommands(router, s.ChatTasks, s.ChatController, s.DefaultChatIdentity)
router.LLM, router.LLMStream = makeTelegramLLMResponder(ctx, tg, s, sessionStore, router)
return router
}
func makeTelegramLLMResponder(ctx context.Context, tg *telegram.Gateway, s telegramSetup, sessionStore gateway.SessionStore) (gateway.LLMResponder, gateway.LLMStreamResponder) {
func makeTelegramLLMResponder(ctx context.Context, tg *telegram.Gateway, s telegramSetup, sessionStore gateway.SessionStore, router *gateway.Router) (gateway.LLMResponder, gateway.LLMStreamResponder) {
if s.LLM == nil {
return nil, nil
}
resolveSession := func(ctx context.Context, msg gateway.Message) string {
return sessionKey(msg)
}
respond := func(ctx context.Context, msg gateway.Message, onDelta func(string)) (string, error) {
sk := resolveSession(ctx, msg)
// Resolve through the router's session tracker, not a local
// channel-keyed helper. They agree until /new, /branch or /resume
// assigns a session a generated id; from then on the commands and
// the conversation address different histories, so /new would report
// history cleared while the next turn still saw all of it.
sk, err := router.ResolveSessionKey(ctx, msg)
if err != nil {
return "", fmt.Errorf("resolve chat session: %w", err)
}
if err := sessionStore.SaveMessage(ctx, sk, msg); err != nil {
return "", fmt.Errorf("save inbound chat message: %w", err)
}
@@ -153,6 +162,15 @@ func makeTelegramLLMResponder(ctx context.Context, tg *telegram.Gateway, s teleg
if err != nil {
return "", fmt.Errorf("load chat history: %w", err)
}
// Chat turns were entirely unlogged, so a report of lost context had
// no evidence to check against: session id, history depth and the
// resolved persona are the three things needed to tell "wrong
// session" from "history not loaded".
s.Log.Info("chat turn",
"session", sk,
"channel", msg.ChannelID,
"thread", msg.ThreadID,
"history_messages", len(history))
compressed := make([]gateway.CompressedMessage, 0, len(history))
for _, h := range history {
role := "user"
@@ -170,6 +188,7 @@ func makeTelegramLLMResponder(ctx context.Context, tg *telegram.Gateway, s teleg
systemPrompt := gateway.BuildSystemPrompt(gateway.SystemPromptConfig{
Persona: s.Personas.GetActive(sk), Tools: toolSummaries(options.Tools),
Channel: tg.Name(), Model: chatModel, SessionID: sk, Now: time.Now(),
Operator: s.Cfg.Chat.Operator,
})
view.Messages = append(
[]gateway.CompressedMessage{{Role: "system", Content: systemPrompt}}, view.Messages...,