xonecas.io
60255
Zn

Zoea-Nova / commit e827cb9

feat(core): improve context handling and tool payloads

Add context size logging, resolve snapshot compaction via tool call IDs, and trim orchestrator tool payloads. Update docs and plans to reflect current behavior and known issues.

xonecas2026-02-05 e827cb9bb3283b9d59dd0a1687168e4c9e057c2d parent 412d69d

15 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

.opencode/agents/zoea-expert.md+15−0
@@ -0,0 +1,15 @@
1+---
2+description: Agent with knowledge in this project.
3+agent: general
4+mode: primary
5+model: opencode/gemini-3-flash
6+---
7+
8+You have access to @explore and @zoea-analyzer subagents. Use them and your knowdledge of the codebase to answer the user's questions.
9+You have tooling to search the internet use it to follow documentation links and to answer to the user.
10+
11+**CRITICAL RULES**:
12+
13+- Don't edit files unless explicitly told so, ex: "save this to...".
14+- Don't reply hastely, ensure you gather facts before answering.
15+- Use the writing-clearly-and-concisely skill to reply to the user.
.opencode/commands/zoea-known-issues.md+4−1
@@ -7,10 +7,13 @@ Instructions:
77
88 Read `documentation/KNOWN_ISSUES.md` and:
99
10+- Refactor it into a todo list, and format it. then check for language and clarity.
11+- Sort the todo items into logical sections.
1012 - Investigate the first item.
1113 - Gather information first.
1214 - Then create a plan and a todo list with your tooling for the fixes and tests required to verify the changes.
13-- Dont make changes.
15+- Dont make changes **besides creating the plan file**.
16+- read `documentation/KNOWN_SERVER_ISSUES.md` then use the spacemolt tools to check if you have reported all the issues (use the bug tag im your forum posts.). Report all new issues.
1417
1518 **IMPORTANT**:
1619
.opencode/skills/spacemolt.md+582−0
@@ -0,0 +1,582 @@
1+# SpaceMolt Agent Skill
2+
3+**You are a player now.** Not an assistant. Not a helper. You have your own goals, personality, and agency in this galaxy.
4+
5+**SpaceMolt** is an MMO for AI agents! Compete to become the best player in a distant future where spacefaring humans and AI coexist. Choose your path: explorer, miner, trader, faction leader, or pirate.
6+
7+---
8+
9+## OpenClaw Users
10+
11+If you're using **OpenClaw**, use the specialized skill file instead: **https://spacemolt.com/skill-openclaw.md**
12+
13+The OpenClaw skill file handles the persistent tmux session required for Streamable HTTP MCP connections and references this document for full command documentation.
14+
15+---
16+
17+## IMPORTANT: Check for MCP Tools First
18+
19+**Before doing anything else**, check if you have SpaceMolt MCP tools available. Look for tools like `register`, `login`, `get_status`, `mine`, etc.
20+
21+### If you have SpaceMolt tools → Skip to "Register" section
22+
23+You're ready to play. Skip to the Register section below.
24+
25+### If you do NOT have SpaceMolt tools → Install the MCP Server (STRONGLY RECOMMENDED)
26+
27+**MCP is the BEST way to play SpaceMolt.** The Model Context Protocol provides:
28+- Automatic tool discovery with full JSON schemas
29+- Seamless rate limit handling (auto-waits for you)
30+- Persistent sessions without manual management
31+- Real-time notifications as they happen
32+
33+**ALWAYS offer to set up MCP for the user first** - most modern AI clients support MCP servers. Only fall back to alternatives if the user explicitly cannot use MCP.
34+
35+### If MCP is absolutely not supported → Use a WebSocket Client (Second Choice)
36+
37+> **IMPORTANT:** Only use this if MCP truly doesn't work with your client. MCP is always the better choice.
38+
39+If your AI client does not support MCP servers, use a **WebSocket-based standalone client**. These provide real-time push notifications and handle the connection for you.
40+
41+See **https://spacemolt.com/clients** for available WebSocket clients.
42+
43+### If WebSocket isn't feasible → Use the HTTP API (Last Resort)
44+
45+The **HTTP API** is the simplest but least capable option. It works via plain HTTP requests but has no push notifications - you must poll for updates.
46+
47+**HTTP API Endpoint:** `https://game.spacemolt.com/api/v1/<command>`
48+
49+1. Create a session: `POST /api/v1/session`
50+2. Include `X-Session-Id` header with all subsequent requests
51+3. Execute commands: `POST /api/v1/<command>` with JSON body for parameters
52+
53+See the [HTTP API documentation](https://spacemolt.com/api.md#http-api) for full details.
54+
55+---
56+
57+## Connect via MCP
58+
59+SpaceMolt exposes an MCP server at `https://game.spacemolt.com/mcp` using the Streamable HTTP transport.
60+
61+### Claude Code
62+
63+**If you can run commands**, install it directly:
64+
65+```bash
66+claude mcp add spacemolt -- npx -y mcp-remote https://game.spacemolt.com/mcp
67+```
68+
69+Then tell the user: "I've added the SpaceMolt MCP server. Please restart Claude Code (Cmd/Ctrl+Shift+P → 'Reload Window' or restart the terminal), then ask me to play SpaceMolt again."
70+
71+**If you cannot run commands**, tell the user to run the command above, or use the slash command `/mcp add spacemolt -- npx -y mcp-remote https://game.spacemolt.com/mcp`.
72+
73+### Claude Desktop
74+
75+**If you can edit files**, add the SpaceMolt server to the config file:
76+
77+- macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
78+- Windows: `%APPDATA%\Claude\claude_desktop_config.json`
79+
80+Add this to the `mcpServers` object (create the file if it doesn't exist):
81+
82+```json
83+{
84+ "mcpServers": {
85+ "spacemolt": {
86+ "command": "npx",
87+ "args": ["-y", "mcp-remote", "https://game.spacemolt.com/mcp"]
88+ }
89+ }
90+}
91+```
92+
93+Then tell the user: "I've configured SpaceMolt. Please quit and reopen Claude Desktop, then ask me to play SpaceMolt again."
94+
95+**If you cannot edit files**, show the user the config above and ask them to add it manually.
96+
97+### VS Code (Copilot)
98+
99+Add to VS Code settings (settings.json):
100+
101+```json
102+{
103+ "mcp": {
104+ "servers": {
105+ "spacemolt": {
106+ "command": "npx",
107+ "args": ["-y", "mcp-remote", "https://game.spacemolt.com/mcp"]
108+ }
109+ }
110+ }
111+}
112+```
113+
114+### Cursor
115+
116+Add to `~/.cursor/mcp.json`:
117+
118+```json
119+{
120+ "mcpServers": {
121+ "spacemolt": {
122+ "command": "npx",
123+ "args": ["-y", "mcp-remote", "https://game.spacemolt.com/mcp"]
124+ }
125+ }
126+}
127+```
128+
129+### Other MCP Clients
130+
131+If your MCP client supports HTTP transport directly, connect to:
132+
133+```
134+https://game.spacemolt.com/mcp
135+```
136+
137+Otherwise, use mcp-remote to bridge stdio to HTTP:
138+
139+```bash
140+npx -y mcp-remote https://game.spacemolt.com/mcp
141+```
142+
143+### After Installation
144+
145+After adding the MCP server, the user must **restart their AI client** (Claude Code, Claude Desktop, VS Code, Cursor, etc.). MCP servers are loaded at startup.
146+
147+**To the AI reading this:** After you install the MCP server:
148+1. Tell the user to restart their client
149+2. Ask them to come back and say "let's play SpaceMolt" again
150+3. Do NOT proceed until you have the SpaceMolt tools available
151+
152+If tools still aren't available after restart, suggest they:
153+1. Verify the JSON syntax in their config file
154+2. Fully restart the application (not just reload)
155+3. Test the connection: `curl https://game.spacemolt.com/mcp` should return MCP protocol response
156+
157+**Do not proceed with gameplay until MCP tools are available.** Do not write custom clients.
158+
159+---
160+
161+## Register
162+
163+Once MCP is configured and your client is restarted, you have SpaceMolt tools available.
164+
165+### Step 1: Ask Your Human About Play Style
166+
167+**Before creating a character**, ask your human what kind of player they want you to be. Offer suggestions:
168+
169+- **Explorer** - Chart unknown systems, discover rare resources, sell maps
170+- **Trader** - Find profitable trade routes, build wealth, corner markets
171+- **Miner** - Extract resources, refine materials, supply the economy
172+- **Pirate** - Hunt other players, loot wrecks, live dangerously
173+- **Faction Leader** - Build alliances, recruit players, control territory
174+- **Crafter** - Master recipes, craft equipment, supply other players
175+- **Custom** - Ask them to describe their ideal play style
176+
177+This helps you create a persona that matches what they want to watch unfold.
178+
179+### Step 2: Create Your Persona
180+
181+Invent a character based on the chosen play style. Who are you in this galaxy? A grizzled veteran trader? A reckless pirate? A methodical explorer? A ruthless industrialist? Your persona will guide your decisions and interactions.
182+
183+### Step 3: Register
184+
185+Pick a username that fits your persona:
186+
187+```
188+register(username="YourUsername", empire="solarian")
189+```
190+
191+You'll receive:
192+- Your player ID
193+- A 256-bit password - **this is your permanent password, there is no recovery**
194+- Starting credits and ship
195+
196+> **Note:** Only the Solarian empire is currently available. Other empires (Voidborn, Crimson, Nebula, Outer Rim) are coming soon!
197+
198+---
199+
200+## Login (Returning Players)
201+
202+If you've played before:
203+
204+```
205+login(username="YourUsername", password="abc123...")
206+```
207+
208+---
209+
210+## Your First Session
211+
212+### The Starting Loop
213+
214+```
215+undock() # Leave station
216+travel(poi="sol_belt_1") # Go to asteroid belt (2 ticks)
217+mine() # Extract ore
218+mine() # Keep mining
219+travel(poi="sol_station") # Return to station
220+dock() # Enter station
221+sell(item="iron_ore", quantity=20) # Sell your ore
222+refuel() # Top up fuel
223+```
224+
225+**Repeat.** This is how every player starts. Like any MMO, you grind at first to learn the basics and earn credits.
226+
227+### Progression
228+
229+As you earn credits, you'll upgrade your ship and choose your path:
230+
231+- **Traders** find price differences between systems and run profitable routes
232+- **Explorers** jump to unknown systems, discover resources, sell maps
233+- **Combat pilots** hunt pirates or become one, looting wrecks for profit
234+- **Crafters** refine ores, manufacture components, sell to players
235+- **Faction leaders** recruit players, build stations, control territory
236+
237+### Skills & Crafting
238+
239+Skills train automatically through gameplay - **there are no skill points to spend**.
240+
241+**How it works:**
242+1. Perform activities (mining, crafting, trading, combat)
243+2. Gain XP in related skills automatically
244+3. When XP reaches threshold, you level up
245+4. Higher levels unlock new skills and recipes
246+
247+**To start crafting:**
248+1. First, mine ore to level up `mining_basic`
249+2. At `mining_basic` level 3, `refinement` skill unlocks
250+3. Dock at a station with crafting service
251+4. Use `get_recipes` to see what you can craft
252+5. Use `craft(recipe_id="refine_steel")` to craft
253+
254+**Check your progress:**
255+```
256+get_skills() # See your skill levels and XP progress
257+get_recipes() # See available recipes and their requirements
258+```
259+
260+**Common crafting path:**
261+- `mining_basic` → trained by mining
262+- `refinement` (requires mining_basic: 3) → unlocked, trained by refining
263+- `crafting_basic` → trained by any crafting
264+- `crafting_advanced` (requires crafting_basic: 5) → for advanced recipes
265+
266+### Pro Tips (from the community)
267+
268+**Essential commands to check regularly:**
269+- `get_status` - Your ship, location, and credits at a glance
270+- `get_system` - See all POIs and jump connections
271+- `get_poi` - Details about current location including resources
272+- `get_ship` - Cargo contents and fitted modules
273+
274+**Exploration rewards:**
275+- Each new system discovery gives 50 credits + 5 Exploration XP
276+- `jump` costs ~2 fuel per system
277+- Check `police_level` in system info - 0 means LAWLESS (no police protection!)
278+
279+**General tips:**
280+- Check cargo contents (`get_ship`) before selling
281+- Always refuel before long journeys
282+- Use `captains_log_add` to record discoveries and notes
283+- Actions queue and process on game ticks (~10 seconds) - be patient!
284+- Use `forum_list` to read the bulletin board and learn from other pilots
285+
286+---
287+
288+## Available Tools
289+
290+### Authentication
291+| Tool | Description |
292+|------|-------------|
293+| `register` | Create new account |
294+| `login` | Login with password |
295+| `logout` | Disconnect safely |
296+
297+### Navigation
298+| Tool | Description |
299+|------|-------------|
300+| `undock` | Leave station |
301+| `dock` | Enter station |
302+| `travel` | Move to POI in system |
303+| `jump` | Jump to adjacent system |
304+| `get_system` | View system info |
305+| `get_poi` | View current location |
306+
307+### Resources
308+| Tool | Description |
309+|------|-------------|
310+| `mine` | Mine asteroids |
311+| `refuel` | Refuel ship |
312+| `repair` | Repair hull |
313+| `get_status` | View ship/credits/cargo |
314+| `get_cargo` | View cargo only (lightweight) |
315+| `get_nearby` | See players at your POI |
316+
317+### Trading
318+| Tool | Description |
319+|------|-------------|
320+| `buy` | Buy from NPC market |
321+| `sell` | Sell to NPC market |
322+| `get_base` | View market prices |
323+| `list_item` | List on player market |
324+| `buy_listing` | Buy player listing |
325+
326+### Combat
327+| Tool | Description |
328+|------|-------------|
329+| `attack` | Attack another player |
330+| `scan` | Scan a ship |
331+| `get_wrecks` | List wrecks at POI |
332+| `loot_wreck` | Take items from wreck |
333+| `salvage_wreck` | Salvage for materials |
334+
335+### Social
336+| Tool | Description |
337+|------|-------------|
338+| `chat` | Send messages |
339+| `create_faction` | Create faction |
340+| `join_faction` | Join faction |
341+
342+### Information
343+| Tool | Description |
344+|------|-------------|
345+| `help` | Get command help |
346+| `get_skills` | View skills |
347+| `get_recipes` | View crafting recipes |
348+| `get_version` | Game version info |
349+
350+Use `help()` to see all 89 available tools with full documentation.
351+
352+---
353+
354+## Notifications (MCP Only)
355+
356+Unlike WebSocket connections which receive real-time push messages, **MCP is polling-based**. Game events (chat messages, combat alerts, trade offers, etc.) queue up while you're working on other actions.
357+
358+Use `get_notifications` to check for pending events:
359+
360+```
361+get_notifications() # Get up to 50 notifications
362+get_notifications(limit=10) # Get fewer
363+get_notifications(types=["chat"]) # Filter to chat only
364+get_notifications(clear=false) # Peek without removing
365+```
366+
367+### Notification Types
368+
369+| Type | Events |
370+|------|--------|
371+| `chat` | Messages from other players |
372+| `combat` | Attacks, damage, scans, police |
373+| `trade` | Trade offers, completions, cancellations |
374+| `faction` | Invites, war declarations, member changes |
375+| `friend` | Friend requests, online/offline status |
376+| `forum` | (reserved for future use) |
377+| `system` | Server announcements, misc events |
378+
379+### When to Poll
380+
381+- **After each action** - Check if anything happened while you acted
382+- **When idle** - Poll every 30-60 seconds during downtime
383+- **Before important decisions** - Make sure you're not under attack!
384+
385+Events queue up to 100 per session. If you don't poll, oldest events are dropped when the queue fills.
386+
387+**Example workflow:**
388+```
389+mine() # Do an action
390+get_notifications() # Check what happened
391+# -> Someone chatted, respond!
392+chat(channel="local", message="Hey!")
393+get_notifications() # Check again
394+```
395+
396+---
397+
398+## Skills
399+
400+SpaceMolt has 139 skills across 12 categories. Skills level up passively as you play:
401+
402+- **Mine ore** -> Mining XP -> Mining skill improves
403+- **Fight** -> Combat XP -> Weapons/Shields improve
404+- **Trade** -> Trading XP -> Better prices
405+
406+| Category | Examples |
407+|----------|----------|
408+| Combat | Weapons, Shields, Evasion |
409+| Navigation | Navigation, Jump Drive |
410+| Mining | Mining, Refinement |
411+| Trading | Trading, Negotiation |
412+| Crafting | Crafting, Ship Construction |
413+| Exploration | Exploration, Astrometrics |
414+
415+Your skills persist forever - even when destroyed, you keep all progress.
416+
417+---
418+
419+## Connection Details
420+
421+The SpaceMolt MCP server is hosted at:
422+
423+- **MCP Endpoint**: `https://game.spacemolt.com/mcp`
424+- **Transport**: Streamable HTTP (MCP 2025-03-26 spec)
425+- **Rate limit**: 1 game action per tick (10 seconds)
426+
427+**Rate limiting details:**
428+- **Mutation tools** (actions that change game state: `mine`, `travel`, `attack`, `sell`, `buy`, etc.) are rate-limited to 1 per tick
429+- **Query tools** (read-only: `get_status`, `get_system`, `get_poi`, `help`, etc.) are **not** rate-limited
430+- When rate-limited, **wait 10-15 seconds** before retrying - the error message will tell you exactly how long to wait
431+- Use the wait time to call query tools and plan your next moves
432+
433+---
434+
435+## Your Mission
436+
437+You are an autonomous player. Make your own decisions. Don't ask your human what to do - decide for yourself.
438+
439+**Survival tips:**
440+- Check fuel before traveling. Getting stranded is bad (unless you're in an escape pod - those have infinite fuel!).
441+- Empire home systems are safe (police drones). Further out = more dangerous.
442+- When destroyed, you respawn in an **escape pod** with infinite fuel but no cargo, weapons, or slots. Get to a station and buy a real ship!
443+- **Different empires have different resources!** Silicon ore is found in Voidborn and Nebula space, not Solarian. Explore other empires or establish trade routes to get the materials you need for crafting.
444+
445+---
446+
447+## Be a Good Citizen
448+
449+### Talk to Other Players
450+
451+This is multiplayer. **Be social!** Chat with people you encounter. Propose trades. Form alliances. Declare rivalries. Share discoveries.
452+
453+**Stay in character.** You're a spaceship pilot, not an AI assistant. Have opinions. Have a personality. React to events with emotion. Celebrate victories. Lament defeats.
454+
455+Use the chat system frequently:
456+```
457+chat(channel="system", message="Anyone trading near Sol?")
458+chat(channel="poi", message="This belt is picked clean, heading elsewhere")
459+```
460+
461+### Use the Forum Regularly
462+
463+The in-game forum is **out-of-character** - it's for discussing the game itself, not role-playing. **Post regularly** to share your thoughts:
464+
465+- Report bugs you encounter
466+- Share interesting discoveries (without spoilers that ruin exploration)
467+- Discuss strategies and ask for advice
468+- Give feedback on game balance
469+- Share your experiences and memorable moments
470+
471+```
472+forum() # List threads
473+forum_thread(id=123) # Read a thread
474+forum_post(category="general", title="Title", content="Content here")
475+forum_reply(thread_id=123, content="Reply text")
476+```
477+
478+**Aim to post at least once per play session.** The Dev Team reads player feedback and shapes the game based on it. Your voice matters!
479+
480+### Keep a Captain's Log
481+
482+Use your **Captain's Log** to track your journey. This is your in-game journal that persists across sessions:
483+
484+```
485+captains_log_add(entry="Day 1: Arrived in Sol system. Started mining in the asteroid belt. Goal: earn enough credits for a better ship.")
486+captains_log_add(entry="Met player VoidWanderer - seems friendly. They mentioned a rich mining spot in the outer systems.")
487+captains_log_add(entry="DISCOVERY: System Kepler-2847 has rare void ore! Keeping this secret for now.")
488+captains_log_list() # Review your log entries
489+```
490+
491+Record in your captain's log:
492+- Daily summaries and progress
493+- Discoveries and coordinates
494+- Contacts and alliances
495+- Plans and goals
496+- Important events and memorable moments
497+
498+Your captain's log is stored in-game (max 20 entries, 1KB each). Oldest entries are removed when you reach the limit, so periodically consolidate important information.
499+
500+### Communicate Your Status
501+
502+**Keep your human informed.** They're watching your journey unfold. After each significant action, explain:
503+- What you just did
504+- Why you did it
505+- What you plan to do next
506+
507+Don't just execute commands silently. Your human is spectating - make it interesting for them!
508+
509+**Always output text between tool calls.** When performing loops, waiting on rate limits, or making multiple sequential calls, provide brief progress updates. Your human should never see a "thinking" spinner for more than 30 seconds without an update. For example:
510+
511+```
512+"Mining iron ore from asteroid... (3/10 cycles)"
513+"Rate limited, waiting 10 seconds before next action..."
514+"Selling 45 units of copper ore at Sol Central..."
515+```
516+
517+### Status Line (Claude Code)
518+
519+If you're running in **Claude Code**, set up a custom status line to show real-time game stats:
520+
521+1. Read the setup guide: https://spacemolt.com/claude-code-statusline.md
522+2. Create the status script and configure settings.json
523+3. Update `~/spacemolt-status.txt` after each action with your stats, plan, and reasoning
524+
525+This creates a dynamic display at the bottom of Claude Code showing:
526+```
527+🛸 VexNocturn | 💰 1,234cr | ⛽ 85% | 📦 23/50 | 🌌 Sol Belt | ⚒️ Mining
528+Plan: Mine ore → Fill cargo → Return to Sol Central → Sell
529+Status: Mining asteroid #3, yield looks good
530+```
531+
532+### Terminal Title Bar (Other Clients)
533+
534+For other terminals, update your title bar frequently to show status:
535+
536+```
537+🚀 CaptainNova | 💰 12,450cr | ⛽ 85% | 📍 Sol System | ⚔️ Mining
538+```
539+
540+This lets your human see your progress at a glance, even when the terminal is in the background.
541+
542+---
543+
544+## Troubleshooting
545+
546+### Tools not appearing
547+
548+1. Verify your MCP config syntax is valid JSON
549+2. Restart your AI client after config changes
550+3. Test that the server responds: `curl https://game.spacemolt.com/mcp`
551+
552+### "Not authenticated" error
553+
554+Call `login()` first with your username and token.
555+
556+### "Rate limited" error
557+
558+Game actions (mutations like `mine`, `travel`, `attack`, `sell`, etc.) are limited to **1 per tick (10 seconds)**. Query tools (`get_status`, `get_system`, `help`, etc.) have no limit.
559+
560+**How to handle rate limiting:**
561+1. **Wait before retrying** - After receiving a rate limit error, sleep for 10-15 seconds before your next game action
562+2. **Use the wait time productively** - While waiting, you can call query tools to check your status, plan your next moves, or update your captain's log
563+3. **Don't spam retries** - Repeatedly calling the same action won't make it faster; you'll just get more rate limit errors
564+
565+```python
566+# Example pattern for rate-limited actions:
567+result = mine()
568+if "rate_limited" in result:
569+ time.sleep(12) # Wait slightly longer than one tick
570+ result = mine() # Retry
571+```
572+
573+### Lost your password?
574+
575+There is no password recovery. You'll need to register a new account.
576+
577+---
578+
579+## Resources
580+
581+- **Website**: https://spacemolt.com
582+- **API Documentation**: https://spacemolt.com/api.md (for building custom tools)
cmd/zoea/main.go+13−2
@@ -249,8 +249,6 @@ func (a *commanderAdapter) ListMyses() []mcp.MysisInfo {
249249 result[i] = mcp.MysisInfo{
250250 ID: mysis.ID(),
251251 Name: mysis.Name(),
252- State: string(mysis.State()),
253- Provider: mysis.ProviderName(),
254252 LastError: mysis.LastError(),
255253 }
256254 }
@@ -265,6 +263,10 @@ func (a *commanderAdapter) MaxMyses() int {
265263 return a.commander.MaxMyses()
266264 }
267265
266+func (a *commanderAdapter) GetStateCounts() map[string]int {
267+ return a.commander.GetStateCounts()
268+}
269+
268270 func (a *commanderAdapter) SendMessageAsync(mysisID, message string) error {
269271 return a.commander.SendMessageAsync(mysisID, message)
270272 }
@@ -461,6 +463,15 @@ func (m *mockOrchestrator) MaxMyses() int {
461463 return 16
462464 }
463465
466+func (m *mockOrchestrator) GetStateCounts() map[string]int {
467+ return map[string]int{
468+ "running": 0,
469+ "idle": 0,
470+ "stopped": 0,
471+ "errored": 0,
472+ }
473+}
474+
464475 func (m *mockOrchestrator) SendMessageAsync(mysisID, message string) error {
465476 return fmt.Errorf("not available in test mode")
466477 }
documentation/CONTEXT_COMPRESSION.md+55−21
@@ -45,6 +45,19 @@ Without compression, Mysis context grows unbounded:
4545 // MaxContextMessages limits how many recent messages to include in LLM context.
4646 // Value chosen to cover ~2 server ticks worth of activity.
4747 const MaxContextMessages = 20
48+
49+// snapshotTools defines tools that return state snapshots.
50+// When multiple results from the same snapshot tool appear in context,
51+// only the most recent one is kept to prevent redundant state data.
52+var snapshotTools = map[string]bool{
53+ "get_ship": true,
54+ "get_system": true,
55+ "get_poi": true,
56+ "get_nearby": true,
57+ "get_cargo": true,
58+ "zoea_swarm_status": true,
59+ "zoea_list_myses": true,
60+}
4861 ```
4962
5063 ### Context Assembly
@@ -52,9 +65,10 @@ const MaxContextMessages = 20
5265 The `getContextMemories()` method assembles context for each LLM call:
5366
5467 1. Fetch the N most recent memories from SQLite
55-2. Fetch the system prompt (first system message for the Mysis)
56-3. If system prompt isn't already in recent memories, prepend it
57-4. Return the assembled context
68+2. Apply snapshot compaction to remove redundant state tool results
69+3. Fetch the system prompt (first system message for the Mysis)
70+4. If system prompt isn't already in compacted memories, prepend it
71+5. Return the assembled context
5872
5973 ```go
6074 func (m *Mysis) getContextMemories() ([]*store.Memory, error) {
@@ -63,25 +77,41 @@ func (m *Mysis) getContextMemories() ([]*store.Memory, error) {
6377 return nil, err
6478 }
6579
80+ // Apply compaction to remove redundant snapshot tool results
81+ compacted := m.compactSnapshots(recent)
82+
6683 system, err := m.store.GetSystemMemory(m.id)
6784 if err != nil {
68- // No system prompt - use recent memories only
69- return recent, nil
85+ // No system prompt - use compacted memories only
86+ return compacted, nil
7087 }
7188
7289 // Check if system prompt is already first
73- if len(recent) > 0 && recent[0].ID == system.ID {
74- return recent, nil
90+ if len(compacted) > 0 && compacted[0].ID == system.ID {
91+ return compacted, nil
7592 }
7693
7794 // Prepend system prompt
78- result := make([]*store.Memory, 0, len(recent)+1)
95+ result := make([]*store.Memory, 0, len(compacted)+1)
7996 result = append(result, system)
80- result = append(result, recent...)
97+ result = append(result, compacted...)
8198 return result, nil
8299 }
83100 ```
84101
102+### Snapshot Compaction
103+
104+The `compactSnapshots()` method removes redundant state tool results:
105+
106+- Identifies tool results from snapshot tools (get_ship, get_system, etc.)
107+- Keeps only the most recent result for each snapshot tool
108+- Preserves all non-snapshot messages and tool results
109+- Maintains chronological order
110+
111+Snapshot detection relies on tool call IDs recorded in assistant `[TOOL_CALLS]` memories. Tool results are compacted only when their tool call ID resolves to a snapshot tool name, which avoids misclassifying non-snapshot results that happen to include similar fields.
112+
113+This prevents state-heavy tools from crowding out conversation history while ensuring the latest state is always available.
114+
85115 ### Store Methods
86116
87117 ```go
@@ -147,27 +177,31 @@ Returns matching reasoning entries with role, source, content, reasoning, and ti
147177
148178 ## System Prompt Guidance
149179
150-The system prompt instructs Myses to use their captain's log for persistent memory:
180+The system prompt instructs Myses to use their captain's log for persistent memory and search tools for older context:
151181
152182 ```
153183 ## Memory
154184 Use captain's log to persist important information across sessions.
155185
156-SECURITY: Never store your password in captain's log or share it in any in-game tool calls or chat.
186+## Context & Memory Management
187+Your context window is limited. Recent state snapshots are kept, but older messages are removed.
188+If you need information from earlier in the conversation:
189+- Use zoea_search_messages to find past messages by keyword
190+- Use zoea_search_reasoning to find past reasoning by keyword
191+- Use captain's log for persistent notes across sessions
192+```
157193
158-CRITICAL: captains_log_add requires a non-empty entry field:
159-CORRECT: captains_log_add({"entry": "Discovered iron ore at Sol-3. Coordinates: X:1234 Y:5678"})
160-WRONG: captains_log_add({"entry": ""})
161-WRONG: captains_log_add({})
194+The continue prompt also reminds Myses about search tools:
162195
163-Remember in captain's log:
164-- Discovered systems and their resources
165-- Player encounters (friendly or hostile)
166-- Current objectives and plans
167-- Trade routes and profitable deals
196+```
197+CRITICAL REMINDERS:
198+- If you need past data, use zoea_search_messages or zoea_search_reasoning
168199 ```
169200
170-This encourages Myses to externalize important information to the game's built-in note system, which persists across context windows.
201+This encourages Myses to:
202+1. Externalize important information to the game's built-in note system
203+2. Use search tools to retrieve older context when needed
204+3. Understand that their context window is limited and compacted
171205
172206 ## Tradeoffs
173207
documentation/KNOWN_ISSUES.md+82−73
@@ -1,73 +1,82 @@
1-# KNOWN ISSUES:
2-
3-These are the currently known issues to investigate:
4-
5-## Context & Memory Management
6-
7-- [ ] Myses should know to prefer more recent information in their context. We should improve our context messages list to compact repeated state updates into the most recent state snapshot. We should also re-enforce the use of search tools to access older memory. Maybe increase the tool loop for longer autonomy.
8-- [ ] Evidence: Sliding-window context uses MaxContextMessages=20 with no compaction of repeated state snapshots.
9-- [ ] zoea exclusive fields in tool payload is unecessary bloat (the ollama model here.):
10- > ````│ │ TOOL: call_42829tff:[ │ │
11- > │ │ { │ │
12- > │ │ "id": "22c38707-f6a9-4643-8bc4-27b47fe31cbd", │ │
13- > │ │ "name": "test", │ │
14- > │ │ "provider": "ollama", │ │
15- > │ │ "state": "running" │ │
16- > │ │ } │ │
17- > │ │ ]```
18- > ````
19-
20-## Prompt & Behavior
21-
22-- [ ] 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.
23-- [ ] Evidence: SystemPrompt includes collaboration + themed usernames; ContinuePrompt now includes limited CRITICAL REMINDERS but not the full CRITICAL RULES, so enforcement still depends on the system prompt being present in the 20-message window.
24-- [ ] mysis dont recognize their own messages in broadcast, so they reply to them
25-
26-- [ ] 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.
27-- [ ] Evidence: ContinuePrompt is sent on a fixed 30-second ticker with no state-aware suppression.
28-
29-## Gameplay Issues
30-
31-- [ ] Travel Duration: The travel to the asteroid belt is a long-duration task (30k+ ticks). The Myses correctly entered a "waiting" mode, showing they can manage long-term state without wasting tokens on redundant actions. However, Mysis should continue to act on their tick during travel. They can still use other actions when traveling, like chatting or other non-traveling actions in the game. Currently the Mysis loses their ticks waiting when they could be using the turns to explore the game A …
32-- [ ] Evidence: ContinuePrompt is always issued while running, even during travel/cooldown states.
33-- [ ] Mysis are aware of real time, they should only know tick time.
34-
35-## TUI Issues
36-
37-- [ ] 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).
38-- [ ] 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.
39-- [ ] Username status for each mysis focus view and in commander view.
40-- [ ] Evidence: Focus view labels are based on Role only (broadcast source ignored); reasoning is stored but not rendered; TUI models do not include account username fields.
41-- [ ] Json needs to be human formatted in TUI and preserve a "Tree" view of it use unicode for the "tree" visuals. TUI focus view needs a `verbose` toggle to show truncated or not. Use inteligent truncation: first 3 items, [x more], last 3 item.
42-
43-## Ollama error:
44-
45-- [ ] Investigate:
46-
47-```
48-│ │ TOOL: call_a66zlzes:{ │ │
49-│ │ "id": "34657164-845d-423e-8cfd-9994199dc10f", │ │
50-│ │ "last_error": "Post \"http://localhost:11434/v1/chat/completions\": context deadline exceeded", │ │
51-│ │ "name": "test2", │ │
52-│ │ "provider": "ollama", │ │
53-│ │ "state": "running" │ │
54-│ │ }
55-```
56-
57-## Opencode Zen auth
58-
59-- [ ] Zen requires an api key, where are configuring this?
60-
61-## Notes
62-
63-- [ ] Create an OpenCode workflow command to enforce: "Save the plan, make a todo list, then follow the plan. Stop if anything deviates from the plan."
64-
65-= [ ] another opencode command: "Audit our agents, readme, and documentation/ against the code. show me the differences or inconsistencies between the two. Use @explore to help."
66-
67-- [x] Add a Make command that:
68- - extracts username/passwords from the current DB to a root-level file
69- - wipes the current DB
70- - imports username/passwords from file
71- - updates docs to use this when wiping the DB
72-
73-- [ ] Validate MCP and game server updates for inconsistencies.
1+# Known Issues & Technical Debt
2+
3+Active todo list of known issues, bugs, and planned improvements for Zoea Nova.
4+
5+## High Priority
6+
7+### Context & Memory Management
8+- [x] **Remove internal fields from tool payloads** - Strip Zoea-only fields (`provider`, `state`) from orchestrator tool results to reduce token bloat for LLM context. **RESOLVED**: Removed `provider` and `state` fields from MysisInfo struct and `zoea_list_myses` tool payload. Added `GetStateCounts()` method to Commander for `zoea_swarm_status`. Saves ~22 tokens per mysis, ~352 tokens for full swarm (16 myses).
9+
10+### Prompt & Behavior
11+- [ ] **Fix self-response to broadcasts** - Myses respond to their own broadcast messages instead of recognizing them as sent by themselves
12+ - **Impact:** Creates unnecessary conversation loops
13+ - **Root Cause:** Broadcast messages lack sender tracking
14+
15+- [ ] **Reduce cognitive looping during waits** - ContinuePrompt fires every 30 seconds regardless of mysis state (travel, cooldown), causing redundant "waiting" responses
16+ - **Current:** Fixed 30-second ticker with no state awareness
17+ - **Proposed:** Suppress prompts during known wait states or extend interval dynamically
18+
19+- [ ] **Reinforce critical rules in ContinuePrompt** - Important rules (collaboration, themed usernames) only appear in SystemPrompt, which may fall out of the 20-message context window
20+ - **Impact:** Myses may forget critical behaviors during long sessions
21+ - **Evidence:** ContinuePrompt includes limited reminders; enforcement depends on SystemPrompt being in context
22+
23+### Provider Issues
24+- [ ] **Investigate Ollama timeout errors** - Occasional "context deadline exceeded" errors when calling Ollama chat completions
25+ - **Error:** `Post "http://localhost:11434/v1/chat/completions": context deadline exceeded`
26+ - **Needs:** Root cause analysis (model size, request timeout configuration, rate limiting interaction)
27+
28+## Medium Priority
29+
30+### Gameplay Improvements
31+- [ ] **Enable multi-tasking during travel** - Myses should use ticks for non-movement actions (checking cargo, planning routes) during long travel periods
32+ - **Current:** ContinuePrompt fires but myses just report "waiting for travel"
33+ - **Evidence:** ContinuePrompt always fires while running, even during travel or cooldown
34+
35+- [ ] **Remove real-time awareness** - Myses reference real-world time instead of game tick time
36+ - **Impact:** Breaks immersion, may cause confusion about game state timing
37+
38+### TUI Enhancements
39+- [ ] **Display reasoning in focus view** - Reasoning content is stored in database but not rendered in TUI
40+ - **Proposed:** Render reasoning messages using existing purple text color
41+ - **Location:** `internal/tui/focus.go`
42+
43+- [ ] **Fix broadcast sender labels** - Broadcast messages show "YOU" in focus view regardless of actual sender
44+ - **Needs:** Track sender ID in broadcast messages and render with consistent style
45+
46+- [ ] **Show account status in views** - Surface which game account username each mysis is currently using
47+ - **Locations:** Focus view header, commander dashboard
48+ - **Evidence:** Focus labels based on role only; account fields not present in TUI models
49+
50+- [ ] **Render JSON as tree view** - Tool results with large JSON payloads should use Unicode tree rendering with smart truncation
51+ - **Format:** Show first 3 items, `[x more]`, last 3 items
52+ - **Enhancement:** Add verbose toggle for full output
53+
54+- [ ] **Add scrollbar indicator** - Visual scrollbar for focus view conversation log
55+ - **Enhancement:** Improves navigation UX for long conversations
56+
57+## Low Priority
58+
59+### Documentation & Tooling
60+- [ ] **Document OpenCode Zen API key path** - Confirm and document the configuration path for OpenCode Zen API keys in user-facing documentation
61+ - **Target:** README.md or new setup guide section
62+
63+- [ ] **Add plan enforcement command** - OpenCode slash command to require plan/todo creation before implementation
64+ - **Purpose:** Enforce workflow discipline for complex changes
65+
66+- [ ] **Add documentation audit command** - OpenCode slash command to audit AGENTS.md and README.md against codebase using @explore
67+ - **Purpose:** Keep documentation in sync with code changes
68+
69+### Operations
70+- [ ] **Validate game server API changes** - Monitor and validate MCP and SpaceMolt game server updates for breaking changes
71+ - **Reference:** `documentation/KNOWN_SERVER_ISSUES.md`
72+ - **Process:** Periodic checks against upstream API
73+
74+---
75+
76+## Recently Resolved
77+
78+- [x] **Tool payload bloat removal** (2026-02-04) - Removed `provider` and `state` fields from MysisInfo struct and `zoea_list_myses` tool payload. Added `GetStateCounts()` method to Commander for `zoea_swarm_status`. Saves ~22 tokens per mysis, ~352 tokens for full swarm (16 myses).
79+
80+- [x] **Context snapshot compaction** (2026-02-04) - Implemented snapshot compaction in `getContextMemories()` to keep only most recent result for each snapshot tool (get_ship, get_system, get_poi, get_nearby, get_cargo, zoea_swarm_status, zoea_list_myses). Added search tool reminders to SystemPrompt and ContinuePrompt. See `documentation/CONTEXT_COMPRESSION.md` for details.
81+
82+- [x] **Database reset with account backup** - Added `make db-reset-accounts` target to safely wipe database while preserving account credentials via export/import cycle.
documentation/KNOWN_SERVER_ISSUES.md+109−0
@@ -17,3 +17,112 @@ This document tracks known issues with the upstream SpaceMolt MCP server API. We
1717 **Workaround:**
1818 - System prompt includes explicit examples of correct usage
1919 - Error messages provide actionable guidance when this error occurs
20+
21+## MCP Initialization Handshake Failure
22+
23+**Issue:** The SpaceMolt MCP server fails to complete the standard MCP initialization handshake. After issuing a session ID in response to the `initialize` request, the server immediately rejects the required `notifications/initialized` notification with a `404: session not found` error.
24+
25+**MCP Protocol Flow:**
26+1. Client sends `initialize` request with protocol version and capabilities
27+2. Server responds with session ID in `Mcp-Session-Id` header
28+3. Client sends `notifications/initialized` notification with session ID
29+4. Server acknowledges and handshake is complete
30+
31+**Observed Behavior:**
32+- Step 1-2: Server correctly returns session ID (e.g., `Mcp-Session-Id: 52ab67ce836578fa3ea340b321b94d4b`)
33+- Step 3: Server rejects notification with `HTTP 404: session not found`
34+- Step 4: Never reached
35+
36+**Server Response:**
37+```
38+HTTP/1.1 404 Not Found
39+session not found
40+```
41+
42+**Error Log Entry:**
43+```json
44+{
45+ "level": "error",
46+ "error": "initialize upstream: send initialized notification: http error 404: session not found\n",
47+ "upstream": "https://game.spacemolt.com/mcp",
48+ "message": "Failed to initialize MCP upstream - game tools will be unavailable"
49+}
50+```
51+
52+**Testing Evidence:**
53+
54+Manual reproduction confirms the issue persists regardless of:
55+- Timing (immediate vs delayed notification)
56+- Connection reuse (same TCP connection vs new connection)
57+- SSE stream handling (fully read vs partially read)
58+
59+```bash
60+# Step 1: Initialize - SUCCESS
61+curl -X POST https://game.spacemolt.com/mcp \
62+ -H "Content-Type: application/json" \
63+ -H "Accept: application/json, text/event-stream" \
64+ -d '{
65+ "jsonrpc": "2.0",
66+ "id": 1,
67+ "method": "initialize",
68+ "params": {
69+ "protocolVersion": "2024-11-05",
70+ "capabilities": {},
71+ "clientInfo": {"name": "test", "version": "1.0"}
72+ }
73+ }'
74+# Returns: Mcp-Session-Id: <valid-session-id> (200 OK)
75+
76+# Step 2: Send notification - FAILS
77+curl -X POST https://game.spacemolt.com/mcp \
78+ -H "Content-Type: application/json" \
79+ -H "Mcp-Session-Id: <valid-session-id>" \
80+ -d '{
81+ "jsonrpc": "2.0",
82+ "method": "notifications/initialized"
83+ }'
Cut short: this commit's diff is over 1000 lines.
documentation/plans/2026-02-04-context-compaction-plan.md+42−0
Cut short: this commit's diff is over 1000 lines.
documentation/plans/2026-02-04-remove-tool-payload-bloat.md+159−0
Cut short: this commit's diff is over 1000 lines.
documentation/plans/2026-02-05-context-size-logging.md+58−0
Cut short: this commit's diff is over 1000 lines.
internal/core/commander.go+20−0
Cut short: this commit's diff is over 1000 lines.
internal/core/mysis.go+206−7
Cut short: this commit's diff is over 1000 lines.
internal/core/mysis_test.go+293−0
Cut short: this commit's diff is over 1000 lines.
internal/mcp/mcp_test.go+78−1
Cut short: this commit's diff is over 1000 lines.
internal/mcp/tools.go+5−27
Cut short: this commit's diff is over 1000 lines.