# Player scripts (AFK / offline)

**Status:** not implemented (design only)  
**Related:** `questward_server_technical_design_v0.6.md` §18 (controller abstraction, offline entity, sandbox rules)

Scripts are a **sandboxed language** interpreted on the **server**. They never mutate world state directly; they emit the same player **intents** as a human client (`moveTo`, gather, craft, attack, shop, equip, …). The server validates every step.

This document is the product + language spec for implementation.

---

## 1. Goals

- Automate simple loops: gather → bank/craft → fight → recover.
- Run **while online** (watch + stop bar), **while AFK** (idle 30+ minutes), or **while offline** (character stays in the world, max 1 hour).
- Keep the language **small**, readable, and hard to misuse.
- Fail loudly: toast (online) or pigeon letter (offline), with line + operation + reason.

---

## 2. Player UI

### 2.1 Scripts button

- HUD control **Scripts** opens the Scripts panel.
- Panel lists the player’s saved scripts (name + badges for Offline / AFK flags).
- Actions per script: **Edit**, **Delete**, **Run** (online).
- **New script** creates an empty script and opens the editor.

### 2.2 Script editor

- Name field.
- Text area with **syntax highlighting** (keywords, strings, numbers, comments, labels, `@` vars).
- Flags (mutually independent; at most one script should be marked for each role — marking one clears that flag on others):
  - **Run this while offline** — eligible on logout confirmation.
  - **Run while AFK** — auto-starts after **30 minutes** with no player actions.
- **Live world coordinates** at the **bottom** of the editor (player’s current tile, e.g. `Position: (5, 18)`), updating as the character moves while the panel is open — so authors can copy values into `set @waypoint (5, 18)`.
- Optional: a small **Copy** control that copies `set @here (x, y)` (or just `(x, y)`) to the clipboard.
- **Save** / **Cancel**.

### 2.3 Online run bar

When a script is running (started manually, AFK auto-start, or resumed after re-login onto an offline script):

- Fixed bar at the **bottom** of the screen.
- Shows: script name, **current line** (number + source text), **Stop**.
- Manual player intents (move, attack, gather, …) **stop** the script (treat as cancel), except pure camera/UI (open bag, zoom, settings).

### 2.4 Logout confirmation

On logout while in the world:

1. Modal: **Are you sure you want to log out?**  
   - **No** — stay.  
   - **Yes** — log out.  
   - Checkbox (default **unchecked**): **Run offline script**  
     - Enabled only if the player has a script marked **Run this while offline**.
2. If the checkbox is checked, show an extra **red** line:  
   **Running a script means your character remains in the world and can still be attacked!**
3. Confirming with the checkbox checked starts/continues the offline script on that character (see §4).

---

## 3. Modes

| Mode | How it starts | Character in world | Client |
|------|---------------|--------------------|--------|
| **Online** | Scripts panel → Run | Yes | Connected; run bar visible |
| **AFK** | No gameplay intents for **30 minutes**, and an AFK-marked script exists | Yes | Still connected; run bar appears when script starts |
| **Offline** | Logout with offline checkbox | Yes (no NetworkIdentity; keeps ChunkLoader) | Disconnected |

**AFK timer:** reset on any **gameplay intent** sent by the player (move, attack, gather, craft, shop, equip, cast, pickup, talk, …). Opening UI / scrolling chat does not reset AFK if those are not intents; prefer resetting on any outbound play command for simplicity.

**Offline duration:** max **1 hour** from offline-script start (or remaining time after restart rehydrate). Then: stop script, despawn character, persist as a normal logout.

**Re-login during offline script:** attach the client to the existing entity; keep the script running; show the run bar so the player can Stop.

---

## 4. Errors

### 4.1 Message shape

Always:

```text
Line <n>: <operation> — <reason>
```

Example:

```text
Line 12: mine — No reachable iron ore nearby.
```

### 4.2 Online / AFK (client connected)

- Stop the script.
- Show a **persistent toast** (stays until the player dismisses it) with the error message.

### 4.3 Offline (no client)

- Stop the script.
- Remove the character from the world (normal offline persist).
- Queue a **pigeon letter**:
  - Author display name: **Frederick**
  - Role flavour: manager of Idle Gaming (author line / signature as other system letters do)
  - Body:  
    `Unfortunately, your script encountered an error.`  
    then a blank line, then the error message from §4.1.

---

## 5. Language overview

- Line-oriented, case-insensitive **keywords**.
- One statement per line (blank lines and comments allowed).
- Comments: `# ...` to end of line.
- Strings: `"double quotes"` (names of blocks, mobs, items).
- **Name matching is exact** (full display name), **case-insensitive**, never fuzzy / substring / “closest spelling”. `"Tin"` does **not** match `"Tin ore"`.
- Numbers: integers (`10`, `100`).
- Labels: `label name_here` — name is letters, digits, underscore.
- **Variables:** `@name` (letters, digits, underscore after `@`). Set with `set` (§5.2). Hold a **target**, a **tile coordinate**, or (later) a number if needed.
- Implicit targets (block / mob / ground) still exist alongside `@` vars.
- No user-defined functions in v1.
- Sandbox: **not** JavaScript; custom interpreter only (§18.7 design doc).

