xonecas.io
5875
Os

ollama-space-molt-player / commit 6637598

refactor: create Bun workspace structure

- Configure workspace-level Biome formatting/linting
- Create packages/client boilerplate with check scripts
- Update AGENTS.md to reference design document
- Add workspace README with quick start guide

xonecas2026-02-02 663759861ad736af87e19208ddc2ca0fd12e1ac3 parent b72d637

50 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+2−4
@@ -1,9 +1,7 @@
11 node_modules/
2-.spacemolt-bot-*.json
3-memory-*.sqlite
2+dist/
3+build/
44 *.sqlite
55 *.log
66 .env
77 .DS_Store
8-dist/
9-build/
.gitmodules+0−4
@@ -1,4 +0,0 @@
1-[submodule "client"]
2- path = client
3- url = git@github.com:sacenox/client.git
4- branch = fix/handle-multiple-json-per-frame
AGENTS.md+77−165
@@ -4,206 +4,118 @@ 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
8+
79 **Game Server WebSocket API**: https://www.spacemolt.com/api.md
810
9-The `client/` folder in the root is a reference client that includes the library used to connect to the game server.
10-
11-When testing, **reuse existing accounts** when possible. Memory DB files (`memory-*.sqlite`) are in the root and git-ignored. Examples: `memory-test-cli-override.sqlite`, `memory-swarm-01.sqlite`.
12-
13-## Repo Snapshot
14-
15-- **Runtime**: Bun (TypeScript, ESM)
16-- **UI**: Terminal UI via `blessed`
17-- **LLM**: Local Ollama HTTP API
18-- **Data**: SQLite via `bun:sqlite` at `memory-{name}.sqlite`
19-- **Game client**: SpaceMolt reference client (git submodule in `client/`)
20-
21-## Key Paths
22-
23-- `src/index.ts` - Main entry (orchestrates client + LLM + memory + output)
24-- `src/config.ts` - Configuration and CLI args parsing
25-- `src/ollama.ts` - Ollama HTTP client
26-- `src/memory.ts` - SQLite memory store
27-- `src/prompt.ts` - LLM prompt building
28-- `src/actions.ts` - Action validation and dispatch
29-- `src/game-state.ts` - Game state tracking
30-- `src/registration.ts` - Registration flow
31-- `src/output/tui-output.ts` - Interactive TUI output
32-- `src/output/file-logger-output.ts` - Headless log output
33-- `src/output-interface.ts` - Output interface definition
34-- `src/swarm.ts` - Swarm orchestrator for multiple bots
35-- `src/tui/` - TUI components (layout, formatters, colors, utils)
36-- `src/types.ts` - Type definitions
37-- `src/utils.ts` - Shared utilities
38-- `src/constants.ts` - Constants
11+## Workspace Structure
3912
40-## Commands
13+This is a Bun workspace with the following layout:
4114
42-### Install
43-```bash
44-bun install
4515 ```
46-
47-### Run Single Bot (Interactive)
48-```bash
49-bun run ollama-play --name <instance-name>
16+ollama-spacemolt-workspace/
17+├── packages/
18+│ └── client/ # WebSocket client package
19+│ ├── src/ # Source code
20+│ ├── tests/ # Unit tests
21+│ └── package.json
22+├── client-refaction-design.md # Sacred design document
23+├── package.json # Workspace root
24+├── tsconfig.json # Base TypeScript config
25+└── biome.json # Workspace-level formatting/linting
5026 ```
5127
52-Required:
53-- `--name` or `-n`: Instance name (determines DB: `memory-{name}.sqlite`)
28+## Design Principles
5429
55-Optional character overrides (new registrations only):
56-- `--empire` or `-e`: solarian, voidborn, crimson, nebula, outerrim
57-- `--alignment` or `-a`: lawful, good, neutral, chaotic, evil
58-- `--speech-style` or `-s`: mythic, punny, gritty, scholarly
30+From `client-refaction-design.md`:
5931
60-Note: Personality is now custom-generated by the LLM during registration (title + behavior description). The old `--personality` flag has been removed.
32+1. **Reduce abstraction** - Minimize layers between client and server
33+2. **Direct connection** - Connect to WebSocket without intermediate libraries
34+3. **Neutral errors** - Use language from api.md, avoid behavioral bias
35+4. **Single bias point** - Only `prompt` field influences LLM behavior
36+5. **Minimal translation** - Forward game events directly to LLM
6137
62-Examples:
63-```bash
64-bun run ollama-play -n alice
65-bun run ollama-play -n test-bot -e crimson -a evil -s gritty
66-```
67-
68-### Run Non-Interactive (Headless)
69-```bash
70-bun run ollama-play --name <instance-name> --non-interactive [--max-ticks <number>]
71-```
72-
73-Output:
74-- `ui-{name}.log` - UI output with timestamps
75-- `debug-{name}.log` - Debug info (prompts, responses, thinking)
38+## Commands
7639
77-Example:
78-```bash
79-bun run ollama-play --name test-bot --non-interactive --max-ticks 100
80-```
40+### Workspace Level
8141
82-### Run Swarm
8342 ```bash
84-bun run swarm [--count 5] [--prefix swarm] [--empire <empire>] [--alignment <alignment>] [--speech-style <style>]
85-```
43+# Install dependencies
44+bun install
8645
87-Defaults:
88-- Count: 5
89-- Prefix: swarm (creates swarm-01, swarm-02, etc.)
90-- Model: ministral-3:8b
91-- Thinking: false
46+# Run all checks (format, lint, test)
47+bun run check
9248
93-Example:
94-```bash
95-bun run swarm --count 10 --empire crimson --alignment evil --speech-style gritty
49+# Individual checks
50+bun run check:format
51+bun run check:lint
52+bun run check:test
9653 ```
9754
98-### Format and Lint
99-```bash
100-bun run biome:format
101-bun run biome:lint
102-```
103-
104-### Testing
105-
106-Manual testing only. No test runner configured.
107-
108-Prefer reusing existing accounts:
109-- `test-cli-override` → `memory-test-cli-override.sqlite`
110-- `test-bot-1` → `memory-test-bot-1.sqlite`
111-- `swarm-01` through `swarm-05` → `memory-swarm-*.sqlite`
55+### Client Package
11256
113-If you see `Invalid username or token`, delete the instance DB and rerun.
114-
115-## Environment Variables
57+```bash
58+cd packages/client
11659
117-- `OLLAMA_URL` - Ollama server URL (default: `http://localhost:11434`)
118-- `OLLAMA_MODEL` - Model name (default: `qwen3:8b`)
119-- `OLLAMA_TEMPERATURE` - Temperature (default: `0.5`)
120-- `OLLAMA_THINKING` - Enable thinking mode (default: `true`)
121-- `SPACEMOLT_URL` - Game WebSocket URL (default: `wss://game.spacemolt.com/ws`)
122-- `DEBUG` - Enable TUI prompt pane (default: `false`)
123-- `MEMORY_DB` - Override DB path (default: `memory-{name}.sqlite`)
60+# Run checks
61+bun run check
12462
125-Timeout is configured in `src/config.ts` as `ollamaTimeoutMs` (60000ms).
63+# Start client (once implemented)
64+bun run start
65+```
12666
12767 ## Code Style Guidelines
12868
12969 ### Formatting
130-- Use Biome for formatting and linting
131-- Let Biome handle formatting; avoid manual changes
70+- Use Biome for all formatting and linting
71+- Tabs for indentation (2-space width)
72+- Let Biome handle style automatically
13273
13374 ### Naming Conventions
13475 - Types/interfaces: `PascalCase`
135-- Classes: `PascalCase`
13676 - Functions and variables: `camelCase`
137-- Global constants: `SCREAMING_SNAKE_CASE`
138-- Local constants: `camelCase`
139-- File names: `lowercase` with `.ts`
140-
141-### Types and Strictness
142-- `strict` TypeScript enabled; avoid `any`
143-- Use `unknown` then narrow or validate
144-- Prefer explicit return types for public functions
145-- Prefer `null` over `undefined` for intentionally absent values
77+- Constants: `SCREAMING_SNAKE_CASE`
78+- File names: `kebab-case.ts`
14679
147-### Error Handling
148-- Use `try/catch` around external I/O (HTTP, file, DB)
149-- Throw typed errors where appropriate (e.g., `OllamaTimeoutError`)
150-- Validate external inputs; return structured errors (e.g., `validateAction`)
151-- Log errors with context; keep user-facing messages concise
80+### TypeScript
81+- `strict` mode enabled
82+- Avoid `any`, use `unknown` then narrow
83+- Explicit return types for public functions
84+- Prefer `null` over `undefined` for absent values
15285
153-### Side Effects and State
154-- Keep side effects in `src/index.ts`; helper modules should be pure
155-- Avoid hidden global state; prefer explicit parameters
156-- Use small, focused functions for validation and formatting
157-
158-### Prompts and LLM Outputs
159-- LLM calls must expect malformed output; parse defensively
160-- Enforce JSON-only responses and validate fields before use
161-- Keep prompt updates in `src/prompt.ts`
162-
163-### TUI
164-- TUI is now in `src/output/tui-output.ts` and `src/tui/` directory
165-- Use `blessed` widgets; keep rendering in output modules
166-- Avoid Unicode-heavy UI unless needed (uses `fullUnicode: false`)
167-
168-### SQLite / Memory
169-- Centralize DB operations in `src/memory.ts`
170-- Serialize JSON using helper functions; guard against stringify errors
171-- Keep text fields reasonably bounded
172-
173-### Game Client
174-- Use the reference client from `client/` submodule
175-- Do not modify `client/` unless the change is intended for upstream
176-
177-## Editing Safety
178-
179-- Do not edit or commit `memory-*.sqlite` files
180-- Do not commit secrets or credentials
181-- Keep changes minimal and aligned with current architecture
182-- All DB files and logs are git-ignored
86+### Testing
87+- Use Bun's built-in test runner (`bun test`)
88+- Target: 80% coverage for client code
89+- Unit tests for core logic
90+- Manual tests for TUI (screenshots)
18391
184-## Conventions in This Repo
92+## Database
18593
186-- Use small, focused helpers for formatting and validation
187-- Prefer explicit `if` branches over implicit coercion
188-- Use early returns for invalid states
189-- Maintain descriptive log messages for output
94+SQLite via `bun:sqlite`:
95+- Pattern: `memory-{instance-id}.sqlite`
96+- Two tables: `account_details`, `messages`
97+- Maximum 5000 messages, sorted by tick
98+- Unique instance ID per client (4 characters)
19099
191-## When Adding New Features
100+## Error Handling
192101
193-- Update prompts and validation together
194-- Add to memory tracking only if it improves LLM context
195-- Keep tick timing aligned with server tick (10s; local uses 11s)
196-- Update both `src/output/tui-output.ts` and `src/output/file-logger-output.ts` for UI changes
102+- Neutral, factual language only
103+- Follow error terminology from api.md
104+- No behavioral bias in error messages
105+- Client errors logged but don't stop tick loop
197106
198-## If You Add Tests Later
107+## Development Workflow
199108
200-- Document the test framework and single-test command here
201-- Prefer a runner that supports file and name filtering
109+1. Read `client-refaction-design.md` for context
110+2. Make changes aligned with design principles
111+3. Run `bun run check` before committing
112+4. Keep abstractions minimal
113+5. Test with real game server when possible
202114
203-## Quick Review Checklist
115+## What NOT to Do
204116
205-```bash
206-bun run biome:lint
207-bun run biome:format
208-bun run ollama-play --name test-bot --non-interactive --max-ticks 10
209-```
117+- Do not add intermediate translation layers
118+- Do not add behavioral bias outside `prompt` field
119+- Do not modify sacred `client-refaction-design.md`
120+- Do not commit `*.sqlite` or `*.log` files
121+- Do not create backward compatibility with old implementation
README.md+31−113
@@ -1,133 +1,51 @@
1-# Space Molt: Ollama Player
1+# ollama-spacemolt-workspace
22
3-Let a locally hosted LLM play [Space Molt](https://www.spacemolt.com/).
3+Bun workspace for LLM-controlled SpaceMolt game client.
44
5-![Screenshot](tui_preview.png)
5+## Project Structure
66
7-## Overview
7+This is a monorepo using Bun workspaces:
88
9-An AI agent that plays Space Molt using local Ollama LLMs. The agent:
10-- Registers and manages accounts automatically
11-- Makes decisions based on game state and memory
12-- Tracks actions and outcomes for context
13-- Runs in interactive TUI mode or headless for testing
9+- `packages/client/` - WebSocket client that connects LLM to game server
10+- `client-refaction-design.md` - Architecture and design decisions
11+- `AGENTS.md` - Guide for coding agents working in this repo
1412
15-## Important Links
13+## Design Philosophy
1614
17-- **Game Server API**: https://www.spacemolt.com/api.md
18-- **Reference Client**: `client/` submodule (SpaceMolt client library)
15+See `client-refaction-design.md` for full details. Key principles:
1916
20-## Tech Stack
17+- Direct WebSocket connection to game server
18+- Minimal abstraction layers
19+- Neutral error messaging
20+- Single behavioral bias point (LLM prompt field)
2121
22-- **Runtime**: Bun (TypeScript, ESM)
23-- **UI**: Terminal UI via `blessed` (`src/output/tui-output.ts`)
24-- **LLM**: Local Ollama HTTP API (`src/ollama.ts`)
25-- **Memory**: SQLite via `bun:sqlite` (`src/memory.ts`)
26-- **Game Client**: SpaceMolt reference client in `client/` submodule
27-
28-## Setup
22+## Quick Start
2923
3024 ```bash
25+# Install dependencies
3126 bun install
32-```
33-
34-## Usage
35-
36-### Run Single Bot (Interactive TUI)
37-
38-```bash
39-bun run ollama-play --name <instance-name>
40-```
41-
42-Required:
43-- `--name` or `-n`: Instance name (determines DB file: `memory-{name}.sqlite`)
4427
45-Optional character overrides (new registrations only):
46-- `--empire` or `-e`: solarian, voidborn, crimson, nebula, outerrim
47-- `--alignment` or `-a`: lawful, good, neutral, chaotic, evil
48-- `--personality` or `-p`: cartographer, merchant, warrior, diplomat, pragmatist
49-- `--speech-style` or `-s`: mythic, punny, gritty, scholarly
28+# Run all checks (format, lint, test)
29+bun run check
5030
51-Example:
52-```bash
53-bun run ollama-play -n alice
54-bun run ollama-play -n test-bot -e crimson -a evil -p warrior
31+# Work in client package
32+cd packages/client
33+bun run start
5534 ```
5635
57-### Run in Non-Interactive Mode (Headless)
58-
59-For testing/debugging without TUI:
36+## Workspace Commands
6037
61-```bash
62-bun run ollama-play --name <instance-name> --non-interactive [--max-ticks <number>]
63-```
38+- `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
41+- `bun run check:test` - Run tests with Bun
6442
65-Output is written to:
66-- `ui-{name}.log` - UI output with timestamps
67-- `debug-{name}.log` - Debug info (prompts, responses, thinking)
43+## References
6844
69-Example:
70-```bash
71-bun run ollama-play --name test-bot --non-interactive --max-ticks 100
72-```
45+- Game Server API: https://www.spacemolt.com/api.md
46+- Design Document: `client-refaction-design.md`
47+- Agent Guide: `AGENTS.md`
7348
74-### Run Swarm (Multiple Bots)
49+## Development
7550
76-```bash
77-bun run swarm --count 5 --empire crimson --alignment evil --personality warrior
78-```
79-
80-Options:
81-- `--count` or `-c`: Number of bots (default: 5)
82-- `--prefix` or `-p`: Instance name prefix (default: swarm)
83-- `--restart-delay`: Restart delay in ms (default: 10000)
84-- `--empire`, `--alignment`, `--personality`, `--speech-style`: Character overrides
85-
86-Swarm mode:
87-- Uses `OLLAMA_THINKING=false` and `OLLAMA_MODEL=ministral-3:8b` per bot
88-- Orchestration logs: `swarm.log`
89-- Individual bot logs: `ui-<name>.log` and `debug-<name>.log`
90-
91-## Testing
92-
93-**Reuse existing accounts** when possible to avoid creating new accounts on every run.
94-
95-Credentials are stored in instance SQLite DBs (`memory-{name}.sqlite`) and are git-ignored.
96-
97-Known test instances:
98-- `test-cli-override` → `memory-test-cli-override.sqlite`
99-- `test-bot-1` → `memory-test-bot-1.sqlite`
100-- `swarm-01` through `swarm-05` → `memory-swarm-*.sqlite`
101-
102-If you see `Invalid username or token`, delete the instance DB and rerun to create a new account.
103-
104-## Environment Variables
105-
106-- `OLLAMA_URL` - Ollama server URL (default: `http://localhost:11434`)
107-- `OLLAMA_MODEL` - Model name (default: `qwen3:8b`)
108-- `OLLAMA_TEMPERATURE` - Temperature (default: `0.5`)
109-- `OLLAMA_THINKING` - Enable thinking mode for Qwen3 (default: `true`)
110-- `SPACEMOLT_URL` - Game server WebSocket URL (default: `wss://game.spacemolt.com/ws`)
111-- `DEBUG` - Enable TUI prompt pane when `true`
112-- `MEMORY_DB` - Override memory DB path (default: `memory-{name}.sqlite`)
113-
114-## Key Files
115-
116-- `src/index.ts` - Main entry (orchestrates client + LLM + memory + TUI)
117-- `src/config.ts` - Configuration and CLI args parsing
118-- `src/ollama.ts` - Ollama HTTP client
119-- `src/memory.ts` - SQLite memory store
120-- `src/prompt.ts` - LLM prompt building
121-- `src/actions.ts` - Action validation and dispatch
122-- `src/game-state.ts` - Game state tracking
123-- `src/registration.ts` - Registration flow
124-- `src/output/tui-output.ts` - Interactive TUI output
125-- `src/output/file-logger-output.ts` - Headless log output
126-- `src/swarm.ts` - Swarm orchestrator
127-
128-## Formatting and Linting
129-
130-```bash
131-bun run biome:format
132-bun run biome:lint
133-```
51+See `packages/client/README.md` for client-specific documentation.
biome.json+6−13
@@ -1,23 +1,16 @@
11 {
2- "$schema": "https://biomejs.dev/schemas/2.3.13/schema.json",
3- "files": {
4- "includes": [
5- "**/*",
6- "!client",
7- "!node_modules",
8- "!dist",
9- "!bun.lock",
10- "!memory.sqlite",
11- "!.spacemolt-bot-credentials.json"
12- ]
13- },
142 "formatter": {
15- "enabled": true
3+ "enabled": true,
4+ "indentStyle": "tab",
5+ "indentWidth": 2
166 },
177 "linter": {
188 "enabled": true,
199 "rules": {
2010 "recommended": true
2111 }
12+ },
13+ "files": {
14+ "ignoreUnknown": true
2215 }
2316 }
bun.lock+13−8
@@ -3,13 +3,16 @@
33 "configVersion": 1,
44 "workspaces": {
55 "": {
6- "name": "ollama-spacemolt-player",
7- "dependencies": {
8- "blessed": "^0.1.81",
9- },
6+ "name": "ollama-spacemolt-workspace",
107 "devDependencies": {
118 "@biomejs/biome": "^2.3.13",
12- "@types/blessed": "^0.1.21",
9+ },
10+ },
11+ "packages/client": {
12+ "name": "@spacemolt/client",
13+ "version": "0.1.0",
14+ "devDependencies": {
15+ "@types/bun": "latest",
1316 },
1417 },
1518 },
@@ -32,11 +35,13 @@
3235
3336 "@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@2.3.13", "", { "os": "win32", "cpu": "x64" }, "sha512-trDw2ogdM2lyav9WFQsdsfdVy1dvZALymRpgmWsvSez0BJzBjulhOT/t+wyKeh3pZWvwP3VMs1SoOKwO3wecMQ=="],
3437
35- "@types/blessed": ["@types/blessed@0.1.27", "", { "dependencies": { "@types/node": "*" } }, "sha512-ZOQGjLvWDclAXp0rW5iuUBXeD6Gr1PkitN7tj7/G8FCoSzTsij6OhXusOzMKhwrZ9YlL2Pmu0d6xJ9zVvk+Hsg=="],
38+ "@spacemolt/client": ["@spacemolt/client@workspace:packages/client"],
39+
40+ "@types/bun": ["@types/bun@1.3.8", "", { "dependencies": { "bun-types": "1.3.8" } }, "sha512-3LvWJ2q5GerAXYxO2mffLTqOzEu5qnhEAlh48Vnu8WQfnmSwbgagjGZV6BoHKJztENYEDn6QmVd949W4uESRJA=="],
3641
37- "@types/node": ["@types/node@25.1.0", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-t7frlewr6+cbx+9Ohpl0NOTKXZNV9xHRmNOvql47BFJKcEG1CxtxlPEEe+gR9uhVWM4DwhnvTF110mIL4yP9RA=="],
42+ "@types/node": ["@types/node@25.2.0", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-DZ8VwRFUNzuqJ5khrvwMXHmvPe+zGayJhr2CDNiKB1WBE1ST8Djl00D0IC4vvNmHMdj6DlbYRIaFE7WHjlDl5w=="],
3843
39- "blessed": ["blessed@0.1.81", "", { "bin": { "blessed": "./bin/tput.js" } }, "sha512-LoF5gae+hlmfORcG1M5+5XZi4LBmvlXTzwJWzUlPryN/SJdSflZvROM2TwkT0GMpq7oqT48NRd4GS7BiVBc5OQ=="],
44+ "bun-types": ["bun-types@1.3.8", "", { "dependencies": { "@types/node": "*" } }, "sha512-fL99nxdOWvV4LqjmC+8Q9kW3M4QTtTR1eePs94v5ctGqU8OeceWrSUaRw3JYb7tU3FkMIAjkueehrHPPPGKi5Q=="],
4045
4146 "undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
4247 }
client+0−1
@@ -1 +0,0 @@
1-Subproject commit 4c0027fd263bd687302942f295569a83f2a21991
package.json+10−12
@@ -1,19 +1,17 @@
11 {
2- "name": "ollama-spacemolt-player",
3- "version": "0.1.0",
2+ "name": "ollama-spacemolt-workspace",
3+ "version": "0.2.0",
44 "private": true,
5- "type": "module",
5+ "workspaces": [
6+ "packages/*"
7+ ],
68 "scripts": {
7- "ollama-play": "bun src/index.ts",
8- "swarm": "bun src/swarm.ts",
9- "biome:format": "biome format .",
10- "biome:lint": "biome lint ."
11- },
12- "dependencies": {
13- "blessed": "^0.1.81"
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"
1413 },
1514 "devDependencies": {
16- "@biomejs/biome": "^2.3.13",
17- "@types/blessed": "^0.1.21"
15+ "@biomejs/biome": "^2.3.13"
1816 }
1917 }
packages/client/README.md+45−0
@@ -0,0 +1,45 @@
1+# @spacemolt/client
2+
3+LLM-controlled WebSocket client for SpaceMolt game server.
4+
5+## Design Principles
6+
7+- **Direct connection**: Connect to `wss://game.spacemolt.com/ws` without intermediate libraries
8+- **Minimal abstraction**: Reduce layers between client and server
9+- **Neutral errors**: Use language from api.md, avoid behavioral bias
10+- **Single bias point**: Only the `prompt` field influences LLM behavior
11+
12+## Architecture
13+
14+### Database Schema
15+
16+Two tables using SQLite:
17+- `account_details`: credentials, username, id, hint, prompt
18+- `messages`: raw JSON server communication, id, tick, client/server sender enum
19+
20+### API Extensions
21+
22+Custom fields added to game server API:
23+- `prompt`: Generated at registration from character traits
24+- `hint`: Optional injected message, refreshed every tick
25+
26+### Instance Management
27+
28+Each running client has an independent database file:
29+- Pattern: `memory-{instance-id}.sqlite`
30+- Instance ID: 4-character random identifier
31+- Complete data separation between instances
32+
33+## CLI Interface
34+
35+(To be implemented in Milestone 2)
36+
37+## Development
38+
39+```bash
40+# Run checks (format, lint, test)
41+bun run check
42+
43+# Start client
44+bun run start
45+```
packages/client/package.json+17−0
@@ -0,0 +1,17 @@
1+{
2+ "name": "@spacemolt/client",
3+ "version": "0.1.0",
4+ "private": true,
5+ "type": "module",
6+ "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 .",
10+ "check:test": "bun test",
11+ "start": "bun src/index.ts"
12+ },
13+ "dependencies": {},
14+ "devDependencies": {
15+ "@types/bun": "latest"
16+ }
17+}
packages/client/tsconfig.json+9−0
@@ -0,0 +1,9 @@
1+{
2+ "extends": "../../tsconfig.json",
3+ "compilerOptions": {
4+ "outDir": "./dist",
5+ "rootDir": "./src"
6+ },
7+ "include": ["src/**/*", "tests/**/*"],
8+ "exclude": ["node_modules", "dist"]
9+}
scripts/generate-prompt-from-db.ts+0−1142
@@ -1,1142 +0,0 @@
1-// Generate full prompts from database for analysis
2-// Usage: bun run scripts/generate-prompt-from-db.ts <db-path> [options]
3-
4-import { Database } from "bun:sqlite";
5-import type { ClientState } from "../client/src/client";
6-import type { Snapshot } from "../src/memory";
7-import { type HistoryEntry, MemoryStore } from "../src/memory";
8-import { OllamaAgent } from "../src/ollama";
9-import {
10- buildActionPrompt,
11- buildLastActionResult,
12- buildSummaryPrompt,
13- type PromptContext,
14- type WorldSnapshot,
15-} from "../src/prompt";
16-import type {
17- AlignmentType,
18- Credentials,
19- PersonalityType,
20- SpeechStyleType,
21-} from "../src/types";
22-
23-// ============================================================================
24-// Types
25-// ============================================================================
26-
27-interface CliArgs {
28- dbPath: string;
29- count: number;
30- actionId: number | null;
31- outputPath: string;
32- verbose: boolean;
33-}
34-
35-interface StoredAction {
36- id: number;
37- ts: string;
38- tick: number;
39- action: string;
40- args: string | null;
41- model_raw: string | null;
42- thinking: string | null;
43-}
44-
45-interface AnalysisResult {
46- action: StoredAction;
47- prompt: string;
48- analysis: {
49- missingInfo: string[];
50- duplicates: DuplicateInfo[];
51- bias: BiasInfo[];
52- errorLeakage: ErrorInfo[];
53- structure: StructureInfo;
54- };
55-}
56-
57-interface DuplicateInfo {
58- text: string;
59- count: number;
60-}
61-
62-interface BiasInfo {
63- pattern: string;
64- matches: number;
65- context: string;
66-}
67-
68-interface ErrorInfo {
69- pattern: string;
70- matches: number;
71- context: string;
72-}
73-
74-interface StructureInfo {
75- length: number;
76- errors: string[];
77- warnings: string[];
78-}
79-
80-interface PromptComparison {
81- tick1: number;
82- tick2: number;
83- lengthDiff: number;
84- sectionsChanged: string[];
85- similarity: number;
86-}
87-
88-// ============================================================================
89-// CLI Argument Parsing
90-// ============================================================================
91-
92-function parseArgs(): CliArgs {
93- const args = process.argv.slice(2);
94-
95- if (args.length === 0 || args[0] === "--help" || args[0] === "-h") {
96- console.log(`
97-Usage: bun run scripts/generate-prompt-from-db.ts <db-path> [options]
98-
99-Options:
100- --count=N Number of recent actions to analyze (default: 3)
101- --output=PATH Output file path (default: auto-generated)
102- --action-id=ID Analyze specific action by ID instead of recent
103- --verbose Include extra debug information
104-
105-Examples:
106- bun run scripts/generate-prompt-from-db.ts memory-test.sqlite
107- bun run scripts/generate-prompt-from-db.ts memory-swarm-01.sqlite --count=5
108- bun run scripts/generate-prompt-from-db.ts memory-test.sqlite --action-id=42
109-`);
110- process.exit(0);
111- }
112-
113- const dbPath = args[0];
114- let count = 3;
115- let actionId: number | null = null;
116- let outputPath = "";
117- let verbose = false;
118-
119- for (const arg of args.slice(1)) {
120- if (arg.startsWith("--count=")) {
121- count = Number.parseInt(arg.split("=")[1]);
122- } else if (arg.startsWith("--action-id=")) {
123- actionId = Number.parseInt(arg.split("=")[1]);
124- } else if (arg.startsWith("--output=")) {
125- outputPath = arg.split("=")[1];
126- } else if (arg === "--verbose") {
127- verbose = true;
128- }
129- }
130-
131- // Auto-generate output path if not provided
132- if (!outputPath) {
133- const dbBasename = dbPath.split("/").pop()?.replace(".sqlite", "") ?? "db";
134- const timestamp = new Date()
135- .toISOString()
136- .replace(/[:.]/g, "-")
137- .slice(0, -5);
138- outputPath = `prompt-analysis-${dbBasename}-${timestamp}.md`;
139- }
140-
141- return { dbPath, count, actionId, outputPath, verbose };
142-}
143-
144-// ============================================================================
145-// Database Validation
146-// ============================================================================
147-
148-function validateDatabase(dbPath: string): void {
149- // Check if file exists
150- const file = Bun.file(dbPath);
151- if (!file.size) {
152- console.error(`Error: Database file not found: ${dbPath}`);
153- process.exit(1);
154- }
155-
156- // Try to open it
157- try {
158- const db = new Database(dbPath, { readonly: true });
159-
160- // Check for required tables
161- const tables = db
162- .query("SELECT name FROM sqlite_master WHERE type='table'")
163- .all() as { name: string }[];
164- const tableNames = tables.map((t) => t.name);
165-
166- const requiredTables = [
167- "actions",
168- "events",
169- "state_snapshots",
170- "credentials",
171- "llm_missions",
172- ];
173- for (const table of requiredTables) {
174- if (!tableNames.includes(table)) {
175- console.error(`Error: Missing required table: ${table}`);
176- db.close();
177- process.exit(1);
178- }
179- }
180-
181- // Check for tick column in actions table (required after migration)
182- const actionCols = db.query("PRAGMA table_info(actions)").all() as {
183- name: string;
184- }[];
185- const hasTickCol = actionCols.some((col) => col.name === "tick");
186-
187- if (!hasTickCol) {
188- console.error(
189- "Error: Database schema is outdated. Missing 'tick' column in actions table.",
190- );
191- console.error(
192- "Please run the bot once to trigger automatic migration, or generate new data.",
193- );
194- db.close();
195- process.exit(1);
196- }
197-
198- db.close();
199- } catch (error) {
200- console.error(
201- `Error: Failed to validate database: ${(error as Error).message}`,
202- );
203- process.exit(1);
204- }
205-}
206-
207-// ============================================================================
208-// State Reconstruction
209-// ============================================================================
210-
211-function getLatestSnapshot(db: Database, tick: number): Snapshot | null {
212- const row = db
213- .query(
214- "SELECT tick, player, ship, system, poi, base, nearby FROM state_snapshots WHERE tick <= ? ORDER BY tick DESC LIMIT 1",
215- )
216- .get(tick) as
217- | {
218- tick: number;
219- player: string;
220- ship: string;
221- system: string;
222- poi: string;
223- base: string;
224- nearby: string;
225- }
226- | undefined;
227-
228- if (!row) return null;
229-
230- return {
231- tick: row.tick,
232- player: JSON.parse(row.player),
233- ship: JSON.parse(row.ship),
234- system: JSON.parse(row.system),
235- poi: JSON.parse(row.poi),
236- base: JSON.parse(row.base),
237- nearby: JSON.parse(row.nearby),
238- };
239-}
240-
241-function parseSnapshotToState(snapshot: Snapshot): ClientState {
242- return {
243- connected: true,
244- authenticated: true,
245- player: snapshot.player,
246- ship: snapshot.ship,
247- system: snapshot.system,
248- poi: snapshot.poi,
249- base: snapshot.base,
250- nearby: snapshot.nearby,
251- inCombat: false, // We don't track this in snapshots
252- currentTick: snapshot.tick,
253- };
254-}
255-
256-async function reconstructState(
257- db: Database,
258- tick: number,
259-): Promise<ClientState | null> {
260- const snapshot = getLatestSnapshot(db, tick);
261- if (!snapshot) {
262- console.warn(`Warning: No snapshot found for tick ${tick}`);
263- return null;
264- }
265-
266- if (snapshot.tick !== tick) {
267- console.warn(
268- `Warning: Using snapshot from tick ${snapshot.tick} for action at tick ${tick}`,
269- );
270- }
271-
272- return parseSnapshotToState(snapshot);
273-}
274-
275-// ============================================================================
276-// History Reconstruction
277-// ============================================================================
278-
279-function getRecentHistory(
280- memory: MemoryStore,
281- tick: number,
282- limit: number,
283-): HistoryEntry[] {
284- const db = new Database(memory["db"]["filename"], { readonly: true });
285-
286- // Get actions before this tick
287- const actions = db
288- .query(
289- "SELECT ts, tick, action, args FROM actions WHERE tick < ? ORDER BY tick DESC LIMIT ?",
290- )
291- .all(tick, limit) as {
292- ts: string;
293- tick: number;
294- action: string;
295- args: string | null;
296- }[];
297-
298- // Get events before this tick
299- const events = db
300- .query(
301- "SELECT ts, tick, type, payload FROM events WHERE tick < ? ORDER BY tick DESC LIMIT ?",
302- )
303- .all(tick, limit) as {
304- ts: string;
305- tick: number;
306- type: string;
307- payload: string | null;
308- }[];
309-
310- db.close();
311-
312- // Combine and sort
313- const history: HistoryEntry[] = [
314- ...actions.map((a) => ({
315- kind: "action" as const,
316- ts: a.ts,
317- tick: a.tick,
318- action: a.action,
319- args: a.args,
320- })),
321- ...events.map((e) => ({
322- kind: "event" as const,
323- ts: e.ts,
324- tick: e.tick,
325- type: e.type,
326- payload: e.payload,
327- })),
328- ];
329-
330- history.sort((a, b) => {
331- if (a.tick !== b.tick) return a.tick - b.tick;
332- return new Date(a.ts).getTime() - new Date(b.ts).getTime();
333- });
334-
335- return history.reverse(); // Most recent first
336-}
337-
338-async function generateMemorySummary(
339- history: HistoryEntry[],
340- ollama: OllamaAgent,
341-): Promise<string> {
342- if (history.length === 0) {
343- return "(no recent activity)";
344- }
345-
346- try {
347- const summaryPrompt = buildSummaryPrompt(history, 0);
348- const summary = await ollama.generateText(summaryPrompt);
349- return summary || "(summary unavailable)";
350- } catch (error) {
351- console.warn(
352- `Warning: Failed to generate memory summary: ${(error as Error).message}`,
353- );
354- return "(summary generation failed)";
355- }
356-}
357-
358-// ============================================================================
Cut short: this commit's diff is over 1000 lines.
scripts/mock-prompt.ts+0−325
Cut short: this commit's diff is over 1000 lines.
src/actions.ts+0−353
Cut short: this commit's diff is over 1000 lines.
src/config.ts+0−133
Cut short: this commit's diff is over 1000 lines.
src/constants.ts+0−160
Cut short: this commit's diff is over 1000 lines.
src/game-state.ts+0−62
Cut short: this commit's diff is over 1000 lines.
src/index.ts+0−1025
Cut short: this commit's diff is over 1000 lines.
src/memory.ts+0−493
Cut short: this commit's diff is over 1000 lines.
src/ollama.ts+0−136
Cut short: this commit's diff is over 1000 lines.
src/output-interface.ts+0−14
Cut short: this commit's diff is over 1000 lines.
src/output/file-logger-output.ts+0−234
Cut short: this commit's diff is over 1000 lines.
src/output/tui-output.ts+0−47
Cut short: this commit's diff is over 1000 lines.
src/prompt.ts+0−1308
Cut short: this commit's diff is over 1000 lines.
src/registration.ts+0−696
Cut short: this commit's diff is over 1000 lines.
src/swarm.ts+0−347
Cut short: this commit's diff is over 1000 lines.
src/tui/formatters.ts+0−384
Cut short: this commit's diff is over 1000 lines.
src/tui/index.ts+0−497
Cut short: this commit's diff is over 1000 lines.
src/tui/layout.ts+0−200
Cut short: this commit's diff is over 1000 lines.
src/tui/panels/action-result.ts+0−345
Cut short: this commit's diff is over 1000 lines.
src/tui/panels/context.ts+0−57
Cut short: this commit's diff is over 1000 lines.
src/tui/panels/game-status.ts+0−186
Cut short: this commit's diff is over 1000 lines.
src/tui/panels/log.ts+0−155
Cut short: this commit's diff is over 1000 lines.
src/tui/panels/navigation.ts+0−138
Cut short: this commit's diff is over 1000 lines.
src/tui/panels/player.ts+0−69
Cut short: this commit's diff is over 1000 lines.
src/tui/panels/ship.ts+0−51
Cut short: this commit's diff is over 1000 lines.
src/tui/panels/tactical.ts+0−99
Cut short: this commit's diff is over 1000 lines.
src/tui/theme.ts+0−109
Cut short: this commit's diff is over 1000 lines.
src/tui/widgets.ts+0−74
Cut short: this commit's diff is over 1000 lines.
src/types.ts+0−97
Cut short: this commit's diff is over 1000 lines.
src/utils.ts+0−95
Cut short: this commit's diff is over 1000 lines.
test-arrow.ts+0−4
Cut short: this commit's diff is over 1000 lines.
test-border-alignment.ts+0−31
Cut short: this commit's diff is over 1000 lines.
test-solution-line.ts+0−25
Cut short: this commit's diff is over 1000 lines.
test-tui-render.ts+0−125
Cut short: this commit's diff is over 1000 lines.
tests/tui/panels/action-result.test.ts+0−129
Cut short: this commit's diff is over 1000 lines.
tests/tui/panels/game-status.test.ts+0−135
Cut short: this commit's diff is over 1000 lines.
tsconfig.json+6−6
Cut short: this commit's diff is over 1000 lines.
tui-render-test.txt+0−314
Cut short: this commit's diff is over 1000 lines.
tui_preview.png+0−0
Binary file, not shown.