import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { createEngine, type SceneDef } from "@nengine/core"; import { createEngineNamespaces, McpGateway } from "../src/index.js"; const TIME_YAML = [ "id: default", "dayLengthTicks: 480", "seasons:", " - { name: spring, dayCount: 28 }", "start: { day: 1, season: spring }", "", ].join("\n"); const FARM_YAML = [ "id: farm", "width: 2", "height: 2", 'tilesetRef: "tiles"', "spawn: { x: 0, y: 0 }", "layers:", " - name: ground", " data:", " - [a, b]", " - [b, a]", "", ].join("\n"); const CHICKEN_YAML = [ "id: chicken", "stages:", " - { name: chick, days: 2, feedRequired: false }", "produces:", " - { itemId: egg, qty: 1 }", "", ].join("\n"); interface Setup { engine: ReturnType; gateway: McpGateway; tmp: string; close: () => Promise; } async function setup(): Promise { const tmp = await mkdtemp(join(tmpdir(), "scene-ns-")); await mkdir(join(tmp, "maps"), { recursive: true }); await mkdir(join(tmp, "animals"), { recursive: true }); await writeFile(join(tmp, "time.yaml"), TIME_YAML); await writeFile(join(tmp, "maps", "farm.yaml"), FARM_YAML); await writeFile(join(tmp, "animals", "chicken.yaml"), CHICKEN_YAML); const engine = createEngine({ contentDir: tmp }); const gateway = new McpGateway(); for (const namespace of createEngineNamespaces(engine, { gateway })) { gateway.register(namespace); } await engine.start(); return { engine, gateway, tmp, close: async () => { await engine.stop(); await rm(tmp, { recursive: true, force: true }); }, }; } async function callText(gateway: McpGateway, name: string, args: Record = {}): Promise<{ ok: boolean; text: string; }> { const result = await gateway.callTool(name, args); return { ok: result.isError !== true, text: result.content[0]?.text ?? "" }; } const FARM_START_DEF: SceneDef = { id: "farm-start", entities: [ { type: "npc", npcId: "mayor", x: 1, y: 1, dialogue: "welcome", label: "Mayor" }, { type: "animal", animalId: "chicken", x: 0, y: 1 }, ], }; describe("scene namespace", () => { it("scene.create writes content/scenes/.yaml, registers live, and seeds on restart", async () => { const { engine, gateway, tmp, close } = await setup(); try { const created = await callText(gateway, "scene.create", { def: FARM_START_DEF }); expect(created.ok).toBe(true); expect(JSON.parse(created.text) as SceneDef).toEqual(FARM_START_DEF); expect(engine.registry.get("scene", "farm-start")).toEqual(FARM_START_DEF); const file = await readFile(join(tmp, "scenes", "farm-start.yaml"), "utf8"); expect(file).toContain("id: farm-start"); expect(file).toContain("npcId: mayor"); expect(engine.world.get("mayor")).toBeUndefined(); await engine.stop(); const reloaded = createEngine({ contentDir: tmp }); await reloaded.start(); try { expect(reloaded.registry.get("scene", "farm-start")).toEqual(FARM_START_DEF); expect(reloaded.world.get("mayor")).toMatchObject({ id: "mayor", type: "npc", x: 1, y: 1 }); expect(reloaded.world.get("animal:chicken:1")).toMatchObject({ type: "animal", animalId: "chicken" }); } finally { await reloaded.stop(); } } finally { await close(); } }); it("scene.validate accepts a valid def and rejects an invalid one", async () => { const { gateway, close } = await setup(); try { const valid = await callText(gateway, "scene.validate", { def: FARM_START_DEF }); expect(valid.ok).toBe(true); expect(JSON.parse(valid.text)).toEqual(FARM_START_DEF); const invalid = await callText(gateway, "scene.validate", { def: { id: "bad", entities: [{ type: "plot", x: 0, y: 0 }] }, }); expect(invalid.ok).toBe(false); expect(invalid.text).toMatch(/Invalid discriminator value/); expect(invalid.text).toMatch(/entities/); const negative = await callText(gateway, "scene.validate", { def: { id: "bad", entities: [{ type: "npc", npcId: "m", x: -1, y: 0 }] }, }); expect(negative.ok).toBe(false); expect(negative.text).toMatch(/x/); } finally { await close(); } }); it("scene.create rejects an invalid def and does not write or register", async () => { const { engine, gateway, tmp, close } = await setup(); try { const bad = await callText(gateway, "scene.create", { def: { id: "broken", entities: [{ type: "npc", npcId: "m", x: 0 }] }, }); expect(bad.ok).toBe(false); expect(engine.registry.get("scene", "broken")).toBeUndefined(); await expect(readFile(join(tmp, "scenes", "broken.yaml"))).rejects.toThrow(); } finally { await close(); } }); it("duplicate scene.create overwrites the existing definition", async () => { const { engine, gateway, tmp, close } = await setup(); try { await callText(gateway, "scene.create", { def: FARM_START_DEF }); const recreated = await callText(gateway, "scene.create", { def: { id: "farm-start", entities: [{ type: "npc", npcId: "villager", x: 0, y: 0 }] }, }); expect(recreated.ok).toBe(true); const current = engine.registry.get("scene", "farm-start"); expect(current?.entities).toEqual([{ type: "npc", npcId: "villager", x: 0, y: 0 }]); const file = await readFile(join(tmp, "scenes", "farm-start.yaml"), "utf8"); expect(file).toContain("npcId: villager"); } finally { await close(); } }); it("scene.update merges a patch, validates, rewrites the file, and re-registers", async () => { const { engine, gateway, tmp, close } = await setup(); try { await callText(gateway, "scene.create", { def: FARM_START_DEF }); const updated = await callText(gateway, "scene.update", { id: "farm-start", patch: { entities: [{ type: "building", buildingId: "shed", x: 0, y: 0 }] }, }); expect(updated.ok).toBe(true); const def = JSON.parse(updated.text) as SceneDef; expect(def.entities).toEqual([{ type: "building", buildingId: "shed", x: 0, y: 0 }]); expect(def.id).toBe("farm-start"); const file = await readFile(join(tmp, "scenes", "farm-start.yaml"), "utf8"); expect(file).toContain("buildingId: shed"); const missing = await callText(gateway, "scene.update", { id: "nope", patch: { entities: [] } }); expect(missing.ok).toBe(false); expect(missing.text).toMatch(/scene not found: nope/); const badPatch = await callText(gateway, "scene.update", { id: "farm-start", patch: { entities: "nope" } }); expect(badPatch.ok).toBe(false); expect(badPatch.text).toMatch(/entities/); expect(engine.registry.get("scene", "farm-start")?.entities).toEqual([ { type: "building", buildingId: "shed", x: 0, y: 0 }, ]); } finally { await close(); } }); it("scene.list returns one-line summaries", async () => { const { gateway, close } = await setup(); try { await callText(gateway, "scene.create", { def: FARM_START_DEF }); await callText(gateway, "scene.create", { def: { id: "farm-empty", entities: [] }, }); const listed = await callText(gateway, "scene.list"); expect(listed.ok).toBe(true); expect(JSON.parse(listed.text)).toEqual({ scenes: [ { id: "farm-start", entityCount: 2 }, { id: "farm-empty", entityCount: 0 }, ], }); } finally { await close(); } }); it("scene.get returns the full def; unknown id is an error result", async () => { const { gateway, close } = await setup(); try { await callText(gateway, "scene.create", { def: FARM_START_DEF }); const got = await callText(gateway, "scene.get", { sceneId: "farm-start" }); expect(got.ok).toBe(true); expect(JSON.parse(got.text)).toEqual(FARM_START_DEF); const missing = await callText(gateway, "scene.get", { sceneId: "nope" }); expect(missing.ok).toBe(false); expect(missing.text).toMatch(/scene not found: nope/); } finally { await close(); } }); it("resources: scene://catalog and scene://{id}; missing id rejects", async () => { const { engine, gateway, close } = await setup(); try { await callText(gateway, "scene.create", { def: FARM_START_DEF }); const catalog = await gateway.readResource("scene://catalog"); expect(JSON.parse(catalog.contents[0]?.text ?? "{}")).toEqual({ scenes: [FARM_START_DEF] }); const single = await gateway.readResource("scene://farm-start"); expect(JSON.parse(single.contents[0]?.text ?? "{}")).toEqual(FARM_START_DEF); await expect(gateway.readResource("scene://missing")).rejects.toThrow(/scene not found: missing/); expect(engine.registry.get("scene", "missing")).toBeUndefined(); } finally { await close(); } }); it("serves the scene.create-prompt prompt", async () => { const { gateway, close } = await setup(); try { const prompt = await gateway.getPrompt("scene.create-prompt", {}); const text = prompt.messages[0]?.content.text ?? ""; expect(text).toContain("building"); expect(text).toContain("npc"); expect(text).toContain("animal"); expect(text).toContain("scene.validate"); expect(text).toContain("content/scenes/.yaml"); expect(text).toContain("overlap"); } finally { await close(); } }); });