# 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. ### 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 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_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. 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. 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 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. 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.