Undo against bots: replay to BGS log positions (engine 0.1.12)

BGS undoes the only human's last saved move by calling replay(data, { to })
with the log length recorded before that move, and requires
logLength(result) === to. The wrapper passed `to` to the internal replay as
a history index, so most undo requests failed or landed elsewhere; admin
replays, which also send log positions, had the same problem.

With a position, replay now rewinds to the first point where the journal
reaches it, then reapplies later name changes and drops, and does not queue
chat announcements of replayed moves again. Choices that add no journal
entry (live route and readiness edits, preparation before the last player is
ready) are not restored: undoing one reopens them for every player, and the
bots choose again. replay(data) without a position, createAnalysis and the
internal history-index replay are unchanged.

Tests play complete 2-4 player games against bots: every undo point reaches
its log length and deep-equals the saved state unless unannounced choices
preceded the move; otherwise the reopened phase stays playable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
coyotte508 2026-10-08 11:59:26 +02:00
commit 0c59dab3d1
5 changed files with 142 additions and 2 deletions

View file

@ -45,6 +45,8 @@ Fuji has a shared win/loss. The wrapper gives all players the same ranking and r
When a single human plays with bots, BGS sends `undo:available` (protocol 0.10.0). While it is true, the header shows **Undo my move** to the seated player, except in analysis and while a move awaits the next state. The control emits `undo`; BGS then sends the earlier state. The viewer stops playback and discards local selections when a state goes backwards. The local harness offers the same control after each move made from the interface.
BGS records the log length before each of that player's saved moves and calls `replay(data, { to })` with it; admin replays also pass log positions. The wrapper replays up to the first point where the journal reaches `to`, then reapplies later name changes and drops. Chat announcements of replayed moves are not queued again. Live route and readiness edits, and preparation choices before the last player is ready, add no journal entry. Undoing one therefore reopens the choices made since the latest journal entry, for every player; the bots choose again. `replay(data)` without a position still restores the complete game.
## Automatic movement resolution
Starting a movement resolves it immediately when no Gatherer has usable bars. Otherwise only the Gatherer(s) are active: each submits one `help` action with `count` from zero to their remaining stock. The last decision applies movement, eruption triggers and stamina automatically. Injury choices still belong to the injured player. The journal snapshots revealed and matching dice with text fallbacks for the platform log. Start a new local game when testing this flow; historical development saves using manual resolution are not migrated.

View file

