1
0
Fork 0
polaris-task-force/tests/int/npc-dialogue-generation.int.spec.ts
Z8MB1E 4264431e4d feat(npc-dialogue): AI-assisted conversation drafting behind the review gate
Add a Generate button to the flow editor that drafts a whole conversation
from a form brief, and per-line Rewrite/Shorten/Sharpen controls in the node
dialog. Both land in unsaved field state, so a draft only reaches players when
an author saves the document: neither server action writes to npc-dialogues.

- src/lib/ai/generate.ts: extract the Unsloth client out of payload.config so
  Compose and dialogue drafting share one path; add generateStructured and
  resolveModel, with an optional UNSLOTH_MODEL_STRUCTURED override
- generationSchema.ts (pure): strict-safe JSON schema, normalizer with
  breadth layout, validator that rejects unknown flag keys, unauthorised
  effects, dangling hops and missing keys
- generation.ts: context loading, one validate-and-retry, then give up rather
  than hand back a broken graph; dash normalization keeps shipped copy clean
- effect vocabulary limited to notify and flag; emit, reward and discord stay
  author-only
- provenance group on npc-dialogues (migration 20261112_171955) records model,
  prompt version, attempts and the brief the draft was accepted from
- tests: 21 cases covering the normalizer, validator, retry paths and the
  rewrite parser, with the model call injected
- docs/npc-dialogue-ai.md and src/lib/npc-dialogue/AGENTS.md
2026-11-12 12:26:35 -05:00

405 lines
13 KiB
TypeScript

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> = {}): 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. */
function stubPayload(): Payload {
return {
findByID: async () => ({
name: "Sgt. Halden",
occupation: "Quartermaster",
location: { name: "Depot" },
faction: { name: "Task Force" },
bio: null,
levelDescription: 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");
},
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,
);
});