| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341 |
- 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 InventorySystem, type TimeSystem, type TriggerDef } 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 SPRING_GIFT_DEF = {
- id: "spring-gift",
- when: { op: "gte", path: "time.day", value: 5 },
- fire: [{ action: "give-item", itemId: "parsnip-seed", qty: 1 }],
- };
- const DAY_ONE_DEF = {
- id: "day-one",
- when: { op: "eq", path: "time.day", value: 1 },
- fire: [{ action: "emit-event", event: "behavior:day-one", payload: { day: 1 } }],
- };
- 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-behavior-"));
- 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 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("behavior namespace", () => {
- it("behavior.trigger.create writes content/behaviors/<id>.yaml, registers live, and persists across restart", async () => {
- const { engine, gateway, tmp, close } = await setup();
- try {
- const created = await callText(gateway, "behavior.trigger.create", { def: SPRING_GIFT_DEF });
- expect(created.ok).toBe(true);
- expect(JSON.parse(created.text) as TriggerDef).toEqual(SPRING_GIFT_DEF);
- expect(engine.registry.get<TriggerDef>("behavior", "spring-gift")).toEqual(SPRING_GIFT_DEF);
- const file = await readFile(join(tmp, "behaviors", "spring-gift.yaml"), "utf8");
- expect(file).toContain("id: spring-gift");
- expect(file).toContain("op: gte");
- expect(file).toContain("give-item");
- await engine.stop();
- const reloaded = createEngine({ contentDir: tmp });
- await reloaded.start();
- try {
- expect(reloaded.registry.get<TriggerDef>("behavior", "spring-gift")).toEqual(SPRING_GIFT_DEF);
- } finally {
- await reloaded.stop();
- }
- } finally {
- await close();
- }
- });
- it("behavior.trigger.validate accepts a valid def and rejects an invalid one", async () => {
- const { gateway, close } = await setup();
- try {
- const valid = await callText(gateway, "behavior.trigger.validate", { def: SPRING_GIFT_DEF });
- expect(valid.ok).toBe(true);
- expect(JSON.parse(valid.text)).toEqual(SPRING_GIFT_DEF);
- const badOp = await callText(gateway, "behavior.trigger.validate", {
- def: { id: "nope", when: { op: "bogus", path: "time.day", value: 1 }, fire: [{ action: "emit-event", event: "x" }] },
- });
- expect(badOp.ok).toBe(false);
- expect(badOp.text).toMatch(/when/);
- const emptyFire = await callText(gateway, "behavior.trigger.validate", {
- def: { id: "nope", when: { op: "exists", path: "time.day" }, fire: [] },
- });
- expect(emptyFire.ok).toBe(false);
- expect(emptyFire.text).toMatch(/fire/);
- const badAction = await callText(gateway, "behavior.trigger.validate", {
- def: { id: "nope", when: { op: "exists", path: "time.day" }, fire: [{ action: "explode" }] },
- });
- expect(badAction.ok).toBe(false);
- } finally {
- await close();
- }
- });
- it("behavior.trigger.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.trigger.create", {
- def: { id: "broken", when: { op: "gte", path: "time.day" }, fire: [{ action: "give-item", itemId: "x", qty: 1 }] },
- });
- expect(bad.ok).toBe(false);
- expect(engine.registry.get("behavior", "broken")).toBeUndefined();
- await expect(readFile(join(tmp, "behaviors", "broken.yaml"))).rejects.toThrow();
- } finally {
- await close();
- }
- });
- it("duplicate behavior.trigger.create overwrites the existing definition", async () => {
- const { engine, gateway, tmp, close } = await setup();
- try {
- await callText(gateway, "behavior.trigger.create", { def: SPRING_GIFT_DEF });
- const recreated = await callText(gateway, "behavior.trigger.create", {
- def: { ...SPRING_GIFT_DEF, fire: [...SPRING_GIFT_DEF.fire, { action: "emit-event", event: "extra" }] },
- });
- expect(recreated.ok).toBe(true);
- const current = engine.registry.get<TriggerDef>("behavior", "spring-gift");
- expect(current?.fire).toHaveLength(2);
- const file = await readFile(join(tmp, "behaviors", "spring-gift.yaml"), "utf8");
- expect(file).toContain("extra");
- } finally {
- await close();
- }
- });
- it("behavior.trigger.update merges a patch, validates, rewrites the file, and re-registers", async () => {
- const { engine, gateway, tmp, close } = await setup();
- try {
- await callText(gateway, "behavior.trigger.create", { def: SPRING_GIFT_DEF });
- const updated = await callText(gateway, "behavior.trigger.update", {
- id: "spring-gift",
- patch: { when: { op: "gte", path: "time.day", value: 10 } },
- });
- expect(updated.ok).toBe(true);
- const def = JSON.parse(updated.text) as TriggerDef;
- expect(def.when).toEqual({ op: "gte", path: "time.day", value: 10 });
- expect(def.fire).toHaveLength(1);
- const file = await readFile(join(tmp, "behaviors", "spring-gift.yaml"), "utf8");
- expect(file).toContain("value: 10");
- const missing = await callText(gateway, "behavior.trigger.update", { id: "nope", patch: { when: SPRING_GIFT_DEF.when } });
- expect(missing.ok).toBe(false);
- expect(missing.text).toMatch(/trigger not found: nope/);
- const badPatch = await callText(gateway, "behavior.trigger.update", {
- id: "spring-gift",
- patch: { fire: [{ action: "dialogue" }] },
- });
- expect(badPatch.ok).toBe(false);
- expect(engine.registry.get<TriggerDef>("behavior", "spring-gift")?.when).toEqual({
- op: "gte",
- path: "time.day",
- value: 10,
- });
- } finally {
- await close();
- }
- });
- it("behavior.trigger.list returns {triggers:[...]} summaries", async () => {
- const { gateway, close } = await setup();
- try {
- await callText(gateway, "behavior.trigger.create", { def: SPRING_GIFT_DEF });
- await callText(gateway, "behavior.trigger.create", {
- def: { id: "hello", when: { op: "exists", path: "time.day" }, fire: [{ action: "emit-event", event: "hello" }] },
- });
- const listed = await callText(gateway, "behavior.trigger.list");
- expect(listed.ok).toBe(true);
- expect(JSON.parse(listed.text)).toEqual({
- triggers: [
- { id: "spring-gift", actionCount: 1 },
- { id: "hello", actionCount: 1 },
- ],
- });
- } finally {
- await close();
- }
- });
- it("behavior.trigger.get returns the full def; unknown id is an error result", async () => {
- const { gateway, close } = await setup();
- try {
- await callText(gateway, "behavior.trigger.create", { def: SPRING_GIFT_DEF });
- const got = await callText(gateway, "behavior.trigger.get", { triggerId: "spring-gift" });
- expect(got.ok).toBe(true);
- expect(JSON.parse(got.text)).toEqual(SPRING_GIFT_DEF);
- const missing = await callText(gateway, "behavior.trigger.get", { triggerId: "nope" });
- expect(missing.ok).toBe(false);
- expect(missing.text).toMatch(/trigger not found: nope/);
- } finally {
- await close();
- }
- });
- it("behavior.fire fires a trigger whose condition is true and returns the result", async () => {
- const { engine, gateway, close } = await setup();
- try {
- registerItems(engine);
- await callText(gateway, "behavior.trigger.create", { def: SPRING_GIFT_DEF });
- await callText(gateway, "behavior.trigger.create", { def: DAY_ONE_DEF });
- const time = engine.systems.get<TimeSystem>("time");
- time?.set(5, "spring");
- const fired = await callText(gateway, "behavior.fire", { triggerId: "spring-gift" });
- expect(fired.ok).toBe(true);
- expect(JSON.parse(fired.text)).toEqual({ triggerId: "spring-gift", fired: true });
- expect(inventoryOf(engine).count("parsnip-seed")).toBe(1);
- const notFired = await callText(gateway, "behavior.fire", { triggerId: "day-one" });
- expect(notFired.ok).toBe(true);
- expect(JSON.parse(notFired.text)).toEqual({ triggerId: "day-one", fired: false });
- } finally {
- await close();
- }
- });
- it("behavior.fire with an unknown trigger id is an error result", async () => {
- const { gateway, close } = await setup();
- try {
- const missing = await callText(gateway, "behavior.fire", { triggerId: "nope" });
- expect(missing.ok).toBe(false);
- expect(missing.text).toMatch(/unknown trigger: nope/);
- const emptyId = await callText(gateway, "behavior.fire", { triggerId: "" });
- expect(emptyId.ok).toBe(false);
- expect(emptyId.text).toMatch(/non-empty string/);
- } finally {
- await close();
- }
- });
- it("behavior.condition.validate reports valid and invalid conditions as normal results", async () => {
- const { gateway, close } = await setup();
- try {
- const valid = await callText(gateway, "behavior.condition.validate", {
- condition: { and: [{ op: "gte", path: "time.day", value: 5 }, { op: "exists", path: "payload.itemId" }] },
- });
- expect(valid.ok).toBe(true);
- expect(JSON.parse(valid.text)).toEqual({ ok: true });
- const invalid = await callText(gateway, "behavior.condition.validate", {
- condition: { op: "gte", path: "time.day" },
- });
- expect(invalid.ok).toBe(true);
- const report = JSON.parse(invalid.text) as { ok: boolean; errors?: string[] };
- expect(report.ok).toBe(false);
- expect(report.errors?.length).toBeGreaterThan(0);
- const nonObject = await callText(gateway, "behavior.condition.validate", { condition: "nonsense" });
- expect((JSON.parse(nonObject.text) as { ok: boolean }).ok).toBe(false);
- } finally {
- await close();
- }
- });
- it("resource behavior://triggers returns all trigger definitions", async () => {
- const { engine, gateway, close } = await setup();
- try {
- await callText(gateway, "behavior.trigger.create", { def: SPRING_GIFT_DEF });
- const resource = await gateway.readResource("behavior://triggers");
- expect(JSON.parse(resource.contents[0]?.text ?? "{}")).toEqual({ triggers: [SPRING_GIFT_DEF] });
- } finally {
- await close();
- }
- });
- it("serves the behavior.trigger-prompt prompt", async () => {
- const { gateway, close } = await setup();
- try {
- const prompt = await gateway.getPrompt("behavior.trigger-prompt", {});
- const text = prompt.messages[0]?.content.text ?? "";
- expect(text).toContain("when");
- expect(text).toContain("fire");
- expect(text).toContain("op: gte");
- expect(text).toContain("give-item");
- expect(text).toContain("behavior.trigger.validate");
- expect(text).toContain("content/behaviors/<id>.yaml");
- } finally {
- await close();
- }
- });
- });
|