# Quests & NPC dialogue (world editor)

**Status:** not implemented (design only)  
**Related:** `docs/FEATURES.md` (Quests, Mob definitions), `docs/SCRIPTS.md` (parity reminder for future script verbs), server authority rules

Quests and NPC dialogue are **admin-authored content**. Authors create and edit them entirely in the **world editor**. Runtime evaluation is **server-authoritative**; clients only display dialogue UI and quest log snapshots.

This document is the product + data + editor spec for implementation.

---

## 1. Goals

- Author quests without code changes (editor **Quests** menu).
- Author full NPC dialogue trees on the **spawner** that owns that NPC.
- Progress quests via clear, checkable **conditions** (inventory, place, dialogue, kills, block interact).
- Keep data stable, reviewable, and Apply-revision friendly (same map-revision pipeline as chunks where content is world-scoped).
- Fail safe: broken references do not soft-lock players forever without admin tools / clear errors.

---

## 2. Persistence & identity

| Asset | Storage | Apply model |
|-------|---------|-------------|
| **Quest definitions** | `world.sqlite` (authored, revisioned with map / pending revision — same spirit as chunks) | Editor save → pending; **Apply now** loads into live sim |
| **Dialogue trees** | On each **spawner config** inside chunk data (`config.dialogue[]`) | Saved with the chunk |
| **Quest progress** | `state.sqlite` per character | Live; never in world revision |

### 2.1 IDs

- **Quest id:** stable string slug, editor-assigned, unique (`deliver-tin-ore`, `guard-rats-1`). Immutable after first publish preferred; rename is a new id + migration warning.
- **Step id:** stable string within a quest (`step-gather`, `step-return`).
- **Dialogue trigger:** stable string within a spawner’s dialogue set (`greeting`, `quest-offer`, `quest-turnin`).
- **NPC reference in quests:** prefer **spawner id** (`chunkX:chunkY:index` or authored `spawnerId`) + optional display-name hint — not transient entity ids.

### 2.2 Quests menu (editor)

Top-level editor control **Quests** (alongside Settings / palette):

- List all quests (id, title, step count, validation warnings).
- **New** / **Edit** / **Duplicate** / **Delete** (delete warns if dialogue responses reference the quest).
- Editor panel is world-global (not per-chunk), but saves go through the same admin auth + revision story as other authored world data.

---

## 3. Quest definition shape

```text
Quest {
  questId: string
  title: string
  description: string          // player-facing log blurb (in-universe)
  steps: Step[]                // ordered progression
  rewards?: Reward[]           // granted on final step complete
  cancelable?: boolean         // default false in v1
}
```

### 3.1 Steps

Each step is completed when **all** of its `require` conditions are true (AND). Optional `anyOf` groups later; v1 stays AND-only for clarity.

```text
Step {
  stepId: string
  title: string                // short log line
  hint?: string                // optional guidance
  require: Condition[]         // all must pass
  onEnter?: Effect[]           // optional (toast, flag) — keep minimal in v1
  onComplete?: Effect[]        // optional mid-quest grants; prefer final rewards
}
```

Advancement: when the active step’s conditions are satisfied, the server marks it complete and activates the next step (or completes the quest).

### 3.2 Conditions (v1)

| Kind | Fields | Meaning |
|------|--------|---------|
| `hasItem` | `itemId`, `quantity` (≥ 1) | Bag (not vault) contains at least N |
| `atTile` | `tileX`, `tileY` (optional `radius` Chebyshev, default 0) | Player stands on/near tile |
| `atChunk` | `chunkX`, `chunkY` | Player’s chunk equals (coarse place) |
| `dialogueTrigger` | `spawnerId`, `trigger` | Player fired that dialogue trigger on an NPC from that spawner (see §5) |
| `killMob` | `mobTypeId` **or** `spawnerId`, optional `displayName` | **Event:** player deals killing blow to matching mob (advances a counter or one-shot flag on the step) |
| `killCount` | `mobTypeId` **or** `spawnerId`, `count` N | Player has killed N matching mobs **while this step is active** (quota) |
| `interactBlock` | `tileX`, `tileY` **or** `blockTypeId` + optional tile, `action?` | Player successfully interacts with that block (LMB/use as defined for the block) |

**Notes:**

