Three one-line corrections after the last review, all in text this range introduced: - the AI Drafting tab no longer claims the preview is the literal prompt, which the shared footer now qualifies; - the return table and the area guide record that a choice marked as the start gets no return, since nothing may point at the start; - the fragment note names the start rule for a start choice instead of claiming the step had nothing after it. A start dialogue with no successor still reports the missing successor, which is the actionable reason there.
13 KiB
AI-assisted NPC dialogue drafting
Two authoring accelerators for NPC conversations, both fed by the local Unsloth model and both behind the same review gate: nothing the model writes is stored until an author saves the dialogue document.
Why the gate is structural
npc-dialogues.flowData is the only source of what a player can see. The runtime
walks that stored graph server-side (triggerNpcDialogueEvent looks each node up
by id from the document), so text that exists only in the editor's unsaved form
state is unreachable. Neither feature below writes to npc-dialogues:
generateNpcDialogueDraftreturns aFlowDatavalue to the browser.rewriteNpcDialogueLinereturns a string to the textarea it came from.
Both land in the editor's field state through the existing serialize /
patch paths, so the document becomes dirty exactly as if the author had typed
the text. Saving is the publish step; there is no separate status field, because
an unsaved draft cannot leak.
The two surfaces
Draft a conversation
Toolbar Generate button in the flow editor, enabled once the dialogue has a
npc. It opens a form (GenerateDraftDialog.tsx):
| Field | Notes |
|---|---|
| Purpose | greet, quest hook, warning, rumor, refusal, recruitment pitch |
| What the player should learn or do | required, at least 8 characters |
| Outcome | none, set a player flag, notify the player |
| Flag to set | dropdown of real player-flags keys, only when the outcome needs one |
| Tone | clipped, tired, bureaucratic, hostile, friendly |
| Length | about 3, 4 or 6 nodes |
| Must include | optional detail the lines have to mention |
Below the brief, when the canvas already has nodes, a Where it goes selector decides the shape of the result:
| Placement | What it writes | Prompt contract |
|---|---|---|
| Attach under the selected node | A branch, wired in from the selected node's output | fragment |
| Insert beside the conversation | A branch, placed to the right, no wire | fragment |
| Replace the whole conversation | A whole conversation over the canvas | full |
Attach is the default whenever a node is selected, because replacing a whole conversation is the destructive option and should not be what happens because nobody looked at the dropdown. On an empty canvas the selector is hidden: there is nothing to branch off, so the draft is a whole conversation by definition.
A Come back to where it attached checkbox (on by default, attach only) gives the branch's open end a way onward, and where it goes depends on the caller:
| Caller | The open end continues to |
|---|---|
| A choice node | Back to that node, re-presenting its other buttons (a side question returns to the menu). The exception is a choice marked as the start: nothing may point at the start, so it gets no return |
| A dialogue, event or delay node that already led somewhere | The step it used to lead to. Attaching replaced that hop, so this is what keeps the rest of the conversation reachable |
| A node with nothing after it, or a condition | Nowhere: the branch stays open for the author to wire. Rejoining a condition would re-evaluate the same flags and take the same branch forever |
The middle row is the one that matters: without it, attaching to a node with an
existing next would orphan everything downstream, and returning to the caller
itself would loop.
Whatever the placement, the result lands as unsaved field state and raises a draft banner. The banner names the attachment, the return hop, any derived choice label, and any refusal (see below), so the author knows what was done for them. If the model hit its token cap the banner says so, because a truncated draft is missing its ending and must not be mistaken for a complete one.
Attaching: the rules worth knowing
src/lib/npc-dialogue/fragmentInsert.ts does the splicing, purely and under test
(tests/int/npc-dialogue-fragment.int.spec.ts). Four rules exist because each
one, done naively, silently damages the document:
- Ids are remapped. The model writes
n1,n2, ..., and a document already has nodes. A collision would silently repoint the author's existing hops, so every branch id becomes a fresh UUID and every hop between them is rewritten. - A branch never claims the start.
isStartis stripped whenconnectHopremaps, andvalidateGeneratedFlowrejects a fragment that marks one, because two starts mean the runtime picks whichever it finds first. - A fragment must leave an opening. The fragment contract requires at least one node with no continuation, and the validator enforces it: a branch where every path loops back inside itself is a pocket the author cannot wire onward.
- A branch lands beside the node it continues from, nudged down until it clears individual cards (not the union of everything, which in a large conversation would march it hundreds of pixels away). The view then frames just the inserted nodes, because fitting the whole document shrinks a new branch to an illegible speck.
Attaching under a choice node creates a button row, and a blank button fails validation, so its text is derived from the branch's first line (truncated to seven words) and called out in the banner. Attaching under an end node is refused, and the branch is inserted unwired with an explanation rather than thrown away: a minute of model time is worth more than a tidy failure.
Rewrite one line
Under the line, lead-in, choice-label and closing fields: Rewrite, Shorten, Sharpen. The request carries the NPC's name, occupation, faction and bio, the node type, the current line, and the line that immediately precedes it (found by walking the incoming hop), so a rewrite does not restate its neighbour. The replacement goes into the node dialog's draft state and is committed by that dialog's Save.
The prompt contract
src/lib/npc-dialogue/generationPrompt.ts owns the wording; bump
PROMPT_VERSION when it changes, because saved provenance records it.
The system prompt states the register (soldier with limited patience, concrete, no exclamation marks, no em-dashes), the structural rules, the field conventions (unused fields are empty strings or arrays), and the state rules. Structure is the only part that forks by scope: a full draft must mark exactly one start node, while a fragment must mark none and must leave at least one branch open. FIELDS, STATE and OUTPUT are shared, so the schema contract cannot drift between the two. The user turn adds the NPC, the brief, the live flag vocabulary, and one 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.
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 thenpc-dialoguesdocument. Precedence is: this dialogue, then the global setting, then the built-in default inDEFAULT_VOICE. - STRUCTURE, FIELDS, STATE and OUTPUT are a contract. They live in
LOCKED_RULESand stay in code becausegenerationSchema.tsandvalidateGeneratedFlowenforce 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
post to Discord and stay author-only.
Flags must already exist
Every {{token}}, condition key and flag effect is checked against the real
player-flags keys (loadKnownFlags, deduplicated by lowercased key and capped
at 80). A branch on a flag that does not exist never fires, so inventing one
produces a conversation that silently dead-ends. The check is skipped entirely
when the flag table is empty, otherwise every draft would be rejected for
referencing anything at all.
Validation and retry
validateGeneratedFlow (in generationSchema.ts, pure and unit-tested) runs
validateGraph for structure, then adds the draft-specific rules. A rejected
draft is retried once with the validator's complaints appended to the prompt.
A second failure returns the errors and changes nothing: the editor never
receives a graph it would have to repair by hand.
normalizeGeneratedFlow assembles DialogueNodeData from the flat schema
(dropping empty placeholders), rejects duplicate ids, and lays nodes out left to
right by breadth from the start node.
Provenance
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 unreadable. If rejected-attempt auditing is ever wanted, the right home is a separate generations log collection, not a field on the dialogue.
Models
Everything resolves through src/lib/ai/generate.ts:
MODEL_ID(unsloth/Ornith-1.0-9B-GGUF) is a stable key in the Compose model enum; changing it needs a migration.UNSLOTH_MODELis what is actually served. Neither dialogue surface names a model, so pointing this at a different GGUF changes Compose and dialogue drafting together.UNSLOTH_MODEL_STRUCTURED(optional, unset) overrides the model for structured work only, for the case where prose and graph generation want different GGUFs.
A connection can be selected per surface from Settings → AI Settings, which is
what lets a remote provider (or a different model on the same box) be used without
an env change. Drafting and line rewrite have separate selectors. When a connection
is active its label and model id are recorded in provenance instead of the
env-derived model. Managing connections, the write-only key, structured modes and
the test probe are documented in docs/ai-settings.md.
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.
Tests
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, 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.
tests/int/npc-dialogue-fragment.int.spec.ts covers branch insertion: id remapping,
stripping the start flag, attaching under a choice (including the derived button
text), a condition's first free branch, refusal on an end node, the return hop and
its refusal when only end nodes are open, placement beside the attachment, and the
fragment side of the validator and the prompt.
The connection side is covered by tests/int/ai-connections.int.spec.ts and
tests/int/ai-generate-modes.int.spec.ts (see docs/ai-settings.md).
Changing the prompts safely
- Edit
generationPrompt.ts, bumpPROMPT_VERSION. - Run the integration spec (it pins the observable behaviour, not the wording).
- 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.