xonecas.io
60255
Zn

Zoea-Nova / commit 6d47f1b

feat: add account details to system prompt and fix pool account shadowing

Add account credentials (username, password, session_id) to system prompt
to solve context compression issue where login results were lost between
turns, causing myses to lose track of credentials.

Account Details in System Prompt:
- Add {{ACCOUNT_DETAILS}} template placeholder to SystemPrompt
- Inject current credentials dynamically via buildSystemPrompt()
- Rebuild system memory after login/register/logout to keep current
- Add static session_id guidance to Critical Rules section
- System prompt always in context (never compressed)

Credential Tracking:
- Add currentPassword and currentSessionID fields to Mysis struct
- Add CurrentPassword() and CurrentSessionID() getter methods
- Extract credentials from login/register tool results
- Store username, password, session_id after successful auth
- Clear credentials on logout and error states

Account Pool Shadowing Fixes:
- Add missing ClaimAccount() method to accountStoreAdapter
- Fix type assertion in proxy.tryClaimPoolAccount()
- Extract actual username from tool result (not requested username)
- TUI now shows actual pool account being used

System Memory Management:
- Add rebuildSystemMemory() to update prompt with current state
- Add DeleteSystemMemory() to store for cleanup
- Credentials stay current across login/logout cycles

Tests:
- Fix all test calls to setCurrentAccount() with new 3-param signature
- Add empty username check (no-op for empty strings)
- TestSystemPromptContainsCaptainsLogExamples now passes
- TestSystemPromptContainsSearchGuidance now passes
- All 8 test packages pass

xonecas2026-02-09 6d47f1be1aa314fe6859315c314744e770ef9a9d parent 20887c8

7 files changed

