From e161510ff3c096a3fb1fcd205a19a59d97af0e2d Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Tue, 24 Nov 2026 18:39:11 +0900 Subject: [PATCH 1/3] feat(mcp): add input recording and deterministic replay tools (#467) --- .../2026-11-24-mcp-record-and-replay.md | 47 + changelog.d/mcp-record-replay.md | 3 + docs/en/mcp.md | 38 + docs/zh/mcp.md | 38 + packages/game/mcp/doc.go | 6 + packages/game/mcp/example_test.go | 6 + packages/game/mcp/mcp.go | 4 + packages/game/mcp/replay.go | 1039 +++++++++++++++++ packages/game/mcp/replay_test.go | 808 +++++++++++++ 9 files changed, 1989 insertions(+) create mode 100644 .agents/notes/implemented/feature/2026-11-24-mcp-record-and-replay.md create mode 100644 changelog.d/mcp-record-replay.md create mode 100644 packages/game/mcp/replay.go create mode 100644 packages/game/mcp/replay_test.go diff --git a/.agents/notes/implemented/feature/2026-11-24-mcp-record-and-replay.md b/.agents/notes/implemented/feature/2026-11-24-mcp-record-and-replay.md new file mode 100644 index 00000000..589e9a52 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-24-mcp-record-and-replay.md @@ -0,0 +1,47 @@ +# Agent Note: MCP input recording and deterministic replay + +Status: implemented + +## Problem + +`game/replay` provides fixed-step input recording (`replay.Recorder`) and deterministic playback (`replay.Player`) over versioned YAML files, and [MCP scene, layer, entity and component inspection](2026-11-24-mcp-scene-entity-inspection.md) lets coding agents inspect a running game via `nsgo mcp`. However, agents have no MCP tools to start or stop an input recording of a running session or replay a stored or inline YAML recording back through the live simulation to reproduce exact state. + +## Decision + +Add `ReplayController` (configured via `ReplayConfig` on `mcp.Config.Replay`) and six `game_replay_*` automation tools in `packages/game/mcp/replay.go`, appended to `Bridge.Tools()` alongside the inspection tools. `ReplayController` itself implements `replay.ActionSource`, switching transparently between live `Source`, an active `replay.Recorder`, and an active `replay.Player` so a game wires MCP record and replay into one unchanged update loop. + +## Architecture and tool contract + +- **Single `ActionSource` facade (`ReplayController`)**: Games construct `ctrl := mcp.NewReplayController(cfg)`, pass `ctrl` to their simulation as its `replay.ActionSource`, and supply `Replay: ctrl` in `mcp.Config`. During live play `ctrl` forwards to `cfg.Source`; during recording it delegates to a `replay.Recorder` wrapping `cfg.Source` (or a pre-built `cfg.Recorder` fallback); during playback it delegates to a `replay.Player` created from the target `replay.Recording`. +- **Final-step playback lifecycle**: In `replay.Player.Step()`, advancing the last recorded frame (`TotalSteps - 1`) sets `Done() == true` before the simulation reads `Pressed`/`JustPressed`/`Axis` for that tick. `ReplayController` therefore keeps `player` attached through the remainder of that final step and only clears it on the subsequent `Step()` (resuming live input), on `game_replay_stop`, at the end of synchronous `run_to_end`/`steps` execution, or before starting a new record/play session. Meanwhile `game_replay_status` reports `replaying: false` and `replay_done: true` as soon as `player.Done()` becomes true so polling agents observe completion without needing an extra live step. +- **Six tools with strict JSON decoding**: + - `game_replay_status`: returns recording/playback flags, frame counters, active names/metadata, and sorted `saved_recordings`. + - `game_replay_record_start`: starts recording with optional `name` (auto-allocated sequentially when omitted), `seed` (falls back to `SeedFunc` or `0`), `step_rate` (falls back to `ReplayConfig.StepRate`, `Loop.Rate`, or `60`), `actions`/`axes` overrides, string `metadata`, and optional `reset: true`. Refuses starting while already recording or actively replaying. + - `game_replay_record_stop`: validates optional `save_path` before mutating state so an invalid path never discards an active recording, encodes canonical `replay` v2 YAML via `Recording.Encode()`, stores a clone in memory under its name, optionally writes inside `ReplayConfig.SaveDir` (strictly rejecting absolute paths and `..` escapes), and returns summary fields plus the YAML text. + - `game_replay_play`: accepts either a stored `name` or inline `yaml` (decoded and validated via `replay.Decode`), invokes `ResetFunc(rec.Seed)` by default (rolling back state if `ResetFunc` fails), and supports frame-by-frame playback (`run_to_end: false`), bounded synchronous stepping (`steps: N`), or full synchronous playback (`run_to_end: true`) using `StepFunc` or `Loop.Update`. + - `game_replay_stop`: stops an active playback early and fires `OnReplayStop`. + - `game_replay_list`: returns sorted summaries (`name`, `frames`, `seed`, `step_rate`, `events`, `actions`, `axes`, `metadata`) of stored recordings. +- **Pure `game/replay` v2 YAML preservation**: Optional MCP `metadata` is stored alongside the `replay.Recording` in `ReplayController`'s in-memory map rather than added to the YAML schema, keeping exported YAML 100% compatible with `replay.Decode`'s `KnownFields(true)` check and `go tool game replay`. + +## Alternatives considered + +### Putting `Recorder`/`Player` wiring callbacks on `mcp.Config` without implementing `replay.ActionSource` + +`mcp.Config` could expose `OnStartRecord` / `OnStartReplay` hooks and require every game to manually swap its own `ActionSource` variable across live, record, and playback modes. This was rejected because every game would reimplement the same three-mode multiplexer and easily hit the final-step `Player.Done()` subtlety (dropping inputs on the last recorded step or getting stuck after playback ends). Making `ReplayController` itself a `replay.ActionSource` encapsulates those invariants once while still offering lifecycle hooks (`OnRecordStart`, `OnRecordStop`, `OnReplayStart`, `OnReplayStop`). + +### Persisting MCP `metadata` inside the `.replay.yaml` file + +Adding a `metadata` field to `replay.Recording` would persist agent labels on disk with the recording. This was rejected because `packages/game/replay` is a Stable package with a strict version-2 YAML contract checked by conformance tests and `go tool game replay`; keeping recordings in canonical v2 YAML ensures recordings created through MCP can be dropped straight into `testdata/` for CI regression tests with no format divergence. + +### Allowing arbitrary filesystem paths in `game_replay_record_stop` + +Letting an agent pass any file path to `save_path` would simplify one-off exports without setting `SaveDir`. This was rejected because MCP tools may be invoked by autonomous coding agents; confining disk writes to an explicit opt-in `ReplayConfig.SaveDir` (and returning the full YAML inline by default with in-memory storage) keeps playback self-contained on every target including WebAssembly while preventing unintended writes outside the project directory. + +## Consequences + +- **Benefits**: Agents can record live input sequences over MCP, inspect their deterministic v2 YAML, store or export them safely, and replay them (by name, from inline YAML, synchronously, or frame-by-frame) to reproduce bit-identical simulation and ECS component state. Games wire the capability in a handful of lines by passing `ReplayController` as their `replay.ActionSource`, and parallel MCP tool groups remain isolated in separate files. +- **Costs**: Games that want `run_to_end` or `steps` synchronous playback must expose a deterministic `StepFunc` (or `Loop`) and `ResetFunc`, and must configure watched `Actions`/`Axes` names (matching `replay.NewRecorder`) because `input.Actions` does not enumerate all dynamic action names by itself. In-memory recordings live for the lifetime of the `ReplayController` unless deleted or replaced by name. + +## Verification + +Verified with `go tool nsgo test ./mcp`, `go tool nsgo test ./replay`, `go tool nsgo test -run TestStabilityTable .`, `go tool nsgo check -target macos,windows,linux,android,web`, `go run ./cmd/gameschema -check`, `go run ./tools/changelog check`, `gofmt`, and `bun run verify-notes`. diff --git a/changelog.d/mcp-record-replay.md b/changelog.d/mcp-record-replay.md new file mode 100644 index 00000000..abb2794b --- /dev/null +++ b/changelog.d/mcp-record-replay.md @@ -0,0 +1,3 @@ +### Added + +- `game/mcp`: add `ReplayController` and MCP record/replay tools (`game_replay_status`, `game_replay_record_start`, `game_replay_record_stop`, `game_replay_play`, `game_replay_stop`, `game_replay_list`) for starting/stopping input recordings and replaying them deterministically (#467). diff --git a/docs/en/mcp.md b/docs/en/mcp.md index fc06f192..075ef518 100644 --- a/docs/en/mcp.md +++ b/docs/en/mcp.md @@ -111,6 +111,12 @@ If `game_entity_spawn` fails while applying `parent` or `components`, or while r | `game_entity_destroy` | `ref` (required), `policy` (optional: `"cascade"`, `"orphan"`, `"keep_world"`, or `"reparent"`) | Confirmation of destruction with `ref`, the `policy` applied to children (the hierarchy's default, usually `"orphan"`, when omitted; `"none"` when omitted and the entity had no children), and count of `destroyed` entities. `"reparent"` keeps the children's world transforms. | | `game_component_set` | `ref` (required), `component` (required), `value` (required), `replace` (optional, default `false`) | Updated component `value` read back from the live entity; edits take effect on the next simulation step. If the write succeeded but the read-back failed, `value` is `null` and `read_error` says why; the edit still stands. | | `game_component_remove` | `ref` (required), `component` (required) | Whether the component was present and `removed` from the live entity. | +| `game_replay_status` | `{}` | Current recording and playback state (`recording`, `replaying`, `replay_done`, `frames_recorded`, `replay_frame`, `replay_total_frames`), active names/metadata, and sorted `saved_recordings`. | +| `game_replay_record_start` | `name`, `seed`, `step_rate`, `actions`, `axes`, `metadata`, `reset` (all optional) | Starts recording per-step inputs via `replay.Recorder`, returning the resolved recording name, seed, step rate, watched names and metadata. | +| `game_replay_record_stop` | `name` (optional), `save_path` (optional, relative to `ReplayConfig.SaveDir`) | Stops the active recording, stores it in memory (and optionally writes it under `SaveDir`), and returns its summary plus deterministic version-2 YAML text (`yaml`). | +| `game_replay_play` | `name` or `yaml` (mutually exclusive), `run_to_end` (default `false`), `steps`, `reset` (default `true` when `ResetFunc` is set) | Starts deterministic playback via `replay.Player`, invoking `ResetFunc(seed)` before playback and optionally advancing all or `steps` frames synchronously via `StepFunc`/`Loop.Update`. | +| `game_replay_stop` | `{}` | Stops an active replay playback cleanly and reports how many frames were played. | +| `game_replay_list` | `{}` | Lists stored recordings in sorted name order with `frames`, `seed`, `step_rate`, `events`, `actions`, `axes` and `metadata`. | All tools reject unknown argument fields. @@ -146,6 +152,38 @@ console.RegisterCommand("spawn", "spawn [count]", g.handleSpawn) - `game_tunables_list` and `game_tunable_get` read live values directly without adding entries to the console's interactive command history or output log. - `game_tunable_set` enforces each tunable's registered type (`float`, `int`, `bool` or `string`) and numeric `[min, max]` bounds by default without mutating the variable on error. Passing `"clamp": true` clamps out-of-range numeric values into `[min, max]` and sets `"clamped": true` in the response. - `game_console_exec` executes built-in commands (`help`, `list`, `get`, `set`, `clear`) and game-registered commands through `debug.Console.Exec`, returning `{command, ok, output, lines, error}`. Invalid MCP arguments or a missing `Console` return a tool error, while command execution failures (such as an unknown command name or invalid command arguments) return `ok: false` with the command's `error` message. +## Recording and replaying inputs + +Create a `*mcp.ReplayController` with `mcp.NewReplayController`, pass it to your simulation as its [`replay.ActionSource`](replay.md), and attach it on `mcp.Config.Replay`: + +```go +var ctrl *mcp.ReplayController +ctrl = mcp.NewReplayController(mcp.ReplayConfig{ + Source: g.actions, + Actions: []string{"left", "right", "jump", "dash"}, + Axes: []string{"move_x"}, + StepRate: 60, + SeedFunc: func() uint64 { return g.seed }, + ResetFunc: func(seed uint64) error { + g.actions.Reset() + g.Reset(seed) + return nil + }, + StepFunc: func(dt time.Duration) { + g.Step(ctrl, dt) + }, +}) + +bridge, err := mcp.Attach(cx, mcp.Config{ + WorldFunc: func() *entities.World { return g.world }, + Replay: ctrl, +}) +``` + +- Because `ReplayController` implements `replay.ActionSource`, your game loop reads input from `ctrl` identically during live play (forwarded to `Source`), recording (`replay.Recorder`) and playback (`replay.Player`). +- Recordings stopped via `game_replay_record_stop` are stored in memory under their name and returned as canonical deterministic [`game/replay`](replay.md) v2 YAML text. Set `ReplayConfig.SaveDir` if you also want agents to write recordings to safe relative paths on disk via `save_path` (absolute paths and `..` escapes are rejected). +- `game_replay_play` accepts either a stored `name` or inline `yaml` text, invokes `ResetFunc(recording.Seed)` to restore the starting state, and replays either synchronously (`run_to_end: true` or `steps: N`) or frame-by-frame as the game loop advances. + ## Stable entity references Every live entity receives a generational reference formatted as `"entity::"` (such as `"entity:0:1"`), produced by `FormatEntityRef` and parsed by `ParseEntityRef`: diff --git a/docs/zh/mcp.md b/docs/zh/mcp.md index 1b8850bf..d4ec8243 100644 --- a/docs/zh/mcp.md +++ b/docs/zh/mcp.md @@ -111,6 +111,12 @@ if err := bridge.RegisterScenePrefab("turret", turretDoc); err != nil { | `game_entity_destroy` | `ref`(必填)、`policy`(可选:`"cascade"`、`"orphan"`、`"keep_world"` 或 `"reparent"`) | 销毁结果,包含 `ref`、应用于子实体的 `policy`(省略时为层级的默认策略,通常是 `"orphan"`;省略且实体没有子实体时为 `"none"`)与实际销毁实体数 `destroyed`。`"reparent"` 会保持子实体的世界变换。 | | `game_component_set` | `ref`(必填)、`component`(必填)、`value`(必填)、`replace`(可选,默认 `false`) | 回读自存活实体的更新后组件 `value`;修改会在下一次模拟步进中生效。若写入成功但回读失败,`value` 为 `null`,`read_error` 说明原因,修改依然有效。 | | `game_component_remove` | `ref`(必填)、`component`(必填) | 报告指定组件是否存在并已从存活实体移除(`removed`)。 | +| `game_replay_status` | `{}` | 当前录制与回放状态(`recording`、`replaying`、`replay_done`、`frames_recorded`、`replay_frame`、`replay_total_frames`)、当前录制/回放名称与元数据,以及排序后的 `saved_recordings`。 | +| `game_replay_record_start` | `name`、`seed`、`step_rate`、`actions`、`axes`、`metadata`、`reset`(均可选) | 通过 `replay.Recorder` 开始按固定步长录制输入,并返回解析后的录制名称、种子、步频、监听列表与元数据。 | +| `game_replay_record_stop` | `name`(可选)、`save_path`(可选,相对于 `ReplayConfig.SaveDir`) | 停止当前录制,将其保存到内存(并可选写入 `SaveDir` 下的安全相对路径),返回摘要与确定性的 v2 YAML 文本(`yaml`)。 | +| `game_replay_play` | `name` 或 `yaml`(二选一)、`run_to_end`(默认 `false`)、`steps`、`reset`(配置 `ResetFunc` 时默认 `true`) | 通过 `replay.Player` 开始确定性回放,在回放前调用 `ResetFunc(seed)` 重置状态,并可选通过 `StepFunc`/`Loop.Update` 同步推进全部或指定步数。 | +| `game_replay_stop` | `{}` | 安全停止当前正在进行的回放,并报告已回放的帧数。 | +| `game_replay_list` | `{}` | 按名称排序列出已存储的录制及其 `frames`、`seed`、`step_rate`、`events`、`actions`、`axes` 与 `metadata`。 | 所有工具都会拒绝未知的参数字段。 @@ -146,6 +152,38 @@ console.RegisterCommand("spawn", "spawn [count]", g.handleSpawn) - `game_tunables_list` 与 `game_tunable_get` 直接读取实时值,不会向控制台交互历史或输出日志中写入多余记录。 - `game_tunable_set` 默认严格校验参数注册类型(`float`、`int`、`bool` 或 `string`)及数值 `[min, max]` 范围,校验失败时不修改变量。传入 `"clamp": true` 时会将越界数值钳位到 `[min, max]` 并在响应中标记 `"clamped": true`。 - `game_console_exec` 通过 `debug.Console.Exec` 运行内置命令(`help`、`list`、`get`、`set`、`clear`)与游戏自定义命令,返回 `{command, ok, output, lines, error}`。无效的 MCP 参数或未配置 `Console` 会返回工具级错误;命令本身的执行失败(例如未知命令名或参数无效)则返回 `ok: false` 与对应的 `error` 信息。 +## 录制与回放输入 + +使用 `mcp.NewReplayController` 创建 `*mcp.ReplayController`,将其作为游戏的 [`replay.ActionSource`](replay.md) 传入更新循环,并挂到 `mcp.Config.Replay`: + +```go +var ctrl *mcp.ReplayController +ctrl = mcp.NewReplayController(mcp.ReplayConfig{ + Source: g.actions, + Actions: []string{"left", "right", "jump", "dash"}, + Axes: []string{"move_x"}, + StepRate: 60, + SeedFunc: func() uint64 { return g.seed }, + ResetFunc: func(seed uint64) error { + g.actions.Reset() + g.Reset(seed) + return nil + }, + StepFunc: func(dt time.Duration) { + g.Step(ctrl, dt) + }, +}) + +bridge, err := mcp.Attach(cx, mcp.Config{ + WorldFunc: func() *entities.World { return g.world }, + Replay: ctrl, +}) +``` + +- `ReplayController` 实现了 `replay.ActionSource`,游戏逻辑在实时游玩(转发至 `Source`)、录制(`replay.Recorder`)与回放(`replay.Player`)三种模式下完全共用同一套更新循环。 +- 通过 `game_replay_record_stop` 结束的录制会按名称存入内存,并返回标准、确定性的 [`game/replay`](replay.md) v2 YAML 文本。若希望智能体同时通过 `save_path` 落盘,可配置 `ReplayConfig.SaveDir`(绝对路径与 `..` 越界路径都会被拒绝)。 +- `game_replay_play` 支持按已存 `name` 或内联 `yaml` 文本回放,默认调用 `ResetFunc(recording.Seed)` 恢复初始确定性状态,并支持同步跑到结束(`run_to_end: true`)、同步步进(`steps: N`)或随游戏循环逐帧回放。 + ## 稳定的实体引用 每个存活实体都会获得一个格式为 `"entity::"`(例如 `"entity:0:1"`)的代数引用,由 `FormatEntityRef` 格式化并由 `ParseEntityRef` 解析: diff --git a/packages/game/mcp/doc.go b/packages/game/mcp/doc.go index d768a192..8bdf9ce0 100644 --- a/packages/game/mcp/doc.go +++ b/packages/game/mcp/doc.go @@ -27,6 +27,12 @@ // - game_entity_destroy: destroy a live entity by stable reference with an optional hierarchy child policy. // - game_component_set: set or patch a component's value on a live entity so the change takes effect on the next simulation step. // - game_component_remove: remove a component from a live entity. +// - game_replay_status: report input recording and playback status, frame progress and saved recordings. +// - game_replay_record_start: start recording per-step inputs into a named recording. +// - game_replay_record_stop: stop the active recording, store it and return its deterministic YAML text and summary. +// - game_replay_play: replay a stored or inline YAML recording deterministically, optionally resetting and running to completion. +// - game_replay_stop: stop an active replay playback cleanly. +// - game_replay_list: list stored recordings with frame counts, seeds, step rates and metadata. // // Components registered on an [entities.World] with [entities.RegisterCodec] are readable and editable automatically. Transient or non-saved components can also be exposed with [RegisterComponent], [RegisterComponentFunc], [RegisterMutableComponent] or [RegisterComponentEditor], and built-in [entities.Transform2D], [entities.WorldTransform2D] and [sceneformat.ObjectRef] components are surfaced automatically when present and not already registered under another name. Prefabs can be registered via [Config.Prefabs], [Bridge.RegisterPrefab], [Bridge.RegisterEntityPrefab] or [Bridge.RegisterScenePrefab]. // diff --git a/packages/game/mcp/example_test.go b/packages/game/mcp/example_test.go index 6eb7719c..206bdba5 100644 --- a/packages/game/mcp/example_test.go +++ b/packages/game/mcp/example_test.go @@ -60,4 +60,10 @@ func ExampleNew() { // game_entity_destroy // game_component_set // game_component_remove + // game_replay_status + // game_replay_record_start + // game_replay_record_stop + // game_replay_play + // game_replay_stop + // game_replay_list } diff --git a/packages/game/mcp/mcp.go b/packages/game/mcp/mcp.go index 8f030331..a3d1cec8 100644 --- a/packages/game/mcp/mcp.go +++ b/packages/game/mcp/mcp.go @@ -123,6 +123,9 @@ type Config struct { // Prefabs registers named prefab spawners available to game_prefabs_list and game_entity_spawn. Additional prefabs (including *entities.Prefab and *sceneformat.SceneDoc templates) can also be registered on the Bridge via RegisterPrefab, RegisterEntityPrefab and RegisterScenePrefab. Prefabs map[string]PrefabSpawner + + // Replay configures input recording and deterministic playback tools. + Replay *ReplayController } type compTypeKey any @@ -295,6 +298,7 @@ func (b *Bridge) Tools() []automation.Tool { out = append(out, b.inputTools()...) out = append(out, b.consoleTools()...) out = append(out, b.editTools()...) + out = append(out, b.replayTools()...) return out } diff --git a/packages/game/mcp/replay.go b/packages/game/mcp/replay.go new file mode 100644 index 00000000..6a8384a5 --- /dev/null +++ b/packages/game/mcp/replay.go @@ -0,0 +1,1039 @@ +package mcp + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "maps" + "os" + "path/filepath" + "slices" + "strings" + "time" + + "github.com/nsgo-dev/game/packages/game" + "github.com/nsgo-dev/game/packages/game/replay" + "github.com/nsgo-dev/nsgo/automation" +) + +// Replay tool names registered by Bridge with github.com/nsgo-dev/nsgo/automation. +const ( + // ToolReplayStatus reports current recording/playback state, frame progress and saved recording names. + ToolReplayStatus = "game_replay_status" + // ToolReplayRecordStart starts recording fixed-step inputs into a named recording. + ToolReplayRecordStart = "game_replay_record_start" + // ToolReplayRecordStop stops the active recording, stores it and returns its deterministic YAML text and summary. + ToolReplayRecordStop = "game_replay_record_stop" + // ToolReplayPlay starts replaying a stored recording by name or an inline YAML recording. + ToolReplayPlay = "game_replay_play" + // ToolReplayStop stops an active replay playback. + ToolReplayStop = "game_replay_stop" + // ToolReplayList lists stored recordings with their frame counts, seeds, step rates and metadata. + ToolReplayList = "game_replay_list" +) + +var ( + // ErrReplayNotConfigured reports a replay tool call on a Bridge without a configured ReplayController. + ErrReplayNotConfigured = errors.New("mcp: no replay controller configured") + // ErrAlreadyRecording reports starting a recording while another recording is already active. + ErrAlreadyRecording = errors.New("mcp: recording is already in progress") + // ErrNotRecording reports stopping a recording when none is active. + ErrNotRecording = errors.New("mcp: no recording in progress") + // ErrAlreadyReplaying reports starting a recording or replay while playback is already in progress. + ErrAlreadyReplaying = errors.New("mcp: replay is already in progress") + // ErrNotReplaying reports stopping a replay when none is active. + ErrNotReplaying = errors.New("mcp: no replay in progress") +) + +const defaultReplayStepRate = 60 + +var _ replay.ActionSource = (*ReplayController)(nil) + +// ReplayConfig configures a ReplayController for MCP input recording and deterministic playback. +// +// Pass the resulting *ReplayController as your game's replay.ActionSource so live play, recording and playback share the exact same update loop. +type ReplayConfig struct { + // Source is the live replay.ActionSource (such as *input.Actions) forwarded during live play and wrapped by replay.Recorder during recording. + Source replay.ActionSource + + // Recorder is an optional pre-built *replay.Recorder used as a fallback when Source is nil. + // When Source is set, ReplayController creates a fresh replay.Recorder on each game_replay_record_start with the requested seed, step rate and watched actions/axes. + Recorder *replay.Recorder + + // Actions lists the default watched action names recorded by game_replay_record_start when the caller omits actions. + Actions []string + + // Axes lists the default watched axis names recorded by game_replay_record_start when the caller omits axes. + Axes []string + + // StepRate is the default fixed step rate in steps per second (falls back to Loop.Rate, then 60 when <= 0). + StepRate int + + // Loop is an optional *game.Loop whose Update callback and Rate serve as fallbacks when StepFunc or StepRate are unset. + Loop *game.Loop + + // StepFunc advances the simulation by one fixed step of duration dt. + // It is used by game_replay_play when run_to_end is true or steps > 0, and is expected to call the controller's Step method once per update. + StepFunc func(dt time.Duration) + + // SeedFunc, when set, supplies the default seed for game_replay_record_start when the caller omits seed. + SeedFunc func() uint64 + + // ResetFunc, when set, resets the simulation deterministically to seed before playback begins (and before recording begins when reset is true). + ResetFunc func(seed uint64) error + + // OnRecordStart, when set, is called after a recording starts. + OnRecordStart func(name string, seed uint64) + + // OnRecordStop, when set, is called after a recording stops with the stored name and a copy of the completed recording. + OnRecordStop func(name string, rec *replay.Recording) + + // OnReplayStart, when set, is called after ResetFunc succeeds and playback starts. + OnReplayStart func(rec *replay.Recording) + + // OnReplayStop, when set, is called when playback finishes or is stopped early. + OnReplayStop func() + + // SaveDir is an optional root directory on disk where game_replay_record_stop may write YAML recordings when save_path is supplied. + // Relative paths are strictly confined inside SaveDir; when SaveDir is empty, save_path is refused. + SaveDir string +} + +type storedRecording struct { + rec *replay.Recording + metadata map[string]string +} + +// ReplayController coordinates live input forwarding, recording via replay.Recorder, and deterministic playback via replay.Player for MCP tools. +// +// ReplayController implements replay.ActionSource so a game can read inputs from it unconditionally across live play, recording and playback. +type ReplayController struct { + cfg ReplayConfig + + activeRec *replay.Recorder + recordingName string + recordingMeta map[string]string + + player *replay.Player + replayName string + + saved map[string]storedRecording + nextSeq int +} + +// NewReplayController creates a ReplayController from cfg. +func NewReplayController(cfg ReplayConfig) *ReplayController { + cfg.Actions = slices.Clone(cfg.Actions) + cfg.Axes = slices.Clone(cfg.Axes) + return &ReplayController{ + cfg: cfg, + saved: make(map[string]storedRecording), + } +} + +// Replay returns the ReplayController configured on b, or nil if none is set. +func (b *Bridge) Replay() *ReplayController { + if b == nil { + return nil + } + return b.cfg.Replay +} + +// SetReplay replaces the ReplayController configured on b. +func (b *Bridge) SetReplay(ctrl *ReplayController) { + if b == nil { + return + } + b.cfg.Replay = ctrl +} + +// Step advances the active replay.Player, active replay.Recorder or live Source by one fixed step. +// +// When a frame-by-frame replay reached its final recorded step on the previous tick, the next Step finishes playback and resumes live input cleanly. +func (c *ReplayController) Step() { + if c == nil { + return + } + if c.player != nil { + if c.player.Done() { + c.finishReplay() + } else { + c.player.Step() + return + } + } + if c.activeRec != nil { + c.activeRec.Step() + return + } + if c.cfg.Source != nil { + c.cfg.Source.Step() + } +} + +// Pressed reports whether name is pressed on the active input source for the current step. +func (c *ReplayController) Pressed(name string) bool { + if c == nil { + return false + } + if c.player != nil { + return c.player.Pressed(name) + } + if c.activeRec != nil { + return c.activeRec.Pressed(name) + } + if c.cfg.Source != nil { + return c.cfg.Source.Pressed(name) + } + return false +} + +// JustPressed reports whether name became pressed on the active input source on the current step. +func (c *ReplayController) JustPressed(name string) bool { + if c == nil { + return false + } + if c.player != nil { + return c.player.JustPressed(name) + } + if c.activeRec != nil { + return c.activeRec.JustPressed(name) + } + if c.cfg.Source != nil { + return c.cfg.Source.JustPressed(name) + } + return false +} + +// JustReleased reports whether name was released on the active input source on the current step. +func (c *ReplayController) JustReleased(name string) bool { + if c == nil { + return false + } + if c.player != nil { + return c.player.JustReleased(name) + } + if c.activeRec != nil { + return c.activeRec.JustReleased(name) + } + if c.cfg.Source != nil { + return c.cfg.Source.JustReleased(name) + } + return false +} + +// Axis returns the value of axis name on the active input source for the current step. +func (c *ReplayController) Axis(name string) float64 { + if c == nil { + return 0 + } + if c.player != nil { + return c.player.Axis(name) + } + if c.activeRec != nil { + return c.activeRec.Axis(name) + } + if c.cfg.Source != nil { + return c.cfg.Source.Axis(name) + } + return 0 +} + +// Recording reports whether an input recording is currently in progress. +func (c *ReplayController) Recording() bool { + return c != nil && c.activeRec != nil +} + +// Replaying reports whether replay playback is currently in progress (not yet finished). +func (c *ReplayController) Replaying() bool { + return c != nil && c.player != nil && !c.player.Done() +} + +// SaveRecording validates and stores a deep copy of rec under name in c's in-memory store. +func (c *ReplayController) SaveRecording(name string, rec *replay.Recording) error { + if c == nil { + return ErrReplayNotConfigured + } + if name == "" { + return errors.New("mcp: recording name is required") + } + if err := rec.Validate(); err != nil { + return fmt.Errorf("mcp: invalid recording %q: %w", name, err) + } + if c.saved == nil { + c.saved = make(map[string]storedRecording) + } + c.saved[name] = storedRecording{rec: rec.Clone()} + return nil +} + +// GetRecording returns a deep copy of the stored recording named name. +func (c *ReplayController) GetRecording(name string) (*replay.Recording, bool) { + if c == nil { + return nil, false + } + entry, ok := c.saved[name] + if !ok || entry.rec == nil { + return nil, false + } + return entry.rec.Clone(), true +} + +// DeleteRecording removes the stored recording named name and reports whether it existed. +func (c *ReplayController) DeleteRecording(name string) bool { + if c == nil { + return false + } + if _, ok := c.saved[name]; !ok { + return false + } + delete(c.saved, name) + return true +} + +// RecordingNames returns the sorted names of all recordings stored in c. +func (c *ReplayController) RecordingNames() []string { + if c == nil || len(c.saved) == 0 { + return []string{} + } + names := make([]string, 0, len(c.saved)) + for name := range c.saved { + names = append(names, name) + } + slices.Sort(names) + return names +} + +func (c *ReplayController) defaultStepRate() int { + if c.cfg.StepRate > 0 { + return c.cfg.StepRate + } + if c.cfg.Loop != nil && c.cfg.Loop.Rate > 0 { + return c.cfg.Loop.Rate + } + return defaultReplayStepRate +} + +func (c *ReplayController) stepFunc() func(time.Duration) { + if c.cfg.StepFunc != nil { + return c.cfg.StepFunc + } + if c.cfg.Loop != nil { + return c.cfg.Loop.Update + } + return nil +} + +func (c *ReplayController) finishReplay() { + if c.player == nil { + return + } + c.player = nil + c.replayName = "" + if c.cfg.OnReplayStop != nil { + c.cfg.OnReplayStop() + } +} + +func (c *ReplayController) allocateName() string { + for { + c.nextSeq++ + candidate := fmt.Sprintf("recording_%d", c.nextSeq) + if _, exists := c.saved[candidate]; !exists { + return candidate + } + } +} + +// ReplayStatusResult is the JSON result of game_replay_status. +type ReplayStatusResult struct { + Recording bool `json:"recording"` + RecordingName string `json:"recording_name,omitempty"` + RecordingSeed uint64 `json:"recording_seed,omitempty"` + RecordingStepRate int `json:"recording_step_rate,omitempty"` + RecordingMetadata map[string]string `json:"recording_metadata,omitempty"` + FramesRecorded int `json:"frames_recorded"` + Replaying bool `json:"replaying"` + ReplayDone bool `json:"replay_done,omitempty"` + ReplayName string `json:"replay_name,omitempty"` + ReplayFrame int `json:"replay_frame"` + ReplayTotalFrames int `json:"replay_total_frames"` + SavedRecordings []string `json:"saved_recordings"` +} + +// ReplayRecordStartResult is the JSON result of game_replay_record_start. +type ReplayRecordStartResult struct { + Recording bool `json:"recording"` + Name string `json:"name"` + Seed uint64 `json:"seed"` + StepRate int `json:"step_rate"` + Actions []string `json:"actions,omitempty"` + Axes []string `json:"axes,omitempty"` + Metadata map[string]string `json:"metadata,omitempty"` +} + +// ReplayRecordStopResult is the JSON result of game_replay_record_stop. +type ReplayRecordStopResult struct { + Name string `json:"name"` + Frames int `json:"frames"` + Seed uint64 `json:"seed"` + StepRate int `json:"step_rate"` + Events int `json:"events"` + Actions []string `json:"actions,omitempty"` + Axes []string `json:"axes,omitempty"` + Metadata map[string]string `json:"metadata,omitempty"` + SavedPath string `json:"saved_path,omitempty"` + YAML string `json:"yaml"` +} + +// ReplayPlayResult is the JSON result of game_replay_play. +type ReplayPlayResult struct { + Name string `json:"name,omitempty"` + Seed uint64 `json:"seed"` + StepRate int `json:"step_rate"` + Replaying bool `json:"replaying"` + Completed bool `json:"completed"` + FramesPlayed int `json:"frames_played"` + ReplayTotalFrames int `json:"replay_total_frames"` +} + +// ReplayStopResult is the JSON result of game_replay_stop. +type ReplayStopResult struct { + Stopped bool `json:"stopped"` + Name string `json:"name,omitempty"` + FramesPlayed int `json:"frames_played"` + ReplayTotalFrames int `json:"replay_total_frames"` +} + +// ReplaySummary describes one stored recording returned by game_replay_list. +type ReplaySummary struct { + Name string `json:"name"` + Frames int `json:"frames"` + Seed uint64 `json:"seed"` + StepRate int `json:"step_rate"` + Events int `json:"events"` + Actions []string `json:"actions,omitempty"` + Axes []string `json:"axes,omitempty"` + Metadata map[string]string `json:"metadata,omitempty"` +} + +// ReplayListResult is the JSON result of game_replay_list. +type ReplayListResult struct { + Count int `json:"count"` + Recordings []ReplaySummary `json:"recordings"` +} + +var ( + schemaReplayStatus = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "properties": {} + }`) + + schemaReplayRecordStart = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "type": "string", + "description": "Name under which the recording will be stored when stopped (auto-generated when omitted)." + }, + "seed": { + "type": "integer", + "minimum": 0, + "description": "Deterministic RNG seed recorded in the replay header (defaults to ReplayConfig.SeedFunc or 0)." + }, + "step_rate": { + "type": "integer", + "minimum": 1, + "description": "Fixed simulation step rate in steps per second (defaults to ReplayConfig.StepRate, Loop.Rate, or 60)." + }, + "actions": { + "type": "array", + "items": {"type": "string"}, + "description": "Override the watched action names for this recording (defaults to ReplayConfig.Actions)." + }, + "axes": { + "type": "array", + "items": {"type": "string"}, + "description": "Override the watched axis names for this recording (defaults to ReplayConfig.Axes)." + }, + "metadata": { + "type": "object", + "additionalProperties": {"type": "string"}, + "description": "Optional string key-value metadata stored alongside the recording." + }, + "reset": { + "type": "boolean", + "description": "Call ReplayConfig.ResetFunc(seed) before recording starts (default false)." + } + } + }`) + + schemaReplayRecordStop = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "type": "string", + "description": "Optional override name under which to store the finished recording." + }, + "save_path": { + "type": "string", + "description": "Optional relative file path under ReplayConfig.SaveDir to also write the deterministic YAML recording." + } + } + }`) + + schemaReplayPlay = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "type": "string", + "description": "Name of a stored recording from game_replay_list. Mutually exclusive with yaml." + }, + "yaml": { + "type": "string", + "description": "Inline deterministic replay YAML text (format version 2). Mutually exclusive with name." + }, + "run_to_end": { + "type": "boolean", + "description": "Advance every recorded frame synchronously via ReplayConfig.StepFunc or Loop.Update before returning (default false)." + }, + "steps": { + "type": "integer", + "minimum": 1, + "description": "Advance up to this many recorded frames synchronously via ReplayConfig.StepFunc or Loop.Update. Mutually exclusive with run_to_end." + }, + "reset": { + "type": "boolean", + "description": "Call ReplayConfig.ResetFunc(recording.Seed) before playback starts (default true when ResetFunc is configured)." + } + } + }`) + + schemaReplayStop = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "properties": {} + }`) + + schemaReplayList = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "properties": {} + }`) +) + +func (b *Bridge) replayTools() []automation.Tool { + return []automation.Tool{ + { + Name: ToolReplayStatus, + Description: "Return the current input recording and replay playback status, frame progress and saved recording names.", + InputSchema: schemaReplayStatus, + Handler: b.handleReplayStatus, + }, + { + Name: ToolReplayRecordStart, + Description: "Start recording per-step game inputs into a named recording.", + InputSchema: schemaReplayRecordStart, + Handler: b.handleReplayRecordStart, + }, + { + Name: ToolReplayRecordStop, + Description: "Stop the active input recording, store it in memory (and optionally under SaveDir) and return its deterministic YAML text and summary.", + InputSchema: schemaReplayRecordStop, + Handler: b.handleReplayRecordStop, + }, + { + Name: ToolReplayPlay, + Description: "Replay a stored recording by name or an inline YAML recording, optionally resetting to its seed and advancing frames to completion.", + InputSchema: schemaReplayPlay, + Handler: b.handleReplayPlay, + }, + { + Name: ToolReplayStop, + Description: "Stop an active replay playback cleanly.", + InputSchema: schemaReplayStop, + Handler: b.handleReplayStop, + }, + { + Name: ToolReplayList, + Description: "List stored input recordings with their frame counts, seeds, step rates and metadata.", + InputSchema: schemaReplayList, + Handler: b.handleReplayList, + }, + } +} + +func (b *Bridge) requireReplay() (*ReplayController, error) { + if b == nil || b.cfg.Replay == nil { + return nil, ErrReplayNotConfigured + } + return b.cfg.Replay, nil +} + +func (b *Bridge) handleReplayStatus(_ context.Context, raw json.RawMessage) (any, error) { + if _, err := decodeArgs[struct{}](raw); err != nil { + return nil, err + } + c, err := b.requireReplay() + if err != nil { + return nil, err + } + res := ReplayStatusResult{ + SavedRecordings: c.RecordingNames(), + } + if c.activeRec != nil { + res.Recording = true + res.RecordingName = c.recordingName + res.RecordingSeed = c.activeRec.Seed() + res.RecordingStepRate = c.activeRec.Rate() + res.RecordingMetadata = cloneStringMap(c.recordingMeta) + res.FramesRecorded = c.activeRec.TotalSteps() + } + if c.player != nil { + res.ReplayName = c.replayName + res.ReplayFrame = c.player.StepIndex() + res.ReplayTotalFrames = c.player.TotalSteps() + if c.player.Done() { + res.ReplayDone = true + } else { + res.Replaying = true + } + } + return res, nil +} + +type replayRecordStartArgs struct { + Name string `json:"name"` + Seed *uint64 `json:"seed"` + StepRate int `json:"step_rate"` + Actions []string `json:"actions"` + Axes []string `json:"axes"` + Metadata map[string]string `json:"metadata"` + Reset bool `json:"reset"` +} + +func (b *Bridge) handleReplayRecordStart(_ context.Context, raw json.RawMessage) (any, error) { + args, err := decodeArgs[replayRecordStartArgs](raw) + if err != nil { + return nil, err + } + c, err := b.requireReplay() + if err != nil { + return nil, err + } + if args.StepRate < 0 { + return nil, fmt.Errorf("mcp: step_rate must be >= 0 (got %d)", args.StepRate) + } + if c.activeRec != nil { + return nil, ErrAlreadyRecording + } + if c.player != nil { + if !c.player.Done() { + return nil, fmt.Errorf("mcp: cannot start recording: %w", ErrAlreadyReplaying) + } + c.finishReplay() + } + if c.cfg.Source == nil && c.cfg.Recorder == nil { + return nil, errors.New("mcp: replay controller has no input source configured") + } + + var seed uint64 + if args.Seed != nil { + seed = *args.Seed + } else if c.cfg.SeedFunc != nil { + seed = c.cfg.SeedFunc() + } + + var rec *replay.Recorder + if c.cfg.Source != nil { + rate := args.StepRate + if rate <= 0 { + rate = c.defaultStepRate() + } + actions := c.cfg.Actions + if len(args.Actions) > 0 { + actions = args.Actions + } + axes := c.cfg.Axes + if len(args.Axes) > 0 { + axes = args.Axes + } + rec = replay.NewRecorder(c.cfg.Source, seed, rate, actions, axes) + } else { + if args.StepRate > 0 && args.StepRate != c.cfg.Recorder.Rate() { + return nil, fmt.Errorf("mcp: cannot override step_rate (%d) when using pre-built Recorder (rate %d); configure ReplayConfig.Source instead", args.StepRate, c.cfg.Recorder.Rate()) + } + if len(args.Actions) > 0 || len(args.Axes) > 0 { + return nil, errors.New("mcp: cannot override actions or axes when using pre-built Recorder; configure ReplayConfig.Source instead") + } + rec = c.cfg.Recorder + } + + if args.Reset { + if c.cfg.ResetFunc == nil { + return nil, errors.New("mcp: reset requested but no ResetFunc configured") + } + if err := c.cfg.ResetFunc(seed); err != nil { + return nil, fmt.Errorf("mcp: reset before record failed: %w", err) + } + } + if c.cfg.Source == nil { + rec.Reset(seed) + } + + name := strings.TrimSpace(args.Name) + if name == "" { + name = c.allocateName() + } + meta := cloneStringMap(args.Metadata) + + c.activeRec = rec + c.recordingName = name + c.recordingMeta = meta + if c.cfg.OnRecordStart != nil { + c.cfg.OnRecordStart(name, seed) + } + + snap := rec.Recording() + return ReplayRecordStartResult{ + Recording: true, + Name: name, + Seed: snap.Seed, + StepRate: snap.Rate, + Actions: snap.Actions, + Axes: snap.Axes, + Metadata: cloneStringMap(meta), + }, nil +} + +type replayRecordStopArgs struct { + Name string `json:"name"` + SavePath string `json:"save_path"` +} + +func (b *Bridge) handleReplayRecordStop(_ context.Context, raw json.RawMessage) (any, error) { + args, err := decodeArgs[replayRecordStopArgs](raw) + if err != nil { + return nil, err + } + c, err := b.requireReplay() + if err != nil { + return nil, err + } + if c.activeRec == nil { + return nil, ErrNotRecording + } + + var targetPath, cleanRel string + if args.SavePath != "" { + targetPath, cleanRel, err = resolveSafeSavePath(c.cfg.SaveDir, args.SavePath) + if err != nil { + return nil, err + } + } + + rec := c.activeRec.Recording() + yamlBytes, err := rec.Encode() + if err != nil { + return nil, fmt.Errorf("mcp: encode recording: %w", err) + } + + if targetPath != "" { + if err := os.MkdirAll(filepath.Dir(targetPath), 0o755); err != nil { + return nil, fmt.Errorf("mcp: create recording directory: %w", err) + } + if err := os.WriteFile(targetPath, yamlBytes, 0o644); err != nil { + return nil, fmt.Errorf("mcp: write recording %q: %w", cleanRel, err) + } + } + + name := strings.TrimSpace(args.Name) + if name == "" { + name = c.recordingName + } + meta := cloneStringMap(c.recordingMeta) + + if c.saved == nil { + c.saved = make(map[string]storedRecording) + } + c.saved[name] = storedRecording{ + rec: rec.Clone(), + metadata: cloneStringMap(meta), + } + + c.activeRec = nil + c.recordingName = "" + c.recordingMeta = nil + + if c.cfg.OnRecordStop != nil { + c.cfg.OnRecordStop(name, rec.Clone()) + } + + return ReplayRecordStopResult{ + Name: name, + Frames: rec.TotalSteps, + Seed: rec.Seed, + StepRate: rec.Rate, + Events: len(rec.Events), + Actions: slices.Clone(rec.Actions), + Axes: slices.Clone(rec.Axes), + Metadata: meta, + SavedPath: cleanRel, + YAML: string(yamlBytes), + }, nil +} + +type replayPlayArgs struct { + Name string `json:"name"` + YAML string `json:"yaml"` + RunToEnd bool `json:"run_to_end"` + Steps int `json:"steps"` + Reset *bool `json:"reset"` +} + +func (b *Bridge) handleReplayPlay(_ context.Context, raw json.RawMessage) (any, error) { + args, err := decodeArgs[replayPlayArgs](raw) + if err != nil { + return nil, err + } + c, err := b.requireReplay() + if err != nil { + return nil, err + } + if args.Name == "" && args.YAML == "" { + return nil, errors.New("mcp: either name or yaml is required") + } + if args.Name != "" && args.YAML != "" { + return nil, errors.New("mcp: specify either name or yaml, not both") + } + if args.Steps < 0 { + return nil, fmt.Errorf("mcp: steps must be >= 0 (got %d)", args.Steps) + } + if args.RunToEnd && args.Steps > 0 { + return nil, errors.New("mcp: cannot specify both run_to_end and steps") + } + if c.activeRec != nil { + return nil, fmt.Errorf("mcp: cannot start replay: %w", ErrAlreadyRecording) + } + if c.player != nil { + if !c.player.Done() { + return nil, ErrAlreadyReplaying + } + c.finishReplay() + } + + var ( + rec *replay.Recording + replayName string + ) + if args.Name != "" { + entry, ok := c.saved[args.Name] + if !ok || entry.rec == nil { + avail := c.RecordingNames() + if len(avail) == 0 { + return nil, fmt.Errorf("mcp: recording %q not found (no recordings saved)", args.Name) + } + return nil, fmt.Errorf("mcp: recording %q not found (available: %s)", args.Name, strings.Join(avail, ", ")) + } + rec = entry.rec.Clone() + replayName = args.Name + } else { + decoded, err := replay.Decode([]byte(args.YAML)) + if err != nil { + return nil, fmt.Errorf("mcp: invalid replay yaml: %w", err) + } + rec = decoded + } + + if err := rec.Validate(); err != nil { + return nil, fmt.Errorf("mcp: invalid recording: %w", err) + } + + var stepFn func(time.Duration) + if args.RunToEnd || args.Steps > 0 { + stepFn = c.stepFunc() + if stepFn == nil { + return nil, errors.New("mcp: advancing replay frames requires ReplayConfig.StepFunc or Loop.Update") + } + } + + doReset := true + if args.Reset != nil { + doReset = *args.Reset + if doReset && c.cfg.ResetFunc == nil { + return nil, errors.New("mcp: reset requested but no ResetFunc configured") + } + } + + player := replay.NewPlayer(rec) + c.player = player + c.replayName = replayName + + if doReset && c.cfg.ResetFunc != nil { + if err := c.cfg.ResetFunc(rec.Seed); err != nil { + c.player = nil + c.replayName = "" + return nil, fmt.Errorf("mcp: reset before replay failed: %w", err) + } + } + if c.cfg.OnReplayStart != nil { + c.cfg.OnReplayStart(rec.Clone()) + } + + dt := rec.StepDuration() + switch { + case args.RunToEnd: + for range rec.TotalSteps { + if c.player != player { + break + } + stepFn(dt) + } + framesPlayed := player.StepIndex() + completed := player.Done() + if c.player == player && completed { + c.finishReplay() + } + return ReplayPlayResult{ + Name: replayName, + Seed: rec.Seed, + StepRate: rec.Rate, + Replaying: c.player == player && !completed, + Completed: completed, + FramesPlayed: framesPlayed, + ReplayTotalFrames: rec.TotalSteps, + }, nil + + case args.Steps > 0: + for range args.Steps { + if c.player != player || player.Done() { + break + } + stepFn(dt) + } + framesPlayed := player.StepIndex() + completed := player.Done() + if c.player == player && completed { + c.finishReplay() + } + return ReplayPlayResult{ + Name: replayName, + Seed: rec.Seed, + StepRate: rec.Rate, + Replaying: c.player == player && !completed, + Completed: completed, + FramesPlayed: framesPlayed, + ReplayTotalFrames: rec.TotalSteps, + }, nil + + default: + completed := player.Done() + if completed { + c.finishReplay() + } + return ReplayPlayResult{ + Name: replayName, + Seed: rec.Seed, + StepRate: rec.Rate, + Replaying: !completed, + Completed: completed, + FramesPlayed: player.StepIndex(), + ReplayTotalFrames: rec.TotalSteps, + }, nil + } +} + +func (b *Bridge) handleReplayStop(_ context.Context, raw json.RawMessage) (any, error) { + if _, err := decodeArgs[struct{}](raw); err != nil { + return nil, err + } + c, err := b.requireReplay() + if err != nil { + return nil, err + } + if c.player == nil { + return nil, ErrNotReplaying + } + if c.player.Done() { + c.finishReplay() + return nil, ErrNotReplaying + } + res := ReplayStopResult{ + Stopped: true, + Name: c.replayName, + FramesPlayed: c.player.StepIndex(), + ReplayTotalFrames: c.player.TotalSteps(), + } + c.finishReplay() + return res, nil +} + +func (b *Bridge) handleReplayList(_ context.Context, raw json.RawMessage) (any, error) { + if _, err := decodeArgs[struct{}](raw); err != nil { + return nil, err + } + c, err := b.requireReplay() + if err != nil { + return nil, err + } + names := c.RecordingNames() + out := ReplayListResult{ + Count: len(names), + Recordings: make([]ReplaySummary, 0, len(names)), + } + for _, name := range names { + entry := c.saved[name] + if entry.rec == nil { + continue + } + out.Recordings = append(out.Recordings, ReplaySummary{ + Name: name, + Frames: entry.rec.TotalSteps, + Seed: entry.rec.Seed, + StepRate: entry.rec.Rate, + Events: len(entry.rec.Events), + Actions: slices.Clone(entry.rec.Actions), + Axes: slices.Clone(entry.rec.Axes), + Metadata: cloneStringMap(entry.metadata), + }) + } + return out, nil +} + +func cloneStringMap(m map[string]string) map[string]string { + if len(m) == 0 { + return nil + } + return maps.Clone(m) +} + +func resolveSafeSavePath(saveDir, rel string) (absTarget, cleanRel string, err error) { + if strings.TrimSpace(saveDir) == "" { + return "", "", errors.New("mcp: save_path requires ReplayConfig.SaveDir to be configured") + } + if strings.TrimSpace(rel) == "" { + return "", "", errors.New("mcp: save_path must not be empty") + } + if filepath.IsAbs(rel) || strings.HasPrefix(rel, "/") || strings.HasPrefix(rel, "\\") || filepath.VolumeName(rel) != "" { + return "", "", fmt.Errorf("mcp: save_path %q must be relative to SaveDir", rel) + } + cleaned := filepath.Clean(rel) + if cleaned == "." || cleaned == ".." || strings.HasPrefix(cleaned, ".."+string(filepath.Separator)) { + return "", "", fmt.Errorf("mcp: save_path %q escapes SaveDir", rel) + } + absRoot, err := filepath.Abs(saveDir) + if err != nil { + return "", "", fmt.Errorf("mcp: resolve SaveDir: %w", err) + } + target := filepath.Join(absRoot, cleaned) + check, err := filepath.Rel(absRoot, target) + if err != nil || check == "." || check == ".." || strings.HasPrefix(check, ".."+string(filepath.Separator)) { + return "", "", fmt.Errorf("mcp: save_path %q escapes SaveDir", rel) + } + return target, filepath.ToSlash(cleaned), nil +} diff --git a/packages/game/mcp/replay_test.go b/packages/game/mcp/replay_test.go new file mode 100644 index 00000000..f47aed70 --- /dev/null +++ b/packages/game/mcp/replay_test.go @@ -0,0 +1,808 @@ +package mcp_test + +import ( + "encoding/json" + "errors" + "math" + "math/rand/v2" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game" + "github.com/nsgo-dev/game/packages/game/entities" + "github.com/nsgo-dev/game/packages/game/input" + "github.com/nsgo-dev/game/packages/game/mcp" + "github.com/nsgo-dev/game/packages/game/replay" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +type replayStatsComp struct { + Score int `json:"score"` + Jumps int `json:"jumps"` + Dashes int `json:"dashes"` + RNGSum uint64 `json:"rng_sum"` + Grounded bool `json:"grounded"` +} + +type deterministicSim struct { + world *entities.World + player entities.Entity + rng *rand.Rand + seed uint64 + step int + score int + jumps int + dashes int + rngSum uint64 +} + +type deterministicSnapshot struct { + Seed uint64 + Step int + PosXBits uint32 + PosYBits uint32 + VelXBits uint32 + VelYBits uint32 + Score int + Jumps int + Dashes int + RNGSum uint64 + Grounded bool +} + +func newDeterministicSim(seed uint64) *deterministicSim { + s := &deterministicSim{} + s.Reset(seed) + return s +} + +func (s *deterministicSim) Reset(seed uint64) { + if s.world != nil && !s.world.Disposed() { + s.world.Dispose() + } + w := entities.NewWorld() + _ = entities.RegisterCodec[posComp](w, "position") + _ = entities.RegisterCodec[velComp](w, "velocity") + _ = entities.RegisterCodec[replayStatsComp](w, "stats") + + p := w.Spawn() + entities.Set(w, p, posComp{X: 16, Y: 0}) + entities.Set(w, p, velComp{VX: 0, VY: 0}) + entities.Set(w, p, replayStatsComp{Grounded: true}) + + s.world = w + s.player = p + s.seed = seed + s.rng = rand.New(rand.NewPCG(seed, seed^0x9e3779b97f4a7c15)) + s.step = 0 + s.score = 0 + s.jumps = 0 + s.dashes = 0 + s.rngSum = 0 +} + +func (s *deterministicSim) Step(src replay.ActionSource, dt time.Duration) { + src.Step() + s.step++ + + sec := float32(dt.Seconds()) + pos, _ := entities.Get[posComp](s.world, s.player) + vel, _ := entities.Get[velComp](s.world, s.player) + st, _ := entities.Get[replayStatsComp](s.world, s.player) + + move := float32(src.Axis("move_x")) + vel.VX = move * 120 + if src.Pressed("dash") { + vel.VX *= 2 + if src.JustPressed("dash") { + s.dashes++ + s.rngSum += s.rng.Uint64() & 0xffff + } + } + if src.JustPressed("jump") && st.Grounded { + vel.VY = 240 + st.Grounded = false + s.jumps++ + s.score += int(s.rng.IntN(50)) + 10 + } + if src.JustReleased("jump") && vel.VY > 100 { + vel.VY = 100 + } + + if !st.Grounded { + vel.VY -= 600 * sec + } + pos.X += vel.VX * sec + pos.Y += vel.VY * sec + if pos.Y <= 0 { + pos.Y = 0 + vel.VY = 0 + st.Grounded = true + } + + if move != 0 { + s.score += 1 + int(s.rng.IntN(3)) + } + s.rngSum ^= s.rng.Uint64() & 0x7fffffff + + st.Score = s.score + st.Jumps = s.jumps + st.Dashes = s.dashes + st.RNGSum = s.rngSum +} + +func (s *deterministicSim) Snapshot() deterministicSnapshot { + pos, _ := entities.Get[posComp](s.world, s.player) + vel, _ := entities.Get[velComp](s.world, s.player) + st, _ := entities.Get[replayStatsComp](s.world, s.player) + return deterministicSnapshot{ + Seed: s.seed, + Step: s.step, + PosXBits: math.Float32bits(pos.X), + PosYBits: math.Float32bits(pos.Y), + VelXBits: math.Float32bits(vel.VX), + VelYBits: math.Float32bits(vel.VY), + Score: st.Score, + Jumps: st.Jumps, + Dashes: st.Dashes, + RNGSum: st.RNGSum, + Grounded: st.Grounded, + } +} + +func TestReplayRecordAndPlaybackDeterminism(t *testing.T) { + actions := input.NewActions() + actions.Bind("left", input.Key("left")) + actions.Bind("right", input.Key("right")) + actions.Bind("jump", input.Key("space")) + actions.Bind("dash", input.Key("shift")) + actions.BindAxis("move_x", "left", "right") + + sim := newDeterministicSim(0) + defer func() { + if sim.world != nil && !sim.world.Disposed() { + sim.world.Dispose() + } + }() + + var ( + cx *core.Scope + ctrl *mcp.ReplayController + resetSeeds []uint64 + recordStarts []string + recordStops []string + replayStarts int + replayStops int + fixedStepRate = 60 + fixedDT = time.Second / time.Duration(fixedStepRate) + ) + + ctrl = mcp.NewReplayController(mcp.ReplayConfig{ + Source: actions, + Actions: []string{"left", "right", "jump", "dash"}, + Axes: []string{"move_x"}, + StepRate: fixedStepRate, + SeedFunc: func() uint64 { return 999 }, + ResetFunc: func(seed uint64) error { + resetSeeds = append(resetSeeds, seed) + actions.Reset() + sim.Reset(seed) + return nil + }, + StepFunc: func(dt time.Duration) { + sim.Step(ctrl, dt) + }, + OnRecordStart: func(name string, _ uint64) { + recordStarts = append(recordStarts, name) + }, + OnRecordStop: func(name string, _ *replay.Recording) { + recordStops = append(recordStops, name) + }, + OnReplayStart: func(*replay.Recording) { + replayStarts++ + }, + OnReplayStop: func() { + replayStops++ + }, + }) + + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + if _, err := mcp.Attach(cx, mcp.Config{ + WorldFunc: func() *entities.World { return sim.world }, + Replay: ctrl, + }); err != nil { + t.Fatal(err) + } + return core.View{} + }) + + // Initial idle status. + status0 := callTool[mcp.ReplayStatusResult](t, app, cx, mcp.ToolReplayStatus, nil) + if status0.Recording || status0.Replaying || status0.FramesRecorded != 0 || len(status0.SavedRecordings) != 0 { + t.Fatalf("initial status = %+v", status0) + } + + // Start recording via MCP with deterministic reset and seed. + const seed uint64 = 123456789 + startRes := callTool[mcp.ReplayRecordStartResult](t, app, cx, mcp.ToolReplayRecordStart, map[string]any{ + "name": "run_alpha", + "seed": seed, + "step_rate": fixedStepRate, + "reset": true, + "metadata": map[string]string{"level": "cavern_1", "agent": "tester"}, + }) + if !startRes.Recording || startRes.Name != "run_alpha" || startRes.Seed != seed || startRes.StepRate != fixedStepRate { + t.Fatalf("startRes = %+v", startRes) + } + if startRes.Metadata["level"] != "cavern_1" || len(recordStarts) != 1 || recordStarts[0] != "run_alpha" { + t.Fatalf("record start metadata/hook mismatch: %+v starts=%v", startRes, recordStarts) + } + + // Drive a varied multi-step input sequence (including step-0 press, holds, taps, release, axis changes). + app.Post(func() { + // Steps 0..14: hold right; tap jump on step 0, release on step 5. + actions.OnKeyDown(core.KeyEvent{Key: "right"}) + actions.OnKeyDown(core.KeyEvent{Key: "space"}) + for range 5 { + sim.Step(ctrl, fixedDT) + } + actions.OnKeyUp(core.KeyEvent{Key: "space"}) + for range 10 { + sim.Step(ctrl, fixedDT) + } + }) + app.Settle() + + // Check mid-recording status via MCP. + statusMid := callTool[mcp.ReplayStatusResult](t, app, cx, mcp.ToolReplayStatus, nil) + if !statusMid.Recording || statusMid.Replaying || statusMid.FramesRecorded != 15 || statusMid.RecordingName != "run_alpha" || statusMid.RecordingSeed != seed { + t.Fatalf("mid-recording status = %+v", statusMid) + } + + // Continue recording: dash right, then switch to left + jump, then idle coast. + app.Post(func() { + actions.OnKeyDown(core.KeyEvent{Key: "shift"}) + for range 8 { + sim.Step(ctrl, fixedDT) + } + actions.OnKeyUp(core.KeyEvent{Key: "right"}) + actions.OnKeyUp(core.KeyEvent{Key: "shift"}) + actions.OnKeyDown(core.KeyEvent{Key: "left"}) + actions.Trigger("jump") // single-step latched tap + for range 12 { + sim.Step(ctrl, fixedDT) + } + actions.OnKeyUp(core.KeyEvent{Key: "left"}) + for range 10 { + sim.Step(ctrl, fixedDT) + } + }) + app.Settle() + + // Capture expected final state and MCP entity inspection output before stopping. + wantSnap := sim.Snapshot() + wantEntity := callTool[mcp.EntityInspectResult](t, app, cx, mcp.ToolEntityInspect, map[string]any{ + "ref": mcp.FormatEntityRef(sim.player), + }) + if wantSnap.Step != 45 || wantSnap.Jumps == 0 || wantSnap.Dashes == 0 || wantSnap.Score == 0 { + t.Fatalf("expected non-trivial simulation state, got %+v", wantSnap) + } + + // Stop recording via MCP. + stopRes := callTool[mcp.ReplayRecordStopResult](t, app, cx, mcp.ToolReplayRecordStop, nil) + if stopRes.Name != "run_alpha" || stopRes.Frames != 45 || stopRes.Seed != seed || stopRes.StepRate != fixedStepRate { + t.Fatalf("stopRes = %+v", stopRes) + } + if stopRes.Events == 0 || !strings.Contains(stopRes.YAML, "version: 2") || !strings.Contains(stopRes.YAML, "total_steps: 45") { + t.Fatalf("unexpected YAML in stopRes: %s", stopRes.YAML) + } + if len(recordStops) != 1 || recordStops[0] != "run_alpha" { + t.Fatalf("recordStops = %v", recordStops) + } + + // List recordings via MCP. + listRes := callTool[mcp.ReplayListResult](t, app, cx, mcp.ToolReplayList, nil) + if listRes.Count != 1 || len(listRes.Recordings) != 1 || listRes.Recordings[0].Name != "run_alpha" || listRes.Recordings[0].Frames != 45 || listRes.Recordings[0].Metadata["agent"] != "tester" { + t.Fatalf("listRes = %+v", listRes) + } + + // Scramble the game state with a different seed and random steps so it diverges completely. + app.Post(func() { + sim.Reset(7777) + actions.OnKeyDown(core.KeyEvent{Key: "left"}) + for range 20 { + sim.Step(ctrl, fixedDT) + } + actions.Reset() + }) + app.Settle() + if reflect.DeepEqual(sim.Snapshot(), wantSnap) { + t.Fatal("scrambled state unexpectedly matched wantSnap") + } + + // 1) Replay by stored name with run_to_end: true. + playNameRes := callTool[mcp.ReplayPlayResult](t, app, cx, mcp.ToolReplayPlay, map[string]any{ + "name": "run_alpha", + "run_to_end": true, + }) + if !playNameRes.Completed || playNameRes.Replaying || playNameRes.FramesPlayed != 45 || playNameRes.ReplayTotalFrames != 45 || playNameRes.Seed != seed { + t.Fatalf("playNameRes = %+v", playNameRes) + } + gotSnapName := sim.Snapshot() + if gotSnapName != wantSnap { + t.Fatalf("replay by name state mismatch:\n got: %+v\nwant: %+v", gotSnapName, wantSnap) + } + gotEntityName := callTool[mcp.EntityInspectResult](t, app, cx, mcp.ToolEntityInspect, map[string]any{ + "ref": mcp.FormatEntityRef(sim.player), + }) + if !reflect.DeepEqual(gotEntityName, wantEntity) { + t.Fatalf("replay by name entity inspect mismatch:\n got: %+v\nwant: %+v", gotEntityName, wantEntity) + } + + // 2) Scramble again and replay from inline YAML text. + app.Post(func() { + sim.Reset(1) + for range 5 { + sim.Step(ctrl, fixedDT) + } + }) + app.Settle() + + playYAMLRes := callTool[mcp.ReplayPlayResult](t, app, cx, mcp.ToolReplayPlay, map[string]any{ + "yaml": stopRes.YAML, + "run_to_end": true, + }) + if !playYAMLRes.Completed || playYAMLRes.Replaying || playYAMLRes.FramesPlayed != 45 || playYAMLRes.Seed != seed { + t.Fatalf("playYAMLRes = %+v", playYAMLRes) + } + if got := sim.Snapshot(); got != wantSnap { + t.Fatalf("replay from inline YAML mismatch:\n got: %+v\nwant: %+v", got, wantSnap) + } + + // 3) Scramble again and replay frame-by-frame (run_to_end: false). + app.Post(func() { + sim.Reset(2) + }) + app.Settle() + + playStepRes := callTool[mcp.ReplayPlayResult](t, app, cx, mcp.ToolReplayPlay, map[string]any{ + "name": "run_alpha", + }) + if !playStepRes.Replaying || playStepRes.Completed || playStepRes.FramesPlayed != 0 || playStepRes.ReplayTotalFrames != 45 { + t.Fatalf("frame-by-frame play start = %+v", playStepRes) + } + + // Advance 20 frames manually. + app.Post(func() { + for range 20 { + sim.Step(ctrl, fixedDT) + } + }) + app.Settle() + + midPlay := callTool[mcp.ReplayStatusResult](t, app, cx, mcp.ToolReplayStatus, nil) + if !midPlay.Replaying || midPlay.ReplayDone || midPlay.ReplayFrame != 20 || midPlay.ReplayTotalFrames != 45 || midPlay.ReplayName != "run_alpha" { + t.Fatalf("mid-replay status = %+v", midPlay) + } + + // Advance remaining 25 frames to reach exact end state. + app.Post(func() { + for range 25 { + sim.Step(ctrl, fixedDT) + } + }) + app.Settle() + + endPlay := callTool[mcp.ReplayStatusResult](t, app, cx, mcp.ToolReplayStatus, nil) + if endPlay.Replaying || !endPlay.ReplayDone || endPlay.ReplayFrame != 45 || endPlay.ReplayTotalFrames != 45 { + t.Fatalf("end-replay status = %+v", endPlay) + } + if got := sim.Snapshot(); got != wantSnap { + t.Fatalf("frame-by-frame replay mismatch:\n got: %+v\nwant: %+v", got, wantSnap) + } + + // Stepping one more tick transitions cleanly back to live input and fires OnReplayStop. + app.Post(func() { + actions.OnKeyDown(core.KeyEvent{Key: "right"}) + sim.Step(ctrl, fixedDT) + if !ctrl.Pressed("right") { + t.Error("expected live input to resume after replay finished") + } + actions.Reset() + }) + app.Settle() + + afterLive := callTool[mcp.ReplayStatusResult](t, app, cx, mcp.ToolReplayStatus, nil) + if afterLive.Replaying || afterLive.ReplayDone || afterLive.ReplayFrame != 0 || afterLive.ReplayTotalFrames != 0 { + t.Fatalf("status after returning to live input = %+v", afterLive) + } + if replayStarts != 3 || replayStops != 3 { + t.Fatalf("replay hooks = (starts=%d, stops=%d), want (3, 3)", replayStarts, replayStops) + } + if len(resetSeeds) != 4 { // 1 record(reset:true) + 3 replays + t.Fatalf("resetSeeds = %v, want 4 resets", resetSeeds) + } + for i, gotSeed := range resetSeeds { + if gotSeed != seed { + t.Fatalf("resetSeeds[%d] = %d, want %d", i, gotSeed, seed) + } + } +} + +func TestReplayStepChunkLoopFallbackAndEarlyStop(t *testing.T) { + actions := input.NewActions() + actions.Bind("jump", input.Key("space")) + + var ( + cx *core.Scope + ctrl *mcp.ReplayController + stepsRun int + jumpPress int + stopCalled int + ) + + loop := &game.Loop{ + Rate: 30, + Update: func(time.Duration) { + ctrl.Step() + stepsRun++ + if ctrl.JustPressed("jump") { + jumpPress++ + } + }, + } + + ctrl = mcp.NewReplayController(mcp.ReplayConfig{ + Source: actions, + Actions: []string{"jump"}, + Loop: loop, + ResetFunc: func(uint64) error { + stepsRun = 0 + jumpPress = 0 + return nil + }, + OnReplayStop: func() { + stopCalled++ + }, + }) + + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + if _, err := mcp.Attach(cx, mcp.Config{Replay: ctrl}); err != nil { + t.Fatal(err) + } + return core.View{} + }) + + // Start with omitted name and step_rate (should auto-name "recording_1" and inherit Loop.Rate=30). + recStart := callTool[mcp.ReplayRecordStartResult](t, app, cx, mcp.ToolReplayRecordStart, nil) + if recStart.Name != "recording_1" || recStart.StepRate != 30 { + t.Fatalf("recStart = %+v", recStart) + } + app.Post(func() { + for i := range 20 { + if i == 2 || i == 10 { + actions.Trigger("jump") + } + loop.Update(time.Second / 30) + } + }) + app.Settle() + + recStop := callTool[mcp.ReplayRecordStopResult](t, app, cx, mcp.ToolReplayRecordStop, map[string]any{ + "name": "jump_demo", + }) + if recStop.Name != "jump_demo" || recStop.Frames != 20 || recStop.StepRate != 30 { + t.Fatalf("recStop = %+v", recStop) + } + + // Advance only 5 steps via Loop.Update fallback, then stop early. + playRes := callTool[mcp.ReplayPlayResult](t, app, cx, mcp.ToolReplayPlay, map[string]any{ + "name": "jump_demo", + "steps": 5, + }) + if !playRes.Replaying || playRes.Completed || playRes.FramesPlayed != 5 || playRes.ReplayTotalFrames != 20 { + t.Fatalf("partial playRes = %+v", playRes) + } + if stepsRun != 5 || jumpPress != 1 { + t.Fatalf("after 5 steps: stepsRun=%d jumpPress=%d, want 5, 1", stepsRun, jumpPress) + } + + stopRes := callTool[mcp.ReplayStopResult](t, app, cx, mcp.ToolReplayStop, nil) + if !stopRes.Stopped || stopRes.Name != "jump_demo" || stopRes.FramesPlayed != 5 || stopRes.ReplayTotalFrames != 20 { + t.Fatalf("stopRes = %+v", stopRes) + } + if stopCalled != 1 || ctrl.Replaying() { + t.Fatalf("expected OnReplayStop once and idle state, stopCalled=%d replaying=%v", stopCalled, ctrl.Replaying()) + } +} + +func TestReplaySaveDirAndPathSecurity(t *testing.T) { + saveDir := t.TempDir() + actions := input.NewActions() + actions.Bind("fire", input.Key("f")) + + ctrl := mcp.NewReplayController(mcp.ReplayConfig{ + Source: actions, + Actions: []string{"fire"}, + SaveDir: saveDir, + }) + + var cx *core.Scope + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + if _, err := mcp.Attach(cx, mcp.Config{Replay: ctrl}); err != nil { + t.Fatal(err) + } + return core.View{} + }) + + _ = callTool[mcp.ReplayRecordStartResult](t, app, cx, mcp.ToolReplayRecordStart, map[string]any{ + "name": "boss_fight", + "seed": 42, + }) + app.Post(func() { + actions.Trigger("fire") + ctrl.Step() + ctrl.Step() + }) + app.Settle() + + // Unsafe paths must fail WITHOUT stopping the active recording. + for _, badPath := range []string{"../escape.replay.yaml", "/tmp/abs.replay.yaml", ".", ".."} { + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayRecordStop, map[string]any{"save_path": badPath}); err == nil { + t.Fatalf("expected error for unsafe save_path %q", badPath) + } + if !ctrl.Recording() { + t.Fatalf("unsafe save_path %q unexpectedly aborted active recording", badPath) + } + } + + // Safe nested relative path succeeds and matches replay.LoadFile byte-for-byte. + stopRes := callTool[mcp.ReplayRecordStopResult](t, app, cx, mcp.ToolReplayRecordStop, map[string]any{ + "save_path": "runs/boss_fight.replay.yaml", + }) + if stopRes.SavedPath != "runs/boss_fight.replay.yaml" { + t.Fatalf("SavedPath = %q, want runs/boss_fight.replay.yaml", stopRes.SavedPath) + } + diskPath := filepath.Join(saveDir, "runs", "boss_fight.replay.yaml") + diskBytes, err := os.ReadFile(diskPath) + if err != nil { + t.Fatalf("read saved replay: %v", err) + } + if string(diskBytes) != stopRes.YAML { + t.Fatalf("disk YAML differs from response YAML:\ndisk:\n%s\nresp:\n%s", diskBytes, stopRes.YAML) + } + loaded, err := replay.LoadFile(diskPath) + if err != nil { + t.Fatalf("replay.LoadFile: %v", err) + } + if loaded.Seed != 42 || loaded.TotalSteps != 2 || len(loaded.Events) != 2 { + t.Fatalf("loaded recording = %+v", loaded) + } +} + +func TestReplayControllerHelpersPrebuiltRecorderAndZeroFrame(t *testing.T) { + // Verify all registered tool schemas are valid JSON. + bridge := mcp.New(mcp.Config{}) + for _, tool := range bridge.Tools() { + if !json.Valid(tool.InputSchema) { + t.Fatalf("tool %q has invalid JSON InputSchema: %s", tool.Name, tool.InputSchema) + } + } + + // Pre-built Recorder fallback + Go helper methods. + actions := input.NewActions() + actions.Bind("a", input.Key("a")) + rec := replay.NewRecorder(actions, 7, 60, []string{"a"}, nil) + ctrl := mcp.NewReplayController(mcp.ReplayConfig{ + Recorder: rec, + }) + bridge.SetReplay(ctrl) + if bridge.Replay() != ctrl { + t.Fatal("Bridge.Replay() mismatch") + } + + fixture := &replay.Recording{ + Version: replay.FormatVersion, + Seed: 55, + Rate: 60, + Actions: []string{"a"}, + TotalSteps: 0, + } + if err := ctrl.SaveRecording("recording_1", fixture); err != nil { + t.Fatal(err) + } + if got, ok := ctrl.GetRecording("recording_1"); !ok || got.Seed != 55 { + t.Fatalf("GetRecording = (%+v, %v)", got, ok) + } + + var cx *core.Scope + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + if err := bridge.Attach(cx); err != nil { + t.Fatal(err) + } + return core.View{} + }) + + // Auto-name skips existing "recording_1" and allocates "recording_2". + startRes := callTool[mcp.ReplayRecordStartResult](t, app, cx, mcp.ToolReplayRecordStart, map[string]any{ + "seed": 88, + }) + if startRes.Name != "recording_2" || startRes.Seed != 88 { + t.Fatalf("startRes = %+v", startRes) + } + // Stop immediately with 0 frames. + stopRes := callTool[mcp.ReplayRecordStopResult](t, app, cx, mcp.ToolReplayRecordStop, nil) + if stopRes.Frames != 0 || stopRes.Name != "recording_2" { + t.Fatalf("zero-frame stopRes = %+v", stopRes) + } + // Replay 0-frame recording completes immediately. + playRes := callTool[mcp.ReplayPlayResult](t, app, cx, mcp.ToolReplayPlay, map[string]any{ + "name": "recording_2", + }) + if !playRes.Completed || playRes.Replaying || playRes.FramesPlayed != 0 { + t.Fatalf("zero-frame playRes = %+v", playRes) + } + + if !ctrl.DeleteRecording("recording_1") || ctrl.DeleteRecording("recording_1") { + t.Fatal("DeleteRecording return value mismatch") + } + if names := ctrl.RecordingNames(); len(names) != 1 || names[0] != "recording_2" { + t.Fatalf("RecordingNames = %v", names) + } +} + +func TestReplayErrorHandling(t *testing.T) { + var ( + cx *core.Scope + bridge *mcp.Bridge + ) + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + var err error + bridge, err = mcp.Attach(cx, mcp.Config{}) + if err != nil { + t.Fatal(err) + } + return core.View{} + }) + + // 1. Unconfigured replay controller: all 6 tools return a clear error without panicking. + for _, toolName := range []string{ + mcp.ToolReplayStatus, + mcp.ToolReplayRecordStart, + mcp.ToolReplayRecordStop, + mcp.ToolReplayPlay, + mcp.ToolReplayStop, + mcp.ToolReplayList, + } { + if _, err := callToolRaw(t, app, cx, toolName, nil); err == nil || !strings.Contains(err.Error(), "no replay controller configured") { + t.Fatalf("%s with nil Replay = %v, want unconfigured error", toolName, err) + } + } + + // 2. Unknown JSON fields rejected on every replay tool. + for _, toolName := range []string{ + mcp.ToolReplayStatus, + mcp.ToolReplayRecordStart, + mcp.ToolReplayRecordStop, + mcp.ToolReplayPlay, + mcp.ToolReplayStop, + mcp.ToolReplayList, + } { + if _, err := callToolRaw(t, app, cx, toolName, `{"bogus_field":1}`); err == nil || !strings.Contains(err.Error(), "unknown field") { + t.Fatalf("%s with unknown field = %v, want unknown field error", toolName, err) + } + } + + // 3. Configure controller with no Source/Recorder -> record_start fails cleanly. + bridge.SetReplay(mcp.NewReplayController(mcp.ReplayConfig{})) + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayRecordStart, nil); err == nil || !strings.Contains(err.Error(), "no input source") { + t.Fatalf("record_start without source = %v", err) + } + + // 4. Configure controller with live Source and failing/optional ResetFunc. + actions := input.NewActions() + resetErr := errors.New("boom reset") + failReset := false + ctrl := mcp.NewReplayController(mcp.ReplayConfig{ + Source: actions, + Actions: []string{"jump"}, + ResetFunc: func(uint64) error { + if failReset { + return resetErr + } + return nil + }, + }) + bridge.SetReplay(ctrl) + + // Stop when not recording / not replaying. + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayRecordStop, nil); err == nil || !strings.Contains(err.Error(), "no recording in progress") { + t.Fatalf("record_stop idle = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayStop, nil); err == nil || !strings.Contains(err.Error(), "no replay in progress") { + t.Fatalf("replay_stop idle = %v", err) + } + + // Negative step_rate rejected. + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayRecordStart, map[string]any{"step_rate": -5}); err == nil { + t.Fatal("expected error for negative step_rate") + } + + // Start recording, then verify conflicting start/play and save_path without SaveDir fail cleanly. + _ = callTool[mcp.ReplayRecordStartResult](t, app, cx, mcp.ToolReplayRecordStart, map[string]any{"name": "rec1"}) + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayRecordStart, nil); err == nil || !strings.Contains(err.Error(), "already in progress") { + t.Fatalf("double record_start = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayPlay, map[string]any{"name": "rec1"}); err == nil || !strings.Contains(err.Error(), "recording is already in progress") { + t.Fatalf("play while recording = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayRecordStop, map[string]any{"save_path": "a.yaml"}); err == nil || !strings.Contains(err.Error(), "SaveDir") { + t.Fatalf("save_path without SaveDir = %v", err) + } + app.Post(func() { + ctrl.Step() + ctrl.Step() + }) + app.Settle() + _ = callTool[mcp.ReplayRecordStopResult](t, app, cx, mcp.ToolReplayRecordStop, nil) + + // Invalid play arguments. + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayPlay, `{}`); err == nil || !strings.Contains(err.Error(), "either name or yaml") { + t.Fatalf("play empty = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayPlay, map[string]any{"name": "rec1", "yaml": "version: 2"}); err == nil || !strings.Contains(err.Error(), "not both") { + t.Fatalf("play both name and yaml = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayPlay, map[string]any{"name": "missing"}); err == nil || !strings.Contains(err.Error(), "not found") { + t.Fatalf("play missing name = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayPlay, map[string]any{"yaml": "version: 1\nseed: 0\n"}); err == nil || !strings.Contains(err.Error(), "unsupported version") { + t.Fatalf("play v1 yaml = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayPlay, map[string]any{"yaml": "not: [valid: yaml"}); err == nil { + t.Fatal("expected error for malformed YAML") + } + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayPlay, map[string]any{"name": "rec1", "run_to_end": true, "steps": 2}); err == nil { + t.Fatal("expected error when both run_to_end and steps are set") + } + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayPlay, map[string]any{"name": "rec1", "steps": -1}); err == nil { + t.Fatal("expected error for negative steps") + } + // run_to_end without StepFunc or Loop.Update fails cleanly before starting replay. + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayPlay, map[string]any{"name": "rec1", "run_to_end": true}); err == nil || !strings.Contains(err.Error(), "StepFunc") { + t.Fatalf("run_to_end without StepFunc = %v", err) + } + if ctrl.Replaying() { + t.Fatal("failed play call should not leave controller replaying") + } + + // Failing ResetFunc rolls back playback state cleanly. + failReset = true + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayPlay, map[string]any{"name": "rec1"}); err == nil || !strings.Contains(err.Error(), "boom reset") { + t.Fatalf("play with failing reset = %v", err) + } + if ctrl.Replaying() { + t.Fatal("failed ResetFunc should roll back replay state") + } + failReset = false + + // Start active playback and verify conflicting record_start / play fail cleanly. + _ = callTool[mcp.ReplayPlayResult](t, app, cx, mcp.ToolReplayPlay, map[string]any{"name": "rec1"}) + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayRecordStart, nil); err == nil || !strings.Contains(err.Error(), "replay is already in progress") { + t.Fatalf("record_start while replaying = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayPlay, map[string]any{"name": "rec1"}); err == nil || !strings.Contains(err.Error(), "already in progress") { + t.Fatalf("double play = %v", err) + } + _ = callTool[mcp.ReplayStopResult](t, app, cx, mcp.ToolReplayStop, nil) +} From 7229cbd6cabaa3f4c5fb72e2ecf178a44ce5c61f Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Wed, 25 Nov 2026 04:23:18 +0900 Subject: [PATCH 2/3] fix(mcp): make replays deterministic against the game's loop, rate and seed Synchronous playback now advances the Bridge's loop (Config.Loop/LoopFunc) with Loop.StepNow instead of calling the raw Update callback, so game_loop_status counts the replayed steps and game time; ReplayConfig.Loop is gone and StepFunc stays as an explicit override. game_replay_play refuses a recording whose rate differs from the game's fixed rate (the loop's StepRate, else ReplayConfig.StepRate, else 60), and record_start no longer takes step_rate: recordings are always made at that rate. Record and play share one reset that defaults to true whenever there is something to reset: the Bridge's seed targets (Config.Random, RandomStreams, SetSeed, as game_loop_seed uses) are re-seeded and then ResetFunc runs. A recording started mid-game with default arguments now replays to the same state. steps is capped at MaxLoopSteps in schema and handler, and run_to_end is refused for recordings longer than MaxLoopSteps. ReplayConfig.Source is required (the Recorder fallback left live play without input), it keeps being stepped during playback, and a trailing playback step releases actions held at the end of the recording before live input resumes. save_path writes go through os.Root, so symlinks cannot leave SaveDir, and an existing file or stored name is refused unless overwrite: true. metadata is documented as in-memory only. --- packages/game/mcp/loop.go | 7 +- packages/game/mcp/replay.go | 356 ++++++++++++++++--------------- packages/game/mcp/replay_test.go | 206 ++++++++++++++++-- 3 files changed, 374 insertions(+), 195 deletions(-) diff --git a/packages/game/mcp/loop.go b/packages/game/mcp/loop.go index 21d4231c..8f56c24a 100644 --- a/packages/game/mcp/loop.go +++ b/packages/game/mcp/loop.go @@ -314,6 +314,12 @@ func (b *Bridge) handleLoopSeed(_ context.Context, raw json.RawMessage) (any, er return nil, errors.New("mcp: no random seed target configured (set Config.Random, Config.RandomStreams, or Config.SetSeed)") } seed := *args.Seed + b.applySeed(seed) + return LoopSeedResult{Seed: seed}, nil +} + +// applySeed re-seeds every configured seed target (Config.Random, Config.RandomStreams and Config.SetSeed) with seed. +func (b *Bridge) applySeed(seed uint64) { if b.cfg.Random != nil { b.cfg.Random.SetSeed(seed) } @@ -323,5 +329,4 @@ func (b *Bridge) handleLoopSeed(_ context.Context, raw json.RawMessage) (any, er if b.cfg.SetSeed != nil { b.cfg.SetSeed(seed) } - return LoopSeedResult{Seed: seed}, nil } diff --git a/packages/game/mcp/replay.go b/packages/game/mcp/replay.go index 6a8384a5..ef97a9f8 100644 --- a/packages/game/mcp/replay.go +++ b/packages/game/mcp/replay.go @@ -12,7 +12,7 @@ import ( "strings" "time" - "github.com/nsgo-dev/game/packages/game" + "github.com/nsgo-dev/game/packages/game/loaderr" "github.com/nsgo-dev/game/packages/game/replay" "github.com/nsgo-dev/nsgo/automation" ) @@ -54,33 +54,25 @@ var _ replay.ActionSource = (*ReplayController)(nil) // // Pass the resulting *ReplayController as your game's replay.ActionSource so live play, recording and playback share the exact same update loop. type ReplayConfig struct { - // Source is the live replay.ActionSource (such as *input.Actions) forwarded during live play and wrapped by replay.Recorder during recording. + // Source is the live replay.ActionSource (such as *input.Actions) forwarded during live play and wrapped by a fresh replay.Recorder on each game_replay_record_start. It is required for recording, and it keeps being stepped during playback so its previous-step snapshot is current when live input resumes. Source replay.ActionSource - // Recorder is an optional pre-built *replay.Recorder used as a fallback when Source is nil. - // When Source is set, ReplayController creates a fresh replay.Recorder on each game_replay_record_start with the requested seed, step rate and watched actions/axes. - Recorder *replay.Recorder - // Actions lists the default watched action names recorded by game_replay_record_start when the caller omits actions. Actions []string // Axes lists the default watched axis names recorded by game_replay_record_start when the caller omits axes. Axes []string - // StepRate is the default fixed step rate in steps per second (falls back to Loop.Rate, then 60 when <= 0). + // StepRate is the game's fixed step rate in steps per second when the Bridge has no game loop (Config.Loop or Config.LoopFunc); with a loop, the loop's StepRate is used. It defaults to 60. Recordings are made at this rate, and game_replay_play refuses a recording made at another rate. StepRate int - // Loop is an optional *game.Loop whose Update callback and Rate serve as fallbacks when StepFunc or StepRate are unset. - Loop *game.Loop - - // StepFunc advances the simulation by one fixed step of duration dt. - // It is used by game_replay_play when run_to_end is true or steps > 0, and is expected to call the controller's Step method once per update. + // StepFunc, when set, advances the simulation by one fixed step of duration dt and is expected to call the controller's Step method once. game_replay_play uses it for run_to_end and steps; without it, those advance the Bridge's game loop with Loop.StepNow. StepFunc func(dt time.Duration) // SeedFunc, when set, supplies the default seed for game_replay_record_start when the caller omits seed. SeedFunc func() uint64 - // ResetFunc, when set, resets the simulation deterministically to seed before playback begins (and before recording begins when reset is true). + // ResetFunc, when set, resets the simulation deterministically to seed. With reset (the default when ResetFunc or a seed target is configured), game_replay_record_start and game_replay_play first re-seed the Bridge's seed targets (Config.Random, Config.RandomStreams, Config.SetSeed) and then call ResetFunc, so a recording and its replay start from the same state. ResetFunc func(seed uint64) error // OnRecordStart, when set, is called after a recording starts. @@ -95,8 +87,7 @@ type ReplayConfig struct { // OnReplayStop, when set, is called when playback finishes or is stopped early. OnReplayStop func() - // SaveDir is an optional root directory on disk where game_replay_record_stop may write YAML recordings when save_path is supplied. - // Relative paths are strictly confined inside SaveDir; when SaveDir is empty, save_path is refused. + // SaveDir is an optional root directory on disk where game_replay_record_stop may write YAML recordings when save_path is supplied. Writes go through os.Root, so relative paths and symbolic links cannot leave SaveDir; when SaveDir is empty, save_path is refused. SaveDir string } @@ -117,6 +108,8 @@ type ReplayController struct { player *replay.Player replayName string + // trailing is set once the player has run its trailing step after the final recorded step, so the next Step returns to live input. + trailing bool saved map[string]storedRecording nextSeq int @@ -150,18 +143,23 @@ func (b *Bridge) SetReplay(ctrl *ReplayController) { // Step advances the active replay.Player, active replay.Recorder or live Source by one fixed step. // -// When a frame-by-frame replay reached its final recorded step on the previous tick, the next Step finishes playback and resumes live input cleanly. +// After the final recorded step, one more Step is a trailing playback step that releases actions still held at the end of the recording (firing JustReleased once); the Step after it finishes playback and resumes live input. The live Source is stepped during playback too, so its previous-step snapshot is current when live input resumes. func (c *ReplayController) Step() { if c == nil { return } + if c.player != nil && c.trailing { + c.finishReplay() + } if c.player != nil { if c.player.Done() { - c.finishReplay() - } else { - c.player.Step() - return + c.trailing = true } + c.player.Step() + if c.cfg.Source != nil { + c.cfg.Source.Step() + } + return } if c.activeRec != nil { c.activeRec.Step() @@ -305,32 +303,50 @@ func (c *ReplayController) RecordingNames() []string { return names } -func (c *ReplayController) defaultStepRate() int { +// replayStepRate returns the game's fixed step rate: the active game loop's StepRate, else ReplayConfig.StepRate, else 60. +func (b *Bridge) replayStepRate(c *ReplayController) int { + if l := b.activeLoop(); l != nil { + return l.StepRate() + } if c.cfg.StepRate > 0 { return c.cfg.StepRate } - if c.cfg.Loop != nil && c.cfg.Loop.Rate > 0 { - return c.cfg.Loop.Rate - } return defaultReplayStepRate } -func (c *ReplayController) stepFunc() func(time.Duration) { - if c.cfg.StepFunc != nil { - return c.cfg.StepFunc - } - if c.cfg.Loop != nil { - return c.cfg.Loop.Update +// canResetReplay reports whether a reset before recording or playback has anything to do. +func (b *Bridge) canResetReplay(c *ReplayController) bool { + return c.cfg.ResetFunc != nil || b.seedConfigured() +} + +// resetReplay re-seeds the Bridge's seed targets and then calls ReplayConfig.ResetFunc with seed. +func (b *Bridge) resetReplay(c *ReplayController, seed uint64) error { + b.applySeed(seed) + if c.cfg.ResetFunc != nil { + return c.cfg.ResetFunc(seed) } return nil } +// resolveReplayReset returns whether to reset, given the caller's optional reset argument: it defaults to true whenever a reset has something to do. +func (b *Bridge) resolveReplayReset(c *ReplayController, arg *bool) (bool, error) { + can := b.canResetReplay(c) + if arg == nil { + return can, nil + } + if *arg && !can { + return false, errors.New("mcp: reset requested but neither ReplayConfig.ResetFunc nor a seed target (Config.Random, Config.RandomStreams, Config.SetSeed) is configured") + } + return *arg, nil +} + func (c *ReplayController) finishReplay() { if c.player == nil { return } c.player = nil c.replayName = "" + c.trailing = false if c.cfg.OnReplayStop != nil { c.cfg.OnReplayStop() } @@ -444,11 +460,6 @@ var ( "minimum": 0, "description": "Deterministic RNG seed recorded in the replay header (defaults to ReplayConfig.SeedFunc or 0)." }, - "step_rate": { - "type": "integer", - "minimum": 1, - "description": "Fixed simulation step rate in steps per second (defaults to ReplayConfig.StepRate, Loop.Rate, or 60)." - }, "actions": { "type": "array", "items": {"type": "string"}, @@ -462,11 +473,11 @@ var ( "metadata": { "type": "object", "additionalProperties": {"type": "string"}, - "description": "Optional string key-value metadata stored alongside the recording." + "description": "Optional string key-value metadata kept with the recording in this game's in-memory store and returned by game_replay_status and game_replay_list. It is not part of the recording's YAML, so save_path, the returned yaml and replays from inline yaml do not carry it." }, "reset": { "type": "boolean", - "description": "Call ReplayConfig.ResetFunc(seed) before recording starts (default false)." + "description": "Re-seed Config.Random, Config.RandomStreams and Config.SetSeed with seed and call ReplayConfig.ResetFunc(seed) before recording starts, so the recording starts from the state game_replay_play resets to (default true when ResetFunc or a seed target is configured)." } } }`) @@ -482,6 +493,10 @@ var ( "save_path": { "type": "string", "description": "Optional relative file path under ReplayConfig.SaveDir to also write the deterministic YAML recording." + }, + "overwrite": { + "type": "boolean", + "description": "Replace an existing stored recording of the same name and an existing file at save_path (default false, which refuses both and keeps recording)." } } }`) @@ -500,16 +515,17 @@ var ( }, "run_to_end": { "type": "boolean", - "description": "Advance every recorded frame synchronously via ReplayConfig.StepFunc or Loop.Update before returning (default false)." + "description": "Advance every recorded frame synchronously via ReplayConfig.StepFunc or the game loop's StepNow before returning (default false). Refused for a recording longer than 3600 steps; play it with steps or frame by frame instead." }, "steps": { "type": "integer", "minimum": 1, - "description": "Advance up to this many recorded frames synchronously via ReplayConfig.StepFunc or Loop.Update. Mutually exclusive with run_to_end." + "maximum": 3600, + "description": "Advance up to this many recorded frames synchronously via ReplayConfig.StepFunc or the game loop's StepNow (1..3600). Mutually exclusive with run_to_end." }, "reset": { "type": "boolean", - "description": "Call ReplayConfig.ResetFunc(recording.Seed) before playback starts (default true when ResetFunc is configured)." + "description": "Re-seed Config.Random, Config.RandomStreams and Config.SetSeed with the recording's seed and call ReplayConfig.ResetFunc(seed) before playback starts (default true when ResetFunc or a seed target is configured)." } } }`) @@ -610,11 +626,10 @@ func (b *Bridge) handleReplayStatus(_ context.Context, raw json.RawMessage) (any type replayRecordStartArgs struct { Name string `json:"name"` Seed *uint64 `json:"seed"` - StepRate int `json:"step_rate"` Actions []string `json:"actions"` Axes []string `json:"axes"` Metadata map[string]string `json:"metadata"` - Reset bool `json:"reset"` + Reset *bool `json:"reset"` } func (b *Bridge) handleReplayRecordStart(_ context.Context, raw json.RawMessage) (any, error) { @@ -626,9 +641,6 @@ func (b *Bridge) handleReplayRecordStart(_ context.Context, raw json.RawMessage) if err != nil { return nil, err } - if args.StepRate < 0 { - return nil, fmt.Errorf("mcp: step_rate must be >= 0 (got %d)", args.StepRate) - } if c.activeRec != nil { return nil, ErrAlreadyRecording } @@ -638,8 +650,12 @@ func (b *Bridge) handleReplayRecordStart(_ context.Context, raw json.RawMessage) } c.finishReplay() } - if c.cfg.Source == nil && c.cfg.Recorder == nil { - return nil, errors.New("mcp: replay controller has no input source configured") + if c.cfg.Source == nil { + return nil, errors.New("mcp: replay controller has no input source configured (set ReplayConfig.Source)") + } + doReset, err := b.resolveReplayReset(c, args.Reset) + if err != nil { + return nil, err } var seed uint64 @@ -649,42 +665,21 @@ func (b *Bridge) handleReplayRecordStart(_ context.Context, raw json.RawMessage) seed = c.cfg.SeedFunc() } - var rec *replay.Recorder - if c.cfg.Source != nil { - rate := args.StepRate - if rate <= 0 { - rate = c.defaultStepRate() - } - actions := c.cfg.Actions - if len(args.Actions) > 0 { - actions = args.Actions - } - axes := c.cfg.Axes - if len(args.Axes) > 0 { - axes = args.Axes - } - rec = replay.NewRecorder(c.cfg.Source, seed, rate, actions, axes) - } else { - if args.StepRate > 0 && args.StepRate != c.cfg.Recorder.Rate() { - return nil, fmt.Errorf("mcp: cannot override step_rate (%d) when using pre-built Recorder (rate %d); configure ReplayConfig.Source instead", args.StepRate, c.cfg.Recorder.Rate()) - } - if len(args.Actions) > 0 || len(args.Axes) > 0 { - return nil, errors.New("mcp: cannot override actions or axes when using pre-built Recorder; configure ReplayConfig.Source instead") - } - rec = c.cfg.Recorder + actions := c.cfg.Actions + if len(args.Actions) > 0 { + actions = args.Actions } + axes := c.cfg.Axes + if len(args.Axes) > 0 { + axes = args.Axes + } + rec := replay.NewRecorder(c.cfg.Source, seed, b.replayStepRate(c), actions, axes) - if args.Reset { - if c.cfg.ResetFunc == nil { - return nil, errors.New("mcp: reset requested but no ResetFunc configured") - } - if err := c.cfg.ResetFunc(seed); err != nil { + if doReset { + if err := b.resetReplay(c, seed); err != nil { return nil, fmt.Errorf("mcp: reset before record failed: %w", err) } } - if c.cfg.Source == nil { - rec.Reset(seed) - } name := strings.TrimSpace(args.Name) if name == "" { @@ -712,8 +707,9 @@ func (b *Bridge) handleReplayRecordStart(_ context.Context, raw json.RawMessage) } type replayRecordStopArgs struct { - Name string `json:"name"` - SavePath string `json:"save_path"` + Name string `json:"name"` + SavePath string `json:"save_path"` + Overwrite bool `json:"overwrite"` } func (b *Bridge) handleReplayRecordStop(_ context.Context, raw json.RawMessage) (any, error) { @@ -729,33 +725,34 @@ func (b *Bridge) handleReplayRecordStop(_ context.Context, raw json.RawMessage) return nil, ErrNotRecording } - var targetPath, cleanRel string + var cleanRel string if args.SavePath != "" { - targetPath, cleanRel, err = resolveSafeSavePath(c.cfg.SaveDir, args.SavePath) + cleanRel, err = resolveSafeSavePath(c.cfg.SaveDir, args.SavePath) if err != nil { return nil, err } } + name := strings.TrimSpace(args.Name) + if name == "" { + name = c.recordingName + } + if _, exists := c.saved[name]; exists && !args.Overwrite { + return nil, fmt.Errorf("mcp: a recording named %q is already stored; pass a different name or overwrite: true (still recording)", name) + } + rec := c.activeRec.Recording() yamlBytes, err := rec.Encode() if err != nil { return nil, fmt.Errorf("mcp: encode recording: %w", err) } - if targetPath != "" { - if err := os.MkdirAll(filepath.Dir(targetPath), 0o755); err != nil { - return nil, fmt.Errorf("mcp: create recording directory: %w", err) - } - if err := os.WriteFile(targetPath, yamlBytes, 0o644); err != nil { - return nil, fmt.Errorf("mcp: write recording %q: %w", cleanRel, err) + if cleanRel != "" { + if err := writeSaveFile(c.cfg.SaveDir, cleanRel, yamlBytes, args.Overwrite); err != nil { + return nil, err } } - name := strings.TrimSpace(args.Name) - if name == "" { - name = c.recordingName - } meta := cloneStringMap(c.recordingMeta) if c.saved == nil { @@ -783,7 +780,7 @@ func (b *Bridge) handleReplayRecordStop(_ context.Context, raw json.RawMessage) Actions: slices.Clone(rec.Actions), Axes: slices.Clone(rec.Axes), Metadata: meta, - SavedPath: cleanRel, + SavedPath: filepath.ToSlash(cleanRel), YAML: string(yamlBytes), }, nil } @@ -811,8 +808,8 @@ func (b *Bridge) handleReplayPlay(_ context.Context, raw json.RawMessage) (any, if args.Name != "" && args.YAML != "" { return nil, errors.New("mcp: specify either name or yaml, not both") } - if args.Steps < 0 { - return nil, fmt.Errorf("mcp: steps must be >= 0 (got %d)", args.Steps) + if args.Steps < 0 || args.Steps > MaxLoopSteps { + return nil, fmt.Errorf("mcp: steps must be between 1 and %d (got %d)", MaxLoopSteps, args.Steps) } if args.RunToEnd && args.Steps > 0 { return nil, errors.New("mcp: cannot specify both run_to_end and steps") @@ -853,29 +850,34 @@ func (b *Bridge) handleReplayPlay(_ context.Context, raw json.RawMessage) (any, if err := rec.Validate(); err != nil { return nil, fmt.Errorf("mcp: invalid recording: %w", err) } + // A recording only reproduces its run at the fixed rate it was made at: a different dt per step changes the simulation. + if rate := b.replayStepRate(c); rec.Rate != rate { + return nil, fmt.Errorf("mcp: invalid recording: %w", loaderr.Errorf("rate", fmt.Sprintf("record again at the game's fixed rate of %d steps per second, or run the game at %d", rate, rec.Rate), "recording rate %d differs from the game's fixed step rate %d", rec.Rate, rate)) + } + if args.RunToEnd && rec.TotalSteps > MaxLoopSteps { + return nil, fmt.Errorf("mcp: run_to_end is limited to %d steps but the recording has %d; omit run_to_end to play it frame by frame and advance it with game_loop_step or the running game", MaxLoopSteps, rec.TotalSteps) + } - var stepFn func(time.Duration) + var advance func(n int) if args.RunToEnd || args.Steps > 0 { - stepFn = c.stepFunc() - if stepFn == nil { - return nil, errors.New("mcp: advancing replay frames requires ReplayConfig.StepFunc or Loop.Update") + advance = b.replayAdvancer(c, rec.StepDuration()) + if advance == nil { + return nil, errors.New("mcp: advancing replay frames requires ReplayConfig.StepFunc or a game loop (Config.Loop or Config.LoopFunc)") } } - doReset := true - if args.Reset != nil { - doReset = *args.Reset - if doReset && c.cfg.ResetFunc == nil { - return nil, errors.New("mcp: reset requested but no ResetFunc configured") - } + doReset, err := b.resolveReplayReset(c, args.Reset) + if err != nil { + return nil, err } player := replay.NewPlayer(rec) c.player = player c.replayName = replayName + c.trailing = false - if doReset && c.cfg.ResetFunc != nil { - if err := c.cfg.ResetFunc(rec.Seed); err != nil { + if doReset { + if err := b.resetReplay(c, rec.Seed); err != nil { c.player = nil c.replayName = "" return nil, fmt.Errorf("mcp: reset before replay failed: %w", err) @@ -885,67 +887,47 @@ func (b *Bridge) handleReplayPlay(_ context.Context, raw json.RawMessage) (any, c.cfg.OnReplayStart(rec.Clone()) } - dt := rec.StepDuration() switch { case args.RunToEnd: - for range rec.TotalSteps { - if c.player != player { - break - } - stepFn(dt) - } - framesPlayed := player.StepIndex() - completed := player.Done() - if c.player == player && completed { - c.finishReplay() - } - return ReplayPlayResult{ - Name: replayName, - Seed: rec.Seed, - StepRate: rec.Rate, - Replaying: c.player == player && !completed, - Completed: completed, - FramesPlayed: framesPlayed, - ReplayTotalFrames: rec.TotalSteps, - }, nil - + advance(rec.TotalSteps) case args.Steps > 0: - for range args.Steps { - if c.player != player || player.Done() { - break + advance(min(args.Steps, rec.TotalSteps)) + } + // A completed player stays active until the game's next Step runs its trailing step, which releases actions held at the end of the recording. + completed := player.Done() + return ReplayPlayResult{ + Name: replayName, + Seed: rec.Seed, + StepRate: rec.Rate, + Replaying: c.player == player && !completed, + Completed: completed, + FramesPlayed: player.StepIndex(), + ReplayTotalFrames: rec.TotalSteps, + }, nil +} + +// replayAdvancer returns a function that advances the simulation by n recorded frames: through ReplayConfig.StepFunc when set, otherwise through the Bridge's game loop with Loop.StepNow so the loop's step count, game time and Draw stay in sync. It returns nil when neither is configured. +func (b *Bridge) replayAdvancer(c *ReplayController, dt time.Duration) func(n int) { + if c.cfg.StepFunc != nil { + step := c.cfg.StepFunc + return func(n int) { + player := c.player + for range n { + if c.player != player || player.Done() { + return + } + step(dt) } - stepFn(dt) } - framesPlayed := player.StepIndex() - completed := player.Done() - if c.player == player && completed { - c.finishReplay() - } - return ReplayPlayResult{ - Name: replayName, - Seed: rec.Seed, - StepRate: rec.Rate, - Replaying: c.player == player && !completed, - Completed: completed, - FramesPlayed: framesPlayed, - ReplayTotalFrames: rec.TotalSteps, - }, nil - - default: - completed := player.Done() - if completed { - c.finishReplay() + } + if l := b.activeLoop(); l != nil { + return func(n int) { + if n > 0 { + l.StepNow(n) + } } - return ReplayPlayResult{ - Name: replayName, - Seed: rec.Seed, - StepRate: rec.Rate, - Replaying: !completed, - Completed: completed, - FramesPlayed: player.StepIndex(), - ReplayTotalFrames: rec.TotalSteps, - }, nil } + return nil } func (b *Bridge) handleReplayStop(_ context.Context, raw json.RawMessage) (any, error) { @@ -1012,28 +994,56 @@ func cloneStringMap(m map[string]string) map[string]string { return maps.Clone(m) } -func resolveSafeSavePath(saveDir, rel string) (absTarget, cleanRel string, err error) { +// resolveSafeSavePath checks that rel is a relative path inside saveDir and returns it cleaned. The write itself goes through os.Root (writeSaveFile), which also refuses symbolic links that leave saveDir. +func resolveSafeSavePath(saveDir, rel string) (cleanRel string, err error) { if strings.TrimSpace(saveDir) == "" { - return "", "", errors.New("mcp: save_path requires ReplayConfig.SaveDir to be configured") + return "", errors.New("mcp: save_path requires ReplayConfig.SaveDir to be configured") } if strings.TrimSpace(rel) == "" { - return "", "", errors.New("mcp: save_path must not be empty") + return "", errors.New("mcp: save_path must not be empty") } if filepath.IsAbs(rel) || strings.HasPrefix(rel, "/") || strings.HasPrefix(rel, "\\") || filepath.VolumeName(rel) != "" { - return "", "", fmt.Errorf("mcp: save_path %q must be relative to SaveDir", rel) + return "", fmt.Errorf("mcp: save_path %q must be relative to SaveDir", rel) } cleaned := filepath.Clean(rel) if cleaned == "." || cleaned == ".." || strings.HasPrefix(cleaned, ".."+string(filepath.Separator)) { - return "", "", fmt.Errorf("mcp: save_path %q escapes SaveDir", rel) + return "", fmt.Errorf("mcp: save_path %q escapes SaveDir", rel) + } + return cleaned, nil +} + +// writeSaveFile writes data to rel inside saveDir through os.Root, creating saveDir and any parent directories. Without overwrite, an existing file is refused. +func writeSaveFile(saveDir, rel string, data []byte, overwrite bool) error { + if err := os.MkdirAll(saveDir, 0o755); err != nil { + return fmt.Errorf("mcp: create SaveDir: %w", err) + } + root, err := os.OpenRoot(saveDir) + if err != nil { + return fmt.Errorf("mcp: open SaveDir: %w", err) + } + defer root.Close() + if dir := filepath.Dir(rel); dir != "." { + if err := root.MkdirAll(dir, 0o755); err != nil { + return fmt.Errorf("mcp: create recording directory for %q: %w", filepath.ToSlash(rel), err) + } + } + flags := os.O_WRONLY | os.O_CREATE | os.O_TRUNC + if !overwrite { + flags |= os.O_EXCL } - absRoot, err := filepath.Abs(saveDir) + f, err := root.OpenFile(rel, flags, 0o644) if err != nil { - return "", "", fmt.Errorf("mcp: resolve SaveDir: %w", err) + if errors.Is(err, os.ErrExist) { + return fmt.Errorf("mcp: save_path %q already exists; pass overwrite: true to replace it (still recording)", filepath.ToSlash(rel)) + } + return fmt.Errorf("mcp: write recording %q: %w", filepath.ToSlash(rel), err) } - target := filepath.Join(absRoot, cleaned) - check, err := filepath.Rel(absRoot, target) - if err != nil || check == "." || check == ".." || strings.HasPrefix(check, ".."+string(filepath.Separator)) { - return "", "", fmt.Errorf("mcp: save_path %q escapes SaveDir", rel) + if _, err := f.Write(data); err != nil { + f.Close() + return fmt.Errorf("mcp: write recording %q: %w", filepath.ToSlash(rel), err) } - return target, filepath.ToSlash(cleaned), nil + if err := f.Close(); err != nil { + return fmt.Errorf("mcp: write recording %q: %w", filepath.ToSlash(rel), err) + } + return nil } diff --git a/packages/game/mcp/replay_test.go b/packages/game/mcp/replay_test.go index f47aed70..0308d2a8 100644 --- a/packages/game/mcp/replay_test.go +++ b/packages/game/mcp/replay_test.go @@ -178,6 +178,7 @@ func TestReplayRecordAndPlaybackDeterminism(t *testing.T) { recordStops []string replayStarts int replayStops int + seededWith []uint64 fixedStepRate = 60 fixedDT = time.Second / time.Duration(fixedStepRate) ) @@ -215,6 +216,7 @@ func TestReplayRecordAndPlaybackDeterminism(t *testing.T) { cx = scope if _, err := mcp.Attach(cx, mcp.Config{ WorldFunc: func() *entities.World { return sim.world }, + SetSeed: func(s uint64) { seededWith = append(seededWith, s) }, Replay: ctrl, }); err != nil { t.Fatal(err) @@ -228,14 +230,22 @@ func TestReplayRecordAndPlaybackDeterminism(t *testing.T) { t.Fatalf("initial status = %+v", status0) } - // Start recording via MCP with deterministic reset and seed. + // Play a while first so recording starts mid-game; the default reset must still rewind to the seed's initial state. + app.Post(func() { + actions.OnKeyDown(core.KeyEvent{Key: "right"}) + for range 7 { + sim.Step(ctrl, fixedDT) + } + actions.OnKeyUp(core.KeyEvent{Key: "right"}) + }) + app.Settle() + + // Start recording via MCP with default arguments apart from name, seed and metadata: reset defaults to true because ResetFunc is set. const seed uint64 = 123456789 startRes := callTool[mcp.ReplayRecordStartResult](t, app, cx, mcp.ToolReplayRecordStart, map[string]any{ - "name": "run_alpha", - "seed": seed, - "step_rate": fixedStepRate, - "reset": true, - "metadata": map[string]string{"level": "cavern_1", "agent": "tester"}, + "name": "run_alpha", + "seed": seed, + "metadata": map[string]string{"level": "cavern_1", "agent": "tester"}, }) if !startRes.Recording || startRes.Name != "run_alpha" || startRes.Seed != seed || startRes.StepRate != fixedStepRate { t.Fatalf("startRes = %+v", startRes) @@ -407,11 +417,15 @@ func TestReplayRecordAndPlaybackDeterminism(t *testing.T) { t.Fatalf("frame-by-frame replay mismatch:\n got: %+v\nwant: %+v", got, wantSnap) } - // Stepping one more tick transitions cleanly back to live input and fires OnReplayStop. + // One trailing playback tick releases recorded holds; the tick after it returns cleanly to live input and fires OnReplayStop. app.Post(func() { + ctrl.Step() + if ctrl.Pressed("right") { + t.Error("trailing playback tick must not read live input") + } actions.OnKeyDown(core.KeyEvent{Key: "right"}) - sim.Step(ctrl, fixedDT) - if !ctrl.Pressed("right") { + ctrl.Step() + if !ctrl.Pressed("right") || !ctrl.JustPressed("right") { t.Error("expected live input to resume after replay finished") } actions.Reset() @@ -425,9 +439,12 @@ func TestReplayRecordAndPlaybackDeterminism(t *testing.T) { if replayStarts != 3 || replayStops != 3 { t.Fatalf("replay hooks = (starts=%d, stops=%d), want (3, 3)", replayStarts, replayStops) } - if len(resetSeeds) != 4 { // 1 record(reset:true) + 3 replays + if len(resetSeeds) != 4 { // 1 record (default reset) + 3 replays t.Fatalf("resetSeeds = %v, want 4 resets", resetSeeds) } + if !reflect.DeepEqual(seededWith, resetSeeds) { + t.Fatalf("Config.SetSeed calls = %v, want %v", seededWith, resetSeeds) + } for i, gotSeed := range resetSeeds { if gotSeed != seed { t.Fatalf("resetSeeds[%d] = %d, want %d", i, gotSeed, seed) @@ -461,7 +478,6 @@ func TestReplayStepChunkLoopFallbackAndEarlyStop(t *testing.T) { ctrl = mcp.NewReplayController(mcp.ReplayConfig{ Source: actions, Actions: []string{"jump"}, - Loop: loop, ResetFunc: func(uint64) error { stepsRun = 0 jumpPress = 0 @@ -474,13 +490,13 @@ func TestReplayStepChunkLoopFallbackAndEarlyStop(t *testing.T) { app := nsgotest.Start(t, func(scope *core.Scope) core.Node { cx = scope - if _, err := mcp.Attach(cx, mcp.Config{Replay: ctrl}); err != nil { + if _, err := mcp.Attach(cx, mcp.Config{Loop: loop, Replay: ctrl}); err != nil { t.Fatal(err) } return core.View{} }) - // Start with omitted name and step_rate (should auto-name "recording_1" and inherit Loop.Rate=30). + // Start with omitted name (should auto-name "recording_1" and use the loop's rate of 30). recStart := callTool[mcp.ReplayRecordStartResult](t, app, cx, mcp.ToolReplayRecordStart, nil) if recStart.Name != "recording_1" || recStart.StepRate != 30 { t.Fatalf("recStart = %+v", recStart) @@ -502,7 +518,8 @@ func TestReplayStepChunkLoopFallbackAndEarlyStop(t *testing.T) { t.Fatalf("recStop = %+v", recStop) } - // Advance only 5 steps via Loop.Update fallback, then stop early. + // Advance only 5 steps through the Bridge's loop (Loop.StepNow), then stop early. + stepsBefore := loop.Steps() playRes := callTool[mcp.ReplayPlayResult](t, app, cx, mcp.ToolReplayPlay, map[string]any{ "name": "jump_demo", "steps": 5, @@ -513,6 +530,9 @@ func TestReplayStepChunkLoopFallbackAndEarlyStop(t *testing.T) { if stepsRun != 5 || jumpPress != 1 { t.Fatalf("after 5 steps: stepsRun=%d jumpPress=%d, want 5, 1", stepsRun, jumpPress) } + if got := loop.Steps() - stepsBefore; got != 5 { + t.Fatalf("loop advanced %d steps during replay, want 5 so game_loop_status stays in sync", got) + } stopRes := callTool[mcp.ReplayStopResult](t, app, cx, mcp.ToolReplayStop, nil) if !stopRes.Stopped || stopRes.Name != "jump_demo" || stopRes.FramesPlayed != 5 || stopRes.ReplayTotalFrames != 20 { @@ -586,9 +606,150 @@ func TestReplaySaveDirAndPathSecurity(t *testing.T) { if loaded.Seed != 42 || loaded.TotalSteps != 2 || len(loaded.Events) != 2 { t.Fatalf("loaded recording = %+v", loaded) } + + // A second recording under the same name and path is refused without overwrite and keeps recording. + _ = callTool[mcp.ReplayRecordStartResult](t, app, cx, mcp.ToolReplayRecordStart, map[string]any{"name": "boss_fight"}) + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayRecordStop, nil); err == nil || !strings.Contains(err.Error(), "already stored") { + t.Fatalf("stop over a stored name = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayRecordStop, map[string]any{"name": "boss_fight_2", "save_path": "runs/boss_fight.replay.yaml"}); err == nil || !strings.Contains(err.Error(), "already exists") { + t.Fatalf("stop over an existing file = %v", err) + } + if !ctrl.Recording() { + t.Fatal("refused overwrite unexpectedly aborted the active recording") + } + + // A symbolic link inside SaveDir cannot carry a write outside it. + outside := t.TempDir() + if err := os.Symlink(outside, filepath.Join(saveDir, "out")); err != nil { + t.Skipf("symlink: %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayRecordStop, map[string]any{"name": "boss_fight_2", "save_path": "out/escape.replay.yaml"}); err == nil { + t.Fatal("expected error for save_path through a symlink leaving SaveDir") + } + if _, err := os.Stat(filepath.Join(outside, "escape.replay.yaml")); !os.IsNotExist(err) { + t.Fatalf("file written outside SaveDir: stat err = %v", err) + } + + again := callTool[mcp.ReplayRecordStopResult](t, app, cx, mcp.ToolReplayRecordStop, map[string]any{ + "save_path": "runs/boss_fight.replay.yaml", + "overwrite": true, + }) + if again.Name != "boss_fight" || again.Frames != 0 { + t.Fatalf("overwrite stop = %+v", again) + } + if b, err := os.ReadFile(diskPath); err != nil || string(b) != again.YAML { + t.Fatalf("overwritten file = %q, %v", b, err) + } +} + +func TestReplayPlayRefusesMismatchedRateAndUnboundedRuns(t *testing.T) { + actions := input.NewActions() + steps := 0 + var ctrl *mcp.ReplayController + ctrl = mcp.NewReplayController(mcp.ReplayConfig{ + Source: actions, + StepRate: 60, + StepFunc: func(time.Duration) { + ctrl.Step() + steps++ + }, + }) + var cx *core.Scope + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + if _, err := mcp.Attach(cx, mcp.Config{Replay: ctrl}); err != nil { + t.Fatal(err) + } + return core.View{} + }) + + // Recorded at 30 Hz, replayed in a 60 Hz game: every step would get the wrong dt. + for _, args := range []map[string]any{ + {"yaml": "version: 2\nseed: 1\nrate: 30\ntotal_steps: 3\n", "run_to_end": true}, + {"yaml": "version: 2\nseed: 1\nrate: 30\ntotal_steps: 3\n"}, + } { + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayPlay, args); err == nil || !strings.Contains(err.Error(), "rate") { + t.Fatalf("play at mismatched rate %v = %v", args, err) + } + } + + // run_to_end over more than MaxLoopSteps is refused before anything runs. + long := "version: 2\nseed: 1\nrate: 60\ntotal_steps: 2000000000\n" + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayPlay, map[string]any{"yaml": long, "run_to_end": true}); err == nil || !strings.Contains(err.Error(), "3600") { + t.Fatalf("run_to_end over the cap = %v", err) + } + if ctrl.Replaying() || steps != 0 { + t.Fatalf("refused play left replaying=%v steps=%d", ctrl.Replaying(), steps) + } + + // steps is capped per call and the rest plays frame by frame. + res := callTool[mcp.ReplayPlayResult](t, app, cx, mcp.ToolReplayPlay, map[string]any{"yaml": long, "steps": mcp.MaxLoopSteps}) + if !res.Replaying || res.FramesPlayed != mcp.MaxLoopSteps || steps != mcp.MaxLoopSteps { + t.Fatalf("capped steps play = %+v steps=%d", res, steps) + } + _ = callTool[mcp.ReplayStopResult](t, app, cx, mcp.ToolReplayStop, nil) } -func TestReplayControllerHelpersPrebuiltRecorderAndZeroFrame(t *testing.T) { +func TestReplayTrailingReleaseAndLiveSnapshot(t *testing.T) { + actions := input.NewActions() + actions.Bind("jump", input.Key("space")) + ctrl := mcp.NewReplayController(mcp.ReplayConfig{ + Source: actions, + Actions: []string{"jump"}, + }) + var cx *core.Scope + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + if _, err := mcp.Attach(cx, mcp.Config{Replay: ctrl}); err != nil { + t.Fatal(err) + } + return core.View{} + }) + + // Record jump held through the final recorded step. + _ = callTool[mcp.ReplayRecordStartResult](t, app, cx, mcp.ToolReplayRecordStart, map[string]any{"name": "hold"}) + app.Post(func() { + actions.OnKeyDown(core.KeyEvent{Key: "space"}) + for range 3 { + ctrl.Step() + } + }) + app.Settle() + _ = callTool[mcp.ReplayRecordStopResult](t, app, cx, mcp.ToolReplayRecordStop, nil) + + // Release the key without a live step, so the live snapshot still says held, then replay frame by frame (no reset is configured). + app.Post(func() { actions.OnKeyUp(core.KeyEvent{Key: "space"}) }) + app.Settle() + _ = callTool[mcp.ReplayPlayResult](t, app, cx, mcp.ToolReplayPlay, map[string]any{"name": "hold"}) + + app.Post(func() { + for i := range 3 { + ctrl.Step() + if !ctrl.Pressed("jump") { + t.Errorf("playback step %d: jump not held", i) + } + } + // Trailing step: the hold recorded at the end is released once. + ctrl.Step() + if ctrl.Pressed("jump") || !ctrl.JustReleased("jump") { + t.Errorf("trailing step: pressed=%v just_released=%v, want false, true", ctrl.Pressed("jump"), ctrl.JustReleased("jump")) + } + // First live step: the live source was stepped during playback, so no stale edge appears. + ctrl.Step() + if ctrl.Replaying() || ctrl.Pressed("jump") || ctrl.JustPressed("jump") || ctrl.JustReleased("jump") { + t.Errorf("first live step: replaying=%v pressed=%v just_pressed=%v just_released=%v, want all false", ctrl.Replaying(), ctrl.Pressed("jump"), ctrl.JustPressed("jump"), ctrl.JustReleased("jump")) + } + }) + app.Settle() + + status := callTool[mcp.ReplayStatusResult](t, app, cx, mcp.ToolReplayStatus, nil) + if status.Replaying || status.ReplayDone || status.ReplayName != "" { + t.Fatalf("status after playback = %+v", status) + } +} + +func TestReplayControllerHelpersAndZeroFrame(t *testing.T) { // Verify all registered tool schemas are valid JSON. bridge := mcp.New(mcp.Config{}) for _, tool := range bridge.Tools() { @@ -597,12 +758,12 @@ func TestReplayControllerHelpersPrebuiltRecorderAndZeroFrame(t *testing.T) { } } - // Pre-built Recorder fallback + Go helper methods. + // Go helper methods. actions := input.NewActions() actions.Bind("a", input.Key("a")) - rec := replay.NewRecorder(actions, 7, 60, []string{"a"}, nil) ctrl := mcp.NewReplayController(mcp.ReplayConfig{ - Recorder: rec, + Source: actions, + Actions: []string{"a"}, }) bridge.SetReplay(ctrl) if bridge.Replay() != ctrl { @@ -733,9 +894,9 @@ func TestReplayErrorHandling(t *testing.T) { t.Fatalf("replay_stop idle = %v", err) } - // Negative step_rate rejected. - if _, err := callToolRaw(t, app, cx, mcp.ToolReplayRecordStart, map[string]any{"step_rate": -5}); err == nil { - t.Fatal("expected error for negative step_rate") + // The recording's rate is the game's fixed rate, not an argument. + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayRecordStart, map[string]any{"step_rate": 30}); err == nil || !strings.Contains(err.Error(), "unknown field") { + t.Fatalf("record_start with step_rate = %v, want unknown field error", err) } // Start recording, then verify conflicting start/play and save_path without SaveDir fail cleanly. @@ -778,6 +939,9 @@ func TestReplayErrorHandling(t *testing.T) { if _, err := callToolRaw(t, app, cx, mcp.ToolReplayPlay, map[string]any{"name": "rec1", "steps": -1}); err == nil { t.Fatal("expected error for negative steps") } + if _, err := callToolRaw(t, app, cx, mcp.ToolReplayPlay, map[string]any{"name": "rec1", "steps": mcp.MaxLoopSteps + 1}); err == nil || !strings.Contains(err.Error(), "3600") { + t.Fatalf("play with steps above MaxLoopSteps = %v", err) + } // run_to_end without StepFunc or Loop.Update fails cleanly before starting replay. if _, err := callToolRaw(t, app, cx, mcp.ToolReplayPlay, map[string]any{"name": "rec1", "run_to_end": true}); err == nil || !strings.Contains(err.Error(), "StepFunc") { t.Fatalf("run_to_end without StepFunc = %v", err) From 253d8540e46b40a76b9a922c72d88dc67d98cfb0 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Wed, 25 Nov 2026 04:23:18 +0900 Subject: [PATCH 3/3] docs(mcp): document replay reset, rate, step limits and save behavior --- .../feature/2026-11-24-mcp-record-and-replay.md | 12 ++++++------ docs/en/mcp.md | 15 +++++++++------ docs/zh/mcp.md | 15 +++++++++------ 3 files changed, 24 insertions(+), 18 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-11-24-mcp-record-and-replay.md b/.agents/notes/implemented/feature/2026-11-24-mcp-record-and-replay.md index 589e9a52..538a5ced 100644 --- a/.agents/notes/implemented/feature/2026-11-24-mcp-record-and-replay.md +++ b/.agents/notes/implemented/feature/2026-11-24-mcp-record-and-replay.md @@ -12,13 +12,13 @@ Add `ReplayController` (configured via `ReplayConfig` on `mcp.Config.Replay`) an ## Architecture and tool contract -- **Single `ActionSource` facade (`ReplayController`)**: Games construct `ctrl := mcp.NewReplayController(cfg)`, pass `ctrl` to their simulation as its `replay.ActionSource`, and supply `Replay: ctrl` in `mcp.Config`. During live play `ctrl` forwards to `cfg.Source`; during recording it delegates to a `replay.Recorder` wrapping `cfg.Source` (or a pre-built `cfg.Recorder` fallback); during playback it delegates to a `replay.Player` created from the target `replay.Recording`. -- **Final-step playback lifecycle**: In `replay.Player.Step()`, advancing the last recorded frame (`TotalSteps - 1`) sets `Done() == true` before the simulation reads `Pressed`/`JustPressed`/`Axis` for that tick. `ReplayController` therefore keeps `player` attached through the remainder of that final step and only clears it on the subsequent `Step()` (resuming live input), on `game_replay_stop`, at the end of synchronous `run_to_end`/`steps` execution, or before starting a new record/play session. Meanwhile `game_replay_status` reports `replaying: false` and `replay_done: true` as soon as `player.Done()` becomes true so polling agents observe completion without needing an extra live step. +- **Single `ActionSource` facade (`ReplayController`)**: Games construct `ctrl := mcp.NewReplayController(cfg)`, pass `ctrl` to their simulation as its `replay.ActionSource`, and supply `Replay: ctrl` in `mcp.Config`. During live play `ctrl` forwards to `cfg.Source`; during recording it delegates to a `replay.Recorder` wrapping `cfg.Source`; during playback it delegates to a `replay.Player` created from the target `replay.Recording` and still steps `cfg.Source`, so the live previous-step snapshot is current when playback ends. `cfg.Source` is required: an earlier pre-built `Recorder` fallback was dropped because with no `Source` live play had no input at all. +- **Final-step playback lifecycle**: In `replay.Player.Step()`, advancing the last recorded frame (`TotalSteps - 1`) sets `Done() == true` before the simulation reads `Pressed`/`JustPressed`/`Axis` for that tick. `ReplayController` therefore keeps `player` attached through that final step, runs one trailing `player.Step()` on the next `Step()` so actions held at the end fire `JustReleased` once, and clears it on the `Step()` after that (resuming live input), on `game_replay_stop`, or before starting a new record/play session. Synchronous `run_to_end`/`steps` leave a completed player attached for the trailing step. Meanwhile `game_replay_status` reports `replaying: false` and `replay_done: true` as soon as `player.Done()` becomes true so polling agents observe completion without needing an extra live step. - **Six tools with strict JSON decoding**: - `game_replay_status`: returns recording/playback flags, frame counters, active names/metadata, and sorted `saved_recordings`. - - `game_replay_record_start`: starts recording with optional `name` (auto-allocated sequentially when omitted), `seed` (falls back to `SeedFunc` or `0`), `step_rate` (falls back to `ReplayConfig.StepRate`, `Loop.Rate`, or `60`), `actions`/`axes` overrides, string `metadata`, and optional `reset: true`. Refuses starting while already recording or actively replaying. - - `game_replay_record_stop`: validates optional `save_path` before mutating state so an invalid path never discards an active recording, encodes canonical `replay` v2 YAML via `Recording.Encode()`, stores a clone in memory under its name, optionally writes inside `ReplayConfig.SaveDir` (strictly rejecting absolute paths and `..` escapes), and returns summary fields plus the YAML text. - - `game_replay_play`: accepts either a stored `name` or inline `yaml` (decoded and validated via `replay.Decode`), invokes `ResetFunc(rec.Seed)` by default (rolling back state if `ResetFunc` fails), and supports frame-by-frame playback (`run_to_end: false`), bounded synchronous stepping (`steps: N`), or full synchronous playback (`run_to_end: true`) using `StepFunc` or `Loop.Update`. + - `game_replay_record_start`: starts recording with optional `name` (auto-allocated sequentially when omitted), `seed` (falls back to `SeedFunc` or `0`), `actions`/`axes` overrides, string `metadata`, and `reset` (default `true` when `ResetFunc` or a seed target is configured, the same default as `game_replay_play`, so a recording started mid-game replays to the same state). The rate is not an argument: it is the game's fixed rate, the Bridge loop's `StepRate()` or else `ReplayConfig.StepRate` or `60`. Refuses starting while already recording or actively replaying. + - `game_replay_record_stop`: validates optional `save_path` before mutating state so an invalid path never discards an active recording, encodes canonical `replay` v2 YAML via `Recording.Encode()`, stores a clone in memory under its name, optionally writes inside `ReplayConfig.SaveDir` through `os.Root` (rejecting absolute paths, `..` and symbolic links that leave it, and refusing an existing file or stored name unless `overwrite: true`), and returns summary fields plus the YAML text. + - `game_replay_play`: accepts either a stored `name` or inline `yaml` (decoded and validated via `replay.Decode`), refuses a recording whose `rate` differs from the game's fixed rate, resets by default (re-seeding `Config.Random`, `Config.RandomStreams` and `Config.SetSeed` as `game_loop_seed` does, then `ResetFunc(rec.Seed)`, rolling back if it fails), and supports frame-by-frame playback, synchronous stepping (`steps: 1..3600`), or full synchronous playback (`run_to_end: true`, recordings up to `MaxLoopSteps`) using `StepFunc` or else the Bridge loop's `StepNow`, so `game_loop_status` stays in sync. - `game_replay_stop`: stops an active playback early and fires `OnReplayStop`. - `game_replay_list`: returns sorted summaries (`name`, `frames`, `seed`, `step_rate`, `events`, `actions`, `axes`, `metadata`) of stored recordings. - **Pure `game/replay` v2 YAML preservation**: Optional MCP `metadata` is stored alongside the `replay.Recording` in `ReplayController`'s in-memory map rather than added to the YAML schema, keeping exported YAML 100% compatible with `replay.Decode`'s `KnownFields(true)` check and `go tool game replay`. @@ -40,7 +40,7 @@ Letting an agent pass any file path to `save_path` would simplify one-off export ## Consequences - **Benefits**: Agents can record live input sequences over MCP, inspect their deterministic v2 YAML, store or export them safely, and replay them (by name, from inline YAML, synchronously, or frame-by-frame) to reproduce bit-identical simulation and ECS component state. Games wire the capability in a handful of lines by passing `ReplayController` as their `replay.ActionSource`, and parallel MCP tool groups remain isolated in separate files. -- **Costs**: Games that want `run_to_end` or `steps` synchronous playback must expose a deterministic `StepFunc` (or `Loop`) and `ResetFunc`, and must configure watched `Actions`/`Axes` names (matching `replay.NewRecorder`) because `input.Actions` does not enumerate all dynamic action names by itself. In-memory recordings live for the lifetime of the `ReplayController` unless deleted or replaced by name. +- **Costs**: Games that want `run_to_end` or `steps` synchronous playback must expose a deterministic `StepFunc` (or a loop on `mcp.Config`) and `ResetFunc`, and must configure watched `Actions`/`Axes` names (matching `replay.NewRecorder`) because `input.Actions` does not enumerate all dynamic action names by itself. In-memory recordings live for the lifetime of the `ReplayController` unless deleted or replaced by name. ## Verification diff --git a/docs/en/mcp.md b/docs/en/mcp.md index 075ef518..8dc056bd 100644 --- a/docs/en/mcp.md +++ b/docs/en/mcp.md @@ -112,9 +112,9 @@ If `game_entity_spawn` fails while applying `parent` or `components`, or while r | `game_component_set` | `ref` (required), `component` (required), `value` (required), `replace` (optional, default `false`) | Updated component `value` read back from the live entity; edits take effect on the next simulation step. If the write succeeded but the read-back failed, `value` is `null` and `read_error` says why; the edit still stands. | | `game_component_remove` | `ref` (required), `component` (required) | Whether the component was present and `removed` from the live entity. | | `game_replay_status` | `{}` | Current recording and playback state (`recording`, `replaying`, `replay_done`, `frames_recorded`, `replay_frame`, `replay_total_frames`), active names/metadata, and sorted `saved_recordings`. | -| `game_replay_record_start` | `name`, `seed`, `step_rate`, `actions`, `axes`, `metadata`, `reset` (all optional) | Starts recording per-step inputs via `replay.Recorder`, returning the resolved recording name, seed, step rate, watched names and metadata. | -| `game_replay_record_stop` | `name` (optional), `save_path` (optional, relative to `ReplayConfig.SaveDir`) | Stops the active recording, stores it in memory (and optionally writes it under `SaveDir`), and returns its summary plus deterministic version-2 YAML text (`yaml`). | -| `game_replay_play` | `name` or `yaml` (mutually exclusive), `run_to_end` (default `false`), `steps`, `reset` (default `true` when `ResetFunc` is set) | Starts deterministic playback via `replay.Player`, invoking `ResetFunc(seed)` before playback and optionally advancing all or `steps` frames synchronously via `StepFunc`/`Loop.Update`. | +| `game_replay_record_start` | `name`, `seed`, `actions`, `axes`, `metadata`, `reset` (all optional; `reset` defaults to `true` when `ResetFunc` or a seed target is configured) | Resets to `seed` (see below) and starts recording per-step inputs via `replay.Recorder` at the game's fixed step rate, returning the resolved recording name, seed, step rate, watched names and metadata. | +| `game_replay_record_stop` | `name` (optional), `save_path` (optional, relative to `ReplayConfig.SaveDir`), `overwrite` (default `false`) | Stops the active recording, stores it in memory (and optionally writes it under `SaveDir`), and returns its summary plus deterministic version-2 YAML text (`yaml`). An existing stored name or file is refused unless `overwrite: true`, and the recording continues. | +| `game_replay_play` | `name` or `yaml` (mutually exclusive), `run_to_end` (default `false`), `steps` (`1..3600`), `reset` (default `true` when `ResetFunc` or a seed target is configured) | Resets to the recording's seed and starts deterministic playback via `replay.Player`, optionally advancing all (`run_to_end`, recordings up to `3600` steps) or `steps` frames synchronously via `StepFunc` or the game loop's `StepNow`. A recording whose `rate` differs from the game's fixed step rate is refused. | | `game_replay_stop` | `{}` | Stops an active replay playback cleanly and reports how many frames were played. | | `game_replay_list` | `{}` | Lists stored recordings in sorted name order with `frames`, `seed`, `step_rate`, `events`, `actions`, `axes` and `metadata`. | @@ -180,9 +180,12 @@ bridge, err := mcp.Attach(cx, mcp.Config{ }) ``` -- Because `ReplayController` implements `replay.ActionSource`, your game loop reads input from `ctrl` identically during live play (forwarded to `Source`), recording (`replay.Recorder`) and playback (`replay.Player`). -- Recordings stopped via `game_replay_record_stop` are stored in memory under their name and returned as canonical deterministic [`game/replay`](replay.md) v2 YAML text. Set `ReplayConfig.SaveDir` if you also want agents to write recordings to safe relative paths on disk via `save_path` (absolute paths and `..` escapes are rejected). -- `game_replay_play` accepts either a stored `name` or inline `yaml` text, invokes `ResetFunc(recording.Seed)` to restore the starting state, and replays either synchronously (`run_to_end: true` or `steps: N`) or frame-by-frame as the game loop advances. +- Because `ReplayController` implements `replay.ActionSource`, your game loop reads input from `ctrl` identically during live play (forwarded to `Source`), recording (`replay.Recorder`) and playback (`replay.Player`). `Source` is required. It is still stepped during playback, so its previous-step snapshot is current when live input resumes. +- Recording and playback share one reset: the Bridge's seed targets (`Config.Random`, `Config.RandomStreams`, `Config.SetSeed`, the same ones `game_loop_seed` uses) are re-seeded with the seed, then `ResetFunc(seed)` runs. `reset` defaults to `true` on both tools whenever there is something to reset, so a recording started mid-game with default arguments replays to the same state. Passing `reset: false` to `game_replay_record_start` records from the current state, and that recording only reproduces from the same state. +- The recording's `rate` is the game's fixed step rate: the Bridge's loop (`Config.Loop` / `Config.LoopFunc`) `StepRate()` when there is one, otherwise `ReplayConfig.StepRate` (default `60`). `game_replay_play` refuses a recording made at another rate, because each step would get a different `dt`. +- Recordings stopped via `game_replay_record_stop` are stored in memory under their name and returned as canonical deterministic [`game/replay`](replay.md) v2 YAML text. Set `ReplayConfig.SaveDir` if you also want agents to write recordings to relative paths on disk via `save_path`; the write goes through `os.Root`, so absolute paths, `..` and symbolic links cannot leave `SaveDir`. `metadata` stays only in the in-memory store: it is not part of the YAML, so a saved file or an inline `yaml` replay does not carry it. +- `game_replay_play` accepts either a stored `name` or inline `yaml` text and replays either synchronously (`run_to_end: true` or `steps: N`) or frame by frame as the game loop advances. Without `StepFunc`, synchronous playback advances the Bridge's loop with `Loop.StepNow`, so `game_loop_status` counts the replayed steps and game time. Like `game_loop_step`, a single call advances at most `MaxLoopSteps` (`3600`) steps. +- After the final recorded step, the next `ctrl.Step()` is a trailing playback step that releases actions still held at the end of the recording (firing `JustReleased` once); the step after it returns to live input and calls `OnReplayStop`. ## Stable entity references diff --git a/docs/zh/mcp.md b/docs/zh/mcp.md index d4ec8243..9f327eb8 100644 --- a/docs/zh/mcp.md +++ b/docs/zh/mcp.md @@ -112,9 +112,9 @@ if err := bridge.RegisterScenePrefab("turret", turretDoc); err != nil { | `game_component_set` | `ref`(必填)、`component`(必填)、`value`(必填)、`replace`(可选,默认 `false`) | 回读自存活实体的更新后组件 `value`;修改会在下一次模拟步进中生效。若写入成功但回读失败,`value` 为 `null`,`read_error` 说明原因,修改依然有效。 | | `game_component_remove` | `ref`(必填)、`component`(必填) | 报告指定组件是否存在并已从存活实体移除(`removed`)。 | | `game_replay_status` | `{}` | 当前录制与回放状态(`recording`、`replaying`、`replay_done`、`frames_recorded`、`replay_frame`、`replay_total_frames`)、当前录制/回放名称与元数据,以及排序后的 `saved_recordings`。 | -| `game_replay_record_start` | `name`、`seed`、`step_rate`、`actions`、`axes`、`metadata`、`reset`(均可选) | 通过 `replay.Recorder` 开始按固定步长录制输入,并返回解析后的录制名称、种子、步频、监听列表与元数据。 | -| `game_replay_record_stop` | `name`(可选)、`save_path`(可选,相对于 `ReplayConfig.SaveDir`) | 停止当前录制,将其保存到内存(并可选写入 `SaveDir` 下的安全相对路径),返回摘要与确定性的 v2 YAML 文本(`yaml`)。 | -| `game_replay_play` | `name` 或 `yaml`(二选一)、`run_to_end`(默认 `false`)、`steps`、`reset`(配置 `ResetFunc` 时默认 `true`) | 通过 `replay.Player` 开始确定性回放,在回放前调用 `ResetFunc(seed)` 重置状态,并可选通过 `StepFunc`/`Loop.Update` 同步推进全部或指定步数。 | +| `game_replay_record_start` | `name`、`seed`、`actions`、`axes`、`metadata`、`reset`(均可选;配置了 `ResetFunc` 或种子目标时 `reset` 默认 `true`) | 按 `seed` 重置(见下文),然后通过 `replay.Recorder` 以游戏的固定步频开始逐步录制输入,并返回解析后的录制名称、种子、步频、监听列表与元数据。 | +| `game_replay_record_stop` | `name`(可选)、`save_path`(可选,相对于 `ReplayConfig.SaveDir`)、`overwrite`(默认 `false`) | 停止当前录制,将其保存到内存(并可选写入 `SaveDir`),返回摘要与确定性的 v2 YAML 文本(`yaml`)。同名的已存录制或已存在的文件会被拒绝(除非 `overwrite: true`),录制继续进行。 | +| `game_replay_play` | `name` 或 `yaml`(二选一)、`run_to_end`(默认 `false`)、`steps`(`1..3600`)、`reset`(配置了 `ResetFunc` 或种子目标时默认 `true`) | 按录制的种子重置,然后通过 `replay.Player` 开始确定性回放,并可选通过 `StepFunc` 或游戏循环的 `StepNow` 同步推进全部帧(`run_to_end`,录制不超过 `3600` 步)或 `steps` 帧。`rate` 与游戏固定步频不同的录制会被拒绝。 | | `game_replay_stop` | `{}` | 安全停止当前正在进行的回放,并报告已回放的帧数。 | | `game_replay_list` | `{}` | 按名称排序列出已存储的录制及其 `frames`、`seed`、`step_rate`、`events`、`actions`、`axes` 与 `metadata`。 | @@ -180,9 +180,12 @@ bridge, err := mcp.Attach(cx, mcp.Config{ }) ``` -- `ReplayController` 实现了 `replay.ActionSource`,游戏逻辑在实时游玩(转发至 `Source`)、录制(`replay.Recorder`)与回放(`replay.Player`)三种模式下完全共用同一套更新循环。 -- 通过 `game_replay_record_stop` 结束的录制会按名称存入内存,并返回标准、确定性的 [`game/replay`](replay.md) v2 YAML 文本。若希望智能体同时通过 `save_path` 落盘,可配置 `ReplayConfig.SaveDir`(绝对路径与 `..` 越界路径都会被拒绝)。 -- `game_replay_play` 支持按已存 `name` 或内联 `yaml` 文本回放,默认调用 `ResetFunc(recording.Seed)` 恢复初始确定性状态,并支持同步跑到结束(`run_to_end: true`)、同步步进(`steps: N`)或随游戏循环逐帧回放。 +- `ReplayController` 实现了 `replay.ActionSource`,游戏逻辑在实时游玩(转发至 `Source`)、录制(`replay.Recorder`)与回放(`replay.Player`)三种模式下完全共用同一套更新循环。`Source` 为必填项。回放期间它仍会被步进,因此恢复实时输入时它的上一步快照是最新的。 +- 录制与回放共用同一个重置:先用种子重新设定桥接器的种子目标(`Config.Random`、`Config.RandomStreams`、`Config.SetSeed`,与 `game_loop_seed` 使用的相同),再调用 `ResetFunc(seed)`。只要有可重置的内容,两个工具的 `reset` 都默认为 `true`,因此在游戏中途以默认参数开始的录制也能回放到相同状态。向 `game_replay_record_start` 传 `reset: false` 会从当前状态开始录制,这样的录制只有从同一状态出发才能复现。 +- 录制的 `rate` 就是游戏的固定步频:桥接器有游戏循环(`Config.Loop` / `Config.LoopFunc`)时取其 `StepRate()`,否则取 `ReplayConfig.StepRate`(默认 `60`)。`game_replay_play` 会拒绝以其他步频录制的录制,因为每一步的 `dt` 都会不同。 +- 通过 `game_replay_record_stop` 结束的录制会按名称存入内存,并返回标准、确定性的 [`game/replay`](replay.md) v2 YAML 文本。若希望智能体同时通过 `save_path` 落盘,可配置 `ReplayConfig.SaveDir`;写入经由 `os.Root` 进行,绝对路径、`..` 与符号链接都无法离开 `SaveDir`。`metadata` 只保存在内存存储中,不属于 YAML,因此保存的文件或内联 `yaml` 回放都不带它。 +- `game_replay_play` 支持按已存 `name` 或内联 `yaml` 文本回放,可同步回放(`run_to_end: true` 或 `steps: N`),也可随游戏循环逐帧回放。未设置 `StepFunc` 时,同步回放通过 `Loop.StepNow` 推进桥接器的游戏循环,因此 `game_loop_status` 会计入回放的步数与游戏时间。与 `game_loop_step` 相同,单次调用最多推进 `MaxLoopSteps`(`3600`)步。 +- 最后一个录制步之后,下一次 `ctrl.Step()` 是一个收尾回放步,会释放录制结束时仍按住的动作(触发一次 `JustReleased`);再下一步才恢复实时输入并调用 `OnReplayStop`。 ## 稳定的实体引用