@@ -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();