import type { Payload } from "payload"; import { describe, expect, it } from "vitest"; import type { DialogueNode } from "@/lib/npc-dialogue/dialogue"; import { generateDialogueDraft, rewriteDialogueLine } from "@/lib/npc-dialogue/generation"; import type { DraftRunner, LineRunner } from "@/lib/npc-dialogue/generation"; import { normalizeGeneratedFlow, validateGeneratedFlow, } from "@/lib/npc-dialogue/generationSchema"; import type { RawDraftNode } from "@/lib/npc-dialogue/generationSchema"; import type { DialogueBrief } from "@/lib/npc-dialogue/generationPrompt"; const TIMEOUT = 30_000; const BRIEF: DialogueBrief = { purpose: "quest-hook", goal: "Learn that the quartermaster is short on magazines.", outcome: "set-flag", flagKey: "met_quartermaster", tone: "clipped", size: 3, mustInclude: "", }; /** Every field, because the model's schema is strict-safe (all required). */ function rawNode(overrides: Partial = {}): RawDraftNode { return { id: "n1", type: "dialogue", isStart: true, speaker: "", body: "You're the new one.", leadIn: "", closing: "", choices: [], nextLabel: "", nextTarget: "", effectType: "none", effectTitle: "", effectMessage: "", effectFlagKey: "", effectFlagOp: "set_true", effectFlagAmount: 0, effectFlagText: "", conditionKey: "", conditionOp: "is_true", conditionAmount: 0, trueTarget: "", falseTarget: "", ...overrides, }; } /** A minimal two-node draft: one line, then an end node. */ const TINY_DRAFT: RawDraftNode[] = [ rawNode({ id: "n1", body: "You're the new one.", nextTarget: "n2" }), rawNode({ id: "n2", type: "end", isStart: false, body: "", closing: "He turns away." }), ]; function flowOf(raw: RawDraftNode[]) { return normalizeGeneratedFlow(raw); } /** Stub payload: the draft service only needs one NPC and a flag list. */ interface StubOptions { /** Global prompt settings, as the settings global would return them. */ globalVoice?: string | null; extraRules?: string | null; revision?: number | null; /** This dialogue's own voice override. */ dialogueVoice?: string | null; } function stubPayload(options: StubOptions = {}): Payload { return { findByID: async (args: { collection: string }) => args.collection === "npc-dialogues" ? { voiceOverride: options.dialogueVoice ?? null } : { name: "Sgt. Halden", occupation: "Quartermaster", location: { name: "Depot" }, faction: { name: "Task Force" }, bio: null, levelDescription: null, }, findGlobal: async () => ({ voice: options.globalVoice ?? null, extraRules: options.extraRules ?? null, revision: options.revision ?? null, }), find: async () => ({ docs: [{ key: "met_quartermaster", flagType: "boolean" }], }), } as unknown as Payload; } describe("normalizeGeneratedFlow", () => { it("assembles node data, drops empty placeholders and lays the graph out by depth", () => { const { nodes, edges, errors } = flowOf(TINY_DRAFT); expect(errors).toEqual([]); expect(nodes).toHaveLength(2); const [first, second] = nodes; // Empty speaker/closing/leadIn must not land on the node. expect(first.data).toEqual({ body: "You're the new one.", isStart: true, next: { target: "n2" } }); expect(second.data.closing).toBe("He turns away."); // Start sits at the origin, its continuation one column to the right. expect(first.position).toEqual({ x: 0, y: 0 }); expect(second.position.x).toBeGreaterThan(0); expect(edges).toHaveLength(1); expect(edges[0]).toMatchObject({ source: "n1", target: "n2" }); }); it("rejects duplicate node ids", () => { const { errors } = flowOf([ rawNode({ id: "n1" }), rawNode({ id: "n1", type: "end", isStart: false }), ]); expect(errors[0]).toContain('Duplicate node id "n1"'); }); it("rejects a node type the generator may not produce", () => { const { errors } = flowOf([ rawNode({ id: "n1" }), rawNode({ id: "n2", type: "delay" as RawDraftNode["type"], isStart: false }), ]); expect(errors.join(" ")).toContain("unsupported node type"); }); it("builds choice hops and keeps their labels", () => { const { nodes } = flowOf([ rawNode({ id: "n1", type: "choice", body: "", leadIn: "He waits.", nextTarget: "" }), rawNode({ id: "n2", type: "end", isStart: false, body: "", closing: "Done." }), ]); // Rewrite the choices properly, since the factory emits an empty list. const withChoices = flowOf([ rawNode({ id: "n1", type: "choice", body: "", leadIn: "He waits.", nextTarget: "", choices: [{ label: "What's he short on?", target: "n2", tooltip: "" }], }), rawNode({ id: "n2", type: "end", isStart: false, body: "", closing: "Done." }), ]); expect(nodes).toHaveLength(2); expect(withChoices.nodes[0].data.choices).toEqual([ { label: "What's he short on?", target: "n2" }, ]); }); }); describe("validateGeneratedFlow", () => { const KNOWN = ["met_quartermaster"]; it("accepts a clean draft", () => { const { nodes } = flowOf(TINY_DRAFT); expect(validateGeneratedFlow(nodes, KNOWN)).toEqual({ ok: true, errors: [] }); }); it("reports dangling hop targets", () => { const { nodes } = flowOf([ rawNode({ id: "n1", isStart: false, nextTarget: "n9" }), rawNode({ id: "n2", type: "end", isStart: false, body: "", closing: "Bye." }), ]); const result = validateGeneratedFlow(nodes, KNOWN); expect(result.ok).toBe(false); expect(result.errors.join(" ")).toContain('points to missing node "n9"'); }); it("rejects an unknown flag key on a condition node", () => { const { nodes } = flowOf([ rawNode({ id: "n1", type: "condition", body: "", nextTarget: "", conditionKey: "invented_flag", conditionOp: "is_true", trueTarget: "n2", falseTarget: "n2", }), rawNode({ id: "n2", type: "end", isStart: false, body: "", closing: "Bye." }), ]); const result = validateGeneratedFlow(nodes, KNOWN); expect(result.ok).toBe(false); expect(result.errors.join(" ")).toContain('unknown flag "invented_flag"'); }); it("rejects an unknown flag token in a line", () => { const { nodes } = flowOf([ rawNode({ id: "n1", body: "Status reads {{reactor_state}}.", nextTarget: "n2" }), rawNode({ id: "n2", type: "end", isStart: false, body: "", closing: "Bye." }), ]); const result = validateGeneratedFlow(nodes, KNOWN); expect(result.ok).toBe(false); expect(result.errors.join(" ")).toContain('unknown flag "reactor_state"'); }); it("skips the vocabulary check when no flags exist yet", () => { const { nodes } = flowOf([ rawNode({ id: "n1", body: "Status reads {{anything}}.", nextTarget: "n2" }), rawNode({ id: "n2", type: "end", isStart: false, body: "", closing: "Bye." }), ]); expect(validateGeneratedFlow(nodes, []).ok).toBe(true); }); it("rejects effects the generator is not allowed to configure", () => { // `emit` is stripped by normalization only when unknown; here the effect is // built from `effectType`, so force an unauthorised kind onto the node. const { nodes } = flowOf(TINY_DRAFT); const forged: DialogueNode[] = nodes.map((node, index) => index === 0 ? { ...node, data: { ...node.data, effect: { type: "emit", message: "x" } } } : node, ); const result = validateGeneratedFlow(forged, KNOWN); expect(result.ok).toBe(false); expect(result.errors.join(" ")).toContain('unauthorised effect "emit"'); }); it("rejects a flag effect that names no key", () => { const { nodes } = flowOf(TINY_DRAFT); const forged: DialogueNode[] = nodes.map((node, index) => index === 0 ? { ...node, data: { ...node.data, effect: { type: "flag", flagOp: "set_true" } } } : node, ); expect(validateGeneratedFlow(forged, KNOWN).errors.join(" ")).toContain( "flag effect with no key", ); }); }); describe("generateDialogueDraft", () => { it( "returns a flow on the first attempt when the model behaves", async () => { const calls: string[] = []; const run: DraftRunner = async (input) => { calls.push(input.prompt); return { object: { nodes: TINY_DRAFT }, truncated: false }; }; const outcome = await generateDialogueDraft( stubPayload(), { npcId: 1, brief: BRIEF }, run, ); expect(outcome.ok).toBe(true); expect(outcome.attempts).toBe(1); expect(outcome.flow?.nodes).toHaveLength(2); expect(calls).toHaveLength(1); // The brief drove the prompt, and the real flag vocabulary was supplied. expect(calls[0]).toContain("Quartermaster"); expect(calls[0]).toContain("met_quartermaster"); }, TIMEOUT, ); it( "retries once with the validator's complaints attached", async () => { const prompts: string[] = []; const run: DraftRunner = async (input) => { prompts.push(input.prompt); if (prompts.length === 1) { // Invented flag: parsable, structurally fine, still unacceptable. return { object: { nodes: [ rawNode({ id: "n1", body: "{{made_up_flag}}", nextTarget: "n2" }), rawNode({ id: "n2", type: "end", isStart: false, body: "", closing: "Bye." }), ], }, truncated: false, }; } return { object: { nodes: TINY_DRAFT }, truncated: false }; }; const outcome = await generateDialogueDraft(stubPayload(), { npcId: 1, brief: BRIEF }, run); expect(outcome.ok).toBe(true); expect(outcome.attempts).toBe(2); expect(prompts).toHaveLength(2); expect(prompts[1]).toContain("YOUR PREVIOUS ATTEMPT WAS REJECTED"); expect(prompts[1]).toContain("made_up_flag"); // The retry must ask for the shape that was requested, or it invites the // model to switch scope on the second attempt. expect(prompts[1]).toContain("return the whole conversation again"); }, TIMEOUT, ); it( "asks a retried branch draft for a branch, not a whole conversation", async () => { const prompts: string[] = []; const run: DraftRunner = async (input) => { prompts.push(input.prompt); if (prompts.length === 1) { return { object: { nodes: [ rawNode({ id: "n1", body: "{{made_up_flag}}", nextTarget: "n2" }), rawNode({ id: "n2", type: "end", isStart: false, body: "", closing: "Bye." }), ], }, truncated: false, }; } return { object: { nodes: [ rawNode({ id: "n1", isStart: false, body: "Short on magazines.", nextTarget: "n2" }), rawNode({ id: "n2", isStart: false, body: "Do not waste them." }), ], }, truncated: false, }; }; const outcome = await generateDialogueDraft( stubPayload(), { npcId: 1, brief: BRIEF, scope: "fragment" }, run, ); expect(outcome.ok).toBe(true); expect(outcome.errors).toEqual([]); expect(prompts[1]).toContain("return the whole branch again"); expect(prompts[1]).not.toContain("return the whole conversation again"); // The worked example must not teach the start flag to a branch. expect(prompts[1]).not.toContain('"isStart": true'); }, TIMEOUT, ); it( "gives up after two attempts instead of handing back a broken graph", async () => { const run: DraftRunner = async () => ({ object: { nodes: [rawNode({ id: "n1", nextTarget: "ghost" })] }, truncated: false, }); const outcome = await generateDialogueDraft(stubPayload(), { npcId: 1, brief: BRIEF }, run); expect(outcome.ok).toBe(false); expect(outcome.flow).toBeUndefined(); expect(outcome.attempts).toBe(2); expect(outcome.errors.join(" ")).toContain('points to missing node "ghost"'); }, TIMEOUT, ); it( "treats an unparsable generation as a failed attempt, not a crash", async () => { let calls = 0; const run: DraftRunner = async () => { calls += 1; if (calls === 1) throw new Error("Unexpected token in JSON"); return { object: { nodes: TINY_DRAFT }, truncated: false }; }; const outcome = await generateDialogueDraft(stubPayload(), { npcId: 1, brief: BRIEF }, run); expect(outcome.ok).toBe(true); expect(calls).toBe(2); }, TIMEOUT, ); it( "reports truncation so a cut-off draft is not mistaken for a complete one", async () => { const run: DraftRunner = async () => ({ object: { nodes: TINY_DRAFT }, truncated: true }); const outcome = await generateDialogueDraft(stubPayload(), { npcId: 1, brief: BRIEF }, run); expect(outcome.truncated).toBe(true); }, TIMEOUT, ); }); describe("rewriteDialogueLine", () => { const INPUT = { npcId: 1, action: "rewrite" as const, text: "You're the new one. Quartermaster's through that door.", nodeType: "dialogue", }; it( "returns the model's line, stripped of the quoting it tends to add", async () => { const run: LineRunner = async () => ({ text: '"So you\'re the replacement. He\'s inside."' }); const outcome = await rewriteDialogueLine(stubPayload(), INPUT, run); expect(outcome.ok).toBe(true); expect(outcome.text).toBe("So you're the replacement. He's inside."); }, TIMEOUT, ); it( "normalises em and en dashes, which must never reach shipped copy", async () => { const run: LineRunner = async () => ({ text: "He shrugs\u2014then points inside. Rounds 1\u201320." }); const outcome = await rewriteDialogueLine(stubPayload(), INPUT, run); expect(outcome.text).toBe("He shrugs, then points inside. Rounds 1-20."); }, TIMEOUT, ); it( "refuses to spend a call on an empty field", async () => { let called = false; const run: LineRunner = async () => { called = true; return { text: "x" }; }; const outcome = await rewriteDialogueLine(stubPayload(), { ...INPUT, text: " " }, run); expect(outcome.ok).toBe(false); expect(called).toBe(false); }, TIMEOUT, ); it( "reports an empty completion instead of clearing the author's line", async () => { const run: LineRunner = async () => ({ text: "```\n\n```" }); const outcome = await rewriteDialogueLine(stubPayload(), INPUT, run); expect(outcome.ok).toBe(false); expect(outcome.text).toBe(""); expect(outcome.error).toContain("nothing usable"); }, TIMEOUT, ); it( "sends the previous line so a rewrite does not restate it", async () => { let prompt = ""; const run: LineRunner = async (input) => { prompt = input.prompt; return { text: "Fine." }; }; await rewriteDialogueLine( stubPayload(), { ...INPUT, previousLine: "You're late." }, run, ); expect(prompt).toContain("You're late."); expect(prompt).toContain("Sgt. Halden"); }, TIMEOUT, ); }); /** * The voice is configuration, so what matters is that the configured text reaches * the model and that the draft records which voice shaped it. Both are checked * against the runner's system prompt rather than the composer in isolation. */ describe("generateDialogueDraft prompt settings", () => { it( "sends the global voice and records it in provenance", async () => { let system = ""; const run: DraftRunner = async (input) => { system = input.system; return { object: { nodes: TINY_DRAFT }, truncated: false }; }; const outcome = await generateDialogueDraft( stubPayload({ globalVoice: "Bored conscript, allergic to ceremony.", revision: 12 }), { npcId: 1, brief: BRIEF }, run, ); expect(outcome.ok).toBe(true); expect(outcome.promptSource).toBe("global"); expect(outcome.promptRevision).toBe(12); expect(system).toContain("Bored conscript, allergic to ceremony."); expect(system).not.toContain("Write like a soldier with limited patience"); // The contract is never replaced by a custom voice. expect(system).toContain("Return one JSON object matching the provided schema."); }, TIMEOUT, ); it( "lets a dialogue override win over the global voice", async () => { let system = ""; const run: DraftRunner = async (input) => { system = input.system; return { object: { nodes: TINY_DRAFT }, truncated: false }; }; const outcome = await generateDialogueDraft( stubPayload({ globalVoice: "The whole unit talks like this.", dialogueVoice: "This one talks like that.", revision: 3, }), { npcId: 1, brief: BRIEF, dialogueId: 5 }, run, ); expect(outcome.promptSource).toBe("dialogue"); expect(system).toContain("This one talks like that."); expect(system).not.toContain("The whole unit talks like this."); }, TIMEOUT, ); it( "adds house rules even when no custom voice applies", async () => { let system = ""; const run: DraftRunner = async (input) => { system = input.system; return { object: { nodes: TINY_DRAFT }, truncated: false }; }; const outcome = await generateDialogueDraft( stubPayload({ extraRules: "Never call the unit an army." }), { npcId: 1, brief: BRIEF }, run, ); expect(outcome.promptSource).toBe("builtin"); expect(system).toContain("HOUSE RULES\nNever call the unit an army."); expect(system).toContain("Write like a soldier with limited patience"); }, TIMEOUT, ); it( "names the custom prompt when both attempts fail, so the author knows where to look", async () => { const run: DraftRunner = async () => ({ object: { nodes: [rawNode({ id: "n1", nextTarget: "ghost" })] }, truncated: false, }); const outcome = await generateDialogueDraft( stubPayload({ globalVoice: "Something the model cannot follow.", revision: 2 }), { npcId: 1, brief: BRIEF }, run, ); expect(outcome.ok).toBe(false); expect(outcome.promptSource).toBe("global"); expect(outcome.errors.join(" ")).toContain("global"); expect(outcome.errors.join(" ")).toContain("before blaming the model"); }, TIMEOUT, ); it( "leaves a built-in failure without the custom-prompt hint", async () => { const run: DraftRunner = async () => ({ object: { nodes: [rawNode({ id: "n1", nextTarget: "ghost" })] }, truncated: false, }); const outcome = await generateDialogueDraft(stubPayload(), { npcId: 1, brief: BRIEF }, run); expect(outcome.promptSource).toBe("builtin"); expect(outcome.errors.join(" ")).not.toContain("before blaming the model"); }, TIMEOUT, ); }); describe("rewriteDialogueLine prompt settings", () => { const REWRITE = { npcId: 1, action: "rewrite" as const, text: "You're the new one.", nodeType: "dialogue", }; it( "applies the custom voice to a rewrite so it matches the draft register", async () => { let system = ""; const run: LineRunner = async (input) => { system = input.system; return { text: "Move it, replacement." }; }; await rewriteDialogueLine(stubPayload({ globalVoice: "Terse and tired." }), REWRITE, run); expect(system).toContain("HOUSE VOICE"); expect(system).toContain("Terse and tired."); }, TIMEOUT, ); it( "keeps the plain instruction when no custom voice is set", async () => { let system = ""; const run: LineRunner = async (input) => { system = input.system; return { text: "Move it." }; }; await rewriteDialogueLine(stubPayload(), REWRITE, run); expect(system).not.toContain("HOUSE VOICE"); expect(system).toContain("You edit dialogue lines"); }, TIMEOUT, ); });