shop-namespace.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join, resolve } from "node:path";
  4. import { describe, expect, it } from "vitest";
  5. import { createEngine, type InventorySystem, type ShopDef } 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 GENERAL_STORE_DEF = {
  29. id: "general-store",
  30. buys: [{ itemId: "parsnip", price: 30 }],
  31. sells: [
  32. { itemId: "hoe", price: 500 },
  33. { itemId: "parsnip-seed", price: 20, stock: 99 },
  34. ],
  35. };
  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(), "farm-shop-"));
  44. await mkdir(join(tmp, "maps"), { recursive: true });
  45. await writeFile(join(tmp, "time.yaml"), TIME_YAML);
  46. await writeFile(join(tmp, "maps", "farm.yaml"), FARM_YAML);
  47. const engine = createEngine({ contentDir: tmp });
  48. const gateway = new McpGateway();
  49. for (const namespace of createEngineNamespaces(engine, { gateway })) {
  50. gateway.register(namespace);
  51. }
  52. await engine.start();
  53. return {
  54. engine,
  55. gateway,
  56. tmp,
  57. close: async () => {
  58. await engine.stop();
  59. await rm(tmp, { recursive: true, force: true });
  60. },
  61. };
  62. }
  63. async function callText(gateway: McpGateway, name: string, args: Record<string, unknown> = {}): Promise<{
  64. ok: boolean;
  65. text: string;
  66. }> {
  67. const result = await gateway.callTool(name, args);
  68. return { ok: result.isError !== true, text: result.content[0]?.text ?? "" };
  69. }
  70. function registerItems(engine: ReturnType<typeof createEngine>): void {
  71. engine.registry.register("item", { id: "hoe", name: "Hoe", kind: "tool", stackable: false });
  72. engine.registry.register("item", { id: "parsnip-seed", name: "Parsnip Seed", kind: "seed", stackable: true });
  73. engine.registry.register("item", { id: "parsnip", name: "Parsnip", kind: "material", stackable: true });
  74. }
  75. function setGold(engine: ReturnType<typeof createEngine>, gold: number): void {
  76. const player = engine.world.get("player");
  77. if (!player) throw new Error("player entity not seeded");
  78. player.gold = gold;
  79. }
  80. function inventoryOf(engine: ReturnType<typeof createEngine>): InventorySystem {
  81. const inv = engine.systems.get<InventorySystem>("inventory");
  82. if (!inv) throw new Error("inventory system not booted");
  83. return inv;
  84. }
  85. describe("shop namespace", () => {
  86. it("shop.create writes content/shops/<id>.yaml, registers live, and persists across restart", async () => {
  87. const { engine, gateway, tmp, close } = await setup();
  88. try {
  89. const created = await callText(gateway, "shop.create", { def: GENERAL_STORE_DEF });
  90. expect(created.ok).toBe(true);
  91. expect(JSON.parse(created.text) as ShopDef).toEqual(GENERAL_STORE_DEF);
  92. expect(engine.registry.get<ShopDef>("shop", "general-store")).toEqual(GENERAL_STORE_DEF);
  93. const file = await readFile(join(tmp, "shops", "general-store.yaml"), "utf8");
  94. expect(file).toContain("id: general-store");
  95. expect(file).toContain("buys:");
  96. expect(file).toContain("stock: 99");
  97. await engine.stop();
  98. const reloaded = createEngine({ contentDir: tmp });
  99. await reloaded.start();
  100. try {
  101. expect(reloaded.registry.get<ShopDef>("shop", "general-store")).toEqual(GENERAL_STORE_DEF);
  102. } finally {
  103. await reloaded.stop();
  104. }
  105. } finally {
  106. await close();
  107. }
  108. });
  109. it("shop.validate accepts a valid def and rejects an invalid one", async () => {
  110. const { gateway, close } = await setup();
  111. try {
  112. const valid = await callText(gateway, "shop.validate", { def: GENERAL_STORE_DEF });
  113. expect(valid.ok).toBe(true);
  114. expect(JSON.parse(valid.text)).toEqual(GENERAL_STORE_DEF);
  115. const invalid = await callText(gateway, "shop.validate", {
  116. def: { id: "nope", buys: [{ itemId: "x", price: 0 }], sells: [] },
  117. });
  118. expect(invalid.ok).toBe(false);
  119. expect(invalid.text).toMatch(/price/);
  120. expect(invalid.text).toMatch(/greater than 0/);
  121. } finally {
  122. await close();
  123. }
  124. });
  125. it("shop.create rejects an invalid def and does not write or register", async () => {
  126. const { engine, gateway, tmp, close } = await setup();
  127. try {
  128. const bad = await callText(gateway, "shop.create", {
  129. def: { id: "broken", buys: [{ itemId: "x", price: -5 }], sells: [] },
  130. });
  131. expect(bad.ok).toBe(false);
  132. expect(engine.registry.get("shop", "broken")).toBeUndefined();
  133. await expect(readFile(join(tmp, "shops", "broken.yaml"))).rejects.toThrow();
  134. } finally {
  135. await close();
  136. }
  137. });
  138. it("duplicate shop.create overwrites the existing definition", async () => {
  139. const { engine, gateway, tmp, close } = await setup();
  140. try {
  141. await callText(gateway, "shop.create", { def: GENERAL_STORE_DEF });
  142. const recreated = await callText(gateway, "shop.create", {
  143. def: {
  144. ...GENERAL_STORE_DEF,
  145. sells: [...GENERAL_STORE_DEF.sells, { itemId: "parsnip", price: 45, stock: 10 }],
  146. },
  147. });
  148. expect(recreated.ok).toBe(true);
  149. const current = engine.registry.get<ShopDef>("shop", "general-store");
  150. expect(current?.sells).toHaveLength(3);
  151. const file = await readFile(join(tmp, "shops", "general-store.yaml"), "utf8");
  152. expect(file).toContain("itemId: parsnip");
  153. expect(file).toContain("stock: 10");
  154. } finally {
  155. await close();
  156. }
  157. });
  158. it("shop.update merges a patch, validates, rewrites the file, and re-registers", async () => {
  159. const { engine, gateway, tmp, close } = await setup();
  160. try {
  161. await callText(gateway, "shop.create", { def: GENERAL_STORE_DEF });
  162. const updated = await callText(gateway, "shop.update", {
  163. id: "general-store",
  164. patch: { buys: [{ itemId: "parsnip", price: 40 }] },
  165. });
  166. expect(updated.ok).toBe(true);
  167. const def = JSON.parse(updated.text) as ShopDef;
  168. expect(def.buys).toEqual([{ itemId: "parsnip", price: 40 }]);
  169. expect(def.sells).toHaveLength(2);
  170. const file = await readFile(join(tmp, "shops", "general-store.yaml"), "utf8");
  171. expect(file).toContain("price: 40");
  172. const missing = await callText(gateway, "shop.update", { id: "nope", patch: { buys: [] } });
  173. expect(missing.ok).toBe(false);
  174. expect(missing.text).toMatch(/shop not found: nope/);
  175. const badPatch = await callText(gateway, "shop.update", { id: "general-store", patch: { sells: [{ itemId: "x", price: 0 }] } });
  176. expect(badPatch.ok).toBe(false);
  177. expect(badPatch.text).toMatch(/price/);
  178. expect(engine.registry.get<ShopDef>("shop", "general-store")?.buys).toEqual([
  179. { itemId: "parsnip", price: 40 },
  180. ]);
  181. } finally {
  182. await close();
  183. }
  184. });
  185. it("shop.list returns one-line summaries", async () => {
  186. const { gateway, close } = await setup();
  187. try {
  188. await callText(gateway, "shop.create", { def: GENERAL_STORE_DEF });
  189. const listed = await callText(gateway, "shop.list");
  190. expect(listed.ok).toBe(true);
  191. expect(JSON.parse(listed.text)).toEqual({
  192. shops: [{ id: "general-store", buyCount: 1, sellCount: 2 }],
  193. });
  194. } finally {
  195. await close();
  196. }
  197. });
  198. it("shop.get returns the full def; unknown id is an error result", async () => {
  199. const { gateway, close } = await setup();
  200. try {
  201. await callText(gateway, "shop.create", { def: GENERAL_STORE_DEF });
  202. const got = await callText(gateway, "shop.get", { shopId: "general-store" });
  203. expect(got.ok).toBe(true);
  204. expect(JSON.parse(got.text)).toEqual(GENERAL_STORE_DEF);
  205. const missing = await callText(gateway, "shop.get", { shopId: "nope" });
  206. expect(missing.ok).toBe(false);
  207. expect(missing.text).toMatch(/shop not found: nope/);
  208. } finally {
  209. await close();
  210. }
  211. });
  212. it("shop.buy deducts gold, grants inventory, and returns the transaction result", async () => {
  213. const { engine, gateway, close } = await setup();
  214. try {
  215. registerItems(engine);
  216. await callText(gateway, "shop.create", { def: GENERAL_STORE_DEF });
  217. setGold(engine, 100);
  218. const bought = await callText(gateway, "shop.buy", { shopId: "general-store", itemId: "parsnip-seed", qty: 2 });
  219. expect(bought.ok).toBe(true);
  220. expect(JSON.parse(bought.text)).toEqual({
  221. shopId: "general-store",
  222. itemId: "parsnip-seed",
  223. qty: 2,
  224. total: 40,
  225. gold: 60,
  226. });
  227. expect(engine.world.get("player")?.gold).toBe(60);
  228. expect(inventoryOf(engine).count("parsnip-seed")).toBe(2);
  229. } finally {
  230. await close();
  231. }
  232. });
  233. it("shop.buy error paths: missing shop, item not sold, insufficient gold, bad qty", async () => {
  234. const { engine, gateway, close } = await setup();
  235. try {
  236. registerItems(engine);
  237. await callText(gateway, "shop.create", { def: GENERAL_STORE_DEF });
  238. setGold(engine, 100);
  239. const noShop = await callText(gateway, "shop.buy", { shopId: "nope", itemId: "hoe", qty: 1 });
  240. expect(noShop.ok).toBe(false);
  241. expect(noShop.text).toMatch(/unknown shop: nope/);
  242. const notSold = await callText(gateway, "shop.buy", { shopId: "general-store", itemId: "parsnip", qty: 1 });
  243. expect(notSold.ok).toBe(false);
  244. expect(notSold.text).toMatch(/does not sell parsnip/);
  245. const broke = await callText(gateway, "shop.buy", { shopId: "general-store", itemId: "hoe", qty: 1 });
  246. expect(broke.ok).toBe(false);
  247. expect(broke.text).toMatch(/insufficient gold/);
  248. expect(engine.world.get("player")?.gold).toBe(100);
  249. const badQty = await callText(gateway, "shop.buy", { shopId: "general-store", itemId: "hoe", qty: 0 });
  250. expect(badQty.ok).toBe(false);
  251. expect(badQty.text).toMatch(/positive integer/);
  252. } finally {
  253. await close();
  254. }
  255. });
  256. it("shop.sell removes inventory, adds gold, and returns the transaction result", async () => {
  257. const { engine, gateway, close } = await setup();
  258. try {
  259. registerItems(engine);
  260. await callText(gateway, "shop.create", { def: GENERAL_STORE_DEF });
  261. inventoryOf(engine).give("parsnip", 3);
  262. const sold = await callText(gateway, "shop.sell", { shopId: "general-store", itemId: "parsnip", qty: 2 });
  263. expect(sold.ok).toBe(true);
  264. expect(JSON.parse(sold.text)).toEqual({
  265. shopId: "general-store",
  266. itemId: "parsnip",
  267. qty: 2,
  268. total: 60,
  269. gold: 60,
  270. });
  271. expect(engine.world.get("player")?.gold).toBe(60);
  272. expect(inventoryOf(engine).count("parsnip")).toBe(1);
  273. } finally {
  274. await close();
  275. }
  276. });
  277. it("shop.sell error paths: item not bought, insufficient inventory, missing shop", async () => {
  278. const { engine, gateway, close } = await setup();
  279. try {
  280. registerItems(engine);
  281. await callText(gateway, "shop.create", { def: GENERAL_STORE_DEF });
  282. const notBought = await callText(gateway, "shop.sell", { shopId: "general-store", itemId: "hoe", qty: 1 });
  283. expect(notBought.ok).toBe(false);
  284. expect(notBought.text).toMatch(/does not buy hoe/);
  285. inventoryOf(engine).give("parsnip", 1);
  286. const short = await callText(gateway, "shop.sell", { shopId: "general-store", itemId: "parsnip", qty: 5 });
  287. expect(short.ok).toBe(false);
  288. expect(short.text).toMatch(/insufficient parsnip/);
  289. expect(engine.world.get("player")?.gold).toBe(0);
  290. const noShop = await callText(gateway, "shop.sell", { shopId: "nope", itemId: "parsnip", qty: 1 });
  291. expect(noShop.ok).toBe(false);
  292. expect(noShop.text).toMatch(/unknown shop: nope/);
  293. } finally {
  294. await close();
  295. }
  296. });
  297. it("resources: shop://catalog and shop://{shopId}; missing id rejects", async () => {
  298. const { engine, gateway, close } = await setup();
  299. try {
  300. await callText(gateway, "shop.create", { def: GENERAL_STORE_DEF });
  301. const catalog = await gateway.readResource("shop://catalog");
  302. expect(JSON.parse(catalog.contents[0]?.text ?? "{}")).toEqual({ shops: [GENERAL_STORE_DEF] });
  303. const single = await gateway.readResource("shop://general-store");
  304. expect(JSON.parse(single.contents[0]?.text ?? "{}")).toEqual(GENERAL_STORE_DEF);
  305. await expect(gateway.readResource("shop://missing")).rejects.toThrow(/shop not found: missing/);
  306. expect(engine.registry.get("shop", "missing")).toBeUndefined();
  307. } finally {
  308. await close();
  309. }
  310. });
  311. it("serves the shop.create-prompt prompt", async () => {
  312. const { gateway, close } = await setup();
  313. try {
  314. const prompt = await gateway.getPrompt("shop.create-prompt", {});
  315. const text = prompt.messages[0]?.content.text ?? "";
  316. expect(text).toContain("buys");
  317. expect(text).toContain("sells");
  318. expect(text).toContain("stock");
  319. expect(text).toContain("shop.validate");
  320. expect(text).toContain("content/shops/<id>.yaml");
  321. } finally {
  322. await close();
  323. }
  324. });
  325. });