### 5.1 Implicit targets

The script keeps three optional targets (cleared when a new target of that kind is set, or on error/stop):

| Target | Set by | Used by |
|--------|--------|---------|
| **Block** | `find block "..."` | `go`, `mine`, `chop`, `harvest`, `craft`, `in range block` |
| **Mob** | `find mob "..."` | `go`, `attack`, `buy`, `sell`, `in range mob` |
| **Ground** | `find ground "..."` | `go`, `take`, `use`, `in range ground` |

`go` without a kind uses the **most recently set** target. Prefer explicit forms when ambiguous: `go block`, `go mob`, `go ground`.

### 5.2 Variables (`@` + `set`)

| Statement | Meaning |
|-----------|---------|
| `set @tree target` | Copy the **most recently set** implicit target (block / mob / ground) into `@tree`. |
| `set @tree block` / `set @tree mob` / `set @tree ground` | Copy that specific implicit target kind into `@tree`. |
| `set @furnace here` | Store the player’s **current tile** as coordinates in `@furnace`. |
| `set @waypoint (5, 18)` | Store absolute tile coordinates `(5, 18)` in `@waypoint`. Preferred literal form. |
| `set @furnace 512 128` | Same as `(512, 128)` — space-separated form also accepted. |
| `go @furnace` | Path to the stored **coords** or to the stored **target** (same rules as `go`). |
| `go block @tree` | If `@tree` holds a block target, path to it (explicit kind). |

Rules:

- Soft cap: **32** variables per running script.
- Variables live in **runtime state** (persisted across offline rehydrate / re-login for that run). They are **not** saved with the script source.
- Using an unset `@name` → error (`go — @furnace is not set.`).
- Storing a target keeps enough identity to re-resolve (tile + kind + name / entityId). If the world object is gone when used → error (`go — Target is gone.`).

Waypoints: because `go` only works within **2 chunks** (§6.2), authors manually chain coordinate variables for long trips (e.g. mine → mid → furnace).

---

## 6. Statements (v1)

### 6.1 Targeting

| Statement | Meaning |
|-----------|---------|
| `find block "Iron ore"` | Closest **reachable** block whose display name equals (case-insensitive). Search = **visible chunk neighbourhood only** (player’s chunk + **8** surrounding = Chebyshev chunk distance ≤ **1**, same as `VISIBLE_CHUNK_RADIUS`). Sets block target. Fails if none. |
| `find mob "Shopkeeper"` | Closest living mob/NPC with exact name match in that same **3×3** chunk window. Sets mob target. Fails if none. |
| `find ground "Log"` | Closest ground item with exact name match in that same **3×3** chunk window. Sets ground target. Fails if none. |

“Closest” = Chebyshev tile distance, then path-reachable. Unreachable candidates are skipped. Multiple exact name matches → closest wins. Scripts must **not** see farther than a connected player would for entity/block discovery — never scan the full 2-chunk map ring.

### 6.2 Movement

| Statement | Meaning |
|-----------|---------|
| `go` | Path to the last set target (block / mob / ground). **Blocks** until arrived or fails. |
| `go block` / `go mob` / `go ground` | Same, explicit target kind. |
| `go @name` | Path to a variable (coords or stored target). |
| `run on` / `run off` | Toggle run gait (same rules as player: needs stamina). |

**Range hard rule:** the destination tile (target or `@` coords) must lie within **2 chunks** of the player (Chebyshev chunk distance ≤ 2; with `CHUNK_SIZE` 16 that is ≤ **32** tiles in chunk metric). Otherwise the op fails immediately:

```text
go — Too far away.
```

There is **no** automatic multi-hop pathing across the world. Use coordinate waypoints (`set @mid …` / `go @mid` / `go @furnace`) for longer trips.

Arrival = standing on the tile (ground item / interactable) or adjacent where the game requires adjacency (stations, melee, gather nodes).

### 6.3 Gathering & world interact

| Statement | Meaning |
|-----------|---------|
| `mine` | Gather/mine the targeted **block** (ore boulder, etc.). **Blocks** until finished or fails. |
| `chop` | Fell the targeted tree block. **Blocks** until finished. |
| `harvest` | Pick/harvest the targeted plant/herb/flower/cotton block. **Blocks** until finished. |
| `take` | Pick up the targeted **ground** item into the bag. |
| `use` | Interact with the targeted **ground** item if it has a use (e.g. light a log). |

Exact gather verb must match what the block supports; wrong verb → error (`chop — That is not a tree.`).

### 6.4 Crafting stations & alchemy

