@@ -1,274 +1,4 @@
1-# TODO: Critical Bugs
1+# TODO:
22
3-## CRITICAL: Agent Repeating Tool Calls
4-
5-Multiple critical bugs cause agents to repeat the same tool calls indefinitely. Root cause identified through comprehensive audit (2026-02-10).
6-
7----
8-
9-### ~~BUG #1: History Snapshot Never Updated in Multi-Round Loop~~ [FIXED]
10-
11-**Status:** ✅ FIXED (2026-02-10)
12-
13-**Priority:** P0 - PRIMARY CAUSE of repeated tool calls
14-
15-**Location:**
16-
17-- `internal/cli/cli.go:266-282`
18-- `internal/llm/loop.go:40-107`
19-
20-**Problem:**
21-`processTurn()` creates a snapshot of conversation history and passes it to `ProcessTurn()`. Inside the loop, `ProcessTurn()` iterates up to 20 rounds for tool calls. Each round uses the **same original snapshot** for compression.
22-
23-When tool results are added via `OnMessage` callback, they update `app.history` but `opts.History` (the snapshot passed to ProcessTurn) never sees these new messages. The LLM repeatedly receives history without its own tool results.
24-
25-**Example Flow:**
26-
27-1. Round 0: LLM gets initial history, calls tool `get_status`
28-2. Tool result added to `app.history` via OnMessage
29-3. Round 1: `compressedHistory` regenerated from original snapshot (doesn't include tool result from round 0)
30-4. LLM receives history WITHOUT the tool result from round 0
31-5. LLM doesn't know it already called `get_status`, calls it again
32-6. Infinite loop until MaxToolRounds limit (20 rounds)
33-
34-**Evidence:**
35-
36-- `loop.go:43`: `compressedHistory := store.CompressHistory(opts.History, opts.HistoryKeepLast)` - always uses same snapshot
37-- `cli.go:269-271`: History snapshot made once, never updated during turn
38-- `loop.go:86-99, 142-146, 159-179`: Tool results added to `app.history`, but `opts.History` unchanged
39-
40-**Fix Applied:** Option A - Update `opts.History` after each round
41-
42-**Changes Made:**
43-
44-1. Modified `internal/llm/loop.go:86-91` - Update `opts.History` after adding assistant response (no tool calls)
45-2. Modified `internal/llm/loop.go:96-103` - Update `opts.History` after adding assistant message with tool calls
46-3. Modified `internal/llm/loop.go:106-110` - Collect tool results and append to `opts.History`
47-4. Modified `executeToolCalls()` signature to return `([]provider.Message, error)` so tool results can be collected
48-5. Modified `executeToolCalls()` implementation to collect and return all tool result messages
49-
50-**How It Works Now:**
51-
52-- After each `OnMessage()` callback, the corresponding message is also appended to `opts.History`
53-- On the next loop iteration, `CompressHistory()` sees the complete history including all tool calls and results from previous rounds
54-- LLM receives compressed history that includes its own previous tool calls and results
55-- LLM no longer repeats tool calls because it can see the results in history
56-
57----
58-
59-### BUG #2: Race Condition in History Append [CRITICAL]
60-
61-**Priority:** P0 - Race condition with autoplay
62-
63-**Location:**
64-
65-- `internal/cli/cli.go:246` (manual input - NO LOCK)
66-- `internal/cli/autoplay.go:190` (autoplay - HAS LOCK)
67-
68-**Problem:**
69-Manual user input appends to `app.history` WITHOUT mutex lock:
70-
71-```go
72-// cli.go:246 - NO LOCK
73-app.history = append(app.history, userMsg)
74-```
75-
76-But autoplay DOES lock:
77-
78-```go
79-// autoplay.go:190 - HAS LOCK
80-app.mu.Lock()
81-app.history = append(app.history, userMsg)
82-app.mu.Unlock()
83-```
84-
85-**Race Scenario:**
86-
87-```
88-Time Main Loop (manual input) Autoplay Goroutine
89----- --------------------------- --------------------
90-T1 mu.Lock()
91-T2 app.history = append(...)
92-T3 app.history = append(...)
93-T4 mu.Unlock()
94-```
95-
96-At T2, main loop appends without lock while autoplay holds lock. Violates mutex semantics.
97-
98-**Impact:**
99-
100-- Slice corruption: append may resize backing array while another goroutine accesses it
101-- Lost messages: concurrent appends may overwrite each other
102-- Panic: possible slice index out of range
103-
104-**Fix:**
105-
106-```go
107-// cli.go:246 - Add mutex protection
108-app.mu.Lock()
109-app.history = append(app.history, userMsg)
110-app.mu.Unlock()
111-```
112-
113----
114-
115-### BUG #3: Shallow Copy in Compression Mutates Backing Arrays [CRITICAL]
116-
117-**Priority:** P0 - Silent data corruption
118-
119-**Location:**
120-
121-- `internal/store/compression.go:132-134`
122-- `internal/store/compression.go:140-142`
123-
124-**Problem:**
125-
126-```go
127-// Line 132-134
128-compressedMsg := msg // SHALLOW COPY - shares backing arrays!
129-compressedMsg.Content = compressedToolResult
130-compressed = append(compressed, compressedMsg)
131-
132-// Line 140-142
133-compressedMsg := msg // SHALLOW COPY - shares backing arrays!
134-compressedMsg.Content = msg.Content[:200] + "... [truncated]"
135-compressed = append(compressed, compressedMsg)
136-```
137-
138-`compressedMsg := msg` creates shallow copy. The `ToolCalls` slice in both `msg` and `compressedMsg` point to the **same backing array**. Later append operations can mutate the backing array visible to both original and compressed history.
139-
140-**Impact:**
141-
142-- Messages in compressed history can have their `ToolCalls` mutated
143-- Database saves may contain corrupted ToolCalls data
144-- LLM may receive inconsistent history across rounds
145-
146-**Fix:**
147-
148-```go
149-// Deep copy the message struct
150-compressedMsg := provider.Message{
151- Role: msg.Role,
152- Content: compressedToolResult,
153- ToolCallID: msg.ToolCallID,
154- ToolCalls: append([]provider.ToolCall(nil), msg.ToolCalls...),
155-}
156-```
157-
158----
159-
160-### BUG #4: Naive Truncation Loses Critical Information [HIGH]
161-
162-**Priority:** P1 - Can cause LLM to miss important game events
163-
164-**Location:** `internal/store/compression.go:139-142`
165-
166-**Problem:**
167-Truncation simply takes first 200 characters of action tool results. If critical information appears later in the response (common in verbose API responses), it gets lost.
168-
169-```go
170-if len(msg.Content) > 500 {
171- compressedMsg := msg
172- compressedMsg.Content = msg.Content[:200] + "... [truncated]"
173- compressed = append(compressed, compressedMsg)
174-}
175-```
176-
177-**Real-world scenario:**
178-
179-- SpaceMolt travel response: 1198 characters
180-- First 200 chars: Headers and departure info
181-- Lost content: "CRITICAL: Base commander requests immediate meeting for urgent mission!"
182-- Result: LLM misses quest hooks and important notifications
183-
184-**Why this causes repeated tool calls:**
185-If truncation removes success confirmation or critical state changes, LLM may think action didn't complete and try again.
186-
187-**Fix Options:**
188-
189-Option A: Smart truncation (keep beginning and end)
190-
191-```go
192-if len(msg.Content) > 500 {
193- compressedMsg := msg
194- start := msg.Content[:150]
195- end := msg.Content[len(msg.Content)-50:]
196- compressedMsg.Content = start + "... [middle truncated] ..." + end
197- compressed = append(compressed, compressedMsg)
198-}
199-```
200-
201-Option B: Configurable truncation
202-
203-```go
204-const truncateKeepFirst = 150
205-const truncateKeepLast = 50
206-
207-if len(msg.Content) > 500 {
208- compressedMsg := msg
209- start := msg.Content[:truncateKeepFirst]
210- end := msg.Content[len(msg.Content)-truncateKeepLast:]
211- compressedMsg.Content = start + "..." + end + " [truncated]"
212- compressed = append(compressed, compressedMsg)
213-}
214-```
215-
216----
217-
218-## Additional Issues Found During Audit
219-
220-### BUG #5: Missing ToolCalls Field in No-Tool-Call Response [MEDIUM]
221-
222-**Priority:** P2 - Data consistency issue
223-
224-**Location:** `internal/llm/loop.go:86-89`
225-
226-**Problem:**
227-When LLM responds with text only (no tool calls), assistant message is added without preserving the ToolCalls field:
228-
229-```go
230-opts.OnMessage(provider.Message{
231- Role: "assistant",
232- Content: resp.Content,
233- // ToolCalls field missing - defaults to nil
234-})
235-```
236-
237-**Fix:**
238-
239-```go
240-opts.OnMessage(provider.Message{
241- Role: "assistant",
242- Content: resp.Content,
243- ToolCalls: resp.ToolCalls, // Include even if empty
244-})
245-```
246-
247----
248-
249-### BUG #6: ProcessTurn Non-Blocking Allows Concurrent Autoplay [HIGH]
250-
251-**Priority:** P1 - Autoplay timing bug
252-
253-**Location:** `internal/cli/autoplay.go:198-206`
254-
255-**Problem:**
256-After calling `processTurn()`, the function returns immediately without waiting for turn completion. The ticker continues and can fire again.
257-
258-```go
259-if err := app.processTurn(ctx); err != nil {
260- fmt.Fprintln(os.Stderr, styles.Error.Render("Error: "+err.Error()))
261- log.Warn().Err(err).Msg("Autoplay turn failed, continuing...")
262-}
263-
264-fmt.Println()
265-return nil // Returns immediately
266-```
267-
268-Autoplay interval: 100 seconds (10 tools × 10s/tick). But `processTurn()` can take longer if there are delays, retries, or >10 tool calls. Timer fires at fixed intervals regardless of whether previous turn finished.
269-
270-**Impact:**
271-If turn takes >100 seconds, ticker fires again before previous turn completes, causing concurrent `processTurn()` executions.
272-
273-**Fix:**
274-Add synchronization to block next autoplay message until current turn completes.
3+- Blinking cursor in TUI
4+- Mouse selection in TUI