| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370 |
- 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<typeof createEngine>;
- gateway: McpGateway;
- tmp: string;
- close: () => Promise<void>;
- }
- async function setup(): Promise<Setup> {
- 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<string, unknown> = {}): 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<typeof createEngine>): 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<typeof createEngine>, 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<typeof createEngine>): InventorySystem {
- const inv = engine.systems.get<InventorySystem>("inventory");
- if (!inv) throw new Error("inventory system not booted");
- return inv;
- }
- describe("shop namespace", () => {
- it("shop.create writes content/shops/<id>.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<ShopDef>("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<ShopDef>("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<ShopDef>("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<ShopDef>("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/<id>.yaml");
- } finally {
- await close();
- }
- });
- });
|