scene-namespace.test.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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 SceneDef } 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_YAML = [
  29. "id: chicken",
  30. "stages:",
  31. " - { name: chick, days: 2, feedRequired: false }",
  32. "produces:",
  33. " - { itemId: egg, qty: 1 }",
  34. "",
  35. ].join("\n");
  36. interface Setup {
  37. engine: ReturnType<typeof createEngine>;
  38. gateway: McpGateway;
  39. tmp: string;
  40. close: () => Promise<void>;
  41. }
  42. async function setup(): Promise<Setup> {
  43. const tmp = await mkdtemp(join(tmpdir(), "scene-ns-"));
  44. await mkdir(join(tmp, "maps"), { recursive: true });
  45. await mkdir(join(tmp, "animals"), { recursive: true });
  46. await writeFile(join(tmp, "time.yaml"), TIME_YAML);
  47. await writeFile(join(tmp, "maps", "farm.yaml"), FARM_YAML);
  48. await writeFile(join(tmp, "animals", "chicken.yaml"), CHICKEN_YAML);
  49. const engine = createEngine({ contentDir: tmp });
  50. const gateway = new McpGateway();
  51. for (const namespace of createEngineNamespaces(engine, { gateway })) {
  52. gateway.register(namespace);
  53. }
  54. await engine.start();
  55. return {
  56. engine,
  57. gateway,
  58. tmp,
  59. close: async () => {
  60. await engine.stop();
  61. await rm(tmp, { recursive: true, force: true });
  62. },
  63. };
  64. }
  65. async function callText(gateway: McpGateway, name: string, args: Record<string, unknown> = {}): Promise<{
  66. ok: boolean;
  67. text: string;
  68. }> {
  69. const result = await gateway.callTool(name, args);
  70. return { ok: result.isError !== true, text: result.content[0]?.text ?? "" };
  71. }
  72. const FARM_START_DEF: SceneDef = {
  73. id: "farm-start",
  74. entities: [
  75. { type: "npc", npcId: "mayor", x: 1, y: 1, dialogue: "welcome", label: "Mayor" },
  76. { type: "animal", animalId: "chicken", x: 0, y: 1 },
  77. ],
  78. };
  79. describe("scene namespace", () => {
  80. it("scene.create writes content/scenes/<id>.yaml, registers live, and seeds on restart", async () => {
  81. const { engine, gateway, tmp, close } = await setup();
  82. try {
  83. const created = await callText(gateway, "scene.create", { def: FARM_START_DEF });
  84. expect(created.ok).toBe(true);
  85. expect(JSON.parse(created.text) as SceneDef).toEqual(FARM_START_DEF);
  86. expect(engine.registry.get<SceneDef>("scene", "farm-start")).toEqual(FARM_START_DEF);
  87. const file = await readFile(join(tmp, "scenes", "farm-start.yaml"), "utf8");
  88. expect(file).toContain("id: farm-start");
  89. expect(file).toContain("npcId: mayor");
  90. expect(engine.world.get("mayor")).toBeUndefined();
  91. await engine.stop();
  92. const reloaded = createEngine({ contentDir: tmp });
  93. await reloaded.start();
  94. try {
  95. expect(reloaded.registry.get<SceneDef>("scene", "farm-start")).toEqual(FARM_START_DEF);
  96. expect(reloaded.world.get("mayor")).toMatchObject({ id: "mayor", type: "npc", x: 1, y: 1 });
  97. expect(reloaded.world.get("animal:chicken:1")).toMatchObject({ type: "animal", animalId: "chicken" });
  98. } finally {
  99. await reloaded.stop();
  100. }
  101. } finally {
  102. await close();
  103. }
  104. });
  105. it("scene.validate accepts a valid def and rejects an invalid one", async () => {
  106. const { gateway, close } = await setup();
  107. try {
  108. const valid = await callText(gateway, "scene.validate", { def: FARM_START_DEF });
  109. expect(valid.ok).toBe(true);
  110. expect(JSON.parse(valid.text)).toEqual(FARM_START_DEF);
  111. const invalid = await callText(gateway, "scene.validate", {
  112. def: { id: "bad", entities: [{ type: "plot", x: 0, y: 0 }] },
  113. });
  114. expect(invalid.ok).toBe(false);
  115. expect(invalid.text).toMatch(/Invalid discriminator value/);
  116. expect(invalid.text).toMatch(/entities/);
  117. const negative = await callText(gateway, "scene.validate", {
  118. def: { id: "bad", entities: [{ type: "npc", npcId: "m", x: -1, y: 0 }] },
  119. });
  120. expect(negative.ok).toBe(false);
  121. expect(negative.text).toMatch(/x/);
  122. } finally {
  123. await close();
  124. }
  125. });
  126. it("scene.create rejects an invalid def and does not write or register", async () => {
  127. const { engine, gateway, tmp, close } = await setup();
  128. try {
  129. const bad = await callText(gateway, "scene.create", {
  130. def: { id: "broken", entities: [{ type: "npc", npcId: "m", x: 0 }] },
  131. });
  132. expect(bad.ok).toBe(false);
  133. expect(engine.registry.get("scene", "broken")).toBeUndefined();
  134. await expect(readFile(join(tmp, "scenes", "broken.yaml"))).rejects.toThrow();
  135. } finally {
  136. await close();
  137. }
  138. });
  139. it("duplicate scene.create overwrites the existing definition", async () => {
  140. const { engine, gateway, tmp, close } = await setup();
  141. try {
  142. await callText(gateway, "scene.create", { def: FARM_START_DEF });
  143. const recreated = await callText(gateway, "scene.create", {
  144. def: { id: "farm-start", entities: [{ type: "npc", npcId: "villager", x: 0, y: 0 }] },
  145. });
  146. expect(recreated.ok).toBe(true);
  147. const current = engine.registry.get<SceneDef>("scene", "farm-start");
  148. expect(current?.entities).toEqual([{ type: "npc", npcId: "villager", x: 0, y: 0 }]);
  149. const file = await readFile(join(tmp, "scenes", "farm-start.yaml"), "utf8");
  150. expect(file).toContain("npcId: villager");
  151. } finally {
  152. await close();
  153. }
  154. });
  155. it("scene.update merges a patch, validates, rewrites the file, and re-registers", async () => {
  156. const { engine, gateway, tmp, close } = await setup();
  157. try {
  158. await callText(gateway, "scene.create", { def: FARM_START_DEF });
  159. const updated = await callText(gateway, "scene.update", {
  160. id: "farm-start",
  161. patch: { entities: [{ type: "building", buildingId: "shed", x: 0, y: 0 }] },
  162. });
  163. expect(updated.ok).toBe(true);
  164. const def = JSON.parse(updated.text) as SceneDef;
  165. expect(def.entities).toEqual([{ type: "building", buildingId: "shed", x: 0, y: 0 }]);
  166. expect(def.id).toBe("farm-start");
  167. const file = await readFile(join(tmp, "scenes", "farm-start.yaml"), "utf8");
  168. expect(file).toContain("buildingId: shed");
  169. const missing = await callText(gateway, "scene.update", { id: "nope", patch: { entities: [] } });
  170. expect(missing.ok).toBe(false);
  171. expect(missing.text).toMatch(/scene not found: nope/);
  172. const badPatch = await callText(gateway, "scene.update", { id: "farm-start", patch: { entities: "nope" } });
  173. expect(badPatch.ok).toBe(false);
  174. expect(badPatch.text).toMatch(/entities/);
  175. expect(engine.registry.get<SceneDef>("scene", "farm-start")?.entities).toEqual([
  176. { type: "building", buildingId: "shed", x: 0, y: 0 },
  177. ]);
  178. } finally {
  179. await close();
  180. }
  181. });
  182. it("scene.list returns one-line summaries", async () => {
  183. const { gateway, close } = await setup();
  184. try {
  185. await callText(gateway, "scene.create", { def: FARM_START_DEF });
  186. await callText(gateway, "scene.create", {
  187. def: { id: "farm-empty", entities: [] },
  188. });
  189. const listed = await callText(gateway, "scene.list");
  190. expect(listed.ok).toBe(true);
  191. expect(JSON.parse(listed.text)).toEqual({
  192. scenes: [
  193. { id: "farm-start", entityCount: 2 },
  194. { id: "farm-empty", entityCount: 0 },
  195. ],
  196. });
  197. } finally {
  198. await close();
  199. }
  200. });
  201. it("scene.get returns the full def; unknown id is an error result", async () => {
  202. const { gateway, close } = await setup();
  203. try {
  204. await callText(gateway, "scene.create", { def: FARM_START_DEF });
  205. const got = await callText(gateway, "scene.get", { sceneId: "farm-start" });
  206. expect(got.ok).toBe(true);
  207. expect(JSON.parse(got.text)).toEqual(FARM_START_DEF);
  208. const missing = await callText(gateway, "scene.get", { sceneId: "nope" });
  209. expect(missing.ok).toBe(false);
  210. expect(missing.text).toMatch(/scene not found: nope/);
  211. } finally {
  212. await close();
  213. }
  214. });
  215. it("resources: scene://catalog and scene://{id}; missing id rejects", async () => {
  216. const { engine, gateway, close } = await setup();
  217. try {
  218. await callText(gateway, "scene.create", { def: FARM_START_DEF });
  219. const catalog = await gateway.readResource("scene://catalog");
  220. expect(JSON.parse(catalog.contents[0]?.text ?? "{}")).toEqual({ scenes: [FARM_START_DEF] });
  221. const single = await gateway.readResource("scene://farm-start");
  222. expect(JSON.parse(single.contents[0]?.text ?? "{}")).toEqual(FARM_START_DEF);
  223. await expect(gateway.readResource("scene://missing")).rejects.toThrow(/scene not found: missing/);
  224. expect(engine.registry.get("scene", "missing")).toBeUndefined();
  225. } finally {
  226. await close();
  227. }
  228. });
  229. it("serves the scene.create-prompt prompt", async () => {
  230. const { gateway, close } = await setup();
  231. try {
  232. const prompt = await gateway.getPrompt("scene.create-prompt", {});
  233. const text = prompt.messages[0]?.content.text ?? "";
  234. expect(text).toContain("building");
  235. expect(text).toContain("npc");
  236. expect(text).toContain("animal");
  237. expect(text).toContain("scene.validate");
  238. expect(text).toContain("content/scenes/<id>.yaml");
  239. expect(text).toContain("overlap");
  240. } finally {
  241. await close();
  242. }
  243. });
  244. });