1
0
Fork 0
polaris-task-force/src/lib/npc-dialogue/AGENTS.md
Z8MB1E 7adfcde72d fix(npc-dialogue): keep the conversation reachable when a branch attaches
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.
2026-11-24 14:47:08 -05:00

11 KiB

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)
  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.

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.

Text markup

Lines support **bold**, *italic*, {red}color{/}, `code`, ![alt](url), list prefixes, {{flag}}, {{countdown:key}}, and ternaries {{ cond ? a : b }} 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.

AI drafting behaviour worth knowing

  • Two attempts maximum: the second prompt carries the validator's complaints. A draft that fails twice is not shown at all.
  • normalizeGeneratedFlow assigns layout positions by breadth from the start node, so a draft opens as a readable chain.
  • Provenance is only written when a draft lands, so rejected drafts leave no trace.
  • Dashes in model output are normalised: em-dash to a comma, a remaining en-dash to a hyphen (it is a range). Shipped copy never carries an em-dash.
  • The model is reachable only through src/lib/ai/generate.ts. Do not call fetch against Unsloth anywhere else.
  • Which model serves a draft comes from resolveConnection(payload, purpose) (src/lib/ai/connections.ts), resolved once per request alongside the voice. A null connection means the env defaults, which is the unchanged behaviour. See docs/ai-settings.md.
  • The voice is resolved once per draft, not per attempt, so a retry cannot change register mid-generation. rewriteDialogueLine resolves it the same way, so a house voice shapes drafts and rewrites alike.
  • A draft that fails twice while a custom voice is active names that voice in the error. Keep that hint: without it a bad voice block looks like a broken model.

Admin panel styling

The admin bundle does not load the frontend's shadcn theme variables, so bg-background, bg-popover, border-input, text-muted-foreground and the rest resolve to nothing inside a custom admin field. A surface styled only with those tokens comes out transparent, and a portaled Radix Select becomes transparent and unable to take pointer events, so it can only be driven with the arrow keys.

So: style every admin-panel element explicitly in zinc (bg-zinc-800 / bg-zinc-900, border-white/20, text-white), as NodeEditDialog does, and prefer a native <select> over the shadcn one. GenerateDraftDialog follows both rules.

Tests

tests/int/npc-dialogue-*.int.spec.ts: interpolate, attachments, condition groups, flag targets, remove-hop, reorder, and generation. The generation spec injects the model call, so it runs without the model host.

Generated drafts are branches unless the canvas is empty

The Generate dialog writes one of two shapes, and the difference is not cosmetic:

  • full replaces the canvas and requires exactly one isStart node;
  • fragment inserts a branch that is wired into an existing node. It must mark no start node and leave at least one branch open, both enforced by validateGeneratedFlow(..., { scope }).

insertGeneratedFragment (fragmentInsert.ts) owns the splice, purely and under test. It remaps every id (a collision silently repoints the author's hops), strips isStart, places the branch beside the node it continues from with per-card collision nudging, gives the branch's open end a way onward (below), and derives a choice button label from the branch's first line when attaching under a choice node (a blank button fails validation). It never throws: a refused attachment returns the branch unwired plus a note, because discarding a draft the model spent a minute on is worse than an untidy result.

The return hop is not "back to the caller" for every caller. Attaching to a single-continuation node overwrites its next, so returnTargetOf sends the branch's open end to the successor that hop used to point at; returning to the caller itself would loop. A choice caller is the one case where coming back to the caller is right (its buttons are still there). A condition gets no return at all: re-entering re-evaluates the same flags and retakes the same branch. Return candidates are restricted to node types that actually read next, since writing next on a choice or condition is a hop no walker follows.

Attach is the default placement whenever one node is selected. Replacing the whole conversation is destructive and must never be what happens because nobody read the dropdown.

Canvas wiring: nodes are the source of truth

Edges in the canvas are a derived projection of node data (deriveEdges), so every wiring edit has to write the hop, never the edge. Both drag-a-new-line and drag-the-end-of-an-existing-line go through connectHop in dialogue.ts, which is pure and unit-tested in tests/int/npc-dialogue-connect.int.spec.ts; the editor only persists the result.

Rules that came out of real bugs:

  • A refused connection must explain itself. React Flow cannot say why a drop was rejected, so a refusal looks like a dead canvas. connectHop therefore reports changed: false for a write it did not make (end node as source, a condition with both branches taken, a choice row that does not exist) and the editor shows an amber notice instead of writing an identical graph. A refused tail-drag keeps the original hop: detaching first would delete the line the author can still see.
  • Reconnection needs onReconnect. React Flow enables edge reconnection by default, draws the line, and then discards the drop with no handler: the edge snaps back and nothing changes. Handle drops arrive at onReconnect; a drop over a node card arrives at onReconnectEnd with no connection, so that handler retargets. Which END was dragged is not reported reliably (handleType said "target" for a drag started on the tail anchor), so a card drop always retargets rather than guessing.
  • Carry the hop. A reconnect passes the original hop as carried, so a choice keeps its button text, tooltip, once flag and gate. Rebuilding it from a target id silently blanks the button.
  • Dropping on a condition card fills its first free branch. Filling both at once wired true and false to the same node, which made the condition pointless.
  • Handle hit areas are horizontal-first. Dots shrink with zoom; a real child element widens the target (a ::before did not hit-test reliably here) but stays short vertically, because choice rows stack a few pixels apart when zoomed out and an over-tall target starts the drag for the neighbouring row.