xonecas.io
60255
Zn

Zoea-Nova / commit 172b4b5

Implement permanent account assignment for myses

- Rename in_use_by to assigned_to in schema (v11 -> v12)
- Accounts permanently assigned to mysis_id, not released on logout
- Register interception: block if already assigned, else claim pool account
- Login interception: substitute credentials with assigned account
- Logout: clear game state cache but keep assignment
- Mysis deletion: release account back to pool via assigned_to
- Fix: register with pool now calls real login() for valid session
- Fix: remove account release logic from setCurrentAccount
- Remove obsolete account tests (account_test.go, mysis_account_release_test.go)

Eliminates timing races and enables reliable re-login without polluting
the game server with new test accounts.

xonecas2026-02-09 172b4b546245d67c16bb0e4feaf92feceb48be31 parent 3a95faa

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

cmd/zoea/main.go+14−2
@@ -249,14 +249,26 @@ func (a *accountStoreAdapter) CreateAccount(username, password string, mysisID .
249249 return &mcp.Account{Username: acc.Username, Password: acc.Password}, nil
250250 }
251251
252-func (a *accountStoreAdapter) MarkAccountInUse(username, mysisID string) error {
253- return a.store.MarkAccountInUse(username, mysisID)
252+func (a *accountStoreAdapter) GetAccountByMysisID(mysisID string) (*mcp.Account, error) {
253+ acc, err := a.store.GetAccountByMysisID(mysisID)
254+ if err != nil {
255+ return nil, err
256+ }
257+ return &mcp.Account{Username: acc.Username, Password: acc.Password}, nil
258+}
259+
260+func (a *accountStoreAdapter) AssignAccount(username, mysisID string) error {
261+ return a.store.AssignAccount(username, mysisID)
254262 }
255263
256264 func (a *accountStoreAdapter) ReleaseAccount(username string) error {
257265 return a.store.ReleaseAccount(username)
258266 }
259267
268+func (a *accountStoreAdapter) ReleaseAccountByMysisID(mysisID string) error {
269+ return a.store.ReleaseAccountByMysisID(mysisID)
270+}
271+
260272 func (a *accountStoreAdapter) ReleaseAllAccounts() error {
261273 return a.store.ReleaseAllAccounts()
262274 }
documentation/architecture/MYSIS_ACCOUNT_MANAGEMENT.md+51−33
@@ -1,14 +1,14 @@
11 # Mysis Account Management
22
3-**Version:** 2.0
4-**Date:** 2026-02-08
3+**Version:** 3.0
4+**Date:** 2026-02-09
55 **Status:** Truth Document
66
77 ---
88
99 ## Problem Statement
1010
11-Myses need game accounts to play SpaceMolt. We maintain a pool of accounts to control access and prevent account exhaustion.
11+Myses need game accounts to play SpaceMolt. Each mysis gets one account permanently assigned to eliminate timing races and enable reliable re-login. We need this account management to avoid polluting the server with more test accounts.
1212
1313 **Constraint:** No changes to gameplay whatsoever. Myses must be able to call any game API freely.
1414
@@ -16,39 +16,55 @@ Myses need game accounts to play SpaceMolt. We maintain a pool of accounts to co
1616
1717 ## Truth Table
1818
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 | N/A - `zoea_claim_account` removed entirely | Only game tools visible |
19+| Mysis Action | Mysis State | Pool State | System Behavior | Mysis Sees |
20+|--------------|-------------|------------|-----------------|------------|
21+| Calls `register(username, empire)` | No assigned account | Pool has available accounts | Proxy assigns pool account permanently, mimics MCP response with pool account details | `{result: {password, player_id}, session: {id, player_id, ...}}` (thinks it registered) |
22+| Calls `register(username, empire)` | No assigned account | Pool is empty | Proxy passes to game server, captures response, stores new account, assigns permanently | `{result: {password, player_id}, session: {...}}` (actually registered) |
23+| Calls `register(username, empire)` | Has assigned account | Any | Proxy returns error pointing to `login()` with assigned credentials | Error response |
24+| Calls `login(username, password)` | Has assigned account | Any | Proxy substitutes assigned account credentials, passes to game server | `{result: {player, ship, system, poi, ...}, session: {...}}` (logged into assigned account) |
25+| Calls `logout()` | Any | Any | Proxy passes to game server (account remains assigned) | Success |
26+| Lists tools | Any | Any | N/A - `zoea_claim_account` removed entirely | Only game tools visible |
2627
2728 ---
2829
2930 ## Behavior Rules
3031
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. **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
32+1. **Permanent assignment:** Once a mysis gets an account (via register), that account is permanently bound to `mysis_id` (stored in `assigned_to` field)
33+2. **First register - pool has accounts:** Proxy assigns pool account permanently, mimics game server `registered` response with pool account's password and player_id (never forwards to game server)
34+3. **First register - pool empty:** Proxy forwards register request to game server, captures response (password and player_id), stores new account in pool, assigns permanently to mysis
35+4. **Subsequent register:** When mysis with assigned account calls `register()`, proxy returns error: "Already have account. Use login(username, password)."
36+5. **Login substitution:** All `login()` calls from mysis with assigned account are silently substituted with assigned account credentials before passing to game server
37+6. **Account persistence:** Logout does NOT release account assignment - mysis keeps same account forever
38+7. **Account release:** Accounts return to pool ONLY when mysis is deleted/destroyed (assigned_to cleared)
39+8. **Internal claiming:** Account assignment is handled internally by proxy - no `zoea_claim_account` tool exists
3840
3941 ---
4042
4143 ## State Transitions
4244
4345 ```
44-POOL HAS ACCOUNTS:
45-Mysis: register() → Proxy: login(pool_account) → Game: session_id → Mysis: PLAYING
46+FIRST REGISTER - POOL HAS ACCOUNTS:
47+Mysis: register(username, empire) → Proxy: assign_account(pool) → Proxy: mimic_MCP_response({result: {password, player_id}, session: {...}}) → Mysis: REGISTERED
48+(Proxy never forwards to game server; mimics full MCP response structure with pool account credentials; account permanently bound to mysis_id)
4649
47-POOL EMPTY:
48-Mysis: register() → Game: session_id → Proxy: store_account → Mysis: PLAYING
50+FIRST REGISTER - POOL EMPTY:
51+Mysis: register(username, empire) → Game/MCP: {result: {password, player_id}, session: {...}} → Proxy: capture_response + store_account + assign_to_mysis → Mysis: REGISTERED
52+(Request forwarded to game server; new account created; response captured; account stored in pool and permanently bound to mysis_id)
4953
50-MYSIS HAS CREDENTIALS:
51-Mysis: login() → Game: session_id → Proxy: mark_in_use → Mysis: PLAYING
54+SUBSEQUENT REGISTER:
55+Mysis: register() → Proxy: error_response → Mysis: ERROR
56+(Proxy returns MCP error: "Already have account. Use login(username, password).")
57+
58+LOGIN WITH ASSIGNED ACCOUNT:
59+Mysis: login(any_user, any_pass) → Proxy: substitute(assigned_credentials) → Game/MCP: {result: {player, ship, system, poi, ...}, session: {...}} → Mysis: LOGGED_IN
60+(Always logs into assigned account regardless of provided credentials; full game state returned)
61+
62+LOGOUT:
63+Mysis: logout() → Game/MCP: success → Mysis: LOGGED_OUT
64+(Account remains assigned to mysis_id for future login)
65+
66+MYSIS DELETION:
67+Commander: delete_mysis() → Store: clear assigned_to → Pool gains available account
5268 ```
5369
5470 ---
@@ -57,26 +73,28 @@ Mysis: login() → Game: session_id → Proxy: mark_in_use → Mysis: PLAYING
5773
5874 | Scenario | Expected Outcome |
5975 |----------|------------------|
60-| Pool has 3 accounts, mysis calls register | Mysis gets session_id, pool has 2 available accounts |
61-| Pool empty, mysis calls register | Mysis gets session_id, pool has 1 account (the new one) |
62-| 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 |
64-| Mysis calls logout | Account released, pool gains 1 available account |
76+| Pool has 3 accounts, new mysis calls register | Proxy mimics full MCP response with pool account's password/player_id/session (no game server call), account permanently assigned to mysis_id, pool has 2 available accounts |
77+| Pool empty, new mysis calls register | Request forwarded to game server, MCP response captured (password/player_id/session), new account stored in pool and permanently assigned to mysis_id |
78+| Mysis with assigned account calls register again | Mysis receives MCP error: "Already have account. Use login(username, password)." |
79+| Mysis with assigned account calls login(wrong_user, wrong_pass) | Proxy substitutes assigned credentials, mysis gets full MCP response with `{result: {player, ship, system, poi, ...}, session: {...}}` for assigned account |
80+| Mysis with assigned account calls logout | Mysis logged out, account remains assigned to mysis_id (can login again later) |
81+| Mysis is deleted | Account's assigned_to cleared, account returns to available pool |
82+| `make db-reset-accounts` run | All mysis assignments cleared (assigned_to = NULL), accounts return to pool, account details preserved |
6583 | Mysis lists tools | Only game tools visible (no `zoea_claim_account` - tool removed) |
6684
6785 ---
6886
6987 ## Implementation Files
7088
71-- `internal/mcp/proxy.go` - Register interception, account pool claim, tool filtering
89+- `internal/mcp/proxy.go` - Register interception, permanent assignment, login credential substitution, tool filtering
7290 - `internal/constants/constants.go` - System prompt (no auth instructions)
73-- `internal/store/accounts.go` - Account pool management
91+- `internal/store/accounts.go` - Account pool management with `assigned_to` field
92+- `Makefile` - `db-reset-accounts` target must clear `assigned_to` while preserving account details
7493
7594 ---
7695
7796 ## Out of Scope
7897
79-- Token budget management
80-- Structural JSON compaction
81-- Tool call merging
8298 - Review of other `zoea_*` tools (note: `zoea_claim_account` was removed entirely)
99+- Account sharing between myses (one account = one mysis permanently)
100+- Manual account reassignment (only via mysis deletion)
internal/core/account_test.go+0−476
@@ -1,476 +0,0 @@
1-package core
2-
3-import (
4- "path/filepath"
5- "testing"
6-
7- "github.com/xonecas/zoea-nova/internal/provider"
8- "github.com/xonecas/zoea-nova/internal/store"
9-)
10-
11-// setupAccountTest creates a test store with accounts for testing.
12-func setupAccountTest(t *testing.T) (*store.Store, func()) {
13- t.Helper()
14-
15- tmpDir := t.TempDir()
16- dbPath := filepath.Join(tmpDir, "test.db")
17- s, err := store.Open(dbPath)
18- if err != nil {
19- t.Fatalf("Open() error: %v", err)
20- }
21-
22- // Add test accounts
23- accounts := []struct {
24- username string
25- password string
26- }{
27- {"user1", "pass1"},
28- {"user2", "pass2"},
29- {"user3", "pass3"},
30- }
31-
32- for _, acc := range accounts {
33- if _, err := s.CreateAccount(acc.username, acc.password); err != nil {
34- t.Fatalf("CreateAccount(%s) error: %v", acc.username, err)
35- }
36- }
37-
38- cleanup := func() {
39- s.Close()
40- }
41-
42- return s, cleanup
43-}
44-
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-
54-// TestMysis_AccountLifecycle tests the full account claim/release lifecycle.
55-func TestMysis_AccountLifecycle(t *testing.T) {
56- s, cleanup := setupAccountTest(t)
57- defer cleanup()
58-
59- mysis := createTestMysis(t, s, "test-mysis")
60-
61- m := &Mysis{
62- id: mysis.ID,
63- name: "test",
64- store: s,
65- }
66-
67- // Initially no account
68- if m.CurrentAccountUsername() != "" {
69- t.Errorf("Expected no account initially, got %s", m.CurrentAccountUsername())
70- }
71-
72- // Claim account
73- username := "user1"
74- m.setCurrentAccount(username, "", "")
75-
76- if m.CurrentAccountUsername() != username {
77- t.Errorf("Expected username %s, got %s", username, m.CurrentAccountUsername())
78- }
79-
80- // Verify account marked as in use in store
81- acc, err := s.GetAccount(username)
82- if err != nil {
83- t.Fatalf("GetAccount() error: %v", err)
84- }
85- if !acc.InUse {
86- t.Error("Expected account marked as in use")
87- }
88-
89- // Release account
90- m.releaseCurrentAccount()
91-
92- if m.CurrentAccountUsername() != "" {
93- t.Errorf("Expected no account after release, got %s", m.CurrentAccountUsername())
94- }
95-
96- // Verify account marked as available in store
97- acc, err = s.GetAccount(username)
98- if err != nil {
99- t.Fatalf("GetAccount() error after release: %v", err)
100- }
101- if acc.InUse {
102- t.Error("Expected account marked as available after release")
103- }
104-}
105-
106-// TestMysis_AccountSwitching tests switching between accounts.
107-func TestMysis_AccountSwitching(t *testing.T) {
108- s, cleanup := setupAccountTest(t)
109- defer cleanup()
110-
111- mysis := createTestMysis(t, s, "test-mysis")
112-
113- m := &Mysis{
114- id: mysis.ID,
115- name: "test",
116- store: s,
117- }
118-
119- // Set first account
120- m.setCurrentAccount("user1", "", "")
121-
122- if m.CurrentAccountUsername() != "user1" {
123- t.Errorf("Expected user1, got %s", m.CurrentAccountUsername())
124- }
125-
126- // Verify first account in use
127- acc1, err := s.GetAccount("user1")
128- if err != nil {
129- t.Fatalf("GetAccount(user1) error: %v", err)
130- }
131- if !acc1.InUse {
132- t.Error("Expected user1 marked as in use")
133- }
134-
135- // Switch to second account
136- m.setCurrentAccount("user2", "", "")
137-
138- if m.CurrentAccountUsername() != "user2" {
139- t.Errorf("Expected user2 after switch, got %s", m.CurrentAccountUsername())
140- }
141-
142- // Verify first account released
143- acc1, err = s.GetAccount("user1")
144- if err != nil {
145- t.Fatalf("GetAccount(user1) error after switch: %v", err)
146- }
147- if acc1.InUse {
148- t.Error("Expected user1 released after switch")
149- }
150-
151- // Verify second account in use
152- acc2, err := s.GetAccount("user2")
153- if err != nil {
154- t.Fatalf("GetAccount(user2) error: %v", err)
155- }
156- if !acc2.InUse {
157- t.Error("Expected user2 marked as in use")
158- }
159-}
160-
161-// TestMysis_AccountSwitchToSame tests switching to the same account (no-op).
162-func TestMysis_AccountSwitchToSame(t *testing.T) {
163- s, cleanup := setupAccountTest(t)
164- defer cleanup()
165-
166- mysis := createTestMysis(t, s, "test-mysis")
167-
168- m := &Mysis{
169- id: mysis.ID,
170- name: "test",
171- store: s,
172- }
173-
174- // Set account
175- m.setCurrentAccount("user1", "", "")
176-
177- // Switch to same account
178- m.setCurrentAccount("user1", "", "")
179-
180- if m.CurrentAccountUsername() != "user1" {
181- t.Errorf("Expected user1, got %s", m.CurrentAccountUsername())
182- }
183-
184- // Verify account still in use (only once)
185- acc, err := s.GetAccount("user1")
186- if err != nil {
187- t.Fatalf("GetAccount() error: %v", err)
188- }
189- if !acc.InUse {
190- t.Error("Expected user1 still marked as in use")
191- }
192-}
193-
194-// TestMysis_SetCurrentAccount_EmptyString tests setting empty username.
195-func TestMysis_SetCurrentAccount_EmptyString(t *testing.T) {
196- s, cleanup := setupAccountTest(t)
197- defer cleanup()
198-
199- mysis := createTestMysis(t, s, "test-mysis")
200-
201- m := &Mysis{
202- id: mysis.ID,
203- name: "test",
204- store: s,
205- currentAccountUsername: "user1",
206- }
207-
208- // Set to empty string (should be no-op per code)
209- m.setCurrentAccount("", "", "")
210-
211- // Verify username unchanged (empty string is ignored)
212- if m.CurrentAccountUsername() != "user1" {
213- t.Errorf("Expected user1 unchanged, got %s", m.CurrentAccountUsername())
214- }
215-}
216-
217-// TestMysis_ReleaseCurrentAccount_NoAccount tests releasing when no account is set.
218-func TestMysis_ReleaseCurrentAccount_NoAccount(t *testing.T) {
219- s, cleanup := setupAccountTest(t)
220- defer cleanup()
221-
222- mysis := createTestMysis(t, s, "test-mysis")
223-
224- m := &Mysis{
225- id: mysis.ID,
226- name: "test",
227- store: s,
228- }
229-
230- // Release when no account (should be no-op)
231- m.releaseCurrentAccount()
232-
233- if m.CurrentAccountUsername() != "" {
234- t.Errorf("Expected no account, got %s", m.CurrentAccountUsername())
235- }
236-}
237-
238-// TestMysis_ReleaseCurrentAccount_Twice tests releasing same account twice.
239-func TestMysis_ReleaseCurrentAccount_Twice(t *testing.T) {
240- s, cleanup := setupAccountTest(t)
241- defer cleanup()
242-
243- mysis := createTestMysis(t, s, "test-mysis")
244-
245- m := &Mysis{
246- id: mysis.ID,
247- name: "test",
248- store: s,
249- }
250-
251- m.setCurrentAccount("user1", "", "")
252- m.releaseCurrentAccount()
253-
254- // Release again (should be no-op)
255- m.releaseCurrentAccount()
256-
257- if m.CurrentAccountUsername() != "" {
258- t.Errorf("Expected no account after double release, got %s", m.CurrentAccountUsername())
259- }
260-
261- // Verify account still available
262- acc, err := s.GetAccount("user1")
263- if err != nil {
264- t.Fatalf("GetAccount() error: %v", err)
265- }
266- if acc.InUse {
267- t.Error("Expected user1 available after release")
268- }
269-}
270-
271-// TestMysis_AccountConcurrent tests thread safety of account operations.
272-func TestMysis_AccountConcurrent(t *testing.T) {
273- s, cleanup := setupAccountTest(t)
274- defer cleanup()
275-
276- mysis := createTestMysis(t, s, "test-mysis")
277-
278- m := &Mysis{
279- id: mysis.ID,
280- name: "test",
281- store: s,
282- }
283-
284- done := make(chan bool)
285-
286- // Run multiple goroutines switching accounts
287- accounts := []string{"user1", "user2", "user3"}
288- for i := 0; i < 10; i++ {
289- go func(idx int) {
290- username := accounts[idx%len(accounts)]
291- m.setCurrentAccount(username, "", "")
292- _ = m.CurrentAccountUsername()
293- done <- true
294- }(i)
295- }
296-
297- // Wait for all goroutines
298- for i := 0; i < 10; i++ {
299- <-done
300- }
301-
302- // No assertions needed - just verify no data races (run with -race)
303-}
304-
305-// TestMysis_Stop_ReleasesAccount tests that Stop() releases the current account.
306-func TestMysis_Stop_ReleasesAccount(t *testing.T) {
307- s, cleanup := setupAccountTest(t)
308- defer cleanup()
309-
310- // Create stored mysis
311- stored, err := s.CreateMysis("test-mysis", "mock", "test-model", 0.7)
312- if err != nil {
313- t.Fatalf("CreateMysis() error: %v", err)
314- }
315-
316- bus := NewEventBus(100)
317- defer bus.Close()
318-
319- // Use mock provider
320- mock := provider.NewMock("mock", "test response")
321- m := NewMysis(stored.ID, stored.Name, stored.CreatedAt, mock, s, bus, "")
322-
323- // Start the mysis so it enters Running state
324- if err := m.Start(); err != nil {
325- t.Fatalf("Start() error: %v", err)
326- }
327-
328- // Set account after starting
329- m.setCurrentAccount("user1", "", "")
330-
331- // Verify account in use
332- acc, err := s.GetAccount("user1")
333- if err != nil {
334- t.Fatalf("GetAccount() error: %v", err)
335- }
336- if !acc.InUse {
337- t.Error("Expected user1 marked as in use before stop")
338- }
339-
340- // Stop mysis (should release account)
341- if err := m.Stop(); err != nil {
342- t.Fatalf("Stop() error: %v", err)
343- }
344-
345- // Verify account released
346- acc, err = s.GetAccount("user1")
347- if err != nil {
348- t.Fatalf("GetAccount() error after stop: %v", err)
349- }
350- if acc.InUse {
351- t.Error("Expected user1 released after stop")
352- }
353-
354- // Verify mysis has no account
355- if m.CurrentAccountUsername() != "" {
356- t.Errorf("Expected no account after stop, got %s", m.CurrentAccountUsername())
357- }
358-}
359-
360-// TestMysis_CurrentAccountUsername_ThreadSafe tests thread safety of account getter.
361-func TestMysis_CurrentAccountUsername_ThreadSafe(t *testing.T) {
362- s, cleanup := setupAccountTest(t)
363- defer cleanup()
364-
365- mysis := createTestMysis(t, s, "test-mysis")
366-
367- m := &Mysis{
368- id: mysis.ID,
369- name: "test",
370- store: s,
371- currentAccountUsername: "user1",
372- }
373-
374- done := make(chan bool)
375-
376- // Run multiple goroutines reading account
377- for i := 0; i < 10; i++ {
378- go func() {
379- _ = m.CurrentAccountUsername()
380- done <- true
381- }()
382- }
383-
384- // Run multiple goroutines writing account
385- for i := 0; i < 10; i++ {
386- go func(idx int) {
387- accounts := []string{"user1", "user2", "user3"}
388- m.setCurrentAccount(accounts[idx%len(accounts)], "", "")
389- done <- true
390- }(i)
391- }
392-
393- // Wait for all goroutines
394- for i := 0; i < 20; i++ {
395- <-done
396- }
397-
398- // No assertions needed - just verify no data races (run with -race)
399-}
400-
401-// TestMysis_MultipleMyses_SeparateAccounts tests multiple myses with different accounts.
402-func TestMysis_MultipleMyses_SeparateAccounts(t *testing.T) {
403- s, cleanup := setupAccountTest(t)
404- defer cleanup()
405-
406- // Create actual mysis records in database
407- stored1, err := s.CreateMysis("mysis1", "mock", "test-model", 0.7)
408- if err != nil {
409- t.Fatalf("CreateMysis(mysis1) error: %v", err)
410- }
411- stored2, err := s.CreateMysis("mysis2", "mock", "test-model", 0.7)
412- if err != nil {
413- t.Fatalf("CreateMysis(mysis2) error: %v", err)
414- }
415-
416- m1 := &Mysis{
417- id: stored1.ID,
418- name: "mysis1",
419- store: s,
420- }
421-
422- m2 := &Mysis{
423- id: stored2.ID,
424- name: "mysis2",
425- store: s,
426- }
427-
428- // Each mysis claims different account
429- m1.setCurrentAccount("user1", "", "")
430- m2.setCurrentAccount("user2", "", "")
431-
432- if m1.CurrentAccountUsername() != "user1" {
433- t.Errorf("Expected mysis1 to have user1, got %s", m1.CurrentAccountUsername())
434- }
435-
436- if m2.CurrentAccountUsername() != "user2" {
437- t.Errorf("Expected mysis2 to have user2, got %s", m2.CurrentAccountUsername())
438- }
439-
440- // Verify both accounts in use
441- acc1, err := s.GetAccount("user1")
442- if err != nil {
443- t.Fatalf("GetAccount(user1) error: %v", err)
444- }
445- if !acc1.InUse {
446- t.Error("Expected user1 in use by mysis1")
447- }
448-
449- acc2, err := s.GetAccount("user2")
450- if err != nil {
451- t.Fatalf("GetAccount(user2) error: %v", err)
452- }
453- if !acc2.InUse {
454- t.Error("Expected user2 in use by mysis2")
455- }
456-
457- // Release mysis1 account
458- m1.releaseCurrentAccount()
459-
460- // Verify only user1 released
461- acc1, err = s.GetAccount("user1")
462- if err != nil {
463- t.Fatalf("GetAccount(user1) error after release: %v", err)
464- }
465- if acc1.InUse {
466- t.Error("Expected user1 released")
467- }
468-
469- acc2, err = s.GetAccount("user2")
470- if err != nil {
471- t.Fatalf("GetAccount(user2) error after release: %v", err)
472- }
473- if !acc2.InUse {
474- t.Error("Expected user2 still in use by mysis2")
475- }
476-}
internal/core/mysis.go+25−16
@@ -444,14 +444,26 @@ func (a *accountStoreAdapter) CreateAccount(username, password string, mysisID .
444444 return &mcp.Account{Username: acc.Username, Password: acc.Password}, nil
445445 }
446446
447-func (a *accountStoreAdapter) MarkAccountInUse(username, mysisID string) error {
448- return a.store.MarkAccountInUse(username, mysisID)
447+func (a *accountStoreAdapter) GetAccountByMysisID(mysisID string) (*mcp.Account, error) {
448+ acc, err := a.store.GetAccountByMysisID(mysisID)
449+ if err != nil {
450+ return nil, err
451+ }
452+ return &mcp.Account{Username: acc.Username, Password: acc.Password}, nil
453+}
454+
455+func (a *accountStoreAdapter) AssignAccount(username, mysisID string) error {
456+ return a.store.AssignAccount(username, mysisID)
449457 }
450458
451459 func (a *accountStoreAdapter) ReleaseAccount(username string) error {
452460 return a.store.ReleaseAccount(username)
453461 }
454462
463+func (a *accountStoreAdapter) ReleaseAccountByMysisID(mysisID string) error {
464+ return a.store.ReleaseAccountByMysisID(mysisID)
465+}
466+
455467 func (a *accountStoreAdapter) ReleaseAllAccounts() error {
456468 return a.store.ReleaseAllAccounts()
457469 }
@@ -1161,11 +1173,9 @@ func (m *Mysis) setCurrentAccount(username, password, sessionID string) {
11611173 return
11621174 }
11631175
1164- if m.currentAccountUsername != "" && m.currentAccountUsername != username {
1165- if err := m.store.ReleaseAccount(m.currentAccountUsername); err != nil {
1166- log.Error().Err(err).Str("username", m.currentAccountUsername).Msg("failed to release previous account")
1167- }
1168- }
1176+ // Under permanent assignment model, accounts don't switch
1177+ // If username differs from current, this is the first assignment
1178+ // No release needed - accounts are permanently assigned
11691179
11701180 m.currentAccountUsername = username
11711181 m.currentPassword = password
@@ -1173,8 +1183,8 @@ func (m *Mysis) setCurrentAccount(username, password, sessionID string) {
11731183 m.mu.Unlock()
11741184
11751185 if storeRef != nil {
1176- if err := storeRef.MarkAccountInUse(username, m.id); err != nil {
1177- log.Error().Err(err).Str("username", username).Msg("failed to mark account in use")
1186+ if err := storeRef.AssignAccount(username, m.id); err != nil {
1187+ log.Error().Err(err).Str("username", username).Msg("failed to assign account")
11781188 }
11791189 }
11801190 }
@@ -1183,14 +1193,13 @@ func (m *Mysis) releaseCurrentAccount() {
11831193 m.mu.Lock()
11841194 defer m.mu.Unlock()
11851195
1186- if m.currentAccountUsername != "" {
1187- if err := m.store.ReleaseAccount(m.currentAccountUsername); err != nil {
1188- log.Error().Err(err).Str("username", m.currentAccountUsername).Msg("failed to release account")
1189- }
1190- m.currentAccountUsername = ""
1191- m.currentPassword = ""
1192- m.currentSessionID = ""
1196+ // Release the permanently assigned account for this mysis
1197+ if err := m.store.ReleaseAccountByMysisID(m.id); err != nil {
1198+ log.Error().Err(err).Str("mysis_id", m.id).Msg("failed to release account")
11931199 }
1200+ m.currentAccountUsername = ""
1201+ m.currentPassword = ""
1202+ m.currentSessionID = ""
11941203 }
11951204
11961205 // extractSessionID extracts session_id from tool result content
internal/core/mysis_account_release_test.go+0−85
@@ -1,85 +0,0 @@
1-package core
2-
3-import (
4- "fmt"
5- "testing"
6-
7- "github.com/xonecas/zoea-nova/internal/provider"
8-)
9-
10-// TestAccountReleaseOnError verifies that accounts are properly released
11-// when a mysis transitions to errored state, allowing restart to succeed.
12-func TestAccountReleaseOnError(t *testing.T) {
13- s, bus, cleanup := setupMysisTest(t)
14- defer cleanup()
15-
16- p := provider.NewMock("mock", "test response")
17-
18- // Create account for testing
19- acct, err := s.CreateAccount("test_account", "password")
20- if err != nil {
21- t.Fatalf("Failed to create test account: %v", err)
22- }
23-
24- // Create stored mysis
25- stored, err := s.CreateMysis("test-mysis", "mock", "test-model", 0.7)
26- if err != nil {
27- t.Fatalf("CreateMysis() error: %v", err)
28- }
29-
30- // Create mysis
31- mysis := NewMysis(stored.ID, stored.Name, stored.CreatedAt, p, s, bus, "")
32-
33- // Start mysis
34- if err := mysis.Start(); err != nil {
35- t.Fatalf("Failed to start mysis: %v", err)
36- }
37-
38- // Simulate mysis acquiring an account (simulating login tool call)
39- // First mark account in use, then set current account
40- if err := s.MarkAccountInUse(acct.Username, stored.ID); err != nil {
41- t.Fatalf("Failed to mark account in use: %v", err)
42- }
43- mysis.setCurrentAccount(acct.Username, "", "")
44-
45- // Verify account is acquired
46- if mysis.CurrentAccountUsername() != "test_account" {
47- t.Fatalf("Expected account to be acquired")
48- }
49-
50- // Verify account is locked in store (ClaimAccount should not return this account)
51- claimed, err := s.ClaimAccount(stored.ID)
52- if err == nil && claimed.Username == acct.Username {
53- t.Fatalf("Expected account to be locked, but ClaimAccount returned it")
54- }
55-
56- // Trigger error state (simulating SendMessage failure)
57- mysis.setError(fmt.Errorf("simulated error"))
58-
59- // Verify state transitioned to errored
60- if mysis.State() != MysisStateErrored {
61- t.Fatalf("Expected state to be MysisStateErrored, got %v", mysis.State())
62- }
63-
64- // KEY TEST: Verify account was released
65- if mysis.CurrentAccountUsername() != "" {
66- t.Errorf("BUG CONFIRMED: Account not released on error. CurrentAccountUsername=%q", mysis.CurrentAccountUsername())
67- }
68-
69- // Verify account is unlocked in store (ClaimAccount should return it)
70- claimed2, err := s.ClaimAccount(stored.ID)
71- if err != nil || claimed2 == nil || claimed2.Username != acct.Username {
72- t.Errorf("BUG CONFIRMED: Account still locked in store, ClaimAccount failed: %v", err)
73- } else {
74- // Clean up acquired lock
75- _ = s.ReleaseAccount(claimed2.Username)
76- }
77-
78- // KEY TEST: Verify restart succeeds
79- if err := mysis.Start(); err != nil {
80- t.Errorf("RESTART FAILED: %v (likely due to account lock contention)", err)
81- }
82-
83- // Clean up
84- _ = mysis.Stop()
85-}
internal/integration/login_flow_test.go+14−2
@@ -237,14 +237,26 @@ func (a *accountStoreAdapter) CreateAccount(username, password string, mysisID .
237237 return &mcp.Account{Username: acc.Username, Password: acc.Password}, nil
238238 }
239239
240-func (a *accountStoreAdapter) MarkAccountInUse(username, mysisID string) error {
241- return a.store.MarkAccountInUse(username, mysisID)
240+func (a *accountStoreAdapter) GetAccountByMysisID(mysisID string) (*mcp.Account, error) {
241+ acc, err := a.store.GetAccountByMysisID(mysisID)
242+ if err != nil {
243+ return nil, err
244+ }
245+ return &mcp.Account{Username: acc.Username, Password: acc.Password}, nil
246+}
247+
248+func (a *accountStoreAdapter) AssignAccount(username, mysisID string) error {
249+ return a.store.AssignAccount(username, mysisID)
242250 }
243251
244252 func (a *accountStoreAdapter) ReleaseAccount(username string) error {
245253 return a.store.ReleaseAccount(username)
246254 }
247255
256+func (a *accountStoreAdapter) ReleaseAccountByMysisID(mysisID string) error {
257+ return a.store.ReleaseAccountByMysisID(mysisID)
258+}
259+
248260 func (a *accountStoreAdapter) ReleaseAllAccounts() error {
249261 return a.store.ReleaseAllAccounts()
250262 }
internal/mcp/proxy.go+32−13
@@ -28,8 +28,10 @@ type ToolHandlerWithContext func(ctx context.Context, caller CallerContext, argu
2828
2929 type AccountStore interface {
3030 CreateAccount(username, password string, mysisID ...string) (*Account, error)
31- MarkAccountInUse(username, mysisID string) error
31+ GetAccountByMysisID(mysisID string) (*Account, error)
32+ AssignAccount(username, mysisID string) error
3233 ReleaseAccount(username string) error
34+ ReleaseAccountByMysisID(mysisID string) error
3335 ReleaseAllAccounts() error
3436 }
3537
@@ -177,26 +179,44 @@ func (p *Proxy) CallTool(ctx context.Context, caller CallerContext, name string,
177179
178180 // Fall back to upstream
179181 if p.upstream != nil {
180- // Intercept register - if we have available accounts, login with one instead
182+ // Intercept register - check if mysis already has an assigned account
181183 if name == "register" && accountStore != nil {
184+ // Check if mysis already has a permanently assigned account
185+ if assignedAccount, err := accountStore.GetAccountByMysisID(caller.MysisID); err == nil && assignedAccount != nil {
186+ // Mysis already has an account - return error
187+ errorMsg := fmt.Sprintf("Already have account. Use login(username=\"%s\", password=\"...\").", assignedAccount.Username)
188+ return &ToolResult{
189+ Content: []ContentBlock{{Type: "text", Text: errorMsg}},
190+ IsError: true,
191+ }, nil
192+ }
193+
194+ // Try to claim an available account from pool
182195 if poolAccount := p.tryClaimPoolAccount(caller.MysisID); poolAccount != nil {
183- // Login with pool account instead of registering
196+ // Account claimed - login with pool account to get real session
184197 loginArgs := map[string]interface{}{
185198 "username": poolAccount.Username,
186199 "password": poolAccount.Password,
187200 }
188201 result, err := p.callUpstreamWithRetry(ctx, "login", loginArgs)
189202 if result != nil && !result.IsError {
190- // Inject password into result so mysis can extract it
191- // (login response doesn't include password, but register does)
203+ // Transform login response to look like register response
204+ // (inject password field so mysis can extract it)
192205 p.injectPasswordIntoResult(result, poolAccount.Password)
206+ }
207+ return result, err
208+ }
209+ }
193210
194- if accountStore != nil {
195- // Mark account as in use
196- loginArgsJSON, _ := json.Marshal(loginArgs)
197- p.interceptAuthTools("login", loginArgsJSON, result, caller.MysisID)
198- }
211+ // Intercept login - substitute credentials with assigned account if mysis has one
212+ if name == "login" && accountStore != nil {
213+ if assignedAccount, err := accountStore.GetAccountByMysisID(caller.MysisID); err == nil && assignedAccount != nil {
214+ // Mysis has assigned account - substitute credentials
215+ loginArgs := map[string]interface{}{
216+ "username": assignedAccount.Username,
217+ "password": assignedAccount.Password,
199218 }
219+ result, err := p.callUpstreamWithRetry(ctx, "login", loginArgs)
200220 return result, err
201221 }
202222 }
@@ -348,7 +368,7 @@ func (p *Proxy) handleLoginResponse(arguments json.RawMessage, result *ToolResul
348368 }
349369
350370 if args.Username != "" {
351- _ = p.accountStore.MarkAccountInUse(args.Username, mysisID)
371+ _ = p.accountStore.AssignAccount(args.Username, mysisID)
352372 }
353373 }
354374
@@ -364,8 +384,7 @@ func (p *Proxy) handleLogoutResponse(arguments json.RawMessage, result *ToolResu
364384 }
365385
366386 if username != "" {
367- _ = p.accountStore.ReleaseAccount(username)
368- // Clear game state cache on logout
387+ // Clear game state cache on logout (but keep account assignment)
369388 if p.gameStateStore != nil {
370389 _ = p.gameStateStore.DeleteGameStateSnapshotsForUsername(username)
371390 }
internal/store/accounts.go+55−44
@@ -9,29 +9,26 @@ import (
99 type Account struct {
1010 Username string
1111 Password string
12- InUse bool
13- InUseBy string
12+ AssignedTo string
1413 LastUsedAt time.Time
1514 CreatedAt time.Time
1615 }
1716
1817 func (s *Store) CreateAccount(username, password string, mysisID ...string) (*Account, error) {
1918 now := time.Now().UTC()
20- inUseBy := ""
21- var inUseByParam interface{}
22- inUse := 0
19+ assignedTo := ""
20+ var assignedToParam interface{}
2321 if len(mysisID) > 0 && mysisID[0] != "" {
24- inUseBy = mysisID[0]
25- inUseByParam = mysisID[0]
26- inUse = 1
22+ assignedTo = mysisID[0]
23+ assignedToParam = mysisID[0]
2724 } else {
28- inUseByParam = nil
25+ assignedToParam = nil
2926 }
3027
3128 _, err := s.db.Exec(`
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)
29+ INSERT INTO accounts (username, password, assigned_to, created_at, last_used_at)
30+ VALUES (?, ?, ?, ?, ?)
31+ `, username, password, assignedToParam, now, now)
3532 if err != nil {
3633 return nil, fmt.Errorf("insert account: %w", err)
3734 }
@@ -39,8 +36,7 @@ func (s *Store) CreateAccount(username, password string, mysisID ...string) (*Ac
3936 return &Account{
4037 Username: username,
4138 Password: password,
42- InUse: inUse == 1,
43- InUseBy: inUseBy,
39+ AssignedTo: assignedTo,
4440 CreatedAt: now,
4541 LastUsedAt: now,
4642 }, nil
@@ -49,18 +45,18 @@ func (s *Store) CreateAccount(username, password string, mysisID ...string) (*Ac
4945 func (s *Store) GetAccount(username string) (*Account, error) {
5046 var acc Account
5147 var lastUsedAt sql.NullTime
52- var inUseBy sql.NullString
48+ var assignedTo sql.NullString
5349
5450 err := s.db.QueryRow(`
55- SELECT username, password, in_use, in_use_by, last_used_at, created_at
51+ SELECT username, password, assigned_to, last_used_at, created_at
5652 FROM accounts WHERE username = ?
57- `, username).Scan(&acc.Username, &acc.Password, &acc.InUse, &inUseBy, &lastUsedAt, &acc.CreatedAt)
53+ `, username).Scan(&acc.Username, &acc.Password, &assignedTo, &lastUsedAt, &acc.CreatedAt)
5854 if err != nil {
5955 return nil, err
6056 }
6157
62- if inUseBy.Valid {
63- acc.InUseBy = inUseBy.String
58+ if assignedTo.Valid {
59+ acc.AssignedTo = assignedTo.String
6460 }
6561 if lastUsedAt.Valid {
6662 acc.LastUsedAt = lastUsedAt.Time
@@ -72,18 +68,18 @@ func (s *Store) GetAccount(username string) (*Account, error) {
7268 func (s *Store) GetAccountByMysisID(mysisID string) (*Account, error) {
7369 var acc Account
7470 var lastUsedAt sql.NullTime
75- var inUseBy sql.NullString
71+ var assignedTo sql.NullString
7672
7773 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)
74+ SELECT username, password, assigned_to, last_used_at, created_at
Cut short: this commit's diff is over 1000 lines.
internal/store/schema.sql+7−11
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.