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 StateMachineDef, type TimeSystem } 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 MACHINE_DEF = { id: "greet-machine", initial: "idle", states: [ { id: "idle" }, { id: "greeted", onEnter: [{ action: "give-item", itemId: "parsnip-seed", qty: 1 }] }, ], transitions: [{ from: "idle", to: "greeted", on: "day-start" }], }; interface Setup { engine: ReturnType; gateway: McpGateway; tmp: string; close: () => Promise; } async function setup(): Promise { const tmp = await mkdtemp(join(tmpdir(), "farm-statemachine-")); 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 timeOf(engine: ReturnType): TimeSystem { const time = engine.systems.get("time"); if (!time) throw new Error("time system not booted"); return time; } describe("behavior.statemachine namespace", () => { it("behavior.statemachine.create writes content/statemachines/.yaml, registers live, and persists across restart", async () => { const { engine, gateway, tmp, close } = await setup(); try { const created = await callText(gateway, "behavior.statemachine.create", { def: MACHINE_DEF }); expect(created.ok).toBe(true); expect(JSON.parse(created.text) as StateMachineDef).toEqual(MACHINE_DEF); expect(engine.registry.get("statemachine", "greet-machine")).toEqual(MACHINE_DEF); const file = await readFile(join(tmp, "statemachines", "greet-machine.yaml"), "utf8"); expect(file).toContain("id: greet-machine"); expect(file).toContain("day-start"); expect(file).toContain("give-item"); await engine.stop(); const reloaded = createEngine({ contentDir: tmp }); await reloaded.start(); try { expect(reloaded.registry.get("statemachine", "greet-machine")).toEqual(MACHINE_DEF); } finally { await reloaded.stop(); } } finally { await close(); } }); it("behavior.statemachine.validate accepts a valid def and rejects invalid ones", async () => { const { gateway, close } = await setup(); try { const valid = await callText(gateway, "behavior.statemachine.validate", { def: MACHINE_DEF }); expect(valid.ok).toBe(true); expect(JSON.parse(valid.text)).toEqual(MACHINE_DEF); const badInitial = await callText(gateway, "behavior.statemachine.validate", { def: { ...MACHINE_DEF, initial: "ghost" }, }); expect(badInitial.ok).toBe(false); expect(badInitial.text).toMatch(/initial/); const badTransition = await callText(gateway, "behavior.statemachine.validate", { def: { ...MACHINE_DEF, transitions: [{ from: "idle", to: "ghost", on: "day-start" }] }, }); expect(badTransition.ok).toBe(false); expect(badTransition.text).toMatch(/transitions\.0\.to/); const noTrigger = await callText(gateway, "behavior.statemachine.validate", { def: { ...MACHINE_DEF, transitions: [{ from: "idle", to: "greeted" }] }, }); expect(noTrigger.ok).toBe(false); expect(noTrigger.text).toMatch(/when or on/); const emptyStates = await callText(gateway, "behavior.statemachine.validate", { def: { ...MACHINE_DEF, states: [] }, }); expect(emptyStates.ok).toBe(false); } finally { await close(); } }); it("behavior.statemachine.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, "behavior.statemachine.create", { def: { ...MACHINE_DEF, initial: "nope" }, }); expect(bad.ok).toBe(false); expect(engine.registry.get("statemachine", "greet-machine")).toBeUndefined(); await expect(readFile(join(tmp, "statemachines", "greet-machine.yaml"))).rejects.toThrow(); } finally { await close(); } }); it("duplicate behavior.statemachine.create overwrites the existing definition", async () => { const { engine, gateway, tmp, close } = await setup(); try { await callText(gateway, "behavior.statemachine.create", { def: MACHINE_DEF }); const recreated = await callText(gateway, "behavior.statemachine.create", { def: { ...MACHINE_DEF, states: [...MACHINE_DEF.states, { id: "extra" }] }, }); expect(recreated.ok).toBe(true); const current = engine.registry.get("statemachine", "greet-machine"); expect(current?.states).toHaveLength(3); const file = await readFile(join(tmp, "statemachines", "greet-machine.yaml"), "utf8"); expect(file).toContain("extra"); } finally { await close(); } }); it("behavior.statemachine.update merges a patch, validates, rewrites the file, and re-registers", async () => { const { engine, gateway, tmp, close } = await setup(); try { await callText(gateway, "behavior.statemachine.create", { def: MACHINE_DEF }); const updated = await callText(gateway, "behavior.statemachine.update", { id: "greet-machine", patch: { initial: "greeted" }, }); expect(updated.ok).toBe(true); const def = JSON.parse(updated.text) as StateMachineDef; expect(def.initial).toBe("greeted"); expect(def.states).toHaveLength(2); const file = await readFile(join(tmp, "statemachines", "greet-machine.yaml"), "utf8"); expect(file).toContain("initial: greeted"); const missing = await callText(gateway, "behavior.statemachine.update", { id: "nope", patch: { initial: "greeted" }, }); expect(missing.ok).toBe(false); expect(missing.text).toMatch(/machine not found: nope/); const badPatch = await callText(gateway, "behavior.statemachine.update", { id: "greet-machine", patch: { initial: "ghost" }, }); expect(badPatch.ok).toBe(false); expect(engine.registry.get("statemachine", "greet-machine")?.initial).toBe("greeted"); } finally { await close(); } }); it("behavior.statemachine.list returns {statemachines:[...]} summaries", async () => { const { gateway, close } = await setup(); try { await callText(gateway, "behavior.statemachine.create", { def: MACHINE_DEF }); await callText(gateway, "behavior.statemachine.create", { def: { id: "other", initial: "a", states: [{ id: "a" }, { id: "b" }], transitions: [{ from: "a", to: "b", on: "kick" }] }, }); const listed = await callText(gateway, "behavior.statemachine.list"); expect(listed.ok).toBe(true); expect(JSON.parse(listed.text)).toEqual({ statemachines: [ { id: "greet-machine", stateCount: 2, transitionCount: 1 }, { id: "other", stateCount: 2, transitionCount: 1 }, ], }); } finally { await close(); } }); it("behavior.statemachine.get returns the full def; unknown id is an error result", async () => { const { gateway, close } = await setup(); try { await callText(gateway, "behavior.statemachine.create", { def: MACHINE_DEF }); const got = await callText(gateway, "behavior.statemachine.get", { machineId: "greet-machine" }); expect(got.ok).toBe(true); expect(JSON.parse(got.text)).toEqual(MACHINE_DEF); const missing = await callText(gateway, "behavior.statemachine.get", { machineId: "nope" }); expect(missing.ok).toBe(false); expect(missing.text).toMatch(/machine not found: nope/); const blank = await callText(gateway, "behavior.statemachine.get", { machineId: "" }); expect(blank.ok).toBe(false); expect(blank.text).toMatch(/non-empty string/); } finally { await close(); } }); it("behavior.statemachine.status reports started:false before the first transition and the live state after", async () => { const { engine, gateway, close } = await setup(); try { await callText(gateway, "behavior.statemachine.create", { def: MACHINE_DEF }); const before = await callText(gateway, "behavior.statemachine.status", { machineId: "greet-machine" }); expect(before.ok).toBe(true); expect(JSON.parse(before.text)).toEqual({ machineId: "greet-machine", state: "idle", started: false }); const time = timeOf(engine); time.advance(480); const after = await callText(gateway, "behavior.statemachine.status", { machineId: "greet-machine" }); expect(JSON.parse(after.text)).toEqual({ machineId: "greet-machine", state: "greeted", started: true }); } finally { await close(); } }); it("behavior.statemachine.transition forces a transition; unknown machine/state are error results", async () => { const { engine, gateway, close } = await setup(); try { await callText(gateway, "behavior.statemachine.create", { def: MACHINE_DEF }); const forced = await callText(gateway, "behavior.statemachine.transition", { machineId: "greet-machine", to: "greeted", }); expect(forced.ok).toBe(true); expect(JSON.parse(forced.text)).toEqual({ machineId: "greet-machine", from: "idle", to: "greeted", transitioned: true, }); expect(engine.world.get("sm:greet-machine")?.state).toBe("greeted"); const noop = await callText(gateway, "behavior.statemachine.transition", { machineId: "greet-machine", to: "greeted", }); expect(JSON.parse(noop.text)).toEqual({ machineId: "greet-machine", from: "greeted", to: "greeted", transitioned: false, }); const unknownMachine = await callText(gateway, "behavior.statemachine.transition", { machineId: "nope", to: "idle", }); expect(unknownMachine.ok).toBe(false); expect(unknownMachine.text).toMatch(/unknown machine: nope/); const unknownState = await callText(gateway, "behavior.statemachine.transition", { machineId: "greet-machine", to: "ghost", }); expect(unknownState.ok).toBe(false); expect(unknownState.text).toMatch(/unknown state: ghost/); } finally { await close(); } }); it("resource behavior://statemachines returns all state machine definitions", async () => { const { gateway, close } = await setup(); try { await callText(gateway, "behavior.statemachine.create", { def: MACHINE_DEF }); const resource = await gateway.readResource("behavior://statemachines"); expect(JSON.parse(resource.contents[0]?.text ?? "{}")).toEqual({ statemachines: [MACHINE_DEF] }); } finally { await close(); } }); it("serves the behavior.statemachine-prompt prompt", async () => { const { gateway, close } = await setup(); try { const prompt = await gateway.getPrompt("behavior.statemachine-prompt", {}); const text = prompt.messages[0]?.content.text ?? ""; expect(text).toContain("states"); expect(text).toContain("transitions"); expect(text).toContain("onSchedule"); expect(text).toContain("content/statemachines/.yaml"); expect(text).toContain("behavior.statemachine.validate"); } finally { await close(); } }); });