Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions ai_prompt.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,11 +158,24 @@ func aiCatalogPromptSection(catalog []aiCatalogEntry) string {
return b.String()
}

// aiVolatileSystem is the post-breakpoint tail: everything here may change
// between requests without touching the cached prefix.
// aiVolatileSystem is the post-breakpoint tail of the system prompt. The
// session renders it ONCE, at the start of the conversation, and resends it
// byte-identical on every request: models with preserved thinking (Opus 5.5,
// Fable 5.x) sign each thinking block against the top-level system prompt, so
// editing it mid-conversation invalidates every earlier thinking block and
// the next request fails with HTTP 400. Later changes to these facts (a
// customer switch, a re-login) reach the model as appended messages instead —
// see localAISession.composeUserMessageLocked.
func aiVolatileSystem(configDir string, now time.Time, customerOverride string) string {
return fmt.Sprintf("Today's date: %s.\n", now.Format("2006-01-02")) + aiSessionContextLines(configDir, customerOverride)
}

// aiSessionContextLines is the part of the volatile tail that can change
// during a session: the active customer context and the signed-in identity.
// The session compares it before each question to detect a change it must
// announce in the conversation.
func aiSessionContextLines(configDir string, customerOverride string) string {
var b strings.Builder
fmt.Fprintf(&b, "Today's date: %s.\n", now.Format("2006-01-02"))
switch context := readCustomerContext(configDir); {
case customerOverride != "":
// The agent's own session-scoped switch (set_customer_context) wins
Expand Down
64 changes: 50 additions & 14 deletions ai_session.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import (

const (
aiSettingsFileName = "ai_settings.json"
aiDefaultModel = "claude-opus-5"
aiDefaultModel = "claude-opus-5-5"
aiMaxToolRounds = 16
// aiMaxOutputTokens bounds one API turn. Adaptive thinking counts against
// max_tokens: analytical questions (aggregating a 200-row result) have
Expand All @@ -46,10 +46,10 @@ const (
// aiKnownModels is the selectable set shown by /model. Other claude-* ids are
// accepted with a warning — the API is the final validator.
var aiKnownModels = []string{
"claude-opus-5",
"claude-sonnet-5",
"claude-opus-4-8",
"claude-haiku-4-5",
"claude-opus-5-5",
"claude-fable-5-2",
"claude-sonnet-5-5",
"claude-haiku-5-5",
}

type aiSettings struct {
Expand Down Expand Up @@ -242,13 +242,19 @@ type localAISession struct {
approvals chan aiUserInput
done chan struct{} // closed by Close; emit drains against it

mu sync.Mutex
history []anthropic.MessageParam
pending []string // injected slash results, consumed by the next question
running bool
cancel context.CancelFunc
turnSeq int
closed bool
mu sync.Mutex
// systemTail is the volatile system block, frozen at the conversation's
// first request (see aiVolatileSystem for why it must never change), and
// announcedContext is the context the model was last told about — in
// systemTail, a set_customer_context result, or an appended update.
systemTail string
announcedContext string
history []anthropic.MessageParam
pending []string // injected slash results, consumed by the next question
running bool
cancel context.CancelFunc
turnSeq int
closed bool
}

// errAITurnRunning is returned by Send(chat) while a turn is in flight.
Expand Down Expand Up @@ -407,8 +413,31 @@ func aiCommandResultContext(input aiUserInput) string {
return b.String()
}

// freezeSystemTailLocked renders the volatile system block on first use and
// keeps it for the rest of the conversation.
func (s *localAISession) freezeSystemTailLocked() {
if s.systemTail != "" {
return
}
override := s.executor.CustomerOverride()
s.systemTail = aiVolatileSystem(s.configDir, time.Now(), override)
s.announcedContext = aiSessionContextLines(s.configDir, override)
}

func (s *localAISession) composeUserMessageLocked(question string) anthropic.MessageParam {
blocks := make([]anthropic.ContentBlockParamUnion, 0, len(s.pending)+1)
blocks := make([]anthropic.ContentBlockParamUnion, 0, len(s.pending)+2)
if s.systemTail == "" {
s.freezeSystemTailLocked()
} else if current := aiSessionContextLines(s.configDir, s.executor.CustomerOverride()); current != s.announcedContext {
// The context changed outside the agent's own tool call (/customer,
// a re-login): the frozen system prompt is now stale, so the update
// rides in the conversation, appended where it became true.
if current == "" {
current = "No customer context is active.\n"
}
blocks = append(blocks, anthropic.NewTextBlock("Session context update (supersedes the context in the system prompt):\n"+current))
s.announcedContext = aiSessionContextLines(s.configDir, s.executor.CustomerOverride())
}
for _, injected := range s.pending {
blocks = append(blocks, anthropic.NewTextBlock(injected))
}
Expand Down Expand Up @@ -459,11 +488,13 @@ func (s *localAISession) tools() []anthropic.ToolUnionParam {

func (s *localAISession) params() anthropic.MessageNewParams {
s.mu.Lock()
s.freezeSystemTailLocked()
history := append([]anthropic.MessageParam{}, s.history...)
model := s.model
tail := s.systemTail
Comment on lines +491 to +494

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 If a user runs /customer while a turn is running, the agent keeps working for the rest of that turn as if the old tenant were active. Its commands already run against the new one. The context-change check now runs only in composeUserMessageLocked, which fires once per question. params() resends the frozen tail on every tool round. Fix: run the same check before each round in runTurn. On a change, add the "Session context update" text block to the user message that carries the tool results (ai_session.go:576), so the change is announced within the turn.

Why this was flagged

The TUI does not block verbs during a turn. submit() sends to runVerb, and the "customer" case (ai_tui.go:1672-1690) writes the saved context and calls ClearCustomerOverride while the turn is in flight. Every later run_dci_command child in that turn runs against the new tenant, because EffectiveCustomer reads the file (ai_tools.go:216). The tool_result sent to the model holds only outcome.Data with no tenant tag (ai_session.go:746). The tenant is attached only to the TUI event. runTurn calls s.params() on each of up to aiMaxToolRounds=16 rounds (ai_session.go:530). Before this change, each call re-rendered aiVolatileSystem with the current customer, so the model saw the switch on its next round. Now params() resends the frozen systemTail. The update is added only on the user's next question (ai_session.go:431). For the rest of the turn the model reports the new tenant's data as the old tenant's. A re-login mid-turn (refreshAuthState, ai_tui.go:722) behaves the same way.

Verification: On the base commit, params() re-rendered the volatile tail on every request, so each tool round showed the model the current tenant. Now params() sends tail := s.systemTail, which is rendered once and never re-rendered. The context check runs only in composeUserMessageLocked, and the tool-result user message in runTurn (ai_session.go:576) gets no such check.

Finding ID: f-185a92f4

s.mu.Unlock()
stable := anthropic.TextBlockParam{Text: s.stablePrompt, CacheControl: anthropic.NewCacheControlEphemeralParam()}
volatile := anthropic.TextBlockParam{Text: aiVolatileSystem(s.configDir, time.Now(), s.executor.CustomerOverride())}
volatile := anthropic.TextBlockParam{Text: tail}
params := anthropic.MessageNewParams{
Model: anthropic.Model(model),
MaxTokens: aiMaxOutputTokens,
Expand Down Expand Up @@ -760,6 +791,11 @@ func (s *localAISession) executeSerialToolCall(turnID string, toolUse anthropic.
started := time.Now()
from, to, outcome := s.executor.SetCustomer(input)
if !outcome.IsError {
// The tool result below is how the model learns the new tenant
// (the system prompt stays frozen), so record it as announced.
s.mu.Lock()
s.announcedContext = aiSessionContextLines(s.configDir, s.executor.CustomerOverride())
s.mu.Unlock()
s.emit(aiEvent{ContextSwitched: &aiContextSwitched{From: from, To: to, By: "agent"}})
}
s.emit(aiEvent{ToolResult: &aiToolResult{
Expand Down
78 changes: 73 additions & 5 deletions ai_session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"context"
"encoding/json"
"os"
"strings"
"sync/atomic"
"testing"
Expand Down Expand Up @@ -606,11 +607,11 @@ func TestAISessionParamsLayout(t *testing.T) {

func TestAISettingsRoundTripAndResolution(t *testing.T) {
dir := t.TempDir()
if err := saveAISettings(dir, aiSettings{APIKey: "sk-test", Model: "claude-sonnet-5"}); err != nil {
if err := saveAISettings(dir, aiSettings{APIKey: "sk-test", Model: "claude-sonnet-5-5"}); err != nil {
t.Fatal(err)
}
loaded := loadAISettings(dir)
if loaded.APIKey != "sk-test" || loaded.Model != "claude-sonnet-5" {
if loaded.APIKey != "sk-test" || loaded.Model != "claude-sonnet-5-5" {
t.Fatalf("loaded = %+v", loaded)
}
t.Setenv("ANTHROPIC_API_KEY", "sk-env")
Expand All @@ -627,7 +628,7 @@ func TestAISettingsRoundTripAndResolution(t *testing.T) {
if err := aiValidateModel("gpt-4"); err == nil {
t.Fatal("non-claude model accepted")
}
if err := aiValidateModel("claude-opus-5"); err != nil {
if err := aiValidateModel("claude-opus-5-5"); err != nil {
t.Fatal(err)
}
}
Expand Down Expand Up @@ -659,8 +660,75 @@ func TestResolveAIEffortAndModelOverrides(t *testing.T) {
t.Fatalf("env default must win over settings, got %q", got)
}
t.Setenv("DCI_AI_EFFORT", "")
t.Setenv("DCI_AI_MODEL", "claude-sonnet-5")
if got := resolveAIModel(aiSettings{Model: "claude-opus-5"}); got != "claude-sonnet-5" {
t.Setenv("DCI_AI_MODEL", "claude-sonnet-5-5")
if got := resolveAIModel(aiSettings{Model: "claude-opus-5-5"}); got != "claude-sonnet-5-5" {
t.Fatalf("model env must win, got %q", got)
}
}

// TestAISessionSystemPromptStableAcrossCustomerSwitch is the regression for
// preserved thinking's prefix check: Opus 5.5 / Fable 5.x sign each thinking
// block against the top-level system prompt, so a system prompt that changes
// after set_customer_context (or /customer) makes the next request a 400. The
// system blocks must stay byte-identical for the whole conversation; the new
// tenant reaches the model through the tool result or an appended message.
func TestAISessionSystemPromptStableAcrossCustomerSwitch(t *testing.T) {
var captured []anthropic.MessageNewParams
turns := []string{
aiTestToolUseTurn(aiTestSwitchBlock("call-1", "acme.com")),
aiTestTextTurn,
aiTestTextTurn,
}
session := newTestSession(t, turns, &scriptedRunner{})
session.tenantAware = true
scripted := session.streamer
session.streamer = func(ctx context.Context, params anthropic.MessageNewParams, onDelta, onThinking func(string)) (anthropic.Message, error) {
captured = append(captured, params)
return scripted(ctx, params, onDelta, onThinking)
}

if err := session.Send(aiUserInput{Kind: aiInputChat, Text: "switch to acme"}); err != nil {
t.Fatal(err)
}
collectTurnEvents(t, session)
// The user then persists a different context with /customer.
if err := os.WriteFile(customerContextPath(session.configDir), []byte("globex.com\n"), 0o600); err != nil {
t.Fatal(err)
}
session.ClearCustomerOverride()
if err := session.Send(aiUserInput{Kind: aiInputChat, Text: "and now?"}); err != nil {
t.Fatal(err)
}
collectTurnEvents(t, session)

if len(captured) != 3 {
t.Fatalf("captured %d requests, want 3", len(captured))
}
first, _ := json.Marshal(captured[0].System)
for i, params := range captured[1:] {
if got, _ := json.Marshal(params.System); string(got) != string(first) {
t.Fatalf("request %d changed the system prompt:\nfirst: %s\nlater: %s", i+2, first, got)
}
}
if strings.Contains(string(first), "acme.com") || strings.Contains(string(first), "globex.com") {
t.Fatalf("frozen system prompt names a later context: %s", first)
}

// The agent's switch is reported in its tool result.
toolResult, _ := json.Marshal(captured[1].Messages[2])
if !strings.Contains(string(toolResult), "acme.com") {
t.Fatalf("tool result does not name the new customer: %s", toolResult)
}
// The /customer change is appended to the next user message.
last := captured[2].Messages[len(captured[2].Messages)-1]
encoded, _ := json.Marshal(last)
if !strings.Contains(string(encoded), "Session context update") || !strings.Contains(string(encoded), "globex.com") {
t.Fatalf("next user message does not announce the /customer change: %s", encoded)
}
// Earlier history is untouched (append-only).
before, _ := json.Marshal(captured[1].Messages)
after, _ := json.Marshal(captured[2].Messages[:len(captured[1].Messages)])
if string(before) != string(after) {
t.Fatal("history before the new question was rewritten")
}
}
5 changes: 4 additions & 1 deletion ai_tools.go
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,10 @@ func (e *aiToolExecutor) SetCustomer(input aiSetCustomerInput) (from, to string,
e.mu.Lock()
e.customerOverride = token
e.mu.Unlock()
return from, token, aiToolOutcome{Data: fmt.Sprintf("customer context switched from %q to %q for this session (the saved context is unchanged)", from, token)}
// The result is the model's only notice of the switch: the system prompt
// is frozen for the conversation (aiVolatileSystem), so say that the new
// tenant supersedes the one it names.
return from, token, aiToolOutcome{Data: fmt.Sprintf("customer context switched from %q to %q for this session (the saved context is unchanged). Active customer context is now %s; this supersedes the context in the system prompt.", from, token, token)}
}

// aiCapToolResult bounds one tool result entering model context (§7.6),
Expand Down
10 changes: 5 additions & 5 deletions ai_tui_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -570,22 +570,22 @@ func TestAIContextSwitchEventRefreshesIdentity(t *testing.T) {

func TestAIModelVerb(t *testing.T) {
m := aiTestModel(t)
m = aiType(m, "/model claude-sonnet-5")
m = aiType(m, "/model claude-sonnet-5-5")
updated, _ := aiPress(m, tea.KeyEnter)
m = updated
if !strings.Contains(aiTranscriptText(m), "Model set to claude-sonnet-5") {
if !strings.Contains(aiTranscriptText(m), "Model set to claude-sonnet-5-5") {
t.Fatal("/model confirmation missing from the transcript")
}
if m.modelName != "claude-sonnet-5" {
if m.modelName != "claude-sonnet-5-5" {
t.Fatalf("modelName = %q", m.modelName)
}
if got := loadAISettings(m.configDir).Model; got != "claude-sonnet-5" {
if got := loadAISettings(m.configDir).Model; got != "claude-sonnet-5-5" {
t.Fatalf("persisted model = %q", got)
}
m = aiType(m, "/model gpt-4")
updated, _ = aiPress(m, tea.KeyEnter)
m = updated
if m.modelName != "claude-sonnet-5" {
if m.modelName != "claude-sonnet-5-5" {
t.Fatalf("invalid model applied: %q", m.modelName)
}
}
Expand Down
Loading