xonecas.io
6119
My

mysis / commit 59b7e89

fix: loop was broken

xonecas2026-02-10 59b7e89066c8071fd6fde966c24eec1ab03c7d0e parent 6bf60ad

5 files changed

config.toml+1−1
@@ -1,7 +1,7 @@
11 # Ollama providers (local)
22 [providers.ollama-qwen]
33 endpoint = "http://localhost:11434"
4-model = "qwen3:14b"
4+model = "qwen3:8b"
55 temperature = 0.3
66
77 [providers.ollama-qwen-small]
documentation/TODO.md+274−0
@@ -0,0 +1,274 @@
1+# TODO: Critical Bugs
2+
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.
documentation/architecture/LLM_LOOP.md+327−0
@@ -0,0 +1,327 @@
1+# LLM Processing Loop
2+
3+Single-turn conversation processing with multi-round tool call support.
4+
5+## Overview
6+
7+The LLM loop handles one conversation turn, which may involve multiple rounds of LLM calls and tool executions. A **turn** begins when the user sends a message and ends when the LLM provides a final text response without tool calls.
8+
9+**Key principle:** The loop accumulates history during the turn so the LLM sees its own tool calls and results across rounds.
10+
11+## Architecture
12+
13+```
14+User Input → ProcessTurn → [Round 0, Round 1, ..., Round N] → Final Response
15+ ↓
16+ Compress History → LLM Call → Tool Execution
17+ ↑_______________|
18+```
19+
20+## Flow Diagram
21+
22+```
23+processTurn (cli.go:266-282)
24+ │
25+ ├─ Snapshot app.history → historyCopy
26+ │
27+ └─ ProcessTurn (llm/loop.go:32-116)
28+ │
29+ └─ Loop: round = 0 to MaxToolRounds (20)
30+ │
31+ ├─ Compress historyCopy → compressedHistory
32+ │
33+ ├─ LLM Call with compressedHistory + tools
34+ │ └─ Returns: content, tool_calls, reasoning
35+ │
36+ ├─ If no tool_calls:
37+ │ ├─ Display content
38+ │ ├─ OnMessage(assistant_msg)
39+ │ ├─ Append to historyCopy
40+ │ └─ RETURN (turn complete)
41+ │
42+ └─ If tool_calls present:
43+ ├─ OnMessage(assistant_msg_with_tools)
44+ ├─ Append to historyCopy
45+ │
46+ ├─ executeToolCalls:
47+ │ └─ For each tool:
48+ │ ├─ Execute via MCP proxy
49+ │ ├─ OnMessage(tool_result)
50+ │ └─ Collect tool_result
51+ │
52+ ├─ Append all tool_results to historyCopy
53+ └─ Continue to next round
54+```
55+
56+## Implementation Details
57+
58+### Entry Point: `ProcessTurn`
59+
60+**Location:** `internal/llm/loop.go:32-116`
61+
62+**Signature:**
63+
64+```go
65+func ProcessTurn(ctx context.Context, opts ProcessTurnOptions) error
66+```
67+
68+**Options:**
69+
70+- `Provider`: LLM provider interface (Ollama, OpenCode Zen, etc.)
71+- `Proxy`: MCP proxy for tool execution
72+- `Tools`: Available tools for this turn
73+- `History`: Initial conversation history snapshot
74+- `OnMessage`: Callback to save messages to database and `app.history`
75+- `MaxToolRounds`: Maximum iterations (default: 20)
76+- `HistoryKeepLast`: How many recent turns to keep uncompressed (default: 10)
77+
78+### Round Loop
79+
80+Each round performs:
81+
82+1. **History Compression** (line 43)
83+ - Compresses old state query results
84+ - Keeps recent turns full
85+ - See `internal/store/compression.go` for details
86+
87+2. **LLM Call** (line 69)
88+ - Sends compressed history + available tools
89+ - Receives response with optional tool calls
90+
91+3. **Response Handling**
92+ - **No tool calls** (lines 80-93): Display content, save message, update history, exit
93+ - **Tool calls present** (lines 96-110): Save assistant message, execute tools, update history, continue
94+
95+4. **History Update** (Critical Fix - Bug #1)
96+ - After `OnMessage()` callback, message is also appended to `opts.History`
97+ - This ensures next round sees messages from previous rounds
98+ - Without this, LLM would repeat tool calls indefinitely
99+
100+### Tool Execution: `executeToolCalls`
101+
102+**Location:** `internal/llm/loop.go:130-195`
103+
104+**Signature:**
105+
106+```go
107+func executeToolCalls(ctx context.Context, proxy *mcp.Proxy, toolCalls []provider.ToolCall, onMessage MessageCallback) ([]provider.Message, error)
108+```
109+
110+**Flow:**
111+
112+1. For each tool call:
113+ - Display tool name and arguments (truncated)
114+ - Execute via MCP proxy
115+ - Display result (success ✓ or error ✗)
116+ - Create tool result message
117+ - Call `onMessage()` to save to database
118+ - Collect message for return
119+
120+2. Return all tool result messages
121+ - Caller appends to `opts.History`
122+ - Ensures next round sees tool results
123+
124+### Message Callback: `OnMessage`
125+
126+**Implementation:** `internal/cli/cli.go:285-293`
127+
128+```go
129+func (app *App) addMessage(msg provider.Message) {
130+ app.mu.Lock()
131+ app.history = append(app.history, msg)
132+ app.mu.Unlock()
133+
134+ if err := app.sessionMgr.SaveMessage(app.sessionID, msg); err != nil {
135+ log.Warn().Err(err).Msg("Failed to save message to database")
136+ }
137+}
138+```
139+
140+**Purpose:**
141+
142+- Updates canonical `app.history` with mutex protection
143+- Saves message to SQLite database for session persistence
144+- Called for every message: user, assistant, tool results
145+
146+**Note:** The callback updates `app.history` but NOT `opts.History`. The caller (`ProcessTurn`) must also update `opts.History` after calling the callback.
147+
148+## History Management
149+
150+### Snapshot vs Reference
151+
152+**Design Decision:** Pass history snapshot, not reference.
153+
154+**Rationale:**
155+
156+- Prevents concurrent modification during processing
157+- Clean separation between "input to turn" and "output from turn"
158+- Next turn gets fresh snapshot with all previous messages
159+
160+**Implementation:**
161+
162+```go
163+// cli.go:268-271
164+app.mu.Lock()
165+historyCopy := make([]provider.Message, len(app.history))
166+copy(historyCopy, app.history)
167+app.mu.Unlock()
168+```
169+
170+### History Accumulation During Turn
171+
172+**Critical Fix (2026-02-10):** After each message is saved via `OnMessage()`, it's also appended to `opts.History`.
173+
174+**Before Fix:**
175+
176+```go
177+opts.OnMessage(assistantMsg)
178+// opts.History unchanged - next round uses stale history
179+```
180+
181+**After Fix:**
182+
183+```go
184+opts.OnMessage(assistantMsg)
185+opts.History = append(opts.History, assistantMsg)
186+// Next round sees this message
187+```
188+
189+**Why This Matters:**
190+
191+Round 0:
192+
193+- `opts.History = [user: "check status"]`
194+- LLM calls `get_status`
195+- Tool result saved via `OnMessage` to `app.history`
196+- **Before fix:** `opts.History` still `[user: "check status"]`
197+- **After fix:** `opts.History = [user: "check status", assistant: tool_call, tool: result]`
198+
199+Round 1:
200+
201+- **Before fix:** LLM sees compressed `[user: "check status"]` → calls `get_status` again (doesn't see result)
202+- **After fix:** LLM sees compressed `[user: "check status", assistant: tool_call, tool: result]` → processes result
203+
204+## Compression During Turn
205+
206+**Key Insight:** Compression operates on `opts.History`, which now includes messages from previous rounds within the same turn.
207+
208+**Process:**
209+
210+1. `CompressHistory(opts.History, keepFullTurns=10)` compresses old state queries
211+2. Recent turns (last 10) kept full
212+3. Old action tool results truncated to 200 chars
213+4. Authentication tools never compressed
214+
215+**See:** `internal/store/compression.go` for compression logic
216+
217+## Loop Termination
218+
219+**Success Exit:**
220+
221+- LLM returns response without tool calls (line 91)
222+- Turn completes, user regains control
223+
224+**Error Exit:**
225+
226+- LLM call fails (line 70-72)
227+- Tool execution fails (line 107-109)
228+- Max rounds exceeded (line 115)
229+
230+**Max Rounds:** 20 iterations prevents infinite loops if LLM repeatedly calls same tool.
231+
232+## Message Roles
233+
234+### User Messages
235+
236+- **Origin:** User input or autoplay
237+- **Added:** Before `processTurn()` call
238+- **Location:** `cli.go:246` (manual), `autoplay.go:190` (autoplay)
239+
240+### Assistant Messages
241+
242+- **Origin:** LLM response
243+- **Added:** During `ProcessTurn` round
244+- **Variants:**
245+ - Text only: `Role: "assistant", Content: "..."`
246+ - With tool calls: `Role: "assistant", Content: "...", ToolCalls: [...]`
247+
248+### Tool Messages
249+
250+- **Origin:** Tool execution results
251+- **Added:** During `executeToolCalls`
252+- **Format:** `Role: "tool", Content: "result", ToolCallID: "..."`
253+
254+## Thread Safety
255+
256+**Mutex Protection:**
257+
258+- `app.mu` protects `app.history` (cli.go:34)
259+- Lock acquired for snapshot creation (cli.go:268-271)
260+- Lock acquired for message append via `addMessage()` (cli.go:286-288)
261+- `opts.History` is local to `ProcessTurn`, no lock needed
262+
263+**Concurrency Scenarios:**
264+
265+- Manual input and autoplay both call `processTurn()` serially
266+- Each turn operates on its own snapshot
267+- Callbacks serialize access to `app.history` via mutex
268+
269+## Error Handling
270+
271+**LLM Call Failure:**
272+
273+- Returns error immediately
274+- Caller displays error to user
275+- Turn aborted
276+
277+**Tool Call Failure:**
278+
279+- Creates error tool result: `Content: "Error: ..."`
280+- Continues to next tool in list
281+- LLM sees error in next round, can recover
282+
283+**Max Rounds Exceeded:**
284+
285+- Returns error: `"too many tool call rounds (limit: 20)"`
286+- Indicates LLM stuck in loop (bug or model issue)
287+- User sees error, can try different prompt
288+
289+## Performance Characteristics
290+
291+**History Compression:**
292+
293+- Reduces token usage for long conversations
294+- Trade-off: Old details lost vs context window limits
295+- Compression runs every round (negligible overhead)
296+
297+**Round Complexity:**
298+
299+- Each round: 1 LLM call + N tool executions
300+- Typical turn: 1-5 rounds
301+- Worst case: 20 rounds (max limit)
302+
303+**Memory:**
304+
305+- `opts.History` grows during turn (O(messages))
306+- Snapshot copied at turn start (O(messages))
307+- Released at turn end
308+
309+## Configuration
310+
311+**MaxToolRounds:** 20
312+
313+- Prevents infinite loops
314+- Increase if legitimate use cases need more rounds
315+- Decrease to fail fast during debugging
316+
317+**HistoryKeepLast:** 10
318+
319+- Number of recent turns to keep uncompressed
320+- Increase for more context (higher token usage)
321+- Decrease for faster compression (less context)
322+
323+## Future Improvements
324+
325+**Streaming:** Support streaming LLM responses for faster perceived performance
326+
327+**History Window:** Smarter compression based on token count, not just turn count
documentation/architecture/PROJECT_STRUCTURE.md+0−203
@@ -1,203 +0,0 @@
1-# Mysis Project Structure
2-
3-This document describes the scaffolded project structure and reused components from zoea-nova.
4-
5-## Directory Structure
6-
7-```
8-mysis/
9-├── cmd/
10-│ └── mysis/ # Main application entry point
11-├── internal/
12-│ ├── config/ # Configuration handling (from zoea-nova)
13-│ ├── constants/ # Application constants
14-│ ├── mcp/ # MCP client and proxy (from zoea-nova)
15-│ ├── provider/ # LLM provider abstraction (from zoea-nova)
16-│ ├── store/ # SQLite persistence for conversation history
17-│ └── styles/ # UI styling with brand colors
18-├── assets/
19-│ └── logos/ # Branding assets (from zoea-nova)
20-├── documentation/
21-│ ├── architecture/ # Architecture documentation
22-│ └── guides/ # User guides
23-├── config.toml # Configuration file (from zoea-nova)
24-├── go.mod # Go module definition
25-├── Makefile # Build automation
26-├── LICENSE # License file
27-├── .gitignore # Git ignore patterns
28-└── README.md # Project documentation
29-```
30-
31-## Reused Components from zoea-nova
32-
33-### 1. MCP Package (`internal/mcp/`)
34-Complete MCP client implementation with:
35-- HTTP transport for Streamable HTTP MCP
36-- Session management
37-- Tool discovery and invocation
38-- Proxy architecture for local tools
39-- Retry logic and error handling
40-
41-**Files:**
42-- `client.go` - MCP HTTP client
43-- `proxy.go` - MCP proxy with local tool support
44-- `stub.go` - Stub server for offline testing
45-- `tools.go` - Local tool implementations (credential management)
46-- `tools_test.go` - Unit tests for tool handlers
47-- `integration_test.go` - Full workflow tests with proxy
48-- Additional tests for all components
49-
50-### 2. Provider Package (`internal/provider/`)
51-LLM provider abstraction with:
52-- OpenAI-compatible API client
53-- Ollama support
54-- Rate limiting
55-- Retry logic
56-- Tool calling support
57-
58-**Files:**
59-- `provider.go` - Provider interface and registry
60-- `openai_common.go` - OpenAI-compatible base implementation
61-- `opencode.go` - OpenCode Zen provider
62-- `ollama.go` - Ollama provider
63-- `factory.go` - Provider factory pattern
64-- Tests for all providers
65-
66-### 3. Config Package (`internal/config/`)
67-Configuration management with:
68-- TOML config file parsing
69-- Credentials handling
70-- Data directory management (`~/.config/mysis`)
71-- Provider configuration
72-
73-**Files:**
74-- `config.go` - Config structures and loading
75-- `credentials.go` - Secure credential handling
76-- Tests
77-
78-### 4. Store Package (`internal/store/`)
79-SQLite persistence layer for conversation history and credentials:
80-- Session management (create, resume, list)
81-- Message storage with tool calls and reasoning
82-- Multi-instance support (no locking conflicts)
83-- WAL mode for concurrent access
84-- Session-scoped credential storage
85-
86-**Database Schema:**
87-- `sessions` - Conversation sessions with provider info
88-- `messages` - Message history per session
89-- `session_credentials` - Game credentials per session (foreign key to sessions)
90-- Stored at `~/.config/mysis/mysis.db`
91-
92-**Files:**
93-- `store.go` - Database operations and schema
94-- `credentials_test.go` - Credential storage tests
95-
96-### 5. Brand Assets
97-- Logo files (SVG format)
98-- Brand colors: #9D00FF (electric purple), #00FFCC (bright teal)
99-- Style definitions in `internal/styles/styles.go`
100-
101-### 6. Configuration
102-- `config.toml` with provider definitions
103-- Support for Ollama (local) and OpenCode Zen (cloud)
104-- MCP upstream configuration
105-
106-## Technology Stack
107-
108-Core dependencies:
109-- **Go 1.25.6** - Programming language
110-- **SQLite 3** - Conversation persistence (`github.com/mattn/go-sqlite3`)
111-- **UUID** - Session IDs (`github.com/google/uuid`)
112-- **Lipgloss** - Terminal styling
113-- **go-openai** - OpenAI-compatible API client (`github.com/sashabaranov/go-openai`)
114-- **zerolog** - Structured logging
115-- **TOML** - Configuration format (`github.com/BurntSushi/toml`)
116-
117-## Brand Colors
118-
119-From zoea-nova design system:
120-- **Primary (Brand Purple):** #9D00FF
121-- **Secondary (Teal):** #00FFCC
122-- **Background:** #08080F (deep space black)
123-- **Error:** #FF3366
124-- **Success:** #00FF66
125-- **Muted:** #5555AA
126-
127-## Next Steps
128-
129-This is a scaffold with reusable infrastructure. Implementation of application-specific features should:
130-
131-1. Define the application's purpose and requirements
132-2. Design data models and state management
133-3. Implement core business logic
134-4. Build TUI components using the established brand styling
135-5. Add tests following the patterns from zoea-nova
136-
137-## Data Storage
138-
139-**Config Directory:** `~/.config/mysis/`
140-- `config.toml` - Configuration file (optional, falls back to `./config.toml`)
141-- `credentials.json` - API keys (mode 0600)
142-- `mysis.db` - SQLite database for conversation history and game credentials
143-- `account-backup.md` - Backup of SpaceMolt test accounts
144-- `credentials-backup-*.sql` - Timestamped credential backups
145-
146-**Session Management:**
147-- Each CLI instance creates a unique session (UUID)
148-- Sessions can be named for easy resumption: `--session my-session`
149-- Anonymous sessions get auto-generated IDs
150-- Multiple instances can run concurrently without conflicts
151-
152-**Database Features:**
153-- WAL mode for concurrent read/write
154-- Automatic schema initialization
155-- Full conversation history (user, assistant, tool messages)
156-- Tool calls stored as JSON
157-- Session metadata (provider, model, timestamps)
158-- Foreign key constraints enabled (CASCADE delete for credentials)
159-
160-**Credential Management:**
161-- Session-scoped credential storage via MCP tools
162-- Agent can save/retrieve game credentials without user re-entry
163-- Credentials isolated by session (Session A cannot access Session B's credentials)
164-- Automatic cleanup when session is deleted (CASCADE)
165-- Tools: `save_credentials`, `get_credentials`
166-- Registered automatically in CLI on startup
167-
168-## Local MCP Tools
169-
170-The project includes local MCP tools registered with the proxy and available to the agent:
171-
172-### Credential Management Tools
173-
174-**`save_credentials`** - Saves username and password for the current session.
175-- **Input:** `{ "username": "string", "password": "string" }`
176-- **Response:** Success message with username confirmation
177-- **Validation:** Both fields required (non-empty)
178-
179-**`get_credentials`** - Retrieves saved credentials for the current session.
180-- **Input:** Empty object `{}`
181-- **Response:** JSON with username/password, or message if none saved
182-- **Session isolation:** Each session can only access its own credentials
183-
184-**Implementation:**
185-- Defined in `internal/mcp/tools.go`
186-- Registered automatically in `internal/cli/cli.go` on startup
187-- Session ID injected via closure (never exposed to agent)
188-- Full test coverage in `tools_test.go` and `integration_test.go`
189-
190-**Backup/Restore:**
191-- `make backup-credentials` - Create timestamped SQL backup
192-- Restore: `sqlite3 ~/.config/mysis/mysis.db < backup-file.sql`
193-
194-See `documentation/architecture/CREDENTIAL_TOOLS.md` for detailed implementation.
195-
196-## Notes
197-
198-- All import paths updated from `github.com/xonecas/zoea-nova` to `github.com/xonecas/mysis`
199-- The MCP client is configured to connect to `https://game.spacemolt.com/mcp`
200-- Provider configurations support both local (Ollama) and cloud (OpenCode Zen) models
201-- The project maintains the retro-futuristic aesthetic from zoea-nova
202-- Config directory changed from `~/.mysis` to `~/.config/mysis` (XDG Base Directory standard)
203-- Foreign key constraints enabled in SQLite for referential integrity
internal/llm/loop.go+29−14
@@ -83,25 +83,31 @@ func ProcessTurn(ctx context.Context, opts ProcessTurnOptions) error {
8383 }
8484
8585 // Add assistant response to history
86- opts.OnMessage(provider.Message{
86+ assistantMsg := provider.Message{
8787 Role: "assistant",
8888 Content: resp.Content,
89- })
89+ }
90+ opts.OnMessage(assistantMsg)
91+ opts.History = append(opts.History, assistantMsg)
9092
9193 return nil
9294 }
9395
9496 // Tool calls present - add assistant message with tool calls to history
95- opts.OnMessage(provider.Message{
97+ assistantMsg := provider.Message{
9698 Role: "assistant",
9799 Content: resp.Content,
98100 ToolCalls: resp.ToolCalls,
99- })
101+ }
102+ opts.OnMessage(assistantMsg)
103+ opts.History = append(opts.History, assistantMsg)
100104
101- // Execute each tool call
102- if err := executeToolCalls(ctx, opts.Proxy, resp.ToolCalls, opts.OnMessage); err != nil {
105+ // Execute each tool call and update history
106+ toolResults, err := executeToolCalls(ctx, opts.Proxy, resp.ToolCalls, opts.OnMessage)
107+ if err != nil {
103108 return err
104109 }
110+ opts.History = append(opts.History, toolResults...)
105111
106112 // Continue loop to let LLM process tool results
107113 }
@@ -124,7 +130,10 @@ func displayReasoning(reasoning string) {
124130 }
125131
126132 // executeToolCalls executes a list of tool calls and adds results to history.
127-func executeToolCalls(ctx context.Context, proxy *mcp.Proxy, toolCalls []provider.ToolCall, onMessage MessageCallback) error {
133+// Returns the list of tool result messages that were added.
134+func executeToolCalls(ctx context.Context, proxy *mcp.Proxy, toolCalls []provider.ToolCall, onMessage MessageCallback) ([]provider.Message, error) {
135+ var toolResults []provider.Message
136+
128137 for _, toolCall := range toolCalls {
129138 fmt.Print(styles.Secondary.Render(fmt.Sprintf("⚙ %s", toolCall.Name)))
130139
@@ -139,11 +148,13 @@ func executeToolCalls(ctx context.Context, proxy *mcp.Proxy, toolCalls []provide
139148 fmt.Println(styles.Error.Render(" Error: " + err.Error()))
140149
141150 // Add error result to history
142- onMessage(provider.Message{
151+ toolMsg := provider.Message{
143152 Role: "tool",
144153 Content: fmt.Sprintf("Error: %v", err),
145154 ToolCallID: toolCall.ID,
146- })
155+ }
156+ onMessage(toolMsg)
157+ toolResults = append(toolResults, toolMsg)
147158 continue
148159 }
149160
@@ -156,11 +167,13 @@ func executeToolCalls(ctx context.Context, proxy *mcp.Proxy, toolCalls []provide
156167 }
157168
158169 // Add error result to history
159- onMessage(provider.Message{
170+ toolMsg := provider.Message{
160171 Role: "tool",
161172 Content: errText,
162173 ToolCallID: toolCall.ID,
163- })
174+ }
175+ onMessage(toolMsg)
176+ toolResults = append(toolResults, toolMsg)
164177 continue
165178 }
166179
@@ -172,14 +185,16 @@ func executeToolCalls(ctx context.Context, proxy *mcp.Proxy, toolCalls []provide
172185 displayToolResult(resultText)
173186
174187 // Add tool result to history
175- onMessage(provider.Message{
188+ toolMsg := provider.Message{
176189 Role: "tool",
177190 Content: resultText,
178191 ToolCallID: toolCall.ID,
179- })
192+ }
193+ onMessage(toolMsg)
194+ toolResults = append(toolResults, toolMsg)
180195 }
181196
182- return nil
197+ return toolResults, nil
183198 }
184199
185200 // displayToolArguments shows tool arguments in a truncated format.