BlueGit

timfa questward

Files

questward / docs / QUESTS.md

QUESTS.md

QUESTS.md 16.8 KiB Download Raw

Quests & NPC dialogue (world editor)

Status: partial (v1 runtime + editors; polish / graph / effects UI later) 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 and dialogue trees as world-scoped assets (editors under World settings).
  • Assign a dialogue to a humanoid spawner by reference (dialogueId); show assignment counts; support unique dialogues.
  • Progress quests via objectives with shared multi-condition sets (including negations) and per-step journal text.
  • Dialogue: line gifts, player-choice triggers, or auto-branches; track dialogueHeard per step; interrupt on attack.
  • Player Quests UI: list + split detail (journal | step/objectives).
  • Fail safe: broken references fail closed; editor validation catches unique/assignment rules.

---

2. Persistence & identity

AssetStorageApply model
Quest definitionsworld.sqlite (revisioned with map)Editor save → pending; Apply now → live
Dialogue treesworld.sqlite (revisioned with map) — not embedded in chunk JSONSame as quests
Spawner → dialogue linkChunk spawner config.dialogueId (string \null)Saved with the chunk
Quest progressstate.sqlite (questState)Live
Dialogue heardstate.sqlite (dialogueHeard)Live

2.1 IDs

  • Quest id: stable slug (deliver-tin-ore). Prefer immutable after publish.
  • Quest step id: stable within quest; conditions also use 1-based index in steps[] (§4).
  • Dialogue id: stable world-scoped id (smith-intro). Keys dialogueHeard, conditions, spawner assignment.
  • Dialogue step id / trigger id: stable within that dialogue.
  • NPC reference in quests: prefer spawner id + optional display-name hint — not transient entity ids.

2.2 World settings: Quests & Dialogues editors

In the world editor chrome, place Quests and Dialogues as separate buttons directly under the Settings button (same control stack, not tabs inside the Settings modal).

ButtonPurpose
SettingsExisting world settings
QuestsCRUD all quest defs (id, title, steps, objectives, rewards, validation)
DialoguesCRUD all dialogue trees (id, unique flag, steps, exits, validation)

Both editors are world-global (not per-chunk). Saves go through the same admin auth + revision story as other authored world data.

Dialogues list columns: id, label/title, step count, unique, assigned spawner count, validation warnings.

Delete dialogue: warn if any spawner still references it; optionally block delete until unassigned.

2.3 Spawner assignment

On a humanoid / talkable spawner:

  • Dropdown: Dialogue → none, or pick from world dialogue list (show id + unique badge).
  • Stores config.dialogueId only (no inline tree on the spawner).

Assignment count: Dialogues editor shows how many spawners currently reference each dialogueId (scan loaded/pending world chunks, or maintain an index on save). Click-through list of assignees (chunk + spawner label) is nice-to-have in v1.

2.4 Unique dialogues

DialogueTree.unique: boolean   // default false

When unique === true:

1. At most one spawner in the world may have config.dialogueId equal to that id. 2. That spawner’s maxAlive must be 1 (editor clamps / blocks save otherwise; server normalize rejects Apply if violated).

Editor UX:

  • Toggling Unique on while 2+ spawners assigned → block or offer “unassign others / cancel”.
  • Assigning a unique dialogue to a second spawner → block with clear error.
  • Setting maxAlive > 1 on a spawner that holds a unique dialogue → block or force maxAlive = 1.

Non-unique dialogues may be shared by many spawners (and many alive NPCs); dialogueHeard is still keyed by dialogueId+stepId (shared script progress).

---

3. Quest definition shape

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 & objectives

A quest advances one step at a time. Each step has one or more objectives. Each objective has a player-facing text and a ConditionSet (multiple conditions with optional negation). The step completes only when all objectives on that step are done (AND).

Step {
  stepId: string
  title: string
  description: string
  completionJournalText: string
  objectives: Objective[]            // ≥ 1; all must complete
  onEnter?: Effect[]
  onComplete?: Effect[]
}

