# AGENTS.md: NPC Dialogue > **Parent**: `../../AGENTS.md` (commands, RBAC, Payload config) and `../AGENTS.md` (lib conventions). Two halves: the runtime that walks a stored conversation, and the authoring surface that builds one. The AI drafting tools are documented in full at `docs/npc-dialogue-ai.md`. ## Never-miss rules 1. **The stored `flowData` graph is the only thing players can see.** The runtime resolves every node server-side from the document, so an unsaved editor draft is unreachable by construction. Do not add a code path that lets the client name a node the document does not contain. 2. **AI output never writes a document.** `generateNpcDialogueDraft` and `rewriteNpcDialogueLine` return values to the editor; only the editor's Save persists them. Keep it that way: a server action that saves on the model's behalf destroys the review gate. 3. **Generated effects are limited to `notify` and `flag`.** `emit`, `reward` and `discord` write game state or post to Discord and are author-only. They are absent from the generation schema and rejected again by the validator. 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 ``` 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, 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) selection.ts # Which conversation is offered to a player (Payload) states.ts # Per-player read markers (Payload) attachments.ts # media ids to URLs (Payload) presentation.ts # Typewriter preference resolution (pure) reorder.ts, DialogueText.tsx (pure) src/components/admin/npc-dialogue/ NpcDialogueEditor.tsx # React Flow canvas, the custom field component 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, voice override, provenance src/collections/game/NpcDialogueSettings.ts # Editable voice global (20 versions) ``` ## Data model in one paragraph `flowData` is `{ nodes, edges }`. Edges are a **derived projection** of the node data (`deriveEdges`) and exist only for the canvas: hops live in the nodes (`next`, `choices`, `trueTarget`/`falseTarget`). Deleting an edge scrubs the hop it represents. Every hop projection goes through `outgoingHops` so the canvas, the validator and the runtime cannot disagree. Node types: `dialogue`, `choice`, `event`, `end`, `delay`, `condition`. Effects (`notify`, `emit`, `reward`, `flag`) are configured on `event` nodes only and are executed by `triggerNpcDialogueEvent`, which re-reads the stored node rather than trusting the client. An `event` node carries `presentation`: `event` (default, the amber left-barred line with no speaker) or `narration` (centered, muted, for a narrator describing a scene rather than the contact speaking). It changes rendering only; the walker and the effect run identically. Availability is double-gated: `game-npcs.canMessage` on the contact, and the `entryGate` / `priority` on the dialogue document selecting which of an NPC's conversations is offered. `testing: true` on a conversation makes it superuser-only. The flag is enforced in one place, `visibility.ts`, which both the offer and every node lookup call: - **Who counts as a tester**: `system:admin-access` (the built-in admin role and superuser roles), not every author. A division officer who can edit conversations still cannot reach a testing one on the player site. - **Absent means live**: only an explicit `true` hides a conversation. Rows written before the flag existed read back as null and stay visible. - **The claim is verified, never trusted**: the conversation client sends its `dialogue.id` and each node lookup re-checks that the id belongs to the NPC and is visible to the reader, so a player cannot read a testing conversation's nodes by guessing an id. Those lookups used to take `limit: 1` on the NPC's conversations with no ordering, which with a testing conversation present could read the wrong document and silently skip an event effect. - **Badges follow the offer**: the NEW marker comes from the offered conversation, so a testing conversation never advertises itself to players. ## Flag conditions Leaves test a `player-flags` value for the reading player, falling back to the global entry (`user: null`). `is_true` / `is_false` test truthiness, so a flag explicitly set to false reads the same as a missing one; use `is_defined` / `is_undefined` when the branch turns on whether a value was ever recorded. A flag whose `activatesAt` is still in the future counts as defined (recorded, not yet in effect) and reads false. An expired personal entry falls through to the global entry rather than reading as absent. `NUMERIC_CONDITION_OPS` in `dialogue.ts` is the single list of ops that take `amount`; the editor, the `entryGate` field visibility and `conditionSummary` all read it. Adding an op to `CONDITION_OPS` also changes the `enum_npc_dialogues_entry_gate_op` Postgres enum, so it needs a migration (`ALTER TYPE ... ADD VALUE`), not just a code change. `generationSchema.ts` keeps its own copy of the op list for the drafting schema; update both. ## Text markup Lines support `**bold**`, `*italic*`, `{red}color{/}`, `` `code` ``, `![alt](url)`, list prefixes, `{{flag}}`, `{{countdown:key}}`, and ternaries `{{ cond ? key : other }}` including numeric comparisons. Interpolation is a single pass server-side, so a flag value can never smuggle in another token. `DialogueText.tsx` is the only renderer; don't hand-roll one. ## Voice clips A line can carry `data.voice = { mediaId, filename? }` (dialogue, event and end nodes). Like attachments, flowData stores only a pointer and `resolveVoiceClip()` turns it into a URL per read, so a deleted file goes quiet instead of breaking the line. - **Storage is always `media`.** Two sources feed it: a direct upload (`uploadNpcDialogueVoice`) and an accepted voiceover take (`importNpcDialogueVoice`, which copies the submission's audio because `voice-submissions` is owner-scoped while `media` is publicly readable). Both normalise to mono MP3 through `src/lib/voiceover/transcode.ts`, because browser recordings are WebM/Opus and iOS will not always play them. Transcode failure stores the original rather than losing the take. - **Playback paces the reveal.** The clip starts before the line lands and `clipDuration()` supplies the reveal length, so text and speech finish together; with no clip (or a muted player) the default cadence applies. - **Autoplay is not guaranteed.** A rejected `play()` marks the entry and the line offers a Play voice button. One `