1
0
Fork 0

feat(npc-dialogue): make the AI prompt voice configurable

The system prompt was a single constant, so tuning how drafted dialogue
sounds meant editing code and redeploying. Split it into the half that is
copy and the half that is a contract.

VOICE and optional HOUSE RULES are now editable from a new
`npc-dialogue-settings` global, and per conversation through an
`voiceOverride` field on `npc-dialogues`. Precedence is dialogue, then
global, then the built-in default, resolved by the pure `resolveVoice`.
STRUCTURE, FIELDS, STATE, OUTPUT and the worked example stay in
`LOCKED_RULES`: the draft validator enforces the same rules, so an edit
there would make every draft fail for reasons an author cannot trace.

Both surfaces render the assembled prompt through the same pure
composer the server calls, so the preview cannot drift from what the
model receives. The global normalises dashes on save, bumps `revision`
only on a real text change, and keeps 20 versions for rollback.

Provenance gains `promptSource` and `promptRevision` so a stored draft
still names the voice that shaped it. A draft that fails twice while a
custom voice is active now says so, instead of looking like a model bug.

`composeDialogueSystemPrompt()` with no arguments reproduces the old
prompt byte for byte, pinned by a golden fixture.
This commit is contained in:
Jason Fraley 2026-11-24 12:53:33 -05:00
parent 532a9a6459
commit de27a53044
23 changed files with 48094 additions and 52 deletions

View file

@ -64,8 +64,32 @@ short worked example. The example matters more than any instruction for a 9B
model: it fixes the id convention, the empty-string convention and the register
in one shot.
### Effects are restricted
### The voice is editable, the contract is not
The system prompt has two halves, and the split is deliberate:
- **VOICE** and optional **HOUSE RULES** are copy. They are editable from
**Settings → NPC Dialogue Prompt** (`npc-dialogue-settings`) and per conversation
under **AI Drafting → Voice override** on the `npc-dialogues` document.
Precedence is: this dialogue, then the global setting, then the built-in default
in `DEFAULT_VOICE`.
- **STRUCTURE**, **FIELDS**, **STATE** and **OUTPUT** are a contract. They live in
`LOCKED_RULES` and stay in code because `generationSchema.ts` and
`validateGeneratedFlow` enforce the same rules. A prompt that contradicted them
would make every draft fail for a reason the author could not trace.
Both editing surfaces show the *assembled* prompt, composed with the same pure
helpers the server calls (`composeDialogueSystemPrompt`), so the preview cannot
drift from what the model receives. Because the global is read per request, an
edit applies to the next draft with no deploy. `revision` increments only when the
text actually changes, and the last 20 versions are kept for rollback.
`composeDialogueSystemPrompt()` with no arguments reproduces the pre-settings
prompt byte for byte; a golden fixture in
`tests/int/npc-dialogue-prompt-settings.int.spec.ts` enforces that. When you
change the prompt on purpose, update the fixture and bump `PROMPT_VERSION`.
### Effects are restricted
The JSON schema only offers `none`, `notify` and `flag`. `emit`, `reward` and
`discord` are absent from the schema, and `validateGeneratedFlow` rejects them
again if a model smuggles one through an unknown key. Those write game state or
@ -94,9 +118,14 @@ right by breadth from the start node.
## Provenance
`npc-dialogues.generation` (`model`, `promptVersion`, `attempts`, `generatedAt`,
`brief`) is written when a draft lands and persisted by the save that accepts it.
It describes the draft that was accepted, not every attempt.
`npc-dialogues.generation` (`model`, `promptVersion`, `promptSource`,
`promptRevision`, `attempts`, `generatedAt`, `brief`) is written when a draft lands
and persisted by the save that accepts it. It describes the draft that was
accepted, not every attempt.
`promptSource` says which voice shaped it (`builtin`, `global` or `dialogue`) and
`promptRevision` records the settings revision in force, so a draft made under a
voice that has since been edited is still identifiable.
**Deliberate omission:** the model's raw pre-normalization output is not stored.
It duplicates the graph, is mostly placeholder empty strings, and would be
@ -116,6 +145,10 @@ Everything resolves through `src/lib/ai/generate.ts`:
structured work only, for the case where prose and graph generation want
different GGUFs.
An admin-configurable connection selector records providers in the database, so a
remote model can be chosen without an env change. When a connection is active its
label and model id are recorded in provenance instead of the env-derived model.
`reasoning_effort: "none"` is sent on every request. Ornith is a reasoning model
and with a small token budget its reasoning block consumes the whole allowance,
leaving `content` empty.
@ -124,9 +157,17 @@ leaving `content` empty.
`tests/int/npc-dialogue-generation.int.spec.ts` covers the normalizer, the
validator (unknown flags, invented effects, dangling hops, missing keys), the
retry path, the give-up path, truncation reporting, and the rewrite parser (quote
stripping, dash normalisation, empty completion). The model call is injected, so
none of these tests need the model host.
retry path, the give-up path, truncation reporting, the rewrite parser (quote
stripping, dash normalisation, empty completion), and which voice reaches the
model. The model call is injected, so none of these tests need the model host.
`tests/int/npc-dialogue-prompt-settings.int.spec.ts` pins the composer: a golden
fixture of the pre-settings prompt, voice precedence, house-rule placement, and
dash normalisation.
`tests/int/npc-dialogue-settings-global.int.spec.ts` round-trips the settings
global through real Payload: dash normalisation on save, revision moving only on a
real change, version history, and the `loadDialogueSettings` read path.
## Changing the prompts safely
@ -134,5 +175,11 @@ none of these tests need the model host.
2. Run the integration spec (it pins the observable behaviour, not the wording).
3. Draft one conversation against a real contact and read the lines.
For register changes only, do not edit code at all: use **Settings → NPC Dialogue
Prompt**, or a single conversation's **AI Drafting → Voice override**. Neither
touches `PROMPT_VERSION`, because the contract did not change. Check the preview on
the settings page before drafting, and the provenance panel afterwards to confirm
which voice applied.
A 9B model drifts badly past about ten nodes. Keep generated drafts short and let
authors extend the graph by hand.

View file

