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 AnimalDef, type GrowthSystem } 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_DEF = { id: "chicken", stages: [ { name: "chick", days: 2, feedRequired: false }, { name: "grown", days: 2, feedRequired: true }, { name: "laying", days: 1, feedRequired: true }, ], produces: [{ itemId: "egg", qty: 1 }], }; interface Setup { engine: ReturnType; gateway: McpGateway; tmp: string; close: () => Promise; } async function setup(): Promise { const tmp = await mkdtemp(join(tmpdir(), "farm-animal-ns-")); await mkdir(join(tmp, "maps"), { recursive: true }); await writeFile(join(tmp, "time.yaml"), TIME_YAML); await writeFile(join(tmp, "maps", "farm.yaml"), FARM_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 ?? "" }; } function growthOf(engine: ReturnType): GrowthSystem { const growth = engine.systems.get("growth"); if (!growth) throw new Error("growth system not booted"); return growth; } describe("animal namespace", () => { it("animal.create writes content/animals/.yaml, registers live, and persists across restart", async () => { const { engine, gateway, tmp, close } = await setup(); try { const created = await callText(gateway, "animal.create", { def: CHICKEN_DEF }); expect(created.ok).toBe(true); expect(JSON.parse(created.text) as AnimalDef).toEqual(CHICKEN_DEF); expect(engine.registry.get("animal", "chicken")).toEqual(CHICKEN_DEF); const file = await readFile(join(tmp, "animals", "chicken.yaml"), "utf8"); expect(file).toContain("id: chicken"); expect(file).toContain("feedRequired: true"); await engine.stop(); const reloaded = createEngine({ contentDir: tmp }); await reloaded.start(); try { expect(reloaded.registry.get("animal", "chicken")).toEqual(CHICKEN_DEF); } finally { await reloaded.stop(); } } finally { await close(); } }); it("animal.validate accepts a valid def and rejects an invalid one", async () => { const { gateway, close } = await setup(); try { const valid = await callText(gateway, "animal.validate", { def: CHICKEN_DEF }); expect(valid.ok).toBe(true); expect(JSON.parse(valid.text)).toEqual(CHICKEN_DEF); const invalid = await callText(gateway, "animal.validate", { def: { id: "nope", stages: [], produces: [] }, }); expect(invalid.ok).toBe(false); expect(invalid.text).toMatch(/stages/); expect(invalid.text).toMatch(/at least 1 element/); } finally { await close(); } }); it("animal.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, "animal.create", { def: { id: "broken", stages: [{ name: "x", days: 0, feedRequired: true }], produces: [] }, }); expect(bad.ok).toBe(false); expect(engine.registry.get("animal", "broken")).toBeUndefined(); await expect(readFile(join(tmp, "animals", "broken.yaml"))).rejects.toThrow(); } finally { await close(); } }); it("animal.update merges a patch, validates, rewrites the file, and re-registers", async () => { const { engine, gateway, tmp, close } = await setup(); try { await callText(gateway, "animal.create", { def: CHICKEN_DEF }); const updated = await callText(gateway, "animal.update", { id: "chicken", patch: { produces: [{ itemId: "egg", qty: 2 }] }, }); expect(updated.ok).toBe(true); const def = JSON.parse(updated.text) as AnimalDef; expect(def.produces).toEqual([{ itemId: "egg", qty: 2 }]); expect(def.stages).toHaveLength(3); const file = await readFile(join(tmp, "animals", "chicken.yaml"), "utf8"); expect(file).toContain("qty: 2"); const missing = await callText(gateway, "animal.update", { id: "cow", patch: { produces: [] } }); expect(missing.ok).toBe(false); expect(missing.text).toMatch(/animal not found: cow/); const badPatch = await callText(gateway, "animal.update", { id: "chicken", patch: { stages: [] } }); expect(badPatch.ok).toBe(false); expect(badPatch.text).toMatch(/stages/); expect(engine.registry.get("animal", "chicken")?.produces).toEqual([{ itemId: "egg", qty: 2 }]); } finally { await close(); } }); it("animal.list and animal.get return definitions", async () => { const { gateway, close } = await setup(); try { await callText(gateway, "animal.create", { def: CHICKEN_DEF }); const listed = await callText(gateway, "animal.list"); expect(listed.ok).toBe(true); expect(JSON.parse(listed.text)).toEqual({ animals: [{ id: "chicken", stageCount: 3 }] }); const got = await callText(gateway, "animal.get", { animalId: "chicken" }); expect(got.ok).toBe(true); expect(JSON.parse(got.text)).toEqual(CHICKEN_DEF); const missing = await callText(gateway, "animal.get", { animalId: "cow" }); expect(missing.ok).toBe(false); expect(missing.text).toMatch(/animal not found: cow/); } finally { await close(); } }); it("animal.spawn creates an entity; unknown def and bad coords are error results", async () => { const { gateway, close } = await setup(); try { await callText(gateway, "animal.create", { def: CHICKEN_DEF }); const spawned = await callText(gateway, "animal.spawn", { animalId: "chicken", x: 3, y: 3 }); expect(spawned.ok).toBe(true); expect(JSON.parse(spawned.text)).toEqual({ id: "animal:chicken:1", type: "animal", animalId: "chicken", x: 3, y: 3, stageIndex: 0, daysInStage: 0, fed: false, }); const unknown = await callText(gateway, "animal.spawn", { animalId: "cow", x: 0, y: 0 }); expect(unknown.ok).toBe(false); expect(unknown.text).toMatch(/unknown animal def: cow/); const bad = await callText(gateway, "animal.spawn", { animalId: "chicken", x: -1, y: 0 }); expect(bad.ok).toBe(false); expect(bad.text).toMatch(/non-negative integers/); } finally { await close(); } }); it("animal.feed sets the fed flag and animal.stage force-advances (fires animal-grow)", async () => { const { engine, gateway, close } = await setup(); try { await callText(gateway, "animal.create", { def: CHICKEN_DEF }); await callText(gateway, "animal.spawn", { animalId: "chicken", x: 3, y: 3 }); const grew: number[] = []; engine.hooks.on("onAnimalGrow", (ctx) => { const animal = ctx.world.query({ type: "animal" })[0] as { stageIndex?: number } | undefined; grew.push(animal?.stageIndex ?? -1); }); const fed = await callText(gateway, "animal.feed", { id: "animal:chicken:1" }); expect(fed.ok).toBe(true); expect(JSON.parse(fed.text)).toEqual({ id: "animal:chicken:1", animalId: "chicken", fed: true }); const staged = await callText(gateway, "animal.stage", { id: "animal:chicken:1", stageIndex: 2 }); expect(staged.ok).toBe(true); expect(JSON.parse(staged.text)).toEqual({ id: "animal:chicken:1", animalId: "chicken", animalDefId: "chicken", stageIndex: 2, stage: "laying", }); expect(grew).toEqual([2]); const unknownFeed = await callText(gateway, "animal.feed", { id: "ghost" }); expect(unknownFeed.ok).toBe(false); expect(unknownFeed.text).toMatch(/unknown animal: ghost/); const badStage = await callText(gateway, "animal.stage", { id: "animal:chicken:1", stageIndex: 9 }); expect(badStage.ok).toBe(false); expect(badStage.text).toMatch(/out of range/); } finally { await close(); } }); it("animal.entities lists placed animals; growth step advances them through the mechanism", async () => { const { engine, gateway, close } = await setup(); try { await callText(gateway, "animal.create", { def: CHICKEN_DEF }); await callText(gateway, "animal.spawn", { animalId: "chicken", x: 3, y: 3 }); const listed = await callText(gateway, "animal.entities"); expect(listed.ok).toBe(true); expect(JSON.parse(listed.text)).toEqual({ animals: [{ id: "animal:chicken:1", type: "animal", animalId: "chicken", x: 3, y: 3, stageIndex: 0, daysInStage: 0, fed: false }], }); growthOf(engine).feed("animal:chicken:1"); growthOf(engine).step(480); growthOf(engine).step(480); const animal = engine.world.get("animal:chicken:1") as { stageIndex?: number }; expect(animal.stageIndex).toBe(1); } finally { await close(); } }); it("resources: animal://catalog and animal://{id}; missing id rejects", async () => { const { gateway, close } = await setup(); try { await callText(gateway, "animal.create", { def: CHICKEN_DEF }); const catalog = await gateway.readResource("animal://catalog"); expect(JSON.parse(catalog.contents[0]?.text ?? "{}")).toEqual({ animals: [CHICKEN_DEF] }); const single = await gateway.readResource("animal://chicken"); expect(JSON.parse(single.contents[0]?.text ?? "{}")).toEqual(CHICKEN_DEF); await expect(gateway.readResource("animal://missing")).rejects.toThrow(/animal not found: missing/); } finally { await close(); } }); it("serves the animal.create-prompt prompt", async () => { const { gateway, close } = await setup(); try { const prompt = await gateway.getPrompt("animal.create-prompt", {}); const text = prompt.messages[0]?.content.text ?? ""; expect(text).toContain("stages"); expect(text).toContain("feedRequired"); expect(text).toContain("produces"); expect(text).toContain("animal.validate"); expect(text).toContain("content/animals/.yaml"); } finally { await close(); } }); });