**Principle:** script steps mirror what a player does in the UI. No free shortcuts that skip materials, skill, adjacency, or recipe knowledge.

**Station state hard rule:** cauldron / furnace / anvil / every craft station progress is **per player**, never shared on the tile. Many characters may use the “same” station block at once without interfering. Scripts and the UI obey the same rule — this applies to **all current and future** crafting stations.

**Inventory hard rule (stations — script and player):** an item is **never committed** into a station. Slots in craft/brew UIs are a **view / reservation** over the bag only — materials do not leave the inventory when placed in a station slot. Even when it *looks* like something sits in the cauldron or bench, it is still in the bag. Therefore:

- Closing the station UI, cancelling, `cauldron clear`, script stop/error, logout, or **death mid-craft / mid-brew** must leave the bag unchanged for those materials (or immediately show them back — there was nothing to return from the station itself).
- Item loss due to closed UI or death while using a station is **impossible**.
- Materials are consumed only when the craft/brew **successfully completes** (same moment the product is created), never earlier.

This is a gameplay rule for humans and scripts alike (also `.cursor/rules/station-inventory.mdc`); the script layer must not invent a different consume-on-insert path.

#### Crafting stations (furnace, anvil, woodworking, bench, spinning wheel, loom, tailor, leatherworking, …)

| Statement | Meaning |
|-----------|---------|
| `craft "Bronze bar"` | At the targeted station **block**, start the same craft the player would (one product). **Blocks** until finished or fails (not at station, unknown recipe, missing mats, skill too low). Mats stay in the bag until success (§6.4). |
| `craft "Cotton sweater" dye` | **Tailor only:** craft with dyeing on. Uses a **random** dye charge from the bag (no colour picker). **Fails** if dyeing is requested and the bag has no dye uses left. |
| `craft "Cotton sweater"` | Tailor (or other station) **without** dyeing. |

#### Alchemy cauldron — manual steps (1:1 with UI)

Require adjacency to a cauldron block (find + go), same as opening the cauldron as a player. Brew progress is **this character’s** cauldron state only.

| Statement | Meaning |
|-----------|---------|
| `cauldron insert "Thyme"` | Select/reserve that ingredient from the bag for the brew UI (does **not** remove it from inventory — §6.4 inventory hard rule). |
| `cauldron heat` | Heat. |
| `cauldron stir` | Stir. |
| `cauldron cool` | Cool. |
| `cauldron bottle` | Bottle into an empty glass bottle. **Blocks** until done. On success, reserved mats + bottle are consumed and the potion is granted. |
| `cauldron clear` | Clear/abandon the brew UI selection; bag unchanged. |

Step order and outcomes match humans: correct sequence → potion (with Alchemy skill roll); wrong sequence → unstable brew. Scripts get **no** easier success path.

Example (same steps a player would click):

```text
find block "Cauldron"
go block
cauldron insert "Thyme"
cauldron heat
cauldron insert "Mint"
cauldron stir
cauldron bottle
```

#### Named `brew` — only with a recipe paper in the bag

| Statement | Meaning |
|-----------|---------|
| `brew "Lesser health tonic"` | Allowed **only** if the inventory contains a **recipe paper** for that potion. Then run that paper’s recorded steps and bottle (skill checks as usual). Mats are reserved until success, then consumed with the bottle — never lost on interrupt. **Fails immediately** if no matching recipe is in the bag (`brew — No recipe for that in your bag.`). |

Without a recipe item, authors must write the `cauldron …` steps themselves. `brew` is “follow this paper,” not free knowledge of the recipe.

#### Dyes (flower list, same as dye tab)

| Statement | Meaning |
|-----------|---------|
| `cauldron dye ["White flower", "Yellow flower", "Yellow flower"]` | Make dye from that multiset of flowers (here: 1 white + 2 yellow). List order = insert order; repeat a name for more of the same flower. Flowers are reserved from the bag until the dye brew completes successfully; colour/yield rules match the normal dye UI. Fails if flowers missing, not at cauldron, or bottling not possible. |

List syntax: `[ "...", "..." ]`. Exact flower display names only.

### 6.5 Dry-run: `can` before any action

`can` prefixes **any action statement** and returns whether that exact line would succeed **right now**, without mutating world state (no path start, no craft start, no item move).

Forms:

- Standalone is not used — always in conditions: `if can …` / `while can …` / `wait until can … or N`
- Syntax: `can` + the same tokens as the action line (including args and `@` vars)

Examples:

| Condition | True when… |
|-----------|------------|
| `can craft "Bronze bar"` | At station, recipe known, mats + skill OK |
| `can mine` | Block target set, in gather range, tool/skill OK, node still there |
| `can go` / `can go @furnace` | Destination set/resolvable, **≤ 2 chunks**, path exists |
| `can bank deposit "Tin ore" 20` | At bank, at least 1 Tin ore movable (qty overflow rules still apply) |
| `can buy "Feather" 10` | Shop mob targeted, in range, stock + coins OK |
| `can cast "Spark" on mob` | Spell known, valid target, not on CD, in approach range or pathable within 2 chunks |
| `can brew "Lesser health tonic"` | Matching recipe paper in bag, at cauldron, mats OK |
| `can find block "Tin ore"` | Exact name exists in the visible **3×3** chunk window (and reachable if `find` requires it) |
| `can cauldron bottle` | Per-player brew ready to bottle + empty bottle |