Objective {
  objectiveId: string
  text: string                       // HUD / detail line
  when: ConditionSet                 // objective complete when set passes (or event latch inside set)
}

Advancement:

1. While a step is active, the server tracks which objectiveIds are satisfied. 2. When every objective on the step is complete → append journal line → state n → n+1 or completed + rewards → show toast “Quest objectives achieved”. Clicking the toast opens the Quests detail modal on that quest. 3. Client: completed objectives struck through.

3.2 Condition sets (quests + dialogue)

Shared in shared/. Evaluated only on the server.

ConditionSet {
  all: ConditionClause[]     // every clause must pass (AND); empty = always true
}

ConditionClause {
  not?: boolean              // default false; if true, invert the condition result
  condition: Condition
}

Semantics: all clauses AND-ed. “Has item X, but not quest completed Y” → two clauses, second with not: true (or use a dedicated negative kind — prefer not on the clause so every kind is invertible).

Used by:

  • quest objectives (when)
  • dialogue triggers (when — hide if fail)
  • dialogue auto-branches (when — first branch whose set passes)

Editor: condition picker rows with a NOT toggle per row; add/remove rows.

Condition kinds

KindFieldsMeaning
hasItemitemId, quantity (≥ 1)Bag (not vault) has ≥ N
atTiledimensionId, tileX, tileYExact tile in that dimension (default overworld)
nearTiledimensionId, tileX, tileY, range (≥ 1)Chebyshev ≤ range in dim
inRectdimensionId, minTileX, minTileY, maxTileX, maxTileYInclusive AABB in dim
atChunkdimensionId, chunkX, chunkYPlayer chunk in dim
inDimensiondimensionIdCurrently in that dimension
hasVisitedDimensiondimensionIdHas entered that dim at least once
questStatequestId, stateEquals not-started \completed \number n
questStepAtLeastquestId, step (≥ 1)Active index ≥ step or completed
dialogueHearddialogueId, stepIdHeard row exists
dialogueTriggerdialogueId, triggerLatch: player chose that trigger (quest objectives)
hpAtLeastamount (≥ 0)Current HP ≥ amount
staminaAtLeastamount (≥ 0)Current stamina ≥ amount
hpPercentAtLeastpercent (0–100)currentHP / maxHP × 100 ≥ percent
staminaPercentAtLeastpercent (0–100)currentStamina / maxStamina × 100 ≥ percent
skillLevelAtLeastskillId, level (1–99)skillLevel(skills, skillId) ≥ level
killCountmobTypeId or spawnerId, count NKills while this quest step active
interactBlockdimensionId, tile and/or blockTypeIdSuccessful interact (once per quest step)

Notes:

  • Prefer not + hasItem over a separate lacksItem kind (legacy alias ok). Same for dialogueNotHeard → not + dialogueHeard.
  • Thresholds use ≥ (“above or equal”); document in editor labels as “at least”.
  • Max HP / max stamina = same formulas the play sim already uses for the character.
  • Unknown ids → clause fails closed (raw condition false; with not, that becomes true — authors should avoid dangling ids; validation warns).
  • Kill attribution = existing combat kill credit.

3.3 Rewards & effects (v1)

KindFields
giveItemitemId, quantity
giveXpskillId, amount
takeItemitemId, quantity
startQuestquestId

Sources: quest onEnter / onComplete, dialogue line, trigger, branch. Full bag → vault via carrier pigeon.

---

4. Character quest state & journal

4.0 Quest state

QuestStateValue = "not-started" | number | "completed"
// number = 1-based index of current incomplete step
CharacterQuest {
  questId: string
  state: QuestStateValue
  completedObjectiveIds: string[]
  counters: { [key: string]: number }
  startedAt?, completedAt?
}

Missing row ⇒ not-started. Conditions read state only; counters/objectives are runtime detail for UI + event objectives.

4.0b Dialogue heard

dialogueHeard (characterId, dialogueId, stepId, heardAt)
UNIQUE (characterId, dialogueId, stepId)

Insert on step enter (first time). Permanent in v1. Gate repeat gifts with when sets (not + dialogueHeard, not + hasItem, etc.).

