import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { describe, expect, it } from "vitest"; import { createEngine, type InventorySystem, type ShopDef } 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 GENERAL_STORE_DEF = { id: "general-store", buys: [{ itemId: "parsnip", price: 30 }], sells: [ { itemId: "hoe", price: 500 }, { itemId: "parsnip-seed", price: 20, stock: 99 }, ], }; interface Setup { engine: ReturnType; gateway: McpGateway; tmp: string; close: () => Promise; } async function setup(): Promise { const tmp = await mkdtemp(join(tmpdir(), "farm-shop-")); 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 = {}): Promise<{ ok: boolean; text: string; }> { const result = await gateway.callTool(name, args); return { ok: result.isError !== true, text: result.content[0]?.text ?? "" }; } function registerItems(engine: ReturnType): void { engine.registry.register("item", { id: "hoe", name: "Hoe", kind: "tool", stackable: false }); engine.registry.register("item", { id: "parsnip-seed", name: "Parsnip Seed", kind: "seed", stackable: true }); engine.registry.register("item", { id: "parsnip", name: "Parsnip", kind: "material", stackable: true }); } function setGold(engine: ReturnType, gold: number): void { const player = engine.world.get("player"); if (!player) throw new Error("player entity not seeded"); player.gold = gold; } function inventoryOf(engine: ReturnType): InventorySystem { const inv = engine.systems.get("inventory"); if (!inv) throw new Error("inventory system not booted"); return inv; } describe("shop namespace", () => { it("shop.create writes content/shops/.yaml, registers live, and persists across restart", async () => { const { engine, gateway, tmp, close } = await setup(); try { const created = await callText(gateway, "shop.create", { def: GENERAL_STORE_DEF }); expect(created.ok).toBe(true); expect(JSON.parse(created.text) as ShopDef).toEqual(GENERAL_STORE_DEF); expect(engine.registry.get("shop", "general-store")).toEqual(GENERAL_STORE_DEF); const file = await readFile(join(tmp, "shops", "general-store.yaml"), "utf8"); expect(file).toContain("id: general-store"); expect(file).toContain("buys:"); expect(file).toContain("stock: 99"); await engine.stop(); const reloaded = createEngine({ contentDir: tmp }); await reloaded.start(); try { expect(reloaded.registry.get("shop", "general-store")).toEqual(GENERAL_STORE_DEF); } finally { await reloaded.stop(); } } finally { await close(); } }); it("shop.validate accepts a valid def and rejects an invalid one", async () => { const { gateway, close } = await setup(); try { const valid = await callText(gateway, "shop.validate", { def: GENERAL_STORE_DEF }); expect(valid.ok).toBe(true); expect(JSON.parse(valid.text)).toEqual(GENERAL_STORE_DEF); const invalid = await callText(gateway, "shop.validate", { def: { id: "nope", buys: [{ itemId: "x", price: 0 }], sells: [] }, }); expect(invalid.ok).toBe(false); expect(invalid.text).toMatch(/price/); expect(invalid.text).toMatch(/greater than 0/); } finally { await close(); } }); it("shop.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, "shop.create", { def: { id: "broken", buys: [{ itemId: "x", price: -5 }], sells: [] }, }); expect(bad.ok).toBe(false); expect(engine.registry.get("shop", "broken")).toBeUndefined(); await expect(readFile(join(tmp, "shops", "broken.yaml"))).rejects.toThrow(); } finally { await close(); } }); it("duplicate shop.create overwrites the existing definition", async () => { const { engine, gateway, tmp, close } = await setup(); try { await callText(gateway, "shop.create", { def: GENERAL_STORE_DEF }); const recreated = await callText(gateway, "shop.create", { def: { ...GENERAL_STORE_DEF, sells: [...GENERAL_STORE_DEF.sells, { itemId: "parsnip", price: 45, stock: 10 }], }, }); expect(recreated.ok).toBe(true); const current = engine.registry.get("shop", "general-store"); expect(current?.sells).toHaveLength(3); const file = await readFile(join(tmp, "shops", "general-store.yaml"), "utf8"); expect(file).toContain("itemId: parsnip"); expect(file).toContain("stock: 10"); } finally { await close(); } }); it("shop.update merges a patch, validates, rewrites the file, and re-registers", async () => { const { engine, gateway, tmp, close } = await setup(); try { await callText(gateway, "shop.create", { def: GENERAL_STORE_DEF }); const updated = await callText(gateway, "shop.update", { id: "general-store", patch: { buys: [{ itemId: "parsnip", price: 40 }] }, }); expect(updated.ok).toBe(true); const def = JSON.parse(updated.text) as ShopDef; expect(def.buys).toEqual([{ itemId: "parsnip", price: 40 }]); expect(def.sells).toHaveLength(2); const file = await readFile(join(tmp, "shops", "general-store.yaml"), "utf8"); expect(file).toContain("price: 40"); const missing = await callText(gateway, "shop.update", { id: "nope", patch: { buys: [] } }); expect(missing.ok).toBe(false); expect(missing.text).toMatch(/shop not found: nope/); const badPatch = await callText(gateway, "shop.update", { id: "general-store", patch: { sells: [{ itemId: "x", price: 0 }] } }); expect(badPatch.ok).toBe(false); expect(badPatch.text).toMatch(/price/); expect(engine.registry.get("shop", "general-store")?.buys).toEqual([ { itemId: "parsnip", price: 40 }, ]); } finally { await close(); } }); it("shop.list returns one-line summaries", async () => { const { gateway, close } = await setup(); try { await callText(gateway, "shop.create", { def: GENERAL_STORE_DEF }); const listed = await callText(gateway, "shop.list"); expect(listed.ok).toBe(true); expect(JSON.parse(listed.text)).toEqual({ shops: [{ id: "general-store", buyCount: 1, sellCount: 2 }], }); } finally { await close(); } }); it("shop.get returns the full def; unknown id is an error result", async () => { const { gateway, close } = await setup(); try { await callText(gateway, "shop.create", { def: GENERAL_STORE_DEF }); const got = await callText(gateway, "shop.get", { shopId: "general-store" }); expect(got.ok).toBe(true); expect(JSON.parse(got.text)).toEqual(GENERAL_STORE_DEF); const missing = await callText(gateway, "shop.get", { shopId: "nope" }); expect(missing.ok).toBe(false); expect(missing.text).toMatch(/shop not found: nope/); } finally { await close(); } }); it("shop.buy deducts gold, grants inventory, and returns the transaction result", async () => { const { engine, gateway, close } = await setup(); try { registerItems(engine); await callText(gateway, "shop.create", { def: GENERAL_STORE_DEF }); setGold(engine, 100); const bought = await callText(gateway, "shop.buy", { shopId: "general-store", itemId: "parsnip-seed", qty: 2 }); expect(bought.ok).toBe(true); expect(JSON.parse(bought.text)).toEqual({ shopId: "general-store", itemId: "parsnip-seed", qty: 2, total: 40, gold: 60, }); expect(engine.world.get("player")?.gold).toBe(60); expect(inventoryOf(engine).count("parsnip-seed")).toBe(2); } finally { await close(); } }); it("shop.buy error paths: missing shop, item not sold, insufficient gold, bad qty", async () => { const { engine, gateway, close } = await setup(); try { registerItems(engine); await callText(gateway, "shop.create", { def: GENERAL_STORE_DEF }); setGold(engine, 100); const noShop = await callText(gateway, "shop.buy", { shopId: "nope", itemId: "hoe", qty: 1 }); expect(noShop.ok).toBe(false); expect(noShop.text).toMatch(/unknown shop: nope/); const notSold = await callText(gateway, "shop.buy", { shopId: "general-store", itemId: "parsnip", qty: 1 }); expect(notSold.ok).toBe(false); expect(notSold.text).toMatch(/does not sell parsnip/); const broke = await callText(gateway, "shop.buy", { shopId: "general-store", itemId: "hoe", qty: 1 }); expect(broke.ok).toBe(false); expect(broke.text).toMatch(/insufficient gold/); expect(engine.world.get("player")?.gold).toBe(100); const badQty = await callText(gateway, "shop.buy", { shopId: "general-store", itemId: "hoe", qty: 0 }); expect(badQty.ok).toBe(false); expect(badQty.text).toMatch(/positive integer/); } finally { await close(); } }); it("shop.sell removes inventory, adds gold, and returns the transaction result", async () => { const { engine, gateway, close } = await setup(); try { registerItems(engine); await callText(gateway, "shop.create", { def: GENERAL_STORE_DEF }); inventoryOf(engine).give("parsnip", 3); const sold = await callText(gateway, "shop.sell", { shopId: "general-store", itemId: "parsnip", qty: 2 }); expect(sold.ok).toBe(true); expect(JSON.parse(sold.text)).toEqual({ shopId: "general-store", itemId: "parsnip", qty: 2, total: 60, gold: 60, }); expect(engine.world.get("player")?.gold).toBe(60); expect(inventoryOf(engine).count("parsnip")).toBe(1); } finally { await close(); } }); it("shop.sell error paths: item not bought, insufficient inventory, missing shop", async () => { const { engine, gateway, close } = await setup(); try { registerItems(engine); await callText(gateway, "shop.create", { def: GENERAL_STORE_DEF }); const notBought = await callText(gateway, "shop.sell", { shopId: "general-store", itemId: "hoe", qty: 1 }); expect(notBought.ok).toBe(false); expect(notBought.text).toMatch(/does not buy hoe/); inventoryOf(engine).give("parsnip", 1); const short = await callText(gateway, "shop.sell", { shopId: "general-store", itemId: "parsnip", qty: 5 }); expect(short.ok).toBe(false); expect(short.text).toMatch(/insufficient parsnip/); expect(engine.world.get("player")?.gold).toBe(0); const noShop = await callText(gateway, "shop.sell", { shopId: "nope", itemId: "parsnip", qty: 1 }); expect(noShop.ok).toBe(false); expect(noShop.text).toMatch(/unknown shop: nope/); } finally { await close(); } }); it("resources: shop://catalog and shop://{shopId}; missing id rejects", async () => { const { engine, gateway, close } = await setup(); try { await callText(gateway, "shop.create", { def: GENERAL_STORE_DEF }); const catalog = await gateway.readResource("shop://catalog"); expect(JSON.parse(catalog.contents[0]?.text ?? "{}")).toEqual({ shops: [GENERAL_STORE_DEF] }); const single = await gateway.readResource("shop://general-store"); expect(JSON.parse(single.contents[0]?.text ?? "{}")).toEqual(GENERAL_STORE_DEF); await expect(gateway.readResource("shop://missing")).rejects.toThrow(/shop not found: missing/); expect(engine.registry.get("shop", "missing")).toBeUndefined(); } finally { await close(); } }); it("serves the shop.create-prompt prompt", async () => { const { gateway, close } = await setup(); try { const prompt = await gateway.getPrompt("shop.create-prompt", {}); const text = prompt.messages[0]?.content.text ?? ""; expect(text).toContain("buys"); expect(text).toContain("sells"); expect(text).toContain("stock"); expect(text).toContain("shop.validate"); expect(text).toContain("content/shops/.yaml"); } finally { await close(); } }); });