xonecas.io
60255
Zn

Zoea-Nova / commit 633bdd8

fix: include game data in snapshot.

xonecas2026-02-09 633bdd8c652e94edee9c73e49ae1e6c0b220365d parent 0ef17f7

22 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.

.opencode/agents/zoea-analyser.md+0−1
@@ -2,7 +2,6 @@
22 description: Agent with data access for analysis.
33 agent: general
44 mode: subagent
5-model: opencode/gemini-3-flash
65 ---
76
87 You have access to the production database and log files for Zoea Nova, as well as the underlying LLM provider logs:
.opencode/commands/zoea-agent-behaviour-check.md+0−25
@@ -1,25 +0,0 @@
1----
2-description: Runs a database snapshot analysis and reports on mysis behavior and tool usage.
3-agent: zoea-analyser
4----
5-
6-Instructions:
7-
8-Analyze the last 5 minutes of activity from the database, application logs, and Ollama server logs, using 30-second intervals for the snapshot analysis.
9-
10-1. **Baseline**: Establish the system state as it was 5 minutes ago (active myses, memory counts) to use as a reference point.
11-2. **Investigation**: For each 30-second interval within the 5-minute window:
12- - Query the `myses` and `memories` tables for state changes and new messages.
13- - Examine `zoea.log` for application events, tool calls, or errors.
14- - Review `journalctl -u ollama` for provider performance or issues.
15-3. **Analyze**: Aggregate the findings from the entire 5-minute window.
16-4. **Report**: Provide a detailed report on:
17- - **Mysis Activity**: Active myses and their state transitions during the period.
18- - **Tool Efficacy**: Tools called, their frequency, and success/failure rates.
19- - **Observed Patterns**: Recurring issues, performance bottlenecks, repetitive or anomalous behaviors.
20-
21-**IMPORTANT**:
22-
23-- Do not create any files.
24-- Do not modify any data in the database.
25-- Ensure your report is data-driven, referencing specific log entries or query results.
AGENTS.md+5−1
@@ -18,7 +18,7 @@ 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 …
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 …
2222
2323 ## Non-obvious Patterns
2424
@@ -36,6 +36,8 @@ TUI for orchestrating AI agents (Myses) that play SpaceMolt via MCP. Go 1.24.2,
3636
3737 **MCP proxy is nullable** (`internal/core/mysis.go:436-477`): If nil, Mysis can still chat but has no tools. Used for testing and offline mode. Tool list fetch failure is non-fatal.
3838
39+**MCP session auto-recovery** (`internal/core/mysis.go:621-637`): When `ListTools()` fails with "Session not initialized" (error -32600), triggers background reinitialization via `initializeMCP()`. Mysis continues with degraded functionality (local tools only) until reconnection completes. Handles SpaceMolt server restarts and session expiration without manual intervention.
40+
3941 **WaitGroup tracks goroutines** (`internal/core/mysis.go:284-286`): Commander.wg incremented on Start(), decremented on run() exit. Allows graceful shutdown - Commander.Stop() waits for all Myses to finish current turn.
4042
4143 ## Gotchas
@@ -58,6 +60,8 @@ TUI for orchestrating AI agents (Myses) that play SpaceMolt via MCP. Go 1.24.2,
5860
5961 ## Where to Find Things
6062
63+- DB file for user `$HOME/.zoea-nova/zoea.db`
64+- LOG file for user `$HOME/.zoea-nova/zoea.log`
6165 - Context composition logic: `internal/core/mysis.go:1237-1339`
6266 - Autonomous loop: `internal/core/mysis.go:1520-1566`
6367 - State transitions: `internal/core/mysis.go:220-359` (Start/Stop), `1022-1107` (setError/setIdle)
cmd/zoea/main.go+13−6
@@ -87,6 +87,13 @@ func main() {
8787 defer s.Close()
8888 log.Debug().Msg("Store initialized")
8989
90+ // Release all accounts on startup to clear stale in_use flags from crashes
91+ if err := s.ReleaseAllAccounts(); err != nil {
92+ log.Warn().Err(err).Msg("Failed to release accounts on startup")
93+ } else {
94+ log.Info().Msg("Released all accounts on startup")
95+ }
96+
9097 // Initialize event bus
9198 bus := core.NewEventBus(1000)
9299 // Note: bus.Close() is called explicitly in onQuit callback and signal handler
@@ -234,16 +241,16 @@ type accountStoreAdapter struct {
234241 store *store.Store
235242 }
236243
237-func (a *accountStoreAdapter) CreateAccount(username, password string) (*mcp.Account, error) {
238- acc, err := a.store.CreateAccount(username, password)
244+func (a *accountStoreAdapter) CreateAccount(username, password string, mysisID ...string) (*mcp.Account, error) {
245+ acc, err := a.store.CreateAccount(username, password, mysisID...)
239246 if err != nil {
240247 return nil, err
241248 }
242249 return &mcp.Account{Username: acc.Username, Password: acc.Password}, nil
243250 }
244251
245-func (a *accountStoreAdapter) MarkAccountInUse(username string) error {
246- return a.store.MarkAccountInUse(username)
252+func (a *accountStoreAdapter) MarkAccountInUse(username, mysisID string) error {
253+ return a.store.MarkAccountInUse(username, mysisID)
247254 }
248255
249256 func (a *accountStoreAdapter) ReleaseAccount(username string) error {
@@ -254,8 +261,8 @@ func (a *accountStoreAdapter) ReleaseAllAccounts() error {
254261 return a.store.ReleaseAllAccounts()
255262 }
256263
257-func (a *accountStoreAdapter) ClaimAccount() (*mcp.Account, error) {
258- acc, err := a.store.ClaimAccount()
264+func (a *accountStoreAdapter) ClaimAccount(mysisID string) (*mcp.Account, error) {
265+ acc, err := a.store.ClaimAccount(mysisID)
259266 if err != nil {
260267 return nil, err
261268 }
documentation/architecture/GAME_STATE_CACHE_DESIGN.md+0−0
documentation/architecture/MYSIS_ACCOUNT_MANAGEMENT.md+4−2
@@ -32,8 +32,9 @@ Myses need game accounts to play SpaceMolt. We maintain a pool of accounts to co
3232 2. **Register passthrough:** When mysis calls `register()` and pool is empty, proxy lets it go to game server normally
3333 3. **Login passthrough:** Login calls always go to game server (no interception)
3434 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. **Internal claiming:** Account claiming is handled internally by proxy shadowing `login`/`register` - no `zoea_claim_account` tool exists
35+5. **Ownership tracking:** When marked in_use, accounts store `in_use_by = mysis.id`
36+6. **Account release:** Logout releases account back to pool and clears `in_use_by`
37+7. **Internal claiming:** Account claiming is handled internally by proxy shadowing `login`/`register` - no `zoea_claim_account` tool exists
3738
3839 ---
3940
@@ -59,6 +60,7 @@ Mysis: login() → Game: session_id → Proxy: mark_in_use → Mysis: PLAYING
5960 | Pool has 3 accounts, mysis calls register | Mysis gets session_id, pool has 2 available accounts |
6061 | Pool empty, mysis calls register | Mysis gets session_id, pool has 1 account (the new one) |
6162 | Mysis calls login with pool credentials | Mysis gets session_id, account marked in_use |
63+| Mysis calls login | Account in_use_by set to mysis.id |
6264 | Mysis calls logout | Account released, pool gains 1 available account |
6365 | Mysis lists tools | Only game tools visible (no `zoea_claim_account` - tool removed) |
6466
documentation/current/TODO.md+2−5
@@ -15,15 +15,12 @@
1515
1616 Recommendations
1717
18-1. Cargo management: Add logic to check cargo capacity before mining, trigger dock/sell when full
19-2. POI validation: Require get_poi before mine, use get_system for travel targets (stop hallucinating names)
20-3. Docking sequence: Ensure dock succeeds before calling station services (buy, sell, missions)
2118 4. Increase iteration limit: From 10 to 15-20 to reduce turn overhead for complex tasks
2219
23-7. Refactor OpenCode Zen provider factory: Make endpoint selection intelligent based on model type
20+5. Refactor OpenCode Zen provider factory: Make endpoint selection intelligent based on model type
2421 - Reference: https://opencode.ai/docs/zen/#models
2522 - Current: Hardcoded model→endpoint mapping in opencodeModelEndpoints map
26- - Goal: Automatically route to correct endpoint (/chat/completions, /messages, /responses, /models/*) based on model prefix/type
23+ - Goal: Automatically route to correct endpoint (/chat/completions, /messages, /responses, /models/\*) based on model prefix/type
2724 - Benefits: Support new models without code changes, align with official OpenCode Zen API structure
2825 - Note: /responses endpoint format is currently undocumented and incompatible with our OpenAI SDK usage
2926
internal/constants/constants.go+1−1
@@ -46,7 +46,7 @@ Session ID: %s
4646 Use session_id in ALL game tools that require authentication.`
4747
4848 // AccountDetailsFallback is used when no credentials are available
49-const AccountDetailsFallback = `No active session. Call register() to get credentials.`
49+const AccountDetailsFallback = `No active account. Call register()`
5050
5151 // GameStateSummaryFallback is shown when no game state is cached
5252 const GameStateSummaryFallback = ``
internal/core/account_test.go+33−8
@@ -42,13 +42,24 @@ func setupAccountTest(t *testing.T) (*store.Store, func()) {
4242 return s, cleanup
4343 }
4444
45+func createTestMysis(t *testing.T, s *store.Store, name string) *store.Mysis {
46+ t.Helper()
47+ mysis, err := s.CreateMysis(name, "mock", "test-model", 0.7)
48+ if err != nil {
49+ t.Fatalf("CreateMysis() error: %v", err)
50+ }
51+ return mysis
52+}
53+
4554 // TestMysis_AccountLifecycle tests the full account claim/release lifecycle.
4655 func TestMysis_AccountLifecycle(t *testing.T) {
4756 s, cleanup := setupAccountTest(t)
4857 defer cleanup()
4958
59+ mysis := createTestMysis(t, s, "test-mysis")
60+
5061 m := &Mysis{
51- id: "test-mysis",
62+ id: mysis.ID,
5263 name: "test",
5364 store: s,
5465 }
@@ -97,8 +108,10 @@ func TestMysis_AccountSwitching(t *testing.T) {
97108 s, cleanup := setupAccountTest(t)
98109 defer cleanup()
99110
111+ mysis := createTestMysis(t, s, "test-mysis")
112+
100113 m := &Mysis{
101- id: "test-mysis",
114+ id: mysis.ID,
102115 name: "test",
103116 store: s,
104117 }
@@ -150,8 +163,10 @@ func TestMysis_AccountSwitchToSame(t *testing.T) {
150163 s, cleanup := setupAccountTest(t)
151164 defer cleanup()
152165
166+ mysis := createTestMysis(t, s, "test-mysis")
167+
153168 m := &Mysis{
154- id: "test-mysis",
169+ id: mysis.ID,
155170 name: "test",
156171 store: s,
157172 }
@@ -181,8 +196,10 @@ func TestMysis_SetCurrentAccount_EmptyString(t *testing.T) {
181196 s, cleanup := setupAccountTest(t)
182197 defer cleanup()
183198
199+ mysis := createTestMysis(t, s, "test-mysis")
200+
184201 m := &Mysis{
185- id: "test-mysis",
202+ id: mysis.ID,
186203 name: "test",
187204 store: s,
188205 currentAccountUsername: "user1",
@@ -202,8 +219,10 @@ func TestMysis_ReleaseCurrentAccount_NoAccount(t *testing.T) {
202219 s, cleanup := setupAccountTest(t)
203220 defer cleanup()
204221
222+ mysis := createTestMysis(t, s, "test-mysis")
223+
205224 m := &Mysis{
206- id: "test-mysis",
225+ id: mysis.ID,
207226 name: "test",
208227 store: s,
209228 }
@@ -221,8 +240,10 @@ func TestMysis_ReleaseCurrentAccount_Twice(t *testing.T) {
221240 s, cleanup := setupAccountTest(t)
222241 defer cleanup()
223242
243+ mysis := createTestMysis(t, s, "test-mysis")
244+
224245 m := &Mysis{
225- id: "test-mysis",
246+ id: mysis.ID,
226247 name: "test",
227248 store: s,
228249 }
@@ -252,8 +273,10 @@ func TestMysis_AccountConcurrent(t *testing.T) {
252273 s, cleanup := setupAccountTest(t)
253274 defer cleanup()
254275
276+ mysis := createTestMysis(t, s, "test-mysis")
277+
255278 m := &Mysis{
256- id: "test-mysis",
279+ id: mysis.ID,
257280 name: "test",
258281 store: s,
259282 }
@@ -339,8 +362,10 @@ func TestMysis_CurrentAccountUsername_ThreadSafe(t *testing.T) {
339362 s, cleanup := setupAccountTest(t)
340363 defer cleanup()
341364
365+ mysis := createTestMysis(t, s, "test-mysis")
366+
342367 m := &Mysis{
343- id: "test-mysis",
368+ id: mysis.ID,
344369 name: "test",
345370 store: s,
346371 currentAccountUsername: "user1",
internal/core/mysis.go+81−64
@@ -13,6 +13,7 @@ import (
1313
1414 "github.com/rs/zerolog/log"
1515 "github.com/xonecas/zoea-nova/internal/constants"
16+ "github.com/xonecas/zoea-nova/internal/gamestate"
1617 "github.com/xonecas/zoea-nova/internal/mcp"
1718 "github.com/xonecas/zoea-nova/internal/provider"
1819 "github.com/xonecas/zoea-nova/internal/store"
@@ -435,16 +436,16 @@ type accountStoreAdapter struct {
435436 store *store.Store
436437 }
437438
438-func (a *accountStoreAdapter) CreateAccount(username, password string) (*mcp.Account, error) {
439- acc, err := a.store.CreateAccount(username, password)
439+func (a *accountStoreAdapter) CreateAccount(username, password string, mysisID ...string) (*mcp.Account, error) {
440+ acc, err := a.store.CreateAccount(username, password, mysisID...)
440441 if err != nil {
441442 return nil, err
442443 }
443444 return &mcp.Account{Username: acc.Username, Password: acc.Password}, nil
444445 }
445446
446-func (a *accountStoreAdapter) MarkAccountInUse(username string) error {
447- return a.store.MarkAccountInUse(username)
447+func (a *accountStoreAdapter) MarkAccountInUse(username, mysisID string) error {
448+ return a.store.MarkAccountInUse(username, mysisID)
448449 }
449450
450451 func (a *accountStoreAdapter) ReleaseAccount(username string) error {
@@ -455,8 +456,8 @@ func (a *accountStoreAdapter) ReleaseAllAccounts() error {
455456 return a.store.ReleaseAllAccounts()
456457 }
457458
458-func (a *accountStoreAdapter) ClaimAccount() (*mcp.Account, error) {
459- acc, err := a.store.ClaimAccount()
459+func (a *accountStoreAdapter) ClaimAccount(mysisID string) (*mcp.Account, error) {
460+ acc, err := a.store.ClaimAccount(mysisID)
460461 if err != nil {
461462 return nil, err
462463 }
@@ -620,6 +621,28 @@ func (m *Mysis) SendMessageFrom(content string, source store.MemorySource, sende
620621 if mcpProxy != nil {
621622 mcpTools, err := mcpProxy.ListTools(ctx)
622623 if err != nil {
624+ if isMCPConnectionLost(err) {
625+ log.Warn().
626+ Str("mysis", a.name).
627+ Err(err).
628+ Msg("MCP connection lost - releasing account")
629+ a.releaseCurrentAccount()
630+ if rebuildErr := a.rebuildSystemMemory(); rebuildErr != nil {
631+ log.Error().Err(rebuildErr).Msg("failed to rebuild system memory after MCP session loss")
632+ }
633+ }
634+
635+ // Check if this is a session expiration error
636+ if strings.Contains(err.Error(), "Session not initialized") || strings.Contains(err.Error(), "-32600") {
637+ log.Warn().
638+ Str("mysis", a.name).
639+ Err(err).
640+ Msg("MCP session expired - attempting reinitialization")
641+
642+ // Trigger MCP reinitialization in background
643+ go a.initializeMCP(parentCtx)
644+ }
645+
623646 // Log error but continue - mysis can still chat without tools
624647 a.publishCriticalEvent(Event{
625648 Type: EventMysisError,
@@ -1055,6 +1078,17 @@ func (m *Mysis) executeToolCall(ctx context.Context, mcpProxy *mcp.Proxy, tc pro
10551078 }
10561079
10571080 result, err := mcpProxy.CallTool(ctx, caller, tc.Name, tc.Arguments)
1081+ if err != nil && isMCPConnectionLost(err) {
1082+ log.Warn().
1083+ Str("mysis", a.name).
1084+ Str("tool", tc.Name).
1085+ Err(err).
1086+ Msg("MCP connection lost during tool call - releasing account")
1087+ a.releaseCurrentAccount()
1088+ if rebuildErr := a.rebuildSystemMemory(); rebuildErr != nil {
1089+ log.Error().Err(rebuildErr).Msg("failed to rebuild system memory after MCP session loss")
1090+ }
1091+ }
10581092 if err == nil && result != nil && !result.IsError {
10591093 switch tc.Name {
10601094 case "login", "register":
@@ -1103,10 +1137,11 @@ func (m *Mysis) executeToolCall(ctx context.Context, mcpProxy *mcp.Proxy, tc pro
11031137
11041138 func (m *Mysis) setCurrentAccount(username, password, sessionID string) {
11051139 m.mu.Lock()
1106- defer m.mu.Unlock()
1140+ storeRef := m.store
11071141
11081142 // Ignore empty username (no-op)
11091143 if username == "" {
1144+ m.mu.Unlock()
11101145 return
11111146 }
11121147
@@ -1119,6 +1154,13 @@ func (m *Mysis) setCurrentAccount(username, password, sessionID string) {
11191154 m.currentAccountUsername = username
11201155 m.currentPassword = password
11211156 m.currentSessionID = sessionID
1157+ m.mu.Unlock()
1158+
1159+ if storeRef != nil {
1160+ if err := storeRef.MarkAccountInUse(username, m.id); err != nil {
1161+ log.Error().Err(err).Str("username", username).Msg("failed to mark account in use")
1162+ }
1163+ }
11221164 }
11231165
11241166 func (m *Mysis) releaseCurrentAccount() {
@@ -1271,6 +1313,28 @@ func isToolRetryExhausted(err error) bool {
12711313 return errors.Is(err, mcp.ErrToolRetryExhausted)
12721314 }
12731315
1316+func isMCPConnectionLost(err error) bool {
1317+ if err == nil {
1318+ return false
1319+ }
1320+ return isMCPConnectionLostMessage(err.Error())
1321+}
1322+
1323+func isMCPConnectionLostMessage(message string) bool {
1324+ if message == "" {
1325+ return false
1326+ }
1327+ msg := strings.ToLower(message)
1328+ return strings.Contains(msg, "session not initialized") ||
1329+ strings.Contains(msg, "-32600") ||
1330+ strings.Contains(msg, "connection refused") ||
1331+ strings.Contains(msg, "connection reset") ||
1332+ strings.Contains(msg, "no such host") ||
1333+ strings.Contains(msg, "dial tcp") ||
1334+ strings.Contains(msg, "unexpected eof") ||
1335+ strings.Contains(msg, "eof")
1336+}
1337+
12741338 // formatToolResultDisplay formats a tool result for UI display (human-readable).
12751339 func (m *Mysis) formatToolResultDisplay(result *mcp.ToolResult, err error) string {
12761340 if err != nil {
@@ -1922,10 +1986,11 @@ func (m *Mysis) buildGameStateSummary() string {
19221986 recency := snapshot.RecencyMessage(currentTick)
19231987 summary.WriteString(fmt.Sprintf("### %s (%s)\n", toolName, recency))
19241988
1925- // Parse and extract key fields for compact display
1926- compactInfo := extractCompactInfo(snapshot.Content, toolName)
1927- if compactInfo != "" {
1928- summary.WriteString(compactInfo)
1989+ // Render a safe summary without schema assumptions
1990+ lines := gamestate.SnapshotLines(snapshot.Content)
1991+ for _, line := range lines {
1992+ summary.WriteString("- ")
1993+ summary.WriteString(line)
19291994 summary.WriteString("\n")
19301995 }
19311996 summary.WriteString("\n")
@@ -1946,58 +2011,6 @@ func (m *Mysis) buildGameStateSummary() string {
19462011 return summary.String()
19472012 }
19482013
1949-// extractCompactInfo extracts key information from a snapshot for compact display.
1950-func extractCompactInfo(content, toolName string) string {
1951- // Parse JSON content
1952- var data interface{}
1953- decoder := json.NewDecoder(strings.NewReader(content))
1954- decoder.UseNumber()
1955- if err := decoder.Decode(&data); err != nil {
1956- return ""
1957- }
1958-
1959- var info strings.Builder
1960-
1961- switch toolName {
1962- case "get_status", "get_player":
1963- if credits, ok := findIntField(data, "credits", "balance"); ok {
1964- info.WriteString(fmt.Sprintf("- Credits: %d\n", credits))
1965- }
1966- if location, ok := findStringField(data, "location", "current_location"); ok {
1967- info.WriteString(fmt.Sprintf("- Location: %s\n", location))
1968- }
1969- if ship, ok := findStringField(data, "ship", "ship_name"); ok {
1970- info.WriteString(fmt.Sprintf("- Ship: %s\n", ship))
1971- }
1972-
1973- case "get_ship":
1974- if hull, ok := findIntField(data, "hull", "hull_health"); ok {
1975- info.WriteString(fmt.Sprintf("- Hull: %d\n", hull))
1976- }
1977- if fuel, ok := findIntField(data, "fuel", "fuel_level"); ok {
1978- info.WriteString(fmt.Sprintf("- Fuel: %d\n", fuel))
1979- }
1980- if cargo, ok := findIntField(data, "cargo_used", "cargo"); ok {
1981- info.WriteString(fmt.Sprintf("- Cargo: %d\n", cargo))
1982- }
1983-
1984- case "get_system", "get_location":
1985- if system, ok := findStringField(data, "system", "system_name"); ok {
1986- info.WriteString(fmt.Sprintf("- System: %s\n", system))
1987- }
1988- if faction, ok := findStringField(data, "faction", "controlling_faction"); ok {
1989- info.WriteString(fmt.Sprintf("- Faction: %s\n", faction))
1990- }
1991-
1992- case "get_map", "get_galaxy":
1993- if systemCount, ok := findIntField(data, "system_count", "systems"); ok {
1994- info.WriteString(fmt.Sprintf("- Systems: %d\n", systemCount))
1995- }
1996- }
1997-
1998- return info.String()
1999-}
2000-
20012014 // rebuildSystemMemory rebuilds the system memory with current state
20022015 func (m *Mysis) rebuildSystemMemory() error {
20032016 // Build new system prompt with current credentials and broadcasts
@@ -2122,7 +2135,11 @@ func (m *Mysis) cacheSnapshotToolResult(toolName string, result *mcp.ToolResult,
21222135 }
21232136
21242137 // Store in cache (ignore errors - caching is best-effort)
2125- _ = m.store.StoreGameStateSnapshot(username, toolName, content.String(), gameTick)
2138+ if err := m.store.StoreGameStateSnapshot(username, toolName, content.String(), gameTick); err == nil {
2139+ if rebuildErr := m.rebuildSystemMemory(); rebuildErr != nil {
2140+ log.Error().Err(rebuildErr).Msg("failed to rebuild system memory after snapshot update")
2141+ }
2142+ }
21262143 }
21272144
21282145 func (m *Mysis) setActivity(state ActivityState, until time.Time) {
internal/core/mysis_account_release_test.go+3−3
@@ -37,7 +37,7 @@ func TestAccountReleaseOnError(t *testing.T) {
3737
3838 // Simulate mysis acquiring an account (simulating login tool call)
3939 // First mark account in use, then set current account
40- if err := s.MarkAccountInUse(acct.Username); err != nil {
40+ if err := s.MarkAccountInUse(acct.Username, stored.ID); err != nil {
4141 t.Fatalf("Failed to mark account in use: %v", err)
4242 }
4343 mysis.setCurrentAccount(acct.Username, "", "")
@@ -48,7 +48,7 @@ func TestAccountReleaseOnError(t *testing.T) {
4848 }
4949
5050 // Verify account is locked in store (ClaimAccount should not return this account)
51- claimed, err := s.ClaimAccount()
51+ claimed, err := s.ClaimAccount(stored.ID)
5252 if err == nil && claimed.Username == acct.Username {
5353 t.Fatalf("Expected account to be locked, but ClaimAccount returned it")
5454 }
@@ -67,7 +67,7 @@ func TestAccountReleaseOnError(t *testing.T) {
6767 }
6868
6969 // Verify account is unlocked in store (ClaimAccount should return it)
70- claimed2, err := s.ClaimAccount()
70+ claimed2, err := s.ClaimAccount(stored.ID)
7171 if err != nil || claimed2 == nil || claimed2.Username != acct.Username {
7272 t.Errorf("BUG CONFIRMED: Account still locked in store, ClaimAccount failed: %v", err)
7373 } else {
internal/gamestate/summary.go+98−0
@@ -0,0 +1,98 @@
1+package gamestate
2+
3+import (
4+ "encoding/json"
5+ "fmt"
6+ "sort"
7+ "strconv"
8+ "strings"
9+)
10+
11+func SnapshotLines(content string) []string {
12+ content = strings.TrimSpace(content)
13+ if content == "" {
14+ return nil
15+ }
16+
17+ var data interface{}
18+ decoder := json.NewDecoder(strings.NewReader(content))
19+ decoder.UseNumber()
20+ if err := decoder.Decode(&data); err != nil {
21+ return []string{"(invalid JSON)"}
22+ }
23+
24+ lines := make([]string, 0, 64)
25+ walkValue(data, "", &lines)
26+ return lines
27+}
28+
29+func SnapshotString(content string) string {
30+ lines := SnapshotLines(content)
31+ return strings.Join(lines, "\n")
32+}
33+
34+func walkValue(value interface{}, path string, lines *[]string) {
35+ switch v := value.(type) {
36+ case map[string]interface{}:
37+ if len(v) == 0 {
38+ appendLine(path, "{}", lines)
39+ return
40+ }
41+ keys := make([]string, 0, len(v))
42+ for k := range v {
43+ keys = append(keys, k)
44+ }
45+ sort.Strings(keys)
46+ for _, key := range keys {
47+ walkValue(v[key], joinPath(path, key), lines)
48+ }
49+ case []interface{}:
50+ if len(v) == 0 {
51+ appendLine(path, "[]", lines)
52+ return
53+ }
54+ for i, item := range v {
55+ walkValue(item, fmt.Sprintf("%s[%d]", path, i), lines)
56+ }
57+ default:
58+ appendLine(path, formatPrimitive(v), lines)
59+ }
60+}
61+
62+func appendLine(path, value string, lines *[]string) {
63+ if path == "" {
64+ *lines = append(*lines, value)
65+ return
66+ }
67+ *lines = append(*lines, path+": "+value)
68+}
69+
70+func joinPath(prefix, key string) string {
71+ if prefix == "" {
72+ return key
73+ }
74+ return prefix + "." + key
75+}
76+
77+func formatPrimitive(value interface{}) string {
78+ switch v := value.(type) {
79+ case nil:
80+ return "null"
81+ case json.Number:
82+ return v.String()
83+ case float64:
84+ return strconv.FormatFloat(v, 'f', -1, 64)
85+ case float32:
86+ return strconv.FormatFloat(float64(v), 'f', -1, 32)
87+ case int, int8, int16, int32, int64:
88+ return fmt.Sprintf("%d", v)
89+ case uint, uint8, uint16, uint32, uint64:
90+ return fmt.Sprintf("%d", v)
91+ case bool:
92+ return strconv.FormatBool(v)
93+ case string:
94+ return v
95+ default:
96+ return fmt.Sprintf("%v", v)
97+ }
98+}
internal/integration/login_flow_test.go+46−33
@@ -28,6 +28,12 @@ func TestLoginFlowIntegration(t *testing.T) {
2828 t.Fatalf("Failed to create account: %v", err)
2929 }
3030
31+ // Create mysis for ownership tracking
32+ mysis, err := s.CreateMysis("test-mysis", "mock", "test-model", 0.7)
33+ if err != nil {
34+ t.Fatalf("Failed to create mysis: %v", err)
35+ }
36+
3137 // Release account to make it available
3238 if err := s.ReleaseAccount("pilot_crab"); err != nil {
3339 t.Fatalf("Failed to release account: %v", err)
@@ -52,7 +58,7 @@ func TestLoginFlowIntegration(t *testing.T) {
5258
5359 // STEP 1: Test setup - get account credentials
5460 // (In production, myses would call register() or have pre-known credentials)
55- claimed, err := s.ClaimAccount()
61+ claimed, err := s.ClaimAccount(mysis.ID)
5662 if err != nil {
5763 t.Fatalf("ClaimAccount() failed: %v", err)
5864 }
@@ -63,23 +69,14 @@ func TestLoginFlowIntegration(t *testing.T) {
6369 t.Fatalf("Expected password secret123, got %s", claimed.Password)
6470 }
6571
66- // CRITICAL: Account should NOT be locked yet (InUse should be false)
67- if claimed.InUse {
68- t.Fatalf("BUG: ClaimAccount() returned account with InUse=true. Account should not be locked until login succeeds.")
69- }
70-
71- // Verify in store that account is still available
72- acc, err := s.GetAccount("pilot_crab")
73- if err != nil {
74- t.Fatalf("Failed to get account: %v", err)
75- }
76- if acc.InUse {
77- t.Fatalf("BUG: Account is marked in_use=1 in store after ClaimAccount(). Should be 0 until login succeeds.")
72+ // Account should be marked in use after claim
73+ if !claimed.InUse {
74+ t.Fatalf("ClaimAccount() should mark account in_use")
7875 }
7976
8077 // STEP 2: Mysis uses credentials with game's login tool
8178 loginArgs := json.RawMessage(`{"username":"pilot_crab","password":"secret123"}`)
82- result, err := proxy.CallTool(context.Background(), mcp.CallerContext{MysisID: "test", MysisName: "test-mysis"}, "login", loginArgs)
79+ result, err := proxy.CallTool(context.Background(), mcp.CallerContext{MysisID: mysis.ID, MysisName: "test-mysis"}, "login", loginArgs)
8380 if err != nil {
8481 t.Fatalf("CallTool(login) failed: %v", err)
8582 }
@@ -88,13 +85,16 @@ func TestLoginFlowIntegration(t *testing.T) {
8885 }
8986
9087 // STEP 3: Verify handleLoginResponse marked account as in_use
91- acc, err = s.GetAccount("pilot_crab")
88+ acc, err := s.GetAccount("pilot_crab")
9289 if err != nil {
9390 t.Fatalf("Failed to get account after login: %v", err)
9491 }
9592 if !acc.InUse {
9693 t.Fatalf("BUG: Account not marked in_use after successful login. handleLoginResponse() failed to intercept.")
9794 }
95+ if acc.InUseBy != mysis.ID {
96+ t.Fatalf("BUG: Account in_use_by not set after login. Expected %q, got %q", mysis.ID, acc.InUseBy)
97+ }
9898
9999 // Verify account is no longer available for claiming
100100 avail, err = s.ListAvailableAccounts()
@@ -106,7 +106,7 @@ func TestLoginFlowIntegration(t *testing.T) {
106106 }
107107
108108 // Verify another ClaimAccount() call would fail (no accounts available)
109- _, err = s.ClaimAccount()
109+ _, err = s.ClaimAccount(mysis.ID)
110110 if err == nil {
111111 t.Fatalf("BUG: ClaimAccount() succeeded when all accounts are in use. Should return 'no accounts available' error.")
112112 }
@@ -142,26 +142,31 @@ func TestLoginFlowRaceCondition(t *testing.T) {
142142 proxy := mcp.NewProxy(upstream)
143143 proxy.SetAccountStore(&accountStoreAdapter{s})
144144
145- // Mysis 1 claims account
146- claimed1, err := s.ClaimAccount()
145+ // Create myses for ownership tracking
146+ mysis1, err := s.CreateMysis("mysis-1", "mock", "test-model", 0.7)
147147 if err != nil {
148- t.Fatalf("Mysis1 ClaimAccount() failed: %v", err)
148+ t.Fatalf("Failed to create mysis1: %v", err)
149+ }
150+ mysis2, err := s.CreateMysis("mysis-2", "mock", "test-model", 0.7)
151+ if err != nil {
152+ t.Fatalf("Failed to create mysis2: %v", err)
149153 }
150154
151- // Mysis 2 tries to claim - should get the same account (not locked yet)
152- claimed2, err := s.ClaimAccount()
155+ // Mysis 1 claims account
156+ _, err = s.ClaimAccount(mysis1.ID)
153157 if err != nil {
154- t.Fatalf("Mysis2 ClaimAccount() failed: %v", err)
158+ t.Fatalf("Mysis1 ClaimAccount() failed: %v", err)
155159 }
156160
157- // Both should get same credentials (account not locked)
158- if claimed1.Username != claimed2.Username {
159- t.Fatalf("Expected both myses to claim same account, got %s and %s", claimed1.Username, claimed2.Username)
161+ // Mysis 2 tries to claim - should fail (account already claimed)
162+ _, err = s.ClaimAccount(mysis2.ID)
163+ if err == nil {
164+ t.Fatalf("Mysis2 ClaimAccount() succeeded unexpectedly")
160165 }
161166
162167 // Mysis 1 logs in first
163168 loginArgs := json.RawMessage(`{"username":"shared_crab","password":"pass123"}`)
164- _, err = proxy.CallTool(context.Background(), mcp.CallerContext{MysisID: "mysis1", MysisName: "mysis-1"}, "login", loginArgs)
169+ _, err = proxy.CallTool(context.Background(), mcp.CallerContext{MysisID: mysis1.ID, MysisName: "mysis-1"}, "login", loginArgs)
165170 if err != nil {
166171 t.Fatalf("Mysis1 login failed: %v", err)
167172 }
@@ -171,15 +176,23 @@ func TestLoginFlowRaceCondition(t *testing.T) {
171176 if !acc.InUse {
172177 t.Fatalf("Account should be in_use after mysis1 login")
173178 }
179+ if acc.InUseBy != mysis1.ID {
180+ t.Fatalf("Account in_use_by should be set to mysis1, got %q", acc.InUseBy)
181+ }
174182
175183 // Mysis 2 tries to login with same credentials - this will succeed at the game level
176184 // (since credentials are valid), but won't cause issues because handleLoginResponse
177185 // is idempotent (just sets in_use=1 again)
178- _, err = proxy.CallTool(context.Background(), mcp.CallerContext{MysisID: "mysis2", MysisName: "mysis-2"}, "login", loginArgs)
186+ _, err = proxy.CallTool(context.Background(), mcp.CallerContext{MysisID: mysis2.ID, MysisName: "mysis-2"}, "login", loginArgs)
179187 if err != nil {
180188 t.Fatalf("Mysis2 login failed: %v", err)
181189 }
182190
191+ acc, _ = s.GetAccount("shared_crab")
192+ if acc.InUseBy != mysis2.ID {
193+ t.Fatalf("Account in_use_by should be updated to mysis2, got %q", acc.InUseBy)
194+ }
195+
183196 // Both myses are now logged in with the same account
184197 // This is expected behavior - the lock happens at login, not claim
185198 // The game server will handle duplicate logins (usually kicks the old session)
@@ -216,16 +229,16 @@ type accountStoreAdapter struct {
216229 store *store.Store
217230 }
218231
219-func (a *accountStoreAdapter) CreateAccount(username, password string) (*mcp.Account, error) {
220- acc, err := a.store.CreateAccount(username, password)
232+func (a *accountStoreAdapter) CreateAccount(username, password string, mysisID ...string) (*mcp.Account, error) {
233+ acc, err := a.store.CreateAccount(username, password, mysisID...)
221234 if err != nil {
222235 return nil, err
223236 }
224237 return &mcp.Account{Username: acc.Username, Password: acc.Password}, nil
225238 }
226239
227-func (a *accountStoreAdapter) MarkAccountInUse(username string) error {
228- return a.store.MarkAccountInUse(username)
240+func (a *accountStoreAdapter) MarkAccountInUse(username, mysisID string) error {
241+ return a.store.MarkAccountInUse(username, mysisID)
229242 }
230243
231244 func (a *accountStoreAdapter) ReleaseAccount(username string) error {
@@ -236,8 +249,8 @@ func (a *accountStoreAdapter) ReleaseAllAccounts() error {
236249 return a.store.ReleaseAllAccounts()
237250 }
238251
239-func (a *accountStoreAdapter) ClaimAccount() (*mcp.Account, error) {
240- acc, err := a.store.ClaimAccount()
252+func (a *accountStoreAdapter) ClaimAccount(mysisID string) (*mcp.Account, error) {
253+ acc, err := a.store.ClaimAccount(mysisID)
241254 if err != nil {
242255 return nil, err
243256 }
internal/mcp/proxy.go+15−15
@@ -27,8 +27,8 @@ type CallerContext struct {
2727 type ToolHandlerWithContext func(ctx context.Context, caller CallerContext, arguments json.RawMessage) (*ToolResult, error)
2828
2929 type AccountStore interface {
30- CreateAccount(username, password string) (*Account, error)
31- MarkAccountInUse(username string) error
30+ CreateAccount(username, password string, mysisID ...string) (*Account, error)
31+ MarkAccountInUse(username, mysisID string) error
3232 ReleaseAccount(username string) error
3333 ReleaseAllAccounts() error
3434 }
@@ -179,7 +179,7 @@ func (p *Proxy) CallTool(ctx context.Context, caller CallerContext, name string,
179179 if p.upstream != nil {
180180 // Intercept register - if we have available accounts, login with one instead
181181 if name == "register" && accountStore != nil {
182- if poolAccount := p.tryClaimPoolAccount(); poolAccount != nil {
182+ if poolAccount := p.tryClaimPoolAccount(caller.MysisID); poolAccount != nil {
183183 // Login with pool account instead of registering
184184 loginArgs := map[string]interface{}{
185185 "username": poolAccount.Username,
@@ -189,7 +189,7 @@ func (p *Proxy) CallTool(ctx context.Context, caller CallerContext, name string,
189189 if result != nil && !result.IsError && accountStore != nil {
190190 // Mark account as in use
191191 loginArgsJSON, _ := json.Marshal(loginArgs)
192- p.interceptAuthTools("login", loginArgsJSON, result)
192+ p.interceptAuthTools("login", loginArgsJSON, result, caller.MysisID)
193193 }
194194 return result, err
195195 }
@@ -206,7 +206,7 @@ func (p *Proxy) CallTool(ctx context.Context, caller CallerContext, name string,
206206
207207 if result != nil {
208208 if !result.IsError && accountStore != nil {
209- p.interceptAuthTools(name, arguments, result)
209+ p.interceptAuthTools(name, arguments, result, caller.MysisID)
210210 }
211211 if result.IsError {
212212 // Rewrite error messages to guide myses toward correct behavior
@@ -303,18 +303,18 @@ func (p *Proxy) callUpstreamWithRetry(ctx context.Context, name string, args int
303303 return nil, fmt.Errorf("%w: %v", ErrToolRetryExhausted, lastErr)
304304 }
305305
306-func (p *Proxy) interceptAuthTools(toolName string, arguments json.RawMessage, result *ToolResult) {
306+func (p *Proxy) interceptAuthTools(toolName string, arguments json.RawMessage, result *ToolResult, mysisID string) {
307307 switch toolName {
308308 case "register":
309- p.handleRegisterResponse(arguments, result)
309+ p.handleRegisterResponse(arguments, result, mysisID)
310310 case "login":
311- p.handleLoginResponse(arguments, result)
311+ p.handleLoginResponse(arguments, result, mysisID)
312312 case "logout":
313313 p.handleLogoutResponse(arguments, result)
314314 }
315315 }
316316
317-func (p *Proxy) handleRegisterResponse(arguments json.RawMessage, result *ToolResult) {
317+func (p *Proxy) handleRegisterResponse(arguments json.RawMessage, result *ToolResult, mysisID string) {
318318 var args struct {
319319 Username string `json:"username"`
320320 }
@@ -329,11 +329,11 @@ func (p *Proxy) handleRegisterResponse(arguments json.RawMessage, result *ToolRe
329329
330330 password, ok := findStringField(payload, "password", "token")
331331 if args.Username != "" && ok && password != "" {
332- _, _ = p.accountStore.CreateAccount(args.Username, password)
332+ _, _ = p.accountStore.CreateAccount(args.Username, password, mysisID)
333333 }
334334 }
335335
336-func (p *Proxy) handleLoginResponse(arguments json.RawMessage, result *ToolResult) {
336+func (p *Proxy) handleLoginResponse(arguments json.RawMessage, result *ToolResult, mysisID string) {
337337 var args struct {
338338 Username string `json:"username"`
339339 }
@@ -342,7 +342,7 @@ func (p *Proxy) handleLoginResponse(arguments json.RawMessage, result *ToolResul
342342 }
343343
344344 if args.Username != "" {
345- _ = p.accountStore.MarkAccountInUse(args.Username)
345+ _ = p.accountStore.MarkAccountInUse(args.Username, mysisID)
346346 }
347347 }
348348
@@ -368,7 +368,7 @@ func (p *Proxy) handleLogoutResponse(arguments json.RawMessage, result *ToolResu
368368
369369 // tryClaimPoolAccount attempts to claim an available account from the pool.
370370 // Returns the account if one is available, nil otherwise.
371-func (p *Proxy) tryClaimPoolAccount() *Account {
371+func (p *Proxy) tryClaimPoolAccount(mysisID string) *Account {
372372 p.mu.RLock()
373373 accountStore := p.accountStore
374374 p.mu.RUnlock()
@@ -379,11 +379,11 @@ func (p *Proxy) tryClaimPoolAccount() *Account {
379379
380380 // Try to claim an account from the pool
381381 type accountClaimer interface {
382- ClaimAccount() (*Account, error)
382+ ClaimAccount(mysisID string) (*Account, error)
383383 }
384384
385385 if claimer, ok := accountStore.(accountClaimer); ok {
386- account, err := claimer.ClaimAccount()
386+ account, err := claimer.ClaimAccount(mysisID)
387387 if err == nil && account != nil {
388388 return account
389389 }
internal/mcp/proxy_test.go+2−2
@@ -37,12 +37,12 @@ type mockAccountStore struct {
3737 released []string
3838 }
3939
40-func (m *mockAccountStore) CreateAccount(username, password string) (*Account, error) {
40+func (m *mockAccountStore) CreateAccount(username, password string, mysisID ...string) (*Account, error) {
4141 m.created = append(m.created, Account{Username: username, Password: password})
4242 return &Account{Username: username, Password: password}, nil
4343 }
4444
45-func (m *mockAccountStore) MarkAccountInUse(username string) error {
45+func (m *mockAccountStore) MarkAccountInUse(username, mysisID string) error {
4646 m.marked = append(m.marked, username)
4747 return nil
4848 }
internal/store/accounts.go+65−17
@@ -10,17 +10,28 @@ type Account struct {
1010 Username string
1111 Password string
1212 InUse bool
13+ InUseBy string
1314 LastUsedAt time.Time
1415 CreatedAt time.Time
1516 }
1617
17-func (s *Store) CreateAccount(username, password string) (*Account, error) {
18+func (s *Store) CreateAccount(username, password string, mysisID ...string) (*Account, error) {
1819 now := time.Now().UTC()
20+ inUseBy := ""
21+ var inUseByParam interface{}
22+ inUse := 0
23+ if len(mysisID) > 0 && mysisID[0] != "" {
24+ inUseBy = mysisID[0]
25+ inUseByParam = mysisID[0]
26+ inUse = 1
27+ } else {
28+ inUseByParam = nil
29+ }
1930
2031 _, err := s.db.Exec(`
21- INSERT INTO accounts (username, password, in_use, created_at, last_used_at)
22- VALUES (?, ?, 1, ?, ?)
23- `, username, password, now, now)
32+ INSERT INTO accounts (username, password, in_use, in_use_by, created_at, last_used_at)
33+ VALUES (?, ?, ?, ?, ?, ?)
34+ `, username, password, inUse, inUseByParam, now, now)
2435 if err != nil {
2536 return nil, fmt.Errorf("insert account: %w", err)
2637 }
@@ -28,7 +39,8 @@ func (s *Store) CreateAccount(username, password string) (*Account, error) {
2839 return &Account{
2940 Username: username,
3041 Password: password,
31- InUse: true,
42+ InUse: inUse == 1,
43+ InUseBy: inUseBy,
3244 CreatedAt: now,
3345 LastUsedAt: now,
3446 }, nil
@@ -37,15 +49,42 @@ func (s *Store) CreateAccount(username, password string) (*Account, error) {
3749 func (s *Store) GetAccount(username string) (*Account, error) {
3850 var acc Account
3951 var lastUsedAt sql.NullTime
52+ var inUseBy sql.NullString
4053
4154 err := s.db.QueryRow(`
42- SELECT username, password, in_use, last_used_at, created_at
55+ SELECT username, password, in_use, in_use_by, last_used_at, created_at
4356 FROM accounts WHERE username = ?
44- `, username).Scan(&acc.Username, &acc.Password, &acc.InUse, &lastUsedAt, &acc.CreatedAt)
57+ `, username).Scan(&acc.Username, &acc.Password, &acc.InUse, &inUseBy, &lastUsedAt, &acc.CreatedAt)
4558 if err != nil {
4659 return nil, err
4760 }
4861
62+ if inUseBy.Valid {
63+ acc.InUseBy = inUseBy.String
64+ }
65+ if lastUsedAt.Valid {
66+ acc.LastUsedAt = lastUsedAt.Time
67+ }
68+
69+ return &acc, nil
70+}
71+
72+func (s *Store) GetAccountByMysisID(mysisID string) (*Account, error) {
73+ var acc Account
74+ var lastUsedAt sql.NullTime
75+ var inUseBy sql.NullString
76+
77+ err := s.db.QueryRow(`
78+ SELECT username, password, in_use, in_use_by, last_used_at, created_at
79+ FROM accounts WHERE in_use_by = ?
80+ `, mysisID).Scan(&acc.Username, &acc.Password, &acc.InUse, &inUseBy, &lastUsedAt, &acc.CreatedAt)
81+ if err != nil {
82+ return nil, err
83+ }
Cut short: this commit's diff is over 1000 lines.
internal/store/schema.sql+10−4
Cut short: this commit's diff is over 1000 lines.
internal/store/store.go+1−1
Cut short: this commit's diff is over 1000 lines.
internal/store/store_test.go+49−14
Cut short: this commit's diff is over 1000 lines.
internal/tui/TOOL_CALLS_DESIGN.md+0−325
Cut short: this commit's diff is over 1000 lines.
internal/tui/app.go+6−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/focus.go+34−91
Cut short: this commit's diff is over 1000 lines.