4.0c Journal

QuestJournalEntry { questId, stepId, text, writtenAt }

Append-only; text frozen at write time.

---

4.1 Player UI — Quests

  • Quests HUD control → list modal: active (state number) first, completed at bottom; hide not-started.
  • Detail modal: left journal (this quest), right step description + objectives (strikethrough when done).
  • Step-complete toast: text “Quest objectives achieved”. Click → open quest detail for the quest that just advanced (same modal stack as the Quests button).

---

5. Dialogue (world asset + spawner link)

5.1 Shape

DialogueTree {
  dialogueId: string
  label: string                   // editor list title
  unique: boolean                 // default false; see §2.4
  steps: DialogueStep[]
  entryStepId?: string
}

DialogueStep {
  stepId: string
  label: string
  lines: DialogueLine[]
  itemRewards?: { itemId: number, quantity: number }[]  // after lines, before exit
  exit:
    | { kind: "triggers", triggers: DialogueTrigger[] }
    | { kind: "branches", branches: DialogueBranch[] }
    | { kind: "end" }
}

DialogueLine {
  speaker: "npc" | "player"
  text: string
  effects?: Effect[]
}

DialogueTrigger {
  trigger: string
  label: string                   // editor
  text: string                    // player button
  nextStepId: string | null       // null → end
  when?: ConditionSet             // hide if fail; omit = always show
  effects?: Effect[]
}

DialogueBranch {
  label?: string
  when: ConditionSet              // empty all[] = always
  nextStepId: string | null
  effects?: Effect[]
}

End rules: null nextStepId, exit.kind: "end", no matching branch, or no visible triggers → close dialogue.

5.2 Runtime

1. Talk to NPC whose spawner has dialogueId → load world DialogueTree → open entryStepId. 2. Enter step → insert dialogueHeard if new → play lines (apply line effects). 3. On advance after the last line: grant itemRewards (bag first, overflow to bank/vault), show reward notices in the dialogue UI, then evaluate exit. 4. Triggers / branches / end as authored (conditions see items already granted). 5. Interrupt: if the NPC is attacked (takes a hostile hit / combat engagement against it) while a player has this dialogue open → immediately close that dialogue session (no further lines, choices, or pending line effects). Re-talk required. Does not roll back already-applied effects or heard rows.

5.3 Editor (Dialogues panel)

  • List + inspector (graph canvas = v1.1).
  • Per dialogue: id, label, unique, assignment count, steps, exit modes, shared condition-set picker (with NOT).
  • Validation: unique rules (§2.4), missing refs, empty texts, unreachable steps.

5.4 Spawner modal

Humanoid: Dialogue dropdown bound to world dialogues (not an inline tree editor). Link to “Open in Dialogues editor” optional.

---

6. How quests start

startQuest effect → not-started → 1. Block if already numeric or completed (v1 no repeats).

---

7. Implementation plan (phased)

1. Shared Condition / ConditionSet / Effect in shared/. 2. World DB: quest defs + dialogue trees; state: questState, dialogueHeard, journal. 3. World settings Quests + Dialogues editors; spawner dialogueId + unique/maxAlive validation; assignment counts. 4. Editor unsaved-chunk guard (§9) — may already ship. 5. Runtime dialogue + combat interrupt; line/trigger/branch effects. 6. Quest engine + Quests HUD. 7. Apply revision + tests (conditions+NOT, unique, interrupt, heard, journal).

---

8. Edge cases (resolved)

TopicDecision
Unique + 2 assigneesEditor/server reject until ≤ 1
Unique + maxAlive ≠ 1Reject / clamp to 1
Mark unique while assigned elsewhereMust unassign others first
Shared (non-unique) dialogueMany spawners OK; heard shared by dialogueId
Spawner dialogueId missing treeTalk no-ops / error log; fail closed
NPC attacked mid-dialogueSession closes immediately
Player walks away / disconnectClose session (no progress loss beyond already applied)
not + unknown idRaw false → NOT true — validation must warn on unknown ids
ThresholdsAll “at least” (≥)
Parallel questsYes; soft cap ~20 active
One step per questYes (single numeric state)
Apply mid-dialogueClose sessions