- `killMob` vs `killCount`: one-shot event vs quota. Prefer `killCount` with `count: 1` instead of a separate one-shot if it simplifies the engine — editor can still show “kill once” UX that writes `killCount: 1`.
- Kill attribution: **last hitting player** / engaged killer consistent with existing combat kill credit (same as bounty).
- `hasItem` does **not** consume items unless an **effect** or turn-in dialogue action says so.
- `interactBlock` must be a real completed interact (open bank alone does not count unless the quest names that block and the interact handler emits the quest event).

### 3.3 Rewards & effects (v1)

| Kind | Fields |
|------|--------|
| `giveItem` | `itemId`, `quantity` |
| `giveXp` | `skillId`, `amount` |
| `takeItem` | `itemId`, `quantity` (turn-in) |
| `startQuest` | `questId` (from dialogue) |
| `setDialogueFlag` | optional local flag — defer if unused |

Full bag on `giveItem`: overflow to vault by **carrier pigeon** (existing FEATURES note).

---

## 4. Character quest state

```text
CharacterQuest {
  questId
  status: inactive | active | completed | failed   // failed unused in v1 unless cancel
  activeStepId: string | null
  completedStepIds: string[]
  counters: { [key: string]: number }  // e.g. kill quotas for current step
  startedAt, completedAt
}
```

- Persist in `state.sqlite`.
- Replicate a compact **quest log** snapshot to the client (title, step title/hint, progress counts).
- Server re-evaluates conditions on relevant events (inventory change, move, kill, interact, dialogue) — not on a tight poll.

---

## 5. Dialogue on spawners

Dialogue is authored **per spawner** (humanoid / talkable NPC), not in code mob defs (defs may keep empty `dialogue: []`).

### 5.1 Shape

```text
DialogueNode {
  trigger: string
  lines: { speaker: "npc" | "player", text: string }[]
  responses: DialogueResponse[]
}

DialogueResponse {
  label: string                 // button text
  nextTrigger: string | null    // follow-up node trigger; null = end
  require?: DialogueRequirement[]   // all must pass to show/enable
  effects?: Effect[]            // on choose: startQuest, takeItem, …
}
```

### 5.2 Requirements on responses

| Kind | Fields |
|------|--------|
| `hasItem` | `itemId`, `quantity` |
| `questActive` | `questId` |
| `questCompleted` | `questId` |
| `questStepActive` | `questId`, `stepId` |
| `questStepCompleted` | `questId`, `stepId` |

Hidden vs disabled: **hide** responses that fail requirements (cleaner UX). Optional later: show disabled with reason.

### 5.3 Runtime

1. Player talks to NPC (existing talkable interact).
2. Server opens dialogue at default trigger (`greeting` or first node) — or a quest-forced trigger if an effect set one.
3. Client shows lines in order (npc/player attribution for layout).
4. Player picks a response → server validates requirements + effects → may emit `dialogueTrigger` quest event with `{ spawnerId, trigger: chosen.nextTrigger or node.trigger }` as designed.
5. **Quest condition `dialogueTrigger`:** fires when the player **selects a response that leads to** that trigger, or when a node with that trigger is **entered** — pick **one** rule and stick to it.

**Resolved default:** condition matches when a dialogue **node with that `trigger` begins** (lines start showing). Starting a quest offer node counts; merely hovering a response does not.

### 5.4 Editor UI (spawner modal)

Under humanoid fields: **Dialogue** section

- List nodes by trigger; add/remove/reorder.
- Per node: trigger id, lines editor (speaker toggle + text), responses (label, next trigger dropdown, requirement rows, optional effects).
- Validation: orphan triggers, missing nextTrigger targets, empty lines, unknown quest ids in requirements.

Central Exchange staff share one spawner config’s dialogue (same as shared equipment) unless we later split per clerk — **v1: shared tree**.

---

## 6. How quests start

Primary: dialogue response effect `startQuest`.  
Secondary (optional v1.1): auto-start on enter tile / pickup — out of scope until needed.

Cannot start if already active or completed (unless quest allows repeat — **v1: no repeats**).

---

## 7. Implementation plan (phased)

1. **Data model + world DB tables** for quest defs; chunk spawner `dialogue[]` normalize/save.
2. **Editor Quests menu** CRUD + validation UI (no runtime).
3. **Editor spawner dialogue** UI + save on chunk.
4. **Editor UX** unsaved-chunk guard (§9) — can ship earlier independently.
5. **Runtime dialogue** — talk → server nodes → client panel; requirements; effects `startQuest` / `takeItem` / `giveItem`.
6. **Runtime quest engine** — state, condition listeners, step advance, rewards, quest log UI.
7. **Apply revision** reloads quest defs; in-flight character progress keeps quest ids (orphan progress if quest deleted — §8).
8. **Tests** for normalize, dialogue requirements, kill quotas, turn-in, overflow pigeon.
9. **Script verbs** (later): `if quest active "…"`, etc., in same commit as needed — see SCRIPTS.md parity rule.

