# The cookbook

How real works were wired onto the SDK, written to Playspace's publishing agent ("the transcoder"), less that agent's own steps; the contract wins on what a name means.
For a work you write, wire input as [the controller](https://www.joinplayspace.com/sdk/docs/controller.md) says; the verbs and the declaration here are how that agent wires a work it did not write.

**The rows**. On a phone: P1 the
layout is truthful, P2 the stick moves it, P3 a drag turns the view where there is one, P4 a tap acts and never walks,
P5 pause and Leave, P6 the button, P7 the same UI (the stick and the disc, nothing else). On a computer: D1 W and A (or
the declared keys) move it, D2 a mouse drag turns the view, D3 one click, D4 Space is the action where declared.
"Looked" is a row a person's eyes judged (the end card, a hint line).

## 0. Ten rules before any row

**Map, never remove** (SDK 0.14.0; it outranks every row below): never remove a control
path, handler, menu, hint or touch mode the creator built. The runtime presses the work's own keys, so a key table, a
Space handler, a menu, a hint line, a joystick of its own and a mute of its own all stay as they are. Where a row or a
recipe below still shows a deletion from before 0.14 (rows 1 and 2, rule 3's source edit, the engine recipes'
"Delete:"), read the work's own lines as kept: the axes may be read beside them, never in their place. **Map, never
remove is about the creator's code, not about drawing**: every
handler stays, and the drawing is **the Playspace set**: every needed action has a control of the set, and a
key that repeats another control or the work's own screen, or that play does not depend on, is left out in the
file's `extra` with its reason (section 0.5).

1. **One shape.** `playspace.layout({ v: 3, ... })`, only what the defaults cannot guess, once, where the work starts
   reading input. On a computer a subscriber or an axis read is already the declaration; declare anyway.
2. **Three verbs and the button.** Each frame `playspace.input.axis("moveX")` and `("moveY")` (-1..1, up negative) in
   the camera's frame; `playspace.camera.onLook((yaw, pitch) => ...)` (radians, yaw right and pitch up positive) onto
   the work's own camera; `playspace.input.onIntent((i) => ...)` returning true for what it handled, where
   `{ type: "action", on, t0 }` is the one verb with no place on the screen.
3. **Two shapes.** A **source edit** where the input region is readable: subscribe on every device beside the key,
   mouse and touch reads it reads, which stay (map, never remove: the real keys and click reach the work on a computer,
   nothing synthetic there; on a phone the player presses the same keys, so a verb answered both ways answers once by
   leaving its intent unanswered, rule 6).
   **A view from inside takes the mouse**: a work whose camera is the player's eyes or rides behind them, the
   look turning where they face (the map's `view: "inside"`), source edit or glue that subscribes to `onLook` on a
   computer, says `"capture": true` beside `"pointer": "look"` in `playspace.json` (SDK 0.28.0; a hand
   `layout()` says `look: { computer: "capture" }`, SDK 0.9.2), whatever its original did: a click takes the mouse, its
   movement turns the view and Esc gives it back; the SDK takes and gives back the lock, so the work still never calls
   `requestPointerLock`. A view from around (an orbit about a thing, a builder's or a viewer's camera;
   `view: "around"`) leaves the word out: a drag turns it. You decide which the work is. Two exceptions: a work whose
   click must land at a point on the scene beside the look (a `tap` that carries a target: place, pick, throw where the
   pointer is) leaves the word out, because under the lock a click lands at the centre; and the glue below, which leaves the original's own
   mouse single on a computer (13th Floor), is outside the rule, since it never subscribes to `onLook` there. A work
   whose original captured the mouse keeps the declaration as before.
   A **glue** beside an untouched original where the input is minified or an engine's: declare on every device, then
   `if (!ps.touch.device) return;` before any `onLook` or intent subscription, so the original's own keys, mouse and
   pointer lock stay single on a computer. A declaration-only glue needs no gate.
4. **The stick is live only when something listens**: a read of the axes, or `keys` naming the direction keys. Nothing
   else lights it for a declared work (the check's recorded keys count only for an undeclared original since
   `f34c8ea`): a work that reads nothing gets no stick drawn (SDK 0.16) and its corner is the playfield's.
5. **A tap acts where it lands and never walks**. Unhandled, it is the click at the point on a touch screen; on
   a computer the real click already reached the work and the SDK adds none. A work whose own tap walks (a
   tap-to-walk, a point-and-click mover) keeps it: the manifest says `tap: "work"` and the tap passes through; that
   rules our stick, never an edit of the work.
6. **Space is the button on a computer** for a declared work with an `action`, once per press, and the real key still
   arrives: keep the work's own Space handler and answer that verb there alone (no `onIntent` branch for it, or it fires
   twice); the file puts Space on A (`a`), and on a phone the player presses Space. No `action` intent is
   raised beside a pressed Space, so there is no reason left to delete the handler.
7. **Every work has the same few controls** (the Playspace set, runtime 1.34.0): the stick, A,
   B and the pill, each where section 0.5's file names it, with its word drawn in it; drawn by the player, never by
   the work. Never a button or a hint drawn over the frame by the glue. A game's own touch mode stays in its code; ours
   draws beside it and owns only its own controls (row 17). A game's own on-screen joystick that
   moves as the keys do is a repeat: leave `move` out and name the keys in `extra` as `repeat`.
8. **A second verb is B** (SDK 0.11): in the file it is `b`; in a glue's declaration `secondary: "Run"` (and
   `keys.secondary` where it must press the work's key), read as `{ type: "secondary", on }` as the action is read. What
   is held goes on B, what is tapped on A (a computer's Shift is B, and five Shifts open Sticky Keys on Windows). Past A
   and B there is the pill for the work's own menu key and nothing else: a verb with no control of the set is in
   `extra` with its reason, or the work does not fit the set (section 0.5). A declared `dash` stays a burst, never a
   stand-in for a held sprint. On a computer Shift and the right mouse button (SDK 0.12) are the second button
   already: a work whose sprint is Shift keeps that handler only where it is not also answering `secondary` (or it
   fires twice), as rule 6 says for Space; where B is live the browser's context menu does not open on the frame.
9. **Escape is the work's** (runtime 1.27.0): it reaches the work like any key on a computer,
   and the player's Home button is a button (a click, a tap), never a key. The Home button freezes the work underneath
   under the player's Home menu, which shows **nothing of the work's**, only what is the same on every work (Leave,
   Next, Save, Share, Sound and volume, Quality, About). The work's pause and resume logic also hangs on
   `playspace.on("pause")` and `on("resume")` (row 29); its own menus, pause screen, pause button, options, restart and
   game over stay whole (map, never remove), on their own keys, Escape included, and their own taps; on a phone a menu
   on Escape gets the pill in the file (`esc`, at the top left since runtime 1.34.0), `Escape` named like any key. Nothing
   of the work's own Esc is rebound. A captured mouse let go by the browser's Esc is the work's to answer
   (`pointerlockchange`); the player does nothing. **What the transcoder writes of a work's menus** (SDK 0.18.0): it inventories the work's pause,
   options and title menus and its HUD as a record and mirrors none of it:
   - **never** `menu.settings`, `modes`, `objective` or `stat` (the player records the calls of a work published
     before and draws them nowhere; the check records one by name, a measurement, never a refusal);
   - `playspace.menu({ score: { unit, better }, restart })` only where the work keeps a score or restarts without a
     reload, `on("restart")` calling its own restart (the end card's Play again and the board read them);
   - the work's own quality switch follows the player's Quality (row 36); volume needs nothing (the player's level sits
     above every sound the work makes); a mute of its own stays and hangs on `on("mute")` (row 43);
   - `end` (or `complete`) only at a real end (row 38); a game over the work retries from at once is a
     `moment("run_ended")` and a `score`, never an `end`.
10. **Words name the gesture, never a number**: "left stick moves", "drag to look", "push harder to dash", "hold a
    moment".

## 0.5 The control manifest: the Playspace set

Every work on Playspace is played with the same few controls, on a phone and on a computer:

| | On a phone | On a computer |
|---|---|---|
| Move (`move`) | the stick, bottom left, pressing the work's own move keys | W A S D or the arrows, both pressing the work's own move keys |
| A (`a`) | the large button, bottom right, pressing the work's own key | Space |
| B (`b`) | the smaller button, up and toward the edge | Shift (either) |
| The menu (`esc`) | the pill, top left, the work's word in it | Esc |
| The pointer (`pointer`) | a drag on the work (the mouse held, or the view turning) and a tap (the click) | the mouse and its click, the work's own |

### The file

**The file's version is 3** (`"v": 3`); the code's `playspace.layout({ v: 3, ... })` is a different thing (for `own`,
`avoid`, `select` and a captured look), never written into the file. `playspace.json`'s `"controls"` (`false` stays the creator's opt-out). Only `v` is required; each of `move`, `a`, `b`, `esc` is drawn
only where named:

    { "v": 3,
      "move":    { "keys": ["KeyW", "KeyS", "KeyA", "KeyD"], "alt": ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"], "word": "Move" },
      "a":       { "key": "Space", "word": "Jump" },
      "b":       { "key": "ShiftLeft", "word": "Run", "press": "switch" },
      "esc":     { "key": "Escape", "word": "Menu" },
      "pointer": "look",
      "click":   "Use",
      "fixed":   true,
      "extra":   [ { "key": "KeyH", "why": "unneeded" }, { "key": "Enter", "why": "repeat" } ] }

- `move.keys`: the work's own four keys (up, down, left, right); `alt` a second four it also reads; `word` at most 8.
- `a.key`, `b.key`, `esc.key`: the work's own key (a `KeyboardEvent.code`). `a.key` may be `"click"` (the left mouse
  button where the finger aims), `b.key` `"click2"` (the right). `press: "switch"`: one press holds, the next lets go;
  absent, held while the finger is down. Words at most 8 letters, the pill's at most 6 (Menu when none).
- `pointer`: `"mouse"` (the default: a finger is the mouse, a tap the click), `"look"` (a drag turns the view, a tap
  the click), `"own"` (the work's own touch: none of ours on the work), `"none"`. `click`: the word under the mouse on
  a computer. `capture: true` beside `"pointer": "look"` (0.28.0): on a computer a click takes the mouse and its
  movement turns the view, Esc gives it back, for a view from inside (rule 3); left out, a drag turns the view; a phone
  is the same either way. `fixed: true` for a layout that cannot adapt upright.
- A key in one control only, and not also in `extra` (`why`: `repeat` or `unneeded`); any other field drops the file.

### On a computer

The player presses Space, Shift, Esc and W A S D or the arrows on every work, and our runtime presses the work's own
key for each (Space presses 13th Floor's E, Shift its F); a small picture with no words shows which of those keys the
work uses (a mini keyboard with only them lit, the arrows, the mouse, a text field where the work takes typing),
centred at the stage's bottom for the first 6 s after the work's first picture and 3 s after each resume (runtime
1.44.0), so a HUD of the work's own at the bottom middle is covered only then. How it plays in Info and About says what
each key does; your words still name the phone's controls. The arrows always move (below); every other key the
work reads keeps working (E still opens the door). Only a manifest of the work's own is translated: with none, every
key reaches the work as pressed. What follows from that:

- **Where the work's own key is already Space, a Shift or Esc, it keeps it** and nothing is pressed for it (Racing
  Game's Boost on Shift and Drift on Space stay the browser's own). A then takes Space, else Shift; B Shift, else
  Space; the pill Esc. A key of those three that the work reads for something else (named in `extra`, or heard by the
  check) stays the work's, and its control takes the other key or none. Under a version 3 file Space, Shift and Esc
  press your keys only once the work calls `playspace.start()`: a title screen's "press Space" gets Space. The click on A (`click`) and the right click on B (`click2`) are the mouse's own and take no key.
- **The arrows are always W A S D.** Both press the stick's keys. A work that gives the arrows another meaning (a turn,
  an aim) keeps only the move on a computer; put that meaning on the mouse, A or B, or leave it in `extra`.
- **Held on Shift, tapped on Space.** On Windows five Shift presses in a row open Sticky Keys and take the focus, so
  what is held (run, boost, a modifier) goes on B and what is tapped (jump, use, fire) on A.
- **The letter case under Shift.** Where the work reads Shift itself, a real Shift held makes the browser say "W", not
  "w". A work comparing `event.key` to a lower-case letter then stops moving while the player runs. Do not change the
  creator's handler for it: say it in your report as advice to the creator (compare `event.code`, or lower-case the
  key). Where B is not the work's own Shift, the runtime sends W A S D as plain letters while Shift is down.
- **What Esc cannot promise.** With the mouse captured, or in full screen, the browser takes the first Esc and lets
  the mouse go (or leaves full screen); no page hears it. The work hears `pointerlockchange`. Esc is the work's menu
  key except for that first press; a work that pauses on losing the mouse needs nothing more.
- **Typing stays typing.** Nothing is pressed for the player while a field of the work has the focus, or with Ctrl,
  Meta or Alt held; a focused button or link of the work keeps Space (the rest of the set still presses your keys). Space and the arrows do not scroll the page where they have a
  control (a page that scrolls keeps its scroll).

### Which control suits which action

- **The default.** The stick is the move keys, A the most used verb's key, B the second's, a tap the click, a drag the
  mouse, the pill the work's own menu key.
- **The shooter.** A drag turns the view, so fire goes on A as the click (`"a": { "key": "click", "word": "Fire" }`);
  a held A passes its drag on as look, so one thumb fires and aims.
- **Aim at a point** (a finger on the work aims and fires where it rests): no button; the default pointer.
- **Up is jump.** A platformer whose jump is the up key gets Jump on A as well: a stick is poor at jumps.
- **Run on the rim.** A run that only speeds the walk is the stick pushed to its rim; B stays free.
- **A switch.** B as a switch where the computer holds a key while clicking (a painter's remove).
- **Held on B, tapped on A.** One thumb rolls from B onto A to press both; on a computer B is Shift (Sticky Keys,
  above).

### Four worked files

- **Musewalk** (W A S D and the arrows walk, Shift runs, a drag looks, a click travels, Q goes back):
  `{ "v": 3, "move": { "keys": ["KeyW", "KeyS", "KeyA", "KeyD"], "alt": ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"] }, "a": { "key": "ShiftLeft", "word": "Run" }, "esc": { "key": "KeyQ", "word": "Back" }, "pointer": "own" }`
- **13th Floor** (W A S D, a drag to look, E use, F light; on a computer Space presses E and Shift F):
  `{ "v": 3, "move": { "keys": ["KeyW", "KeyS", "KeyA", "KeyD"] }, "a": { "key": "KeyE", "word": "Use" }, "b": { "key": "KeyF", "word": "Light" }, "pointer": "look", "click": "Use" }`
- **Racing Game** (the arrows and W A S D drive, Shift boosts, Space drifts, R resets; C and H are a camera and a
  horn play does not depend on): Reset on the pill (Esc presses R on a computer; Shift and Space are its own).
  `{ "v": 3, "move": { "keys": ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"], "alt": ["KeyW", "KeyS", "KeyA", "KeyD"], "word": "Drive" }, "a": { "key": "ShiftLeft", "word": "Boost" }, "b": { "key": "Space", "word": "Drift" }, "esc": { "key": "KeyR", "word": "Reset" }, "extra": [{ "key": "KeyC", "why": "unneeded" }, { "key": "KeyH", "why": "unneeded" }] }`
- **Svelte Snake** (its own swipe turns the snake exactly as its arrows do): nothing of ours.
  `{ "v": 3, "pointer": "own", "extra": [{ "key": "ArrowUp", "why": "repeat" }, { "key": "ArrowDown", "why": "repeat" }, { "key": "ArrowLeft", "why": "repeat" }, { "key": "ArrowRight", "why": "repeat" }] }`

**The never-list line that outranks the rest:** never remove a control path, handler, menu, hint or touch mode the
creator built; it stays on its own key, and the set presses that key.

## 0.6 Autoplay: Buddy plays first

A visitor who opens a work and does nothing for 3 seconds sees Buddy play it: a few seconds of calm play with the
Playspace set, under a label of the player's ("Buddy is playing · touch to play"), until the visitor's first touch,
key, click or wheel takes over in that same input. It stops by itself after 30 seconds. It is a preview of what the
work is and of what each control does, never a show and never a speedrun. You write it once, in the build, as a small
policy; our runtime plays it beside the work at no cost per view. Nothing Buddy does is kept as a person's: while he
plays the SDK drops the work's scores, saves, stats, outcomes and moments (the work's own storage is yours to put back,
below).

For every work, decide one of two, and say which in your report under Wire the SDK, in one line that starts
`Autoplay:` (and the same line in NOTES.md):

- **A policy** (`Autoplay: a policy: <what Buddy does, in a few words>`): the call below, in the build, and the
  manifest's block `"autoplay": { "mode": "policy", "handover": "fresh" }` (or `"continue"`).
- **No autoplay** (`Autoplay: declined: <why, in one sentence>`): no call, and the manifest's block
  `"autoplay": { "mode": "off" }`. A declined work is a right answer where the list under "When to decline" says so:
  it is never a failure, and the work publishes and plays as always.

A creator's own `playspace.autoplay(...)` in the source is theirs: keep it, write none beside it. A work's own attract
mode or demo is the work moving by itself (below).

### The call

`playspace.autoplay(policy)`, once (a second call is ignored), where the work's state is in scope: beside the code
that makes the game (the Svelte component, the scene's setup, the adapter where it reaches the work's objects). It
returns true when the policy is kept. The policy:

    playspace.autoplay({
      handover: "fresh",                                    // or "continue": below
      map: { move: ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"], a: "Enter" },  // only where nothing else names a key
      start: [["tapText", "Play"], ["wait", 800]],          // once, past a title
      every: 150, rule(c, s) { /* each `every` ms: read the work's own variables, press the set */ },
      // or, in place of `rule`: loop: [["stick", 0, -1, 900], ["wait", 600]],   (for ever)
      reset() { /* the work's own way back to its start */ },
    });

- **Steps** (`start`, `loop`): `["stick", x, y, ms]` holds the stick at x, y (-1..1, up negative) for `ms`, then the
  next step (`["stick", 0, 0, ms]` lets it go); `["a", ms]` and `["b", ms]` press A or B for `ms`; `["tap", x, y]` and
  `["drag", x0, y0, x1, y1, ms]` on the work (x and y 0..1 of the frame); `["tapText", "Play"]` clicks the work's own
  control whose text is exactly those words (case aside); `["wait", ms]`. `start` runs once; then `rule`, or `loop`
  for ever. A step's `ms` is by the clock, not by frames or ticks: a 2 s drag lasts about 2 s on a slow phone too.
- **A rule** (`rule(c, s)`): called every `every` ms (50 to 5,000; 250 when absent), after the last call settles (it
  may return a promise). `s` is a scratch object of its own between calls. `c` is the controller.
- **The controller, the set and nothing else**: `c.stick(x, y)` (held until the next `stick`; past 0.4 on an axis is
  that direction's key down), `c.a(on)` and `c.b(on)` (held), `c.press("a" | "b", ms)` (90 ms when absent),
  `c.tap(x, y)`, `c.drag(x0, y0, x1, y1, ms)`, `c.tapText(words)` (true where it found the control), `c.reset()`,
  `c.now()` (ms since Buddy began). No key by name, no Esc, no menu, no pointer lock: what he cannot do with the set
  he does not do.

### The keys he presses

The stick, A and B press the work's own keys, each from the first of these that names one:

1. the build's manifest (section 0.5): `move.keys` in its order up, down, left, right; `a.key`; `b.key`;
2. the work's own `playspace.layout()` keys (`forward`, `back`, `left`, `right`, `action`, `secondary`);
3. the policy's `map`: `move` in the same order up, down, left, right, and `a`, `b`.

A control with no key from any of the three presses nothing. `map` never replaces a key the manifest or the layout
names; it is for a work whose manifest leaves a key out, as Svelte Snake's does (its own swipe is the phone's, so its
arrows are `extra`, and its policy's `map` names them). A manifest's `"click"` or `"click2"` on A or B is the mouse's,
not a key: for that, `tap` or `drag` on the work. A tap or a drag goes to the work's element under the point, never to
our controls; Buddy never presses through our touch layer.

### Read the work's own state

You write inside the build, so a rule reads the work's own variables: the snake's head and the food, the car's
position on the track's checkpoints, the level's state. Never the pixels (a canvas read many times a second costs a
phone its battery, and a WebGL canvas cannot be read at all). Keep a rule cheap: a few variables, one decision, then
the set. Where the state is not reachable (a minified bundle with no globals), write steps, or decline.

### Fresh or continue, and the reset

- **`"fresh"`** for a work with a score, a clock, lives or a run: the visitor's first touch is spent on `reset()` and
  their game starts from the beginning, as an arcade's coin starts a fresh game. Buddy's score is not theirs.
- **`"continue"`** for a toy, a walk, a viewer, a painter: the first touch passes through as the visitor's first input,
  and they carry on from where Buddy is.

`reset()` is the work's own way back to its start: its restart function, its new game, its level reload. Never a page
reload (the visitor sees a flash and loses the load). **Put back what Buddy stored in the work's own storage**: a best
score, a save, an unlocked level. Read that storage once, where you register the policy (before Buddy plays), and
write it back in `reset()`; in the work's memory too, where the work keeps a copy (Snake kept "best: 18", Buddy's, as
the visitor's in the first trial). An error in `reset()` is caught; the visitor plays on.

### Past a title, and the pace

- **A title or a "click to start"**: `start` steps, `["tapText", "<the work's own words>"]` then a wait for the scene.
  Under a version 3 manifest Buddy may play before the work calls `playspace.start()`: his `start` steps are what pass
  the title. Sound stays off until the visitor's own touch (the browser's rule); a work that needs a gesture to make
  sound plays silent for Buddy, and that is fine.
- **The pace: slow and calm.** Hold the stick for most of a second, wait between moves, turn the view slowly. In the
  first ten seconds show each control the work uses once (move, then A, then a look), so the visitor learns what the
  set does on this work by watching. A careful player, not a fast one. A rule that steers an arcade game at its own
  speed is fine; a rule that presses ten keys a second is not.
- **Never stand still.** The check fails a picture that does not change for 5 seconds while he plays. After a game
  over, press the work's own way on (a key the set reaches, `tapText` on its "Play again"). A rule stuck against a
  wall should turn, or call `c.reset()`.

### What the check watches

After the check's own play, where the build registered a policy and the manifest does not say `"mode": "off"`, the
check loads the build afresh on each device (the phone first, then the computer), with no input of its own, waits for
Buddy, and watches his 30 seconds: a picture every 0.4 s (our controls hidden: only the work's picture counts), the
keys he pressed and his own reports. It fails him with one of these, in these words:

- `he never started` (no policy registered in time, or it never began: within 30 s of the work being armed)
- `his plan stopped with an error` (the rule threw; Buddy stops and the work is left as it is)
- `he stopped by himself after N s` (he ended before his 30 s)
- `he left a key held down (KeyW)` (a key still down at the end)
- `the picture never changed while he played`
- `the picture stood still for N s while he played` (5 s or more)

A picture reading that fails is read once more before it counts. The row's verdict is `pass`, `fail` with the device
and the reason (`on a phone, the picture stood still for 7 s while he played, both times he was watched`), or `unread`
(no time left to watch him again). `measure` and `measure --full` print the row: one line per device (when he started,
how long he played, the longest still stretch, the keys pressed by count) and the verdict, starting `autoplay`. A
policy that does not pass is simply never played for a visitor: the work publishes as always. Read the reason, change
the policy, build, measure; or decline. A reviewing model also looks at pictures of his play: calm, competent, showing
the controls, so that someone watching for ten seconds understands what the work is and that they can take over.

### When to decline

- **Music and rhythm works** (an instrument, a beat game): play without the sound means nothing, and the sound waits
  for a touch.
- **A puzzle past its first move or two**: show the first move, then nothing more; where even that spoils it, decline.
- **A skill the policy does not have**: a driving game on a real track, a platformer's jumps, a shooter's aim, unless
  the rule reads what it needs from the game's own data (the track's checkpoints, the platforms' positions) and the
  check passes it. A blind policy that crashes into the first bend looks broken, and a broken preview is worse than
  none.
- **A work that already moves by itself** (a fluid, a shader, a scene that animates, the work's own attract mode) and
  needs no input to be alive.
- **A work whose play is typing, or a form**: there is nothing for the set to show.

### Two worked policies

- **Svelte Snake** (an arcade rule on the game's own state; `"fresh"`). In `App.svelte`, after `const game = new
  Game(...)`: its manifest leaves the arrows to the work's own swipe (`extra`), so `map` names them; Enter is the
  work's own "new game" after a game over; the best score is put back.

      const storage = getAppContext('storageService'), best = storage.highScore;   // read before Buddy plays
      const DIRS = { up: [0, -1], down: [0, 1], left: [-1, 0], right: [1, 0] };
      playspace.autoplay({
        handover: "fresh",
        map: { move: ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"], a: "Enter" },
        every: 150,
        rule(c) {
          if (game.currentGameState.gameOver) return c.press("a", 100);        // the work's own new game
          const N = game.config.gridSize, h = game.snake.head, f = game.food.position, body = game.snake.parts;
          const free = (x, y) => x >= 0 && y >= 0 && x < N && y < N && !body.some((p) => p.x === x && p.y === y);
          let pick = null, far = Infinity;
          for (const [name, [dx, dy]] of Object.entries(DIRS)) {
            if (!free(h.x + dx, h.y + dy)) continue;
            const d = Math.abs(f.x - h.x - dx) + Math.abs(f.y - h.y - dy);
            if (d < far) { far = d; pick = name; }
          }
          if (pick && pick !== game.snake.direction) { c.stick(...DIRS[pick]); c.stick(0, 0); }   // one press of its arrow
        },
        reset() {
          game.restart();
          storage.highScore = best;                                            // the work's own storage, as it was
          gameState.update((s) => ({ ...s, highScore: best }));                // and its copy in memory
        },
      });

  Manifest: `"autoplay": { "mode": "policy", "handover": "fresh" }`. Report: `Autoplay: a policy: steers the snake
  to the food from the game's own board, a new game after each game over`.

- **Musewalk** (a walk's steps; `"continue"`). Past its title by its own words, then a slow look and a step, again
  and again; its manifest names W A S D, so no `map`; nothing to put back.

      playspace.autoplay({
        handover: "continue",
        start: [["tapText", "Enter the Museum"], ["wait", 3500]],
        loop: [["drag", 0.7, 0.45, 0.5, 0.45, 2200], ["wait", 1200], ["stick", 0, -1, 900], ["stick", 0, 0, 1000],
               ["drag", 0.4, 0.45, 0.66, 0.46, 2600], ["wait", 1200], ["stick", 0, 1, 800], ["stick", 0, 0, 900]],
      });

  Manifest: `"autoplay": { "mode": "policy", "handover": "continue" }`. A declined one, for contrast: Qwertone
  (`Autoplay: declined: an instrument played by the letter rows; silent, Buddy's notes would show nothing`), manifest
  `"autoplay": { "mode": "off" }`.

## 0.7 Text entry

A work may take typed text on a computer and on a phone: a name for a score, a line of chat, a search, an editor. The
controller stays the Playspace set; letters as game controls are still over it (section 0.5). Text is the work's own field and
the device's own keyboard, never a control: there is no SDK call and no manifest entry for it.

- **Use your own field.** An `<input>` of a type that takes text (`text`, `search`, `email`, `url`, `password`,
  `number`, `tel`, or no type), a `<textarea>`, or a `contenteditable` element, on your own page and in your own
  style. A range, a checkbox or a select is not a text field.
- **On a phone, focus it from a touch.** iOS raises the keyboard only for a focus inside a person's touch: a field
  the person taps, or your `field.focus()` called in the touch's own handler. A `focus()` from a timer, after an
  `await` or at load raises no keyboard (and the player keeps its controls shown for it). On a computer a focus at
  load is fine.
- **Give it a `maxlength`.** The cap is the field's own, which the browser applies to typing and to paste and which
  never breaks a composed character: a name 24, a line 280, a text area 2,000. Nothing caps it for you.
- **Say what Enter does** with `enterkeyhint` (`done` for a name, `send` for a chat line, `search` for a search) and
  answer Enter yourself (submit, send, a new line); the player does nothing with it.
- **A name is not a sentence.** On a name field set `autocomplete="off" autocorrect="off" autocapitalize="off"
  spellcheck="false"`: iOS autocorrected "wasd" to "Wash" with none of them.
- **Let it go when done.** On submit call `field.blur()`, so the keyboard closes and the player's controls come back
  (hiding or removing the focused field does the same).
- **Put the field in the top half of the screen.** Sideways the phone's keyboard covers about half the height; a
  field low on the screen is pushed out of view or sits under the keys.
- **Never read letters with a window `keydown` listener** for a name or a line: read the field's `value` (or its
  `input` event). A window listener also hears W A S D while the person types; where your play moves on keys, check
  the event's target first (`if (e.target.closest("input, textarea, [contenteditable]")) return;`).

**What the player does while your field has the focus.**

| | A computer | A phone |
|---|---|---|
| Keys | Every key goes to your field as typed; nothing of the set is translated. | The phone's own keyboard types. |
| Our controls | The controls picture is hidden (from then on it shows the text field too; back for 3 s when the focus leaves). | The stick, A, B and the pill are hidden and every key they held is let go (when the focus followed a touch); back when the focus leaves. |
| A touch or click elsewhere | The browser's own. | The touch reaches your work first (your Continue's click reads the field), then the field is let go (blurred) if it still has the focus; a touch in the small box around the field (an editor's own buttons) keeps it. |
| Esc | The first Esc is yours; if your field still has the focus after your handlers ran and you did not prevent it, the player lets it go (never during a composition). The next Esc is your menu key as always. | The keyboard's own Done or hide key. |
| The pause | Pausing lets the field go. | The same. |
| Buddy (autoplay, section 0.6) | Never starts while a field has the focus and presses no key then; a key or touch on a field is never spent by a `"fresh"` hand-over. | The same. |

Our runtime never reads, records or sends what is typed: a key typed in a field is not counted in the runtime's
`keyed`, and the player is told only that a field has the focus (`typing`, on or off). Keep the field in your own
page (an open shadow root is fine): one inside a closed shadow root or an `<iframe>` of your own is not seen as a
field, so the player's controls stay up and its keys may be counted as keys.

## 1. The idiom table

Each row: the idiom and the corpus work it was found in, what it becomes, the original's line and the block's line
(quoted from `packages/seeds/corpus/<work>/contract/`), and the row that proved it.

| # | Idiom, where found | What it becomes | Before (the original's line) | After (the block's line) | Proved by |
|---|---|---|---|---|---|
| 1 | A held-key table by `event.code`, read each frame (games_fps `keyStates`; Starter Kit Racing `this.keys[ e.code ]`) | The listeners and the four branches deleted; the axes read where the table was read, analog, in the camera's frame | `keyStates[ event.code ] = true;` … `if ( keyStates[ 'KeyW' ] ) { playerVelocity.add( getForwardVector().multiplyScalar( speedDelta ) ); }` | `const mx = playspace.input.axis( 'moveX' ), my = playspace.input.axis( 'moveY' ); playerVelocity.add( getForwardVector().multiplyScalar( - my * speedDelta ) ); playerVelocity.add( getSideVector().multiplyScalar( mx * speedDelta ) );` | games_fps P2, D1; Starter Kit written, not live (CORPUS.md note 1) |
| 2 | A `keyCode` table with a conversion map (UNDERRUN `key_convert`, `_document.onkeydown`) | The handlers deleted; the digital `ax`/`az` become the axes times the speed | `t.ax = keys[key_left] ? -speed : keys[key_right] ? speed : 0;` | `t.ax = playspace.input.axis('moveX') * speed; t.az = playspace.input.axis('moveY') * speed;` | UNDERRUN P2, D1 |
| 3 | A key-axis library feeding physics (Astray `KeyboardJS.bind.axis`) | Both bindings and their callback deleted; the pair read before the impulse (Box2D's y is up: the stick's down is positive) | `KeyboardJS.bind.axis('left', 'right', 'down', 'up', onMoveKey);` | `keyAxis = [playspace.input.axis("moveX"), -playspace.input.axis("moveY")];` and `playspace.layout({ v: 3 });` | Astray P2, D1 (the arrows still roll it: the SDK's axis reads them) |
| 4 | A key table in a minified bundle with no globals (racing-game, a React bundle; `keyMap[event.key.toLowerCase()]`) | The declaration is the whole transcode: the keys named, every verb digital; the SDK holds the forward key, presses the sides past 0.35, the stick's down presses `back`, the button holds the action's key, a double tap pulses `doubleTap`'s key, a push past the rim pulses `dash`'s | (the bundle's table, unreadable) | `ps.layout({ v: 3, forward: "always", keys: { forward: "ArrowUp", back: "ArrowDown", left: "ArrowLeft", right: "ArrowRight", action: "Space", doubleTap: "KeyR", dash: "ShiftLeft" }, action: "Brake" });` and no other line | racing-game P1, P2, P6; D1 by the game's own keys |
| 5 | Pointer lock and `movementX`/`movementY` at a gain (games_fps, 1/500 rad per px) | The lock request, the locked `mousemove` and the `mouseup` deleted; the look applied to the camera's own Euler angles, pitch clamped | `container.addEventListener( 'mousedown', () => { document.body.requestPointerLock(); ... } );` … `camera.rotation.y -= event.movementX / 500;` | `playspace.layout( { v: 3, action: 'Jump', look: { computer: 'capture' } } );` and `playspace.camera.onLook( ( yaw, pitch ) => { camera.rotation.y -= yaw; camera.rotation.x = Math.max( - Math.PI / 2, Math.min( Math.PI / 2, camera.rotation.x + pitch ) ); } );` | games_fps P3, D2 (the drag), D6 (the SDK's captured look, 0.9.2) |
| 6 | The same, minified, with no globals (13th Floor, its own engine; 0.001 rad per px onto `cameraRotation`) | A glue: the fallback's mouse units named for the computer's lock, the look applied on a touch screen only, the lock left the original's | `tmpl.requestPointerLock()` on `document.onclick`; `cameraRotation` from `movementX` (the bundle's) | `ps.layout({ v: 3, avoid: [], look: { radPerPx: 0.001, mouse: "movement" }, keys: { forward: "KeyW", doubleTap: "KeyF" } });` … `if (i.type === "look") { ... r.y = (r.y - i.yaw) % (Math.PI * 2); r.x = Math.max(-PITCH, Math.min(PITCH, r.x + i.pitch)); ... return true; }` | 13th Floor P3; D2 by its own lock |
| 7 | An engine camera with its own key, mouse and touch inputs (Babylon `UniversalCamera.attachControl`: Valley Village, Pirate Fort) | The inputs cleared, the key codes and the sensibility deleted; the look onto `camera.rotation` (left-handed); the stick into `cameraDirection` at the engine's own speed, so its collisions and gravity stay | `camera.angularSensibility = 2500;` … `camera.keysUp.push(87);` … `camera.attachControl(canvas, true);` | `camera.inputs.clear(); ps.layout({ v: 3 }); ps.camera.onLook(function (yaw, pitch) { camera.rotation.y += yaw; camera.rotation.x = Math.max(-1.4, Math.min(1.4, camera.rotation.x - pitch)); });` and each frame `camera.cameraDirection.x += (Math.sin(ry) * -my + Math.cos(ry) * mx) * v; camera.cameraDirection.z += (Math.cos(ry) * -my - Math.sin(ry) * mx) * v;` with `v = camera._computeLocalCameraSpeed()` | Valley Village P2, P3, D1, D2 |
| 8 | An engine controller with several input sources (PlayCanvas `FirstPersonController`: `KeyboardMouseSource({ pointerLock: true })`, `DualGestureSource()`, `GamepadSource()`; Courtyard) | A subclass: the sources destroyed in `initialize`, one `InputFrame` built from the contract each `update`, the controller's own physics called with it; the look accumulated in degrees | `cc.script.create(FirstPersonController, { properties: { camera, jumpForce: 650, speedGround: 40 } });` | `class ContractController extends FirstPersonController { initialize() { super.initialize(); this._desktopInput.destroy(); this._mobileInput.destroy(); this._gamepadInput.destroy(); } update(dt) { ... this.frame.deltas.move.append([mx * speed, 0, -my * speed]); this.frame.deltas.rotate.append([look[0], look[1], 0]); this.frame.deltas.jump.append([jump]); ... this._updateController(this.frame, dt); } }` with `ps.camera.onLook((yaw, pitch) => { look[0] += yaw * 180 / Math.PI; look[1] -= pitch * 180 / Math.PI; });` | Courtyard P2, P3, P6, D1 to D4 |
| 9 | Space to jump, a held key read on the floor (games_fps; Courtyard) | `action: "Jump"`; the `action` intent's `on` kept in a flag the work's own jump test reads | `if ( playerOnFloor ) { if ( keyStates[ 'Space' ] ) { playerVelocity.y = 15; } }` | `playspace.layout( { v: 3, action: 'Jump' } );` … `if ( i.type === 'action' ) { jumpHeld = i.on; return true; }` … `if ( playerOnFloor && jumpHeld ) playerVelocity.y = 15;` | games_fps P6, D4 |
| 10 | The work's own Space handler kept beside a declared `action` (ON/OFF's flip; Bunny Jump's restart) | Kept (map, never remove): the file puts Space on A (`a`) and the player presses it on a phone; the work's handler answers the verb on both devices, so no `onIntent` branch answers it too (it would fire twice) | `if (event.key === ' ') this.toggle()`; `this.input.keyboard.once('keydown-SPACE', () => { this.scene.start('game') })` | `if (i.type === 'action') { if (i.on && !this.scene.hidden && !this.scene.paused) this.toggle(); return true }`; `playspace.layout({ v: 3, action: 'Restart' })` with, on `i.type === 'tap'` or `action` on, `off(); this.scene.start('game'); return true` | ON/OFF D4 (Space flips once); Bunny Jump P6 |
| 11 | A platformer's up is its jump (ON/OFF `upKey`; a 2D game has no forward) | The stick's up into the jump key's reading at -0.5, its sides at ±0.35; the button is the second verb | `export const upKey = () => (` `DOWN.has('w')`, `DOWN.has('ArrowUp')`, the gamepad's `PRESSED.has(0)`, `PRESSED.has(12)` `)` | `axis('moveY') < -0.5` OR-ed onto `upKey`, with `const axis = (name) => window.playspace.input.axis(name)`; `axis('moveX') < -0.35` onto `leftKey`, `> 0.35` onto `rightKey`; `ps.layout({ v: 3, action: 'Flip', select: { hit } })` | ON/OFF P2 (left walks, forward jumps), P6, D1 |
| 12 | Phaser's cursor keys on one axis (Bunny Jump `createCursorKeys()`) | The axis read in `update` and OR-ed into each cursor's test at 0.35 (digital, as the game reads) | `if (this.cursors.left.isDown && !touchingDown)` | `const mx = playspace.input.axis('moveX')` at the top of `update`, then `mx < -0.35` OR-ed onto `this.cursors.left.isDown` and `mx > 0.35` onto `this.cursors.right.isDown` | Bunny Jump P2; D1 (the cursors and the axis agree, no double; the picture red by the bounce, note 2) |
| 13 | A racer's throttle key (HexGL's ArrowUp; racing-game's forward) | The throttle is a held key on the stick's up (the manifest's `move` keys): the work's own throttle stays as it is, the stick's up holds it, its sides steer, its down brakes. `forward: "always"` is gone from what a transcode writes (a work's own published declaration still reads) | `ShipControls` on `keyCode` 38, 37, 39 (the bundle's) | `var keys = { forward: "ArrowUp", left: "ArrowLeft", right: "ArrowRight" };` … `var menu = { v: 3, forward: "always", keys: keys, ... }; ps.layout(menu);` (the `...` is the Menu button row 34 forbids) | HexGL P2 (forward held), D1 (the arrows named: the check presses them); racing-game P2 |
| 14 | A racer with its own analog steer and ramped pedals (APEX FORMULA `SteeringModel`, `PEDAL_RISE`) | `forward` through the game's own held forward key; the `steer` intent handled with its x into the game's analog steer (the digital side keys never pressed); the brake its `back`; the DRS the button | `inp.steer = clamp(this.steering.output() + this.pad.steer, -1, 1);` | `ps.layout({ v: 3, forward: 'always', keys: { forward: 'KeyW', back: 'KeyS', left: 'KeyA', right: 'KeyD' }, action: 'DRS' });` … `if (i.type === 'steer') { this.stickSteer = -(i.x ?? 0); return true; }` … `inp.steer = clamp(this.steering.output() + this.pad.steer + this.stickSteer, -1, 1);` | APEX written, not live (note 1) |
| 15 | Extra place-less verbs: two air brakes, a reset, a boost (HexGL Q and E; racing-game R and Shift; APEX Backspace) | The held one on B (`b`; on a computer B is also Shift and the right mouse button, SDK 0.12; a shooter's aim on B is a switch on a phone, rule 8); the most needed other verb on A; every verb past A and B and the pill is in `extra` with its reason, or the work does not fit the set (section 0.5): HexGL's two brakes on A and B (KeyQ and KeyE, held), its Restart on the pill or in `extra`; never folded onto the tap, the double tap or the dash | `keyCode` 81 and 69 on the document (HexGL); `reset r`, `boost shift` (racing-game's map) | `if (i.type === "tap") { if (steer > 0) brake("KeyE", 69); else brake("KeyQ", 81); return true; } if (i.type === "doubleTap") { if (steer > 0) brake("KeyQ", 81); else brake("KeyE", 69); return true; }`; `doubleTap: "KeyR", dash: "ShiftLeft"`; `if (i.type === 'doubleTap') { if (this.drivingEnabled) this.resetQueue++; return true; }` | HexGL P4, P6 dimmed (the brakes have a side); racing-game P6 |
| 16 | Aim at the pointer, fire on `mousedown` (UNDERRUN `mouse_x`, `key_shoot`) | `holdDrag: "drag"`: a hold fires where it rests, its drag aims, a tap fires once at the point (on a touch screen only: a click's real `mousedown` already fires); the mouse handlers stay for a computer | `_document.onmousedown` → `keys[key_shoot] = 1` with `mouse_x` from `onmousemove` | `playspace.layout({ v: 3, holdDrag: 'drag' });` … `if (i.type == 'hold') { aim_at(i); keys[key_shoot] = i.on ? 1 : 0; return true; } if (i.type == 'drag' && i.from == 'hold') { aim_at(i); if (i.phase == 'end') keys[key_shoot] = 0; return true; }` with `mouse_x = (i.nx + 1) / 2 * c.width; mouse_y = (1 - i.ny) / 2 * c.height;` | UNDERRUN P4; P3 none (`view` false: the drag is the aim); D3 (one click) |
| 17 | A game's own virtual joystick or touch mode (Starter Kit `setupTouchUI()`; HexGL's 2012 touch mode on by `isTouchDevice()`) | Kept: the work's own touch mode stays in its code; the file says `"pointer": "own"`, no stick of ours where its own touch already moves, and only a needed verb its own touch cannot reach gets a control of the set; nothing is switched off | `this.setupTouchUI();` … `if ( this.touchActive ) { ... x = ( jx + jy ) * Math.SQRT1_2 / mag; ... }` | Nothing of it deleted: `ps.layout({ v: 3, own: true });` and the file's `"pointer": "own"`; a key its own touch already carries is left out as a `repeat`, a key it has no touch for is A or B (HexGL's seed since its re-proof, its own touch steering kept, the old seed's rewrite to our stick and its Controls item clicked round to KEYBOARD retired) | HexGL P7, P1; Starter Kit written (note 9) |
| 18 | An Enter-only menu drawn in SVG (ON/OFF `.menu .item` groups) | `select: { hit }` with the items' boxes (`select.targets` misses an SVG group: `elementFromPoint` hits painted strokes only); a handled `select` chooses; a tap after the last level is the work's Enter | `title.js`: ArrowUp and ArrowDown select, Enter chooses | `const hit = (p) => [...document.querySelectorAll('svg:not([hidden]) .menu .item')].find((el) => inside(el, p))` (null when none) … `if (i.type === 'select') { if (!this.title.hidden) { this.title.selected = this.title.items.indexOf(i.target); this.title.choose(); return true } ... }` … `if (i.type === 'tap' && !this.scene.hidden && this.scene.finished) { this.scene.keydown({ key: 'Enter' }); return true }` | ON/OFF P4 (the menu's item), D3 |
| 19 | A DOM point-and-click where nothing reads keys or touch (Elematter: `click` on tiles, towers, menus) | `{ v: 3 }` is the whole transcode: no stick and no disc drawn (SDK 0.16), a tap is the click where it lands; hover previews do not fire on touch (noted, not replaced) | `g.on(el, "click", ...)` (the bundle's) | `ps.layout({ v: 3 }); ps.ready();` | Elematter P1 (dimmed, the touches the work's), P4, D3 |
| 20 | "Click to start", "Press Enter", an `<a href="#">` intro (13th Floor, HexGL `#start`, racing-game `.start-link`, APEX's title) | Nothing: the first tap passes through as the click; a title whose items confirm on their click is left as it is; the check's `start` recipe reaches play behind a menu | `document.onclick` starts it; `nav.ts`: `click` confirms | `if (!ready()) return false; // the start screen: the tap passes through as the click that starts the game`; `return false; // a tap is the click where it lands (every menu item confirms on its click)` | 13th Floor P4; HexGL, racing-game, ON/OFF by their `start` recipes |
| 21 | A toy that reads its own touch (The Cube: `touchstart` on the game element, a drag flips a layer, a double tap starts) | `own: true`: every finger the work's (every first finger before SDK 0.17.0), no stick and no disc drawn; the SDK keeps the viewport meta and `touch-action: none`; nothing of the input touched | `Draggable.js`: `touchstart` and `mousedown` on the element, `touchmove` prevented on the document | `ps.layout({ v: 3, own: true }); ps.ready();` | The Cube P1, P2 (the drag reaches the cube), D3 |
| 22 | A tap that must carry what it hit (Pirate Fort, made on the contract: a cannon to fire) | `select: { hit }` over the engine's own pick; a handled `select` is the tap. Babylon's pick takes the canvas's CSS px (note 8); three.js's raycaster takes `p.nx, p.ny` | (none: made on the contract) | `ps.layout({ v: 3, select: { hit: function (p) { var r = canvas.getBoundingClientRect(), h = scene.pick(p.x - r.left, p.y - r.top); return h && h.hit && h.pickedMesh && h.pickedMesh.name.indexOf("cannon") === 0 ? h.pickedMesh : null; } } });` … `if (i.type === "select") { start(); fire(i.target); return true; }` | Pirate Fort P4 (a `select` handled on the cannon) |
| 23 | A fixed canvas (13th Floor 1920 by 1080; Bunny Jump 480 by 640 with no scale manager; UNDERRUN 320 by 180) | The engine's scale manager, or the canvas sized from the live viewport by the work; never the SDK. A canvas the work already CSS-scales is left alone | `width: 480, height: 640,` and no `scale` | `scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH },`; 13th Floor's `layoutCanvas()` sizes `#c3d` to `window.innerWidth` by `window.innerHeight` and refits the projection; UNDERRUN untouched | Bunny Jump P1; 13th Floor P1 |
| 24 | A vertical field of view made for 16:9 (HexGL's chase camera 70; Valley Village 57.3; Courtyard 80; Starter Kit 40) | Never rewritten: the work's own field of view stays; `playspace.camera.fovFor(base, aspect)` is there for a work that asks for it, never written into one that does not | `camera.fov = 1.0;` (Babylon); `new THREE.PerspectiveCamera( 40, aspect, 0.1, 60 )` | `camera.fov = ps.camera.fovFor(57.3, window.innerWidth / Math.max(1, window.innerHeight)) * Math.PI / 180;`; `new THREE.PerspectiveCamera( playspace.camera.fovFor( 40, window.innerWidth / window.innerHeight ), ... )`; `c.fov = ps.camera.fovFor(70, c.aspect); c.updateProjectionMatrix();` | Looked (each work); Valley Village P1 |
| 25 | The work's HUD on the player's corners (Starter Kit's `#lap-timer` top left, `#editor-link` lower right) | The HUD's own CSS stays (a CSS file beside the build that a transcode wrote before stays too; nothing new moves the work's HUD); a HUD under the pause corner or a place is declared in `avoid` (row 41) and stays; its buttons, links and fields stay tappable by the pass-through | `#lap-timer` at the top left | `html body #lap-timer { top: 72px; left: auto; right: 12px; } html body #editor-link { right: auto; left: 50%; transform: translateX(-50%); }` | Starter Kit written (note 9); P7 is the rule |
| 26 | The lifecycle from the work's own state (every work) | `ready()` after the first frame or the world's load; `gameplayStart()` at the first movement or the run's start; `score(n)` where the work counts; `complete({ score })` where the run ends; `progress(step, of, label)` where there are steps | `fade in` draws the first frame (Astray); `handleCollectCarrot` counts (Bunny Jump) | `if (!shown) { shown = true; playspace.ready(); }`; at the first nonzero axis `{ started = true; playspace.gameplayStart(); }`; `playspace.score(this.carrotsCollected)`; `playspace.complete({ score: this.carrotsCollected })` before `this.scene.start('game-over')`; `ps.progress(1, 2, "Reach the cannon");` | Looked (the end card) |
| 27 | A minified game that calls its methods through `this` (Elematter `g.play`; The Cube `window.game`) | An own property on the instance is the hook: the method kept, wrapped, the lifecycle said from what it did | `this.advanceWave()`, `this.state.removeLife()` (the bundle's) | `var st = window.g && window.g.play;` … `var advance = st.advanceWave; st.advanceWave = function () { var first = !this.hasPlayed; var r = advance.apply(this, arguments); if (first && this.hasPlayed) ps.gameplayStart(); ... return r; };`; `g.timer.start = function (cont) { var r = start.apply(this, arguments); if (cont) ps.gameplayStart(); return r; };` | Looked |
| 28 | A bundle with no globals at all (13th Floor: one minified module, its controller and player module locals) | A one-time setter on `Object.prototype` for a property only that class assigns in its constructor, lifted at the first assignment; the per-frame read wrapped. If a hook never fires, the declaration's defaults stand; where nothing can be hooked, `ready()` alone and the row says so | (nothing reachable) | `hook("inputDirection", function (c) { ... ctl = c; var query = c.queryController; c.queryController = function () { query.call(this); frame(); }; }); hook("feetCenter", function (p) { player = p; });` | 13th Floor P2, P3 |
| 29 | The player's pause and resume (APEX `pause(paused)`; Courtyard `app.timeScale`; Valley Village's render loop) | The work's own pause called from the player's events; the runtime holds `requestAnimationFrame` and timers regardless, so `dt` is clamped | `this.pause(true)` on its own Escape | `ps.on('pause', () => this.pause(true)); ps.on('resume', () => this.pause(false));`; `ps?.on('pause', () => (app.timeScale = 0)); ps?.on('resume', () => (app.timeScale = 1));` | P5 (every work) |
| 30 | An adapter from before the SDK (UNDERRUN's `playspace-adapter.js`: the score, then the old stop call) | One call: `complete` with the score | `ps.score(total);` then the old stop call | `ps.complete({ score: total });` | Looked |
| 31 | A work that moves by itself (a racer under `forward`; a bouncing jumper) | Nothing in the work: the picture oracle reads the self-motion as the stick's (HexGL's race rows read on the computer only, its phone rows on the menu; Bunny Jump D1 red by the bounce). The transcoder's own verification reads the work's movement (the axes read, a key handled) beside the picture | | | CORPUS.md note 2 |
| 32 | A declared work and the stick's light (racing-game names its keys; Elematter names and reads none) | Lit by the read or the named `keys` only: Elematter's stick is not drawn (dimmed before SDK 0.16) though the check recorded the arrows scrolling its page (`f34c8ea`); racing-game's is lit and D1 presses the arrows it names | | `keys: { forward: "ArrowUp", ... }` (lit); `ps.layout({ v: 3 })` with no read (not drawn) | racing-game D1; Elematter P1 |
| 33 | A glue on a computer (13th Floor, HexGL, Elematter, The Cube, racing-game) | The gate after the declaration: the original's keys, mouse and lock stay single; a declaration-only glue needs none | | `ps.layout(menu);` … `if (!ps.touch.device) return;` | 13th Floor D1 to D3 by the original; racing-game D1 |
| 34 | Escape as the work's pause, back or menu (APEX; HexGL's menu; ON/OFF's back) | The work's own on a computer since runtime 1.27.0 (the runtime no longer takes Escape; from 1.13.0 to 1.26.0 it was unreachable), and on a phone the pill (`esc`) may name `Escape`; the pause also from row 29, the menus from row 20. The work's own pause menu, pause button and options stay: its pause and resume also hang on `on("pause")` and `on("resume")`, its menu is reached by its own Escape, its key on the pill or its own taps, and nothing of it is mirrored onto ours. HexGL's declared Menu button (a `controls` entry, Escape, top right) broke P7 and is the mistake this page forbids (note 3; since SDK 0.9.1 the word draws nothing and the glue's row is gone) | `Escape` → `pause` when driving else `menu-back` (APEX) | (nothing: rows 20 and 29) | P7 |
| 35 | The hint line that names a mouse and keys (Valley Village, Courtyard, games_fps `#info`, 13th Floor "Click to Start") | Left as it is (map, never remove); the player shows the set's words, so the work's own words stand | `Drag or click to look around. WASD or the arrow keys to walk.` | Under `"drag"`: `Left stick moves. Drag to look.`; `Left stick (or WASD) moves. Drag to look. The button (or Space) jumps.`; `Drag to look around, tap or click to throw balls`; `Tap to start` with `Left stick moves · Drag to look · Tap a prompt to use it · Double tap for light`. Under `capture` (rule 3) the line names the click, not the drag, beside the stick's and the buttons' words: `Left stick (or WASD) moves. Click to take the mouse; Esc gives it back. The button (or Space) jumps; hold the second button (or Shift, or the right mouse button) to run.` (the Courtyard's) | Looked |
| 36 | A quality switch of the work's own (HexGL's title: Quality LOW, MID, HIGH, VERY HIGH, read at load; a renderer's pixel ratio; a shadow-map size; a particle count) | The player's Quality is Auto, Low or High on every work (SDK 0.18.0): under Low the runtime alone caps the pixel ratio at 1.0 (every frame still delivered since runtime 1.28.0), under High it lifts its cap. Where the work has a switch of its own, it follows ours: set from `playspace.quality` at load (before the work reads its own setting) and in `playspace.on("quality", fn)`, `low` its lowest, `high` its highest, `auto` its own default; applied as its own control applies it (at once where it does, at the next load where the work reads it only at load); written to the same storage key its own control writes, never a new one. Its own menu item stays (map, never remove); a work with no switch needs nothing. Never `menu({ settings })` (rule 9). Recipes: three.js `renderer.setPixelRatio(...)` and a shadow map's `mapSize` in the handler (then the work's own resize); R3F `setDpr` from `useThree` in a component's effect; Babylon `engine.setHardwareScalingLevel(1 / r)`; Phaser's `resolution` in the game config (it applies at the next load) | HexGL (`launch.js`): the tier is kept in memory, never stored: the title's `s-quality` item cycles LOW, MID, HIGH, VERY HIGH on its own click (`e.onclick = function() { return f(a[3] = (a[3] + 1) % a[1].length); }`, from `?quality=` or VERY HIGH), and Start passes it to `init(...)`, which builds the renderer | The seed's `playspace-glue.js` clicks the title's own item round until it reads ours, before Start only (the tier is read at init): `var LABEL = { low: "LOW", high: "VERY HIGH", auto: "VERY HIGH" }; function quality(tier, atLoad) { if (atLoad && tier === "auto") return; var want = LABEL[tier], el = document.getElementById("s-quality"); if (!want \|\| !el \|\| typeof el.onclick !== "function" \|\| window.hexGL) return; for (var n = 0; n < 4 && el.innerHTML !== "Quality: " + want; n++) el.onclick(); } quality(ps.quality, true); ps.on("quality", function (t) { quality(t, false); });` (no storage key: the work has none) | Looked (HexGL's re-proof, Low at pixel ratio 1.0 and cadence 30, its title reading "Quality: LOW" under ours; the p95 was unread on HexGL, whose profile gives no frame times; the read case is a held-out work's run: Low's p95 116.7 ms against Auto's 183.3) |
| 37 | The HUD's values (Neon Runner's Score, Coins, COMBO; HexGL's speed, shield, lap "n / 3"; a health bar) | Nothing: the HUD is the work's and stays where it is; `stat()` is never written by the transcoder (the player draws no stat; a work published before still sends them, recorded). `score(n)` where the work's own count changes and `progress(step, of, label)` where an ordered step begins, never once per frame (Neon Runner's proof anchored a score in `_updateScore`, called every frame, about 30 messages a second to the host). The gate's parse rule holds it: an added `score`, `end` or `complete` never stands in a loop's body, nor unconditionally in a function named update, tick, render, animate, loop, frame or step; inside the update's own test of a change (`if (lap !== last)`) it stands. A lap or a level is `progress`; a death that restarts the run is a `moment`, never an `end` | `scoreEl.textContent = Math.floor(dist);` | `if (window.playspace) window.playspace.score(Math.floor(dist)); // playspace` beside the HUD's own write | Looked (the HUD stays the work's; the SDK report's `menu.stats` reads a work published before) |
| 38 | The end's words (Neon Runner's "CRASHED"; HexGL's "Finish" and "Destroyed"; "Game Over", "You Win!") | `end({ score, outcome })` (or `complete`, its first name) only where the experience really ends, the work itself treating it as over (a finished race it does not restart, a story's last scene), its outcome the end's meaning: `"won"`, `"lost"`, `"done"`. The player's end card follows each `end`. **A game over the work retries from at once (a crash, a death, a "tap to restart") is not an end**: there `moment("run_ended")` and `score(n)`, the work's own game over and retry left as they are; the check flags a visit with more than one `end`. Most arcade games and pieces never call `end` | `this.showPanel('CRASHED');` before its own Retry | `if (window.playspace) window.playspace.moment("run_ended"); // playspace` and `if (window.playspace) window.playspace.score(Math.floor(this.distance)); // playspace` | Looked (no end card after a game over the work retries from; the check's end count) |
| 39 | A fixed canvas, or nothing refits it when the frame changes size (Bunny Jump's `width: 480, height: 640` with no scale manager, at the page's top left; UNDERRUN's 320 by 180 at `width: 100%`, cut at the bottom on a wide phone; 13th Floor's 1920 by 1080) | The canvas follows its container: the engine's own scale or fill mode where it has one, else the canvas sized from the live viewport at the start and on `resize`, and the camera refit there (row 24). A canvas whose drawing buffer is the work's art (a pixel-art 320 by 180) keeps its buffer and is fitted by CSS whole (`object-fit: contain` on the full viewport), never stretched. The map's finding `fixed-canvas` or `no-resize`; the recipes by engine are 2.9 | `width: 480,` `height: 640,` and no `scale` (Bunny Jump's `main.js`) | `scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH },` beside the work's own `width` and `height` (Bunny Jump's proof patch, `js/main.js`) | Bunny Jump's proof: the grade's fill row, the original cut off or short at all four sizes (the phone's two, 1280 by 720, 960 by 600), the output fills at all four |
| 40 | The drawing buffer ignores `devicePixelRatio` (Astray's `renderer.setSize(window.innerWidth, window.innerHeight)` on three.js r49, which has no `setPixelRatio`) | The renderer's pixel ratio is the device's, capped at 2 as the engines' docs advise (a phone's 3 costs more than it shows): `Math.min(window.devicePixelRatio \|\| 1, 2)`, read at the start and on each resize (the runtime caps it at 1.5 in the app: read it, never assume it). A lower cap of the work's own (a pixel budget, a quality tier) stays, and the finding is `kept` with that note; a pixel-art buffer is `kept` too. The map's finding `pixel-ratio` | `renderer.setSize(window.innerWidth, window.innerHeight);` (Astray's `index.html`) | where the engine has no ratio of its own, one function at the start and in `onResize`: `function sizeRenderer() { var r = Math.min(window.devicePixelRatio \|\| 1, 2); renderer.setSize(Math.round(window.innerWidth * r), Math.round(window.innerHeight * r)); renderer.domElement.style.width = window.innerWidth + 'px'; renderer.domElement.style.height = window.innerHeight + 'px'; }` (Astray's proof patch) | Astray's proof: the phone's drawing buffer 1 px per CSS px in the original, 2 (the device's) in the output, at both phone sizes; the grade holds a patched ratio to it |
| 41 | The work's HUD under the player's corners or past the insets (Bunny Jump's `Carrots: 0` drawn at 240, 10; UNDERRUN's `#a` line at `top: 4vw; left: 2vw`, under the pause corner; Starter Kit's `#lap-timer`, row 25) | Inside `touch.geometry()`'s `safe` rect (the insets) and off its `reserved` corners: the HUD moved where the work places it (a CSS rule, or its text's position read from the geometry at the start and on `playspace.on("insets")`). Under the pause corner (the top left, `TOUCH_STYLE.reserved.left`, 72 by 60) a control of the work's own (a button, a link, a field, a slider: its music button) is never moved: it is declared, `playspace.layout({ v: 3, avoid: [".music-player"] })`, and reported in `gaps`: our pill (the work's menu key, where the file names `esc`) is at the top left, and it yields to a control of the work's own under it (not drawn, no touch, while the control is there). Map, never redesign: the control is not moved for the pill. Text the work only draws there may be moved off as above, or declared. A HUD elsewhere under the stick or A and B that must stay where it is is declared too, `playspace.layout({ v: 3, avoid: ["#hud"] })`, its touches the work's. The map's finding `under-corner` or `safe-area` | `#level { position: absolute; left: 0px; top: 0px; ... }` (Astray's `index.html`; UNDERRUN's `#a` the same) | `#level { position: absolute; left: max(12px, env(safe-area-inset-left, 0px)); top: max(64px, env(safe-area-inset-top, 0px)); ... }` and `#help` from the bottom left (the stick's zone) to `left: 50%; transform: translateX(-50%); bottom: env(safe-area-inset-bottom, 0px);` (Astray's proof patch) | Astray's proof: the frame row's corner count, the work's own elements under the pause corner, 1 in the original and 0 in the output at both phone sizes |
| 42 | The loop's step from the clock with no cap (UNDERRUN's `time_elapsed = (time_now - time_last)/1000;` in `game_tick`; Astray steps Box2D a fixed `1/60` a frame and needs none) | One line where the loop computes its step: `dt = Math.min(dt, 0.1)` (a tenth of a second at most). The runtime already holds `requestAnimationFrame` and timers while the player is paused and while the tab is hidden, but `performance.now()` and the frame's timestamp keep counting, so an unclamped step integrates the whole pause into the first frame after it (the player jumps, the physics tunnels). An engine whose loop clamps already is left alone: PlayCanvas's `app.maxDeltaTime` (0.1 by default), a fixed step per frame (Astray). The map's finding `unclamped-dt` | `time_elapsed = (time_now - time_last)/1000;` (UNDERRUN's `game.js`) | `time_elapsed = Math.min((time_now - time_last)/1000, 0.1);` | Bunny Jump's and Astray's proofs: neither has an unclamped step (Phaser's arcade step, Astray's fixed 1/60) and the agents named none; the resume row read both unmeasured (Bunny Jump's bounce changes the picture at one pace, Astray's still maze none), so it is written, not yet proved on a jump |
| 43 | A mute or sound control of the work's own (UNDERRUN plays its music and effects through one `audio_ctx` and has none; Neon Runner's ♪ button and M key, cut) | Kept (map, never remove; the button and the key stay). The work's audio also hangs on `playspace.on("mute")` as its pause hangs on `on("pause")` (rule 9): the runtime already suspends every `AudioContext` and media element while muted, so the handler keeps the work's own sound state with it (a music flag, a master gain, an engine's global volume) and the work never resumes a sound itself while muted; `playspace.muted` is the value at load. Recipes by engine in 2.9. The map's finding `own-mute`, `kept` (`removed` reads only on a map pinned by an older version) | `audio_ctx = new (window.webkitAudioContext\|\|window.AudioContext)()` (UNDERRUN's `audio.js`: the bus a handler mutes) | `playspace.on("mute", function (on) { if (on) audio_ctx.suspend(); else audio_ctx.resume(); });` | Bunny Jump's and Astray's proofs: neither has a sound control of its own (Astray plays none; Bunny Jump plays its jump sound with no control for it), so the grade's mute row passed with no finding; its fail on a removed mute with no `on("mute")` call site is tested on Bunny Jump's real record, written, not yet proved on a work with one |
| 44 | A Next app-router page whose one client component mounts the scene (night-street's `src/app/Gate.tsx`, `'use client'`, the scene behind `next/dynamic` with `ssr: false`), read as a source (the source mode) | The adapter `src/playspace-sdk.ts` with `importFrom` the client component (the harness writes its import after `'use client'`); in it, at module load and behind `typeof window !== "undefined"`, the declaration and the subscriptions, forwarding to a small exported object the scene's component fills in its own effect once it exists (`contract.look`, `contract.intent`); the lifecycle lines stay in the client component where its state says the scene is up | `const NightStreet = dynamic(() => import('@/scene/NightStreet'), { ssr: false });` | `ps.layout({ v: 3, secondary: 'Run', look: { computer: 'capture' } }); ps.camera.onLook((yaw, pitch) => { if (contract.look) contract.look(yaw, pitch); });` | night-street's source run: applied and built at the first build, the typed contract read (`Playspace.Intent`); the gate failed: on the check's software GL the output's computer stage drew nothing and no controller record was read (the scene's own GLSL bake runs 30 s or more on a desktop GPU, and the patch also mounts it on a phone) |
| 45 | An R3F rig that keeps held keys in a set from `window` keydown and turns on a locked pointer's `movementX` (night-street's `src/scene/Rig.tsx`: `KEYS[e.code]`, `canvas.requestPointerLock()`, `walker.look(e.movementX, e.movementY)`) | The key table, the listeners and the lock deleted in the rig's effect; `useFrame` reads `input.axis("moveX")` and `("moveY")` into the walker's own `forward` and `strafe`; the look onto the walker's yaw and pitch inside its own limits; a held sprint on the `secondary` intent (row 15) | `useFrame((_, rawDelta) => { ... walker.update(dt, { forward: (h.has('f') ? 1 : 0) - (h.has('b') ? 1 : 0), ... }) })` | `const mx = ps ? ps.input.axis('moveX') : 0; const my = ps ? ps.input.axis('moveY') : 0; walker.update(dt, { forward: -my, strafe: mx, sprint: h.has('sp') });` | night-street's source run, as row 44: built, the gate failed on the picture |
| 46 | A pages-router page that wires its own pointer drag and wheel on `document` in a `useEffect` (3D-Carousel's `pages/index.js`: `document.onpointerdown` turns `tX` and `tY`, `document.onmousewheel` changes `radius`), JSX in a `.js` file, read as a source | A source edit inside the same effect, no adapter: `camera.onLook` onto the work's own `tX` and `tY` in degrees (`yaw * 180 / Math.PI`), the `zoom` intent onto its `radius` as the wheel did, `gameplayStart()` once on the first `pointerdown` (capture, once: the first touch or click of any kind, not only a drag); `on("pause")` and `on("resume")` onto its own spin; a music bar of its own kept (its sound also on `on("mute")`, row 43) | `document.onpointerdown = function (e) { ... tX += desX * 0.1; tY += desY * 0.1; applyTranform(odrag); ... }` | `ps.camera.onLook(function (yaw, pitch) { begin(); tX += yaw * 180 / Math.PI; tY -= pitch * 180 / Math.PI; applyTranform(odrag); });` | 3D-Carousel's source run: the build passed its controls, menu and frame at the second check (the first missed `gameplayStart` because it waited for a drag) |
| 47 | Upright (a phone held upright plays every work, no turn screen, no lock; the frame fills the stage between the page's top bar and the row under it, about 374 by 656 on a 390 by 844 phone) | The work's own layout adapts where its code allows: a `resize` handler that reads `innerWidth` and `innerHeight` (never a fixed 16:9), `camera.aspect` set from the frame and `updateProjectionMatrix()` on each resize (three.js; Babylon's `engine.resize()`), a HUD laid out by CSS from the frame's edges; else `fixed: true` in the manifest and the player fits the frame to the width at its sideways aspect. Never a rotate prompt, never `screen.orientation.lock`, never a branch that hides the work upright; `playspace.on("orientation")` is there to re-lay a HUD, not to stop play | `renderer.setSize(window.innerWidth, window.innerHeight)` only at the start (Astray's `index.html`: its `onResize` keeps it) | `window.addEventListener('resize', function () { camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix(); renderer.setSize(innerWidth, innerHeight); });` | Looked: HexGL and Astray upright at 390 by 844 on the dev stack; the check's upright reading (the frame row's third size, with the layer's) is the proof on every build |

## 2. Engine recipes: the camera and the input

Each recipe: where the input lives, what to write, what to delete, and which corpus work proved it. "Unproved" means
no corpus work has the idiom yet: the recipe is the engine's API read against the contract, and the proof set
should add one.

### 2.1 three.js

**A raw pointer lock** (`document.body.requestPointerLock()`, `movementX` at a gain, a key table): row 1 and row 5,
games_fps; the declaration's `look: { computer: "capture" }` keeps the original's free mouse on a computer (0.9.2). The walk in the camera's frame is the example's own: `getForwardVector()` is the camera's direction with
`y = 0` normalized, `getSideVector()` its cross with up; `moveY` negative is forward, `moveX` positive is right.

**`PointerLockControls`** (the addon: `controls.lock()` on a click, a blocker overlay on `lock`/`unlock`, the loop gated
on `controls.isLocked`; movement by `controls.moveForward(d)` and `controls.moveRight(d)`). Write: keep the controls
object for its `moveForward`/`moveRight` (they walk in the camera's yaw and work unlocked), fed each frame by
`playspace.input.axis("moveY")` (negated) and `("moveX")`; turn the camera by `onLook` through a `'YXZ'` Euler:
`e.setFromQuaternion(camera.quaternion); e.y -= yaw; e.x = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, e.x + pitch)); camera.quaternion.setFromEuler(e);`.
Delete: `controls.lock()` and the blocker's click, the `isLocked` gate on the loop, the controls' `connect()` if the
version has one (its `mousemove` would turn the camera a second time under the computer's drag). Unproved; the nearest
proof is games_fps (the same math without the addon).

**`OrbitControls`** (a viewer: the camera orbits a target on pointer events, pans and zooms by pinch and wheel; drei's
`<OrbitControls>`, `TrackballControls` and `MapControls` alike). Write: `"pointer": "own"` in the file;
keep the controls; declare `playspace.layout({ v: 3, own: true, avoid: [...] })` and nothing else (no `inspect`, no
`look` or `scroll` reading, no `camera.onLook`: a plain `{ v: 3 }` is the layout reading, which takes the drag and the
pinch). Delete:
nothing. Under `"pointer": "own"` every finger is the work's (SDK 0.17.0): its one-finger orbit, its two-finger
pinch and pan and the wheel reach it as they always did; an `inspect` reading over it would take the pinch as the
`zoom` intent and lose it (Solar System 3D). **A viewer with no touch input of its own** (a model the work only
draws): declare `inspect` (`playspace.layout({ v: 3, inspect: { distance: [far, near], limits: { pitch: [lo, hi] } } })`:
no stick drawn, the drag the look, `view` true) and turn the camera by `onLook` on a spherical around the target:
`sph.setFromVector3(camera.position.clone().sub(target)); sph.theta -= yaw; sph.phi = Math.max(0.1, Math.min(Math.PI - 0.1, sph.phi - pitch)); camera.position.setFromSpherical(sph).add(target); camera.lookAt(target);`;
the zoom on a handled `doubleTap` (ease `sph.radius` between the two distances) or the `zoom` intent. The Turntable and
Lamp Shop probes prove `inspect` with the SDK's own orbit (a probe is not a cookbook citation).

**`FirstPersonControls`** (keys W A S D R F in the object, the look from the mouse's position over the element,
`lookSpeed`, `movementSpeed`, `activeLook`). Write: delete the object (`controls.dispose()`) and replace it whole with
the raw recipe above: the walk by the axes along the flattened camera direction, the look by `onLook` on the Euler.
Unproved.

**The field of view:** `camera.fov = playspace.camera.fovFor(base, camera.aspect); camera.updateProjectionMatrix();` at
the start and on resize (HexGL's chase camera; Starter Kit's `Camera.js`). A raycaster: `raycaster.setFromCamera({ x: p.nx, y: p.ny }, camera)`
inside `select.hit` (Three Rooms and Box & Pieces, probes).

### 2.2 Babylon.js

**`UniversalCamera` / `FreeCamera`** (`attachControl(canvas)` adds the keyboard, mouse and touch inputs; `keysUp` and
the rest hold key codes; `angularSensibility` is the mouse gain): row 7, Valley Village and Pirate Fort. Write:
`camera.inputs.clear()` before any `attachControl`; `onLook` onto `camera.rotation.y += yaw` and
`camera.rotation.x -= pitch` clamped (left-handed: `rotation.x` grows looking down); the stick into
`camera.cameraDirection` rotated by `camera.rotation.y` at `camera._computeLocalCameraSpeed()` inside
`scene.onBeforeRenderObservable`, so `checkCollisions`, `applyGravity` and `inertia` keep working. Delete: the key
pushes, the sensibility, `attachControl`, any `keydown` or `pointerdown` that started the work (a tap or the first
axis read starts it instead). Proved: Valley Village P2, P3, D1, D2.

**Its touch input** (`FreeCameraTouchInput`, added by `attachControl` on a touch screen; `touchAngularSensibility`,
`touchMoveSensibility`): gone with `inputs.clear()`; where the work keeps the mouse for a computer by design (a glue),
`camera.inputs.removeByType("FreeCameraTouchInput")` alone. Proved by Valley Village (cleared whole).

**`ArcRotateCamera`** (a viewer: `alpha`, `beta`, `radius` around `target`; `ArcRotateCameraPointersInput`, the
mouse wheel, `panningSensibility`). Write: `"pointer": "own"` in the file; keep the controls
(`attachControl` and its pointer input: its drag, its pinch and the wheel stay the work's, every finger under `own`
since SDK 0.17.0); declare `{ v: 3, own: true }` and nothing else. Delete: nothing. **A viewer with no touch input of its own** (the camera
never attached): declare `inspect` and turn it by `onLook` onto `camera.alpha -= yaw; camera.beta += pitch` (a drag
right turns the thing's front with the finger; a drag up lowers the camera; `lowerBetaLimit`/`upperBetaLimit` still
clamp), the zoom on a handled `doubleTap` between two `radius` values within `lowerRadiusLimit`/`upperRadiusLimit`.
Unproved.

**The pick:** `scene.pick(x, y)` takes the canvas's CSS pixels: `p.x - rect.left, p.y - rect.top` from
`canvas.getBoundingClientRect()` (row 22; CORPUS.md note 8). **The field of view:** `camera.fov` is radians:
`playspace.camera.fovFor(57.3, aspect) * Math.PI / 180`, again on resize beside `engine.resize()`.

### 2.3 PlayCanvas

**The engine's `FirstPersonController`** (2.x: `KeyboardMouseSource`, `DualGestureSource`, `GamepadSource` read into
one `InputFrame` of `move`, `rotate`, `jump` deltas, then `_updateController(frame, dt)`): row 8, Courtyard. Write: a
subclass that destroys the three sources in `initialize()` and in `update(dt)` appends `[mx * speed, 0, -my * speed]`
to `move`, the look accumulated in degrees (`yaw * 180 / Math.PI`, pitch negated) to `rotate`, `[1]` to `jump` on the
frame of `action` on, then calls `_updateController`; `import { InputFrame } from 'playcanvas'`. Delete: the pointer
lock (`pointerLock: true` goes with its source), the two-thumb touch, the gamepad (it goes with the set; later). Proved:
Courtyard P2, P3, P6, D1 to D4.

**A classic script camera** (`pc.createScript`; `this.app.keyboard.isPressed(pc.KEY_W)` in `update`;
`this.app.mouse.on(pc.EVENT_MOUSEMOVE, ...)` reading `dx`/`dy` under `pc.Mouse.isPointerLocked()`, with
`this.app.mouse.enablePointerLock()` on a click; `this.app.touch` handlers). Write: the four `isPressed` branches
become the axes into the script's own move vector; the `mousemove` becomes `onLook` onto the script's Euler angles
(`this.eulers.x -= yaw` in degrees, `.y += pitch` clamped, as the script already applies them with
`setLocalEulerAngles`); the field of view by `camera.camera.fov = playspace.camera.fovFor(base, aspect)` (degrees).
Delete: `enablePointerLock()` and its click, the `mousemove` listener, the touch handlers. Unproved (the engine's own
controller is proved).

### 2.4 Phaser 3

**`createCursorKeys()`** (`cursors.left.isDown` polled in `update`): row 12, Bunny Jump. Write: `const mx =
playspace.input.axis('moveX')` at the top of `update` and `|| mx < -0.35` / `|| mx > 0.35` on each side's test; where
the game has an up or down key, `my < -0.5` and `my > 0.5` the same way. Delete nothing: the cursors still work on a
computer and agree with the axis (no double). Proved: Bunny Jump P2, D1.

**`addKeys('W,A,S,D')` / `addKey(KeyCodes.SPACE)`** (`keys.W.isDown`; `Phaser.Input.Keyboard.JustDown(keys.SPACE)` for
an edge). Write: the `isDown` tests as the cursors above; a `JustDown` on Space becomes a flag set by the `action`
intent's `on` in `onIntent`, read and cleared in `update` (declare `action: "Jump"`); `keyboard.once('keydown-SPACE')`
and `keyboard.on('keydown-SPACE')` for the same verb are deleted (row 10) and the `action` handler calls what they
called. Subscribe in the scene's `create`, keep the unsubscribe and call it on the scene's `shutdown` (Bunny Jump's
`GameOver`). Unproved for `addKeys`; the Space rule proved by Bunny Jump P6.

**`this.input.on('pointerdown', fn)` / `activePointer`**: a tap is the click where it lands, so Phaser's `pointerdown`
fires on a touch screen with nothing written; a pointer polled each frame for an aim (`activePointer.x`) becomes
`holdDrag: "drag"` with the hold's and drag's point (row 16; `nx, ny` to canvas px through the game's `scale`
transform, or `p.x - canvas.getBoundingClientRect().left` scaled by `game.scale.displayScale`). Unproved.

**The canvas:** `scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH }` in the game config where
there is none (row 23). **A touch-screen branch** (`this.sys.game.device.input.touch` building the game's own
joystick or buttons): deleted (row 17).

### 2.5 Plain canvas key tables

Row 1 (`keyStates[event.code]`), row 2 (`keyCode` with a conversion map), row 3 (a key-axis library). The one
decision: **digital or analog.** A table read as `if (keys.left) x -= 1` becomes a threshold read (`mx < -0.35`,
ON/OFF, Bunny Jump) when the game's physics expects a step, or the axis times the speed (`t.ax = mx * speed`, UNDERRUN,
games_fps) when it takes a magnitude. Delete the `keydown`/`keyup` listeners the table was filled from, unless the
table also carries verbs the contract does not (a menu's keys, an inventory): then keep the listeners and only replace
the direction reads. A library (KeyboardJS, Mousetrap, `keyboardjs.bind`) is left in place for its other bindings
(Astray keeps it for the `i` instructions).

### 2.6 DOM and SVG menus

A DOM menu needs nothing: buttons, links and fields pass through, a tap on anything else is the click at the point
(row 19, Elematter; row 20, the starts). An **SVG** menu whose items are groups needs `select: { hit }` over the items'
`getBoundingClientRect()` boxes (row 18, ON/OFF). A menu that only Enter confirms (APEX's title, HexGL's) is left
when its items confirm on their click; when they do not, the tap on the title raises the work's own confirm
(`push({ type: 'menu-confirm' })`, APEX's event) from `onIntent`. A menu's own Escape or Backspace verb keeps its key on a
computer (row 34, since runtime 1.27.0); on a phone its back goes on a tappable item of the menu or the pill (`esc`).

### 2.7 React Three Fiber

A built R3F site with no globals (racing-game) is the declaration-only glue of row 4. Readable R3F source: the per-frame
read goes in `useFrame((state, dt) => { const mx = playspace.input.axis("moveX"), my = playspace.input.axis("moveY"); ... })`;
the subscriptions in an effect, returning the unsubscribe the SDK hands back:
`useEffect(() => playspace.camera.onLook((yaw, pitch) => { ... }), [])` and
`useEffect(() => playspace.input.onIntent((i) => { ... }), [])`; `playspace.layout({ v: 3, ... })` once in the root
component's effect. drei's `<PointerLockControls>` and `<OrbitControls>` are the three.js recipes of 2.1 (the
components wrap the same objects: take the `ref` and apply the recipe); drei's `KeyboardControls` map stays for a
computer and the axes are read beside it. Read as a source (the source mode): rows 44 and 45, night-street's
rig, where the declaration sits in the adapter at module load and the rig plugs its handlers in from its own effect,
since the scene mounts only after a long bake; built, not yet passed by the check (its software GL never drew it).

### 2.8 A bundle with no globals

Row 28 (13th Floor): the one-time setter on `Object.prototype`, the property name taken from the class's constructor
in the minified source, lifted at the first assignment. Row 27 (Elematter, The Cube): a reachable instance's own
property wraps its method. Where neither reaches the game, the declaration alone (row 4) and `ready()`.

### 2.9 The frame and the envelope, by engine (rows 39 to 43)

The map lists each finding (`findings`: its kind, its `path:line`, its fix); a fix of a source edit goes in the
controls' reach (a file the map calls input or page, inside a region), a glue's in the glue. One line each where the
engine has the knob:

- **three.js**: on `resize`, `renderer.setSize(window.innerWidth, window.innerHeight); camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix();`;
  `renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))` before the first `setSize` (a release before
  `setPixelRatio`, Astray's r49: the buffer sized by the ratio and the CSS size set, row 40); the step
  `const dt = Math.min(clock.getDelta(), 0.1)`; the sound `listener.setMasterVolume(on ? 0 : 1)` in `on("mute")`.
- **Babylon.js**: `window.addEventListener("resize", () => engine.resize())`; the ratio by
  `new BABYLON.Engine(canvas, true, { adaptToDeviceRatio: true })` or
  `engine.setHardwareScalingLevel(1 / Math.min(window.devicePixelRatio, 2))`; the step from `engine.getDeltaTime()`
  clamped where the work integrates it (`Math.min(engine.getDeltaTime(), 100)` ms); the sound
  `BABYLON.Engine.audioEngine.setGlobalVolume(on ? 0 : 1)`.
- **PlayCanvas**: `app.setCanvasFillMode(pc.FILLMODE_FILL_WINDOW); app.setCanvasResolution(pc.RESOLUTION_AUTO);` and
  `window.addEventListener("resize", () => app.resizeCanvas())`; `app.graphicsDevice.maxPixelRatio = Math.min(window.devicePixelRatio, 2)`;
  the step is already clamped (`app.maxDeltaTime`, 0.1); the sound `app.systems.sound.volume = on ? 0 : 1`.
- **Phaser 3**: `scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH }` in the game config (row 39;
  the game's own `width` and `height` stay, they are its world); its resolution is its art (`kept`); a HUD text off the
  pause corner by its position (`this.add.text(x, y, ...)` past 72 by 60 of the canvas's displayed px, or right-aligned
  at the top right); a `delta` the work integrates itself clamped (`Math.min(delta, 100)`, ms), while arcade physics'
  own step is the engine's; the sound `this.sound.mute = on` (the game's `SoundManager`).
- **Plain canvas**: the canvas's CSS size from the viewport (`width: 100vw; height: 100vh; object-fit: contain` for a
  buffer kept as art), else `c.width = Math.round(innerWidth * r); c.height = Math.round(innerHeight * r);` with
  `r = Math.min(devicePixelRatio || 1, 2)` and the context scaled by `r`, on `resize`; the step
  `Math.min((now - last) / 1000, 0.1)`; the sound a master `GainNode` (`gain.value = on ? 0 : 1`) or the work's one
  `AudioContext` suspended and resumed, and any `<audio>` element's `muted`.

## 3. The boilerplate rows

| Boilerplate | The rule | Where seen |
|---|---|---|
| The loop (`requestAnimationFrame`, `setAnimationLoop`, an engine's loop, fixed substeps) | Left alone but for its step. Pause holds `requestAnimationFrame` and timers while the clock keeps counting, so the step is clamped where the loop computes it, one line (row 42; games_fps's five substeps already do); the player's pause and resume reach the work's own pause (row 29) | games_fps, Valley Village, Courtyard, APEX, UNDERRUN |
| The audio unlock on the first click, a "click to start" screen | Nothing added: the first tap passes through as the click and `AudioContext.resume()` resolves on it; the start screen's tap is the arming tap. Never a sound gate of the work's own over the frame; the player mutes until the first touch inside the frame | 13th Floor ("Tap to start"), UNDERRUN (the click that starts it) |
| The pixel ratio (`renderer.setPixelRatio(window.devicePixelRatio)`, a canvas sized by `devicePixelRatio`) | Left alone where the work reads it: it keeps reading `window.devicePixelRatio`, which the runtime caps at 1.5 in the app and on a touch screen (CONTRACT.md, Sharp screens); never replaced by a hard-coded ratio. A work's own lower cap (a pixel budget) stays. A work that ignores it is row 40 | games_fps (`setPixelRatio( window.devicePixelRatio )`); 13th Floor's `layoutCanvas()` (`Math.min(window.devicePixelRatio \|\| 1, ...)`) |
| Resize and the viewport meta | The SDK inserts the viewport meta when the page has none (`viewport-fit=cover`) and pins the page (`touch-action: none`, `overscroll-behavior: none`). The work sizes from the live viewport (`window.innerWidth`, `innerHeight`), never a phone's screen size, and refits its field of view by `fovFor` on `resize` (row 24) | Valley Village `fit()` on resize; 13th Floor `layoutCanvas()` |
| Pointer-lock requests | A source edit deletes the request and the lock-gated branches (row 5). A glue leaves the original's lock for a computer and names the fallback's units, `look: { radPerPx, mouse: "movement" }` (row 6); under a lock the SDK's drag look stays out | games_fps, 13th Floor |
| A work's own mobile-mode switches (`'ontouchstart' in window`, `pointer: coarse`, `isTouchDevice()`, nipplejs, an engine's touch input) | Kept (row 17): the work's own touch mode stays in its code under `"pointer": "own"`, a control of the set only for a needed verb its own touch cannot reach; never removed or switched off (HexGL's re-proof, keeps its own touch steering) | Starter Kit, HexGL, Valley Village, Courtyard |
| Escape is the work's | Since runtime 1.27.0 Escape reaches the work like any key and the Home button is a click or a tap; a work's own Escape verb keeps its key on a computer and may be the pill (`esc`) on a phone (row 34). The work's own pause menu and pause button stay: its pause also hangs on `playspace.on("pause")`, its resume on `on("resume")`; back by a tappable item or its mapped key | APEX, HexGL, ON/OFF |
| A platformer's up is its jump | `playspace.input.axis("moveY") < -0.5` into the jump key's reading; the button is the second verb; there is no forward (row 11) | ON/OFF; Bunny Jump (an automatic bounce: no jump key) |
| The second button, then tap, doubleTap and dash | Section 0.5's order first: a verb the work's own touch, a tap or its own screen carries gets no button. The work's second place-less verb is the second button (rule 8; a held verb first); its third and fourth ride on `tap`, `doubleTap` and `dash` in that order of weight where the playfield has nothing to tap (row 15); a verb with a side rides on the tap on that side. Three verbs that must be held together: A, B and C each hold their own key, presented, not refused (section 4) | HexGL, racing-game, APEX |
| No third button, no small buttons | The Playspace set on every work (P7): the stick, A, B and the pill, each with its word, drawn by the player from the file (`controls` in playspace.json), never a button drawn by the work or the glue; a verb past them is in `extra` with its reason, or the work does not fit the set; a work's own on-screen buttons stay its own, inside its frame, off the player's corners (row 25) | HexGL's Menu button (note 3) |
| The Space handler beside a declared action | Kept (rule 6, row 10): the manifest maps Space to A and the work's own handler answers the verb; no `onIntent` branch answers it too, or it fires twice | ON/OFF, Bunny Jump |
| The keys' set | Name `keys` only in a glue (the SDK must press them) or where the work's own key reading stays (a racer's `forward`); a source edit that reads the axes names none and gets W A S D and the arrows on a computer from the SDK | racing-game, HexGL, APEX; games_fps names none |
| Play behind a menu | The transcoder removes no title, start, pause or options menu and mirrors none of them onto the contract (rule 9). The check reaches play by the work's `start` recipe in `seed.json` (taps by selector or point, keys, waits) before its rows; a work with no recipe is measured where it lands | HexGL, ON/OFF, racing-game |
| The hint line | The work's own, left as it is (row 35); a line the glue writes, where it writes one, in the contract's words, never a number | Valley Village, Courtyard, games_fps, 13th Floor |
| `playspace.json` | The control manifest (section 0.5: version 3, the Playspace set; versions 1 and 2 still read) in the folder the build ships (a source's `public/` only where its bundler copies it); `false` is the creator's opt-out, never the transcoder's (the corpus glues before the manifest shipped); `kind` and `idle` where the work is not a game | 13th Floor, HexGL, Elematter, The Cube, racing-game |
| A glue's devices | Declare on every device; subscribe under `ps.touch.device` only (row 33); a declaration-only glue needs no gate | 13th Floor, HexGL, racing-game |

## 4. What the SDK does with each name

**Never remove a control path, handler, menu, hint or touch mode the creator built; map it in the manifest**.
This line outranks the rest.

What follows is what the SDK and the player do when a work uses a name, so a change can be judged by what it will do.
None of it is a rule of the wrapper's: the safety rules at the end of this section are the only ones a
build is stopped by.

**The gone names** (the 0.9 promise's list; each is absent from the SDK, and a read of one is recorded in the SDK's
report as `legacy`, which the check keeps on the build):
- the action map (`input.use`, `.bind`, `.down`, `.pressed`, `.released`, `.on`, `.emitKeys`, `.update`, `.lock`,
  `.unlock`), the old touch calls (`touch.insets`, `.click`, `.fit`, `.state`, and `touch.show` since 0.20.0: mark where
  play begins with `start()` instead), `geometry().zone`,
  `geometry().grammar`, `sdk.pinned` and `sdk.load` read as `undefined`: a call to one throws in the work. Each has a
  contract word in its place (the stick's `input.axis`, the intents by `onIntent`, `touch.geometry()`'s reservations);
- the old names read as `undefined` too; their new names: `touch.layout`, `touch.layouts` and `touch.scheme()` are
  `playspace.layout`; `thrust` and `keys.sprint` are `dash` and `keys.dash`; `select.hold` is
  `select.waitForDoubleTap`; the old `secondary` (the double tap) is `doubleTap`, and `secondary` since 0.11.0 is the
  second button and nothing else;
- a `playspace.layout` whose `v` is not 3 (`v: 2` or any other) is no declaration: the layout stays the default and the
  report records `layout.v2` (or the version it saw);
- `gameplayStop` still works for the old `playspace.js` script (it says `complete`'s end) and is recorded as legacy;
  say `end`, or its 0.10.0 name `stop`. `playspace.version` reads `"0"` for that script; the version is
  `playspace.sdk.version`.

**The optional members** (they stay and may still change before 1.0): `camera.attach`, `.preset`, `.update`,
`.resize`, `.yaw`, `.pitch`, `.distance`, `.focus` and `locomotion.*` (three.js only, the camera module's),
`camera.drain()`, `loop.*` and `audio` work as the reference says, but a work that leans on them may need a change at a
later 0.x; the contract's camera is the work's own, turned by `onLook`. `camera.comfort()` reads the player's feel: an
argument is ignored, the call returns the player's values and the report counts it in `comfortWrites`.

**The player's names** (what the player keeps for itself; the player surface, rule 7):
- the player draws the set (the stick, A, B, the pill) from the file only; a work's own third button, a label on A or B, a hint over
  the frame, a colour or a count asked of the chrome is drawn by nobody but the work;
- `menu({ score, restart })` is read by the end card's Play again and the board; `score`, `end` (at a real end),
  `moment`, `progress` and `save` are recorded as the reference says. `menu({ settings })`, `modes`, `objective` and
  `stat()` are taken within their bounds and reported (the report's `menu` summary), and shown nowhere: the Home
  button shows nothing of the work's, so the work's own menus and HUD stay where the work draws them.
  The one setting the player answers is a declared `quality`, from the player's quality tier; a setting the
  host answers is checked against the declaration and dropped when it does not fit;
- the tap never walks (the stick is the only locomotion), and `locomotion.goto` is the camera module's;
- on a computer the SDK adds no key, click or mouse: the real ones reach the work. An `onLook` subscriber outside
  `ps.touch.device` turns the camera twice where the work's own mouse look also runs;
- an `onIntent` branch that answers a verb the work's own handler already hears (Space beside a declared `action`,
  rule 6) fires the act twice;
- the work's own touch path, pause menu, pause button and sound controls keep working beside the player's: its pause
  and audio also hear `on("pause")` and `on("mute")` (rows 29 and 43);
- a hint line names a control in words ("push harder to dash", never "past 0.35"): the reference's numbers are the
  player's and may be tuned (the 0.9 promise);
- the gamepad reaches the work as the browser gives it; the runtime counts the work's polls and
  never changes them.

**What stops a build** (safety, the scan over what a change adds against the original): a new `fetch`,
`XMLHttpRequest`, `WebSocket`, `EventSource`, `WebTransport`, WebRTC, `sendBeacon`, an import or a script from a host, a new worker, `window.open`, a
navigation, `postMessage`, `eval` or `new Function`, `document.cookie`, a service worker's registration, a path under
`/.playspace/` (reserved), new storage the original never used, or an absolute URL the original never held. A hit
ends the run `failed: suspicious` with no version. Multiplayer sockets are refused by the same rule and by the
frame's egress. Whether a work can be played with the Playspace set is section 0.5's: a needed action
with no control of the set is named in the report.

## 5. What the transcoder never touches

- **Loaders and assets**: `GLTFLoader`, `AssetListLoader`, a Phaser `preload`, textures, models, sounds, fonts, the
  paths they load from. A port's vendoring (a CDN import made local) is the overlay's, both cards', never the transcode.
- **Physics and the simulation**: Box2D's impulses, Ammo, arcade physics, the controller's own velocities, collisions,
  gravity and substeps (the contract feeds them; it does not rewrite them).
- **Content**: levels, art, text, menus, scores, the game's own rules and words, except the hint line that names a
  control (row 35) and a start line that names a mouse.
- **Network**: `fetch`, sockets, analytics tags (blocked by the CSP and recorded), sign-in stubs (a port's overlay);
  the egress scan compares the transcode with the original.
- **Storage**: `localStorage`, IndexedDB, cookies, a best time, a save file, a service worker's registration (left,
  even where the worker itself is left out of the site).
- **The build tooling**: the project's lockfile, its build script, its bundler config; the transcode is a patch over the
  assembled site or a glue beside it.
- **The engine**: its version as uploaded, its loop, its scene graph; only the input region and the camera's turn.
- **The gamepad** where it sits beside the contract (section 4).
- **The page's own identity**: its `<title>`, `og:` tags, licence files and attributions (The Cube keeps its trademark
  in its title; the card's title is the creator's).

## 6. Measured moments

What the "Add analytics" goal is written with. A moment is one call, `playspace.moment("snake_case_name")`, added in
the work's own code at the place it happens: where a player decides (a choice, a path, a mode), stalls or quits, or
succeeds. Rare, never every frame or jump, and named in the work's own terms (`level_cleared`, `painting_opened`),
never ours. A game over the work retries from is a `moment` and a `score`, never an `end`.

Each moment is declared once so the creator's page can count it: at most
twelve, each name once, every one declared in full (never some with all seven fields and some without). All seven
fields, in these shapes, or the declaration is refused with an error (`readMeasurementDefinition`,
`@tinker/contract/hosted-runtime`; a test holds this example to it):

    { "name": "level_cleared", "when": "the last brick of a level breaks", "where": "src/game.js:212",
      "label": "Level cleared", "kind": "progress",
      "why": "How far do people get before they stop?",
      "limitations": ["Counts each level once per play.", "It cannot tell a player who quit from one who lost."] }

| Field | What it holds |
|---|---|
| `name` | The same snake_case name the call sends: a lowercase letter first, then lowercase letters, digits and `_`, at most 40 characters |
| `when` | The trigger, in the work's terms (a string, at most 300 characters) |
| `where` | The call's `path:line` (a string, at most 300) |
| `label` | The creator's words for it (a string, at most 80) |
| `kind` | One of `request`, `state_change`, `progress`, `outcome` |
| `why` | The question it answers for the creator (a string, at most 300) |
| `limitations` | **An array** of one to four strings, each one sentence on what it cannot tell (at most 200 characters each). A single string is refused |
