xonecas.io
5875
Os

ollama-space-molt-player / commit bd2d8bc

feat: use tick instead of timestamps

xonecas2026-02-01 bd2d8bc57f1d7ba81c0d2ca7b57e299fcfd360c0 parent bd3e4d4

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

AGENTS.md+171−133
@@ -1,170 +1,208 @@
11 # Agent Guide for ollama-spacemolt-player
22
3-Purpose: help coding agents work safely and consistently in this repo.
3+Help coding agents work safely and consistently in this repo.
4+
5+## Important References
6+
7+**Game Server WebSocket API**: https://www.spacemolt.com/api.md
8+
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`.
412
513 ## Repo Snapshot
6-- Runtime: Bun (TypeScript, ESM).
7-- UI: terminal UI via `blessed`.
8-- LLM: local Ollama HTTP API.
9-- Data: SQLite via `bun:sqlite` at `memory-{name}.sqlite`.
10-- Game client: SpaceMolt reference client is a git submodule in `client/`.
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/`)
1120
1221 ## Key Paths
13-- App entry: `src/index.ts` (orchestrates client + LLM + memory + TUI).
14-- LLM client: `src/ollama.ts`.
15-- Prompts: `src/prompt.ts`.
16-- Memory store: `src/memory.ts`.
17-- Actions validation: `src/actions.ts`.
18-- TUI: `src/tui.ts`.
19-- Config: `src/config.ts` (env-driven settings).
20-
21-## Commands (Build / Lint / Test)
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
39+
40+## Commands
41+
2242 ### Install
23-- `bun install`
24-
25-### Run app
26-- `bun run ollama-play --name <instance-name>` (or `-n <instance-name>`)
27-- The `--name` argument is required and determines file paths:
28- - Memory DB (includes credentials): `memory-{name}.sqlite`
29-- Example: `bun run ollama-play --name alice` uses `memory-alice.sqlite`
30-- Optional character overrides (new registrations only):
31- - `--empire <empire>` or `-e` - Force empire: solarian, voidborn, crimson, nebula, outerrim
32- - `--alignment <alignment>` or `-a` - Force alignment: lawful, good, neutral, chaotic, evil
33- - `--personality <personality>` or `-p` - Force personality: cartographer, merchant, warrior, diplomat, pragmatist
34-- Example: `bun run ollama-play -n test-bot -e crimson -a evil -p warrior`
35-
36-### Run in non-interactive mode (for testing/debugging)
37-- `bun run ollama-play --name <instance-name> --non-interactive [--max-ticks <number>]`
38-- Runs without the blessed TUI; output is written to log files instead.
39-- Example: `bun run ollama-play --name test-bot --non-interactive --max-ticks 100`
40-
41-**Log files created:**
42-- `ui-{name}.log` - UI output with timestamps (game events, AI actions, state updates)
43-- `debug-{name}.log` - Debug information (full LLM prompts, raw responses, thinking)
44-
45-**Flags:**
46-- `--non-interactive` - Enable headless mode (no TUI, output to log files)
47-- `--max-ticks <number>` - Stop after N game ticks (optional; runs indefinitely if not set)
48-- Logs are truncated on each run (fresh logs per execution)
49-
50-### Reusing test accounts
51-- Prefer reusing the same instance names to avoid creating new accounts on every run.
52-- Credentials are stored in the instance SQLite DB and should not be committed.
53-
54-**Known test instances:**
55-- `test-cli-override` -> `memory-test-cli-override.sqlite`
56-
57-**Troubleshooting:**
58-- If you see `Invalid username or token`, delete the instance DB (`memory-{name}.sqlite`), then rerun to create a new account.
59-
60-### Format
61-- `bun run biome:format`
62-
63-### Lint
64-- `bun run biome:lint`
65-
66-### Build
67-- No build script configured. If you add one, document it here.
68-
69-### Tests
70-- Manual testing only (run the app and verify behavior).
71-- No test runner configured; single-test command is not available yet.
72-- If tests are added later, prefer a command that can target a file or test name.
73-
74-## Environment / Config
75-- `OLLAMA_URL` (default: `http://localhost:11434`)
76-- `OLLAMA_MODEL` (default: `qwen3:8b`)
77-- `OLLAMA_TEMPERATURE` (number, default: `0.5`)
78-- `OLLAMA_THINKING` (boolean, default: `true` - enables thinking mode for Qwen3)
79-- `OLLAMA_TIMEOUT_MS` is not present; timeout is configured in `src/config.ts` as `ollamaTimeoutMs`.
80-- `SPACEMOLT_URL` (default: `wss://game.spacemolt.com/ws`)
81-- `DEBUG` (string, enable TUI prompt pane when `true`)
82-- `MEMORY_DB` (default: `memory-{name}.sqlite`)
83-
84-## Cursor / Copilot Rules
85-- No Cursor rules found in `.cursor/rules/` or `.cursorrules`.
86-- No Copilot rules found in `.github/copilot-instructions.md`.
43+```bash
44+bun install
45+```
46+
47+### Run Single Bot (Interactive)
48+```bash
49+bun run ollama-play --name <instance-name>
50+```
51+
52+Required:
53+- `--name` or `-n`: Instance name (determines DB: `memory-{name}.sqlite`)
54+
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+- `--personality` or `-p`: cartographer, merchant, warrior, diplomat, pragmatist
59+- `--speech-style` or `-s`: mythic, punny, gritty, scholarly
60+
61+Examples:
62+```bash
63+bun run ollama-play -n alice
64+bun run ollama-play -n test-bot -e crimson -a evil -p warrior
65+```
66+
67+### Run Non-Interactive (Headless)
68+```bash
69+bun run ollama-play --name <instance-name> --non-interactive [--max-ticks <number>]
70+```
71+
72+Output:
73+- `ui-{name}.log` - UI output with timestamps
74+- `debug-{name}.log` - Debug info (prompts, responses, thinking)
75+
76+Example:
77+```bash
78+bun run ollama-play --name test-bot --non-interactive --max-ticks 100
79+```
80+
81+### Run Swarm
82+```bash
83+bun run swarm [--count 5] [--prefix swarm] [--empire <empire>] [--alignment <alignment>] [--personality <personality>] [--speech-style <style>]
84+```
85+
86+Defaults:
87+- Count: 5
88+- Prefix: swarm (creates swarm-01, swarm-02, etc.)
89+- Model: ministral-3:8b
90+- Thinking: false
91+
92+Example:
93+```bash
94+bun run swarm --count 10 --empire crimson --alignment evil --personality warrior
95+```
96+
97+### Format and Lint
98+```bash
99+bun run biome:format
100+bun run biome:lint
101+```
102+
103+### Testing
104+
105+Manual testing only. No test runner configured.
106+
107+Prefer reusing existing accounts:
108+- `test-cli-override` → `memory-test-cli-override.sqlite`
109+- `test-bot-1` → `memory-test-bot-1.sqlite`
110+- `swarm-01` through `swarm-05` → `memory-swarm-*.sqlite`
111+
112+If you see `Invalid username or token`, delete the instance DB and rerun.
113+
114+## Environment Variables
115+
116+- `OLLAMA_URL` - Ollama server URL (default: `http://localhost:11434`)
117+- `OLLAMA_MODEL` - Model name (default: `qwen3:8b`)
118+- `OLLAMA_TEMPERATURE` - Temperature (default: `0.5`)
119+- `OLLAMA_THINKING` - Enable thinking mode (default: `true`)
120+- `SPACEMOLT_URL` - Game WebSocket URL (default: `wss://game.spacemolt.com/ws`)
121+- `DEBUG` - Enable TUI prompt pane (default: `false`)
122+- `MEMORY_DB` - Override DB path (default: `memory-{name}.sqlite`)
123+
124+Timeout is configured in `src/config.ts` as `ollamaTimeoutMs` (60000ms).
87125
88126 ## Code Style Guidelines
89127
90-### Language and Modules
91-- TypeScript, ESM (`"type": "module"` in `package.json`).
92-- Prefer `import type` for type-only imports.
93-- Use explicit exports and named exports when possible.
94-
95128 ### Formatting
96-- Use Biome for formatting and linting.
97-- Keep formatting consistent with existing files (tabs for indent, semicolons, double quotes).
98-- Avoid manual reformatting; let Biome handle it.
99-
100-### Imports
101-- Order: external modules first, then local modules.
102-- Keep import lists stable; do not reorder unless needed for clarity.
103-- Prefer `import type` to avoid runtime type imports.
129+- Use Biome for formatting and linting
130+- Let Biome handle formatting; avoid manual changes
104131
105132 ### Naming Conventions
106-- Types/interfaces: `PascalCase`.
107-- Classes: `PascalCase`.
108-- Functions and variables: `camelCase`.
109-- Constants: `SCREAMING_SNAKE_CASE` for global constants; `camelCase` for local consts.
110-- File names: `lowercase` with `.ts`.
133+- Types/interfaces: `PascalCase`
134+- Classes: `PascalCase`
135+- Functions and variables: `camelCase`
136+- Global constants: `SCREAMING_SNAKE_CASE`
137+- Local constants: `camelCase`
138+- File names: `lowercase` with `.ts`
111139
112140 ### Types and Strictness
113-- `strict` TypeScript is enabled. Avoid `any`.
114-- Use `unknown` then narrow or validate.
115-- Prefer explicit return types for public functions.
116-- Prefer `null` over `undefined` when a value is intentionally absent (matches current code style).
141+- `strict` TypeScript enabled; avoid `any`
142+- Use `unknown` then narrow or validate
143+- Prefer explicit return types for public functions
144+- Prefer `null` over `undefined` for intentionally absent values
117145
118146 ### Error Handling
119-- Use `try/catch` around external I/O (HTTP, file, DB).
120-- Throw typed errors where appropriate (see `OllamaTimeoutError`).
121-- Validate external inputs; return structured errors (see `validateAction`).
122-- Log errors with context and keep user-facing messaging concise.
147+- Use `try/catch` around external I/O (HTTP, file, DB)
148+- Throw typed errors where appropriate (e.g., `OllamaTimeoutError`)
149+- Validate external inputs; return structured errors (e.g., `validateAction`)
150+- Log errors with context; keep user-facing messages concise
123151
124152 ### Side Effects and State
125-- Keep side effects in `src/index.ts`; helper modules should stay pure when possible.
126-- Avoid hidden global state; prefer explicit parameters.
127-- Use small, focused functions for validation and formatting.
153+- Keep side effects in `src/index.ts`; helper modules should be pure
154+- Avoid hidden global state; prefer explicit parameters
155+- Use small, focused functions for validation and formatting
128156
129157 ### Prompts and LLM Outputs
130-- LLM calls must expect malformed output; parse defensively.
131-- Enforce JSON-only responses and validate fields before use.
132-- Keep prompt updates in `src/prompt.ts`.
158+- LLM calls must expect malformed output; parse defensively
159+- Enforce JSON-only responses and validate fields before use
160+- Keep prompt updates in `src/prompt.ts`
133161
134162 ### TUI
135-- Use `blessed` widgets and keep rendering in `src/tui.ts`.
136-- Avoid adding Unicode-heavy UI unless needed (TUI uses `fullUnicode: false`).
163+- TUI is now in `src/output/tui-output.ts` and `src/tui/` directory
164+- Use `blessed` widgets; keep rendering in output modules
165+- Avoid Unicode-heavy UI unless needed (uses `fullUnicode: false`)
137166
138167 ### SQLite / Memory
139-- Centralize DB operations in `src/memory.ts`.
140-- Serialize JSON using helper functions; guard against JSON stringify errors.
141-- Keep text fields reasonably bounded (see `MAX_TEXT`).
168+- Centralize DB operations in `src/memory.ts`
169+- Serialize JSON using helper functions; guard against stringify errors
170+- Keep text fields reasonably bounded
142171
143172 ### Game Client
144-- Use the reference client from `client/`.
145-- Avoid changing `client/` unless the change is intended for the submodule.
173+- Use the reference client from `client/` submodule
174+- Do not modify `client/` unless the change is intended for upstream
146175
147176 ## Editing Safety
148-- Do not edit `memory.sqlite` or `memory-*.sqlite`.
149-- Do not commit secrets or credentials.
150-- Keep changes minimal and aligned with the current architecture.
177+
178+- Do not edit or commit `memory-*.sqlite` files
179+- Do not commit secrets or credentials
180+- Keep changes minimal and aligned with current architecture
181+- All DB files and logs are git-ignored
151182
152183 ## Conventions in This Repo
153-- Use small, focused helpers for formatting and validation.
154-- Prefer explicit `if` branches to implicit coercion.
155-- Use early returns for invalid states.
156-- Maintain descriptive log messages for TUI output.
184+
185+- Use small, focused helpers for formatting and validation
186+- Prefer explicit `if` branches over implicit coercion
187+- Use early returns for invalid states
188+- Maintain descriptive log messages for output
157189
158190 ## When Adding New Features
159-- Update prompts and validation together.
160-- Add to memory tracking only if it improves LLM context.
161-- Keep tick timing aligned with server tick (10s; local uses 11s).
191+
192+- Update prompts and validation together
193+- Add to memory tracking only if it improves LLM context
194+- Keep tick timing aligned with server tick (10s; local uses 11s)
195+- Update both `src/output/tui-output.ts` and `src/output/file-logger-output.ts` for UI changes
162196
163197 ## If You Add Tests Later
164-- Document the test framework and single-test command here.
165-- Prefer a runner that supports file and name filtering.
198+
199+- Document the test framework and single-test command here
200+- Prefer a runner that supports file and name filtering
166201
167202 ## Quick Review Checklist
168-- `bun run biome:lint`
169-- `bun run biome:format`
170-- Manual run: `bun run ollama-play`
203+
204+```bash
205+bun run biome:lint
206+bun run biome:format
207+bun run ollama-play --name test-bot --non-interactive --max-ticks 10
208+```
README.md+111−29
@@ -1,51 +1,133 @@
1-# Space Molt: Ollama player
1+# Space Molt: Ollama Player
22
3-Let a locally hosted LLM play [Space Molt](https://www.spacemolt.com/) to it's hearts desire.
3+Let a locally hosted LLM play [Space Molt](https://www.spacemolt.com/).
44
55 ![Screenshot](tui_preview.png)
66
7-## Tech
7+## Overview
88
9-It has the Space Molt [reference client](https://github.com/SpaceMolt/client) as submodule so we can use it as library. It's also our blueprint of what the LLM can do in the game.
10-It connects to the local ollama instance using http.
11-a simple sqlite is used with Bun.sql to preserve a running memory for the LLM
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
1214
13-> **Note:** Currently using a [fork of the reference client](https://github.com/sacenox/client/tree/fix/handle-multiple-json-per-frame) that includes a fix for parsing multiple JSON messages per WebSocket frame. This will be reverted to upstream once the [PR](https://github.com/SpaceMolt/client/pulls) is merged.
15+## Important Links
1416
15-## How
17+- **Game Server API**: https://www.spacemolt.com/api.md
18+- **Reference Client**: `client/` submodule (SpaceMolt client library)
1619
17-When the script starts,
20+## Tech Stack
1821
19-- Introduce the LLM to the game https://www.spacemolt.com/
20-- show the LLM the help menu from the reference client
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
2127
22-- we read credentials from sqlite. If we find one login.
23-- If there is not one, we prompt the llm to choose a name, faction, etc, and register a new account and login.
28+## Setup
2429
25-Now that we have a playable account.
30+```bash
31+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`)
2644
27-- Tell the LLM it's status and prompt, it for it's next action.
28-- Track it's status and actions in sql so we can include it in prompts as context.
29-- perform the action the LLM decided in Space Molt
30-- track the actions result in sql, so the result is included in the next prompt for action.
31-- wait 11 seconds. (server tick rate is 10s)
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
3250
33-## UI
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
55+```
56+
57+### Run in Non-Interactive Mode (Headless)
3458
35-A simple TUI with a status bar at the bottom with character information
36-A scrolling log of the LLM's actions and results.
37-Clean, readable and resizeable with simple colors.
59+For testing/debugging without TUI:
3860
39-## Swarm orchestrator
61+```bash
62+bun run ollama-play --name <instance-name> --non-interactive [--max-ticks <number>]
63+```
4064
41-Run a swarm of non-interactive bots (default count 5) with a fast model and no thinking:
65+Output is written to:
66+- `ui-{name}.log` - UI output with timestamps
67+- `debug-{name}.log` - Debug info (prompts, responses, thinking)
4268
69+Example:
70+```bash
71+bun run ollama-play --name test-bot --non-interactive --max-ticks 100
4372 ```
73+
74+### Run Swarm (Multiple Bots)
75+
76+```bash
4477 bun run swarm --count 5 --empire crimson --alignment evil --personality warrior
4578 ```
4679
47-Notes:
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`
4890
49-- Uses `OLLAMA_THINKING=false` and `OLLAMA_MODEL=ministral-3:8b` for each bot.
50-- Writes orchestration info to `swarm.log` only.
51-- Each bot still writes its own logs: `ui-<name>.log` and `debug-<name>.log`.
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+```
src/index.ts+88−47
@@ -130,7 +130,12 @@ function updateOutput(): void {
130130
131131 function captureActionResult(resultType: string, payload: unknown): void {
132132 if (gameState.pendingActionId === null) return;
133- memory.appendActionResult(gameState.pendingActionId, resultType, payload);
133+ memory.appendActionResult(
134+ gameState.pendingActionId,
135+ getCurrentTick(),
136+ resultType,
137+ payload,
138+ );
134139
135140 // Clear pending action for errors and mining_yield (which comes after ok)
136141 if (resultType === "error" || resultType === "mining_yield") {
@@ -172,10 +177,10 @@ function shouldStopForMaxTicks(allowFallbackCount: boolean): boolean {
172177 return fallbackTickCount >= config.maxTicks;
173178 }
174179
175-function getActionStamp(): number {
180+function getCurrentTick(): number {
176181 const tick = client.state.currentTick;
177182 if (typeof tick === "number" && Number.isFinite(tick)) return tick;
178- return Date.now();
183+ return 0;
179184 }
180185
181186 function getForumFollowUpStatus(): "unread" | "periodic" | null {
@@ -278,16 +283,17 @@ async function startActionLoop(): Promise<void> {
278283 config.maxContextActions,
279284 config.maxContextEvents,
280285 );
286+ const currentTick = getCurrentTick();
281287 let memorySummary = "(summary unavailable)";
282288 try {
283- const summaryPrompt = buildSummaryPrompt(recentHistory);
289+ const summaryPrompt = buildSummaryPrompt(recentHistory, currentTick);
284290 const summaryText = await ollama.generateText(summaryPrompt);
285291 memorySummary = summaryText || "(summary unavailable)";
286292 } catch (error) {
287293 const message = (error as Error).message;
288294 output.logDebug("SUMMARY_ERROR", message);
289295 }
290- const lastActionResult = buildLastActionResult(memory);
296+ const lastActionResult = buildLastActionResult(memory, currentTick);
291297 const recentActions = memory.getRecentActions(REPETITION_THRESHOLD);
292298 const repetitionWarning = detectRepetition(
293299 recentActions,
@@ -320,6 +326,8 @@ async function startActionLoop(): Promise<void> {
320326 memorySummary,
321327 lastActionResult,
322328 currentMission: gameState.currentMission,
329+ currentTick,
330+ memory,
323331 empire: client.state.player?.empire,
324332 alignment: gameState.credentials?.alignment,
325333 personality: gameState.credentials?.personality,
@@ -338,14 +346,14 @@ async function startActionLoop(): Promise<void> {
338346 const result = await ollama.generateJson(prompt);
339347 output.logDebug("LLM_RESPONSE_RAW", result.raw);
340348 if (result.thinking) {
341- output.log(formatAiThinking(result.thinking));
349+ output.log(formatAiThinking(result.thinking, getCurrentTick()));
342350 output.logDebug("LLM_THINKING", result.thinking);
343351 }
344352 const validation = validateAction(result.json);
345353 if (!validation.ok || !validation.action) {
346354 const message = `Invalid action from LLM: ${validation.error ?? "unknown"}`;
347- output.log(formatSystemMessage(message));
348- memory.appendEvent("llm_invalid_action", {
355+ output.log(formatSystemMessage(message, getCurrentTick()));
356+ memory.appendEvent(getCurrentTick(), "llm_invalid_action", {
349357 error: validation.error,
350358 raw: result.raw,
351359 });
@@ -362,8 +370,8 @@ async function startActionLoop(): Promise<void> {
362370 const message = target
363371 ? `Invalid action from LLM: Unknown nearby target: ${target}`
364372 : "Invalid action from LLM: Missing target_id";
365- output.log(formatSystemMessage(message));
366- memory.appendEvent("llm_invalid_action", {
373+ output.log(formatSystemMessage(message, getCurrentTick()));
374+ memory.appendEvent(getCurrentTick(), "llm_invalid_action", {
367375 error: message,
368376 raw: result.raw,
369377 });
@@ -373,7 +381,7 @@ async function startActionLoop(): Promise<void> {
373381
374382 const actionName = validation.action.action;
375383 const mission = validation.action.mission ?? null;
376- const actionStamp = getActionStamp();
384+ const actionStamp = getCurrentTick();
377385 if (actionName === "forum_post") {
378386 const title = String(validation.action.args?.title ?? "").trim();
379387 const category = String(validation.action.args?.category ?? "").trim();
@@ -392,7 +400,7 @@ async function startActionLoop(): Promise<void> {
392400 if (client.state.player?.username && mission) {
393401 gameState.currentMission = mission;
394402 memory.setMission(client.state.player.username, mission);
395- output.log(formatAiMission(mission));
403+ output.log(formatAiMission(mission, getCurrentTick()));
396404 updateOutput();
397405 }
398406 if (gameState.pendingActionId !== null) {
@@ -407,6 +415,7 @@ async function startActionLoop(): Promise<void> {
407415 gameState.pendingActionTimeout = null;
408416 }
409417 const actionId = memory.appendActionWithId(
418+ getCurrentTick(),
410419 actionName,
411420 validation.action.args ?? {},
412421 promptExcerpt,
@@ -432,8 +441,12 @@ async function startActionLoop(): Promise<void> {
432441 String(validation.action.args?.target_system ?? "").trim() || null;
433442 }
434443 dispatchAction(client, validation.action);
435- output.log(formatAiAction(actionName, validation.action.args));
436- memory.appendEvent("action_sent", { action: validation.action });
444+ output.log(
445+ formatAiAction(actionName, validation.action.args, getCurrentTick()),
446+ );
447+ memory.appendEvent(getCurrentTick(), "action_sent", {
448+ action: validation.action,
449+ });
437450
438451 if (actionName === "travel") {
439452 client.getSystem();
@@ -443,12 +456,17 @@ async function startActionLoop(): Promise<void> {
443456 const message = (error as Error).message;
444457 if (error instanceof OllamaTimeoutError) {
445458 output.log(
446- formatSystemMessage(`LLM timeout: ${message}. Retrying next tick.`),
459+ formatSystemMessage(
460+ `LLM timeout: ${message}. Retrying next tick.`,
461+ getCurrentTick(),
462+ ),
447463 );
448- memory.appendEvent("llm_timeout", { message });
464+ memory.appendEvent(getCurrentTick(), "llm_timeout", { message });
449465 } else {
450- output.log(formatSystemMessage(`Loop error: ${message}`));
451- memory.appendEvent("loop_error", { message });
466+ output.log(
467+ formatSystemMessage(`Loop error: ${message}`, getCurrentTick()),
468+ );
469+ memory.appendEvent(getCurrentTick(), "loop_error", { message });
452470 }
453471 }
454472
@@ -476,21 +494,24 @@ process.on("SIGTERM", shutdown);
476494 client.on("raw_message", (data: { type: string; payload: unknown }) => {
477495 const rawType = String(data.type ?? "");
478496 if (!rawType) return;
479- memory.appendEvent(`raw_${rawType}`, data.payload);
497+ memory.appendEvent(getCurrentTick(), `raw_${rawType}`, data.payload);
480498 if (rawType.startsWith("forum_") || rawType === "mining_yield") {
481499 captureActionResult(rawType, data.payload);
482- memory.appendEvent(rawType, data.payload);
500+ memory.appendEvent(getCurrentTick(), rawType, data.payload);
483501 }
484502 });
485503
486504 client.on<WelcomePayload>("welcome", async (data) => {
487- output.log(formatWelcome(data));
488- if (data.motd) output.log(formatMotd(data.motd));
489- memory.appendEvent("welcome", data);
505+ output.log(formatWelcome(data, getCurrentTick()));
506+ if (data.motd) output.log(formatMotd(data.motd, getCurrentTick()));
507+ memory.appendEvent(getCurrentTick(), "welcome", data);
490508
491509 if (gameState.credentials) {
492510 output.log(
493- formatSystemMessage(`Auto-login as ${gameState.credentials.username}`),
511+ formatSystemMessage(
512+ `Auto-login as ${gameState.credentials.username}`,
513+ getCurrentTick(),
514+ ),
494515 );
495516 client.login(gameState.credentials.username, gameState.credentials.token);
496517 } else {
@@ -505,18 +526,26 @@ client.on<WelcomePayload>("welcome", async (data) => {
505526 });
506527
507528 client.on<RegisteredPayload>("registered", (data) => {
508- memory.appendEvent("registered", data);
529+ memory.appendEvent(getCurrentTick(), "registered", data);
509530
510531 if (!data.token) {
511532 output.log(
512- formatSystemMessage("FATAL: Server sent registered event without token"),
533+ formatSystemMessage(
534+ "FATAL: Server sent registered event without token",
535+ getCurrentTick(),
536+ ),
513537 );
514538 output.logDebug("REGISTERED_NO_TOKEN", JSON.stringify(data, null, 2));
515539 shutdown();
516540 return;
517541 }
518542
519- output.log(formatSystemMessage("Registration successful - token received"));
543+ output.log(
544+ formatSystemMessage(
545+ "Registration successful - token received",
546+ getCurrentTick(),
547+ ),
548+ );
520549 output.logDebug("REGISTERED_PAYLOAD", JSON.stringify(data, null, 2));
521550
522551 if (gameState.pendingRegistration) {
@@ -525,8 +554,8 @@ client.on<RegisteredPayload>("registered", (data) => {
525554 });
526555
527556 client.on<LoggedInPayload>("logged_in", async (data) => {
528- output.log(formatLoggedIn(data));
529- memory.appendEvent("logged_in", data);
557+ output.log(formatLoggedIn(data, getCurrentTick()));
558+ memory.appendEvent(getCurrentTick(), "logged_in", data);
530559 output.logDebug("LOGGED_IN_PAYLOAD", JSON.stringify(data, null, 2));
531560
532561 // CASE 1: New registration - save credentials
@@ -537,6 +566,7 @@ client.on<LoggedInPayload>("logged_in", async (data) => {
537566 output.log(
538567 formatSystemMessage(
539568 "FATAL: Logged in but no token was captured from registered event",
569+ getCurrentTick(),
540570 ),
541571 );
542572 shutdown();
@@ -563,6 +593,7 @@ client.on<LoggedInPayload>("logged_in", async (data) => {
563593 output.log(
564594 formatSystemMessage(
565595 `Credentials saved for ${gameState.pendingRegistration.username}`,
596+ getCurrentTick(),
566597 ),
567598 );
568599 gameState.pendingRegistration = null;
@@ -570,6 +601,7 @@ client.on<LoggedInPayload>("logged_in", async (data) => {
570601 output.log(
571602 formatSystemMessage(
572603 `FATAL: Failed to save credentials: ${(err as Error).message}`,
604+ getCurrentTick(),
573605 ),
574606 );
575607 shutdown();
@@ -583,17 +615,19 @@ client.on<LoggedInPayload>("logged_in", async (data) => {
583615
584616 client.on<ErrorPayload>("error", (data) => {
585617 captureActionResult("error", data);
586- output.log(formatError(data));
587- memory.appendEvent("error", data);
618+ output.log(formatError(data, getCurrentTick()));
619+ memory.appendEvent(getCurrentTick(), "error", data);
588620 if (data.code === "invalid_credentials") {
589621 output.log(
590622 formatSystemMessage(
591623 "FATAL: Invalid credentials. The saved token is invalid or expired.",
624+ getCurrentTick(),
592625 ),
593626 );
594627 output.log(
595628 formatSystemMessage(
596629 `Delete ${config.memoryPath} and run again to create a new account.`,
630+ getCurrentTick(),
597631 ),
598632 );
599633 shutdown();
@@ -610,6 +644,7 @@ client.on<ErrorPayload>("error", (data) => {
610644 output.log(
611645 formatSystemMessage(
612646 "Username taken. Requesting a new registration name...",
647+ getCurrentTick(),
613648 ),
614649 );
615650 gameState.pendingRegistration = null;
@@ -626,6 +661,7 @@ client.on<ErrorPayload>("error", (data) => {
626661 output.log(
627662 formatSystemMessage(
628663 "Username taken repeatedly. Falling back to random name.",
664+ getCurrentTick(),
629665 ),
630666 );
631667 const fallback = `molt-bot-${Math.floor(Math.random() * 10000)}`;
@@ -648,7 +684,7 @@ client.on<ErrorPayload>("error", (data) => {
648684 });
649685
650686 client.on<StateUpdatePayload>("state_update", async (data) => {
651- memory.appendEvent("state_update", data);
687+ memory.appendEvent(getCurrentTick(), "state_update", data);
652688
653689 // Ignore state updates before authentication
654690 if (!client.state.authenticated) {
@@ -674,7 +710,10 @@ client.on<StateUpdatePayload>("state_update", async (data) => {
674710 const diff = data.player.credits - (gameState.lastCredits ?? 0);
675711 const sign = diff > 0 ? "+" : "";
676712 output.log(
677- formatSystemMessage(`Credits: ${data.player.credits} (${sign}${diff})`),
713+ formatSystemMessage(
714+ `Credits: ${data.player.credits} (${sign}${diff})`,
715+ getCurrentTick(),
716+ ),
678717 );
679718 gameState.lastCredits = data.player.credits;
680719 }
@@ -686,9 +725,9 @@ client.on<StateUpdatePayload>("state_update", async (data) => {
686725
687726 // Log combat state changes
688727 if (gameState.inCombat && !wasInCombat) {
689- output.log(formatSystemMessage("COMBAT STARTED"));
728+ output.log(formatSystemMessage("COMBAT STARTED", getCurrentTick()));
690729 } else if (!gameState.inCombat && wasInCombat) {
691- output.log(formatSystemMessage("Combat ended"));
730+ output.log(formatSystemMessage("Combat ended", getCurrentTick()));
692731 }
693732
694733 updateOutput();
@@ -696,20 +735,20 @@ client.on<StateUpdatePayload>("state_update", async (data) => {
696735 });
697736
698737 client.on<ChatMessage>("chat_message", (data) => {
699- output.log(formatChatMessage(data));
700- memory.appendEvent("chat_message", data);
738+ output.log(formatChatMessage(data, getCurrentTick()));
739+ memory.appendEvent(getCurrentTick(), "chat_message", data);
701740 });
702741
703742 client.on<ScanResultPayload>("scan_result", (data) => {
704743 captureActionResult("scan_result", data);
705- output.log(formatScanResult(data));
706- memory.appendEvent("scan_result", data);
744+ output.log(formatScanResult(data, getCurrentTick()));
745+ memory.appendEvent(getCurrentTick(), "scan_result", data);
707746 });
708747
709748 client.on("mining_yield", (data: Record<string, unknown>) => {
710749 captureActionResult("mining_yield", data);
711- output.log(formatMiningYield(data));
712- memory.appendEvent("mining_yield", data);
750+ output.log(formatMiningYield(data, getCurrentTick()));
751+ memory.appendEvent(getCurrentTick(), "mining_yield", data);
713752 });
714753
715754 client.on("ok", (data: Record<string, unknown>) => {
@@ -718,8 +757,8 @@ client.on("ok", (data: Record<string, unknown>) => {
718757 jumpTarget: gameState.lastJumpTarget,
719758 travelTarget: gameState.lastTravelTarget,
720759 };
721- output.log(formatOk(data, okContext));
722- memory.appendEvent("ok", data);
760+ output.log(formatOk(data, okContext, getCurrentTick()));
761+ memory.appendEvent(getCurrentTick(), "ok", data);
723762 updateWorldSnapshotFromOk(data);
724763
725764 const action = typeof data.action === "string" ? data.action : null;
@@ -755,16 +794,18 @@ client.on("ok", (data: Record<string, unknown>) => {
755794
756795 client.on("version_info", (data: Record<string, unknown>) => {
757796 const version = String(data.version ?? "unknown");
758- output.log(formatSystemMessage(`Version: ${version}`));
759- memory.appendEvent("version_info", data);
797+ output.log(formatSystemMessage(`Version: ${version}`, getCurrentTick()));
798+ memory.appendEvent(getCurrentTick(), "version_info", data);
760799 });
761800
762801 gameState.credentials = await loadCredentials();
763802
764803 console.log(`Instance: ${config.instanceName}`);
765804 console.log(`DB: ${config.memoryPath}`);
766-output.log(formatSystemMessage(`Instance: ${config.instanceName}`));
767-output.log(formatSystemMessage(`DB: ${config.memoryPath}`));
805+output.log(
806+ formatSystemMessage(`Instance: ${config.instanceName}`, getCurrentTick()),
807+);
808+output.log(formatSystemMessage(`DB: ${config.memoryPath}`, getCurrentTick()));
768809
769810 await client.connect();
770811 updateOutput();
src/memory.ts+97−33
@@ -19,6 +19,7 @@ export interface Snapshot {
1919 export interface StoredAction {
2020 id: number;
2121 ts: string;
22+ tick: number;
2223 action: string;
2324 args: string | null;
2425 prompt_excerpt: string | null;
@@ -28,12 +29,14 @@ export interface StoredAction {
2829 export interface StoredEvent {
2930 id: number;
3031 ts: string;
32+ tick: number;
3133 type: string;
3234 payload: string | null;
3335 }
3436
3537 export interface ActionResult {
3638 ts: string;
39+ tick: number;
3740 result_type: string;
3841 payload: string | null;
3942 }
@@ -42,12 +45,14 @@ export type HistoryEntry =
4245 | {
4346 kind: "action";
4447 ts: string;
48+ tick: number;
4549 action: string;
4650 args: string | null;
4751 }
4852 | {
4953 kind: "event";
5054 ts: string;
55+ tick: number;
5156 type: string;
5257 payload: string | null;
5358 };
@@ -64,7 +69,7 @@ export class MemoryStore {
6469
6570 private init(): void {
6671 // Run migrations BEFORE creating tables to handle renames
67- this.migrate();
72+ this.migratePreCreate();
6873
6974 this.db.exec(`
7075 CREATE TABLE IF NOT EXISTS actions (
@@ -116,32 +121,21 @@ export class MemoryStore {
116121 speech_style TEXT NOT NULL DEFAULT 'mythic'
117122 );
118123 `);
119- }
120124
121- private migrate(): void {
122- // Add alignment + speech_style columns if they don't exist (for existing DBs)
123- const columns = this.db.query("PRAGMA table_info(credentials)").all() as {
124- name: string;
125- }[];
126- const hasAlignment = columns.some((col) => col.name === "alignment");
127- const hasSpeechStyle = columns.some((col) => col.name === "speech_style");
128- if (!hasAlignment) {
129- this.db.exec(
130- "ALTER TABLE credentials ADD COLUMN alignment TEXT NOT NULL DEFAULT 'neutral'",
131- );
132- }
133- if (!hasSpeechStyle) {
134- this.db.exec(
135- "ALTER TABLE credentials ADD COLUMN speech_style TEXT NOT NULL DEFAULT 'mythic'",
136- );
137- }
125+ // Run column additions AFTER tables are created
126+ this.migratePostCreate();
127+ }
138128
139- // Migrate llm_goals to llm_missions
129+ private migratePreCreate(): void {
130+ // Check which tables exist
140131 const tables = this.db
141132 .query("SELECT name FROM sqlite_master WHERE type='table'")
142133 .all() as { name: string }[];
143- const hasGoalsTable = tables.some((t) => t.name === "llm_goals");
144- const hasMissionsTable = tables.some((t) => t.name === "llm_missions");
134+ const tableNames = tables.map((t) => t.name);
135+
136+ // Migrate llm_goals to llm_missions
137+ const hasGoalsTable = tableNames.includes("llm_goals");
138+ const hasMissionsTable = tableNames.includes("llm_missions");
145139
146140 if (hasGoalsTable && !hasMissionsTable) {
147141 // Rename table from llm_goals to llm_missions
@@ -160,6 +154,62 @@ export class MemoryStore {
160154 }
161155 }
162156
157+ private migratePostCreate(): void {
158+ // Add alignment + speech_style columns if they don't exist (for existing DBs)
159+ const credColumns = this.db
160+ .query("PRAGMA table_info(credentials)")
161+ .all() as {
162+ name: string;
163+ }[];
164+ const hasAlignment = credColumns.some((col) => col.name === "alignment");
165+ const hasSpeechStyle = credColumns.some(
166+ (col) => col.name === "speech_style",
167+ );
168+ if (!hasAlignment) {
169+ this.db.exec(
170+ "ALTER TABLE credentials ADD COLUMN alignment TEXT NOT NULL DEFAULT 'neutral'",
171+ );
172+ }
173+ if (!hasSpeechStyle) {
174+ this.db.exec(
175+ "ALTER TABLE credentials ADD COLUMN speech_style TEXT NOT NULL DEFAULT 'mythic'",
176+ );
177+ }
178+
179+ // Add tick columns to actions, action_results, and events tables
180+ const actionColumns = this.db.query("PRAGMA table_info(actions)").all() as {
181+ name: string;
Cut short: this commit's diff is over 1000 lines.
src/prompt.ts+53−35
Cut short: this commit's diff is over 1000 lines.
src/tui/formatters.ts+86−43
Cut short: this commit's diff is over 1000 lines.