---

## 8. Edge cases (resolved in plan)

| Topic | Decision |
|-------|----------|
| Quest deleted while players active | Progress remains `orphaned`; log shows “Quest unavailable”; cannot advance; admin may clear |
| Spawner id renamed | Dialogue/quest refs break → editor validation warning; runtime condition fails closed |
| Multiple NPCs same dialogue trigger string | Triggers are **per spawnerId**; no global trigger namespace |
| `hasItem` while item in vault | False — bag only |
| Kill credit for `killCount` | Only kills while step active; deaths by unrelated players don’t count for this character |
| Player dies mid-quest | Progress kept (no fail-on-death in v1) |
| Aggressive NPC + dialogue | Talkable only when not in combat / or always if talkable flag — **defer:** talkable if not currently targeting the player |
| Turn-in without removing items | Use explicit `takeItem` effect on the turn-in response or step `onComplete` |
| Concurrent steps | **No** — one active step per quest |
| Parallel quests | **Yes** — multiple active quests per character; soft cap e.g. **20** |
| `atTile` with multiplayer crowding | Standing on tile is enough |
| Interact same block repeatedly | `interactBlock` sets a once-flag per step unless condition is re-checkable each interact — **once per step** |
| Dialogue effects vs quest step conditions | Both allowed; prefer turn-in items via dialogue effects so the NPC “takes” them narratively |
| Chunk not loaded | Kill/interact on unloaded sim: only live simulating entities emit events (normal) |
| Apply mid-dialogue | Close dialogue on revision apply; reopen requires talk again |
| Non-humanoid dialogue | Only `talkable` / humanoid spawners show dialogue editor |

### 8.1 Known weaknesses / open problems

1. **Quest ↔ dialogue coupling** — easy to leave dangling quest ids in responses. *Mitigation:* editor validation + delete warnings.
2. **No visual tile picker in v1 quest editor** — authors type coordinates (reuse live position readout idea from scripts). *Mitigation:* “Use current editor hover tile” button later.
3. **Repeatable quests / daily** — not in v1.
4. **Branching quest graphs** — v1 is linear steps only; branches via different quests or dialogue-only forks.
5. **Localization** — single language strings in authored data.
6. **Script parity** — quest inspect/advance verbs lag until play scripts need them.

---

## 9. World editor: unsaved chunk navigation & Save affordance

Independent of quests; ship with this plan’s commit.

### 9.1 Dirty state

- Track a **baseline** snapshot when the selected chunk finishes loading / after successful save.
- Any paint, erase, open toggle, spawner add/edit/remove → **dirty**.
- Compare structurally (grounds, blocks, spawners, open), not by reference.

### 9.2 Navigate away

Navigating to another chunk (N/S/E/W or any future jump) while dirty:

1. Modal: **You have unsaved changes on this chunk.**  
   - **Cancel** — stay.  
   - **Discard** — load target chunk, drop local draft.  
   - **Save** — save current chunk, then navigate (on save success).

### 9.3 Save button

- **Disabled** when not dirty (or no draft loaded).
- **Enabled + blinking** (CSS pulse) when dirty — draws attention that a save is pending.
- After successful save: clear dirty, stop blink, disable until next edit.

---

## 10. Authority & safety

- Clients never decide quest completion or dialogue effect outcomes.
- Dialogue response payloads send `trigger` / `responseIndex`; server re-checks requirements.
- Quest defs and dialogue are admin-only edits.
- Condition checks use the same inventory/combat/interact pipelines as play.

---

## 11. Feasibility

**High** for linear quests + spawner dialogue + editor CRUD.  
**Medium** for polished validation and revision/orphan UX.  
Kill quotas and dialogue start/turn-in cover most MMO tutorial/fetch/kill loops without a full quest graph language.

**Stability:** good if events are explicit (kill, interact, dialogue enter) and conditions fail closed on bad refs. Risk concentrates in authoring mistakes (dangling ids) — editor validation is mandatory for a sturdy content pipeline.