**Not** actions (no `can`): pure control (`label`, `goto`, `if`, `end`, `for`, `while`, `wait`, `stop`, `set`, `run on`/`off`). `find` **is** an action for `can find block "Tin ore"` (true if such a find would succeed).

Implementation: share the same validation path as the real command; skip the mutate/apply step.

### 6.6 Combat & shops

| Statement | Meaning |
|-----------|---------|
| `attack` | Attack the targeted mob (player Attack intent). Uses the equipped weapon’s mode (**melee** or **ranged** bow + offhand arrows). Does **not** wait for the kill by itself — use `wait until target dead or 60` (§6.13). |
| `stop attack` | Cancel the current attack engage (player cancel-attack). |
| `buy "Feather" 10` | Buy quantity from targeted shop mob. Fails if no shop, not in range, can’t afford, or not stocked. |
| `sell "Soft leather" 5` | Sell quantity to targeted shop mob (if it buys). |

**Follow** is intentionally **not** supported.

### 6.7 Inventory, gear & vitals

| Statement | Meaning |
|-----------|---------|
| `equip "Bronze pickaxe"` | Equip a matching item from the bag into its proper slot. Fails if missing or not equippable. |
| `unequip weapon` | Clear that equipment **slot** into the bag. Slots: `head`, `chest`, `legs`, `boots`, `weapon`, `offhand` (same as game). **Fails if the bag has no free space.** |
| `drink "Lesser health tonic"` | Drink a matching consumable from the bag. |
| `eat "Apple"` | Eat a matching food from the bag. |
| `drop "Tin ore" 5` | Drop quantity from the bag onto the ground. |
| `read "Spark spellbook"` | Read a spellbook from the bag to learn its spell (same as player). Fails if missing, already known, or requirements not met. |
| `if health below 30` … | See control flow. |
| `if stamina below 5` … | See control flow. |

### 6.8 Range checks & queries

| Statement | Meaning |
|-----------|---------|
| `if in range block "Furnace"` | True if a matching block exists in the **visible 3×3** chunk window (same as `find`) and is within interaction/path rules. |
| `if in range mob "Deer"` | True if a matching living mob is within **15 tiles** Chebyshev **and** inside the visible 3×3 chunk window. |
| `if in range ground "Bones"` | True if a matching ground item is within **15 tiles** **and** inside the visible 3×3 chunk window. |
| `if in range item "Bronze bar"` | True if the bag contains that item (quantity ≥ 1). |
| `if bag has "Tin ore" at least 10` | Bag quantity check. |
| `if bag has "Tin ore" below 10` | Bag quantity check. |
| `if target health below 20` | Targeted **mob** current HP below N. Fails the condition (false) if no mob target; does not hard-error. |
| `if target dead` | Targeted mob is gone or at 0 HP. |

### 6.9 Bank, cheques, market, social economy

Requires being at / having path-interacted with the right block where the game requires it (bank counter, bounty office, marketplace).

| Statement | Meaning |
|-----------|---------|
| `bank deposit "Tin ore" 20` | Move quantity from bag → vault. |
| `bank withdraw "Tin ore" 20` | Move quantity from vault → bag. |
| `write cheque "Tin ore" 50` | Write a cheque reserving that item+qty from the **bank (vault)**. Fails if the vault lacks enough. |
| `redeem cheque` | Redeem a written cheque from the bag at a bank (goods → vault), same as player. |
| `market sell "Tin ore" 10 for 8` | Place sell order (qty, min unit price). Escrows goods + listing fee like the UI. |
| `market buy "Tin ore" 10 for 12` | Place buy order (qty, max unit price). Escrows coins like the UI. |
| `market cancel sell` / `market cancel buy` | Cancel the character’s open order of that side (or nearest matching — prefer cancelling by item name if multiple: `market cancel sell "Tin ore"`). |
| `raise bounty on "Ada Worker" 100` | Raise bounty (near bounty office, pays from bag). |
| `send pigeon to bank` | Courier cargo to own bank (same rules as UI). |
| `send pigeon to "Ada Worker"` | Courier to that character; payload prefers a written letter, else a cheque (§13). |
| `write letter "..."` | Write body onto a **blank letter** in the bag (fails if none); does not send. |
| `say "hello"` | Local chat say. |

### 6.10 Spells

