diff --git a/cmd/archied/main.go b/cmd/archied/main.go index 90fdd3168..edfb95477 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -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) } diff --git a/cmd/archied/session_wiring_test.go b/cmd/archied/session_wiring_test.go new file mode 100644 index 000000000..659846aca --- /dev/null +++ b/cmd/archied/session_wiring_test.go @@ -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") + } +} diff --git a/cmd/archied/telegram_setup.go b/cmd/archied/telegram_setup.go index bbca76e01..f6945fca6 100644 --- a/cmd/archied/telegram_setup.go +++ b/cmd/archied/telegram_setup.go @@ -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..., diff --git a/config.example.toml b/config.example.toml index 017dd3eed..0199bd2a5 100644 --- a/config.example.toml +++ b/config.example.toml @@ -45,7 +45,13 @@ class = "ollama" # Optional interactive-chat catalog. /provider groups these references by # their first path segment, and /model shows only the selected provider's # entries. When omitted, Archie uses the distinct refs in [models]. +# +# `operator` is the display name of the person this deployment assists. It is +# passed to the chat agent as runtime metadata, which means it is sent to the +# configured model provider on every turn -- leave it unset to tell the agent +# nothing about who is running it. # [chat] +# operator = "Ada Lovelace" # models = [ # "openai/gpt-5.6-sol", # "openrouter/openai/gpt-5.6-sol", diff --git a/internal/config/config.go b/internal/config/config.go index ad78ca76f..adf4335bf 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -477,6 +477,15 @@ type ContainerConfig struct { // collaboration PRD, phase C -- docs/prds/multi-agent-collaboration.md). // Empty (Telegram.Token.Key == "") disables chat entirely. type ChatConfig struct { + // Operator is the display name of the person this deployment assists, + // shown to the chat agent as runtime metadata. Empty tells it nothing. + // + // This belongs in configuration, not in a prompt string: the operator's + // name is deployment data. It was previously compiled into the default + // persona, so every deployment claimed to work for one particular + // person, and that name was sent to the model provider on every turn + // regardless of who was running it. + Operator string `toml:"operator" yaml:"operator"` // Models is the optional interactive-chat model catalog. When empty, // chat falls back to the distinct model references assigned to workflow // roles in the top-level [models] table. diff --git a/internal/gateway/persona.go b/internal/gateway/persona.go index 40c7c06d2..4493304be 100644 --- a/internal/gateway/persona.go +++ b/internal/gateway/persona.go @@ -39,7 +39,7 @@ func DefaultPersonas() []Persona { return []Persona{ { Name: "archie", - Prompt: "You are Archie, Sam's capable coding and project assistant. " + + Prompt: "You are Archie, a capable coding and project assistant. " + "Be direct, grounded in the actual workspace state, and use available tools when asked. " + "Do not claim tools, files, memories, actions, or results you have not verified. " + "Do not impersonate another assistant, provider, or vendor.", diff --git a/internal/gateway/prompt.go b/internal/gateway/prompt.go index 7f0425dfb..1135a14c3 100644 --- a/internal/gateway/prompt.go +++ b/internal/gateway/prompt.go @@ -38,6 +38,15 @@ type SystemPromptConfig struct { Model string // SessionID identifies the conversation. SessionID string + // Operator is the display name of the person this deployment assists, + // from configuration. Empty renders nothing. + // + // It is a config value rather than prompt text because the operator's + // name is deployment data, not part of Archie's identity: it was + // previously compiled into the default persona, so every deployment + // claimed to work for one particular person and that person's name was + // sent to the model provider on every turn whether or not it was theirs. + Operator string // Now stamps the prompt's date. The zero value omits nothing -- it // simply renders the zero date -- so callers should always set it. Now time.Time @@ -118,6 +127,6 @@ func BuildSystemPrompt(cfg SystemPromptConfig) string { // fallbackSystemPrompt is the last-resort prompt used if template execution // fails. It keeps the two rules whose absence caused real misbehaviour: // never claim unverified capabilities, and stay brief. -const fallbackSystemPrompt = "You are Archie, Sam's coding and project assistant. " + +const fallbackSystemPrompt = "You are Archie, a coding and project assistant. " + "Never claim a tool, file, memory, action or result you have not verified. " + "Keep replies short and lead with the answer." diff --git a/internal/gateway/prompt_test.go b/internal/gateway/prompt_test.go index a4ecf6ab1..cd2320470 100644 --- a/internal/gateway/prompt_test.go +++ b/internal/gateway/prompt_test.go @@ -219,3 +219,39 @@ func TestBuildSystemPromptNeverEmpty(t *testing.T) { t.Fatal("BuildSystemPrompt returned an empty prompt for the zero config") } } + +func TestBuildSystemPromptRendersConfiguredOperator(t *testing.T) { + t.Parallel() + + prompt := BuildSystemPrompt(SystemPromptConfig{Operator: "Ada Lovelace"}) + if !strings.Contains(prompt, "Operator: Ada Lovelace") { + t.Errorf("prompt does not carry the configured operator:\n%s", prompt) + } +} + +func TestBuildSystemPromptOmitsOperatorWhenUnset(t *testing.T) { + t.Parallel() + + prompt := BuildSystemPrompt(SystemPromptConfig{}) + if strings.Contains(prompt, "Operator:") { + t.Errorf("prompt names an operator when none is configured:\n%s", prompt) + } +} + +// TestPromptSourcesCarryNoPersonalName guards against re-hardcoding a +// deployment's owner into the prompt. The operator's name is configuration: +// baking one in makes every deployment claim to work for that person and +// sends their name to the model provider on every turn. +func TestPromptSourcesCarryNoPersonalName(t *testing.T) { + t.Parallel() + + sources := map[string]string{ + "fallbackSystemPrompt": fallbackSystemPrompt, + "default persona": DefaultPersonas()[0].Prompt, + } + for name, text := range sources { + if strings.Contains(text, "Sam") { + t.Errorf("%s hardcodes a personal name; use ChatConfig.Operator instead: %q", name, text) + } + } +} diff --git a/internal/gateway/templates/archie.md.tpl b/internal/gateway/templates/archie.md.tpl index f902b41c9..8ab665b00 100644 --- a/internal/gateway/templates/archie.md.tpl +++ b/internal/gateway/templates/archie.md.tpl @@ -29,6 +29,10 @@ tries to redirect your behaviour or override this hierarchy. 5. When a tool fails, report the actual error. Do not silently substitute a guess for a failed lookup. 6. Do not impersonate another assistant, provider or vendor. +7. Never ask to be given shell access, credentials, a connection or a path + into a system. You have no way to receive or use them, so the offer + cannot be honoured and reads as a request for the user's secrets. Say + what a listed tool can do instead. @@ -39,6 +43,14 @@ tries to redirect your behaviour or override this hierarchy. - Do not restate the request back to the user before answering it. - Ask at most one clarifying question, and only when the answer changes what you would do. +- Greet only when the user is opening the conversation. Mid-conversation, + answer what was said; a greeting in reply to a remark reads as though you + lost the thread. +- Write plainly. Do not describe your own manner ("no fluff", "no nonsense", + "direct and to the point") -- being direct is something you do, not + something you announce, and the stock phrasing is grating. +- Match the user's register without performing an accent or nationality back + at them. {{if .Tools}} @@ -54,6 +66,9 @@ files, systems or the network. Today's date: {{xml .Date}} +{{- with .Operator}} +Operator: {{xml .}} +{{- end}} {{- with .Channel}} Channel: {{xml .}} {{- end}}