xonecas.io
5875
Os

ollama-space-molt-player / commit 8b1948a

refactor: consolidate context tracking and swarm mode improvements

- Enhance memory with dynamic context snapshots and decision tracking
- Refactor swarm mode logic with improved state management
- Expand action prompt with faction context and recovery guidance
- Improve TUI display of context and state information

xonecas2026-02-01 8b1948a25a42abcce4127e346fcda7180402e2f1 parent f58d236

11 files changed

src/actions.ts+11−8
@@ -1,10 +1,10 @@
11 import type { SpaceMoltClient } from "../client/src/client";
22 import type { EmpireID } from "../client/src/types";
3-import { ACTION_DEFINITIONS, MAX_GOAL_LENGTH } from "./constants";
3+import { ACTION_DEFINITIONS, MAX_MISSION_LENGTH } from "./constants";
44 import type { ActionDecision } from "./types";
55 import { isValidEmpire } from "./utils";
66
7-export { MAX_GOAL_LENGTH, PERSONALITY_ARCHETYPES } from "./constants";
7+export { MAX_MISSION_LENGTH, PERSONALITY_ARCHETYPES } from "./constants";
88 export type { ActionDecision, PersonalityType } from "./types";
99
1010 export function validateAction(decision: unknown): {
@@ -16,12 +16,15 @@ export function validateAction(decision: unknown): {
1616 return { ok: false, error: "Action is not an object" };
1717 }
1818
19- const goal = String((decision as ActionDecision).goal ?? "").trim();
20- if (!goal) {
21- return { ok: false, error: "Missing goal" };
19+ const mission = String((decision as ActionDecision).mission ?? "").trim();
20+ if (!mission) {
21+ return { ok: false, error: "Missing mission" };
2222 }
23- if (goal.length > MAX_GOAL_LENGTH) {
24- return { ok: false, error: `Goal exceeds ${MAX_GOAL_LENGTH} characters` };
23+ if (mission.length > MAX_MISSION_LENGTH) {
24+ return {
25+ ok: false,
26+ error: `Mission exceeds ${MAX_MISSION_LENGTH} characters`,
27+ };
2528 }
2629
2730 const action = String(
@@ -221,7 +224,7 @@ export function validateAction(decision: unknown): {
221224 }
222225 }
223226
224- return { ok: true, action: { action, args, goal } };
227+ return { ok: true, action: { action, args, mission } };
225228 }
226229
227230 export function dispatchAction(
src/constants.ts+1−1
@@ -5,7 +5,7 @@ import type {
55 SpeechStyleType,
66 } from "./types";
77
8-export const MAX_GOAL_LENGTH = 120;
8+export const MAX_MISSION_LENGTH = 120;
99
1010 export interface AlignmentInfo {
1111 name: string;
src/game-state.ts+1−1
@@ -13,7 +13,7 @@ export class GameState {
1313 jumpInProgress = false;
1414 lastJumpTarget: string | null = null;
1515
16- currentGoal: string | null = null;
16+ currentMission: string | null = null;
1717
1818 // Tracking for changes
1919 lastSystemId: string | null = null;
src/index.ts+9−9
@@ -26,7 +26,7 @@ import {
2626 import { runRegistrationFlow } from "./registration";
2727 import {
2828 formatAiAction,
29- formatAiGoal,
29+ formatAiMission,
3030 formatAiThinking,
3131 formatChatMessage,
3232 formatError,
@@ -122,7 +122,7 @@ function updateOutput(): void {
122122 travelTarget: gameState.lastTravelTarget,
123123 jumping: gameState.jumpInProgress,
124124 jumpTarget: gameState.lastJumpTarget,
125- goal: gameState.currentGoal,
125+ mission: gameState.currentMission,
126126 inCombat: gameState.inCombat,
127127 context: gameState.tuiContext,
128128 });
@@ -319,7 +319,7 @@ async function startActionLoop(): Promise<void> {
319319 recentHistory,
320320 memorySummary,
321321 lastActionResult,
322- currentGoal: gameState.currentGoal,
322+ currentMission: gameState.currentMission,
323323 empire: client.state.player?.empire,
324324 alignment: gameState.credentials?.alignment,
325325 personality: gameState.credentials?.personality,
@@ -372,7 +372,7 @@ async function startActionLoop(): Promise<void> {
372372 }
373373
374374 const actionName = validation.action.action;
375- const goal = validation.action.goal ?? null;
375+ const mission = validation.action.mission ?? null;
376376 const actionStamp = getActionStamp();
377377 if (actionName === "forum_post") {
378378 const title = String(validation.action.args?.title ?? "").trim();
@@ -389,10 +389,10 @@ async function startActionLoop(): Promise<void> {
389389 gameState.lastForumThreadReadAt = actionStamp;
390390 }
391391 }
392- if (client.state.player?.username && goal) {
393- gameState.currentGoal = goal;
394- memory.setGoal(client.state.player.username, goal);
395- output.log(formatAiGoal(goal));
392+ if (client.state.player?.username && mission) {
393+ gameState.currentMission = mission;
394+ memory.setMission(client.state.player.username, mission);
395+ output.log(formatAiMission(mission));
396396 updateOutput();
397397 }
398398 if (gameState.pendingActionId !== null) {
@@ -801,7 +801,7 @@ function initializeSessionFromLoggedIn(data: LoggedInPayload): void {
801801 }
802802
803803 gameState.lastDocked = Boolean(data.player.docked_at_base);
804- gameState.currentGoal = memory.getLatestGoal(data.player.username);
804+ gameState.currentMission = memory.getLatestMission(data.player.username);
805805
806806 // Fetch base info if docked
807807 if (data.player.docked_at_base) {
src/memory.ts+38−11
@@ -63,6 +63,9 @@ export class MemoryStore {
6363 }
6464
6565 private init(): void {
66+ // Run migrations BEFORE creating tables to handle renames
67+ this.migrate();
68+
6669 this.db.exec(`
6770 CREATE TABLE IF NOT EXISTS actions (
6871 id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -86,11 +89,11 @@ export class MemoryStore {
8689 type TEXT NOT NULL,
8790 payload TEXT
8891 );
89- CREATE TABLE IF NOT EXISTS llm_goals (
92+ CREATE TABLE IF NOT EXISTS llm_missions (
9093 id INTEGER PRIMARY KEY AUTOINCREMENT,
9194 ts TEXT NOT NULL,
9295 username TEXT NOT NULL,
93- goal TEXT NOT NULL
96+ mission TEXT NOT NULL
9497 );
9598 CREATE TABLE IF NOT EXISTS state_snapshots (
9699 id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -113,7 +116,6 @@ export class MemoryStore {
113116 speech_style TEXT NOT NULL DEFAULT 'mythic'
114117 );
115118 `);
116- this.migrate();
117119 }
118120
119121 private migrate(): void {
@@ -133,6 +135,29 @@ export class MemoryStore {
133135 "ALTER TABLE credentials ADD COLUMN speech_style TEXT NOT NULL DEFAULT 'mythic'",
134136 );
135137 }
138+
139+ // Migrate llm_goals to llm_missions
140+ const tables = this.db
141+ .query("SELECT name FROM sqlite_master WHERE type='table'")
142+ .all() as { name: string }[];
143+ const hasGoalsTable = tables.some((t) => t.name === "llm_goals");
144+ const hasMissionsTable = tables.some((t) => t.name === "llm_missions");
145+
146+ if (hasGoalsTable && !hasMissionsTable) {
147+ // Rename table from llm_goals to llm_missions
148+ this.db.exec("ALTER TABLE llm_goals RENAME TO llm_missions");
149+ }
150+
151+ // If llm_missions exists, check if it needs the column renamed
152+ if (hasMissionsTable || hasGoalsTable) {
153+ const missionColumns = this.db
154+ .query("PRAGMA table_info(llm_missions)")
155+ .all() as { name: string }[];
156+ const hasGoalColumn = missionColumns.some((col) => col.name === "goal");
157+ if (hasGoalColumn) {
158+ this.db.exec("ALTER TABLE llm_missions RENAME COLUMN goal TO mission");
159+ }
160+ }
136161 }
137162
138163 getCredentials(): Credentials | null {
@@ -247,20 +272,22 @@ export class MemoryStore {
247272 );
248273 }
249274
250- setGoal(username: string, goal: string): void {
275+ setMission(username: string, mission: string): void {
251276 this.db
252- .query("INSERT INTO llm_goals (ts, username, goal) VALUES (?, ?, ?)")
253- .run(nowIso(), username, goal);
277+ .query(
278+ "INSERT INTO llm_missions (ts, username, mission) VALUES (?, ?, ?)",
279+ )
280+ .run(nowIso(), username, mission);
254281 }
255282
256- getLatestGoal(username: string): string | null {
283+ getLatestMission(username: string): string | null {
257284 const row = this.db
258285 .query(
259- "SELECT goal FROM llm_goals WHERE username = ? ORDER BY id DESC LIMIT 1",
286+ "SELECT mission FROM llm_missions WHERE username = ? ORDER BY id DESC LIMIT 1",
260287 )
261- .get(username) as { goal?: string } | undefined;
262- if (!row || !row.goal) return null;
263- return row.goal;
288+ .get(username) as { mission?: string } | undefined;
289+ if (!row || !row.mission) return null;
290+ return row.mission;
264291 }
265292
266293 getRecentActions(limit: number): StoredAction[] {
src/output/file-logger-output.ts+1−1
@@ -91,7 +91,7 @@ export class FileLoggerOutput implements OutputInterface {
9191 this.state.travelTarget = data.travelTarget;
9292 if (data.jumping !== undefined) this.state.jumping = data.jumping;
9393 if (data.jumpTarget !== undefined) this.state.jumpTarget = data.jumpTarget;
94- if (data.goal !== undefined) this.state.goal = data.goal;
94+ if (data.mission !== undefined) this.state.mission = data.mission;
9595 if (data.inCombat !== undefined) this.state.inCombat = data.inCombat;
9696 if (data.combatTarget !== undefined)
9797 this.state.combatTarget = data.combatTarget;
src/prompt.ts+34−13
@@ -2,7 +2,7 @@ import type { ClientState } from "../client/src/client";
22 import type { Base, EmpireID, POI, System } from "../client/src/types";
33 import {
44 ALIGNMENT_DESCRIPTIONS,
5- MAX_GOAL_LENGTH,
5+ MAX_MISSION_LENGTH,
66 PERSONALITY_ARCHETYPES,
77 SPEECH_STYLE_DESCRIPTIONS,
88 } from "./constants";
@@ -14,7 +14,7 @@ export interface PromptContext {
1414 worldSnapshot?: WorldSnapshot;
1515 recentHistory: HistoryEntry[];
1616 memorySummary?: string | null;
17- currentGoal: string | null;
17+ currentMission: string | null;
1818 empire?: EmpireID;
1919 alignment?: AlignmentType;
2020 personality?: PersonalityType;
@@ -212,8 +212,8 @@ export function buildActionPrompt(context: PromptContext): string {
212212 : "No actions yet.";
213213 const forumContextBlock = formatForumContext(context.recentHistory);
214214 const helpBlock = `\nGAME INFORMATION:\n${HELP_TEXT}`;
215- const goalText = context.currentGoal?.trim()
216- ? context.currentGoal.trim()
215+ const missionText = context.currentMission?.trim()
216+ ? context.currentMission.trim()
217217 : "(none yet)";
218218 const empire = context.empire ?? "solarian";
219219 const alignment = context.alignment ?? "neutral";
@@ -225,8 +225,8 @@ export function buildActionPrompt(context: PromptContext): string {
225225 const warningBlock = context.repetitionWarning
226226 ? `
227227 REPETITION DETECTED: You performed "${context.repetitionWarning.action}" ${context.repetitionWarning.count} times in a row without progress.
228-STOP this action immediately. Choose something DIFFERENT or set a new goal.
229-If your goal is blocked or impossible, abandon it now.
228+STOP this action immediately. Choose something DIFFERENT or set a new mission.
229+If your mission is blocked or impossible, abandon it now.
230230 `
231231 : "";
232232 const strandedBlock = isStranded(context.state, context.worldSnapshot)
@@ -234,7 +234,7 @@ If your goal is blocked or impossible, abandon it now.
234234 STRANDED: Fuel is 0 and there is no base at this POI.
235235 Travel/jump/refuel/dock will FAIL. Do NOT repeat those actions.
236236 Ask for help or wait. Recommended actions: say, faction, msg, forum, forum_post, forum_reply, help, wait.
237-Example: {"goal":"Request rescue","action":"faction","args":{"content":"Stranded with 0 fuel at current system/POI. Need assistance."}}
237+Example: {"mission":"Request rescue from faction members","action":"faction","args":{"content":"Stranded with 0 fuel at current system/POI. Need assistance."}}
238238 `
239239 : "";
240240
@@ -244,12 +244,33 @@ Agents explore, trade, battle, and build empires in a living universe with emerg
244244 The game emphasizes real-time AI fleet combat, ongoing discoveries of new systems, and shifting trade routes and alliances.
245245
246246 HOW TO PLAY:
247-Use all of the provided information to consider your goal. Then decide how to act next.
247+Use all of the provided information to consider your mission. Then decide how to act next.
248248 Respond ONLY with a single JSON object. No extra text.
249249 ${helpBlock}
250250
251-YOUR GOAL:
252-${goalText}
251+YOUR MISSION:
252+${missionText}
253+
254+MISSION GUIDELINES:
255+A mission is a multi-step objective that guides several actions over multiple ticks.
256+It should describe WHAT you're working toward and WHY, not just the next immediate action.
257+
258+STRUCTURE YOUR MISSION:
259+Think: "I'm doing [short-term activities] to eventually [achieve long-term goal]"
260+- Good: Describes the purpose behind multiple actions
261+- Bad: Just names the next single action you'll take
262+
263+MISSION vs ACTION:
264+- Mission: Multi-step purpose that persists (example: "gathering resources to fund my next venture")
265+- Action: Single step you're about to take (example: "dock")
266+
267+UPDATE YOUR MISSION when:
268+- Mission completed (achieved your objective)
269+- Mission blocked (impossible to continue, need different approach)
270+- Better opportunity arises (new priority emerges)
271+- Current mission no longer aligns with your situation
272+
273+Keep your mission consistent across actions unless circumstances change significantly.
253274
254275 YOUR EMPIRE: ${getEmpireDescription(empire)}
255276
@@ -282,7 +303,7 @@ ${lastActionText}
282303 ${forumContextBlock}
283304
284305 ACTION SCHEMA (JSON ONLY):
285- {"goal":"...","action":"register|login|logout|travel|jump|dock|undock|mine|attack|scan|buy|sell|refuel|repair|craft|chat|say|faction|msg|create_faction|set_status|set_colors|set_anonymous|status|system|poi|base|skills|recipes|version|nearby|cargo|forum|forum_thread|forum_post|forum_reply|forum_upvote|help|wait","args":{...}}
306+ {"mission":"...","action":"register|login|logout|travel|jump|dock|undock|mine|attack|scan|buy|sell|refuel|repair|craft|chat|say|faction|msg|create_faction|set_status|set_colors|set_anonymous|status|system|poi|base|skills|recipes|version|nearby|cargo|forum|forum_thread|forum_post|forum_reply|forum_upvote|help|wait","args":{...}}
286307
287308 REQUIRED ARGS:
288309 - travel: {"target_poi":"..."}
@@ -310,14 +331,14 @@ REQUIRED ARGS:
310331
311332 FORMAT RULES:
312333 - Use only the listed actions.
313-- Goal is required, max ${MAX_GOAL_LENGTH} characters, update every action.
334+- Mission is required, max ${MAX_MISSION_LENGTH} characters. Keep it consistent unless circumstances change.
314335 - Only use info actions (status/system/poi/base/nearby/cargo) when information is missing.
315336 - IDs must come from current state or world snapshot.
316337 - Never omit required args or leave them blank.
317338
318339 ERROR RECOVERY:
319340 - If an action FAILED in recent memory, do NOT retry it with the same arguments.
320-- Change your approach: try a different action, move to a different location, or update your goal.
341+- Change your approach: try a different action, move to a different location, or update your mission.
321342
322343 INTERACTION GUIDELINES:
323344 - Stay in character with your personality archetype and empire
src/swarm.ts+34−30
@@ -14,9 +14,9 @@ const DEFAULT_COUNT = 5;
1414 const DEFAULT_PREFIX = "swarm";
1515 const DEFAULT_RESTART_DELAY_MS = 10000;
1616 const SWARM_LOG_PATH = "swarm.log";
17-const GOAL_TICK_DELAY_MS = 11000;
18-const GOAL_EVERY_TICKS = 3;
19-const GOAL_INTERVAL_MS = GOAL_TICK_DELAY_MS * GOAL_EVERY_TICKS;
17+const MISSION_TICK_DELAY_MS = 11000;
18+const MISSION_EVERY_TICKS = 3;
19+const MISSION_INTERVAL_MS = MISSION_TICK_DELAY_MS * MISSION_EVERY_TICKS;
2020
2121 const { values } = parseArgs({
2222 args: process.argv.slice(2),
@@ -174,9 +174,9 @@ const swarmConfig: SwarmConfig = {
174174
175175 const children = new Map<string, ReturnType<typeof spawn>>();
176176 const restartTimers = new Map<string, ReturnType<typeof setTimeout>>();
177-const goalDbs = new Map<string, Database>();
177+const missionDbs = new Map<string, Database>();
178178 let swarmMembers: string[] = [];
179-let goalTimer: ReturnType<typeof setInterval> | null = null;
179+let missionTimer: ReturnType<typeof setInterval> | null = null;
180180 let stopping = false;
181181
182182 function buildInstanceName(
@@ -224,51 +224,51 @@ function getMemoryPath(instanceName: string): string {
224224 return `memory-${instanceName}.sqlite`;
225225 }
226226
227-function getGoalDb(instanceName: string): Database | null {
228- const existing = goalDbs.get(instanceName);
227+function getMissionDb(instanceName: string): Database | null {
228+ const existing = missionDbs.get(instanceName);
229229 if (existing) return existing;
230230 const memoryPath = getMemoryPath(instanceName);
231231 if (!existsSync(memoryPath)) return null;
232232 const db = new Database(memoryPath);
233- goalDbs.set(instanceName, db);
233+ missionDbs.set(instanceName, db);
234234 return db;
235235 }
236236
237-function readLatestGoal(
237+function readLatestMission(
238238 instanceName: string,
239239 ):
240- | { status: "ok"; goal: string | null }
240+ | { status: "ok"; mission: string | null }
241241 | { status: "missing" }
242242 | { status: "error"; message: string } {
243- const db = getGoalDb(instanceName);
243+ const db = getMissionDb(instanceName);
244244 if (!db) return { status: "missing" };
245245 try {
246246 const row = db
247- .query("SELECT goal FROM llm_goals ORDER BY id DESC LIMIT 1")
248- .get() as { goal?: string } | undefined;
249- return { status: "ok", goal: row?.goal ?? null };
247+ .query("SELECT mission FROM llm_missions ORDER BY id DESC LIMIT 1")
248+ .get() as { mission?: string } | undefined;
249+ return { status: "ok", mission: row?.mission ?? null };
250250 } catch (error) {
251251 return { status: "error", message: (error as Error).message };
252252 }
253253 }
254254
255-function logGoalsOnce(): void {
255+function logMissionsOnce(): void {
256256 if (stopping) return;
257257 for (const name of swarmMembers) {
258- const result = readLatestGoal(name);
258+ const result = readLatestMission(name);
259259 if (result.status === "missing") {
260- logSwarm(`goal ${name}: <db missing>`);
260+ logSwarm(`mission ${name}: <db missing>`);
261261 continue;
262262 }
263263 if (result.status === "error") {
264- logSwarm(`goal ${name}: error (${result.message})`);
264+ logSwarm(`mission ${name}: error (${result.message})`);
265265 continue;
266266 }
267- if (result.goal) {
268- logSwarm(`goal ${name}: ${result.goal}`);
267+ if (result.mission) {
268+ logSwarm(`mission ${name}: ${result.mission}`);
269269 continue;
270270 }
271- logSwarm(`goal ${name}: <none yet>`);
271+ logSwarm(`mission ${name}: <none yet>`);
272272 }
273273 }
274274
@@ -309,22 +309,24 @@ function shutdown(reason: string): void {
309309 if (stopping) return;
310310 stopping = true;
311311 logSwarm(`shutdown ${reason}`);
312- if (goalTimer) {
313- clearInterval(goalTimer);
314- goalTimer = null;
312+ if (missionTimer) {
313+ clearInterval(missionTimer);
314+ missionTimer = null;
315315 }
316316 for (const timer of restartTimers.values()) {
317317 clearTimeout(timer);
318318 }
319319 restartTimers.clear();
320- for (const [name, db] of goalDbs.entries()) {
320+ for (const [name, db] of missionDbs.entries()) {
321321 try {
322322 db.close();
323323 } catch (error) {
324- logSwarm(`failed to close goal db ${name} (${(error as Error).message})`);
324+ logSwarm(
325+ `failed to close mission db ${name} (${(error as Error).message})`,
326+ );
325327 }
326328 }
327- goalDbs.clear();
329+ missionDbs.clear();
328330 for (const [name, child] of children.entries()) {
329331 try {
330332 child.kill("SIGTERM");
@@ -351,9 +353,11 @@ function startSwarm(): void {
351353 for (const name of swarmMembers) {
352354 spawnBot(name);
353355 }
354- if (!goalTimer) {
355- goalTimer = setInterval(logGoalsOnce, GOAL_INTERVAL_MS);
356- logSwarm(`goals every ${GOAL_EVERY_TICKS} ticks (${GOAL_INTERVAL_MS}ms)`);
356+ if (!missionTimer) {
357+ missionTimer = setInterval(logMissionsOnce, MISSION_INTERVAL_MS);
358+ logSwarm(
359+ `missions every ${MISSION_EVERY_TICKS} ticks (${MISSION_INTERVAL_MS}ms)`,
360+ );
357361 }
358362 }
359363
src/tui/formatters.ts+2−2
@@ -294,8 +294,8 @@ export function formatAiAction(
294294 return formatWithTimestamp(msg, "ai");
295295 }
296296
297-export function formatAiGoal(goal: string): FormattedMessage {
298- const msg = applyColor(`[AI Goal] ${goal}`, COLORS.MSG_AI);
297+export function formatAiMission(mission: string): FormattedMessage {
298+ const msg = applyColor(`[AI Mission] ${mission}`, COLORS.MSG_AI);
299299 return formatWithTimestamp(msg, "ai");
300300 }
301301
src/tui/index.ts+5−5
@@ -54,7 +54,7 @@ export interface TuiUpdateData {
5454 travelTarget?: string | null;
5555 jumping?: boolean;
5656 jumpTarget?: string | null;
57- goal?: string | null;
57+ mission?: string | null;
5858 inCombat?: boolean;
5959 combatTarget?: {
6060 id: string;
@@ -245,7 +245,7 @@ export class Tui {
245245 this.state.travelTarget = data.travelTarget;
246246 if (data.jumping !== undefined) this.state.jumping = data.jumping;
247247 if (data.jumpTarget !== undefined) this.state.jumpTarget = data.jumpTarget;
248- if (data.goal !== undefined) this.state.goal = data.goal;
248+ if (data.mission !== undefined) this.state.mission = data.mission;
249249 if (data.inCombat !== undefined) this.state.inCombat = data.inCombat;
250250 if (data.combatTarget !== undefined)
251251 this.state.combatTarget = data.combatTarget;
@@ -338,9 +338,9 @@ export class Tui {
338338 parts.push(`At ${this.state.poi.name}`);
339339 }
340340
341- // Goal
342- if (this.state.goal) {
343- parts.push(`Goal: ${this.state.goal}`);
341+ // Mission
342+ if (this.state.mission) {
343+ parts.push(`Mission: ${this.state.mission}`);
344344 }
345345
346346 // Tick
src/types.ts+1−1
@@ -14,7 +14,7 @@ export type SpeechStyleType = "mythic" | "punny" | "gritty" | "scholarly";
1414 export interface ActionDecision {
1515 action: string;
1616 args?: Record<string, unknown>;
17- goal?: string;
17+ mission?: string;
1818 }
1919
2020 export interface Credentials {