create-session-command-fact.test.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { describe, expect, it, vi } from "vitest";
  2. import type { SessionId, SessionInputRecord, SessionStorePort } from "@zcode/contracts";
  3. import { lookupGlobalCreateSessionCommand } from "../src/zcode-protocol-v4/create-session-command-fact.js";
  4. const sessionId = "session-created-first" as SessionId;
  5. function record(status: SessionInputRecord["status"]): SessionInputRecord {
  6. return {
  7. id: "queue_create-command",
  8. sessionID: sessionId,
  9. kind: "sendText",
  10. delivery: "queue",
  11. payload: {
  12. text: "first input",
  13. sourceCommandType: "createSession",
  14. conversationInputIntent: { sourceCommandId: "create-command" },
  15. },
  16. admittedSequence: 0,
  17. status,
  18. time: { created: 1, updated: 1 },
  19. };
  20. }
  21. describe("global createSession command fact", () => {
  22. it("promoted firstInput 在 ACK 丢失/重启后返回第一次创建的 session", async () => {
  23. const store = {
  24. getSessionInputById: vi.fn().mockResolvedValue(record("promoted")),
  25. } as unknown as SessionStorePort;
  26. await expect(lookupGlobalCreateSessionCommand(store, "create-command")).resolves.toEqual({
  27. commandId: "create-command",
  28. status: "accepted",
  29. revisionAtDecision: 0,
  30. result: { type: "createSession", sessionId },
  31. });
  32. expect(store.getSessionInputById).toHaveBeenCalledWith("queue_create-command");
  33. });
  34. it("restart 前仅 admitted 的 firstInput 显式 discarded,不创建第二个 session", async () => {
  35. const settleSessionInput = vi.fn().mockResolvedValue(undefined);
  36. const store = {
  37. getSessionInputById: vi.fn().mockResolvedValue(record("admitted")),
  38. settleSessionInput,
  39. } as unknown as SessionStorePort;
  40. await expect(lookupGlobalCreateSessionCommand(store, "create-command")).resolves.toMatchObject({
  41. commandId: "create-command",
  42. status: "failed",
  43. reasonCode: "fault.command.inputDiscardedOnRestart",
  44. });
  45. expect(settleSessionInput).toHaveBeenCalledWith({
  46. id: "queue_create-command",
  47. sessionID: sessionId,
  48. status: "discarded",
  49. reason: "session_resumed",
  50. });
  51. });
  52. it("普通 sendText 的同名 ledger 不能冒充 global createSession fact", async () => {
  53. const ordinary = record("promoted");
  54. ordinary.payload.sourceCommandType = "sendText";
  55. const store = {
  56. getSessionInputById: vi.fn().mockResolvedValue(ordinary),
  57. } as unknown as SessionStorePort;
  58. await expect(lookupGlobalCreateSessionCommand(store, "create-command")).resolves.toBeNull();
  59. });
  60. });