@ -1,6 +1,6 @@
{
"name": "fuji-engine",
"version": "0.1.11",
"version": "0.1.12",
"private": true,
"license": "AGPL-3.0-only",
"files": [

View file

@ -1224,6 +1224,23 @@ export function replay(s: State, to?: number, logTo?: number): State {
if (to === undefined && logTo === undefined && s.planningSnapshot) restorePlanning(state, s.planningSnapshot);
return state;
}
/**
* Go back to a public log position, as BGS does to undo a move against bots: replay up to the
* first point where the journal has `logTo` entries. Choices that add no journal entry after it
* (live route and readiness edits, preparation before the last player is ready) are not
* restored, so undoing one reopens those choices for every player. Names and drops recorded
* later still apply. Chat announcements of replayed moves were delivered and are not queued again.
*/
export function rewind(s: State, logTo: number): State {
if (!Number.isInteger(logTo) || logTo < 0 || logTo > s.log.length) throw Error("Invalid history position.");
let state = replay(s, undefined, logTo);
for (const e of s.history.slice(state.history.length)) {
if (e.move.action === "$name") state = setPlayerName(state, e.player, e.move.name as string);
else if (e.move.action === "$drop") state = dropGamePlayer(state, e.player);
}
delete state.chatMessages;
return state;
}
/** Start a manual sandbox from only the requesting seat's visible information. */
export function createAnalysisScenario(data: State, { player, seed }: { player?: number; seed: string }): State {

View file

@ -0,0 +1,119 @@
import test from "node:test";
import assert from "node:assert/strict";
import * as wrapper from "../wrapper.js";
import { activePlayers, applyMove, initGame, moveAI, paths, replay, type State } from "../index.js";
// BGS undo against bots: the game-server records the log length before each saved move of the
// only human, then calls replay(data, { to }) and requires logLength(result) === to. Like BGS,
// these games name the seats after init, deliver queued chat after each move and persist JSON.
const json = <T>(value: T): T => JSON.parse(JSON.stringify(value));
const games = new Map<string, ReturnType<typeof playBotGame>>();
const botGame = (players: number, seed: string) => {
if (!games.has(seed)) games.set(seed, playBotGame(players, seed));
return games.get(seed)!;
};
async function playBotGame(players: number, seed: string, human = 0) {
let data: State = await wrapper.init(players, [], {}, seed);
for (let seat = 0; seat < players; seat++) data = wrapper.setPlayerMetaData(data, seat, { name: `Explorer ${seat}` });
const undoPoints: { to: number; saved: State }[] = [];
for (let moves = 0; !wrapper.ended(data) && moves < 400; moves++) {
const seats = [wrapper.currentPlayer(data)].flat();
// Bots sometimes act first in simultaneous phases.
const seat = seats.includes(human) && moves % 3 !== 1 ? human : (seats.find((i) => i !== human) ?? human);
if (seat === human) undoPoints.push({ to: wrapper.logLength(data), saved: json(data) });
data = wrapper.messages(wrapper.moveAI(data, seat)).data;
}
return { data, undoPoints };
}
/** Choices recorded since the journal reached that length (names are carried over anyway). */
function unannouncedChoices(saved: State, to: number) {
const since = saved.history.slice(replay(saved, undefined, to).history.length);
return !!saved.planningSnapshot || since.some((entry) => entry.move.action !== "$name");
}
function assertReopened(undone: State, saved: State, seats: number[]) {
assert.equal(undone.phase, saved.phase);
assert.equal(undone.round, saved.round);
assert.deepEqual(
undone.players.map((p) => [p.name, p.position]),
saved.players.map((p) => [p.name, p.position])
);
for (const seat of seats) assert(activePlayers(undone).includes(seat), `seat ${seat} chooses again`);
assert.equal(wrapper.isLiveUpdate(undone), false);
let next = undone;
for (let i = 0; i < 80 && next.phase === saved.phase && next.round === saved.round && !wrapper.ended(next); i++)
next = wrapper.moveAI(next, [wrapper.currentPlayer(next)].flat()[0]!);
assert(next.phase !== saved.phase || next.round !== saved.round || wrapper.ended(next), "the phase can finish");
}
test("undo against bots returns to every recorded log position", async () => {
let exact = 0;
let reopened = 0;
for (const [players, seed] of [
[2, "undo-a"],
[3, "undo-b"],
[4, "undo-c"],
] as const) {
const { data, undoPoints } = await botGame(players, seed);
assert(wrapper.ended(data));
for (const { to, saved } of undoPoints) {
const undone = json(wrapper.replay(data, { to }));
assert.equal(wrapper.logLength(undone), to);
// A later batch replay of the saved result must not diverge.
const { chatMessages: _, ...again } = replay(undone);
assert.deepEqual(json(again), undone);
if (!unannouncedChoices(saved, to)) {
assert.deepEqual(undone, saved);
exact++;
} else {
// Live route and readiness edits add no journal entry: undo reopens that phase's choices.
assertReopened(undone, saved, [0]);
reopened++;
}
}
}
assert(exact > 0 && reopened > 0, "both kinds of positions are covered");
});
test("undoing the last preparation choice reopens unannounced bot preparations", async () => {
// Seats 2 and 3 choose equipment; the bot at seat 2 packs first and adds no journal entry.
let data: State = await wrapper.init(4, [], { skillAssignment: "fixed" }, "undo-setup");
for (let seat = 0; seat < 4; seat++) data = wrapper.setPlayerMetaData(data, seat, { name: `Explorer ${seat}` });
assert.deepEqual(activePlayers(data), [2, 3]);
const to = wrapper.logLength(data);
data = wrapper.moveAI(data, 2);
assert.equal(wrapper.logLength(data), to);
const saved = json(data);
data = wrapper.moveAI(data, 3);
assert.notEqual(data.phase, "setup");
const undone = json(wrapper.replay(data, { to }));
assert.equal(wrapper.logLength(undone), to);
assert(unannouncedChoices(saved, to));
assertReopened(undone, saved, [2, 3]);
});
test("undo keeps later names and drops without queuing chat announcements again", async () => {
const { undoPoints } = await botGame(3, "undo-b");
const { saved } = undoPoints.at(-1)!;
const { to } = undoPoints.at(-2)!;
assert((replay(saved, undefined, to).chatMessages ?? []).length > 0, "replayed moves announced equipment");
const renamed = wrapper.setPlayerMetaData(saved, 1, { name: "Renamed" });
const undone = wrapper.replay(renamed, { to });
assert.equal(undone.players[1]!.name, "Renamed");
assert.equal(replay(undone).players[1]!.name, "Renamed");
assert.equal(undone.chatMessages, undefined);
assert.deepEqual(wrapper.messages(undone).messages, []);
const dropped = wrapper.replay(wrapper.dropPlayer(renamed, 2), { to });
assert.equal(dropped.outcome, "lost");
assert.equal(dropped.reason, "Explorer 2 left the expedition.");
});
test("replay without a position is unchanged and invalid positions are refused", () => {
let s = initGame(3, { skillAssignment: "fixed" }, "undo-full");
while (s.phase === "setup") s = moveAI(s, activePlayers(s)[0]!);
s = applyMove(s, { action: "plan", path: Object.values(paths(s, 0)).at(-1)! }, 0);
assert.equal(wrapper.isLiveUpdate(s), true);
assert.deepEqual(wrapper.replay(s), replay(s));
assert.deepEqual(wrapper.replay(s), s);
for (const to of [-1, 0.5, s.log.length + 1])
assert.throws(() => wrapper.replay(s, { to }), /Invalid history position/);
});

View file

@ -7,6 +7,7 @@ import {
dropGamePlayer,
setPlayerName,
replay as replayGame,
rewind,
} from "./src/game.js";
import type { State } from "./src/types.js";
export { stripSecret };
@ -41,7 +42,8 @@ export const logLength = (s: State) => s.log.length;
export const logSlice = (s: State, o: { player?: number; start: number; end?: number }) => ({
log: s.log.slice(o.start, o.end).map((e) => ({ ...e, simple: e.text })),
});
export const replay = (s: State, o?: { to?: number }) => replayGame(s, o?.to);
// BGS positions are public log lengths (undo against bots, admin replays): see rewind.
export const replay = (s: State, o?: { to?: number }) => (o?.to === undefined ? replayGame(s) : rewind(s, o.to));
export function setPlayerMetaData(s: State, seat: number, meta: { name: string }) {
return setPlayerName(s, seat, meta.name);
}