placement-namespace.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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 BuildingDef } 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: 5",
  18. "height: 5",
  19. 'tilesetRef: "tiles"',
  20. "spawn: { x: 0, y: 0 }",
  21. "layers:",
  22. " - name: ground",
  23. " data:",
  24. " - [grass, grass, water, water, water]",
  25. " - [grass, grass, water, water, water]",
  26. " - [grass, grass, grass, grass, grass]",
  27. " - [tilled, tilled, grass, grass, grass]",
  28. " - [tilled, tilled, grass, grass, grass]",
  29. "",
  30. ].join("\n");
  31. const SHED_YAML = [
  32. "id: shed",
  33. "name: Shed",
  34. "footprint: { w: 2, h: 2 }",
  35. "buildable: map",
  36. "blocksMovement: true",
  37. 'description: "Stores tools and harvests."',
  38. "",
  39. ].join("\n");
  40. const FENCE_YAML = [
  41. "id: fence",
  42. "name: Fence",
  43. "footprint: { w: 1, h: 1 }",
  44. "buildable: { tiles: [grass] }",
  45. "blocksMovement: true",
  46. "",
  47. ].join("\n");
  48. const BARN_DEF = {
  49. id: "barn",
  50. name: "Barn",
  51. footprint: { w: 3, h: 2 },
  52. buildable: { tiles: ["grass"] },
  53. blocksMovement: true,
  54. description: "Houses animals.",
  55. };
  56. interface Setup {
  57. engine: ReturnType<typeof createEngine>;
  58. gateway: McpGateway;
  59. tmp: string;
  60. close: () => Promise<void>;
  61. }
  62. async function setup(): Promise<Setup> {
  63. const tmp = await mkdtemp(join(tmpdir(), "farm-placement-ns-"));
  64. await mkdir(join(tmp, "maps"), { recursive: true });
  65. await mkdir(join(tmp, "buildings"), { recursive: true });
  66. await writeFile(join(tmp, "time.yaml"), TIME_YAML);
  67. await writeFile(join(tmp, "maps", "farm.yaml"), FARM_YAML);
  68. await writeFile(join(tmp, "buildings", "shed.yaml"), SHED_YAML);
  69. await writeFile(join(tmp, "buildings", "fence.yaml"), FENCE_YAML);
  70. const engine = createEngine({ contentDir: tmp });
  71. const gateway = new McpGateway();
  72. for (const namespace of createEngineNamespaces(engine, { gateway })) {
  73. gateway.register(namespace);
  74. }
  75. await engine.start();
  76. return {
  77. engine,
  78. gateway,
  79. tmp,
  80. close: async () => {
  81. await engine.stop();
  82. await rm(tmp, { recursive: true, force: true });
  83. },
  84. };
  85. }
  86. async function callText(gateway: McpGateway, name: string, args: Record<string, unknown> = {}): Promise<{
  87. ok: boolean;
  88. text: string;
  89. }> {
  90. const result = await gateway.callTool(name, args);
  91. return { ok: result.isError !== true, text: result.content[0]?.text ?? "" };
  92. }
  93. describe("placement namespace", () => {
  94. it("building.create writes content/buildings/<id>.yaml, registers live, and persists across restart", async () => {
  95. const { engine, gateway, tmp, close } = await setup();
  96. try {
  97. const created = await callText(gateway, "placement.building.create", { def: BARN_DEF });
  98. expect(created.ok).toBe(true);
  99. expect(JSON.parse(created.text) as BuildingDef).toEqual(BARN_DEF);
  100. expect(engine.registry.get<BuildingDef>("building", "barn")).toEqual(BARN_DEF);
  101. const file = await readFile(join(tmp, "buildings", "barn.yaml"), "utf8");
  102. expect(file).toContain("id: barn");
  103. expect(file).toContain("blocksMovement: true");
  104. await engine.stop();
  105. const reloaded = createEngine({ contentDir: tmp });
  106. await reloaded.start();
  107. try {
  108. expect(reloaded.registry.get<BuildingDef>("building", "barn")).toEqual(BARN_DEF);
  109. } finally {
  110. await reloaded.stop();
  111. }
  112. } finally {
  113. await close();
  114. }
  115. });
  116. it("building.validate accepts a valid def and rejects an invalid one", async () => {
  117. const { gateway, close } = await setup();
  118. try {
  119. const valid = await callText(gateway, "placement.building.validate", { def: BARN_DEF });
  120. expect(valid.ok).toBe(true);
  121. expect(JSON.parse(valid.text)).toEqual(BARN_DEF);
  122. const invalid = await callText(gateway, "placement.building.validate", {
  123. def: { id: "nope", footprint: { w: 0, h: 1 }, buildable: "map", blocksMovement: true },
  124. });
  125. expect(invalid.ok).toBe(false);
  126. expect(invalid.text).toMatch(/footprint/);
  127. } finally {
  128. await close();
  129. }
  130. });
  131. it("placement.building.create rejects an invalid def and does not write or register", async () => {
  132. const { engine, gateway, tmp, close } = await setup();
  133. try {
  134. const bad = await callText(gateway, "placement.building.create", {
  135. def: { id: "broken", footprint: { w: 1, h: 1 }, buildable: { tiles: [] }, blocksMovement: true },
  136. });
  137. expect(bad.ok).toBe(false);
  138. expect(engine.registry.get("building", "broken")).toBeUndefined();
  139. await expect(readFile(join(tmp, "buildings", "broken.yaml"))).rejects.toThrow();
  140. } finally {
  141. await close();
  142. }
  143. });
  144. it("building.update merges a patch, validates, rewrites the file, and re-registers", async () => {
  145. const { engine, gateway, tmp, close } = await setup();
  146. try {
  147. const updated = await callText(gateway, "placement.building.update", {
  148. id: "fence",
  149. patch: { description: "A sturdy fence post." },
  150. });
  151. expect(updated.ok).toBe(true);
  152. const def = JSON.parse(updated.text) as BuildingDef;
  153. expect(def.description).toBe("A sturdy fence post.");
  154. expect(def.blocksMovement).toBe(true);
  155. const file = await readFile(join(tmp, "buildings", "fence.yaml"), "utf8");
  156. expect(file).toContain("A sturdy fence post.");
  157. const missing = await callText(gateway, "placement.building.update", {
  158. id: "nope",
  159. patch: { blocksMovement: false },
  160. });
  161. expect(missing.ok).toBe(false);
  162. expect(missing.text).toMatch(/building not found: nope/);
  163. const badPatch = await callText(gateway, "placement.building.update", {
  164. id: "fence",
  165. patch: { footprint: { w: 0, h: 1 } },
  166. });
  167. expect(badPatch.ok).toBe(false);
  168. expect(badPatch.text).toMatch(/footprint/);
  169. expect(engine.registry.get<BuildingDef>("building", "fence")?.description).toBe("A sturdy fence post.");
  170. } finally {
  171. await close();
  172. }
  173. });
  174. it("building.list returns one-line summaries and building.get the full def", async () => {
  175. const { gateway, close } = await setup();
  176. try {
  177. const listed = await callText(gateway, "placement.building.list");
  178. expect(listed.ok).toBe(true);
  179. expect(JSON.parse(listed.text)).toEqual({
  180. buildings: [
  181. { id: "fence", name: "Fence", w: 1, h: 1, blocksMovement: true },
  182. { id: "shed", name: "Shed", w: 2, h: 2, blocksMovement: true },
  183. ],
  184. });
  185. const got = await callText(gateway, "placement.building.get", { buildingId: "shed" });
  186. expect(got.ok).toBe(true);
  187. expect(JSON.parse(got.text)).toMatchObject({ id: "shed", footprint: { w: 2, h: 2 } });
  188. const missing = await callText(gateway, "placement.building.get", { buildingId: "nope" });
  189. expect(missing.ok).toBe(false);
  190. expect(missing.text).toMatch(/building not found: nope/);
  191. } finally {
  192. await close();
  193. }
  194. });
  195. it("placement.place creates a placed entity and placement.list/occupies/remove roundtrip", async () => {
  196. const { gateway, close } = await setup();
  197. try {
  198. const placed = await callText(gateway, "placement.place", { buildingId: "shed", x: 3, y: 3 });
  199. expect(placed.ok).toBe(true);
  200. expect(JSON.parse(placed.text)).toEqual({
  201. id: "building:shed:3:3",
  202. type: "building",
  203. buildingId: "shed",
  204. x: 3,
  205. y: 3,
  206. w: 2,
  207. h: 2,
  208. blocksMovement: true,
  209. });
  210. const listed = await callText(gateway, "placement.list");
  211. expect(JSON.parse(listed.text)).toEqual({
  212. buildings: [{ id: "building:shed:3:3", type: "building", buildingId: "shed", x: 3, y: 3, w: 2, h: 2, blocksMovement: true }],
  213. });
  214. const inside = await callText(gateway, "placement.occupies", { x: 4, y: 4 });
  215. expect(JSON.parse(inside.text)).toMatchObject({ id: "building:shed:3:3" });
  216. const outside = await callText(gateway, "placement.occupies", { x: 0, y: 0 });
  217. expect(JSON.parse(outside.text)).toBeNull();
  218. const removed = await callText(gateway, "placement.remove", { x: 3, y: 3 });
  219. expect(JSON.parse(removed.text)).toMatchObject({ id: "building:shed:3:3" });
  220. const empty = await callText(gateway, "placement.list");
  221. expect(JSON.parse(empty.text)).toEqual({ buildings: [] });
  222. } finally {
  223. await close();
  224. }
  225. });
  226. it("placement.place error paths: unknown building, out of bounds, unbuildable tile, overlap", async () => {
  227. const { gateway, close } = await setup();
  228. try {
  229. const unknown = await callText(gateway, "placement.place", { buildingId: "barn", x: 0, y: 0 });
  230. expect(unknown.ok).toBe(false);
  231. expect(unknown.text).toMatch(/unknown building: barn/);
  232. const bounds = await callText(gateway, "placement.place", { buildingId: "shed", x: 4, y: 4 });
  233. expect(bounds.ok).toBe(false);
  234. expect(bounds.text).toMatch(/footprint out of bounds/);
  235. const tile = await callText(gateway, "placement.place", { buildingId: "fence", x: 2, y: 0 });
  236. expect(tile.ok).toBe(false);
  237. expect(tile.text).toMatch(/tile \(2,0\) is not buildable for fence/);
  238. await callText(gateway, "placement.place", { buildingId: "fence", x: 0, y: 0 });
  239. const overlap = await callText(gateway, "placement.place", { buildingId: "fence", x: 0, y: 0 });
  240. expect(overlap.ok).toBe(false);
  241. expect(overlap.text).toMatch(/overlaps existing building/);
  242. const badCoord = await callText(gateway, "placement.place", { buildingId: "fence", x: -1, y: 0 });
  243. expect(badCoord.ok).toBe(false);
  244. expect(badCoord.text).toMatch(/non-negative integers/);
  245. } finally {
  246. await close();
  247. }
  248. });
  249. it("resources: placement://buildings, placement://{id}, placement://placed", async () => {
  250. const { gateway, close } = await setup();
  251. try {
  252. const catalog = await gateway.readResource("placement://buildings");
  253. const defs = JSON.parse(catalog.contents[0]?.text ?? "{}");
  254. expect(defs.buildings.map((building: { id: string }) => building.id)).toEqual(["fence", "shed"]);
  255. const single = await gateway.readResource("placement://shed");
  256. expect(JSON.parse(single.contents[0]?.text ?? "{}")).toMatchObject({ id: "shed" });
  257. await callText(gateway, "placement.place", { buildingId: "fence", x: 0, y: 0 });
  258. const placed = await gateway.readResource("placement://placed");
  259. expect(JSON.parse(placed.contents[0]?.text ?? "{}")).toEqual({
  260. buildings: [{ id: "building:fence:0:0", type: "building", buildingId: "fence", x: 0, y: 0, w: 1, h: 1, blocksMovement: true }],
  261. });
  262. await expect(gateway.readResource("placement://missing")).rejects.toThrow(/building not found: missing/);
  263. } finally {
  264. await close();
  265. }
  266. });
  267. it("serves the placement.create-prompt prompt", async () => {
  268. const { gateway, close } = await setup();
  269. try {
  270. const prompt = await gateway.getPrompt("placement.create-prompt", {});
  271. const text = prompt.messages[0]?.content.text ?? "";
  272. expect(text).toContain("footprint");
  273. expect(text).toContain("buildable");
  274. expect(text).toContain("blocksMovement");
  275. expect(text).toContain("placement.building.validate");
  276. expect(text).toContain("content/buildings/<id>.yaml");
  277. } finally {
  278. await close();
  279. }
  280. });
  281. });