8.1 Open product choices (see §12)

Small list of remaining decisions before / during implementation — none are architectural blockers if defaults in §12 are accepted.

---

9. World editor: unsaved chunk navigation & Save affordance

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

9.1 Dirty state

  • Baseline when chunk loads / after save; paint/spawner edits → dirty; structural compare.

9.2 Navigate away

Modal: Cancel / Discard / Save then navigate.

9.3 Save button

Disabled when clean; enabled + blinking when dirty.

---

10. Authority & safety

  • Client never decides conditions, heard, quest state, or effects.
  • Choose payload: dialogueId, stepId, trigger; server re-evaluates when.
  • Branches and interrupts are server-side.
  • Unique / maxAlive enforced on save and Apply.

---

11. Feasibility

High–medium. World-scoped dialogue assets + assignment is cleaner than per-spawner trees. ConditionSet + not covers “A but not B” without exploding kind count. Combat interrupt is a small session hook.

Hardest: event wiring for quest objectives + revision/orphan UX. Graph canvas still v1.1.

---

12. Defaults if unspecified (implementation may proceed)

Accept these unless overridden:

1. Condition polarity: per-clause not?: boolean inside ConditionSet.all (no separate OR groups in v1; use multiple ordered dialogue branches for OR). 2. Thresholds: all ≥ (“at least”). 3. Interrupt: any hostile damage/engagement on the NPC closes dialogue for whoever was talking to it (not only if the talker is the attacker). 4. Unique conflict: editor blocks the illegal save (does not auto-unassign silently). 5. Assignment count: computed from pending/applied chunk spawners when opening Dialogues editor (accurate enough for v1). 6. lacksItem / dialogueNotHeard: not separate kinds; use not + positive kind (editor may offer presets). 7. Objectives: one objective completes when its entire ConditionSet is true (event kinds latch once true). 8. Editors placement: Quests and Dialogues buttons stacked under the Settings button (separate modals, not Settings tabs). 9. Step-complete toast: “Quest objectives achieved”; click opens that quest’s detail modal.

Not blocking for v1: graph canvas, script verbs, repeatable quests, localization, visual tile picker.

