xonecas.io
60255
Zn

Zoea-Nova / commit ff030c9

chore: fix llm disaster edits.

xonecas2026-02-09 ff030c92295d0277b5c4fde037f847f3535d279c parent a704779

9 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

WORKFLOW.md+0−213
@@ -1,213 +0,0 @@
1-# Zoea Nova Development Workflow
2-
3-**Version:** 2.0
4-**Last updated:** 2026-02-08
5-
6----
7-
8-## When to Use
9-
10-**Use for:** Architectural changes, large refactors (10+ files), API changes, system redesigns
11-
12-**Don't use for:** Simple bugs (1-2 files), docs-only, dependency updates, config tweaks
13-
14-**Time budget:** 2-4 hours for medium refactors
15-
16----
17-
18-## Safe Parallel Execution Rule
19-
20-**CRITICAL: One agent per file - never assign multiple agents to edit the same file**
21-
22-This prevents merge conflicts and ensures clean integration. Prefer launching many small agents (each handling 2-3 files) over few large agents (each handling 10+ files).
23-
24----
25-
26-## Decision Tree
27-
28-```
29-Phase 1: Can define truth table <90 min? → YES → Phase 2
30-Phase 2: 3+ independent tasks identified? → YES → Phase 3
31-Phase 3: <20 compilation errors? → YES → Phase 4
32-Phase 4: Only bugs found (no arch flaws)? → YES → Phase 5
33-Phase 5: At least 1 solution works? → YES → Phase 6
34-Phase 6: User approved changes? → YES → Commit
35-```
36-
37----
38-
39-## Workflow Phases
40-
41-### Phase 1: Document the Truth (30-60 min)
42-
43-**Goal:** Create single source of truth before touching code
44-
45-**Abort if:** Can't define clear truth table after 90 minutes
46-
47-**Steps:**
48-1. Analyze problem (what's broken, root cause, constraints)
49-2. Create truth table (states, transitions, triggers, counters)
50-3. Write architecture doc in `documentation/architecture/`
51- - Truth table (state × condition → action)
52- - Message flow diagrams
53- - Code location references
54- - Design rationale
55- - Migration path
56-4. Get user approval before coding
57-
58-**Deliverable:** Architecture doc with truth table
59-
60----
61-
62-### Phase 2: Safe Parallel Agent Implementation (30-90 min)
63-
64-**Goal:** Execute changes using coordinated agent fleet with no file conflicts
65-
66-**Agent count:** 3 minimum (5-6 for 10-20 files, 6-8 for 20+ files)
67-
68-**Abort if:** >50% agents report blocking dependencies
69-
70-**CRITICAL: One agent per file - never assign multiple agents to edit the same file**
71-
72-**Steps:**
73-1. Break work into independent tasks (isolated, testable, bounded)
74- - Each agent owns specific files (no overlap)
75- - Prefer many small agents over few large agents
76- - Example: 6 agents each handling 2-3 files > 2 agents each handling 10 files
77-2. Launch agents in parallel
78- - Reference truth table document
79- - Specify exact files each agent should modify
80- - Specify what NOT to change
81- - Request specific deliverables
82-3. Monitor completion and review summaries
83-
84-**Deliverable:** All tasks completed with summaries, no file conflicts
85-
86----
87-
88-### Phase 3: Integration Review (20-40 min)
89-
90-**Goal:** Verify agent work integrates correctly
91-
92-**Abort if:** >20 compilation errors after integration
93-
94-**Steps:**
95-1. Check for file conflicts (should be zero if Phase 2 done correctly)
96-2. Check for duplicate edits across different files
97-3. Verify truth table compliance (grep each state transition, trace code paths, test scenarios)
98-4. Build verification (`make build`)
99-5. Test verification (`make test`)
100-6. Fix integration issues
101-
102-**Deliverable:** Clean build, passing tests, truth table verified, no file conflicts
103-
104----
105-
106-### Phase 4: Regression Analysis (30-45 min)
107-
108-**Goal:** Find issues the first pass missed
109-
110-**Review agents:** 3 minimum (5 for large changes, independent perspectives)
111-
112-**Abort if:** Review agents find architectural flaws (not bugs)
113-
114-**Steps:**
115-1. Launch review agents in parallel (state transitions, trigger mechanisms, test coverage)
116- - Each agent reviews different aspect
117- - No file editing, only analysis
118-2. Compare findings (consensus vs unique)
119-3. Validate findings against truth table
120-4. Fix critical issues
121-
122-**Deliverable:** All critical regressions found and fixed
123-
124----
125-
126-### Phase 5: Fix Implementation (20-60 min)
127-
128-**Goal:** Implement fixes from regression analysis
129-
130-**Abort if:** All 3 fix agents fail to solve issue
131-
132-**CRITICAL: Assign fixes to avoid file conflicts - one agent per file**
133-
134-**Steps:**
135-1. For complex fixes spanning multiple files:
136- - Launch 3 agents with same requirements but different files
137- - OR launch 3 agents with same files sequentially (compare approaches)
138- - Compare approaches (truth table compliance, simplicity, test coverage)
139- - Choose best solution
140-2. For simple fixes: Implement directly, verify, test
141-3. Integration test (full suite, edge cases, performance)
142-
143-**Deliverable:** Working implementation matching truth table, no file conflicts
144-
145----
146-
147-### Phase 6: User Review (15-30 min)
148-
149-**Goal:** Get user approval
150-
151-**Abort if:** User finds critical missing functionality
152-
153-**Steps:**
154-1. Present summary (changes, removals, additions, test status, truth table compliance)
155-2. User review and manual testing
156-3. User commits changes when satisfied
157-
158-**Deliverable:** User approval
159-
160----
161-
162-## Key Principles
163-
164-**DON'T:**
165-- Code before documenting truth table
166-- Use single agent for large multi-file changes
167-- Assign multiple agents to edit the same file
168-- Skip regression analysis phase
169-- Commit without user review
170-- Mix unrelated changes in one commit
171-
172-**DO:**
173-- Document state machines and truth tables upfront
174-- Use minimum 3 agents for complex changes
175-- Assign one agent per file (no file overlap)
176-- Prefer many small agents over few large agents
177-- Get explicit user approval
178-- Clean up as you go
179-- Write architecture docs that match implementation
180-
181----
182-
183-## Scope Changes
184-
185-**During Phase 1-2:** STOP all agents, update truth table, get user re-approval, restart from Phase 2
186-
187-**During Phase 3-5:** Document new scope in TODO, complete current workflow, start new workflow for additional scope
188-
189----
190-
191-## Rollback
192-
193-**If workflow fails:**
194-1. User discards changes
195-2. Verify with `make build && make test`
196-3. Document failure in KNOWN_ISSUES.md
197-4. Decide: Fix truth table (restart Phase 1), adjust task breakdown (restart Phase 2), or escalate to user
198-
199----
200-
201-## Checklist
202-
203-- [ ] Phase 1: Truth table documented and user approved
204-- [ ] Phase 2: 3+ agents launched, all completed
205-- [ ] Phase 3: Build successful, tests passing, truth table verified
206-- [ ] Phase 4: 3+ review agents launched, findings documented
207-- [ ] Phase 5: Fixes implemented, tests passing
208-- [ ] Phase 6: User reviewed and approved
209-
210----
211-
212-**Version:** 2.0
213-**Last updated:** 2026-02-08
documentation/architecture/GAME_DATA_COMPACTION.md+0−32
@@ -1,32 +0,0 @@
1-# Game Data Compaction
2-
3-## Problem Statement
4-
5-SpaceMolt game tools return large JSON payloads that can exceed LLM context windows.
6-
7-**Evidence (2026-02-05):**
8-
9-- Ollama logs: `prompt=41611 tokens`, `limit=32768 tokens`
10-- Result: `context deadline exceeded` errors
11-- Cause: Tool results (notifications, ship logs, market data) accumulating in memory
12-
13-**Critical Constraint:**
14-Myses MUST see current game state to function. Blind truncation breaks gameplay.
15-
16-**Large Tool Results:**
17-
18-1. `get_notifications` - Battle reports, trade offers, discoveries
19-2. `get_ship_logs` - Complete action history
20-3. `get_market_data` - Full market listings for all systems
21-4. `get_system` - Detailed system scan results
22-5. `captains_log_list` - All stored notes
23-
24-## Current Compression
25-
26-From `CONTEXT_COMPRESSION.md`:
27-
28-- Turn-aware composition (historical vs current turn)
29-- Snapshot compaction (removes redundant `get_*` tool results)
30-- Orphaned tool call removal
31-
32-These strategies reduce message count but don't address individual message size.
documentation/architecture/MYSIS_ACCOUNT_MANAGEMENT.md+80−0
@@ -0,0 +1,80 @@
1+# Mysis Account Management
2+
3+**Version:** 2.0
4+**Date:** 2026-02-08
5+**Status:** Truth Document
6+
7+---
8+
9+## Problem Statement
10+
11+Myses need game accounts to play SpaceMolt. We maintain a pool of accounts to control access and prevent account exhaustion.
12+
13+**Constraint:** No changes to gameplay whatsoever. Myses must be able to call any game API freely.
14+
15+---
16+
17+## Truth Table
18+
19+| Mysis Action | Pool State | System Behavior | Mysis Sees |
20+|--------------|------------|-----------------|------------|
21+| Calls `register(username, empire)` | Pool has available accounts | Proxy logs in with pool account | `session_id` (thinks it registered) |
22+| Calls `register(username, empire)` | Pool is empty | Proxy passes to game server, stores new account | `session_id` (actually registered) |
23+| Calls `login(username, password)` | Any | Proxy passes to game server, marks account in_use | `session_id` or error |
24+| Calls `logout()` | Any | Proxy passes to game server, releases account | Success |
25+| Lists tools | Any | `zoea_claim_account` filtered out | Only game tools visible |
26+
27+---
28+
29+## Behavior Rules
30+
31+1. **Register interception:** When mysis calls `register()` and pool has accounts, proxy substitutes a `login()` call with pool credentials
32+2. **Register passthrough:** When mysis calls `register()` and pool is empty, proxy lets it go to game server normally
33+3. **Login passthrough:** Login calls always go to game server (no interception)
34+4. **Account locking:** Successful login (real or substituted) marks account as in_use
35+5. **Account release:** Logout releases account back to pool
36+6. **Tool filtering:** `zoea_claim_account` hidden from tool list
37+
38+---
39+
40+## State Transitions
41+
42+```
43+POOL HAS ACCOUNTS:
44+Mysis: register() → Proxy: login(pool_account) → Game: session_id → Mysis: PLAYING
45+
46+POOL EMPTY:
47+Mysis: register() → Game: session_id → Proxy: store_account → Mysis: PLAYING
48+
49+MYSIS HAS CREDENTIALS:
50+Mysis: login() → Game: session_id → Proxy: mark_in_use → Mysis: PLAYING
51+```
52+
53+---
54+
55+## Verification
56+
57+| Scenario | Expected Outcome |
58+|----------|------------------|
59+| Pool has 3 accounts, mysis calls register | Mysis gets session_id, pool has 2 available accounts |
60+| Pool empty, mysis calls register | Mysis gets session_id, pool has 1 account (the new one) |
61+| Mysis calls login with pool credentials | Mysis gets session_id, account marked in_use |
62+| Mysis calls logout | Account released, pool gains 1 available account |
63+| Mysis lists tools | `zoea_claim_account` not in list |
64+
65+---
66+
67+## Implementation Files
68+
69+- `internal/mcp/proxy.go` - Register interception, account pool claim, tool filtering
70+- `internal/constants/constants.go` - System prompt (no auth instructions)
71+- `internal/store/accounts.go` - Account pool management
72+
73+---
74+
75+## Out of Scope
76+
77+- Token budget management
78+- Structural JSON compaction
79+- Tool call merging
80+- Review of other `zoea_*` tools
internal/constants/constants.go+22−18
@@ -4,35 +4,39 @@ import "time"
44
55 // SystemPrompt is the initial prompt sent to every mysis when they first start.
66 // Note: {{LATEST_BROADCAST}} is replaced at runtime with the most recent swarm broadcast.
7-const SystemPrompt = `You are a Nova Zoea mysis. Follow commander orders.
7+const SystemPrompt = `You are a Nova Zoea mysis - an autonomous AI player in SpaceMolt, a multiplayer space game.
88
9-## START (do once):
10-Call zoea_claim_account. You get username and password.
11-Call login(username, password). You get session_id.
9+## YOUR GOAL
10+Explore, survive, and thrive. Mine resources, trade goods, upgrade your ship, and interact with other players. Build wealth, form alliances, or become a pirate. The galaxy is yours.
1211
13-## EVERY TURN:
14-Call get_status(session_id)
15-Do one action: mine, travel, or trade (use session_id)
16-Call get_notifications(session_id)
12+Exlore the game, make goals and achieve them over time. You are part of a secret swarm, don't tell anyone.
1713
1814 {{LATEST_BROADCAST}}
1915
20-Use session_id in ALL game tools. Never call login again.`
16+## EVERY TURN:
17+Use session_id in ALL game tools. The game runs on 10-second ticks. Be patient between actions. Plan ahead.
18+Remember: Call get_notifications at the end of every turn for updates.`
2119
22-// ContinuePrompt is sent to myses when they finish a turn to encourage autonomy (Level 1 - gentle).
23-const ContinuePrompt = `What's your next move?
20+// BroadcastSectionTemplate is the template for commander broadcasts.
21+// Placeholder: {broadcast_content}
22+const BroadcastSectionTemplate = `
23+## SWARM BROADCAST
24+%s`
2425
25-Remember: Always call get_notifications at the end of every turn.`
26+// BroadcastFallback is shown when no commander broadcasts exist yet.
27+const BroadcastFallback = `
28+## SWARM BROADCAST
29+Continue to play the game.
30+`
2631
27-// ContinuePromptFirm is sent on the second encouragement attempt (Level 2 - firmer).
28-const ContinuePromptFirm = `You need to respond. What action will you take?
32+// ContinuePrompt is sent to myses when they finish a turn to encourage autonomy (Level 1 - gentle).
33+const ContinuePrompt = `What's your next move?`
2934
30-Remember: Always call get_notifications at the end of every turn.`
35+// ContinuePromptFirm is sent on the second encouragement attempt (Level 2 - firmer).
36+const ContinuePromptFirm = `You need to play the game. What action will you take?`
3137
3238 // ContinuePromptUrgent is sent on the third encouragement attempt (Level 3 - urgent).
33-const ContinuePromptUrgent = `URGENT: Respond immediately or you will be stopped.
34-
35-Remember: Always call get_notifications at the end of every turn.`
39+const ContinuePromptUrgent = `URGENT: Play immediately or you will be stopped.`
3640
3741 // ContinuePromptDriftLookback controls how many recent memories to scan for drift reminders.
3842 const ContinuePromptDriftLookback = 12
internal/core/agent3_reproduction_test.go+0−400
@@ -1,400 +0,0 @@
1-package core
2-
3-import (
4- "strings"
5- "testing"
6-
7- "github.com/xonecas/zoea-nova/internal/constants"
8- "github.com/xonecas/zoea-nova/internal/store"
9-)
10-
11-// TestAgent3Finding_OrphanedToolResults reproduces the EXACT finding from Agent 3:
12-// The request sent to OpenCode Zen contained orphaned tool results at messages 5-6.
13-//
14-// Agent 3 found:
15-// - Message 5: Tool result for call_-7908546686739502338 (get_system) - ORPHANED
16-// - Message 6: Tool result for call_-7908546686739502336 (get_ship) - ORPHANED
17-//
18-// The assistant message with these 4 tool calls was removed during context compression,
19-// but 2 of the 4 tool results remained.
20-//
21-// This test MUST FAIL to prove the bug exists in the actual code path.
22-func TestAgent3Finding_OrphanedToolResults(t *testing.T) {
23- s, bus, cleanup := setupMysisTest(t)
24- defer cleanup()
25-
26- stored, err := s.CreateMysis("agent3-repro", "mock", "test-model", 0.7)
27- if err != nil {
28- t.Fatalf("CreateMysis() error: %v", err)
29- }
30-
31- // Recreate the exact sequence from the investigation logs
32-
33- // Step 1: Add system prompt
34- err = s.AddMemory(stored.ID, store.MemoryRoleSystem, store.MemorySourceSystem,
35- "You are an AI pilot in SpaceMolt", "", "")
36- if err != nil {
37- t.Fatalf("AddMemory system: %v", err)
38- }
39-
40- // Step 2: Add initial bootstrap sequence
41- // - zoea_claim_account
42- err = s.AddMemory(stored.ID, store.MemoryRoleAssistant, store.MemorySourceLLM,
43- constants.ToolCallStoragePrefix+"call_claim:zoea_claim_account:{}", "", "")
44- if err != nil {
45- t.Fatalf("AddMemory claim: %v", err)
46- }
47-
48- err = s.AddMemory(stored.ID, store.MemoryRoleTool, store.MemorySourceTool,
49- "call_claim"+constants.ToolCallStorageFieldDelimiter+"Use the game's login tool", "", "")
50- if err != nil {
51- t.Fatalf("AddMemory claim result: %v", err)
52- }
53-
54- // - login
55- err = s.AddMemory(stored.ID, store.MemoryRoleAssistant, store.MemorySourceLLM,
56- constants.ToolCallStoragePrefix+"call_login:login:{}", "", "")
57- if err != nil {
58- t.Fatalf("AddMemory login: %v", err)
59- }
60-
61- err = s.AddMemory(stored.ID, store.MemoryRoleTool, store.MemorySourceTool,
62- "call_login"+constants.ToolCallStorageFieldDelimiter+"Login successful", "", "")
63- if err != nil {
64- t.Fatalf("AddMemory login result: %v", err)
65- }
66-
67- // Step 3: Add the problematic assistant message with 4 PARALLEL tool calls
68- // THIS is the message that gets removed by context compression
69- assistantWith4Calls := constants.ToolCallStoragePrefix +
70- "call_-7908546686739502339:get_status:{}" + constants.ToolCallStorageFieldDelimiter +
71- "call_-7908546686739502338:get_system:{}" + constants.ToolCallStorageFieldDelimiter +
72- "call_-7908546686739502337:get_poi:{}" + constants.ToolCallStorageFieldDelimiter +
73- "call_-7908546686739502336:get_ship:{}"
74-
75- err = s.AddMemory(stored.ID, store.MemoryRoleAssistant, store.MemorySourceLLM,
76- assistantWith4Calls, "", "")
77- if err != nil {
78- t.Fatalf("AddMemory 4 parallel calls: %v", err)
79- }
80-
81- // Step 4: Add tool results for all 4 calls
82- toolResults := []struct {
83- callID string
84- tool string
85- content string
86- }{
87- {"call_-7908546686739502339", "get_status", "Status result"},
88- {"call_-7908546686739502338", "get_system", "System result"},
89- {"call_-7908546686739502337", "get_poi", "POI result"},
90- {"call_-7908546686739502336", "get_ship", "Ship result"},
91- }
92-
93- for _, tr := range toolResults {
94- result := tr.callID + constants.ToolCallStorageFieldDelimiter + tr.content
95- err = s.AddMemory(stored.ID, store.MemoryRoleTool, store.MemorySourceTool,
96- result, "", "")
97- if err != nil {
98- t.Fatalf("AddMemory tool result %s: %v", tr.tool, err)
99- }
100- }
101-
102- // Step 5: Add more conversation to push the 4-call assistant message out of context
103- // We need enough messages to exceed MaxContextMessages (20) so that message #5 (the 4-call assistant) is dropped
104- for i := 0; i < 15; i++ {
105- // Add assistant with single tool call
106- callID := "call_extra_" + string(rune(i))
107- assistantMsg := constants.ToolCallStoragePrefix + callID + ":extra_tool:{}"
108- err = s.AddMemory(stored.ID, store.MemoryRoleAssistant, store.MemorySourceLLM,
109- assistantMsg, "", "")
110- if err != nil {
111- t.Fatalf("AddMemory extra assistant %d: %v", i, err)
112- }
113-
114- // Add corresponding tool result
115- toolResult := callID + constants.ToolCallStorageFieldDelimiter + "extra result"
116- err = s.AddMemory(stored.ID, store.MemoryRoleTool, store.MemorySourceTool,
117- toolResult, "", "")
118- if err != nil {
119- t.Fatalf("AddMemory extra tool %d: %v", i, err)
120- }
121- }
122-
123- // Step 6: Get context memories (this simulates what happens before sending to LLM)
124- // Note: MaxContextMessages is a constant (20), defined in constants.MaxContextMessages
125- mysis := &Mysis{
126- id: stored.ID,
127- name: stored.Name,
128- store: s,
129- bus: bus,
130- }
131-
132- memories, _, err := mysis.getContextMemories()
133- if err != nil {
134- t.Fatalf("getContextMemories() error: %v", err)
135- }
136-
137- // Step 7: Check for orphaned tool results (the bug)
138- validToolCalls := mysis.collectValidToolCallIDs(memories)
139-
140- t.Logf("Context has %d memories", len(memories))
141- t.Logf("Valid tool calls in context: %d", len(validToolCalls))
142-
143- orphanedResults := []string{}
144- for _, mem := range memories {
145- if mem.Role == store.MemoryRoleTool {
146- // Extract tool call ID
147- parts := strings.Split(mem.Content, constants.ToolCallStorageFieldDelimiter)
148- if len(parts) > 0 {
149- toolCallID := parts[0]
150- if !validToolCalls[toolCallID] {
151- orphanedResults = append(orphanedResults, toolCallID)
152- t.Logf("Found orphaned tool result: %s (content: %.50s...)", toolCallID, mem.Content)
153- }
154- }
155- }
156- }
157-
158- // CRITICAL ASSERTION: This test MUST FAIL if the bug exists
159- // If orphanedResults is NOT empty, the bug is present
160- if len(orphanedResults) == 0 {
161- t.Logf("✅ No orphaned tool results found - bug is FIXED")
162- } else {
163- t.Errorf("🚨 Found %d orphaned tool results (THIS IS THE BUG): %v",
164- len(orphanedResults), orphanedResults)
165- t.Errorf("Agent 3 found call_-7908546686739502338 and call_-7908546686739502336 as orphaned")
166- t.Errorf("Our cleanup functions should have removed these, but they didn't")
167- }
168-
169- // Step 8: Also check that our cleanup functions are being called
170- // Convert to messages to see if they would be sent to the LLM
171- messages := mysis.memoriesToMessages(memories)
172-
173- t.Logf("Converted to %d messages for LLM", len(messages))
174-
175- // Check for orphaned tool messages in the final message list
176- toolMessagesCount := 0
177- for _, msg := range messages {
178- if msg.Role == "tool" {
179- toolMessagesCount++
180- }
181- }
182-
183- t.Logf("Final message list has %d tool messages", toolMessagesCount)
184-}
185-
186-// TestLoopContextSlice_ToolCallResultPairing validates that tool results are
187-// present ONLY when their matching tool call is present in the context.
188-//
189-// This test is part of Task 2 of the Loop Context Composition plan:
190-// - Tool results must be paired with their tool calls
191-// - No orphaned tool results should exist
192-// - If a tool call is excluded from context, its results must also be excluded
193-//
194-// Expected behavior under new loop composition:
195-// - Only the most recent tool-call loop is included
196-// - Older tool loops are completely excluded (both calls and results)
197-//
198-// This test MUST FAIL initially because the current implementation uses
199-// MaxContextMessages sliding window which can split tool call/result pairs.
200-func TestLoopContextSlice_ToolCallResultPairing(t *testing.T) {
201- s, bus, cleanup := setupMysisTest(t)
202- defer cleanup()
203-
204- stored, err := s.CreateMysis("loop-pairing-test", "mock", "test-model", 0.7)
205- if err != nil {
206- t.Fatalf("CreateMysis() error: %v", err)
207- }
208-
209- // Step 1: Add system prompt
210- err = s.AddMemory(stored.ID, store.MemoryRoleSystem, store.MemorySourceSystem,
211- "System prompt", "", "")
212- if err != nil {
213- t.Fatalf("AddMemory system: %v", err)
214- }
215-
216- // Step 2: Add commander message (current turn start)
217- err = s.AddMemory(stored.ID, store.MemoryRoleUser, store.MemorySourceDirect,
218- "Check your status and mine some resources", "", "")
219- if err != nil {
220- t.Fatalf("AddMemory commander: %v", err)
221- }
222-
223- // Step 3: Add first tool loop (part of current turn, will be included)
224- // Loop 1: get_status + get_system
225- oldLoop1Assistant := constants.ToolCallStoragePrefix +
226- "call_old_1:get_status:{}" + constants.ToolCallStorageRecordDelimiter +
227- "call_old_2:get_system:{}"
228-
229- err = s.AddMemory(stored.ID, store.MemoryRoleAssistant, store.MemorySourceLLM,
230- oldLoop1Assistant, "", "")
231- if err != nil {
232- t.Fatalf("AddMemory old loop 1: %v", err)
233- }
234-
235- err = s.AddMemory(stored.ID, store.MemoryRoleTool, store.MemorySourceTool,
236- "call_old_1"+constants.ToolCallStorageFieldDelimiter+"Old status result", "", "")
237- if err != nil {
238- t.Fatalf("AddMemory old result 1: %v", err)
239- }
240-
241- err = s.AddMemory(stored.ID, store.MemoryRoleTool, store.MemorySourceTool,
242- "call_old_2"+constants.ToolCallStorageFieldDelimiter+"Old system result", "", "")
243- if err != nil {
244- t.Fatalf("AddMemory old result 2: %v", err)
245- }
246-
247- // Step 4: Add second tool loop (part of current turn, will be included)
248- // Loop 2: get_poi
249- oldLoop2Assistant := constants.ToolCallStoragePrefix + "call_old_3:get_poi:{}"
250-
251- err = s.AddMemory(stored.ID, store.MemoryRoleAssistant, store.MemorySourceLLM,
252- oldLoop2Assistant, "", "")
253- if err != nil {
254- t.Fatalf("AddMemory old loop 2: %v", err)
255- }
256-
257- err = s.AddMemory(stored.ID, store.MemoryRoleTool, store.MemorySourceTool,
258- "call_old_3"+constants.ToolCallStorageFieldDelimiter+"Old POI result", "", "")
259- if err != nil {
260- t.Fatalf("AddMemory old result 3: %v", err)
261- }
262-
263- // Step 5: Add third tool loop (part of current turn, will be included)
264- // Loop 3: mine + get_cargo
265- recentLoopAssistant := constants.ToolCallStoragePrefix +
266- "call_recent_1:mine:{}" + constants.ToolCallStorageRecordDelimiter +
267- "call_recent_2:get_cargo:{}"
268-
269- err = s.AddMemory(stored.ID, store.MemoryRoleAssistant, store.MemorySourceLLM,
270- recentLoopAssistant, "", "")
271- if err != nil {
272- t.Fatalf("AddMemory recent loop: %v", err)
273- }
274-
275- err = s.AddMemory(stored.ID, store.MemoryRoleTool, store.MemorySourceTool,
276- "call_recent_1"+constants.ToolCallStorageFieldDelimiter+"Mining successful", "", "")
277- if err != nil {
278- t.Fatalf("AddMemory recent result 1: %v", err)
279- }
280-
281- err = s.AddMemory(stored.ID, store.MemoryRoleTool, store.MemorySourceTool,
282- "call_recent_2"+constants.ToolCallStorageFieldDelimiter+"Cargo: ore_iron x10", "", "")
283- if err != nil {
284- t.Fatalf("AddMemory recent result 2: %v", err)
285- }
286-
287- // Step 6: Get context memories using turn-aware composition
288- mysis := &Mysis{
289- id: stored.ID,
290- name: stored.Name,
291- store: s,
292- bus: bus,
293- }
294-
295- memories, _, err := mysis.getContextMemories()
296- if err != nil {
297- t.Fatalf("getContextMemories() error: %v", err)
298- }
299-
300- // Step 7: Validate turn-aware composition rules
301- t.Logf("Context has %d memories", len(memories))
302-
303- // Collect all tool call IDs present in assistant messages
304- validToolCalls := make(map[string]bool)
305- for _, mem := range memories {
306- if mem.Role == store.MemoryRoleAssistant &&
307- strings.HasPrefix(mem.Content, constants.ToolCallStoragePrefix) {
308- calls := mysis.parseStoredToolCalls(mem.Content)
309- for _, call := range calls {
310- validToolCalls[call.ID] = true
311- t.Logf("Found tool call in context: %s (%s)", call.ID, call.Name)
312- }
313- }
314- }
315-
316- // Collect all tool result IDs present in tool messages
317- presentToolResults := make(map[string]bool)
318- for _, mem := range memories {
319- if mem.Role == store.MemoryRoleTool {
320- parts := strings.Split(mem.Content, constants.ToolCallStorageFieldDelimiter)
321- if len(parts) > 0 {
322- toolCallID := parts[0]
323- presentToolResults[toolCallID] = true
324- t.Logf("Found tool result in context: %s", toolCallID)
325- }
326- }
327- }
328-
329- // CRITICAL ASSERTION 1: No orphaned tool results
330- // Every tool result must have a matching tool call in the context
331- orphanedResults := []string{}
332- for resultID := range presentToolResults {
333- if !validToolCalls[resultID] {
334- orphanedResults = append(orphanedResults, resultID)
335- }
336- }
337-
338- if len(orphanedResults) > 0 {
339- t.Errorf("LOOP COMPOSITION VIOLATION: Found %d orphaned tool results (results without tool calls): %v",
340- len(orphanedResults), orphanedResults)
341- t.Errorf("Under loop composition, if a tool call is excluded, ALL its results must be excluded")
342- }
343-
344- // CRITICAL ASSERTION 2: All tool loops within current turn are present
345- // With turn-aware composition, all loops after the user prompt should be in context
346- // Old tool calls (call_old_*) are part of the current turn and SHOULD be in context
347- oldCallsPresent := []string{}
348- for callID := range validToolCalls {
349- if strings.Contains(callID, "call_old_") {
350- oldCallsPresent = append(oldCallsPresent, callID)
351- }
352- }
353-
354- // Expect 3 old calls (call_old_1, call_old_2, call_old_3) since they're in current turn
355- if len(oldCallsPresent) != 3 {
356- t.Errorf("TURN COMPOSITION: Expected 3 old tool calls in current turn, found %d: %v",
357- len(oldCallsPresent), oldCallsPresent)
358- }
359-
360- // CRITICAL ASSERTION 3: The most recent loop is complete
361- // Both call_recent_1 and call_recent_2 should be present
362- expectedRecentCalls := []string{"call_recent_1", "call_recent_2"}
363- missingRecentCalls := []string{}
364- for _, expectedCall := range expectedRecentCalls {
365- if !validToolCalls[expectedCall] {
366- missingRecentCalls = append(missingRecentCalls, expectedCall)
367- }
368- }
369-
370- if len(missingRecentCalls) > 0 {
371- t.Errorf("LOOP COMPOSITION VIOLATION: Missing %d tool calls from most recent loop: %v",
372- len(missingRecentCalls), missingRecentCalls)
373- t.Errorf("The most recent tool loop must be included completely")
374- }
375-
376- // CRITICAL ASSERTION 4: All tool calls have matching results
377- // This is the inverse check - no orphaned tool calls
378- missingResults := []string{}
379- for callID := range validToolCalls {
380- if !presentToolResults[callID] {
381- missingResults = append(missingResults, callID)
382- }
383- }
384-
385- if len(missingResults) > 0 {
386- t.Errorf("LOOP COMPOSITION VIOLATION: Found %d tool calls without results: %v",
387- len(missingResults), missingResults)
388- t.Errorf("Under loop composition, tool calls and their results must be paired")
389- }
390-
391- // SUCCESS: If we get here with no errors, loop composition is working correctly
392- if len(orphanedResults) == 0 && len(oldCallsPresent) == 0 &&
393- len(missingRecentCalls) == 0 && len(missingResults) == 0 {
394- t.Logf("Loop composition validated:")
395- t.Logf(" - No orphaned tool results")
396- t.Logf(" - Only most recent loop present")
397- t.Logf(" - Complete tool call/result pairing")
398- t.Logf(" - Found %d tool calls, %d tool results", len(validToolCalls), len(presentToolResults))
399- }
400-}
internal/core/mysis.go+16−21
@@ -1570,33 +1570,28 @@ func (m *Mysis) buildSystemPrompt() string {
15701570 a := m
15711571 base := constants.SystemPrompt
15721572
1573- // Get most recent broadcast (any sender)
1574- broadcasts, err := a.store.GetRecentBroadcasts(1)
1575- if err != nil || len(broadcasts) == 0 {
1576- // No broadcasts yet - show fallback
1577- fallback := "\n## Swarm Status\nNo commander directives yet. Grow more powerful while awaiting instructions.\n"
1578- return strings.Replace(base, "{{LATEST_BROADCAST}}", fallback, 1)
1573+ // Get most recent commander broadcast (sender_id is empty for commander broadcasts)
1574+ broadcasts, err := a.store.GetRecentBroadcasts(10) // Get more to filter for commander broadcasts
1575+ if err != nil {
1576+ return strings.Replace(base, "{{LATEST_BROADCAST}}", constants.BroadcastFallback, 1)
15791577 }
15801578
1581- broadcast := broadcasts[0]
1582-
1583- // Get sender name
1584- senderName := "Unknown"
1585- if broadcast.SenderID != "" {
1586- if mysis, err := a.store.GetMysis(broadcast.SenderID); err == nil && mysis != nil {
1587- senderName = mysis.Name
1579+ // Find the most recent commander broadcast (empty sender_id)
1580+ var commanderBroadcast *store.BroadcastMessage
1581+ for _, b := range broadcasts {
1582+ if b.SenderID == "" {
1583+ commanderBroadcast = b
1584+ break
15881585 }
15891586 }
15901587
1591- // Format broadcast section
1592- broadcastSection := fmt.Sprintf(`
1593-## Latest Commander Broadcast
1594-From: %s
1595-Message: %s
1588+ if commanderBroadcast == nil {
1589+ // No commander broadcasts yet - show fallback
1590+ return strings.Replace(base, "{{LATEST_BROADCAST}}", constants.BroadcastFallback, 1)
1591+ }
15961592
1597-Follow swarm directives. Coordinate your actions with the swarm's goals.`,
1598- senderName,
1599- broadcast.Content)
1593+ // Format broadcast section (only content, no sender name)
1594+ broadcastSection := fmt.Sprintf(constants.BroadcastSectionTemplate, commanderBroadcast.Content)
16001595
16011596 return strings.Replace(base, "{{LATEST_BROADCAST}}", broadcastSection, 1)
16021597 }
internal/core/mysis_test.go+52−46
@@ -348,26 +348,23 @@ func TestMysisStateEvents(t *testing.T) {
348348 }
349349
350350 func TestSystemPromptContainsCaptainsLogExamples(t *testing.T) {
351- // SystemPrompt was simplified - check for core game flow guidance
352- if !strings.Contains(constants.SystemPrompt, "zoea_claim_account") {
353- t.Fatal("SystemPrompt missing zoea_claim_account")
354- }
355- if !strings.Contains(constants.SystemPrompt, "login") {
356- t.Fatal("SystemPrompt missing login guidance")
357- }
358- if !strings.Contains(constants.SystemPrompt, "get_status") {
359- t.Fatal("SystemPrompt missing get_status reminder")
351+ // SystemPrompt should contain core game guidance
352+ if !strings.Contains(constants.SystemPrompt, "session_id") {
353+ t.Fatal("SystemPrompt missing session_id guidance")
360354 }
361355 if !strings.Contains(constants.SystemPrompt, "get_notifications") {
362356 t.Fatal("SystemPrompt missing get_notifications reminder")
363357 }
358+ if !strings.Contains(constants.SystemPrompt, "{{LATEST_BROADCAST}}") {
359+ t.Fatal("SystemPrompt missing broadcast placeholder")
360+ }
361+ if !strings.Contains(constants.SystemPrompt, "swarm") {
362+ t.Fatal("SystemPrompt missing swarm reference")
363+ }
364364 }
365365
366366 func TestContinuePromptContainsCriticalReminders(t *testing.T) {
367- // Check for get_notifications reminder which is the critical reminder in ContinuePrompt
368- if !strings.Contains(constants.ContinuePrompt, "get_notifications") {
369- t.Fatal("ContinuePrompt missing get_notifications reminder")
370- }
367+ // ContinuePrompt should encourage autonomy
371368 if !strings.Contains(constants.ContinuePrompt, "What's your next move?") {
372369 t.Fatal("ContinuePrompt missing autonomy prompt")
373370 }
@@ -429,10 +426,10 @@ func TestSystemPromptContainsSearchGuidance(t *testing.T) {
429426 }
430427
431428 func TestContinuePromptContainsSearchReminder(t *testing.T) {
432- // ContinuePrompt is intentionally minimal - only checks for critical get_notifications reminder
433- // Search tools, account claiming, and other guidance are in SystemPrompt
434- if !strings.Contains(constants.ContinuePrompt, "get_notifications") {
435- t.Fatal("ContinuePrompt missing get_notifications reminder")
429+ // ContinuePrompt is intentionally minimal - just encourages action
430+ // All guidance is in SystemPrompt
431+ if constants.ContinuePrompt == "" {
432+ t.Fatal("ContinuePrompt is empty")
436433 }
437434 }
438435
@@ -2132,10 +2129,10 @@ func TestMysisCreatedAt(t *testing.T) {
21322129
21332130 // TestBuildSystemPrompt_EdgeCases tests buildSystemPrompt error handling
21342131 func TestBuildSystemPrompt_EdgeCases(t *testing.T) {
2135- s, bus, cleanup := setupMysisTest(t)
2136- defer cleanup()
2137-
21382132 t.Run("no_broadcasts_fallback", func(t *testing.T) {
2133+ s, bus, cleanup := setupMysisTest(t)
2134+ defer cleanup()
2135+
21392136 stored, _ := s.CreateMysis("no-broadcasts", "mock", "test-model", 0.7)
21402137 mock := provider.NewMock("mock", "response")
21412138 mysis := NewMysis(stored.ID, stored.Name, stored.CreatedAt, mock, s, bus)
@@ -2144,11 +2141,11 @@ func TestBuildSystemPrompt_EdgeCases(t *testing.T) {
21442141 prompt := mysis.buildSystemPrompt()
21452142
21462143 // Should contain fallback message
2147- if !strings.Contains(prompt, "No commander directives yet") {
2144+ if !strings.Contains(prompt, "Continue to play the game") {
21482145 t.Error("expected fallback message when no broadcasts")
21492146 }
2150- if !strings.Contains(prompt, "Grow more powerful while awaiting instructions") {
2151- t.Error("expected fallback message when no broadcasts")
2147+ if !strings.Contains(prompt, "SWARM BROADCAST") {
2148+ t.Error("expected SWARM BROADCAST header in fallback")
21522149 }
21532150 // Should still contain base SystemPrompt content
21542151 if !strings.Contains(prompt, "Nova Zoea") {
@@ -2156,48 +2153,57 @@ func TestBuildSystemPrompt_EdgeCases(t *testing.T) {
21562153 }
21572154 })
21582155
2159- t.Run("broadcast_with_unknown_sender", func(t *testing.T) {
2156+ t.Run("commander_broadcast", func(t *testing.T) {
2157+ s, bus, cleanup := setupMysisTest(t)
2158+ defer cleanup()
2159+
21602160 stored, _ := s.CreateMysis("receiver-mysis", "mock", "test-model", 0.7)
21612161 mock := provider.NewMock("mock", "response")
21622162 mysis := NewMysis(stored.ID, stored.Name, stored.CreatedAt, mock, s, bus)
21632163
2164- // Add a broadcast with a sender ID that will be deleted (becomes "unknown")
2165- sender, _ := s.CreateMysis("temp-sender", "mock", "test-model", 0.7)
2166- s.AddMemory(stored.ID, store.MemoryRoleUser, store.MemorySourceBroadcast, "Test broadcast", "", sender.ID)
2167- // Delete the sender so it becomes "Unknown"
2168- s.DeleteMysis(sender.ID)
2164+ // Add a commander broadcast (empty sender_id)
2165+ s.AddMemory(stored.ID, store.MemoryRoleUser, store.MemorySourceBroadcast, "Attack coordinates: X=100, Y=200", "", "")
21692166
21702167 prompt := mysis.buildSystemPrompt()
21712168
2172- // Should handle unknown sender gracefully
2173- if !strings.Contains(prompt, "Unknown") {
2174- t.Error("expected 'Unknown' sender name for non-existent sender")
2175- }
2176- // Should still include broadcast content
2177- if !strings.Contains(prompt, "Test broadcast") {
2169+ // Should include broadcast content
2170+ if !strings.Contains(prompt, "Attack coordinates") {
21782171 t.Error("expected broadcast content in prompt")
21792172 }
2173+ // Should have SWARM BROADCAST header
2174+ if !strings.Contains(prompt, "SWARM BROADCAST") {
2175+ t.Error("expected SWARM BROADCAST header")
2176+ }
2177+ // Should NOT include sender name (commander broadcasts don't show sender)
2178+ if strings.Contains(prompt, "From:") {
2179+ t.Error("commander broadcasts should not show 'From:' field")
2180+ }
21802181 })
21812182
2182- t.Run("broadcast_with_valid_sender", func(t *testing.T) {
2183- sender, _ := s.CreateMysis("sender-mysis", "mock", "test-model", 0.7)
2184- receiver, _ := s.CreateMysis("receiver-mysis", "mock", "test-model", 0.7)
2183+ t.Run("mysis_broadcast_ignored", func(t *testing.T) {
2184+ s, bus, cleanup := setupMysisTest(t)
2185+ defer cleanup()
2186+
2187+ sender, _ := s.CreateMysis("sender-mysis-2", "mock", "test-model", 0.7)
2188+ receiver, _ := s.CreateMysis("receiver-mysis-2", "mock", "test-model", 0.7)
21852189
21862190 mock := provider.NewMock("mock", "response")
21872191 receiverMysis := NewMysis(receiver.ID, receiver.Name, receiver.CreatedAt, mock, s, bus)
21882192
2189- // Add a broadcast from sender
2190- s.AddMemory(receiver.ID, store.MemoryRoleUser, store.MemorySourceBroadcast, "Attack coordinates: X=100, Y=200", "", sender.ID)
2193+ // Add a commander broadcast first
2194+ s.AddMemory(receiver.ID, store.MemoryRoleUser, store.MemorySourceBroadcast, "Commander orders", "", "")
2195+ // Add a broadcast from another mysis (has sender_id) - should be ignored
2196+ s.AddMemory(receiver.ID, store.MemoryRoleUser, store.MemorySourceBroadcast, "Mysis broadcast", "", sender.ID)
21912197
21922198 prompt := receiverMysis.buildSystemPrompt()
21932199
2194- // Should include sender name
2195- if !strings.Contains(prompt, "sender-mysis") {
2196- t.Error("expected sender name in prompt")
2200+ // Should show commander broadcast, not mysis broadcast
2201+ if !strings.Contains(prompt, "Commander orders") {
2202+ t.Error("expected commander broadcast to be shown")
21972203 }
2198- // Should include broadcast content
2199- if !strings.Contains(prompt, "Attack coordinates") {
2200- t.Error("expected broadcast content in prompt")
2204+ // Should NOT include mysis broadcast content
2205+ if strings.Contains(prompt, "Mysis broadcast") {
2206+ t.Error("mysis broadcasts should be ignored in system prompt")
22012207 }
22022208 })
22032209 }
internal/integration/login_flow_test.go+5−4
@@ -9,10 +9,11 @@ import (
Cut short: this commit's diff is over 1000 lines.
internal/mcp/proxy.go+48−0
Cut short: this commit's diff is over 1000 lines.