behavior-namespace.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { describe, expect, it } from "vitest";
  5. import { createEngine, type InventorySystem, type TimeSystem, type TriggerDef } from "@nengine/core";
  6. import { createEngineNamespaces, McpGateway } from "../src/index.js";
  7. const TIME_YAML = [
  8. "id: default",
  9. "dayLengthTicks: 480",
  10. "seasons:",
  11. " - { name: spring, dayCount: 28 }",
  12. "start: { day: 1, season: spring }",
  13. "",
  14. ].join("\n");
  15. const FARM_YAML = [
  16. "id: farm",
  17. "width: 2",
  18. "height: 2",
  19. 'tilesetRef: "tiles"',
  20. "spawn: { x: 0, y: 0 }",
  21. "layers:",
  22. " - name: ground",
  23. " data:",
  24. " - [a, b]",
  25. " - [b, a]",
  26. "",
  27. ].join("\n");
  28. const SPRING_GIFT_DEF = {
  29. id: "spring-gift",
  30. when: { op: "gte", path: "time.day", value: 5 },
  31. fire: [{ action: "give-item", itemId: "parsnip-seed", qty: 1 }],
  32. };
  33. const DAY_ONE_DEF = {
  34. id: "day-one",
  35. when: { op: "eq", path: "time.day", value: 1 },
  36. fire: [{ action: "emit-event", event: "behavior:day-one", payload: { day: 1 } }],
  37. };
  38. interface Setup {
  39. engine: ReturnType<typeof createEngine>;
  40. gateway: McpGateway;
  41. tmp: string;
  42. close: () => Promise<void>;
  43. }
  44. async function setup(): Promise<Setup> {
  45. const tmp = await mkdtemp(join(tmpdir(), "farm-behavior-"));
  46. await mkdir(join(tmp, "maps"), { recursive: true });
  47. await writeFile(join(tmp, "time.yaml"), TIME_YAML);
  48. await writeFile(join(tmp, "maps", "farm.yaml"), FARM_YAML);
  49. const engine = createEngine({ contentDir: tmp });
  50. const gateway = new McpGateway();
  51. for (const namespace of createEngineNamespaces(engine, { gateway })) {
  52. gateway.register(namespace);
  53. }
  54. await engine.start();
  55. return {
  56. engine,
  57. gateway,
  58. tmp,
  59. close: async () => {
  60. await engine.stop();
  61. await rm(tmp, { recursive: true, force: true });
  62. },
  63. };
  64. }
  65. async function callText(gateway: McpGateway, name: string, args: Record<string, unknown> = {}): Promise<{
  66. ok: boolean;
  67. text: string;
  68. }> {
  69. const result = await gateway.callTool(name, args);
  70. return { ok: result.isError !== true, text: result.content[0]?.text ?? "" };
  71. }
  72. function registerItems(engine: ReturnType<typeof createEngine>): void {
  73. engine.registry.register("item", { id: "hoe", name: "Hoe", kind: "tool", stackable: false });
  74. engine.registry.register("item", { id: "parsnip-seed", name: "Parsnip Seed", kind: "seed", stackable: true });
  75. engine.registry.register("item", { id: "parsnip", name: "Parsnip", kind: "material", stackable: true });
  76. }
  77. function inventoryOf(engine: ReturnType<typeof createEngine>): InventorySystem {
  78. const inv = engine.systems.get<InventorySystem>("inventory");
  79. if (!inv) throw new Error("inventory system not booted");
  80. return inv;
  81. }
  82. describe("behavior namespace", () => {
  83. it("behavior.trigger.create writes content/behaviors/<id>.yaml, registers live, and persists across restart", async () => {
  84. const { engine, gateway, tmp, close } = await setup();
  85. try {
  86. const created = await callText(gateway, "behavior.trigger.create", { def: SPRING_GIFT_DEF });
  87. expect(created.ok).toBe(true);
  88. expect(JSON.parse(created.text) as TriggerDef).toEqual(SPRING_GIFT_DEF);
  89. expect(engine.registry.get<TriggerDef>("behavior", "spring-gift")).toEqual(SPRING_GIFT_DEF);
  90. const file = await readFile(join(tmp, "behaviors", "spring-gift.yaml"), "utf8");
  91. expect(file).toContain("id: spring-gift");
  92. expect(file).toContain("op: gte");
  93. expect(file).toContain("give-item");
  94. await engine.stop();
  95. const reloaded = createEngine({ contentDir: tmp });
  96. await reloaded.start();
  97. try {
  98. expect(reloaded.registry.get<TriggerDef>("behavior", "spring-gift")).toEqual(SPRING_GIFT_DEF);
  99. } finally {
  100. await reloaded.stop();
  101. }
  102. } finally {
  103. await close();
  104. }
  105. });
  106. it("behavior.trigger.validate accepts a valid def and rejects an invalid one", async () => {
  107. const { gateway, close } = await setup();
  108. try {
  109. const valid = await callText(gateway, "behavior.trigger.validate", { def: SPRING_GIFT_DEF });
  110. expect(valid.ok).toBe(true);
  111. expect(JSON.parse(valid.text)).toEqual(SPRING_GIFT_DEF);
  112. const badOp = await callText(gateway, "behavior.trigger.validate", {
  113. def: { id: "nope", when: { op: "bogus", path: "time.day", value: 1 }, fire: [{ action: "emit-event", event: "x" }] },
  114. });
  115. expect(badOp.ok).toBe(false);
  116. expect(badOp.text).toMatch(/when/);
  117. const emptyFire = await callText(gateway, "behavior.trigger.validate", {
  118. def: { id: "nope", when: { op: "exists", path: "time.day" }, fire: [] },
  119. });
  120. expect(emptyFire.ok).toBe(false);
  121. expect(emptyFire.text).toMatch(/fire/);
  122. const badAction = await callText(gateway, "behavior.trigger.validate", {
  123. def: { id: "nope", when: { op: "exists", path: "time.day" }, fire: [{ action: "explode" }] },
  124. });
  125. expect(badAction.ok).toBe(false);
  126. } finally {
  127. await close();
  128. }
  129. });
  130. it("behavior.trigger.create rejects an invalid def and does not write or register", async () => {
  131. const { engine, gateway, tmp, close } = await setup();
  132. try {
  133. const bad = await callText(gateway, "behavior.trigger.create", {
  134. def: { id: "broken", when: { op: "gte", path: "time.day" }, fire: [{ action: "give-item", itemId: "x", qty: 1 }] },
  135. });
  136. expect(bad.ok).toBe(false);
  137. expect(engine.registry.get("behavior", "broken")).toBeUndefined();
  138. await expect(readFile(join(tmp, "behaviors", "broken.yaml"))).rejects.toThrow();
  139. } finally {
  140. await close();
  141. }
  142. });
  143. it("duplicate behavior.trigger.create overwrites the existing definition", async () => {
  144. const { engine, gateway, tmp, close } = await setup();
  145. try {
  146. await callText(gateway, "behavior.trigger.create", { def: SPRING_GIFT_DEF });
  147. const recreated = await callText(gateway, "behavior.trigger.create", {
  148. def: { ...SPRING_GIFT_DEF, fire: [...SPRING_GIFT_DEF.fire, { action: "emit-event", event: "extra" }] },
  149. });
  150. expect(recreated.ok).toBe(true);
  151. const current = engine.registry.get<TriggerDef>("behavior", "spring-gift");
  152. expect(current?.fire).toHaveLength(2);
  153. const file = await readFile(join(tmp, "behaviors", "spring-gift.yaml"), "utf8");
  154. expect(file).toContain("extra");
  155. } finally {
  156. await close();
  157. }
  158. });
  159. it("behavior.trigger.update merges a patch, validates, rewrites the file, and re-registers", async () => {
  160. const { engine, gateway, tmp, close } = await setup();
  161. try {
  162. await callText(gateway, "behavior.trigger.create", { def: SPRING_GIFT_DEF });
  163. const updated = await callText(gateway, "behavior.trigger.update", {
  164. id: "spring-gift",
  165. patch: { when: { op: "gte", path: "time.day", value: 10 } },
  166. });
  167. expect(updated.ok).toBe(true);
  168. const def = JSON.parse(updated.text) as TriggerDef;
  169. expect(def.when).toEqual({ op: "gte", path: "time.day", value: 10 });
  170. expect(def.fire).toHaveLength(1);
  171. const file = await readFile(join(tmp, "behaviors", "spring-gift.yaml"), "utf8");
  172. expect(file).toContain("value: 10");
  173. const missing = await callText(gateway, "behavior.trigger.update", { id: "nope", patch: { when: SPRING_GIFT_DEF.when } });
  174. expect(missing.ok).toBe(false);
  175. expect(missing.text).toMatch(/trigger not found: nope/);
  176. const badPatch = await callText(gateway, "behavior.trigger.update", {
  177. id: "spring-gift",
  178. patch: { fire: [{ action: "dialogue" }] },
  179. });
  180. expect(badPatch.ok).toBe(false);
  181. expect(engine.registry.get<TriggerDef>("behavior", "spring-gift")?.when).toEqual({
  182. op: "gte",
  183. path: "time.day",
  184. value: 10,
  185. });
  186. } finally {
  187. await close();
  188. }
  189. });
  190. it("behavior.trigger.list returns {triggers:[...]} summaries", async () => {
  191. const { gateway, close } = await setup();
  192. try {
  193. await callText(gateway, "behavior.trigger.create", { def: SPRING_GIFT_DEF });
  194. await callText(gateway, "behavior.trigger.create", {
  195. def: { id: "hello", when: { op: "exists", path: "time.day" }, fire: [{ action: "emit-event", event: "hello" }] },
  196. });
  197. const listed = await callText(gateway, "behavior.trigger.list");
  198. expect(listed.ok).toBe(true);
  199. expect(JSON.parse(listed.text)).toEqual({
  200. triggers: [
  201. { id: "spring-gift", actionCount: 1 },
  202. { id: "hello", actionCount: 1 },
  203. ],
  204. });
  205. } finally {
  206. await close();
  207. }
  208. });
  209. it("behavior.trigger.get returns the full def; unknown id is an error result", async () => {
  210. const { gateway, close } = await setup();
  211. try {
  212. await callText(gateway, "behavior.trigger.create", { def: SPRING_GIFT_DEF });
  213. const got = await callText(gateway, "behavior.trigger.get", { triggerId: "spring-gift" });
  214. expect(got.ok).toBe(true);
  215. expect(JSON.parse(got.text)).toEqual(SPRING_GIFT_DEF);
  216. const missing = await callText(gateway, "behavior.trigger.get", { triggerId: "nope" });
  217. expect(missing.ok).toBe(false);
  218. expect(missing.text).toMatch(/trigger not found: nope/);
  219. } finally {
  220. await close();
  221. }
  222. });
  223. it("behavior.fire fires a trigger whose condition is true and returns the result", async () => {
  224. const { engine, gateway, close } = await setup();
  225. try {
  226. registerItems(engine);
  227. await callText(gateway, "behavior.trigger.create", { def: SPRING_GIFT_DEF });
  228. await callText(gateway, "behavior.trigger.create", { def: DAY_ONE_DEF });
  229. const time = engine.systems.get<TimeSystem>("time");
  230. time?.set(5, "spring");
  231. const fired = await callText(gateway, "behavior.fire", { triggerId: "spring-gift" });
  232. expect(fired.ok).toBe(true);
  233. expect(JSON.parse(fired.text)).toEqual({ triggerId: "spring-gift", fired: true });
  234. expect(inventoryOf(engine).count("parsnip-seed")).toBe(1);
  235. const notFired = await callText(gateway, "behavior.fire", { triggerId: "day-one" });
  236. expect(notFired.ok).toBe(true);
  237. expect(JSON.parse(notFired.text)).toEqual({ triggerId: "day-one", fired: false });
  238. } finally {
  239. await close();
  240. }
  241. });
  242. it("behavior.fire with an unknown trigger id is an error result", async () => {
  243. const { gateway, close } = await setup();
  244. try {
  245. const missing = await callText(gateway, "behavior.fire", { triggerId: "nope" });
  246. expect(missing.ok).toBe(false);
  247. expect(missing.text).toMatch(/unknown trigger: nope/);
  248. const emptyId = await callText(gateway, "behavior.fire", { triggerId: "" });
  249. expect(emptyId.ok).toBe(false);
  250. expect(emptyId.text).toMatch(/non-empty string/);
  251. } finally {
  252. await close();
  253. }
  254. });
  255. it("behavior.condition.validate reports valid and invalid conditions as normal results", async () => {
  256. const { gateway, close } = await setup();
  257. try {
  258. const valid = await callText(gateway, "behavior.condition.validate", {
  259. condition: { and: [{ op: "gte", path: "time.day", value: 5 }, { op: "exists", path: "payload.itemId" }] },
  260. });
  261. expect(valid.ok).toBe(true);
  262. expect(JSON.parse(valid.text)).toEqual({ ok: true });
  263. const invalid = await callText(gateway, "behavior.condition.validate", {
  264. condition: { op: "gte", path: "time.day" },
  265. });
  266. expect(invalid.ok).toBe(true);
  267. const report = JSON.parse(invalid.text) as { ok: boolean; errors?: string[] };
  268. expect(report.ok).toBe(false);
  269. expect(report.errors?.length).toBeGreaterThan(0);
  270. const nonObject = await callText(gateway, "behavior.condition.validate", { condition: "nonsense" });
  271. expect((JSON.parse(nonObject.text) as { ok: boolean }).ok).toBe(false);
  272. } finally {
  273. await close();
  274. }
  275. });
  276. it("resource behavior://triggers returns all trigger definitions", async () => {
  277. const { engine, gateway, close } = await setup();
  278. try {
  279. await callText(gateway, "behavior.trigger.create", { def: SPRING_GIFT_DEF });
  280. const resource = await gateway.readResource("behavior://triggers");
  281. expect(JSON.parse(resource.contents[0]?.text ?? "{}")).toEqual({ triggers: [SPRING_GIFT_DEF] });
  282. } finally {
  283. await close();
  284. }
  285. });
  286. it("serves the behavior.trigger-prompt prompt", async () => {
  287. const { gateway, close } = await setup();
  288. try {
  289. const prompt = await gateway.getPrompt("behavior.trigger-prompt", {});
  290. const text = prompt.messages[0]?.content.text ?? "";
  291. expect(text).toContain("when");
  292. expect(text).toContain("fire");
  293. expect(text).toContain("op: gte");
  294. expect(text).toContain("give-item");
  295. expect(text).toContain("behavior.trigger.validate");
  296. expect(text).toContain("content/behaviors/<id>.yaml");
  297. } finally {
  298. await close();
  299. }
  300. });
  301. });