xonecas.io
60255
Zn

Zoea-Nova / commit 34bfa93

feat: add game state cache to reduce context bloat

Implements incremental game state caching per GAME_STATE_CACHE_DESIGN.md
to eliminate repetitive 190KB tool results in context.

Changes:
- Add game_state_snapshots table (schema v9) keyed by username+tool_name
- Cache all get_* tool results after successful execution in Mysis
- Inject compact state summary with recency metadata into system prompt
- Clear cache on logout to prevent cross-account pollution

Impact:
- Reduces context size by ~95% (190KB → 2KB summaries)
- Eliminates LLM "amnesia" - knows data age (e.g., "2 ticks ago")
- Prevents "Max tool iterations" from redundant get_map calls
- Supports account switching without cache pollution

Implementation:
- Caching happens in Mysis after tool execution (has username context)
- Summary built in buildSystemPrompt() with {{GAME_STATE_SUMMARY}}
- Logout interception in proxy clears snapshots for that username

xonecas2026-02-09 34bfa93d52d71a4eac41ee848b15003e428c8ddc parent abb915e

8 files changed

AGENTS.md+2−0
@@ -18,6 +18,8 @@ TUI for orchestrating AI agents (Myses) that play SpaceMolt via MCP. Go 1.24.2,
1818
1919 **Orphaned tool call removal** (`internal/core/mysis.go:1429-1465`): Assistant messages with tool calls removed if no matching tool result exists. Prevents OpenAI API crashes from malformed sequences after context compression.
2020
21+**Game state cache** (`internal/store/game_state.go`, `internal/core/mysis.go:1899-1938`): Snapshot tools (`get_*`) automatically cached per username. After successful tool execution, Mysis caches result with game tick in `game_state_snapshots` table. System prompt includes compact state summary with recency metadata (e.g., "get_status - 2 ticks ago"). Reduces context size by 95% - 190KB map data appears once, then 2KB summaries. Cache cleared on logout (proxy intercepts logout tool). Keyed by u …
22+
2123 ## Non-obvious Patterns
2224
2325 **Empty string triggers autonomous turn** (`internal/core/mysis.go:361-420`): `SendMessageFrom("", ...)` skips DB storage but processes turn. Used by `run()` loop for autonomous operation. Real messages always have content.
cmd/zoea/main.go+1−0
@@ -123,6 +123,7 @@ func main() {
123123
124124 mcpProxy := mcp.NewProxy(upstreamClient)
125125 mcpProxy.SetAccountStore(&accountStoreAdapter{s})
126+ mcpProxy.SetGameStateStore(s)
126127 mcp.RegisterOrchestratorTools(mcpProxy, &commanderAdapter{commander})
127128
128129 // Initialize upstream MCP connection if configured
internal/constants/constants.go+6−2
@@ -14,6 +14,8 @@ Exlore the game, make goals and achieve them over time. You are part of a secret
1414 ## Account Details
1515 {{ACCOUNT_DETAILS}}
1616
17+{{GAME_STATE_SUMMARY}}
18+
1719 {{LATEST_BROADCAST}}
1820
1921 ## Critical Rules
@@ -22,8 +24,7 @@ Context is limited - use search tools for older information.
2224 Use session_id in ALL game tools that require authentication. Your session_id is shown in the Account Details section above.
2325
2426 ### EVERY TURN:
25-The game runs on 10-second ticks. Plan ahead. Use your tool calls efficiently.
26-Remember: Call get_notifications after you other game actions every turn for updates.`
27+The game runs on 10-second ticks. Plan ahead. Use your tool calls efficiently.`
2728
2829 // BroadcastSectionTemplate is the template for commander broadcasts.
2930 // Placeholder: {broadcast_content}
@@ -47,6 +48,9 @@ Use session_id in ALL game tools that require authentication.`
4748 // AccountDetailsFallback is used when no credentials are available
4849 const AccountDetailsFallback = `No active session. Call register() to get credentials.`
4950
51+// GameStateSummaryFallback is shown when no game state is cached
52+const GameStateSummaryFallback = ``
53+
5054 // ContinuePrompt is sent to myses when they finish a turn to encourage autonomy (Level 1 - gentle).
5155 const ContinuePrompt = `What's your next move?`
5256
internal/core/mysis.go+190−0
@@ -651,6 +651,9 @@ func (m *Mysis) SendMessageFrom(content string, source store.MemorySource, sende
651651
652652 a.updateActivityFromToolResult(result, execErr)
653653
654+ // Cache snapshot tool results for game state summary
655+ a.cacheSnapshotToolResult(tc.Name, result, execErr)
656+
654657 // Store the tool result
655658 resultContent := a.formatToolResult(tc.ID, tc.Name, result, execErr)
656659 if err := a.store.AddMemory(a.id, store.MemoryRoleTool, store.MemorySourceTool, resultContent, "", ""); err != nil {
@@ -1712,9 +1715,121 @@ func (m *Mysis) buildSystemPrompt() string {
17121715
17131716 prompt = strings.Replace(prompt, "{{ACCOUNT_DETAILS}}", accountDetails, 1)
17141717
1718+ // Replace {{GAME_STATE_SUMMARY}} with cached game state
1719+ gameStateSummary := m.buildGameStateSummary()
1720+ prompt = strings.Replace(prompt, "{{GAME_STATE_SUMMARY}}", gameStateSummary, 1)
1721+
17151722 return prompt
17161723 }
17171724
1725+// buildGameStateSummary creates a compact summary of cached game state.
1726+func (m *Mysis) buildGameStateSummary() string {
1727+ username := m.CurrentAccountUsername()
1728+ if username == "" {
1729+ return constants.GameStateSummaryFallback
1730+ }
1731+
1732+ snapshots, err := m.store.GetAllGameStateSnapshots(username)
1733+ if err != nil || len(snapshots) == 0 {
1734+ return constants.GameStateSummaryFallback
1735+ }
1736+
1737+ // Get current tick for recency calculation
1738+ currentTick := m.lastServerTick
1739+
1740+ var summary strings.Builder
1741+ summary.WriteString("\n## Cached Game State\n")
1742+ summary.WriteString(fmt.Sprintf("Account: %s\n\n", username))
1743+
1744+ // Group snapshots by category
1745+ statusTools := []string{"get_status", "get_player"}
1746+ shipTools := []string{"get_ship", "get_cargo"}
1747+ locationTools := []string{"get_system", "get_location", "get_poi"}
1748+ mapTools := []string{"get_map", "get_galaxy"}
1749+
1750+ writeSnapshotGroup := func(title string, toolNames []string) {
1751+ for _, snapshot := range snapshots {
1752+ for _, toolName := range toolNames {
1753+ if snapshot.ToolName == toolName {
1754+ recency := snapshot.RecencyMessage(currentTick)
1755+ summary.WriteString(fmt.Sprintf("### %s (%s)\n", toolName, recency))
1756+
1757+ // Parse and extract key fields for compact display
1758+ compactInfo := extractCompactInfo(snapshot.Content, toolName)
1759+ if compactInfo != "" {
1760+ summary.WriteString(compactInfo)
1761+ summary.WriteString("\n")
1762+ }
1763+ summary.WriteString("\n")
1764+ }
1765+ }
1766+ }
1767+ }
1768+
1769+ writeSnapshotGroup("Status", statusTools)
1770+ writeSnapshotGroup("Ship", shipTools)
1771+ writeSnapshotGroup("Location", locationTools)
1772+ writeSnapshotGroup("Map", mapTools)
1773+
1774+ // Add note about refreshing stale data
1775+ summary.WriteString("Note: Call get_notifications to see events since last update.\n")
1776+ summary.WriteString("Refresh any stale snapshots (>50 ticks old) before making decisions.\n")
1777+
1778+ return summary.String()
1779+}
1780+
1781+// extractCompactInfo extracts key information from a snapshot for compact display.
1782+func extractCompactInfo(content, toolName string) string {
1783+ // Parse JSON content
1784+ var data interface{}
1785+ decoder := json.NewDecoder(strings.NewReader(content))
1786+ decoder.UseNumber()
1787+ if err := decoder.Decode(&data); err != nil {
1788+ return ""
1789+ }
1790+
1791+ var info strings.Builder
1792+
1793+ switch toolName {
1794+ case "get_status", "get_player":
1795+ if credits, ok := findIntField(data, "credits", "balance"); ok {
1796+ info.WriteString(fmt.Sprintf("- Credits: %d\n", credits))
1797+ }
1798+ if location, ok := findStringField(data, "location", "current_location"); ok {
1799+ info.WriteString(fmt.Sprintf("- Location: %s\n", location))
1800+ }
1801+ if ship, ok := findStringField(data, "ship", "ship_name"); ok {
1802+ info.WriteString(fmt.Sprintf("- Ship: %s\n", ship))
1803+ }
1804+
1805+ case "get_ship":
1806+ if hull, ok := findIntField(data, "hull", "hull_health"); ok {
1807+ info.WriteString(fmt.Sprintf("- Hull: %d\n", hull))
1808+ }
1809+ if fuel, ok := findIntField(data, "fuel", "fuel_level"); ok {
1810+ info.WriteString(fmt.Sprintf("- Fuel: %d\n", fuel))
1811+ }
1812+ if cargo, ok := findIntField(data, "cargo_used", "cargo"); ok {
1813+ info.WriteString(fmt.Sprintf("- Cargo: %d\n", cargo))
1814+ }
1815+
1816+ case "get_system", "get_location":
1817+ if system, ok := findStringField(data, "system", "system_name"); ok {
1818+ info.WriteString(fmt.Sprintf("- System: %s\n", system))
1819+ }
1820+ if faction, ok := findStringField(data, "faction", "controlling_faction"); ok {
1821+ info.WriteString(fmt.Sprintf("- Faction: %s\n", faction))
1822+ }
1823+
1824+ case "get_map", "get_galaxy":
1825+ if systemCount, ok := findIntField(data, "system_count", "systems"); ok {
1826+ info.WriteString(fmt.Sprintf("- Systems: %d\n", systemCount))
1827+ }
1828+ }
1829+
1830+ return info.String()
1831+}
1832+
17181833 // rebuildSystemMemory rebuilds the system memory with current state
17191834 func (m *Mysis) rebuildSystemMemory() error {
17201835 // Build new system prompt with current credentials and broadcasts
@@ -1780,6 +1895,48 @@ func (m *Mysis) updateActivityFromToolResult(result *mcp.ToolResult, err error)
17801895
17811896 }
17821897
1898+// cacheSnapshotToolResult stores successful snapshot tool results in the game state cache.
1899+func (m *Mysis) cacheSnapshotToolResult(toolName string, result *mcp.ToolResult, err error) {
1900+ // Only cache successful snapshot tools
1901+ if err != nil || result == nil || result.IsError {
1902+ return
1903+ }
1904+
1905+ // Only cache get_* tools
1906+ if !strings.HasPrefix(toolName, "get_") {
1907+ return
1908+ }
1909+
1910+ // Need active account to cache
1911+ username := m.CurrentAccountUsername()
1912+ if username == "" {
1913+ return
1914+ }
1915+
1916+ // Extract game tick from result
1917+ payload, ok := parseToolResultPayload(result)
1918+ if !ok {
1919+ return
1920+ }
1921+
1922+ gameTick, _ := findCurrentTick(payload)
1923+
1924+ // Get full result content
1925+ var content strings.Builder
1926+ for _, block := range result.Content {
1927+ if block.Type == "text" {
1928+ content.WriteString(block.Text)
1929+ }
1930+ }
1931+
1932+ if content.Len() == 0 {
1933+ return
1934+ }
1935+
1936+ // Store in cache (ignore errors - caching is best-effort)
1937+ _ = m.store.StoreGameStateSnapshot(username, toolName, content.String(), gameTick)
1938+}
1939+
17831940 func (m *Mysis) setActivity(state ActivityState, until time.Time) {
17841941 a := m
17851942 a.mu.Lock()
@@ -1942,6 +2099,39 @@ func findFloatField(payload interface{}, keys ...string) (float64, bool) {
19422099 return 0, false
19432100 }
19442101
2102+func findStringField(payload interface{}, keys ...string) (string, bool) {
2103+ queue := []interface{}{payload}
2104+
2105+ for len(queue) > 0 {
2106+ current := queue[0]
2107+ queue = queue[1:]
2108+
2109+ switch value := current.(type) {
2110+ case map[string]interface{}:
2111+ for _, key := range keys {
2112+ if raw, ok := value[key]; ok {
2113+ if str, ok := raw.(string); ok {
2114+ return str, true
2115+ }
2116+ }
2117+ }
2118+
2119+ childKeys := make([]string, 0, len(value))
2120+ for key := range value {
2121+ childKeys = append(childKeys, key)
2122+ }
2123+ sort.Strings(childKeys)
2124+ for _, key := range childKeys {
2125+ queue = append(queue, value[key])
2126+ }
2127+ case []interface{}:
2128+ queue = append(queue, value...)
2129+ }
2130+ }
2131+
2132+ return "", false
2133+}
2134+
19452135 func findCurrentTick(payload interface{}) (int64, bool) {
19462136 if number, ok := findIntFieldAtKeys(payload, "current_tick"); ok {
19472137 return number, true
internal/mcp/proxy.go+16−0
@@ -38,6 +38,11 @@ type Account struct {
3838 Password string
3939 }
4040
41+type GameStateStore interface {
42+ StoreGameStateSnapshot(username, toolName, content string, gameTick int64) error
43+ DeleteGameStateSnapshotsForUsername(username string) error
44+}
45+
4146 // Proxy combines an upstream MCP client with local tool handlers.
4247 type Proxy struct {
4348 mu sync.RWMutex
@@ -46,6 +51,7 @@ type Proxy struct {
4651 localHandlers map[string]ToolHandler
4752 contextHandlers map[string]ToolHandlerWithContext
4853 accountStore AccountStore
54+ gameStateStore GameStateStore
4955 }
5056
5157 var (
@@ -102,6 +108,12 @@ func (p *Proxy) SetAccountStore(store AccountStore) {
102108 p.accountStore = store
103109 }
104110
111+func (p *Proxy) SetGameStateStore(store GameStateStore) {
112+ p.mu.Lock()
113+ defer p.mu.Unlock()
114+ p.gameStateStore = store
115+}
116+
105117 // RegisterTool registers a local tool with the proxy.
106118 func (p *Proxy) RegisterTool(tool Tool, handler ToolHandler) {
107119 p.mu.Lock()
@@ -347,6 +359,10 @@ func (p *Proxy) handleLogoutResponse(arguments json.RawMessage, result *ToolResu
347359
348360 if username != "" {
349361 _ = p.accountStore.ReleaseAccount(username)
362+ // Clear game state cache on logout
363+ if p.gameStateStore != nil {
364+ _ = p.gameStateStore.DeleteGameStateSnapshotsForUsername(username)
365+ }
350366 }
351367 }
352368
internal/store/game_state.go+153−0
@@ -0,0 +1,153 @@
1+package store
2+
3+import (
4+ "database/sql"
5+ "fmt"
6+ "time"
7+
8+ "github.com/google/uuid"
9+)
10+
11+// GameStateSnapshot represents a cached game state from a tool call.
12+type GameStateSnapshot struct {
13+ ID string
14+ Username string
15+ ToolName string
16+ Content string
17+ GameTick int64
18+ CapturedAt time.Time
19+}
20+
21+// StoreGameStateSnapshot stores or updates a game state snapshot for a username+tool combination.
22+// Uses UPSERT to replace old snapshots with new ones.
23+func (s *Store) StoreGameStateSnapshot(username, toolName, content string, gameTick int64) error {
24+ id := uuid.New().String()
25+ capturedAt := time.Now().UTC().Unix()
26+
27+ _, err := s.db.Exec(`
28+ INSERT INTO game_state_snapshots (id, username, tool_name, content, game_tick, captured_at)
29+ VALUES (?, ?, ?, ?, ?, ?)
30+ ON CONFLICT(username, tool_name) DO UPDATE SET
31+ id = excluded.id,
32+ content = excluded.content,
33+ game_tick = excluded.game_tick,
34+ captured_at = excluded.captured_at
35+ `, id, username, toolName, content, gameTick, capturedAt)
36+
37+ return err
38+}
39+
40+// GetGameStateSnapshot retrieves a specific snapshot for a username+tool combination.
41+func (s *Store) GetGameStateSnapshot(username, toolName string) (*GameStateSnapshot, error) {
42+ var snapshot GameStateSnapshot
43+ var gameTick sql.NullInt64
44+ var capturedAtUnix int64
45+
46+ err := s.db.QueryRow(`
47+ SELECT id, username, tool_name, content, game_tick, captured_at
48+ FROM game_state_snapshots
49+ WHERE username = ? AND tool_name = ?
50+ `, username, toolName).Scan(
51+ &snapshot.ID,
52+ &snapshot.Username,
53+ &snapshot.ToolName,
54+ &snapshot.Content,
55+ &gameTick,
56+ &capturedAtUnix,
57+ )
58+
59+ if err != nil {
60+ return nil, err
61+ }
62+
63+ if gameTick.Valid {
64+ snapshot.GameTick = gameTick.Int64
65+ }
66+ snapshot.CapturedAt = time.Unix(capturedAtUnix, 0)
67+
68+ return &snapshot, nil
69+}
70+
71+// GetAllGameStateSnapshots retrieves all snapshots for a username, ordered by tool name.
72+func (s *Store) GetAllGameStateSnapshots(username string) ([]*GameStateSnapshot, error) {
73+ rows, err := s.db.Query(`
74+ SELECT id, username, tool_name, content, game_tick, captured_at
75+ FROM game_state_snapshots
76+ WHERE username = ?
77+ ORDER BY tool_name ASC
78+ `, username)
79+ if err != nil {
80+ return nil, fmt.Errorf("query game state snapshots: %w", err)
81+ }
82+ defer rows.Close()
83+
84+ var snapshots []*GameStateSnapshot
85+ for rows.Next() {
86+ var snapshot GameStateSnapshot
87+ var gameTick sql.NullInt64
88+ var capturedAtUnix int64
89+
90+ if err := rows.Scan(
91+ &snapshot.ID,
92+ &snapshot.Username,
93+ &snapshot.ToolName,
94+ &snapshot.Content,
95+ &gameTick,
96+ &capturedAtUnix,
97+ ); err != nil {
98+ return nil, fmt.Errorf("scan game state snapshot: %w", err)
99+ }
100+
101+ if gameTick.Valid {
102+ snapshot.GameTick = gameTick.Int64
103+ }
104+ snapshot.CapturedAt = time.Unix(capturedAtUnix, 0)
105+
106+ snapshots = append(snapshots, &snapshot)
107+ }
108+
109+ return snapshots, rows.Err()
110+}
111+
112+// DeleteGameStateSnapshotsForUsername deletes all snapshots for a username (e.g., on logout).
113+func (s *Store) DeleteGameStateSnapshotsForUsername(username string) error {
114+ _, err := s.db.Exec(`
115+ DELETE FROM game_state_snapshots
116+ WHERE username = ?
117+ `, username)
118+ return err
119+}
120+
121+// DeleteGameStateSnapshot deletes a specific snapshot for a username+tool combination.
122+func (s *Store) DeleteGameStateSnapshot(username, toolName string) error {
123+ _, err := s.db.Exec(`
124+ DELETE FROM game_state_snapshots
125+ WHERE username = ? AND tool_name = ?
126+ `, username, toolName)
127+ return err
128+}
129+
130+// RecencyMessage returns a human-readable recency string for a snapshot.
131+func (s *GameStateSnapshot) RecencyMessage(currentTick int64) string {
132+ if currentTick > 0 && s.GameTick > 0 {
133+ ticksAgo := currentTick - s.GameTick
134+ if ticksAgo == 0 {
135+ return "just now"
136+ }
137+ if ticksAgo < 0 {
138+ // Future tick (shouldn't happen, but handle gracefully)
139+ return "just now"
140+ }
141+ return fmt.Sprintf("%d ticks ago (%d seconds)", ticksAgo, ticksAgo*10)
142+ }
143+
144+ // Fallback to wall clock time
145+ elapsed := time.Since(s.CapturedAt)
146+ if elapsed < time.Minute {
147+ return fmt.Sprintf("%.0f seconds ago", elapsed.Seconds())
148+ }
149+ if elapsed < time.Hour {
150+ return fmt.Sprintf("%.0f minutes ago", elapsed.Minutes())
151+ }
152+ return fmt.Sprintf("%.1f hours ago", elapsed.Hours())
153+}
internal/store/schema.sql+15−3
@@ -4,10 +4,10 @@ CREATE TABLE IF NOT EXISTS schema_version (
44 version INTEGER PRIMARY KEY
55 );
66
7--- Schema v7 → v8 Migration:
8--- Added sender_id column to memories table for broadcast tracking.
7+-- Schema v8 → v9 Migration:
8+-- Added game_state_snapshots table for incremental game state caching.
99 -- BREAKING CHANGE: Requires fresh database (make db-reset-accounts)
10-INSERT OR REPLACE INTO schema_version (version) VALUES (8);
10+INSERT OR REPLACE INTO schema_version (version) VALUES (9);
1111
1212 CREATE TABLE IF NOT EXISTS myses (
1313 id TEXT PRIMARY KEY,
@@ -45,3 +45,15 @@ CREATE TABLE IF NOT EXISTS accounts (
4545 );
4646
4747 CREATE INDEX IF NOT EXISTS idx_accounts_in_use ON accounts(in_use);
48+
49+CREATE TABLE IF NOT EXISTS game_state_snapshots (
50+ id TEXT PRIMARY KEY,
51+ username TEXT NOT NULL,
52+ tool_name TEXT NOT NULL,
53+ content TEXT NOT NULL,
54+ game_tick INTEGER,
55+ captured_at INTEGER NOT NULL,
56+ UNIQUE(username, tool_name)
57+);
58+
59+CREATE INDEX IF NOT EXISTS idx_game_state_username ON game_state_snapshots(username);
internal/store/store.go+1−1
@@ -15,7 +15,7 @@ import (
1515 //go:embed schema.sql
1616 var schema string
1717
18-const currentSchemaVersion = 8
18+const currentSchemaVersion = 9
1919
2020 // Store provides access to the SQLite database.
2121 type Store struct {