Source
1# Quests & NPC dialogue (world editor)
2
3**Status:** partial (v1 runtime + editors; polish / graph / effects UI later)
4**Related:** `docs/FEATURES.md` (Quests, Mob definitions), `docs/SCRIPTS.md` (parity reminder for future script verbs), server authority rules
5
6Quests 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.
7
8This document is the product + data + editor spec for implementation.
9
10---
11
12## 1. Goals
13
14- Author **quests** and **dialogue trees** as world-scoped assets (editors under **World settings**).
15- Assign a dialogue to a **humanoid spawner** by reference (`dialogueId`); show assignment counts; support **unique** dialogues.
16- Progress quests via **objectives** with shared multi-condition sets (including negations) and per-step **journal** text.
17- Dialogue: line gifts, player-choice triggers, or **auto-branches**; track **dialogueHeard** per step; **interrupt on attack**.
18- Player **Quests** UI: list + split detail (journal | step/objectives).
19- Fail safe: broken references fail closed; editor validation catches unique/assignment rules.
20
21---
22
23## 2. Persistence & identity
24
25| Asset | Storage | Apply model |
26|-------|---------|-------------|
27| **Quest definitions** | `world.sqlite` (revisioned with map) | Editor save → pending; **Apply now** → live |
28| **Dialogue trees** | `world.sqlite` (revisioned with map) — **not** embedded in chunk JSON | Same as quests |
29| **Spawner → dialogue link** | Chunk spawner `config.dialogueId` (string \| null) | Saved with the chunk |
30| **Quest progress** | `state.sqlite` (`questState`) | Live |
31| **Dialogue heard** | `state.sqlite` (`dialogueHeard`) | Live |
32
33### 2.1 IDs
34
35- **Quest id:** stable slug (`deliver-tin-ore`). Prefer immutable after publish.
36- **Quest step id:** stable within quest; conditions also use **1-based index** in `steps[]` (§4).
37- **Dialogue id:** stable world-scoped id (`smith-intro`). Keys `dialogueHeard`, conditions, spawner assignment.
38- **Dialogue step id / trigger id:** stable within that dialogue.
39- **NPC reference in quests:** prefer **spawner id** + optional display-name hint — not transient entity ids.
40
41### 2.2 World settings: Quests & Dialogues editors
42
43In the world editor chrome, place **Quests** and **Dialogues** as **separate buttons directly under the Settings button** (same control stack, not tabs inside the Settings modal).
44
45| Button | Purpose |
46|--------|---------|
47| **Settings** | Existing world settings |
48| **Quests** | CRUD all quest defs (id, title, steps, objectives, rewards, validation) |
49| **Dialogues** | CRUD all dialogue trees (id, unique flag, steps, exits, validation) |
50
51Both editors are **world-global** (not per-chunk). Saves go through the same admin auth + revision story as other authored world data.
52
53**Dialogues list columns:** id, label/title, step count, **`unique`**, **assigned spawner count**, validation warnings.
54
55**Delete dialogue:** warn if any spawner still references it; optionally block delete until unassigned.
56
57### 2.3 Spawner assignment
58
59On a **humanoid / talkable** spawner:
60
61- Dropdown: **Dialogue** → none, or pick from world dialogue list (show id + unique badge).
62- Stores `config.dialogueId` only (no inline tree on the spawner).
63
64**Assignment count:** Dialogues editor shows how many spawners currently reference each `dialogueId` (scan loaded/pending world chunks, or maintain an index on save). Click-through list of assignees (chunk + spawner label) is nice-to-have in v1.
65
66### 2.4 Unique dialogues
67
68```text
69DialogueTree.unique: boolean // default false
70```
71
72When `unique === true`:
73
741. **At most one spawner** in the world may have `config.dialogueId` equal to that id.
752. That spawner’s **`maxAlive` must be `1`** (editor clamps / blocks save otherwise; server normalize rejects Apply if violated).
76
77Editor UX:
78
79- Toggling **Unique** on while 2+ spawners assigned → block or offer “unassign others / cancel”.
80- Assigning a unique dialogue to a second spawner → block with clear error.
81- Setting `maxAlive > 1` on a spawner that holds a unique dialogue → block or force `maxAlive = 1`.
82
83Non-unique dialogues may be shared by many spawners (and many alive NPCs); `dialogueHeard` is still keyed by `dialogueId`+`stepId` (shared script progress).
84
85---
86
87## 3. Quest definition shape
88
89```text
90Quest {
91 questId: string
92 title: string
93 description: string // player-facing log blurb (in-universe)
94 steps: Step[] // ordered progression
95 rewards?: Reward[] // granted on final step complete
96 cancelable?: boolean // default false in v1
97}
98```
99
100### 3.1 Steps & objectives
101
102A quest advances one **step** at a time. Each step has one or more **objectives**. Each objective has a player-facing **text** and a **ConditionSet** (multiple conditions with optional negation). The step completes only when **all** objectives on that step are done (AND).
103
104```text
105Step {
106 stepId: string
107 title: string
108 description: string
109 completionJournalText: string
110 objectives: Objective[] // ≥ 1; all must complete
111 onEnter?: Effect[]
112 onComplete?: Effect[]
113}
114
115Objective {
116 objectiveId: string
117 text: string // HUD / detail line
118 when: ConditionSet // objective complete when set passes (or event latch inside set)
119}
120```
121
122**Advancement:**
123
1241. While a step is active, the server tracks which `objectiveId`s are satisfied.
1252. When every objective on the step is complete → append journal line → `state` `n` → `n+1` or `completed` + rewards → show toast **“Quest objectives achieved”**. Clicking the toast opens the **Quests** detail modal on **that quest**.
1263. Client: completed objectives struck through.
127
128### 3.2 Condition sets (quests + dialogue)
129
130Shared in `shared/`. Evaluated **only on the server**.
131
132```text
133ConditionSet {
134 all: ConditionClause[] // every clause must pass (AND); empty = always true
135}
136
137ConditionClause {
138 not?: boolean // default false; if true, invert the condition result
139 condition: Condition
140}
141```
142
143**Semantics:** `all` clauses AND-ed. “Has item X, but **not** quest completed Y” → two clauses, second with `not: true` (or use a dedicated negative kind — prefer **`not` on the clause** so every kind is invertible).
144
145Used by:
146
147- quest **objectives** (`when`)
148- dialogue **triggers** (`when` — hide if fail)
149- dialogue **auto-branches** (`when` — first branch whose set passes)
150
151Editor: condition picker rows with a **NOT** toggle per row; add/remove rows.
152
153#### Condition kinds
154
155| Kind | Fields | Meaning |
156|------|--------|---------|
157| `hasItem` | `itemId`, `quantity` (≥ 1) | Bag (not vault) has ≥ N |
158| `atTile` | `dimensionId`, `tileX`, `tileY` | Exact tile in that dimension (default `overworld`) |
159| `nearTile` | `dimensionId`, `tileX`, `tileY`, `range` (≥ 1) | Chebyshev ≤ range in dim |
160| `inRect` | `dimensionId`, `minTileX`, `minTileY`, `maxTileX`, `maxTileY` | Inclusive AABB in dim |
161| `atChunk` | `dimensionId`, `chunkX`, `chunkY` | Player chunk in dim |
162| `inDimension` | `dimensionId` | Currently in that dimension |
163| `hasVisitedDimension` | `dimensionId` | Has entered that dim at least once |
164| `questState` | `questId`, `state` | Equals `not-started` \| `completed` \| number `n` |
165| `questStepAtLeast` | `questId`, `step` (≥ 1) | Active index ≥ step **or** `completed` |
166| `dialogueHeard` | `dialogueId`, `stepId` | Heard row exists |
167| `dialogueTrigger` | `dialogueId`, `trigger` | **Latch:** player chose that trigger (quest objectives) |
168| `hpAtLeast` | `amount` (≥ 0) | Current HP ≥ amount |
169| `staminaAtLeast` | `amount` (≥ 0) | Current stamina ≥ amount |
170| `hpPercentAtLeast` | `percent` (0–100) | currentHP / maxHP × 100 ≥ percent |
171| `staminaPercentAtLeast` | `percent` (0–100) | currentStamina / maxStamina × 100 ≥ percent |
172| `skillLevelAtLeast` | `skillId`, `level` (1–99) | `skillLevel(skills, skillId) ≥ level` |
173| `killCount` | `mobTypeId` **or** `spawnerId`, `count` N | Kills while this quest step active |
174| `interactBlock` | `dimensionId`, tile and/or `blockTypeId` | Successful interact (once per quest step) |
175
176**Notes:**
177
178- Prefer **`not` + `hasItem`** over a separate `lacksItem` kind (legacy alias ok). Same for `dialogueNotHeard` → `not` + `dialogueHeard`.
179- Thresholds use **≥** (“above or equal”); document in editor labels as “at least”.
180- Max HP / max stamina = same formulas the play sim already uses for the character.
181- Unknown ids → clause **fails closed** (raw condition false; with `not`, that becomes true — authors should avoid dangling ids; validation warns).
182- Kill attribution = existing combat kill credit.
183
184### 3.3 Rewards & effects (v1)
185
186| Kind | Fields |
187|------|--------|
188| `giveItem` | `itemId`, `quantity` |
189| `giveXp` | `skillId`, `amount` |
190| `takeItem` | `itemId`, `quantity` |
191| `startQuest` | `questId` |
192
193Sources: quest `onEnter` / `onComplete`, dialogue **line**, **trigger**, **branch**.
194Full bag → vault via carrier pigeon.
195
196---
197
198## 4. Character quest state & journal
199
200### 4.0 Quest state
201
202```text
203QuestStateValue = "not-started" | number | "completed"
204// number = 1-based index of current incomplete step
205```
206
207```text
208CharacterQuest {
209 questId: string
210 state: QuestStateValue
211 completedObjectiveIds: string[]
212 counters: { [key: string]: number }
213 startedAt?, completedAt?
214}
215```
216
217Missing row ⇒ `not-started`. Conditions read `state` only; counters/objectives are runtime detail for UI + event objectives.
218
219### 4.0b Dialogue heard
220
221```text
222dialogueHeard (characterId, dialogueId, stepId, heardAt)
223UNIQUE (characterId, dialogueId, stepId)
224```
225
226Insert on step **enter** (first time). Permanent in v1. Gate repeat gifts with `when` sets (`not` + `dialogueHeard`, `not` + `hasItem`, etc.).
227
228### 4.0c Journal
229
230```text
231QuestJournalEntry { questId, stepId, text, writtenAt }
232```
233
234Append-only; text frozen at write time.
235
236---
237
238## 4.1 Player UI — Quests
239
240- **Quests** HUD control → list modal: active (`state` number) first, **completed** at bottom; hide `not-started`.
241- Detail modal: left journal (this quest), right step description + objectives (strikethrough when done).
242- **Step-complete toast:** text **“Quest objectives achieved”**. Click → open quest detail for the quest that just advanced (same modal stack as the Quests button).
243
244---
245
246## 5. Dialogue (world asset + spawner link)
247
248### 5.1 Shape
249
250```text
251DialogueTree {
252 dialogueId: string
253 label: string // editor list title
254 unique: boolean // default false; see §2.4
255 steps: DialogueStep[]
256 entryStepId?: string
257}
258
259DialogueStep {
260 stepId: string
261 label: string
262 lines: DialogueLine[]
263 itemRewards?: { itemId: number, quantity: number }[] // after lines, before exit
264 exit:
265 | { kind: "triggers", triggers: DialogueTrigger[] }
266 | { kind: "branches", branches: DialogueBranch[] }
267 | { kind: "end" }
268}
269
270DialogueLine {
271 speaker: "npc" | "player"
272 text: string
273 effects?: Effect[]
274}
275
276DialogueTrigger {
277 trigger: string
278 label: string // editor
279 text: string // player button
280 nextStepId: string | null // null → end
281 when?: ConditionSet // hide if fail; omit = always show
282 effects?: Effect[]
283}
284
285DialogueBranch {
286 label?: string
287 when: ConditionSet // empty all[] = always
288 nextStepId: string | null
289 effects?: Effect[]
290}
291```
292
293**End rules:** null `nextStepId`, `exit.kind: "end"`, no matching branch, or no visible triggers → **close dialogue**.
294
295### 5.2 Runtime
296
2971. Talk to NPC whose spawner has `dialogueId` → load world DialogueTree → open `entryStepId`.
2982. Enter step → insert `dialogueHeard` if new → play lines (apply line effects).
2993. On **advance** after the last line: grant `itemRewards` (bag first, overflow to bank/vault), show reward notices in the dialogue UI, then evaluate exit.
3004. Triggers / branches / end as authored (conditions see items already granted).
3015. **Interrupt:** if the NPC is **attacked** (takes a hostile hit / combat engagement against it) while a player has this dialogue open → **immediately close** that dialogue session (no further lines, choices, or pending line effects). Re-talk required. Does not roll back already-applied effects or heard rows.
302
303### 5.3 Editor (Dialogues panel)
304
305- List + inspector (graph canvas = v1.1).
306- Per dialogue: id, label, **unique**, assignment count, steps, exit modes, shared condition-set picker (with NOT).
307- Validation: unique rules (§2.4), missing refs, empty texts, unreachable steps.
308
309### 5.4 Spawner modal
310
311Humanoid: **Dialogue** dropdown bound to world dialogues (not an inline tree editor). Link to “Open in Dialogues editor” optional.
312
313---
314
315## 6. How quests start
316
317`startQuest` effect → `not-started` → `1`. Block if already numeric or `completed` (v1 no repeats).
318
319---
320
321## 7. Implementation plan (phased)
322
3231. Shared `Condition` / `ConditionSet` / `Effect` in `shared/`.
3242. World DB: quest defs + dialogue trees; state: `questState`, `dialogueHeard`, journal.
3253. World settings **Quests** + **Dialogues** editors; spawner `dialogueId` + unique/maxAlive validation; assignment counts.
3264. Editor unsaved-chunk guard (§9) — may already ship.
3275. Runtime dialogue + combat interrupt; line/trigger/branch effects.
3286. Quest engine + Quests HUD.
3297. Apply revision + tests (conditions+NOT, unique, interrupt, heard, journal).
330
331---
332
333## 8. Edge cases (resolved)
334
335| Topic | Decision |
336|-------|----------|
337| Unique + 2 assignees | Editor/server reject until ≤ 1 |
338| Unique + maxAlive ≠ 1 | Reject / clamp to 1 |
339| Mark unique while assigned elsewhere | Must unassign others first |
340| Shared (non-unique) dialogue | Many spawners OK; heard shared by dialogueId |
341| Spawner dialogueId missing tree | Talk no-ops / error log; fail closed |
342| NPC attacked mid-dialogue | Session closes immediately |
343| Player walks away / disconnect | Close session (no progress loss beyond already applied) |
344| `not` + unknown id | Raw false → NOT true — validation must warn on unknown ids |
345| Thresholds | All “at least” (≥) |
346| Parallel quests | Yes; soft cap ~20 active |
347| One step per quest | Yes (single numeric state) |
348| Apply mid-dialogue | Close sessions |
349
350### 8.1 Open product choices (see §12)
351
352Small list of remaining decisions before / during implementation — none are architectural blockers if defaults in §12 are accepted.
353
354---
355
356## 9. World editor: unsaved chunk navigation & Save affordance
357
358Independent of quests; ship with this plan’s commit.
359
360### 9.1 Dirty state
361
362- Baseline when chunk loads / after save; paint/spawner edits → dirty; structural compare.
363
364### 9.2 Navigate away
365
366Modal: Cancel / Discard / Save then navigate.
367
368### 9.3 Save button
369
370Disabled when clean; enabled + blinking when dirty.
371
372---
373
374## 10. Authority & safety
375
376- Client never decides conditions, heard, quest state, or effects.
377- Choose payload: `dialogueId`, `stepId`, `trigger`; server re-evaluates `when`.
378- Branches and interrupts are server-side.
379- Unique / maxAlive enforced on save and Apply.
380
381---
382
383## 11. Feasibility
384
385**High–medium.** World-scoped dialogue assets + assignment is cleaner than per-spawner trees. ConditionSet + `not` covers “A but not B” without exploding kind count. Combat interrupt is a small session hook.
386
387Hardest: event wiring for quest objectives + revision/orphan UX. Graph canvas still v1.1.
388
389---
390
391## 12. Defaults if unspecified (implementation may proceed)
392
393Accept these unless overridden:
394
3951. **Condition polarity:** per-clause `not?: boolean` inside `ConditionSet.all` (no separate OR groups in v1; use multiple ordered dialogue branches for OR).
3962. **Thresholds:** all ≥ (“at least”).
3973. **Interrupt:** any hostile damage/engagement **on the NPC** closes dialogue for whoever was talking to it (not only if the talker is the attacker).
3984. **Unique conflict:** editor **blocks** the illegal save (does not auto-unassign silently).
3995. **Assignment count:** computed from pending/applied chunk spawners when opening Dialogues editor (accurate enough for v1).
4006. **`lacksItem` / `dialogueNotHeard`:** not separate kinds; use `not` + positive kind (editor may offer presets).
4017. **Objectives:** one objective completes when its entire `ConditionSet` is true (event kinds latch once true).
4028. **Editors placement:** **Quests** and **Dialogues** buttons stacked **under** the Settings button (separate modals, not Settings tabs).
4039. **Step-complete toast:** “Quest objectives achieved”; click opens that quest’s detail modal.
404
405**Not blocking for v1:** graph canvas, script verbs, repeatable quests, localization, visual tile picker.