# Quirkling specification, version 0.1 (draft)

> Generated by `bun run spec` from `spec/src/*.md` and `spec/data/*.json`. Do not edit.
> The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are to be read as described in RFC 2119.

## Contents

- 1. Scope and conformance (#scope)
  - 1.1 Normative and informative parts (#normative)
  - 1.2 Conformance levels (#levels)
  - 1.3 Versioning (#versioning)
- 2. Units, clock and randomness (#units)
  - 2.1 Units (#unit-table)
  - 2.2 Clock (#clock)
  - 2.3 Timers (#timers)
  - 2.4 Randomness (#rng)
- 3. Config and resolve() (#config)
  - 3.1 Config (#config-file)
  - 3.2 Instance options (#options)
  - 3.3 resolve() (#resolve)
- 4. Geometry (#geometry)
  - 4.1 Body (#body)
  - 4.2 Eyes (#eyes)
  - 4.3 Accessories (#accessories)
- 5. State model (#state)
  - 5.1 State (#state-fields)
  - 5.2 Channels (#channels)
  - 5.3 create() (#create)
- 6. Dynamics (#dynamics)
  - 6.1 step() (#step)
  - 6.2 Springs (#springs)
  - 6.3 Body, eye and accessory targets (#targets)
  - 6.4 Gaze (#gaze)
  - 6.5 Hop (#hop)
  - 6.6 Blink (#blink)
  - 6.7 Shake (#shake)
  - 6.8 Tremble (#tremble)
  - 6.9 Loops (#loops)
- 7. Expressions and layers (#expressions)
  - 7.1 Expression table (#expression-table)
  - 7.2 Layers (#layers)
- 8. Acts (#acts)
  - 8.1 Running an act (#run-act)
  - 8.2 Act table (#act-table)
  - 8.3 Ops (#ops)
  - 8.4 Notes on specific acts (#act-notes)
- 9. Input and interaction (#input)
  - 9.1 Events (#events)
  - 9.2 Activity (#activity)
  - 9.3 Hover and press (#hover-press)
  - 9.4 Pointer and follow (#pointer)
  - 9.5 Scare (#scare)
  - 9.6 Click (#click)
  - 9.7 Idle, sleep and wake (#idle)
  - 9.8 Other events (#other-events)
- 10. Pose and rendering (#pose)
  - 10.1 pose() (#pose-formulas)
  - 10.2 Pose order (#pose-order)
  - 10.3 SVG reference mapping (#svg)
- 11. Reduced motion (#reduced)
- 12. Accessibility (#a11y)
- 13. Theming (#theming)
- 14. Favicon, app icon and terminal face (#favicon)
  - 14.1 Favicon (#favicon-derivation)
  - 14.2 App icon (informative) (#app-icon)
  - 14.3 Terminal face (#terminal)
- 15. Conformance (#conformance)
  - 15.1 Artefacts (#artefacts)
  - 15.2 Trace format (#trace-format)
  - 15.3 Scenarios (#scenarios)
  - 15.4 Runner protocol (#runner)
  - 15.5 Running the suite (#cli)
  - 15.6 Golden strips (informative) (#strips)
- 99. Changes from the glim.js study (#changes)
  - 99.1 Determinism (#changes-determinism)
  - 99.2 Behaviour (#changes-behaviour)
  - 99.3 Kept on purpose (#changes-kept)
- A. Informative notes (#informative)
  - A.1 Host loop (#host-loop)
  - A.2 Performance (#performance)
  - A.3 Other renderers (#renderers)
  - A.4 Spring sets in platform terms (#spring-mapping)
  - A.5 Porting checklist (#porting)

## 1. Scope and conformance {#scope}

This document specifies **Quirkling**, a small animated mascot: a rounded square body with two eyes. It covers the mascot's geometry, its motion, how it reacts to input and how it is drawn. The goal is that any implementation, in any language, produces the **same motion**: given the same configuration, seed and input events, two conforming implementations produce the same numbers at every tick, within a small tolerance.

The spec describes a deterministic engine:

- `create(config, options) → state` builds the initial state (§5).
- `step(state, events) → state` advances the state by one tick of 1/120 s (§6.1).
- `pose(state) → pose` maps a state to numbers that a renderer draws (§10).

Rendering is a mapping from the pose. The SVG mapping in §10.3 is the reference; other renderers SHOULD match it visually.

### 1.1 Normative and informative parts {#normative}

- Chapters 2–12, 14 and 15 are normative unless a section says otherwise. Chapter 13 (theming) is normative for the role names only.
- The data files `spec/data/constants.json`, `expressions.json`, `acts.json` and `config.json` are normative. Tables in this document are rendered from them; if a table and a data file ever disagree, the data file wins.
- Examples (`example` blocks) are normative test vectors. Their outputs are generated by the reference engine and extracted into `conformance/vectors/examples/`.
- Rationale paragraphs, appendix A and the golden strips (§15.6) are informative.

### 1.2 Conformance levels {#levels}

An implementation declares the levels it supports. Each level includes the ones below it.

| level | name | covers |
|---|---|---|
| L0 | Static | `resolve()` (§3), geometry (§4), favicon (§14) |
| L1 | Expressive | springs, expressions, layers and the timer queue (§2.3, §6.2, §7), with `setExpr` and `setConfig` events only; L1 scenarios turn blinking off, so no PRNG is needed |
| L2 | Acts | every act (§8), hop, blink, shake, tremble, loops, sleep, the PRNG (§2.4) |
| L3 | Interactive | pointer, hover, press, click counting, follow, scare, idle, keyboard (§9) |
| L4 | Reduced motion and accessibility | §11 by traces; §12 by checklist |

An implementation **conforms at level Ln** when it passes every vector and scenario tagged L0…Ln in the conformance suite (§15) and, for L4, meets the checklist in §12.

### 1.3 Versioning {#versioning}

The spec version is `major.minor` (this document: 0.1).

- A **minor** version MAY add optional config keys, events, acts or scenarios. Existing traces MUST NOT change.
- Any change that alters an existing golden trace is a **major** change. (While the major version is 0, a minor bump MAY change traces; the changelog lists every such change.)
- Configs carry the spec version they target (§3.1). An engine MUST refuse a config whose major version differs from its own.


## 2. Units, clock and randomness {#units}

### 2.1 Units {#unit-table}

| quantity | unit | notes |
|---|---|---|
| length (geometry, pose) | **u** | one hundredth of the mascot's box: the box is 100 × 100 u, origin top-left, y down |
| angle | degrees | positive = clockwise on screen (SVG convention) |
| time (engine) | **tick** | 1 tick = 1/120 s |
| time (data files) | ms | converted to ticks with `ticks()` (§2.2) |
| pointer position | host px | relative to the centre of the host, y down (§9.1) |
| pointer velocity | px/ms | |

All arithmetic uses IEEE 754 binary64 (double precision). Implementations MUST NOT use single-precision floats for state.

### 2.2 Clock {#clock}

The engine has one clock: the integer tick counter `tick`, starting at 0 when the state is created. There is no wall clock in the engine. A host maps real time to ticks (appendix A.1).

Two conversions are used everywhere:

```
ticks(ms) = ⌈3·ms / 25⌉        for integer ms ≥ 0; in integers: (3·ms + 24) div 25
msOf(n)   = n·25 / 3           elapsed ms for n ticks, a double, computed as (n·25)/3
```

`ticks(ms)` is the number of ticks until the first tick whose time is ≥ ms. Every ms value in the data files is an integer.

```example id=ticks-001 kind=ticks features=[clock]
{"ms": [0, 8, 9, 90, 420, 1100, 2200, 4000]}
---
{"ticks":[0,1,2,11,51,132,264,480]}
```

### 2.3 Timers {#timers}

All delayed work goes through **one timer queue** in the state. A timer is `{due, seq, group, op}`:

- `due` is a tick: `state.tick + ticks(delay_ms)` at the moment it is scheduled.
- `seq` is a counter in the state, incremented on every schedule. It breaks ties.
- `group` is a **cancel group** (table below). Cancelling a group removes every pending timer in it.
- `op` is the operation to run (§8.3).

| group | holds | cancelled by |
|---|---|---|
| `seq` | act timelines (§8), hop launches, the release hop, the wake hop | `cancelSeq` (§8.3), the annoyed path of a click (§9.6) |
| `layer:<name>` | the expiry of layer `<name>` (§7.2) | setting layer `<name>` again |
| `blink` | the blink schedule and the second blink of a double blink | `setConfig` turning blinking off |
| `hover` | the hover → happy switch | `leave`, a click while hovering, `enter` (restarts it) |
| `press` | the long-press detector | `up`, `cancel`, `leave`, `down` (restarts it) |
| `glint` | the end of a twinkle | a new twinkle |

**Firing (step phase 2).** Repeat: among timers with `due ≤ tick`, take the one with the smallest `(due, seq)`, remove it from the queue, run its op. Stop when no timer is due. A timer scheduled while firing with a delay of 0 ticks fires in the same pass. Implementations MUST fire timers in exactly this order.

### 2.4 Randomness {#rng}

The only source of randomness is **xorshift32** with shifts (13, 17, 5) on an unsigned 32-bit state:

```
x = x XOR (x << 13)   (mod 2^32)
x = x XOR (x >> 17)   (logical shift)
x = x XOR (x << 5)    (mod 2^32)
draw = x / 2^32       (a double in [0, 1))
```

The state is seeded from the instance option `seed`, an integer in 0…2^32 − 1 (default 1; other values are invalid). Seed 0 is not a valid xorshift state and MUST be replaced by 1831565813.

Draws happen **only** at these points, in this order of occurrence:

1. At `create()`, if blinking is on: one draw for the first blink delay (§6.6).
2. Each time a blink timer fires and its guard passes: one draw for "double blink?", then one draw for the next delay. If the guard fails: only the delay draw.
3. When `setConfig` turns blinking on: one draw for the next delay.

An implementation MUST NOT draw at any other time.

```example id=rng-001 kind=rng features=[rng]
{"seed": 1, "draws": 4}
---
{"u32":[270369,67634689,2647435461,307599695],"u":[0.000063,0.015747,0.616404,0.071619]}
```

*Rationale (informative):* xorshift32 needs only 32-bit shifts and xor, so it runs unchanged in languages without 64-bit integers or `imul`.


## 3. Config and resolve() {#config}

### 3.1 Config {#config-file}

A config is a **sparse** JSON object (file name `quirkling.json`). Every key is optional; a missing key takes its default. Schema: `spec/schema/config.v1.json`.

| key | default | range / values |
|---|---|---|
| `spec` | 0.1 |  |
| `name` | Quirkling |  |
| `body.roundness` | 0.5 | 0 … 1 |
| `body.aspect` | 0 | -1 … 1 |
| `body.wobble` | 0 | 0 … 1 |
| `eyes.shape` | tall | tall, dot, vpill, hpill, ring |
| `eyes.size` | 0.19 | 0.06 … 0.3 |
| `eyes.spacing` | 0.44 | 0.18 … 0.8 |
| `eyes.height` | 0.43 | 0.2 … 0.75 |
| `eyes.pupils` | false |  |
| `color.body` | #2256F2 |  |
| `color.eye` | #FFFFFF |  |
| `color.glint` | #FFB800 |  |
| `color.accent` | #8D8A84 |  |
| `extras.glint` | false |  |
| `behavior.follow` | true |  |
| `behavior.blink` | true |  |
| `behavior.scare` | true |  |
| `behavior.sleepy` | false |  |
| `behavior.idleMs` | 20000 | 1000 … 3600000 |

- `spec`: the spec version the config targets, `"major.minor"`.
- `name`: used in the accessible label (§12) and export file names.
- `behavior`: switches for follow (§9.4), blinking (§6.6), scare (§9.5) and idle sleep (§9.7). *v0.1 note: this group is a stand-in for the `personality` group planned for spec 0.2.*

### 3.2 Instance options {#options}

These belong to one mascot instance, not to the shared config:

| option | default | meaning |
|---|---|---|
| `seed` | 1 | PRNG seed (§2.4) |
| `expr` | `"neutral"` | base expression (§7.2); an unknown name means `"neutral"` |
| `loop` | null | start in a loop: `"loading"` or `"thinking"` (§6.9) |
| `interactive` | true | accept `enter`, `leave`, `down`, `up` and `cancel` events and key clicks (§9.1, §9.6) |
| `peek` | false | duck less when scared (the mascot peeks from an edge, §8.4) |
| `reducedMotion` | false | §11 |
| `hostSize` | 100 | the rendered width of the 100 u box, in host px (§9.1) |

### 3.3 resolve() {#resolve}

`resolve(config) → {resolved, adjusted, warnings, errors}` turns a sparse config into a **ResolvedConfig**: fully populated, with every value valid. It never throws. Every formula in this spec reads the ResolvedConfig only. `create` MUST refuse a config whose `errors` is not empty (§5.3); `setConfig` ignores such a change (§9.8).

JSON types here are null, boolean, number, string, array and object; integers and fractions are both number. Each adjustment is `{path, from, to, rule}`: `from` is the value before the rule and `to` the value after it. A path can appear twice (for example "integer", then "range"). Colours are matched case-insensitively and kept verbatim. If `config` itself is not an object, `resolve` adds the error `config must be an object` and resolves `{}`.

1. **Version.** If `spec` is present and is not a string matching `^\d+\.\d+$`, add an error. If its major differs from the engine's, add an error. Errors are reported; the result is still produced.
2. **Start** from the defaults (§3.1).
3. **Overlay** the config. For each top-level key except `$schema` and `spec`, in the order the keys appear in the config:
   - unknown key → warning `unknown key: <key>`, skip;
   - the default is an object but the value isn't → adjustment `{path, from, to: default, rule: "type"}`, skip;
   - otherwise, for each nested key in order: unknown → warning `unknown key: <key>.<sub>`; a different JSON type than the default, or a non-finite number → adjustment with rule `"type"`, keep the default; else take the value.
   - a top-level scalar with the wrong type → adjustment with rule `"type"`.
4. **Integers.** `behavior.idleMs` that is not an integer is rounded (JavaScript `Math.round`: half up) with rule `"integer"`.
5. **Ranges.** Each number in the ranges table is clamped into its range, with rule `"range"`.
6. **Enums.** `eyes.shape` outside its values becomes the default, with rule `"enum"`.
7. **Colours.** A colour that is not `#rgb`, `#rrggbb` or `#rrggbbaa` becomes the default, with rule `"color"`.
8. **Derived values.** `resolved.spec` is the engine's version; `resolved.springs` copies the spring sets from `constants.json` (§6.2).

`adjusted` lists adjustments in the order the steps above produce them: step 3 in config order, then steps 4–7 in the order of the tables (`integers`, `ranges`, `enums` in `config.json`; colours in role order `body, eye, glint, accent`).

```example id=resolve-001 kind=resolve features=[resolve]
{"config": {"body": {"aspect": 3}, "eyes": {"shape": "star", "size": "big"}, "hat": true}}
---
{
  "resolved": {
    "spec": "0.1",
    "name": "Quirkling",
    "body": {"roundness":0.5,"aspect":1,"wobble":0},
    "eyes": {"shape":"tall","size":0.19,"spacing":0.44,"height":0.43,"pupils":false},
    "color": {"body":"#2256F2","eye":"#FFFFFF","glint":"#FFB800","accent":"#8D8A84"},
    "extras": {"glint":false},
    "behavior": {"follow":true,"blink":true,"scare":true,"sleepy":false,"idleMs":20000},
    "springs": {"body":{"k":380,"c":20},"eye":{"k":620,"c":34},"gaze":{"k":200,"c":24},"soft":{"k":140,"c":18}}
  },
  "adjusted": [
    {"path":"eyes.size","from":"big","to":0.19,"rule":"type"},
    {"path":"body.aspect","from":3,"to":1,"rule":"range"},
    {"path":"eyes.shape","from":"star","to":"tall","rule":"enum"}
  ],
  "warnings": ["unknown key: hat"],
  "errors": []
}
```

*v0.1 note:* containment, eye-separation and favicon-legibility clamps, `extends` and presets are planned for spec 0.2. Until then, configs at the edge of the ranges can place the eyes outside the body.


## 4. Geometry {#geometry}

Geometry is a pure function of the ResolvedConfig. Constants come from `constants.json#geometry`.

| constant | value |
|---|---|
| `geometry.base` | 80 |
| `geometry.cx` | 50 |
| `geometry.bottom` | 92 |
| `geometry.clipBottom` | 100 |
| `geometry.aspectK` | 0.17 |
| `geometry.shapeN.at0` | 40 |
| `geometry.shapeN.at05` | 4.6 |
| `geometry.shapeN.at1` | 2.3 |
| `geometry.rectBelow` | 0.01 |
| `geometry.polylineN` | 144 |
| `geometry.wobble.amp` | 0.032 |
| `geometry.wobble.terms` | `[[1,3,1.1],[0.55,5,0.3],[0.35,9,2.2]]` |
| `geometry.eyes.tall.w` | 0.86 |
| `geometry.eyes.tall.h` | 1.15 |
| `geometry.eyes.dot.w` | 1 |
| `geometry.eyes.dot.h` | 1 |
| `geometry.eyes.vpill.w` | 0.72 |
| `geometry.eyes.vpill.h` | 1.5 |
| `geometry.eyes.hpill.w` | 1.55 |
| `geometry.eyes.hpill.h` | 0.62 |
| `geometry.eyes.ring.w` | 1.12 |
| `geometry.eyes.ring.h` | 1.12 |
| `geometry.eyes.ringStroke.min` | 2 |
| `geometry.eyes.ringStroke.k` | 0.27 |
| `geometry.eyes.pupils.size` | 1.35 |
| `geometry.eyes.pupils.pupil` | 0.48 |
| `geometry.eyes.pupils.travel` | 0.2 |
| `geometry.margins.maxX` | 7 |
| `geometry.margins.maxY` | 6 |
| `geometry.margins.padX` | 0.07 |
| `geometry.margins.padY` | 0.08 |
| `geometry.margins.clampPad` | 0.5 |
| `geometry.arc.widthK` | 1.15 |
| `geometry.arc.ehK` | 0.9 |
| `geometry.arc.strokeMin` | 2.4 |
| `geometry.arc.strokeK` | 0.42 |
| `geometry.arc.endY` | 0.2 |
| `geometry.arc.ctrlY` | -0.42 |
| `geometry.glint.r` | 4.4 |
| `geometry.glint.dx` | 2 |
| `geometry.glint.dy` | -2 |
| `geometry.dots.r` | 2.6 |
| `geometry.dots.dx` | -8 |
| `geometry.dots.step` | 7.5 |
| `geometry.dots.dy` | -9 |
| `geometry.dots.rise` | -2 |
| `geometry.dots.spin.dx` | -2 |
| `geometry.dots.spin.dy` | -12 |
| `geometry.dots.spin.radius` | 8 |
| `geometry.z.dx` | -6 |
| `geometry.z.dy` | -2 |
| `geometry.z.driftX` | 8 |
| `geometry.z.driftY` | -16 |
| `geometry.z.scale0` | 0.7 |
| `geometry.z.scaleK` | 0.5 |
| `geometry.z.glyph` | `[[0.4,-7.6],[6.8,-7.6],[0.4,0],[6.8,0]]` |
| `geometry.z.stroke` | 1.9 |

### 4.1 Body {#body}

```
w   = 80 · (1 + 0.17 · aspect)
h   = 80 · (1 − 0.17 · aspect)
cx  = 50                      bottom = 92          top = bottom − h
body centre = (cx, bottom − h/2)
```

The body stands on y = 92. Everything inside the body group is clipped below y = 100 (§10.3), so a body moved down by more than 8 u sinks out of sight.

**Superellipse exponent.** `roundness` (0…1) maps to an exponent n, log-linearly between three anchors:

```
shapeN(s) = exp( ln 40  + (ln 4.6 − ln 40)  · s/0.5 )          if s < 0.5
          = exp( ln 4.6 + (ln 2.3 − ln 4.6) · (s − 0.5)/0.5 )  otherwise
```

```example id=shapen-001 kind=shapeN features=[geometry]
{"s": [0, 0.25, 0.5, 0.75, 1]}
---
{"n":[40,13.56466,4.6,3.252691,2.3]}
```

**Outline.** The body is a closed polygon, never a curve:

- If `roundness ≤ 0.01` and `wobble = 0`: the 4 corners of the w × h rectangle, starting top-left, clockwise.
- Otherwise 144 points. With `e = 2/shapeN(roundness)`, for i = 0…143, `θ = 2π·i/144`:

```
x = sgn(cos θ) · |cos θ|^e · w/2
y = sgn(sin θ) · |sin θ|^e · h/2
if wobble > 0:
  k = 1 + wobble · 0.032 · ( sin(3θ + 1.1) + 0.55·sin(5θ + 0.3) + 0.35·sin(9θ + 2.2) )
  x = x·k ;  y = y·k
point_i = (cx + x, (bottom − h/2) + y)
```

Point 0 is the middle of the right edge. Points go clockwise on screen. `sgn(0) = 0` and `0^e = 0`.

### 4.2 Eyes {#eyes}

```
d = eyes.size · w
(ew, eh) = (kw·d, kh·d)  with (kw, kh) from the eye shape:
    tall (0.86, 1.15)   dot (1, 1)   vpill (0.72, 1.5)   hpill (1.55, 0.62)   ring (1.12, 1.12)
stroke = max(2, 0.27·d)  for ring, else 0
if eyes.pupils: ew = eh = 1.35·d, stroke = 0   (pupils override the shape; the eye is a filled circle)
ex = eyes.spacing · w / 2            half the distance between the eye centres
ey = top + eyes.height · h
eye centres at rest: (cx − ex, ey) and (cx + ex, ey)
```

An eye is a **stadium**: a rect `ew × eh` centred on the eye centre, corner radius `min(ew, eh)/2`. A ring eye (shape `ring` without pupils) is drawn as a stroke: the rect is inset by `stroke/2` on each side, radius `(min(ew, eh) − stroke)/2`, no fill. A pupil is a circle of diameter `0.48·ew`, filled with the body colour (§10.3).

**Gaze margins**, the furthest the eyes travel when looking around:

```
mgx = clamp( w/2 − ex − ew/2 − 0.07·w,                          0, 7 )
mgy = clamp( min(ey − top − eh/2, bottom − ey − eh/2) − 0.08·h,  0, 6 )
```

```example id=geometry-001 kind=geometry features=[geometry]
{"config": {}, "omitBody": true}
---
{
  "cx": 50,
  "bottom": 92,
  "w": 80,
  "h": 80,
  "top": 12,
  "d": 15.2,
  "ew": 13.072,
  "eh": 17.48,
  "stroke": 0,
  "ex": 17.6,
  "ey": 46.4,
  "mgx": 7,
  "mgy": 6,
  "ring": false,
  "pupils": false,
  "eyes": [
    {"x":25.864,"y":37.66,"w":13.072,"h":17.48,"rx":6.536},
    {"x":61.064,"y":37.66,"w":13.072,"h":17.48,"rx":6.536}
  ]
}
```

### 4.3 Accessories {#accessories}

| part | geometry |
|---|---|
| happy arc | quadratic curve `M −aw/2, 0.2·aw  Q 0, −0.42·aw  aw/2, 0.2·aw` with `aw = 1.15 · max(ew, 0.9·eh)`, stroke width `max(2.4, 0.42·min(ew, eh))`, round caps and joins, no fill, in eye-local coordinates |
| glint | circle, r = 4.4, centre `(cx + w/2 + 2, top − 2)` |
| loop dots | 3 circles, r = 2.6. Row (thinking, rest): centres `(cx + w/2 − 8 + 7.5·i, top − 9 − 2·i)`, i = 0, 1, 2. Spinner (loading): on the circle of radius 8 about `(cx + w/2 − 2, top − 12)`. The pose places them (§10.1). |
| z | the polyline `(0.4, −7.6) → (6.8, −7.6) → (0.4, 0) → (6.8, 0)`, stroke 1.9, round caps and joins, origin at its baseline-left; anchored at `(cx + w/2 − 6, top − 2)` |

The z is a path, not text, so it doesn't depend on fonts.


## 5. State model {#state}

### 5.1 State {#state-fields}

A state holds exactly the following. Implementations MAY store it differently but MUST behave as if it held these values.

| field | type | initial | meaning |
|---|---|---|---|
| `tick` | integer | 0 | the clock (§2.2) |
| `rng` | u32 | from `seed` | PRNG state (§2.4) |
| `sparse` | sparse config | the `config` argument | the config as given, merged by `setConfig` (§9.8) |
| `cfg` | ResolvedConfig | `resolve(config)` | §3 |
| `G` | geometry | `geometry(cfg)` | §4 |
| `interactive`, `peek`, `reduced`, `hostSize` | | options | §3.2 |
| `ch` | 25 channels | at rest (§5.3) | springs `{x, v, t}` (§5.2) |
| `layers` | map name → expression | `{base: expr}` | §7.2 |
| `act` | map key → number | empty | body pose overrides set by acts, keys `x y sx sy r` (§6.3) |
| `gazeOverride` | (x, y) or null | null | set by acts (§6.4) |
| `air` | `{vy, v0}` or null | null | hop ballistics (§6.5) |
| `jy` | number | 0 | hop height offset, u, negative = up |
| `shake` | `{amp, t0, ms}` or null | null | §6.7 |
| `tremble` | `{t0, until}` or null | null | §6.8 |
| `blinkT0` | tick or −1 | −1 | start of the current blink (§6.6) |
| `sleeping`, `sleepT0` | bool, tick | false, 0 | §9.7 |
| `loop`, `loopT0` | name or null, tick | null, 0 | §6.9 |
| `hovering`, `pressed`, `squeezed`, `suppressClick` | bool | false | §9 |
| `clicks` | list of ticks | empty | §9.6 |
| `glintOn` | bool | false | a twinkle is showing the glint (§8.3) |
| `scareCD` | tick | 0 | scare cooldown end (§9.5) |
| `lastAct` | tick | 0 | last activity (§9.7) |
| `pointer` | `{has, x, y, vx, vy, lastTick, fx, fy, prevD}` | `has = false`, `prevD = 10^9`, rest 0 | §9.1 |
| `timers`, `seq` | queue, integer | empty, 0 | §2.3 |

### 5.2 Channels {#channels}

A channel is a damped spring `{x, v, t}`: position, velocity, target. There are 25, always processed in this order:

| # | channel | set | rest value |
|---|---|---|---|
| 0 | `x` | body | 0 |
| 1 | `y` | body | 0 |
| 2 | `sx` | body | 1 |
| 3 | `sy` | body | 1 |
| 4 | `r` | body | 0 |
| 5 | `gx` | gaze | 0 |
| 6 | `gy` | gaze | 0 |
| 7 | `gs` | eye | 1 |
| 8 | `go` | soft | 0 |
| 9 | `do` | soft | 0 |
| 10 | `ds` | soft | 0 |
| 11 | `Lsx` | eye | 1 |
| 12 | `Lsy` | eye | 1 |
| 13 | `Lr` | eye | 0 |
| 14 | `Ldx` | eye | 0 |
| 15 | `Ldy` | eye | 0 |
| 16 | `Lhap` | eye | 0 |
| 17 | `Lsc` | eye | 1 |
| 18 | `Rsx` | eye | 1 |
| 19 | `Rsy` | eye | 1 |
| 20 | `Rr` | eye | 0 |
| 21 | `Rdx` | eye | 0 |
| 22 | `Rdy` | eye | 0 |
| 23 | `Rhap` | eye | 0 |
| 24 | `Rsc` | eye | 1 |

`gs` is the glint scale and `go` the glint opacity; `do` is the loop-dots opacity and `ds` blends them from the thinking row (0) to the loading spinner (1). The eye channels are per eye: scale x/y (`sx sy`), tilt `r`, offset `dx dy`, happy squint `hap` and overall scale `sc`.

### 5.3 create() {#create}

`create(config, options)` fails (throws, or the platform's equivalent) if `resolve(config).errors` is not empty. Otherwise:

1. Build the state as in §5.1, every channel `{x: rest, v: 0, t: rest}`. If `options.expr` is a known expression it is the base layer, else `"neutral"`.
2. If `cfg.behavior.blink`: schedule the first blink (§6.6), which draws once.
3. If `options.loop` is `"loading"` or `"thinking"`: start that loop (§6.9) at tick 0.
4. Compute all targets exactly as step phase 5 does (§6.3, §6.4), with `now = 0`.
5. Snap: every channel `x = t, v = 0`.

So a mascot created with `expr: "lookDown"` starts already looking down, with no motion.


## 6. Dynamics {#dynamics}

### 6.1 step() {#step}

`step(state, events)` advances one tick. Let `now = state.tick` at the start. It MUST do exactly this, in this order:

1. **Input.** Apply each event in `events`, in order (§9).
2. **Timers.** Fire due timers (§2.3).
3. **Idle.** Check idle sleep (§9.7).
4. **Expiry.** If `blinkT0 ≥ 0` and `msOf(now − blinkT0) ≥ 200`: `blinkT0 = −1`. If `shake` and `msOf(now − shake.t0) ≥ shake.ms`: `shake = null`. If `tremble` and `now ≥ tremble.until`: `tremble = null`.
5. **Targets.** Set every channel target (§6.3, §6.4).
6. **Hop.** Advance the hop ballistics (§6.5).
7. **Springs.** For each channel in channel order: integrate it and apply its rest snap (§6.2), or, if `reduced`, set `x = t, v = 0`.
8. `tick = now + 1`.

The pose (§10) is read after a step, at time `state.tick`. Events stamped with tick n are applied by the step that starts at tick n.

Expiry (phase 4) only tidies state up; the pose formulas already give the finished values at those times.

### 6.2 Springs {#springs}

Every channel is a damped spring with unit mass. The stiffness `k` and damping `c` come from the channel's set (`resolved.springs`):

| set | k | c | ζ = c/(2√k) | response 2π/√k (s) | channels |
|---|---|---|---|---|---|
| body | 380 | 20 | 0.513 | 0.322 | `x` `y` `sx` `sy` `r` |
| eye | 620 | 34 | 0.683 | 0.252 | `gs` `Lsx` `Lsy` `Lr` `Ldx` `Ldy` `Lhap` `Lsc` `Rsx` `Rsy` `Rr` `Rdx` `Rdy` `Rhap` `Rsc` |
| gaze | 200 | 24 | 0.849 | 0.444 | `gx` `gy` |
| soft | 140 | 18 | 0.761 | 0.531 | `go` `do` `ds` |

Rest snapping uses `restEpsilon = 0.002` for every channel, whatever its unit.

**Integration.** With `h = 1.0/120.0` (the binary64 value), for each channel in channel order (§5.2), semi-implicit Euler, exactly:

```
v = v + (−k·(x − t) − c·v) · h
x = x + v · h
if |v| < 0.002 and |x − t| < 0.002:  x = t ;  v = 0
```

Implementations MUST NOT substitute a platform spring (SwiftUI `spring`, Flutter `SpringSimulation`, Framer Motion) or a closed-form solution. Their transients differ and fail the traces.

**Retargeting** changes only `t`; it never changes `x` or `v`. **Impulses** (hop, landing, release, twinkle) add directly to `v` or set `x` and `v`, as stated where they occur.

**Reduced motion.** While `reduced` is true, phase 7 instead sets `x = t, v = 0` for every channel (§11).

```example id=springs-001 kind=springs features=[springs]
{"set": "body", "x": 0, "v": 0, "t": 1, "steps": 120, "sample": [1, 2, 12, 24, 60, 90, 120]}
---
{
  "rows": [
    {"tick":1,"x":0.026389,"v":3.166667},
    {"tick":2,"x":0.074072,"v":5.721991},
    {"tick":12,"x":0.873237,"v":8.022354},
    {"tick":24,"x":1.125068,"v":-0.817083},
    {"tick":60,"x":1.001278,"v":0.073776},
    {"tick":90,"x":1,"v":0},
    {"tick":120,"x":1,"v":0}
  ]
}
```

### 6.3 Body, eye and accessory targets {#targets}

Phase 5, part 1. Let `E = expressions[current()]` (§7.1, §7.2).

- **Eyes.** For each eye s ∈ {L, R} and each key k of `sx sy r dx dy hap sc`: `ch[s+k].t = E[s][k]` if present, else the eye rest value (§7.1).
- **Body.** Build a map `b`:
  - if `reduced`: `b = {x: 0, y: 0, sx: 1, sy: 1, r: 0}`;
  - else `b` = the body rest values, overlaid with `E.body`, overlaid with `act` (act wins).
  - **Breathing.** If `sleeping` and not `reduced`: with `w = sin(2π · msOf(now − sleepT0) / 3400)`, set `b.sy = 1 + 0.018·w` and `b.sx = 1 − 0.01·w` (replacing the values above).
  - Set `ch.x.t, ch.y.t, ch.sx.t, ch.sy.t, ch.r.t` from `b`.
- **Accessories.** `ch.gs.t = 1`. `ch.go.t = 1` if `cfg.extras.glint` or `glintOn`, else 0. `ch.do.t = 1` if `loop` is not null, else 0. `ch.ds.t = 1` if `loop = "loading"`, 0 if `loop = "thinking"`; with no loop `ch.ds.t` keeps its value.

### 6.4 Gaze {#gaze}

Phase 5, part 2. Let `lm = msOf(now − loopT0)`.

1. **Loop gaze `lg`.**
   - `loop = "loading"`: if `reduced`, `lg = null`; else with `a = 2π · lm / 1500`, `lg = (0.9·cos a, 0.8·sin a)`.
   - `loop = "thinking"`: `lg = (0.75 + (reduced ? 0 : 0.25·sin(lm / 700)), −0.9)`.
   - otherwise `lg = null`.
2. **Expression gaze `eg`** = `(E.gaze.x, E.gaze.y)` if `E` has a gaze (missing components are 0), else null.
3. `g` = the first of `gazeOverride`, `lg`, `eg` that is not null. A gaze of (0, 0) is not null.
4. `follow = cfg.behavior.follow and not reduced and pointer.has`.
5. Target direction `(tx, ty)`:
   - if `g` is not null: `mix = 0.25` if `follow` and `gazeOverride` is null and `lg` is null, else 0; `(tx, ty) = (g.x + mix·pointer.fx, g.y + mix·pointer.fy)`;
   - else if `follow`: `(tx, ty) = (pointer.fx, pointer.fy)`;
   - else `(0, 0)`.
6. `ch.gx.t = clamp(tx, −1, 1) · G.mgx`, `ch.gy.t = clamp(ty, −1, 1) · G.mgy`.

`pointer.fx` and `pointer.fy` are computed when pointer events arrive (§9.4).

### 6.5 Hop {#hop}

| constant | value |
|---|---|
| `hop.gravity` | 2600 |
| `hop.apex` | 22 |
| `hop.windupMs` | 90 |
| `hop.squat.sy` | 0.86 |
| `hop.squat.sx` | 1.09 |
| `hop.launchImpulse.sy` | 4 |
| `hop.launchImpulse.sx` | -3 |
| `hop.stretch.sy` | 0.1 |
| `hop.stretch.sx` | -0.07 |
| `hop.landingImpulse.sy` | -5.5 |
| `hop.landingImpulse.sx` | 4 |

**hop(power)** (an op, §8.3):

1. If `reduced` or `air` is not null: do nothing.
2. Wind-up: `act.sy = 0.86`, `act.sx = 1.09` (other act keys stay).
3. Schedule `hopLaunch(power)` in group `seq` after 90 ms.

**hopLaunch(power):**

1. Remove `sx` and `sy` from `act`.
2. If `reduced` or `air` is not null: stop here.
3. `v0 = sqrt(2 · 2600 · 22 · power)`; `air = {vy: −v0, v0}`; `ch.sy.v += 4`; `ch.sx.v += −3`.

**Ballistics** (step phase 6), with `h = 1/120`. If `air` is null, skip. If `reduced`: `air = null, jy = 0`, stop. Otherwise:

```
air.vy = air.vy + 2600·h
jy     = jy + air.vy·h
s      = min(1, |air.vy| / air.v0)
ch.sy.t = 1 + 0.1·s ;  ch.sx.t = 1 − 0.07·s           (stretch while airborne)
if jy ≥ 0 and air.vy > 0:                             (landing)
    jy = 0 ;  air = null
    ch.sy.t = b.sy ;  ch.sx.t = b.sx                  (b from §6.3)
    ch.sy.v += −5.5·s ;  ch.sx.v += 4·s
```

The nominal apex is `22·power` u. Because of the discrete step it comes out about `v0·h/2` lower (about 20.6 u at power 1).

### 6.6 Blink {#blink}

| constant | value |
|---|---|
| `blink.closeMs` | 70 |
| `blink.holdMs` | 25 |
| `blink.openMs` | 105 |
| `blink.closed` | 0.06 |
| `blink.intervalMs` | 2200 |
| `blink.jitterMs` | 4000 |
| `blink.doubleChance` | 0.2 |
| `blink.doubleDelayMs` | 260 |

**Schedule.** `scheduleBlink`: `u = draw()`; schedule `blinkTick` in group `blink` after `ticks(2200) + floor(u · ticks(4000))` ticks. (This is the only timer whose delay is given in ticks rather than ms.)

**blinkTick:** if not `squeezed` and `current() ≠ "happy"`: `double = draw() < 0.2`, then `blink(double)`. In all cases, `scheduleBlink` afterwards.

**blink(double):** if `reduced` or `sleeping`, do nothing. Else `blinkT0 = now`; if `double`, schedule `blinkDouble` in group `blink` after 260 ms.

**blinkDouble:** if not `reduced` and not `sleeping`: `blinkT0 = now`.

**Blink factor** for `t = msOf(tick − blinkT0)` (1 = open; 1 when `blinkT0 = −1`):

```
t < 0          1
t < 70         1 − 0.94·u²               u = t/70
t < 95         0.06
t < 200        0.06 + 0.94·(1 − (1 − u)²)  u = (t − 95)/105
otherwise      1
```

```example id=blink-001 kind=blink features=[blink]
{"ms": [0, 35, 70, 94, 95, 150, 200]}
---
{"factor":[1,0.765,0.06,0.06,0.06,0.786848,1]}
```

### 6.7 Shake {#shake}

**shake(amp, ms)**: if not `reduced`, `shake = {amp, t0: now, ms}` (replacing any running shake). In the pose, with `el = msOf(tick − t0)` and `p = el/ms`, for `p < 1`:

```
ox = amp · sin(0.0817·el) · (1 − p)^1.4
```

### 6.8 Tremble {#tremble}

**tremble(ms)**: if not `reduced`, `tremble = {t0: now, until: now + ticks(ms)}`. In the pose, while `tick < until`, with `el = msOf(tick − t0)`:

```
ox += 0.9 · sin(0.11·el) ;  oy += 0.5 · sin(0.077·el)
```

### 6.9 Loops {#loops}

A loop runs until it is stopped.

- **startLoop(name):** `loop = name`, `loopT0 = now`. Any running loop is replaced.
- **stopLoop:** `loop = null`, `gazeOverride = null`. `loopT0` keeps its value, and so does `ch.ds.t`, so the dots fade out in phase and in place.

While a loop runs, its gaze comes from §6.4 and its expression from the loop layer (§7.2). The loop dots fade in through the `do` channel. Thinking pulses them in a row; loading spins them on a circle, and the `ds` channel morphs between the two (§10.1).


## 7. Expressions and layers {#expressions}

### 7.1 Expression table {#expression-table}

Each expression gives per-eye targets (left `L`, right `R`), body targets and a gaze direction in −1…1 of the eye travel. Missing keys take the rest values. An eye's `r` is mirrored in the pose (§10.1): a positive `r` lowers the inner corner of either eye.

| part | rest values |
|---|---|
| eye | `{"sx":1,"sy":1,"r":0,"dx":0,"dy":0,"hap":0,"sc":1}` |
| body | `{"x":0,"y":0,"sx":1,"sy":1,"r":0}` |

| expression | left eye | right eye | body | gaze (x, y) |
|---|---|---|---|---|
| `neutral` |  |  |  |  |
| `curious` | sc 0.92, dy 0.8 | sc 1.22, dy -2.4 | r -4, y -2 | 0.35, -0.45 |
| `happy` | hap 1 | hap 1 | sy 1.03, sx 0.985 |  |
| `focused` | sy 0.42, dy 1.4 | sy 0.42, dy 1.4 |  | 0, 0.3 |
| `surprised` | sc 1.4 | sc 1.4 | sy 1.04, sx 0.975 |  |
| `wink` | sc 1.06 | hap 1 | r -3 |  |
| `angry` | sy 0.42, sx 1.12, r 22, dy 1.6 | sy 0.42, sx 1.12, r 22, dy 1.6 | sx 1.05, sy 0.96 |  |
| `worried` | sy 0.5, sx 1.12, r -24, dy 1.8 | sy 0.5, sx 1.12, r -24, dy 1.8 | sy 0.97, sx 1.015 | 0, 0.5 |
| `scared` | sc 1.45, sy 1.12 | sc 1.45, sy 1.12 | sx 0.86, sy 0.82 |  |
| `sleepy` | sy 0.1, dy 3 | sy 0.1, dy 3 |  | 0, 0.6 |
| `squeezed` | sy 0.3, sx 1.25 | sy 0.3, sx 1.25 | sx 1.32, sy 0.56 |  |
| `lookUp` |  |  |  | 0.15, -1 |
| `lookDown` |  |  |  | 0, 1 |
| `thinking` | sy 0.78, dy -0.4 | sc 1.12, dy -1.6 | r 3 | 0.75, -0.9 |

### 7.2 Layers {#layers}

The expression shown is chosen from **layers**. Each layer holds one expression name or nothing. `current()` returns the first non-empty layer, in this priority order:

1. `press`
2. `scare`
3. `angry`
4. `show`
5. `loop`
6. `wake`
7. `hover`
8. `sleep`
9. `base`

- `press`: held long press (§9.3). `scare`: scared (§8). `angry`: annoyed (§8, §9.6). `show`: transient expressions from acts. `wake`: waking up (§9.7). `hover`: pointer over the mascot. `sleep`: sleeping. `base`: the instance's base expression.
- `loop` is **derived**, not stored: it is `"thinking"` while `loop = "thinking"`, `"focused"` while `loop = "loading"` and `reduced`, and empty otherwise.
- If every layer is empty, `current()` is `"neutral"`.

**setLayer(name, expr, ms = 0):**

1. Cancel timer group `layer:<name>`.
2. If `expr` is null, empty the layer; else set it.
3. If `ms > 0` and `expr` is not null: schedule `layerClear(name)` in group `layer:<name>` after `ms`.

Only expression names from §7.1 are valid. An op or event naming an unknown expression MUST be ignored (no state change).

The **mood** reported to hosts is `current()`. A host that needs change notifications compares the mood after each step.


## 8. Acts {#acts}

An **act** is a named reaction, started by a `react` event (§9.8) or by the engine itself (scare, §9.5). Acts are data: `spec/data/acts.json` lists each act as ops at times in ms.

### 8.1 Running an act {#run-act}

**runAct(name)**, for a known act name:

1. Use `reduced` ops if `reduced` is true and the act has them, else `ops`.
2. For each op **in list order**:
   - if the op has `motion: true` and `reduced` is true, skip it;
   - if `t = 0`, run it now;
   - else schedule it in group `seq` after `t` ms.

All delays count from the act's start tick, not from earlier ops. Ops at the same time run in list order (FIFO by `seq`).

### 8.2 Act table {#act-table}

| act | ops (t, op, args) | reduced-motion ops |
|---|---|---|
| `hop` | 0 ms `hop` {"power":1} |  |
| `hide` | 0 ms `cancelSeq`<br>0 ms `actSet` {"values":{"sy":0.9,"sx":1.05}}<br>110 ms `actClear` {"keys":["sx","sy"]}<br>110 ms `actSet` {"values":{"y":98}}<br>1100 ms `actSet` {"values":{"y":44}}<br>1100 ms `show` {"expr":"curious","ms":2200}<br>1500 ms `gaze` {"x":-1,"y":-0.3}<br>2050 ms `gaze` {"x":1,"y":-0.3}<br>2600 ms `gaze` {"clear":true}<br>2600 ms `actClear`<br>2720 ms `hop` {"power":0.5} | 0 ms `cancelSeq`<br>0 ms `show` {"expr":"worried","ms":1500} |
| `scared` | 0 ms `scareCooldown` {"ms":2200}<br>0 ms `layer` {"name":"scare","expr":"scared","ms":1300}<br>0 ms `duck` {"motion":true}<br>0 ms `tremble` {"ms":1100,"motion":true}<br>1300 ms `actClear` {"keys":["y"],"motion":true} |  |
| `curious` | 0 ms `show` {"expr":"curious","ms":1800} |  |
| `focused` | 0 ms `show` {"expr":"focused","ms":1800} |  |
| `surprised` | 0 ms `show` {"expr":"surprised","ms":1400}<br>0 ms `hop` {"power":0.35} |  |
| `wink` | 0 ms `show` {"expr":"wink","ms":900} |  |
| `lookUp` | 0 ms `show` {"expr":"lookUp","ms":1800} |  |
| `lookDown` | 0 ms `show` {"expr":"lookDown","ms":1800} |  |
| `lookAround` | 0 ms `cancelSeq`<br>0 ms `gaze` {"x":-1,"y":0}<br>520 ms `gaze` {"x":1,"y":-0.2}<br>1100 ms `gaze` {"x":0.3,"y":-1}<br>1600 ms `gaze` {"clear":true}<br>1600 ms `blink` {"double":false} |  |
| `loading` | 0 ms `loopToggle` {"loop":"loading"} |  |
| `thinking` | 0 ms `loopToggle` {"loop":"thinking"} |  |
| `success` | 0 ms `show` {"expr":"happy","ms":1600}<br>0 ms `hop` {"power":0.8}<br>0 ms `twinkle` |  |
| `error` | 0 ms `show` {"expr":"worried","ms":1800}<br>120 ms `shake` {"amp":4.5,"ms":520} |  |
| `angry` | 0 ms `layer` {"name":"angry","expr":"angry","ms":1600}<br>0 ms `shake` {"amp":4.5,"ms":460} |  |
| `squeeze` | 0 ms `press` {"forced":true}<br>900 ms `release` |  |
| `sleepy` | 0 ms `sleep` |  |

`react(name)` for a name that is not an act but is an expression shows it: `setLayer("show", name, 1800)`. Any other name is ignored.

### 8.3 Ops {#ops}

| op | effect |
|---|---|
| `hop {power}` | §6.5 |
| `hopLaunch {power}` | §6.5 (internal) |
| `cancelSeq` | cancel group `seq`; `act = {}`; `gazeOverride = null` |
| `actSet {values}` | set each key of `values` in `act` |
| `actClear {keys?}` | remove the listed keys from `act`; with no `keys`, empty it |
| `duck` | `act.y = peek ? 62 : 24` |
| `show {expr, ms}` | `setLayer("show", expr, ms)` |
| `layer {name, expr, ms}` | `setLayer(name, expr, ms)` |
| `layerClear {name}` | `setLayer(name, null)` (internal) |
| `gaze {x, y}` / `gaze {clear}` | `gazeOverride = (x, y)` / `gazeOverride = null` |
| `blink {double}` | §6.6 |
| `blinkTick`, `blinkDouble` | §6.6 (internal) |
| `twinkle` | cancel group `glint`; `glintOn = true`; `ch.gs.x = 0.2`; `ch.gs.v = 14`; schedule `glintOff` in group `glint` after 1500 ms |
| `glintOff` | `glintOn = false` (internal) |
| `shake {amp, ms}` | §6.7 |
| `tremble {ms}` | §6.8 |
| `scareCooldown {ms}` | `scareCD = now + ticks(ms)` |
| `press {forced}` / `longPress` | §9.3 (`longPress` = `press` with `forced = false`) |
| `release` | §9.3 |
| `loopToggle {loop}` | if `loop` is already running, stopLoop; else startLoop(loop) (§6.9) |
| `sleep` | §9.7 |
| `hoverHappy` | if `hovering`: `setLayer("hover", "happy")` (internal) |

"Internal" ops are only scheduled by the engine; they don't appear in `acts.json`. `now` is the tick of the step that runs the op.

### 8.4 Notes on specific acts {#act-notes}

- **hide** sinks the body out of view (`y = 98` puts it below the clip at 100), peeks back at `y = 44` looking curious, looks left and right, then hops back up. The reduced-motion version only shows `worried`.
- **scared** shrinks the body (from the expression), ducks it (`duck`) and trembles. With `peek` the duck is shallower, for a mascot that peeks from an edge. It also starts the scare cooldown (§9.5), so a pointer rush right after a scripted scare doesn't scare it again.
- **loading** and **thinking** toggle: reacting with the running loop's name stops it.
- **squeeze** is a scripted long press: squeezed for 900 ms, then released with a boing and a small hop.
- **sleepy** falls asleep; any activity wakes it (§9.7). Note that `react` itself is activity, so `react("sleepy")` while asleep wakes first and then sleeps again; the wake-up's hop (60 ms later, group `seq`) still fires, and its pending timer holds off idle sleep until then.

```example id=trace-hop-001 kind=trace features=[acts,hop]
{"scenario": {"id": "hop-example", "ticks": 60, "options": {"seed": 1}, "config": {"behavior": {"blink": false}}, "events": [{"tick": 0, "type": "react", "name": "hop"}]}, "at": [1, 11, 12, 20, 36, 44, 60], "fields": ["sy", "sx", "root.ty"]}
---
{
  "rows": [
    {"t":1,"mood":"neutral","sy":0.996306,"sx":1.002375,"root.ty":0},
    {"t":11,"mood":"neutral","sy":0.887106,"sx":1.072575,"root.ty":0},
    {"t":12,"mood":"neutral","sy":0.911689,"sx":1.053654,"root.ty":-2.638034},
    {"t":20,"mood":"neutral","sy":1.069712,"sx":0.942856,"root.ty":-17.242302},
    {"t":36,"mood":"neutral","sy":1.034225,"sx":0.977431,"root.ty":-11.784172},
    {"t":44,"mood":"neutral","sy":0.951789,"sx":1.037118,"root.ty":0},
    {"t":60,"mood":"neutral","sy":0.976005,"sx":1.01716,"root.ty":0}
  ]
}
```


## 9. Input and interaction {#input}

### 9.1 Events {#events}

Events are applied in phase 1 of the step whose start tick they carry. Schema: `spec/schema/scenario.v1.json`.

| event | fields | needs `interactive` |
|---|---|---|
| `pointer` | `x, y`: pointer position in host px, relative to the centre of the host | no |
| `enter`, `leave` | pointer entered or left the host | yes |
| `down` | `button` (default 0) | yes |
| `up`, `cancel` | | yes |
| `key` | `key` (`"Enter"` or `" "`), `phase` (`"down"`/`"up"`), `repeat` | for the click only (§9.6) |
| `activity` | | no |
| `react` | `name` | no |
| `setExpr` | `expr`: new base expression (ignored if unknown) | no |
| `setLoop` | `loop`: `"loading"`, `"thinking"` or null | no |
| `setReduced` | `value` | no |
| `setHostSize` | `size` in px | no |
| `setConfig` | `config`: a sparse config merged onto the current one | no |

When `interactive` is false, `enter`, `leave`, `down`, `up` and `cancel` are ignored entirely, and a `key` event still counts as activity but never clicks. Events with an unknown `type` are ignored.

The **host** owns the platform: it turns pointer, keyboard and media-query input into these events (appendix A.1). Pointer events are global: a host SHOULD send `pointer` for pointer moves anywhere in its window, not only over the mascot, because follow and scare work at a distance. A host SHOULD send `activity` for key presses, wheel and pointer-down anywhere.

### 9.2 Activity {#activity}

**activity:** `lastAct = now`; if `sleeping`, wake up (§9.7).

The `pointer`, `enter`, `down`, `key`, `activity` and `react` events and every click (§9.6) count as activity.

### 9.3 Hover and press {#hover-press}

**enter:** `hovering = true`; activity; `setLayer("hover", "curious")`; cancel group `hover`; schedule `hoverHappy` in group `hover` after 1100 ms.

**leave:** `hovering = false`; cancel group `hover`; `setLayer("hover", null)`; cancelPress.

**down:** if `button ≠ 0`, ignore. Activity; `pressed = true`; `suppressClick = false`; if not `reduced`, `act.sy = 0.94, act.sx = 1.03`; cancel group `press`; schedule `longPress` in group `press` after 420 ms.

**up:** cancel group `press`. If not `pressed`, stop (an `up` without a `down` on the host does nothing). `pressed = false`. If `squeezed`: release, stop. Else remove `sx` and `sy` from `act`; if not `suppressClick`, click (§9.6).

**cancel** = cancelPress: cancel group `press`; if not `pressed`, stop; `pressed = false`; if `squeezed`, release; else if `air` is null, remove `sx` and `sy` from `act`.

**press(forced):** remove `sx` and `sy` from `act` (so the squeezed body shows, not the press squat); `squeezed = true`; `setLayer("press", "squeezed")`; if not `forced`, `suppressClick = true` (so the `up` that ends a long press is not a click).

**release:** if not `squeezed`, do nothing. `squeezed = false`; `setLayer("press", null)`; if `reduced`, stop; `ch.sy.v += 7`; `ch.sx.v += −4`; schedule `hop(0.45)` in group `seq` after 50 ms.

### 9.4 Pointer and follow {#pointer}

**pointer(x, y):**

1. Activity.
2. **Velocity.** If `pointer.has`: `dt = max(4, msOf(now − pointer.lastTick))`, then `vx = 0.5·vx + 0.5·(x − pointer.x)/dt` and the same for `vy`.
3. `pointer.x = x`, `pointer.y = y`, `pointer.lastTick = now`, `pointer.has = true`.
4. `W = hostSize`, `d = sqrt(x² + y²)`, or 1 if that is 0.
5. **Follow.** If `cfg.behavior.follow`: `k = min(1, d / max(180, 1.6·W))`, `e = 1 − (1 − k)²`, `fx = (x/d)·e`, `fy = (y/d)·e`. If follow is off, `fx` and `fy` keep their old values (they are unused until follow is on again). Steps 2, 3 and 7 run either way.
6. **Scare check** (§9.5).
7. `pointer.prevD = d`.

Implementations SHOULD compute `d` as `sqrt(x·x + y·y)` rather than a library `hypot`, so thresholds agree bit for bit.

### 9.5 Scare {#scare}

In `pointer`, after follow: if `cfg.behavior.scare`, not `reduced`, `now > scareCD` and not `squeezed`, then with

```
near   = max(80, 0.95·W)
v      = sqrt(vx² + vy²), or 1 if that is 0
toward = −(vx·x + vy·y) / (v·d)
```

run act `scared` when **all** hold: `v > 2.2`, `toward > 0.8`, `d < near`, `prevD > 0.55·W`, `d < prevD − 6`. In words: the pointer moves fast, straight at the mascot, has just crossed into the near zone from outside, and is closing in.

### 9.6 Click {#click}

**click** (from `up` or a key):

1. Activity.
2. Drop entries of `clicks` with `now − t ≥ ticks(1100)`; append `now`; `n` = the number of entries.
3. If `n ≥ 4` (**annoyed**): `cancelSeq` (§8.3); `setLayer("angry", "angry", 1700)`; `shake(4 + min(4, n − 4)·1.2, 460)`. Stop. A hop already in the air keeps going and lands normally.
4. Else: `hop(n > 1 ? 0.8 : 1)`. If `hovering`: cancel group `hover` and `setLayer("hover", "happy")`.

**Keyboard.** Every `key` event is activity. Then, if `interactive` and not `repeat`: `Enter` with phase `down` clicks, and Space (`" "`) with phase `up` clicks, as native buttons do. Other keys and phases do nothing more. The host SHOULD prevent the page from scrolling on Space keydown.

### 9.7 Idle, sleep and wake {#idle}

**Idle sleep** (step phase 3): if `cfg.behavior.sleepy`, not `sleeping`, `loop` is null, not `squeezed`, the `show` layer is empty, no timer of group `seq` is pending, and `now − lastAct ≥ ticks(cfg.behavior.idleMs)`: sleep.

**sleep:** if `sleeping`, do nothing. `sleeping = true`; `sleepT0 = now`; `setLayer("sleep", "sleepy")`.

**Wake up** (from activity): if not `sleeping`, do nothing. `sleeping = false`; `setLayer("sleep", null)`; `setLayer("wake", "surprised", 600)`; schedule `hop(0.3)` in group `seq` after 60 ms.

While asleep the body breathes (§6.3) and two z's drift up (§10.1). Blinks are skipped.

### 9.8 Other events {#other-events}

- **react(name):** activity, then runAct(name) if it is an act, else `setLayer("show", name, 1800)` if it is an expression, else nothing (§8.2).
- **setExpr(expr):** if `expr` is a known expression, `layers.base = expr`.
- **setLoop(loop):** null → stopLoop; otherwise startLoop(loop) unless that loop is already running.
- **setReduced(value):** `reduced = value`. When turning on: `air = null`, `jy = 0`, `shake = null`, `tremble = null`, `blinkT0 = −1`.
- **setHostSize(size):** `hostSize = size`.
- **setConfig(config):** `merged = deepMerge(sparse, config)` (objects merge key by key; every other value, including null and arrays, replaces). If `resolve(merged).errors` is not empty, ignore the event. Else `sparse = merged`, `cfg = resolve(merged).resolved`, recompute `G`. If blinking was on and is now off, cancel group `blink`. If it was off and is now on, scheduleBlink (one draw).


## 10. Pose and rendering {#pose}

### 10.1 pose() {#pose-formulas}

`pose(state)` is pure. It reads the state at time `tick` (after the last step). Let `c` be the channels, `G` the geometry, `msOf` as in §2.2.

**Offsets.** `ox = oy = 0`; add the shake (§6.7) and the tremble (§6.8).

**Clamped gaze.** `gx = clamp(c.gx.x, −(G.mgx + 0.5), G.mgx + 0.5)`, `gy` likewise with `mgy`.

**Root (body group).**

```
tx  = c.x.x + ox
ty  = c.y.x + jy + oy
rot = c.r.x + 0.14·gx + 0.7·ox          (the body leans 0.14° per u of gaze)
sx  = c.sx.x
sy  = max(0.05, c.sy.x)
```

**Eyes.** Blink factor `bf` from §6.6 (1 when no blink). For eye s with `m = −1` (L) or `+1` (R):

```
sc   = c[s.sc].x ;  hap = clamp(c[s.hap].x, 0, 1)
x    = G.cx + m·G.ex + gx + c[s.dx].x
y    = G.ey + gy + c[s.dy].x
rot  = −m · c[s.r].x
sx   = c[s.sx].x · sc
sy   = max(0.02, c[s.sy].x · bf · (1 − 0.85·hap)) · sc
opacity    = clamp(1 − 2.2·hap, 0, 1)
pupilX     = G.pupils ? (gx / (G.mgx or 1)) · G.ew · 0.2 : 0
pupilY     = G.pupils ? (gy / (G.mgy or 1)) · G.eh · 0.2 : 0
arcScale   = sc
arcOpacity = clamp((hap − 0.4) / 0.6, 0, 1)
```

(`G.mgx or 1` means 1 when `mgx = 0`.) As `hap` goes to 1 the eye squints and fades out while the happy arc fades in.

**Glint.** `opacity = clamp(c.go.x, 0, 1)`, `scale = max(0, c.gs.x)`.

**Dots.** Each dot is `{opacity, x, y}`, in body coordinates. Let `o = clamp(c.do.x, 0, 1)`, `lm = msOf(tick − loopT0)`, `frac(v) = v − floor(v)`, and for i = 0, 1, 2 the row centre `(rx_i, ry_i) = (G.cx + G.w/2 − 8 + 7.5·i, G.top − 9 − 2·i)` (§4.3).

If `reduced`: `dot_i = {o, rx_i, ry_i}` (no pulse, no spin). Otherwise, with `s = clamp(c.ds.x, 0, 1)` and `tail = (1, 0.6, 0.3)`:

```
pulse_i = 0.3 + 0.7·max(0, sin(π · frac(lm/1300 − 0.2·i)))     (thinking)
a_i     = 2π·lm/900 − i·60°                                    (loading: clockwise from 12 o'clock)
sx_i    = G.cx + G.w/2 − 2 + 8·sin(a_i)
sy_i    = G.top − 12 − 8·cos(a_i)
opacity = o · (pulse_i + s·(tail_i − pulse_i))
x       = rx_i + s·(sx_i − rx_i)
y       = ry_i + s·(sy_i − ry_i)
```

Dot 0 leads the spin and is the brightest; one turn takes 900 ms (108 ticks). With `s = 0` this is the thinking row; with `s = 1` it is the loading spinner.

**Zs.** Anchor `(zx, zy) = (G.cx + G.w/2 − 6, G.top − 2)`. For i = 0, 1:

- not `sleeping`: `{opacity: 0, x: zx, y: zy, scale: 1}`;
- `sleeping` and `reduced`: z0 `{0.8, zx, zy, 1}`, z1 `{0, zx, zy, 1}`;
- `sleeping`: with `ph = frac(msOf(tick − sleepT0)/2400 + 0.5·i)`: `{opacity: 0.85·sin(π·ph), x: zx + 8·ph, y: zy − 16·ph, scale: 0.7 + 0.5·ph}`.

**Mood** = `current()` (§7.2).

### 10.2 Pose order {#pose-order}

Traces (§15.2) list the pose as 44 numbers in this order:

| # | pose key |
|---|---|
| 0 | `root.tx` |
| 1 | `root.ty` |
| 2 | `root.rot` |
| 3 | `root.sx` |
| 4 | `root.sy` |
| 5 | `L.x` |
| 6 | `L.y` |
| 7 | `L.rot` |
| 8 | `L.sx` |
| 9 | `L.sy` |
| 10 | `L.opacity` |
| 11 | `L.pupilX` |
| 12 | `L.pupilY` |
| 13 | `L.arcScale` |
| 14 | `L.arcOpacity` |
| 15 | `R.x` |
| 16 | `R.y` |
| 17 | `R.rot` |
| 18 | `R.sx` |
| 19 | `R.sy` |
| 20 | `R.opacity` |
| 21 | `R.pupilX` |
| 22 | `R.pupilY` |
| 23 | `R.arcScale` |
| 24 | `R.arcOpacity` |
| 25 | `glint.opacity` |
| 26 | `glint.scale` |
| 27 | `dot0.opacity` |
| 28 | `dot0.x` |
| 29 | `dot0.y` |
| 30 | `dot1.opacity` |
| 31 | `dot1.x` |
| 32 | `dot1.y` |
| 33 | `dot2.opacity` |
| 34 | `dot2.x` |
| 35 | `dot2.y` |
| 36 | `z0.opacity` |
| 37 | `z0.x` |
| 38 | `z0.y` |
| 39 | `z0.scale` |
| 40 | `z1.opacity` |
| 41 | `z1.x` |
| 42 | `z1.y` |
| 43 | `z1.scale` |

### 10.3 SVG reference mapping {#svg}

The reference renderer (`core/src/render-svg.ts`) draws one `<svg viewBox="0 0 100 100" overflow="visible">`. Paint order and transforms:

```
<defs><clipPath id=K><rect x=-300 y=-400 width=700 height=500/></clipPath></defs>
<g clip-path=url(#K)>                         — clips only below y = 100
  <g transform="translate(tx ty) rotate(rot 50 92) translate(50 92) scale(sx sy) translate(-50 -92)">
    body polygon (§4.1)                                   fill: body
    for L, R:
      <g transform="translate(x y) rotate(rot) scale(sx sy)" opacity=opacity>
        eye stadium (§4.2)                                 fill: eye  (ring: stroke eye, no fill)
        pupil circle, translate(pupilX pupilY)             fill: body (only with pupils)
      </g>
      <g transform="translate(x y) scale(arcScale)" opacity=arcOpacity>
        happy arc (§4.3)                                   stroke: eye
      </g>
    glint circle, scaled by glint.scale about its centre, opacity glint.opacity     fill: glint
    3 dots, circle r = 2.6 at (dot_i.x, dot_i.y), opacity dot_i.opacity   fill: accent
  </g>
</g>
for each z: <g transform="translate(x y) scale(scale)" opacity=opacity> z polyline </g>   stroke: accent
```

The body group rotates and scales about the bottom centre (50, 92). The zs sit outside the clip and outside the body group. Rendered numbers MAY be rounded (the reference rounds to 0.01); rounding MUST NOT feed back into the state.

Other renderers (Canvas, SwiftUI, Flutter) MUST apply the same transforms in the same order. Appendix A.3 has notes.


## 11. Reduced motion {#reduced}

`reduced` is a per-instance flag: the `reducedMotion` option and the `setReduced` event. A host SHOULD drive it from the platform setting (`prefers-reduced-motion`, UIAccessibility, etc.).

While `reduced` is true:

- Springs snap: every channel `x = t, v = 0` each step (§6.2), so expressions switch instantly.
- Body targets are neutral (§6.3): expressions change the eyes only.
- No hop (§6.5), no shake (§6.7), no tremble (§6.8), no blink (§6.6), no follow (§6.4), no scare (§9.5), no breathing (§6.3), no release boing (§9.3).
- The loading loop doesn't move the eyes; the loop layer shows `focused` instead (§7.2). Thinking holds its gaze at (0.75, −0.9). In both loops the dots sit still in the row at full opacity: no pulse, no spin (§10.1).
- `hide` runs its reduced ops: `worried` for 1500 ms (§8.2).
- Sleep shows one still z (§10.1).
- Acts still run their timelines: layers, gaze overrides and the glint behave as usual, without motion.

Turning `reduced` on mid-motion clears the hop, shake, tremble and blink at once (§9.8).


## 12. Accessibility {#a11y}

This chapter is a checklist; it is not tested by traces. An implementation claiming L4 MUST meet every item.

1. A non-interactive mascot is **decorative**: hidden from assistive technology (`aria-hidden="true"`, or the platform equivalent).
2. An interactive mascot is a **button**: focusable, with role button and an accessible name. The default name is `"<name>. Press to make it hop."` with `name` from the config; the host MUST allow overriding it.
3. Enter activates on keydown and Space on keyup, and key repeat is ignored (§9.6). The host prevents the page from scrolling on Space.
4. Focus is visible: the host shows a focus ring around the mascot.
5. The mascot doesn't announce its mood. Announcing state (loading, error) is the host app's job, for example with `aria-busy` or a live region next to the mascot.
6. Reduced motion is respected (§11), following the platform setting unless the user overrides it.
7. No information is conveyed by the mascot alone; its moods decorate states the app already shows.
8. Pointer interactions have keyboard equivalents for the click. The long press has none in v0.1 (it is decorative).


## 13. Theming {#theming}

The renderer uses five colour roles. The role names are normative; the values come from the config (§3.1).

| role | paints | default |
|---|---|---|
| `body` | the body | `#2256F2` |
| `eye` | eyes, ring strokes, happy arcs | `#FFFFFF` |
| `glint` | the glint | `#FFB800` |
| `accent` | loop dots and z's | `#8D8A84` |
| `pupil` | pupils (an alias of `body`) | = body |

- **Web:** CSS custom properties `--quirkling-body`, `--quirkling-eye`, `--quirkling-glint`, `--quirkling-accent`, with the config values as fallbacks. A page can switch them for dark mode or a theme without touching the engine.
- **Native:** constants with the same role names.
- The eye colour SHOULD contrast with the body colour by at least 3:1 (WCAG 1.4.11). (`resolve()` will enforce this from spec 0.2.)

*v0.1 note:* light and dark values per role, DTCG colour tokens and palette presets are planned for spec 0.2.


## 14. Favicon, app icon and terminal face {#favicon}

### 14.1 Favicon {#favicon-derivation}

The favicon is derived from the ResolvedConfig on a 32-unit grid (each unit is half a pixel at 16 px, so even units are whole pixels):

1. Scale `s = 32 / max(G.w, G.h)`. The body is `G.w·s × G.h·s`, centred in the grid, with the config's roundness and **no wobble**.
2. Eye size: `w = max(4, 2·⌈(G.ew·s)/2 − 10⁻⁹⌉)`, `h` likewise from `G.eh`: rounded **up** to even units. The 10⁻⁹ keeps a value that is even up to float noise from rounding up by 2.
3. Left eye centre: `cxL = 16 − G.ex·s`, `cy = 16 + (G.ey − (G.bottom − G.h/2))·s`.
4. Left eye: `x = 2·round((cxL − w/2)/2)`, `y = 2·round((cy − h/2)/2)`, with `round(v) = floor(v + 0.5)`. Right eye: `x' = 32 − x − w`, same y. Corner radius `min(w, h)/2`.
Evaluate in binary64 exactly as written, left to right: `s = 32/max(G.w, G.h)` first.

5. Ring eyes stay rings with stroke `max(2, 2·round(G.stroke·s/2))` (JavaScript `Math.round`); pupils and the glint are dropped.

The default config MUST give exactly the eyes `(6, 10, 6, 8)` and `(20, 10, 6, 8)`:

```example id=favicon-001 kind=favicon features=[favicon]
{"config": {}}
---
{
  "grid": 32,
  "body": {"x":0,"y":0,"w":32,"h":32,"roundness":0.5},
  "eyes": [{"x":6,"y":10,"w":6,"h":8,"rx":3},{"x":20,"y":10,"w":6,"h":8,"rx":3}],
  "ring": 0
}
```

### 14.2 App icon (informative) {#app-icon}

The "peek" app icon, on a 180 grid with full bleed: a tile in the body colour; the mascot body in the eye colour, `108 × 150` centred at `(90, 153)` (so it rises from the bottom edge to y = 78); two eyes in the body colour at `(68, 92)` and `(108, 92)`, `18 × 24`, radius 9; a glint circle at `(144, 52)`, r = 9. Roundness follows the config.

### 14.3 Terminal face {#terminal}

A two-character face for terminals, drawn on the body colour (24-bit background escape `ESC[48;2;R;G;Bm`), with the fallback `[••]` when colour is unavailable:

| expression | face |
|---|---|
| `neutral` | `••` |
| `curious` | `•°` |
| `happy` | `^^` |
| `focused` | `--` |
| `surprised` | `°°` |
| `wink` | `•^` |
| `angry` | `><` |
| `worried` | `><` |
| `scared` | `°°` |
| `sleepy` | `--` |
| `squeezed` | `><` |
| `lookUp` | `••` |
| `lookDown` | `••` |
| `thinking` | `••` |


## 15. Conformance {#conformance}

### 15.1 Artefacts {#artefacts}

Everything below is generated by the reference engine (`core/`). `bun run check` regenerates it and fails if it differs from what is committed.

| tier | what | where | tolerance | normative |
|---|---|---|---|---|
| T0 | `resolve()` vectors | `conformance/vectors/resolve/` | 1e-6 | yes |
| T1 | geometry, favicon, shapeN, clock, springs, blink, rng vectors | `conformance/vectors/*/` | 1e-4 | yes |
| T1 | the examples in this document | `conformance/vectors/examples/` | 1e-4 | yes |
| T2 | motion traces, one per scenario | `conformance/traces/<id>.jsonl` | 1e-4 | yes |
| T3 | golden strips, PNG frames rendered from the engine | `conformance/strips/` | visual review | no |

Numbers in golden files are rounded to 6 decimals. Strings and booleans compare exactly.

### 15.2 Trace format {#trace-format}

A trace is JSONL (schema `spec/schema/trace.v1.json`). Line 1 is a header:

```json
{"type":"header","spec":"0.1","scenario":"act-hop","hz":120,"sample":4,"ticks":120,"channels":[…25 names…],"pose":[…44 names…]}
```

Every following line is a **sample**: the state after `t` steps, for `t = 0` and every `t` with `t mod sample = 0`, plus `t = ticks` if that isn't already included:

```json
{"t":12,"mood":"neutral","c":[…25 channel positions x…],"p":[…44 pose numbers…]}
```

`c` is in channel order (§5.2): `x y sx sy r gx gy gs go do ds Lsx Lsy Lr Ldx Ldy Lhap Lsc Rsx Rsy Rr Rdx Rdy Rhap Rsc`. `p` is in pose order (§10.2).

### 15.3 Scenarios {#scenarios}

A scenario (schema `spec/schema/scenario.v1.json`) is `{id, level, features, config, options, ticks, sample, events}`, with defaults `config = {}`, `options = {}`, `sample = 4`. Events carry the tick of the step that applies them; events with the same tick apply in list order; events with `tick ≥ ticks` are never applied. To run one: `create(config, options)`, emit the `t = 0` sample, then repeat `step(state, events stamped with state.tick)` until `tick = ticks`, emitting samples.

| id | level | ticks | what it covers |
|---|---|---|---|
| `expr-cycle` | L1 | 560 | Every expression as the base expression, 40 ticks each |
| `act-angry` | L2 | 240 | Act: angry |
| `act-curious` | L2 | 260 | Act: curious |
| `act-error` | L2 | 280 | Act: error |
| `act-focused` | L2 | 260 | Act: focused |
| `act-hide` | L2 | 420 | Act: hide |
| `act-hop` | L2 | 120 | Act: hop |
| `act-loading` | L2 | 300 | Act: loading |
| `act-lookAround` | L2 | 240 | Act: lookAround |
| `act-lookDown` | L2 | 260 | Act: lookDown |
| `act-lookUp` | L2 | 260 | Act: lookUp |
| `act-scared` | L2 | 300 | Act: scared |
| `act-sleepy` | L2 | 480 | Act: sleepy |
| `act-squeeze` | L2 | 220 | Act: squeeze |
| `act-success` | L2 | 240 | Act: success |
| `act-surprised` | L2 | 200 | Act: surprised |
| `act-thinking` | L2 | 360 | Act: thinking |
| `act-wink` | L2 | 150 | Act: wink |
| `blink-seed-1` | L2 | 1440 | Idle blinking for 12 s (seed 1) |
| `blink-seed-7` | L2 | 1440 | Idle blinking for 12 s (seed 7) |
| `look-hand-drawn-error` | L2 | 280 | Look 'hand-drawn' (wobble 0.7): error |
| `look-ring-success` | L2 | 240 | Look 'ring eyes': success |
| `look-tall-up-hide` | L2 | 420 | Look 'tall, up' (vpill, aspect -0.6): hide |
| `loop-option-loading` | L2 | 300 | Created in the loading loop; stopped with setLoop |
| `peek-scared` | L2 | 300 | Peek option: scared ducks to 62 |
| `ruling-scared-lookaround` | L2 | 300 | Ruling: lookAround right after scared resets the duck |
| `ruling-success-in-thinking` | L2 | 420 | Ruling: success during the thinking loop returns to thinking |
| `set-config` | L2 | 960 | setConfig mid-run: eye shape, roundness, blink off and on, follow off, an invalid config |
| `click` | L3 | 150 | Click: squat, hop with stretch, landing squash |
| `click-x5` | L3 | 300 | Rapid clicks (5 in 0.5 s): annoyed + growing shake |
| `follow` | L3 | 486 | Follow: pointer at 8 positions around the mascot |
| `hover` | L3 | 240 | Hover: curious, then happy after 1.1 s; leave |
| `idle-sleep-wake` | L3 | 720 | Idle 2 s → sleepy (breathing, z), pointer wakes it with a surprised hop |
| `keyboard` | L3 | 300 | Keyboard: Enter on keydown, Space on keyup, repeats ignored |
| `long-press` | L3 | 240 | Long press: squeezed while held, boing on release |
| `look-pupils-follow` | L3 | 300 | Look 'pupils': follow and hover |
| `ruling-annoy-midair` | L3 | 240 | Ruling: annoyed on a click mid-hop settles down smoothly |
| `scare` | L3 | 330 | Pointer rushing in: scared, ducks and trembles, then recovers |
| `reduced` | L4 | 600 | Reduced motion: click, success, error, loading, hide, sleepy |
| `reduced-thinking` | L4 | 240 | Reduced motion: the thinking loop holds still (dots at full opacity) |
| `reduced-toggle` | L4 | 120 | Reduced motion switched on mid-hop: the hop stops on the ground |

### 15.4 Runner protocol {#runner}

A port ships a **runner**: a program that reads one JSON document on stdin and writes the result on stdout.

- A **scenario** (no `kind` field) → the JSONL trace (§15.2).
- A **vector input** `{"kind": K, "input": …}` → one JSON line with the result:

| kind | input | output |
|---|---|---|
| `rng` | `{seed, draws}` | `{u32: [...], u: [...]}`: the next `draws` states and draws after seeding (§2.4) |
| `ticks` | `{ms: [...]}` | `{ticks: [...]}` (§2.2) |
| `shapeN` | `{s: [...]}` | `{n: [...]}` (§4.1) |
| `blink` | `{ms: [...]}` | `{factor: [...]}` (§6.6) |
| `springs` | `{set, x, v, t, steps, sample}` | `{rows: [{tick, x, v}]}`: one channel of that set integrated with §6.2, including the rest snap, sampled after the listed steps |
| `geometry` | `{config, omitBody?}` | the fields of §4 (`cx bottom w h top d ew eh stroke ex ey mgx mgy` as numbers; `ring` = shape is ring and no pupils; `pupils`), `eyes`: left then right `{x: cx ∓ ex − ew/2, y: ey − eh/2, w: ew, h: eh, rx: min(ew, eh)/2}` (never inset), and unless `omitBody`, `body`: the outline as `[x, y]` pairs in outline order (4 or 144, §4.1) |
| `resolve` | `{config}` | `{resolved, adjusted, warnings, errors}` (§3.3) |
| `favicon` | `{config}` | `{grid: 32, body: {x, y, w, h, roundness}, eyes: [left, right] as {x, y, w, h, rx}, ring}`; `ring` is the ring stroke from §14.1 step 5, or 0 when the eyes are not rings |
| `trace` | `{scenario, at, fields}` | `{rows: [{t, mood, <field>: value…}]}`: the scenario run with sample 1; one row per value of `at` (ticks 0…`ticks`, ascending); a field is a channel name from §5.2 (its position `x`) or a pose key from §10.2 |

Output is UTF-8, one JSON value per line, each line ending in `\n`. Numbers MAY be unrounded; the CLI compares with the tolerance. Examples in this document show only the `input` and the result; the runner receives `{"kind": K, "input": …}`.

Stacks where a subprocess is awkward (browser-only, Elm) can load the same JSON files in their own test framework.

### 15.5 Running the suite {#cli}

```sh
bun conformance/cli/index.ts --runner "<command>" [--level L3] [--only id,id] [--tol 1e-4] [--report conformance-report.json]
```

The CLI feeds every scenario and vector up to the chosen level to the runner, compares the output with the goldens, prints `PASS`/`FAIL` with the first difference (tick, field, expected, got), and writes a JSON report. It exits non-zero on any failure.

### 15.6 Golden strips (informative) {#strips}

`bun run strips` renders the frames listed in each scenario's `strip` field to PNG with the reference SVG mapping and resvg. They are for people: a quick visual check that a change looks right, and the motion shown on the site.


## 99. Changes from the glim.js study {#changes}

This spec describes a cleaned-up version of the original study engine (glim.js, an earlier prototype of the same mascot), not a bug-compatible copy. Each ruling below is deliberate. "glim" means the study's behaviour. Rulings marked **(visible)** change what a viewer sees; the others only remove nondeterminism or edge-case bugs.

### 99.1 Determinism {#changes-determinism}

| id | glim | this spec |
|---|---|---|
| D1 | Variable frame `dt` (1–50 ms) with spring substeps; the hop integrated once per frame | Fixed 1/120 s step for everything (§6.1). **(visible)** The hop apex is about 20.6 u instead of about 19 u at 60 fps, closer to the designed 22 u. |
| D2 | `setTimeout` for timers, `requestAnimationFrame` for frames: two clocks | One integer tick clock and one timer queue with cancel groups (§2.3) |
| D3 | `Math.random` for blinks | xorshift32 with a fixed draw order (§2.4) |
| D4 | Tremble, breathing and z drift phased from page uptime | Phased from their own start tick (§6.3, §6.8, §10.1). **(visible)** They start at phase 0. |
| D5 | Idle sleep polled every 500 ms (up to 500 ms late) | Exact deadline `lastAct + idleMs` (§9.7) |
| D6 | The blink delay drawn in ms | Drawn in ticks: `264 + floor(u·480)` (§6.6); the same 2.2–6.2 s range |
| D7 | Off-screen mascots froze physics while timers kept running | No visibility concept: a host that stops stepping freezes everything, timers included (appendix A.1) |
| D8 | Global pointer in page px, cached host rects | Host-local px relative to the host centre, with an explicit host size (§9.1) |
| D9 | Mood callback fired on every expression update | Mood is `current()`; hosts compare after each step (§7.2) |
| D10 | The z drawn as text in a web font | A stroked path (§4.3) |
| D11 | `prefers-reduced-motion` read globally | A per-instance flag and event (§11) |

### 99.2 Behaviour {#changes-behaviour}

| id | glim | this spec |
|---|---|---|
| R1 | The second blink of a double blink was a raw `setTimeout`. It wasn't cancellable and blinked even after falling asleep or switching to reduced motion | It is a `blink`-group timer and re-checks `reduced` and `sleeping` (§6.6) |
| R2 | `cancelSeq` cleared act timers but not the body pose: `lookAround` or `hide` within 1.3 s of `scared` left the body **ducked forever** | `cancelSeq` also clears `act` and the gaze override (§8.3). **(visible)** |
| R3 | Cancelling during a hop's 90 ms wind-up (and the release/wake hops) left the squat squash on | Same fix as R2 |
| R4 | The fourth rapid click killed the hop mid-air without resetting its height: the body **hung in the air** until the next hop | Annoyed lets an airborne hop land normally and cancels pending hop launches (§9.6). **(visible)** |
| R5 | Loops and transient shows shared one layer: `success` during `thinking` lost the thinking face for good; starting `loading` cleared any show; `stopLoop` cleared a show it didn't own | A separate, derived `loop` layer below `show` (§7.2). Loops don't touch `show`. **(visible)** |
| R6 | `setAct` replaced the whole body pose: a hop during `hide` popped the body up from its hiding place, and pointer-up cleared every act key | `act` is a map of keys; ops set or clear only their keys (§8.3). **(visible)** |
| R7 | A hop while airborne reset the vertical speed: rapid clicks stacked jumps far above the box | A hop requested while airborne is ignored (§6.5). **(visible)** |
| R8 | A pointer-up on the host without a pointer-down there (dragging onto it) clicked | Ignored; only an `up` after a `down` on the host clicks (§9.3) |
| R9 | Space clicked on keydown; held keys auto-repeated into the annoyed path | Enter on keydown, Space on keyup, repeats ignored (§9.6) |
| R10 | `cancelPress` on pointer-leave cleared the act even with no press in progress (cutting a hop's wind-up) | Only acts when a press is in progress (§9.3) |
| R11 | Unknown expression names (e.g. `lookRight`) were reported as the mood but drawn as neutral | Ignored: no state change (§7.2) |
| R12 | Turning on reduced motion didn't stop a running tremble | It clears the tremble too (§9.8) |
| R13 | Hop requests, shakes and loops all wrote body targets on events; breathing and the hop overwrote them per frame | Body targets are recomputed each step from expression, act, breathing and hop, in a fixed order (§6.3, §6.5) |
| R14 | Favicon roundness 0.45, mascot 0.5 | One default, 0.5, for both (§3.1, §14.1) |
| R15 | The favicon was hand-picked from a list of candidates | Derived from the config; the default reproduces the pick a2 exactly (§14.1) |
| R16 | The page copy said the body leans 0.35° per unit of gaze | The code's 0.14° per unit is normative (§10.1) |
| R17 | Pointer distance used `Math.hypot` | `sqrt(x² + y²)` (§9.4) |
| R18 | Under reduced motion the thinking dots kept pulsing | They hold at full opacity (§10.1, §11) |
| R19 | The pointer-down squat (`sy 0.94`) overrode the squeezed body during a long press and outlived the release | A long press clears the squat, so the body flattens to 0.56 as designed (§9.3). **(visible)** |
| R20 | `setParams` accepted anything | `create` refuses configs with errors; `setConfig` ignores them (§3.3, §9.8) |
| R21 | The loading loop showed no dots; only thinking pulsed its three dots in a row | Loading shows the dots too and spins them as a spinner: three dots on a circle, 900 ms a turn, leading dot brightest (tail 1, 0.6, 0.3). A `ds` channel morphs row ↔ spinner, and the pose carries each dot's position (§5.2, §6.3, §10.1). Under reduced motion they sit in the row at full opacity. **(visible)** |

### 99.3 Kept on purpose {#changes-kept}

- The scare cooldown is set by the scared act itself, so `react("scared")` bypasses the cooldown check but restarts it.
- Under reduced motion, expressions drop their body pose (the squeezed flat body, the scared shrink); only the eyes change.
- The rest threshold 0.002 applies to every channel regardless of unit.
- Hovering keeps priority over sleeping: a sleeping mascot under the pointer shows the hover expression.


## A. Informative notes {#informative}

### A.1 Host loop {#host-loop}

A host drives the engine from its frame callback:

```
acc += min(0.25 s, frame_dt)
n = 0
while acc ≥ 1/120 and n < 6:
    step(state, n == 0 ? queued_events : [])
    acc −= 1/120 ;  n += 1
if n == 6: acc = 0            (drop the excess after a long frame)
draw(pose(state))
```

- **One ticker** for all mascots on a page; pause it when every mascot is off-screen or settled.
- **Settled.** When every channel is at rest and there is no hop, shake, tremble, loop, sleep or blink, stepping changes nothing but the clock until the next timer or the idle deadline. A host MAY stop its frame loop and fast-forward `tick` to that point (the reference core exposes `isSettled` and `nextDue`), or simply keep stepping. Fast-forwarding must still fire timers at their due ticks, in order.
- **Off-screen.** A host MAY stop stepping while the mascot is hidden. The state then freezes as a whole, timers included.
- **Input mapping.** Global pointer moves → `pointer` (relative to the host centre). Pointer enter/leave/down/up/cancel on the host → the matching events. Key events on the focused host → `key`. Key presses, wheel and pointer-down anywhere → `activity`. The platform's reduced-motion setting → `setReduced`. Size changes → `setHostSize`.

### A.2 Performance {#performance}

The step is a few hundred floating-point operations. For the web: write SVG attributes directly (no virtual DOM re-render per frame), share one `requestAnimationFrame` loop, and use an IntersectionObserver to pause off-screen mascots.

### A.3 Other renderers {#renderers}

- **Canvas 2D:** `translate(tx, ty)`, `translate(50, 92)`, `rotate(rot·π/180)`, `scale(sx, sy)`, `translate(−50, −92)` for the body; clip to `y < 100` before drawing it. Draw the stadiums with `roundRect`.
- **SwiftUI / Flutter:** draw in a 100 × 100 coordinate space scaled to the view. Use the pose numbers directly. Don't wrap them in implicit animations: the engine already animates.

### A.4 Spring sets in platform terms {#spring-mapping}

For reference only (implementations MUST still integrate §6.2 exactly): a set with `k, c` has response `2π/√k` seconds and damping ratio `c/(2√k)`, the parameters SwiftUI's `spring(response:dampingFraction:)` takes.

### A.5 Porting checklist {#porting}

1. Load the data files; don't retype constants.
2. Implement `ticks`, xorshift32, `shapeN` and geometry. Pass L0 (resolve, geometry, favicon vectors).
3. Implement channels, springs, expressions and layers. Pass L1.
4. Implement the timer queue, ops and acts, hop, blink, shake, tremble and loops. Pass L2.
5. Implement the input events. Pass L3.
6. Implement reduced motion and the §12 checklist. Pass L4.
7. Write a renderer from §10.3 and compare it with the golden strips.
