@@ -1,304 +0,0 @@
1-# Client Refactor Design
2-
3-## Motivation
4-
5-The current implementation has three core issues:
6-
7-1. **Behavior bias** - Prompt and translation layer bias LLM player behavior
8-2. **Translation complexity** - Translation layer creates bug surface and complicates development
9-3. **Tight coupling** - TUI and client logic are not properly decoupled
10-
11-## Goals
12-
13-### Architecture
14-
15-- **Reduce abstraction** - Minimize layers between client and server
16-- **Simplify protocol** - Streamline game update forwarding to LLM player
17-- **Direct server sync** - Use MOTD messages and [Game Server API](https://www.spacemolt.com/api.md) for quick updates
18-- **Workspace structure** - Migrate to [Bun Workspaces](https://bun.com/docs/pm/workspaces)
19-- **Package separation** - Split TUI and Client into separate packages with TUI imported by client
20-- **Shared code across both packages** - Like types, test tools, or other future utilities, should be in a shared package in this workspace.
21-- **Unified tooling** - Bun scripts in repo root (with/without TUI), shared Prettier config
22-
23-### Database
24-
25-- **Simplified schema** - Two tables only:
26- - `account_details`: credentials, username, id, hint, prompt
27- - `messages`: raw JSON server communication, id, tick, client/server sender enum
28-- **Proper indexing** - Optimized for query patterns, tick for sorting by it
29-- **Size management** - Truncate messages table to 5000 rows max sorted by tick when read.
30-- **SQLite with Bun** - Continue using Bun to interact with SQLite
31-- **Instancing** - Use a unique ID for each database instance, this ID is used as argument to bind future runs to a specific instance. use memory-{instance-name}.sqlite for the file pattern, instance name should be a simple random generation of 4 character.
32-
33-### Performance
34-
35-- **Token efficiency** - Reduce tokens sent per tick
36-- **Fast failures** - Quick Ollama timeouts to avoid losing ticks
37-- **Optimized prompting** - Fewer Ollama calls, faster prompt generation per tick
38-
39-### Testing
40-
41-- **Combined approach** - Unit tests + manual visual tests for TUI (print UI components to terminal or screenshot the TUI)
42-- **Coverage target** - 80% test coverage at the end of the refactor in the client code.
43-- **TUI** - test scripts to run manually to create screenshots for visual inspection.
44-
45-## Non-Goals
46-
47-- **No backward compatibility** - New DB schema, fresh start
48-- **No legacy code reuse** - Apply lessons learned to build clean foundation
49-
50-## Client Design
51-
52-### Core Principles
53-
54-- **Direct connection** - Connect to `wss://game.spacemolt.com/ws` without intermediate libraries
55-- **Server sync** - Use [api.md](https://www.spacemolt.com/api.md) to maintain client-server compatibility
56-- **API merging** - Extend game server API while maintaining JSON protocol consistency
57-- **Registration shadowing** - Hook register command to generate player prompt along with registration
58-- **Instances** - Each running client instance has an independent database file. Complete data separation between instances.
59-- **Errors** - When showing errors to the LLM, always use the language found in the api.md document from the server. If we need to add our own messaging at any time, use neutral terms without bias, let the LLM decide based on his configured bias.
60-
61-### Ollama
62-
63-- A ollama server will be available. manually controlled by the user.
64-- A single call per tick, sends full JSON context including prompt.
65-- Used in the registatrion flow
66-- Ollama calls need to fail fast, they should resolve in less than 1 tick so that the player doesn't loose more than 1 turn waiting for generation.
67-- If the ollama call fails add a client error message
68-- Model thinking should be a cli argument of the client and not saved anywhere in it's entirety as it's usually a lot of tokens. Default to thinking on but at the lowest values for quick thinking. (You can assume the model is qwen3:8b as default.)
69-- Model temperature should be a config value as well, with a high creativity temprature (1.2)
70-
71-### Registration flow
72-
73-- When the LLM player calls register it will do so with the same arguments the server api requires.
74-- We will intercept and use those arguments to prompt the LLM for a bias prompt based on Name and empire + a behavuour archtype that fits the MMO RPG genre for a sci fi universe of Crustaceans Cosmos.
75-- Archtypes are suggested gameplay styles defined in code, as constants, it should be a concise excerpt defining a common gamestyle suitable for an Online multiplayer rpg game.
76- - **The Diplomat** (Good): Seeks alliances through negotiation and mutual benefit. Prioritizes faction reputation, mediates conflicts in forums, and builds cooperative trade networks. Values honor and collective prosperity.
77- - **The Opportunist** (Neutral): Adapts strategy based on maximum personal gain. Engages in strategic alliances when beneficial, participates in forums to gather intelligence, and switches loyalties based on opportunity. Values pragmatism and survival.
78- - **The Agitator** (Evil): Thrives on chaos and manipulation. Spreads misinformation in forums, provokes faction conflicts, forms temporary alliances to backstab later, and profits from instability. Values power and dominance through deception.
79- - Archetypes can be specified via config too (and cli).
80-- Once started the registatrion flow needs to complete, retry with the LLM showing clear errors if any.
81-
82-### Client Flow
83-
84-**1. Initialization**
85-
86-- Parse CLI arguments (each custom API field has corresponding CLI arg; currently just hint)
87-- Check for existing account:
88- - If exists: auto-login and continue
89- - **Note**: Auto-login only at boot; respect LLM logout decisions (no re-login)
90-
91-**2. Main Loop** (Server tick-driven)
92-
93-Client reacts to server `tick` messages instead of using a fixed interval timer. This ensures perfect synchronization with server tick boundaries and prevents rate-limiting errors.
94-
95-**Tick Synchronization:**
96-
97-- Server sends `tick` message every 10 seconds
98-- Client receives tick message and immediately processes:
99- - Updates `currentTick` value
100- - Debounces duplicate tick messages (tracks `lastProcessedTick`)
101- - Resets watchdog timer (detects missing ticks after 20 seconds)
102- - Triggers LLM prompt and command generation
103-
104-**Each tick processing:**
105-
106-a. **Prompt LLM**
107-
108-- Check for hint updates in database
109-- Provide: game event history + combined API + prompt + hint
110-- On client error: create client event in DB (avoid behavioral bias, do use words that can be interpreted as suggestions or directions), continue to next tick
111-
112-b. **Forward Response**
113-
114-- Send LLM reply to server
115-- On connection failure: create client message, continue to next tick
116-
117-c. **Wait for next server tick**
118-
119-**Safety mechanisms:**
120-
121-- **Duplicate detection**: Ignores duplicate tick messages using `lastProcessedTick` tracking
122-- **Processing lock**: Prevents parallel tick processing when LLM response time exceeds tick interval
123- - Uses `isProcessingTick` flag to ensure only one tick processes at a time
124- - Skips subsequent ticks if previous tick still processing (logs skip, no DB entry)
125- - Prevents rate limiting violations and resource waste from parallel LLM calls
126-- **Watchdog timer**: Warns if no tick received within `tick_rate * 2` (20 seconds)
127-- **Connection monitoring**: Logs watchdog timeouts as client errors in database
128-
129-### API Extensions
130-
131-**Custom Registration Command**
132-
133-- Hook registration to inject character prompt and hint when LLM creates new character
134-
135-**LLM Player Prompt Field**
136-
137-- New JSON API field describing player character
138-- **Single point of behavioral bias** - Only place to influence LLM toward character traits
139-- Generated from registration personality traits
140-- Hint injection capability (refreshed every tick) from the database
141-
142-**Format**:
143-
144-```jsonc
145-{
146- "prompt": "...", // Generated at registration
147- "hint": "...", // Optional injected message
148- // Standard commands from https://www.spacemolt.com/api.md
149-}
150-```
151-
152-### Output
153-
154-- When running without TUI, print human-readable log lines without omitting information for every message. No log files, no multiple instance support.
155-
156-### Client API Data Formats
157-
158-**What the LLM receives each tick:**
159-
160-```jsonc
161-{
162- "prompt": "...",
163- "hint": "...",
164- "history": [
165- {
166- "sender": "server",
167- "tick": 42,
168- "data": {
169- "action": "move",
170- "result": "success",
171- "message": "You moved to sector Alpha-7",
172- },
173- },
174- {
175- "sender": "client",
176- "tick": 43,
177- "data": {
178- "error": "Connection interrupted",
179- },
180- },
181- ],
182- "api": {
183- "register": {
184- "args": ["username", "empire"],
185- "description": "Register a new character",
186- },
187- "chat": {
188- "args": ["message"],
189- "description": "Send a chat message",
190- },
191- "move": {
192- "args": ["sector"],
193- "description": "Move to a different sector",
194- },
195- // ... rest of server API from api.md
196- },
197-}
198-```
199-
200-**Client error message format:**
201-
202-```jsonc
203-{
204- "sender": "client",
205- "tick": 45,
206- "data": {
207- "error": "Network connection interrupted",
208- "code": "CONNECTION_FAILED",
209- },
210-}
211-```
212-
213-**Client messages follow server patterns:**
214-
215-- Same JSON structure (sender, tick, data)
216-- Neutral, factual language
217-- Consistent error codes and messaging
218-
219-# TUI Design
220-
221-## Design Thinking Approach
222-
223-**Context & Purpose**
224-
225-- Terminal interface for LLM-controlled game client
226-- Users: developers/observers monitoring AI gameplay
227-- Primary function: real-time game state visualization and debugging
228-
229-**Aesthetic Direction: 1980's Sci-Fi Terminal**
230-
231-- **Tone**: Retro-futuristic, raw technical aesthetic
232-- **Differentiation**: Authentic vintage terminal feel with modern Unicode precision
233-- **Key memorable element**: Cohesive sci-fi terminal atmosphere that feels functional, not decorative
234-
235-**Design Principles**
236-
237-- **Typography**: Monospace (terminal native), rely on weight and spacing for hierarchy
238-- **Color & Theme**: Basic 16 terminal colors only - commit to restrained palette with intentional accent use
239-- **Spatial Composition**: Grid-based layouts with clear information hierarchy, generous use of borders and separators
240-- **Visual Details**: ASCII art iconography, modern Unicode for clean lines and boxes, layered information density
241-- **Motion**: Static by nature (terminal), but consider progressive reveals and state transitions, plenty of continuous animations, particularly to show activity.
242-
243-**Implementation Strategy**
244-
245-- Start with smallest reusable components, build up to complex layouts
246-- Precision in spacing, alignment, and container handling
247-- Handle resize gracefully - test at multiple terminal sizes
248-- No emojis - maintain technical aesthetic purity
249-
250-**Focus Areas**
251-
252-- Clear visual hierarchy through boxing, spacing, and ASCII decoration
253-- Cohesive use of Unicode line-drawing characters
254-- Intentional color use - dominant theme color with sharp accents for state/alerts
255-- Information density balanced with readability
256-
257-## Game client considerations
258-
259-Should separate player actions and their responses from other server messages.
260-Should separate chat and forum interactions to a social grouping.
261-Show all game data, use main panels for player actions and response as well as social actions. Sidebars and panels for other data.
262-Should clearly show current game tick, and the different states of the client game loop.
263-
264-# TUI library
265-
266-We should Ink as it's actively maintained. https://github.com/vadimdemedes/ink
267-
268----
269-
270-## Milestones
271-
272-### 1. Clean Slate [ DONE ]
273-
274-- Switch to git branch `refactor-new-client-internals`
275-- Wipe project: remove previous code, logs, memory files
276-- Update agents file: reference this document, remove old implementation details
277-- Migrate to Bun workspace structure
278-- Configure Prettier at workspace level (using Prettier instead of Biome for formatting)
279-- Create client package boilerplate:
280- - Bun `check` command (format with Prettier, lint with TypeScript, tests)
281- - Placeholder README
282-
283-### 2. Client Package Development [ ]
284-
285-- Create server mock from [api.md](https://www.spacemolt.com/api.md)
286-- Build test suite for desired features
287-- Implement core functionality
288-- Ensure all tests pass
289-- Add a Bun command to update the hint for an existing database file.
290-
291-### 3. TUI [ ]
292-
293-- Create the TUI Bun package.
294-- Create manual tests that render individual UI components in isolation and create a screenshot for layout and color verification.
295-- Generate some tests that render a preview of the new design.
296- - Test components with different size configurations to ensure it's resizeable.
297-- Review before proceeding (human decision)
298-- Implement the individual components (don't create components that we dont use.)
299-- Compose the final UI
300-- Ask for manual UI check in varied terminals (human decision)
301-
302----
303-
304-**IMPORTANT** - This plan file is sacred NEVER delete it in any case.