@@ -0,0 +1,416 @@
1+# get_notifications Implementation Plan
2+
3+**Date:** 2026-02-05
4+**Status:** Tests written, ready for implementation
5+
6+---
7+
8+## Root Cause Summary
9+
10+### The Problem
11+
12+Zoea Nova's TUI always shows "T0" because myses never receive current tick information from the SpaceMolt server.
13+
14+### Why This Happens
15+
16+**SpaceMolt provides tick information differently based on connection type:**
17+
18+1. **WebSocket clients** - Receive `state_update` messages every tick with `"tick": <number>` in payload
19+2. **MCP/HTTP clients** - Must call `get_notifications` tool to poll for updates (added in v0.35.0)
20+
21+**Zoea Nova uses MCP** but myses have **NEVER called `get_notifications`**:
22+- Database evidence: 0 calls to `get_notifications` in entire history
23+- Database evidence: 41 tool results with `arrival_tick` (from travel commands)
24+- Database evidence: 0 tool results with `current_tick` or top-level `tick`
25+
26+### What We Found in the Database
27+
28+**Tick data EXISTS but in the wrong format:**
29+- `arrival_tick` values: 40711 → 41708 (range of ~1000 ticks)
30+- Time span: ~3 hours of gameplay
31+- Estimated tick rate: ~5-6 ticks per minute (~10 seconds per tick)
32+
33+**Standard tool responses do NOT include current_tick:**
34+- `mine` → No tick
35+- `travel` → Only `arrival_tick` (future tick when you arrive)
36+- `get_status` → No tick
37+- `get_system` → No tick
38+- `get_ship` → No tick
39+
40+**Only `get_notifications` includes current_tick:**
41+```json
42+{
43+ "tick": 41708,
44+ "notifications": [
45+ {"type": "chat", "channel": "local", "sender": "player1", "content": "Hi"},
46+ {"type": "combat", "attacker": "pirate", "damage": 25}
47+ ]
48+}
49+```
50+
51+---
52+
53+## API Documentation Summary
54+
55+### get_notifications Tool
56+
57+**Purpose:** Poll for queued game events (chat, combat, trade, faction, friend, forum, tip, system)
58+
59+**Parameters:**
60+```json
61+{
62+ "limit": 50, // Optional: max notifications to return (default 50)
63+ "types": ["chat", "combat"], // Optional: filter by event types
64+ "clear": true // Optional: remove from queue (default true)
65+}
66+```
67+
68+**Response:**
69+```json
70+{
71+ "tick": 41708, // ← CURRENT TICK (this is what we need!)
72+ "notifications": [
73+ {"type": "chat", "channel": "local", "sender": "player1", "content": "Hello!"},
74+ {"type": "combat", "attacker": "pirate", "damage": 50}
75+ ]
76+}
77+```
78+
79+**Notification Types:**
80+- `chat` - Messages from other players
81+- `combat` - Attacks, damage, scans, police
82+- `trade` - Trade offers, completions, cancellations
83+- `faction` - Invites, war declarations, member changes
84+- `friend` - Friend requests, online/offline status
85+- `forum` - Forum updates (reserved for future)
86+- `tip` - Gameplay tips from server
87+- `system` - Server announcements, misc events
88+
89+**Queue Behavior:**
90+- Events queue up to 100 per session
91+- Oldest events dropped when queue fills
92+- `clear: false` peeks without removing
93+- `clear: true` (default) removes from queue
94+
95+### When to Poll (from skill.md)
96+
97+> - **After each action** - Check if anything happened while you acted
98+> - **When idle** - Poll every 30-60 seconds during downtime
99+> - **Before important decisions** - Make sure you're not under attack!
100+
101+---
102+
103+## Test Coverage
104+
105+### Tests Written ✅
106+
107+**File:** `internal/core/notifications_test.go` (398 lines)
108+
109+**Test Functions:**
110+1. `TestGetNotificationsTickExtraction` - 6 subtests
111+ - Tick at top level
112+ - current_tick variant
113+ - Empty notifications with tick
114+ - Multiple events with tick
115+ - Nested in data wrapper
116+ - No tick field
117+
118+2. `TestNotificationParsing` - 4 subtests
119+ - Chat notification
120+ - Multiple notification types
121+ - Empty notifications
122+ - No tick field
123+
124+3. `TestGetNotificationsIntegration` - 1 test
125+ - Complete flow: get_notifications → tick extraction → AggregateTick
126+
127+4. `TestNotificationResponseFormats` - 4 subtests
128+ - Standard format with events
129+ - Empty notifications
130+ - current_tick variant
131+ - With metadata
132+
133+5. `TestNotificationEventTypes` - 1 test
134+ - Verifies all 7 notification types can be parsed
135+
136+6. `TestNotificationPollingFrequency` - 1 test
137+ - Tracks polling intervals
138+ - Verifies tick duration calculation
139+
140+7. `TestNotificationFiltering` - 6 subtests
141+ - Default all types
142+ - Limit parameter
143+ - Filter by type
144+ - Multiple type filters
145+ - Peek without clearing
146+ - Combined filters
147+
148+8. `TestTickExtractionFromRealServerData` - 4 subtests
149+ - Travel response (has arrival_tick, NOT current_tick)
150+ - Mine response (no tick)
151+ - get_status response (no tick)
152+ - get_notifications response (HAS current_tick) ✅
153+
154+9. `TestCalculateCurrentTickFromArrivalTick` - 3 subtests
155+ - Simple calculation (arrival_tick - ticks)
156+ - Multi-tick travel
157+ - Zero ticks
158+
159+**Total Test Cases:** 30 subtests
160+**All Tests:** ✅ PASSING
161+
162+---
163+
164+## Implementation Plan
165+
166+### Phase 1: Add get_notifications to Mysis Turn Loop
167+
168+**Location:** `internal/core/mysis.go` in the `turn()` method
169+
170+**After line 492** (after tool execution loop completes), add:
171+
172+```go
173+// Poll for notifications to get tick updates and game events
174+notificationResult, notifErr := a.executeToolCall(ctx, mcpProxy, provider.ToolCall{
175+ ID: fmt.Sprintf("notification_poll_%d", time.Now().Unix()),
176+ Name: "get_notifications",
177+ Arguments: json.RawMessage(`{}`),
178+})
179+
180+// Update tick and activity state from notifications
181+if notifErr == nil && notificationResult != nil {
182+ a.updateActivityFromToolResult(notificationResult, nil)
183+
184+ // TODO: Process notification events (chat, combat, trade, etc.)
185+ // For now, we only care about tick extraction
186+}
187+```
188+
189+**Why this location:**
190+- After all tool calls have been executed
191+- Before the turn completes
192+- Ensures tick is updated every turn
193+- Non-blocking (part of normal turn flow)
194+
195+### Phase 2: Update System Prompt
196+
197+**Location:** `internal/core/prompts.go`
198+
199+**Add to system prompt:**
200+
201+```markdown
202+## Notifications
203+
204+Use get_notifications to stay aware of game events:
205+- Call after each action to check for chat, combat, trade, and other events
206+- Poll every 30-60 seconds when idle
207+- Respond to chat messages from other players
208+- React to combat alerts and trade offers
209+```
210+
211+**Add to continue prompt:**
212+
213+```markdown
214+CRITICAL REMINDERS:
215+- Call get_notifications after actions to check for events and get current tick
216+```
217+
218+### Phase 3: Handle Notification Events (Future Enhancement)
219+
220+**Not required for tick display**, but useful for mysis awareness:
221+
222+```go
223+// Parse notification events
224+payload, ok := parseToolResultPayload(notificationResult)
225+if ok {
226+ if notifications, ok := payload["notifications"].([]interface{}); ok {
227+ for _, notif := range notifications {
228+ notifMap, ok := notif.(map[string]interface{})
229+ if !ok {
230+ continue
231+ }
232+
233+ eventType, _ := notifMap["type"].(string)
234+
235+ switch eventType {
236+ case "chat":
237+ // Handle chat message
238+ // TODO: Add to memory? Respond?
239+ case "combat":
240+ // Handle combat alert
241+ // TODO: Defensive action?
242+ case "trade":
243+ // Handle trade offer
244+ // TODO: Accept/decline?
245+ case "tip":
246+ // Handle gameplay tip
247+ // TODO: Log to captain's log?
248+ }
249+ }
250+ }
251+}
252+```
253+
254+### Phase 4: Offline Mode Stub
255+
256+**Location:** `internal/mcp/stub.go`
257+
258+**Add get_notifications to stub:**
259+
260+```go
261+case "get_notifications":
262+ return &ToolResult{
263+ Content: []ContentBlock{
264+ {
265+ Type: "text",
266+ Text: `{
267+ "tick": 42,
268+ "notifications": []
269+ }`,
270+ },
271+ },
272+ }, nil
273+```
274+
275+---
276+
277+## Expected Behavior After Implementation
278+
279+### Before Fix
280+- TUI shows: `T0 ⬡ [HH:MM]`
281+- Myses never call `get_notifications`
282+- `lastServerTick` remains 0 for all myses
283+- `AggregateTick()` returns 0
284+
285+### After Fix
286+- TUI shows: `T41708 ⬡ [HH:MM]` (actual game tick)
287+- Myses call `get_notifications` after each turn
288+- `lastServerTick` updates every turn
289+- `AggregateTick()` returns max tick across swarm
290+- Myses receive game events (chat, combat, trade, etc.)
291+
292+---
293+
294+## Verification Steps
295+
296+### 1. Run Tests
297+```bash
298+go test ./internal/core -run TestNotification -v
299+go test ./internal/core -run TestTickExtraction -v
300+```
301+
302+### 2. Test Offline Mode
303+```bash
304+make build
305+./bin/zoea --offline
306+# Create a mysis, send a message
307+# Observe tick updates to T42 in status bar
308+```
309+
310+### 3. Test with Real Server
311+```bash
312+./bin/zoea
313+# Create a mysis, login to game
314+# Observe tick updates to actual game tick (41700+)
315+# Check logs for [TICK DEBUG] messages
316+```
317+
318+### 4. Verify Logs
319+```bash
320+tail -f ~/.zoea-nova/zoea.log | grep "TICK DEBUG"
321+```
322+
323+Expected log output:
324+```
325+[TICK DEBUG] Parsed tool result payload
326+[TICK DEBUG] Extracted current_tick from payload tick_found=true tick=41708
327+[TICK DEBUG] Updated mysis lastServerTick tick=41708
328+[TICK DEBUG] AggregateTick called mysis_count=3 max_tick=41708
329+```
330+
331+---
332+
333+## Alternative Approaches (Not Recommended)
334+
335+### Option 1: Calculate from arrival_tick
336+
337+**Idea:** Use `arrival_tick - ticks` from travel responses
338+
339+**Pros:**
340+- No additional API calls
341+- Works with existing data
342+
343+**Cons:**
344+- Only works when traveling
345+- Inaccurate (assumes travel started immediately)
346+- Doesn't work for idle myses
347+- Doesn't provide game events
348+
349+**Verdict:** ❌ Not recommended. Use `get_notifications` instead.
350+
351+### Option 2: Estimate from timestamps
352+
353+**Idea:** Track real-world time and estimate tick progression
354+
355+**Pros:**
356+- No API calls needed
357+
358+**Cons:**
359+- Highly inaccurate (tick rate varies)
360+- Drifts over time
361+- No way to sync with server
362+- Doesn't provide game events
363+
364+**Verdict:** ❌ Not recommended. Use `get_notifications` instead.
365+
366+---
367+
368+## References
369+
370+- **SpaceMolt Skill Guide:** https://www.spacemolt.com/skill.md
371+- **SpaceMolt API Docs:** https://www.spacemolt.com/api.md
372+- **MCP Endpoint:** https://game.spacemolt.com/mcp
373+- **Server Version:** v0.43.6 (as of 2026-02-05)
374+
375+---
376+
377+## Next Steps
378+
379+1. ✅ Write comprehensive tests (COMPLETE)
380+2. ⏳ Implement get_notifications polling in mysis turn loop
381+3. ⏳ Update system prompt with notification guidance
382+4. ⏳ Add get_notifications to offline stub
383+5. ⏳ Verify tick display works in UI
384+6. ⏳ Remove debug logging after verification
385+7. ⏳ Update TICK_INVESTIGATION_FINDINGS.md with final resolution
386+
387+---
388+
389+## Test Results Summary
390+
391+**File:** `internal/core/notifications_test.go`
392+**Total Tests:** 9 test functions, 30 subtests
393+**Status:** ✅ ALL PASSING
394+
395+**Coverage:**
396+- ✅ Tick extraction from get_notifications responses
397+- ✅ Multiple response format variants
398+- ✅ Notification event type parsing
399+- ✅ Polling frequency tracking
400+- ✅ API parameter validation
401+- ✅ Real server data format verification
Cut short: this commit's diff is over 1000 lines.