| Statement | Meaning |
|-----------|---------|
| `cast "Light"` | Cast on the targeted **block** tile (tile-target spells). Approaches into range if needed (same as player cast). **Blocks** until cast attempt resolves; **fizzle is not an error** (line completes). Approach still obeys the **2-chunk** `go` limit. |
| `cast "Spark" on mob` | Cast entity-target spell on the mob target. |
| `cast "Light" on block` | Explicit tile target = targeted block’s tile. |

Fails if unknown spell, not learned, on cooldown, out of range with no path, or wrong target kind.

### 6.11 Labels & jumps

| Statement | Meaning |
|-----------|---------|
| `label camp` | Declare label `camp`. |
| `goto camp` | Jump to that label. |

Forward and backward jumps allowed. Jumping into/out of loops is **disallowed** (error if attempted).

### 6.12 Control flow

```text
if health below 30
  goto heal
end

if stamina below 5
  run off
end

if can craft "Bronze bar"
  craft "Bronze bar"
end

if can go @furnace
  go @furnace
end

if in range item "Bronze pickaxe"
  equip "Bronze pickaxe"
end

for 10
  find block "Tin ore"
  go block
  mine
end

while in range mob "Rat"
  find mob "Rat"
  go mob
  attack
  wait until target dead or 60
end
```

Rules:

- Blocks end with `end`.
- `if` body runs when the condition is true; no `else` (use a second `if` / `goto`).
- `for N` — repeat body **N** times (N ≥ 1, max **1000**).
- `while <condition>` — repeat while condition true; **max 1000** iterations per `while` then error (`while — Too many repeats.`).
- Conditions:  
  `health below N` · `stamina below N` · `can <action…>` (§6.5) · `in range block|mob|ground|item "..."` · `bag has "..." at least|below N` · `target health below N` · `target dead`

### 6.13 Waiting (`wait` / `wait until`)

| Statement | Meaning |
|-----------|---------|
| `wait 2` | Pause **2 seconds** (server time). Max **60** per wait. |
| `wait until arrived or 30` | Block until the current path finishes (usually redundant after `go`, which already waits). |
| `wait until gathered or 120` | Block until the active mine/chop/harvest completes. |
| `wait until crafted or 120` | Block until the active station craft / `brew` / `cauldron bottle` completes. |
| `wait until target dead or 60` | Block until the mob target is dead or despawned. Fails if no mob target. |
| `wait until health at least 50 or 120` | Block until own HP ≥ N. |
| `wait until stamina at least 5 or 60` | Block until stamina ≥ N. |
| `wait until in range item "Bronze bar" or 60` | Block until bag has that item. |
| `wait until in range mob "Deer" or 30` | Block until such a mob is in range. |
| `wait until bag has "Tin ore" at least 10 or 300` | Block until quantity met. |
| `wait until can craft "Bronze bar" or 60` | Block until that dry-run would succeed. |
| `wait until can go @furnace or 60` | Block until the destination is ≤ 2 chunks and pathable (e.g. after walking a midpoint waypoint). |

**Principle:** every boolean condition usable in `if` / `while` is also valid after `wait until`. Extend this set whenever new conditions ship. `can <action>` is valid anywhere a condition is.

**Timeout is mandatory:** every `wait until` must end with `or <seconds>` (1–300). Bare `wait until …` without `or N` is a **parse error**. On timeout → script error (`wait until — Timed out.`).

`go` / gather / `craft` / `brew` already **block** like a built-in wait for their own completion (they have natural end conditions; no separate `or N` on those verbs).

### 6.14 Utility

| Statement | Meaning |
|-----------|---------|
| `stop` | End the script successfully (no error letter). |

---

## 7. Death while a script is running

If the character **dies** for any reason while a script is active (online, AFK, or offline):

1. **Stop** the script immediately (not an “error letter” unless death was caused mid-op failure — death itself is a clean stop).
2. Cancel any in-progress station/cauldron UI state for that player; **bag contents for reserved station mats are unchanged** (§6.4 inventory hard rule).
3. **Fully log the instance out** of the world (despawn entity, persist dead flag / position as normal death logout).
4. When the player next connects, they see the normal **respawn** screen — no auto-respawn from scripts.

There is **no** `respawn` script command.

---

## 8. Example scripts

### 8.1 Tin loop with panic flee

```text
# Tin loop with panic flee
label start
equip "Bronze pickaxe"
run on

for 20
  if health below 25
    goto flee
  end
  find block "Tin ore"
  go block
  mine
  if in range ground "Tin ore"
    find ground "Tin ore"
    go ground
    take
  end
end
stop

label flee
run on
drink "Lesser health tonic"
stop attack
find block "Bank"
go block
bank deposit "Tin ore" 999
stop
```

### 8.2 Bronze mining bot (equal tin/copper → smelt → bank)

Furnace is ~4 chunks from the mine (beyond the 2-chunk `go` limit), so the author pre-saves waypoints by standing on tiles and using `set @… here`, or by writing coordinates. Bank is near the furnace here; bronze goes to the vault via `bank deposit` (or `send pigeon to bank` if preferred).

