diff --git a/.agents/notes/implemented/feature/2026-11-24-mcp-agent-skill.md b/.agents/notes/implemented/feature/2026-11-24-mcp-agent-skill.md new file mode 100644 index 00000000..d0237d02 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-24-mcp-agent-skill.md @@ -0,0 +1,48 @@ +# Agent Note: Agent Skill for the NSGo game layer + +Status: implemented + +## Problem + +NSGo ships an installable Agent Skill (`skills/nsgo`) so coding agents can build, test and drive NSGo apps via `go tool nsgo` and `nsgo mcp`, while the game layer (`github.com/nsgo-dev/game/packages/game`) adds 100+ packages, the `go tool game` CLI, strict versioned YAML formats, and the `game/mcp` tool suite. Without a dedicated, installable skill describing those conventions and MCP tools, agents guess package names, bypass `go tool nsgo check`/`test`, write non-canonical YAML, or miss the deterministic `game_loop_*` and inspection workflows. + +## Decision + +Publish an Agent Skill at `skills/nsgo-game/` (installable via `bunx skills add nsgo-dev/game`) with a concise `SKILL.md` entry point and three on-demand reference files (`references/packages.md`, `references/cli-and-formats.md`, `references/mcp-tools.md`), backed by automated Go tests that keep the skill mechanically aligned with the repository and verify the documented CLI-to-MCP workflow end to end. + +## Skill layout and test invariants + +- **Standard Agent Skills layout**: `skills/nsgo-game/SKILL.md` carries strict YAML frontmatter (`name: nsgo-game` and `description`) matching the directory name, mirroring NSGo's `skills/nsgo/` layout so `bunx skills add nsgo-dev/game` discovers and installs it cleanly. +- **Progressive disclosure via `references/`**: `SKILL.md` stays short and task-oriented (core rules, `game new`/`generate`/`assets`/`check`/`dev` workflow, minimal `game.Loop` + `mcp.Attach` pattern, and the deterministic MCP verification loop), delegating dense catalogs to `references/packages.md`, `references/cli-and-formats.md`, and `references/mcp-tools.md`. +- **Drift prevention tests (`packages/game/skill_test.go`)**: `TestAgentSkillValid` parses `SKILL.md` frontmatter with `KnownFields(true)`, verifies every relative Markdown link stays inside `skills/nsgo-game/` and resolves on disk, checks `references/packages.md` against `modulePackages(t)` (both directions) and each package's status against `docs/en/stability.md`, and requires the tool tables in `references/mcp-tools.md` to name exactly the tools `mcp.New(mcp.Config{}).Tools()` returns. `TestAgentSkillDocumentsEveryCommand` (`packages/game/cmd/game`) loops over the `commands` slice and requires each subcommand in `references/cli-and-formats.md`. +- **End-to-end CLI and MCP verification**: `TestAgentSkillWorkflowBuildAndVerifyThroughMCP` (`packages/game/skill_test.go`) and `TestAgentSkillCLIScaffoldGenerateCheckAndMCP` (`packages/game/cmd/game/skill_e2e_test.go`) scaffold/validate a project (`game new`, `game generate`, `game index`, `game check`), load the YAML scene into `entities.World`, attach `mcp.Bridge` inside `nsgotest.Start`, and verify deterministic simulation over MCP (`game_scenes_list`, `game_layers_list`, `game_loop_pause`, `game_loop_seed`, `game_loop_step`, `game_entities_list`, `game_entity_inspect`, `game_component_get`). +- **Additive rebase boundary**: Tests live in `packages/game/skill_test.go` and `packages/game/cmd/game/skill_e2e_test.go`, and user docs live in new `docs/{en,zh}/agent-skill.md` pages rather than heavily editing `packages/game/mcp/` or `docs/{en,zh}/mcp.md`, avoiding merge conflicts with sibling MCP tool PRs (#463–#469). `references/mcp-tools.md` documents the complete `#461`–`#469` tool catalog while Go tests compile strictly against the tools landed on `main` (`#461` and `#462`, see [MCP scene, layer, entity and component inspection](2026-11-24-mcp-scene-entity-inspection.md) and [MCP loop control and deterministic seeding](2026-11-24-mcp-loop-control.md)). + +## Alternatives considered + +### Putting everything into one monolithic `skills/nsgo-game/SKILL.md` + +Strongest argument: a single file requires no secondary reads when an agent loads the skill. + +Rejected because listing 111 packages, 19 CLI commands, dozens of YAML formats, and 38 MCP tools in one file bloats every agent prompt where the skill triggers. Splitting into a compact `SKILL.md` plus three focused `references/` files matches NSGo's `skills/nsgo/` structure and Agent Skills progressive-disclosure guidelines. + +### Placing the skill under `.agents/skills/nsgo-game/` instead of `skills/nsgo-game/` + +Strongest argument: `.agents/skills/` is where repository-local contributor skills live (such as `write-notes-like-deepseek`). + +Rejected because `.agents/skills/` is for internal repository workflow skills, whereas `skills/nsgo-game/` matches NSGo's published `skills/nsgo/` location for downstream users installing via `bunx skills add nsgo-dev/game`. + +### Relying on manual review to keep the skill synchronized with code + +Strongest argument: markdown files do not normally require Go tests. + +Rejected because new packages, CLI commands, and MCP tools land frequently; without `TestAgentSkillValid`, the skill's package list, relative links, and MCP tool names would silently drift from the codebase. + +## Consequences + +- **Benefits**: Downstream users can install the game-layer skill with `bunx skills add nsgo-dev/game`; agents have an accurate, concise map of packages, CLI commands, YAML rules, and MCP tools; CI automatically catches missing packages, broken links, or undocumented MCP tools. +- **Costs**: Adding a new package under `packages/game/` now requires updating `skills/nsgo-game/references/packages.md` alongside `docs/{en,zh}/stability.md`, and adding a new tool to `mcp.Bridge.Tools()` requires ensuring its name appears in `skills/nsgo-game/references/mcp-tools.md` (already pre-populated for `#461`–`#469`). + +## Verification + +Verified with `gofmt`, `go run ./cmd/gameschema -check`, `go tool nsgo check -target macos,windows,linux,android,web`, `go tool nsgo test ./cmd/game`, `go tool nsgo test ./mcp`, `go tool nsgo test . -- -run '^Test(AgentSkill|ASecond|FormatsPage|FormatPackagesRunConformance|StabilityTable)'`, `go run ./tools/changelog check`, and `bun run verify-notes`. diff --git a/README.md b/README.md index b7c47fae..0e29717c 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ Import the packages from `github.com/nsgo-dev/game/packages/game`: - [Tutorial: Star Catcher](docs/en/tutorial.md) ([中文](docs/zh/tutorial.md)), nine chapters from an empty project to a shipped game, with each chapter's code in [`examples/tutorial`](examples/tutorial/) - [Packages](docs/en/packages.md) ([中文](docs/zh/packages.md)): [Loop](docs/en/loop.md), [sprite](docs/en/sprite.md), [sound](docs/en/sound.md) - [API Stability](docs/en/stability.md) ([中文](docs/zh/stability.md)) +- [Agent Skill](docs/en/agent-skill.md) ([中文](docs/zh/agent-skill.md)) — installable via `bunx skills add nsgo-dev/game` - [3D Models from Blender](docs/en/3d-models-blender.md) ([中文](docs/zh/3d-models-blender.md)) - [Building and Shipping](docs/en/shipping.md) ([中文](docs/zh/shipping.md)) diff --git a/apps/website/src/content/groups.ts b/apps/website/src/content/groups.ts index 5269cbb5..cbad0298 100644 --- a/apps/website/src/content/groups.ts +++ b/apps/website/src/content/groups.ts @@ -3,7 +3,7 @@ export type GroupKey = 'guides' | 'tutorial' | 'comingFrom' | 'core2d' | 'extended2d' | 'multiplayerModding' | 'threeD' | 'other' const SIDEBAR_GROUPS: readonly { key: Exclude; slugs: readonly string[] }[] = [ - { key: 'guides', slugs: ['index', 'getting-started', 'project', 'playground', 'packages', 'stability', 'shipping', 'cli', 'cli-reference'] }, + { key: 'guides', slugs: ['index', 'getting-started', 'project', 'playground', 'packages', 'stability', 'shipping', 'cli', 'cli-reference', 'agent-skill'] }, { key: 'tutorial', slugs: [ diff --git a/changelog.d/mcp-agent-skill-470.md b/changelog.d/mcp-agent-skill-470.md new file mode 100644 index 00000000..6e2b59dd --- /dev/null +++ b/changelog.d/mcp-agent-skill-470.md @@ -0,0 +1,3 @@ +### Added + +- `skills/nsgo-game`: Agent Skill installable via `bunx skills add nsgo-dev/game` covering the game-layer packages, `go tool game` CLI, plain-text YAML file formats, and `game/mcp` tool suite, along with automated structure and end-to-end MCP workflow tests (#470). diff --git a/docs/en/agent-skill.md b/docs/en/agent-skill.md new file mode 100644 index 00000000..d21f78be --- /dev/null +++ b/docs/en/agent-skill.md @@ -0,0 +1,36 @@ +# Agent Skill + +The repository publishes an Agent Skill at [`skills/nsgo-game`](../../skills/nsgo-game/SKILL.md) so coding agents know how to scaffold, build, test, inspect and drive NSGo games using the `go tool game` CLI, plain-text YAML formats and the `game/mcp` tool suite. + +## Install + +Install the skill with `bunx skills add`: + +```sh +bunx skills add nsgo-dev/game +``` + +Pair it with NSGo's own `nsgo` skill for core UI primitives, signals, `nsgotest` and `go tool nsgo`: + +```sh +bunx skills add nsgo-dev/nsgo +``` + +To let an agent inspect and drive a running game live, also register NSGo's MCP server: + +```sh +claude mcp add nsgo -- go tool nsgo mcp +``` + +## What the skill covers + +- **[`SKILL.md`](../../skills/nsgo-game/SKILL.md)**: project rules (Go only, plain-text versioned YAML formats, `go tool nsgo check`/`test`, stability tiers), quick-start CLI workflow, minimal `game.Loop` + `mcp.Attach` wiring, and the deterministic MCP verification loop. +- **[`references/packages.md`](../../skills/nsgo-game/references/packages.md)**: complete grouped catalog of every package in `github.com/nsgo-dev/game/packages/game`, with import paths and stability status matching [API Stability](stability.md). +- **[`references/cli-and-formats.md`](../../skills/nsgo-game/references/cli-and-formats.md)**: all `go tool game` subcommands ([Command Reference](cli-reference.md)), companion module tools, the YAML format contract ([File Formats](formats.md)), JSON Schemas ([Schemas](schemas.md)) and native external formats (Tiled, LDtk, Aseprite, TexturePacker, BMFont, glTF, Yarn). +- **[`references/mcp-tools.md`](../../skills/nsgo-game/references/mcp-tools.md)**: `mcp.Bridge` setup ([mcp](mcp.md)) and the full tool catalog covering scene/entity inspection, fixed-step loop control, game-coordinate input, live spawning and component editing, screenshots with diagnostic overlays, debug console tunables, input recording/replay, performance telemetry and live asset hot reload. + +## Typical agent workflow + +1. Scaffold and add building blocks with `go tool game new`, `go tool game generate`, `go tool game assets` and `go tool game check`. +2. Attach `mcp.Bridge` on the game's `*core.Scope` and run `go tool nsgo dev -automation` (or `nsgotest.Start` in tests). +3. Drive reproducible checks through MCP: pause with `game_loop_pause`, seed with `game_loop_seed`, inject inputs or spawn entities, advance synchronously with `game_loop_step`, inspect entities with `game_entities_list` / `game_entity_inspect` / `game_component_get`, and capture overlays with `game_screenshot`. diff --git a/docs/en/index.md b/docs/en/index.md index e78cf875..40ef0b67 100644 --- a/docs/en/index.md +++ b/docs/en/index.md @@ -137,3 +137,5 @@ With those, this repository would add an XR camera rig to `scene3d` and XR actio ## For language models The site publishes the English docs for language models and coding agents, as [nsgo.dev](https://nsgo.dev/llms.txt) does: [llms.txt](https://game.nsgo.dev/llms.txt) lists every page with a line about it, and [llms-full.txt](https://game.nsgo.dev/llms-full.txt) holds every page's Markdown in one file. Both are built from `docs/en` with the site, so they always match these pages. For contributors, the [Agent Evaluation Suite](agent-eval.md) grades fixed game tasks with YAML, build and `game/mcp` checks, and can run a coding agent on them. + +For coding agents that support Agent Skills, install the game-layer skill with `bunx skills add nsgo-dev/game`; see [Agent Skill](agent-skill.md). diff --git a/docs/zh/agent-skill.md b/docs/zh/agent-skill.md new file mode 100644 index 00000000..5a84b8f3 --- /dev/null +++ b/docs/zh/agent-skill.md @@ -0,0 +1,36 @@ +# 智能体技能 + +本仓库在 [`skills/nsgo-game`](../../skills/nsgo-game/SKILL.md) 发布了一个智能体技能(Agent Skill),让编程智能体了解如何通过 `go tool game` 命令行工具、纯文本 YAML 格式和 `game/mcp` 工具集来创建、构建、测试、检查并驱动 NSGo 游戏。 + +## 安装 + +使用 `bunx skills add` 安装该技能: + +```sh +bunx skills add nsgo-dev/game +``` + +建议同时安装 NSGo 自身的 `nsgo` 技能,以涵盖核心 UI 组件、signal、`nsgotest` 与 `go tool nsgo`: + +```sh +bunx skills add nsgo-dev/nsgo +``` + +如需让智能体实时检查并驱动运行中的游戏,还需注册 NSGo 的 MCP 服务器: + +```sh +claude mcp add nsgo -- go tool nsgo mcp +``` + +## 技能内容 + +- **[`SKILL.md`](../../skills/nsgo-game/SKILL.md)**:项目核心规则(纯 Go、带版本号的纯文本 YAML 格式、`go tool nsgo check`/`test`、稳定性分级)、快速上手的 CLI 流程、最小 `game.Loop` + `mcp.Attach` 接入示例,以及确定性 MCP 验证循环。 +- **[`references/packages.md`](../../skills/nsgo-game/references/packages.md)**:`github.com/nsgo-dev/game/packages/game` 下所有包的分组目录、导入路径与稳定性状态,与[API 稳定性](stability.md)保持一致。 +- **[`references/cli-and-formats.md`](../../skills/nsgo-game/references/cli-and-formats.md)**:全部 `go tool game` 子命令([命令参考](cli-reference.md))、配套模块工具、YAML 格式契约([文件格式](formats.md))、JSON Schema([YAML 文件的 Schema](schemas.md))及直接读取的外部工具格式(Tiled、LDtk、Aseprite、TexturePacker、BMFont、glTF、Yarn)。 +- **[`references/mcp-tools.md`](../../skills/nsgo-game/references/mcp-tools.md)**:`mcp.Bridge` 接入方法([mcp](mcp.md))与完整工具目录,覆盖场景/实体检查、固定步长循环控制、游戏坐标输入、实时生成与组件编辑、带诊断叠加层的截图、调试控制台可调参数、输入录制与回放、性能读数以及资源热重载。 + +## 典型智能体工作流 + +1. 使用 `go tool game new`、`go tool game generate`、`go tool game assets` 与 `go tool game check` 搭建项目并校验资源和引用。 +2. 在游戏的 `*core.Scope` 上挂载 `mcp.Bridge`,并运行 `go tool nsgo dev -automation`(或在测试中使用 `nsgotest.Start`)。 +3. 通过 MCP 执行可复现验证:调用 `game_loop_pause` 暂停、`game_loop_seed` 设定随机种子、注入输入或生成实体、调用 `game_loop_step` 同步推进步数、通过 `game_entities_list` / `game_entity_inspect` / `game_component_get` 检查实体状态,并用 `game_screenshot` 截取叠加层画面。 diff --git a/docs/zh/index.md b/docs/zh/index.md index 91f2247b..fdf2914d 100644 --- a/docs/zh/index.md +++ b/docs/zh/index.md @@ -137,3 +137,5 @@ macOS、iOS、Windows、Linux、Android 和 Web。鸿蒙、小程序、watchOS ## 面向语言模型 与 [nsgo.dev](https://nsgo.dev/llms.txt) 一样,本站为语言模型和编程智能体发布英文文档:[llms.txt](https://game.nsgo.dev/llms.txt) 列出每个页面并附一句简介,[llms-full.txt](https://game.nsgo.dev/llms-full.txt) 把每个页面的 Markdown 合在一个文件里。两者都随网站从 `docs/en` 构建,因此始终与这些页面一致。面向贡献者的[智能体评测套件](agent-eval.md)用 YAML、构建与 `game/mcp` 检查为固定的游戏任务评分,也可以让编程智能体来完成这些任务。 + +对于支持 Agent Skills 的编程智能体,可通过 `bunx skills add nsgo-dev/game` 安装游戏层技能,详见[智能体技能](agent-skill.md)。 diff --git a/packages/game/cmd/game/skill_e2e_test.go b/packages/game/cmd/game/skill_e2e_test.go new file mode 100644 index 00000000..81f0168a --- /dev/null +++ b/packages/game/cmd/game/skill_e2e_test.go @@ -0,0 +1,274 @@ +package main + +import ( + "encoding/json" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game" + "github.com/nsgo-dev/game/packages/game/entities" + "github.com/nsgo-dev/game/packages/game/mcp" + "github.com/nsgo-dev/game/packages/game/project" + "github.com/nsgo-dev/game/packages/game/random" + "github.com/nsgo-dev/game/packages/game/scene" + "github.com/nsgo-dev/game/packages/game/sceneformat" + "github.com/nsgo-dev/game/packages/game/tilemap" + "github.com/nsgo-dev/nsgo/automation" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +func TestMain(m *testing.M) { nsgotest.Main(m) } + +// TestAgentSkillDocumentsEveryCommand requires the skill's CLI reference to name every game subcommand, so a new command fails here until skills/nsgo-game documents it. +func TestAgentSkillDocumentsEveryCommand(t *testing.T) { + doc, err := os.ReadFile(filepath.Join("..", "..", "..", "..", "skills", "nsgo-game", "references", "cli-and-formats.md")) + if err != nil { + t.Fatal(err) + } + names := []string{"help"} + for _, c := range commands { + names = append(names, c.name) + } + for _, name := range names { + if !strings.Contains(string(doc), "`game "+name+"`") { + t.Errorf("skills/nsgo-game/references/cli-and-formats.md does not document `game %s`", name) + } + } +} + +// skillHealth stands in for the Health component game generate writes into the project, which the test cannot import. +type skillHealth struct{} + +// TestAgentSkillCLIScaffoldGenerateCheckAndMCP exercises the end-to-end workflow documented in skills/nsgo-game: scaffold with `game new`, generate a scene and component with `game generate`, place an object using the component in the generated scene, index and validate with `game index` and `game check`, load the scene into a running game with mcp.Bridge, and verify the scene's object through MCP calls. +func TestAgentSkillCLIScaffoldGenerateCheckAndMCP(t *testing.T) { + stubGo(t, nil) + dir := filepath.Join(t.TempDir(), "star-hop") + + // 1. Scaffold project with `game new`. + a, stdout, stderr := newTestApp(t) + if code := run([]string{"new", "-name", "Star Hop", "-module", "example.com/star-hop", dir}, a); code != 0 { + t.Fatalf("game new exited %d\nstdout:\n%s\nstderr:\n%s", code, stdout.String(), stderr.String()) + } + + // 2. Generate a main scene and a component using `game generate`. + if code, out, errOut := runGenerate(t, dir, "-main", "scene", "arena"); code != 0 { + t.Fatalf("game generate scene exited %d\nstdout:\n%s\nstderr:\n%s", code, out, errOut) + } + if code, out, errOut := runGenerate(t, dir, "component", "health"); code != 0 { + t.Fatalf("game generate component exited %d\nstdout:\n%s\nstderr:\n%s", code, out, errOut) + } + + // 3. Place a player using the generated health component in the generated scene, as an agent edits the YAML. + var componentFile string + for _, name := range listFiles(t, dir) { + if strings.HasSuffix(name, "/health_component.go") || name == "health_component.go" { + componentFile = name + } + } + if componentFile == "" { + t.Fatalf("game generate component health wrote no health_component.go: %v", listFiles(t, dir)) + } + componentSrc, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(componentFile))) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(componentSrc), `Name: "health"`) { + t.Fatalf("%s does not register a component named health:\n%s", componentFile, componentSrc) + } + generatedScene := filepath.Join(dir, "scenes", "arena.scene.yaml") + raw, err := os.ReadFile(generatedScene) + if err != nil { + t.Fatal(err) + } + edit, err := sceneformat.Parse(raw) + if err != nil { + t.Fatalf("sceneformat.Parse(generated arena scene): %v", err) + } + edit.Layers[0].Objects = append(edit.Layers[0].Objects, sceneformat.ObjectDoc{ + ID: "player", Name: "Player", X: 10, Y: 20, + Components: map[string]any{"health": map[string]any{}}, + }) + raw, err = sceneformat.Encode(edit) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(generatedScene, raw, 0o644); err != nil { + t.Fatal(err) + } + + // 4. Assign stable UIDs with `game index` and validate everything with `game check`. + a, stdout, stderr = newTestApp(t) + if code := run([]string{"index", dir}, a); code != 0 { + t.Fatalf("game index exited %d\nstdout:\n%s\nstderr:\n%s", code, stdout.String(), stderr.String()) + } + a, stdout, stderr = newTestApp(t) + if code := run([]string{"check", dir}, a); code != 0 { + t.Fatalf("game check exited %d\nstdout:\n%s\nstderr:\n%s", code, stdout.String(), stderr.String()) + } + + // 5. Parse the generated project and main scene YAML files, checking components against the generated registry. + proj, err := project.Check(os.DirFS(dir)) + if err != nil { + t.Fatalf("project.Check: %v", err) + } + if proj.Autoload.MainScene != "arena" || len(proj.Autoload.Scenes) != 1 { + t.Fatalf("unexpected autoload scenes in game.yaml: %+v", proj.Autoload) + } + scenePath := filepath.Join(dir, filepath.FromSlash(proj.Autoload.Scenes[0].Path)) + sceneBytes, err := os.ReadFile(scenePath) + if err != nil { + t.Fatalf("read generated scene %s: %v", scenePath, err) + } + registry := sceneformat.NewComponentRegistry() + registry.MustRegister(sceneformat.ComponentType{Name: "health", Doc: "Health"}) + doc, err := sceneformat.ParseWith(sceneBytes, sceneformat.ParseOptions{File: proj.Autoload.Scenes[0].Path, Components: registry}) + if err != nil { + t.Fatalf("sceneformat.ParseWith(%s): %v", scenePath, err) + } + + world := entities.NewWorld() + if err := entities.RegisterCodec[skillHealth](world, "health"); err != nil { + t.Fatal(err) + } + spawned, err := sceneformat.SpawnEntities(doc, world) + if err != nil { + t.Fatalf("sceneformat.SpawnEntities: %v", err) + } + names := map[entities.Entity]string{} + for li := range doc.Layers { + sceneformat.WalkObjects(doc.Layers[li].Objects, func(o, _ *sceneformat.ObjectDoc) bool { + e := spawned[o.ID] + names[e] = o.Name + if _, ok := o.Components["health"]; ok { + entities.Set(world, e, skillHealth{}) + } + return true + }) + } + player, ok := spawned["player"] + if !ok { + t.Fatalf("player was not spawned from %s", scenePath) + } + + sc := scene.NewScene(&tilemap.Camera{Width: 480, Height: 640}) + sc.AddLayer(scene.NewLayer("world", scene.SpaceWorld, 0)) + + rng := random.NewStreams(7) + var cx *core.Scope + app := nsgotest.Start(t, func(s *core.Scope) core.Node { + cx = s + mgr := scene.NewManager(s) + mgr.Push(&scene.Controller{Scene: sc}) + loop := &game.Loop{ + Rate: 60, + Update: func(dt time.Duration) { + if tr, ok := entities.Get[entities.Transform2D](world, player); ok { + tr.X += float32(60 * dt.Seconds()) + } + }, + Draw: func(float64) {}, + } + loop.Run(s) + if _, err := mcp.Attach(s, mcp.Config{ + Scenes: mgr, + SceneName: func(*scene.Controller) string { return proj.Autoload.MainScene }, + WorldFunc: func() *entities.World { return world }, + EntityName: func(e entities.Entity) string { return names[e] }, + Loop: loop, + RandomStreams: rng, + }); err != nil { + t.Errorf("mcp.Attach: %v", err) + } + return core.View{} + }) + + call := func(tool string, args any) json.RawMessage { + t.Helper() + var payload json.RawMessage + if args != nil { + b, err := json.Marshal(args) + if err != nil { + t.Fatal(err) + } + payload = b + } + var ( + res json.RawMessage + err error + ) + app.Post(func() { + res, err = automation.Call(cx, t.Context(), tool, payload) + }) + app.Settle() + if err != nil { + t.Fatalf("%s failed: %v", tool, err) + } + return res + } + + var scenes mcp.ScenesListResult + if err := json.Unmarshal(call(mcp.ToolScenesList, nil), &scenes); err != nil { + t.Fatal(err) + } + if scenes.Current != "arena" { + t.Fatalf("current scene = %q, want %q", scenes.Current, "arena") + } + + call(mcp.ToolLoopPause, nil) + app.Post(func() { + tr, _ := entities.Get[entities.Transform2D](world, player) + tr.X = 10 + }) + app.Settle() + call(mcp.ToolLoopSeed, map[string]any{"seed": uint64(99)}) + + var step mcp.LoopStepResult + if err := json.Unmarshal(call(mcp.ToolLoopStep, map[string]any{"count": 60}), &step); err != nil { + t.Fatal(err) + } + if step.StepsAdvanced != 60 || step.DeltaSeconds != 1.0 { + t.Fatalf("game_loop_step = %+v, want 60 steps / 1.0s", step) + } + + var list mcp.EntitiesListResult + if err := json.Unmarshal(call(mcp.ToolEntitiesList, map[string]any{"name": "Player", "component": "health"}), &list); err != nil { + t.Fatal(err) + } + if list.Returned != 1 { + t.Fatalf("game_entities_list(name=Player, component=health) = %+v", list) + } + + var inspect mcp.EntityInspectResult + if err := json.Unmarshal(call(mcp.ToolEntityInspect, map[string]any{"ref": list.Entities[0].Ref}), &inspect); err != nil { + t.Fatal(err) + } + components := make([]string, 0, len(inspect.Components)) + for name := range inspect.Components { + components = append(components, name) + } + for _, want := range []string{"health", "object_ref", "transform2d"} { + if !slices.Contains(components, want) { + t.Fatalf("game_entity_inspect(player) components = %v, want %s", components, want) + } + } + + var comp mcp.ComponentGetResult + if err := json.Unmarshal(call(mcp.ToolComponentGet, map[string]any{ + "ref": list.Entities[0].Ref, + "component": "transform2d", + }), &comp); err != nil { + t.Fatal(err) + } + var tr entities.Transform2D + if err := json.Unmarshal(comp.Value, &tr); err != nil { + t.Fatal(err) + } + if tr.X < 69.9 || tr.X > 70.1 { + t.Fatalf("player X after 60 steps = %v, want ~70", tr.X) + } +} diff --git a/packages/game/skill_test.go b/packages/game/skill_test.go new file mode 100644 index 00000000..2bb6d3f8 --- /dev/null +++ b/packages/game/skill_test.go @@ -0,0 +1,492 @@ +package game_test + +import ( + "bytes" + "encoding/json" + "io/fs" + "math" + "os" + "path/filepath" + "regexp" + "slices" + "strings" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game" + "github.com/nsgo-dev/game/packages/game/entities" + "github.com/nsgo-dev/game/packages/game/mcp" + "github.com/nsgo-dev/game/packages/game/project" + "github.com/nsgo-dev/game/packages/game/random" + "github.com/nsgo-dev/game/packages/game/scene" + "github.com/nsgo-dev/game/packages/game/sceneformat" + "github.com/nsgo-dev/game/packages/game/tilemap" + "github.com/nsgo-dev/game/packages/game/tooling/assetcheck" + "github.com/nsgo-dev/nsgo/automation" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" + "go.yaml.in/yaml/v3" +) + +type skillFrontmatter struct { + Name string `yaml:"name"` + Description string `yaml:"description"` +} + +var ( + skillNamePattern = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*$`) + markdownLinkPattern = regexp.MustCompile(`!?\[[^\]]*\]\(([^)\s]+)(?:\s+"[^"]*")?\)`) + skillPackageRowRegexp = regexp.MustCompile("^\\| `(game(?:/[a-z0-9_.-]+)*)` \\| (Stable|Experimental) \\|") + skillToolRowRegexp = regexp.MustCompile("^\\| `(game_[a-z0-9_]+)` \\|") +) + +func parseSkillFrontmatter(t *testing.T, data []byte) (skillFrontmatter, string) { + t.Helper() + text := strings.ReplaceAll(string(data), "\r\n", "\n") + if !strings.HasPrefix(text, "---\n") { + t.Fatalf("SKILL.md must start with YAML frontmatter delimiter ---") + } + rest := text[len("---\n"):] + fmText, body, ok := strings.Cut(rest, "\n---\n") + if !ok { + t.Fatalf("SKILL.md is missing closing YAML frontmatter delimiter ---") + } + var fm skillFrontmatter + dec := yaml.NewDecoder(strings.NewReader(fmText)) + dec.KnownFields(true) + if err := dec.Decode(&fm); err != nil { + t.Fatalf("parse SKILL.md frontmatter: %v", err) + } + return fm, body +} + +func stripFencedCodeBlocks(md string) string { + var out strings.Builder + inFence := false + for _, line := range strings.Split(strings.ReplaceAll(md, "\r\n", "\n"), "\n") { + trimmed := strings.TrimSpace(line) + if strings.HasPrefix(trimmed, "```") { + inFence = !inFence + continue + } + if !inFence { + out.WriteString(line) + out.WriteByte('\n') + } + } + return out.String() +} + +// TestAgentSkillValid verifies that skills/nsgo-game conforms to the Agent Skills layout (installable via `bunx skills add`), has valid relative links, lists every package under packages/game with the status docs/en/stability.md gives it, and catalogs exactly the tools game/mcp registers. cmd/game's TestAgentSkillDocumentsEveryCommand checks the CLI subcommands. +func TestAgentSkillValid(t *testing.T) { + skillDir := filepath.Join("..", "..", "skills", "nsgo-game") + skillPath := filepath.Join(skillDir, "SKILL.md") + + raw, err := os.ReadFile(skillPath) + if err != nil { + t.Fatalf("read %s: %v", skillPath, err) + } + fm, body := parseSkillFrontmatter(t, raw) + + if fm.Name != "nsgo-game" { + t.Errorf("SKILL.md frontmatter name = %q, want %q", fm.Name, "nsgo-game") + } + if !skillNamePattern.MatchString(fm.Name) || len(fm.Name) > 64 { + t.Errorf("SKILL.md frontmatter name %q is not a valid Agent Skill name", fm.Name) + } + if strings.TrimSpace(fm.Description) == "" { + t.Errorf("SKILL.md frontmatter description must be non-empty") + } + if len(fm.Description) > 1024 { + t.Errorf("SKILL.md frontmatter description length = %d, want <= 1024", len(fm.Description)) + } + + for _, ref := range []string{ + "references/packages.md", + "references/cli-and-formats.md", + "references/mcp-tools.md", + } { + if !strings.Contains(body, ref) { + t.Errorf("SKILL.md must reference %s", ref) + } + } + + absSkillDir, err := filepath.Abs(skillDir) + if err != nil { + t.Fatal(err) + } + err = filepath.WalkDir(skillDir, func(p string, d fs.DirEntry, walkErr error) error { + if walkErr != nil || d.IsDir() || !strings.HasSuffix(d.Name(), ".md") { + return walkErr + } + data, err := os.ReadFile(p) + if err != nil { + return err + } + cleaned := stripFencedCodeBlocks(string(data)) + for _, m := range markdownLinkPattern.FindAllStringSubmatch(cleaned, -1) { + target := m[1] + if strings.HasPrefix(target, "http://") || + strings.HasPrefix(target, "https://") || + strings.HasPrefix(target, "mailto:") || + strings.HasPrefix(target, "#") { + continue + } + targetPath, _, _ := strings.Cut(target, "#") + if targetPath == "" { + continue + } + resolved, err := filepath.Abs(filepath.Join(filepath.Dir(p), filepath.FromSlash(targetPath))) + if err != nil { + t.Errorf("%s: resolve link %q: %v", p, target, err) + continue + } + rel, err := filepath.Rel(absSkillDir, resolved) + if err != nil || strings.HasPrefix(rel, "..") { + t.Errorf("%s: relative link %q escapes %s", p, target, skillDir) + continue + } + if _, err := os.Stat(resolved); err != nil { + t.Errorf("%s: broken relative link %q: %v", p, target, err) + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } + + // Verify references/packages.md matches the real module packages. + pkgsDoc, err := os.ReadFile(filepath.Join(skillDir, "references", "packages.md")) + if err != nil { + t.Fatal(err) + } + documentedPkgs := map[string]string{} + for i, line := range strings.Split(string(pkgsDoc), "\n") { + m := skillPackageRowRegexp.FindStringSubmatch(line) + if m == nil { + continue + } + pkg := m[1] + if _, dup := documentedPkgs[pkg]; dup { + t.Errorf("skills/nsgo-game/references/packages.md:%d: duplicate package %q", i+1, pkg) + } + documentedPkgs[pkg] = statusWords["en"][m[2]] + } + for _, row := range readStabilityTable(t, "en") { + if got, ok := documentedPkgs[row.pkg]; ok && got != row.status { + t.Errorf("skills/nsgo-game/references/packages.md gives %s status %q, docs/en/stability.md gives %q", row.pkg, got, row.status) + } + } + actualPkgs := modulePackages(t) + for pkg := range documentedPkgs { + if _, ok := actualPkgs[pkg]; !ok { + t.Errorf("skills/nsgo-game/references/packages.md lists unknown package %q", pkg) + } + } + var missingPkgs []string + for pkg := range actualPkgs { + if _, ok := documentedPkgs[pkg]; !ok { + missingPkgs = append(missingPkgs, pkg) + } + } + slices.Sort(missingPkgs) + for _, pkg := range missingPkgs { + t.Errorf("skills/nsgo-game/references/packages.md is missing package %q", pkg) + } + + // Verify the tool catalog in references/mcp-tools.md names exactly the tools game/mcp registers. + mcpDoc, err := os.ReadFile(filepath.Join(skillDir, "references", "mcp-tools.md")) + if err != nil { + t.Fatal(err) + } + documentedTools := map[string]bool{} + for i, line := range strings.Split(string(mcpDoc), "\n") { + m := skillToolRowRegexp.FindStringSubmatch(line) + if m == nil { + continue + } + if documentedTools[m[1]] { + t.Errorf("skills/nsgo-game/references/mcp-tools.md:%d: duplicate tool %q", i+1, m[1]) + } + documentedTools[m[1]] = true + } + tools := mcp.New(mcp.Config{}).Tools() + if len(tools) == 0 { + t.Fatal("mcp.New returned zero tools") + } + registered := map[string]bool{} + for _, tool := range tools { + registered[tool.Name] = true + if !documentedTools[tool.Name] { + t.Errorf("skills/nsgo-game/references/mcp-tools.md is missing registered MCP tool %q", tool.Name) + } + } + for name := range documentedTools { + if !registered[name] { + t.Errorf("skills/nsgo-game/references/mcp-tools.md documents %q, which game/mcp does not register", name) + } + } +} + +type skillVelocity struct { + VX float32 `json:"vx"` + VY float32 `json:"vy"` +} + +func callSkillMCPTool[T any](t *testing.T, app *nsgotest.App, cx *core.Scope, name string, args any) T { + t.Helper() + var payload json.RawMessage + if args != nil { + b, err := json.Marshal(args) + if err != nil { + t.Fatalf("marshal args for %s: %v", name, err) + } + payload = b + } + var ( + raw json.RawMessage + err error + ) + app.Post(func() { + raw, err = automation.Call(cx, t.Context(), name, payload) + }) + app.Settle() + if err != nil { + t.Fatalf("%s failed: %v", name, err) + } + var out T + if err := json.Unmarshal(raw, &out); err != nil { + t.Fatalf("unmarshal %s result %s: %v", name, raw, err) + } + return out +} + +// TestAgentSkillWorkflowBuildAndVerifyThroughMCP simulates an agent following skills/nsgo-game: authoring plain-text YAML project & scene files, validating them, loading the scene into an ECS world with a fixed-step game.Loop, attaching mcp.Bridge, and verifying deterministic gameplay over MCP. +func TestAgentSkillWorkflowBuildAndVerifyThroughMCP(t *testing.T) { + dir := t.TempDir() + gameYAML := strings.Join([]string{ + "version: 1", + "name: Skill Demo", + "id: dev.nsgo.skilldemo", + "appVersion: 0.1.0", + "window:", + " width: 320", + " height: 180", + "autoload:", + " mainScene: arena", + " scenes:", + " - name: arena", + " path: scenes/arena.scene.yaml", + "", + }, "\n") + nsgoYAML := "name: Skill Demo\nid: dev.nsgo.skilldemo\nversion: 0.1.0\ngame: true\n" + arenaYAML := strings.Join([]string{ + "version: 1", + "name: arena", + "virtualWidth: 320", + "virtualHeight: 180", + "layers:", + " - name: world", + " space: world", + " order: 0", + " objects:", + " - id: hero", + " x: 20", + " \"y\": 40", + " - id: target", + " x: 140", + " \"y\": 40", + " - name: hud", + " space: screen", + " order: 10", + "", + }, "\n") + + if err := os.MkdirAll(filepath.Join(dir, "scenes"), 0o755); err != nil { + t.Fatal(err) + } + for rel, content := range map[string]string{ + project.FileName: gameYAML, + "nsgo.yaml": nsgoYAML, + "scenes/arena.scene.yaml": arenaYAML, + } { + if err := os.WriteFile(filepath.Join(dir, filepath.FromSlash(rel)), []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + + // Step 1: Validate project file and scene references (as `game check` does). + proj, err := project.Check(os.DirFS(dir)) + if err != nil { + t.Fatalf("project.Check: %v", err) + } + if proj.Autoload.MainScene != "arena" { + t.Fatalf("MainScene = %q, want %q", proj.Autoload.MainScene, "arena") + } + report, err := assetcheck.Check(os.DirFS(dir)) + if err != nil { + t.Fatalf("assetcheck.Check: %v", err) + } + if len(report.Problems) > 0 { + t.Fatalf("assetcheck reported problems: %v", report.Problems) + } + + // Step 2: Load the YAML scene and spawn entities into an ECS world. + sceneBytes, err := os.ReadFile(filepath.Join(dir, "scenes", "arena.scene.yaml")) + if err != nil { + t.Fatal(err) + } + doc, err := sceneformat.Parse(sceneBytes) + if err != nil { + t.Fatalf("sceneformat.Parse: %v", err) + } + world := entities.NewWorld() + if err := entities.RegisterCodec[skillVelocity](world, "velocity"); err != nil { + t.Fatal(err) + } + + spawned, err := sceneformat.SpawnEntities(doc, world) + if err != nil { + t.Fatalf("sceneformat.SpawnEntities: %v", err) + } + hero := spawned["hero"] + if hero == entities.Zero { + t.Fatal("hero entity was not spawned from arena.scene.yaml") + } + entities.Set(world, hero, skillVelocity{VX: 120, VY: 0}) + + sc := scene.NewScene(&tilemap.Camera{X: 160, Y: 90, Width: 320, Height: 180}) + sc.AddLayer(scene.NewLayer("world", scene.SpaceWorld, 0)) + sc.AddLayer(scene.NewLayer("hud", scene.SpaceScreen, 10)) + + rng := random.NewStreams(1) + var ( + cx *core.Scope + loop *game.Loop + bridge *mcp.Bridge + ) + + // Step 3: Start the game with a fixed-step Loop and attach mcp.Bridge. + app := nsgotest.Start(t, func(s *core.Scope) core.Node { + cx = s + mgr := scene.NewManager(s) + mgr.Push(&scene.Controller{Scene: sc}) + frame := core.NewSignal(s, uint64(0)) + loop = &game.Loop{ + Rate: 60, + Update: func(dt time.Duration) { + secs := float32(dt.Seconds()) + jitter := float32(rng.Stream("movement").Intn(3)) // deterministic given seed + if tr, ok := entities.Get[entities.Transform2D](world, hero); ok { + if vel, ok := entities.Get[skillVelocity](world, hero); ok { + tr.X += vel.VX*secs + jitter*0.01 + tr.Y += vel.VY * secs + } + } + }, + Draw: func(float64) { + frame.Update(func(n uint64) uint64 { return n + 1 }) + }, + } + loop.Run(s) + + var attachErr error + bridge, attachErr = mcp.Attach(s, mcp.Config{ + Scenes: mgr, + SceneName: func(c *scene.Controller) string { return "arena" }, + WorldFunc: func() *entities.World { return world }, + Loop: loop, + RandomStreams: rng, + }) + if attachErr != nil { + t.Errorf("mcp.Attach: %v", attachErr) + } + + return core.Canvas{ + TestID: "game-canvas", + Style: core.Style{FlexGrow: 1, FlexShrink: 1}, + Draw: func(d *core.Drawing, _ core.Size) { + _ = frame.Get() + sc.Draw(d) + }, + } + }) + if bridge == nil || !bridge.Attached() { + t.Fatal("mcp.Bridge failed to attach") + } + + // Step 4: Follow the skill's MCP verification loop: inspect -> pause -> seed -> step -> assert. + scenesRes := callSkillMCPTool[mcp.ScenesListResult](t, app, cx, mcp.ToolScenesList, nil) + if scenesRes.Current != "arena" || scenesRes.StackDepth != 1 { + t.Fatalf("game_scenes_list = %+v, want current=arena depth=1", scenesRes) + } + + layersRes := callSkillMCPTool[mcp.LayersListResult](t, app, cx, mcp.ToolLayersList, nil) + if len(layersRes.Layers) != 2 || layersRes.Layers[0].Name != "world" || layersRes.Layers[1].Name != "hud" { + t.Fatalf("game_layers_list = %+v, want [world, hud]", layersRes.Layers) + } + + pauseRes := callSkillMCPTool[mcp.LoopStatusResult](t, app, cx, mcp.ToolLoopPause, nil) + if !pauseRes.Paused || !pauseRes.SeedConfigured { + t.Fatalf("game_loop_pause = %+v, want paused=true seed_configured=true", pauseRes) + } + + // Reset hero position and apply a fixed seed for a reproducible 1-second simulation. + app.Post(func() { + tr, _ := entities.Get[entities.Transform2D](world, hero) + tr.X = 20 + tr.Y = 40 + }) + app.Settle() + + seedRes := callSkillMCPTool[mcp.LoopSeedResult](t, app, cx, mcp.ToolLoopSeed, map[string]any{"seed": uint64(42)}) + if seedRes.Seed != 42 { + t.Fatalf("game_loop_seed = %+v, want seed=42", seedRes) + } + + entList := callSkillMCPTool[mcp.EntitiesListResult](t, app, cx, mcp.ToolEntitiesList, map[string]any{"name": "hero"}) + if entList.Returned != 1 || entList.Entities[0].Name != "hero" { + t.Fatalf("game_entities_list(name=hero) = %+v", entList) + } + heroRef := entList.Entities[0].Ref + + stepRes := callSkillMCPTool[mcp.LoopStepResult](t, app, cx, mcp.ToolLoopStep, map[string]any{"count": 60}) + if stepRes.StepsAdvanced != 60 || math.Abs(stepRes.DeltaSeconds-1.0) > 1e-9 { + t.Fatalf("game_loop_step(60) = %+v, want steps_advanced=60 delta_seconds=1.0", stepRes) + } + + inspectRes := callSkillMCPTool[mcp.EntityInspectResult](t, app, cx, mcp.ToolEntityInspect, map[string]any{"ref": heroRef}) + if _, ok := inspectRes.Components["velocity"]; !ok { + t.Fatalf("game_entity_inspect missing velocity component: %+v", inspectRes.Components) + } + + trRes := callSkillMCPTool[mcp.ComponentGetResult](t, app, cx, mcp.ToolComponentGet, map[string]any{ + "ref": heroRef, + "component": "transform2d", + }) + var tr entities.Transform2D + if err := json.Unmarshal(trRes.Value, &tr); err != nil { + t.Fatalf("unmarshal transform2d %s: %v", trRes.Value, err) + } + + // Recompute exact expected X from seed 42 over 60 steps at 60 Hz. + checkRNG := random.NewStreams(42) + expectedX := float32(20) + dtSecs := float32((time.Second / 60).Seconds()) + for range 60 { + expectedX += 120*dtSecs + float32(checkRNG.Stream("movement").Intn(3))*0.01 + } + if math.Abs(float64(tr.X-expectedX)) > 1e-4 { + t.Fatalf("hero transform2d.X = %v, want %v (seed 42, 60 steps)", tr.X, expectedX) + } + + // Verify that a fresh YAML project file round-trips canonically. + canonical, err := project.Encode(proj) + if err != nil { + t.Fatalf("project.Encode: %v", err) + } + if !bytes.Equal(canonical, []byte(gameYAML)) { + t.Fatalf("game.yaml did not round-trip canonically:\ngot:\n%s\nwant:\n%s", canonical, gameYAML) + } +} diff --git a/skills/nsgo-game/SKILL.md b/skills/nsgo-game/SKILL.md new file mode 100644 index 00000000..19c560b7 --- /dev/null +++ b/skills/nsgo-game/SKILL.md @@ -0,0 +1,133 @@ +--- +name: nsgo-game +description: Build, run, test, inspect and drive 2D and 3D games on NSGo with github.com/nsgo-dev/game/packages/game. Use when scaffolding a game with `go tool game`, writing fixed-step game loops, sprites, tilemaps, scenes, ECS worlds, physics, audio, 3D scenes, plain-text YAML game files, attaching `game/mcp` tools to `nsgo mcp`, or verifying a running game through MCP. +--- + +# NSGo Game + +`github.com/nsgo-dev/game/packages/game` is the game layer for [NSGo](https://github.com/nsgo-dev/nsgo) apps, written in Go. A game draws into one NSGo view (`core.Canvas`, pixel buffer, shader, or GPU view), while HUDs and menus remain native NSGo views layered on top. It uses only NSGo's public API and supports macOS, iOS, Windows, Linux, Android and the web. + +Pair this skill with NSGo's own `nsgo` skill (`bunx skills add nsgo-dev/nsgo`) for UI primitives, layouts, signals, `nsgotest`, and `go tool nsgo`. + +Read the version-matched source in your module cache rather than guessing signatures: + +```sh +go get github.com/nsgo-dev/game/packages/game@latest +go get -tool github.com/nsgo-dev/game/packages/game/cmd/game@latest +go get -tool github.com/nsgo-dev/nsgo/cmd/nsgo@latest +go list -m -f '{{.Dir}}' github.com/nsgo-dev/game/packages/game +``` + +Published English docs for agents live at (index) and (full Markdown). + +## Core rules + +- **Go only, no hand-written C.** Never add cgo or C toolchains; use NSGo services, purego or `syscall`. +- **Every authored file is plain-text YAML.** Scenes (`*.scene.yaml`), project settings (`game.yaml`), import sidecars (`*.import.yaml`), shared resources, data tables, animations, particles, input recordings, and gameplay configs are versioned YAML with strict unknown-key refusal and deterministic canonical saves. Program-written snapshots and save slots use YAML or JSON, never `encoding/gob` or custom binary layouts. +- **Keep third-party exports native.** Read Tiled `.tmj`, LDtk `.ldtk`, Aseprite/TexturePacker JSON, BMFont/MSDF fonts, glTF `.gltf`/`.glb`, and Yarn `.yarn` directly without binary conversion steps. +- **Vet and test with `go tool nsgo`.** Always run `go tool nsgo check` and `go tool nsgo test`, never `go vet` or `go test` directly. Pass all touched targets in one check: `go tool nsgo check -target macos,windows,linux,android,web`. +- **Respect stability tiers.** Core 2D packages (`game`, `math2d`, `random`, `screen`, `flow`, `tween`, `sprite`, `tilemap`, `scene`, `input`, `physics`, `sound`, `save`, `ai`, `loaderr`) are **Stable**; newer packages (including `mcp`, `entities`, `sceneformat`, 3D, and genre kits) are **Experimental** — pin versions and check the source. +- **Engine goroutine ownership.** Start `game.Loop`, `mcp.Attach`, and signal writes on the engine goroutine (`*core.Scope`). Use `cx.Post` from background goroutines and `app.Post` + `app.Settle` in `nsgotest`. + +## Quick-start workflow + +1. **Scaffold a project:** + + ```sh + go tool game new my-game + cd my-game + ``` + + Creates `go.mod` (with `game` and `nsgo` tools), `game.yaml`, `nsgo.yaml`, `main.go`, `game.go`, `project.go`, and tests. + +2. **Generate gameplay building blocks:** + + ```sh + go tool game generate -main scene arena + go tool game generate prefab player + go tool game generate component velocity + go tool game generate system movement + ``` + +3. **Build assets and validate references:** + + ```sh + go tool game assets # packs atlases, encodes KTX2, converts audio, writes typed manifest + go tool game index # assigns stable file UIDs and updates the project index + go tool game check # checks scenes, Tiled/LDtk maps, atlases, and all file references + ``` + +4. **Run, test, and verify through MCP:** + + ```sh + go tool game dev # runs nsgo dev with live asset hot reload + go tool nsgo test ./... # headless deterministic tests via nsgotest + go tool nsgo dev -automation # exposes built-in + game/mcp tools for nsgo mcp + claude mcp add nsgo -- go tool nsgo mcp # connects an MCP client to the running app + ``` + +5. **Package for release:** + + ```sh + go tool game credits # verifies asset license sidecars + go tool game release # builds export presets from game.yaml via nsgo build + ``` + +## Minimal game with `game.Loop` and `game/mcp` + +A game component owns a fixed-step `game.Loop` and triggers `core.Canvas` redraws via a frame signal so the native view tree does not re-commit every frame. Attach `mcp.Bridge` on the same `*core.Scope` so agents can inspect and drive the running game over `nsgo mcp` (in normal and release builds `automation.Register` is a no-op): + +```go +func Root(cx *core.Scope) core.Node { + frame := core.NewSignal(cx, uint64(0)) + rng := random.NewStreams(1) + world := entities.NewWorld() + sc := scene.NewScene(&tilemap.Camera{Width: 320, Height: 180}) + + loop := &game.Loop{ + Rate: 60, + Update: func(dt time.Duration) { + stepWorld(world, rng, dt) + }, + Draw: func(alpha float64) { + frame.Update(func(n uint64) uint64 { return n + 1 }) + }, + } + loop.Run(cx) + + bridge, _ := mcp.Attach(cx, mcp.Config{ + Scene: sc, + WorldFunc: func() *entities.World { return world }, + Loop: loop, + RandomStreams: rng, + }) + _ = mcp.RegisterComponent[Velocity](bridge, "velocity") + + return core.Canvas{ + TestID: "game-canvas", + Style: core.Style{FlexGrow: 1, FlexShrink: 1}, + Draw: func(d *core.Drawing, size core.Size) { + _ = frame.Get() + sc.Draw(d) + }, + } +} +``` + +## Verifying a running game through MCP + +When testing or debugging a game over `nsgo mcp` (or headlessly via `nsgotest.Start` + `automation.Call`): + +1. **Discover state:** call `game_scenes_list`, `game_layers_list`, and `game_entities_list` to find active scenes and stable generational entity references (`"entity::"`). +2. **Make runs deterministic:** call `game_loop_pause`, then `game_loop_seed` with a fixed unsigned 64-bit seed. +3. **Drive gameplay:** inject actions/axes/pointer events (`game_input_action`, `game_input_axis`, `game_input_pointer`) or spawn/edit entities (`game_entity_spawn`, `game_component_set`) and advance an exact step count synchronously with `game_loop_step` (60 steps at 60 Hz advances exactly `1.0` second). +4. **Assert state & visuals:** read updated component values with `game_entity_inspect` / `game_component_get`, check performance with `game_perf_readout`, and capture aligned debug screenshots with `game_screenshot` (`bounds: true`, `collision_shapes: true`). +5. **Reproduce & regress:** record sequences with `game_replay_record_start` / `game_replay_record_stop` to save editable YAML recordings, then replay them deterministically with `game_replay_play` or `go tool game replay`. + +## References + +Load on demand for exact APIs, flags, schemas, and tool arguments: + +- [references/packages.md](references/packages.md) — complete catalog of `packages/game/*` packages grouped by stage and domain, with import paths and stability status. +- [references/cli-and-formats.md](references/cli-and-formats.md) — `go tool game` subcommands, companion tools, YAML file format contract, schemas, and external tool formats. +- [references/mcp-tools.md](references/mcp-tools.md) — full `game/mcp` tool reference, `mcp.Config` wiring, component/prefab/asset registration, and `nsgotest` verification patterns. diff --git a/skills/nsgo-game/references/cli-and-formats.md b/skills/nsgo-game/references/cli-and-formats.md new file mode 100644 index 00000000..42f39c77 --- /dev/null +++ b/skills/nsgo-game/references/cli-and-formats.md @@ -0,0 +1,87 @@ +# CLI Commands and Text File Formats + +## `go tool game` CLI + +Install the tool once per module: + +```sh +go get -tool github.com/nsgo-dev/game/packages/game/cmd/game@latest +``` + +### Project and development workflow + +| Command | Usage | Purpose | +| --- | --- | --- | +| `game new` | `game new [-name -module -template -version] ` | Scaffold a game project (`go.mod`, `game.yaml`, `nsgo.yaml`, starter code and tests) | +| `game dev` | `game dev [-assets -fps -target] [dir] [nsgo dev flags]` | Run `nsgo dev` with live asset hot reload (`hotreload.DevAssetsDir`) | +| `game generate` | `game generate [-in -autoload -main] component\|system\|scene\|prefab ` | Generate Go code, tests, `.scene.yaml` files and registrations into a project | +| `game editor` | `game editor [-library] [project-dir \| game.yaml \| scene.yaml] [clip.animation.yaml [object-id]]` | Open the scene and animation clip editor | +| `game check` | `game check [-in] [dir]` | Validate scenes, Tiled/LDtk maps, sprite atlases and every referenced file | +| `game index` | `game index [-dry-run -in] [dir]` | Assign stable UIDs to scene/resource files and update the project index | +| `game mv` | `game mv [-dry-run -in] ` | Move/rename a file or folder and rewrite every reference in the project | +| `game library` | `game library [-dir -index -kind -project] list\|install\|remove\|digest ...` | Browse and install digest-checked asset, plugin or template packs into `game.yaml` | + +### Asset pipeline + +| Command | Usage | Purpose | +| --- | --- | --- | +| `game assets` | `game assets [-in game.yaml -check -force]` | Incrementally build all atlases, textures, audio and manifests declared in `game.yaml` | +| `game pack` | `game pack -in [-out -name -padding -extrude -trim -max-width -max-height -scale]` | Pack a folder of PNGs into sprite atlas pages + TexturePacker JSON | +| `game audio` | `game audio -in -out [-format wav\|aac\|mp3 -rate -channels -bitrate -peak-db -rms-db]` | Normalize, resample and convert audio | +| `game tex` | `game tex [-format bc1\|bc3\|etc2\|rgba8 -mipmaps -srgb -o] ` | Encode textures into KTX2 containers | +| `game manifest` | `game manifest [-in assets -out -pkg -prefix -embed -embed-dir -check]` | Generate a typed Go asset manifest so missing assets fail compilation | +| `game credits` | `game credits [-in game.yaml -out file]` | Generate the asset author/license credits file from `.import.yaml` sidecars | + +### Testing, performance, shipping and shell support + +| Command | Usage | Purpose | +| --- | --- | --- | +| `game replay` | `game replay [-run Replay] [dir ...]` | Validate YAML input recordings and run their headless replay tests | +| `game bench` | `game bench [-baseline -bench -benchtime -count -in -update] [dir ...]` | Run headless benchmarks and fail on regressions against a YAML baseline | +| `game release` | `game release [-target -channel -output -jobs -release-notes -dry-run] [dir]` | Build release packages for `game.yaml` export presets via `nsgo build` with credits | +| `game completion` | `game completion zsh\|bash\|fish` | Output shell completion scripts | +| `game help` | `game help [command]` | Show commands or a subcommand's flags | + +### Companion module tools + +- `go run github.com/nsgo-dev/game/packages/game/cmd/gameschema` — regenerate or `-check` the published JSON Schemas (`scene.v1.json`, `scene.v2.json`, `import.v1.json`, `voxel.v1.json`). +- `go run github.com/nsgo-dev/game/packages/game/cmd/gameproject` — format (`fmt`) and validate `game.yaml` against `nsgo.yaml`. +- `go run github.com/nsgo-dev/game/packages/game/cmd/sizecheck` — check WebAssembly and mobile package size budgets. + +## Text file formats contract + +Every file authored by a human or coding agent is plain-text YAML: + +1. **Top-level `version` integer** (or `manifestVersion` in `mod.yaml`). Missing `version`, `version: 0`, or an unsupported future version is rejected. +2. **Strict schema validation.** Unknown keys, duplicate keys, and multi-document YAML streams are refused with `loaderr` errors naming file, line, field and fix. +3. **Canonical deterministic round-trip.** Encoders write fixed key order, sort unordered collections, and omit timestamps or random IDs so load -> save produces identical bytes. +4. **Editor & agent JSON Schemas.** Add `# yaml-language-server: $schema=...` headers (`https://game.nsgo.dev/schemas/scene.v1.json`, `scene.v2.json`, `import.v1.json` and `voxel.v1.json`) or validate programmatically via `tooling/jsonschema`. + +### Common authored YAML formats + +| File / pattern | Package | Purpose | +| --- | --- | --- | +| `game.yaml` | `project` | Project name/ID, window, virtual resolution, input map, audio buses, autoloads, asset targets, export presets (`version: 1`) | +| `.import.yaml` | `tooling/importsettings` | Per-asset texture filter, slicing, audio settings and license/author credits (`version: 1`) | +| `*.scene.yaml` | `sceneformat` | Scenes and prefabs: camera, layers, hierarchical objects, components and prefab instances (`version: 1`, or `version: 2` for a scene that instances or inherits other scene files) | +| `..yaml`, such as `stone.material.yaml` | `resource` | Shared resources; `type` is `material`, `curve`, `gradient`, `animation`, `theme`, `busLayout` or `physicsMaterial` (`version: 1`) | +| `*.replay.yaml` | `replay` | Editable deterministic input recordings (seed, step rate, per-step action/axis transitions; `version: 2`) | +| Any `.yaml` or `.yml` file, such as `weapons.yaml` | `tooling/datatable` | Typed game data tables (`version: 1`); `.csv` and `.json` exports load too, without a version | +| `mod.yaml` | `modding` | Mod metadata, capabilities and dependencies (`manifestVersion: 1`) | +| Gameplay YAML configs | `particles`, `skeletal`, `cutscene`, `rooms`, `worldmap`, `cards`, `stats`, `ability`, `inventory`, `quest`, `loot`, `achievements`, `leaderboard`, `fighting`, `framedata`, `platformer`, `vehicle`, `bullets`, `rts`, `procgen`, `vn`, `rhythm`, `idle`, `quality`, `voxel` | Domain-specific versioned YAML assets validated by each package's `Parse`/`Encode` | + +### Program-written text formats (YAML / JSON) + +- **YAML**: asset build cache (`tooling/assetbuild`), benchmark baselines (`tooling/bench`), achievement progress (`achievements`), latency calibrations (`rhythm`), ghost laps (`vehicle`), undo logs (`undo`), headless state dumps (`statedump`), project index (`refs`). +- **JSON**: versioned save slots & player settings (`save`), world map discovery (`worldmap`), quest snapshots (`quest`), fog state (`fog`), ECS world snapshots (`entities`), persisted input bindings (`input`), debug console tunables (`debug`), dev session state (`tooling/devstate`), cloud sync (`liveops`), string tables (`l10n`). + +### External tool exports read directly + +- **Tiled** `.tmj` maps and **LDtk** `.ldtk` projects (`tilemap`) +- **TexturePacker** and **Aseprite** JSON sprite atlases (`sprite`) +- **AngelCode BMFont** and **MSDF** fonts (`text`) +- **glTF 2.0** `.gltf` / `.glb` 3D models (`gltf`) +- **Yarn Spinner** `.yarn` dialogue scripts (`flow`) +- **Chrome trace** JSON profiler exports (`debug`) + +Binary files are used only for inherently binary media (PNG/KTX2 images, WAV/AAC/MP3 audio, fonts, glTF buffers) and network packets (`net`). diff --git a/skills/nsgo-game/references/mcp-tools.md b/skills/nsgo-game/references/mcp-tools.md new file mode 100644 index 00000000..48793a78 --- /dev/null +++ b/skills/nsgo-game/references/mcp-tools.md @@ -0,0 +1,187 @@ +# `game/mcp` Tool Reference + +`github.com/nsgo-dev/game/packages/game/mcp` registers game-specific MCP tools on NSGo's reactive graph through `github.com/nsgo-dev/nsgo/automation`. When the game runs under `go tool nsgo dev -automation` (or `go tool nsgo test`), `go tool nsgo mcp` serves these tools alongside NSGo's built-in view tools. In ordinary and release builds, `automation.Register` is a no-op. + +## Connecting an MCP client + +```sh +# One-time client setup +claude mcp add nsgo -- go tool nsgo mcp + +# Start the game with automation enabled +go tool nsgo dev -automation +``` + +## Wiring `mcp.Bridge` in Go + +Call `mcp.Attach(cx, cfg)` (or `mcp.New(cfg)` + `bridge.Attach(cx)`) on the engine goroutine. Every `mcp.Config` field is optional; tools remain registered until `cx` is disposed or `bridge.Detach()` is called. Use `*Func` getters when level restarts replace the active scene, world, loop, input actions, console, physics world, or asset manager. + +```go +bridge, err := mcp.Attach(cx, mcp.Config{ + // Scene & entity inspection (#461) + Scenes: g.scenes, // *scene.Manager + Scene: g.activeScene, // or SceneFunc: func() *scene.Scene + SceneName: func(c *scene.Controller) string { return c.ID }, // optional display names + NamedScenes: map[string]*scene.Scene{"title": g.title}, + WorldFunc: func() *entities.World { return g.world }, + EntityName: func(e entities.Entity) string { return g.names[e] }, + EntityTags: func(e entities.Entity) []string { return g.tags[e] }, + EntityLayer: func(e entities.Entity) string { return g.layers[e] }, + + // Fixed-step loop & seeding (#462) + Loop: g.loop, // or LoopFunc: func() *game.Loop + Random: g.rng, // *random.Stream + RandomStreams: g.rngs, // *random.Streams + SetSeed: g.resetSeed, + + // Input at game coordinates (#463) + Actions: g.actions, // or ActionsFunc: func() *input.Actions + Viewport: &g.viewport, + ViewSizeFunc: func() core.Size { return g.viewSize }, + OnPointer: g.handlePointer, + + // Prefabs for live spawning (#464) + Prefabs: map[string]mcp.PrefabSpawner{"slime": g.spawnSlime}, + + // Screenshots & diagnostic overlays (#465) + Physics: g.physics, // or PhysicsFunc + RigidPhysics: g.rigidPhysics, // or RigidPhysicsFunc + DrawFrame: g.drawFrame, + CaptureFrame: g.captureFrame, + ScreenshotDir: g.screenshotDir, + ScreenshotBackground: core.RGB(0x0f172a), + + // Debug tunables & console (#466) + Console: g.console, // or ConsoleFunc: func() *debug.Console + + // Input recording & replay (#467) + Replay: g.replayCtrl, // *mcp.ReplayController (implements replay.ActionSource) + + // Performance telemetry (#468) + Overlay: g.overlay, // *debug.Overlay + Profiler: g.profiler, // *debug.Profiler + GC: g.gcMon, // *debug.GCMonitor + Memory: g.memTrack, // *debug.MemoryTracker + DrawStatsFunc: g.drawStats, + RenderStatsFunc: g.render3DStats, + + // Assets & hot reload (#469) + Assets: g.assets, // or AssetsFunc: func() *assets.Manager + Resources: g.resources, // *resource.Library + Shaders: g.shaders, // *hotreload.ShaderReloader + Materials: g.materials, // *hotreload.MaterialReloader + ReloadAsset: g.reloadAsset, +}) +``` + +Additional registration helpers on `*mcp.Bridge`: + +- `mcp.RegisterComponent[T](bridge, name)` / `mcp.RegisterComponentFunc(bridge, name, read)` — expose transient/non-codec components for inspection (built-in `"transform2d"`, `"world_transform2d"`, and `"object_ref"` plus `entities.RegisterCodec` components are readable automatically; `NaN`/`±Inf`/funcs/chans/cycles are safely sanitized). +- `bridge.RegisterPrefab(name, spawner)`, `bridge.RegisterEntityPrefab(p)`, `bridge.RegisterScenePrefab(name, doc)` — register prefabs for `game_entity_spawn`. +- `bridge.RegisterAsset(mcp.CustomAsset{...})`, `bridge.RegisterAtlas(key, group, jsonPath, atlas, readFile)` — expose standalone assets for `game_assets_list` and `game_asset_reload`. + +All MCP tools strictly refuse unknown JSON argument fields. + +## Tool catalog + +### 1. Scene, layer, entity and component inspection + +| Tool | Arguments | Returns | +| --- | --- | --- | +| `game_scenes_list` | `{}` | Active scene stack (bottom to top), `current`, `stack_depth`, `transitioning`/`progress`, layer counts, camera state and inactive `NamedScenes` | +| `game_layers_list` | `scene` (opt), `include_hidden` (opt, default `true`) | Scene layers in draw order (`index`, `draw_index`, `name`, `space`, `visible`, `order`, `parallax_x`/`parallax_y`, offsets, repeat, `depth_sort`, item/batch/sprite/tilemap/drawable counts) | +| `game_entities_list` | `component`, `layer`, `name` (substring), `tag`, `parent` (ref or `"root"`), `include_components` (default `false`), `offset`, `limit` | Live entities in ascending slot order with `total`, `returned`, stable generational `ref` (`"entity::"`), metadata, `parent`, `child_count`, `components` names and optional `values` | +| `game_entity_inspect` | `ref` (req) | One live entity's `ref`, `index`, `generation`, `name`, `layer`, `tags`, `parent`, `children` refs and all readable `components` values | +| `game_component_get` | `ref` (req), `component` (req) | Serialized `value` of one component on a live entity | + +Stable entity references use `"entity::"` (`mcp.FormatEntityRef` / `mcp.ParseEntityRef`). Stale references to destroyed or recycled slots return a `"not alive"` error. + +### 2. Fixed-step loop control and seeding + +| Tool | Arguments | Returns | +| --- | --- | --- | +| `game_loop_status` | `{}` | `paused`, effective `time_scale`, `step_seconds`, `step_hz`, `steps`, `game_time_seconds`, `seed_configured` | +| `game_loop_pause` | `{}` | Pauses `Loop` without catch-up backlog; returns updated loop status | +| `game_loop_resume` | `{}` | Resumes `Loop`; returns updated loop status | +| `game_loop_step` | `count` (opt, default `1`, `1..3600`) | Synchronously runs `count` fixed updates (`Loop.StepNow`) and one `Draw`; returns `steps_advanced`, `total_steps`, `game_time_seconds`, `delta_seconds`, `paused` (60 steps at 60 Hz advances exactly `1.0` s) | +| `game_loop_time_scale` | `time_scale` (req, finite `>= 0`; `0` resets to `1x`) | Updates `Loop.TimeScale`; returns updated loop status | +| `game_loop_seed` | `seed` (req, uint64) | Re-seeds `Random`, `RandomStreams` and/or `SetSeed`; returns `{seed}` | + +### 3. Input injection at game coordinates + +| Tool | Arguments | Returns | +| --- | --- | --- | +| `game_input_action` | `name` (req), `mode` (`"press"` \| `"release"` \| `"tap"`, default `"tap"`), `value` (opt, `-1..1`) | Injects action hold/release/single-step tap or analog value into `input.Actions`; returns current step state (`pressed`, `just_pressed`, `just_released`, `axis`) | +| `game_input_axis` | `name` (opt), `value` (`-1..1`), `axes` (map of name -> `-1..1`), `clear` (opt bool) | Sets or clears 1D/2D analog axes in `input.Actions`; returns `{axes, cleared}` | +| `game_input_pointer` | `x` (req), `y` (req), `action` (`"press"` \| `"release"` \| `"move"` \| `"click"`, default `"click"`), `space` (`"game"` \| `"world"`, default `"game"`), `button` (`"left"` \| `"right"` \| `"middle"`, default `"left"`) | Maps coordinates through `screen.Viewport` and active camera, dispatches to `input.Actions`, `scene.Scene.HitTest`/`DispatchPress`, and `Config.OnPointer`; returns mapped coordinates and topmost hit details | +| `game_input_actions_list` | `{}` | `configured`, all registered `actions` (with step states and binding counts) and `axes` | + +### 4. Live entity spawning, destruction and component editing + +| Tool | Arguments | Returns | +| --- | --- | --- | +| `game_prefabs_list` | `{}` | Registered prefabs (`name`, `kind`: `"custom"`, `"entity_prefab"`, `"scene"`) | +| `game_entity_spawn` | `prefab` (opt), `overrides` (opt object), `parent` (opt ref), `x` (opt), `y` (opt), `components` (opt map) | Spawns a registered prefab or empty entity, returns `ref`, metadata, hierarchy links and initial `components` | +| `game_entity_destroy` | `ref` (req), `policy` (opt: `"cascade"` \| `"orphan"` \| `"keep_world"` \| `"reparent"`) | Destroys the entity and reports `destroyed` count | +| `game_component_set` | `ref` (req), `component` (req), `value` (req), `replace` (opt bool, default `false` patches existing fields) | Updates a live component so the next step observes the new value; returns `{ref, component, value}` | +| `game_component_remove` | `ref` (req), `component` (req) | Removes one component from a live entity; returns `{ref, component, removed}` | + +### 5. Screenshots and diagnostic overlays + +| Tool | Arguments | Returns | +| --- | --- | --- | +| `game_screenshot` | `scene` (opt), `width`/`height` (opt pair, `1..8192`), `format` (`"png"`), `path` (opt relative path inside `ScreenshotDir`), top-level booleans or `overlays` object (`bounds`, `collision_shapes` / `physics`, `grid`, `grid_step`, `camera`, `labels`) | Captures the game view as PNG (`png_base64` or written `path`), with `width`, `height`, `bytes` and `overlays_drawn` counts | + +### 6. Debug tunables and console commands + +| Tool | Arguments | Returns | +| --- | --- | --- | +| `game_tunables_list` | `prefix` (opt) | Sorted debug console tunables (`name`, `type`, `value`, `default`, `min`, `max`) | +| `game_tunable_get` | `name` (req) | One tunable's current value, type, default and bounds | +| `game_tunable_set` | `name` (req), `value` (req), `clamp` (opt bool, default `false`) | Validates type/bounds (or clamps), updates tunable and returns `old_value`, `value`, `clamped` | +| `game_console_commands_list` | `include_builtin` (opt, default `true`) | Built-in (`clear`, `get`, `help`, `list`, `set`) and custom debug console commands | +| `game_console_exec` | `command` (req) | Executes a console command line; returns `ok`, `output`, `lines`, `error` | + +### 7. Input recording and deterministic replay + +| Tool | Arguments | Returns | +| --- | --- | --- | +| `game_replay_status` | `{}` | Current recording/playback status, frame progress and `saved_recordings` | +| `game_replay_record_start` | `name` (opt), `seed` (opt), `step_rate` (opt), `actions` (opt), `axes` (opt), `metadata` (opt), `reset` (opt bool) | Begins recording per-step inputs via `ReplayController` | +| `game_replay_record_stop` | `name` (opt), `save_path` (opt relative path under `ReplayConfig.SaveDir`) | Stops recording, stores it and returns deterministic YAML (`yaml`), frame/event summary and `saved_path` | +| `game_replay_play` | `name` OR `yaml` (one required), `run_to_end` (opt bool), `steps` (opt int, exclusive with `run_to_end`), `reset` (opt bool, default `true` when `ResetFunc` is set) | Replays a stored or inline YAML recording, optionally advancing frames synchronously | +| `game_replay_stop` | `{}` | Stops active replay playback | +| `game_replay_list` | `{}` | Lists stored recordings with `frames`, `seed`, `step_rate`, `events`, `actions`, `axes`, `metadata` | + +### 8. Performance telemetry + +| Tool | Arguments | Returns | +| --- | --- | --- | +| `game_perf_readout` | `include_history` (opt), `history_limit` (opt), `include_zones` (opt), `zones_limit` (opt) | `fps`, `frame_ms`/`update_ms`/`draw_ms`, percentiles (`p50`/`p95`/`p99`), `draw_calls`/`sprites`/`batches`/`triangles`, `allocs_per_frame`, heap/GC stats, `render3d`, `asset_memory`, optional `history` and `zones` | +| `game_perf_zones` | `limit` (opt) | Named `debug.Profiler` zones sorted by recent cost (`last_ms`, `avg_ms`, `max_ms`, `calls`) | +| `game_perf_reset` | `{}` | Resets overlay frame stats, draw stats, profiler zones and GC monitor history | + +### 9. Assets and live hot reload + +| Tool | Arguments | Returns | +| --- | --- | --- | +| `game_assets_list` | `group` (opt), `state` (`"loaded"` \| `"loading"` \| `"unloaded"` \| `"failed"`), `kind` (opt) | Asset groups, states, asset entries (`key`, `kind`, `uri`, `loaded`, `bytes`, `frames`) and `total_bytes` | +| `game_asset_reload` | `key` (asset name/URI/path, req unless `all: true`), `group` (opt), `all` (opt bool) | Reloads one asset (or all loaded assets) in place; surfaces parse/compile errors cleanly | +| `game_assets_reload_group` | `group` (req) | Reloads every loaded asset in a group and reports per-asset results and errors | + +## Headless verification in `nsgotest` + +Call registered MCP tools directly inside Go tests with `automation.Call`: + +```go +var ( + raw json.RawMessage + err error +) +app.Post(func() { + raw, err = automation.Call(cx, t.Context(), mcp.ToolLoopStep, json.RawMessage(`{"count":60}`)) +}) +app.Settle() +``` + +Every tool above is always registered once the Bridge is attached. A tool whose subsystem is not configured in `mcp.Config` returns an error naming what is missing, such as `mcp: no game loop configured` or `mcp: no debug console configured`, so wire the matching `Config` field before calling it. diff --git a/skills/nsgo-game/references/packages.md b/skills/nsgo-game/references/packages.md new file mode 100644 index 00000000..5c9bf719 --- /dev/null +++ b/skills/nsgo-game/references/packages.md @@ -0,0 +1,154 @@ +# Package Catalog + +Every non-internal package under `github.com/nsgo-dev/game/packages` (shown relative to that prefix). **Stable** packages only break in minor releases after a deprecation period and never import experimental packages; **Experimental** packages may change in minor releases. + +## Core, math and timing + +| Package | Status | Purpose | +| --- | --- | --- | +| `game` | Stable | Fixed-step `Loop` (`Rate`, `Update`, `Draw`, `Paused`, `TimeScale`, `Step`, `StepNow`, `Steps`, `ElapsedSeconds`) | +| `game/math2d` | Stable | Shared 2D `Vec2`, `Rect`, `Circle`, `Affine` types with lossless `core` conversions | +| `game/random` | Stable | Seeded deterministic `Stream` and named `Streams` with `SetSeed` | +| `game/screen` | Stable | Virtual resolution `Viewport` scaling, pixel snapping, safe areas, video settings | +| `game/flow` | Stable | Game-clock `Timers`, `Machine[S]`, `Seq`/`Parallel`/`Race`, typed event `Bus`, Yarn dialogue | +| `game/tween` | Stable | Fixed-step `Tween`, `Timeline`, easing functions and camera choreography | +| `game/animclip` | Experimental | Property-keyed animation clips played on scene objects through `tween.Timeline` | +| `game/loaderr` | Stable | Structured load errors with file, line, field and actionable fix hints | + +## 2D rendering, scenes, ECS and assets + +| Package | Status | Purpose | +| --- | --- | --- | +| `game/sprite` | Stable | Atlases (TexturePacker/Aseprite), frames, animations, sprites, effects and `Batch` drawing | +| `game/tilemap` | Stable | 2D `Camera`, culled tilemaps, Tiled `.tmj` and LDtk loaders, animated tiles, raycasts | +| `game/scene` | Stable | World/screen layers, parallax, hit testing, `DispatchPress`, scene stacks and transitions | +| `game/sceneformat` | Experimental | Plain-text YAML `.scene.yaml` documents, validation, prefab resolution and `SpawnEntities` | +| `game/entities` | Experimental | Generational ECS `World`, typed component stores, `Transform2D`/`Hierarchy2D`, `Prefab`, codecs | +| `game/assets` | Experimental | Async per-scene asset groups, `Manager`, reactive loading progress, `LoadingScreen`, DLC manifests | +| `game/resource` | Experimental | Shared YAML resources (materials, curves, gradients, clips, UI themes, physics materials) and `Library` | +| `game/text` | Experimental | AngelCode BMFont bitmap fonts, 2D/3D MSDF/SDF fonts and `DrawPlatform` | +| `game/particles` | Experimental | Seeded deterministic 2D `Emitter`, spawn shapes, bursts and YAML definitions | +| `game/lights2d` | Experimental | 2D ambient darkness, point/cone lights, visibility-polygon shadows, normal-mapped sprites | +| `game/effects` | Experimental | Chained Kage shader post-processing passes over the game frame | +| `game/skeletal` | Experimental | 2D bone rigs, IK, skins and YAML rig definitions | +| `game/cutscene` | Experimental | Skippable video cutscenes over the game view from YAML | +| `game/placeholder` | Experimental | CC0 prototyping pack (sprites, tiles, pixel font, sounds, glTF models) with import sidecars | + +## Input, 2D physics, audio and UI + +| Package | Status | Purpose | +| --- | --- | --- | +| `game/input` | Stable | Named `Actions` and axes across keyboard, mouse, touch, pointer-lock and gamepads; `core.Storage` bindings | +| `game/physics` | Stable | `Box`/`Circle` overlaps, `MoveAndSlide` tile resolution, `World`, `CharacterBody`, `RigidWorld` | +| `game/sound` | Stable | `Mixer`, sound effects, music playback, bus routing, 3D positional audio and pause-with-game | +| `game/gameui` | Experimental | In-canvas box-layout menus, virtual-resolution scaling, spatial focus nav, world-anchored views | +| `game/a11y` | Experimental | Live captions, color-blind palettes, CVD simulation, assist options, accessible menus | +| `game/l10n` | Experimental | JSON string tables with CLDR plurals, script `FontSet`, RTL ordering, localized asset catalogs | +| `game/quality` | Experimental | Low/medium/high quality presets from device class and measured frame times | + +## 3D stage + +| Package | Status | Purpose | +| --- | --- | --- | +| `game/math3d` | Experimental | 3D vectors, matrices, quaternions, transforms, AABBs, rays and frustums | +| `game/scene3d` | Experimental | 3D node tree, sockets/attachments, dynamic BVH, Orbit/FPS/ThirdPerson cameras, picking, decals | +| `game/render3d` | Experimental | GPU mesh buffers, textures/samplers, culling, sorting, 0-alloc instancing, LODs, gizmos, trails, `RenderStats` | +| `game/anim3d` | Experimental | 3D pose state machines, 1D/2D blend spaces, bone masks, clip events, IK, root motion | +| `game/physics3d` | Experimental | 3D rigid bodies, shapes, raycasts, sweeps and character movement | +| `game/world3d` | Experimental | Heightmap terrain, multi-level 3D navmeshes, 3D `GridMap`, foliage, floating-origin streaming | +| `game/voxel` | Experimental | Chunked 3D voxel worlds, greedy meshing, cross-chunk AO, DDA raycasting, YAML saves | +| `game/gltf` | Experimental | glTF 2.0 (`.gltf`/`.glb`) loader for meshes, materials, skins and animations | +| `game/vehicle` | Experimental | Raycast cars on `physics3d`, suspension, tire friction, checkpoints, laps and YAML lap ghosts | + +## Gameplay and genre kits + +| Package | Status | Purpose | +| --- | --- | --- | +| `game/ai` | Stable | Grid `AStar`, 2D `NavMesh`, steering behaviors and behavior trees | +| `game/platformer` | Experimental | Platformer `Controller` (coyote time, jump buffer, variable jump, wall slide/jump) from YAML | +| `game/bullets` | Experimental | Pooled shooter bullet patterns (rings, spirals, aimed bursts) from YAML | +| `game/cards` | Experimental | Board slot drag-and-drop, fanned hands, decks, piles, grids and YAML boards | +| `game/rooms` | Experimental | Room maps with per-room camera bounds and cut/slide/fade transitions | +| `game/worldmap` | Experimental | YAML room maps, saved discovery/markers, minimap and world map | +| `game/fog` | Experimental | Per-team shadowcast fog of war, explored vs visible cells, map overlay, JSON saves | +| `game/rts` | Experimental | Flow fields, `Crowd` separation, YAML formations, box selection and control groups | +| `game/procgen` | Experimental | Seeded BSP rooms, cellular-automata caves and wave function collapse from YAML rules | +| `game/rhythm` | Experimental | YAML beat maps, audio-clock music timing and per-device A/V latency calibration | +| `game/undo` | Experimental | Reversible moves with unlimited undo/redo/`Seek` and YAML `Log` | +| `game/fighting` | Experimental | Per-step input buffer, numpad motion inputs, charges, chords and combos from YAML | +| `game/framedata` | Experimental | Fighting game per-frame hitboxes, hurtboxes, hitstun and cancel windows in YAML | +| `game/stats` | Experimental | Base stats with sourced add/mul/override modifiers, timed modifiers and YAML configs | +| `game/inventory` | Experimental | YAML item catalogs, stacking containers, typed equipment slots and snapshots | +| `game/ability` | Experimental | YAML ability sets and per-step `Caster` (costs, cooldowns, charges, cast/channel times) | +| `game/quest` | Experimental | YAML quest books with objectives, prerequisites, rewards and event-bus progression | +| `game/loot` | Experimental | Nested weighted drop tables in YAML with guaranteed drops and hard/soft pity | +| `game/vn` | Experimental | Visual novel presenter (YAML cast, portraits, typewriter text, choices, backlog, auto/skip) | +| `game/vn/cmd/vnsample` | Experimental | Sample executable demonstrating `game/vn` | +| `game/idle` | Experimental | Big `Number` beyond float64, capped offline progress and localized formatting | + +## Persistence, networking, liveops and modding + +| Package | Status | Purpose | +| --- | --- | --- | +| `game/save` | Stable | Versioned JSON save slots, schema migrations, player settings and atomic backup recovery | +| `game/net` | Experimental | Cross-target WebSocket/UDP/loopback transports, snapshot replication, lockstep/rollback | +| `game/server` | Experimental | Headless fixed-step `Runner` for dedicated game servers with multiple match loops | +| `game/server/cmd/dedicatedserver` | Experimental | Example dedicated server binary built on `game/server` | +| `game/liveops` | Experimental | Cloud sync interfaces (`CloudSync`), conflict handling and liveops helpers | +| `game/accounts` | Experimental | Self-hosted player accounts, guest upgrades, OAuth/email, argon2id passwords | +| `game/accounts/cmd/accountsd` | Experimental | Self-hosted accounts daemon | +| `game/accounts/pgstore` | Experimental | PostgreSQL store backend for `game/accounts` | +| `game/accounts/sqlitestore` | Experimental | SQLite store backend for `game/accounts` | +| `game/accounts/sqlstore` | Experimental | Shared SQL helpers for `game/accounts` stores | +| `game/accounts/storetest` | Experimental | Conformance test suite for `game/accounts` stores | +| `game/accounts/token` | Experimental | Ed25519 account tokens verified offline by game servers | +| `game/cloudsave` | Experimental | Self-hosted HTTPS cloud save service behind `liveops.CloudSync` | +| `game/cloudsave/cmd/cloudsaved` | Experimental | Self-hosted cloud save daemon | +| `game/cloudsave/sqlstore` | Experimental | SQL store backend for `game/cloudsave` | +| `game/cloudsave/storetest` | Experimental | Conformance test suite for `game/cloudsave` stores | +| `game/achievements` | Experimental | YAML achievement definitions, monotonic `core.Storage` progress, Game Center / Play Games | +| `game/leaderboard` | Experimental | YAML leaderboards for Game Center and Play Games | +| `game/leaderboard/selfhost` | Experimental | Self-hosted cross-platform leaderboards (all-time/daily/weekly, signed scores) | +| `game/leaderboard/selfhost/cmd/leaderboardd` | Experimental | Self-hosted leaderboard daemon | +| `game/presence` | Experimental | Provider-neutral rich presence (`Activity`, `Manager`) on Steam and Discord | +| `game/modding` | Experimental | Capability-sandboxed TSX `"game"` modding API and `mod.yaml` lifecycle manager | + +## Debugging, testing, MCP and editor + +| Package | Status | Purpose | +| --- | --- | --- | +| `game/debug` | Experimental | Frame-time `Overlay`, `Profiler`, `GCMonitor`, `MemoryTracker`, `Console` tunables, wireframe debug draw (`-tags release` stripped) | +| `game/mcp` | Experimental | `Bridge` registering game MCP tools with `nsgo/automation` for `nsgo mcp` and `nsgotest` | +| `game/replay` | Experimental | `Recorder`/`Player`, editable YAML recordings and deterministic replay assertions | +| `game/statedump` | Experimental | Headless deterministic YAML state dumps and line diffs between runs | +| `game/gametest` | Experimental | Testing helpers and fixtures for game-layer tests | +| `game/perf` | Experimental | Zero-alloc `Pool`/`Arena`/`SlicePool`, `SpatialHash`, `Quadtree` and `CullBatch` | +| `game/editor` | Experimental | Visual scene and animation clip editor embedded behind `go tool game editor` | + +## Project, CLI and asset tooling + +| Package | Status | Purpose | +| --- | --- | --- | +| `game/project` | Experimental | `game.yaml` parser, canonical encoder and `nsgo.yaml` consistency checker | +| `game/refs` | Experimental | Stable file UIDs, project index and reference-rewriting file moves | +| `game/cmd/game` | Experimental | The `go tool game` CLI | +| `game/cmd/gameapi` | Experimental | Generates API reference JSON from package doc comments | +| `game/cmd/gameproject` | Experimental | Formats and checks `game.yaml` against `nsgo.yaml` | +| `game/cmd/gameschema` | Experimental | Generates and checks published JSON Schemas for YAML formats | +| `game/cmd/sizecheck` | Experimental | Verifies WebAssembly and mobile package size budgets | +| `game/cmd/wasmprobe` | Experimental | Probe app used to measure WebAssembly binary size per package | +| `game/tooling/apiref` | Experimental | Go doc parser powering `cmd/gameapi` | +| `game/tooling/assetbuild` | Experimental | Incremental asset pipeline driven by `game.yaml` | +| `game/tooling/assetcheck` | Experimental | Validator for scenes, Tiled/LDtk maps, atlases and file references | +| `game/tooling/audioconv` | Experimental | WAV normalization, resampling and WAV/AAC/MP3 conversion | +| `game/tooling/bench` | Experimental | Headless benchmark runner and baseline regression checker | +| `game/tooling/credits` | Experimental | Asset license/author credits generator from `.import.yaml` sidecars | +| `game/tooling/datatable` | Experimental | Typed YAML/CSV/JSON data tables with cell-level errors and hot reload | +| `game/tooling/devstate` | Experimental | Dev session state snapshots persisted across reloads | +| `game/tooling/hotreload` | Experimental | Asset, 3D shader (`ShaderReloader`) and material (`MaterialReloader`) hot reload | +| `game/tooling/importsettings` | Experimental | `.import.yaml` sidecar parser and encoder | +| `game/tooling/jsonschema` | Experimental | JSON Schema builder and validator with JSON Pointer error paths | +| `game/tooling/ktx2` | Experimental | KTX2 texture encoder (BC1, BC3, ETC2, RGBA8, mipmaps, sRGB) | +| `game/tooling/library` | Experimental | Digest-verified asset, plugin and template pack registry | +| `game/tooling/manifest` | Experimental | Typed Go asset manifest generator (`asset:` URIs or `//go:embed`) | +| `game/tooling/pack` | Experimental | PNG sprite atlas packer outputting PNG pages and TexturePacker JSON |