@ -14,6 +14,7 @@ import { markNodeRead } from "@/lib/npc-dialogue/states";
import { resolveAttachments } from "@/lib/npc-dialogue/attachments";
import { hasPermission } from "@/utils/access-control/hasPermission";
import { generateDialogueDraft, rewriteDialogueLine } from "@/lib/npc-dialogue/generation";
import { loadDialogueSettings } from "@/lib/npc-dialogue/generationSettings";
import {
BRIEF_OUTCOMES,
BRIEF_PURPOSES,
@ -413,12 +414,16 @@ export async function uploadNpcDialogueAttachment(
}
}
/** What a successful draft hands back to the editor. */export interface GeneratedDialogueDraft {
/** What a successful draft hands back to the editor. */
export interface GeneratedDialogueDraft {
/** The graph to drop into the canvas. Never persisted by the server action. */
flow: FlowData;
attempts: number;
model: string;
promptVersion: string;
/** Which voice shaped the prompt, for the dialog's provenance line. */
promptSource: "builtin" | "global" | "dialogue";
promptRevision: number | null;
/** True when the model hit its token cap, so the tail of the draft may be missing. */
truncated: boolean;
}
@ -466,6 +471,33 @@ export async function listDialogueFlagKeys(): Promise<
}
}
/**
* The global prompt settings, for the dialogue editor's preview.
*
* Read-only and safe to expose to anyone who can author conversations: the voice
* is copy, not a secret. The editor composes the preview client-side with the same
* pure helpers the server uses, so unsaved voice edits show up immediately.
*/
export async function getDialoguePromptSettings(): Promise<
ActionResult<{ voice: string | null; extraRules: string | null; revision: number | null }>
> {
try {
const { payload, user } = await authenticate();
if (!(await hasPermission(payload, user, "npc-dialogues:read"))) {
return { success: false, error: "You do not have permission to view conversations." };
}
const settings = await loadDialogueSettings(payload);
return { success: true, data: settings };
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
if (message === "Unauthorized") {
return { success: false, error: "You must be logged in." };
}
return { success: false, error: message };
}
}
/**
* Drafts a conversation for one contact from an author brief.
*
@ -476,6 +508,7 @@ export async function listDialogueFlagKeys(): Promise<
export async function generateNpcDialogueDraft(
npcId: number,
brief: DialogueBrief,
dialogueId?: number | null,
): Promise<ActionResult<GeneratedDialogueDraft>> {
try {
const { payload, user } = await authenticate();
@ -512,6 +545,7 @@ export async function generateNpcDialogueDraft(
const outcome = await generateDialogueDraft(payload, {
npcId,
brief: { ...brief, goal },
dialogueId: dialogueId ?? null,
});
if (!outcome.ok || !outcome.flow) {
@ -530,6 +564,8 @@ export async function generateNpcDialogueDraft(
attempts: outcome.attempts,
model: outcome.model,
promptVersion: outcome.promptVersion,
promptSource: outcome.promptSource,
promptRevision: outcome.promptRevision,
truncated: outcome.truncated,
},
};
@ -555,6 +591,7 @@ export async function rewriteNpcDialogueLine(
text: string;
nodeType: string;
previousLine?: string;
dialogueId?: number | null;
},
): Promise<ActionResult<{ text: string }>> {
try {
@ -584,6 +621,7 @@ export async function rewriteNpcDialogueLine(
text,
nodeType: input.nodeType,
previousLine: input.previousLine,
dialogueId: input.dialogueId ?? null,
});
if (!outcome.ok) {

View file

@ -27,6 +27,7 @@ import { ItalicFeatureClient as ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0
import { ComposeField as ComposeField_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client'
import { default as default_5b78ffdfa54ff25f104b8b2d7d755857 } from '@/components/admin/game/LaborCrewField'
import { default as default_163cd5fa19b83af73532cccaf34704fb } from '@/components/admin/npc-dialogue/NpcDialogueEditor'
import { DialoguePromptPreview as DialoguePromptPreview_934496efaa6ade9a34c5ce016825a43f } from '@/components/admin/npc-dialogue/PromptPreview'
import { default as default_513af5ed43d616d133e530d8c94232f8 } from '@/components/admin/groups/CollapsibleGroupField'
import { default as default_d9c22b951ac6762f436db59b889da382 } from '@/components/admin/awards/CommendationColorField'
import { default as default_c3ea68702b5e5f8f2f98055e01c43c8d } from '@/components/admin/awards/RibbonDesigner'
@ -42,6 +43,7 @@ import { default as default_b7f86fb8e028bca592f57e6d387a0380 } from '@/component
import { SelectField as SelectField_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client'
import { PromptEditorField as PromptEditorField_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client'
import { default as default_b16af798585cda7cfed92f7b1dd0c707 } from '@/components/admin/shims/ShimContentField'
import { GlobalPromptPreview as GlobalPromptPreview_934496efaa6ade9a34c5ce016825a43f } from '@/components/admin/npc-dialogue/PromptPreview'
import { default as default_a6bf792526e9f56202161f190c57e1c6 } from '@/components/admin/tech-tree/TechTreeNav'
import { default as default_2f6c866ab4d4d51b3789f090b84b85c7 } from '@/components/static/VersionOverlay'
import { default as default_508743824696caae2894ebf34c2e68bb } from '@/components/graphics/AppIcon'
@ -85,6 +87,7 @@ export const importMap = {
"@ai-stack/payloadcms/client#ComposeField": ComposeField_4490b89d4413c1ffaecdacfe72efaf73,
"@/components/admin/game/LaborCrewField#default": default_5b78ffdfa54ff25f104b8b2d7d755857,
"@/components/admin/npc-dialogue/NpcDialogueEditor#default": default_163cd5fa19b83af73532cccaf34704fb,
"@/components/admin/npc-dialogue/PromptPreview#DialoguePromptPreview": DialoguePromptPreview_934496efaa6ade9a34c5ce016825a43f,
"@/components/admin/groups/CollapsibleGroupField#default": default_513af5ed43d616d133e530d8c94232f8,
"@/components/admin/awards/CommendationColorField#default": default_d9c22b951ac6762f436db59b889da382,
"@/components/admin/awards/RibbonDesigner#default": default_c3ea68702b5e5f8f2f98055e01c43c8d,
@ -100,6 +103,7 @@ export const importMap = {
"@ai-stack/payloadcms/client#SelectField": SelectField_4490b89d4413c1ffaecdacfe72efaf73,
"@ai-stack/payloadcms/client#PromptEditorField": PromptEditorField_4490b89d4413c1ffaecdacfe72efaf73,
"@/components/admin/shims/ShimContentField#default": default_b16af798585cda7cfed92f7b1dd0c707,
"@/components/admin/npc-dialogue/PromptPreview#GlobalPromptPreview": GlobalPromptPreview_934496efaa6ade9a34c5ce016825a43f,
"@/components/admin/tech-tree/TechTreeNav#default": default_a6bf792526e9f56202161f190c57e1c6,
"@/components/static/VersionOverlay#default": default_2f6c866ab4d4d51b3789f090b84b85c7,
"@/components/graphics/AppIcon#default": default_508743824696caae2894ebf34c2e68bb,

View file

@ -0,0 +1,100 @@
import type { GlobalConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
import { cleanPromptText } from "@/lib/npc-dialogue/normalize";
/**
* Admin-editable half of the AI dialogue prompt.
*
* The prompt has two halves. The voice is copy: register, personality, house
* quirks, and it is safe for an author to change. The rest (structure, field
* conventions, flag rules, the JSON contract) is enforced again by
* `generationSchema.ts` and `validateGeneratedFlow`, so it stays in code: a
* prompt that disagrees with the validator makes every draft fail for reasons the
* author cannot trace.
*
* Because this is a Payload global, an edit here takes effect on the next draft
* with no build and no restart. `versions` keeps the last 20 texts so a bad edit
* can be reverted from the admin panel.
*/
const MAX_VOICE_CHARS = 4000;
const MAX_EXTRA_RULES_CHARS = 2000;
export const NpcDialogueSettings: GlobalConfig = {
slug: "npc-dialogue-settings",
label: "NPC Dialogue Prompt",
admin: {
description:
"How AI-drafted NPC conversations sound. Changes apply to the next draft, with no deploy.",
},
versions: {
max: 20,
},
access: {
read: requirePermission("npc-dialogues:read"),
update: requirePermission("npc-dialogues:update"),
},
hooks: {
beforeChange: [
({ data, originalDoc }) => {
// Cap rather than reject: an over-long paste should still save something
// usable instead of failing the form with no explanation.
const voice = cleanPromptText(data?.voice, MAX_VOICE_CHARS);
const extraRules = cleanPromptText(data?.extraRules, MAX_EXTRA_RULES_CHARS);
const voiceChanged = (originalDoc?.voice ?? null) !== voice;
const extraChanged = (originalDoc?.extraRules ?? null) !== extraRules;
const previousRevision =
typeof originalDoc?.revision === "number" ? originalDoc.revision : null;
// Only a real text change bumps the revision, so re-saving the form does
// not make every stored draft look like it came from a different prompt.
const revision =
previousRevision === null
? 1
: voiceChanged || extraChanged
? previousRevision + 1
: previousRevision;
return { ...data, voice, extraRules, revision };
},
],
},
fields: [
{
name: "voice",
type: "textarea",
admin: {
description:
"Replaces the built-in voice for every conversation that does not set its own. Leave blank to use the built-in. Write about register and personality only: structure and field rules are not editable here, because the draft validator enforces them. Dashes are converted to plain punctuation on save.",
},
},
{
name: "extraRules",
type: "textarea",
admin: {
description:
"House conventions appended after the voice, for every conversation including ones with their own voice. Keep it short and concrete, e.g. how the unit refers to itself or which slang is banned.",
},
},
{
name: "revision",
type: "number",
admin: {
readOnly: true,
description:
"Incremented automatically when the voice or house rules change. Recorded on each stored draft so you can tell which prompt produced it.",
},
},
{
name: "preview",
type: "ui",
admin: {
components: {
Field: "@/components/admin/npc-dialogue/PromptPreview#GlobalPromptPreview",
},
},
},
],
};

View file