Smelting consumes tin and copper in pairs, so the loop mines whichever ore is missing first — stock stays balanced.

```text
# Waypoints (edit coords to your world; mid is ~2 chunks from mine toward furnace)
# Tip: open the script editor and read Position: (x, y) at the bottom while standing on each tile
set @mine (800, 400)
set @mid (800, 432)
set @furnace (800, 464)
set @bank (804, 464)

equip "Bronze pickaxe"
run on

label loop
# Equal ores: mine whichever is missing; smelting consumes pairs so stock stays balanced
if bag has "Tin ore" below 1
  goto mine_tin
end
if bag has "Copper ore" below 1
  goto mine_copper
end
goto smelt

label mine_tin
go @mid
go @mine
find block "Tin ore"
if can go block
  go block
  mine
end
if in range ground "Tin ore"
  find ground "Tin ore"
  go ground
  take
end
goto loop

label mine_copper
go @mid
go @mine
find block "Copper ore"
if can go block
  go block
  mine
end
if in range ground "Copper ore"
  find ground "Copper ore"
  go ground
  take
end
goto loop

label smelt
go @mid
go @furnace
find block "Furnace"
go block
while can craft "Bronze bar"
  craft "Bronze bar"
end
go @bank
find block "Bank"
go block
bank deposit "Bronze bar" 999
goto loop
```

---

## 9. Syntax highlighting (editor)

Highlight at least:

| Class | Examples |
|-------|----------|
| Keyword | `find`, `go`, `mine`, `chop`, `harvest`, `craft`, `brew`, `cauldron`, `attack`, `buy`, `sell`, `equip`, `unequip`, `drink`, `eat`, `drop`, `read`, `cast`, `bank`, `market`, `write`, `redeem`, `raise`, `send`, `say`, `label`, `goto`, `if`, `end`, `for`, `while`, `wait`, `stop`, `run`, `take`, `use`, `can`, `set` |
| Subkeyword | `block`, `mob`, `ground`, `item`, `health`, `stamina`, `below`, `at`, `least`, `in`, `range`, `on`, `off`, `until`, `or`, `arrived`, `gathered`, `crafted`, `target`, `dead`, `here`, `deposit`, `withdraw`, `cheque`, `pigeon`, `bounty`, `sell`, `buy`, `cancel`, `insert`, `heat`, `stir`, `cool`, `bottle`, `clear`, `dye` |
| String | `"..."` |
| List | `[ "...", "..." ]` (flower lists for `cauldron dye`) |
| Number | `10`, `30` |
| Comment | `# ...` |
| Label name | after `label` / `goto` |
| Slot name | after `unequip` (`weapon`, `head`, …) |

| Variable | `@furnace`, `@mid` |
| Coord pair | `(5, 18)` or `512 128` after `set @name` |

Invalid lines can be marked with a subtle error underline on Save (optional v1).

---

## 10. Persistence & limits

- Scripts stored per character in state DB (name, source text, flags, updatedAt).
- Soft caps (suggested): **20** scripts / character, **200** lines / script, **4 KB** source.
- Offline script runtime state: program counter, targets, `@` variables, loop stack, `offlineUntil` timestamp — rehydrated on server restart (§18.6).
- Instruction budget: small per simulation tick (at most one **blocking** wait/path/gather/craft at a time; non-blocking lines burst with a low cap).

---

## 11. Authority & safety (implementation notes)

- Interpreter runs only on the server.
- Every gameplay effect goes through existing command handlers.
- No filesystem, network, `eval`, or shared mutable globals across characters.
- Name matching uses the same display names players see in tooltips / shops — **exact**, case-insensitive, never fuzzy.
- Script controller and client controller: only one produces intents at a time; **any manual gameplay intent stops** the script.
- Offline `say` / pigeon / bounty: same validation as players; add rate limits if abused.

---

## 12. Implementation plan (phased)

1. **Data + UI shell** — CRUD scripts, flags, editor with highlighting + **live position readout**, no execution.
2. **Online runner** — interpreter + run bar + stop; `find` / `go` (blocking, **2-chunk** cap) / `set` / `@` vars / `wait` / `wait until` / `label` / `goto` / `stop` / universal `can`.
3. **Gather + gear + vitals** — `mine` / `chop` / `harvest` / `equip` / `unequip` / `drink` / `eat` / `if health|stamina`.
4. **Combat + shops + craft/alchemy** — stations via `craft` (tailor `dye` flag); cauldron via step verbs + recipe-gated `brew` + `cauldron dye [...]`; per-player station state.
5. **Loops + range + bag/target queries**.
6. **Bank, cheques, market, spells, pigeon, chat, bounty, spellbooks**.
7. **AFK auto-start** — 30-minute idle.
8. **Offline logout flow** — modal, entity retention, 1-hour cap, re-login attach, error pigeon, **death → full logout**.