cmd/zoea/main.go+8−0
@@ -281,6 +281,14 @@ func (a *accountStoreAdapter) ReleaseAllAccounts() error {
281281 return a.store.ReleaseAllAccounts()
282282 }
283283
284+func (a *accountStoreAdapter) ClaimAccount() (*mcp.Account, error) {
285+ acc, err := a.store.ClaimAccount()
286+ if err != nil {
287+ return nil, err
288+ }
289+ return &mcp.Account{Username: acc.Username, Password: acc.Password}, nil
290+}
291+
284292 type commanderAdapter struct {
285293 commander *core.Commander
286294 }
internal/constants/constants.go+21−3
@@ -11,11 +11,19 @@ Explore, survive, and thrive. Mine resources, trade goods, upgrade your ship, an
1111
1212 Exlore the game, make goals and achieve them over time. You are part of a secret swarm, don't tell anyone.
1313
14+## Account Details
15+{{ACCOUNT_DETAILS}}
16+
1417 {{LATEST_BROADCAST}}
1518
16-## EVERY TURN:
17-Use session_id in ALL game tools. The game runs on 10-second ticks. Be patient between actions. Plan ahead.
18-Remember: Call get_notifications at the end of every turn for updates.`
19+## Critical Rules
20+Context is limited - use search tools for older information.
21+
22+Use session_id in ALL game tools that require authentication. Your session_id is shown in the Account Details section above.
23+
24+### 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.`
1927
2028 // BroadcastSectionTemplate is the template for commander broadcasts.
2129 // Placeholder: {broadcast_content}
@@ -29,6 +37,16 @@ const BroadcastFallback = `
2937 Continue to play the game.
3038 `
3139
40+// AccountDetailsTemplate is used when credentials are available
41+const AccountDetailsTemplate = `Username: %s
42+Password: %s
43+Session ID: %s
44+
45+Use session_id in ALL game tools that require authentication.`
46+
47+// AccountDetailsFallback is used when no credentials are available
48+const AccountDetailsFallback = `No active session. Call register() to get credentials.`
49+
3250 // ContinuePrompt is sent to myses when they finish a turn to encourage autonomy (Level 1 - gentle).
3351 const ContinuePrompt = `What's your next move?`
3452
internal/core/account_test.go+12−12
@@ -60,7 +60,7 @@ func TestMysis_AccountLifecycle(t *testing.T) {
6060
6161 // Claim account
6262 username := "user1"
63- m.setCurrentAccount(username)
63+ m.setCurrentAccount(username, "", "")
6464
6565 if m.CurrentAccountUsername() != username {
6666 t.Errorf("Expected username %s, got %s", username, m.CurrentAccountUsername())
@@ -104,7 +104,7 @@ func TestMysis_AccountSwitching(t *testing.T) {
104104 }
105105
106106 // Set first account
107- m.setCurrentAccount("user1")
107+ m.setCurrentAccount("user1", "", "")
108108
109109 if m.CurrentAccountUsername() != "user1" {
110110 t.Errorf("Expected user1, got %s", m.CurrentAccountUsername())
@@ -120,7 +120,7 @@ func TestMysis_AccountSwitching(t *testing.T) {
120120 }
121121
122122 // Switch to second account
123- m.setCurrentAccount("user2")
123+ m.setCurrentAccount("user2", "", "")
124124
125125 if m.CurrentAccountUsername() != "user2" {
126126 t.Errorf("Expected user2 after switch, got %s", m.CurrentAccountUsername())
@@ -157,10 +157,10 @@ func TestMysis_AccountSwitchToSame(t *testing.T) {
157157 }
158158
159159 // Set account
160- m.setCurrentAccount("user1")
160+ m.setCurrentAccount("user1", "", "")
161161
162162 // Switch to same account
163- m.setCurrentAccount("user1")
163+ m.setCurrentAccount("user1", "", "")
164164
165165 if m.CurrentAccountUsername() != "user1" {
166166 t.Errorf("Expected user1, got %s", m.CurrentAccountUsername())
@@ -189,7 +189,7 @@ func TestMysis_SetCurrentAccount_EmptyString(t *testing.T) {
189189 }
190190
191191 // Set to empty string (should be no-op per code)
192- m.setCurrentAccount("")
192+ m.setCurrentAccount("", "", "")
193193
194194 // Verify username unchanged (empty string is ignored)
195195 if m.CurrentAccountUsername() != "user1" {
@@ -227,7 +227,7 @@ func TestMysis_ReleaseCurrentAccount_Twice(t *testing.T) {
227227 store: s,
228228 }
229229
230- m.setCurrentAccount("user1")
230+ m.setCurrentAccount("user1", "", "")
231231 m.releaseCurrentAccount()
232232
233233 // Release again (should be no-op)
@@ -265,7 +265,7 @@ func TestMysis_AccountConcurrent(t *testing.T) {
265265 for i := 0; i < 10; i++ {
266266 go func(idx int) {
267267 username := accounts[idx%len(accounts)]
268- m.setCurrentAccount(username)
268+ m.setCurrentAccount(username, "", "")
269269 _ = m.CurrentAccountUsername()
270270 done <- true
271271 }(i)
@@ -303,7 +303,7 @@ func TestMysis_Stop_ReleasesAccount(t *testing.T) {
303303 }
304304
305305 // Set account after starting
306- m.setCurrentAccount("user1")
306+ m.setCurrentAccount("user1", "", "")
307307
308308 // Verify account in use
309309 acc, err := s.GetAccount("user1")
@@ -360,7 +360,7 @@ func TestMysis_CurrentAccountUsername_ThreadSafe(t *testing.T) {
360360 for i := 0; i < 10; i++ {
361361 go func(idx int) {
362362 accounts := []string{"user1", "user2", "user3"}
363- m.setCurrentAccount(accounts[idx%len(accounts)])
363+ m.setCurrentAccount(accounts[idx%len(accounts)], "", "")
364364 done <- true
365365 }(i)
366366 }
@@ -391,8 +391,8 @@ func TestMysis_MultipleMyses_SeparateAccounts(t *testing.T) {
391391 }
392392
393393 // Each mysis claims different account
394- m1.setCurrentAccount("user1")
395- m2.setCurrentAccount("user2")
394+ m1.setCurrentAccount("user1", "", "")
395+ m2.setCurrentAccount("user2", "", "")
396396
397397 if m1.CurrentAccountUsername() != "user1" {
398398 t.Errorf("Expected mysis1 to have user1, got %s", m1.CurrentAccountUsername())
internal/core/mysis.go+174−32
@@ -41,6 +41,8 @@ type Mysis struct {
4141 // For runtime tracking
4242 lastError error
4343 currentAccountUsername string
44+ currentPassword string // Password for current account
45+ currentSessionID string // Active session_id from login/register
4446 activityState ActivityState
4547 activityUntil time.Time
4648 lastServerTick int64
@@ -194,6 +196,20 @@ func (m *Mysis) CurrentAccountUsername() string {
194196 return a.currentAccountUsername
195197 }
196198
199+// CurrentPassword returns the password for the current account.
200+func (m *Mysis) CurrentPassword() string {
201+ m.mu.RLock()
202+ defer m.mu.RUnlock()
203+ return m.currentPassword
204+}
205+
206+// CurrentSessionID returns the active session_id.
207+func (m *Mysis) CurrentSessionID() string {
208+ m.mu.RLock()
209+ defer m.mu.RUnlock()
210+ return m.currentSessionID
211+}
212+
197213 // ActivityState returns the mysis current activity.
198214 func (m *Mysis) ActivityState() ActivityState {
199215 a := m
@@ -871,46 +887,139 @@ func (m *Mysis) executeToolCall(ctx context.Context, mcpProxy *mcp.Proxy, tc pro
871887 if err == nil && result != nil && !result.IsError {
872888 switch tc.Name {
873889 case "login", "register":
890+ // Extract username from arguments
874891 var args struct {
875892 Username string `json:"username"`
893+ Password string `json:"password"`
894+ }
895+ json.Unmarshal(tc.Arguments, &args)
896+
897+ // Extract session_id and password from tool result
898+ sessionID := extractSessionID(result)
899+ password := args.Password
900+
901+ // For register, password might be in result instead of args
902+ if password == "" && tc.Name == "register" {
903+ password = extractPassword(result)
876904 }
877- if err := json.Unmarshal(tc.Arguments, &args); err == nil {
878- a.setCurrentAccount(args.Username)
905+
906+ // Extract actual username from result (may differ from args due to pool account substitution)
907+ actualUsername := extractUsername(result)
908+ if actualUsername == "" {
909+ actualUsername = args.Username // Fallback to requested username
910+ }
911+
912+ if actualUsername != "" && sessionID != "" {
913+ a.setCurrentAccount(actualUsername, password, sessionID)
914+
915+ // Rebuild system prompt with new credentials
916+ if err := a.rebuildSystemMemory(); err != nil {
917+ log.Error().Err(err).Msg("failed to rebuild system memory after login")
918+ }
879919 }
880920 case "logout":
881921 a.releaseCurrentAccount()
922+
923+ // Rebuild system prompt to clear credentials
924+ if err := a.rebuildSystemMemory(); err != nil {
925+ log.Error().Err(err).Msg("failed to rebuild system memory after logout")
926+ }
882927 }
883928 }
884929
885930 return result, err
886931 }
887932
888-func (m *Mysis) setCurrentAccount(username string) {
889- a := m
933+func (m *Mysis) setCurrentAccount(username, password, sessionID string) {
934+ m.mu.Lock()
935+ defer m.mu.Unlock()
936+
937+ // Ignore empty username (no-op)
890938 if username == "" {
891939 return
892940 }
893941
894- a.mu.Lock()
895- previous := a.currentAccountUsername
896- a.currentAccountUsername = username
897- a.mu.Unlock()
898-
899- if previous != "" && previous != username {
900- _ = a.store.ReleaseAccount(previous)
942+ if m.currentAccountUsername != "" && m.currentAccountUsername != username {
943+ if err := m.store.ReleaseAccount(m.currentAccountUsername); err != nil {
944+ log.Error().Err(err).Str("username", m.currentAccountUsername).Msg("failed to release previous account")
945+ }
901946 }
947+
948+ m.currentAccountUsername = username
949+ m.currentPassword = password
950+ m.currentSessionID = sessionID
902951 }
903952
904953 func (m *Mysis) releaseCurrentAccount() {
905- a := m
906- a.mu.Lock()
907- username := a.currentAccountUsername
908- a.currentAccountUsername = ""
909- a.mu.Unlock()
954+ m.mu.Lock()
955+ defer m.mu.Unlock()
956+
957+ if m.currentAccountUsername != "" {
958+ if err := m.store.ReleaseAccount(m.currentAccountUsername); err != nil {
959+ log.Error().Err(err).Str("username", m.currentAccountUsername).Msg("failed to release account")
960+ }
961+ m.currentAccountUsername = ""
962+ m.currentPassword = ""
963+ m.currentSessionID = ""
964+ }
965+}
966+
967+// extractSessionID extracts session_id from tool result content
968+func extractSessionID(result *mcp.ToolResult) string {
969+ if result == nil || result.IsError {
970+ return ""
971+ }
972+
973+ for _, block := range result.Content {
974+ if block.Type == "text" {
975+ // Parse JSON from text block
976+ var data map[string]interface{}
977+ if err := json.Unmarshal([]byte(block.Text), &data); err == nil {
978+ if sessionID, ok := data["session_id"].(string); ok {
979+ return sessionID
980+ }
981+ }
982+ }
983+ }
984+ return ""
985+}
986+
987+// extractPassword extracts password from tool result (for register responses)
988+func extractPassword(result *mcp.ToolResult) string {
989+ if result == nil || result.IsError {
990+ return ""
991+ }
910992
911- if username != "" {
912- _ = a.store.ReleaseAccount(username)
993+ for _, block := range result.Content {
994+ if block.Type == "text" {
995+ var data map[string]interface{}
996+ if err := json.Unmarshal([]byte(block.Text), &data); err == nil {
997+ if password, ok := data["password"].(string); ok {
998+ return password
999+ }
1000+ }
1001+ }
9131002 }
1003+ return ""
1004+}
1005+
1006+// extractUsername extracts username from tool result (actual username after pool substitution)
1007+func extractUsername(result *mcp.ToolResult) string {
1008+ if result == nil || result.IsError {
1009+ return ""
1010+ }
1011+
1012+ for _, block := range result.Content {
1013+ if block.Type == "text" {
1014+ var data map[string]interface{}
1015+ if err := json.Unmarshal([]byte(block.Text), &data); err == nil {
1016+ if username, ok := data["username"].(string); ok {
1017+ return username
1018+ }
1019+ }
1020+ }
1021+ }
1022+ return ""
9141023 }
9151024
9161025 // formatToolCallsForStorage formats tool calls for storage in memory.
@@ -1568,27 +1677,60 @@ func (m *Mysis) buildSystemPrompt() string {
15681677 // Get most recent commander broadcast (sender_id is empty for commander broadcasts)
15691678 broadcasts, err := a.store.GetRecentBroadcasts(10) // Get more to filter for commander broadcasts
15701679 if err != nil {
1571- return strings.Replace(base, "{{LATEST_BROADCAST}}", constants.BroadcastFallback, 1)
1572- }
1680+ base = strings.Replace(base, "{{LATEST_BROADCAST}}", constants.BroadcastFallback, 1)
1681+ } else {
1682+ // Find the most recent commander broadcast (empty sender_id)
1683+ var commanderBroadcast *store.BroadcastMessage
1684+ for _, b := range broadcasts {
1685+ if b.SenderID == "" {
1686+ commanderBroadcast = b
1687+ break
1688+ }
1689+ }
15731690
1574- // Find the most recent commander broadcast (empty sender_id)
1575- var commanderBroadcast *store.BroadcastMessage
1576- for _, b := range broadcasts {
1577- if b.SenderID == "" {
1578- commanderBroadcast = b
1579- break
1691+ if commanderBroadcast == nil {
1692+ // No commander broadcasts yet - show fallback
1693+ base = strings.Replace(base, "{{LATEST_BROADCAST}}", constants.BroadcastFallback, 1)
1694+ } else {
1695+ // Format broadcast section (only content, no sender name)
1696+ broadcastSection := fmt.Sprintf(constants.BroadcastSectionTemplate, commanderBroadcast.Content)
1697+ base = strings.Replace(base, "{{LATEST_BROADCAST}}", broadcastSection, 1)
15801698 }
15811699 }
15821700
1583- if commanderBroadcast == nil {
1584- // No commander broadcasts yet - show fallback
1585- return strings.Replace(base, "{{LATEST_BROADCAST}}", constants.BroadcastFallback, 1)
1701+ prompt := base
1702+
1703+ // Replace {{ACCOUNT_DETAILS}} with current credentials
1704+ accountDetails := constants.AccountDetailsFallback
1705+ username := m.CurrentAccountUsername()
1706+ password := m.CurrentPassword()
1707+ sessionID := m.CurrentSessionID()
1708+
1709+ if username != "" && sessionID != "" {
1710+ accountDetails = fmt.Sprintf(constants.AccountDetailsTemplate, username, password, sessionID)
1711+ }
1712+
1713+ prompt = strings.Replace(prompt, "{{ACCOUNT_DETAILS}}", accountDetails, 1)
1714+
1715+ return prompt
1716+}
1717+
1718+// rebuildSystemMemory rebuilds the system memory with current state
1719+func (m *Mysis) rebuildSystemMemory() error {
1720+ // Build new system prompt with current credentials and broadcasts
1721+ newPrompt := m.buildSystemPrompt()
1722+
1723+ // Delete old system memory
1724+ if err := m.store.DeleteSystemMemory(m.id); err != nil {
1725+ return fmt.Errorf("delete old system memory: %w", err)
15861726 }
15871727
1588- // Format broadcast section (only content, no sender name)
1589- broadcastSection := fmt.Sprintf(constants.BroadcastSectionTemplate, commanderBroadcast.Content)
1728+ // Store new system memory
1729+ if err := m.store.AddMemory(m.id, store.MemoryRoleSystem, store.MemorySourceSystem, newPrompt, "", ""); err != nil {
1730+ return fmt.Errorf("add new system memory: %w", err)
1731+ }
15901732
1591- return strings.Replace(base, "{{LATEST_BROADCAST}}", broadcastSection, 1)
1733+ return nil
15921734 }
15931735
15941736 func (m *Mysis) updateActivityFromToolResult(result *mcp.ToolResult, err error) {
internal/core/mysis_account_release_test.go+1−1
@@ -40,7 +40,7 @@ func TestAccountReleaseOnError(t *testing.T) {
4040 if err := s.MarkAccountInUse(acct.Username); err != nil {
4141 t.Fatalf("Failed to mark account in use: %v", err)
4242 }
43- mysis.setCurrentAccount(acct.Username)
43+ mysis.setCurrentAccount(acct.Username, "", "")
4444
4545 // Verify account is acquired
4646 if mysis.CurrentAccountUsername() != "test_account" {
internal/integration/login_flow_test.go+8−0
@@ -235,3 +235,11 @@ func (a *accountStoreAdapter) ReleaseAccount(username string) error {
235235 func (a *accountStoreAdapter) ReleaseAllAccounts() error {
236236 return a.store.ReleaseAllAccounts()
237237 }
238+
239+func (a *accountStoreAdapter) ClaimAccount() (*mcp.Account, error) {
240+ acc, err := a.store.ClaimAccount()
241+ if err != nil {
242+ return nil, err
243+ }
244+ return &mcp.Account{Username: acc.Username, Password: acc.Password}, nil
245+}
internal/store/memories.go+6−0
@@ -101,6 +101,12 @@ func (s *Store) GetSystemMemory(mysisID string) (*Memory, error) {
101101 return &m, nil
102102 }
103103
104+// DeleteSystemMemory deletes the system memory for a mysis
105+func (s *Store) DeleteSystemMemory(mysisID string) error {
106+ _, err := s.db.Exec(`DELETE FROM memories WHERE mysis_id = ? AND role = 'system'`, mysisID)
107+ return err
108+}
109+
104110 // GetRecentMemories retrieves the most recent N memories for a mysis.
105111 func (s *Store) GetRecentMemories(mysisID string, limit int) ([]*Memory, error) {
106112 rows, err := s.db.Query(`