animal-namespace.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { describe, expect, it } from "vitest";
  5. import { createEngine, type AnimalDef, type GrowthSystem } from "@nengine/core";
  6. import { createEngineNamespaces, McpGateway } from "../src/index.js";
  7. const TIME_YAML = [
  8. "id: default",
  9. "dayLengthTicks: 480",
  10. "seasons:",
  11. " - { name: spring, dayCount: 28 }",
  12. "start: { day: 1, season: spring }",
  13. "",
  14. ].join("\n");
  15. const FARM_YAML = [
  16. "id: farm",
  17. "width: 2",
  18. "height: 2",
  19. 'tilesetRef: "tiles"',
  20. "spawn: { x: 0, y: 0 }",
  21. "layers:",
  22. " - name: ground",
  23. " data:",
  24. " - [a, b]",
  25. " - [b, a]",
  26. "",
  27. ].join("\n");
  28. const CHICKEN_DEF = {
  29. id: "chicken",
  30. stages: [
  31. { name: "chick", days: 2, feedRequired: false },
  32. { name: "grown", days: 2, feedRequired: true },
  33. { name: "laying", days: 1, feedRequired: true },
  34. ],
  35. produces: [{ itemId: "egg", qty: 1 }],
  36. };
  37. interface Setup {
  38. engine: ReturnType<typeof createEngine>;
  39. gateway: McpGateway;
  40. tmp: string;
  41. close: () => Promise<void>;
  42. }
  43. async function setup(): Promise<Setup> {
  44. const tmp = await mkdtemp(join(tmpdir(), "farm-animal-ns-"));
  45. await mkdir(join(tmp, "maps"), { recursive: true });
  46. await writeFile(join(tmp, "time.yaml"), TIME_YAML);
  47. await writeFile(join(tmp, "maps", "farm.yaml"), FARM_YAML);
  48. const engine = createEngine({ contentDir: tmp });
  49. const gateway = new McpGateway();
  50. for (const namespace of createEngineNamespaces(engine, { gateway })) {
  51. gateway.register(namespace);
  52. }
  53. await engine.start();
  54. return {
  55. engine,
  56. gateway,
  57. tmp,
  58. close: async () => {
  59. await engine.stop();
  60. await rm(tmp, { recursive: true, force: true });
  61. },
  62. };
  63. }
  64. async function callText(gateway: McpGateway, name: string, args: Record<string, unknown> = {}): Promise<{
  65. ok: boolean;
  66. text: string;
  67. }> {
  68. const result = await gateway.callTool(name, args);
  69. return { ok: result.isError !== true, text: result.content[0]?.text ?? "" };
  70. }
  71. function growthOf(engine: ReturnType<typeof createEngine>): GrowthSystem {
  72. const growth = engine.systems.get<GrowthSystem>("growth");
  73. if (!growth) throw new Error("growth system not booted");
  74. return growth;
  75. }
  76. describe("animal namespace", () => {
  77. it("animal.create writes content/animals/<id>.yaml, registers live, and persists across restart", async () => {
  78. const { engine, gateway, tmp, close } = await setup();
  79. try {
  80. const created = await callText(gateway, "animal.create", { def: CHICKEN_DEF });
  81. expect(created.ok).toBe(true);
  82. expect(JSON.parse(created.text) as AnimalDef).toEqual(CHICKEN_DEF);
  83. expect(engine.registry.get<AnimalDef>("animal", "chicken")).toEqual(CHICKEN_DEF);
  84. const file = await readFile(join(tmp, "animals", "chicken.yaml"), "utf8");
  85. expect(file).toContain("id: chicken");
  86. expect(file).toContain("feedRequired: true");
  87. await engine.stop();
  88. const reloaded = createEngine({ contentDir: tmp });
  89. await reloaded.start();
  90. try {
  91. expect(reloaded.registry.get<AnimalDef>("animal", "chicken")).toEqual(CHICKEN_DEF);
  92. } finally {
  93. await reloaded.stop();
  94. }
  95. } finally {
  96. await close();
  97. }
  98. });
  99. it("animal.validate accepts a valid def and rejects an invalid one", async () => {
  100. const { gateway, close } = await setup();
  101. try {
  102. const valid = await callText(gateway, "animal.validate", { def: CHICKEN_DEF });
  103. expect(valid.ok).toBe(true);
  104. expect(JSON.parse(valid.text)).toEqual(CHICKEN_DEF);
  105. const invalid = await callText(gateway, "animal.validate", {
  106. def: { id: "nope", stages: [], produces: [] },
  107. });
  108. expect(invalid.ok).toBe(false);
  109. expect(invalid.text).toMatch(/stages/);
  110. expect(invalid.text).toMatch(/at least 1 element/);
  111. } finally {
  112. await close();
  113. }
  114. });
  115. it("animal.create rejects an invalid def and does not write or register", async () => {
  116. const { engine, gateway, tmp, close } = await setup();
  117. try {
  118. const bad = await callText(gateway, "animal.create", {
  119. def: { id: "broken", stages: [{ name: "x", days: 0, feedRequired: true }], produces: [] },
  120. });
  121. expect(bad.ok).toBe(false);
  122. expect(engine.registry.get("animal", "broken")).toBeUndefined();
  123. await expect(readFile(join(tmp, "animals", "broken.yaml"))).rejects.toThrow();
  124. } finally {
  125. await close();
  126. }
  127. });
  128. it("animal.update merges a patch, validates, rewrites the file, and re-registers", async () => {
  129. const { engine, gateway, tmp, close } = await setup();
  130. try {
  131. await callText(gateway, "animal.create", { def: CHICKEN_DEF });
  132. const updated = await callText(gateway, "animal.update", {
  133. id: "chicken",
  134. patch: { produces: [{ itemId: "egg", qty: 2 }] },
  135. });
  136. expect(updated.ok).toBe(true);
  137. const def = JSON.parse(updated.text) as AnimalDef;
  138. expect(def.produces).toEqual([{ itemId: "egg", qty: 2 }]);
  139. expect(def.stages).toHaveLength(3);
  140. const file = await readFile(join(tmp, "animals", "chicken.yaml"), "utf8");
  141. expect(file).toContain("qty: 2");
  142. const missing = await callText(gateway, "animal.update", { id: "cow", patch: { produces: [] } });
  143. expect(missing.ok).toBe(false);
  144. expect(missing.text).toMatch(/animal not found: cow/);
  145. const badPatch = await callText(gateway, "animal.update", { id: "chicken", patch: { stages: [] } });
  146. expect(badPatch.ok).toBe(false);
  147. expect(badPatch.text).toMatch(/stages/);
  148. expect(engine.registry.get<AnimalDef>("animal", "chicken")?.produces).toEqual([{ itemId: "egg", qty: 2 }]);
  149. } finally {
  150. await close();
  151. }
  152. });
  153. it("animal.list and animal.get return definitions", async () => {
  154. const { gateway, close } = await setup();
  155. try {
  156. await callText(gateway, "animal.create", { def: CHICKEN_DEF });
  157. const listed = await callText(gateway, "animal.list");
  158. expect(listed.ok).toBe(true);
  159. expect(JSON.parse(listed.text)).toEqual({ animals: [{ id: "chicken", stageCount: 3 }] });
  160. const got = await callText(gateway, "animal.get", { animalId: "chicken" });
  161. expect(got.ok).toBe(true);
  162. expect(JSON.parse(got.text)).toEqual(CHICKEN_DEF);
  163. const missing = await callText(gateway, "animal.get", { animalId: "cow" });
  164. expect(missing.ok).toBe(false);
  165. expect(missing.text).toMatch(/animal not found: cow/);
  166. } finally {
  167. await close();
  168. }
  169. });
  170. it("animal.spawn creates an entity; unknown def and bad coords are error results", async () => {
  171. const { gateway, close } = await setup();
  172. try {
  173. await callText(gateway, "animal.create", { def: CHICKEN_DEF });
  174. const spawned = await callText(gateway, "animal.spawn", { animalId: "chicken", x: 3, y: 3 });
  175. expect(spawned.ok).toBe(true);
  176. expect(JSON.parse(spawned.text)).toEqual({
  177. id: "animal:chicken:1",
  178. type: "animal",
  179. animalId: "chicken",
  180. x: 3,
  181. y: 3,
  182. stageIndex: 0,
  183. daysInStage: 0,
  184. fed: false,
  185. });
  186. const unknown = await callText(gateway, "animal.spawn", { animalId: "cow", x: 0, y: 0 });
  187. expect(unknown.ok).toBe(false);
  188. expect(unknown.text).toMatch(/unknown animal def: cow/);
  189. const bad = await callText(gateway, "animal.spawn", { animalId: "chicken", x: -1, y: 0 });
  190. expect(bad.ok).toBe(false);
  191. expect(bad.text).toMatch(/non-negative integers/);
  192. } finally {
  193. await close();
  194. }
  195. });
  196. it("animal.feed sets the fed flag and animal.stage force-advances (fires animal-grow)", async () => {
  197. const { engine, gateway, close } = await setup();
  198. try {
  199. await callText(gateway, "animal.create", { def: CHICKEN_DEF });
  200. await callText(gateway, "animal.spawn", { animalId: "chicken", x: 3, y: 3 });
  201. const grew: number[] = [];
  202. engine.hooks.on("onAnimalGrow", (ctx) => {
  203. const animal = ctx.world.query({ type: "animal" })[0] as { stageIndex?: number } | undefined;
  204. grew.push(animal?.stageIndex ?? -1);
  205. });
  206. const fed = await callText(gateway, "animal.feed", { id: "animal:chicken:1" });
  207. expect(fed.ok).toBe(true);
  208. expect(JSON.parse(fed.text)).toEqual({ id: "animal:chicken:1", animalId: "chicken", fed: true });
  209. const staged = await callText(gateway, "animal.stage", { id: "animal:chicken:1", stageIndex: 2 });
  210. expect(staged.ok).toBe(true);
  211. expect(JSON.parse(staged.text)).toEqual({
  212. id: "animal:chicken:1",
  213. animalId: "chicken",
  214. animalDefId: "chicken",
  215. stageIndex: 2,
  216. stage: "laying",
  217. });
  218. expect(grew).toEqual([2]);
  219. const unknownFeed = await callText(gateway, "animal.feed", { id: "ghost" });
  220. expect(unknownFeed.ok).toBe(false);
  221. expect(unknownFeed.text).toMatch(/unknown animal: ghost/);
  222. const badStage = await callText(gateway, "animal.stage", { id: "animal:chicken:1", stageIndex: 9 });
  223. expect(badStage.ok).toBe(false);
  224. expect(badStage.text).toMatch(/out of range/);
  225. } finally {
  226. await close();
  227. }
  228. });
  229. it("animal.entities lists placed animals; growth step advances them through the mechanism", async () => {
  230. const { engine, gateway, close } = await setup();
  231. try {
  232. await callText(gateway, "animal.create", { def: CHICKEN_DEF });
  233. await callText(gateway, "animal.spawn", { animalId: "chicken", x: 3, y: 3 });
  234. const listed = await callText(gateway, "animal.entities");
  235. expect(listed.ok).toBe(true);
  236. expect(JSON.parse(listed.text)).toEqual({
  237. animals: [{ id: "animal:chicken:1", type: "animal", animalId: "chicken", x: 3, y: 3, stageIndex: 0, daysInStage: 0, fed: false }],
  238. });
  239. growthOf(engine).feed("animal:chicken:1");
  240. growthOf(engine).step(480);
  241. growthOf(engine).step(480);
  242. const animal = engine.world.get("animal:chicken:1") as { stageIndex?: number };
  243. expect(animal.stageIndex).toBe(1);
  244. } finally {
  245. await close();
  246. }
  247. });
  248. it("resources: animal://catalog and animal://{id}; missing id rejects", async () => {
  249. const { gateway, close } = await setup();
  250. try {
  251. await callText(gateway, "animal.create", { def: CHICKEN_DEF });
  252. const catalog = await gateway.readResource("animal://catalog");
  253. expect(JSON.parse(catalog.contents[0]?.text ?? "{}")).toEqual({ animals: [CHICKEN_DEF] });
  254. const single = await gateway.readResource("animal://chicken");
  255. expect(JSON.parse(single.contents[0]?.text ?? "{}")).toEqual(CHICKEN_DEF);
  256. await expect(gateway.readResource("animal://missing")).rejects.toThrow(/animal not found: missing/);
  257. } finally {
  258. await close();
  259. }
  260. });
  261. it("serves the animal.create-prompt prompt", async () => {
  262. const { gateway, close } = await setup();
  263. try {
  264. const prompt = await gateway.getPrompt("animal.create-prompt", {});
  265. const text = prompt.messages[0]?.content.text ?? "";
  266. expect(text).toContain("stages");
  267. expect(text).toContain("feedRequired");
  268. expect(text).toContain("produces");
  269. expect(text).toContain("animal.validate");
  270. expect(text).toContain("content/animals/<id>.yaml");
  271. } finally {
  272. await close();
  273. }
  274. });
  275. });