---

## 13. Open choices (resolve during implementation)

Resolved defaults (change only with a good reason):

| Topic | Decision |
|-------|----------|
| `in range mob/ground` radius | **15** tiles Chebyshev |
| AFK timer vs Scripts panel | Opening the panel does **not** reset idle |
| Name matching | **Exact** display name, case-insensitive; never fuzzy. Multiple exact matches → **closest** in the visible **3×3** chunk window |
| `find` / nearest search | Player chunk + 8 neighbours only (`VISIBLE_CHUNK_RADIUS` = 1) — what a real player would see |
| `go` max distance | Destination must be within **2 chunks** or fail `Too far away.` |
| AFK idle duration | **30 minutes** |
| `wait until` timeout | **Required** form: `wait until <cond> or <seconds>` (max 300). Bare `wait until` without `or N` is a **parse error** so offline scripts cannot hang forever |
| `cast` fizzle | **Not** a script error — line completes; use `if` / skill checks if you care |
| Quantity overflow (`bank deposit "Tin ore" 999` with only 5) | Deposit/withdraw/sell/buy **as many as possible up to N**; error only if **zero** moved |
| `redeem cheque` with several cheques | Redeem the **first** written cheque in bag order |
| `market cancel sell "Tin ore"` | Cancel the **oldest** open sell order for that item name |
| `send pigeon to "Name"` | Payload = **one** selected bag item: prefer a written **letter** if present, else a **cheque**, else fail asking for a letter/cheque (`send pigeon — Carry a letter or cheque to send.`) |
| `write letter "..."` | Writes onto a **blank letter** in the bag (fails if none); does not send |
| Editing a script while it runs | Save applies next **Run** only; running copy is a snapshot |
| AFK start while a script already runs | Do **not** start a second script |
| Offline logout while a script already runs online | Offline flag continues **that** run (same PC); do not restart from line 1 |
| Station inventory | Mats **never leave** the bag until craft/brew **succeeds**; death/UI close cannot destroy them |

Still soft:

- Flower **display names** in `cauldron dye` must match item defs exactly (document in editor autocomplete later).

---

## 14. Out of scope

| Area | Reason |
|------|--------|
| **Follow** | Not needed for scripts |
| **Friends** | Social; low AFK value |
| **Barber / hair** | Cosmetics |
| **Inspect / social panel** | Not needed for AFK |
| **Graphics settings** | Client-only |
| **World editor** | Admin |
| **`respawn` command** | Death always full-logout; player uses respawn UI on next login |
| **User-defined functions** | v1 stays line+label+`@` vars only |

Script steps should stay aligned with player UI actions; never add a verb that skips a check the human UI enforces (recipe paper for `brew`, random dye only for tailor, etc.).

### Still fine to add later if play gains new intents

Inheritance claim, blank-cheque get/return — add a matching verb when useful.

When a new player-facing intent ships, add a matching script statement in the same feature commit.

---

## 15. Runtime edge cases (resolved in plan)

### 15.1 Targeting & names

- `find` uses **exact** display names (case-insensitive). Ore nodes, trees, and dyed clothing must match tooltips character-for-character aside from case.
- `find` / `in range` world searches only the **visible 3×3** chunks (current + 8 surrounding). `go` may still path up to **2 chunks**; farther → `Too far away.` Use `@` coordinate waypoints for long trips.
- After `find`, if the world changes (ore depleted, mob died, item picked up) before `go`/`mine` completes → **fail** that op with a clear reason (`mine — Target is gone.`).
- Block vs ground vs bag: verbs decide the namespace (`mine` always uses **block** target; `take` uses **ground**; `in range item` uses bag).
- `@` vars holding targets re-resolve on use; gone → error. Coords always valid geometrically but still need path + 2-chunk proximity at `go` time.

### 15.2 Blocking ops interrupted

- If the player is **shoved**, loses the gather, or combat cancels a path while `go`/`mine`/… is blocking → treat as **script error** for that line (not silent continue).
- `run on` with 0 stamina: gait falls back to walk (same as player); **not** an error.
- Full bag on `take` / gather loot / `unequip` → error for that line.

### 15.3 Combat & waits

- `wait until target dead or 60`: success when target entity is despawned or HP ≤ 0; if the script never had a mob target → immediate error.
- `attack` then `wait until target dead` while the mob flees out of chase range: wait hits **timeout** → error (script must re-`find`).
- Town guards / retaliation killing the character → §7 death logout (clean stop, no Frederick letter).

### 15.4 Stations & cauldron

