import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { createEngine, type DialogueDef } 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 DIALOGUE_DEF = { id: "welcome", startNode: "hello", nodes: [ { id: "hello", text: "Hello!", choices: [ { text: "Give me a seed", to: "thanks", actions: [{ action: "give-item", itemId: "parsnip-seed", qty: 1 }] }, { text: "No thanks", to: "bye" }, ], }, { id: "thanks", text: "Here you go." }, { id: "bye", text: "Bye!" }, ], }; interface Setup { engine: ReturnType; gateway: McpGateway; tmp: string; close: () => Promise; } async function setup(): Promise { const tmp = await mkdtemp(join(tmpdir(), "farm-dialogue-")); 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 ?? "" }; } describe("dialogue namespace", () => { it("dialogue.create writes content/dialogues/.yaml, registers live, and persists across restart", async () => { const { engine, gateway, tmp, close } = await setup(); try { const created = await callText(gateway, "dialogue.create", { def: DIALOGUE_DEF }); expect(created.ok).toBe(true); expect(JSON.parse(created.text) as DialogueDef).toEqual(DIALOGUE_DEF); expect(engine.registry.get("dialogue", "welcome")).toEqual(DIALOGUE_DEF); const file = await readFile(join(tmp, "dialogues", "welcome.yaml"), "utf8"); expect(file).toContain("id: welcome"); expect(file).toContain("startNode: hello"); expect(file).toContain("give-item"); await engine.stop(); const reloaded = createEngine({ contentDir: tmp }); await reloaded.start(); try { expect(reloaded.registry.get("dialogue", "welcome")).toEqual(DIALOGUE_DEF); } finally { await reloaded.stop(); } } finally { await close(); } }); it("dialogue.validate accepts a valid def and rejects invalid ones", async () => { const { gateway, close } = await setup(); try { const valid = await callText(gateway, "dialogue.validate", { def: DIALOGUE_DEF }); expect(valid.ok).toBe(true); expect(JSON.parse(valid.text)).toEqual(DIALOGUE_DEF); const badStart = await callText(gateway, "dialogue.validate", { def: { ...DIALOGUE_DEF, startNode: "ghost" }, }); expect(badStart.ok).toBe(false); expect(badStart.text).toMatch(/startNode/); const mixed = await callText(gateway, "dialogue.validate", { def: { ...DIALOGUE_DEF, nodes: [{ id: "hello", text: "x", to: "bye", choices: [{ text: "Go", to: "bye" }] }], }, }); expect(mixed.ok).toBe(false); expect(mixed.text).toMatch(/choices and to/); const badTarget = await callText(gateway, "dialogue.validate", { def: { ...DIALOGUE_DEF, nodes: [{ id: "hello", text: "x", to: "ghost" }] }, }); expect(badTarget.ok).toBe(false); expect(badTarget.text).toMatch(/to must be a declared node/); } finally { await close(); } }); it("dialogue.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, "dialogue.create", { def: { ...DIALOGUE_DEF, startNode: "nope" }, }); expect(bad.ok).toBe(false); expect(engine.registry.get("dialogue", "welcome")).toBeUndefined(); await expect(readFile(join(tmp, "dialogues", "welcome.yaml"))).rejects.toThrow(); } finally { await close(); } }); it("duplicate dialogue.create overwrites the existing definition", async () => { const { engine, gateway, tmp, close } = await setup(); try { await callText(gateway, "dialogue.create", { def: DIALOGUE_DEF }); const recreated = await callText(gateway, "dialogue.create", { def: { ...DIALOGUE_DEF, nodes: [...DIALOGUE_DEF.nodes, { id: "extra", text: "extra" }] }, }); expect(recreated.ok).toBe(true); const current = engine.registry.get("dialogue", "welcome"); expect(current?.nodes).toHaveLength(4); const file = await readFile(join(tmp, "dialogues", "welcome.yaml"), "utf8"); expect(file).toContain("extra"); } finally { await close(); } }); it("dialogue.update merges a patch, validates, rewrites the file, and re-registers", async () => { const { engine, gateway, tmp, close } = await setup(); try { await callText(gateway, "dialogue.create", { def: DIALOGUE_DEF }); const updated = await callText(gateway, "dialogue.update", { id: "welcome", patch: { startNode: "bye" }, }); expect(updated.ok).toBe(true); const def = JSON.parse(updated.text) as DialogueDef; expect(def.startNode).toBe("bye"); expect(def.nodes).toHaveLength(3); const file = await readFile(join(tmp, "dialogues", "welcome.yaml"), "utf8"); expect(file).toContain("startNode: bye"); const missing = await callText(gateway, "dialogue.update", { id: "nope", patch: { startNode: "bye" }, }); expect(missing.ok).toBe(false); expect(missing.text).toMatch(/dialogue not found: nope/); const badPatch = await callText(gateway, "dialogue.update", { id: "welcome", patch: { startNode: "ghost" }, }); expect(badPatch.ok).toBe(false); expect(engine.registry.get("dialogue", "welcome")?.startNode).toBe("bye"); } finally { await close(); } }); it("dialogue.list returns {dialogues:[...]} summaries", async () => { const { gateway, close } = await setup(); try { await callText(gateway, "dialogue.create", { def: DIALOGUE_DEF }); await callText(gateway, "dialogue.create", { def: { id: "other", startNode: "a", nodes: [ { id: "a", text: "a" }, { id: "b", text: "b" }, ], }, }); const listed = await callText(gateway, "dialogue.list"); expect(listed.ok).toBe(true); expect(JSON.parse(listed.text)).toEqual({ dialogues: [ { id: "welcome", nodeCount: 3, startNode: "hello" }, { id: "other", nodeCount: 2, startNode: "a" }, ], }); } finally { await close(); } }); it("dialogue.get returns the full def; unknown id is an error result", async () => { const { gateway, close } = await setup(); try { await callText(gateway, "dialogue.create", { def: DIALOGUE_DEF }); const got = await callText(gateway, "dialogue.get", { dialogueId: "welcome" }); expect(got.ok).toBe(true); expect(JSON.parse(got.text)).toEqual(DIALOGUE_DEF); const missing = await callText(gateway, "dialogue.get", { dialogueId: "nope" }); expect(missing.ok).toBe(false); expect(missing.text).toMatch(/dialogue not found: nope/); const blank = await callText(gateway, "dialogue.get", { dialogueId: "" }); expect(blank.ok).toBe(false); expect(blank.text).toMatch(/non-empty string/); } finally { await close(); } }); it("dialogue.start returns the current node; unknown dialogue is an error result", async () => { const { engine, gateway, close } = await setup(); try { await callText(gateway, "dialogue.create", { def: DIALOGUE_DEF }); const started = await callText(gateway, "dialogue.start", { dialogueId: "welcome" }); expect(started.ok).toBe(true); expect(JSON.parse(started.text)).toEqual({ dialogueId: "welcome", nodeId: "hello", text: "Hello!", choices: [ { text: "Give me a seed", to: "thanks" }, { text: "No thanks", to: "bye" }, ], }); expect(engine.world.get("dialogue:active")?.nodeId).toBe("hello"); const missing = await callText(gateway, "dialogue.start", { dialogueId: "nope" }); expect(missing.ok).toBe(false); expect(missing.text).toMatch(/unknown dialogue: nope/); } finally { await close(); } }); it("dialogue.choose advances the dialogue and errors on bad indices / no active dialogue", async () => { const { engine, gateway, close } = await setup(); try { await callText(gateway, "dialogue.create", { def: DIALOGUE_DEF }); await callText(gateway, "dialogue.start", { dialogueId: "welcome" }); const chosen = await callText(gateway, "dialogue.choose", { index: 0 }); expect(chosen.ok).toBe(true); expect(JSON.parse(chosen.text)).toEqual({ dialogueId: "welcome", nodeId: "thanks", text: "Here you go.", choices: [], }); expect(engine.world.get("dialogue:active")).toBeUndefined(); const ended = await callText(gateway, "dialogue.choose", { index: 0 }); expect(ended.ok).toBe(false); expect(ended.text).toMatch(/no active dialogue/); await callText(gateway, "dialogue.start", { dialogueId: "welcome" }); const outOfRange = await callText(gateway, "dialogue.choose", { index: 9 }); expect(outOfRange.ok).toBe(false); expect(outOfRange.text).toMatch(/choice index out of range/); const nonInt = await callText(gateway, "dialogue.choose", { index: -1 }); expect(nonInt.ok).toBe(false); expect(nonInt.text).toMatch(/non-negative integer/); } finally { await close(); } }); it("resources dialogue://catalog and dialogue://{id}; missing id rejects", async () => { const { gateway, close } = await setup(); try { await callText(gateway, "dialogue.create", { def: DIALOGUE_DEF }); const catalog = await gateway.readResource("dialogue://catalog"); expect(JSON.parse(catalog.contents[0]?.text ?? "{}")).toEqual({ dialogues: [DIALOGUE_DEF] }); const single = await gateway.readResource("dialogue://welcome"); expect(JSON.parse(single.contents[0]?.text ?? "{}")).toEqual(DIALOGUE_DEF); await expect(gateway.readResource("dialogue://missing")).rejects.toThrow(/dialogue not found: missing/); } finally { await close(); } }); it("serves the dialogue.create-prompt prompt", async () => { const { gateway, close } = await setup(); try { const prompt = await gateway.getPrompt("dialogue.create-prompt", {}); const text = prompt.messages[0]?.content.text ?? ""; expect(text).toContain("nodes"); expect(text).toContain("choices"); expect(text).toContain("content/dialogues/.yaml"); expect(text).toContain("dialogue.validate"); expect(text).toContain("give-item"); } finally { await close(); } }); });