| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345 |
- 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<typeof createEngine>;
- gateway: McpGateway;
- tmp: string;
- close: () => Promise<void>;
- }
- async function setup(): Promise<Setup> {
- 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<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 timeOf(engine: ReturnType<typeof createEngine>): TimeSystem {
- const time = engine.systems.get<TimeSystem>("time");
- if (!time) throw new Error("time system not booted");
- return time;
- }
- describe("behavior.statemachine namespace", () => {
- it("behavior.statemachine.create writes content/statemachines/<id>.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<StateMachineDef>("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<StateMachineDef>("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<StateMachineDef>("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<StateMachineDef>("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/<id>.yaml");
- expect(text).toContain("behavior.statemachine.validate");
- } finally {
- await close();
- }
- });
- });
|