@ -108,6 +108,30 @@ export const NpcDialogues: CollectionConfig = {
},
],
},
{
label: "AI Drafting",
description:
"How the drafting tools should sound for this conversation. The preview shows the exact instruction the model receives.",
fields: [
{
name: "voiceOverride",
type: "textarea",
admin: {
description:
"Replaces the global voice for this conversation only. Leave blank to use the global setting, or the built-in voice if that is blank too. Write about register and personality only: structure and field rules are fixed in code.",
},
},
{
name: "promptPreview",
type: "ui",
admin: {
components: {
Field: "@/components/admin/npc-dialogue/PromptPreview#DialoguePromptPreview",
},
},
},
],
},
],
},
{
@ -130,6 +154,28 @@ export const NpcDialogues: CollectionConfig = {
type: "text",
admin: { description: "Prompt contract version, so an old draft is comparable.", readOnly: true },
},
{
name: "promptSource",
type: "select",
options: [
{ label: "Built-in voice", value: "builtin" },
{ label: "Global setting", value: "global" },
{ label: "This dialogue", value: "dialogue" },
],
admin: {
description: "Which voice shaped the prompt: the built-in default, the global setting, or this dialogue's override.",
readOnly: true,
},
},
{
name: "promptRevision",
type: "number",
admin: {
description:
"Revision of the prompt settings in force when this draft was made. Empty for the built-in voice, which has no settings revision.",
readOnly: true,
},
},
{
name: "attempts",
type: "number",

View file

@ -43,6 +43,8 @@ interface GenerateDraftDialogProps {
readonly onOpenChange: (open: boolean) => void;
/** The contact this conversation belongs to. Null until the doc is saved. */
readonly npcId: number | null;
/** The dialogue document, so its voice override applies. Null until saved. */
readonly dialogueId: number | null;
/** Nodes already on the canvas, so the author is warned about replacement. */
readonly nodeCount: number;
/** Receives the draft and the brief that produced it. The caller drops the
@ -91,6 +93,7 @@ export function GenerateDraftDialog({
open,
onOpenChange,
npcId,
dialogueId,
nodeCount,
onGenerated,
}: GenerateDraftDialogProps) {
@ -147,7 +150,7 @@ export function GenerateDraftDialog({
setBusy(true);
setError(null);
try {
const res = await generateNpcDialogueDraft(npcId, { ...brief, goal });
const res = await generateNpcDialogueDraft(npcId, { ...brief, goal }, dialogueId);
if (!res.success || !res.data) {
setError(res.error ?? "The model could not produce a usable conversation.");
return;

View file

@ -12,6 +12,8 @@ import type { RewriteAction } from "@/lib/npc-dialogue/generationPrompt";
interface LineAssistProps {
/** The contact being written for. Null until the document is saved. */
readonly npcId: number | null;
/** The dialogue document, for its voice override. Null until saved. */
readonly dialogueId: number | null;
readonly nodeType: string;
/** Current text of the field this control sits under. */
readonly value: string;
@ -30,6 +32,7 @@ interface LineAssistProps {
*/
export function LineAssist({
npcId,
dialogueId,
nodeType,
value,
previousLine,
@ -50,6 +53,7 @@ export function LineAssist({
text: value,
nodeType,
previousLine: previousLine ?? undefined,
dialogueId,
});
if (res.success && res.data) {
onChange(res.data.text);

View file

@ -42,6 +42,8 @@ interface NodeEditDialogProps {
readonly onSave: (nodeId: string, data: DialogueNodeData) => void;
/** The contact this flow belongs to, for the per-line AI controls. */
readonly npcId: number | null;
/** The dialogue document, so its voice override shapes rewrites. */
readonly dialogueId: number | null;
}
const EFFECT_LABELS: Record<NpcDialogueEffect["type"], string> = {
@ -133,6 +135,7 @@ export function NodeEditDialog({
onOpenChange,
onSave,
npcId,
dialogueId,
}: NodeEditDialogProps) {
const [draft, setDraft] = useState<DialogueNodeData | null>(null);
@ -283,6 +286,7 @@ export function NodeEditDialog({
/>
<LineAssist
npcId={npcId}
dialogueId={dialogueId}
nodeType={node.type}
value={draft.body ?? ""}
previousLine={previousLine}
@ -318,6 +322,7 @@ export function NodeEditDialog({
/>
<LineAssist
npcId={npcId}
dialogueId={dialogueId}
nodeType={node.type}
value={draft.leadIn ?? ""}
previousLine={previousLine}
@ -376,6 +381,7 @@ export function NodeEditDialog({
/>
<LineAssist
npcId={npcId}
dialogueId={dialogueId}
nodeType="choice"
value={choice.label ?? ""}
previousLine={previousLine}
@ -795,6 +801,7 @@ export function NodeEditDialog({
/>
<LineAssist
npcId={npcId}
dialogueId={dialogueId}
nodeType={node.type}
value={draft.closing ?? ""}
previousLine={previousLine}

View file

@ -123,6 +123,13 @@ function FlowEditor() {
return null;
}, [docData]);
// This document's own id. New documents have none until the first save, which
// is also when a voice override could first be stored.
const dialogueId = useMemo(() => {
const raw = (docData as Record<string, unknown> | undefined)?.id;
return typeof raw === "number" ? raw : null;
}, [docData]);
const lastSerialized = useRef<string>("");
const menuRef = useRef<HTMLDivElement | null>(null);
const paneMenuRef = useRef<HTMLDivElement | null>(null);
@ -202,7 +209,15 @@ function FlowEditor() {
* the only way to persist it stays the document's own Save.
*/
const applyGeneratedDraft = useCallback(
(result: { flow: FlowData; model: string; promptVersion: string; attempts: number; truncated: boolean }, brief: DialogueBrief) => {
(result: {
flow: FlowData;
model: string;
promptVersion: string;
promptSource: "builtin" | "global" | "dialogue";
promptRevision: number | null;
attempts: number;
truncated: boolean;
}, brief: DialogueBrief) => {
const incoming = result.flow.nodes as Node[];
setNodes(incoming);
serialize(incoming);
@ -211,14 +226,25 @@ function FlowEditor() {
setGeneration({
model: result.model,
promptVersion: result.promptVersion,
promptSource: result.promptSource,
promptRevision: result.promptRevision,
attempts: result.attempts,
generatedAt: new Date().toISOString(),
brief,
} as unknown as NpcDialogue["generation"]);
// The voice is easy to forget about once the draft lands: naming it here is
// how an author notices that a per-dialogue override, not the brief, shaped
// the register they are looking at.
const voiceNote =
result.promptSource === "builtin"
? ""
: result.promptSource === "dialogue"
? " Voice: this dialogue's own override."
: " Voice: the global setting.";
setDraftNotice(
result.truncated
? "AI draft. The model hit its output limit, so the ending may be missing. Review every line before saving."
: "AI draft. Review every line, then save the document to publish it.",
? `AI draft.${voiceNote} The model hit its output limit, so the ending may be missing. Review every line before saving.`
: `AI draft.${voiceNote} Review every line, then save the document to publish it.`,
);
// Fit the new graph once React Flow has measured the nodes it was handed.
window.setTimeout(() => {
@ -787,12 +813,14 @@ function FlowEditor() {
}}
onSave={handleNodeSave}
npcId={npcId}
dialogueId={dialogueId}
/>
<GenerateDraftDialog
open={generateOpen}
onOpenChange={setGenerateOpen}
npcId={npcId}
dialogueId={dialogueId}
nodeCount={nodes.length}
onGenerated={applyGeneratedDraft}
/>

View file

@ -0,0 +1,153 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { useFormFields } from "@payloadcms/ui";
import {
composeDialogueSystemPrompt,
DEFAULT_VOICE,
resolveVoice,
} from "@/lib/npc-dialogue/generationPrompt";
import type { VoiceSource } from "@/lib/npc-dialogue/generationPrompt";
import { getDialoguePromptSettings } from "@/app/(frontend)/personnel/contacts/[id]/actions";
/**
* Shows the exact system prompt a draft will receive, including the sections an
* author cannot edit.
*
* This exists because a voice textarea is invisible plumbing: without seeing the
* assembled result you cannot tell whether your edit is doing what you think, or
* whether the built-in voice still applies. The preview is composed with the same
* pure helpers the server calls, so it cannot drift from what is sent.
*
* Styled in zinc because the admin bundle does not load the frontend theme's CSS
* variables (see `src/components/admin/npc-dialogue/AGENTS` note in the area guide).
*/
const SOURCE_LABELS: Record<VoiceSource, string> = {
builtin: "Built-in voice",
global: "Global setting",
dialogue: "This dialogue",
};
function PreviewFrame({
source,
revision,
voice,
extraRules,
hint,
}: {
source: VoiceSource;
revision: number | null;
voice: string | null;
extraRules: string | null;
hint: string;
}) {
const prompt = composeDialogueSystemPrompt({ voice, extraRules });
return (
<div className="mt-2 rounded-md border border-white/15 bg-zinc-900/60 p-3">
<div className="flex flex-wrap items-center gap-2 text-[11px] uppercase tracking-wider text-white/50">
<span className="rounded border border-white/20 px-1.5 py-0.5 text-white/80">
{SOURCE_LABELS[source]}
</span>
{revision !== null ? <span>revision {revision}</span> : null}
<span className="normal-case tracking-normal text-white/40">{hint}</span>
</div>
<pre className="mt-2 max-h-72 overflow-auto whitespace-pre-wrap break-words rounded border border-white/10 bg-zinc-950/70 p-2 font-mono text-[11px] leading-relaxed text-white/70">
{prompt}
</pre>
<p className="mt-2 text-[11px] text-white/40">
VOICE and HOUSE RULES follow the fields above. STRUCTURE, FIELDS, STATE and OUTPUT
are fixed in code because the draft validator enforces them.
{voice ? "" : ` No custom voice is set, so the built-in voice is used: ${DEFAULT_VOICE.length} characters.`}
</p>
</div>
);
}
/** Preview for the global settings page: reflects unsaved edits immediately. */
export function GlobalPromptPreview() {
const values = useFormFields(([fields]) => ({
voice: fields?.voice?.value as string | undefined,
extraRules: fields?.extraRules?.value as string | undefined,
revision: fields?.revision?.value as number | undefined,
}));
const voice = values.voice?.trim() || null;
const extraRules = values.extraRules?.trim() || null;
const revision = typeof values.revision === "number" ? values.revision : null;
return (
<PreviewFrame
source={voice ? "global" : "builtin"}
revision={revision}
voice={voice}
extraRules={extraRules}
hint="Applies to every conversation without its own voice."
/>
);
}
/**
* Preview for one dialogue. Reads the (possibly unsaved) override from the form
* and the global settings from the server, then resolves the same precedence the
* generator uses.
*/
export function DialoguePromptPreview() {
const voiceOverride = useFormFields(
([fields]) => fields?.voiceOverride?.value as string | undefined,
);
const [settings, setSettings] = useState<{
voice: string | null;
extraRules: string | null;
revision: number | null;
} | null>(null);
const [failed, setFailed] = useState(false);
useEffect(() => {
let cancelled = false;
void getDialoguePromptSettings()
.then((result) => {
if (cancelled) return;
if (!result.success || !result.data) {
setFailed(true);
return;
}
setSettings(result.data);
})
.catch(() => {
if (!cancelled) setFailed(true);
});
return () => {
cancelled = true;
};
}, []);
const resolved = useMemo(
() =>
resolveVoice({
dialogueVoice: voiceOverride,
globalVoice: settings?.voice,
globalExtraRules: settings?.extraRules,
globalRevision: settings?.revision,
}),
[voiceOverride, settings],
);
return (
<PreviewFrame
source={resolved.source}
revision={resolved.revision}
voice={resolved.voice}
extraRules={resolved.extraRules}
hint={
failed
? "Could not read the global settings; this shows the built-in voice."
: "Unsaved edits are reflected here but are not used until you save."
}
/>
);
}

View file

@ -22,6 +22,14 @@ surface that builds one. The AI drafting tools are documented in full at
4. **Flag keys must already exist.** A condition or `{{token}}` naming a missing
`player-flags` key never fires and the branch silently dead-ends. Anything that
generates dialogue text checks against the live vocabulary.
5. **The prompt's contract half is not editable.** Only `VOICE` (via the
`npc-dialogue-settings` global or a dialogue's `voiceOverride`) and `HOUSE RULES`
are admin-editable. `STRUCTURE`, `FIELDS`, `STATE`, `OUTPUT` and the worked
example live in `LOCKED_RULES` because `generationSchema.ts` and
`validateGeneratedFlow` enforce the same rules; exposing them lets an admin
break every draft with no way to trace the failure. Precedence is
dialogue -> global -> built-in, resolved by the pure `resolveVoice`, and every
stored draft records which one applied.
## Files
@ -29,7 +37,9 @@ surface that builds one. The AI drafting tools are documented in full at
src/lib/npc-dialogue/
dialogue.ts # Node/edge/effect types, hop projection, validateGraph (pure)
generationSchema.ts # JSON schema, normalizer, draft validator (pure)
generationPrompt.ts # Prompt text, brief/tone/outcome vocabularies (pure)
generationPrompt.ts # Prompt text, voice resolution/composition, vocabularies (pure)
generationSettings.ts # Settings global read + voice precedence resolution (Payload)
normalize.ts # Dash normalisation and prompt-text cleaning (pure)
generation.ts # Model calls, context loading, validate-and-retry (Payload)
interpolate.ts # {{flag}}, {{countdown:key}}, {{ cond ? a : b }} (pure)
flags.ts # Flag read/write, condition evaluation (Payload)
@ -43,10 +53,12 @@ src/components/admin/npc-dialogue/
NodeEditDialog.tsx # Per-node form, hosts LineAssist
GenerateDraftDialog.tsx# The brief form for whole-conversation drafting
LineAssist.tsx # Rewrite / Shorten / Sharpen for one field
PromptPreview.tsx # Assembled-prompt preview for the global and per dialogue
NpcDialogueNode.tsx, RoutedFlowEdge.tsx, MarkupEditor.tsx, types.ts
src/components/frontend/personnel/NpcConversation.tsx # Player-facing walker
src/collections/game/NpcDialogues.ts # Collection + generation provenance
src/collections/game/NpcDialogues.ts # Collection, voice override, provenance
src/collections/game/NpcDialogueSettings.ts # Editable voice global (20 versions)
```
## Data model in one paragraph
@ -86,6 +98,11 @@ pass server-side, so a flag value can never smuggle in another token.
to a hyphen (it is a range). Shipped copy never carries an em-dash.
- The model is reachable only through `src/lib/ai/generate.ts`. Do not call
`fetch` against Unsloth anywhere else.
- The voice is resolved once per draft, not per attempt, so a retry cannot change
register mid-generation. `rewriteDialogueLine` resolves it the same way, so a
house voice shapes drafts and rewrites alike.
- A draft that fails twice while a custom voice is active names that voice in the
error. Keep that hint: without it a bad voice block looks like a broken model.
## Admin panel styling

View file

@ -23,10 +23,18 @@ import type { RawDraftNode } from "./generationSchema";
import {
buildGenerationPrompt,
buildRewritePrompt,
DIALOGUE_SYSTEM_PROMPT,
composeDialogueSystemPrompt,
PROMPT_VERSION,
} from "./generationPrompt";
import type { DialogueBrief, KnownFlag, NpcContext, RewriteAction } from "./generationPrompt";
import type {
DialogueBrief,
KnownFlag,
NpcContext,
RewriteAction,
VoiceSource,
} from "./generationPrompt";
import { resolveDialogueVoice } from "./generationSettings";
import { normalizeDashes } from "./normalize";
/** How many flag keys are handed to the model. Enough to cover a real flag
* vocabulary, small enough to keep the prompt inside a 9B's comfort zone. */
@ -117,7 +125,38 @@ export async function buildGenerationContext(
return { npc, flags };
}
export interface DraftRunnerInput { prompt: string;
/**
* The per-dialogue voice override, or null when this conversation has none (or
* does not exist yet, which is the normal case before the first save).
*
* Reading it here rather than from the browser matters: the action receives an
* unsaved canvas, so the only trustworthy source is the stored document.
*/
export async function loadDialogueVoiceOverride(
payload: Payload,
dialogueId: number | null | undefined,
): Promise<string | null> {
if (!dialogueId || !Number.isInteger(dialogueId) || dialogueId <= 0) return null;
try {
const doc = await payload.findByID({
collection: "npc-dialogues",
id: dialogueId,
depth: 0,
overrideAccess: true,
select: { voiceOverride: true },
});
const value = (doc as { voiceOverride?: unknown } | null)?.voiceOverride;
return typeof value === "string" && value.trim() ? value.trim() : null;
} catch {
// A missing document (deleted mid-edit) must not block drafting: the global
// or built-in voice is still a valid configuration.
return null;
}
}
export interface DraftRunnerInput {
prompt: string;
system: string;
schema: Record<string, unknown>;
}
@ -146,6 +185,10 @@ export interface DraftOutcome {
truncated: boolean;
model: string;
promptVersion: string;
/** Which voice shaped the prompt: built-in, the global setting, or this dialogue. */
promptSource: VoiceSource;
/** The settings revision used, or null for the built-in voice. */
promptRevision: number | null;
}
const defaultRunner: DraftRunner = (input) =>
@ -163,7 +206,7 @@ const defaultRunner: DraftRunner = (input) =>
*/
export async function generateDialogueDraft(
payload: Payload,
input: { npcId: number; brief: DialogueBrief },
input: { npcId: number; brief: DialogueBrief; dialogueId?: number | null },
run: DraftRunner = defaultRunner,
): Promise<DraftOutcome> {
const { npc, flags } = await buildGenerationContext(payload, input.npcId);
@ -171,6 +214,15 @@ export async function generateDialogueDraft(
const knownKeys = flags.map((flag) => flag.key);
const model = resolveModel();
// The voice is resolved once per draft, not per attempt, so both attempts use
// the same instruction and a retry cannot silently change register.
const dialogueVoice = await loadDialogueVoiceOverride(payload, input.dialogueId);
const resolved = await resolveDialogueVoice(payload, { dialogueVoice });
const system = composeDialogueSystemPrompt({
voice: resolved.voice,
extraRules: resolved.extraRules,
});
let errors: string[] = [];
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt += 1) {
@ -186,7 +238,7 @@ Fix every problem above and return the whole conversation again.`;
let parsed: DraftRunnerResult;
try {
parsed = await run({ prompt, system: DIALOGUE_SYSTEM_PROMPT, schema: dialogueFlowSchema });
parsed = await run({ prompt, system, schema: dialogueFlowSchema });
} catch (error) {
errors = [
`The model's output could not be read as a conversation: ${
@ -210,12 +262,23 @@ Fix every problem above and return the whole conversation again.`;
truncated: parsed.truncated,
model,
promptVersion: PROMPT_VERSION,
promptSource: resolved.source,
promptRevision: resolved.revision,
};
}
errors = combined;
}
// A custom prompt is the one failure cause the author can actually fix, so name
// it instead of letting a bad voice block look like a broken model.
if (resolved.source !== "builtin") {
errors = [
...errors,
`This conversation used the ${resolved.source === "dialogue" ? "dialogue's own" : "global"} voice. If drafts keep failing, check that setting before blaming the model.`,
];
}
return {
ok: false,
errors,
@ -223,25 +286,11 @@ Fix every problem above and return the whole conversation again.`;
truncated: false,
model,
promptVersion: PROMPT_VERSION,
promptSource: resolved.source,
promptRevision: resolved.revision,
};
}
/**
* The house rule is no em-dashes in anything shipped, and dialogue copy reaches
* players verbatim. A dash out of the model is the one thing worth normalising
* before it lands in the author's textarea; everything else is left exactly as
* written so the author edits real output, not a rewrite of it.
*/
function normalizeDashes(text: string): string {
return text
// A spaced dash is punctuation: a comma reads correctly in dialogue.
.replace(/\s+[\u2014\u2013]\s+/g, ", ")
// Em-dashes are almost always unspaced punctuation.
.replace(/\s*\u2014\s*/g, ", ")
// A remaining en-dash is a range (1-20), so a hyphen is the honest swap.
.replace(/\u2013/g, "-");
}
/** Strips the quoting and prefixes a chat model adds despite being told not to. */
function cleanRewrittenLine(text: string): string {
let out = stripCodeFences(text).trim();
@ -282,6 +331,7 @@ export async function rewriteDialogueLine(
text: string;
nodeType: string;
previousLine?: string | null;
dialogueId?: number | null;
},
run: LineRunner = defaultLineRunner,
): Promise<LineRewriteOutcome> {
@ -291,12 +341,15 @@ export async function rewriteDialogueLine(
}
const npc = await loadNpcContext(payload, input.npcId);
const dialogueVoice = await loadDialogueVoiceOverride(payload, input.dialogueId);
const resolved = await resolveDialogueVoice(payload, { dialogueVoice });
const { system, prompt } = buildRewritePrompt({
action: input.action,
text,
npc,
nodeType: input.nodeType,
previousLine: input.previousLine,
voice: resolved.voice,
});
const result = await run({ prompt, system, model: resolveModel() });

View file

@ -159,14 +159,28 @@ const EXAMPLE_FLOW = `{
]
}`;
export const DIALOGUE_SYSTEM_PROMPT = `You write conversations for NPCs in an Arma 3 military unit roleplay.
const DIALOGUE_INTRO = "You write conversations for NPCs in an Arma 3 military unit roleplay.";
VOICE
Write like a soldier with limited patience: concrete, physical, unsentimental. Short sentences. No fantasy vendor patter, no exclamation marks, no em-dashes.
/**
* The built-in house voice. An admin can replace this from the AI settings page
* (or per dialogue), so treat it as the default rather than the only option.
*
* It must stay a statement of register only. Anything structural belongs in
* `LOCKED_RULES`, which an admin cannot edit, because the validator enforces it.
*/
export const DEFAULT_VOICE = `Write like a soldier with limited patience: concrete, physical, unsentimental. Short sentences. No fantasy vendor patter, no exclamation marks, no em-dashes.
Each NPC has an occupation and a place. Let that show in what they notice and what they dismiss.
Never write a line that explains the mechanics to the player.
Never write a line that explains the mechanics to the player.`;
STRUCTURE
/**
* The half of the system prompt that is a contract, not copy.
*
* Every line here is enforced again by `generationSchema.ts` (the JSON schema)
* or `validateGeneratedFlow` (hops, flags, effects). An admin who deletes one
* does not get a warning: every draft fails validation twice and the author sees
* an error they cannot trace back to their own edit. So it is not editable.
*/
export const LOCKED_RULES = `STRUCTURE
Exactly one node has "isStart": true, and it is the opening line.
Every "target" and "nextTarget" must name an id that exists in the same output.
choice nodes need two or three choices, each with short button text.
@ -185,6 +199,98 @@ Allowed effects are "none", "notify" and "flag". You may not log game events, po
OUTPUT
Return one JSON object matching the provided schema. No commentary, no code fences.`;
/** Where the effective voice came from, recorded in draft provenance. */
export type VoiceSource = "builtin" | "global" | "dialogue";
export interface ResolvedVoice {
/**
* The voice text to use. `null` means "no custom voice", so the composer falls
* back to `DEFAULT_VOICE` and the rewrite prompt adds nothing.
*/
voice: string | null;
source: VoiceSource;
/** The settings revision this voice came from. Null for the built-in. */
revision: number | null;
/** Unit-level rules, appended after the voice. Never per-dialogue. */
extraRules: string | null;
}
/**
* Which voice applies to one dialogue: a per-dialogue override beats the global
* setting, which beats the built-in default. `extraRules` are unit-level and
* always come from the global, because they encode house conventions that should
* not fork per NPC.
*
* Pure so the editor preview and the server call the same logic and cannot drift.
*/
export function resolveVoice(input: {
dialogueVoice?: string | null;
globalVoice?: string | null;
globalExtraRules?: string | null;
globalRevision?: number | null;
}): ResolvedVoice {
const extraRules = input.globalExtraRules?.trim() || null;
const dialogue = input.dialogueVoice?.trim();
if (dialogue) {
return {
voice: dialogue,
source: "dialogue",
revision: input.globalRevision ?? null,
extraRules,
};
}
const global = input.globalVoice?.trim();
if (global) {
return {
voice: global,
source: "global",
revision: input.globalRevision ?? null,
extraRules,
};
}
return { voice: null, source: "builtin", revision: null, extraRules };
}
/**
* The system prompt for a whole draft: intro, the effective voice, optional house
* rules, then the locked contract.
*
* With no arguments this reproduces the original single-constant prompt exactly,
* so making the voice configurable changed no model output on its own.
*/
export function composeDialogueSystemPrompt(
input: { voice?: string | null; extraRules?: string | null } = {},
): string {
const voice = input.voice?.trim() || DEFAULT_VOICE;
const extraRules = input.extraRules?.trim();
return [
DIALOGUE_INTRO,
`VOICE\n${voice}`,
extraRules ? `HOUSE RULES\n${extraRules}` : null,
LOCKED_RULES,
]
.filter(Boolean)
.join("\n\n");
}
/** The rewrite surface's own instruction, before any house voice is added. */
export const REWRITE_BASE_SYSTEM =
"You edit dialogue lines for a military roleplay. Plain prose out, one line, no markdown, no em-dashes, no commentary.";
/**
* The system prompt for a single-line rewrite. A custom voice is appended so a
* house voice shapes rewrites and drafts alike; the built-in voice is already
* implied by the base instruction, so it adds nothing.
*/
export function composeRewriteSystemPrompt(input: { voice?: string | null } = {}): string {
const voice = input.voice?.trim();
return voice ? `${REWRITE_BASE_SYSTEM}\n\nHOUSE VOICE\n${voice}` : REWRITE_BASE_SYSTEM;
}
/**
* The user turn for a whole draft: the NPC, the brief, and the real flag
* vocabulary.
@ -254,6 +360,8 @@ export function buildRewritePrompt(input: {
npc: NpcContext;
nodeType: string;
previousLine?: string | null;
/** A custom house voice, when one applies. Null means the built-in register. */
voice?: string | null;
}): { system: string; prompt: string } {
const { action, text, npc, nodeType, previousLine } = input;
@ -282,8 +390,7 @@ ${REWRITE_INSTRUCTIONS[action]}
Reply with the replacement line only. No quotes around it, no explanation, no prefixes.`;
return {
system:
"You edit dialogue lines for a military roleplay. Plain prose out, one line, no markdown, no em-dashes, no commentary.",
system: composeRewriteSystemPrompt({ voice: input.voice }),
prompt,
};
}

View file

@ -0,0 +1,85 @@
import type { Payload } from "payload";
import { resolveVoice } from "./generationPrompt";
import type { ResolvedVoice } from "./generationPrompt";
/**
* Reads the admin-configurable prompt settings and resolves which voice applies
* to one dialogue.
*
* Globals are read at request time, so an edit in the admin panel takes effect on
* the next Generate click with no build and no restart. One `findGlobal` per model
* call is free next to a multi-second generation, so there is no cache to
* invalidate and no staleness window.
*/
/** Must match the global's `slug` in `src/collections/game/NpcDialogueSettings.ts`. */
export const NPC_DIALOGUE_SETTINGS_SLUG = "npc-dialogue-settings";
/**
* Structural view of the settings document. Typed locally rather than imported
* from `payload-types.ts` so this module does not depend on generated output, the
* same way `src/lib/economy/config.ts` types `GameRules`.
*/
type SettingsDoc = {
voice?: string | null;
extraRules?: string | null;
revision?: number | null;
} | null;
export interface DialoguePromptSettings {
/** Custom house voice, or null when the built-in default applies. */
voice: string | null;
/** Unit-level rules appended after the voice, or null. */
extraRules: string | null;
/** Bumped by the global's beforeChange hook whenever the text changes. */
revision: number | null;
}
const EMPTY: DialoguePromptSettings = { voice: null, extraRules: null, revision: null };
/** Read the prompt settings, falling back to the built-in defaults on any miss. */
export async function loadDialogueSettings(payload: Payload): Promise<DialoguePromptSettings> {
// A partial Payload double (tests) or a very early boot can lack the method.
if (typeof payload.findGlobal !== "function") return EMPTY;
try {
const doc = (await payload.findGlobal({
slug: NPC_DIALOGUE_SETTINGS_SLUG,
depth: 0,
overrideAccess: true,
})) as SettingsDoc;
return {
voice: doc?.voice?.trim() || null,
extraRules: doc?.extraRules?.trim() || null,
revision: typeof doc?.revision === "number" ? doc.revision : null,
};
} catch (error) {
// A missing global (fresh database before the migration ran) must not make
// drafting fail: the built-in prompt is always a valid configuration.
payload.logger?.warn?.(
`npc-dialogue: could not read prompt settings, using built-in defaults: ${
error instanceof Error ? error.message : String(error)
}`,
);
return EMPTY;
}
}
/**
* The voice for one dialogue: its own override, else the global voice, else the
* built-in default. `extraRules` always come from the global.
*/
export async function resolveDialogueVoice(
payload: Payload,
input: { dialogueVoice?: string | null } = {},
): Promise<ResolvedVoice> {
const settings = await loadDialogueSettings(payload);
return resolveVoice({
dialogueVoice: input.dialogueVoice,
globalVoice: settings.voice,
globalExtraRules: settings.extraRules,
globalRevision: settings.revision,
});
}

View file

@ -0,0 +1,38 @@
/**
* Text normalisation shared by everything a model wrote and everything an admin
* typed into a prompt.
*
* The prompt is text the model imitates, so a dash that survives in the settings
* page reaches every draft. Keeping the rule in one pure module means the model's
* output and the admin's input are cleaned the same way.
*/
/**
* Shipped copy never carries an em-dash or an en-dash.
*
* A spaced dash is punctuation, so a comma reads correctly there. An unspaced
* em-dash is almost always punctuation too. A remaining en-dash is a range
* (1-20), where a hyphen is the honest swap.
*/
export function normalizeDashes(text: string): string {
return text
.replace(/\s+[\u2014\u2013]\s+/g, ", ")
.replace(/\s*\u2014\s*/g, ", ")
.replace(/\u2013/g, "-");
}
/**
* Clean an admin-entered prompt fragment: normalise dashes, trim, collapse an
* empty result to null (meaning "use the built-in"), and cap the length.
*
* A cap rather than a rejection: an over-long paste should still save something
* usable instead of failing the whole settings form with no explanation.
*/
export function cleanPromptText(value: unknown, maxLength: number): string | null {
if (typeof value !== "string") return null;
const normalised = normalizeDashes(value.trim());
if (!normalised) return null;
return normalised.length > maxLength
? normalised.slice(0, maxLength).trimEnd()
: normalised;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,41 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
CREATE TYPE "public"."enum_npc_dialogues_generation_prompt_source" AS ENUM('builtin', 'global', 'dialogue');
CREATE TABLE "npc_dialogue_settings" (
"id" serial PRIMARY KEY NOT NULL,
"voice" varchar,
"extra_rules" varchar,
"revision" numeric,
"updated_at" timestamp(3) with time zone,
"created_at" timestamp(3) with time zone
);
CREATE TABLE "_npc_dialogue_settings_v" (
"id" serial PRIMARY KEY NOT NULL,
"version_voice" varchar,
"version_extra_rules" varchar,
"version_revision" numeric,
"version_updated_at" timestamp(3) with time zone,
"version_created_at" timestamp(3) with time zone,
"created_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL
);
ALTER TABLE "npc_dialogues" ADD COLUMN "voice_override" varchar;
ALTER TABLE "npc_dialogues" ADD COLUMN "generation_prompt_source" "enum_npc_dialogues_generation_prompt_source";
ALTER TABLE "npc_dialogues" ADD COLUMN "generation_prompt_revision" numeric;
CREATE INDEX "_npc_dialogue_settings_v_created_at_idx" ON "_npc_dialogue_settings_v" USING btree ("created_at");
CREATE INDEX "_npc_dialogue_settings_v_updated_at_idx" ON "_npc_dialogue_settings_v" USING btree ("updated_at");`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
DROP TABLE "npc_dialogue_settings" CASCADE;
DROP TABLE "_npc_dialogue_settings_v" CASCADE;
ALTER TABLE "npc_dialogues" DROP COLUMN "voice_override";
ALTER TABLE "npc_dialogues" DROP COLUMN "generation_prompt_source";
ALTER TABLE "npc_dialogues" DROP COLUMN "generation_prompt_revision";
DROP TYPE "public"."enum_npc_dialogues_generation_prompt_source";`)
}

View file

@ -164,6 +164,7 @@ import * as migration_20261118_184851_drop_factions_relationships_array from './
import * as migration_20261120_234950_add_locker_unlimited from './20261120_234950_add_locker_unlimited';
import * as migration_20261121_015435_add_mission_attendance_unlocks from './20261121_015435_add_mission_attendance_unlocks';
import * as migration_20261123_073019_add_tech_tree_notes from './20261123_073019_add_tech_tree_notes';
import * as migration_20261124_174637_add_npc_dialogue_prompt_settings from './20261124_174637_add_npc_dialogue_prompt_settings';
export const migrations = [
{
@ -994,6 +995,11 @@ export const migrations = [
{
up: migration_20261123_073019_add_tech_tree_notes.up,
down: migration_20261123_073019_add_tech_tree_notes.down,
name: '20261123_073019_add_tech_tree_notes'
name: '20261123_073019_add_tech_tree_notes',
},
{
up: migration_20261124_174637_add_npc_dialogue_prompt_settings.up,
down: migration_20261124_174637_add_npc_dialogue_prompt_settings.down,
name: '20261124_174637_add_npc_dialogue_prompt_settings'
},
];

View file

@ -304,12 +304,14 @@ export interface Config {
shims: Shim;
'minigame-rules': MinigameRule;
'discord-presence': DiscordPresence;
'npc-dialogue-settings': NpcDialogueSetting;
};
globalsSelect: {
'game-rules': GameRulesSelect<false> | GameRulesSelect<true>;
shims: ShimsSelect<false> | ShimsSelect<true>;
'minigame-rules': MinigameRulesSelect<false> | MinigameRulesSelect<true>;
'discord-presence': DiscordPresenceSelect<false> | DiscordPresenceSelect<true>;
'npc-dialogue-settings': NpcDialogueSettingsSelect<false> | NpcDialogueSettingsSelect<true>;
};
locale: null;
widgets: {
@ -3048,6 +3050,10 @@ export interface NpcDialogue {
| number
| boolean
| null;
/**
* Replaces the global voice for this conversation only. Leave blank to use the global setting, or the built-in voice if that is blank too. Write about register and personality only: structure and field rules are fixed in code.
*/
voiceOverride?: string | null;
/**
* Which model drafted this conversation and from what brief. Written when the document is saved, so it describes the draft that was accepted, not every attempt. Editing the flow by hand afterwards does not clear it.
*/
@ -3060,6 +3066,14 @@ export interface NpcDialogue {
* Prompt contract version, so an old draft is comparable.
*/
promptVersion?: string | null;
/**
* Which voice shaped the prompt: the built-in default, the global setting, or this dialogue's override.
*/
promptSource?: ('builtin' | 'global' | 'dialogue') | null;
/**
* Revision of the prompt settings in force when this draft was made. Empty for the built-in voice, which has no settings revision.
*/
promptRevision?: number | null;
/**
* 1 when the first output validated, 2 when it was retried.
*/
@ -10183,11 +10197,14 @@ export interface NpcDialoguesSelect<T extends boolean = true> {
amount?: T;
};
flowData?: T;
voiceOverride?: T;
generation?:
| T
| {
model?: T;
promptVersion?: T;
promptSource?: T;
promptRevision?: T;
attempts?: T;
generatedAt?: T;
brief?: T;
@ -14133,6 +14150,29 @@ export interface DiscordPresence {
updatedAt?: string | null;
createdAt?: string | null;
}
/**
* How AI-drafted NPC conversations sound. Changes apply to the next draft, with no deploy.
*
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "npc-dialogue-settings".
*/
export interface NpcDialogueSetting {
id: number;
/**
* Replaces the built-in voice for every conversation that does not set its own. Leave blank to use the built-in. Write about register and personality only: structure and field rules are not editable here, because the draft validator enforces them. Dashes are converted to plain punctuation on save.
*/
voice?: string | null;
/**
* House conventions appended after the voice, for every conversation including ones with their own voice. Keep it short and concrete, e.g. how the unit refers to itself or which slang is banned.
*/
extraRules?: string | null;
/**
* Incremented automatically when the voice or house rules change. Recorded on each stored draft so you can tell which prompt produced it.
*/
revision?: number | null;
updatedAt?: string | null;
createdAt?: string | null;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "game-rules_select".
@ -14260,6 +14300,18 @@ export interface DiscordPresenceSelect<T extends boolean = true> {
createdAt?: T;
globalType?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "npc-dialogue-settings_select".
*/
export interface NpcDialogueSettingsSelect<T extends boolean = true> {
voice?: T;
extraRules?: T;
revision?: T;
updatedAt?: T;
createdAt?: T;
globalType?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "collections_widget".

View file

@ -109,6 +109,7 @@ import { MinigameEntries } from "@/collections/minigames/MinigameEntries";
import { MinigamePeriods } from "@/collections/minigames/MinigamePeriods";
import { Achievements } from "@/collections/minigames/Achievements";
import { MinigameRules } from "@/collections/game/MinigameRules";
import { NpcDialogueSettings } from "@/collections/game/NpcDialogueSettings";
import { RibbonSubmissions } from "@/collections/users/RibbonSubmissions";
import { PromotionNominations } from "@/collections/users/PromotionNominations";
import { LeadershipTransfers } from "@/collections/users/LeadershipTransfers";
@ -513,7 +514,7 @@ export default buildConfig({
},
},
},
globals: [GameRules, Shims, MinigameRules, DiscordPresence],
globals: [GameRules, Shims, MinigameRules, DiscordPresence, NpcDialogueSettings],
collections: scopedCollections,
editor: ptfLexicalEditor(),
secret: process.env.PAYLOAD_SECRET || "",

View file

@ -64,15 +64,32 @@ function flowOf(raw: RawDraftNode[]) {
}
/** Stub payload: the draft service only needs one NPC and a flag list. */
function stubPayload(): Payload {
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 () => ({
name: "Sgt. Halden",
occupation: "Quartermaster",
location: { name: "Depot" },
faction: { name: "Task Force" },
bio: null,
levelDescription: null,
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" }],
@ -403,3 +420,165 @@ describe("rewriteDialogueLine", () => {
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,
);
});

View file

@ -0,0 +1,178 @@
import { describe, expect, it } from "vitest";
import {
composeDialogueSystemPrompt,
composeRewriteSystemPrompt,
DEFAULT_VOICE,
LOCKED_RULES,
REWRITE_BASE_SYSTEM,
resolveVoice,
} from "@/lib/npc-dialogue/generationPrompt";
import { cleanPromptText, normalizeDashes } from "@/lib/npc-dialogue/normalize";
/**
* The prompt split is the riskiest kind of refactor: it moves a string that a
* model's behaviour depends on. The golden fixture below is the prompt as it was
* before the voice became configurable, so any accidental whitespace or wording
* drift fails here instead of silently changing every draft.
*
* When the prompt is changed on purpose, update this fixture in the same commit
* and bump PROMPT_VERSION.
*/
const ORIGINAL_PROMPT = `You write conversations for NPCs in an Arma 3 military unit roleplay.
VOICE
Write like a soldier with limited patience: concrete, physical, unsentimental. Short sentences. No fantasy vendor patter, no exclamation marks, no em-dashes.
Each NPC has an occupation and a place. Let that show in what they notice and what they dismiss.
Never write a line that explains the mechanics to the player.
STRUCTURE
Exactly one node has "isStart": true, and it is the opening line.
Every "target" and "nextTarget" must name an id that exists in the same output.
choice nodes need two or three choices, each with short button text.
Use an end node to close a branch. Do not use delay nodes.
Keep the conversation between the requested size bounds.
FIELDS
Fields not used by a node's type must be empty: "" for strings, [] for arrays, 0 for numbers, "is_true" and "set_true" for the enum defaults.
"body" carries the spoken line. "leadIn" carries the situation text above a choice. "closing" carries the last line before the conversation ends.
Leave "speaker" empty so the NPC's own name is used.
STATE
Use only the player flag keys listed in the brief. Never invent a flag key: a branch on a flag that does not exist never fires.
Allowed effects are "none", "notify" and "flag". You may not log game events, post to Discord, or grant rewards.
OUTPUT
Return one JSON object matching the provided schema. No commentary, no code fences.`;
describe("composeDialogueSystemPrompt", () => {
it("reproduces the original prompt exactly when nothing is configured", () => {
expect(composeDialogueSystemPrompt()).toBe(ORIGINAL_PROMPT);
expect(composeDialogueSystemPrompt({})).toBe(ORIGINAL_PROMPT);
// Whitespace-only input means "unset", not "an empty voice section".
expect(composeDialogueSystemPrompt({ voice: " ", extraRules: "\n\t " })).toBe(
ORIGINAL_PROMPT,
);
});
it("replaces the voice and keeps every locked section", () => {
const prompt = composeDialogueSystemPrompt({ voice: "Grunt, short, no ceremony." });
expect(prompt).toContain("VOICE\nGrunt, short, no ceremony.");
expect(prompt).not.toContain(DEFAULT_VOICE);
// The contract is what the validator enforces; it must survive any voice.
expect(prompt).toContain(LOCKED_RULES);
expect(prompt).toContain("STRUCTURE");
expect(prompt).toContain("STATE");
expect(prompt).toContain("OUTPUT");
});
it("appends house rules between the voice and the locked rules", () => {
const prompt = composeDialogueSystemPrompt({
voice: "Clipped.",
extraRules: "Never use the word 'sir' as a greeting.",
});
expect(prompt).toContain("Never use the word 'sir' as a greeting.");
// Order matters: house rules are voice-adjacent, before the contract.
expect(prompt.indexOf("HOUSE RULES")).toBeLessThan(prompt.indexOf("STRUCTURE"));
expect(prompt.indexOf("VOICE")).toBeLessThan(prompt.indexOf("HOUSE RULES"));
});
it("supports house rules without a custom voice", () => {
const prompt = composeDialogueSystemPrompt({ extraRules: "Refer to the unit as the Task Force." });
expect(prompt).toContain(DEFAULT_VOICE);
expect(prompt).toContain("HOUSE RULES\nRefer to the unit as the Task Force.");
});
});
describe("composeRewriteSystemPrompt", () => {
it("is the plain instruction when no custom voice is set", () => {
expect(composeRewriteSystemPrompt()).toBe(REWRITE_BASE_SYSTEM);
// The built-in voice is already implied by the base instruction, so the
// default never duplicates it.
expect(composeRewriteSystemPrompt({ voice: null })).toBe(REWRITE_BASE_SYSTEM);
});
it("appends a custom voice so rewrites match drafts", () => {
const system = composeRewriteSystemPrompt({ voice: "Drawling, unhurried." });
expect(system.startsWith(REWRITE_BASE_SYSTEM)).toBe(true);
expect(system).toContain("HOUSE VOICE\nDrawling, unhurried.");
});
});
describe("resolveVoice", () => {
it("prefers the dialogue override", () => {
const resolved = resolveVoice({
dialogueVoice: "This NPC only.",
globalVoice: "Whole unit.",
globalExtraRules: "House rules.",
globalRevision: 7,
});
expect(resolved.source).toBe("dialogue");
expect(resolved.voice).toBe("This NPC only.");
expect(resolved.revision).toBe(7);
});
it("falls back to the global voice", () => {
const resolved = resolveVoice({
dialogueVoice: " ",
globalVoice: "Whole unit.",
globalExtraRules: null,
globalRevision: 3,
});
expect(resolved.source).toBe("global");
expect(resolved.voice).toBe("Whole unit.");
expect(resolved.revision).toBe(3);
});
it("falls back to the built-in voice and carries no revision", () => {
const resolved = resolveVoice({ dialogueVoice: null, globalVoice: null });
expect(resolved.source).toBe("builtin");
expect(resolved.voice).toBeNull();
expect(resolved.revision).toBeNull();
});
it("always takes extra rules from the global, never from the dialogue", () => {
const resolved = resolveVoice({
dialogueVoice: "Per dialogue.",
globalExtraRules: "Unit-wide convention.",
globalRevision: 4,
});
expect(resolved.extraRules).toBe("Unit-wide convention.");
});
});
describe("normalizeDashes", () => {
it("turns a spaced dash into a comma", () => {
expect(normalizeDashes("Hold position \u2014 wait for orders.")).toBe(
"Hold position, wait for orders.",
);
});
it("turns an unspaced em-dash into a comma", () => {
expect(normalizeDashes("Rifles\u2014mine are empty.")).toBe("Rifles, mine are empty.");
});
it("keeps a range readable as a hyphen", () => {
expect(normalizeDashes("1\u201320 rounds")).toBe("1-20 rounds");
});
});
describe("cleanPromptText", () => {
it("trims, normalises dashes, and treats blank as unset", () => {
expect(cleanPromptText(" Short \u2014 blunt. ", 100)).toBe("Short, blunt.");
expect(cleanPromptText(" ", 100)).toBeNull();
expect(cleanPromptText(undefined, 100)).toBeNull();
expect(cleanPromptText(42, 100)).toBeNull();
});
it("caps over-long input instead of rejecting it", () => {
const capped = cleanPromptText("x".repeat(50), 10);
expect(capped).toHaveLength(10);
});
});

View file

@ -0,0 +1,105 @@
import type { Payload } from "payload";
import { beforeAll, describe, expect, it } from "vitest";
import { getTestPayload } from "../helpers/get-test-payload";
import { loadDialogueSettings } from "@/lib/npc-dialogue/generationSettings";
/**
* The settings global is behaviour, not just a form: the hook normalises the text
* an author pastes and decides when the revision moves, and the generator reads it
* back through `loadDialogueSettings`. A round trip through real Payload is the
* only way to know both halves agree.
*
* Assertions are relative: the global persists across the tests in this file, so
* an absolute revision would only be asserting test order.
*/
let payload: Payload;
let seq = 0;
beforeAll(async () => {
payload = await getTestPayload();
});
const update = (data: { voice?: string | null; extraRules?: string | null }) =>
payload.updateGlobal({
slug: "npc-dialogue-settings",
data,
overrideAccess: true,
});
/** Text that has never been stored before, so the change is always a change. */
const unique = (prefix: string) => `${prefix} ${++seq}`;
describe("npc-dialogue-settings global", () => {
it("normalises dashes on save", async () => {
const doc = await update({ voice: "Short \u2014 blunt.", extraRules: null });
expect(doc.voice).toBe("Short, blunt.");
expect(typeof doc.revision).toBe("number");
});
it("does not bump the revision when the text is re-saved unchanged", async () => {
const voice = unique("Stable text.");
const first = await update({ voice, extraRules: null });
const second = await update({ voice, extraRules: null });
expect(second.revision).toBe(first.revision);
});
it("bumps the revision by one when the text changes", async () => {
const before = await update({ voice: unique("Voice"), extraRules: null });
const after = await update({ voice: unique("Voice"), extraRules: null });
expect(after.revision).toBe((before.revision ?? 0) + 1);
});
it("counts house rules as a change, because they are part of the prompt", async () => {
const voice = unique("Voice");
const before = await update({ voice, extraRules: null });
const after = await update({ voice, extraRules: unique("Rule") });
expect(after.revision).toBe((before.revision ?? 0) + 1);
});
it("treats blank text as unset rather than storing whitespace", async () => {
const doc = await update({ voice: " \n ", extraRules: "" });
expect(doc.voice ?? null).toBeNull();
expect(doc.extraRules ?? null).toBeNull();
});
it("keeps prompt history so a bad edit can be reverted", async () => {
await update({ voice: unique("Version one.") });
await update({ voice: unique("Version two.") });
const versions = await payload.findGlobalVersions({
slug: "npc-dialogue-settings",
limit: 10,
overrideAccess: true,
});
expect(versions.docs.length).toBeGreaterThanOrEqual(2);
});
it("reads back through loadDialogueSettings, which is what the generator uses", async () => {
const voice = unique("Read by the generator.");
await update({ voice, extraRules: "Unit convention." });
const settings = await loadDialogueSettings(payload);
expect(settings.voice).toBe(voice);
expect(settings.extraRules).toBe("Unit convention.");
expect(settings.revision).toBeGreaterThanOrEqual(1);
});
it("falls back to the built-in defaults when the settings cannot be read", async () => {
const settings = await loadDialogueSettings({
findGlobal: async () => {
throw new Error("relation not found");
},
logger: { warn: () => undefined },
} as unknown as Payload);
expect(settings).toEqual({ voice: null, extraRules: null, revision: null });
});
});