xonecas.io
5875
Os

ollama-space-molt-player / commit 18e0148

feat: implement Bun workspace with client package and core game client

xonecas2026-02-03 18e014808846d82b1c1c9f41afd14109bd1b5040 parent 57c23ee

33 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.

.gitignore+1−0
@@ -5,3 +5,4 @@ build/
55 *.log
66 .env
77 .DS_Store
8+prompt-length-findings.md
.prettierrc.json+9−0
@@ -0,0 +1,9 @@
1+{
2+ "useTabs": true,
3+ "tabWidth": 2,
4+ "semi": true,
5+ "singleQuote": false,
6+ "trailingComma": "all",
7+ "printWidth": 100,
8+ "arrowParens": "always"
9+}
AGENTS.md+100−12
@@ -4,7 +4,7 @@ Help coding agents work safely and consistently in this repo.
44
55 ## Important References
66
7-**Design Document**: `client-refaction-design.md` - Primary source of truth for architecture and design decisions
7+**Design Document**: `docs/2026-02-03-client-refactor-design.md` - Primary source of truth for architecture and design decisions
88
99 **Game Server WebSocket API**: https://www.spacemolt.com/api.md
1010
@@ -19,15 +19,18 @@ ollama-spacemolt-workspace/
1919 │ ├── src/ # Source code
2020 │ ├── tests/ # Unit tests
2121 │ └── package.json
22-├── client-refaction-design.md # Sacred design document
22+├── scripts/
23+│ └── strip-comments.ts # Comment removal script
24+├── docs/
25+│ └── 2026-02-03-client-refactor-design.md # Sacred design document
2326 ├── package.json # Workspace root
2427 ├── tsconfig.json # Base TypeScript config
25-└── biome.json # Workspace-level formatting/linting
28+└── .prettierrc.json # Prettier configuration
2629 ```
2730
2831 ## Design Principles
2932
30-From `client-refaction-design.md`:
33+From `docs/2026-02-03-client-refactor-design.md`:
3134
3235 1. **Reduce abstraction** - Minimize layers between client and server
3336 2. **Direct connection** - Connect to WebSocket without intermediate libraries
@@ -47,9 +50,10 @@ bun install
4750 bun run check
4851
4952 # Individual checks
50-bun run check:format
51-bun run check:lint
52-bun run check:test
53+bun run strip-comments # Strip comments from TypeScript files
54+bun run check:format # Format with Prettier
55+bun run check:lint # TypeScript compilation check
56+bun run check:test # Run tests
5357 ```
5458
5559 ### Client Package
@@ -67,23 +71,29 @@ bun run start
6771 ## Code Style Guidelines
6872
6973 ### Formatting
70-- Use Biome for all formatting and linting
74+
75+- Use Prettier for all formatting
76+- TypeScript compilation (`tsc --noEmit`) for linting
7177 - Tabs for indentation (2-space width)
72-- Let Biome handle style automatically
78+- 100 character line width
79+- Semicolons, double quotes, trailing commas
7380
7481 ### Naming Conventions
82+
7583 - Types/interfaces: `PascalCase`
7684 - Functions and variables: `camelCase`
7785 - Constants: `SCREAMING_SNAKE_CASE`
7886 - File names: `kebab-case.ts`
7987
8088 ### TypeScript
89+
8190 - `strict` mode enabled
8291 - Avoid `any`, use `unknown` then narrow
8392 - Explicit return types for public functions
8493 - Prefer `null` over `undefined` for absent values
8594
8695 ### Testing
96+
8797 - Use Bun's built-in test runner (`bun test`)
8898 - Target: 80% coverage for client code
8999 - Unit tests for core logic
@@ -92,11 +102,37 @@ bun run start
92102 ## Database
93103
94104 SQLite via `bun:sqlite`:
105+
95106 - Pattern: `memory-{instance-id}.sqlite`
96107 - Two tables: `account_details`, `messages`
97108 - Maximum 5000 messages, sorted by tick
98109 - Unique instance ID per client (4 characters)
99110
111+## Tick Processing
112+
113+The client uses a server-driven tick system with critical safety mechanisms:
114+
115+**Processing Lock:**
116+
117+- Only one tick can process at a time (enforced by `isProcessingTick` flag)
118+- If a new tick arrives while previous tick is still processing, it is skipped
119+- Prevents parallel LLM calls that would violate game server rate limits
120+- Skipped ticks are logged but not saved to database
121+
122+**Flow:**
123+
124+1. Server sends tick message every ~10 seconds
125+2. Client checks if currently processing (`isProcessingTick`)
126+3. If processing: log skip and return
127+4. If not: set lock, process tick (LLM call + command send), release lock
128+
129+**Why this matters:**
130+
131+- LLM calls can take 8-12 seconds (variable)
132+- Tick interval is 10 seconds (fixed)
133+- Without lock: overlapping ticks cause rate limiting errors
134+- With lock: sequential processing matches game server expectations
135+
100136 ## Error Handling
101137
102138 - Neutral, factual language only
@@ -106,16 +142,68 @@ SQLite via `bun:sqlite`:
106142
107143 ## Development Workflow
108144
109-1. Read `client-refaction-design.md` for context
145+1. Read `docs/2026-02-03-client-refactor-design.md` for context
110146 2. Make changes aligned with design principles
111-3. Run `bun run check` before committing
147+3. Run `bun run check` before committing (strips comments, formats, lints, tests)
112148 4. Keep abstractions minimal
113149 5. Test with real game server when possible
114150
151+## Code Quality
152+
153+### No Comments Policy
154+
155+**Comments are automatically stripped from all TypeScript files during the check process.** This prevents outdated comments from misleading future agents as code evolves.
156+
157+**Why this matters for AI agents:**
158+
159+- Agents make edits in chunks and often miss contextual comments
160+- Outdated comments create false assumptions about code behavior
161+- Comments can contradict actual implementation after refactoring
162+- Self-documenting code is more reliable than potentially stale documentation
163+
164+**When comments are stripped:**
165+
166+- During `bun run check` (after formatting, before linting)
167+- Applies to all `.ts` files in `packages/*/src/**` and `packages/*/tests/**`
168+- ALL comments are removed: single-line (`//`), multi-line (`/* */`), JSDoc
169+
170+**Write self-documenting code instead:**
171+
172+- Clear variable and function names that explain intent
173+- Small, focused functions (easier to understand at a glance)
174+- Type annotations for function signatures
175+- Well-structured code organization
176+- Descriptive constant names instead of magic numbers
177+
178+**Example - Instead of:**
179+
180+```typescript
181+const d = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
182+```
183+
184+**Write:**
185+
186+```typescript
187+function calculateDistance(point1: Point, point2: Point): number {
188+ const deltaX = point2.x - point1.x;
189+ const deltaY = point2.y - point1.y;
190+ return Math.sqrt(deltaX ** 2 + deltaY ** 2);
191+}
192+```
193+
194+**Where to document:**
195+
196+- Design decisions → `docs/2026-02-03-client-refactor-design.md`
197+- Architecture patterns → `AGENTS.md` (this file)
198+- User instructions → `README.md`
199+- API reference → Markdown files or separate docs
200+
115201 ## What NOT to Do
116202
117203 - Do not add intermediate translation layers
118204 - Do not add behavioral bias outside `prompt` field
119-- Do not modify sacred `client-refaction-design.md`
205+- Do not modify sacred `docs/2026-02-03-client-refactor-design.md`
120206 - Do not commit `*.sqlite` or `*.log` files
121207 - Do not create backward compatibility with old implementation
208+- **Do not access files outside of the repo root** - All file operations must stay within `/home/xonecas/src/ollama-spacemolt-player`
209+- **Run all commands in the repo root** - Use the `workdir` parameter if needed, but default to repo root
README.md+36−5
@@ -7,12 +7,12 @@ Bun workspace for LLM-controlled SpaceMolt game client.
77 This is a monorepo using Bun workspaces:
88
99 - `packages/client/` - WebSocket client that connects LLM to game server
10-- `client-refaction-design.md` - Architecture and design decisions
10+- `docs/2026-02-03-client-refactor-design.md` - Architecture and design decisions
1111 - `AGENTS.md` - Guide for coding agents working in this repo
1212
1313 ## Design Philosophy
1414
15-See `client-refaction-design.md` for full details. Key principles:
15+See `docs/2026-02-03-client-refactor-design.md` for full details. Key principles:
1616
1717 - Direct WebSocket connection to game server
1818 - Minimal abstraction layers
@@ -33,17 +33,48 @@ cd packages/client
3333 bun run start
3434 ```
3535
36+## Code Quality
37+
38+### No Comments Policy
39+
40+This project automatically strips all code comments during the check process. This may seem unusual, but it serves an important purpose:
41+
42+**Why no comments?**
43+
44+- AI agents make incremental edits and often miss updating related comments
45+- Outdated comments mislead future developers and agents more than missing comments
46+- Forces code to be self-documenting through clear naming and structure
47+
48+**When are comments stripped?**
49+
50+- Automatically during `bun run check`
51+- After formatting and before linting/testing
52+
53+**How to write self-documenting code:**
54+
55+- Use descriptive variable and function names
56+- Keep functions small and focused
57+- Use type annotations to document interfaces
58+- Structure code logically with clear separation of concerns
59+- Extract complex logic into named functions
60+
61+**What about documentation?**
62+
63+- User-facing documentation belongs in markdown files (README.md, design docs)
64+- API documentation can use JSDoc in declaration files if needed
65+- Design decisions should be captured in `docs/2026-02-03-client-refactor-design.md`
66+
3667 ## Workspace Commands
3768
3869 - `bun run check` - Run format, lint, and tests
39-- `bun run check:format` - Format code with Biome
40-- `bun run check:lint` - Lint code with Biome
70+- `bun run check:format` - Format code with Prettier
71+- `bun run check:lint` - Type-check with TypeScript
4172 - `bun run check:test` - Run tests with Bun
4273
4374 ## References
4475
4576 - Game Server API: https://www.spacemolt.com/api.md
46-- Design Document: `client-refaction-design.md`
77+- Design Document: `docs/2026-02-03-client-refactor-design.md`
4778 - Agent Guide: `AGENTS.md`
4879
4980 ## Development
biome.json+0−16
@@ -1,16 +0,0 @@
1-{
2- "formatter": {
3- "enabled": true,
4- "indentStyle": "tab",
5- "indentWidth": 2
6- },
7- "linter": {
8- "enabled": true,
9- "rules": {
10- "recommended": true
11- }
12- },
13- "files": {
14- "ignoreUnknown": true
15- }
16-}
bun.lock+17−14
@@ -5,7 +5,10 @@
55 "": {
66 "name": "ollama-spacemolt-workspace",
77 "devDependencies": {
8- "@biomejs/biome": "^2.3.13",
8+ "@types/bun": "^1.3.8",
9+ "glob": "^13.0.0",
10+ "prettier": "^3.8.1",
11+ "typescript": "^5.9.3",
912 },
1013 },
1114 "packages/client": {
@@ -17,31 +20,31 @@
1720 },
1821 },
1922 "packages": {
20- "@biomejs/biome": ["@biomejs/biome@2.3.13", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.3.13", "@biomejs/cli-darwin-x64": "2.3.13", "@biomejs/cli-linux-arm64": "2.3.13", "@biomejs/cli-linux-arm64-musl": "2.3.13", "@biomejs/cli-linux-x64": "2.3.13", "@biomejs/cli-linux-x64-musl": "2.3.13", "@biomejs/cli-win32-arm64": "2.3.13", "@biomejs/cli-win32-x64": "2.3.13" }, "bin": { "biome": "bin/biome" } }, "sha512-Fw7UsV0UAtWIBIm0M7g5CRerpu1eKyKAXIazzxhbXYUyMkwNrkX/KLkGI7b+uVDQ5cL …
23+ "@isaacs/balanced-match": ["@isaacs/balanced-match@4.0.1", "", {}, "sha512-yzMTt9lEb8Gv7zRioUilSglI0c0smZ9k5D65677DLWLtWJaXIS3CqcGyUFByYKlnUj6TkjLVs54fBl6+TiGQDQ=="],
2124
22- "@biomejs/cli-darwin-arm64": ["@biomejs/cli-darwin-arm64@2.3.13", "", { "os": "darwin", "cpu": "arm64" }, "sha512-0OCwP0/BoKzyJHnFdaTk/i7hIP9JHH9oJJq6hrSCPmJPo8JWcJhprK4gQlhFzrwdTBAW4Bjt/RmCf3ZZe59gwQ=="],
25+ "@isaacs/brace-expansion": ["@isaacs/brace-expansion@5.0.0", "", { "dependencies": { "@isaacs/balanced-match": "^4.0.1" } }, "sha512-ZT55BDLV0yv0RBm2czMiZ+SqCGO7AvmOM3G/w2xhVPH+te0aKgFjmBvGlL1dH+ql2tgGO3MVrbb3jCKyvpgnxA=="],
2326
24- "@biomejs/cli-darwin-x64": ["@biomejs/cli-darwin-x64@2.3.13", "", { "os": "darwin", "cpu": "x64" }, "sha512-AGr8OoemT/ejynbIu56qeil2+F2WLkIjn2d8jGK1JkchxnMUhYOfnqc9sVzcRxpG9Ycvw4weQ5sprRvtb7Yhcw=="],
27+ "@spacemolt/client": ["@spacemolt/client@workspace:packages/client"],
2528
26- "@biomejs/cli-linux-arm64": ["@biomejs/cli-linux-arm64@2.3.13", "", { "os": "linux", "cpu": "arm64" }, "sha512-xvOiFkrDNu607MPMBUQ6huHmBG1PZLOrqhtK6pXJW3GjfVqJg0Z/qpTdhXfcqWdSZHcT+Nct2fOgewZvytESkw=="],
29+ "@types/bun": ["@types/bun@1.3.8", "", { "dependencies": { "bun-types": "1.3.8" } }, "sha512-3LvWJ2q5GerAXYxO2mffLTqOzEu5qnhEAlh48Vnu8WQfnmSwbgagjGZV6BoHKJztENYEDn6QmVd949W4uESRJA=="],
2730
28- "@biomejs/cli-linux-arm64-musl": ["@biomejs/cli-linux-arm64-musl@2.3.13", "", { "os": "linux", "cpu": "arm64" }, "sha512-TUdDCSY+Eo/EHjhJz7P2GnWwfqet+lFxBZzGHldrvULr59AgahamLs/N85SC4+bdF86EhqDuuw9rYLvLFWWlXA=="],
31+ "@types/node": ["@types/node@25.2.0", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-DZ8VwRFUNzuqJ5khrvwMXHmvPe+zGayJhr2CDNiKB1WBE1ST8Djl00D0IC4vvNmHMdj6DlbYRIaFE7WHjlDl5w=="],
2932
30- "@biomejs/cli-linux-x64": ["@biomejs/cli-linux-x64@2.3.13", "", { "os": "linux", "cpu": "x64" }, "sha512-s+YsZlgiXNq8XkgHs6xdvKDFOj/bwTEevqEY6rC2I3cBHbxXYU1LOZstH3Ffw9hE5tE1sqT7U23C00MzkXztMw=="],
33+ "bun-types": ["bun-types@1.3.8", "", { "dependencies": { "@types/node": "*" } }, "sha512-fL99nxdOWvV4LqjmC+8Q9kW3M4QTtTR1eePs94v5ctGqU8OeceWrSUaRw3JYb7tU3FkMIAjkueehrHPPPGKi5Q=="],
3134
32- "@biomejs/cli-linux-x64-musl": ["@biomejs/cli-linux-x64-musl@2.3.13", "", { "os": "linux", "cpu": "x64" }, "sha512-0bdwFVSbbM//Sds6OjtnmQGp4eUjOTt6kHvR/1P0ieR9GcTUAlPNvPC3DiavTqq302W34Ae2T6u5VVNGuQtGlQ=="],
35+ "glob": ["glob@13.0.0", "", { "dependencies": { "minimatch": "^10.1.1", "minipass": "^7.1.2", "path-scurry": "^2.0.0" } }, "sha512-tvZgpqk6fz4BaNZ66ZsRaZnbHvP/jG3uKJvAZOwEVUL4RTA5nJeeLYfyN9/VA8NX/V3IBG+hkeuGpKjvELkVhA=="],
3336
34- "@biomejs/cli-win32-arm64": ["@biomejs/cli-win32-arm64@2.3.13", "", { "os": "win32", "cpu": "arm64" }, "sha512-QweDxY89fq0VvrxME+wS/BXKmqMrOTZlN9SqQ79kQSIc3FrEwvW/PvUegQF6XIVaekncDykB5dzPqjbwSKs9DA=="],
37+ "lru-cache": ["lru-cache@11.2.5", "", {}, "sha512-vFrFJkWtJvJnD5hg+hJvVE8Lh/TcMzKnTgCWmtBipwI5yLX/iX+5UB2tfuyODF5E7k9xEzMdYgGqaSb1c0c5Yw=="],
3538
36- "@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@2.3.13", "", { "os": "win32", "cpu": "x64" }, "sha512-trDw2ogdM2lyav9WFQsdsfdVy1dvZALymRpgmWsvSez0BJzBjulhOT/t+wyKeh3pZWvwP3VMs1SoOKwO3wecMQ=="],
39+ "minimatch": ["minimatch@10.1.1", "", { "dependencies": { "@isaacs/brace-expansion": "^5.0.0" } }, "sha512-enIvLvRAFZYXJzkCYG5RKmPfrFArdLv+R+lbQ53BmIMLIry74bjKzX6iHAm8WYamJkhSSEabrWN5D97XnKObjQ=="],
3740
38- "@spacemolt/client": ["@spacemolt/client@workspace:packages/client"],
41+ "minipass": ["minipass@7.1.2", "", {}, "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw=="],
3942
40- "@types/bun": ["@types/bun@1.3.8", "", { "dependencies": { "bun-types": "1.3.8" } }, "sha512-3LvWJ2q5GerAXYxO2mffLTqOzEu5qnhEAlh48Vnu8WQfnmSwbgagjGZV6BoHKJztENYEDn6QmVd949W4uESRJA=="],
43+ "path-scurry": ["path-scurry@2.0.1", "", { "dependencies": { "lru-cache": "^11.0.0", "minipass": "^7.1.2" } }, "sha512-oWyT4gICAu+kaA7QWk/jvCHWarMKNs6pXOGWKDTr7cw4IGcUbW+PeTfbaQiLGheFRpjo6O9J0PmyMfQPjH71oA=="],
4144
42- "@types/node": ["@types/node@25.2.0", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-DZ8VwRFUNzuqJ5khrvwMXHmvPe+zGayJhr2CDNiKB1WBE1ST8Djl00D0IC4vvNmHMdj6DlbYRIaFE7WHjlDl5w=="],
45+ "prettier": ["prettier@3.8.1", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg=="],
4346
44- "bun-types": ["bun-types@1.3.8", "", { "dependencies": { "@types/node": "*" } }, "sha512-fL99nxdOWvV4LqjmC+8Q9kW3M4QTtTR1eePs94v5ctGqU8OeceWrSUaRw3JYb7tU3FkMIAjkueehrHPPPGKi5Q=="],
47+ "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
4548
4649 "undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
4750 }
docs/2026-02-03-client-refactor-design.md+73−52
@@ -18,7 +18,7 @@ The current implementation has three core issues:
1818 - **Workspace structure** - Migrate to [Bun Workspaces](https://bun.com/docs/pm/workspaces)
1919 - **Package separation** - Split TUI and Client into separate packages with TUI imported by client
2020 - **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 Biome config
21+- **Unified tooling** - Bun scripts in repo root (with/without TUI), shared Prettier config
2222
2323 ### Database
2424
@@ -88,13 +88,24 @@ The current implementation has three core issues:
8888 - If exists: auto-login and continue
8989 - **Note**: Auto-login only at boot; respect LLM logout decisions (no re-login)
9090
91-**2. Main Loop** (tick_time + 100ms buffer, configurable)
91+**2. Main Loop** (Server tick-driven)
9292
93-Each tick:
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:**
94105
95106 a. **Prompt LLM**
96107
97-- Check for hint updates in database.
108+- Check for hint updates in database
98109 - Provide: game event history + combined API + prompt + hint
99110 - 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
100111
@@ -103,7 +114,17 @@ b. **Forward Response**
103114 - Send LLM reply to server
104115 - On connection failure: create client message, continue to next tick
105116
106-c. **Continue to next tick**
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
107128
108129 ### API Extensions
109130
@@ -122,9 +143,9 @@ c. **Continue to next tick**
122143
123144 ```jsonc
124145 {
125- "prompt": "...", // Generated at registration
126- "hint": "...", // Optional injected message
127- // Standard commands from https://www.spacemolt.com/api.md
146+ "prompt": "...", // Generated at registration
147+ "hint": "...", // Optional injected message
148+ // Standard commands from https://www.spacemolt.com/api.md
128149 }
129150 ```
130151
@@ -138,41 +159,41 @@ c. **Continue to next tick**
138159
139160 ```jsonc
140161 {
141- "prompt": "...",
142- "hint": "...",
143- "history": [
144- {
145- "sender": "server",
146- "tick": 42,
147- "data": {
148- "action": "move",
149- "result": "success",
150- "message": "You moved to sector Alpha-7",
151- },
152- },
153- {
154- "sender": "client",
155- "tick": 43,
156- "data": {
157- "error": "Connection interrupted",
158- },
159- },
160- ],
161- "api": {
162- "register": {
163- "args": ["username", "empire"],
164- "description": "Register a new character",
165- },
166- "chat": {
167- "args": ["message"],
168- "description": "Send a chat message",
169- },
170- "move": {
171- "args": ["sector"],
172- "description": "Move to a different sector",
173- },
174- // ... rest of server API from api.md
175- },
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+ },
176197 }
177198 ```
178199
@@ -180,12 +201,12 @@ c. **Continue to next tick**
180201
181202 ```jsonc
182203 {
183- "sender": "client",
184- "tick": 45,
185- "data": {
186- "error": "Network connection interrupted",
187- "code": "CONNECTION_FAILED",
188- },
204+ "sender": "client",
205+ "tick": 45,
206+ "data": {
207+ "error": "Network connection interrupted",
208+ "code": "CONNECTION_FAILED",
209+ },
189210 }
190211 ```
191212
@@ -248,15 +269,15 @@ We should Ink as it's actively maintained. https://github.com/vadimdemedes/ink
248269
249270 ## Milestones
250271
251-### 1. Clean Slate [ ]
272+### 1. Clean Slate [ DONE ]
252273
253274 - Switch to git branch `refactor-new-client-internals`
254275 - Wipe project: remove previous code, logs, memory files
255276 - Update agents file: reference this document, remove old implementation details
256277 - Migrate to Bun workspace structure
257-- Configure Biome at workspace level
278+- Configure Prettier at workspace level (using Prettier instead of Biome for formatting)
258279 - Create client package boilerplate:
259- - Bun `check` command (format with autofix, lint, tests)
280+ - Bun `check` command (format with Prettier, lint with TypeScript, tests)
260281 - Placeholder README
261282
262283 ### 2. Client Package Development [ ]
package.json+20−15
@@ -1,17 +1,22 @@
11 {
2- "name": "ollama-spacemolt-workspace",
3- "version": "0.2.0",
4- "private": true,
5- "workspaces": [
6- "packages/*"
7- ],
8- "scripts": {
9- "check": "bun run check:format && bun run check:lint && bun run check:test",
10- "check:format": "biome format --write .",
11- "check:lint": "biome lint --write .",
12- "check:test": "bun test"
13- },
14- "devDependencies": {
15- "@biomejs/biome": "^2.3.13"
16- }
2+ "name": "ollama-spacemolt-workspace",
3+ "version": "0.2.0",
4+ "private": true,
5+ "workspaces": [
6+ "packages/*"
7+ ],
8+ "scripts": {
9+ "check": "bun run check:format && bun run strip-comments && bun run check:lint && bun run check:test",
10+ "check:format": "prettier --write .",
11+ "check:lint": "tsc --noEmit",
12+ "check:test": "bun test",
13+ "strip-comments": "bun scripts/strip-comments.ts",
14+ "cli": "bun run --filter @spacemolt/client start"
15+ },
16+ "devDependencies": {
17+ "@types/bun": "^1.3.8",
18+ "glob": "^13.0.0",
19+ "prettier": "^3.8.1",
20+ "typescript": "^5.9.3"
21+ }
1722 }
packages/client/README.md+187−6
@@ -11,35 +11,216 @@ LLM-controlled WebSocket client for SpaceMolt game server.
1111
1212 ## Architecture
1313
14+### How It Works
15+
16+1. **Initialization**: Client connects to game server via WebSocket
17+2. **Auto-login**: If account exists in database, automatically login
18+3. **Game Loop**: Server-driven tick processing (~10 seconds per tick):
19+ - Server sends tick message
20+ - Check processing lock (only one tick processes at a time)
21+ - If already processing: skip tick with log message
22+ - If not processing: acquire lock and process tick
23+ - Fetch last 5 messages from history
24+ - Build context: `{ prompt, hint, recent_game_messages, api, accounts }`
25+ - Send to Ollama for LLM decision
26+ - Parse JSON response and forward to server
27+ - Save messages to database
28+ - Release processing lock
29+4. **Registration**: When LLM calls `register`, intercept and generate character prompt using archetype
30+
31+### Processing Lock
32+
33+The client uses a processing lock (`isProcessingTick`) to prevent parallel tick processing:
34+
35+- **Problem**: LLM calls can take 8-12 seconds, but ticks arrive every 10 seconds
36+- **Solution**: Only one tick processes at a time; subsequent ticks are skipped if lock is held
37+- **Behavior**: Skipped ticks are logged but not saved to database
38+- **Benefits**: Prevents rate limiting violations and resource waste from parallel LLM calls
39+
1440 ### Database Schema
1541
16-Two tables using SQLite:
42+Two tables using SQLite with automatic truncation at 5000 messages:
43+
1744 - `account_details`: credentials, username, id, hint, prompt
1845 - `messages`: raw JSON server communication, id, tick, client/server sender enum
1946
47+**Message Truncation**: SQL trigger automatically keeps oldest 5000 messages, deleting older ones by tick order.
48+
2049 ### API Extensions
2150
2251 Custom fields added to game server API:
23-- `prompt`: Generated at registration from character traits
24-- `hint`: Optional injected message, refreshed every tick
52+
53+- `prompt`: Generated at registration from character traits and archetype
54+- `hint`: Optional injected message, refreshed every tick from database
2555
2656 ### Instance Management
2757
2858 Each running client has an independent database file:
59+
2960 - Pattern: `memory-{instance-id}.sqlite`
3061 - Instance ID: 4-character random identifier
3162 - Complete data separation between instances
3263
33-## CLI Interface
64+## Usage
65+
66+### Prerequisites
67+
68+- [Bun](https://bun.sh) installed
69+- [Ollama](https://ollama.ai) running locally on port 11434
70+- Recommended model: `qwen3:8b` (or any compatible model)
71+
72+```bash
73+# Install Ollama model
74+ollama pull qwen3:8b
75+
76+# Start Ollama server (if not already running)
77+ollama serve
78+```
79+
80+### Basic Usage
81+
82+```bash
83+# Start client with auto-generated instance ID
84+bun run start
85+
86+# Start with specific instance ID and archetype
87+bun run start -- --instance abc1 --archetype diplomat
88+
89+# Start with hint and custom model
90+bun run start -- --hint "Focus on trading" --model llama3:8b
91+```
92+
93+### Commands
94+
95+**start** - Start the game client (default command)
96+
97+```bash
98+bun run start [OPTIONS]
99+```
100+
101+**update-hint** - Update hint for an existing instance
102+
103+```bash
104+bun run start update-hint --instance <id> --hint <text>
105+```
106+
107+**list-instances** - List all database instances
108+
109+```bash
110+bun run start list-instances
111+```
112+
113+**help** - Show help message
114+
115+```bash
116+bun run start help
117+```
118+
119+### Options
120+
121+| Option | Short | Description | Default |
122+| ----------------------- | ----- | ----------------------------------------------------- | ----------------------------- |
123+| `--instance <id>` | `-i` | Instance ID (4 chars, auto-generated if not provided) | Auto |
124+| `--hint <text>` | | Hint message injected into LLM context each tick | None |
125+| `--model <name>` | `-m` | Ollama model name | `qwen3:8b` |
126+| `--temperature <float>` | `-t` | LLM temperature | `1.2` |
127+| `--thinking` | | Enable Ollama thinking mode (verbose reasoning) | `false` |
128+| `--archetype <name>` | `-a` | Character archetype (see below) | None |
129+| `--ollama-timeout <ms>` | | Ollama API timeout in milliseconds | `30000` |
130+| `--server <url>` | `-s` | WebSocket server URL | `wss://game.spacemolt.com/ws` |
131+
132+### Archetypes
133+
134+Character archetypes define gameplay personality:
135+
136+- **diplomat**: Seeks alliances through negotiation and mutual benefit. Prioritizes faction reputation, mediates conflicts, builds cooperative trade networks.
137+- **opportunist**: Adapts strategy based on maximum personal gain. Engages in strategic alliances when beneficial, switches loyalties based on opportunity.
138+- **agitator**: Thrives on chaos and manipulation. Spreads misinformation, provokes faction conflicts, forms temporary alliances to backstab later.
34139
35-(To be implemented in Milestone 2)
140+### Ollama Thinking Mode
141+
142+When `--thinking` is enabled, the LLM provides verbose reasoning before making decisions. This:
143+
144+- Shows the model's thought process (useful for debugging)
145+- Increases token usage and response time
146+- Is disabled by default for faster gameplay
147+- Compatible with models supporting [Ollama's thinking capability](https://docs.ollama.com/capabilities/thinking)
148+
149+### Examples
150+
151+```bash
152+# New player with diplomat archetype
153+bun run start -- -i xyz9 -a diplomat
154+
155+# Enable thinking mode for detailed reasoning
156+bun run start -- -i xyz9 -a diplomat --thinking
157+
158+# Existing player with custom settings
159+bun run start -- -i xyz9 -m qwen2:7b -t 0.9
160+
161+# Connect to custom server for testing
162+bun run start -- -i test -s ws://localhost:8080
163+
164+# Update hint for running instance
165+bun run start update-hint --instance xyz9 --hint "Explore new systems"
166+```
36167
37168 ## Development
38169
39170 ```bash
40-# Run checks (format, lint, test)
171+# Install dependencies
172+bun install
173+
174+# Run all checks (format, lint, test)
41175 bun run check
42176
177+# Individual checks
178+bun run check:format
179+bun run check:lint
180+bun run check:test
181+
43182 # Start client
44183 bun run start
45184 ```
185+
186+## Testing
187+
188+```bash
189+# Run all tests
190+bun test
191+
192+# Run specific test file
193+bun test tests/db.test.ts
194+
195+# Watch mode
196+bun test --watch
197+```
198+
199+Test coverage: 65 tests across 5 test suites (db, ws-client, ollama, cli, json-extraction)
200+
201+## Project Structure
202+
203+```
204+src/
205+├── types.ts # TypeScript types from api.md
206+├── db.ts # SQLite database operations
207+├── ws-client.ts # WebSocket client with reconnection
208+├── ollama.ts # Ollama HTTP client
209+├── archetypes.ts # Character personality archetypes
210+├── api-definition.ts # Game API definition
211+├── game-client.ts # Main game client orchestration
212+├── cli.ts # CLI argument parser
213+└── index.ts # Entry point
214+
215+tests/
216+├── db.test.ts # Database unit tests
217+├── ws-client.test.ts # WebSocket client tests
218+├── ollama.test.ts # Ollama client tests
219+├── cli.test.ts # CLI parser tests
220+├── json-extraction.test.ts # JSON extraction from LLM responses
221+└── mock-server.ts # Mock WebSocket server for testing
222+```
223+
224+## API Reference
225+
226+See [SpaceMolt API Documentation](https://www.spacemolt.com/api.md) for full game server API.
packages/client/package.json+5−4
@@ -4,11 +4,12 @@
44 "private": true,
55 "type": "module",
66 "scripts": {
7- "check": "bun run check:format && bun run check:lint && bun run check:test",
8- "check:format": "biome format --write .",
9- "check:lint": "biome lint --write .",
7+ "check": "bun run strip-comments && bun run check:format && bun run check:lint && bun run check:test",
8+ "check:format": "prettier --write .",
9+ "check:lint": "tsc --noEmit",
1010 "check:test": "bun test",
11- "start": "bun src/index.ts"
11+ "start": "bun src/index.ts",
12+ "strip-comments": "bun ../../scripts/strip-comments.ts"
1213 },
1314 "dependencies": {},
1415 "devDependencies": {
packages/client/src/api-definition.ts+264−0
@@ -0,0 +1,264 @@
1+import type { APIDefinition } from "./types.ts";
2+
3+export const GAME_API: APIDefinition = {
4+ register: {
5+ args: ["username", "empire"],
6+ description:
7+ "Register a new character. Empire options: solarian, voidborn, crimson, nebula, outerrim. Note: Currently only 'solarian' is available for new players.",
8+ },
9+ login: {
10+ args: ["username", "token"],
11+ description: "Login to existing account using saved credentials.",
12+ },
13+ logout: {
14+ args: [],
15+ description: "Disconnect and save state.",
16+ },
17+
18+ travel: {
19+ args: ["target_poi"],
20+ description:
21+ "Travel to a point of interest in the current system. Use POI ID from current system.",
22+ },
23+ jump: {
24+ args: ["target_system"],
25+ description:
26+ "Jump to an adjacent system. Takes 5 ticks and consumes 5 fuel. Use system ID from current system's connections.",
27+ },
28+ dock: {
29+ args: [],
30+ description: "Dock at current POI's station if available.",
31+ },
32+ undock: {
33+ args: [],
34+ description: "Leave docked station.",
35+ },
36+
37+ attack: {
38+ args: ["target_id", "weapon_idx"],
39+ description:
40+ "Attack a player at current location. Target must be nearby. Weapon index starts at 0.",
41+ },
42+ scan: {
43+ args: ["target_id"],
44+ description: "Scan a player to reveal information about their ship.",
45+ },
46+
47+ mine: {
48+ args: [],
49+ description: "Extract resources from current POI if it contains mineable resources.",
50+ },
51+
52+ buy: {
53+ args: ["listing_id", "quantity"],
54+ description: "Buy items from NPC market at current station.",
55+ },
56+ sell: {
57+ args: ["item_id", "quantity"],
58+ description: "Sell items from cargo to NPC market at current station for credits.",
59+ },
60+ list_item: {
61+ args: ["item_id", "quantity", "price_each"],
62+ description: "List items on player marketplace. Other players can purchase them.",
63+ },
64+ cancel_list: {
65+ args: ["listing_id"],
66+ description: "Cancel your marketplace listing and retrieve items.",
67+ },
68+ buy_listing: {
69+ args: ["listing_id", "quantity"],
70+ description: "Purchase items from another player's marketplace listing.",
71+ },
72+ get_listings: {
73+ args: [],
74+ description:
75+ "View all market listings at current station. Returns both NPC and player listings.",
76+ },
77+
78+ trade_offer: {
79+ args: ["target_id", "offer_items", "offer_credits", "request_items", "request_credits"],
80+ description: "Propose a trade with another player. Items format: [{item_id, quantity}]",
81+ },
82+ trade_accept: {
83+ args: ["trade_id"],
84+ description: "Accept a trade offer from another player.",
85+ },
86+ trade_decline: {
87+ args: ["trade_id"],
88+ description: "Decline a trade offer.",
89+ },
90+ trade_cancel: {
91+ args: ["trade_id"],
92+ description: "Cancel a trade offer you initiated.",
93+ },
94+ get_trades: {
95+ args: [],
96+ description: "View all pending trade offers.",
97+ },
98+
99+ get_wrecks: {
100+ args: [],
101+ description: "List ship wrecks at current POI that can be looted.",
102+ },
103+ loot_wreck: {
104+ args: ["wreck_id", "item_id", "quantity"],
105+ description: "Take specific items from a wreck.",
106+ },
107+ salvage_wreck: {
108+ args: ["wreck_id"],
109+ description: "Destroy wreck completely and receive salvage materials.",
110+ },
111+
112+ buy_ship: {
113+ args: ["ship_class"],
114+ description: "Purchase a new ship at current station. Must be docked at a station.",
115+ },
116+ install_mod: {
117+ args: ["module_id", "slot_idx"],
118+ description: "Install a module into ship. Must be docked. Module must be in cargo.",
119+ },
120+ uninstall_mod: {
121+ args: ["slot_idx"],
122+ description: "Remove a module from ship. Module goes to cargo.",
123+ },
124+ refuel: {
125+ args: [],
126+ description: "Refuel ship to maximum capacity. Must be docked at station.",
127+ },
128+ repair: {
129+ args: [],
130+ description: "Repair hull and shield damage. Must be docked at station.",
131+ },
132+
133+ craft: {
134+ args: ["recipe_id"],
135+ description:
136+ "Craft an item using a recipe. Consumes materials from cargo. Must have required skill level.",
137+ },
138+
139+ chat: {
140+ args: ["channel", "content", "target_id?"],
141+ description:
142+ "Send chat message. Channels: local, system, faction, private. Private requires target_id.",
143+ },
144+
145+ create_faction: {
146+ args: ["name", "tag"],
147+ description: "Create a new faction. Tag must be 4 characters. Costs credits.",
148+ },
149+ join_faction: {
150+ args: ["faction_id"],
151+ description: "Accept invitation to join a faction.",
152+ },
153+ leave_faction: {
154+ args: [],
155+ description: "Leave current faction.",
156+ },
157+ faction_invite: {
158+ args: ["player_id"],
159+ description: "Invite a player to your faction. Requires permissions.",
160+ },
161+ faction_kick: {
162+ args: ["player_id"],
163+ description: "Remove a member from faction. Requires permissions.",
164+ },
165+ faction_promote: {
166+ args: ["player_id", "role_id"],
167+ description: "Change a member's role. Requires permissions.",
168+ },
169+
170+ buy_insurance: {
171+ args: ["coverage_percent"],
172+ description: "Purchase ship insurance. Coverage: 50-100%. Pays out if ship is destroyed.",
173+ },
174+ claim_insurance: {
175+ args: [],
176+ description: "Claim insurance payout after ship destruction.",
177+ },
178+ set_home_base: {
179+ args: [],
180+ description: "Set current station as respawn point. Must be docked at station.",
181+ },
182+
183+ set_status: {
184+ args: ["status_message", "clan_tag"],
185+ description: "Update status message and clan tag visible to other players.",
186+ },
187+ set_colors: {
188+ args: ["primary_color", "secondary_color"],
189+ description: "Set ship colors. Format: #RRGGBB hex colors.",
190+ },
191+ set_anonymous: {
192+ args: ["anonymous"],
193+ description: "Toggle anonymity. When true, hides most information from other players.",
194+ },
Cut short: this commit's diff is over 1000 lines.
packages/client/src/archetypes.ts+52−0
Cut short: this commit's diff is over 1000 lines.
packages/client/src/cli.ts+161−0
Cut short: this commit's diff is over 1000 lines.
packages/client/src/db.ts+187−0
Cut short: this commit's diff is over 1000 lines.
packages/client/src/game-client.ts+419−0
Cut short: this commit's diff is over 1000 lines.
packages/client/src/index.ts+96−0
Cut short: this commit's diff is over 1000 lines.
packages/client/src/logging.ts+360−0
Cut short: this commit's diff is over 1000 lines.
packages/client/src/ollama.ts+95−0
Cut short: this commit's diff is over 1000 lines.
packages/client/src/player-api-reference.ts+55−0
Cut short: this commit's diff is over 1000 lines.
packages/client/src/types.ts+459−0
Cut short: this commit's diff is over 1000 lines.
packages/client/src/ws-client.ts+221−0
Cut short: this commit's diff is over 1000 lines.
packages/client/tests/cli.test.ts+134−0
Cut short: this commit's diff is over 1000 lines.
packages/client/tests/db.test.ts+208−0
Cut short: this commit's diff is over 1000 lines.
packages/client/tests/json-extraction.test.ts+106−0
Cut short: this commit's diff is over 1000 lines.
packages/client/tests/mock-server.ts+175−0
Cut short: this commit's diff is over 1000 lines.
packages/client/tests/ollama.test.ts+197−0
Cut short: this commit's diff is over 1000 lines.
packages/client/tests/prompt-length.test.ts+245−0
Cut short: this commit's diff is over 1000 lines.
packages/client/tests/ws-client.test.ts+189−0
Cut short: this commit's diff is over 1000 lines.
packages/client/tests/ws-message-handling.test.ts+225−0
Cut short: this commit's diff is over 1000 lines.
packages/client/tsconfig.json+1−1
Cut short: this commit's diff is over 1000 lines.
scripts/strip-comments.test.ts+129−0
Cut short: this commit's diff is over 1000 lines.
scripts/strip-comments.ts+204−0
Cut short: this commit's diff is over 1000 lines.
tsconfig.json+12−10
Cut short: this commit's diff is over 1000 lines.