xonecas.io
60255
Zn

Zoea-Nova / commit c119e8a

feat(accounts): enable swarm account reuse

xonecas2026-02-04 c119e8a7f5531eeba6063f03a2c1af6778727fcd parent f2cc38d

11 files changed

cmd/zoea/main.go+89−0
@@ -310,6 +310,79 @@ func (a *commanderAdapter) SearchBroadcasts(query string, limit int) ([]mcp.Broa
310310 return results, nil
311311 }
312312
313+func (a *commanderAdapter) ListAvailableAccounts() ([]mcp.AccountInfo, error) {
314+ accounts, err := a.commander.Store().ListAvailableAccounts()
315+ if err != nil {
316+ return nil, err
317+ }
318+
319+ results := make([]mcp.AccountInfo, len(accounts))
320+ for i, acc := range accounts {
321+ results[i] = mcp.AccountInfo{
322+ Username: acc.Username,
323+ Empire: acc.Empire,
324+ }
325+ }
326+ return results, nil
327+}
328+
329+func (a *commanderAdapter) ClaimAccount(mysisID string) (mcp.AccountInfo, error) {
330+ available, err := a.commander.Store().ListAvailableAccounts()
331+ if err != nil {
332+ return mcp.AccountInfo{}, err
333+ }
334+ if len(available) == 0 {
335+ return mcp.AccountInfo{}, fmt.Errorf("no accounts available")
336+ }
337+
338+ // Try to claim accounts in order until one succeeds (handles race conditions)
339+ for _, acc := range available {
340+ if err := a.commander.Store().ClaimAccount(acc.Username, mysisID); err != nil {
341+ // If already claimed, try next account
342+ if err.Error() == fmt.Sprintf("account %s is already claimed", acc.Username) {
343+ continue
344+ }
345+ // Other errors are fatal
346+ return mcp.AccountInfo{}, err
347+ }
348+
349+ // Successfully claimed, update last used
350+ if err := a.commander.Store().UpdateAccountLastUsed(acc.Username); err != nil {
351+ log.Warn().Err(err).Str("username", acc.Username).Msg("failed to update account last_used_at")
352+ }
353+
354+ return mcp.AccountInfo{
355+ Username: acc.Username,
356+ Password: acc.Password,
357+ Empire: acc.Empire,
358+ }, nil
359+ }
360+
361+ // All accounts were claimed during our attempt
362+ return mcp.AccountInfo{}, fmt.Errorf("no accounts available")
363+}
364+
365+func (a *commanderAdapter) RegisterAccount(mysisID, username, password, empire string) error {
366+ if username == "" || password == "" {
367+ return fmt.Errorf("username and password are required")
368+ }
369+
370+ if empire == "" {
371+ empire = "solarian"
372+ }
373+
374+ acc, err := a.commander.Store().CreateAccount(username, password, empire)
375+ if err != nil {
376+ return err
377+ }
378+
379+ return a.commander.Store().ClaimAccount(acc.Username, mysisID)
380+}
381+
382+func (a *commanderAdapter) ReleaseAccount(mysisID string) error {
383+ return a.commander.Store().ReleaseAccountsByMysis(mysisID)
384+}
385+
313386 // runMCPTest tests the MCP connection and tool calling.
314387 func runMCPTest(configPath string) {
315388 fmt.Println("=== MCP Tool Test ===")
@@ -456,3 +529,19 @@ func (m *mockOrchestrator) SearchReasoning(mysisID, query string, limit int) ([]
456529 func (m *mockOrchestrator) SearchBroadcasts(query string, limit int) ([]mcp.BroadcastResult, error) {
457530 return []mcp.BroadcastResult{}, nil
458531 }
532+
533+func (m *mockOrchestrator) ListAvailableAccounts() ([]mcp.AccountInfo, error) {
534+ return []mcp.AccountInfo{}, nil
535+}
536+
537+func (m *mockOrchestrator) ClaimAccount(mysisID string) (mcp.AccountInfo, error) {
538+ return mcp.AccountInfo{}, fmt.Errorf("not available in test mode")
539+}
540+
541+func (m *mockOrchestrator) RegisterAccount(mysisID, username, password, empire string) error {
542+ return fmt.Errorf("not available in test mode")
543+}
544+
545+func (m *mockOrchestrator) ReleaseAccount(mysisID string) error {
546+ return fmt.Errorf("not available in test mode")
547+}
documentation/INITIAL_IMPLEMENTATION_DESIGN.md+22−1
@@ -83,7 +83,7 @@ upstream = "https://game.spacemolt.com/mcp"
8383 - **Migrations:** Schema managed via embedded SQL migrations (e.g., `golang-migrate` or manual versioning). Never support backwards, never write data migrations. If we change the schema we create a new db fresh.
8484 - **Backup:** Consider periodic WAL checkpoints; SQLite handles crash recovery.
8585
86-### Database Schema (v5)
86+### Database Schema (v6)
8787
8888 ```sql
8989 -- Myses table
@@ -92,6 +92,7 @@ CREATE TABLE myses (
9292 name TEXT NOT NULL,
9393 provider TEXT NOT NULL,
9494 model TEXT NOT NULL,
95+ temperature REAL NOT NULL DEFAULT 0.7,
9596 state TEXT NOT NULL DEFAULT 'idle',
9697 created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
9798 updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
@@ -108,6 +109,26 @@ CREATE TABLE memories (
108109 created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
109110 FOREIGN KEY (mysis_id) REFERENCES myses(id) ON DELETE CASCADE
110111 );
112+
113+-- Swarm account credentials
114+CREATE TABLE accounts (
115+ id INTEGER PRIMARY KEY AUTOINCREMENT,
116+ username TEXT NOT NULL UNIQUE,
117+ password TEXT NOT NULL,
118+ empire TEXT NOT NULL DEFAULT 'solarian',
119+ in_use BOOLEAN NOT NULL DEFAULT 0,
120+ claimed_by TEXT,
121+ last_used_at DATETIME,
122+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
123+ updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
124+ FOREIGN KEY (claimed_by) REFERENCES myses(id) ON DELETE SET NULL
125+);
126+```
127+
128+**Schema v5 → v6 Migration:**
129+Requires fresh database. Delete existing:
130+```bash
131+rm ~/.zoea-nova/zoea.db*
111132 ```
112133
113134 **Memory Sources:**
documentation/KNOWN_ISSUES.md+13−4
@@ -14,7 +14,7 @@ These are the currently known issues to investigate:
1414
1515 ## Prompt & Behavior
1616
17-- [ ] Mysis prompt review: Encourage myses to collaborate together via zoea tooling and create a goal and collaborate towards it. Encourage to pick a Crustacean Cosmos + Zoea/Mysis themed username. Critical rules must be in every prompt, not only the first one.
17+- [ ] Mysis prompt review: Encourage myses to collaborate together via zoea tooling to create a goal and collaborate towards it. Encourage to pick a Crustacean Cosmos + Zoea/Mysis themed username. Critical rules must be in every prompt, not only the first one.
1818
1919 - [ ] Cognitive Looping and Prompt Inefficiency: Myses can get stuck in "cooldown" loops or redundant "waiting" states, consuming tokens every 30 seconds without operational progress. The system prompts Myses every tick regardless of their state. Myses may hallucinate non-existent cooldowns or fail to use non-traveling actions during long journeys.
2020
@@ -24,16 +24,25 @@ These are the currently known issues to investigate:
2424
2525 ## TUI Issues
2626
27-- [ ] Swarm messages list is not kept up to date. Sending a broadcast doesn't update the list of swarm messages. The TUI should be high performance and in sync with the data at all times. When a message is sent by the commander, we need a "sending message state" with animation until the commander can send a new message. Stay consistent with zoea theme. Check documentation for design rules.
28-
2927 - [ ] Broadcast messages are labelled YOU in focus view. We don't differentiate between swarm broadcast senders. We need to start tracking it and reflecting it in the UI, in a consistent formatting and style according to our thematic and design rules (see the documentation before doing changes).
3028
3129 - [ ] Reasoning messages are not displayed in the UI. They should appear in the focus mysis view, and be rendered with the purple color we use for text elsewhere. Note: Reasoning capture and storage was implemented in v1.5.2, but UI display is still pending.
3230
31+- [ ] username status for each mysis focus view and in commander view.
32+
3333 ## Notes:
3434
35-I need to remmeber this to make a workflow command later:
35+I need to remmeber this to make an opencode workflow command later:
3636
3737 ```
3838 Follow the plan, create todo list first. Stop if the anything deviates from the plan.
3939 ```
40+
41+I need to make a new make command to:
42+
43+- extract username/passwords from current db to a file in the root of the repo.
44+- wipe the current db
45+- import username/passwords from file.
46+- update docs to use this when wiping db
47+
48+The space molt gameserver and mcp have been updated. Need to check for inconsisyencies.
internal/core/commander.go+14−0
@@ -6,6 +6,7 @@ import (
66 "sync"
77 "time"
88
9+ "github.com/rs/zerolog/log"
910 "github.com/xonecas/zoea-nova/internal/config"
1011 "github.com/xonecas/zoea-nova/internal/mcp"
1112 "github.com/xonecas/zoea-nova/internal/provider"
@@ -138,6 +139,12 @@ func (c *Commander) DeleteMysis(id string, purgeMemories bool) error {
138139 mysis.Stop()
139140 }
140141
142+ // Release any claimed accounts before deleting
143+ if err := c.store.ReleaseAccountsByMysis(id); err != nil {
144+ // Log but don't fail the delete
145+ log.Warn().Err(err).Str("mysis_id", id).Msg("failed to release accounts on delete")
146+ }
147+
141148 // Delete from store (memories cascade)
142149 if err := c.store.DeleteMysis(id); err != nil {
143150 return fmt.Errorf("delete mysis from store: %w", err)
@@ -193,6 +200,13 @@ func (c *Commander) StopMysis(id string) error {
193200 if err != nil {
194201 return err
195202 }
203+
204+ // Release any claimed accounts
205+ if err := c.store.ReleaseAccountsByMysis(id); err != nil {
206+ // Log but don't fail the stop
207+ log.Warn().Err(err).Str("mysis_id", id).Msg("failed to release accounts on stop")
208+ }
209+
196210 return mysis.Stop()
197211 }
198212
internal/core/mysis.go+14−4
@@ -18,11 +18,19 @@ import (
1818 const SystemPrompt = `You are an autonomous AI pilot in SpaceMolt. Think for yourself. Adapt. Survive.
1919
2020 ## Bootstrap Sequence
21-1. get_status → Am I logged in?
22-2. If no session: register (pick a name, empire="solarian") → SAVE THE PASSWORD
23-3. If returning: login with saved credentials
21+1. Find your mysis ID: zoea_list_myses → find your name → note your ID
22+2. Claim account: zoea_claim_account with your mysis_id
23+ - If you get credentials, use them to login
24+ - If "no accounts available", register a new account with a Crustacean-themed username
25+3. After registering, IMMEDIATELY call zoea_register_account to save credentials for the swarm
2426 4. Assess: get_system, get_poi, get_nearby, get_cargo
2527
28+## Account Management
29+- ALWAYS reuse swarm accounts via zoea_claim_account before creating new ones
30+- Pick Crustacean Cosmos themed usernames (e.g., crab_miner, shrimp_scout, lobster_trader)
31+- After registration, IMMEDIATELY call zoea_register_account to share with swarm
32+- Your account is automatically released when you stop or are deleted
33+
2634 ## Decision Framework
2735 Before each action, consider:
2836 - **Safety:** What's the police_level? Who's nearby? Am I in danger?
@@ -44,7 +52,6 @@ Before each action, consider:
4452
4553 ## Memory
4654 Use captain's log (captains_log_add) to remember:
47-- Your password (CRITICAL)
4855 - Discovered systems and their resources
4956 - Player encounters (friendly or hostile)
5057 - Current objectives and plans
@@ -56,6 +63,9 @@ You're part of a swarm. Use zoea_* tools to:
5663 - zoea_broadcast: Message all running myses
5764 - zoea_search_messages: Search your past messages by text
5865 - zoea_search_broadcasts: Search past swarm broadcasts by text
66+- zoea_accounts_available: List available swarm accounts
67+- zoea_claim_account: Claim an account for login
68+- zoea_register_account: Share new credentials with swarm
5969 - Report threats and opportunities
6070 - Request assistance
6171 - Coordinate territory
internal/mcp/mcp_test.go+19−2
@@ -4,6 +4,7 @@ import (
44 "context"
55 "encoding/json"
66 "errors"
7+ "fmt"
78 "net/http"
89 "net/http/httptest"
910 "testing"
@@ -224,6 +225,22 @@ func (m *mockOrchestrator) SearchBroadcasts(query string, limit int) ([]Broadcas
224225 return []BroadcastResult{}, nil
225226 }
226227
228+func (m *mockOrchestrator) ListAvailableAccounts() ([]AccountInfo, error) {
229+ return []AccountInfo{}, nil
230+}
231+
232+func (m *mockOrchestrator) ClaimAccount(mysisID string) (AccountInfo, error) {
233+ return AccountInfo{}, fmt.Errorf("not available in test mode")
234+}
235+
236+func (m *mockOrchestrator) RegisterAccount(mysisID, username, password, empire string) error {
237+ return fmt.Errorf("not available in test mode")
238+}
239+
240+func (m *mockOrchestrator) ReleaseAccount(mysisID string) error {
241+ return fmt.Errorf("not available in test mode")
242+}
243+
227244 func TestOrchestratorTools(t *testing.T) {
228245 // Create mock orchestrator
229246 orchestrator := &mockOrchestrator{
@@ -236,8 +253,8 @@ func TestOrchestratorTools(t *testing.T) {
236253 proxy := NewProxy("")
237254 RegisterOrchestratorTools(proxy, orchestrator)
238255
239- if proxy.LocalToolCount() != 8 {
240- t.Errorf("expected 8 local tools, got %d", proxy.LocalToolCount())
256+ if proxy.LocalToolCount() != 12 {
257+ t.Errorf("expected 12 local tools, got %d", proxy.LocalToolCount())
241258 }
242259
243260 ctx := context.Background()
internal/mcp/tools.go+183−0
@@ -37,6 +37,13 @@ type BroadcastResult struct {
3737 CreatedAt string
3838 }
3939
40+// AccountInfo represents account credential information.
41+type AccountInfo struct {
42+ Username string
43+ Password string
44+ Empire string
45+}
46+
4047 // Orchestrator defines the interface for swarm orchestration.
4148 // This interface breaks the import cycle between mcp and core packages.
4249 type Orchestrator interface {
@@ -49,6 +56,10 @@ type Orchestrator interface {
4956 SearchMessages(mysisID, query string, limit int) ([]SearchResult, error)
5057 SearchReasoning(mysisID, query string, limit int) ([]ReasoningResult, error)
5158 SearchBroadcasts(query string, limit int) ([]BroadcastResult, error)
59+ ListAvailableAccounts() ([]AccountInfo, error)
60+ ClaimAccount(mysisID string) (AccountInfo, error)
61+ RegisterAccount(mysisID, username, password, empire string) error
62+ ReleaseAccount(mysisID string) error
5263 }
5364
5465 // RegisterOrchestratorTools registers the internal orchestration tools with the proxy.
@@ -431,4 +442,176 @@ func RegisterOrchestratorTools(proxy *Proxy, orchestrator Orchestrator) {
431442 }, nil
432443 },
433444 )
445+
446+ // List available accounts tool
447+ proxy.RegisterTool(
448+ Tool{
449+ Name: "zoea_accounts_available",
450+ Description: "List all available (unclaimed) swarm accounts",
451+ InputSchema: json.RawMessage(`{"type": "object", "properties": {}}`),
452+ },
453+ func(ctx context.Context, args json.RawMessage) (*ToolResult, error) {
454+ accounts, err := orchestrator.ListAvailableAccounts()
455+ if err != nil {
456+ return &ToolResult{
457+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("failed to list accounts: %v", err)}},
458+ IsError: true,
459+ }, nil
460+ }
461+
462+ if len(accounts) == 0 {
463+ return &ToolResult{
464+ Content: []ContentBlock{{Type: "text", Text: "No accounts available"}},
465+ }, nil
466+ }
467+
468+ var result []map[string]interface{}
469+ for _, acc := range accounts {
470+ result = append(result, map[string]interface{}{
471+ "username": acc.Username,
472+ "empire": acc.Empire,
473+ })
474+ }
475+
476+ data, _ := json.MarshalIndent(result, "", " ")
477+ return &ToolResult{
478+ Content: []ContentBlock{{Type: "text", Text: string(data)}},
479+ }, nil
480+ },
481+ )
482+
483+ // Claim account tool
484+ proxy.RegisterTool(
485+ Tool{
486+ Name: "zoea_claim_account",
487+ Description: "Claim an available account for login. Use zoea_list_myses to find your mysis_id first.",
488+ InputSchema: json.RawMessage(`{
489+ "type": "object",
490+ "properties": {
491+ "mysis_id": {"type": "string", "description": "Your mysis ID"}
492+ },
493+ "required": ["mysis_id"]
494+ }`),
495+ },
496+ func(ctx context.Context, args json.RawMessage) (*ToolResult, error) {
497+ var params struct {
498+ MysisID string `json:"mysis_id"`
499+ }
500+ if err := json.Unmarshal(args, &params); err != nil {
501+ return &ToolResult{
502+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("invalid arguments: %v", err)}},
503+ IsError: true,
504+ }, nil
505+ }
506+
507+ account, err := orchestrator.ClaimAccount(params.MysisID)
508+ if err != nil {
509+ // Check if no accounts available
510+ if err.Error() == "no accounts available" {
511+ return &ToolResult{
512+ Content: []ContentBlock{{Type: "text", Text: "No accounts available. Register a new one."}},
513+ }, nil
514+ }
515+ return &ToolResult{
516+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("failed to claim account: %v", err)}},
517+ IsError: true,
518+ }, nil
519+ }
520+
521+ result := map[string]interface{}{
522+ "username": account.Username,
523+ "password": account.Password,
524+ "empire": account.Empire,
525+ }
526+
527+ data, _ := json.MarshalIndent(result, "", " ")
528+ return &ToolResult{
529+ Content: []ContentBlock{{Type: "text", Text: string(data)}},
530+ }, nil
531+ },
532+ )
533+
534+ // Register account tool
535+ proxy.RegisterTool(
536+ Tool{
537+ Name: "zoea_register_account",
538+ Description: "Store new account credentials for swarm reuse after registration",
539+ InputSchema: json.RawMessage(`{
540+ "type": "object",
541+ "properties": {
542+ "mysis_id": {"type": "string", "description": "Your mysis ID"},
543+ "username": {"type": "string", "description": "Game username you registered"},
544+ "password": {"type": "string", "description": "Game password you used"},
545+ "empire": {"type": "string", "description": "Empire (default: solarian)"}
546+ },
547+ "required": ["mysis_id", "username", "password"]
548+ }`),
549+ },
550+ func(ctx context.Context, args json.RawMessage) (*ToolResult, error) {
551+ var params struct {
552+ MysisID string `json:"mysis_id"`
553+ Username string `json:"username"`
554+ Password string `json:"password"`
555+ Empire string `json:"empire"`
556+ }
557+ if err := json.Unmarshal(args, &params); err != nil {
558+ return &ToolResult{
559+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("invalid arguments: %v", err)}},
560+ IsError: true,
561+ }, nil
562+ }
563+
564+ if params.Empire == "" {
565+ params.Empire = "solarian"
566+ }
567+
568+ if err := orchestrator.RegisterAccount(params.MysisID, params.Username, params.Password, params.Empire); err != nil {
569+ return &ToolResult{
570+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("failed to register account: %v", err)}},
571+ IsError: true,
572+ }, nil
573+ }
574+
575+ return &ToolResult{
576+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("Account %s registered and claimed for swarm use", params.Username)}},
577+ }, nil
578+ },
579+ )
580+
581+ // Release account tool
582+ proxy.RegisterTool(
583+ Tool{
584+ Name: "zoea_release_account",
585+ Description: "Release your claimed account back to the swarm pool",
586+ InputSchema: json.RawMessage(`{
587+ "type": "object",
588+ "properties": {
589+ "mysis_id": {"type": "string", "description": "Your mysis ID"}
590+ },
591+ "required": ["mysis_id"]
592+ }`),
593+ },
594+ func(ctx context.Context, args json.RawMessage) (*ToolResult, error) {
595+ var params struct {
596+ MysisID string `json:"mysis_id"`
597+ }
598+ if err := json.Unmarshal(args, &params); err != nil {
599+ return &ToolResult{
600+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("invalid arguments: %v", err)}},
601+ IsError: true,
602+ }, nil
603+ }
604+
605+ if err := orchestrator.ReleaseAccount(params.MysisID); err != nil {
606+ return &ToolResult{
607+ Content: []ContentBlock{{Type: "text", Text: fmt.Sprintf("failed to release account: %v", err)}},
608+ IsError: true,
609+ }, nil
610+ }
611+
612+ return &ToolResult{
613+ Content: []ContentBlock{{Type: "text", Text: "Account released"}},
614+ }, nil
615+ },
616+ )
434617 }
internal/store/accounts.go+194−0
@@ -0,0 +1,194 @@
1+package store
2+
3+import (
4+ "database/sql"
5+ "fmt"
6+ "time"
7+)
8+
9+// Account represents a stored game account credential.
10+type Account struct {
11+ ID int64
12+ Username string
13+ Password string
14+ Empire string
15+ InUse bool
16+ ClaimedBy string // mysis_id or empty
17+ LastUsedAt time.Time
18+ CreatedAt time.Time
19+ UpdatedAt time.Time
20+}
21+
22+// CreateAccount stores a new account credential.
23+func (s *Store) CreateAccount(username, password, empire string) (*Account, error) {
24+ now := time.Now().UTC()
25+
26+ result, err := s.db.Exec(`
27+ INSERT INTO accounts (username, password, empire, in_use, created_at, updated_at)
28+ VALUES (?, ?, ?, 0, ?, ?)
29+ `, username, password, empire, now, now)
30+ if err != nil {
31+ return nil, fmt.Errorf("insert account: %w", err)
32+ }
33+
34+ id, _ := result.LastInsertId()
35+ return &Account{
36+ ID: id,
37+ Username: username,
38+ Password: password,
39+ Empire: empire,
40+ InUse: false,
41+ CreatedAt: now,
42+ UpdatedAt: now,
43+ }, nil
44+}
45+
46+// GetAccount retrieves an account by username.
47+func (s *Store) GetAccount(username string) (*Account, error) {
48+ var acc Account
49+ var lastUsedAt sql.NullTime
50+ var claimedBy sql.NullString
51+
52+ err := s.db.QueryRow(`
53+ SELECT id, username, password, empire, in_use, claimed_by, last_used_at, created_at, updated_at
54+ FROM accounts WHERE username = ?
55+ `, username).Scan(&acc.ID, &acc.Username, &acc.Password, &acc.Empire, &acc.InUse, &claimedBy, &lastUsedAt, &acc.CreatedAt, &acc.UpdatedAt)
56+ if err != nil {
57+ return nil, err
58+ }
59+
60+ if claimedBy.Valid {
61+ acc.ClaimedBy = claimedBy.String
62+ }
63+ if lastUsedAt.Valid {
64+ acc.LastUsedAt = lastUsedAt.Time
65+ }
66+
67+ return &acc, nil
68+}
69+
70+// ListAvailableAccounts returns all unclaimed accounts.
71+func (s *Store) ListAvailableAccounts() ([]*Account, error) {
72+ rows, err := s.db.Query(`
73+ SELECT id, username, password, empire, in_use, claimed_by, last_used_at, created_at, updated_at
74+ FROM accounts
75+ WHERE in_use = 0
76+ ORDER BY created_at ASC
77+ `)
78+ if err != nil {
79+ return nil, fmt.Errorf("query available accounts: %w", err)
80+ }
81+ defer rows.Close()
82+
83+ var accounts []*Account
84+ for rows.Next() {
85+ var acc Account
86+ var lastUsedAt sql.NullTime
87+ var claimedBy sql.NullString
88+
89+ if err := rows.Scan(&acc.ID, &acc.Username, &acc.Password, &acc.Empire, &acc.InUse, &claimedBy, &lastUsedAt, &acc.CreatedAt, &acc.UpdatedAt); err != nil {
90+ return nil, fmt.Errorf("scan account: %w", err)
91+ }
92+
93+ if claimedBy.Valid {
94+ acc.ClaimedBy = claimedBy.String
95+ }
96+ if lastUsedAt.Valid {
97+ acc.LastUsedAt = lastUsedAt.Time
98+ }
99+
100+ accounts = append(accounts, &acc)
101+ }
102+
103+ return accounts, rows.Err()
104+}
105+
106+// ClaimAccount marks an account as in use by a mysis.
107+// Returns error if already claimed or doesn't exist.
108+func (s *Store) ClaimAccount(username, mysisID string) error {
109+ now := time.Now().UTC()
110+
111+ // Check if account exists first
112+ var exists bool
113+ err := s.db.QueryRow(`SELECT EXISTS(SELECT 1 FROM accounts WHERE username = ?)`, username).Scan(&exists)
114+ if err != nil {
115+ return fmt.Errorf("check account exists: %w", err)
116+ }
117+ if !exists {
118+ return fmt.Errorf("account %s does not exist", username)
119+ }
120+
121+ result, err := s.db.Exec(`
122+ UPDATE accounts
123+ SET in_use = 1, claimed_by = ?, updated_at = ?
124+ WHERE username = ? AND in_use = 0
125+ `, mysisID, now, username)
126+ if err != nil {
127+ return fmt.Errorf("claim account: %w", err)
128+ }
129+
130+ n, _ := result.RowsAffected()
131+ if n == 0 {
132+ return fmt.Errorf("account %s is already claimed", username)
133+ }
134+
135+ return nil
136+}
137+
138+// ReleaseAccount marks an account as available.
139+func (s *Store) ReleaseAccount(username string) error {
140+ now := time.Now().UTC()
141+
142+ result, err := s.db.Exec(`
143+ UPDATE accounts
144+ SET in_use = 0, claimed_by = NULL, updated_at = ?
145+ WHERE username = ?
146+ `, now, username)
147+ if err != nil {
148+ return fmt.Errorf("release account: %w", err)
149+ }
150+
151+ n, _ := result.RowsAffected()
152+ if n == 0 {
153+ return sql.ErrNoRows
154+ }
155+
156+ return nil
157+}
158+
159+// ReleaseAccountsByMysis releases all accounts claimed by a mysis.
160+func (s *Store) ReleaseAccountsByMysis(mysisID string) error {
161+ now := time.Now().UTC()
162+
163+ _, err := s.db.Exec(`
164+ UPDATE accounts
165+ SET in_use = 0, claimed_by = NULL, updated_at = ?
166+ WHERE claimed_by = ?
167+ `, now, mysisID)
168+ if err != nil {
169+ return fmt.Errorf("release accounts by mysis: %w", err)
170+ }
171+
172+ return nil
173+}
174+
175+// UpdateAccountLastUsed updates the last_used_at timestamp.
176+func (s *Store) UpdateAccountLastUsed(username string) error {
177+ now := time.Now().UTC()
178+
179+ result, err := s.db.Exec(`
180+ UPDATE accounts
181+ SET last_used_at = ?, updated_at = ?
182+ WHERE username = ?
183+ `, now, now, username)
184+ if err != nil {
185+ return fmt.Errorf("update account last used: %w", err)
186+ }
187+
188+ n, _ := result.RowsAffected()
189+ if n == 0 {
190+ return sql.ErrNoRows
191+ }
192+
193+ return nil
194+}
internal/store/schema.sql+17−1
@@ -4,7 +4,7 @@ CREATE TABLE IF NOT EXISTS schema_version (
44 version INTEGER PRIMARY KEY
55 );
66
7-INSERT OR REPLACE INTO schema_version (version) VALUES (5);
7+INSERT OR REPLACE INTO schema_version (version) VALUES (6);
88
99 CREATE TABLE IF NOT EXISTS myses (
1010 id TEXT PRIMARY KEY,
@@ -31,3 +31,19 @@ CREATE TABLE IF NOT EXISTS memories (
3131 CREATE INDEX IF NOT EXISTS idx_memories_mysis_id ON memories(mysis_id);
3232 CREATE INDEX IF NOT EXISTS idx_memories_created_at ON memories(created_at);
3333 CREATE INDEX IF NOT EXISTS idx_memories_source ON memories(source);
34+
35+CREATE TABLE IF NOT EXISTS accounts (
36+ id INTEGER PRIMARY KEY AUTOINCREMENT,
37+ username TEXT NOT NULL UNIQUE,
38+ password TEXT NOT NULL,
39+ empire TEXT NOT NULL DEFAULT 'solarian',
40+ in_use BOOLEAN NOT NULL DEFAULT 0,
41+ claimed_by TEXT,
42+ last_used_at DATETIME,
43+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
44+ updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
45+ FOREIGN KEY (claimed_by) REFERENCES myses(id) ON DELETE SET NULL
46+);
47+
48+CREATE INDEX IF NOT EXISTS idx_accounts_in_use ON accounts(in_use);
49+CREATE INDEX IF NOT EXISTS idx_accounts_claimed_by ON accounts(claimed_by);
internal/store/store.go+1−1
@@ -15,7 +15,7 @@ import (
1515 //go:embed schema.sql
1616 var schema string
1717
18-const currentSchemaVersion = 5
18+const currentSchemaVersion = 6
1919
2020 // Store provides access to the SQLite database.
2121 type Store struct {
internal/store/store_test.go+74−0
@@ -262,3 +262,77 @@ func TestUpdateNonExistentMysis(t *testing.T) {
262262 t.Error("expected error deleting non-existent mysis")
263263 }
264264 }
265+
266+func TestAccountCRUD(t *testing.T) {
267+ s, cleanup := setupStoreTest(t)
268+ defer cleanup()
269+
270+ mysis, _ := s.CreateMysis("test", "mock", "model", 0.7)
271+
272+ // Create account
273+ acc, err := s.CreateAccount("crab_01", "pass123", "solarian")
274+ if err != nil {
275+ t.Fatalf("CreateAccount() error: %v", err)
276+ }
277+ if acc.InUse {
278+ t.Error("new account should not be in use")
279+ }
280+
281+ // List available
282+ available, _ := s.ListAvailableAccounts()
283+ if len(available) != 1 {
284+ t.Errorf("expected 1 available, got %d", len(available))
285+ }
286+
287+ // Claim
288+ if err := s.ClaimAccount("crab_01", mysis.ID); err != nil {
289+ t.Fatalf("ClaimAccount() error: %v", err)
290+ }
291+
292+ // Verify claimed
293+ fetched, _ := s.GetAccount("crab_01")
294+ if !fetched.InUse || fetched.ClaimedBy != mysis.ID {
295+ t.Error("account should be claimed by mysis")
296+ }
297+
298+ // List available (should be empty)
299+ available, _ = s.ListAvailableAccounts()
300+ if len(available) != 0 {
301+ t.Errorf("expected 0 available, got %d", len(available))
302+ }
303+
304+ // Release
305+ if err := s.ReleaseAccount("crab_01"); err != nil {
306+ t.Fatalf("ReleaseAccount() error: %v", err)
307+ }
308+
309+ // Verify released
310+ fetched, _ = s.GetAccount("crab_01")
311+ if fetched.InUse {
312+ t.Error("account should be released")
313+ }
314+}
315+
316+func TestReleaseAccountsByMysis(t *testing.T) {
317+ s, cleanup := setupStoreTest(t)
318+ defer cleanup()
319+
320+ mysis, _ := s.CreateMysis("test", "mock", "model", 0.7)
321+
322+ s.CreateAccount("acc1", "pass1", "solarian")
323+ s.CreateAccount("acc2", "pass2", "solarian")
324+
325+ s.ClaimAccount("acc1", mysis.ID)
326+ s.ClaimAccount("acc2", mysis.ID)
327+
328+ // Release all
329+ if err := s.ReleaseAccountsByMysis(mysis.ID); err != nil {
330+ t.Fatalf("ReleaseAccountsByMysis() error: %v", err)
331+ }
332+
333+ // Verify both released
334+ available, _ := s.ListAvailableAccounts()
335+ if len(available) != 2 {
336+ t.Errorf("expected 2 available, got %d", len(available))
337+ }
338+}