- `craft` / `brew` / `cauldron *` require adjacency to the targeted station block like the UI.
- Station / cauldron progress is **per player** — never tile-global. Concurrent users at the same block do not share or corrupt each other’s brew/craft.
- Materials in station slots are **never removed from the bag** until a craft/brew **succeeds**; close UI / clear / death / script stop cannot destroy those items (§6.4).
- `brew` with a recipe paper: if **this player’s** cauldron already has leftover steps, **fail** (`brew — Cauldron is busy.`) unless cleared. Prefer: scripts `cauldron clear` before `brew` (clear is safe — bag unchanged).
- `cauldron dye [...]` fails if **this player’s** alchemy brew is mid-potion.
- Unstable potion from wrong manual steps is **success of bottling**, not a script error (player can get unstable too) — only then are reserved mats consumed.

### 15.5 Mode switches

- Disconnect while online script running **without** offline checkbox → stop script + normal logout (entity despawn).
- Disconnect **with** offline already running → keep offline run.
- Re-login onto offline script: restore run bar; PC unchanged.
- Server restart: persist PC, targets (by tile + name + entityId if still valid), wait deadline, `offlineUntil`; invalid target after rehydrate → error letter.

### 15.6 Safety / abuse

- Rate-limit offline `say` and pigeon sends (e.g. max 1 say / 10s, max 3 pigeons / hour) — same spirit as anti-spam, documented in implementation.
- Cap concurrent **offline-scripting** characters per server (suggested **50** initially) to protect ChunkLoader cost; further logouts with offline checked fail with toast if at cap.

---

## 16. Known weaknesses & open problems

Issues that remain hard or only partly specified — fix in implementation or revisit the design:

1. **Display-name fragility** — renames in item/block defs break scripts (exact match). *Mitigation:* editor autocomplete from live defs; optional stable ids later.
2. **Manual waypoints** — long trips need author-maintained `@` coords; wrong midpoints → `Too far away.` *Mitigation:* document hop spacing (≤ 2 chunks); later optional `go via @a @b @c` sugar.
3. **Equal ore without bag-vs-bag compare** — scripts approximate balance with thresholds (`below 5`), not true `Tin < Copper`. *Mitigation:* add `if bag "Tin ore" below bag "Copper ore"` later if needed.
4. **Recipe paper ↔ `brew "Name"` matching** — papers may store potion keys/hashes, not display strings. *Must* define a canonical match (displayName on the paper instance). If ambiguous, fail.
5. **Pigeon cargo model** — real UI may allow more than letter/cheque; script support may lag the UI until cargo selection is unified.
6. **Marketplace disambiguation** — multiple sell orders same item at different prices; “oldest” may surprise players. Acceptable v1; later allow `market cancel sell "Tin ore" for 8`.
7. **Tailor random dye** — non-deterministic scripts (harder to test). Intentional per design; document it.
8. **`goto` vs loops** — statically forbidding jump into/`out of` `for`/`while` needs a clear compiler pass; easy to get wrong with nested `if`. *Must* implement a block-stack checker at save/run.
9. **Offline ChunkLoader cost** — many offline miners keep regions hot; the concurrency cap helps but economy/world load can still spike. Needs live metrics after ship.
10. **Partial command surface** — any new play feature without a script verb creates parity drift (§14 reminder). Process discipline, not a technical guarantee.
11. **Universal `can` cost** — dry-running every action (esp. pathfinding) each `while can` tick must be cheap or cached. *Must* budget path checks.
12. **AFK false positives** — idle 30 minutes in a menu reading skills still starts AFK script. Acceptable; players can Stop or unmark AFK.

---

## 17. Feasibility & stability (assessment)

**Feasibility: high for a phased build; medium-high for “full parity.”**  
The architecture already assumes a script controller emitting the same intents (§18). Online runner + gather/`go`/`wait until` is straightforward. Offline + ChunkLoader + re-login + restart rehydrate is the hard part but is sketched in the design doc. Full verb parity (market, cauldron, pigeons) is mostly glue once the interpreter and blocking scheduler exist — estimate **several milestones**, not one dump.

**Stability in use: good if timeouts and fail-loud rules hold; fragile if name-matching and waits are sloppy.**

| Area | Outlook |
|------|---------|
| Online scripts | Stable: same validation as players; run bar + Stop; manual intent cancels script |
| AFK auto-start | Stable with clear Stop; occasional surprise starts (§16.12) |
| Offline hour | Stable for gameplay; **ops risk** on region load — needs caps + metrics |
| Long `wait until` | Stable **only** with mandatory `or N` timeouts |
| Economy bots | Will exist (shops/market/gather); rate limits and normal game costs are the balance knobs |
| Player trust | Death→logout and Frederick letters are clear; station mats cannot be lost on death/UI close (§6.4) |

**Bottom line:** the concept is **implementable and can be sturdy** for gather/bank/fight loops. Treat **exact** name matching, **visible-only** `find` (3×3 chunks), the **2-chunk** `go` cap, mandatory wait timeouts, offline concurrency caps, per-player station state, **non-committing station inventory**, and recipe matching as **non-negotiable** for stability. Full “every button in the game” parity is **achievable over phases**, not day one — the plan is strongest when each new UI action ships with its script verb in the same commit.
