Review findings, all in code this range introduced. Attaching a branch to a node that already had a next step replaced that hop, and "come back where it attached" pointed the branch back at the caller, which loops: the caller then leads into the branch it just returned from. Everything downstream was orphaned. The branch now continues into the step that hop used to point at, so attaching inserts in front of it instead of deleting it. Rejoining a condition is refused outright, because re-entering re-evaluates the same flags and retakes the same branch. Return candidates are limited to node types that read `next`: a choice or condition open end would have received a hop no walker follows. The dialog says which of the three applies, and only offers the toggle when a return exists, so an untouched default is not sent and reported back as a refusal. Condition true/false dots were drawn on the input handle: the hit-area class sets left and right on the handle itself, which over-constrains React Flow's `right: 0`, so both dots drifted to the card's left edge. They now take the hit area as a child, like the other handles. Refusals are honest: `connectHop` reports `changed: false` for a write it did not make (it used to report true and return a new array), the editor explains instead of rewriting an identical graph, and a refused tail-drag keeps the original hop rather than deleting it first. A passing connection test now really is invalidated when the configuration changes. That ran in `afterChange`, whose return value is only the operation's response, so the stored row kept showing a stale pass while the test asserted the response. It moved to `beforeChange`, counts only fields actually submitted (so the Test button's own result write does not invalidate itself), and the test reads the row back. Also: the fragment prompt no longer teaches `isStart: true` through the worked example or asks for "the whole conversation" on retry; requests carry a ten minute ceiling so an unreachable-but-accepting host cannot hang Generate, Compose or the Test button; the API key description no longer claims at-rest encryption, which does not exist; the per-dialogue voice override gets the same dash and length cleaning as the global it outranks; and the unused `describeAttachmentPoint` is gone, with the attachment output now included in the hint the model receives.
254 lines
13 KiB
Markdown
254 lines
13 KiB
Markdown
# 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 |
|
|
|
|
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) |
|
|
| 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.** `isStart` is stripped when `connectHop`
|
|
remaps, and `validateGeneratedFlow` rejects 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 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.
|
|
|
|
`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
|
|
|
|
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.
|