| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315 |
- 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<typeof createEngine>;
- gateway: McpGateway;
- tmp: string;
- close: () => Promise<void>;
- }
- async function setup(): Promise<Setup> {
- 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<string, unknown> = {}): 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<typeof createEngine>): GrowthSystem {
- const growth = engine.systems.get<GrowthSystem>("growth");
- if (!growth) throw new Error("growth system not booted");
- return growth;
- }
- describe("animal namespace", () => {
- it("animal.create writes content/animals/<id>.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<AnimalDef>("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<AnimalDef>("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<AnimalDef>("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/<id>.yaml");
- } finally {
- await close();
- }
- });
- });
|