From 6b71cb88f7f4ede616d2ed0ae47802a27aade3d7 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Tue, 24 Nov 2026 18:37:28 +0900 Subject: [PATCH 1/3] feat(mcp): add spawn, destroy and component edit tools (#464) --- .../2026-11-24-mcp-spawn-destroy-edit.md | 43 + changelog.d/mcp-spawn-destroy-edit.md | 4 + docs/en/mcp.md | 44 +- docs/zh/mcp.md | 44 +- packages/game/entities/codec_edit_test.go | 122 ++ packages/game/entities/snapshot.go | 113 +- packages/game/mcp/doc.go | 7 +- packages/game/mcp/edit.go | 1123 +++++++++++++++++ packages/game/mcp/edit_test.go | 752 +++++++++++ packages/game/mcp/example_test.go | 5 + packages/game/mcp/mcp.go | 16 +- 11 files changed, 2255 insertions(+), 18 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-11-24-mcp-spawn-destroy-edit.md create mode 100644 changelog.d/mcp-spawn-destroy-edit.md create mode 100644 packages/game/entities/codec_edit_test.go create mode 100644 packages/game/mcp/edit.go create mode 100644 packages/game/mcp/edit_test.go diff --git a/.agents/notes/implemented/feature/2026-11-24-mcp-spawn-destroy-edit.md b/.agents/notes/implemented/feature/2026-11-24-mcp-spawn-destroy-edit.md new file mode 100644 index 00000000..0ab70fc8 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-24-mcp-spawn-destroy-edit.md @@ -0,0 +1,43 @@ +# Agent Note: MCP object spawning, destruction and component editing + +Status: implemented + +## Problem + +With [MCP scene, layer, entity and component inspection](2026-11-24-mcp-scene-entity-inspection.md) in place, coding agents running a game under `nsgo dev -automation` can read scenes, layers, live entities, and components, but cannot mutate runtime world state—they cannot spawn prefabs to reproduce bugs, destroy entities, or tweak component values to test gameplay hypotheses on the next simulation step. + +## Decision + +Extend `packages/game/mcp` with a dedicated mutation tool group in `edit.go` (`game_prefabs_list`, `game_entity_spawn`, `game_entity_destroy`, `game_component_set`, `game_component_remove`) hooked into `Bridge.Tools()`, backed by prefab registration APIs (`Config.Prefabs`, `Bridge.RegisterPrefab`, `Bridge.RegisterEntityPrefab`, `Bridge.RegisterScenePrefab`), typed component editor APIs (`RegisterMutableComponent`, `RegisterComponentEditor`), and zero-reflection strict codec mutation helpers (`World.DecodeComponent`, `World.PatchComponent`, `World.RemoveComponent`) in `packages/game/entities`. + +## Architecture and mutation contract + +- **Minimal hookup in `mcp.go`**: All mutation types, schemas, registration APIs, and handlers live in `packages/game/mcp/edit.go`; `mcp.go` adds only `Config.Prefabs`, `write`/`remove` hooks on `componentEntry`, prefab storage fields on `Bridge`, and `b.editTools()` in `Bridge.Tools()`. This isolates parallel MCP PRs (#462–#469) from merge conflicts. +- **Prefab sources**: `Bridge` supports three prefab kinds (`"custom"`, `"entity_prefab"`, `"scene"`): custom `PrefabSpawner` callbacks with optional `overrides`, `*entities.Prefab` templates via `RegisterEntityPrefab`, and validated self-contained `*sceneformat.SceneDoc` templates via `RegisterScenePrefab` (instantiated through `sceneformat.SpawnEntities`). `game_prefabs_list` enumerates all registered prefabs in deterministic sorted order. +- **Atomic spawning and rollback**: `game_entity_spawn` validates `x`/`y` finite float32 bounds, parent ref liveness, and prefab existence before spawning. If applying `parent` or any entry in `components` fails after spawn, every newly created entity (including scene-prefab children) is destroyed before returning the error so failed calls never leak half-initialized entities. +- **Patch-by-default strict component edits**: `game_component_set` defaults to patching existing component fields (`replace: false`) so editing a single field (such as `transform2d.x` or `health.hp`) preserves omitted fields like `scaleX`/`scaleY` or `max`, while `replace: true` decodes into a fresh zero value. Both codec helpers (`World.PatchComponent` / `World.DecodeComponent`) and bridge editors decode JSON with `DisallowUnknownFields()`, reject trailing tokens, reject `null` for non-nullable types, and reject non-finite floats (`NaN`, `±Inf`). Patching deep-copies the current value before decoding so a partial decode error never mutates maps or slices on the live entity. +- **Hierarchy invariants**: Built-in `"transform2d"` writes go through `entities.Set`, which delegates to `Hierarchy2D.SetLocal` whenever a hierarchy is attached so `WorldTransform2D` dirty flags propagate to descendants automatically. Built-in `"world_transform2d"` is explicitly read-only because it is a derived cache overwritten on `Hierarchy2D.Sync()`. `game_entity_destroy` accepts `"cascade"`, `"orphan"`, `"keep_world"`, and `"reparent"` policies without lazily instantiating `Hierarchy2D` when an entity has no children. +- **Read-only vs mutable bridge components**: `RegisterComponent[T]` and `RegisterComponentFunc` remain read-only so inspection-only registrations (such as components carrying callbacks) do not silently become writable. Callers opt in with `RegisterMutableComponent[T]` or upgrade an existing registration with `RegisterComponentEditor[T]` to enforce domain invariants before writing. + +## Alternatives considered + +### Making `RegisterComponent[T]` automatically writable + +Allowing `game_component_set` to write to every `RegisterComponent[T]` registration would save one registration call for transient structs. It was rejected because games intentionally use `RegisterComponent` for read-only debug views or structs with runtime callbacks/handles (`OnTick func()`, pointers), where unconstrained JSON writes could corrupt invariants or zero unexported fields; explicit `RegisterMutableComponent` and `RegisterComponentEditor` keep the safety boundary clear while `entities.RegisterCodec` components remain automatically editable. + +### Replace-only `game_component_set` (no default patch mode) + +Decoding every `game_component_set` payload into a zero-valued struct would be simpler to implement. It was rejected because Go's zero value for `entities.Transform2D` has `ScaleX: 0, ScaleY: 0` (collapsed scale), so an agent sending `{"x": 100, "y": 50}` would silently make the object invisible, and tweaking one field on a gameplay struct (like `health.hp`) would wipe unrelated fields (`health.max`). Patching by default with an explicit `"replace": true` flag supports both workflows safely. + +### Handling codec decoding purely inside `packages/game/mcp` via `World.Snapshot` / `Restore` + +Avoiding changes to `packages/game/entities` by snapshotting, editing JSON, and calling `World.Restore` would keep `entities` untouched. It was rejected because `Snapshot`/`Restore` is O(world size), resets un-serialized transient component stores, and does not support strict `DisallowUnknownFields` decoding for a single entity's component. Adding zero-reflection `DecodeComponent`, `PatchComponent`, and `RemoveComponent` methods to `entities.World` keeps single-entity edits O(1) and preserves transient components. + +## Consequences + +- **Benefits**: Coding agents can discover prefabs, spawn entities (with hierarchy and initial components), edit codec/built-in/custom components with immediate effect on the next simulation step, remove components, and destroy subtrees with explicit hierarchy policies—all with strict validation and atomic rollback on error. +- **Costs**: `packages/game/entities` gains three public codec mutation methods (`DecodeComponent`, `PatchComponent`, `RemoveComponent`) to maintain alongside `EncodeComponent`. Patch mode performs a JSON round-trip copy on existing component values to guarantee map/slice isolation during error rollback, which is negligible for interactive MCP edits but not intended for per-frame inner loops. + +## Verification + +Verified with `gofmt`, `go run ./cmd/gameschema -check`, `go tool nsgo check -target macos,windows,linux,android,web`, `go tool nsgo test ./mcp`, `go tool nsgo test ./entities`, `go tool nsgo test -run TestStabilityTable .`, `go run ./tools/changelog check`, and `bun run verify-notes`. diff --git a/changelog.d/mcp-spawn-destroy-edit.md b/changelog.d/mcp-spawn-destroy-edit.md new file mode 100644 index 00000000..8481da9a --- /dev/null +++ b/changelog.d/mcp-spawn-destroy-edit.md @@ -0,0 +1,4 @@ +### Added + +- `game/mcp`: add `game_prefabs_list`, `game_entity_spawn`, `game_entity_destroy`, `game_component_set`, and `game_component_remove` tools along with prefab registration (`Config.Prefabs`, `Bridge.RegisterPrefab`, `Bridge.RegisterEntityPrefab`, `Bridge.RegisterScenePrefab`) and typed component editing (`RegisterMutableComponent`, `RegisterComponentEditor`) (#464). +- `game/entities`: add `World.DecodeComponent`, `World.PatchComponent`, and `World.RemoveComponent` strict JSON codec mutation helpers (#464). diff --git a/docs/en/mcp.md b/docs/en/mcp.md index c8b9fa85..193e91b7 100644 --- a/docs/en/mcp.md +++ b/docs/en/mcp.md @@ -39,20 +39,49 @@ if err != nil { - When a `scene.Manager` controller draws via a custom `Controller.Draw` without setting `Controller.Scene`, `SceneFunc` / `Scene` provides the current scene's layers automatically. - When `EntityName` or `EntityLayer` is omitted (or returns `""`), `game/mcp` falls back to [`sceneformat.ObjectRef`](editor.md) if the entity carries one. -## Inspecting components +## Inspecting and editing components -Components registered on an [`entities.World`](entities.md) with `entities.RegisterCodec` are readable automatically. In addition: +Components registered on an [`entities.World`](entities.md) with `entities.RegisterCodec` are readable and editable automatically. In addition: -- Built-in `entities.Transform2D`, `entities.WorldTransform2D` and `sceneformat.ObjectRef` components are surfaced automatically as `"transform2d"`, `"world_transform2d"` and `"object_ref"` unless that type or name is already registered. -- Transient or non-saved runtime components can be exposed with `mcp.RegisterComponent[T](bridge, name)` or a custom reader via `mcp.RegisterComponentFunc(bridge, name, read)`. +- Built-in `entities.Transform2D`, `entities.WorldTransform2D` and `sceneformat.ObjectRef` components are surfaced automatically as `"transform2d"`, `"world_transform2d"` and `"object_ref"` unless that type or name is already registered. `"transform2d"` and `"object_ref"` are editable directly (with `"transform2d"` propagating `Hierarchy2D` dirty flags automatically); `"world_transform2d"` is derived from the hierarchy and read-only. +- Transient or non-saved runtime components can be exposed read-only with `mcp.RegisterComponent[T](bridge, name)` or `mcp.RegisterComponentFunc(bridge, name, read)`, or exposed for both reading and editing with `mcp.RegisterMutableComponent[T](bridge, name)` or `mcp.RegisterComponentEditor[T](bridge, name, apply)`. +- `game_component_set` decodes values strictly with `DisallowUnknownFields`, rejects non-finite floats (`NaN`, `±Inf`) and invalid nulls, and patches existing fields by default (preserving omitted fields unless `"replace": true` is passed) without leaving partially mutated state on error. - Component values are serialized with `encoding/json`; if a runtime value contains non-finite floats (`NaN`, `+Inf`, `-Inf`), callback fields, channels or cyclic pointers, `game/mcp` falls back to a safe sanitizer (`"NaN"`, `"+Inf"`, `"-Inf"`, `""`, `""`, `""`) so an agent can still diagnose broken runtime state. ```go -if err := mcp.RegisterComponent[AIState](bridge, "ai"); err != nil { +if err := mcp.RegisterMutableComponent[AIState](bridge, "ai"); err != nil { + return err +} +if err := mcp.RegisterComponentEditor[Health](bridge, "health", func(w *entities.World, e entities.Entity, h Health) error { + if h.HP < 0 { + return errors.New("hp cannot be negative") + } + entities.Set(w, e, h) + return nil +}); err != nil { return err } ``` +## Registering prefabs + +Prefabs can be registered on `mcp.Config.Prefabs` or on the `*mcp.Bridge` so agents can discover them with `game_prefabs_list` and spawn them with `game_entity_spawn`: + +- `bridge.RegisterPrefab(name, spawn)` (or `Config.Prefabs`) registers a custom `mcp.PrefabSpawner` (`func(w *entities.World, overrides map[string]any) (entities.Entity, error)`). +- `bridge.RegisterEntityPrefab(p)` registers an [`*entities.Prefab`](entities.md) under `p.Name()`. +- `bridge.RegisterScenePrefab(name, doc)` registers a validated, self-contained [`*sceneformat.SceneDoc`](editor.md) template spawned via `sceneformat.SpawnEntities`. + +```go +if err := bridge.RegisterEntityPrefab(coinPrefab); err != nil { + return err +} +if err := bridge.RegisterScenePrefab("turret", turretDoc); err != nil { + return err +} +``` + +If `game_entity_spawn` fails while applying `parent`, `x`/`y`, or `components` after spawning, the newly spawned entity (and any scene-prefab children) are rolled back automatically. + ## Registered tools | Tool | Arguments | What it returns | @@ -77,6 +106,11 @@ if err := mcp.RegisterComponent[AIState](bridge, "ai"); err != nil { | `game_tunable_set` | `name` (required), `value` (required), `clamp` (optional, default `false`) | Updates a registered tunable (`float`, `int`, `bool` or `string`) with strict type checking and range validation (or clamping when `clamp: true`), returning `old_value`, applied `value`, metadata and `clamped`. | | `game_console_commands_list` | `include_builtin` (optional, default `true`) | Built-in and custom `debug.Console` commands sorted by name with `help` text and `builtin` flag. | | `game_console_exec` | `command` (required) | Runs one command line through `debug.Console`, returning `command`, `ok`, `output`, `lines`, and `error` (when the console command fails). | +| `game_prefabs_list` | `{}` | Sorted list of registered prefabs (`name` and `kind`: `"custom"`, `"entity_prefab"`, or `"scene"`). | +| `game_entity_spawn` | `prefab`, `overrides`, `parent`, `x`, `y`, `components` (all optional) | Newly spawned live entity's stable `ref`, `index`, `generation`, `prefab`, metadata, `parent`, `children`, and initial `components` snapshot. | +| `game_entity_destroy` | `ref` (required), `policy` (optional: `"cascade"`, `"orphan"`, `"keep_world"`, or `"reparent"`) | Confirmation of destruction with `ref`, effective `policy`, and count of `destroyed` entities. | +| `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. | +| `game_component_remove` | `ref` (required), `component` (required) | Whether the component was present and `removed` from the live entity. | All tools reject unknown argument fields. diff --git a/docs/zh/mcp.md b/docs/zh/mcp.md index 5a12ad2c..8d171774 100644 --- a/docs/zh/mcp.md +++ b/docs/zh/mcp.md @@ -39,20 +39,49 @@ if err != nil { - 如果 `scene.Manager` 的控制器通过自定义 `Controller.Draw` 绘制而没有设置 `Controller.Scene`,`SceneFunc` / `Scene` 会自动作为当前场景的图层来源。 - 未提供 `EntityName` 或 `EntityLayer`(或其返回 `""`)时,若实体带有 [`sceneformat.ObjectRef`](editor.md),`game/mcp` 会自动回退到其中的 `ID` 和 `Layer`。 -## 检查组件 +## 检查与编辑组件 -已在 [`entities.World`](entities.md) 上通过 `entities.RegisterCodec` 注册的组件会自动可读。此外: +已在 [`entities.World`](entities.md) 上通过 `entities.RegisterCodec` 注册的组件会自动支持读取和编辑。此外: -- 内置的 `entities.Transform2D`、`entities.WorldTransform2D` 和 `sceneformat.ObjectRef` 组件在未被同类型或同名注册覆盖时,会自动以 `"transform2d"`、`"world_transform2d"` 和 `"object_ref"` 的名称暴露。 -- 未写入存档的瞬态运行时组件可以通过 `mcp.RegisterComponent[T](bridge, name)` 注册,或使用 `mcp.RegisterComponentFunc(bridge, name, read)` 提供自定义读取器。 +- 内置的 `entities.Transform2D`、`entities.WorldTransform2D` 和 `sceneformat.ObjectRef` 组件在未被同类型或同名注册覆盖时,会自动以 `"transform2d"`、`"world_transform2d"` 和 `"object_ref"` 的名称暴露。其中 `"transform2d"` 和 `"object_ref"` 可直接编辑(编辑 `"transform2d"` 会自动传播 `Hierarchy2D` 脏标记);`"world_transform2d"` 由层级派生,为只读组件。 +- 未写入存档的瞬态运行时组件可以通过 `mcp.RegisterComponent[T](bridge, name)` 或 `mcp.RegisterComponentFunc(bridge, name, read)` 只读暴露,也可以通过 `mcp.RegisterMutableComponent[T](bridge, name)` 或 `mcp.RegisterComponentEditor[T](bridge, name, apply)` 同时支持读取与编辑。 +- `game_component_set` 使用 `DisallowUnknownFields` 严格解码,拒绝非有限浮点数(`NaN`、`±Inf`)及非法 `null`,默认以补丁模式更新现有字段(保留未传入字段,传入 `"replace": true` 时从零值整块替换),且解码失败时不会留下半修改状态。 - 组件值默认用 `encoding/json` 序列化;若运行时值包含非有限浮点数(`NaN`、`+Inf`、`-Inf`)、回调函数字段、channel 或循环指针,`game/mcp` 会回退到安全的清洗编码(`"NaN"`、`"+Inf"`、`"-Inf"`、`""`、`""`、`""`),使智能体在状态异常时仍能诊断问题。 ```go -if err := mcp.RegisterComponent[AIState](bridge, "ai"); err != nil { +if err := mcp.RegisterMutableComponent[AIState](bridge, "ai"); err != nil { + return err +} +if err := mcp.RegisterComponentEditor[Health](bridge, "health", func(w *entities.World, e entities.Entity, h Health) error { + if h.HP < 0 { + return errors.New("hp cannot be negative") + } + entities.Set(w, e, h) + return nil +}); err != nil { return err } ``` +## 注册预制体 + +可以在 `mcp.Config.Prefabs` 或 `*mcp.Bridge` 上注册预制体,供智能体通过 `game_prefabs_list` 发现并用 `game_entity_spawn` 生成: + +- `bridge.RegisterPrefab(name, spawn)`(或 `Config.Prefabs`)注册自定义 `mcp.PrefabSpawner`(`func(w *entities.World, overrides map[string]any) (entities.Entity, error)`)。 +- `bridge.RegisterEntityPrefab(p)` 按 `p.Name()` 注册 [`*entities.Prefab`](entities.md)。 +- `bridge.RegisterScenePrefab(name, doc)` 注册经过校验且自包含的 [`*sceneformat.SceneDoc`](editor.md) 模板,并通过 `sceneformat.SpawnEntities` 实例化。 + +```go +if err := bridge.RegisterEntityPrefab(coinPrefab); err != nil { + return err +} +if err := bridge.RegisterScenePrefab("turret", turretDoc); err != nil { + return err +} +``` + +如果在 `game_entity_spawn` 生成实体后,应用 `parent`、`x`/`y` 或 `components` 时发生错误,新生成的实体(以及场景预制体的子实体)会自动回滚销毁。 + ## 已注册的工具 | 工具 | 参数 | 返回内容 | @@ -77,6 +106,11 @@ if err := mcp.RegisterComponent[AIState](bridge, "ai"); err != nil { | `game_tunable_set` | `name`(必填)、`value`(必填)、`clamp`(可选,默认 `false`) | 按严格类型检查与范围校验(或 `clamp: true` 时钳位)更新已注册的可调参数(`float`、`int`、`bool` 或 `string`),返回 `old_value`、生效后的 `value`、元数据与 `clamped` 标记。 | | `game_console_commands_list` | `include_builtin`(可选,默认 `true`) | 按名称排序的 `debug.Console` 内置命令与自定义命令列表,包含 `help` 说明与 `builtin` 标记。 | | `game_console_exec` | `command`(必填) | 通过 `debug.Console` 执行一条命令行,返回 `command`、`ok`、`output`、`lines` 以及命令失败时的 `error`。 | +| `game_prefabs_list` | `{}` | 已注册预制体的排序列表(`name` 与 `kind`:`"custom"`、`"entity_prefab"` 或 `"scene"`)。 | +| `game_entity_spawn` | `prefab`、`overrides`、`parent`、`x`、`y`、`components`(均为可选) | 新生成存活实体的稳定引用 `ref`、`index`、`generation`、`prefab`、元数据、`parent`、`children` 及初始 `components` 快照。 | +| `game_entity_destroy` | `ref`(必填)、`policy`(可选:`"cascade"`、`"orphan"`、`"keep_world"` 或 `"reparent"`) | 销毁结果,包含 `ref`、生效的 `policy` 与实际销毁实体数 `destroyed`。 | +| `game_component_set` | `ref`(必填)、`component`(必填)、`value`(必填)、`replace`(可选,默认 `false`) | 回读自存活实体的更新后组件 `value`;修改会在下一次模拟步进中生效。 | +| `game_component_remove` | `ref`(必填)、`component`(必填) | 报告指定组件是否存在并已从存活实体移除(`removed`)。 | 所有工具都会拒绝未知的参数字段。 diff --git a/packages/game/entities/codec_edit_test.go b/packages/game/entities/codec_edit_test.go new file mode 100644 index 00000000..1a4d2677 --- /dev/null +++ b/packages/game/entities/codec_edit_test.go @@ -0,0 +1,122 @@ +package entities_test + +import ( + "encoding/json" + "errors" + "testing" + + "github.com/nsgo-dev/game/packages/game/entities" +) + +func TestWorldDecodePatchRemoveComponent(t *testing.T) { + type stats struct { + HP int `json:"hp"` + Max int `json:"max"` + Tags map[string]int `json:"tags,omitempty"` + } + + w := entities.NewWorld() + if err := entities.RegisterCodec[stats](w, "stats"); err != nil { + t.Fatal(err) + } + if err := entities.RegisterCodec[entities.Transform2D](w, "xform"); err != nil { + t.Fatal(err) + } + e := w.Spawn() + entities.Set(w, e, stats{HP: 10, Max: 20, Tags: map[string]int{"fire": 1}}) + + // Patch updates only supplied fields and preserves omitted fields. + if err := w.PatchComponent(e, "stats", json.RawMessage(`{"hp": 7}`)); err != nil { + t.Fatalf("PatchComponent: %v", err) + } + got, ok := entities.Get[stats](w, e) + if !ok || got.HP != 7 || got.Max != 20 || got.Tags["fire"] != 1 { + t.Fatalf("after patch = %+v, want hp=7 max=20 tags={fire:1}", got) + } + + // Failed patch with unknown field must NOT mutate existing map/struct fields. + if err := w.PatchComponent(e, "stats", json.RawMessage(`{"tags": {"ice": 2}, "bogus": true}`)); err == nil { + t.Fatal("expected error for unknown field in PatchComponent") + } + got, _ = entities.Get[stats](w, e) + if _, leaked := got.Tags["ice"]; leaked || got.Tags["fire"] != 1 { + t.Fatalf("failed patch mutated existing map: %+v", got.Tags) + } + + // DecodeComponent replaces from zero value. + if err := w.DecodeComponent(e, "stats", json.RawMessage(`{"hp": 5}`)); err != nil { + t.Fatalf("DecodeComponent: %v", err) + } + got, _ = entities.Get[stats](w, e) + if got.HP != 5 || got.Max != 0 || len(got.Tags) != 0 { + t.Fatalf("after DecodeComponent = %+v, want hp=5 max=0 empty tags", got) + } + + // Reject null for struct, trailing data, unknown codec, dead entity, disposed/nil world. + if err := w.DecodeComponent(e, "stats", json.RawMessage(`null`)); err == nil { + t.Fatal("expected error decoding null into struct") + } + if err := w.DecodeComponent(e, "stats", json.RawMessage(`{"hp":1} {"hp":2}`)); err == nil { + t.Fatal("expected error for trailing JSON data") + } + if err := w.DecodeComponent(e, "missing", json.RawMessage(`{}`)); !errors.Is(err, entities.ErrUnknownCodec) { + t.Fatalf("unknown codec = %v, want ErrUnknownCodec", err) + } + + // Decoding Transform2D codec marks Hierarchy2D dirty automatically. + h := w.Hierarchy2D() + h.SetLocal(e, entities.NewTransform2D(1, 2)) + h.Sync() + if h.IsDirty(e) { + t.Fatal("expected clean transform after Sync") + } + if err := w.PatchComponent(e, "xform", json.RawMessage(`{"x": 42}`)); err != nil { + t.Fatalf("patch xform: %v", err) + } + if !h.IsDirty(e) { + t.Fatal("expected Transform2D codec edit to mark Hierarchy2D dirty") + } + h.Sync() + wt, ok := h.WorldTransform(e) + if !ok || wt.X != 42 || wt.Y != 2 || wt.ScaleX != 1 || wt.ScaleY != 1 { + t.Fatalf("world transform = %+v, want x=42 y=2 scale=(1,1)", wt) + } + + // RemoveComponent removes present component and returns false when absent. + removed, err := w.RemoveComponent(e, "stats") + if err != nil || !removed || entities.Has[stats](w, e) { + t.Fatalf("first RemoveComponent = (%v, %v), has=%v", removed, err, entities.Has[stats](w, e)) + } + removed, err = w.RemoveComponent(e, "stats") + if err != nil || removed { + t.Fatalf("second RemoveComponent = (%v, %v), want (false, nil)", removed, err) + } + if _, err := w.RemoveComponent(e, "missing"); !errors.Is(err, entities.ErrUnknownCodec) { + t.Fatalf("remove unknown codec = %v, want ErrUnknownCodec", err) + } + + // Dead entity & disposed/nil world errors. + w.Destroy(e) + if err := w.DecodeComponent(e, "stats", json.RawMessage(`{"hp":1}`)); !errors.Is(err, entities.ErrDeadEntity) { + t.Fatalf("dead entity decode = %v, want ErrDeadEntity", err) + } + if _, err := w.RemoveComponent(e, "stats"); !errors.Is(err, entities.ErrDeadEntity) { + t.Fatalf("dead entity remove = %v, want ErrDeadEntity", err) + } + + var nilW *entities.World + if err := nilW.DecodeComponent(e, "stats", json.RawMessage(`{}`)); err == nil { + t.Fatal("expected nil world decode error") + } + if _, err := nilW.RemoveComponent(e, "stats"); err == nil { + t.Fatal("expected nil world remove error") + } + + w.Dispose() + if err := w.DecodeComponent(e, "stats", json.RawMessage(`{}`)); !errors.Is(err, entities.ErrWorldDisposed) { + t.Fatalf("disposed world decode = %v, want ErrWorldDisposed", err) + } + if _, err := w.RemoveComponent(e, "stats"); !errors.Is(err, entities.ErrWorldDisposed) { + t.Fatalf("disposed world remove = %v, want ErrWorldDisposed", err) + } +} diff --git a/packages/game/entities/snapshot.go b/packages/game/entities/snapshot.go index cf0be52d..6129b8a1 100644 --- a/packages/game/entities/snapshot.go +++ b/packages/game/entities/snapshot.go @@ -1,9 +1,11 @@ package entities import ( + "bytes" "encoding/json" "errors" "fmt" + "io" "slices" "github.com/nsgo-dev/game/packages/game/loaderr" @@ -25,11 +27,13 @@ var ( const maxSnapshotIndex = 1 << 20 type componentCodec struct { - name string - key typeKey - has func(w *World, e Entity) bool - encode func(w *World, e Entity) (json.RawMessage, bool, error) - decode func(w *World, e Entity, raw json.RawMessage) error + name string + key typeKey + has func(w *World, e Entity) bool + encode func(w *World, e Entity) (json.RawMessage, bool, error) + decode func(w *World, e Entity, raw json.RawMessage) error + decodeStrict func(w *World, e Entity, raw json.RawMessage, patch bool) error + remove func(w *World, e Entity) bool } // WorldSnapshot is a deterministic, JSON-serializable snapshot of a World's live entities and registered components. @@ -99,6 +103,42 @@ func RegisterCodec[T any](w *World, typeName string) error { Set[T](w, e, v) return nil }, + decodeStrict: func(w *World, e Entity, raw json.RawMessage, patch bool) error { + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 { + return errors.New("empty JSON value") + } + var v T + if bytes.Equal(trimmed, []byte("null")) { + zeroJSON, err := json.Marshal(v) + if err != nil || !bytes.Equal(bytes.TrimSpace(zeroJSON), []byte("null")) { + return errors.New("cannot decode null into non-nullable component") + } + } else if patch { + if cur, ok := Get[T](w, e); ok { + // Deep-copy via JSON so a partial decode error never mutates *cur's maps or slices. + curJSON, err := json.Marshal(*cur) + if err != nil { + return err + } + if err := json.Unmarshal(curJSON, &v); err != nil { + return err + } + } + } + if err := decodeStrictJSON(trimmed, &v); err != nil { + return err + } + Set[T](w, e, v) + return nil + }, + remove: func(w *World, e Entity) bool { + if !Has[T](w, e) { + return false + } + Remove[T](w, e) + return true + }, } w.codecByKey[k] = typeName w.codecOrder = append(w.codecOrder, typeName) @@ -158,6 +198,69 @@ func (w *World) EncodeComponent(e Entity, typeName string) (json.RawMessage, boo return raw, present, nil } +func decodeStrictJSON(trimmed []byte, dst any) error { + dec := json.NewDecoder(bytes.NewReader(trimmed)) + dec.DisallowUnknownFields() + if err := dec.Decode(dst); err != nil { + return err + } + var extra any + if err := dec.Decode(&extra); err != io.EOF { + return errors.New("unexpected trailing data") + } + return nil +} + +// DecodeComponent strictly decodes raw JSON into the codec-registered component named typeName and attaches or replaces it on live entity e. +// Unknown JSON fields, trailing data and invalid nulls for non-nullable component types are rejected without mutating e. +func (w *World) DecodeComponent(e Entity, typeName string, raw json.RawMessage) error { + return w.decodeComponentStrict(e, typeName, raw, false) +} + +// PatchComponent strictly decodes raw JSON into a copy of live entity e's existing codec-registered component (or its zero value when absent) and writes the result back atomically. +// Unknown JSON fields and trailing data are rejected without mutating e. +func (w *World) PatchComponent(e Entity, typeName string, raw json.RawMessage) error { + return w.decodeComponentStrict(e, typeName, raw, true) +} + +func (w *World) decodeComponentStrict(e Entity, typeName string, raw json.RawMessage, patch bool) error { + if w == nil { + return errors.New("entities: nil world") + } + if w.disposed { + return ErrWorldDisposed + } + if !w.Alive(e) { + return ErrDeadEntity + } + codec, ok := w.codecs[typeName] + if !ok { + return fmt.Errorf("entities: component %q: %w", typeName, ErrUnknownCodec) + } + if err := codec.decodeStrict(w, e, raw, patch); err != nil { + return fmt.Errorf("entities: decode %s on %s: %w", typeName, e, err) + } + return nil +} + +// RemoveComponent detaches the codec-registered component named typeName from live entity e and reports whether it was present. +func (w *World) RemoveComponent(e Entity, typeName string) (bool, error) { + if w == nil { + return false, errors.New("entities: nil world") + } + if w.disposed { + return false, ErrWorldDisposed + } + if !w.Alive(e) { + return false, ErrDeadEntity + } + codec, ok := w.codecs[typeName] + if !ok { + return false, fmt.Errorf("entities: component %q: %w", typeName, ErrUnknownCodec) + } + return codec.remove(w, e), nil +} + // EntityComponents encodes all codec-registered components carried by live entity e in ascending codec-name order. func (w *World) EntityComponents(e Entity) ([]ComponentSnapshot, error) { if w == nil { diff --git a/packages/game/mcp/doc.go b/packages/game/mcp/doc.go index 6ffa8aa8..d768a192 100644 --- a/packages/game/mcp/doc.go +++ b/packages/game/mcp/doc.go @@ -22,8 +22,13 @@ // - game_tunable_set: update one registered tunable's value with type checking and range validation or optional clamping. // - game_console_commands_list: list built-in and registered debug console commands with their usage descriptions. // - game_console_exec: execute a debug console command line and return its structured status, output text, output lines and error. +// - game_prefabs_list: list registered prefabs available to game_entity_spawn. +// - game_entity_spawn: spawn a registered prefab or empty entity with optional parent, position and component overrides. +// - 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. // -// Components registered on an [entities.World] with [entities.RegisterCodec] are readable automatically. Transient or non-saved components can also be exposed with [RegisterComponent] or [RegisterComponentFunc], and built-in [entities.Transform2D], [entities.WorldTransform2D] and [sceneformat.ObjectRef] components are surfaced automatically when present and not already registered under another name. +// 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]. // // Like [automation.Register], attachment is active in `nsgo dev -automation` and test builds (`nsgo test`) and is a no-op in ordinary and release builds. Call [Attach], [Bridge.Attach] and [Bridge.Detach] on the engine goroutine. package mcp diff --git a/packages/game/mcp/edit.go b/packages/game/mcp/edit.go new file mode 100644 index 00000000..eeb5ee3d --- /dev/null +++ b/packages/game/mcp/edit.go @@ -0,0 +1,1123 @@ +package mcp + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "reflect" + "slices" + "strings" + + "github.com/nsgo-dev/game/packages/game/entities" + "github.com/nsgo-dev/game/packages/game/sceneformat" + "github.com/nsgo-dev/nsgo/automation" +) + +// Tool names for object mutation registered by Bridge with github.com/nsgo-dev/nsgo/automation. +const ( + // ToolPrefabsList lists registered prefabs available to game_entity_spawn. + ToolPrefabsList = "game_prefabs_list" + // ToolEntitySpawn spawns a registered prefab or an empty entity with optional parent, position and component overrides. + ToolEntitySpawn = "game_entity_spawn" + // ToolEntityDestroy destroys a live entity by stable reference with an optional hierarchy child policy. + ToolEntityDestroy = "game_entity_destroy" + // ToolComponentSet sets or patches one component's value on a live entity. + ToolComponentSet = "game_component_set" + // ToolComponentRemove removes one component from a live entity. + ToolComponentRemove = "game_component_remove" +) + +var ( + // ErrEmptyPrefabName reports registering a prefab with an empty name. + ErrEmptyPrefabName = errors.New("mcp: empty prefab name") + // ErrDuplicatePrefab reports registering a prefab name that is already registered on the Bridge. + ErrDuplicatePrefab = errors.New("mcp: duplicate prefab registration") +) + +// PrefabSpawner spawns a live entity into w with optional override parameters from game_entity_spawn. +type PrefabSpawner func(w *entities.World, overrides map[string]any) (entities.Entity, error) + +type prefabEntry struct { + name string + kind string + spawn func(w *entities.World, overrides map[string]any) (entities.Entity, []entities.Entity, error) +} + +// PrefabInfo describes one registered prefab returned by game_prefabs_list. +type PrefabInfo struct { + Name string `json:"name"` + Kind string `json:"kind"` +} + +// PrefabsListResult is the JSON result of game_prefabs_list. +type PrefabsListResult struct { + Prefabs []PrefabInfo `json:"prefabs"` +} + +// EntitySpawnResult is the JSON result of game_entity_spawn. +type EntitySpawnResult struct { + Ref string `json:"ref"` + Index uint32 `json:"index"` + Generation uint32 `json:"generation"` + Prefab string `json:"prefab,omitempty"` + Name string `json:"name,omitempty"` + Layer string `json:"layer,omitempty"` + Tags []string `json:"tags,omitempty"` + Parent string `json:"parent,omitempty"` + Children []string `json:"children,omitempty"` + Components map[string]json.RawMessage `json:"components"` +} + +// EntityDestroyResult is the JSON result of game_entity_destroy. +type EntityDestroyResult struct { + Ref string `json:"ref"` + Policy string `json:"policy"` + Destroyed int `json:"destroyed"` +} + +// ComponentSetResult is the JSON result of game_component_set. +type ComponentSetResult struct { + Ref string `json:"ref"` + Component string `json:"component"` + Value json.RawMessage `json:"value"` +} + +// ComponentRemoveResult is the JSON result of game_component_remove. +type ComponentRemoveResult struct { + Ref string `json:"ref"` + Component string `json:"component"` + Removed bool `json:"removed"` +} + +var ( + schemaPrefabsList = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "properties": {} + }`) + + schemaEntitySpawn = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "properties": { + "prefab": { + "type": "string", + "description": "Registered prefab name from game_prefabs_list; omit to spawn an empty entity." + }, + "overrides": { + "type": "object", + "description": "Prefab-specific override values passed to a custom PrefabSpawner." + }, + "parent": { + "type": "string", + "description": "Stable entity reference (e.g. \"entity:0:1\") to parent the spawned entity under in Hierarchy2D." + }, + "x": { + "type": "number", + "description": "Initial local Transform2D.X position." + }, + "y": { + "type": "number", + "description": "Initial local Transform2D.Y position." + }, + "components": { + "type": "object", + "description": "Map of component names to JSON values to attach or patch on the spawned entity." + } + } + }`) + + schemaEntityDestroy = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "required": ["ref"], + "properties": { + "ref": { + "type": "string", + "description": "Stable entity reference returned by game_entities_list or game_entity_spawn (e.g. \"entity:0:1\")." + }, + "policy": { + "type": "string", + "enum": ["cascade", "orphan", "keep_world", "reparent"], + "description": "How to handle hierarchy children: \"cascade\" destroys descendants, \"orphan\" detaches direct children to root keeping local transforms, \"keep_world\" detaches direct children to root preserving world transforms, \"reparent\" moves direct children to the destroyed entity's parent (or root). Omit to use the world's default policy." + } + } + }`) + + schemaComponentSet = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "required": ["ref", "component", "value"], + "properties": { + "ref": { + "type": "string", + "description": "Stable entity reference returned by game_entities_list or game_entity_spawn." + }, + "component": { + "type": "string", + "description": "Component name to set or patch on the entity." + }, + "value": { + "description": "JSON value for the component (patches existing fields by default unless replace is true)." + }, + "replace": { + "type": "boolean", + "description": "When true, decode value into a zero-valued component instead of patching existing fields (default false)." + } + } + }`) + + schemaComponentRemove = json.RawMessage(`{ + "type": "object", + "additionalProperties": false, + "required": ["ref", "component"], + "properties": { + "ref": { + "type": "string", + "description": "Stable entity reference returned by game_entities_list or game_entity_spawn." + }, + "component": { + "type": "string", + "description": "Component name to remove from the entity." + } + } + }`) +) + +func (b *Bridge) editTools() []automation.Tool { + return []automation.Tool{ + { + Name: ToolPrefabsList, + Description: "List registered prefabs that can be spawned with game_entity_spawn.", + InputSchema: schemaPrefabsList, + Handler: b.handlePrefabsList, + }, + { + Name: ToolEntitySpawn, + Description: "Spawn a registered prefab (or an empty entity) into the live world with optional parent, 2D position and component values, returning its stable reference and initial components.", + InputSchema: schemaEntitySpawn, + Handler: b.handleEntitySpawn, + }, + { + Name: ToolEntityDestroy, + Description: "Destroy a live entity by its stable reference, with an optional hierarchy policy (cascade, orphan, keep_world, or reparent).", + InputSchema: schemaEntityDestroy, + Handler: b.handleEntityDestroy, + }, + { + Name: ToolComponentSet, + Description: "Set or patch one component's value on a live entity by its stable reference so the edited value takes effect on the next simulation step.", + InputSchema: schemaComponentSet, + Handler: b.handleComponentSet, + }, + { + Name: ToolComponentRemove, + Description: "Remove one component from a live entity by its stable reference and component name.", + InputSchema: schemaComponentRemove, + Handler: b.handleComponentRemove, + }, + } +} + +func (b *Bridge) initPrefabs(prefabs map[string]PrefabSpawner) { + if len(prefabs) == 0 { + return + } + names := make([]string, 0, len(prefabs)) + for name, spawner := range prefabs { + if name == "" || spawner == nil { + continue + } + names = append(names, name) + } + slices.Sort(names) + for _, name := range names { + _ = b.RegisterPrefab(name, prefabs[name]) + } +} + +func (b *Bridge) addPrefabEntry(entry prefabEntry) error { + if b == nil { + return ErrNilBridge + } + if entry.name == "" { + return ErrEmptyPrefabName + } + if _, dup := b.prefabs[entry.name]; dup { + return fmt.Errorf("mcp: prefab %q: %w", entry.name, ErrDuplicatePrefab) + } + if b.prefabs == nil { + b.prefabs = make(map[string]prefabEntry) + } + b.prefabs[entry.name] = entry + b.prefabOrder = append(b.prefabOrder, entry.name) + slices.Sort(b.prefabOrder) + return nil +} + +// RegisterPrefab registers a custom prefab spawner under name on b for game_prefabs_list and game_entity_spawn. +func (b *Bridge) RegisterPrefab(name string, spawn PrefabSpawner) error { + if b == nil { + return ErrNilBridge + } + if name == "" { + return ErrEmptyPrefabName + } + if spawn == nil { + return errors.New("mcp: nil prefab spawner") + } + return b.addPrefabEntry(prefabEntry{ + name: name, + kind: "custom", + spawn: func(w *entities.World, overrides map[string]any) (entities.Entity, []entities.Entity, error) { + e, err := spawn(w, overrides) + if err != nil { + return entities.Zero, nil, err + } + if e == entities.Zero || !w.Alive(e) { + return entities.Zero, nil, fmt.Errorf("mcp: prefab %q returned a non-live entity", name) + } + return e, []entities.Entity{e}, nil + }, + }) +} + +// RegisterEntityPrefab registers an *entities.Prefab under its Prefab.Name on b for game_prefabs_list and game_entity_spawn. +func (b *Bridge) RegisterEntityPrefab(p *entities.Prefab) error { + if b == nil { + return ErrNilBridge + } + if p == nil { + return errors.New("mcp: nil entity prefab") + } + name := p.Name() + if name == "" { + return ErrEmptyPrefabName + } + return b.addPrefabEntry(prefabEntry{ + name: name, + kind: "entity_prefab", + spawn: func(w *entities.World, overrides map[string]any) (entities.Entity, []entities.Entity, error) { + if len(overrides) > 0 { + return entities.Zero, nil, fmt.Errorf("mcp: entity prefab %q does not accept overrides (pass component values in \"components\" instead)", name) + } + e := p.Spawn(w) + if e == entities.Zero || !w.Alive(e) { + return entities.Zero, nil, fmt.Errorf("mcp: prefab %q failed to spawn entity", name) + } + return e, []entities.Entity{e}, nil + }, + }) +} + +// RegisterScenePrefab registers a self-contained *sceneformat.SceneDoc template under name on b so game_entity_spawn can instantiate it via sceneformat.SpawnEntities. +// +// doc must pass sceneformat.Validate, must not refer to unresolved external scenes, and must contain at least one object. The first top-level object in document order is returned as the spawned root entity. +func (b *Bridge) RegisterScenePrefab(name string, doc *sceneformat.SceneDoc) error { + if b == nil { + return ErrNilBridge + } + if name == "" { + return ErrEmptyPrefabName + } + if doc == nil { + return errors.New("mcp: nil scene prefab") + } + if err := sceneformat.Validate(doc); err != nil { + return fmt.Errorf("mcp: scene prefab %q: %w", name, err) + } + if doc.RefersToScenes() { + return fmt.Errorf("mcp: scene prefab %q refers to external scenes; call sceneformat.Resolve first", name) + } + rootID := firstSceneObjectID(doc) + if rootID == "" { + return fmt.Errorf("mcp: scene prefab %q has no objects", name) + } + return b.addPrefabEntry(prefabEntry{ + name: name, + kind: "scene", + spawn: func(w *entities.World, overrides map[string]any) (entities.Entity, []entities.Entity, error) { + if len(overrides) > 0 { + return entities.Zero, nil, fmt.Errorf("mcp: scene prefab %q does not accept overrides (pass component values in \"components\" instead)", name) + } + spawned, err := sceneformat.SpawnEntities(doc, w) + if err != nil { + return entities.Zero, nil, fmt.Errorf("mcp: spawn scene prefab %q: %w", name, err) + } + root, ok := spawned[rootID] + if !ok || !w.Alive(root) { + return entities.Zero, nil, fmt.Errorf("mcp: scene prefab %q did not produce root object %q", name, rootID) + } + all := make([]entities.Entity, 0, len(spawned)) + for _, ent := range spawned { + all = append(all, ent) + } + return root, all, nil + }, + }) +} + +func firstSceneObjectID(doc *sceneformat.SceneDoc) string { + for li := range doc.Layers { + if len(doc.Layers[li].Objects) > 0 { + return doc.Layers[li].Objects[0].ID + } + } + return "" +} + +// RegisterMutableComponent registers component type T under name on b for both inspection (game_entities_list, game_entity_inspect, game_component_get) and mutation (game_component_set, game_component_remove, game_entity_spawn). +// +// Edits are strictly decoded with DisallowUnknownFields, validated against NaN/Inf floats, and written with entities.Set[T]. +func RegisterMutableComponent[T any](b *Bridge, name string) error { + if b == nil { + return ErrNilBridge + } + if name == "" { + return ErrEmptyComponentName + } + if _, dup := b.components[name]; dup { + return fmt.Errorf("mcp: component %q: %w", name, ErrDuplicateComponent) + } + return registerTypedComponentEditor[T](b, name, func(w *entities.World, e entities.Entity, v T) error { + entities.Set[T](w, e, v) + return nil + }) +} + +// RegisterComponentEditor registers a typed component editor for component type T under name on b. +// +// When name is not yet registered on b, it also registers inspection and removal for T. When name was previously registered read-only with RegisterComponent[T] (for the same type T) or RegisterComponentFunc, it attaches the editor to that registration. +// apply receives the strictly decoded and finite-validated value and may enforce domain invariants or synchronize secondary runtime state before writing. +func RegisterComponentEditor[T any](b *Bridge, name string, apply func(w *entities.World, e entities.Entity, v T) error) error { + if b == nil { + return ErrNilBridge + } + if name == "" { + return ErrEmptyComponentName + } + if apply == nil { + return errors.New("mcp: nil component editor") + } + return registerTypedComponentEditor[T](b, name, apply) +} + +func registerTypedComponentEditor[T any](b *Bridge, name string, apply func(w *entities.World, e entities.Entity, v T) error) error { + k := compTypeKeyOf[T]() + writeFn := func(w *entities.World, e entities.Entity, raw json.RawMessage, replace bool) error { + v, err := decodeTypedComponent[T](w, e, name, raw, replace) + if err != nil { + return err + } + return apply(w, e, v) + } + removeFn := func(w *entities.World, e entities.Entity) (bool, error) { + if !entities.Has[T](w, e) { + return false, nil + } + entities.Remove[T](w, e) + return true, nil + } + + if existing, exists := b.components[name]; exists { + if existing.write != nil { + return fmt.Errorf("mcp: component %q: %w", name, ErrDuplicateComponent) + } + if existing.typeKey != nil && existing.typeKey != k { + return fmt.Errorf("mcp: component %q already registered with a different type: %w", name, ErrDuplicateComponent) + } + existing.typeKey = k + existing.write = writeFn + existing.remove = removeFn + b.components[name] = existing + if b.compByType == nil { + b.compByType = make(map[compTypeKey]string) + } + b.compByType[k] = name + return nil + } + + if b.components == nil { + b.components = make(map[string]componentEntry) + b.compByType = make(map[compTypeKey]string) + } + b.components[name] = componentEntry{ + name: name, + typeKey: k, + has: func(w *entities.World, e entities.Entity) bool { + return entities.Has[T](w, e) + }, + read: func(w *entities.World, e entities.Entity) (any, bool, error) { + v, ok := entities.Get[T](w, e) + if !ok { + return nil, false, nil + } + return *v, true, nil + }, + write: writeFn, + remove: removeFn, + } + b.compOrder = append(b.compOrder, name) + slices.Sort(b.compOrder) + b.compByType[k] = name + return nil +} + +func (b *Bridge) handlePrefabsList(_ context.Context, raw json.RawMessage) (any, error) { + if _, err := decodeArgs[struct{}](raw); err != nil { + return nil, err + } + res := PrefabsListResult{ + Prefabs: make([]PrefabInfo, 0, len(b.prefabOrder)), + } + for _, name := range b.prefabOrder { + entry := b.prefabs[name] + res.Prefabs = append(res.Prefabs, PrefabInfo{ + Name: entry.name, + Kind: entry.kind, + }) + } + return res, nil +} + +type entitySpawnArgs struct { + Prefab string `json:"prefab"` + Overrides map[string]any `json:"overrides"` + Parent string `json:"parent"` + X *float64 `json:"x"` + Y *float64 `json:"y"` + Components map[string]json.RawMessage `json:"components"` +} + +func (b *Bridge) handleEntitySpawn(_ context.Context, raw json.RawMessage) (any, error) { + args, err := decodeArgs[entitySpawnArgs](raw) + if err != nil { + return nil, err + } + w, err := b.requireWorld() + if err != nil { + return nil, err + } + + if args.X != nil { + if err := validateFloat32Arg("x", *args.X); err != nil { + return nil, err + } + } + if args.Y != nil { + if err := validateFloat32Arg("y", *args.Y); err != nil { + return nil, err + } + } + + var parentEnt entities.Entity + if args.Parent != "" { + parentEnt, err = ParseEntityRef(args.Parent) + if err != nil { + return nil, err + } + if !w.Alive(parentEnt) { + return nil, fmt.Errorf("mcp: parent entity %q is not alive", args.Parent) + } + } + + var pEntry prefabEntry + hasPrefab := args.Prefab != "" + if hasPrefab { + var ok bool + pEntry, ok = b.prefabs[args.Prefab] + if !ok { + if len(b.prefabOrder) == 0 { + return nil, fmt.Errorf("mcp: unknown prefab %q (no prefabs registered)", args.Prefab) + } + return nil, fmt.Errorf("mcp: unknown prefab %q (available: %s)", args.Prefab, strings.Join(b.prefabOrder, ", ")) + } + } else if len(args.Overrides) > 0 { + return nil, errors.New("mcp: overrides require a prefab name") + } + + var ( + e entities.Entity + spawned []entities.Entity + ) + if hasPrefab { + e, spawned, err = pEntry.spawn(w, args.Overrides) + if err != nil { + return nil, err + } + } else { + e = w.Spawn() + if e == entities.Zero { + return nil, fmt.Errorf("mcp: %w", entities.ErrWorldDisposed) + } + spawned = []entities.Entity{e} + } + + rollback := func() { + for _, ent := range spawned { + if !w.Alive(ent) { + continue + } + if len(w.ChildrenOf(ent)) > 0 { + w.Hierarchy2D().DestroyWithPolicy(ent, entities.RemoveCascade) + } else { + w.Destroy(ent) + } + } + } + + if args.X != nil || args.Y != nil { + t := entities.IdentityTransform2D() + if cur, ok := entities.Get[entities.Transform2D](w, e); ok { + t = *cur + } + if args.X != nil { + t.X = float32(*args.X) + } + if args.Y != nil { + t.Y = float32(*args.Y) + } + entities.Set(w, e, t) + } + + if parentEnt != entities.Zero { + if err := w.Hierarchy2D().SetParent(e, parentEnt, false); err != nil { + rollback() + return nil, fmt.Errorf("mcp: set parent %q: %w", args.Parent, err) + } + } + + if len(args.Components) > 0 { + compNames := make([]string, 0, len(args.Components)) + for name := range args.Components { + compNames = append(compNames, name) + } + slices.Sort(compNames) + for _, name := range compNames { + if err := b.writeComponent(w, e, name, args.Components[name], false); err != nil { + rollback() + return nil, err + } + } + } + + vals, err := b.readAllComponents(w, e) + if err != nil { + return nil, err + } + res := EntitySpawnResult{ + Ref: FormatEntityRef(e), + Index: e.Index(), + Generation: e.Generation(), + Prefab: args.Prefab, + Name: b.entityName(w, e), + Layer: b.entityLayer(w, e), + Tags: b.entityTags(e), + Components: vals, + } + if p, ok := w.ParentOf(e); ok { + res.Parent = FormatEntityRef(p) + } + if ch := w.ChildrenOf(e); len(ch) > 0 { + res.Children = make([]string, len(ch)) + for i, c := range ch { + res.Children[i] = FormatEntityRef(c) + } + } + return res, nil +} + +type entityDestroyArgs struct { + Ref string `json:"ref"` + Policy string `json:"policy"` +} + +func (b *Bridge) handleEntityDestroy(_ context.Context, raw json.RawMessage) (any, error) { + args, err := decodeArgs[entityDestroyArgs](raw) + if err != nil { + return nil, err + } + if args.Ref == "" { + return nil, errors.New("mcp: ref is required") + } + switch args.Policy { + case "", "cascade", "orphan", "keep_world", "reparent": + default: + return nil, fmt.Errorf("mcp: invalid destroy policy %q (want \"cascade\", \"orphan\", \"keep_world\", or \"reparent\")", args.Policy) + } + + w, err := b.requireWorld() + if err != nil { + return nil, err + } + e, err := ParseEntityRef(args.Ref) + if err != nil { + return nil, err + } + if !w.Alive(e) { + return nil, fmt.Errorf("mcp: entity %q is not alive", args.Ref) + } + + before := w.Count() + effectivePolicy := args.Policy + if effectivePolicy == "" { + effectivePolicy = "default" + } + + switch args.Policy { + case "": + w.Destroy(e) + case "cascade": + if len(w.ChildrenOf(e)) > 0 { + w.Hierarchy2D().DestroyWithPolicy(e, entities.RemoveCascade) + } else { + w.Destroy(e) + } + case "orphan": + if len(w.ChildrenOf(e)) > 0 { + w.Hierarchy2D().DestroyWithPolicy(e, entities.RemoveDetach) + } else { + w.Destroy(e) + } + case "keep_world": + if len(w.ChildrenOf(e)) > 0 { + w.Hierarchy2D().DestroyWithPolicy(e, entities.RemoveDetachKeepWorld) + } else { + w.Destroy(e) + } + case "reparent": + if children := w.ChildrenOf(e); len(children) > 0 { + h := w.Hierarchy2D() + parent, hasParent := w.ParentOf(e) + for _, ch := range children { + if hasParent { + if err := h.SetParent(ch, parent, false); err != nil { + return nil, fmt.Errorf("mcp: reparent child %s: %w", FormatEntityRef(ch), err) + } + } else { + h.Detach(ch, false) + } + } + } + w.Destroy(e) + } + + return EntityDestroyResult{ + Ref: FormatEntityRef(e), + Policy: effectivePolicy, + Destroyed: before - w.Count(), + }, nil +} + +type componentSetArgs struct { + Ref string `json:"ref"` + Component string `json:"component"` + Value json.RawMessage `json:"value"` + Replace bool `json:"replace"` +} + +func (b *Bridge) handleComponentSet(_ context.Context, raw json.RawMessage) (any, error) { + args, err := decodeArgs[componentSetArgs](raw) + if err != nil { + return nil, err + } + if args.Ref == "" { + return nil, errors.New("mcp: ref is required") + } + if args.Component == "" { + return nil, errors.New("mcp: component is required") + } + if len(bytes.TrimSpace(args.Value)) == 0 { + return nil, errors.New("mcp: value is required") + } + + w, err := b.requireWorld() + if err != nil { + return nil, err + } + e, err := ParseEntityRef(args.Ref) + if err != nil { + return nil, err + } + if !w.Alive(e) { + return nil, fmt.Errorf("mcp: entity %q is not alive", args.Ref) + } + + if err := b.writeComponent(w, e, args.Component, args.Value, args.Replace); err != nil { + return nil, err + } + + val, ok, err := b.readComponent(w, e, args.Component) + if err != nil { + return nil, err + } + if !ok { + val = json.RawMessage("null") + } + return ComponentSetResult{ + Ref: FormatEntityRef(e), + Component: args.Component, + Value: val, + }, nil +} + +type componentRemoveArgs struct { + Ref string `json:"ref"` + Component string `json:"component"` +} + +func (b *Bridge) handleComponentRemove(_ context.Context, raw json.RawMessage) (any, error) { + args, err := decodeArgs[componentRemoveArgs](raw) + if err != nil { + return nil, err + } + if args.Ref == "" { + return nil, errors.New("mcp: ref is required") + } + if args.Component == "" { + return nil, errors.New("mcp: component is required") + } + + w, err := b.requireWorld() + if err != nil { + return nil, err + } + e, err := ParseEntityRef(args.Ref) + if err != nil { + return nil, err + } + if !w.Alive(e) { + return nil, fmt.Errorf("mcp: entity %q is not alive", args.Ref) + } + + removed, err := b.removeComponent(w, e, args.Component) + if err != nil { + return nil, err + } + return ComponentRemoveResult{ + Ref: FormatEntityRef(e), + Component: args.Component, + Removed: removed, + }, nil +} + +func (b *Bridge) writeComponent(w *entities.World, e entities.Entity, name string, raw json.RawMessage, replace bool) error { + if entry, ok := b.components[name]; ok { + if entry.write == nil { + return fmt.Errorf("mcp: component %q is read-only (register with RegisterMutableComponent or RegisterComponentEditor to allow edits)", name) + } + if err := entry.write(w, e, raw, replace); err != nil { + return fmt.Errorf("mcp: set component %q on %s: %w", name, FormatEntityRef(e), err) + } + return nil + } + + var codecErr error + if replace { + codecErr = w.DecodeComponent(e, name, raw) + } else { + codecErr = w.PatchComponent(e, name, raw) + } + if codecErr == nil { + return nil + } + if !errors.Is(codecErr, entities.ErrUnknownCodec) { + return fmt.Errorf("mcp: set component %q on %s: %w", name, FormatEntityRef(e), codecErr) + } + + for _, bc := range builtinComponents { + if bc.name != name || !b.builtinActive(w, bc) { + continue + } + switch bc.name { + case "transform2d": + return writeBuiltinTransform2D(w, e, raw, replace) + case "object_ref": + return writeBuiltinObjectRef(w, e, raw, replace) + case "world_transform2d": + return errors.New(`mcp: component "world_transform2d" is derived from hierarchy and read-only; edit "transform2d" instead`) + } + } + + return b.unknownEditableComponentError(w, name) +} + +func (b *Bridge) removeComponent(w *entities.World, e entities.Entity, name string) (bool, error) { + if entry, ok := b.components[name]; ok { + if entry.remove == nil { + return false, fmt.Errorf("mcp: component %q is read-only (register with RegisterMutableComponent or RegisterComponentEditor to allow edits)", name) + } + return entry.remove(w, e) + } + + removed, err := w.RemoveComponent(e, name) + if err == nil { + return removed, nil + } + if !errors.Is(err, entities.ErrUnknownCodec) { + return false, fmt.Errorf("mcp: remove component %q on %s: %w", name, FormatEntityRef(e), err) + } + + for _, bc := range builtinComponents { + if bc.name != name || !b.builtinActive(w, bc) { + continue + } + switch bc.name { + case "transform2d": + if !entities.Has[entities.Transform2D](w, e) { + return false, nil + } + entities.Remove[entities.Transform2D](w, e) + if entities.Has[entities.WorldTransform2D](w, e) || len(w.ChildrenOf(e)) > 0 { + w.Hierarchy2D().MarkDirty(e) + } + return true, nil + case "object_ref": + if !entities.Has[sceneformat.ObjectRef](w, e) { + return false, nil + } + entities.Remove[sceneformat.ObjectRef](w, e) + return true, nil + case "world_transform2d": + return false, errors.New(`mcp: component "world_transform2d" is derived from hierarchy and read-only`) + } + } + + return false, b.unknownEditableComponentError(w, name) +} + +func (b *Bridge) unknownEditableComponentError(w *entities.World, name string) error { + editable := b.editableComponentNames(w) + if len(editable) == 0 { + return fmt.Errorf("mcp: unknown component %q (no editable components registered)", name) + } + return fmt.Errorf("mcp: unknown component %q (editable: %s)", name, strings.Join(editable, ", ")) +} + +func (b *Bridge) editableComponentNames(w *entities.World) []string { + seen := make(map[string]struct{}) + var names []string + add := func(name string) { + if _, dup := seen[name]; dup { + return + } + seen[name] = struct{}{} + names = append(names, name) + } + for _, name := range b.compOrder { + if b.components[name].write != nil { + add(name) + } + } + for _, name := range w.CodecNames() { + if _, overridden := b.components[name]; overridden { + continue + } + add(name) + } + for _, bc := range builtinComponents { + if bc.name == "world_transform2d" { + continue + } + if b.builtinActive(w, bc) { + add(bc.name) + } + } + slices.Sort(names) + return names +} + +func writeBuiltinTransform2D(w *entities.World, e entities.Entity, raw json.RawMessage, replace bool) error { + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 { + return errors.New("mcp: empty transform2d value") + } + if bytes.Equal(trimmed, []byte("null")) { + return errors.New(`mcp: cannot set "transform2d" to null; use game_component_remove to remove a component`) + } + var t entities.Transform2D + if !replace { + if cur, ok := entities.Get[entities.Transform2D](w, e); ok { + t = *cur + } else { + t = entities.IdentityTransform2D() + } + } + if err := decodeStrictValue(trimmed, &t); err != nil { + return fmt.Errorf("mcp: set component %q on %s: %w", "transform2d", FormatEntityRef(e), err) + } + for _, pair := range []struct { + field string + val float32 + }{ + {"x", t.X}, + {"y", t.Y}, + {"rotation", t.Rotation}, + {"scaleX", t.ScaleX}, + {"scaleY", t.ScaleY}, + } { + if math.IsNaN(float64(pair.val)) || math.IsInf(float64(pair.val), 0) { + return fmt.Errorf("mcp: transform2d.%s must be finite", pair.field) + } + } + entities.Set(w, e, t) + return nil +} + +func writeBuiltinObjectRef(w *entities.World, e entities.Entity, raw json.RawMessage, replace bool) error { + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 { + return errors.New("mcp: empty object_ref value") + } + if bytes.Equal(trimmed, []byte("null")) { + return errors.New(`mcp: cannot set "object_ref" to null; use game_component_remove to remove a component`) + } + var ref sceneformat.ObjectRef + if !replace { + if cur, ok := entities.Get[sceneformat.ObjectRef](w, e); ok { + ref = *cur + } + } + if err := decodeStrictValue(trimmed, &ref); err != nil { + return fmt.Errorf("mcp: set component %q on %s: %w", "object_ref", FormatEntityRef(e), err) + } + entities.Set(w, e, ref) + return nil +} + +func decodeTypedComponent[T any](w *entities.World, e entities.Entity, name string, raw json.RawMessage, replace bool) (T, error) { + var v T + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 { + return v, errors.New("empty JSON value") + } + if bytes.Equal(trimmed, []byte("null")) { + rt := reflect.TypeFor[T]() + switch rt.Kind() { + case reflect.Pointer, reflect.Slice, reflect.Map, reflect.Interface: + return v, nil + default: + return v, fmt.Errorf("cannot set non-nullable component %q to null; use game_component_remove to remove a component", name) + } + } + if !replace { + if cur, ok := entities.Get[T](w, e); ok { + // Prefer an isolated JSON copy so a partial decode error never mutates *cur's maps or slices; + // fall back to a shallow copy when *cur contains non-JSON fields (such as callbacks or NaN being repaired). + if curJSON, err := json.Marshal(*cur); err == nil { + if err := json.Unmarshal(curJSON, &v); err != nil { + v = *cur + } + } else { + v = *cur + } + } + } + if err := decodeStrictValue(trimmed, &v); err != nil { + return v, err + } + if err := validateFiniteValue(reflect.ValueOf(v), 0, make(map[visitKey]bool)); err != nil { + return v, err + } + return v, nil +} + +func decodeStrictValue(trimmed []byte, dst any) error { + dec := json.NewDecoder(bytes.NewReader(trimmed)) + dec.DisallowUnknownFields() + if err := dec.Decode(dst); err != nil { + return err + } + var extra any + if err := dec.Decode(&extra); err != io.EOF { + return errors.New("unexpected trailing data") + } + return nil +} + +func validateFloat32Arg(field string, v float64) error { + if math.IsNaN(v) || math.IsInf(v, 0) || math.Abs(v) > math.MaxFloat32 { + return fmt.Errorf("mcp: %s must be a finite float32", field) + } + return nil +} + +func validateFiniteValue(rv reflect.Value, depth int, seen map[visitKey]bool) error { + if !rv.IsValid() || depth >= maxEncodeDepth { + return nil + } + switch rv.Kind() { + case reflect.Float32, reflect.Float64: + f := rv.Float() + if math.IsNaN(f) || math.IsInf(f, 0) { + return errors.New("non-finite float value (NaN or Inf)") + } + case reflect.Interface: + if !rv.IsNil() { + return validateFiniteValue(rv.Elem(), depth+1, seen) + } + case reflect.Pointer: + if rv.IsNil() { + return nil + } + key := visitKey{ptr: rv.Pointer(), typ: rv.Type()} + if seen[key] { + return nil + } + seen[key] = true + defer delete(seen, key) + return validateFiniteValue(rv.Elem(), depth+1, seen) + case reflect.Slice: + if rv.IsNil() || rv.Len() == 0 { + return nil + } + key := visitKey{ptr: rv.Pointer(), typ: rv.Type()} + if seen[key] { + return nil + } + seen[key] = true + defer delete(seen, key) + for i := range rv.Len() { + if err := validateFiniteValue(rv.Index(i), depth+1, seen); err != nil { + return err + } + } + case reflect.Array: + for i := range rv.Len() { + if err := validateFiniteValue(rv.Index(i), depth+1, seen); err != nil { + return err + } + } + case reflect.Map: + if rv.IsNil() { + return nil + } + key := visitKey{ptr: rv.Pointer(), typ: rv.Type()} + if seen[key] { + return nil + } + seen[key] = true + defer delete(seen, key) + iter := rv.MapRange() + for iter.Next() { + if err := validateFiniteValue(iter.Value(), depth+1, seen); err != nil { + return err + } + } + case reflect.Struct: + rt := rv.Type() + for i := range rt.NumField() { + if !rt.Field(i).IsExported() { + continue + } + if err := validateFiniteValue(rv.Field(i), depth+1, seen); err != nil { + return err + } + } + } + return nil +} diff --git a/packages/game/mcp/edit_test.go b/packages/game/mcp/edit_test.go new file mode 100644 index 00000000..79a90ca3 --- /dev/null +++ b/packages/game/mcp/edit_test.go @@ -0,0 +1,752 @@ +package mcp_test + +import ( + "encoding/json" + "errors" + "math" + "strings" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game/entities" + "github.com/nsgo-dev/game/packages/game/mcp" + "github.com/nsgo-dev/game/packages/game/sceneformat" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +type armorComp struct { + Points int `json:"points"` + Kind string `json:"kind,omitempty"` + Mods map[string]int `json:"mods,omitempty"` +} + +type nanFloatComp struct { + V float64 +} + +func (n *nanFloatComp) UnmarshalJSON(data []byte) error { + var s string + if err := json.Unmarshal(data, &s); err == nil && s == "make_nan" { + n.V = math.NaN() + return nil + } + var f float64 + if err := json.Unmarshal(data, &f); err != nil { + return err + } + n.V = f + return nil +} + +// TestSpawnEditStepAndDestroyLifecycle exercises the full MCP mutation workflow: +// listing prefabs, spawning prefabs (custom, entities.Prefab, sceneformat.SceneDoc, and empty), +// editing components so changes take effect on the very next simulation step, removing components, +// and destroying entities with every hierarchy policy. +func TestSpawnEditStepAndDestroyLifecycle(t *testing.T) { + w := entities.NewWorld() + if err := entities.RegisterCodec[posComp](w, "position"); err != nil { + t.Fatal(err) + } + if err := entities.RegisterCodec[velComp](w, "velocity"); err != nil { + t.Fatal(err) + } + if err := entities.RegisterCodec[healthComp](w, "health"); err != nil { + t.Fatal(err) + } + h := w.Hierarchy2D() + + names := make(map[entities.Entity]string) + tags := make(map[entities.Entity][]string) + + // Entity prefab template using game/entities.Prefab. + coinPrefab := entities.With( + entities.With(entities.NewPrefab("coin"), posComp{X: 0, Y: 0}), + velComp{VX: 0, VY: 0}, + ) + + // Scene prefab template using game/sceneformat.SceneDoc with a parent-child subtree. + turretDoc := &sceneformat.SceneDoc{ + Version: sceneformat.CurrentVersion, + Name: "turret_prefab", + Layers: []sceneformat.LayerDoc{ + { + Name: "actors", + Objects: []sceneformat.ObjectDoc{ + { + ID: "turret_base", + X: 10, + Y: 20, + Children: []sceneformat.ObjectDoc{ + {ID: "turret_barrel", X: 5, Y: 0}, + }, + }, + }, + }, + }, + } + + stepSim := func(dt time.Duration) { + sec := float32(dt.Seconds()) + entities.Each2(w, func(e entities.Entity, p *posComp, v *velComp) bool { + p.X += v.VX * sec + p.Y += v.VY * sec + if entities.Has[entities.Transform2D](w, e) { + h.SetPosition(e, p.X, p.Y) + } + return true + }) + h.Sync() + } + + var ( + cx *core.Scope + bridge *mcp.Bridge + err error + ) + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + w.Attach(cx) + bridge = mcp.New(mcp.Config{ + World: w, + EntityName: func(e entities.Entity) string { return names[e] }, + EntityTags: func(e entities.Entity) []string { return tags[e] }, + Prefabs: map[string]mcp.PrefabSpawner{ + "slime": func(world *entities.World, overrides map[string]any) (entities.Entity, error) { + hp := 10 + if rawHP, ok := overrides["hp"]; ok { + f, ok := rawHP.(float64) + if !ok { + return entities.Zero, errors.New("slime hp override must be a number") + } + hp = int(f) + } + e := world.Spawn() + entities.Set(world, e, posComp{X: 0, Y: 0}) + entities.Set(world, e, velComp{VX: 10, VY: 0}) + entities.Set(world, e, healthComp{HP: hp, Max: hp}) + entities.Set(world, e, entities.NewTransform2D(0, 0)) + names[e] = "slime" + tags[e] = []string{"enemy"} + return e, nil + }, + }, + }) + if err = bridge.RegisterEntityPrefab(coinPrefab); err != nil { + return core.View{} + } + if err = bridge.RegisterScenePrefab("turret", turretDoc); err != nil { + return core.View{} + } + if err = mcp.RegisterMutableComponent[armorComp](bridge, "armor"); err != nil { + return core.View{} + } + if err = mcp.RegisterComponentEditor[healthComp](bridge, "health", func(world *entities.World, e entities.Entity, v healthComp) error { + if v.HP < 0 { + return errors.New("hp cannot be negative") + } + if v.Max > 0 && v.HP > v.Max { + v.HP = v.Max + } + entities.Set(world, e, v) + return nil + }); err != nil { + return core.View{} + } + err = bridge.Attach(cx) + return core.View{} + }) + if err != nil { + t.Fatalf("setup failed: %v", err) + } + + // 1. Agent lists registered prefabs in deterministic sorted order. + prefabsRes := callTool[mcp.PrefabsListResult](t, app, cx, mcp.ToolPrefabsList, nil) + if len(prefabsRes.Prefabs) != 3 { + t.Fatalf("prefabs = %+v, want 3", prefabsRes) + } + wantPrefabs := []mcp.PrefabInfo{ + {Name: "coin", Kind: "entity_prefab"}, + {Name: "slime", Kind: "custom"}, + {Name: "turret", Kind: "scene"}, + } + for i, want := range wantPrefabs { + if prefabsRes.Prefabs[i] != want { + t.Fatalf("prefabs[%d] = %+v, want %+v", i, prefabsRes.Prefabs[i], want) + } + } + + // 2. Spawn custom prefab "slime" with overrides, x/y position, and component patches. + slimeSpawn := callTool[mcp.EntitySpawnResult](t, app, cx, mcp.ToolEntitySpawn, map[string]any{ + "prefab": "slime", + "overrides": map[string]any{"hp": 25}, + "x": 40, + "y": 60, + "components": map[string]any{ + "position": map[string]any{"x": 40, "y": 60}, + "armor": map[string]any{"points": 5, "kind": "gel", "mods": map[string]int{"cold": 2}}, + }, + }) + if slimeSpawn.Ref == "" || slimeSpawn.Prefab != "slime" || slimeSpawn.Name != "slime" { + t.Fatalf("slime spawn = %+v", slimeSpawn) + } + var spawnXform entities.Transform2D + if err := json.Unmarshal(slimeSpawn.Components["transform2d"], &spawnXform); err != nil { + t.Fatal(err) + } + if spawnXform.X != 40 || spawnXform.Y != 60 || spawnXform.ScaleX != 1 || spawnXform.ScaleY != 1 { + t.Fatalf("slime transform2d = %+v, want (40,60) scale (1,1)", spawnXform) + } + var spawnHP healthComp + if err := json.Unmarshal(slimeSpawn.Components["health"], &spawnHP); err != nil { + t.Fatal(err) + } + if spawnHP.HP != 25 || spawnHP.Max != 25 { + t.Fatalf("slime health = %+v, want 25/25", spawnHP) + } + + // Spawned entity is immediately visible in game_entities_list and game_entity_inspect. + listed := callTool[mcp.EntitiesListResult](t, app, cx, mcp.ToolEntitiesList, map[string]any{"name": "slime"}) + if listed.Total != 1 || listed.Entities[0].Ref != slimeSpawn.Ref { + t.Fatalf("entities list after spawn = %+v", listed) + } + inspected := callTool[mcp.EntityInspectResult](t, app, cx, mcp.ToolEntityInspect, map[string]any{"ref": slimeSpawn.Ref}) + if inspected.Ref != slimeSpawn.Ref || len(inspected.Components) < 5 { + t.Fatalf("inspect spawned slime = %+v", inspected) + } + + // 3. Edit velocity and armor (patch mode) and verify the edit takes effect on the VERY NEXT step! + velSet := callTool[mcp.ComponentSetResult](t, app, cx, mcp.ToolComponentSet, map[string]any{ + "ref": slimeSpawn.Ref, + "component": "velocity", + "value": map[string]any{"vx": 120}, // vy omitted -> preserved (0) + }) + var gotVel velComp + if err := json.Unmarshal(velSet.Value, &gotVel); err != nil { + t.Fatal(err) + } + if gotVel.VX != 120 || gotVel.VY != 0 { + t.Fatalf("set velocity = %+v, want (120, 0)", gotVel) + } + + // Patch armor: update points only, keeping kind="gel" and mods. + armorSet := callTool[mcp.ComponentSetResult](t, app, cx, mcp.ToolComponentSet, map[string]any{ + "ref": slimeSpawn.Ref, + "component": "armor", + "value": map[string]any{"points": 9}, + }) + var gotArmor armorComp + if err := json.Unmarshal(armorSet.Value, &gotArmor); err != nil { + t.Fatal(err) + } + if gotArmor.Points != 9 || gotArmor.Kind != "gel" || gotArmor.Mods["cold"] != 2 { + t.Fatalf("patched armor = %+v, want points=9 kind=gel mods={cold:2}", gotArmor) + } + + // Replace armor completely (replace=true resets omitted fields). + armorReplace := callTool[mcp.ComponentSetResult](t, app, cx, mcp.ToolComponentSet, map[string]any{ + "ref": slimeSpawn.Ref, + "component": "armor", + "value": map[string]any{"points": 3}, + "replace": true, + }) + gotArmor = armorComp{} + if err := json.Unmarshal(armorReplace.Value, &gotArmor); err != nil { + t.Fatal(err) + } + if gotArmor.Points != 3 || gotArmor.Kind != "" || len(gotArmor.Mods) != 0 { + t.Fatalf("replaced armor = %+v, want points=3 empty kind/mods", gotArmor) + } + + // Custom RegisterComponentEditor clamps HP to Max and rejects negative HP. + clampedHP := callTool[mcp.ComponentSetResult](t, app, cx, mcp.ToolComponentSet, map[string]any{ + "ref": slimeSpawn.Ref, + "component": "health", + "value": map[string]any{"hp": 999}, + }) + var gotHP healthComp + if err := json.Unmarshal(clampedHP.Value, &gotHP); err != nil { + t.Fatal(err) + } + if gotHP.HP != 25 || gotHP.Max != 25 { + t.Fatalf("clamped health = %+v, want 25/25", gotHP) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolComponentSet, map[string]any{ + "ref": slimeSpawn.Ref, + "component": "health", + "value": map[string]any{"hp": -5}, + }); err == nil || !strings.Contains(err.Error(), "negative") { + t.Fatalf("negative hp = %v, want editor error", err) + } + + // Advance ONE simulation step (0.5s) and verify edited velocity took effect! + app.Post(func() { stepSim(500 * time.Millisecond) }) + app.Settle() + + posAfter := callTool[mcp.ComponentGetResult](t, app, cx, mcp.ToolComponentGet, map[string]any{ + "ref": slimeSpawn.Ref, + "component": "position", + }) + var gotPos posComp + if err := json.Unmarshal(posAfter.Value, &gotPos); err != nil { + t.Fatal(err) + } + if math.Abs(float64(gotPos.X-100)) > 0.01 || gotPos.Y != 60 { + t.Fatalf("position after 1 step at vx=120 = %+v, want (100, 60)", gotPos) + } + + // 4. Spawn sceneformat prefab "turret" (root + child) at (100, 50) and verify Hierarchy2D propagation! + turretSpawn := callTool[mcp.EntitySpawnResult](t, app, cx, mcp.ToolEntitySpawn, map[string]any{ + "prefab": "turret", + "x": 100, + "y": 50, + }) + if turretSpawn.Name != "turret_base" || turretSpawn.Layer != "actors" || len(turretSpawn.Children) != 1 { + t.Fatalf("turret spawn = %+v", turretSpawn) + } + barrelRef := turretSpawn.Children[0] + app.Post(func() { stepSim(time.Second / 60) }) + app.Settle() + + barrelWT := callTool[mcp.ComponentGetResult](t, app, cx, mcp.ToolComponentGet, map[string]any{ + "ref": barrelRef, + "component": "world_transform2d", + }) + var wt entities.WorldTransform2D + if err := json.Unmarshal(barrelWT.Value, &wt); err != nil { + t.Fatal(err) + } + if wt.X != 105 || wt.Y != 50 { + t.Fatalf("barrel world transform = (%v, %v), want (105, 50)", wt.X, wt.Y) + } + + // Edit turret root's built-in transform2d via game_component_set -> child's world transform updates next step! + _ = callTool[mcp.ComponentSetResult](t, app, cx, mcp.ToolComponentSet, map[string]any{ + "ref": turretSpawn.Ref, + "component": "transform2d", + "value": map[string]any{"x": 200, "y": 80}, + }) + app.Post(func() { stepSim(time.Second / 60) }) + app.Settle() + + barrelWT2 := callTool[mcp.ComponentGetResult](t, app, cx, mcp.ToolComponentGet, map[string]any{ + "ref": barrelRef, + "component": "world_transform2d", + }) + if err := json.Unmarshal(barrelWT2.Value, &wt); err != nil { + t.Fatal(err) + } + if wt.X != 205 || wt.Y != 80 { + t.Fatalf("barrel world transform after parent edit = (%v, %v), want (205, 80)", wt.X, wt.Y) + } + + // 5. Spawn entity prefab "coin" parented under turret root, and an empty entity. + coinSpawn := callTool[mcp.EntitySpawnResult](t, app, cx, mcp.ToolEntitySpawn, map[string]any{ + "prefab": "coin", + "parent": turretSpawn.Ref, + "x": 2, + "y": 3, + }) + if coinSpawn.Parent != turretSpawn.Ref { + t.Fatalf("coin parent = %q, want %q", coinSpawn.Parent, turretSpawn.Ref) + } + emptySpawn := callTool[mcp.EntitySpawnResult](t, app, cx, mcp.ToolEntitySpawn, map[string]any{ + "x": 7, + "y": 8, + "components": map[string]any{ + "object_ref": map[string]any{"ID": "marker_1", "Layer": "ui"}, + }, + }) + if emptySpawn.Name != "marker_1" || emptySpawn.Layer != "ui" { + t.Fatalf("empty spawn with object_ref = %+v", emptySpawn) + } + + // 6. Remove components (bridge-registered, codec, built-in) and verify idempotency. + remArmor := callTool[mcp.ComponentRemoveResult](t, app, cx, mcp.ToolComponentRemove, map[string]any{ + "ref": slimeSpawn.Ref, + "component": "armor", + }) + if !remArmor.Removed { + t.Fatalf("remove armor = %+v, want removed=true", remArmor) + } + remArmorAgain := callTool[mcp.ComponentRemoveResult](t, app, cx, mcp.ToolComponentRemove, map[string]any{ + "ref": slimeSpawn.Ref, + "component": "armor", + }) + if remArmorAgain.Removed { + t.Fatalf("second remove armor = %+v, want removed=false", remArmorAgain) + } + remVel := callTool[mcp.ComponentRemoveResult](t, app, cx, mcp.ToolComponentRemove, map[string]any{ + "ref": slimeSpawn.Ref, + "component": "velocity", + }) + if !remVel.Removed { + t.Fatalf("remove velocity = %+v, want removed=true", remVel) + } + remXform := callTool[mcp.ComponentRemoveResult](t, app, cx, mcp.ToolComponentRemove, map[string]any{ + "ref": emptySpawn.Ref, + "component": "transform2d", + }) + if !remXform.Removed { + t.Fatalf("remove transform2d = %+v, want removed=true", remXform) + } + + // 7. Destroy policies: cascade, orphan, keep_world, reparent! + // 7a. Cascade on turret destroys turret + barrel + coin (3 entities). + cascRes := callTool[mcp.EntityDestroyResult](t, app, cx, mcp.ToolEntityDestroy, map[string]any{ + "ref": turretSpawn.Ref, + "policy": "cascade", + }) + if cascRes.Destroyed != 3 || cascRes.Policy != "cascade" { + t.Fatalf("cascade destroy = %+v, want destroyed=3", cascRes) + } + // Stale refs for parent and child must fail cleanly on inspect/edit/destroy. + for _, stale := range []string{turretSpawn.Ref, barrelRef, coinSpawn.Ref} { + if _, err := callToolRaw(t, app, cx, mcp.ToolEntityInspect, map[string]any{"ref": stale}); err == nil || !strings.Contains(err.Error(), "not alive") { + t.Fatalf("inspect stale %s = %v, want not alive", stale, err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolComponentSet, map[string]any{"ref": stale, "component": "position", "value": map[string]any{"x": 1}}); err == nil || !strings.Contains(err.Error(), "not alive") { + t.Fatalf("set stale %s = %v, want not alive", stale, err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolEntityDestroy, map[string]any{"ref": stale}); err == nil || !strings.Contains(err.Error(), "not alive") { + t.Fatalf("destroy stale %s = %v, want not alive", stale, err) + } + } + + // 7b. Reparent policy: grandparent -> mid -> leaf; destroy mid with reparent -> leaf becomes child of grandparent. + gp := callTool[mcp.EntitySpawnResult](t, app, cx, mcp.ToolEntitySpawn, map[string]any{"x": 10, "y": 10}) + mid := callTool[mcp.EntitySpawnResult](t, app, cx, mcp.ToolEntitySpawn, map[string]any{"parent": gp.Ref, "x": 20, "y": 0}) + leaf := callTool[mcp.EntitySpawnResult](t, app, cx, mcp.ToolEntitySpawn, map[string]any{"parent": mid.Ref, "x": 5, "y": 0}) + repRes := callTool[mcp.EntityDestroyResult](t, app, cx, mcp.ToolEntityDestroy, map[string]any{ + "ref": mid.Ref, + "policy": "reparent", + }) + if repRes.Destroyed != 1 || repRes.Policy != "reparent" { + t.Fatalf("reparent destroy = %+v", repRes) + } + leafAfterReparent := callTool[mcp.EntityInspectResult](t, app, cx, mcp.ToolEntityInspect, map[string]any{"ref": leaf.Ref}) + if leafAfterReparent.Parent != gp.Ref { + t.Fatalf("leaf parent after reparent = %q, want %q", leafAfterReparent.Parent, gp.Ref) + } + + // 7c. keep_world policy: sync transforms, destroy gp with keep_world -> leaf becomes root with local X = 10 + 5 = 15. + app.Post(func() { h.Sync() }) + app.Settle() + kwRes := callTool[mcp.EntityDestroyResult](t, app, cx, mcp.ToolEntityDestroy, map[string]any{ + "ref": gp.Ref, + "policy": "keep_world", + }) + if kwRes.Destroyed != 1 || kwRes.Policy != "keep_world" { + t.Fatalf("keep_world destroy = %+v", kwRes) + } + leafAfterKW := callTool[mcp.EntityInspectResult](t, app, cx, mcp.ToolEntityInspect, map[string]any{"ref": leaf.Ref}) + if leafAfterKW.Parent != "" { + t.Fatalf("leaf parent after keep_world = %q, want root", leafAfterKW.Parent) + } + var leafXform entities.Transform2D + if err := json.Unmarshal(leafAfterKW.Components["transform2d"], &leafXform); err != nil { + t.Fatal(err) + } + if leafXform.X != 15 || leafXform.Y != 10 { + t.Fatalf("leaf local transform after keep_world = (%v, %v), want (15, 10)", leafXform.X, leafXform.Y) + } + + // 7d. orphan policy: parent -> child; destroy parent with orphan -> child becomes root keeping local transform (3, 4). + pOrph := callTool[mcp.EntitySpawnResult](t, app, cx, mcp.ToolEntitySpawn, map[string]any{"x": 100, "y": 100}) + cOrph := callTool[mcp.EntitySpawnResult](t, app, cx, mcp.ToolEntitySpawn, map[string]any{"parent": pOrph.Ref, "x": 3, "y": 4}) + orphRes := callTool[mcp.EntityDestroyResult](t, app, cx, mcp.ToolEntityDestroy, map[string]any{ + "ref": pOrph.Ref, + "policy": "orphan", + }) + if orphRes.Destroyed != 1 || orphRes.Policy != "orphan" { + t.Fatalf("orphan destroy = %+v", orphRes) + } + cAfterOrph := callTool[mcp.EntityInspectResult](t, app, cx, mcp.ToolEntityInspect, map[string]any{"ref": cOrph.Ref}) + if cAfterOrph.Parent != "" { + t.Fatalf("child parent after orphan = %q, want root", cAfterOrph.Parent) + } + if err := json.Unmarshal(cAfterOrph.Components["transform2d"], &leafXform); err != nil { + t.Fatal(err) + } + if leafXform.X != 3 || leafXform.Y != 4 { + t.Fatalf("child local transform after orphan = (%v, %v), want (3, 4)", leafXform.X, leafXform.Y) + } + + // 7e. Default destroy on leaf and verify recycled slot rejects old ref. + defRes := callTool[mcp.EntityDestroyResult](t, app, cx, mcp.ToolEntityDestroy, map[string]any{"ref": leaf.Ref}) + if defRes.Destroyed != 1 || defRes.Policy != "default" { + t.Fatalf("default destroy = %+v", defRes) + } + reused := callTool[mcp.EntitySpawnResult](t, app, cx, mcp.ToolEntitySpawn, nil) + if reused.Ref == leaf.Ref { + t.Fatalf("reused ref %q must not alias destroyed ref %q", reused.Ref, leaf.Ref) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolComponentSet, map[string]any{ + "ref": leaf.Ref, + "component": "transform2d", + "value": map[string]any{"x": 1}, + }); err == nil || !strings.Contains(err.Error(), "not alive") { + t.Fatalf("edit recycled stale ref = %v, want not alive", err) + } +} + +func TestEditValidationAtomicityAndErrorCases(t *testing.T) { + var ( + cx *core.Scope + b *mcp.Bridge + ) + app := nsgotest.Start(t, func(scope *core.Scope) core.Node { + cx = scope + var err error + b, err = mcp.Attach(cx, mcp.Config{}) + if err != nil { + t.Fatal(err) + } + return core.View{} + }) + + // Nil world errors across all mutation tools (no panic). + if _, err := callToolRaw(t, app, cx, mcp.ToolEntitySpawn, nil); err == nil || !strings.Contains(err.Error(), "no entity world") { + t.Fatalf("spawn with nil world = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolEntityDestroy, map[string]any{"ref": "entity:0:1"}); err == nil || !strings.Contains(err.Error(), "no entity world") { + t.Fatalf("destroy with nil world = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolComponentSet, map[string]any{"ref": "entity:0:1", "component": "transform2d", "value": map[string]any{"x": 1}}); err == nil || !strings.Contains(err.Error(), "no entity world") { + t.Fatalf("set with nil world = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolComponentRemove, map[string]any{"ref": "entity:0:1", "component": "transform2d"}); err == nil || !strings.Contains(err.Error(), "no entity world") { + t.Fatalf("remove with nil world = %v", err) + } + // game_prefabs_list works even with no world and returns empty slice. + emptyPrefabs := callTool[mcp.PrefabsListResult](t, app, cx, mcp.ToolPrefabsList, nil) + if len(emptyPrefabs.Prefabs) != 0 { + t.Fatalf("empty prefabs = %+v", emptyPrefabs) + } + + // Unknown argument fields rejected on every edit tool. + for _, tool := range []string{mcp.ToolPrefabsList, mcp.ToolEntitySpawn, mcp.ToolEntityDestroy, mcp.ToolComponentSet, mcp.ToolComponentRemove} { + if _, err := callToolRaw(t, app, cx, tool, `{"bogus":1}`); err == nil || !strings.Contains(err.Error(), "unknown field") { + t.Fatalf("%s unknown arg = %v, want unknown field", tool, err) + } + } + + // Wire up a live world and test validation & atomicity. + w := entities.NewWorld() + if err := entities.RegisterCodec[healthComp](w, "health"); err != nil { + t.Fatal(err) + } + b.SetWorld(w) + if err := mcp.RegisterComponent[posComp](b, "readonly_pos"); err != nil { + t.Fatal(err) + } + if err := mcp.RegisterMutableComponent[armorComp](b, "armor"); err != nil { + t.Fatal(err) + } + if err := mcp.RegisterMutableComponent[nanFloatComp](b, "nan_float"); err != nil { + t.Fatal(err) + } + if err := b.RegisterEntityPrefab(entities.With(entities.NewPrefab("crate"), healthComp{HP: 5, Max: 5})); err != nil { + t.Fatal(err) + } + if err := b.RegisterPrefab("bad_spawner", func(*entities.World, map[string]any) (entities.Entity, error) { + return entities.Zero, nil + }); err != nil { + t.Fatal(err) + } + + // Spawn rollback: invalid component or unknown field must NOT leak an entity into w! + before := w.Count() + if _, err := callToolRaw(t, app, cx, mcp.ToolEntitySpawn, map[string]any{ + "prefab": "crate", + "components": map[string]any{ + "health": map[string]any{"hp": 1, "unknown_field": 2}, + }, + }); err == nil || !strings.Contains(err.Error(), "unknown field") { + t.Fatalf("spawn with unknown component field = %v", err) + } + if w.Count() != before { + t.Fatalf("failed spawn leaked entity: count=%d, want %d", w.Count(), before) + } + + // Unregistered prefab, overrides without prefab, overrides on entity prefab, dead parent, overflow x, bad spawner. + if _, err := callToolRaw(t, app, cx, mcp.ToolEntitySpawn, map[string]any{"prefab": "ghost"}); err == nil || !strings.Contains(err.Error(), "unknown prefab") { + t.Fatalf("unknown prefab = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolEntitySpawn, map[string]any{"overrides": map[string]any{"a": 1}}); err == nil || !strings.Contains(err.Error(), "overrides require a prefab") { + t.Fatalf("overrides without prefab = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolEntitySpawn, map[string]any{"prefab": "crate", "overrides": map[string]any{"a": 1}}); err == nil || !strings.Contains(err.Error(), "does not accept overrides") { + t.Fatalf("overrides on entity prefab = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolEntitySpawn, map[string]any{"parent": "entity:99:1"}); err == nil || !strings.Contains(err.Error(), "not alive") { + t.Fatalf("dead parent = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolEntitySpawn, map[string]any{"x": 1e300}); err == nil || !strings.Contains(err.Error(), "finite float32") { + t.Fatalf("overflow x = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolEntitySpawn, map[string]any{"prefab": "bad_spawner"}); err == nil || !strings.Contains(err.Error(), "non-live") { + t.Fatalf("bad spawner = %v", err) + } + if w.Count() != before { + t.Fatalf("error spawns leaked entities: count=%d, want %d", w.Count(), before) + } + + // Spawn a valid entity to test component set/remove/destroy errors. + ent := callTool[mcp.EntitySpawnResult](t, app, cx, mcp.ToolEntitySpawn, map[string]any{ + "components": map[string]any{ + "armor": map[string]any{"points": 4, "mods": map[string]int{"acid": 1}}, + }, + }) + + // Failed patch on armor must leave existing map untouched. + if _, err := callToolRaw(t, app, cx, mcp.ToolComponentSet, map[string]any{ + "ref": ent.Ref, + "component": "armor", + "value": map[string]any{"mods": map[string]int{"poison": 9}, "nope": 1}, + }); err == nil || !strings.Contains(err.Error(), "unknown field") { + t.Fatalf("unknown field on mutable component = %v", err) + } + gotArmorRes := callTool[mcp.ComponentGetResult](t, app, cx, mcp.ToolComponentGet, map[string]any{ + "ref": ent.Ref, + "component": "armor", + }) + var gotArmor armorComp + if err := json.Unmarshal(gotArmorRes.Value, &gotArmor); err != nil { + t.Fatal(err) + } + if _, leaked := gotArmor.Mods["poison"]; leaked || gotArmor.Mods["acid"] != 1 { + t.Fatalf("failed patch corrupted armor map: %+v", gotArmor.Mods) + } + + // Reject NaN produced by custom unmarshaler, overflowing float32 in transform2d, null for struct, read-only & derived components, unknown component, missing required args, invalid policy. + if _, err := callToolRaw(t, app, cx, mcp.ToolComponentSet, map[string]any{ + "ref": ent.Ref, + "component": "nan_float", + "value": "make_nan", + }); err == nil || !strings.Contains(err.Error(), "non-finite") { + t.Fatalf("nan float = %v, want non-finite error", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolComponentSet, map[string]any{ + "ref": ent.Ref, + "component": "transform2d", + "value": map[string]any{"x": 1e300}, + }); err == nil { + t.Fatal("expected error for float32 overflow in transform2d") + } + if _, err := callToolRaw(t, app, cx, mcp.ToolComponentSet, map[string]any{ + "ref": ent.Ref, + "component": "transform2d", + "value": nil, + }); err == nil || !strings.Contains(err.Error(), "null") { + t.Fatalf("null transform2d = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolComponentSet, map[string]any{ + "ref": ent.Ref, + "component": "world_transform2d", + "value": map[string]any{"X": 1}, + }); err == nil || !strings.Contains(err.Error(), "read-only") { + t.Fatalf("edit world_transform2d = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolComponentRemove, map[string]any{ + "ref": ent.Ref, + "component": "world_transform2d", + }); err == nil || !strings.Contains(err.Error(), "read-only") { + t.Fatalf("remove world_transform2d = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolComponentSet, map[string]any{ + "ref": ent.Ref, + "component": "readonly_pos", + "value": map[string]any{"x": 1}, + }); err == nil || !strings.Contains(err.Error(), "read-only") { + t.Fatalf("edit readonly component = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolComponentRemove, map[string]any{ + "ref": ent.Ref, + "component": "readonly_pos", + }); err == nil || !strings.Contains(err.Error(), "read-only") { + t.Fatalf("remove readonly component = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolComponentSet, map[string]any{ + "ref": ent.Ref, + "component": "no_such_comp", + "value": map[string]any{}, + }); err == nil || !strings.Contains(err.Error(), "unknown component") { + t.Fatalf("unknown component = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolComponentSet, map[string]any{ + "ref": ent.Ref, + "component": "health", + }); err == nil || !strings.Contains(err.Error(), "value is required") { + t.Fatalf("missing value = %v", err) + } + if _, err := callToolRaw(t, app, cx, mcp.ToolEntityDestroy, map[string]any{ + "ref": ent.Ref, + "policy": "explode", + }); err == nil || !strings.Contains(err.Error(), "invalid destroy policy") { + t.Fatalf("invalid policy = %v", err) + } + + // Upgrading a read-only RegisterComponent[posComp] via RegisterComponentEditor[posComp] works, + // while a mismatched type or duplicate editor is rejected! + if err := mcp.RegisterComponentEditor[velComp](b, "readonly_pos", func(*entities.World, entities.Entity, velComp) error { return nil }); !errors.Is(err, mcp.ErrDuplicateComponent) { + t.Fatalf("mismatched editor type = %v, want ErrDuplicateComponent", err) + } + if err := mcp.RegisterComponentEditor[posComp](b, "readonly_pos", func(world *entities.World, e entities.Entity, v posComp) error { + entities.Set(world, e, v) + return nil + }); err != nil { + t.Fatalf("upgrade readonly_pos to editable = %v", err) + } + if err := mcp.RegisterComponentEditor[posComp](b, "readonly_pos", func(*entities.World, entities.Entity, posComp) error { return nil }); !errors.Is(err, mcp.ErrDuplicateComponent) { + t.Fatalf("duplicate editor = %v, want ErrDuplicateComponent", err) + } + posSet := callTool[mcp.ComponentSetResult](t, app, cx, mcp.ToolComponentSet, map[string]any{ + "ref": ent.Ref, + "component": "readonly_pos", + "value": map[string]any{"x": 12, "y": 34}, + }) + var gotPos posComp + if err := json.Unmarshal(posSet.Value, &gotPos); err != nil { + t.Fatal(err) + } + if gotPos.X != 12 || gotPos.Y != 34 { + t.Fatalf("upgraded readonly_pos = %+v, want (12, 34)", gotPos) + } + + // Registration validation errors. + var nilBridge *mcp.Bridge + if err := nilBridge.RegisterPrefab("a", func(*entities.World, map[string]any) (entities.Entity, error) { return entities.Zero, nil }); !errors.Is(err, mcp.ErrNilBridge) { + t.Fatalf("nil bridge RegisterPrefab = %v", err) + } + if err := b.RegisterPrefab("", func(*entities.World, map[string]any) (entities.Entity, error) { return entities.Zero, nil }); !errors.Is(err, mcp.ErrEmptyPrefabName) { + t.Fatalf("empty RegisterPrefab = %v", err) + } + if err := b.RegisterPrefab("x", nil); err == nil { + t.Fatal("expected error for nil prefab spawner") + } + if err := b.RegisterPrefab("crate", func(*entities.World, map[string]any) (entities.Entity, error) { return entities.Zero, nil }); !errors.Is(err, mcp.ErrDuplicatePrefab) { + t.Fatalf("dup prefab = %v, want ErrDuplicatePrefab", err) + } + if err := b.RegisterEntityPrefab(nil); err == nil { + t.Fatal("expected error for nil entity prefab") + } + if err := b.RegisterEntityPrefab(entities.NewPrefab("")); !errors.Is(err, mcp.ErrEmptyPrefabName) { + t.Fatalf("empty entity prefab = %v", err) + } + if err := b.RegisterScenePrefab("empty_scene", &sceneformat.SceneDoc{Version: sceneformat.CurrentVersion, Name: "empty"}); err == nil { + t.Fatal("expected error for scene prefab with no objects") + } + if err := mcp.RegisterMutableComponent[posComp](nil, "p"); !errors.Is(err, mcp.ErrNilBridge) { + t.Fatalf("nil bridge RegisterMutableComponent = %v", err) + } + if err := mcp.RegisterComponentEditor[posComp](b, "e", nil); err == nil { + t.Fatal("expected error for nil editor func") + } + + // Disposed world error on mutation tools. + w.Dispose() + if _, err := callToolRaw(t, app, cx, mcp.ToolEntitySpawn, nil); err == nil || !strings.Contains(err.Error(), "disposed") { + t.Fatalf("spawn on disposed world = %v", err) + } +} diff --git a/packages/game/mcp/example_test.go b/packages/game/mcp/example_test.go index 93f7f756..6eb7719c 100644 --- a/packages/game/mcp/example_test.go +++ b/packages/game/mcp/example_test.go @@ -55,4 +55,9 @@ func ExampleNew() { // game_tunable_set // game_console_commands_list // game_console_exec + // game_prefabs_list + // game_entity_spawn + // game_entity_destroy + // game_component_set + // game_component_remove } diff --git a/packages/game/mcp/mcp.go b/packages/game/mcp/mcp.go index 057e0abb..8f030331 100644 --- a/packages/game/mcp/mcp.go +++ b/packages/game/mcp/mcp.go @@ -120,6 +120,9 @@ type Config struct { // ConsoleFunc dynamically resolves the active debug console on each tool call. When non-nil and returning a non-nil console, it overrides Console. ConsoleFunc func() *debug.Console + + // 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 } type compTypeKey any @@ -135,11 +138,13 @@ type componentEntry struct { typeKey compTypeKey has func(w *entities.World, e entities.Entity) bool read func(w *entities.World, e entities.Entity) (any, bool, error) + write func(w *entities.World, e entities.Entity, raw json.RawMessage, replace bool) error + remove func(w *entities.World, e entities.Entity) (bool, error) } // Bridge exposes a running game's subsystems to nsgo mcp via automation.Register. // -// Create a Bridge with New or Attach, optionally register additional component inspectors with RegisterComponent or RegisterComponentFunc, and attach it to a core.Scope on the engine goroutine. Disposing the scope or calling Detach unregisters every tool automatically. +// Create a Bridge with New or Attach, optionally register additional component inspectors, editors or prefabs, and attach it to a core.Scope on the engine goroutine. Disposing the scope or calling Detach unregisters every tool automatically. type Bridge struct { cfg Config sub *core.Scope @@ -148,6 +153,9 @@ type Bridge struct { compOrder []string compByType map[compTypeKey]string pointerButton core.MouseButton + + prefabs map[string]prefabEntry + prefabOrder []string } // New constructs a Bridge for cfg without registering its tools yet. @@ -160,7 +168,10 @@ func New(cfg Config) *Bridge { } cfg.NamedScenes = copied } - return &Bridge{cfg: cfg} + b := &Bridge{cfg: cfg} + b.initPrefabs(cfg.Prefabs) + b.cfg.Prefabs = nil + return b } // Attach constructs a Bridge for cfg and registers its tools on cx until cx is disposed. @@ -283,6 +294,7 @@ func (b *Bridge) Tools() []automation.Tool { out = append(out, b.loopTools()...) out = append(out, b.inputTools()...) out = append(out, b.consoleTools()...) + out = append(out, b.editTools()...) return out } From 0dd26df0e14f84c5e01db3bfd7e10e1bd596ec48 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Wed, 25 Nov 2026 04:11:30 +0900 Subject: [PATCH 2/3] fix(entities): keep runtime fields on patch and refuse unencodable codec edits PatchComponent built its starting value with a JSON round trip, which zeroed unexported fields and json:"-" fields and replaced every pointee with a copy. Patches now go through internal/jsonedit, which decodes onto a clone whose exported pointers, maps, slices and interfaces are freshly allocated and then takes only the fields the patch changed, so untouched runtime state and pointer identity survive and a failed decode never reaches the live value. DecodeComponent and PatchComponent also refuse a decoded value that cannot be encoded back, such as a NaN produced by a custom UnmarshalJSON, which would otherwise break every later EncodeComponent and Snapshot of the entity. --- packages/game/entities/codec_edit_test.go | 59 +++++++ packages/game/entities/snapshot.go | 43 ++--- packages/game/formats_test.go | 1 + packages/game/internal/jsonedit/jsonedit.go | 143 +++++++++++++++ .../game/internal/jsonedit/jsonedit_test.go | 164 ++++++++++++++++++ 5 files changed, 380 insertions(+), 30 deletions(-) create mode 100644 packages/game/internal/jsonedit/jsonedit.go create mode 100644 packages/game/internal/jsonedit/jsonedit_test.go diff --git a/packages/game/entities/codec_edit_test.go b/packages/game/entities/codec_edit_test.go index 1a4d2677..18db8f0e 100644 --- a/packages/game/entities/codec_edit_test.go +++ b/packages/game/entities/codec_edit_test.go @@ -3,6 +3,7 @@ package entities_test import ( "encoding/json" "errors" + "math" "testing" "github.com/nsgo-dev/game/packages/game/entities" @@ -120,3 +121,61 @@ func TestWorldDecodePatchRemoveComponent(t *testing.T) { t.Fatalf("disposed world remove = %v, want ErrWorldDisposed", err) } } + +type codecNaN struct { + V float64 `json:"v"` +} + +func (c *codecNaN) UnmarshalJSON(data []byte) error { + var s string + if err := json.Unmarshal(data, &s); err == nil && s == "nan" { + c.V = math.NaN() + return nil + } + type plain codecNaN + return json.Unmarshal(data, (*plain)(c)) +} + +func TestWorldPatchComponentPreservesRuntimeFieldsAndRefusesUnencodable(t *testing.T) { + type handle struct{ id int } + type ai struct { + State string `json:"state"` + Mods map[string]int `json:"mods,omitempty"` + Path *handle `json:"-"` + Scratch map[string]int `json:"-"` + cache *handle + } + + w := entities.NewWorld() + if err := entities.RegisterCodec[ai](w, "ai"); err != nil { + t.Fatal(err) + } + if err := entities.RegisterCodec[codecNaN](w, "nan"); err != nil { + t.Fatal(err) + } + e := w.Spawn() + path, cache := &handle{id: 1}, &handle{id: 2} + entities.Set(w, e, ai{State: "idle", Mods: map[string]int{"a": 1}, Path: path, Scratch: map[string]int{"n": 3}, cache: cache}) + + if err := w.PatchComponent(e, "ai", json.RawMessage(`{"state":"chase"}`)); err != nil { + t.Fatalf("PatchComponent: %v", err) + } + got, _ := entities.Get[ai](w, e) + if got.State != "chase" || got.Path != path || got.cache != cache || got.Scratch["n"] != 3 || got.Mods["a"] != 1 { + t.Fatalf("patch lost runtime fields: %+v", got) + } + + entities.Set(w, e, codecNaN{V: 1}) + if err := w.PatchComponent(e, "nan", json.RawMessage(`"nan"`)); err == nil { + t.Fatal("PatchComponent stored an unencodable NaN value") + } + if err := w.DecodeComponent(e, "nan", json.RawMessage(`"nan"`)); err == nil { + t.Fatal("DecodeComponent stored an unencodable NaN value") + } + if v, _ := entities.Get[codecNaN](w, e); v.V != 1 { + t.Fatalf("refused edit changed the component: %+v", v) + } + if _, err := w.Snapshot(); err != nil { + t.Fatalf("Snapshot after refused NaN edit: %v", err) + } +} diff --git a/packages/game/entities/snapshot.go b/packages/game/entities/snapshot.go index 6129b8a1..3ef0306a 100644 --- a/packages/game/entities/snapshot.go +++ b/packages/game/entities/snapshot.go @@ -5,9 +5,9 @@ import ( "encoding/json" "errors" "fmt" - "io" "slices" + "github.com/nsgo-dev/game/packages/game/internal/jsonedit" "github.com/nsgo-dev/game/packages/game/loaderr" "github.com/nsgo-dev/game/packages/game/save" ) @@ -114,21 +114,19 @@ func RegisterCodec[T any](w *World, typeName string) error { if err != nil || !bytes.Equal(bytes.TrimSpace(zeroJSON), []byte("null")) { return errors.New("cannot decode null into non-nullable component") } - } else if patch { - if cur, ok := Get[T](w, e); ok { - // Deep-copy via JSON so a partial decode error never mutates *cur's maps or slices. - curJSON, err := json.Marshal(*cur) - if err != nil { - return err - } - if err := json.Unmarshal(curJSON, &v); err != nil { - return err - } + } else if cur, ok := Get[T](w, e); patch && ok { + patched, err := jsonedit.Patch(cur, trimmed) + if err != nil { + return err } - } - if err := decodeStrictJSON(trimmed, &v); err != nil { + v = patched + } else if err := jsonedit.DecodeStrict(trimmed, &v); err != nil { return err } + // A value the codec cannot encode, such as one holding a NaN produced by a custom UnmarshalJSON, would make every later EncodeComponent and Snapshot of e fail, so it is refused before it is stored. + if _, err := json.Marshal(v); err != nil { + return fmt.Errorf("decoded value cannot be encoded: %w", err) + } Set[T](w, e, v) return nil }, @@ -198,27 +196,12 @@ func (w *World) EncodeComponent(e Entity, typeName string) (json.RawMessage, boo return raw, present, nil } -func decodeStrictJSON(trimmed []byte, dst any) error { - dec := json.NewDecoder(bytes.NewReader(trimmed)) - dec.DisallowUnknownFields() - if err := dec.Decode(dst); err != nil { - return err - } - var extra any - if err := dec.Decode(&extra); err != io.EOF { - return errors.New("unexpected trailing data") - } - return nil -} - -// DecodeComponent strictly decodes raw JSON into the codec-registered component named typeName and attaches or replaces it on live entity e. -// Unknown JSON fields, trailing data and invalid nulls for non-nullable component types are rejected without mutating e. +// DecodeComponent strictly decodes raw JSON into the codec-registered component named typeName and attaches or replaces it on live entity e. Unknown JSON fields, trailing data, invalid nulls for non-nullable component types and values the codec cannot encode back, such as a NaN, are rejected without mutating e. func (w *World) DecodeComponent(e Entity, typeName string, raw json.RawMessage) error { return w.decodeComponentStrict(e, typeName, raw, false) } -// PatchComponent strictly decodes raw JSON into a copy of live entity e's existing codec-registered component (or its zero value when absent) and writes the result back atomically. -// Unknown JSON fields and trailing data are rejected without mutating e. +// PatchComponent strictly decodes raw JSON onto live entity e's existing codec-registered component (or its zero value when absent) and writes the result back atomically. Fields the patch does not change keep their current values, including unexported fields, fields tagged `json:"-"` and the identity of pointers, maps and slices. Unknown JSON fields, trailing data and values the codec cannot encode back, such as a NaN, are rejected without mutating e. func (w *World) PatchComponent(e Entity, typeName string, raw json.RawMessage) error { return w.decodeComponentStrict(e, typeName, raw, true) } diff --git a/packages/game/formats_test.go b/packages/game/formats_test.go index ffd6b153..0a5ee2b6 100644 --- a/packages/game/formats_test.go +++ b/packages/game/formats_test.go @@ -47,6 +47,7 @@ var notJSONFormats = map[string]string{ "accounts/token": "decodes the JSON payload of a signed token, which is data on the wire", "gameui": "marshals and unmarshals settings values inside save.Settings.Custom, the format of the save#settings entry", "idle": "decodes a Number from a JSON value inside another format", + "internal/jsonedit": "strictly decodes component edits sent through mcp tool calls, which are RPC payloads on the wire", "internal/samplegltf": "validates the sample glTF models, glTF being the gltf entry's format", "loaderr": "decodes a document only to find a field's line and column for an error", "mcp": "decodes JSON arguments and results of MCP automation tool calls, which are RPC payloads on the wire", diff --git a/packages/game/internal/jsonedit/jsonedit.go b/packages/game/internal/jsonedit/jsonedit.go new file mode 100644 index 00000000..b9e1581c --- /dev/null +++ b/packages/game/internal/jsonedit/jsonedit.go @@ -0,0 +1,143 @@ +// Package jsonedit strictly decodes JSON edits onto live Go values without touching the edited value until the edit has succeeded. +package jsonedit + +import ( + "bytes" + "encoding" + "encoding/json" + "errors" + "io" + "reflect" +) + +// maxDepth bounds the recursion of detach and merge so a value that refers to itself through interfaces or slices cannot recurse forever. +const maxDepth = 1000 + +var ( + jsonUnmarshalerType = reflect.TypeFor[json.Unmarshaler]() + textUnmarshalerType = reflect.TypeFor[encoding.TextUnmarshaler]() +) + +// DecodeStrict decodes exactly one JSON value from data into dst, refusing unknown object fields and trailing data. +func DecodeStrict(data []byte, dst any) error { + dec := json.NewDecoder(bytes.NewReader(data)) + dec.DisallowUnknownFields() + if err := dec.Decode(dst); err != nil { + return err + } + var extra any + if err := dec.Decode(&extra); err != io.EOF { + return errors.New("unexpected trailing data") + } + return nil +} + +// Patch strictly decodes data onto a copy of *cur and returns the edited value, leaving *cur and everything it refers to unchanged whether or not the decode succeeds. +// +// The decode runs on a clone of *cur whose exported pointers, maps, slices and interfaces are freshly allocated, so a decode that fails halfway cannot reach the live value. The result then starts from a plain copy of *cur and takes from the decoded clone only the exported fields the patch changed, so unexported fields, fields tagged `json:"-"` and the identity of every pointer, map and slice the patch left alone survive. A field the patch changed holds a freshly allocated value. A type that implements json.Unmarshaler or encoding.TextUnmarshaler is taken whole from the decoded clone, because its own decoding may set fields Patch cannot see. +func Patch[T any](cur *T, data []byte) (T, error) { + decoded := *cur + dv := reflect.ValueOf(&decoded).Elem() + detach(dv, make(map[visit]reflect.Value), 0) + if err := DecodeStrict(data, &decoded); err != nil { + var zero T + return zero, err + } + out := *cur + merge(reflect.ValueOf(&out).Elem(), reflect.ValueOf(cur).Elem(), dv, 0) + return out, nil +} + +type visit struct { + ptr uintptr + typ reflect.Type +} + +// detach replaces every settable pointer, map, slice and interface reachable from the addressable value v with a fresh copy, so decoding into v cannot write to memory shared with the value v was copied from. +func detach(v reflect.Value, seen map[visit]reflect.Value, depth int) { + if depth >= maxDepth { + return + } + switch v.Kind() { + case reflect.Struct: + for i := range v.NumField() { + detach(v.Field(i), seen, depth+1) + } + case reflect.Array: + for i := range v.Len() { + detach(v.Index(i), seen, depth+1) + } + case reflect.Pointer: + if v.IsNil() || !v.CanSet() { + return + } + key := visit{ptr: v.Pointer(), typ: v.Type()} + if c, ok := seen[key]; ok { + v.Set(c) + return + } + np := reflect.New(v.Type().Elem()) + seen[key] = np + np.Elem().Set(v.Elem()) + detach(np.Elem(), seen, depth+1) + v.Set(np) + case reflect.Map: + if v.IsNil() || !v.CanSet() { + return + } + key := visit{ptr: v.Pointer(), typ: v.Type()} + if c, ok := seen[key]; ok { + v.Set(c) + return + } + nm := reflect.MakeMapWithSize(v.Type(), v.Len()) + seen[key] = nm + iter := v.MapRange() + for iter.Next() { + ev := reflect.New(v.Type().Elem()).Elem() + ev.Set(iter.Value()) + detach(ev, seen, depth+1) + nm.SetMapIndex(iter.Key(), ev) + } + v.Set(nm) + case reflect.Slice: + if v.IsNil() || !v.CanSet() { + return + } + ns := reflect.MakeSlice(v.Type(), v.Len(), v.Len()) + reflect.Copy(ns, v) + for i := range ns.Len() { + detach(ns.Index(i), seen, depth+1) + } + v.Set(ns) + case reflect.Interface: + if v.IsNil() || !v.CanSet() { + return + } + inner := reflect.New(v.Elem().Type()).Elem() + inner.Set(v.Elem()) + detach(inner, seen, depth+1) + v.Set(inner) + } +} + +// merge sets each settable part of dst whose value differs between cur and decoded to the decoded value, descending into structs so unchanged sibling fields keep cur's values. +func merge(dst, cur, decoded reflect.Value, depth int) { + if dst.Kind() == reflect.Struct && depth < maxDepth && !customUnmarshaler(dst.Type()) { + for i := range dst.NumField() { + merge(dst.Field(i), cur.Field(i), decoded.Field(i), depth+1) + } + return + } + if !dst.CanSet() { + return + } + if !reflect.DeepEqual(cur.Interface(), decoded.Interface()) { + dst.Set(decoded) + } +} + +func customUnmarshaler(t reflect.Type) bool { + pt := reflect.PointerTo(t) + return t.Implements(jsonUnmarshalerType) || pt.Implements(jsonUnmarshalerType) || t.Implements(textUnmarshalerType) || pt.Implements(textUnmarshalerType) +} diff --git a/packages/game/internal/jsonedit/jsonedit_test.go b/packages/game/internal/jsonedit/jsonedit_test.go new file mode 100644 index 00000000..6306e517 --- /dev/null +++ b/packages/game/internal/jsonedit/jsonedit_test.go @@ -0,0 +1,164 @@ +package jsonedit + +import ( + "strings" + "testing" + "time" +) + +type inner struct { + A int `json:"a"` + B int `json:"b"` +} + +type cache struct { + hits int +} + +type component struct { + State string `json:"state"` + Speed float64 `json:"speed"` + Mods map[string]int `json:"mods,omitempty"` + List []int `json:"list,omitempty"` + Target *inner `json:"target,omitempty"` + Handle *cache `json:"-"` + Runtime map[string]int `json:"-"` + OnHit func() `json:"-"` + Hook func() + At time.Time `json:"at"` + Nested inner `json:"nested"` + private *cache + note string +} + +func newComponent() *component { + return &component{ + State: "idle", + Speed: 1, + Mods: map[string]int{"acid": 1}, + List: []int{1, 2, 3}, + Target: &inner{A: 1, B: 2}, + Handle: &cache{hits: 3}, + Runtime: map[string]int{"frames": 9}, + OnHit: func() {}, + Hook: func() {}, + At: time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC), + Nested: inner{A: 5, B: 6}, + private: &cache{hits: 7}, + note: "kept", + } +} + +func TestPatchKeepsUnchangedFieldsAndIdentity(t *testing.T) { + cur := newComponent() + got, err := Patch(cur, []byte(`{"state":"chase","nested":{"a":50}}`)) + if err != nil { + t.Fatal(err) + } + if got.State != "chase" || got.Speed != 1 || got.Nested != (inner{A: 50, B: 6}) { + t.Fatalf("patched exported fields = %+v", got) + } + if got.private != cur.private || got.note != "kept" { + t.Fatal("unexported fields were not preserved") + } + if got.Handle != cur.Handle || got.Runtime == nil || got.Runtime["frames"] != 9 || got.OnHit == nil || got.Hook == nil { + t.Fatal(`json:"-" fields were not preserved`) + } + if got.Target != cur.Target { + t.Fatal("unchanged pointer field lost its identity") + } + got.Mods["new"] = 1 + if _, shared := cur.Mods["new"]; !shared { + t.Fatal("unchanged map field lost its identity") + } + if !got.At.Equal(cur.At) { + t.Fatalf("time field = %v, want %v", got.At, cur.At) + } + if cur.State != "idle" || cur.Nested.A != 5 { + t.Fatalf("Patch mutated *cur: %+v", cur) + } +} + +func TestPatchChangedContainersAreFresh(t *testing.T) { + cur := newComponent() + got, err := Patch(cur, []byte(`{"mods":{"fire":2},"list":[9],"target":{"a":10},"at":"2027-01-01T00:00:00Z"}`)) + if err != nil { + t.Fatal(err) + } + if got.Mods["acid"] != 1 || got.Mods["fire"] != 2 { + t.Fatalf("patched map = %v, want acid and fire", got.Mods) + } + if len(cur.Mods) != 1 || cur.Mods["fire"] != 0 { + t.Fatalf("Patch mutated the live map: %v", cur.Mods) + } + if len(got.List) != 1 || got.List[0] != 9 || cur.List[0] != 1 { + t.Fatalf("list = %v, live list = %v", got.List, cur.List) + } + if got.Target == cur.Target || *got.Target != (inner{A: 10, B: 2}) || *cur.Target != (inner{A: 1, B: 2}) { + t.Fatalf("target = %+v, live target = %+v", got.Target, cur.Target) + } + if got.At.Year() != 2027 || cur.At.Year() != 2026 { + t.Fatalf("time = %v, live time = %v", got.At, cur.At) + } +} + +func TestPatchFailureLeavesLiveValueUntouched(t *testing.T) { + cur := newComponent() + for _, patch := range []string{ + `{"mods":{"poison":9},"bogus":1}`, + `{"list":[7,7,7],"target":{"a":99},"bogus":1}`, + `{"target":{"a":99}} {"state":"x"}`, + `{"speed":"fast"}`, + } { + if _, err := Patch(cur, []byte(patch)); err == nil { + t.Fatalf("Patch(%s) succeeded, want error", patch) + } + } + if len(cur.Mods) != 1 || cur.Mods["acid"] != 1 { + t.Fatalf("failed patches mutated the live map: %v", cur.Mods) + } + if cur.List[0] != 1 || cur.List[1] != 2 || cur.List[2] != 3 { + t.Fatalf("failed patches mutated the live slice: %v", cur.List) + } + if *cur.Target != (inner{A: 1, B: 2}) { + t.Fatalf("failed patches mutated the live pointee: %+v", *cur.Target) + } +} + +func TestPatchNonStructAndCycles(t *testing.T) { + m := map[string]int{"a": 1} + got, err := Patch(&m, []byte(`{"b":2}`)) + if err != nil { + t.Fatal(err) + } + if got["a"] != 1 || got["b"] != 2 || len(m) != 1 { + t.Fatalf("map patch = %v, live = %v", got, m) + } + + type node struct { + Name string `json:"name"` + Next *node `json:"-"` + } + n := &node{Name: "loop"} + n.Next = n + patched, err := Patch(n, []byte(`{"name":"renamed"}`)) + if err != nil { + t.Fatal(err) + } + if patched.Name != "renamed" || patched.Next != n || n.Name != "loop" { + t.Fatalf("cyclic patch = %+v", patched) + } +} + +func TestDecodeStrict(t *testing.T) { + var v inner + if err := DecodeStrict([]byte(`{"a":1}`), &v); err != nil || v.A != 1 { + t.Fatalf("DecodeStrict = %v, %+v", err, v) + } + if err := DecodeStrict([]byte(`{"c":1}`), &v); err == nil || !strings.Contains(err.Error(), "unknown field") { + t.Fatalf("unknown field = %v", err) + } + if err := DecodeStrict([]byte(`{"a":1} 2`), &v); err == nil || !strings.Contains(err.Error(), "trailing") { + t.Fatalf("trailing data = %v", err) + } +} From e8edb28f446164b896f27de71488c7437deda79e Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Wed, 25 Nov 2026 04:11:30 +0900 Subject: [PATCH 3/3] fix(mcp): make spawn, destroy and component edits atomic and report what ran - Typed component patches use internal/jsonedit, so unexported, json:"-" and pointer fields survive and a decode error or a rejecting editor leaves the live component untouched, including components with callback fields that cannot be marshalled. - game_entity_spawn rolls back when reading the new entity back fails; game_component_set reports a failed read-back in read_error instead of an error, since the write already stands. - game_entity_destroy reports the hierarchy's actual default policy (or "none" for a childless entity), "reparent" keeps children's world transforms, and children are checked before any of them moves. - RegisterScenePrefab requires exactly one top-level object, and RegisterComponentEditor only upgrades a RegisterComponent[T] registration of the same type. - Docs, the design note and hard-wrapped comments are updated to match. --- .../2026-11-24-mcp-spawn-destroy-edit.md | 10 +- docs/en/mcp.md | 12 +- docs/zh/mcp.md | 12 +- packages/game/mcp/edit.go | 134 +++++++++--------- packages/game/mcp/edit_test.go | 111 +++++++++++++-- 5 files changed, 183 insertions(+), 96 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-11-24-mcp-spawn-destroy-edit.md b/.agents/notes/implemented/feature/2026-11-24-mcp-spawn-destroy-edit.md index 0ab70fc8..a126dec3 100644 --- a/.agents/notes/implemented/feature/2026-11-24-mcp-spawn-destroy-edit.md +++ b/.agents/notes/implemented/feature/2026-11-24-mcp-spawn-destroy-edit.md @@ -8,15 +8,15 @@ With [MCP scene, layer, entity and component inspection](2026-11-24-mcp-scene-en ## Decision -Extend `packages/game/mcp` with a dedicated mutation tool group in `edit.go` (`game_prefabs_list`, `game_entity_spawn`, `game_entity_destroy`, `game_component_set`, `game_component_remove`) hooked into `Bridge.Tools()`, backed by prefab registration APIs (`Config.Prefabs`, `Bridge.RegisterPrefab`, `Bridge.RegisterEntityPrefab`, `Bridge.RegisterScenePrefab`), typed component editor APIs (`RegisterMutableComponent`, `RegisterComponentEditor`), and zero-reflection strict codec mutation helpers (`World.DecodeComponent`, `World.PatchComponent`, `World.RemoveComponent`) in `packages/game/entities`. +Extend `packages/game/mcp` with a dedicated mutation tool group in `edit.go` (`game_prefabs_list`, `game_entity_spawn`, `game_entity_destroy`, `game_component_set`, `game_component_remove`) hooked into `Bridge.Tools()`, backed by prefab registration APIs (`Config.Prefabs`, `Bridge.RegisterPrefab`, `Bridge.RegisterEntityPrefab`, `Bridge.RegisterScenePrefab`), typed component editor APIs (`RegisterMutableComponent`, `RegisterComponentEditor`), and strict codec mutation helpers (`World.DecodeComponent`, `World.PatchComponent`, `World.RemoveComponent`) in `packages/game/entities`. ## Architecture and mutation contract - **Minimal hookup in `mcp.go`**: All mutation types, schemas, registration APIs, and handlers live in `packages/game/mcp/edit.go`; `mcp.go` adds only `Config.Prefabs`, `write`/`remove` hooks on `componentEntry`, prefab storage fields on `Bridge`, and `b.editTools()` in `Bridge.Tools()`. This isolates parallel MCP PRs (#462–#469) from merge conflicts. - **Prefab sources**: `Bridge` supports three prefab kinds (`"custom"`, `"entity_prefab"`, `"scene"`): custom `PrefabSpawner` callbacks with optional `overrides`, `*entities.Prefab` templates via `RegisterEntityPrefab`, and validated self-contained `*sceneformat.SceneDoc` templates via `RegisterScenePrefab` (instantiated through `sceneformat.SpawnEntities`). `game_prefabs_list` enumerates all registered prefabs in deterministic sorted order. - **Atomic spawning and rollback**: `game_entity_spawn` validates `x`/`y` finite float32 bounds, parent ref liveness, and prefab existence before spawning. If applying `parent` or any entry in `components` fails after spawn, every newly created entity (including scene-prefab children) is destroyed before returning the error so failed calls never leak half-initialized entities. -- **Patch-by-default strict component edits**: `game_component_set` defaults to patching existing component fields (`replace: false`) so editing a single field (such as `transform2d.x` or `health.hp`) preserves omitted fields like `scaleX`/`scaleY` or `max`, while `replace: true` decodes into a fresh zero value. Both codec helpers (`World.PatchComponent` / `World.DecodeComponent`) and bridge editors decode JSON with `DisallowUnknownFields()`, reject trailing tokens, reject `null` for non-nullable types, and reject non-finite floats (`NaN`, `±Inf`). Patching deep-copies the current value before decoding so a partial decode error never mutates maps or slices on the live entity. -- **Hierarchy invariants**: Built-in `"transform2d"` writes go through `entities.Set`, which delegates to `Hierarchy2D.SetLocal` whenever a hierarchy is attached so `WorldTransform2D` dirty flags propagate to descendants automatically. Built-in `"world_transform2d"` is explicitly read-only because it is a derived cache overwritten on `Hierarchy2D.Sync()`. `game_entity_destroy` accepts `"cascade"`, `"orphan"`, `"keep_world"`, and `"reparent"` policies without lazily instantiating `Hierarchy2D` when an entity has no children. +- **Patch-by-default strict component edits**: `game_component_set` defaults to patching existing component fields (`replace: false`) so editing a single field (such as `transform2d.x` or `health.hp`) preserves omitted fields like `scaleX`/`scaleY` or `max`, while `replace: true` decodes into a fresh zero value. Both codec helpers (`World.PatchComponent` / `World.DecodeComponent`) and bridge editors decode JSON with `DisallowUnknownFields()`, reject trailing tokens, reject `null` for non-nullable types, and reject non-finite floats (`NaN`, `±Inf`). Patching (`internal/jsonedit.Patch`) decodes onto a clone whose exported pointers, maps, slices and interfaces are freshly allocated, so a partial decode error or a rejecting editor never reaches the live entity, and then takes from the clone only the fields the patch changed, so unexported fields, `json:"-"` fields (callbacks, handles, caches) and the identity of untouched pointers survive. A JSON round-trip copy was the first approach; it was replaced because it zeroed exactly those runtime fields on `RegisterMutableComponent` types, and its shallow-copy fallback for values that cannot be marshalled shared live maps with the decoder. Codec edits are also refused when the decoded value cannot be encoded back, so a custom `UnmarshalJSON` that yields `NaN` cannot break later snapshots. +- **Hierarchy invariants**: Built-in `"transform2d"` writes go through `entities.Set`, which delegates to `Hierarchy2D.SetLocal` whenever a hierarchy is attached so `WorldTransform2D` dirty flags propagate to descendants automatically. Built-in `"world_transform2d"` is explicitly read-only because it is a derived cache overwritten on `Hierarchy2D.Sync()`. `game_entity_destroy` accepts `"cascade"`, `"orphan"`, `"keep_world"`, and `"reparent"` policies without lazily instantiating `Hierarchy2D` when an entity has no children; `"reparent"` keeps the children's world transforms, and an omitted policy reports the hierarchy's actual default (or `"none"` for a childless entity). Scene prefabs must have exactly one top-level object so the spawn result names every spawned entity through the root's subtree. - **Read-only vs mutable bridge components**: `RegisterComponent[T]` and `RegisterComponentFunc` remain read-only so inspection-only registrations (such as components carrying callbacks) do not silently become writable. Callers opt in with `RegisterMutableComponent[T]` or upgrade an existing registration with `RegisterComponentEditor[T]` to enforce domain invariants before writing. ## Alternatives considered @@ -31,12 +31,12 @@ Decoding every `game_component_set` payload into a zero-valued struct would be s ### Handling codec decoding purely inside `packages/game/mcp` via `World.Snapshot` / `Restore` -Avoiding changes to `packages/game/entities` by snapshotting, editing JSON, and calling `World.Restore` would keep `entities` untouched. It was rejected because `Snapshot`/`Restore` is O(world size), resets un-serialized transient component stores, and does not support strict `DisallowUnknownFields` decoding for a single entity's component. Adding zero-reflection `DecodeComponent`, `PatchComponent`, and `RemoveComponent` methods to `entities.World` keeps single-entity edits O(1) and preserves transient components. +Avoiding changes to `packages/game/entities` by snapshotting, editing JSON, and calling `World.Restore` would keep `entities` untouched. It was rejected because `Snapshot`/`Restore` is O(world size), resets un-serialized transient component stores, and does not support strict `DisallowUnknownFields` decoding for a single entity's component. Adding `DecodeComponent`, `PatchComponent`, and `RemoveComponent` methods to `entities.World` keeps single-entity edits O(1) and preserves transient components. ## Consequences - **Benefits**: Coding agents can discover prefabs, spawn entities (with hierarchy and initial components), edit codec/built-in/custom components with immediate effect on the next simulation step, remove components, and destroy subtrees with explicit hierarchy policies—all with strict validation and atomic rollback on error. -- **Costs**: `packages/game/entities` gains three public codec mutation methods (`DecodeComponent`, `PatchComponent`, `RemoveComponent`) to maintain alongside `EncodeComponent`. Patch mode performs a JSON round-trip copy on existing component values to guarantee map/slice isolation during error rollback, which is negligible for interactive MCP edits but not intended for per-frame inner loops. +- **Costs**: `packages/game/entities` gains three public codec mutation methods (`DecodeComponent`, `PatchComponent`, `RemoveComponent`) to maintain alongside `EncodeComponent`. Patch mode clones the existing component value with reflection and compares fields to merge the result, which is negligible for interactive MCP edits but not intended for per-frame inner loops. ## Verification diff --git a/docs/en/mcp.md b/docs/en/mcp.md index 193e91b7..fc06f192 100644 --- a/docs/en/mcp.md +++ b/docs/en/mcp.md @@ -44,8 +44,8 @@ if err != nil { Components registered on an [`entities.World`](entities.md) with `entities.RegisterCodec` are readable and editable automatically. In addition: - Built-in `entities.Transform2D`, `entities.WorldTransform2D` and `sceneformat.ObjectRef` components are surfaced automatically as `"transform2d"`, `"world_transform2d"` and `"object_ref"` unless that type or name is already registered. `"transform2d"` and `"object_ref"` are editable directly (with `"transform2d"` propagating `Hierarchy2D` dirty flags automatically); `"world_transform2d"` is derived from the hierarchy and read-only. -- Transient or non-saved runtime components can be exposed read-only with `mcp.RegisterComponent[T](bridge, name)` or `mcp.RegisterComponentFunc(bridge, name, read)`, or exposed for both reading and editing with `mcp.RegisterMutableComponent[T](bridge, name)` or `mcp.RegisterComponentEditor[T](bridge, name, apply)`. -- `game_component_set` decodes values strictly with `DisallowUnknownFields`, rejects non-finite floats (`NaN`, `±Inf`) and invalid nulls, and patches existing fields by default (preserving omitted fields unless `"replace": true` is passed) without leaving partially mutated state on error. +- Transient or non-saved runtime components can be exposed read-only with `mcp.RegisterComponent[T](bridge, name)` or `mcp.RegisterComponentFunc(bridge, name, read)`, or exposed for both reading and editing with `mcp.RegisterMutableComponent[T](bridge, name)` or `mcp.RegisterComponentEditor[T](bridge, name, apply)`. `RegisterComponentEditor` can add editing to an earlier `RegisterComponent[T]` registration of the same type, but not to a `RegisterComponentFunc` reader, whose value need not be stored as `T`. +- `game_component_set` decodes values strictly with `DisallowUnknownFields`, rejects non-finite floats (`NaN`, `±Inf`) and invalid nulls, and patches existing fields by default (preserving omitted fields unless `"replace": true` is passed) without leaving partially mutated state on error. A patch keeps every field it does not change exactly as it was, including unexported fields, fields tagged `json:"-"` such as callbacks and handles, and the identity of pointers, maps and slices; a field it changes gets a freshly allocated value, so an error or an editor that rejects the value leaves the live component untouched. A codec component whose decoded value cannot be encoded back, such as a `NaN` produced by a custom `UnmarshalJSON`, is refused before it is stored. - Component values are serialized with `encoding/json`; if a runtime value contains non-finite floats (`NaN`, `+Inf`, `-Inf`), callback fields, channels or cyclic pointers, `game/mcp` falls back to a safe sanitizer (`"NaN"`, `"+Inf"`, `"-Inf"`, `""`, `""`, `""`) so an agent can still diagnose broken runtime state. ```go @@ -69,7 +69,7 @@ Prefabs can be registered on `mcp.Config.Prefabs` or on the `*mcp.Bridge` so age - `bridge.RegisterPrefab(name, spawn)` (or `Config.Prefabs`) registers a custom `mcp.PrefabSpawner` (`func(w *entities.World, overrides map[string]any) (entities.Entity, error)`). - `bridge.RegisterEntityPrefab(p)` registers an [`*entities.Prefab`](entities.md) under `p.Name()`. -- `bridge.RegisterScenePrefab(name, doc)` registers a validated, self-contained [`*sceneformat.SceneDoc`](editor.md) template spawned via `sceneformat.SpawnEntities`. +- `bridge.RegisterScenePrefab(name, doc)` registers a validated, self-contained [`*sceneformat.SceneDoc`](editor.md) template spawned via `sceneformat.SpawnEntities`. The document must hold exactly one top-level object, the spawned root; nest the rest under it. Every spawn attaches the document's `sceneformat.ObjectRef` IDs unchanged, so repeated spawns produce entities with the same object IDs, which `game_entities_list` also shows as their names unless `EntityName` says otherwise. ```go if err := bridge.RegisterEntityPrefab(coinPrefab); err != nil { @@ -80,7 +80,7 @@ if err := bridge.RegisterScenePrefab("turret", turretDoc); err != nil { } ``` -If `game_entity_spawn` fails while applying `parent`, `x`/`y`, or `components` after spawning, the newly spawned entity (and any scene-prefab children) are rolled back automatically. +If `game_entity_spawn` fails while applying `parent` or `components`, or while reading the new entity's components back, the newly spawned entity (and any scene-prefab children) are rolled back automatically. `x` and `y` are validated before anything is spawned. ## Registered tools @@ -108,8 +108,8 @@ If `game_entity_spawn` fails while applying `parent`, `x`/`y`, or `components` a | `game_console_exec` | `command` (required) | Runs one command line through `debug.Console`, returning `command`, `ok`, `output`, `lines`, and `error` (when the console command fails). | | `game_prefabs_list` | `{}` | Sorted list of registered prefabs (`name` and `kind`: `"custom"`, `"entity_prefab"`, or `"scene"`). | | `game_entity_spawn` | `prefab`, `overrides`, `parent`, `x`, `y`, `components` (all optional) | Newly spawned live entity's stable `ref`, `index`, `generation`, `prefab`, metadata, `parent`, `children`, and initial `components` snapshot. | -| `game_entity_destroy` | `ref` (required), `policy` (optional: `"cascade"`, `"orphan"`, `"keep_world"`, or `"reparent"`) | Confirmation of destruction with `ref`, effective `policy`, and count of `destroyed` entities. | -| `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. | +| `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. | All tools reject unknown argument fields. diff --git a/docs/zh/mcp.md b/docs/zh/mcp.md index 8d171774..1b8850bf 100644 --- a/docs/zh/mcp.md +++ b/docs/zh/mcp.md @@ -44,8 +44,8 @@ if err != nil { 已在 [`entities.World`](entities.md) 上通过 `entities.RegisterCodec` 注册的组件会自动支持读取和编辑。此外: - 内置的 `entities.Transform2D`、`entities.WorldTransform2D` 和 `sceneformat.ObjectRef` 组件在未被同类型或同名注册覆盖时,会自动以 `"transform2d"`、`"world_transform2d"` 和 `"object_ref"` 的名称暴露。其中 `"transform2d"` 和 `"object_ref"` 可直接编辑(编辑 `"transform2d"` 会自动传播 `Hierarchy2D` 脏标记);`"world_transform2d"` 由层级派生,为只读组件。 -- 未写入存档的瞬态运行时组件可以通过 `mcp.RegisterComponent[T](bridge, name)` 或 `mcp.RegisterComponentFunc(bridge, name, read)` 只读暴露,也可以通过 `mcp.RegisterMutableComponent[T](bridge, name)` 或 `mcp.RegisterComponentEditor[T](bridge, name, apply)` 同时支持读取与编辑。 -- `game_component_set` 使用 `DisallowUnknownFields` 严格解码,拒绝非有限浮点数(`NaN`、`±Inf`)及非法 `null`,默认以补丁模式更新现有字段(保留未传入字段,传入 `"replace": true` 时从零值整块替换),且解码失败时不会留下半修改状态。 +- 未写入存档的瞬态运行时组件可以通过 `mcp.RegisterComponent[T](bridge, name)` 或 `mcp.RegisterComponentFunc(bridge, name, read)` 只读暴露,也可以通过 `mcp.RegisterMutableComponent[T](bridge, name)` 或 `mcp.RegisterComponentEditor[T](bridge, name, apply)` 同时支持读取与编辑。`RegisterComponentEditor` 可以为此前同类型的 `RegisterComponent[T]` 注册补上编辑能力,但不能用于 `RegisterComponentFunc` 读取器,因为后者返回的值不一定以 `T` 存储。 +- `game_component_set` 使用 `DisallowUnknownFields` 严格解码,拒绝非有限浮点数(`NaN`、`±Inf`)及非法 `null`,默认以补丁模式更新现有字段(保留未传入字段,传入 `"replace": true` 时从零值整块替换),且解码失败时不会留下半修改状态。补丁不会改动它没有修改的字段,包括未导出字段、带 `json:"-"` 标签的字段(如回调和句柄),以及指针、map 和切片的同一性;被修改的字段会得到新分配的值,因此解码出错或编辑器拒绝该值时,存活组件保持原样。对于 codec 组件,解码结果若无法重新编码(例如自定义 `UnmarshalJSON` 产生的 `NaN`),会在写入前被拒绝。 - 组件值默认用 `encoding/json` 序列化;若运行时值包含非有限浮点数(`NaN`、`+Inf`、`-Inf`)、回调函数字段、channel 或循环指针,`game/mcp` 会回退到安全的清洗编码(`"NaN"`、`"+Inf"`、`"-Inf"`、`""`、`""`、`""`),使智能体在状态异常时仍能诊断问题。 ```go @@ -69,7 +69,7 @@ if err := mcp.RegisterComponentEditor[Health](bridge, "health", func(w *entities - `bridge.RegisterPrefab(name, spawn)`(或 `Config.Prefabs`)注册自定义 `mcp.PrefabSpawner`(`func(w *entities.World, overrides map[string]any) (entities.Entity, error)`)。 - `bridge.RegisterEntityPrefab(p)` 按 `p.Name()` 注册 [`*entities.Prefab`](entities.md)。 -- `bridge.RegisterScenePrefab(name, doc)` 注册经过校验且自包含的 [`*sceneformat.SceneDoc`](editor.md) 模板,并通过 `sceneformat.SpawnEntities` 实例化。 +- `bridge.RegisterScenePrefab(name, doc)` 注册经过校验且自包含的 [`*sceneformat.SceneDoc`](editor.md) 模板,并通过 `sceneformat.SpawnEntities` 实例化。文档必须恰好有一个顶层对象作为生成的根实体,其余对象都应嵌套在它下面。每次生成都会原样附加文档中的 `sceneformat.ObjectRef` ID,因此多次生成的实体拥有相同的对象 ID;除非 `EntityName` 另有返回,`game_entities_list` 也会把它显示为实体名称。 ```go if err := bridge.RegisterEntityPrefab(coinPrefab); err != nil { @@ -80,7 +80,7 @@ if err := bridge.RegisterScenePrefab("turret", turretDoc); err != nil { } ``` -如果在 `game_entity_spawn` 生成实体后,应用 `parent`、`x`/`y` 或 `components` 时发生错误,新生成的实体(以及场景预制体的子实体)会自动回滚销毁。 +如果在 `game_entity_spawn` 生成实体后,应用 `parent` 或 `components`、或回读新实体的组件时发生错误,新生成的实体(以及场景预制体的子实体)会自动回滚销毁。`x` 和 `y` 在生成任何实体之前就已校验。 ## 已注册的工具 @@ -108,8 +108,8 @@ if err := bridge.RegisterScenePrefab("turret", turretDoc); err != nil { | `game_console_exec` | `command`(必填) | 通过 `debug.Console` 执行一条命令行,返回 `command`、`ok`、`output`、`lines` 以及命令失败时的 `error`。 | | `game_prefabs_list` | `{}` | 已注册预制体的排序列表(`name` 与 `kind`:`"custom"`、`"entity_prefab"` 或 `"scene"`)。 | | `game_entity_spawn` | `prefab`、`overrides`、`parent`、`x`、`y`、`components`(均为可选) | 新生成存活实体的稳定引用 `ref`、`index`、`generation`、`prefab`、元数据、`parent`、`children` 及初始 `components` 快照。 | -| `game_entity_destroy` | `ref`(必填)、`policy`(可选:`"cascade"`、`"orphan"`、`"keep_world"` 或 `"reparent"`) | 销毁结果,包含 `ref`、生效的 `policy` 与实际销毁实体数 `destroyed`。 | -| `game_component_set` | `ref`(必填)、`component`(必填)、`value`(必填)、`replace`(可选,默认 `false`) | 回读自存活实体的更新后组件 `value`;修改会在下一次模拟步进中生效。 | +| `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`)。 | 所有工具都会拒绝未知的参数字段。 diff --git a/packages/game/mcp/edit.go b/packages/game/mcp/edit.go index eeb5ee3d..55fc754b 100644 --- a/packages/game/mcp/edit.go +++ b/packages/game/mcp/edit.go @@ -6,13 +6,13 @@ import ( "encoding/json" "errors" "fmt" - "io" "math" "reflect" "slices" "strings" "github.com/nsgo-dev/game/packages/game/entities" + "github.com/nsgo-dev/game/packages/game/internal/jsonedit" "github.com/nsgo-dev/game/packages/game/sceneformat" "github.com/nsgo-dev/nsgo/automation" ) @@ -84,6 +84,8 @@ type ComponentSetResult struct { Ref string `json:"ref"` Component string `json:"component"` Value json.RawMessage `json:"value"` + // ReadError is set when the write succeeded but reading the component back failed; Value is then null. + ReadError string `json:"read_error,omitempty"` } // ComponentRemoveResult is the JSON result of game_component_remove. @@ -143,7 +145,7 @@ var ( "policy": { "type": "string", "enum": ["cascade", "orphan", "keep_world", "reparent"], - "description": "How to handle hierarchy children: \"cascade\" destroys descendants, \"orphan\" detaches direct children to root keeping local transforms, \"keep_world\" detaches direct children to root preserving world transforms, \"reparent\" moves direct children to the destroyed entity's parent (or root). Omit to use the world's default policy." + "description": "How to handle hierarchy children: \"cascade\" destroys descendants, \"orphan\" detaches direct children to root keeping local transforms, \"keep_world\" detaches direct children to root preserving world transforms, \"reparent\" moves direct children to the destroyed entity's parent (or root) preserving world transforms. Omit to use the hierarchy's default policy." } } }`) @@ -316,7 +318,7 @@ func (b *Bridge) RegisterEntityPrefab(p *entities.Prefab) error { // RegisterScenePrefab registers a self-contained *sceneformat.SceneDoc template under name on b so game_entity_spawn can instantiate it via sceneformat.SpawnEntities. // -// doc must pass sceneformat.Validate, must not refer to unresolved external scenes, and must contain at least one object. The first top-level object in document order is returned as the spawned root entity. +// doc must pass sceneformat.Validate, must not refer to unresolved external scenes, and must hold exactly one top-level object across its layers, which becomes the spawned root entity; nest every other object under it as a child. Each spawn attaches the document's sceneformat.ObjectRef IDs unchanged, so repeated spawns produce entities with the same object IDs and names. func (b *Bridge) RegisterScenePrefab(name string, doc *sceneformat.SceneDoc) error { if b == nil { return ErrNilBridge @@ -333,9 +335,9 @@ func (b *Bridge) RegisterScenePrefab(name string, doc *sceneformat.SceneDoc) err if doc.RefersToScenes() { return fmt.Errorf("mcp: scene prefab %q refers to external scenes; call sceneformat.Resolve first", name) } - rootID := firstSceneObjectID(doc) - if rootID == "" { - return fmt.Errorf("mcp: scene prefab %q has no objects", name) + rootID, top := sceneRootObjectID(doc) + if top != 1 { + return fmt.Errorf("mcp: scene prefab %q has %d top-level objects, want exactly 1 root object", name, top) } return b.addPrefabEntry(prefabEntry{ name: name, @@ -361,13 +363,18 @@ func (b *Bridge) RegisterScenePrefab(name string, doc *sceneformat.SceneDoc) err }) } -func firstSceneObjectID(doc *sceneformat.SceneDoc) string { +func sceneRootObjectID(doc *sceneformat.SceneDoc) (string, int) { + var id string + top := 0 for li := range doc.Layers { - if len(doc.Layers[li].Objects) > 0 { - return doc.Layers[li].Objects[0].ID + for oi := range doc.Layers[li].Objects { + if top == 0 { + id = doc.Layers[li].Objects[oi].ID + } + top++ } } - return "" + return id, top } // RegisterMutableComponent registers component type T under name on b for both inspection (game_entities_list, game_entity_inspect, game_component_get) and mutation (game_component_set, game_component_remove, game_entity_spawn). @@ -391,8 +398,7 @@ func RegisterMutableComponent[T any](b *Bridge, name string) error { // RegisterComponentEditor registers a typed component editor for component type T under name on b. // -// When name is not yet registered on b, it also registers inspection and removal for T. When name was previously registered read-only with RegisterComponent[T] (for the same type T) or RegisterComponentFunc, it attaches the editor to that registration. -// apply receives the strictly decoded and finite-validated value and may enforce domain invariants or synchronize secondary runtime state before writing. +// When name is not yet registered on b, it also registers inspection and removal for T. When name was previously registered read-only with RegisterComponent[T] for the same type T, it attaches the editor to that registration. It refuses a name registered with RegisterComponentFunc, whose reader may expose data that is not stored as T, and a name registered for another type. apply receives the strictly decoded and finite-validated value and may enforce domain invariants or synchronize secondary runtime state before writing. func RegisterComponentEditor[T any](b *Bridge, name string, apply func(w *entities.World, e entities.Entity, v T) error) error { if b == nil { return ErrNilBridge @@ -427,17 +433,15 @@ func registerTypedComponentEditor[T any](b *Bridge, name string, apply func(w *e if existing.write != nil { return fmt.Errorf("mcp: component %q: %w", name, ErrDuplicateComponent) } - if existing.typeKey != nil && existing.typeKey != k { + if existing.typeKey == nil { + return fmt.Errorf("mcp: component %q is registered with RegisterComponentFunc, whose reader is not backed by a stored type: %w", name, ErrDuplicateComponent) + } + if existing.typeKey != k { return fmt.Errorf("mcp: component %q already registered with a different type: %w", name, ErrDuplicateComponent) } - existing.typeKey = k existing.write = writeFn existing.remove = removeFn b.components[name] = existing - if b.compByType == nil { - b.compByType = make(map[compTypeKey]string) - } - b.compByType[k] = name return nil } @@ -607,6 +611,7 @@ func (b *Bridge) handleEntitySpawn(_ context.Context, raw json.RawMessage) (any, vals, err := b.readAllComponents(w, e) if err != nil { + rollback() return nil, err } res := EntitySpawnResult{ @@ -663,9 +668,13 @@ func (b *Bridge) handleEntityDestroy(_ context.Context, raw json.RawMessage) (an } before := w.Count() + children := w.ChildrenOf(e) effectivePolicy := args.Policy if effectivePolicy == "" { - effectivePolicy = "default" + effectivePolicy = "none" + if len(children) > 0 { + effectivePolicy = removePolicyName(w.Hierarchy2D().RemovePolicy()) + } } switch args.Policy { @@ -690,16 +699,18 @@ func (b *Bridge) handleEntityDestroy(_ context.Context, raw json.RawMessage) (an w.Destroy(e) } case "reparent": - if children := w.ChildrenOf(e); len(children) > 0 { + if len(children) > 0 { h := w.Hierarchy2D() - parent, hasParent := w.ParentOf(e) + parent, _ := w.ParentOf(e) + // Every child is alive and parent is one of its ancestors, so SetParent cannot fail with a dead entity or a cycle; it is checked anyway before any child moves so a change in entities cannot leave a half-moved family. for _, ch := range children { - if hasParent { - if err := h.SetParent(ch, parent, false); err != nil { - return nil, fmt.Errorf("mcp: reparent child %s: %w", FormatEntityRef(ch), err) - } - } else { - h.Detach(ch, false) + if !w.Alive(ch) || (parent != entities.Zero && !w.Alive(parent)) { + return nil, fmt.Errorf("mcp: reparent child %s: %w", FormatEntityRef(ch), entities.ErrDeadEntity) + } + } + for _, ch := range children { + if err := h.SetParent(ch, parent, true); err != nil { + return nil, fmt.Errorf("mcp: reparent child %s: %w", FormatEntityRef(ch), err) } } } @@ -713,6 +724,17 @@ func (b *Bridge) handleEntityDestroy(_ context.Context, raw json.RawMessage) (an }, nil } +func removePolicyName(p entities.RemovePolicy) string { + switch p { + case entities.RemoveCascade: + return "cascade" + case entities.RemoveDetachKeepWorld: + return "keep_world" + default: + return "orphan" + } +} + type componentSetArgs struct { Ref string `json:"ref"` Component string `json:"component"` @@ -751,18 +773,20 @@ func (b *Bridge) handleComponentSet(_ context.Context, raw json.RawMessage) (any return nil, err } - val, ok, err := b.readComponent(w, e, args.Component) - if err != nil { - return nil, err - } - if !ok { - val = json.RawMessage("null") - } - return ComponentSetResult{ + res := ComponentSetResult{ Ref: FormatEntityRef(e), Component: args.Component, - Value: val, - }, nil + Value: json.RawMessage("null"), + } + // The write has already happened, so a failing read-back is reported next to the result rather than as an error that would suggest the edit did not apply. + val, ok, err := b.readComponent(w, e, args.Component) + switch { + case err != nil: + res.ReadError = err.Error() + case ok: + res.Value = val + } + return res, nil } type componentRemoveArgs struct { @@ -947,7 +971,7 @@ func writeBuiltinTransform2D(w *entities.World, e entities.Entity, raw json.RawM t = entities.IdentityTransform2D() } } - if err := decodeStrictValue(trimmed, &t); err != nil { + if err := jsonedit.DecodeStrict(trimmed, &t); err != nil { return fmt.Errorf("mcp: set component %q on %s: %w", "transform2d", FormatEntityRef(e), err) } for _, pair := range []struct { @@ -982,7 +1006,7 @@ func writeBuiltinObjectRef(w *entities.World, e entities.Entity, raw json.RawMes ref = *cur } } - if err := decodeStrictValue(trimmed, &ref); err != nil { + if err := jsonedit.DecodeStrict(trimmed, &ref); err != nil { return fmt.Errorf("mcp: set component %q on %s: %w", "object_ref", FormatEntityRef(e), err) } entities.Set(w, e, ref) @@ -1004,20 +1028,13 @@ func decodeTypedComponent[T any](w *entities.World, e entities.Entity, name stri return v, fmt.Errorf("cannot set non-nullable component %q to null; use game_component_remove to remove a component", name) } } - if !replace { - if cur, ok := entities.Get[T](w, e); ok { - // Prefer an isolated JSON copy so a partial decode error never mutates *cur's maps or slices; - // fall back to a shallow copy when *cur contains non-JSON fields (such as callbacks or NaN being repaired). - if curJSON, err := json.Marshal(*cur); err == nil { - if err := json.Unmarshal(curJSON, &v); err != nil { - v = *cur - } - } else { - v = *cur - } + if cur, ok := entities.Get[T](w, e); ok && !replace { + patched, err := jsonedit.Patch(cur, trimmed) + if err != nil { + return v, err } - } - if err := decodeStrictValue(trimmed, &v); err != nil { + v = patched + } else if err := jsonedit.DecodeStrict(trimmed, &v); err != nil { return v, err } if err := validateFiniteValue(reflect.ValueOf(v), 0, make(map[visitKey]bool)); err != nil { @@ -1026,19 +1043,6 @@ func decodeTypedComponent[T any](w *entities.World, e entities.Entity, name stri return v, nil } -func decodeStrictValue(trimmed []byte, dst any) error { - dec := json.NewDecoder(bytes.NewReader(trimmed)) - dec.DisallowUnknownFields() - if err := dec.Decode(dst); err != nil { - return err - } - var extra any - if err := dec.Decode(&extra); err != io.EOF { - return errors.New("unexpected trailing data") - } - return nil -} - func validateFloat32Arg(field string, v float64) error { if math.IsNaN(v) || math.IsInf(v, 0) || math.Abs(v) > math.MaxFloat32 { return fmt.Errorf("mcp: %s must be a finite float32", field) diff --git a/packages/game/mcp/edit_test.go b/packages/game/mcp/edit_test.go index 79a90ca3..77bb74cc 100644 --- a/packages/game/mcp/edit_test.go +++ b/packages/game/mcp/edit_test.go @@ -21,6 +21,17 @@ type armorComp struct { Mods map[string]int `json:"mods,omitempty"` } +type aiHandle struct{ id int } + +// aiComp mixes JSON fields with runtime-only state: an exported callback (which makes json.Marshal fail), a json:"-" pointer, and an unexported cache. +type aiComp struct { + State string `json:"state"` + Mods map[string]int `json:"mods,omitempty"` + OnEnter func() + Path *aiHandle `json:"-"` + cache *aiHandle +} + type nanFloatComp struct { V float64 } @@ -39,10 +50,7 @@ func (n *nanFloatComp) UnmarshalJSON(data []byte) error { return nil } -// TestSpawnEditStepAndDestroyLifecycle exercises the full MCP mutation workflow: -// listing prefabs, spawning prefabs (custom, entities.Prefab, sceneformat.SceneDoc, and empty), -// editing components so changes take effect on the very next simulation step, removing components, -// and destroying entities with every hierarchy policy. +// TestSpawnEditStepAndDestroyLifecycle exercises the full MCP mutation workflow: listing prefabs, spawning prefabs (custom, entities.Prefab, sceneformat.SceneDoc, and empty), editing components so changes take effect on the very next simulation step, removing components, and destroying entities with every hierarchy policy. func TestSpawnEditStepAndDestroyLifecycle(t *testing.T) { w := entities.NewWorld() if err := entities.RegisterCodec[posComp](w, "position"); err != nil { @@ -413,10 +421,12 @@ func TestSpawnEditStepAndDestroyLifecycle(t *testing.T) { } } - // 7b. Reparent policy: grandparent -> mid -> leaf; destroy mid with reparent -> leaf becomes child of grandparent. + // 7b. Reparent policy: grandparent -> mid -> leaf; destroy mid with reparent -> leaf becomes child of grandparent and keeps its world position (10 + 20 + 5 = 35), so its local X under the grandparent is 25. gp := callTool[mcp.EntitySpawnResult](t, app, cx, mcp.ToolEntitySpawn, map[string]any{"x": 10, "y": 10}) mid := callTool[mcp.EntitySpawnResult](t, app, cx, mcp.ToolEntitySpawn, map[string]any{"parent": gp.Ref, "x": 20, "y": 0}) leaf := callTool[mcp.EntitySpawnResult](t, app, cx, mcp.ToolEntitySpawn, map[string]any{"parent": mid.Ref, "x": 5, "y": 0}) + app.Post(func() { h.Sync() }) + app.Settle() repRes := callTool[mcp.EntityDestroyResult](t, app, cx, mcp.ToolEntityDestroy, map[string]any{ "ref": mid.Ref, "policy": "reparent", @@ -428,8 +438,15 @@ func TestSpawnEditStepAndDestroyLifecycle(t *testing.T) { if leafAfterReparent.Parent != gp.Ref { t.Fatalf("leaf parent after reparent = %q, want %q", leafAfterReparent.Parent, gp.Ref) } + var leafXform entities.Transform2D + if err := json.Unmarshal(leafAfterReparent.Components["transform2d"], &leafXform); err != nil { + t.Fatal(err) + } + if leafXform.X != 25 || leafXform.Y != 0 { + t.Fatalf("leaf local transform after reparent = (%v, %v), want (25, 0)", leafXform.X, leafXform.Y) + } - // 7c. keep_world policy: sync transforms, destroy gp with keep_world -> leaf becomes root with local X = 10 + 5 = 15. + // 7c. keep_world policy: sync transforms, destroy gp with keep_world -> leaf becomes root with local X = 10 + 25 = 35. app.Post(func() { h.Sync() }) app.Settle() kwRes := callTool[mcp.EntityDestroyResult](t, app, cx, mcp.ToolEntityDestroy, map[string]any{ @@ -443,12 +460,11 @@ func TestSpawnEditStepAndDestroyLifecycle(t *testing.T) { if leafAfterKW.Parent != "" { t.Fatalf("leaf parent after keep_world = %q, want root", leafAfterKW.Parent) } - var leafXform entities.Transform2D if err := json.Unmarshal(leafAfterKW.Components["transform2d"], &leafXform); err != nil { t.Fatal(err) } - if leafXform.X != 15 || leafXform.Y != 10 { - t.Fatalf("leaf local transform after keep_world = (%v, %v), want (15, 10)", leafXform.X, leafXform.Y) + if leafXform.X != 35 || leafXform.Y != 10 { + t.Fatalf("leaf local transform after keep_world = (%v, %v), want (35, 10)", leafXform.X, leafXform.Y) } // 7d. orphan policy: parent -> child; destroy parent with orphan -> child becomes root keeping local transform (3, 4). @@ -472,10 +488,17 @@ func TestSpawnEditStepAndDestroyLifecycle(t *testing.T) { t.Fatalf("child local transform after orphan = (%v, %v), want (3, 4)", leafXform.X, leafXform.Y) } - // 7e. Default destroy on leaf and verify recycled slot rejects old ref. + // 7e. Default destroy of a parent reports the hierarchy's default policy (orphan), and of a childless leaf reports "none"; a recycled slot rejects the old ref. + pDef := callTool[mcp.EntitySpawnResult](t, app, cx, mcp.ToolEntitySpawn, nil) + cDef := callTool[mcp.EntitySpawnResult](t, app, cx, mcp.ToolEntitySpawn, map[string]any{"parent": pDef.Ref}) + parentDefRes := callTool[mcp.EntityDestroyResult](t, app, cx, mcp.ToolEntityDestroy, map[string]any{"ref": pDef.Ref}) + if parentDefRes.Destroyed != 1 || parentDefRes.Policy != "orphan" { + t.Fatalf("default parent destroy = %+v, want orphan", parentDefRes) + } + callTool[mcp.EntityDestroyResult](t, app, cx, mcp.ToolEntityDestroy, map[string]any{"ref": cDef.Ref}) defRes := callTool[mcp.EntityDestroyResult](t, app, cx, mcp.ToolEntityDestroy, map[string]any{"ref": leaf.Ref}) - if defRes.Destroyed != 1 || defRes.Policy != "default" { - t.Fatalf("default destroy = %+v", defRes) + if defRes.Destroyed != 1 || defRes.Policy != "none" { + t.Fatalf("default destroy = %+v, want none", defRes) } reused := callTool[mcp.EntitySpawnResult](t, app, cx, mcp.ToolEntitySpawn, nil) if reused.Ref == leaf.Ref { @@ -619,6 +642,50 @@ func TestEditValidationAtomicityAndErrorCases(t *testing.T) { t.Fatalf("failed patch corrupted armor map: %+v", gotArmor.Mods) } + // Patching one field keeps the callback, json:"-" pointer and unexported cache, and a failed or rejected patch leaves the live map unchanged. + if err := mcp.RegisterMutableComponent[aiComp](b, "ai"); err != nil { + t.Fatal(err) + } + if err := mcp.RegisterComponentEditor[aiComp](b, "ai_strict", func(*entities.World, entities.Entity, aiComp) error { + return errors.New("rejected by editor") + }); err != nil { + t.Fatal(err) + } + aiEnt, err := mcp.ParseEntityRef(ent.Ref) + if err != nil { + t.Fatal(err) + } + path, cache := &aiHandle{id: 1}, &aiHandle{id: 2} + called := false + app.Post(func() { + entities.Set(w, aiEnt, aiComp{State: "idle", Mods: map[string]int{"a": 1}, OnEnter: func() { called = true }, Path: path, cache: cache}) + }) + app.Settle() + callTool[mcp.ComponentSetResult](t, app, cx, mcp.ToolComponentSet, map[string]any{"ref": ent.Ref, "component": "ai", "value": map[string]any{"state": "chase"}}) + if _, err := callToolRaw(t, app, cx, mcp.ToolComponentSet, map[string]any{"ref": ent.Ref, "component": "ai", "value": map[string]any{"mods": map[string]int{"b": 2}, "bogus": 1}}); err == nil { + t.Fatal("patch with an unknown trailing field succeeded") + } + if _, err := callToolRaw(t, app, cx, mcp.ToolComponentSet, map[string]any{"ref": ent.Ref, "component": "ai_strict", "value": map[string]any{"mods": map[string]int{"c": 3}}}); err == nil || !strings.Contains(err.Error(), "rejected by editor") { + t.Fatalf("editor rejection = %v", err) + } + var gotAI aiComp + app.Post(func() { + if v, ok := entities.Get[aiComp](w, aiEnt); ok { + gotAI = *v + } + }) + app.Settle() + if gotAI.State != "chase" || gotAI.Path != path || gotAI.cache != cache || gotAI.OnEnter == nil { + t.Fatalf("patch lost runtime fields: %+v", gotAI) + } + if len(gotAI.Mods) != 1 || gotAI.Mods["a"] != 1 { + t.Fatalf("failed or rejected patch mutated the live map: %v", gotAI.Mods) + } + gotAI.OnEnter() + if !called { + t.Fatal("patched component lost its callback") + } + // Reject NaN produced by custom unmarshaler, overflowing float32 in transform2d, null for struct, read-only & derived components, unknown component, missing required args, invalid policy. if _, err := callToolRaw(t, app, cx, mcp.ToolComponentSet, map[string]any{ "ref": ent.Ref, @@ -687,8 +754,7 @@ func TestEditValidationAtomicityAndErrorCases(t *testing.T) { t.Fatalf("invalid policy = %v", err) } - // Upgrading a read-only RegisterComponent[posComp] via RegisterComponentEditor[posComp] works, - // while a mismatched type or duplicate editor is rejected! + // Upgrading a read-only RegisterComponent[posComp] via RegisterComponentEditor[posComp] works, while a mismatched type or duplicate editor is rejected! if err := mcp.RegisterComponentEditor[velComp](b, "readonly_pos", func(*entities.World, entities.Entity, velComp) error { return nil }); !errors.Is(err, mcp.ErrDuplicateComponent) { t.Fatalf("mismatched editor type = %v, want ErrDuplicateComponent", err) } @@ -737,6 +803,23 @@ func TestEditValidationAtomicityAndErrorCases(t *testing.T) { if err := b.RegisterScenePrefab("empty_scene", &sceneformat.SceneDoc{Version: sceneformat.CurrentVersion, Name: "empty"}); err == nil { t.Fatal("expected error for scene prefab with no objects") } + twoRoots := &sceneformat.SceneDoc{ + Version: sceneformat.CurrentVersion, + Name: "two_roots", + Layers: []sceneformat.LayerDoc{ + {Name: "a", Objects: []sceneformat.ObjectDoc{{ID: "one"}}}, + {Name: "b", Objects: []sceneformat.ObjectDoc{{ID: "two"}}}, + }, + } + if err := b.RegisterScenePrefab("two_roots", twoRoots); err == nil || !strings.Contains(err.Error(), "2 top-level objects") { + t.Fatalf("scene prefab with two top-level objects = %v, want refusal", err) + } + if err := mcp.RegisterComponentFunc(b, "func_pos", func(*entities.World, entities.Entity) (any, bool, error) { return posComp{}, true, nil }); err != nil { + t.Fatal(err) + } + if err := mcp.RegisterComponentEditor[posComp](b, "func_pos", func(*entities.World, entities.Entity, posComp) error { return nil }); !errors.Is(err, mcp.ErrDuplicateComponent) { + t.Fatalf("editor over RegisterComponentFunc = %v, want ErrDuplicateComponent", err) + } if err := mcp.RegisterMutableComponent[posComp](nil, "p"); !errors.Is(err, mcp.ErrNilBridge) { t.Fatalf("nil bridge RegisterMutableComponent = %v", err) }