# 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`: - `generateNpcDialogueDraft` returns a `FlowData` value to the browser. - `rewriteNpcDialogueLine` returns 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 | The result replaces the canvas contents, is fitted into view, and raises an unsaved-draft banner. 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. ### 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 (exactly one start node, every hop resolves, choice nodes need labels, no delay nodes), the field conventions (unused fields are empty strings or arrays), and the state rules. 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. ### 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`, `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. **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_MODEL` is 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. `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, and the rewrite parser (quote stripping, dash normalisation, empty completion). The model call is injected, so none of these tests need the model host. ## Changing the prompts safely 1. Edit `generationPrompt.ts`, bump `PROMPT_VERSION`. 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. A 9B model drifts badly past about ten nodes. Keep generated drafts short and let authors extend the graph by hand.