<!-- PIPIST MASTER SPECIFICATION v1.3. Generated by concatenating the 14 source files below, byte for byte, in this order. Each source is delimited by SOURCE-BEGIN / SOURCE-END markers. -->
# PIPIST — MASTER SPECIFICATION v1.3 (complete, combined)

This file contains the entire specification in one place. Every source document appears unmodified between its `SOURCE-BEGIN` and `SOURCE-END` markers, in the order of the document map in Part 1. Contents:

1. `pipist-spec.md` — PIPIST — Unified Game Dev Environment: Build Specification
2. `pipist-spec-part2.md` — PIPIST — Build Specification v1.3, Part 2 of 3 (sections 6–13A)
3. `pipist-spec-part3.md` — PIPIST — Build Specification v1.3, Part 3 of 3 (sections 13B–21)
4. `pipist-spec-13c-input.md` — PIPIST SPEC — Section 13C: Input model (vi command line, buffer switcher, leader menu, vi text inputs)
5. `pipist-spec-a1-protocol-core.md` — PIPIST SPEC — Appendix A1: Protocol, core (wire, envelope, types, kernel namespaces)
6. `pipist-spec-a2-protocol-domain.md` — PIPIST SPEC — Appendix A2: Protocol, domain namespaces and event catalogue
7. `pipist-spec-b1-web-adapter.md` — PIPIST SPEC — Appendix B1: Web-game adapter and headless web host
8. `pipist-spec-b1b-web-host-ui.md` — PIPIST SPEC — Appendix B1b: Web host renderer, configuration, tools and tests
9. `pipist-spec-c1-timeline-storage.md` — PIPIST SPEC — Appendix C1: Snapshot store and timeline storage (module `timeline`)
10. `pipist-spec-d1-gui-framework.md` — PIPIST SPEC — Appendix D1: GUI framework (window anatomy, chrome, theme, workspaces, common patterns)
11. `pipist-spec-d2-panels-work.md` — PIPIST SPEC — Appendix D2: Panels, part 1 (writing, running and finding things)
12. `pipist-spec-d3-panels-inspect.md` — PIPIST SPEC — Appendix D3: Panels, part 2 (time, state, code changes, experiments, system, Studio) and GUI done-when
13. `pipist-spec-e1-test-framework.md` — PIPIST SPEC — Appendix E1: Test framework, gates, evidence and cost control
14. `pipist-spec-e2-milestone-tests.md` — PIPIST SPEC — Appendix E2: Per-milestone test plans (M0–M14)


<!-- SOURCE-BEGIN: pipist-spec.md -->

# PIPIST — Unified Game Dev Environment: Build Specification

Spec v1.3, Nov 3 2026. v1.3 adds the exact appendices for timeline storage (C1), the GUI framework and every panel (D1–D3) and the test framework and per-milestone suites (E1–E2), merges C1's protocol additions into A2, and resolves the precedence between those appendices and the older numbered sections (see the document map). v1.1 added the module/lazy-loading architecture, the Dear ImGui + SDL3 GUI, the viewport bridge, Studio, the dependency policy, and Appendix A (protocol); v1.2 renames the project to **Pipist** (daemon `pipistd`, CLI `pipist`), merges Appendix B1's protocol additions into A1/A2, renames the headless host to `pipist-host-web`, and generalizes the headless web host and adapter to any HTML/JS game, including real-time canvas games and games without a text prompt (Appendix B1). Product, binary and path names come from `cmake/names.cmake` and `libpipist/names.h` only; no other file hardcodes them.
**Document map (all normative).** In the combined file `pipist-spec-MASTER.md` every part below appears in this order; the individual files are listed for reference.

| Part | Content | File |
|---|---|---|
| 1 | Sections 0–5: rules, vision, principles, architecture, modules, daemon, protocol overview | `pipist-spec.md` |
| 2 | Sections 6–13A: runtime, web, time travel, patching, experiments, GUI, viewport | `pipist-spec-part2.md` |
| 3 | Sections 13B–21: Studio, config, layout, dependencies, testing, milestones, notes, owner inputs | `pipist-spec-part3.md` |
| 13C | Input model | `pipist-spec-13c-input.md` |
| A1, A2 | Protocol core; protocol domain namespaces and events | `pipist-spec-a1-protocol-core.md`, `pipist-spec-a2-protocol-domain.md` |
| B1, B1b | Web-game adapter and headless web host (B1.0–B1.8; B1.9–B1.14) | `pipist-spec-b1-web-adapter.md`, `pipist-spec-b1b-web-host-ui.md` |
| C1 | Timeline and snapshot storage | `pipist-spec-c1-timeline-storage.md` |
| D1, D2, D3 | GUI framework; work panels; inspection and Studio panels, registry, actions | `pipist-spec-d1-gui-framework.md`, `pipist-spec-d2-panels-work.md`, `pipist-spec-d3-panels-inspect.md` |
| E1, E2 | Test framework; per-milestone suites M0–M14 | `pipist-spec-e1-test-framework.md`, `pipist-spec-e2-milestone-tests.md` |

**Precedence when documents disagree:** Appendix A for message formats; Appendix B1 for the web adapter and host; Appendix C1 for timeline storage, thinning, quota and `[timeline]` configuration (sections 4.6 and 9.1 and the `[snapshot]` table are superseded); 13C for input and keybindings; Appendix D for GUI framework, layouts, panels, themes and panel actions (it supersedes 13.3–13.5 and 13.9 where they differ); Appendix E for test tiers, gates and per-milestone suites (it supersedes section 16 and makes the "Done when" lines of section 17 exact); then the numbered sections; then older notes.
Sources (background only; no part of the build depends on them): the Game Dev Tool handover (Oct 29), the FPS engine design overview, the Los Ciegos handoffs (Oct 16, Oct 28, Nov 1) and the gang route design doc, plus the decisions made in this planning chat.

---

## 0. READ FIRST — rules for the unattended build run

This spec is meant to be executed by a Claude cloud session with little or no human supervision. Follow these rules.

1. **Do not stop to ask questions.** Where the spec is silent, choose the simplest option that fits section 2 (principles), record the choice in `docs/DECISIONS.md` (date, decision, alternatives, reason), and continue. Stop only for an irreversible or destructive action.
2. **Work milestone by milestone** (section 17), strictly in order. A milestone is done only when every item in its "Done when" list passes by running a command, not by reading code. Do not start a milestone while the previous one's tests fail.
3. **Keep `STATUS.md` current** at the repo root: current milestone, what works, what is broken, what is unverified, next 3 steps. Update it at every commit. A human will read this first.
4. **Commit after every green step**, small commits, imperative messages. Tag `m<N>-done` when a milestone finishes. **Do not add any "Co-Authored-By" trailer or Claude attribution to commits** (the owner's standing preference).
5. **Tests are the gate.** Each subsystem ships with tests (section 16). Never mark something done that you could not run. If something cannot be verified in the sandbox (for example a real GPU window), say so in `STATUS.md` under "Unverified" and add a test that will verify it on the owner's machine.
6. **Budget awareness.** Roughly $100 of credit. Do M0–M6 thoroughly before anything else; they are the product's spine. If budget looks short, cut from the end of the list, never from tests. Never leave the tree not building: the last commit of any session must build and pass tests.
7. **No network dependence at runtime.** Dependencies come from system packages or are fetched at configure time (CMake FetchContent, pinned to tags or hashes) into `third_party/`. The tool itself makes no network calls.
8. **Licences.** Every dependency must be FOSS (MIT, BSD, Zlib, BSL, Apache-2.0, MPL, LGPL used as shared libs, GPL for tools run as separate processes). Record each in `licenses/THIRD_PARTY_NOTICES.md`. Pipist's own code: **GPL-3.0-or-later** (default; owner may change).
9. The owner runs **Gentoo / OpenRC / X11**, non-root. All install instructions in docs use `sudo emerge`; the owner expects a note that commands assume a non-root user.
10. **The game's own files are the owner's property.** Treat any owner-supplied project (for example `examples/los-ciegos/`, which is optional) as read-only input: never rewrite its game code except through Pipist features being tested on a scratch copy.
11. **Lazy by default.** Never add eager startup work to the kernel or to profile `min`. The budgets in section 3A.12 are tests that gate every milestone.
12. **Dependency admission (section 2A) is mandatory.** No dependency is added without a `third_party/DEPS.md` row; `scripts/deps-check.sh` must pass in CI.
13. **Supersession:** where this document and an older note disagree, the later section number in this text wins; section 3A, 13, 13A, 13B, 13C, 15 and 17 are authoritative for modules, GUI, viewport, Studio, input, dependencies and milestone order.
14. **Normative appendices:** the exact message formats in Appendix A1/A2, the web adapter and host in Appendix B1, and the input model in section 13C are requirements, not suggestions. Generate JSON Schemas from Appendix A and keep them in sync with the code (A2.17).
15. **Generality:** nothing in Pipist code, defaults or tests may depend on one game's vocabulary (command words, element ids, function names). Defaults are derived from the page or stated in config; the owner's game appears only as a worked example. Every web-adapter feature must pass on all three fixtures (`hello-js`, `hello-ui`, `hello-canvas`; Appendix B1.14).

---

## 1. Vision

One program (a small family of cooperating processes) that handles all of a solo developer's dev environment needs for several kinds of games:

- text adventures and web games (JS/HTML) — any such game, with no assumption about its vocabulary or structure; the owner's text game (Los Ciegos / Tales of a Dope Fiend) appears in this document only as a **worked example, never as a requirement**
- a graphical 2D RPG reusing the text game's mechanics (stick-RPG-2 style spiritual successor)
- a map / grand-strategy game (Victoria 2 / EU4 style)
- an evolution / biology simulation
- a 3D first-person shooter (Cruelty Squad / Psycho Patrol R style, Lua-moddable, C/C++ runtime)

It provides: code editing, running the game, logs and debug panels, code search ("where is everything"), time travel with fork, live code injection without restarting, parameterized test experiments, code checking, and swappable language/runtime libraries. It offers two ways of working on the same files: **text mode** (nvim, CLI, console) and **Studio mode** (live viewport, hierarchy, inspector, schema-driven forms, live-tweak sliders; section 13B). It is **not** a game engine, but it must be able to supervise one (the FPS runtime) through the same protocol. Everything beyond a minimal write-compile-run core is a **module that loads lazily** (section 3A).

### Non-goals (v1)
Not a replacement for nvim (it hosts nvim). Not an asset authoring suite. Not a cloud service. No Electron. No bundled proprietary language servers. No multiplayer debugging beyond running several runtime instances. No node-graph visual scripting; no mesh, terrain, animation or material authoring in v1.

---

## 2. Principles (use these to break ties)

1. **Unix philosophy.** Small programs, one job each, text/JSON between them. Anything the GUI can do, `pipist` on the command line can do (the GUI console and the CLI share one command table).
2. **One protocol.** All components talk to the core only through the protocol (section 5). No component imports another's code. This keeps languages, front ends and modules swappable.
3. **Own what is central, borrow specialist engines.** Own: the kernel, protocol, module manager, snapshot store, timeline, patcher, experiment runner, format-preserving data editor, adapters, the `pipist-ui` layer. Borrow: tree-sitter, QuickJS-ng, Lua, SQLite, zstd, libvterm, SDL3, Dear ImGui.
4. **Fast, reliable, lightweight.** Budgets are in 3A.12 and are enforced by tests.
5. **Always have a correct fallback.** Every clever feature (function swap, instrumentation, dma-buf frames) falls back to a slower one that is always correct (reload + restore snapshot; shared-memory frames).
6. **Configuration over code.** Supporting a new game or language is a config file plus, at most, a small adapter in the game's own language.
7. **Local-first, no telemetry.** `pipistd` is a per-project user process started on demand (no OpenRC service).
8. **Lazy by default.** Nothing loads until it is asked for or required by something that was. The bare-minimum session (profile `min`) is: kernel + editor + build + run + log, in one small process plus nvim and your game. Everything else is a module that loads on first use, or explicitly (`pipist load x`), or via config.
9. **Spend resources where they pay.** Minimal by default, but do not skimp on what defines the product: correctness of snapshots/timeline/patching, index quality, viewport throughput, GUI responsiveness, test infrastructure. Do not spend on frameworks, abstraction layers or conveniences (2A lists examples).
10. **Vendor and own what we expect to bend.** Libraries we will likely modify (Dear ImGui, libvterm, QuickJS-ng) live in-tree under `third_party/vendored/` with a `third_party/patches/<lib>/*.patch` series, pinned to a commit. We never wait on upstream, and we never fork-and-forget: every patch is a file with a rationale header.

### 2A. Dependency and minimalism policy

**Admission test.** A third-party dependency is accepted only if **all** hold:
1. *Necessity:* writing it ourselves would cost more than about a week or carry high correctness risk (parsers, JS engine, SQL, compression, terminal emulation, windowing/GL context).
2. *Licence:* FOSS (MIT, BSD, Zlib, ISC, BSL, Apache-2.0, MPL, public domain; LGPL only as a dynamically linked library; GPL only as a separate process).
3. *Size:* small or already a normal system package; very small deps are vendored (single-file or two-file libraries preferred).
4. *Containment:* used by exactly one module (or one adapter file `*_adapter.cpp`); no third-party types in public headers, in the protocol, or in another module's code.
5. *Recorded:* one row in `third_party/DEPS.md`: name, pinned version/hash, purpose, owning module, added binary size (KB), alternatives rejected, how to remove it.

**Enforcement.** `scripts/deps-check.sh` runs in CI and fails if: a `FetchContent`/vendored directory has no DEPS.md row; the kernel binary links any shared library outside the allowlist (`libc`, `libm`, `libstdc++`, `libgcc_s`, `libpthread`, `libdl`, `libuv` if dynamically linked); any module links a library its manifest does not list.

**Hard caps.**
- Kernel (`pipistd`): at most 3 third-party libraries (libuv, yyjson, tomlc17). No SQLite, no zstd, no tree-sitter, no GUI code in the kernel.
- Stripped binaries: kernel < 2 MB; each process module < 8 MB (grammar libraries are separate files loaded on demand); `pipist-gui` < 15 MB excluding fonts.
- Clean release build of Pipist's own code (vendored third-party excluded from the timing): < 5 min on 8 cores; kernel alone < 30 s.

**Do not add** (examples of "bullshit just to have it"): Boost; logging frameworks (a ~150-line logger in `libpipist`); CLI-parsing libraries (a subcommand table shared with the GUI console); JSON/serialization frameworks beyond yyjson; reflection/meta libraries; ORMs; async/coroutine frameworks beyond the event loop; DI containers; in-process plugin ABIs; scripting engines other than QuickJS-ng and Lua; web servers/frameworks; GUI toolkits other than SDL3 + Dear ImGui.

**Spend freely on:** SQLite FTS5 and tree-sitter for the index; a real snapshot store (zstd + content addressing); libvterm for a correct terminal; libuv for a correct event loop; a proper test suite with sanitizers; shared-memory/dma-buf plumbing for the viewport.

**Language rules.** C++20. Exceptions may be used inside a component; no exception crosses a public library boundary (`Result<T, Error>` there). No RTTI in `libpipist`/kernel. Prefer value types and `std::span`/`string_view`. No global mutable state outside `main`/event-loop owners.

---

## 3. Architecture

Pipist is a **tiny always-on kernel** plus **modules that load only when needed** (section 3A), **clients** (CLI, GUI, tmux panes, scripts) and **runtime hosts** (the games being developed). Everything speaks JSON-RPC 2.0 (section 5).

```
   clients:   pipist (CLI)      pipist-gui (SDL3 + Dear ImGui)      tmux panes / scripts
                  │                      │                               │
                  └────────── JSON-RPC 2.0: unix socket (WebSocket for browsers/remote) ──────┘
                                         │
        ┌────────────────────────────────┴─────────────────────────────────┐
        │ pipistd KERNEL (always on; target < 8 MB RSS)                    │
        │ event loop · RPC router · bus · config+profiles · module manager │
        │ process supervisor (pipes, PTY) · log ring                       │
        │ builtin lazy modules: targets, watcher, editor(nvim), blob, game │
        └───┬──────────────┬──────────────┬──────────────┬─────────────────┘
            │ one socketpair per PROCESS module, spawned on first use
   ┌────────┴───┐ ┌────────┴───┐ ┌────────┴────┐ ┌───────┴────┐ ┌──────────────┐
   │ index      │ │ diag       │ │ timeline    │ │ patch      │ │ studio       │ …
   │ (tree-sit, │ │ (parse chk,│ │ (snapshots, │ │ (hot-patch │ │ (schemas,    │
   │  SQLite)   │ │  LSP, lint)│ │  branches)  │ │  planner)  │ │  fmtedit)    │
   └────────────┘ └────────────┘ └─────────────┘ └────────────┘ └──────────────┘
   experiments · trace · dap · logdb · plugins   (all process modules, all lazy)

   runtime hosts (supervised by `targets`, connect back as protocol clients):
   pipist-host-web · pipist-host-browser · native runtimes · any external process
        └─ side channels that bypass the kernel: viewport frames/input ↔ GUI (13A), PTY fds ↔ GUI
```

### 3.1 Processes

| Process | Language | Role | Always running? |
|---|---|---|---|
| `pipistd` | C++20 | Kernel: loop, router, bus, config, module manager, supervisor, builtin modules | Yes (per project) |
| `pipist` | C++20 | CLI + REPL client. Own subcommand table (shared with GUI console) | Per invocation |
| `pipist-gui` | C++20, SDL3 + Dear ImGui + OpenGL 3.3 | Full GUI client (13) | Only if launched |
| `pipist-mod-<name>` | C++20 | Process modules (3A.8) | Only when loaded |
| `pipist-host-web` | C++20 + QuickJS-ng | Headless web-game host (8.1, Appendix B1) | While a headless web target runs |
| `pipist-host-browser` | C++20 | Static HTTP + WebSocket bridge for browser games (8.2) | While a browser target runs |
| runtimes | any | Your games (C/C++/Lua/...) speaking the protocol | While a target runs |
| SDKs | JS, Lua, C header, Python | Game-side adapter, tweak, viewport, module helpers | n/a |

### 3.2 Hard rules

1. The kernel never parses source code, never opens SQLite, never compresses, never renders. If a feature needs those, it is a module.
2. Modules never talk to each other directly. They call each other through the kernel router (`kernel.call`), so loading, dependencies and lazy start stay in one place.
3. High-volume data bypasses the kernel: viewport frames and input (13A), PTY byte streams (the GUI receives the PTY master fd over `SCM_RIGHTS` via `proc.attach_pty`; over WebSocket it falls back to base64 `proc.output` events), snapshot payloads (blob files, never inline).
4. Every client and module must tolerate any other part being absent or restarting.
5. Everything is C++20 except the game-side SDKs. The build is CMake + Ninja.

---

## 3A. Module system and lazy loading

### 3A.1 Concepts
- **Kernel:** the always-on process. Small, boring, never crashes on bad input.
- **Module:** a unit of functionality with a manifest. Two kinds:
  - `builtin`: compiled into the kernel binary but **initialized lazily** (cheap: no allocation, no threads, no file descriptors until first use). A CMake option per builtin can compile it out entirely.
  - `process`: a separate executable (`pipist-mod-<name>`), spawned on demand, connected to the kernel by a `socketpair` (inherited as fd 3), speaking the same JSON-RPC. Freed by killing the process, so unloading really returns the memory.
- **Client:** CLI, GUI, scripts. Clients never load modules directly; they call methods and the kernel loads what is needed.

### 3A.2 Kernel responsibilities (complete list)
Event loop; JSON-RPC server (unix socket, WebSocket); method router and method registry; bus (topics, subscriptions, history ring); configuration with layers, profiles and live reload; module manager; process supervisor (spawn, pipes, PTY, process groups, signals, restart policy); log ring (in memory, default 20 000 records) and `log.*` basics; project discovery; socket/lock management. Nothing else.

### 3A.3 Module manifest — `module.toml`
Searched in order: `<project>/.pipist/modules/<name>/`, `~/.config/pipist/modules/<name>/`, `$PREFIX/share/pipist/modules/<name>/`. Later entries do not override earlier ones for the same name (first wins).

```toml
[module]
name = "index"
version = "1"
kind = "process"                 # "process" | "builtin"
exec = "pipist-mod-index"         # process only; resolved in $PREFIX/libexec/pipist/, then PATH
protocol = "1"
description = "Symbol, string, entity and text index"

[provides]
methods = ["search.*", "index.*"]       # globs registered in the router
events  = ["index.updated"]

[requires]
modules = ["watcher"]                   # started first; cycles are a load error

[activation]                            # what causes a cold module to start
on_method  = ["search.*", "index.*"]    # a client called one of these
on_event   = []                         # a subscription to one of these topics was created
on_startup = false                      # start at session start (profiles/config can force this)

[lifecycle]
start_timeout_ms = 3000
idle_unload_secs = 0                    # 0 = never auto-unload
restart = "on-failure"                  # never | on-failure | always
max_restarts = 3
backoff_ms = [200, 1000, 5000]

[resources]
rss_budget_mb = 300                     # soft; exceeding it emits module.state {degraded}

[config]
section = "index"                       # [index] table in pipist.toml is passed to mod.init

[ui]
panels = ["search", "outline", "symbols"]   # GUI shows stub panels for these until loaded
```

### 3A.4 States
`unavailable` (manifest present but executable/feature not built) → `registered` (cold) → `starting` → `ready` → (`degraded` | `stopping` → `registered`) ; `failed` (after max restarts; `pipist load` retries manually). Every transition emits `module.state {name, state, reason}`.

### 3A.5 On-demand activation flow
1. A client calls a method; the router matches the module's `provides.methods`.
2. If the module is not `ready`: state → `starting`; dependencies are started first (topological order); the kernel emits `module.loading {name}`.
3. Process modules: `fork/exec` with fd 3 = socketpair end, `PIPIST_MODULE=<name>`, cwd = project root, scrubbed environment plus `[env]` from config. The module sends `mod.ready {name, version, provides}`; the kernel replies `mod.init {config, project, paths, protocol}`; module answers; state → `ready`.
4. Calls arriving while `starting` are queued (max 256, per-call timeout = `start_timeout_ms`); on ready they are forwarded in order; on failure each gets JSON-RPC error `-32010 module_unavailable {name, reason}`.
5. A crashed module follows `restart`/`backoff_ms`; outstanding calls get `-32011 module_crashed`; clients may retry.
6. Event-activated modules start when the first matching subscription is created.

### 3A.6 Module ↔ kernel protocol
Standard JSON-RPC plus control methods:
- kernel → module: `mod.init`, `mod.shutdown {grace_ms}`, `mod.health`, `mod.stats` (returns `{rss_kb, cpu_ms, queue}`), `mod.config.changed {section, value}`.
- module → kernel: `bus.publish {topic, data}`, `kernel.call {method, params}` (routed to another module or builtin), `log.write`, `blob.put/get`, `mod.ready`.
- Modules are restartable from disk state alone. Each module documents its persistent state location under `.pipist/<module>/` (index: SQLite file; timeline: store + SQLite; patch: history file; experiments: results dir; studio: undo not persisted).

### 3A.7 Builtin modules (kernel-resident, lazily initialized)
| Name | Provides | Initializes when |
|---|---|---|
| `targets` | `[[target]]` handling: build/run/test, problem matchers, `game.start` launching of hosts | at session start (it is nearly free) |
| `watcher` | inotify watching, debounce, content hashes, `file.*` events | first `file.*` subscription, or when a required-by module starts |
| `editor` | nvim adapter (`editor.*`), own minimal msgpack codec, cursor/buffer events | first `editor.*` call or `pipist edit` |
| `blob` | content blob store paths, `blob.*` | first use |
| `game` | tracks connected runtime hosts, relays `game.*` and `runtime.*`, brokers viewport side channels (`viewport.*`) | first runtime connects or first `game.*` call |

### 3A.8 Process modules shipped in v1
| Module | Requires | Activation (default) | Owns third-party deps |
|---|---|---|---|
| `index` | watcher | `search.*`, `index.*` | tree-sitter + grammars (per-language `.so`, dlopen'd on first file of that language), SQLite |
| `diag` | index | `diag.*` | QuickJS-ng (parse check only), Lua (parse check only); own LSP client |
| `timeline` | blob | `timeline.*`, snapshot traffic from adapters | SQLite, zstd, xxHash |
| `patch` | index, watcher, timeline | `patch.*`, or `file.changed` while a game runs and `[patch].auto = true` | none (asks `index` for top-level item diffs) |
| `trace` | index | `trace.*` | none |
| `experiments` | targets, timeline (optional) | `exp.*` | none |
| `studio` | watcher | `scene.*`, `schema.*`, `tweak.*`, `asset.*` | tree-sitter (toml, lua, json grammars) |
| `dap` | targets | `dap.*` | none (own DAP client for lldb-dap/gdb) |
| `logdb` | – | `log.query` with `persist = true`, or `[log].persist` | SQLite |
| `plugins` | – | declared plugins | none |

Method namespaces not listed here (`session`, `project`, `config`, `proc`, `module`, `editor`, `game`, `runtime`, `viewport`, `blob`, basic `log`) are served by the kernel or its builtins.

### 3A.9 Profiles
A profile is a named module set. Shipped (in the built-in default config):

| Profile | Modules started eagerly | Use |
|---|---|---|
| `min` (**built-in default**) | builtins only (`targets`, `watcher`/`editor`/`game` lazily) | write, compile, run |
| `code` | min + `index`, `diag` | editing with search and diagnostics |
| `play` | min + `timeline` | playing and testing games with time travel |
| `dev` | code + `timeline`, `patch` | everyday development |
| `studio` | dev + `studio`, GUI | visual mode |
| `full` | everything shipped | exploration |
| `ci` | targets, diag, experiments, timeline; no editor, no GUI | headless |

Profiles can `extends = ["code"]`, add `modules`, and list `lazy_only` modules that never start unless explicitly requested (even if some other profile includes them). User-defined profiles live in config.

### 3A.10 Selection and precedence (highest wins)
CLI flags → environment (`PIPIST_PROFILE`, `PIPIST_WITH`, `PIPIST_WITHOUT`, `PIPIST_SOCKET`) → `pipist.local.toml` → `pipist.toml` → `~/.config/pipist/config.toml` → built-in default (`min`). Project templates written by `pipist init` set `profile = "dev"`; with no config at all you get `min`.

### 3A.11 Invocation (CLI contract)
```
pipist up    [--profile P] [--with a,b] [--without c] [--gui|--no-gui]
            [--workspace W] [--target T] [--open FILE[:LINE[:COL]]]...
pipist edit  [FILES...]          # up --profile min --no-gui if no daemon; runs nvim attached in this terminal
pipist build [TARGET] | run [TARGET] | test [TARGET]    # work in the min profile
pipist gui                       # start/attach the GUI to the running daemon
pipist modules                   # table: name, state, RSS, uptime, requires
pipist load a b … | unload a b … [--force] | reload a
pipist down | status | doctor
```
- **Daemon discovery:** `$PIPIST_SOCKET`, else walk up from cwd to the nearest `pipist.toml`; project hash → `$XDG_RUNTIME_DIR/pipist/<hash>.sock` (fallback `/tmp/pipist-$UID/`). If no socket: take `flock` on `<hash>.lock`, double-fork `pipistd --daemonize`, poll the socket up to 500 ms. Stale sockets/locks are cleaned.
- **Ad-hoc mode:** outside any project, `pipist edit foo.c` / `pipist run` use an implicit project rooted at cwd with the `min` profile and no `pipist.toml`.
- **Idle exit:** `[daemon].idle_exit_secs` (default 0 = never) shuts down when no clients, no supervised processes and no running targets remain.
- **GUI behaviour for cold modules:** panels whose module is not loaded render as a dimmed stub: *"Search — module `index` not loaded  [Load] [Always load]"*. Opening a panel loads its module when `[gui].autoload_on_open = true` (default). The status bar shows module states and total RSS; a Modules panel lists everything with Load/Unload buttons.

### 3A.12 Budgets (tests, not aspirations; fail CI if exceeded by more than 25%)
| Measure | Budget |
|---|---|
| Kernel cold start (exec → first `ping` reply) | < 40 ms |
| Kernel idle RSS, `min` profile | < 8 MB; 0% CPU over 10 s idle |
| `pipist edit file` → nvim visible (warm page cache) | < 150 ms |
| `pipist run` overhead over raw exec of the same command | < 30 ms |
| Process list after `pipist up --profile min` | exactly: `pipistd` (no module processes) |
| Builtin module first-use init | < 5 ms |
| `timeline` module spawn → ready | < 100 ms |
| `index` spawn → ready with warm DB / cold index of the 25k-line reference project | < 250 ms / < 2 s |
| GUI first frame, `min` profile, software GL | < 600 ms; with GPU < 400 ms |
| GUI idle | 0 frames rendered in 10 s of no input and no events |
| Protocol round trip (local socket) | < 2 ms p99 |

### 3A.13 Laziness inside modules
Tree-sitter grammars load on the first file of that language. SQLite databases open on first query. Language servers (`diag`) start per language on the first diagnostics request for that language and never at module start (`[diag.lsp].autostart = false` by default). Language packs are data and are read on demand. Runtime hosts exist only while a target runs.

### 3A.14 Extending Pipist
A user module is a directory with `module.toml` and an executable in any language that speaks the protocol on fd 3. Helper SDKs: `sdk/pipist_module.py`, `sdk/pipist-module.js`, `sdk/pipist_module.h`. A module can add GUI panels declaratively (13.8) without recompiling the GUI.

---

## 4. Core daemon (`pipistd`) subsystems

> **Module mapping (v1.1).** The subsections below describe functionality; where each lives is defined in 3A. 4.1, 4.2, 4.9 and the log ring of 4.10 = kernel; 4.3 = builtin `watcher`; 4.4 = module `index`; 4.5 = module `diag`; 4.6 = module `timeline`; 4.7 = module `patch`; 4.8 = module `experiments`; persistent log queries of 4.10 = module `logdb`; 4.11 = module `plugins` (and any user module, 3A.14). Nothing from 4.4–4.8 may be linked into the kernel.

### 4.1 Project model and configuration
- A **project** is a directory containing `pipist.toml` (section 14). `pipistd --project <dir>` opens it; `pipist up` starts it in the background if not running (socket at `$XDG_RUNTIME_DIR/pipist/<project-hash>.sock`; fallback `/tmp/pipist-$UID/`).
- Config is layered: built-in defaults < `~/.config/pipist/config.toml` < project `pipist.toml` < `pipist.local.toml` (git-ignored) < CLI flags. Reload on change, emit `config.changed`.
- A project declares: source roots, ignore globs, **language packs** in use, **targets** (how to build/run/test), **runtime hosts**, **adapter** settings, snapshot policy, lint rules, editor command, GUI layouts.

### 4.2 Message bus
- In-process pub/sub with topics (`file.*`, `index.*`, `game.*`, `log.*`, `diag.*`, `timeline.*`, `patch.*`, `exp.*`, `proc.*`, `config.*`).
- Clients subscribe with glob patterns. Bounded per-client queues; slow clients get a `bus.dropped {count}` event, never block the daemon.
- A ring buffer of the last N events (default 10 000) is replayable: `bus.history {topic, since}`.

### 4.3 File watcher
- inotify on Linux (own thin wrapper), recursive, debounced (default 80 ms), ignores per `.gitignore`/config. Emits `file.changed/created/deleted/renamed {path, hash}`.
- Maintains a content-hash table; the **source revision id** = hash of all tracked source hashes, used to tag snapshots.

### 4.4 Index and search (the "where is everything" backbone)
- **Parsing:** tree-sitter with grammars per language pack. For `.html`, parse HTML, then parse each `<script>` block as JS with a line/col offset map (so inline scripts index with correct positions). `<style>` blocks as CSS.
- **Symbol index (SQLite):** functions, methods, classes, top-level const/let/var, Lua tables/functions, C/C++ declarations (via tree-sitter, optionally enriched by clangd), JSON/TOML keys. Fields: kind, name, file, range, parent, signature, doc comment.
- **Text search:** trigram index (or SQLite FTS5) over all source; ranked results, regex mode, case modes, file-type filters. Incremental update on `file.changed`.
- **String/dialogue index:** every string literal and template literal with its range, normalized text, and enclosing function. Exact-text lookup (used by "where did this text come from").
- **Entity-definition index (generic):** configurable per project via `[[index.entity]]` rules (a tree-sitter query or regex plus a naming scheme), e.g. for Los Ciegos: keys of `ROOMS`, `NPCS`, `ITEM_DESC`, `NPC_SHOPS`, `CLOTHES`, `DRUGS`, `GANG_JOBS`. Lets `pipist where npc:la_senora` list the definition and all references.
- **Cross references:** best-effort call graph and identifier references from tree-sitter (name-based, flagged `approximate`); upgraded by LSP `references` when a language server is available.
- Targets: index a 25k-line, 29-file JS project cold in < 2 s; incremental re-index of one file in < 50 ms; query < 30 ms.

### 4.5 Diagnostics and code checking ("the parser")
Sources, unified into one `Diagnostic {file, range, severity, source, code, message, fix?}` feed (`diag.updated`):
1. **Syntax**: tree-sitter ERROR/MISSING nodes (instant, every keystroke-save, all languages).
2. **Engine parse**: for JS, also parse with QuickJS (`JS_Eval` with `COMPILE_ONLY`) for exact engine errors; for Lua, `luaL_loadbuffer`.
3. **Language servers** (LSP client built into the daemon): clangd, lua-language-server, a JS/TS server or eslint, ruff/pylsp, per pack config. Optional; absence is not an error, just a warning in `pipist doctor`.
4. **Project lint rules** (built-in rule engine, configured in `pipist.toml`): see 11.
5. **Build output parsers**: regex/problem-matchers for gcc/clang/cmake/ninja/node/lua errors from supervised build processes.

### 4.6 Snapshot store and timeline (section 9; exact design in Appendix C1)
Module `timeline`: content-addressed, zstd-compressed chunks in pack files with SQLite (WAL) metadata, full-manifest snapshots (no delta chains), tiered thinning under a disk quota, mark-and-sweep GC, crash recovery. Appendix C1 is normative for everything about storage; this paragraph is only a pointer.

### 4.7 Hot-patch manager (section 10)
Decides per change which patch tier applies, instructs the runtime host, records outcome, falls back when needed.

### 4.8 Experiment runner (section 12)
Spawns N headless host instances, applies base state + inputs + overrides, collects results.

### 4.9 Process supervisor
Spawns and supervises: runtime hosts, build commands, language servers, nvim, arbitrary tools. Captures stdout/stderr into the structured log, restarts per policy, kills process groups cleanly, reports `proc.started/exited/crashed`. PTY mode for interactive children (nvim, shells) with resize support. Runs children with a scrubbed environment plus configured vars.

### 4.10 Structured log
All sources (daemon, hosts, games via adapter `log`, tools) write `LogRecord {ts, tick?, level, source, channel, message, fields}` into the kernel's in-memory ring (default 20 000 records). `log.query {filter, since, limit}` reads the ring, or the SQLite store when the `logdb` module is loaded (`[log].persist = true`); live stream `log.record`. File:line patterns in messages become click-to-source links.

### 4.11 Plugin host
Daemon plugins are **external processes speaking the protocol** (any language) declared in config (`[[plugin]] command=…, subscribes=[…]`). No in-process dlopen plugins in v1 (reliability). Language packs (section 6) are data plus optional plugin processes. Plugins are process modules (3A.14) and can add GUI panels declaratively (13.8); there are no GUI plugin binaries.

---

## 5. Protocol

> **Overview only.** The exact, normative message formats (envelope, errors, types, every method, every event) are in **Appendix A1 and A2**. Where this section differs, the appendices win. In particular the event format shown in 5.4 is superseded: events are `{"method":"event","params":{"topic","seq","ts","data"}}` (A1.2).

### 5.1 Transport and framing
- **JSON-RPC 2.0**, UTF-8, newline-delimited (NDJSON) over a unix domain socket. The same messages over WebSocket text frames (for the browser agent and any web UI). Default WebSocket bind is `127.0.0.1` only, with a per-session token in the URL.
- Large/binary payloads (snapshots, screenshots, assets) never travel inline: they are stored in the blob store and referenced as `{"blob":"sha256:<hex>","size":N,"mime":"…"}`; clients fetch with `blob.get` (base64 chunks) or read the file path from `blob.path` when local.
- Version handshake: first message is `hello {client, protocol:"1", capabilities:[…]}`; reply carries server version, project info, and negotiated capabilities. Unknown methods return JSON-RPC error `-32601`; unknown optional fields are ignored.
- Methods are `namespace.verb`. Notifications (no id) are events. All times are ms since the project epoch or ISO-8601 UTC.

### 5.2 Method catalogue (v1)

| Namespace | Methods |
|---|---|
| `session` | `hello`, `ping`, `shutdown`, `subscribe {patterns}`, `unsubscribe` |
| `project` | `info`, `config.get`, `config.set`, `files.list`, `files.read`, `files.write` (for tools; editor writes go through nvim) |
| `search` | `text {query, regex?, case?, globs?, limit}`, `symbols {query, kind?}`, `strings {text, exact?}`, `entities {query, type?}`, `outline {file}`, `refs {symbol|pos}`, `where {query}` (meta-search over all of the above) |
| `editor` | `open {file,line?,col?}`, `goto {file,line,col}`, `current`, `buffers`, `command {ex}`, `attach`/`detach` |
| `diag` | `list {file?, severity?}`, `run {checks?}`, `fix {id}` |
| `proc` | `start {id|cmd}`, `stop`, `restart`, `list`, `write {id, data}`, `resize {id, cols, rows}`, `signal`, `attach_pty {id}` (returns the PTY master fd via SCM_RIGHTS on unix sockets) |
| `game` | `start {target, options}`, `stop`, `reload {mode}`, `pause`, `resume`, `step {n}`, `input {…}`, `state.get {path?}`, `state.set {path, value}`, `state.watch {paths}`, `output.tail`, `screen.get` |
| `timeline` | `list {branch?, range?}`, `branches`, `get {tick}`, `goto {tick, fork:true}`, `bookmark {tick,name}`, `diff {a,b}`, `prune {policy}` |
| `patch` | `apply {files|text, tier?}`, `preview`, `history`, `revert {id}`, `status` |
| `trace` | `start {mode}`, `stop`, `back {n}` (what executed in the last n ticks), `now` (functions/strings/entities touched this tick), `who_wrote {path}` (if provenance on) |
| `exp` | `list`, `run {name|inline}`, `status`, `cancel`, `results {run}` |
| `log` | `query`, `tail`, `clear`, `levels.set` |
| `blob` | `get`, `path`, `put` |
| `runtime` | pass-through namespace for native runtimes: `runtime.pause/resume/reload_scene/reload_asset/set_variable/get_entity/spawn_entity/teleport_player/physics_inspect` (names taken from the FPS design). Pipist forwards these to the connected runtime and does not interpret them. |
| `module` | `list`, `load {names}`, `unload {names, force?}`, `reload`, `stats`, `profile.get`, `profile.set` |
| `viewport` | `offer`, `attach`, `detach`, `list` (control only; frames and input use the side channel, 13A) |
| `scene` / `asset` | `scene.tree/get/set/spawn/delete/duplicate/reparent/rename/select/pick/bounds/mode/reload/save`, `asset.list/thumbnail` — implemented by runtimes (13B.8) |
| `schema` | `list`, `get {name}`, `validate {file}`, `infer {files}` |
| `tweak` | `register`, `list`, `set`, `reset`, `commit {path}`, `preset.save/load/list` |
| `ui` | `panel.set`, `panel.patch`, `panel.close`; event `ui.event` (13.8) |
| `dap` | `launch`, `attach`, `breakpoints.set`, `continue/next/step`, `stack`, `vars`, `eval` |
| `target` | `list`, `run`, `stop`, `status` (A1.11) |
| `studio` | `read`, `edit`, `undo`, `redo`, `play`, `stop`, `changes`, `keep` (A2.12) |
| `index` | `status`, `reindex`, `spans`, `transform` (A2.9, B1.2) |
| `adapter` | served by hosts: `describe`, `fingerprint` (A2.16) |
| `gui` | served by `pipist-gui` via `session.provide`: `action.*`, `cmdline`, `panel.*`, `workspace.*`, `focus`, `mode`, `screenshot`, `dump`, `keys`, `notify` (A2.14) |

### 5.3 Events (notifications)
`file.changed`, `index.updated`, `diag.updated`, `config.changed`, `proc.started|exited|crashed|output`, `game.started|stopped|ready|tick {tick,t}|output {text,class}|crashed`, `timeline.snapshot {tick,id,bytes}`, `timeline.branch {id,from}`, `patch.applied|failed|fellback {tier}`, `trace.hit`, `exp.progress|done`, `log.record`, `editor.cursor {file,line,col}`, `bus.dropped`, `module.state {name,state,reason}`, `module.loading {name}`, `viewport.offered|attached|lost|fallback`, `scene.selection {ids}`, `scene.changed {ids}`, `tweak.changed {path,value}`, `ui.event {panel,id,kind,value}`.

### 5.4 Example exchanges
```json
{"jsonrpc":"2.0","id":7,"method":"search.where","params":{"query":"la senora dress code"}}
{"jsonrpc":"2.0","id":7,"result":{"hits":[
 {"kind":"function","name":"laSenoraDressCheck","file":"js/10-npc-talk.js","range":[412,12,447,1],"score":0.92},
 {"kind":"string","text":"Your men turn you away…","file":"js/10-npc-talk.js","range":[430,9,430,60],"in":"laSenoraDressCheck"}]}}

{"jsonrpc":"2.0","id":9,"method":"timeline.goto","params":{"tick":412,"fork":true,"reload":"patch-then-restore"}}
{"jsonrpc":"2.0","method":"patch.applied","params":{"id":"p31","tier":"function-swap","functions":["laSenoraDressCheck"]}}
{"jsonrpc":"2.0","method":"timeline.branch","params":{"id":"b4","from":"b2@412"}}
```

---


<!-- SOURCE-END: pipist-spec.md -->

---

<!-- SOURCE-BEGIN: pipist-spec-part2.md -->

# PIPIST — Build Specification v1.3, Part 2 of 3 (sections 6–13A)

See the document map in Part 1 (`pipist-spec.md`).

---

## 6. Language packs and plugins

A **language pack** is a directory (`packs/<name>/` shipped, or `~/.config/pipist/packs/`, or inside a project) with `pack.toml`:

```toml
[pack]
name = "javascript"
version = "1"
extensions = [".js", ".mjs", ".html"]
[parse]
grammar = "tree-sitter-javascript"        # shared lib path or built-in id
embedded = [{ in = "html", node = "script_element", lang = "javascript" }]
queries = "queries/"                      # symbols.scm, strings.scm, refs.scm
[check]
engine_parse = "quickjs"
lsp = { command = "typescript-language-server", args = ["--stdio"], optional = true }
[run]
hosts = ["web-quickjs", "browser", "node"]
[patch]
tiers = ["function-swap", "data-merge", "reload-restore"]
[adapter]
sdk = "sdk/pipist-adapter.js"
```

Shipped packs for the default build:

| Pack | Parse | Check | Run / host | Patch tiers |
|---|---|---|---|---|
| `javascript` (+`html`,`css`) | tree-sitter js/html/css | QuickJS parse, optional eslint/ts server | web-quickjs, browser, node | function-swap, data-merge, reload-restore |
| `lua` | tree-sitter-lua | `luaL_loadbuffer`, lua-language-server, luacheck | native runtime (embedded Lua), standalone lua | module-reload, function-swap, reload-restore |
| `c-cpp` | tree-sitter-c / -cpp | clangd, clang-tidy (optional), build output parser | native runtime (supervised executable) | module-reload (advanced, M8+), restart-restore |
| `python` | tree-sitter-python | ruff, python-lsp-server (optional) | python host (for sim tools) | module-reload, restart-restore |
| `glsl` | tree-sitter-glsl | glslangValidator | native runtime | shader-hot-reload (runtime-implemented) |
| `data` (json, toml, yaml, csv) | tree-sitter/own | schema check if provided | all | data-merge |
| `markdown` | tree-sitter-markdown | none | none | none |

New game types add a pack only if they introduce a new language; otherwise they add a **host/target** in `pipist.toml` plus an adapter.

---

## 7. Game adapter contract

The adapter is the small game-side layer that makes a game controllable. Every host and SDK implements the same logical contract; the wire form is protocol messages (for native/browser) or direct function calls (inside `pipist-host-web`).

```
snapshot() -> serializable state tree          # required for time travel
restore(state)                                 # required; must redraw screen and return control
onTick(cb)                                     # game calls cb() after each unit of play
getState(path) / setState(path, value)         # optional; powers inspector and experiments
input(event)                                   # optional; headless input injection
output hook                                    # optional; structured game output (text, class)
hotpatch hooks: beforePatch(info), afterPatch(info)   # optional
migrate(oldState, info) -> newState            # optional; state-shape changes after code edits
meta() -> {name, version, tickUnit, determinism:{rng,clock}}   # optional
```

- **Tick** is the game's unit of play: one input for turn-based and UI games, every N-th frame for real-time games; `auto` picks between them (Appendix B1.4). Declared in `meta().tick_unit`.
- **JS SDK** (`sdk/pipist-adapter.js`, ~150 lines, no dependencies): defines `window.__pipist` / `globalThis.__pipist`, registers the game's `snapshot/restore/onTick`, connects to the daemon (WebSocket in browsers; direct binding in `pipist-host-web`), batches `game.output`, `game.tick`.
- **Lua SDK** (`sdk/pipist.lua`): same contract, uses a socket or in-process binding provided by the native runtime.
- **C header** (`sdk/pipist_adapter.h`): `pipist_register_adapter(const pipist_adapter_vtable*)`, C ABI, usable from C++; transport via unix socket helper `libpipist-client`.
- **Python SDK** (`sdk/pipist_adapter.py`): minimal.

### 7.1 Worked example: Los Ciegos (generic mechanism in Appendix B1)
The generic web-game adapter (automatic state registry, tick and quiescence rules, DOM capture, restore) is specified in Appendix B1 and needs no game-specific code. This subsection lists what the example game requires of it:
- `snapshot()` must capture **more than `G`**: `combatState`, `replayRngQueue`, `dialogueSession`, `barterSession`, and every other module-level `let`/`var` (an automated audit step lists them, see M5). Functions and DOM references are not serializable; the adapter reconstructs them from keys.
- Also capture screen scrollback (the `#output` content or an equivalent captured buffer) so a restore shows history, or re-render the last K lines.
- Game has `G.eventLog` (save = replay of CMD/EVT lines). Snapshots are an additional, independent mechanism and must not mutate `eventLog`.
- Tick = one handled command (hook `handleCommand` completion, or the `Enter` handler end).
- Async narration uses `setTimeout` beats. The host's virtual clock must let the adapter wait for **quiescence** (no pending timers) before snapshotting, and `restore` must cancel pending timers.

---

## 8. Runtime hosts (the "viewer" side)

All hosts implement the adapter contract; the daemon never needs to know which one is running (`meta.host` is informational).

### 8.1 `pipist-host-web` — headless web-game host
A C++ program embedding **QuickJS (quickjs-ng, MIT)** that loads a game's HTML + scripts without a browser. **Appendix B1 is normative** (boot sequence, loader rules, DOM/Web API shim table, virtual clock and RNG, state registry, snapshots, tick/input/quiescence rules, renderer, tools). Summary:
- Runs any HTML/JS game: DOM/text/UI games fully; canvas games (including real-time `requestAnimationFrame` games) against a recording no-op canvas; WebGL and audible audio need the browser backend.
- Zero game changes: scripts load through `index.transform`, which makes module-level bindings reachable (B1.2).
- Virtual time and a seeded RNG make runs reproducible and fast-forwardable (`realtime`, `fast`, `stepped`).
- Output reaches clients as structured events plus an ANSI terminal rendering of the page's text regions (or a status summary for canvas-only games).
- A `node` fallback backend with the same adapter interface exists for games QuickJS cannot run; `pipist doctor --host-compat` diffs the host against Chromium.
- Pin one JS engine per project in `pipist.toml`; `Math.*` can differ in the last bits across engines and would quietly break replay-style comparisons.

### 8.2 Browser backend
- `pipist-host-browser` (a supervised host executable launched by a target, not part of the kernel) serves the game directory over HTTP on localhost (static files) and **rewrites HTML on the fly** to inject `/__pipist/agent.js` (the adapter + WebSocket client + optional instrumentation). Works with any browser (Firefox or Chromium) and needs no browser-specific automation protocol.
- Live reload and restore: on `file.changed`, daemon decides `reload`/`patch` (section 10); the agent receives `reload` → page reloads → agent reconnects → daemon sends `restore(snapshot)`.
- Optional: launch via a configured command (`firefox --new-window …`); the page always lives in an external browser window (embedding is out of scope, see 13.9).
- Screenshots/console capture are extras via CDP/Marionette, off the core path.
- The agent, the script transform and the restore semantics are specified in Appendix B1.10.

### 8.3 Native runtime protocol (FPS and graphical games)
A native runtime (e.g. `./game-runtime --project …`) connects to the daemon's unix socket as a client and implements the `game.*` and `runtime.*` namespaces. Pipist supervises the process, forwards `runtime.*` calls unchanged, shows its log, and offers snapshot/timeline when the runtime provides `snapshot/restore` (serialized with the runtime's own format into blobs). A reference **demo runtime** (M8) proves the path.

### 8.4 Where-tracing (instrumentation)
- **JS:** the browser backend or the headless web host rewrites source on load: inserts `__f(<id>)` at each function entry, on the same line so line numbers never shift. A per-tick set of executed function ids maps back to file/line via the index. Strings/dialogue map back by exact text; entities by key lookup into the entity-definition index. Toggleable, default off in `play`, on in `debug`.
- **Value provenance (later, optional):** Proxy over the state tree attributing each write to the current function: `trace.who_wrote state.npcs.x.mood`.
- **Lua:** `debug.sethook` call hook (sampling off by default). **C/C++:** not instrumented by Pipist; rely on gdb/DAP.

---

## 9. Time travel

### 9.1 Snapshots
- Taken **per tick** by default (per host-defined unit for real-time games). **Retention, quota and thinning are specified exactly in Appendix C1** and configured under `[timeline]` (C1.11): default quota 8 GiB with a free-disk guard, tiered thinning that keeps recent snapshots dense and older ones sparse (starting at 80% of quota), and permanent protection for bookmarks, pins, fork roots, branch heads, the root, edit-state, golden and patch-base snapshots. Persistence defaults to `project` and is configurable (`project|session|pinned`).
- Stored in the **daemon** on disk, never only in the page (pages die on reload, exactly when snapshots are needed; this also survives crashes). The host sends serialized state as a blob (JSON, structured-clone-like encoding that handles Map/Set/cycles/typed arrays; functions and DOM refs are rejected with a clear error naming the path).
- Metadata per snapshot is `SnapshotMeta` (A2.5). Chunked, content-addressed, zstd; identical chunks deduplicate (C1.2–C1.4).
- Quiescence rule: snapshot only when the host reports no pending timers/async work (otherwise defer to the next quiet moment and note it).

### 9.2 Timeline as a tree
Time is a **tree of branches**, not a line. `timeline.goto {tick, fork:true}` restores the snapshot at that tick and starts a **new branch** from it; the old branch stays intact. Each branch records the source revision(s) it ran under. The GUI shows this tree with a scrubber.

### 9.3 Restore semantics (the "fork")
1. Select snapshot S (tick K) on branch B.
2. Apply any pending code changes (reload or hot-patch, section 10).
3. Restore S into the (new or live) runtime; adapter `restore()` redraws the screen and returns control to the player.
4. Create branch B′ from S. Subsequent ticks snapshot onto B′.
5. If the state shape changed (key diff between S and a fresh `snapshot()` after boot), warn with the diff; call `migrate()` if defined; otherwise proceed and flag the branch `shape-mismatch`.

### 9.4 Replay tier (optional, per game, specified now, built late)
Input log + RNG log + virtual clock make re-simulation possible: "what if the code had always been this". Games declare `meta().determinism`. The daemon records inputs/RNG per tick when declared. Replay is **fragile** by nature (an edit that changes the order or count of RNG draws desyncs a pre-recorded RNG queue — this is exactly the case for Los Ciegos's `rrand()` queue). Implement after everything else (M14); label results `replay (may diverge)`; detect divergence with periodic state hashes and stop with a report. The snapshot fork is the supported, generic mechanism.

---

## 10. Hot patching — inject new code mid-run, no restart

### 10.1 Tiers, tried in order of speed; every tier can fall back to the next
| Tier | What it does | Used for |
|---|---|---|
| **T1 function-swap** | Re-evaluate only changed *function declarations/expressions* in the live realm, leaving state and timers untouched | JS functions, Lua functions |
| **T2 data-merge** | Update changed *top-level data tables/objects* in place (deep assign by key; delete removed keys if configured) so existing references stay valid | `ROOMS`, `NPCS`, `ITEM_DESC`, Lua tables, JSON/TOML data |
| **T3 module-reload** | Reload a whole module/file, then transplant function bodies and upvalues onto the old objects | Lua modules, Python modules, C/C++ shared modules with host-owned state (advanced, M8+) |
| **T4 reload-restore** | Reload everything and `restore(latest snapshot)` | Always correct fallback |
| **T5 restart-restore** | Restart the process, then restore | Native runtimes without hot code support |

### 10.2 Change analysis (the indexer drives it)
On `file.changed`, diff old vs new parse trees at top-level granularity. Classify each changed top-level item as: function body change; data literal change; new/removed declaration; top-level *statement with side effects* (a call, an assignment, a `let` initializer with calls). A change touching a side-effect statement, a signature that closures capture, a `const`/`let` binding in lexical scope, a class shape, or an unparseable file → **go to T4** (never silently skip). Pure function bodies → T1. Pure data literals → T2. Anything that the patcher cannot classify → T4.

### 10.3 JS specifics (classic scripts, shared global scope)
- T1: evaluate the new function text as a function declaration/assignment in the global scope (indirect eval) so that all existing callers (resolved by name at call time) see it. `const`/`let` globals cannot be reassigned by eval: data tables are mutated in place (T2), not rebound.
- Closures that captured the *old* function object keep calling the old code. Detect and warn when a patched function is referenced from a captured table/closure (best effort: scan registered handler tables and `setTimeout` callbacks the host tracks).
- Patch is transactional: evaluate in a trial context first (syntax + load check); on any exception, roll back and report `patch.failed`.
- After patch, call `afterPatch`, then verify the game still passes a cheap `assertAlive` (adapter `snapshot()` succeeds).

### 10.4 Lua specifics
Module reload via `package.loaded[name]=nil; require`; then walk old/new module tables and for each function replace the old closure's code using `debug.upvaluejoin`/`debug.setupvalue` so shared upvalues stay live; metatables updated in place. The FPS runtime's mod system benefits from this directly (weapon/enemy definitions reload without losing level state).

### 10.5 Safety rails
- Every patch gets a `patch.history` entry with a diff, tier, result and the source revision; `patch.revert` replays the previous text.
- A patch never runs while the host is mid-tick; the host applies it at the next quiescent point.
- `pipist.toml` can pin files as `no-hotpatch` (forces T4) or `rerun-ok` (top-level code may be re-executed).

---

## 11. Project lint rules (the extensible "parser" layer)

A tiny rule engine: each rule is a tree-sitter query or a script plugin returning diagnostics. Built-ins (enable per project):
- `load-order`: in multi-file classic-script projects, flag top-level code in file N that calls a function declared in a later file (the exact Los Ciegos rule; generalizes `loadcheck.js`). Reads script order from `index.html`.
- `unresolved-global`: identifier used but never declared/defined (JS, with a configurable allowlist: DOM globals).
- `determinism`: flag `Math.random`, `Date.now`, `new Date()`, and `setTimeout`-ordered logic inside configured "outcome-determining" modules; message suggests the project's logged RNG wrapper (configurable name, e.g. `rrand`). Informational by default.
- `unlogged-state`: heuristics for game-state writes not routed through a configured logging function (configurable; Los Ciegos: new flags that affect later outcomes must go through `logEvt`).
- `anchor-hazard`: not a code rule — a warning used by `patch.preview` when a text edit range ends on an `if (...) {` opener (the recurring edit hazard in the handoffs).
- `duplicate-definition`: same top-level function/key defined twice.
- `todo-fixme`: lists markers.
Project-specific checks live in `pipist.toml` as `[[lint.rule]]` entries.

---

## 12. Experiments (test mode with changed parameters)

Purpose: "tweak code or parameters, drop back into a gameplay sequence, and see what happens", reproducibly and in bulk.

`experiments/<name>.toml`:
```toml
[experiment]
name = "chuy-run-pay"
base = { snapshot = "bookmark:before-chuy-job" }      # or { fresh = true, seed = 42 } or { branch="b2", tick=412 }
host = "web-quickjs"
mode = "fast"                       # virtual time, no real waiting
[script]
inputs = ["go hendrix", "talk chuy", "ask for work", "take package", "go downtown", "talk man"]   # or file = "scripts/run1.txt", or { recorded = "branch:b2 ticks 412..430" }
[[override]]
path = "G.flags.chuyRep"            # state override via adapter setState
values = [0, 2, 5]
[[override]]
code = "patches/pay-25-to-30.patch" # optional code patch applied via hot-patch tiers
[[override]]
path = "CONFIG.payRate"             # any addressable value, JS/Lua/data
values = { from = 0.2, to = 0.4, step = 0.05 }
[sweep]
strategy = "grid"                   # or "list", "random(n=50)"
repeat = 5                          # runs per combination with different seeds
[[assert]]
expr = "G.cash >= 0"
[[assert]]
expr = "G.flags.gangLockedOut == false"
[[collect]]
paths = ["G.cash", "G.flags.chuyRep", "G.gameMinutes"]
output = ["last_text(20)"]          # also: full transcript, screenshot, diag errors
```
- Runner launches up to `jobs` (default = CPU count−1) headless hosts, each from the base snapshot, applies overrides, feeds inputs, collects results, evaluates assertions, and writes `.pipist/experiments/<run-id>/{results.json,report.md,transcripts/}`. The report is a table of parameter combinations → collected values, with pass/fail and first-failure transcript excerpt.
- Interactive variant (`pipist exp try`): same thing but leave the final run live in the GUI viewer.
- A **playthrough regression** mode records a scripted playthrough and its transcript hash as a golden file; `pipist exp check` fails on divergence (replaces the ~60 print-only scenario scripts in the game's `tests/`, optionally importing them).

---

## 13. GUI — `pipist-gui` (SDL3 + Dear ImGui, C++)

The GUI is **only a client** of `pipistd`: anything it shows or does is also available from the CLI/protocol. It must be full-featured: tabs, docking, splitting, and **every panel can be popped out into its own OS window** (and docked back).

### 13.1 Toolkit decision (provisional until the owner confirms; the protocol makes it replaceable)
Requirements from the owner: lightweight; tabs and pop-out windows; a live 3D viewport with gizmos; terminal and code panes; and *no ceiling* — the toolkit must be something we can bend and own.

| Option | Verdict |
|---|---|
| **SDL3 + Dear ImGui (docking + multi-viewport branch), vendored and patchable** | **Chosen.** Small (~20k lines of C++ we can read and patch), MIT, we control the render loop and every pixel, panels pop out into real OS windows, the viewport is just a texture in a panel, the FPS runtime already uses SDL3 + ImGui for in-game tooling so panels can later be reused in-game. Costs: no native widgets, no screen-reader accessibility, limited IME, redraw policy must be managed (13.3). |
| Qt6 Widgets | Best docking and text widgets, accessibility. Large dependency and compile on Gentoo, a framework we bend around rather than own, harder to embed a custom GPU viewport. Rejected for v1. |
| GTK4 / Slint / egui | Either heavy, immature for docking, or not C++. Rejected. |
| Own toolkit on SDL3 + GL | Maximum control, months of work. Not now; `pipist-ui` (13.3) is the seam where parts of it can grow later. |

Accepted limitations (documented in `docs/gui-limitations.md`): no accessibility tree; IME works through SDL3 text-input events only; no native file dialogs (use an in-app picker, or `zenity`/`kdialog` if present via a configurable command).

### 13.2 Stack
SDL3 (window, input, clipboard, DPI, multi-monitor, GL context, relative mouse); OpenGL 3.3 core via a generated glad loader (vendored); Dear ImGui `docking` branch vendored at a pinned commit; ImPlot (Perf and Experiments plots) and ImGuizmo (viewport gizmos), vendored; libvterm (terminal); `stb_image_write` (screenshots); fonts: one monospace and one UI font under permissive/OFL licences (record in `licenses/`), icons subset from a permissive icon font. FreeType is optional (`PIPIST_UI_FREETYPE=OFF` by default; ImGui's stb_truetype is used).

### 13.3 The `pipist-ui` layer (our code, so we are never boxed in)
`pipist-ui/` wraps ImGui; all panels use it, never raw docking calls.
- **Panel registry:** `PanelDesc {id, title, icon, module, factory, default_dock, allow_multiple}`; lifecycle `onCreate / onShow / onHide / onFrame / onProtocolEvent / onSerialize / onDeserialize / onDestroy`. A panel whose `module` is not loaded renders the stub (3A.11).
- **Dock and window manager:** workspaces (named layouts), tab groups, split, pop-out, re-dock, fullscreen per OS window (F11), per-monitor geometry memory, tab context menu (*Move to new window*, *Dock back*, *Close*, *Duplicate*), and a title-bar button row on every panel: `[⧉ pop out] [≡ menu] [✕ close]`.
- **Pop-out semantics:** `⧉` undocks the panel into a new OS window at the panel's current screen position and size (offset 24 px), remembering its previous dock slot and tab order; `Dock back` (button or double-click title bar) returns it there. Mode `[gui].popout = "os_window"` (default) uses ImGui multi-viewport; `"floating"` keeps floating panels inside the main window for window managers where extra windows misbehave (some tiling WMs).
- **Redraw policy (event-driven):** the main loop blocks in `SDL_WaitEventTimeout`. A frame is rendered only when an SDL event arrives, a protocol message that changes visible data arrives, a viewport frame arrives, or an animation is active (terminal cursor blink can be disabled; default blink 2 Hz only while a terminal is focused). Idle GUI = zero frames and ~0% CPU (budget 3A.12).
- **Threads:** main thread = SDL + ImGui + GL. One IO thread runs `libpipist-client` and posts messages to the main thread through a lock-free queue and `SDL_PushEvent` wake-up. One reader thread per viewport side channel. No blocking RPC on the main thread: calls are async with callbacks/futures polled per frame; timeouts show a spinner.
- **Widgets:** `TerminalView` (libvterm; 256/truecolor; mouse; bracketed paste; scrollback 10 000; selection; clickable `path:line:col` and URLs), `CodeView` (read-only, tree-sitter highlighting delivered by the `index` module as spans, line numbers, markers, search, click-to-jump; used for log context, diffs, patch preview, search results), `TreeTable` and `LogView` (virtualized, 100k+ rows), `PropertyGrid` (schema-driven forms, 13B), `Scrubber` (timeline), `ViewportImage` (13A), `Plot` (ImPlot), `Toast`, `Modal`, `FuzzyList`.
- **Actions and keymaps:** see **13C** (normative: input modes, passthrough prefix, vi command line, buffer switcher, leader menu, `ViEngine`). Summary: every command is an *action* `id → handler`. Keymap presets `default` and `vi-leader` in TOML; scopes `global`, `panel:<id>`, `mode:viewport-edit`, `mode:viewport-play`; chords; a data-driven leader tree with a which-key popup (Space leader in normal-like contexts, closing on Space again, Backspace goes up a level). Esc alternates Ctrl+[ and Ctrl+Space are honored wherever Esc is. Fully remappable; conflicts reported in a Problems-style list.
- **Command palette** (Ctrl+Shift+P): fuzzy over actions, files, symbols, entities, timeline bookmarks, experiments, modules.
- **Theming:** TOML themes (dark, light, high-contrast shipped), per-level log colors, mode colors, font/size/DPI scale, live reload.
- **Testability:** `pipist-gui --video offscreen|x11`, `--script <file>` (synthetic input/actions), `--screenshot out.png --after-frames N`, `--dump-layout`, `--fake-daemon <fixtures>`.

### 13.4 Window model
- One main window with a dock space. Any panel/tab group can be torn off; OS windows can span monitors; layouts persist per project (`.pipist/layouts/<workspace>.toml`) and globally.
- **Workspaces** shipped: `edit` (editor + search + problems + log), `debug` (game view + log + inspector + timeline + where), `play` (game view large + console drawer), `studio` (viewport + hierarchy + inspector + assets + tweakables + log), `experiment`, `focus-game` (viewport fullscreen). Switch via palette/keys; `[startup].workspace` picks the initial one.
- **Command line and console.** The vi-style command line (`:`) is specified in 13C.3. The **Console drawer** (default key `` ` ``) on top of any panel: REPL for the `pipist` command grammar (`find`, `where`, `trace`, `goto`, `inspect`, `patch`, `exp`, `load`, `unload`, raw JSON-RPC). Output is clickable (jump to source). Same command table as the CLI.

### 13.5 Panels (v1) — module requirement and behaviour
> **Superseded in detail by Appendix D.** D1 defines the layout framework, patterns and themes; D2 and D3 specify every panel (header, wireframe, contents, keys, states, tests) and D3.12 is the complete panel registry. The table below is the summary; where it differs from D2/D3, the appendices win.

| Panel | Module | Shows / does |
|---|---|---|
| Editor | `editor` (builtin) | nvim in a `TerminalView`; GUI tabs mirror nvim tabpages; `editor.goto` from any panel jumps there |
| Game view (terminal) | `game` + host | Terminal rendering of a headless web game (log/status/buttons/prompt regions, or a status summary for canvas-only games), clickable buttons from `game.buttons`, speed/pause/step controls |
| Game view (native) | `game` + runtime | `ViewportImage` (13A) |
| Game view (browser) | `game` + host | Connection state, captured console, quick controls (the page is in an external browser window) |
| Console | kernel | REPL, history, completion |
| Log | kernel (ring) / `logdb` | Structured, filterable (level, source, channel, text/regex, tick range), follow, click-to-source, export, pin to tick |
| State inspector | `timeline`/host | Tree of current or snapshot state, diff vs previous tick / other snapshot, live edit (`state.set`), watch list, search, copy path |
| Timeline | `timeline` | Scrubber + branch tree, labels/bookmarks, snapshot sizes, *fork here and run with current code*, compare two points |
| Where | `trace`, `index` | For the current tick: functions run (ordered), strings/dialogue with source locations, entities involved; trace back N ticks |
| Search | `index` | Text/symbol/string/entity search with preview and jump |
| Problems | `diag` | Unified diagnostics with filters and quick fixes |
| Outline / Files | `index` / kernel | Symbols of current file; project tree |
| Patches | `patch` | Hot-patch history, tier used, fallback reason, revert |
| Experiments | `experiments` | Definitions, run progress, results table, transcript drill-down, run comparison |
| Processes | kernel | Supervised processes with `TerminalView`, restart/kill |
| Modules | kernel | State, RSS, uptime, Load/Unload/Always-load |
| Bus monitor | kernel | Raw protocol event stream with filters |
| Perf | kernel + hosts | Tick/frame time, host memory, snapshot store size, module RSS (ImPlot) |
| Terminal | kernel | General shell tabs |
| Viewport, Hierarchy, Inspector, Assets, Tweakables, Definitions | `studio` + runtime | Studio panels (13B) |
| Declarative panels | any module | Module-defined UI (13.8) |
Later: breakpoints/DAP, asset import tools.

### 13.6 Terminal panes and nvim
- PTYs are owned by the kernel supervisor; the GUI obtains the master fd with `proc.attach_pty` (fd passing) and drives `TerminalView` directly (resize via `proc.resize`).
- nvim runs normally in a PTY with `--listen <socket>`; the `editor` builtin connects over msgpack-RPC (own minimal codec: nil/bool/int/float/str/bin/array/map/ext, request/response/notification). At attach it injects a small Lua snippet (`nvim_exec_lua`) that registers `BufEnter/BufWritePost/CursorHold/TabEnter` autocommands calling `rpcnotify`, producing `editor.cursor`, `editor.saved`, `editor.buffers` events. Methods used: `nvim_command`, `nvim_list_bufs`, `nvim_buf_get_name`, `nvim_win_set_cursor`, `nvim_buf_get_lines`, `nvim_buf_set_text`, `nvim_get_current_tabpage`.
- No built-in text editor widget. If nvim is absent, the Editor panel offers `CodeView` read-only plus *Open with `$EDITOR`*.
- A general `Terminal` panel starts `$SHELL` with the project as cwd.

### 13.7 Terminal-only workflow (first class)
`pipist` subcommands and `pipist repl`; `pipist tmux` creates a tmux session: nvim (listening), `pipist repl`, `pipist tail log`, `pipist tail events`, `pipist tail diag`, and `pipist play` for headless web games (or an external browser/window for others). No GUI libraries needed; works on a machine without GL. `pipist doctor` prints missing tools and Gentoo hints.

### 13.8 Declarative panels (module-defined UI, optional, M14)
A module may call `ui.panel.set {id, title, root}` where `root` is a tree of widgets: `row`, `col`, `text`, `heading`, `button {action}`, `input {id,type}`, `checkbox`, `select`, `table {columns,rows}`, `tree`, `plot {series}`, `progress`, `separator`, `code {text,lang}`. Updates: `ui.panel.set` (full) or `ui.panel.patch` (list of path-addressed replacements). User interaction returns as `ui.event {panel,id,kind,value}` to the owning module. Limits: 10 000 widgets, 5 updates/s per panel. This lets new modules have UI without recompiling the GUI.

### 13.9 Viewers by game type
Headless web game with text/DOM output → in-panel `TerminalView` fed by `pipist-host-web` (needs no GL beyond the GUI itself); headless real-time canvas game → status summary plus controls (pixels need the browser target). Browser game → external browser window (launch command from the target) plus a status/console panel; no web view is embedded (no WebKit, no QtWebEngine, no CEF in v1). Native runtime → `ViewportImage` through the viewport bridge (13A). A runtime that insists on its own window → control strip only.

---

## 13A. Viewport bridge (runtime ↔ GUI)

**Model.** The game runtime is a separate process. It renders to an offscreen image and hands frames to the GUI, which shows them as a texture inside a panel (so it can be docked, scaled to fit, or popped out into its own OS window). The GUI forwards keyboard/mouse input back. The kernel only introduces the two sides; frames and input never pass through it.

Why a separate process (and not the runtime loaded into the editor): a runtime crash or infinite loop cannot take the editor down; the runtime can be rebuilt and restarted while the GUI stays up; the same design works for C++, Lua, and anything else; and several runtimes can run at once (multiplayer testing).

### 13A.1 Attach handshake
1. The runtime connects to the kernel, announces `game.hello`, then calls `viewport.offer {id, caps:{formats:["bgra8"], dmabuf:bool, modes:[…], input:["kbd","mouse","gamepad"]}}` and creates a listening unix socket `$XDG_RUNTIME_DIR/pipist/vp-<id>.sock`.
2. A GUI Game view panel calls `viewport.list` / `viewport.attach {id}`; the kernel returns the socket path. The GUI connects to it directly.
3. Binary framing on that socket: `u32 length, u16 type, u16 flags, payload`, little-endian, version negotiated in `HELLO`. Message types: `HELLO`, `CONFIGURE` (GUI→rt), `FRAME_READY` (rt→GUI), `FRAME_RELEASE` (GUI→rt), `INPUT` (GUI→rt), `CAPTURE` (GUI→rt), `CURSOR` (rt→GUI), `PING/PONG`, `BYE`.

### 13A.2 Shared-memory frame transport (v1, always supported)
- The **GUI allocates** the frame memory: one `memfd` containing `N = 3` slots, each `pitch × height` bytes, `pitch = align64(width × 4)`, format **BGRA8** (sRGB, non-premultiplied). It sends the fd to the runtime with `SCM_RIGHTS` inside `CONFIGURE {width, height, scale, render_scale, slots, pitch, format, mode}`.
- The runtime renders into its own offscreen framebuffer (EGL surfaceless or a hidden SDL window context), reads back asynchronously (double-buffered PBO) into a free slot, then sends `FRAME_READY {slot, seq, width, height, time_ns, view[16], proj[16], flags}`. A slot is *free* until `FRAME_READY`, *owned by GUI* until `FRAME_RELEASE`. If no free slot exists the runtime skips presenting (never blocks the simulation).
- The GUI keeps the newest ready slot, uploads it to a GL texture (`glTexSubImage2D` through a PBO) on the main thread, and releases older slots immediately. Frame pacing is the runtime's; the GUI redraws when a frame arrives (13.3).
- `view`/`proj` (column-major float32) are the camera matrices for that frame; the GUI uses them for gizmos and overlays (13B).
- **Budgets:** hand-off overhead < 3 ms at 1080p; sustained ≥ 60 fps at 1080p with the demo runtime on a normal desktop; memory = 3 × frame size (1080p ≈ 24 MB).

### 13A.3 Zero-copy upgrade (optional, v1 stretch; auto-fallback)
If both sides advertise `dmabuf` and `PIPIST_VIEWPORT_DMABUF=ON`, the runtime exports its render target as a dma-buf (EGL `EGL_MESA_image_dma_buf_export` or Vulkan external memory) with format modifier and sends fd(s) + an acquire fence (`sync_file`); the GUI imports via `EGL_EXT_image_dma_buf_import` into a GL texture. Any failure (driver, modifier mismatch, proprietary-driver quirks) silently falls back to 13A.2 and emits `viewport.fallback {reason}`. This path **cannot be verified in the cloud sandbox**: implement behind the flag, add a diagnostic tool `pipist-vp-test --dmabuf`, and record it as *Unverified* in STATUS.md.

### 13A.4 Resize, scaling, pop-out
- The panel size in **physical pixels** is the render size (`exact` fit mode, default) so the image is crisp at any panel size, including after pop-out or fullscreen. The GUI sends `CONFIGURE` on resize, debounced 50 ms; while a drag is in progress it scales the last frame to fit and snaps to the new exact size when the new frames arrive. A new `CONFIGURE` carries a new `memfd`.
- Other fit modes (per Game view panel): `letterbox` (fixed aspect), `integer` (pixel-art scaling), `render_scale` 0.25–2.0 (render below/above panel resolution and scale in the GUI).
- HiDPI: `scale` (float) is passed so the game can scale its UI; width/height are physical.
- Pop-out/redock changes only the panel's container; the connection is untouched.

### 13A.5 Input forwarding and capture
- `INPUT` events (all with GUI timestamp `ns`): `key {scancode, keycode, down, repeat, mods}`, `text {utf8}`, `mouse_move {x,y}` (viewport pixels) or `{dx,dy}` (captured), `mouse_button {button, down, x,y}`, `wheel {dx,dy}`, `focus {in}`, later `gamepad`.
- **Edit mode:** the GUI uses the mouse for selection/gizmos (13B); while right mouse is held it sends fly-camera input (`dx,dy` plus WASD/QE state) as `editor_camera` events; keyboard shortcuts stay with the GUI.
- **Play mode:** all input goes to the game. Click inside the panel to *capture* (SDL relative mouse mode, cursor hidden and grabbed; `CAPTURE {on:true}` tells the runtime to use relative motion). Release hotkey (default `Ctrl+Alt+G`; also release on focus loss and when the panel is closed or popped out). While captured, only the release hotkey and configured pause/step keys are intercepted by the GUI.
- The runtime may send `CURSOR {visible, shape}`; the GUI applies it when not captured.

### 13A.6 Failure behaviour
Socket EOF or a 250 ms timeout on a synchronous request: the panel keeps the last frame, dimmed, with an overlay *"Runtime exited (code N / signal S) [Restart] [Restart & restore latest snapshot]"*. The GUI never blocks on the runtime; the runtime never blocks on the GUI (frame skipping, 13A.2).

### 13A.7 Multiple viewports
Each Game view panel binds to one runtime instance (dropdown). Several panels can show several instances (multiplayer testing) or the same instance with different cameras if the runtime supports `viewport.camera`.

### 13A.8 Reference code and conformance
`sdk/pipist_viewport.h` + `sdk/pipist_viewport.c` (runtime side: offer, listen, configure handling, slot management, async readback helper for GL, EGL surfaceless helper). GUI side: `pipist-ui/viewport_bridge.*`. `docs/viewport.md` is the binary protocol spec. Tool `pipist-vp-test`: a fake runtime that renders a moving test pattern with a frame counter and checks resize, input, capture, crash and slot-starvation behaviour; used by CI with software GL (Mesa llvmpipe, EGL surfaceless) when available.

---


<!-- SOURCE-END: pipist-spec-part2.md -->

---

<!-- SOURCE-BEGIN: pipist-spec-part3.md -->

# PIPIST — Build Specification v1.3, Part 3 of 3 (sections 13B–21)

See the document map in Part 1 (`pipist-spec.md`).

---

## 13B. Studio (visual mode)

Studio lets you edit games through menus, forms and a live viewport instead of (or alongside) typing. It is a **second way of editing the same text files**, not a separate project format.

### 13B.1 Principles
1. **Files are the truth.** Scenes and definitions live in plain text (TOML, Lua data tables, JSON). nvim and Studio edit the same files at the same time.
2. **Minimal edits.** Studio changes only the bytes it must: no reformatting, no reordering, comments and layout preserved, so `git diff` stays clean.
3. **The runtime is authoritative for live objects.** Studio does not simulate the game; it talks to the running runtime through `scene.*` and shows its frames.
4. **Edit and Play are separate.** Playing never pollutes authored data (13B.11).
5. **Pipist stays game-agnostic.** Game-specific knowledge lives in schemas and in the runtime's `scene.*` implementation, never in Pipist code.
6. **Scope discipline.** Not in v1: node-graph visual scripting, mesh/terrain/animation/material/particle authoring, lightmap baking. Logic stays in Lua/C++.

### 13B.2 Components
| Component | Where | Role |
|---|---|---|
| `studio` module | process module | `fmtedit` (format-preserving edits), schemas and validation, tweak registry/presets, undo stack, edit/play orchestration |
| Runtime `scene.*` service | the game runtime (or `studio` for file-backed scenes) | live entity tree, picking, transforms, spawn/delete |
| Studio panels | `pipist-gui` | Viewport, Hierarchy, Inspector, Assets, Tweakables, Definitions |
| Schemas | project files `schemas/*.schema.toml` | Describe fields for forms and validation |

### 13B.3 `fmtedit` — format-preserving data editor
Formats: **TOML** (full), **Lua data files** (a file whose content is a table constructor, e.g. `return { … }` or `NAME = { … }`, with literal leaves only), **JSON**. Parsing uses tree-sitter with exact byte ranges.

Operations: `set(path, value)`, `insert(path, key, value, position)`, `remove(path)`, `append_table(path, text)`, `rename_key`, `reorder_array`, `move`. Paths address documents like `entity[id=crate_01].pos[1]`.

Guarantees (each is a property test):
- Bytes outside the edited ranges are unchanged (indentation, quote style, comments, blank lines, trailing commas, key order).
- Numbers: unchanged values keep their original text; changed floats print with the shortest round-trip representation, keeping the original number of decimals if that is lossless.
- Inline tables stay inline; multi-line arrays keep one element per line and the file's indentation; single-line arrays stay single-line.
- New keys go after the last key of the same table with matching indentation; new `[[entity]]` blocks go after the selected entity's block (or at end of file) with one blank line separation as in the file.
- After every edit the result is re-parsed; if the re-parsed tree differs from the intended tree, the edit is **aborted, nothing is written**, and an error diagnostic is emitted.
- Lua files containing logic (function bodies, computed values) remain editable for their literal leaves only; non-literal fields are shown read-only with *Open in editor*.
- Test corpora under `tests/fixtures/data/` (hand-written, tricky TOML/Lua/JSON); randomized edit sequences must satisfy the guarantees above and be idempotent.

### 13B.4 Write path and coordination with nvim
1. **File not open in nvim:** atomic write (temp file in the same directory + `rename`, preserving mode).
2. **Open in nvim, buffer unmodified:** apply the edit through `nvim_buf_set_text`, then `:silent write`; this keeps nvim's undo history and avoids "file changed" prompts.
3. **Open in nvim, buffer modified (unsaved):** apply to the buffer only; mark the Inspector with *unsaved in editor*; do not write.
4. **Conflict check:** every edit carries the content hash it was computed against; if the file changed since, re-parse and re-resolve the path; if it cannot be resolved, reject with a clear message. Never overwrite blindly.
5. **Echo suppression:** each Studio write records its expected post-hash; the matching `file.changed` event is ignored by Studio's re-parse (the runtime reload still happens).

### 13B.5 Live preview vs persistence
While dragging a gizmo or slider, Studio sends `scene.set {…, preview:true}` / `runtime.set_variable` to the runtime at ≤ 60 Hz (instant feedback, nothing written). On commit (mouse up, Enter, or 250 ms idle for sliders) it persists through `fmtedit`; the resulting file change triggers the normal reload, which is idempotent.

### 13B.6 Schemas — `schemas/<name>.schema.toml`
```toml
[schema]
name = "weapon"
applies_to = ["weapons/*.toml", "mods/*/weapons/*.lua"]   # file globs
root = ""                          # path inside the file; "" = file root; or "entity[def=weapon]"
title_field = "name"

[field.name]        type = "string"
[field.damage]      type = "float"  min = 0    max = 500  step = 1    unit = "hp"  default = 10  group = "Combat"   hot = true
[field.fire_rate]   type = "float"  min = 0.01 max = 5    step = 0.01 unit = "s"   group = "Combat"   hot = true
[field.recoil]      type = "float"  min = 0    max = 10   group = "Handling" tooltip = "Vertical kick per shot"
[field.model]       type = "asset"  kinds = ["glb", "gltf"]
[field.sound]       type = "asset"  kinds = ["ogg", "wav"]
[field.ammo_type]   type = "enum"   values = ["9mm", "7.62", "shell"]
[field.mode]        type = "enum"   values = ["semi", "auto", "burst"]
[field.burst_count] type = "int"    min = 2 max = 10 visible_if = "mode == 'burst'"
[field.tags]        type = "list"   of = "string"
[field.attachments] type = "list"   of = "ref:attachment"
[field.muzzle_pos]  type = "vec3"   step = 0.01
[field.tint]        type = "color"
```
- **Types:** `bool, int, float, string, text, enum, flags, vec2, vec3, vec4, euler, quat, color (rgb|rgba|hex), angle, asset, ref:<schema>, list, map, struct (nested `[field.x.field.y]`)`.
- **Metadata:** `min, max, step, default, unit, group, order, tooltip, readonly, required, pattern, deprecated, hot` (`hot = true` means the runtime applies it live without restart), `visible_if` (tiny expression language: field references, `== != < > <= >=`, `&& || !`, string/number/bool literals).
- **Validation** runs on file change and produces diagnostics in the Problems panel with file/range.
- **Unknown fields** appear under *Other*, edited as raw typed values, always preserved.
- `pipist schema infer <files…>` writes a draft schema from existing data (ints vs floats, `vec3` for 3-float arrays named `pos|scale|rot|color|…`, enums for repeated small string sets) with `# TODO` comments, so schemas do not have to be written from scratch.
- A runtime may instead serve schemas via `schema.get`; project files win on name conflict.

### 13B.7 Panels
> Exact wireframes, keys, states and tests for these six panels are in Appendix D3.11; the complete panel registry is D3.12. Where they differ, Appendix D wins.

- **Viewport:** `ViewportImage` plus toolbar — Edit / Play / Pause / Step; tools Select (Q), Move (W), Rotate (E), Scale (R); space local/world; snapping (position 0.25 m, rotation 15°, scale 0.1, all configurable); view modes from `viewport.modes` (lit, wireframe, unlit, collision, physics, AI perception, …); camera speed; perspective/orthographic and axis views; grid; stats overlay; *Focus selected* (F); camera bookmarks. Picking: click → `scene.pick {x,y}` (ID-buffer or raycast in the runtime) → selection. **Gizmos and selection outlines are drawn by the GUI** over the image using the frame's `view`/`proj` matrices (ImGuizmo + projected AABBs); dragging sends transforms to the runtime live.
- **Hierarchy:** virtualized tree from `scene.tree`; icons by kind; visibility/lock toggles stored in `.pipist/editor-state.toml` (never in game files); drag to reparent; context menu: add (from prefab/definition list), duplicate, delete, rename, copy/paste (as text blocks), *Reveal in file* (opens nvim at the entity's source range); filter/search.
- **Inspector:** schema-driven `PropertyGrid` for the selection (multi-select shows mixed values); per-field *revert to file value* / *reset to default*; *source: file:line* link; undo/redo; *raw* toggle shows the exact text block read-only with *Edit in nvim*.
- **Assets:** tree + grid by type (models, textures, audio, prefabs, scripts, schemas), search, thumbnails (`asset.thumbnail` from the runtime or cached PNGs), drag into the viewport (`scene.spawn` at the ray hit) or onto asset fields.
- **Definitions:** every file matched by a schema, grouped by schema (Weapons, Enemies, Items, …), *New from template* (copies `templates/<schema>.toml` and registers the id), opens the Inspector.
- **Tweakables:** 13B.9.

### 13B.8 Scene protocol (what a runtime implements for Studio; all optional, discovered via `caps`)
`scene.tree {root?}` → nodes `{id, parent, name, kind, children, flags, source:{file, path|range}}` · `scene.get {id}` · `scene.set {id, path, value, preview?}` · `scene.spawn {prefab|def, parent?, transform?, name?}` → id · `scene.delete {ids}` · `scene.duplicate {ids}` · `scene.reparent {id, parent, index?}` · `scene.rename` · `scene.select {ids}` and event `scene.selection {ids}` · `scene.pick {x,y,mode}` · `scene.bounds {ids}` · `scene.mode {edit|play|paused}` · `scene.reload {file}` · `scene.save` (optional; Studio normally persists with `fmtedit`) · `viewport.modes` / `viewport.set_mode` · `asset.list`, `asset.thumbnail {path,size}`.

**Source mapping.** Every entity the runtime exposes carries `source {file, key path | byte range}` so edits go to the correct text. For Pipist's **reference scene format** the `studio` module maps by `id`:
```toml
[scene]
name = "warehouse_01"
version = 1

[[entity]]
id     = "crate_01"
prefab = "props/crate"
pos    = [1.0, 0.0, 3.5]
rot    = [0.0, 90.0, 0.0]
scale  = [1.0, 1.0, 1.0]
[entity.override]
mass = 12.0

[[entity]]
id     = "guard_01"
def    = "enemies/guard"
parent = "tower_01"
pos    = [4.0, 6.0, -2.0]
```
`runtime-demo` loads this format. A game with another format implements `scene.*` and returns `source` mappings, or supplies a Lua `pipist.scene_adapter` that maps its tables.

### 13B.9 Tweakables (live tuning)
Runtime-side registration:
- C: `pipist_tweak_float("player.air_accel", &v, min, max, step, "Movement")` (also `int`, `bool`, `vec3`, `color`, `enum`).
- Lua: `local air_accel = pipist.tweak("player.air_accel", 12.0, {min=0, max=50, step=0.1, group="Movement"})` (returns a live accessor).
- JS: `__pipist.tweak(path, default, opts)`.
Each registration sends `tweak.register {path, type, value, default, range, group, source}`; `source` is the file/line/range of the default literal when it can be located (Lua: call-site line via `debug.getinfo`, literal found by `studio` parsing that line with tree-sitter).
Panel actions: drag slider/edit field (live `runtime.set_variable`), **Reset**, **Commit to source** (writes the current value into the literal at `source` via `fmtedit`; disabled with a reason if the default is not a literal), **Save preset** / **Load preset** (`.pipist/tweaks/<name>.toml`), **Sweep…** (opens the Experiments panel prefilled with the selected tweakables and ranges), and a **changed-since-start** filter.

### 13B.10 Undo / redo
Studio keeps a command stack (depth 500) of inverse operations (recorded text patches plus runtime operations). Ctrl+Z / Ctrl+Y act in the viewport, hierarchy and inspector contexts; text edits inside nvim use nvim's own undo. A drag or slider gesture is one entry. If a file changes externally, stack entries that touch it are marked stale and disabled (never applied blindly).

### 13B.11 Edit / Play state model
- **Edit:** simulation paused; the files are authoritative; edits write to files.
- **Play:** on Play, Studio takes a snapshot (`timeline`, bookmark `edit-state`) and starts the simulation as a new timeline branch. Changes made during play (moved entities, tweaked values) are **transient**.
- **Stop:** restores `edit-state`, so authored data is untouched.
- **Keep changes:** while playing or after stop, a *Changes during play* list shows values that differ from `edit-state`; selected ones can be written to files with `fmtedit` (**Apply**).
- Extras: *Play from camera* (player starts at the editor camera), Pause, Step one tick/frame, Slow-mo (0.1×–2×).

### 13B.12 Compile-on-edit loop for C/C++ (explicit scope)
Studio does not compile arbitrary C++ "live". What exists:
1. **Data and Lua** changes apply instantly (hot-patch tiers T1–T3).
2. **C++ gameplay modules** built as shared libraries with a documented contract (runtime-owned state arenas; module exports `pipist_module_vtable {init, shutdown, update, serialize, deserialize}`): on save, `targets` runs the incremental build for that target (ninja + ccache; debounced 300 ms), problem matchers feed Problems, and on success the runtime swaps the module (T3) or restart-restores (T5). A build indicator shows state, duration and a sparkline of recent build times.
3. **Engine-level C++** changes: rebuild, restart, restore snapshot (T5).
4. Every apply reports which tier was used and why (Patches panel).

---

## 14. Configuration — `pipist.toml` (worked example: a text game such as Los Ciegos)

```toml
[project]
name = "los-ciegos"
root = "."
ignore = ["dist/", ".pipist/", "node_modules/", "*.zip"]
packs = ["javascript", "data", "markdown"]

[[source]]
path = "index.html"
[[source]]
path = "js/"
[[source]]
path = "css/"

[editor]
command = "nvim"
listen = true

[[target]]
name = "play-text"
kind = "game"
host = "web-quickjs"
entry = "index.html"
engine = "quickjs-ng"
mode = "realtime"                 # realtime | fast | stepped (B1.6)
# state capture, ticks, input and rendering are automatic; overrides live in [adapter] / [host.web] (Appendix B1.11)

[[target]]
name = "play-browser"
kind = "game"
host = "browser"
entry = "index.html"
launch = "firefox --new-window {url}"

[[target]]
name = "bundle"
kind = "build"
command = "python3 build.py"
problem_matcher = "generic"

[[target]]
name = "loadcheck"
kind = "test"
command = "node tests/loadcheck.js"
expect_stdout = "done"

[timeline]                       # replaces the old [snapshot] table; all keys and defaults in Appendix C1.11
persist = "project"
quota_mb = 8192
tiers = [ {within_ticks = 300, every = 1}, {within_ticks = 3000, every = 10}, {within_ticks = 30000, every = 100}, {within_ticks = 0, every = 1000} ]

[web]                            # formerly [snapshot].capture_scrollback
capture_scrollback = 200

[patch]
default_tiers = ["function-swap", "data-merge", "reload-restore"]
no_hotpatch = []
rerun_ok = []

[index]
html_inline_scripts = true
[[index.entity]]
name = "room"
query = '(variable_declarator name: (identifier) @n (#eq? @n "ROOMS") value: (object (pair key: (_) @key)))'
[[index.entity]]
name = "npc"
query = '(variable_declarator name: (identifier) @n (#eq? @n "NPCS") value: (object (pair key: (_) @key)))'

[[lint.rule]]
id = "load-order"
enabled = true
[[lint.rule]]
id = "determinism"
modules = ["js/13-combat.js", "js/07-karma-log-death.js"]
wrapper = "rrand"
severity = "info"

[gui]
default_workspace = "debug"
keymap = "vi-leader"
```
Targets of other kinds (`kind = "native-runtime"`, `command = "./build/game-runtime --project …"`, `build = "cmake --build build"`, `host = "native"`) look the same. Per-game adapter settings (`[adapter]`, `[host.web]`, Appendix B1.11) and per-game pack/lint rules are all that distinguishes projects.

---

## 14A. Startup, profiles and module configuration

```toml
[daemon]
idle_exit_secs = 0                  # 0 = stay until `pipist down`

[startup]
profile   = "dev"                   # built-in default if omitted: "min"
autoload  = ["index"]               # extra modules to start eagerly on top of the profile
lazy_only = ["experiments", "studio", "dap"]   # never auto-start; only via explicit call/load
open      = ["js/13-combat.js:1"]   # files to open in nvim at start (optional)
target    = ""                      # target to run automatically (optional)
gui       = false                   # launch the GUI at start
workspace = "edit"

[profile.dev]
extends = ["code"]
modules = ["timeline", "patch"]

[profile.minimal-play]
description = "just build and run, nothing else"
modules     = []

[modules.index]                     # per-module overrides of manifest defaults
idle_unload_secs = 900
rss_budget_mb    = 200

[log]
ring_records = 20000
persist      = false                # true => `logdb` module records to SQLite

[gui]
autoload_on_open = true
popout           = "os_window"      # or "floating"
keymap           = "vi-leader"
default_workspace = "debug"

[viewport]
transport     = "shm"               # "shm" | "dmabuf-if-available"
render_scale  = 1.0
release_key   = "ctrl+alt+g"
```
One-off examples: `pipist -p min edit foo.c`; `pipist up --profile dev --with studio --gui --workspace studio --target play-native`; `PIPIST_WITHOUT=patch pipist up`.

---

## 15. Repository layout, build, dependencies

```
pipist/
├── CMakeLists.txt  CMakePresets.json  STATUS.md  README.md
├── docs/            DECISIONS.md protocol.md viewport.md modules.md packs.md adapters.md studio.md user-guide.md gui-limitations.md
├── libpipist/        protocol types, JSON wrapper (yyjson), framing, WebSocket (own RFC 6455 subset), msgpack, logger, client lib, vi/ (ViEngine, shared by GUI and `pipist repl`); no GUI deps
├── protocol/        schema/ (JSON Schemas generated from Appendix A) ; tests/protocol/examples/
├── pipistd/          KERNEL ONLY: loop, router, bus, config+profiles, module manager, supervisor, builtin modules (targets, watcher, editor, blob, game, log ring)
├── modules/         process modules, one directory each: index diag timeline patch trace experiments studio dap logdb plugins
├── pipist-cli/       `pipist` (own subcommand table, shared with the GUI console)
├── pipist-ui/        SDL3 + ImGui layer: panel registry, docking/pop-out, widgets, keymaps, themes, viewport bridge client
├── pipist-gui/       panels + main()
├── pipist-host-web/ QuickJS-ng headless web-game host (8.1, Appendix B1)
├── pipist-host-browser/  static HTTP + WebSocket bridge for browser games (8.2)
├── sdk/             pipist-adapter.js, pipist.lua, pipist_adapter.h, pipist_viewport.h/.c, pipist_tweak.h, pipist_module.{py,js,h}, pipist_adapter.py
├── packs/           language packs
├── keymaps/         default.toml leader.toml (shipped keymaps; user/project overrides in ~/.config/pipist/keymaps and .pipist/keymaps)
├── schemas/         example schemas   templates/  example definition templates
├── runtime-demo/    SDL3 + Lua demo runtime (viewport, scene.*, tweak, snapshot/restore)
├── examples/        hello-js (text prompt)  hello-ui (ES modules, buttons)  hello-canvas (real-time canvas)  hello-lua  <owner game> (optional, owner-supplied, read-only, e.g. los-ciegos)
├── tests/           unit integration e2e golden fixtures
├── scripts/         ci.sh deps-check.sh pipist-tmux doctor dev-setup.sh
├── packaging/       gentoo ebuild stub, desktop file
├── third_party/     DEPS.md  versions.txt  vendored/  patches/<lib>/*.patch
└── licenses/        THIRD_PARTY_NOTICES.md  third-party/
```

**Build.** CMake ≥ 3.24, Ninja, C++20 (gcc ≥ 12 or clang ≥ 15). Options: `PIPIST_GUI` (ON), `PIPIST_HOST_WEB` (ON), `PIPIST_HOST_BROWSER` (ON), `PIPIST_RUNTIME_DEMO` (ON), `PIPIST_VIEWPORT_DMABUF` (OFF), `PIPIST_UI_FREETYPE` (OFF), and one `PIPIST_MOD_<NAME>` per process module (ON). Presets: `min` (kernel + CLI only, `-Os`, LTO), `debug`, `release` (`-O2`), `asan`, `tsan`, `headless` (no GUI/runtime-demo). The kernel and CLI must build with no dependency other than libuv, yyjson, tomlc17 (vendored) and the C++ standard library.

**Dependencies (v1.3).** Each is admitted under 2A and recorded in `third_party/DEPS.md`. "Owner" is the only target allowed to link it.

| Need | Library | Licence | Owner |
|---|---|---|---|
| Event loop, processes, pipes | libuv | MIT | kernel, libpipist |
| JSON | yyjson (2 files, vendored) behind `pipist::json` | MIT | libpipist |
| TOML config | tomlc17 (2 files, vendored) | MIT | kernel |
| WebSocket server/client | own RFC 6455 subset incl. SHA-1/base64 (~600 lines, fuzz-tested) | own | libpipist |
| msgpack (nvim RPC) | own minimal codec (~300 lines) | own | `editor` builtin |
| Logging, CLI parsing | own | own | libpipist, pipist-cli |
| Parsing | tree-sitter + grammars (js, html, css, lua, c, cpp, python, glsl, json, toml, markdown; each built as its own `.so`) | MIT | `index`, `studio` |
| Database / full-text | SQLite amalgamation with FTS5 | public domain | `index`, `timeline`, `logdb` |
| Compression | zstd | BSD-3 | `timeline` |
| Content hashing | xxHash (XXH3-128, single header) | BSD-2 | `timeline` |
| JS engine | quickjs-ng | MIT | `pipist-host-web`, `diag` (parse check) |
| HTML parsing | gumbo-parser (vendored; archived upstream, stable; risk noted in DEPS.md) | Apache-2.0 | `pipist-host-web`, `pipist-host-browser` |
| Lua | Lua 5.4 | MIT | `diag` (parse check), `runtime-demo` |
| Windowing, GL context, input | SDL3 | zlib | `pipist-ui`, `runtime-demo` |
| GUI | Dear ImGui (docking), ImPlot, ImGuizmo (vendored with patches) | MIT | `pipist-ui` |
| GL loader | glad (generated, vendored) | MIT/public domain | `pipist-ui`, `runtime-demo` |
| Terminal emulation | libvterm | MIT | `pipist-ui` |
| Image output | stb_image_write | MIT/public domain | `pipist-ui` |
| Tests | Catch2 v3; pytest for e2e; Playwright for the browser agent | BSL-1.0 / MIT / Apache-2.0 | tests only |

Removed from v1.0: Qt, nlohmann/json, spdlog, CLI11, msgpack-c, libwebsockets, QtWebEngine/WebKitGTK.

**Gentoo hints** (verify atoms with `emerge -s`; commands assume a non-root user): `sudo emerge --ask dev-build/cmake dev-build/ninja dev-libs/libuv dev-db/sqlite app-arch/zstd dev-libs/libvterm app-editors/neovim sys-devel/clang dev-lang/lua media-libs/libsdl3`. tree-sitter grammars, quickjs-ng, gumbo, ImGui, ImPlot, ImGuizmo, yyjson and tomlc17 are built from `third_party/`.

**Cloud-sandbox notes.** SDL3, tree-sitter, etc. are fetched from source at configure time (pinned) so no system Qt/GTK is needed. For GUI and viewport tests use `SDL_VIDEODRIVER=offscreen` with EGL (Mesa llvmpipe software rendering) or Xvfb; if neither yields a GL context, build and test everything with `-DPIPIST_GUI=OFF`, keep GUI code compiling in CI, and mark GUI/viewport rendering **Unverified** in STATUS.md with the exact command the owner should run (`pipist-gui --video x11 --script tests/gui/smoke.script --screenshot out.png`). Never claim a GUI works that was not run.

---

## 16. Testing strategy

- **Unit** (Catch2): JSON-RPC framing, bus filtering/backpressure, config layering, watcher debounce, trigram index, snapshot store (round-trip, dedupe, pruning, corruption handling), timeline tree ops, patch classification (table-driven: before/after source → expected tier), lint rules.
- **Integration**: start `pipistd` against `examples/hello-js`, drive it purely over the socket (a Python client in `tests/integration/`), assert events and results. Same for `hello-lua`.
- **E2E (headless web games)**: boot each fixture (`hello-js`, `hello-ui`, `hello-canvas`) and, if the owner supplied one, a copy of the owner's game in `pipist-host-web`; a scripted input sequence per fixture produces a stable transcript and per-tick state-hash golden file; snapshot at tick K, continue, restore K, continue differently, verify branch tree and state equality; edit a function → T1 patch → behavior changes without losing state; edit a data table → T2; edit a side-effect statement → falls back to T4 with an explanatory event.
- **Web adapter**: the Appendix B1.14 suites (transform corpus, DOM differential tests against Chromium, walker corpus, restore fidelity, performance, fuzz).
- **Browser agent**: Playwright drives Chromium against the injected page; reload/restore loop verified.
- **Experiments**: a sweep on `hello-js` with known analytic outcomes; failure reporting.
- **Test framework and per-milestone suites: Appendix E1 (tiers `quick`/`milestone N`/`full`/`nightly`, gates, teeth checks, the `unverified` registry, cost control) and Appendix E2 (suites M0–M14); they supersede this section where they differ.**
- **Performance gates** (fail the build if blown by > 2×; Appendix E1.7 sets ×1.25 at milestone gates and ×2.0 otherwise): index cold/incremental, query latency, snapshot capture/restore for a 5 MB state, kernel idle RSS, module spawn times, viewport hand-off (see 3A.12 and 13A.2).
- **Chaos**: kill the host mid-tick, truncate a snapshot file, send malformed JSON-RPC, flood events to a slow client; the daemon must not crash or hang. Run key suites under ASan/UBSan and TSan presets.
- **GUI**: `pipist-gui --video offscreen` (EGL + Mesa llvmpipe, or Xvfb) with `--script`: panels construct, dock/undock, pop-out creates a second OS window and re-dock restores the slot, layout save/restore, screenshots non-blank, zero frames rendered in 10 s idle, fake-daemon fixtures for panel logic.
- **Protocol**: conformance suite of Appendix A2.17 (schemas, examples, fuzz, handshake, lazy activation, event ordering, fd passing, Value round trips).
- **Input**: `ViEngine` table test (≥ 300 rows) + fuzz, keymap/leader loaders with golden errors, scripted GUI key tests (13C.12).
- **Modules**: manifest parsing, dependency ordering and cycle rejection, activation queueing, crash/backoff, unload frees the process, profile precedence, every budget in 3A.12.
- **Viewport**: `pipist-vp-test` conformance (handshake, resize, input, capture, slot starvation, crash overlay).
- **Studio**: `fmtedit` randomized property tests on `tests/fixtures/data/` (untouched bytes identical, re-parse equals intended tree, idempotence), nvim-buffer write-path tests, edit/play/keep round trips.
- CI script `scripts/ci.sh` runs everything headless and exits nonzero on any failure; run before every tag.

---

## 17. Milestones (execute in order; each ends with a `STATUS.md` update and tag `m<N>-done`)

The "Done when" lines below are made exact by Appendix E2 (suite ids `M<N>.<k>`; ★ = core, a failing ★ test stops the milestone). Order reflects priority: the spine (M0–M6) first, then hot patching and the native/visual path (M7–M9) which the FPS and graphical games depend on, then the rest. If budget runs short, **cut from the end**; never cut tests.

**M0 — Skeleton and policy tooling.** Repo, CMake presets (`min`, `debug`, `release`, `asan`, `tsan`, `headless`), vendoring + pinned fetch, `third_party/DEPS.md`, `scripts/deps-check.sh`, `scripts/ci.sh`, Catch2, `libpipist` JSON wrapper/framing/logger, kernel that answers `session.hello/ping`, `pipist ping`, `examples/hello-js` and `hello-lua`, STATUS/DECISIONS docs. *Done when:* `ci.sh` green; `pipist ping` round-trip < 2 ms; `deps-check.sh` passes and fails correctly on a seeded violation.

**M1 — Kernel, modules, targets.** Event loop, router, bus (subscribe, backpressure, history), config layering + profiles (3A.9–3A.10), module manager for builtin and process modules (manifest parsing, states, activation flow, queueing, restart/backoff, dependencies, unload), supervisor (pipes + PTY, process groups, `proc.attach_pty` fd passing), log ring, blob store, `targets` (build/run/test, problem matchers), `watcher` (inotify, debounce, hashes), WebSocket endpoint with token, discovery/autostart/lock handling, CLI: `up/down/status/doctor/edit(stub)/build/run/test/modules/load/unload`, a fixture process module `pipist-mod-echo`. *Done when:* in profile `min` the process list is exactly `pipistd`; a call to an echo method spawns the module, queues correctly, and unload frees it; a crashing module backs off and then reports `failed`; kernel budgets in 3A.12 pass; file edit → `file.changed` < 150 ms; killing a child → `proc.crashed`.

**M2 — Index and syntax diagnostics (`index`, `diag` modules).** tree-sitter packs (js, html, css, lua, c, cpp, python, json, toml, markdown), lazy grammar loading, HTML inline-script offsets, symbols/strings/entities/trigram text search, `search.where`, outline, syntax + engine-parse diagnostics. *Done when:* the `hello-js` fixture and a generated 25k-line synthetic game index under budget; `pipist where "dress code"` returns the dress-check function and the turn-away string in `hello-js` (and the owner's equivalent if supplied); seeded syntax errors are reported with correct line/col in `.js` and inline `<script>`; index module absent from the process list until first search.

**M3 — Editor integration (`editor` builtin).** Own msgpack codec, `nvim --listen`, injected Lua notifier, `editor.open/goto/current/buffers/command`, `pipist edit`. *Done when:* `pipist goto js/13-combat.js:120` moves a running nvim; saving in nvim triggers an index update; `pipist edit` budget met.

**M4 — Headless web host (`pipist-host-web`, Appendix B1).** QuickJS-ng, HTML5 parser and loader rules, DOM/Web API shim (B1.8), virtual clock/timers/RNG, `index.transform` integration and binding registry, region detection and renderer (terminal and summary modes), all input kinds (B1.4), `eval`, `pipist play`, `pipist adapter describe|audit|suggest`, `HostShimError` reporting. Fixtures authored by this milestone: `hello-js` (text prompt), `hello-ui` (ES modules, buttons and forms, no prompt), `hello-canvas` (real-time canvas, rAF loop, keyboard and pointer input). *Done when:* all three fixtures run headless under the strict shim with zero unexplained gaps; golden transcripts and state-hash sequences are identical across 3 runs with a fixed seed; the Los Ciegos copy boots, accepts a name and runs a scripted 30-input playthrough with a stable golden transcript (or `UNVERIFIED: game not provided`); `pipist doctor --host-compat` agrees with Chromium on all fixtures or lists explained differences; the DOM differential suite passes.

**M5 — Adapter, snapshots, timeline, fork (`timeline` module).** JS SDK; the automatic web adapter of Appendix B1 (binding registry, walker, delta snapshots, restore) with an example config for the owner's game copy (optional; `hello-js` ships its own); snapshot store (zstd + XXH3 chunk dedupe, thinning policy, quota); quiescence handling; timeline tree; `timeline.goto {fork}`; `pipist goto`; `trace back N` stub. *Done when:* E2E restore/branch tests pass on all three fixtures and, when provided, the owner's game copy (including in-flight narration with timers cancelled on restore, and a mid-combat snapshot); `pipist adapter verify` PASS on `hello-js`, `hello-ui` and `hello-canvas` (B1.14), with its negative tests failing as required; the delta-snapshot size target of B1.14 is met; timeline budget met.

**M6 — GUI shell v1 (`pipist-ui`, `pipist-gui`).** Includes the complete input model of **13C** (modal input system, passthrough prefix, vi command line with history/completion/built-in commands, buffer switcher, leader menu loader and default tree, `ViEngine` in `libpipist/vi/`, keymap loader, action registry) and its done-when list (13C.12). SDL3 + ImGui; event-driven redraw; panel registry; docking, tab groups, pop-out/re-dock, workspaces, fullscreen windows; lazy stubs for cold modules; keymaps (`default`, `vi-leader`) + which-key; command palette; console drawer; themes; `TerminalView` (libvterm) running nvim; panels: Editor, Game view (terminal), Console, Log, Search, Problems, Timeline (scrubber + branch tree), State inspector (read, diff, edit), Processes, Modules, Bus monitor, Perf. GUI test hooks (`--script`, `--screenshot`, `--dump-layout`, `--fake-daemon`). *Done when:* offscreen tests pass (panels construct, pop-out creates a second OS window, re-dock restores slot, layout save/restore round-trips, screenshots non-blank, **0 frames in 10 s idle**); every panel works against the fake daemon and the real one; or, if no GL is available in the sandbox, Unverified per section 15.

**M7 — Hot patch (`patch` module): JS and data.** Top-level change analysis (via `index`), tiers T1/T2/T4, transactional apply, history/revert, closure-capture warning, `no-hotpatch`/`rerun-ok` config, Patches panel. *Done when:* the table-driven classification tests pass; editing a function mid-run changes behaviour with state preserved; a `const` table edit merges in place; a side-effect edit falls back to T4 with an event naming why; the anchor-hazard warning triggers in `patch.preview`.

**M8 — Native runtime path and viewport bridge.** `runtime-demo` (SDL3 + embedded Lua + small entity world) implementing `game.*`, `runtime.*`, snapshot/restore; `sdk/pipist_viewport.*`; viewport bridge (shm transport, resize, input, capture, failure overlay); `pipist-vp-test`; `ViewportImage` and Game view (native) panel with pop-out; Lua module hot reload (T3); supervised C++ build + restart-restore (T5); C++ gameplay-module swap demo (13B.12); multiple runtime instances; dma-buf transport behind its flag. *Done when:* a moving test pattern shows in a docked panel and in a popped-out window at the exact panel size, resizing re-renders at the new size; input and capture work in tests; killing the runtime shows the overlay and *Restart & restore* works; editing a Lua weapon definition changes the live demo without losing state; the 1080p ≥ 60 fps and < 3 ms hand-off budgets hold with llvmpipe or are marked Unverified with a measurement tool.

**M9 — Studio (`studio` module).** `fmtedit` (TOML, Lua data, JSON) with property tests; write path and nvim coordination; schemas, validation, `pipist schema infer`; panels Viewport (picking, gizmos, snapping, view modes), Hierarchy, Inspector, Assets, Definitions, Tweakables; `scene.*` and `tweak.*` implemented in `runtime-demo` plus the reference scene format; Edit/Play state model with Keep changes; undo/redo; commit-to-source and presets. *Done when:* in `runtime-demo`, moving an entity with the gizmo changes only that entity's `pos` line in the scene file (`git diff` shows a one-line change) while nvim has the file open and sees it update; a slider tweak applies live and *Commit to source* edits the literal; Play → modify → Stop restores the edit state; *Keep* writes only selected values; fmtedit randomized tests pass.

**M10 — Browser backend (`pipist-host-browser`).** Own static HTTP server with HTML injection of the agent, WebSocket bridge, reload/restore loop, launch command, console capture. *Done when:* Playwright test: edit a file → page reloads → state restored through the same adapter as the headless web host.

**M11 — Experiments (`experiments` module).** TOML schema, parallel headless runs, sweeps, assertions, reports, Experiments panel, golden playthrough record/check, `Sweep…` from Tweakables. *Done when:* the `hello-js` sweep matches analytic expectations; a seeded failing assertion is reported with transcript; 20 `hello-js` variants run in parallel without cross-talk.

**M12 — Diagnostics+.** LSP client (clangd, lua-language-server, ruff/pylsp, optional JS server), build-output problem matchers, project lint rules (`load-order`, `determinism`, `unlogged-state`, …), quick-fix plumbing. *Done when:* broken fixture projects produce the expected diagnostics; `load-order` reproduces what `tests/loadcheck.js` catches.

**M13 — Where-tracing (`trace` module).** JS instrumentation (same-line `__f(id)`), per-tick executed-function sets, string and entity mapping, `trace.now/back`, Where panel, optional value provenance. *Done when:* on `hello-js`, a talk interaction with the dress-check NPC with and without the required item shows the dress-check function and its turn-away string with correct lines (and the equivalent on the owner's game if supplied); overhead < 25% with tracing on, none when off.

**M14 — Polish and extras.** DAP (`dap` module), replay tier (flagged), declarative panels (`ui.*`), `plugins` module, `logdb`, Python host/pack, docs (user guide, protocol/viewport/module/studio references), Gentoo ebuild stub, `pipist init <template>` (`text-js`, `lua-native`, `cpp-native`, `python-sim`). *Done when:* docs build; templates pass their own smoke tests.

---

## 18. Worked example: Los Ciegos integration notes (from the handoffs; optional)

> Informational only. Nothing in Pipist code, defaults or tests may depend on anything in this section (rule 15). If the game folder is not supplied, none of this is built or tested; the same mechanisms are covered by the fixtures `hello-js`, `hello-ui` and `hello-canvas`.


- **Source of truth:** the Nov 1 handoff references `js/31-fishing.js`, `js/33-phone.js`, `js/34-cmd-assist.js` and `tests/t80+`, so the **multi-file layout** (`index.html`, `css/`, `js/NN-*.js` as classic scripts in shared global scope, `build.py`, `tests/`) is current. The Oct 28 handoff's single `index.html` is an older/branch layout. Pipist must support both (inline-script indexing covers the single-file case). The owner must place the current game folder at `examples/los-ciegos/` before the run (see section 20).
- Run the game's own sanity checks as targets: `node tests/loadcheck.js` (expect `done`), `python3 build.py`, `node tests/t57.js` (expect `LOG STABLE`).
- Dev mode: names `ccpe` / `cheatercheaterpumpkineater` enable `G.flags.devMode` and a dev kit; dev commands (`devgo`, `devgive`, `devskip`, `devgang`, `testfight`, …) are the natural **fixtures** for experiments (jump to a scene fast).
- State outside `G` that must be in `snapshot()`: `combatState`, `replayRngQueue`, `dialogueSession`, `barterSession`, phone/notebook state, fishing sessions, food-spoilage timers, any other top-level `let`. The M5 audit enumerates them mechanically; do not trust this list to be complete.
- Existing save/load is full replay of `G.eventLog` with `rrand()` + `replayRngQueue`. Pipist snapshots are independent. Note for the replay tier: edits that change `rrand()` call counts/order desync replay. The `determinism` lint warns on exactly this.
- Narration beats use `setTimeout` (e.g. `startPrisonerTransport`, called without `await`): the quiescence rule and timer cancellation on restore are required.
- File sizes are large (module sizes up to ~2.1k lines). Index and patch classification must handle them without noticeable lag.
- Known edit hazard (anchors ending on `if (...) {`) is surfaced by `patch.preview`.
- Do not touch the parked `fakeDoctor` unlock or the baptism route when testing.

---

## 19. How the other planned games use Pipist (design must not preclude these)

| Game | Runtime | Key needs from Pipist |
|---|---|---|
| Stick-RPG-2-style 2D RPG reusing text-game mechanics | JS canvas (browser backend) or Lua/C++ with SDL | Shared rules module between text and graphical versions; same adapter; sprite/asset reload via `runtime.reload_asset`; timeline of game days; experiments for economy balance |
| Map / grand-strategy (Vic2/EU4-like) | C++ native, data-heavy (provinces, pops, trade) | Huge state → snapshot delta/dedupe quality matters; `data-merge` hot reload of data files; headless fast-forward experiments (simulate 100 years × N seeds); map/overlay inspection panels (later plugin) |
| Evolution / biology sim | C++ or Python/Lua native, long-running | Seeded determinism, fast headless sweeps, time-series collection/plot export in experiments (CSV/JSON out), parameter overrides at scale |
| FPS (Cruelty-Squad-like) | C/C++ runtime + Lua mods (per the design overview) | `runtime.*` pass-through, Lua hot reload, restart-restore, physics/entity inspection panels, multiple runtime instances, DAP, mod loader hot reload |

Therefore: the snapshot store must support large states with chunk-level dedupe; experiments must support headless native runtimes (`host = "native"`); the protocol must never assume text output.

---

## 20. Inputs the owner must supply before launching the cloud run

1. **Optional: your own game folder** (for example the current Los Ciegos folder: `index.html`, `css/`, `js/`, `build.py`, `tests/`) placed at `examples/<name>/` or attached. It is **not required**: every milestone passes on the built-in fixtures, and tests that need your game are registered `unverified` (reason: game not provided) with an owner command to run later.
2. **Confirmation of defaults taken in this spec** (all will be logged as decisions): C++20 core; module/lazy-loading architecture with built-in default profile `min`; SDL3 + Dear ImGui GUI (provisional); shared-memory viewport frames with optional dma-buf; Studio edits plain text files; GPL-3.0-or-later; project name "Pipist".
3. **Machine facts that affect the GUI and viewport** (optional but useful): GPU and driver (Mesa or NVIDIA), window manager (tiling or floating), monitor resolution/scale. Used for the `doctor` hints and for choosing `popout` and `transport` defaults.
4. Optional: one or two other HTML/JS games of yours with a different structure from Los Ciegos, placed under `examples/` as extra fixtures (the adapter's generality is only proven by games it was not designed around).
5. Optional: real playthrough command lists to use as golden scripts; a few real weapon/enemy/item definition files (to seed schemas and `fmtedit` fixtures).

---

## 21. Open questions deferred (defaults chosen; revisit later)
- GUI toolkit confirmation (ImGui + SDL3 chosen). Revisit only if accessibility or rich IME becomes a requirement; the protocol allows another front end.
- Whether to grow `pipist-ui` into a fuller custom toolkit (the seam exists; not planned for v1).
- Whether packs and modules should be distributable through a registry (default: local directories only).
- Whether to add a remote or multi-user mode (default: no).
- Embedding a web view for browser games (default: external browser window only).
- Visual scripting / node graphs, terrain, animation and material editors (out of scope for v1; extension points exist).

<!-- SOURCE-END: pipist-spec-part3.md -->

---

<!-- SOURCE-BEGIN: pipist-spec-13c-input.md -->

# PIPIST SPEC — Section 13C: Input model (vi command line, buffer switcher, leader menu, vi text inputs)

Part of Pipist spec v1.3. Extends section 13 (GUI). Where this section and 13.3 ("Actions and keymaps") overlap, 13C wins. Milestone: part of **M6**. Adds no third-party dependency.

## 13C.0 Principles
1. **The editor of choice owns text editing.** Real text editing happens in nvim inside a terminal pane (the owner's vi setup is already configured there). Pipist never tries to be a text editor.
2. **Vi-style everywhere Pipist itself handles text.** Every text input that Pipist draws itself (command line, search, filters, console) is a vi-modal input (13C.4).
3. **One action table, three front doors.** Command line (`:`), leader menu (Space), and direct keys all trigger the same registered *actions* (13C.7). The CLI uses the same table.
4. **Keyboard-complete.** Every GUI function reachable by mouse is reachable by keyboard; every key binding is data (TOML), remappable, listed by `:help keys`.
5. **No conflict with the terminal.** A terminal pane receives every key (so nvim behaves exactly as in a normal terminal) except one configurable *prefix key* (13C.2).

## 13C.1 Input modes
The GUI has exactly one *input mode* at a time. The current mode is shown in the status bar (`-- NORMAL --`, `-- PASSTHROUGH --`, `-- COMMAND --`, `-- SEARCH --`, `-- LEADER --`, `-- INSERT --`), colored per mode (colors in theme TOML, like the Los Ciegos mode colors).

| Mode | When | Keys go to |
|---|---|---|
| `gui-normal` | Focus is on any non-terminal panel, or the user left a terminal with `<Prefix><Esc>` | GUI keymap for the focused panel's scope, then global scope |
| `passthrough` | Focus is on a terminal pane (Editor, Terminal, Processes terminal) | The PTY, except the prefix key |
| `command` | `:` pressed (cmdline open) | The cmdline `ViInput` |
| `search` | `/` or `?` pressed (panel filter/search open) | The search `ViInput` |
| `leader` | Leader key pressed | The leader-menu engine |
| `insert` | A text field that is not the cmdline/search is focused (property field, rename box, etc.) | That widget (plain editing unless it is a `ViInput`, 13C.4) |
| `viewport-edit` | Focus on a Viewport panel in Edit state | Viewport tool keymap (13B.7) |
| `viewport-play` | Viewport captured in Play state | The game (13A.5), except the release hotkey |

Mode transitions: clicking a panel focuses it and sets the mode from the panel type. `<Esc>` (or `<C-[>`, or `<C-Space>`; all three are equivalent in every mode **except** `passthrough` and `viewport-play`) returns `command`, `search`, `leader`, `insert` to `gui-normal`.

## 13C.2 Passthrough prefix
- Default prefix: **`<C-\>`** (configurable: `[gui].prefix`). Chosen because it is rarely used by nvim, shells and games.
- In `passthrough`, the prefix is a one-shot: the next key is interpreted by the GUI:

| Keys | Effect |
|---|---|
| `<Prefix><Esc>` | Leave the terminal; mode becomes `gui-normal`, focus stays on the panel |
| `<Prefix><Space>` | Open the leader menu |
| `<Prefix>:` | Open the command line |
| `<Prefix>b` | Open the buffer switcher (13C.5) |
| `<Prefix><Tab>` | Toggle alternate panel (like `<C-^>`) |
| `<Prefix>h/j/k/l` | Move focus to the neighbouring dock/window |
| `<Prefix>p` | Pop out the current panel; `<Prefix>d` dock it back |
| `<Prefix><Prefix>` | Send a literal prefix key to the PTY |
| anything else | Sent to the PTY unchanged (the prefix is swallowed) |

- Prefix timeout: if no second key within `[gui].prefix_timeout_ms` (default 1500) the prefix is cancelled silently (nothing sent).
- Terminal-focus entry: clicking a terminal pane or activating it from the switcher enters `passthrough` immediately.

## 13C.3 Command line (`:`)
**Appearance.** A one-line bar at the bottom of the main window (above the status bar), opened with `:` in `gui-normal` (or `<Prefix>:`). In pop-out windows it opens as an overlay at the bottom of that window. Contents: prompt `:`, the input, and a completion popup above it.

**Editing.** The line is a `ViInput` (13C.4) that starts in *insert* sub-mode. `<Esc>` once → vi normal sub-mode within the line (so `0`, `w`, `dw`, `cw` work); `<Esc>` again, or `<C-c>`, cancels the cmdline. `<CR>` executes in either sub-mode.

**History.** Persistent in `.pipist/history/cmdline` (max 1000, de-duplicated, per project) and `~/.local/state/pipist/history/cmdline` (global, max 1000). `<Up>/<Down>` and `<C-p>/<C-n>` walk entries that match the typed prefix; `<C-r>` opens reverse incremental search (`ViInput` search over history). In vi normal sub-mode, `k`/`j` also walk history.

**Completion.** `<Tab>`/`<S-Tab>` cycle; the popup also appears automatically after 150 ms of typing (disable: `[gui].cmdline_autocomplete = false`). Completion sources by argument kind: command names; panel ids; workspace names; module names (including unloaded); target names; file paths (project-relative); symbols and entities (from `index`, only if loaded; otherwise a hint *"index not loaded"*); timeline ticks and bookmark names; state paths (from the current instance); config keys; action ids; theme names. Each command declares its argument kinds (13C.7).

**Grammar.**
```
cmdline  := command ( ' | ' command )*            # '|' chains commands; stops at first error
command  := name [ '!' ] ( ' ' arg )*
arg      := bare-word | "double quoted" | 'single quoted'     # backslash escapes inside quotes
expands  := '%' current file (project-relative)  |  '#' alternate file  |  '%:l' current line  |  '<cword>'  (word under cursor in the focused CodeView)
```
`!` means force/override where a command defines it (`:q!`, `:unload! index`). Numeric prefixes are not supported.

**Output.** Short results (one line) show in the message area replacing the cmdline for 4 s (errors in the error color, kept until the next input). Multi-line results open the *Output peek* (bottom panel, height up to 40% of window, dismiss with `<Esc>`/`q`, scroll with `j/k/<C-d>/<C-u>`, entries are clickable/`<CR>`-activatable when they carry file locations).

**Built-in commands** (each is an action with a `cmd` alias, 13C.7):

| Command | Meaning |
|---|---|
| `:q` / `:q!` | Close the focused panel (if it is the last panel in a pop-out window, closes the window) / force |
| `:qa` | Quit the GUI (daemon keeps running); `:qa!` also shuts the daemon down |
| `:w`, `:wa`, `:wq`, `:x` | Forwarded to the focused nvim: save current / all / save+close buffer |
| `:e <file>[:line[:col]]`, `:edit` | Open in the editor (`editor.open`) |
| `:b <name|n>`, `:bn`, `:bp`, `:ls`, `:buffers`, `:b#` | Panel switcher commands (13C.5); `:ls` lists in the Output peek |
| `:panel <id>` / `:p <id>` | Open (or focus) a panel |
| `:pop [<id>]`, `:dock [<id>]` | Pop out / dock back the given or focused panel |
| `:ws <name>` / `:workspace` | Switch workspace; `:ws save <name>`; `:ws list` |
| `:split [<id>]`, `:vsplit [<id>]` | Split the focused dock area horizontally/vertically and place the panel in the new area |
| `:tabnew [<id>]`, `:tabn`, `:tabp`, `:tabc` | Tab-group operations on the focused dock area |
| `:only` | Close every other panel in the focused window |
| `:find <text>` / `:grep <text>` | `search.text` → Search panel |
| `:sym <name>`, `:ent <name>`, `:str <text>`, `:where <text>` | The other search kinds |
| `:goto <file[:line]>` | Alias of `:e` for code; `:goto <tick>` when the argument is an integer prefixed with `t` (e.g. `:goto t412`) → `timeline.goto` fork |
| `:fork [t<tick>]` | Fork at the given/current tick with current code (`reload: auto`) |
| `:bookmark <name>` | Bookmark the current tick |
| `:run <target>`, `:build [<target>]`, `:test [<target>]`, `:stop` | Targets and game control |
| `:pause`, `:resume`, `:step [n]`, `:speed <x>` | Game control |
| `:patch`, `:patch preview`, `:patch revert [id]` | Hot-patch control |
| `:load <modules…>`, `:unload[!] <modules…>`, `:modules` | Module control (`:modules` opens the Modules panel) |
| `:exp run <name>`, `:exp list` | Experiments |
| `:set <key>[=<value>]`, `:set <key>?`, `:set no<key>`, `:setlocal` | Config: writes `pipist.local.toml` (`:set`) or session-only (`:setlocal`). Keys use dotted TOML paths (`gui.popout=floating`) |
| `:map`, `:unmap` | Show / session-override keymap entries |
| `:help [<topic>]`, `:help keys`, `:help commands`, `:help actions` | In-app help in the Output peek or a Help panel |
| `:!<shell command>` | Run a command in a new Processes entry (PTY); `:!!` repeats the last |
| `:theme <name>` | Switch theme live |
| `:screenshot [<path>]` | Save a PNG of the focused window |
| `:messages` | Show the last 100 messages/errors |
| `:log [<level>]` | Open the Log panel (optionally filtered) |
| `:rpc <method> [<json params>]` | Raw JSON-RPC call; result in the Output peek (developer tool) |

Unknown command: error `E492: not a command: <name>` plus up to 3 nearest suggestions.

## 13C.4 Vi text input — the `ViInput` widget and `ViEngine`
**Engine.** `ViEngine` is a pure C++ class in `libpipist/vi/` with no GUI or terminal dependency. Input: key events in the key notation of 13C.8. State: text (UTF-8, line array), cursor (line, byte column), selection, mode, pending operator/count/register, registers, undo tree, last-change record (for `.`), last-find (`f/t` repeat), last search. Output: new state plus optional *effects* (`yank_to_clipboard(text)`, `request_paste`, `submit`, `cancel`, `bell`, `search(pattern, direction)`). The same engine drives (a) `ViInput` in the GUI and (b) the `pipist repl` line editor in a plain terminal (own raw-mode terminal handling, no readline/linenoise dependency).

**Modes.** `insert`, `normal`, `visual` (charwise), `visual-line` (multi-line widgets only), `replace` (`R`), `operator-pending`.

**Supported commands (v1).**
- *Motions:* `h l 0 ^ $ g_ w W b B e E ge f{c} F{c} t{c} T{c} ; ,` and, in multi-line widgets only, `j k gg G { }` (`H L M` are not supported); `%` matches `() [] {} <> "" ''` on the line; counts (`3w`, `2fx`).
- *Operators* (with motions or text objects, and doubled for the whole line `dd cc yy`): `d c y > <` (`> <` only in multi-line). Text objects: `iw aw iW aW i" a" i' a' i( a( i[ a[ i{ a{ i< a< ip ap` (`ip ap` multi-line).
- *Single commands:* `x X D C Y s S r{c} R ~ J p P u <C-r> . a A i I o O` (`o O` multi-line only), `gi`, `ga`-style not supported.
- *Insert-mode keys (emacs-style subset):* `<C-a>` start of line, `<C-e>` end, `<C-b>/<C-f>` char left/right, `<C-w>` delete word back, `<C-u>` delete to start, `<C-k>` delete to end, `<C-h>`/`<BS>` backspace, `<C-d>`/`<Del>` delete char, `<C-v>` insert next key literally, `<C-r>{reg}` insert register, `<C-o>` one normal command, `<C-n>/<C-p>` completion navigation (cmdline/search only).
- *Registers:* `""` unnamed; `"0` last yank; `"a`–`"z` named (uppercase appends); `"+` and `"*` system clipboard (via SDL); `"_` blackhole; `"/` last search; `":` last command. Yanks also go to the clipboard when `[gui].yank_to_clipboard = true` (default true).
- *Visual:* `v V` toggle; `o` swap ends; operators `d c y > < ~ u U r` act on the selection; `iw` etc. extend.
- *Search inside multi-line widgets:* `/` `?` `n` `N` (smart-case) with incremental highlight.
- *Undo:* linear undo/redo with change grouping per insert session; `u` / `<C-r>`; history cleared on submit.
- *Dot repeat:* `.` repeats the last change including inserted text.
- *Not supported (documented, intentional):* marks, macros (`q`/`@`), ex ranges, folds, `:s`, window commands, `gq`, digraphs.
- Escape alternates: `<C-[>` and `<C-Space>` are equivalent to `<Esc>`.

**Cursor and indicator.** Block cursor in normal/visual/operator-pending, bar in insert, underline in replace. Blink 2 Hz only while the widget is focused and `[gui].cursor_blink = true` (default). The mode indicator is in the status bar (and, for the cmdline, at the left of the bar).

**Where it is used.**

| Widget | Default |
|---|---|
| Command line | vi (insert sub-mode first) |
| Search / filter fields (`/`) in every panel; Search panel query; Log filter; Problems filter; Switcher query | vi (insert sub-mode first), single line |
| Console drawer REPL | vi, multi-line (Shift+Enter inserts a newline; Enter submits) |
| Declarative-panel `input` widgets, Inspector text fields, rename boxes, dialogs | plain editing (no modal) |
| All of the above | `[gui].vi_inputs = "all"` turns every Pipist-drawn text field into a `ViInput`; `"none"` makes the cmdline/search plain |

**Tests.** `tests/unit/vi_engine_table.cpp` is a table of `{initial text+cursor, keys, expected text+cursor+mode+registers}` rows. It must contain at least 300 rows covering every command above, and a fuzz test that feeds random key sequences and asserts invariants (cursor in bounds, UTF-8 validity, undo restores the original text).

## 13C.5 Buffer switcher (`<Leader>b`, `:b`, `<Prefix>b`)
"Buffers" in Pipist are everything you can switch to: **panels** (open or openable), **nvim buffers**, **terminals**, **game instances**, **OS windows**, **workspaces**, and **tools** (panels whose module is not loaded yet, shown dimmed with *load* hint).

**Popup.** A centered list with a `ViInput` query (fuzzy, subsequence match with score; MRU order when the query is empty).
Each row: `<index>  <kind icon> <name>  <detail>  <state>` where detail is window/dock location (e.g. `main/right`, `win2`), file path for nvim buffers, target name for instances; state is `modified`, `running`, `exited(1)`, `not loaded`.

**Keys inside the switcher.**

| Key | Action |
|---|---|
| typing | Filter |
| `<C-j>/<C-k>` or `<Down>/<Up>` | Move selection |
| `<CR>` | Activate: focus the panel (raise its window if it lives in another OS window); open it if closed; load its module first if needed |
| `<C-v>` / `<C-s>` | Open in a vertical / horizontal split of the focused area |
| `<C-t>` | Open in a new tab in the focused area |
| `<C-o>` | Open popped out in its own window |
| `<C-d>` | Close the selected panel / buffer |
| `1`–`9` (when query empty) | Jump directly to row N |
| `<Tab>` | Toggle between panels/nvim-buffers/terminals/instances/all categories (shown as chips) |
| `<Esc>` | Close the switcher |

**Related quick keys (`gui-normal`):** `<Leader><Leader>` toggle alternate panel; `gt`/`gT` next/previous tab in the focused tab group; `<C-w>` window-command prefix: `h j k l` move focus, `H J K L` move the panel to that side, `q` close panel, `o` only, `T` pop out, `=` equalize sizes, `s`/`v` split, `w` cycle windows. `<C-Tab>`/`<C-S-Tab>` cycle tabs (also in passthrough when `[gui].intercept_ctrl_tab = true`, default false).

## 13C.6 Leader menu (which-key)
**Leader key:** `<Space>` in `gui-normal` (and `<Prefix><Space>` in passthrough). Configurable `[gui].leader`.

**Behaviour.**
- Pressing the leader enters `leader` mode and shows the which-key popup after `[gui].which_key_delay_ms` (default 250; 0 = immediately; typing fast enough never shows it). The popup lists the keys available at the current node as `key  label` (groups end with `+`), laid out in columns at the bottom center, with the current path in the header (`LEADER  g  game`).
- A key either descends into a group, runs an action, or (for an action with `prompt = true`) opens the cmdline prefilled (`:run `, `:goto t`), leaving the user to finish and press `<CR>`.
- `<BS>` goes up one level; `<Esc>`/`<C-[>`/`<C-Space>` or `<Space>` at the root closes (so double-space toggles); an unmapped key closes with a message `leader: no mapping for <keys>`.
- Dynamic groups: a node can declare `children_from = "<provider>"` where the provider yields `{key, label, action, args}` entries computed at open time. Providers: `panels` (assigns letters/digits), `workspaces`, `modules`, `targets`, `bookmarks`, `recent_files`, `instances`, `windows`. Letters are assigned by first unused character of the label, stable per session.
- Timeout: none (the menu stays until a decision), except `[gui].leader_timeout_ms` if set > 0.

**Definition file.** `keymaps/leader.toml` (shipped default; overridden by `~/.config/pipist/keymaps/leader.toml` and `<project>/.pipist/keymaps/leader.toml`, merged node-by-node, later wins; `remove = true` deletes a node).
```toml
[[node]]
path   = "g"                  # key sequence relative to the leader
label  = "game"               # a node with children is a group
[[node]]
path   = "g r"
label  = "run target…"
action = "target.run"
prompt = true                 # opens :run with completion instead of running immediately
[[node]]
path   = "b"
label  = "buffers"
action = "switcher.open"
[[node]]
path   = "w"
label  = "workspaces"
children_from = "workspaces"  # dynamic children
```
Maximum depth 4 levels (the loader rejects deeper trees and duplicate keys within a group, reporting the file and node).

**Default tree** (all of this ships in the default file; each leaf names a registered action, full list in `docs/keymap.md`, generated from the file):

| Keys | Meaning |
|---|---|
| `<Leader>` `<Leader>` | Alternate panel |
| `b` | Buffer switcher (all) · `bp` panels · `bn` nvim buffers · `bt` terminals · `bi` instances · `bw` windows |
| `f` | files/search: `ff` find file · `fg` grep · `fs` symbols · `fe` entities · `fw` where · `fr` recent files |
| `p` | panels: `po` open panel… · `pp` pop out · `pd` dock back · `pc` close · `pm` modules panel · `pl` list |
| `w` | workspaces/windows: `we` edit · `wd` debug · `wp` play · `ws` studio · `wx` experiment · `wf` focus-game · `ww` save layout · `w` + `h/j/k/l` move focus · `w` + `H/J/K/L` move panel · `w-` split · `w\|` vsplit · `w=` equalize |
| `t` | timeline: `tt` open · `tg` goto tick… · `tf` fork here · `tb` bookmark · `t]`/`t[` next/previous snapshot · `td` diff · `ts` save point |
| `g` | game: `gr` run target… · `gs` stop · `gp` pause/resume · `gn` step · `gR` reload (auto) · `ge` edit/play toggle · `gc` release capture · `gv` viewport mode… |
| `c` | code: `ca` apply patch · `cp` preview patch · `cr` revert patch · `cd` diagnostics · `cb` build · `ct` test |
| `m` | modules: `ml` load… · `mu` unload… · `mm` modules panel · `ma` always-load… |
| `e` | editor: `eo` open… · `eg` goto… · `es` save · `en` nvim command… |
| `x` | experiments: `xr` run… · `xl` list · `xc` check goldens |
| `s` | studio: `ss` select · `sm` move · `sr` rotate · `sS` scale (tool shortcuts, equal to `q/w/e/r` in the viewport) · `sk` keep changes · `su` undo · `sU` redo · `sn` new entity · `sd` delete |
| `l` | log: `lo` open · `lc` clear · `ll` level… · `lf` follow toggle |
| `h` | help: `hk` keys · `hc` commands · `ha` actions · `hh` help panel |
| `q` | quit: `qq` quit GUI · `qd` quit GUI and shut down daemon · `qr` restart GUI |

## 13C.7 Actions
Every command is an *action* registered in code through one table (`pipist-ui/actions.*`, and the CLI-visible subset in `pipist-cli`):
```
Action { id: "ns.verb", title, cmd?: ":name" aliases[], args: [ArgSpec], scope: global|panel:<id>|viewport|..., when?: condition, run: handler,
         default_keys: [ {mode, keys} ] }
ArgSpec { name, kind: string|int|bool|file|panel|workspace|module|target|symbol|entity|tick|bookmark|statepath|configkey|action|theme|json, optional, variadic }
```
- Keymap entries, leader nodes, cmdline commands and the palette all reference actions by id. `:help actions` lists id, title, cmd, keys, and description; `:help keys` is generated from the active keymaps (not hand-written).
- Actions are also callable remotely: `gui.action.run {id, args}` (Appendix A, `gui.*`), so `pipist gui action panel.open timeline` from a terminal drives the GUI.
- `when` conditions use a tiny expression language over context keys: `module.loaded:<name>`, `instance.exists`, `instance.kind == "native"`, `panel.focused:<id>`, `mode == "gui-normal"`, `state.playing`.

## 13C.8 Key notation, keymap files, precedence
- **Notation (vim-style, case-sensitive for letters):** `a`, `A` (shift+a), `<C-x>`, `<A-x>`, `<S-Tab>`, `<D-x>` (super), combinations `<C-A-x>`, named keys `<Space> <CR> <Esc> <Tab> <BS> <Del> <Up> <Down> <Left> <Right> <Home> <End> <PageUp> <PageDown> <F1>…<F12> <Leader> <Prefix>`. Sequences are concatenated: `<Leader>fg`, `gt`, `<C-w>h`.
- **Keymap file** `keymaps/*.toml`:
```toml
[[map]]
mode   = "gui-normal"          # gui-normal | list | cmdline-normal | cmdline-insert | search-normal | search-insert | viewport-edit | passthrough-prefix | leader | switcher
scope  = "global"              # "global" or "panel:<id>"
keys   = "gt"
action = "tab.next"
args   = {}
desc   = "Next tab"
```
- **Precedence** (first match wins): modal widget in focus (`ViInput`, switcher) → `passthrough-prefix`/terminal → `panel:<id>` scope entries → `global` entries → built-in defaults. Layers merge in the order built-in < user < project < `pipist.local.toml`; a later entry with the same `mode+scope+keys` replaces the earlier; `action = ""` unmaps.
- **Sequences and timeout:** an ambiguous prefix (e.g. `g` vs `gt`) waits `[gui].key_timeout_ms` (default 1000) then runs the shorter binding if one exists. Counts (`3gt`) are accepted for actions that declare `count = true`.
- **Presets:** `default` (above) and `vi-leader` (same as `default`, kept for compatibility with earlier notes); `emacs` is out of scope.
- **Conflict report:** the loader writes duplicates and shadowed bindings to the Problems panel (`source = keymap`).

## 13C.9 List-navigation keys (all list-like panels in `gui-normal`)
Applies to Log, Search, Problems, Hierarchy, Timeline list, Modules, Processes, Experiments results, Assets list, State inspector tree, Output peek, Switcher results:

| Key | Action |
|---|---|
| `j` `k` / `<Down>` `<Up>` | Next / previous row |
| `<C-d>` `<C-u>` / `<PageDown>` `<PageUp>` | Half / full page |
| `gg` `G` | First / last row |
| `<CR>` | Activate (open source location, load module, select, expand) |
| `o` | Toggle expand/collapse (tree panels); `zo`/`zc`/`zR`/`zM` open/close/open-all/close-all |
| `/` `?` `n` `N` | Filter/search within the panel (vi search input); next/previous match |
| `yy` / `yp` | Copy the row text / copy its path (file:line or state path) |
| `x` | Dismiss/close the row if the panel supports it (Problems, Processes) |
| `r` | Refresh/re-run |
| `<Esc>` | Clear filter / leave panel search |
Panel-specific keys are defined in each panel's layout (planned in a later spec item) and registered with `scope = "panel:<id>"`.

## 13C.10 CLI side (`pipist repl`, terminal-only workflow)
`pipist repl` uses `ViEngine` as its line editor (default `insert` mode; `<Esc>` → normal) with the same history files as the GUI cmdline, the same completion sources (via protocol calls) and the same command grammar, minus GUI-only commands (they are sent to a running GUI with `gui.action.run` when one is connected). `pipist tmux` panes use it too.

## 13C.11 Config keys added
```toml
[gui]
prefix = "<C-\\>"
prefix_timeout_ms = 1500
leader = "<Space>"
which_key_delay_ms = 250
leader_timeout_ms = 0
key_timeout_ms = 1000
vi_inputs = "cmd"            # "cmd" (cmdline/search/console) | "all" | "none"
yank_to_clipboard = true
cursor_blink = true
cmdline_autocomplete = true
intercept_ctrl_tab = false
```

## 13C.12 Done-when additions for M6
- `vi_engine_table` ≥ 300 rows pass; fuzz test passes under ASan/UBSan.
- Scripted GUI test (`--script`) drives: `:panel timeline<CR>`, `<Space>bt` (switcher → terminals), `<C-\><Space>` from a terminal, `:pop log` (second OS window appears), `:dock log`, `<Space>wd` (workspace switch), `:set gui.popout=floating`; the status bar mode text and the cmdline/which-key popup are captured by `--screenshot` and compared by non-blank and by text dump (`--dump-ui` prints visible text per widget).
- Terminal passthrough: with `cat -v` running in a Terminal panel, every key except the prefix reaches it unchanged (test sends a key table, compares echoed bytes); `<Prefix><Prefix>` delivers one literal prefix byte (0x1c).
- Keymap and leader loaders reject invalid files with line-accurate errors (golden error texts).

<!-- SOURCE-END: pipist-spec-13c-input.md -->

---

<!-- SOURCE-BEGIN: pipist-spec-a1-protocol-core.md -->

# PIPIST SPEC — Appendix A1: Protocol, core (wire, envelope, types, kernel namespaces)

Part of Pipist spec v1.3. Replaces and makes exact sections 5.1–5.4 of the main spec (where they differ, **this appendix wins**; in particular the event format in 5.4 is superseded by A1.2). Notation is TypeScript-style interfaces; `?` = optional; all keys are `snake_case`; unknown keys MUST be ignored by receivers; unknown enum values MUST be treated as "other" by clients. Appendix A2 covers the domain namespaces (game, timeline, patch, search, studio, ...) and the event catalogue.

The cloud run MUST: (1) generate JSON Schema (draft 2020-12) files from these definitions into `protocol/schema/` (one per method params/result and per event), (2) implement the C++ types in `libpipist/protocol/` by hand or generation, (3) add a conformance test that every example message in `tests/protocol/examples/*.jsonl` validates against the schemas, and every schema has at least one example.

## A1.1 Transports and framing
| Transport | Framing | Notes |
|---|---|---|
| Unix domain socket (`SOCK_STREAM`) | NDJSON: one JSON object per line, terminated by `\n` (0x0A). Raw newlines never occur inside a message (JSON escapes them). `\r\n` is accepted on input. | Primary. File descriptors may be attached (A1.7). |
| WebSocket (RFC 6455), text frames | One JSON object per frame; no trailing newline | For the browser agent and web tools. No fd passing. |
| Module socketpair (fd 3) | Same as Unix socket | Kernel ↔ process module. |

- Encoding UTF-8, no BOM. Max message size **16 MiB** (`limits.max_message_bytes`); a larger line closes the connection after an error `-32008`.
- JSON batches (top-level arrays) are **not supported**: reply `-32600`.
- Kernel never sends requests to ordinary clients, except to a client that registered `session.provide` (A1.5), or to modules (A1.9). Everything else the kernel sends to clients is a notification.
- Idle: either side may send `session.ping`; connections silent for `limits.idle_timeout_s` (default 0 = never) are closed.
- Ordering: responses to different requests may arrive in any order; notifications from one connection are delivered in `seq` order.

## A1.2 Message envelope
Exactly JSON-RPC 2.0, `"jsonrpc":"2.0"` required on every message.
```ts
interface Request      { jsonrpc: "2.0"; id: number | string; method: string; params?: object }   // params, if present, is an object (never an array)
interface Notification { jsonrpc: "2.0"; method: string; params?: object }                          // no id
interface Response     { jsonrpc: "2.0"; id: number | string | null; result?: any; error?: RpcError }  // exactly one of result|error
interface RpcError     { code: number; message: string; data?: ErrorData }
interface ErrorData    { kind: string; detail?: any; [k: string]: any }   // kind = machine name from A1.3
```
- `id` is chosen by the sender, unique among that sender's in-flight requests; reuse while in flight → `-32600`. Kernel-originated request ids are strings of the form `"k:<n>"`.
- **Reserved params key `_meta`** (all methods): `{ timeout_ms?: number; trace_id?: string; caller?: string }`. Default request timeout is 30 000 ms unless a method states otherwise; on expiry the kernel answers `-32006` and, if the request had been forwarded, sends the target a `session.cancel`.
- **Event envelope** (kernel → subscribed clients), always this one method name:
```json
{"jsonrpc":"2.0","method":"event","params":{"topic":"file.changed","seq":1042,"ts":1793574000123,"data":{"path":"js/13-combat.js","hash":"sha256:9f2c…"}}}
```
```ts
interface Event { topic: string; seq: number /* monotonic per kernel run, starts at 1 */; ts: number /* ms since Unix epoch UTC */; data: object }
```

## A1.3 Errors
Standard JSON-RPC codes plus the Pipist range. Every error carries `data.kind`.
| Code | `kind` | Meaning | Typical `data` extras |
|---|---|---|---|
| -32700 | `parse_error` | Invalid JSON | `offset` |
| -32600 | `invalid_request` | Not a valid request; batch; hello required; duplicate in-flight id | |
| -32601 | `method_not_found` | No such method (or provider gone) | `method` |
| -32602 | `invalid_params` | Params fail schema | `path` (JSON pointer), `expected` |
| -32603 | `internal_error` | Bug in the receiver | `detail` |
| -32001 | `unauthorized` | Bad/missing token, wrong uid, forbidden origin | |
| -32002 | `not_found` | Entity does not exist | `what`, `id` |
| -32003 | `conflict` | Optimistic-concurrency failure or duplicate registration | `expected_hash`, `actual_hash` |
| -32004 | `invalid_state` | Valid request in the wrong state | `state` |
| -32005 | `unsupported` | Capability absent (host/runtime/platform) | `capability` |
| -32006 | `timeout` | Request timed out | `after_ms` |
| -32007 | `cancelled` | Cancelled by `session.cancel` or shutdown | |
| -32008 | `too_large` | Payload exceeds a limit; use a blob | `limit`, `size` |
| -32009 | `busy` | Resource in use / queue full | `reason?` (`timeline.prune`/`branch.delete`: `fork_root`\|`protected`\|`disk_full`\|`quota`), `protected?` |
| -32010 | `module_unavailable` | Module could not start | `name`, `reason` |
| -32011 | `module_crashed` | Module died while handling the request | `name`, `exit` |
| -32012 | `no_instance` | No (or ambiguous) runtime instance | `candidates: string[]` |
| -32013 | `protocol_mismatch` | Protocol major version unsupported | `supported: string[]` |
| -32015 | `patch_failed` | Hot patch rejected | `tier`, `diagnostics` |
| -32016 | `rejected` | The game/runtime refused (not quiescent, mid-tick, etc.) | `reason` |

`data.detail.code` may carry adapter codes (Appendix B1): `E_SNAP_TOO_LARGE`, `E_CONST_DIFF`, `E_REG_TDZ`, `E_REG_MISSING` (errors) and `W_INERT_CONTROLS`, `W_TIMERS_DROPPED`, `W_SHIM_MISSING` (warnings, also in `adapter.describe`).

## A1.4 Common types
```ts
type Id        = string;                       // opaque, [A-Za-z0-9_.:-]{1,64}
type Path      = string;                       // project-relative, '/' separators, no '..', no leading '/'
type AbsPath   = string;
type Hash      = string;                       // "sha256:<64 lowercase hex>" (content hash of file bytes / blobs)
type Pos       = [line: number, col: number];  // 1-based line, 1-based column counted in UTF-8 bytes
type Range     = [start_line: number, start_col: number, end_line: number, end_col: number]; // end-exclusive
type Severity  = "error" | "warning" | "info" | "hint";
type Tick      = number;                       // integer >= 0, per instance
type SnapshotId = string;                      // "s_<base32>"
type BranchId  = string;                       // "b<N>"
type InstanceId = string;                      // "i<N>"
type ProcId    = string;                       // "p<N>" or user-chosen id
interface BlobRef { blob: Hash; size: number; mime?: string }
interface TextEdit { file: Path; range: Range; text: string }
interface Page<T> { items: T[]; next_cursor?: string }           // cursor-based pagination; params: limit?: number (default 100, max 1000), cursor?: string
type StatePath = string;       // grammar: ident ( "." ident | "[" (int | "\"" chars "\"") "]" )*   e.g.  G.flags.chuyRep   npcs["la_senora"].mood   entities[3].pos[0]
```

### Pipist Value encoding (state, snapshots, tweaks, eval results)
JSON plus tagged objects for things JSON cannot express. A plain object that happens to have a `"$t"` key is wrapped as `{"$t":"esc","v":{…}}`.
| Value | Encoding |
|---|---|
| null, bool, string, finite number, array, plain object | as JSON |
| `undefined` | `{"$t":"undef"}` |
| NaN / ±Infinity / -0 | `{"$t":"nan"}` / `{"$t":"inf","sign":1}` or `-1` / `{"$t":"negzero"}` |
| BigInt | `{"$t":"bigint","v":"123456789012345678901"}` |
| Date | `{"$t":"date","ms":1793574000123}` |
| Map | `{"$t":"map","e":[[k,v],…]}` |
| Set | `{"$t":"set","e":[v,…]}` |
| Bytes / typed array | `{"$t":"bytes","kind":"u8","b64":"…"}` (≤ 64 KiB) or `{"$t":"bytes","kind":"u8","blob":BlobRef}` |
| Shared/cyclic reference | `{"$t":"ref","path":"G.player"}` (first occurrence is inline; later ones are refs; path is from the root of the snapshot) |
| Class instance | `{"$t":"obj","class":"Foo","v":{…}}` (restorable only if the adapter knows the class) |
| RegExp | `{"$t":"re","src":"…","flags":"…"}` |
| DOM node | `{"$t":"dom","id":N}` (headless host, stable node ids) or `{"$t":"dom","sel":"<css path>"}` (browser agent, best effort) |
| Unchanged key in a delta snapshot | `{"$t":"same"}` (only inside deltas; see `timeline.snapshot.put` `base`/`unchanged` in A2.2) |
| Function / Symbol / opaque host object | In snapshots, functions are allowed only as `{"$t":"fn","name":"foo"}` markers when the adapter policy is `keep-live` (restore never replaces a live function); otherwise `snapshot()` must fail naming the path. Symbols and opaque objects are never allowed. In `state.get` views: `{"$t":"fn","name":"foo"}`, `{"$t":"opaque","kind":"HTMLElement"}`, `{"$t":"sym","d":"desc"}` |
| Truncated view (read-only, never in snapshots) | `{"$t":"summary","type":"object","size":120}` or `"array"`, `"string"` (with `"prefix"`) |
Inline state in a message is limited to 256 KiB serialized; larger payloads travel as `BlobRef` (error `-32008` otherwise).

## A1.5 Session namespace
```ts
// session.hello — MUST be the first request on every connection (else -32600). Over WebSocket the token is checked first.
interface HelloParams {
  client: { name: string; version: string; kind: "cli" | "gui" | "module" | "host" | "runtime" | "script" | "agent" };
  protocol: string;                       // "1"
  capabilities?: string[];                // client features, e.g. ["event.batch"] (none required in v1)
  token?: string;                         // WebSocket only
}
interface HelloResult {
  server: { name: "pipistd"; version: string; protocol: "1" };
  session_id: string;
  project: { name: string; root: AbsPath; config_hash: Hash; revision: Hash };
  profile: string;
  capabilities: string[];                 // kernel features, e.g. ["fd_passing","blob.put_path"] (fd_passing only on unix sockets)
  limits: { max_message_bytes: number; max_inline_state_bytes: number; client_queue_events: number; idle_timeout_s: number };
  clock: { now_ms: number };              // kernel Unix time, for skew detection
}
```
| Method | Params | Result | Notes |
|---|---|---|---|
| `session.ping` | `{}` | `{ ts: number }` | |
| `session.subscribe` | `{ topics: string[]; since_seq?: number; replay?: number }` | `{ subscription: number; current_seq: number; gap?: { oldest_seq: number } }` | Topic globs: segments separated by `.`; `*` = one segment, `**` = one or more; `file.*` matches `file.changed`, not `file.a.b`. `since_seq` replays from the bus ring (default ring 10 000 events); if older events were dropped, `gap` is set. `replay: N` = replay the last N matching events. Activating a subscription may load lazy modules (spec 3A.3 `on_event`). |
| `session.unsubscribe` | `{ subscription: number }` | `{}` | |
| `session.provide` | `{ methods: string[]; replace?: boolean }` | `{}` | The client will serve these method globs (e.g. the GUI serves `gui.*`). Kernel forwards matching requests as `Request` with `id:"k:<n>"` and `params._meta.caller`. Conflict with another provider → `-32003` unless `replace`. Provider disconnect → pending calls get `-32601`. |
| `session.cancel` | `{ id: number \| string }` | `{ cancelled: boolean }` | Cancels an in-flight request of this connection; the original gets `-32007`. |
| `session.clients` | `{}` | `{ clients: { id: string; name: string; kind: string; pid?: number; since: number; provides: string[]; subscriptions: string[][] }[] }` | |
| `session.shutdown` | `{ mode: "daemon" \| "disconnect"; grace_ms?: number }` | `{}` | `daemon`: stop supervised processes per policy, then exit. |

Backpressure: each client has a bounded event queue (`client_queue_events`, default 4096). On overflow the oldest events are dropped and one `bus.dropped` event `{count, first_seq, last_seq}` is queued. Requests are never dropped.

## A1.6 Project and config namespaces
```ts
// project.*
project.info     {} -> { name; root: AbsPath; version: string; profile: string; packs: string[]; targets: string[]; config_files: AbsPath[]; revision: Hash; instances: number }
project.files    { glob?: string; limit?; cursor? } -> Page<{ path: Path; size: number; mtime: number; hash?: Hash }>
project.read     { path: Path; range?: Range } -> { text: string; hash: Hash; eol: "lf"|"crlf" }        // UTF-8 files only, <= 4 MiB else -32008; non-UTF-8 -> -32602
project.write    { path: Path; text: string; expect_hash?: Hash; create?: boolean } -> { hash: Hash }      // atomic (tmp+rename); mismatch -> -32003. Tools only; interactive edits go through the editor
project.revision {} -> { revision: Hash; files: number }                                                  // hash over (path, content hash) of tracked source files
project.hash     { paths: Path[] } -> { hashes: Record<Path, Hash | null> }
// config.*
config.get    { key?: string } -> { value: any; origin: { layer: "builtin"|"user"|"project"|"local"|"cli"|"env"; file?: AbsPath } }   // key = dotted TOML path; omitted key = whole effective config
config.set    { key: string; value: any; layer: "local" | "project" | "user" } -> { file: AbsPath }      // comment- and order-preserving edit of that TOML layer
config.reload {} -> { changed: string[] }
config.dump   {} -> { effective: object; layers: { name: string; file?: AbsPath; exists: boolean }[] }
```
`project.*` paths are validated: absolute, `..`, symlinks that escape the project root → `-32602`.

## A1.7 Process namespace (`proc.*`) and file-descriptor passing
```ts
interface ProcInfo { proc: ProcId; pid: number; state: "running"|"exited"|"crashed"|"stopping"; cmd: string[]; cwd: AbsPath; started: number; exit_code?: number; signal?: string; pty: boolean; tags: string[]; restarts: number }
proc.start {
  id?: ProcId; cmd?: string[]; shell?: string;            // exactly one of cmd (argv) or shell (run via $SHELL -c)
  cwd?: Path | AbsPath; env?: Record<string,string>;      // merged over the scrubbed base environment
  pty?: { cols: number; rows: number }; stdin?: boolean;  // pty => single combined stream through a PTY
  restart?: "never" | "on-failure" | "always"; backoff_ms?: number[]; tags?: string[]; group?: string;
} -> { proc: ProcId; pid: number }
proc.stop     { proc; signal?: "INT"|"TERM"|"KILL"; grace_ms?: number }   -> {}     // default TERM, then KILL after grace_ms (5000); whole process group
proc.restart  { proc }  -> { pid: number }
proc.signal   { proc; signal: string } -> {}
proc.list     { tags?: string[] } -> { procs: ProcInfo[] }
proc.write    { proc; data?: string; data_b64?: string } -> { written: number }
proc.resize   { proc; cols: number; rows: number } -> {}
proc.attach_pty { proc } -> { cols: number; rows: number; fds: [{ index: 0; kind: "pty_master" }]; replay_b64?: string }
proc.output.tail { proc; bytes?: number } -> { data_b64: string }          // last <= 256 KiB
```
- **fd passing:** on a Unix socket the response line is sent with `sendmsg` and an `SCM_RIGHTS` control message holding the fds listed in `fds[].index` order. The receiver reads with `recvmsg`; fds arrive with the first byte of that line. The client now owns the PTY master (dup'd by the kernel; reads/writes directly). Over WebSocket, `proc.attach_pty` returns `-32005` (`capability: "fd_passing"`); use the events below.
- Non-PTY processes: output is delivered as `proc.output` events only for subscribed clients. PTY processes emit **no** `proc.output` events unless `[proc].pty_events = true`; then `proc.pty` events carry `{proc, data_b64}`.
- Environment is scrubbed to: `HOME, USER, LOGNAME, PATH, LANG, LC_*, TERM (xterm-256color for PTY), SHELL, DISPLAY, WAYLAND_DISPLAY, XDG_RUNTIME_DIR, XDG_*` plus `[env]` from config plus request `env`.

## A1.8 Module namespace
```ts
interface ModuleInfo { name: string; kind: "builtin"|"process"; state: "unavailable"|"registered"|"starting"|"ready"|"degraded"|"stopping"|"failed";
  version?: string; pid?: number; rss_kb?: number; uptime_ms?: number; requires: string[]; provides: string[]; lazy_only: boolean; always: boolean; restarts: number; last_error?: string }
module.list    {} -> { modules: ModuleInfo[]; profile: string }
module.load    { names: string[]; wait?: boolean /* default true */; timeout_ms?: number } -> { results: { name: string; state: string; error?: string }[] }
module.unload  { names: string[]; force?: boolean } -> { results: { name: string; state: string; error?: string }[] }   // refuses if another loaded module requires it, unless force (which unloads dependents first)
module.reload  { name: string } -> { state: string }
module.stats   { name?: string } -> { stats: { name: string; rss_kb: number; cpu_ms: number; queue: number; calls: number; errors: number }[] }
module.profile.get {} -> { profile: string; modules: string[]; available: string[] }
module.profile.set { profile: string; apply?: "now" | "next" } -> { loaded: string[]; unloaded: string[] }      // 'now': load profile's eager modules; never unloads lazily-started ones
module.always  { name: string; enabled: boolean } -> { file: AbsPath }                               // persists to pipist.local.toml [startup].autoload
```
Method-triggered activation: when a request's method matches a cold module's `provides.methods`, the kernel loads it (A1.9 flow), queues the call, and forwards it when ready. `module.load` of an unknown name → `-32002`.

## A1.9 Kernel ↔ process-module protocol (socketpair fd 3)
Same envelope. The module connects by being spawned; it MUST send `mod.ready` within `start_timeout_ms`.
```ts
// module -> kernel
mod.ready        { name: string; version: string; protocol: "1"; provides: string[] /* method globs */; events?: string[] }   (request)  -> { }
// kernel -> module
mod.init         { config: object /* the module's [config].section table */; project: { root: AbsPath; name: string }; paths: { state_dir: AbsPath /* .pipist/<module>/ */; runtime_dir: AbsPath }; protocol: "1" } -> { }
mod.shutdown     { grace_ms: number } -> { }          // module flushes and exits 0; kernel SIGTERM after grace, SIGKILL after 2x
mod.health       {} -> { ok: boolean; detail?: string }
mod.stats        {} -> { rss_kb: number; cpu_ms: number; queue: number }
mod.config.changed { section: string; value: object }   (notification)
// module -> kernel (request unless noted)
bus.publish      { topic: string; data: object }   (notification allowed)
kernel.call      { method: string; params?: object; timeout_ms?: number } -> <proxied result or error>   // routes to another module/builtin/provider; the kernel loads the target if cold
log.write        { level; message; channel?; fields?; tick?; instance? }   (notification allowed)
blob.put / blob.get / blob.put_path  -- same as A1.10
```
Routing: client request → kernel router → module (JSON-RPC forwarded with a fresh `k:<n>` id, original `_meta` preserved). A module that exits while handling calls → each pending client request gets `-32011`. Restart policy and backoff follow the manifest (spec 3A.3); after `max_restarts` the state is `failed` and calls return `-32010`.

## A1.10 Log, blob and bus namespaces
```ts
type Level = "trace"|"debug"|"info"|"warn"|"error";
interface LogRecord { seq: number; ts: number; level: Level; source: string /* "kernel" | module | "proc:<id>" | "game:<instance>" */; channel?: string; message: string; fields?: object; tick?: Tick; instance?: InstanceId; link?: { file: Path; line: number; col?: number } }
log.write   { level: Level; message: string; source?: string; channel?: string; fields?: object; tick?: Tick; instance?: InstanceId } -> {}        // also accepted as a notification
log.query   { filter?: { levels?: Level[]; sources?: string[]; channels?: string[]; text?: string; regex?: string; tick_from?: Tick; tick_to?: Tick; since_ts?: number; instance?: InstanceId };
              order?: "asc"|"desc"; limit?; cursor? } -> Page<LogRecord>          // kernel ring (20 000) or, if module `logdb` is loaded, SQLite
log.clear   {} -> { removed: number }
log.levels.set { source?: string; level: Level } -> {}                           // minimum level kept per source ("*" default)
blob.put      { data_b64: string; mime?: string } -> BlobRef                      // <= 8 MiB; hash = sha256 of bytes
blob.put_path { path: AbsPath; mime?: string; move?: boolean } -> BlobRef         // local only (unix socket); kernel hardlinks or copies into .pipist/blobs/xx/yy/<hash>
blob.get      { blob: Hash; offset?: number; length?: number } -> { data_b64: string; eof: boolean }   // <= 1 MiB per call
blob.path     { blob: Hash } -> { path: AbsPath }                                 // local only
blob.stat     { blob: Hash } -> { size: number; mime?: string; exists: boolean }
blob.gc       { keep?: Hash[] } -> { removed: number; bytes: number }
bus.history   { topics: string[]; since_seq?: number; limit?: number } -> { events: Event[]; oldest_seq: number }
bus.stats     {} -> { seq: number; ring: number; clients: number; dropped: number }
```
Blobs are immutable and content-addressed; referenced snapshots keep their blobs alive (`blob.gc` never removes referenced ones; `timeline` registers references through `blob.ref { blob, owner }` / `blob.unref`, request, module-only).

## A1.11 Target namespace (`target.*`)
```ts
interface TargetInfo { name: string; kind: "game"|"build"|"test"|"tool"; description?: string; host?: string; entry?: Path; command?: string[]; depends?: string[] }
target.list   {} -> { targets: TargetInfo[] }
target.run    { name: string; args?: string[]; env?: Record<string,string>; wait?: boolean; timeout_ms?: number } -> { run_id: Id; proc?: ProcId } | { run_id: Id; exit_code: number; duration_ms: number; problems: number }   // second form when wait=true
target.stop   { run_id: Id } -> {}
target.status { run_id?: Id } -> { runs: { run_id: Id; name: string; state: "running"|"finished"|"failed"|"stopped"; exit_code?: number; started: number; ended?: number; problems: number }[] }
```
`kind="game"` targets launch a host/runtime that later registers (`game.hello`, A2); use `game.start` (A2) to wait for the registered instance. `depends` targets (e.g. a build) run first; failure aborts. Output of build/test targets is parsed by the configured `problem_matcher`; each match is a `target.problem` event.

## A1.12 Core event topics (data schemas)
| Topic | `data` |
|---|---|
| `file.changed` / `file.created` / `file.deleted` | `{ path: Path; hash?: Hash; size?: number }` |
| `file.renamed` | `{ from: Path; to: Path }` |
| `config.changed` | `{ layers: string[]; keys: string[] }` |
| `proc.started` | `{ proc: ProcId; pid: number; cmd: string[]; tags: string[] }` |
| `proc.exited` | `{ proc; exit_code?: number; signal?: string; duration_ms: number }` |
| `proc.crashed` | `{ proc; exit_code?: number; signal?: string; will_restart: boolean; restarts: number }` |
| `proc.output` | `{ proc; stream: "stdout"\|"stderr"; text: string }` (lossy UTF-8; batched ≤ 50 ms) |
| `proc.pty` | `{ proc; data_b64: string }` (only if `[proc].pty_events`) |
| `target.started` | `{ run_id; name; proc?: ProcId }` |
| `target.finished` | `{ run_id; name; exit_code: number; duration_ms: number; problems: number }` |
| `target.problem` | `{ run_id; file?: Path; range?: Range; severity: Severity; message: string; matcher: string }` |
| `module.loading` | `{ name }` |
| `module.state` | `{ name; state: string; reason?: string; pid?: number }` |
| `log.record` | `LogRecord` (only subscribers; high volume, batch-friendly) |
| `bus.dropped` | `{ count: number; first_seq: number; last_seq: number }` |

## A1.13 Security and limits
- Unix socket directory `$XDG_RUNTIME_DIR/pipist/` mode 0700; socket mode 0600; the kernel checks `SO_PEERCRED` uid == own uid, else closes with `-32001`.
- WebSocket listens on `127.0.0.1` only (`[net].ws_port`, default random, written to `$XDG_RUNTIME_DIR/pipist/<hash>.ws`); requires `session.hello` `token` equal to the contents of `<hash>.token` (mode 0600, 32 random bytes hex, regenerated per daemon start) AND, if an `Origin` header exists, it must be `http://127.0.0.1:<port>` or `http://localhost:<port>` of the game server. The injected browser agent receives its token inline from the host server.
- Kernel rate limits: ≤ 2000 requests/s per connection (excess → `-32009`).
- No method executes arbitrary shell except `proc.start`/`target.run` (the GUI/CLI user's own privileges); WebSocket sessions are granted only the `agent` method set: `session.*`, `game.*`, `log.write`, `timeline.snapshot.put`, `tweak.register`, `scene.*`, `blob.put`, `viewport.*`.

## A1.14 Wire examples (one per family; complete set in `tests/protocol/examples/`)
```json
{"jsonrpc":"2.0","id":1,"method":"session.hello","params":{"client":{"name":"pipist-cli","version":"0.1.0","kind":"cli"},"protocol":"1"}}
{"jsonrpc":"2.0","id":1,"result":{"server":{"name":"pipistd","version":"0.1.0","protocol":"1"},"session_id":"c_01","project":{"name":"los-ciegos","root":"/home/u/los-ciegos","config_hash":"sha256:aa…","revision":"sha256:bb…"},"profile":"min","capabilities":["fd_passing","blob.put_path"],"limits":{"max_message_bytes":16777216,"max_inline_state_bytes":262144,"client_queue_events":4096,"idle_timeout_s":0},"clock":{"now_ms":1793574000000}}}
{"jsonrpc":"2.0","id":2,"method":"session.subscribe","params":{"topics":["file.*","module.state"]}}
{"jsonrpc":"2.0","id":2,"result":{"subscription":1,"current_seq":57}}
{"jsonrpc":"2.0","method":"event","params":{"topic":"module.state","seq":58,"ts":1793574000500,"data":{"name":"index","state":"starting"}}}
{"jsonrpc":"2.0","id":3,"method":"search.text","params":{"query":"dress code","limit":5}}
{"jsonrpc":"2.0","id":3,"error":{"code":-32010,"message":"module index failed to start","data":{"kind":"module_unavailable","name":"index","reason":"exec not found: pipist-mod-index"}}}
{"jsonrpc":"2.0","id":4,"method":"proc.attach_pty","params":{"proc":"p3"}}
{"jsonrpc":"2.0","id":4,"result":{"cols":120,"rows":40,"fds":[{"index":0,"kind":"pty_master"}]}}
```

<!-- SOURCE-END: pipist-spec-a1-protocol-core.md -->

---

<!-- SOURCE-BEGIN: pipist-spec-a2-protocol-domain.md -->

# PIPIST SPEC — Appendix A2: Protocol, domain namespaces and event catalogue

> **v1.3:** the protocol additions of Appendix C1.12 (timeline storage) are merged into this appendix; C1.12 and B1.13 remain as change lists only. Appendix D adds no protocol methods (the GUI uses the `gui.*` namespace of A2.14 and existing methods).

Continues Appendix A1 (read it first for envelope, errors, common types, Pipist Value encoding, pagination and `_meta`). Same conventions. Routing: requests to `game.*`, `runtime.*`, `scene.*`, `asset.*`, `tweak.*` (host side) and `viewport.*` that name an `instance` are forwarded by the kernel to the connection that registered that instance.

## A2.1 Instance selection
Most game-related methods accept `instance?: InstanceId`. Resolution: given → that instance (`-32002` if unknown); omitted and exactly one instance registered → it; omitted and several → the kernel's *current instance* if one was set with `game.select`, else error `-32012` with `candidates`. The kernel strips `instance` before forwarding to the host.

## A2.2 Game namespace
### Registration (host/runtime → kernel)
```ts
type HostKind = "web" | "browser" | "native" | "other";   // web = pipist-host-web (headless QuickJS), browser = browser agent
type GameCap = "snapshot" | "restore" | "state.get" | "state.set" | "input" | "output" | "eval" | "buttons" | "quiesce" | "pause" | "step" | "speed"
             | "hotpatch" | "trace" | "viewport" | "scene" | "tweak" | "screen" | "reload";
game.hello {                      // request; the connection must already have done session.hello with kind "host" or "runtime"
  name: string; kind: HostKind; engine?: string; pid?: number; target?: string; run_id?: Id;
  caps: (GameCap | `runtime.${string}`)[];                               // runtime.* names list pass-through methods this runtime implements
  meta: { tick_unit: "input" | "call" | "event" | "frame" | "interval" | "step"; input_kinds?: ("line"|"key"|"button"|"click"|"pointer"|"wheel"|"text")[]; version?: string; determinism?: { rng: boolean; clock: boolean }; screen?: { cols: number; rows: number } };   // "command" is accepted as an alias of "input"
} -> { instance: InstanceId; snapshot: { enabled: boolean; every_ticks: number; keep_full: number }; branch: BranchId }
game.bye { reason?: string } -> {}                                       // clean deregistration (also implied by disconnect)
game.select { instance: InstanceId } -> {}                               // sets the kernel's current instance
game.list {} -> { instances: { instance; name; kind: HostKind; target?: string; state: "starting"|"ready"|"paused"|"running"|"restoring"|"exited"|"crashed"; tick: Tick; branch: BranchId; caps: string[]; pid?: number; viewport?: Id }[]; current?: InstanceId }
```
### Control (client → kernel → host)
```ts
game.start   { target: string; options?: { mode?: "realtime"|"fast"|"stepped"; seed?: number; speed?: number; args?: string[]; env?: Record<string,string>; restore?: SnapshotId; branch?: BranchId; profile?: string }; wait?: boolean; timeout_ms?: number }
             -> { run_id: Id; instance?: InstanceId }                    // instance present when wait=true (default true, timeout default 15000 -> -32006)
game.stop    { instance?; grace_ms?: number } -> {}
game.reload  { instance?; mode?: "auto"|"patch"|"restore"|"restart" } -> { tier: "T1"|"T2"|"T3"|"T4"|"T5"; patch_id?: Id; restored?: SnapshotId }   // 'auto' lets the patch module choose (A2.6)
game.pause   { instance? } -> { tick: Tick }         game.resume { instance? } -> { tick: Tick }
game.step    { instance?; n?: number /* default 1 */ } -> { tick: Tick }
game.speed   { instance?; factor: number /* 0.1..16 or 0 for 'fast' */ } -> {}
game.quiesce { instance?; timeout_ms?: number } -> { tick: Tick; waited_ms: number; pending: number }    // waits until no pending timers/async; pending>0 on timeout
game.input   { instance?; event: GameInput } -> { accepted: boolean; tick: Tick }
type GameInput = { kind: "line"; text: string }                                   // needs a text prompt (Appendix B1.4), else -32005 {capability:"text_prompt"}
              | { kind: "text"; text: string }                                    // type characters into the focused element
              | { kind: "key"; key: string; code?: string; mods?: string[]; down?: boolean; hold_frames?: number; hold_ms?: number }
              | { kind: "button"; id: string }                                    // full click sequence on a game.buttons entry
              | { kind: "click"; selector?: string; x?: number; y?: number; button?: 0|1|2; double?: boolean }   // x,y on the pointer target (largest canvas, else body)
              | { kind: "pointer"; type: "move"|"down"|"up"; x: number; y: number; button?: 0|1|2 }
              | { kind: "wheel"; dx: number; dy: number; x?: number; y?: number };
game.buttons { instance? } -> { buttons: { id: string; label: string; kind?: "button"|"link"|"clickable"; group?: string; enabled: boolean }[] }   // visible clickable elements (B1.4)
game.state.get   { instance?; path?: StatePath; depth?: number /* default 3, max 16 */; snapshot?: SnapshotId; max_bytes?: number /* default 65536 */ } -> { value: Value; truncated: boolean }
game.state.set   { instance?; path: StatePath; value: Value } -> { old: Value }                     // rejects functions; goes through adapter setState
game.state.watch { instance?; paths: StatePath[]; interval_ticks?: number } -> { watch: Id }          // emits game.state.changed; stops on game.state.unwatch / disconnect
game.state.unwatch { watch: Id } -> {}
game.output.tail { instance?; lines?: number /* default 200 */ } -> { lines: { tick: Tick; text: string; class?: string }[] }
game.screen.get  { instance? } -> { text?: string; cols?: number; rows?: number; image?: BlobRef }   // headless web host: rendered terminal screen (ANSI stripped) or summary; native/browser: PNG blob
game.eval        { instance?; code: string; lang?: "js"|"lua"|"python"; timeout_ms?: number } -> { value: Value; stdout?: string; error?: { message: string; stack?: string } }
```
### Host → kernel notifications and requests
```ts
game.tick   (notification) { instance; tick: Tick; t_ms: number /* game clock */ }                    // rate-limited to <= 30/s to subscribers; every tick still snapshots per policy
game.output (notification) { instance; tick: Tick; text: string; ansi?: string; class?: string; append?: boolean }  // structured game output (log regions of web games, console of others)
game.state  (notification) { instance; state: "ready"|"paused"|"running"|"restoring"|"exited"; reason?: string }
game.crash  (notification) { instance; message: string; stack?: string }
game.screen (notification) { instance; tick: Tick; region: string; kind: "status"|"buttons"|"prompt"|"summary"; text: string; ansi?: string; buttons?: { id: string; label: string; enabled: boolean }[] }   // in-place regions
// timeline puts (host -> kernel); the kernel forwards to the timeline module (loaded on demand)
timeline.snapshot.put { instance; tick: Tick; state: Value | BlobRef; quiescent: boolean; base?: SnapshotId; unchanged?: string[]; format?: string; format_args?: object; reason?: "policy"|"request"|"before_patch"|"bookmark"|"studio"|"experiment"; thumb?: BlobRef; label?: string; shape_hash?: string; screen?: { text: string } } -> { accepted: boolean; reason?: "quota"|"too_early"; snapshot?: SnapshotId; branch?: BranchId }
                      // base/unchanged = delta snapshot: `unchanged` lists StatePath prefixes (binding or binding.key) whose value equals the base snapshot's; `timeline` reconstructs full state on timeline.get. `state` is usually a BlobRef made with blob.put_path. `format_args` is `{page_kib}` for the `pages/1` chunker; `thumb` is a PNG of at most 64 KiB; `snapshot` and `branch` are present only when `accepted` (C1.12, merged in v1.3).
```
### Kernel → host requests (what an adapter/host MUST implement for the caps it advertises)
| Method | Params | Result | Cap |
|---|---|---|---|
| `game.snapshot` | `{ reason: "policy"\|"request"\|"before_patch" }` | `{ tick: Tick; state: Value \| BlobRef; quiescent: boolean; shape_hash?: string }` | snapshot |
| `game.restore` | `{ state: Value \| BlobRef; tick: Tick; snapshot: SnapshotId; mode?: "reboot" \| "in-place"; cancel_timers: true; redraw: true }` | `{ tick: Tick; rebooted?: boolean; shape_diff?: { added: StatePath[]; removed: StatePath[]; type_changed: StatePath[] }; migrated?: boolean }` | restore |
| `game.apply_patch` | `{ patch_id: Id; tier: "T1"\|"T2"\|"T3"; items: { path: Path; kind: "function"\|"data"\|"module"; name?: string; text: string; range?: Range }[]; at: "quiescent" }` | `{ applied: { path: Path; name?: string }[]; failed?: { path: Path; name?: string; message: string }[] }` | hotpatch |
| `game.reload_code` | `{ mode: "reload"\|"restart" }` | `{ ok: true }` (host re-executes scripts; the kernel then sends `game.restore`) | reload |
| plus all of `game.pause/resume/step/speed/quiesce/input/buttons/state.get/state.set/output.tail/screen.get/eval` | as above (without `instance`) | as above | per cap |
Rules: `game.restore` MUST cancel pending timers/promises owned by the game, redraw the screen from restored state (hosts that captured scrollback restore it too), and only then return. A host that cannot comply returns `-32016 rejected` with `reason`. Hosts decide quiescence: `game.snapshot` with `quiescent:false` is stored but flagged and excluded from fork targets unless `allow_non_quiescent`.

## A2.3 Runtime pass-through
`runtime.<method>`: params `{ instance?: InstanceId; ...method params }` → forwarded verbatim (minus `instance`) to the runtime; result/error forwarded verbatim. Allowed names are those listed in the runtime's `game.hello.caps` as `runtime.<name>`; others → `-32005`. Names reserved by the FPS design: `runtime.pause`, `runtime.resume`, `runtime.reload_scene`, `runtime.reload_asset {path}`, `runtime.set_variable {name, value}`, `runtime.get_entity {id}`, `runtime.spawn_entity {def, transform?}`, `runtime.teleport_player {pos, rot?}`, `runtime.physics_inspect {id?}`. Their result shapes are defined by the runtime and documented in the runtime's own docs; Pipist only guarantees transport.

## A2.4 Viewport control (kernel side; frames use the binary side channel, spec 13A)
```ts
viewport.offer  { instance; id: Id; socket: AbsPath; caps: { formats: ("bgra8")[]; dmabuf: boolean; modes: string[]; input: ("kbd"|"mouse"|"gamepad")[]; camera: boolean } } -> {}
viewport.list   {} -> { viewports: { id; instance; socket: AbsPath; caps: object; clients: number }[] }
viewport.attach { id } -> { socket: AbsPath; side_protocol: 1; caps: object }
viewport.detach { id } -> {}
viewport.modes  { instance? } -> { modes: { id: string; label: string }[]; current: string }          // forwarded to runtime
viewport.set_mode { instance?; mode: string } -> {}
viewport.camera { instance?; set?: { pos: [number,number,number]; rot: [number,number,number]; fov?: number }; get?: boolean } -> { pos; rot; fov }
```

## A2.5 Timeline namespace (module `timeline`)
```ts
interface SnapshotMeta { id: SnapshotId; branch: BranchId; tick: Tick; parent?: SnapshotId; ts: number; source_revision: Hash; host: string; instance: InstanceId; bytes: number; stored_bytes: number;
                         quiescent: boolean; shape_hash?: string; label?: string; bookmarks: string[]; pinned: boolean;
                         format: string; reasons: string[] /* protection reasons */; damaged: boolean; has_thumb: boolean; new_bytes: number }
interface BranchInfo   { id: BranchId; parent?: { branch: BranchId; snapshot: SnapshotId; tick: Tick }; head_tick: Tick; head_snapshot: SnapshotId; created: number; label?: string; source_revisions: Hash[]; flags: ("shape-mismatch"|"studio-play"|"experiment")[]; run: number; parent_missing: boolean; snapshot_count: number; archived: boolean }
timeline.list      { branch?: BranchId; from?: Tick; to?: Tick; bookmarks_only?: boolean; limit?; cursor? } -> Page<SnapshotMeta>
timeline.branches  {} -> { branches: BranchInfo[]; current: BranchId }
timeline.get       { snapshot?: SnapshotId; branch?: BranchId; tick?: Tick; include?: "meta"|"state" } -> { meta: SnapshotMeta; state?: Value | BlobRef }   // tick+branch resolves to the nearest snapshot at or before tick
timeline.goto      { target: SnapshotId | { branch?: BranchId; tick: Tick }; instance?; fork?: boolean /* default true */; reload?: "none"|"auto"|"patch"|"restore"|"restart" /* default "auto" */; allow_non_quiescent?: boolean }
                   -> { branch: BranchId; snapshot: SnapshotId; tick: Tick; tier?: "T1"|"T2"|"T3"|"T4"|"T5"; shape_diff?: object; patch_id?: Id }
timeline.bookmark  { snapshot?: SnapshotId; tick?: Tick; name: string; note?: string } -> { snapshot: SnapshotId }
timeline.bookmarks { } -> { bookmarks: { name: string; snapshot: SnapshotId; tick: Tick; branch: BranchId; note?: string }[] }
timeline.unbookmark{ name: string } -> {}
timeline.pin       { snapshot: SnapshotId; pinned: boolean } -> {}
timeline.diff      { a: SnapshotId; b: SnapshotId; path?: StatePath; depth?: number; limit?: number } -> { changes: { path: StatePath; op: "add"|"remove"|"change"; a?: Value; b?: Value }[]; truncated: boolean }
timeline.prune     { policy?: { keep_full?: number; thin_every?: number; quota_mb?: number }; ids?: SnapshotId[]; branch?: BranchId; dry_run?: boolean; force?: boolean } -> { removed: number; bytes_freed: number; would_remove?: SnapshotId[] }   // -32009 busy, data.reason in fork_root|protected|disk_full|quota, data.protected: {id, reasons[]}[]
timeline.stats     {} -> { snapshots: number; branches: number; bytes: number; stored_bytes: number; quota_bytes: number; dedupe_ratio: number;
                            dropped: number; dead_bytes: number; usage_bytes: number; effective_quota_bytes: number; level: 0|1|2|3|4; packs: number; persist: string; dir: AbsPath }
timeline.branch.label { branch; label: string } -> {}     timeline.branch.archive { branch; archived: boolean } -> {}
timeline.branch.delete { branch: BranchId; cascade?: boolean; dry_run?: boolean; confirm?: boolean } -> { removed: number; bytes_freed: number; kept_fork_roots: SnapshotId[] }
timeline.fsck      { deep?: boolean; repair?: boolean } -> { snapshots: number; chunks: number; bad_chunks: number; damaged_snapshots: SnapshotId[]; repaired: boolean }
timeline.compact   {} -> { packs: number; bytes_freed: number }
timeline.reset     { confirm: true } -> {}
// source capture (C1.9): the project source as it was at a snapshot's revision
timeline.source.list { snapshot: SnapshotId } -> { revision: Hash; files: { path: Path; size: number }[] }
timeline.source.read { snapshot: SnapshotId; path: Path } -> { text: string }                       // <= 4 MiB else -32008
timeline.source.diff { a: SnapshotId; b: SnapshotId | "working"; path?: Path } -> { diff: string; files_changed: number }
```
`timeline.goto` semantics (spec 9.3): resolve snapshot S → (if `reload` not `none`) ask `patch` for the tier appropriate for pending source changes → ensure the target instance exists (start it if `restore` requires, using the branch's target) → `game.restore` → create branch B′ from S when `fork` (otherwise move head only if S is on the current branch and is its head's ancestor — else `-32004`). Events: `timeline.branch`, `timeline.snapshot`, `game.state restoring→running`.
Storage behaviour (chunking, packs, thinning, quota, protection, persistence modes, recovery) is specified exactly in Appendix C1; the shapes above are the wire contract for it. Warning codes added by C1: `W_SNAP_TOO_LARGE`, `W_SOURCE_TOO_LARGE` (in `data.detail.code` or events).

## A2.6 Patch namespace (module `patch`)
```ts
interface PatchItem { path: Path; kind: "function-body"|"function-added"|"function-removed"|"data-literal"|"declaration-added"|"declaration-removed"|"side-effect"|"signature"|"class-shape"|"unparseable"|"other";
                      name?: string; range: Range; tier: "T1"|"T2"|"T3"|"T4"|"T5"; reason: string }
interface PatchPlan { tier: "T1"|"T2"|"T3"|"T4"|"T5"; items: PatchItem[]; warnings: { code: string; message: string; path?: Path; range?: Range }[] }   // overall tier = max tier over items
patch.preview { paths?: Path[]; text?: { path: Path; content: string }; instance? } -> { plan: PatchPlan; diff: string /* unified diff vs. the code currently loaded in the instance */ }
patch.apply   { paths?: Path[]; tier?: "auto"|"T1"|"T2"|"T3"|"T4"|"T5"; instance?; dry_run?: boolean } -> { patch_id: Id; tier: string; applied: { path: Path; name?: string }[]; fellback?: { from: string; reason: string }; restored?: SnapshotId }
                                                                                                          // failure -> -32015 {tier, diagnostics:[{path,message,range?}]}
patch.history { instance?; limit?; cursor? } -> Page<{ patch_id: Id; ts: number; tier: string; paths: Path[]; result: "applied"|"failed"|"fellback"|"reverted"; instance: InstanceId; source_revision: Hash }>
patch.revert  { patch_id: Id } -> { patch_id: Id /* the revert patch */ }
patch.status  {} -> { auto: boolean; pending: Path[]; last?: Id; held_for_quiescence: boolean }
patch.auto    { enabled: boolean } -> {}                                                                  // persisted via config [patch].auto
```
Lint warnings emitted in `plan.warnings` include `anchor-hazard` (edit range ends on an `if (...) {` opener). `auto` mode: on `file.changed` for tracked sources while an instance is running, the module computes a plan; T1/T2 are applied at the next quiescent point; T3+ are *held* (`patch.pending` event) until `patch.apply` or `game.reload` unless `[patch].auto_restore = true`.

## A2.7 Trace namespace (module `trace`)
```ts
interface TraceTick { tick: Tick; functions: { id: number; name: string; file: Path; range: Range; calls: number }[];
                      strings: { text: string; file: Path; range: Range; in?: string }[]; entities: { type: string; key: string; file: Path; range: Range }[] }
trace.start { instance?; mode?: "functions"|"provenance"|"both"; window_ticks?: number /* default 200 */ } -> { instrumented_files: number }     // reloads scripts instrumented (T4-like); restores state
trace.stop  { instance? } -> {}
trace.now   { instance? } -> TraceTick
trace.back  { instance?; n: number } -> { ticks: TraceTick[] }
trace.who_wrote { instance?; path: StatePath; limit?: number } -> { writes: { tick: Tick; function?: string; file?: Path; range?: Range; old?: Value; new: Value }[] }
```

## A2.8 Experiments namespace (module `experiments`)
```ts
interface ExperimentSummary { name: string; file: Path; description?: string; variants: number }
exp.list    {} -> { experiments: ExperimentSummary[] }
exp.run     { name?: string; inline?: object /* same structure as experiments/*.toml */; jobs?: number; seed?: number; keep_transcripts?: boolean } -> { run_id: Id; variants: number }
exp.status  { run_id } -> { state: "queued"|"running"|"done"|"cancelled"|"failed"; done: number; total: number; failed: number; started: number; ended?: number; eta_ms?: number }
exp.cancel  { run_id } -> {}
exp.results { run_id; limit?; cursor?; filter?: { failed?: boolean } } -> { columns: string[]; rows: { variant: Record<string, Value>; seed: number; collected: Record<string, Value>; asserts: { expr: string; ok: boolean }[]; transcript?: Path; error?: string }[]; next_cursor?: string; report: Path }
exp.golden.record { name: string; instance?: InstanceId; from_tick?: Tick } -> { file: Path; ticks: number; hash: Hash }
exp.verify_adapter { script: Path | string[]; stride?: number; seed?: number; instance?: InstanceId } -> { ok: boolean; checked: number; first_divergence?: { from_tick: number; tick: number; kind: "state"|"transcript"; paths?: string[]; expected?: string; actual?: string } }   // restore-fidelity test (B1.12)
exp.check   { name?: string } -> { results: { name: string; ok: boolean; first_divergence?: { tick: Tick; expected: string; actual: string } }[] }
```
Runs execute in headless host processes spawned by the module through `target.run`/`proc.start`; they register as instances flagged `experiment` and are hidden from `game.list` unless `include_experiments`.

## A2.9 Search / index namespace (module `index`)
```ts
type SymbolKind = "function"|"method"|"class"|"variable"|"constant"|"table"|"key"|"macro"|"type"|"enum"|"module"|"other";
interface Hit { file: Path; range: Range }
search.text     { query: string; regex?: boolean; case?: "smart"|"sensitive"|"insensitive"; globs?: string[]; limit?; context?: number } -> { hits: (Hit & { line_text: string; before?: string[]; after?: string[] })[]; truncated: boolean }
search.symbols  { query: string; kinds?: SymbolKind[]; limit? } -> { symbols: { name: string; kind: SymbolKind; file: Path; range: Range; parent?: string; signature?: string; score: number }[] }
search.strings  { text: string; exact?: boolean; limit? } -> { hits: (Hit & { text: string; in?: string })[] }
search.entities { query: string; type?: string; limit? } -> { entities: { type: string; key: string; file: Path; range: Range; refs: number }[] }
search.outline  { file: Path } -> { symbols: OutlineNode[] }     // OutlineNode { name; kind: SymbolKind; range: Range; children: OutlineNode[] }
search.refs     { symbol?: string; file?: Path; pos?: Pos; limit? } -> { refs: (Hit & { kind: "def"|"ref"|"call"; approximate: boolean })[] }
search.where    { query: string; kinds?: ("function"|"string"|"entity"|"text"|"file")[]; limit? } -> { hits: { kind: string; score: number; name?: string; text?: string; type?: string; key?: string; file: Path; range: Range; in?: string }[] }
index.status    {} -> { state: "idle"|"indexing"; files: number; symbols: number; strings: number; entities: number; last_ms: number; languages: string[] }
index.reindex   { paths?: Path[] } -> { queued: number }
index.transform { path: Path; mode?: ("registry")[]; script_index?: number } -> { kind: "script"|"html"; blocks: { index: number; src?: Path; start: Pos; end: Pos; text: string }[]; cached: boolean }   // B1.2: original source + appended binding-registry statement; html => one block per inline script plus the src scripts in document order
index.spans     { file: Path; range?: Range } -> { spans: { range: Range; kind: string }[] }        // syntax-highlight spans for CodeView; kind = tree-sitter capture name
```

## A2.10 Diagnostics namespace (module `diag`)
```ts
interface Diagnostic { id: Id; file: Path; range: Range; severity: Severity; source: "syntax"|"engine"|"lsp:<server>"|"lint:<rule>"|"build:<matcher>"|"schema"|"keymap"; code?: string; message: string; fixes?: { title: string; edits: TextEdit[] }[] }
diag.list { file?: Path; severity?: Severity; source?: string; limit?; cursor? } -> Page<Diagnostic>
diag.run  { checks?: ("syntax"|"engine"|"lsp"|"lint"|"schema")[]; files?: Path[] } -> { run_id: Id }          // results arrive as diag.updated events
diag.fix  { id: Id; fix?: number /* index, default 0 */; apply?: boolean } -> { edits: TextEdit[]; applied?: boolean }   // apply=true sends edits through editor.apply
```
`diag.updated` always carries the **complete** current list for one `(file, source)` pair (replace semantics).

## A2.11 Editor namespace (builtin `editor`)
```ts
editor.start   { files?: Path[]; cwd?: Path; args?: string[] } -> { proc: ProcId; socket: AbsPath }         // spawns `nvim --listen <socket>` in a PTY via proc.start (command from [editor].command)
editor.attach  { socket?: AbsPath; proc?: ProcId } -> { connected: true; nvim_version: string }
editor.detach  {} -> {}
editor.open    { file: Path; line?: number; col?: number; mode?: "edit"|"split"|"vsplit"|"tab" } -> {}
editor.goto    { file: Path; line: number; col?: number } -> {}
editor.current { } -> { file?: Path; line: number; col: number; mode: string /* nvim mode, e.g. "n" */; modified: boolean }
editor.buffers { } -> { buffers: { id: number; file?: Path; modified: boolean; tab?: number; loaded: boolean }[]; tabs: number[]; current_tab: number }
editor.command { ex: string } -> { output: string }
editor.save    { file?: Path } -> { saved: Path[] }
editor.apply   { edits: TextEdit[]; save?: boolean } -> { via: "buffer"|"disk"; saved: Path[]; unsaved: Path[] }   // buffer-aware (spec 13B.4): open+clean buffer -> nvim_buf_set_text then write; open+dirty -> buffer only (unsaved); closed -> atomic disk write
```
If no nvim is attached: `editor.open/goto/current/...` → `-32004 invalid_state {state:"no_editor"}` except `editor.apply` (disk path) and `editor.start`.

## A2.12 Studio, scene, asset, schema, tweak
```ts
interface Transform { pos?: [number,number,number]; rot?: [number,number,number] /* euler degrees */; scale?: [number,number,number] }
interface SceneNode { id: Id; parent?: Id; name: string; kind: string; children?: Id[]; flags?: ("hidden"|"locked"|"selected"|"prefab-instance"|"generated")[]; transform?: Transform; source?: { file: Path; path?: string; range?: Range } }
// implemented by the runtime (or by `studio` for file-backed scenes); all take instance?
scene.tree      { root?: Id; depth?: number } -> { nodes: SceneNode[]; version: number }
scene.get       { id: Id } -> { node: SceneNode; properties: Record<string, Value> }
scene.set       { id: Id; path: string; value: Value; preview?: boolean } -> { version: number }
scene.spawn     { prefab?: string; def?: string; parent?: Id; name?: string; transform?: Transform } -> { id: Id; version: number }
scene.delete    { ids: Id[] } -> { version: number }                 scene.duplicate { ids: Id[] } -> { ids: Id[]; version: number }
scene.reparent  { id: Id; parent?: Id; index?: number } -> { version: number }     scene.rename { id: Id; name: string } -> { version: number }
scene.select    { ids: Id[] } -> {}                                   scene.pick { x: number; y: number; mode?: "first"|"all" } -> { ids: Id[]; hit?: { point: [number,number,number]; normal: [number,number,number] } }
scene.bounds    { ids: Id[] } -> { boxes: { id: Id; min: [number,number,number]; max: [number,number,number] }[] }
scene.mode      { mode: "edit"|"play"|"paused" } -> {}                 scene.reload { file?: Path } -> { version: number }
asset.list      { kind?: string; dir?: Path; query?: string; limit?; cursor? } -> Page<{ path: Path; kind: string; size: number; thumb: boolean }>
asset.thumbnail { path: Path; size: number } -> BlobRef
// schemas (module studio)
interface SchemaField { type: "bool"|"int"|"float"|"string"|"text"|"enum"|"flags"|"vec2"|"vec3"|"vec4"|"euler"|"quat"|"color"|"angle"|"asset"|"ref"|"list"|"map"|"struct";
  min?: number; max?: number; step?: number; unit?: string; default?: Value; group?: string; order?: number; tooltip?: string; readonly?: boolean; required?: boolean; pattern?: string; deprecated?: boolean; hot?: boolean;
  values?: string[]; of?: string | SchemaField; kinds?: string[]; schema?: string; fields?: Record<string, SchemaField>; visible_if?: string }
interface SchemaDef { name: string; applies_to: string[]; root: string; title_field?: string; fields: Record<string, SchemaField>; source: Path }
schema.list     {} -> { schemas: { name: string; applies_to: string[]; source: Path }[] }
schema.get      { name: string } -> { schema: SchemaDef }
schema.for_file { file: Path } -> { schema?: string; root: string }
schema.validate { file: Path } -> { diagnostics: Diagnostic[] }
schema.infer    { files: Path[]; name?: string } -> { schema_text: string }
// studio data editing (module studio)
type EditOp = { op: "set"; path: string; value: Value } | { op: "insert"; path: string; key?: string; index?: number; value: Value } | { op: "remove"; path: string }
            | { op: "append_table"; path: string; text: string } | { op: "rename_key"; path: string; to: string } | { op: "move"; path: string; to: string; index?: number };
studio.read   { file: Path; path?: string } -> { value: Value; range: Range; hash: Hash; literal: boolean }
studio.edit   { file: Path; expect_hash: Hash; ops: EditOp[]; label?: string } -> { hash: Hash; changed: Range[]; via: "disk"|"buffer"|"buffer_unsaved"; undo_id: Id }   // conflict -> -32003; failed re-parse check -> -32602 {kind:"edit_rejected"}
studio.undo   {} -> { undone?: { undo_id: Id; label?: string } }     studio.redo {} -> { redone?: { undo_id: Id; label?: string } }
studio.play   { from_camera?: boolean } -> { branch: BranchId; edit_state: SnapshotId }     studio.stop {} -> { restored: SnapshotId }
studio.changes{} -> { changes: { id: Id; entity?: Id; path: string; from: Value; to: Value; file?: Path }[] }        // diffs between play state and edit_state
studio.keep   { changes: Id[] } -> { written: { file: Path; hash: Hash }[] }
// tweaks
interface TweakInfo { path: string; type: "float"|"int"|"bool"|"vec3"|"color"|"enum"|"string"; value: Value; default: Value; min?: number; max?: number; step?: number; values?: string[]; group?: string; unit?: string; source?: { file: Path; range: Range }; changed: boolean }
tweak.register { instance; tweaks: Omit<TweakInfo,"changed">[] } -> {}                                  // host -> kernel
tweak.list     { instance?; group?: string } -> { tweaks: TweakInfo[] }
tweak.set      { instance?; path: string; value: Value; preview?: boolean } -> {}                       // forwarded to host as runtime.set_variable semantic
tweak.reset    { instance?; path: string } -> {}
tweak.commit   { instance?; path: string } -> { file: Path; range: Range; hash: Hash }                  // -32005 {capability:"literal_source"} if no literal source
tweak.preset.save {name} -> {file: Path}   tweak.preset.load {name} -> {applied: number}   tweak.preset.list {} -> {presets: string[]}
```

## A2.13 Declarative UI and DAP (M14, shapes frozen now)
```ts
type Widget = { t: "row"|"col"; children: Widget[]; gap?: number }
            | { t: "text"|"heading"; text: string; style?: "muted"|"error"|"ok" }
            | { t: "button"; id: string; label: string; enabled?: boolean }
            | { t: "input"; id: string; kind: "text"|"int"|"float"; value: string | number; hint?: string }
            | { t: "checkbox"; id: string; label: string; value: boolean }
            | { t: "select"; id: string; options: string[]; value: string }
            | { t: "table"; id: string; columns: string[]; rows: (string|number)[][]; selectable?: boolean }
            | { t: "tree"; id: string; nodes: { id: string; label: string; children?: any[] }[] }
            | { t: "plot"; id: string; series: { name: string; points: [number, number][] }[] }
            | { t: "progress"; value: number /* 0..1 */; label?: string } | { t: "separator" } | { t: "code"; text: string; lang?: string };
ui.panel.set   { id: string; title: string; root: Widget; dock?: "left"|"right"|"bottom"|"center" } -> {}      // module -> kernel -> GUI; limits: 10 000 widgets, 5 updates/s
ui.panel.patch { id: string; patches: { path: string /* JSON pointer into root */; value: any }[] } -> {}
ui.panel.close { id: string } -> {}
// event ui.event { panel: string; id: string; kind: "click"|"change"|"select"; value?: any }  -> delivered to the owning module as notification "ui.event"
dap.launch { target: string; adapter?: "lldb-dap"|"gdb"|"node"|"debugpy"; args?: object } -> { session: Id }
dap.attach { pid?: number; adapter?: string } -> { session: Id }
dap.breakpoints.set { file: Path; lines: { line: number; condition?: string }[] } -> { verified: { line: number; verified: boolean }[] }
dap.continue/next/step_in/step_out/pause { session } -> {}    dap.stack { session; thread?: number } -> { frames: { id: number; name: string; file?: Path; line?: number }[] }
dap.vars { session; frame: number } -> { scopes: { name: string; vars: { name: string; value: string; type?: string; ref?: number }[] }[] }    dap.eval { session; frame?: number; expr: string } -> { value: string }
```

## A2.14 GUI-served namespace (`gui.*`, provided by `pipist-gui` through `session.provide`)
If no GUI is connected, calls return `-32601`; `pipist gui ...` CLI subcommands start the GUI first when asked to (`--start`).
```ts
gui.action.list  {} -> { actions: { id: string; title: string; cmd?: string[]; keys: { mode: string; keys: string }[]; scope: string }[] }
gui.action.run   { id: string; args?: object } -> { ok: boolean; message?: string }
gui.cmdline      { text: string; run?: boolean } -> { output?: string; error?: string }        // run=false just opens the cmdline prefilled
gui.panel.list   {} -> { panels: { id: string; title: string; module?: string; open: boolean; window: number; focused: boolean }[]; windows: { id: number; title: string; main: boolean; rect: [number,number,number,number] }[] }
gui.panel.open   { id: string; window?: "main"|"new"|number; focus?: boolean } -> { window: number }
gui.panel.close  { id: string } -> {}      gui.panel.popout { id: string } -> { window: number }      gui.panel.dock { id: string } -> {}
gui.workspace.list {} -> { workspaces: string[]; current: string }      gui.workspace.set { name: string } -> {}      gui.workspace.save { name: string } -> {}
gui.focus        { panel: string } -> {}
gui.mode         {} -> { mode: "gui-normal"|"passthrough"|"command"|"search"|"leader"|"insert"|"viewport-edit"|"viewport-play"; focus?: string }
gui.screenshot   { window?: number; path?: AbsPath } -> BlobRef | { path: AbsPath }
gui.dump         { what: "layout"|"ui"|"keymap" } -> { text: string; json?: object }      // test hook: layout tree, visible text per widget, effective keymap
gui.keys         { keys: string } -> {}                                                    // inject key sequence in vim notation (test hook; also used by scripted tests)
gui.notify       { level: Level; text: string; ms?: number } -> {}
```

## A2.15 Event catalogue (domain topics)
| Topic | `data` |
|---|---|
| `game.registered` | `{ instance; name; kind: HostKind; target?: string; caps: string[] }` |
| `game.started` / `game.ready` | `{ instance; run_id?: Id }` |
| `game.stopped` | `{ instance; reason: "stop"\|"exit"\|"crash"; exit_code?: number }` |
| `game.state` | `{ instance; state: string; reason?: string }` |
| `game.tick` | `{ instance; tick: Tick; t_ms: number }` |
| `game.output` | `{ instance; tick: Tick; text: string; ansi?: string; class?: string; append?: boolean }` |
| `game.screen` | `{ instance; tick: Tick; region: string; kind: string; text: string; ansi?: string; buttons?: { id; label; enabled }[] }` |
| `game.crash` | `{ instance; message: string; stack?: string }` |
| `game.state.changed` | `{ instance; watch: Id; changes: { path: StatePath; value: Value }[]; tick: Tick }` |
| `viewport.offered` / `viewport.lost` | `{ id: Id; instance }` |
| `viewport.fallback` | `{ id: Id; from: "dmabuf"; to: "shm"; reason: string }` |
| `timeline.snapshot` | `SnapshotMeta` (without state) |
| `timeline.branch` | `BranchInfo` |
| `timeline.goto` | `{ branch; snapshot; tick; tier?: string; instance }` |
| `timeline.dropped` | `{ count: number; since_tick: Tick; instance }` (policy snapshots dropped under backpressure) |
| `timeline.quota` | `{ level: 1\|2\|3\|4; usage_bytes: number; quota_bytes: number }` |
| `timeline.pruned` | `{ removed: number; bytes_freed: number; cause: "thin"\|"manual"\|"branch-delete"\|"experiment" }` |
| `timeline.damaged` | `{ snapshots: SnapshotId[] }` |
| `patch.pending` | `{ paths: Path[]; tier: string; reason: string }` |
| `patch.applied` | `{ patch_id; tier; paths: Path[]; instance }` |
| `patch.failed` | `{ patch_id?: Id; tier; paths: Path[]; diagnostics: { path: Path; message: string }[] }` |
| `patch.fellback` | `{ patch_id; from: string; to: string; reason: string }` |
| `diag.updated` | `{ file: Path; source: string; diagnostics: Diagnostic[] }` (replace semantics) |
| `index.updated` | `{ files: Path[]; state: "idle"\|"indexing" }` |
| `exp.progress` | `{ run_id; done: number; total: number; failed: number }` |
| `exp.done` | `{ run_id; state: string; failed: number; report: Path }` |
| `editor.attached` / `editor.detached` | `{ socket?: AbsPath }` |
| `editor.cursor` | `{ file?: Path; line: number; col: number; mode: string }` (debounced 50 ms) |
| `editor.saved` | `{ file: Path; hash: Hash }` |
| `editor.buffers` | `{ buffers: { id: number; file?: Path; modified: boolean }[] }` |
| `scene.changed` | `{ instance; version: number; ids: Id[]; cause: "runtime"\|"file"\|"studio" }` |
| `scene.selection` | `{ instance; ids: Id[]; origin: "viewport"\|"hierarchy"\|"runtime" }` |
| `tweak.changed` | `{ instance; path: string; value: Value; source: "ui"\|"runtime"\|"preset" }` |
| `studio.state` | `{ mode: "edit"\|"play"\|"paused"; branch?: BranchId; edit_state?: SnapshotId }` |
| `studio.undo` | `{ stack_depth: number; can_undo: boolean; can_redo: boolean }` |
| `ui.event` | `{ panel; id; kind; value? }` (delivered to the owning module only) |
| `trace.updated` | `{ instance; tick: Tick }` |
| `dap.stopped` / `dap.output` | `{ session; reason: string; thread?: number; file?: Path; line?: number }` / `{ session; text: string }` |
| `gui.mode` | `{ mode: string; focus?: string }` |

## A2.16 Adapter namespace (served by headless hosts and browser agents; semantics in Appendix B1)
```ts
adapter.describe    { instance? } -> { config: object; tick_unit: string; quiescence: string; text_prompt?: { selector: string }; regions: { kind: string; selector: string }[]; render_mode: string;
                      bindings: { file: string; name: string; kind: string; classification: "state"|"code"|"excluded"; bytes: number; script: string }[];
                      transforms: { file: Path; status: "ok"|"skipped"|"error"; reason?: string }[]; dom: { capture: string[] }; canvas?: { width: number; height: number; draw_calls_last_frame: number };
                      warnings: { code: string; message: string }[] }
adapter.fingerprint { instance?; path?: StatePath } -> { hash: string; per_key?: Record<string, string> }
```

## A2.17 Conformance requirements
1. **Schemas and examples:** every method in A1/A2 has JSON Schemas for params and result under `protocol/schema/<method>.params.json` / `.result.json`, every event topic under `protocol/schema/event.<topic>.json`; every file has ≥ 1 valid example in `tests/protocol/examples/` and the tests also contain ≥ 1 invalid example per method (wrong type, missing required key) that must produce `-32602`.
2. **Fuzz:** a protocol fuzz test sends random bytes, truncated lines, 17 MiB lines, deeply nested JSON (depth 10 000), duplicate ids, and mixed valid/invalid sequences; the kernel must stay up, never leak fds, and close only the offending connection.
3. **Handshake:** requests before `session.hello` are rejected; `hello` with an unsupported major `protocol` returns `-32013`; WebSocket without/with wrong token returns `-32001` and closes.
4. **Lazy activation:** a call to a method of a cold module returns the correct result after spawning it, with ≤ 1 spawn per module under 100 concurrent callers; a call during `starting` queues; a crash during a call yields `-32011`.
5. **Event semantics:** `seq` is strictly increasing with no duplicates per kernel run; `since_seq` replay delivers exactly the missed matching events in order; overflow produces exactly one `bus.dropped` per overflow burst.
6. **Pass-through fidelity:** `runtime.*` params/results round-trip byte-identically (modulo whitespace) for a large nested sample.
7. **fd passing:** `proc.attach_pty` delivers a usable PTY master fd (test writes `echo hi` and reads output); on WebSocket it returns `-32005`.
8. **Value encoding:** a property test round-trips random Pipist Values through encode → JSON → decode in C++ and in the JS SDK, including `$t` escaping; cycles become `ref`s; functions are rejected with the offending path unless the adapter policy is `keep-live`, in which case they round-trip as `fn` markers.
9. **Adapter formats:** web snapshot documents (`web/1`), delta snapshots, `adapter.describe` and the new input kinds validate against schemas generated from Appendix B1 and this appendix; walker output is byte-identical between the headless host and the browser agent on the shared corpus (B1.14).
10. **Version policy:** protocol `"1"` is additive-only; any breaking change bumps the major and the kernel may advertise several (`supported`).

<!-- SOURCE-END: pipist-spec-a2-protocol-domain.md -->

---

<!-- SOURCE-BEGIN: pipist-spec-b1-web-adapter.md -->

# PIPIST SPEC — Appendix B1: Web-game adapter and headless web host

Part of Pipist spec v1.3. Normative for M4 (headless web host) and M5 (adapter, snapshots). Extends sections 7, 8.1, 8.2 and 9. Message formats it relies on are in Appendix A; the protocol additions it introduced are listed in B1.13 and are already merged into A1/A2.

**Goal.** Work with **any HTML + JavaScript game** that lives in a project directory, with zero changes to the game by default. The owner's current game (Los Ciegos / Tales of a Dope Fiend: 29 classic scripts in a shared global scope, a `#cmd-input` prompt, `setTimeout` narration, state in a global `G` plus module-level `let`s) is a worked example (B1.11), not a special case: nothing in Pipist code may name its functions or files.

**Generality rules.** (1) No default may depend on a game's vocabulary: input targets, regions, smoke inputs and tick style are derived from the page or given in config, never from fixed element ids or command words. (2) Text-prompt games, button/form-driven apps and real-time canvas games are all first-class. (3) Every behaviour is verified on three structurally different fixtures (B1.14), none of which is the owner's game.

## B1.0 Compatibility tiers
| Tier | Game type | Headless host (`pipist-host-web`) | Browser backend (`pipist-host-browser`) |
|---|---|---|---|
| A | DOM / text / form-driven games: `innerHTML`, `textContent`, classes, events, timers, `localStorage`, local `fetch` | Full | Full |
| B | Canvas 2D games, including real-time (`requestAnimationFrame`) games | Logic, input, state, timeline, patching and experiments work against a recording no-op canvas; no pixels or screenshots | Full |
| C | WebGL, audible WebAudio, WebRTC, WebSockets, heavy Workers | Unsupported (stubs listed in B1.8; unknown APIs raise `HostShimError`) | Full |
When a game cannot run headless the user uses a browser target; timeline, patching, search and the rest still work through the agent (B1.10). Unsupported-API use is reported by `pipist adapter audit` (B1.12), never silently ignored.

## B1.1 Adapter levels
| Level | What the user provides | What Pipist does |
|---|---|---|
| L0 auto | nothing | Detect scripts, build the binding registry (B1.2), capture all state bindings, wrap input/tick/quiescence with defaults |
| L1 config | `[adapter]` table in `pipist.toml` (B1.11 shows the full schema) | L0 plus include/exclude lists, tick hooks, DOM capture list, redraw expressions, extra providers |
| L2 file | a JS file `adapter = "adapters/x.js"` calling `__pipist.adapter({...})` | Per-feature override of L0/L1 |
Resolution per feature (state, dom, tick, quiesce, input, output, redraw): defaults < L0 detection < L1 config < L2 file. An L2 file can switch an automatic feature off (`auto: { state: false }`).

**L2 API** (available as global `__pipist` in the game's realm, in both hosts; absent in a plain browser, so game code must guard calls):
```js
__pipist.adapter({
  meta:    { name, version, tick_unit: "input" | "call" | "event" | "frame" | "interval" | "step" },
  auto:    { state: true, dom: true, tick: true, input: true, output: true },      // per-feature opt-out
  state:   { get(ctx) { return plainValue }, set(value, ctx) {} },                  // replaces auto state capture
  extra:   { "name": { get() { return v }, set(v) {} } },                          // merged with auto state
  tick:    { install(emitTick) {} },                                                // custom tick source
  quiesce: () => true,                                                              // extra "game is idle" condition
  input:   { line(text) {}, key(k) {}, button(id) {} },
  output:  { subscribe(cb) {} },                                                    // cb({text, class, append})
  redraw:  () => {},                                                                // after restore
  beforePatch(info) {}, afterPatch(info) {}, migrate(oldState, info) { return newState }
})
__pipist.state(name, getter, setter)    // register one extra provider at runtime from game code (optional convenience)
```
`ctx` offers `ctx.walk(value)` (Pipist Value encoder), `ctx.sync(target, value)` (in-place restore, B1.3.5), `ctx.log(level, msg)`.

## B1.2 Binding registry via source transform
Top-level `let`/`const`/`class` bindings of classic scripts and all non-exported bindings of ES modules are invisible from outside the script. Pipist makes them reachable **by appending one line** to each script, so no original line numbers move.

**Transform.** The `index` module (tree-sitter, exact parse) owns the transform: `index.transform` (B1.13). For a JS file or each `<script>` block of an HTML file it returns the original text plus an appended registration statement; results are cached by content hash in `.pipist/cache/transform/<hash>`. Hosts call it through `kernel.call`; if `index` is unavailable (build without tree-sitter) the host runs untransformed and L0 state capture is limited to `var`/`function` globals (`Object.getOwnPropertyNames(globalThis)` minus a baseline taken before the game scripts) with a warning; L1/L2 still work.

**Appended code (classic script):**
```js
;(function(){var R=(globalThis.__pipist_reg||(globalThis.__pipist_reg={}));
 var S="<file>#<script-index>";   // unique script key
 R[S]={file:"<file>",b:{
  G:{k:"const",get:function(){return G},set:function(v){G=v}},        // const: assignment throws TypeError; the host never calls set() on const
  combatState:{k:"let",get:function(){return combatState},set:function(v){combatState=v}},
  oldFn:{k:"function",get:function(){return oldFn}}, Cls:{k:"class",get:function(){return Cls}} }};})();
```
- One entry per **top-level declared name**: `var`, `let`, `const`, `function`, `class`, including destructuring patterns (`const {a,b}=x`, `let [p,q]=y`), comma declarators (`let a=1,b=2`), `async function` and generators. Only top-level declarations count (not names declared inside blocks, loops or functions).
- Getters are wrapped so a TDZ or missing binding yields `undefined` and a recorded registry error (`E_REG_TDZ`, `E_REG_MISSING`) instead of throwing into game code.
- The appended statement is placed after the last token (a trailing `//` comment on the final line is handled by inserting a newline first; `"use strict"` is unaffected).
- **ES modules** (`type="module"`): the same statement is appended inside the module scope and registers under the module URL; `import`/`export` are untouched. A module's names are addressed as `"<path>"#name` (B1.3.1).
- **Never transformed:** files matching `[adapter].no_transform` globs, `node_modules/`, minified files over 1 MiB (warning: *"huge/minified, skipping registry"*), and anything already containing `__pipist_reg`.
- **Not reachable** (documented limit, reported by audit): state held only in closures or IIFE locals, class `#private` fields, module-private state of third-party bundles. Escape hatches: `__pipist.state(...)`, L1 `extra`, L2 `state`.
- The transform must be **semantically transparent**: running a project with and without it yields identical game behaviour (tested, B1.14).

## B1.3 State capture and restore
### B1.3.1 What is state
Registry entries (B1.2) → *bindings*. A binding is **state** when `kind ∈ {var,let,const}` and its current value is not a function or class. `function`/`class` bindings are code. L1 `include`/`exclude` (glob over `"<file>:<name>"`) override the default. Plain-object bindings are split one level (`split_depth = 1`): the unit of change tracking is `(binding, top-level key)`, e.g. `G.eventLog`, `G.inventory`, so that a huge but unchanged key costs nothing per tick.

Addressing (`StatePath` roots): classic-script bindings use their bare name (`G.flags.chuyRep`); module bindings use `"js/x.js"#name`; extras use `$extra.<name>`; DOM, storage and host meta use `$dom`, `$storage`, `$host`.

### B1.3.2 Snapshot document
```ts
interface WebSnapshot {
  format: "web/1";
  bindings: Record<string /* StatePath root */, Value>;      // state bindings (each plain-object binding is an object of its top-level keys)
  extra:    Record<string, Value>;                            // L1/L2 providers
  $dom?:    Record<string /* selector */, { html: string; attrs?: Record<string,string>; value?: string }>;   // B1.5
  $storage?: Record<string,string>;                           // localStorage
  $host:    { rng: number[4]; clock_ms: number; epoch_ms: number; timer_seq: number; boot_timers: { seq: number; remaining_ms: number; interval_ms?: number }[]; focus?: string; scroll?: Record<string,number> };
}
```
The document is a Pipist Value tree (A1.4). Aliasing across bindings is preserved with `ref` tags (path relative to the document root). Functions: `{"$t":"fn","name":…}` markers are **allowed** (policy `functions = "keep-live"`, default): restore never replaces a live function. DOM nodes referenced from state: `{"$t":"dom","id":N}` (host-assigned stable node ids; unresolved ids restore as `null` with a warning). Accessor properties, Symbol keys, non-enumerable properties (except array `length`), WeakMap/WeakSet/Promise/Proxy/timer ids are skipped and counted in the audit.

### B1.3.3 Walker semantics (identical in the C++ host and the JS agent)
- Depth-first, own enumerable string keys in insertion order. Cycle/alias detection by object identity (map object → first path).
- Plain objects, arrays (holes preserved as `undef`), `Map`, `Set`, `Date`, `RegExp` (`{"$t":"re","src","flags"}`), typed arrays/`ArrayBuffer`/`DataView` as `bytes`, boxed primitives unwrapped, class instances as `obj` with `class` = `constructor.name`. Cap: `max_depth` 64, `max_bytes` 8 MiB per snapshot (excess → snapshot rejected, `E_SNAP_TOO_LARGE`, state of largest bindings listed in the warning).
- **Fingerprint:** a 64-bit structural hash per `(binding, key)` computed in the same traversal without allocating (FNV-1a over type tags and values, objects by traversal order). A snapshot is built from the fingerprints first; only keys whose fingerprint differs from the base snapshot are serialized; the rest go into `unchanged`. Budget: fingerprint pass ≤ 10 ms and full serialize ≤ 50 ms for 5 MB of state in the C++ host.
- The C++ host implements the walker natively over the QuickJS C API; the agent implements it in JS. Both must produce byte-identical JSON for the shared corpus (B1.14).

### B1.3.4 Snapshot transfer
The host serializes to a temp file and calls `blob.put_path {path, move:true}` (A1.10); `timeline.snapshot.put` carries the resulting `BlobRef` plus `base`/`unchanged` (B1.13). Payloads under 256 KiB may go inline.

### B1.3.5 Restore algorithm
`game.restore` with `mode`:
- **`reboot` (default for the headless web host):** discard the JS context, re-create it, re-run the HTML (including the transform), run to the end of boot (B1.7), then apply the snapshot. Guarantees closure-held state is fresh and avoids leftover timers.
- **`in-place`:** apply into the live context (faster; correct only when the game has no hidden state — `pipist adapter verify` tells). Used by `studio.stop` and quick scrubbing when `[adapter].restore = "in-place"`.
Application steps (both modes):
1. Cancel all non-boot timers/animation frames (B1.6), clear pending event dispatch.
2. Resolve `ref`s with a per-restore alias table so shared objects stay shared.
3. For each binding, `sync(live, snap)`: plain objects — delete missing keys, assign others, recursing when both sides are objects of the same kind (identity of live containers preserved, so closures and handler tables that captured them keep working); arrays — set `length` then sync elements; `Map`/`Set` — clear and refill (insertion order kept); `Date` — `setTime`; class instance — `Object.setPrototypeOf` to the live class prototype found by name (top-level class/function binding or `globalThis[name]`; missing → plain object + warning) then sync own props; primitives — assign via the binding's `set` (skipped for `const`; a `const` primitive that differs → warning `E_CONST_DIFF`). Where recursion is impossible (live is a primitive and snap is an object, etc.) the binding is assigned (`let`/`var`) or warned (`const`).
4. `$storage`: replace host `localStorage` content. `$host`: restore PRNG state, virtual clock, epoch, timer sequence counter, and re-arm **boot timers** (B1.6). `$dom`: restore captured regions (B1.5). Run `redraw` expressions.
5. Return `shape_diff` (A2.2) computed between the snapshot's binding set/types and the freshly booted live set.

## B1.4 Ticks, input and quiescence
**Tick unit** (`[adapter.tick].unit`, default `auto`). `auto` is resolved once, at the end of boot: if a `requestAnimationFrame` loop is running (a callback re-registered itself at least twice within the first 2 000 virtual ms) the unit is `frame`; otherwise `input`. The resolved unit is reported by `adapter.describe` and can always be forced in config.
| Unit | A tick ends when |
|---|---|
| `input` | One host input (a `game.input`, or in the browser one user input event matching `[adapter.input]`) has been fully processed **and** the page is quiescent (below). Chained commands and async follow-ups belong to the same tick. |
| `frame` | Every `every_ticks`-th `requestAnimationFrame` batch has finished (default 6, about 10 snapshots per second at 60 fps). Inputs are processed inside frames. |
| `call` | A listed global function returns (`[adapter.tick].after = ["name"]`; wrappers are installed by name on `globalThis`; a returned thenable ends the tick on settlement). |
| `event` | A DOM event matching `{target, type, key?}` has finished dispatching. |
| `interval` | Every `interval_ms` of virtual time. |
| `step` | Only via `game.step` (one step = one tick of the resolved unit; for frame games, one frame batch). |

**Quiescence** (`[adapter.quiesce].mode`, default `auto`: `strict` for every unit except `frame`, which uses `frame`).
- `strict`: the microtask queue is empty; no pending **gameplay** `setTimeout` due within `horizon_ms` (default 60 000 virtual ms); no pending `requestAnimationFrame` loop that is not a boot loop; no in-flight `fetch`; the L2 `quiesce()` hook (if any) returns true. `setInterval` timers and boot timers never block quiescence unless `interval_blocks = true`. In `fast` and `stepped` clock modes the host drains due timers (virtual jump) up to `max_wait_ms` (default 30 000 virtual ms); if the page is still not quiet it reports `quiescent:false` (A2.2). In `realtime` mode the snapshot is deferred to the next quiet moment.
- `frame`: the page is quiescent at every frame boundary (microtasks drained). Pending gameplay timers and in-flight fetches are allowed but **will not survive a restore**; a snapshot taken while any exist logs `W_TIMERS_DROPPED` (with their creation sites) and `adapter verify` fails on them. Games that run on `requestAnimationFrame` and frame counters are unaffected.
- `off`: no check.

**Text-prompt detection** (end of boot), first match wins: (1) `[adapter.input].target`; (2) the element focused at boot end, if it is editable (`input` text-like, `textarea`, `contenteditable`); (3) the only visible text-entry control, if exactly one exists; (4) none. No element ids or command words are ever guessed. With no prompt, `line` input fails with `-32005 unsupported {capability:"text_prompt"}` and the other input kinds remain available.

**Input kinds** (`game.input.event`, A2.2; the host lists those it can perform in `game.hello.meta.input_kinds`):
- `line {text}` — needs a text prompt: focus it, set its `value`, dispatch `keydown` `{key:"Enter", code:"Enter", keyCode:13, which:13}`, `keypress`, `keyup` (default `submit = "keydown:Enter"`; `"form"` = `submit` event on the enclosing form; `"call:fn"` = call a global function with the text).
- `text {text}` — type characters one by one into the focused element with `keydown`/`input`/`keyup` events.
- `key {key, code?, mods?, down?, hold_frames?, hold_ms?}` — `keydown` then `keyup` on the focused element (else `document`). With `hold_frames` / `hold_ms` the host advances virtual time between press and release; `down: true|false` sends only one half. `key` and `code` use DOM names (`"ArrowLeft"`, `"KeyW"`, `"Space"`); `keyCode`/`which` come from a standard table.
- `button {id}` — a full click sequence (`pointerdown, mousedown, pointerup, mouseup, click`) on the element that `game.buttons` listed with that id.
- `click {selector?, x?, y?, button?, double?}` — the click sequence on `selector`, else at coordinates on the **pointer target** (`[adapter.input].pointer_target`; default: the largest `<canvas>`, else `<body>`). Events carry `clientX/clientY/offsetX/offsetY/pageX/pageY` = x,y: the headless host has no layout, so `getBoundingClientRect()` is all zeros and coordinates pass through unchanged.
- `pointer {type: "move"|"down"|"up", x, y, button?}` and `wheel {dx, dy, x?, y?}` — the same targeting, for dragging, aiming and scrolling.

**Buttons.** `game.buttons` lists visible clickable elements: `button`, `input[type=button|submit]`, `[role=button]`, `a[href]`, and any element with a `click` listener registered through `addEventListener`/`onclick` (the shim tracks them). `id` is the element id, else a stable CSS path; `label` comes from text, `aria-label`, `title` or `alt`.

## B1.5 DOM, storage and redraw
The screen and any dynamic UI are DOM state that lives outside the binding registry. Capture is explicit and cheap:
- `[adapter.dom].capture = ["#log", "#toolbar", "#status", "#screen-title", "#screen-game"]` — for each selector the snapshot stores `innerHTML` and the listed attributes (`attrs`, default `["class","style","hidden"]`) of the element itself, plus `value` for inputs. Scrollback is included by capturing the log container, trimmed to the last `[adapter.dom].max_html_bytes` (default 512 KiB, whole-child boundaries).
- **Restore** sets `innerHTML`/attributes in place (the container element identity is preserved; replaced children lose any listeners attached directly to them). `redraw` expressions (`[adapter.dom].redraw = ["renderToolbar()"]`, JS evaluated at global scope, errors logged) let the game rebuild dynamic controls from restored state. Without a `redraw` hook and with dynamic controls detected (buttons created at runtime that vanish on restore) the host logs `W_INERT_CONTROLS` once with the offending selectors.
- `pipist adapter suggest` (B1.12) proposes `capture` and `redraw` from observed mutations.
- `$storage` captures `localStorage` entirely (`[adapter].storage = true`); `sessionStorage` and `document.cookie` are captured when non-empty.

## B1.6 Determinism, clocks and timers
- **Clock:** `Date`, `Date.now`, `performance.now`, `performance.timeOrigin`, timer scheduling and `requestAnimationFrame` timestamps all derive from the **virtual clock**. `epoch_ms` (virtual 0 as Unix time) defaults to the real time at first boot of the session and is stored in `$host` so a restored session continues with the same calendar time. `Date` is replaced by a wrapper class that preserves the full API (`Date.UTC`, `parse`, local-time getters using the system time zone).
- **Clock modes** (`game.start options.mode` / `[host.web].mode`): `realtime` (virtual advances with wall time, timers fire when due), `fast` (virtual time jumps to the next due timer immediately; used by experiments and tests), `stepped` (virtual time advances only inside `game.step`/`game.input` processing, running timers to quiescence).
- **RNG:** `Math.random`, `crypto.getRandomValues`, `crypto.randomUUID` use one seeded **xoshiro128\*\*** generator (seed from `game.start options.seed`, else random per session, recorded in session metadata; state saved in `$host.rng`). `[adapter.determinism].rng = "native"` leaves the engine RNG (reproducibility lost, warning in audit).
- **Timer classes:** timers created before the end of boot are **boot timers** (`seq` numbered in creation order); the rest are **gameplay timers**. Restore cancels gameplay timers and keeps boot timers, re-arming each (matched by `seq`) at `now + remaining_ms` stored in the snapshot (intervals keep their period). If a boot timer with that `seq` does not exist (code changed) it is skipped with a warning. Snapshots are only taken at quiescence, i.e. when no gameplay timers are pending, so nothing that cannot be serialized (closures) is ever lost.
- Browser backend: `Math.random`/`Date` are left native unless `[adapter.determinism]` asks the agent to install the same virtual clock and PRNG (supported; default off because it changes real-time behaviour).

## B1.7 Headless host (`pipist-host-web`)
**Process model.** One process per game instance. Embeds quickjs-ng; one realm per page load. libuv loop shared with the protocol connection. A **watchdog** interrupts any single macrotask longer than `[host.web].watchdog_ms` (default 10 000 real ms): the task is aborted with an uncatchable interrupt, the host logs the stack, emits `game.crash` and enters state `paused` awaiting `game.restore`/`game.stop`. Memory cap `memory_mb` (default 512), stack cap 1 MiB.

**Boot sequence (exact):**
1. Parse arguments (`--project --target --entry --adapter --mode --seed --epoch --cols --rows --url --socket`); connect; `session.hello` (kind `host`); fetch effective `[adapter]`/`[host.web]` via `config.get`.
2. Create runtime/context; install native modules (virtual clock, timers, PRNG, console, storage backing, file access sandboxed to the project dir); evaluate embedded `dom-shim.js` and `web-apis.js`.
3. Read the entry HTML; parse with the HTML5 parser (document mode). For each script (blocks and `src` files) request `index.transform`; build the execution list.
4. Execute scripts per the loader rules below; fire `DOMContentLoaded`, then `load`; run the macrotask queue until quiescent or `boot.max_ms` virtual (default 5 000); record boot timers; mark **boot end**.
5. Resolve `unit = auto` and detect the text prompt (B1.4), detect render regions (B1.9), install adapter hooks (tick wrappers), compute the binding table and take the **boot baseline fingerprint**.
6. `game.hello` (A2.2); state `ready`; start serving `game.*`.

**Loader rules.** Document order. `<script src>` classic and inline classic scripts run synchronously in place; `defer` scripts and `type="module"` scripts run after parsing completes, in order, before `DOMContentLoaded`; `async` scripts run after `defer` ones in document order; `nomodule` scripts are skipped; `<script type="importmap">` is honoured for module specifiers; other `type` values are ignored. Resolution is relative to the HTML file; `file:` only; paths escaping the project root are refused. Script errors are logged (`error`, with `link {file,line}`; inline-script lines are offset to the HTML file) and loading continues, as in a browser. Inline `on*` attributes are compiled on first use with `new Function("event", code)` bound to the element. `document.write` during parsing and `<iframe>` content are unsupported (`HostShimError`).

**Event loop.** After every macrotask (timer callback, event dispatch, input) the host drains microtasks (`JS_ExecutePendingJob` until empty). Uncaught exceptions and unhandled rejections are logged and dispatched to `window.onerror` / `unhandledrejection` listeners; they do not stop the host.

**State serving:** `game.state.get/set/watch`, `game.snapshot`, `game.restore`, `game.eval` operate on the registry (B1.2–B1.3); `game.eval {code, lang:"js"}` runs `(0,eval)(code)` in global scope with the result converted by the walker (depth-limited). `adapter.describe` returns the binding table (B1.13).

## B1.8 Web API surface (exact)
Legend: **S** supported with browser semantics; **L** limited (notes); **N** no-op stub; **X** unsupported → `HostShimError` (or no-op proxy in `lenient` mode).
| Area | APIs |
|---|---|
| Document | **S** `getElementById`, `querySelector(All)`, `getElementsBy{TagName,ClassName,Name}`, `createElement`, `createTextNode`, `createDocumentFragment`, `createComment`, `body`, `head`, `documentElement`, `title`, `readyState`, `activeElement`, `hidden`(=false), `cookie` (in-memory); **L** `createEvent` (legacy constructors); **X** `execCommand`, `designMode` |
| Node/Element | **S** `appendChild`, `append`, `prepend`, `insertBefore`, `insertAdjacentHTML/Element/Text`, `removeChild`, `remove`, `replaceChild`, `replaceWith`, `cloneNode`, `contains`, `firstChild…`, `children`, `parentNode`, `nextSibling`…, `textContent`, `innerHTML`/`outerHTML` (fragment parsing), `innerText` (render-aware approximation: block newlines), `id`, `className`, `classList`, `dataset`, `attributes`/`get|set|has|removeAttribute`, `hidden`, `style` (object with `cssText`, property get/set incl. camelCase and `setProperty`), `matches`, `closest`, `getBoundingClientRect` (zeros), `offsetWidth/Height` (0), `scrollTop/Height` (stored value; `scrollIntoView` N), `focus`/`blur`, `click`, `addEventListener` (capture, once, passive, signal), `removeEventListener`, `dispatchEvent` |
| Forms | **S** `input`/`textarea`/`select` `value`, `checked`, `disabled`, `selectedIndex`, `form`, `submit`/`requestSubmit`, `reset`, `FormData`(basic) |
| Selectors | **S** type, `#id`, `.class`, `[a]`, `[a=v]`, `~= |= ^= $= *=`, descendant/child/adjacent/sibling combinators, comma lists, `:first-child :last-child :only-child :nth-child() :nth-of-type() :not() :empty :checked :disabled :enabled :root`; **X** `:has()` `:is()` `:where()` (added if a corpus script needs them) |
| Events | **S** `Event`, `CustomEvent`, `KeyboardEvent`, `MouseEvent`, `InputEvent`, `FocusEvent`, `PointerEvent`(basic), `WheelEvent`(basic), capture→target→bubble, `preventDefault`, `stopPropagation`, `stopImmediatePropagation`, `on*` properties and attributes, `DOMContentLoaded`, `load`, `beforeunload`(never), `resize`(on `cols/rows` config), `visibilitychange`(never) |
| Timers | **S** `setTimeout`, `clearTimeout`, `setInterval`, `clearInterval`, `requestAnimationFrame` (16.667 ms virtual steps), `cancelAnimationFrame`, `queueMicrotask`; **L** `setImmediate`, `requestIdleCallback` (run after 1 ms virtual); nesting clamp (4 ms) is **not** emulated |
| Storage/net | **S** `localStorage`, `sessionStorage` (file-backed under `.pipist/host-storage/<target>/`), `fetch` / `XMLHttpRequest` to project-relative paths (text, json, arrayBuffer, blob; status 200/404), `URL`, `URLSearchParams`, `Blob`(text/bytes), `TextEncoder/Decoder`, `atob/btoa`, `structuredClone`; **N** cross-origin network (`net = "deny"` rejects with `TypeError("network disabled")`; `net = "allow"` unsupported in host) |
| Window | **S** `window`, `self`, `globalThis`, `location` (file URL; `hash`/`search` from `--url`), `history` (pushState/replaceState updating `location`), `navigator` (`userAgent = "Pipist/<ver> QuickJS"`, `language`, `hardwareConcurrency=4`, `clipboard` stub), `screen`, `innerWidth/innerHeight` (= `cols×8`, `rows×16`), `devicePixelRatio=1`, `matchMedia` (never matches), `getComputedStyle` (inline style + parsed CSS `display/color/font-*`), `alert` (log), `confirm` (`[host.web].dialogs.confirm`, default true), `prompt` (default value), `open` N, `close` N, `console.*` (to `log.write`, channel `console`), `performance.now/mark/measure`(basic), `crypto.getRandomValues/randomUUID`, `MutationObserver` (childList/attributes/characterData, subtree), **N** `ResizeObserver`, `IntersectionObserver`, `Notification` |
| Media/graphics | **N** `Audio`/`HTMLAudioElement`/`AudioContext` (methods return resolved promises, no sound), `Image`/`HTMLImageElement` (`load` fires asynchronously; `naturalWidth/Height` read from PNG/JPEG/GIF headers when the file exists), **S** `Path2D`, `ImageData`, `DOMMatrix`/`DOMPoint` (basic); **L** `HTMLCanvasElement.getContext("2d")` returns a recording no-op context (every method exists; `getImageData` returns zeroed data of the requested size, `toDataURL` a blank PNG, `measureText` a width of 0.5 × font size × length; draw-call and sprite counters are reported by `adapter.describe`); **X** WebGL, WebGPU, `OffscreenCanvas`, `WebSocket`, `Worker`/`SharedWorker`, `WebRTC`, service workers, IndexedDB (planned) |
| Language | quickjs-ng ES2023 incl. modules, async/await, generators, BigInt, `Intl` limited (no locale data beyond `en`; `toLocaleString` falls back to `en-US`) |
**Shim modes:** `[host.web].shim = "lenient"` (default for `pipist play`/experiments: unknown members of `window`/`document`/elements return a callable no-op proxy and log one `W_SHIM_MISSING <api>` per API) or `"strict"` (default in CI and `pipist doctor`: unknown API → `HostShimError`). Counts are reported by `adapter audit`.

*Continued in `pipist-spec-b1b-web-host-ui.md` (B1.9–B1.14: renderer, browser backend, configuration, tools, protocol additions, tests).*

<!-- SOURCE-END: pipist-spec-b1-web-adapter.md -->

---

<!-- SOURCE-BEGIN: pipist-spec-b1b-web-host-ui.md -->

# PIPIST SPEC — Appendix B1b: Web host renderer, configuration, tools and tests

Continues Appendix B1 (`pipist-spec-b1-web-adapter.md`, sections B1.0–B1.8). Same status and conventions.

## B1.9 Renderer and terminal view
The host turns the page into a terminal screen with a small flow renderer (no layout engine). `[host.web.render].mode`: `auto` (default), `terminal`, `summary`, `none`.

**Region detection** (when `render.regions` is absent; runs at boot end and again after the first 20 ticks; results are in `adapter.describe`). It uses DOM mutation statistics collected since load, never fixed ids:
- *log*: the element with the most appended children (≥ 3, few removals), or one marked `role="log"` / `aria-live`;
- *status*: elements whose own text changed ≥ 3 times in place (excluding the log and prompt);
- *buttons*: containers (never `<body>`) holding ≥ 2 visible clickable elements;
- *prompt*: the text prompt of B1.4.
If no log or status region exists but visible text does, `<body>` becomes one *status* region (static pages). `auto` selects `terminal` when at least one region exists, otherwise `summary`.

**Explicit regions** override detection entirely (example for a text-prompt game):
```toml
[[host.web.render.regions]]
selector = "#output"       # append-only log area: new children become scrollback lines
kind = "log"
[[host.web.render.regions]]
selector = "#statusbar, #stats"      # re-rendered in place whenever descendants change
kind = "status"
[[host.web.render.regions]]
selector = "#hotbar, .quick-buttons" # every clickable element inside becomes a numbered button
kind = "buttons"
[[host.web.render.regions]]
selector = "#cmd-input"
kind = "prompt"
```
**Summary mode** (canvas-only games, or no visible text): the screen is a status block with the resolved tick unit and tick, virtual time, frames per virtual second, available input kinds, canvas size and the last frame's draw-call/sprite counters (from the recording canvas), counts of `W_*` warnings, and the last 5 console lines. `none` renders nothing (events only).

**Flow rules.** Block elements (`div p pre h1-h6 ul ol li tr table blockquote section article header footer form br hr`) start new lines (`li` prefixed `• ` or `N. `; `hr` becomes a rule; `td`/`th` are separated by two spaces). Inline text flows with whitespace collapsed except under `pre` or `white-space: pre*`. Hidden content is skipped: `hidden` attribute, or `display:none` / `visibility:hidden` from an inline style or a CSS class (class rules come from `<style>` and linked CSS through a tiny tokenizer: simple selectors `tag`, `.class`, `#id`, comma lists; declarations `display`, `visibility`, `color`, `background-color`, `font-weight`, `font-style`, `text-decoration`, `white-space`, `opacity` (≤ 0.4 → dim)). `<input>` renders `[value]`, `<button>` renders `[ label ]`, `<img>` renders `[alt]`, `<a>` is underlined, `<canvas>` renders `[canvas WxH]`.
**Styling → ANSI.** CSS colors map to the nearest xterm-256 color (truecolor when the terminal reports it); bold, italic, underline and dim come from the corresponding declarations. `[host.web.render].styles` overrides per class (`system = "yellow"`, `hint = "italic fg:178"`).
**Events.** Each new log child produces `game.output {instance, tick, text, ansi, class, append}` where `class` is the element's first class. In-place regions emit `game.screen` (A2.2) with the new rendered block.
**Screen model.** `game.screen.get` returns the composed screen: status regions on top, the last N scrollback lines, the buttons bar (`1: Look  2: Inventory …`), and the prompt line when a text prompt exists; sized `--cols × --rows`. In summary mode it returns the status block.
**`pipist play` (terminal client).** Raw terminal. With a text prompt, the prompt is a `ViEngine` line (13C.4) whose `<CR>` sends `game.input {kind:"line"}`; without one, keys pass through to the game as `key` inputs (press/release pairs) and, when the terminal reports mouse events, mouse clicks and drags become `pointer`/`click` inputs on the pointer target. The buttons bar is driven by `<Alt-1>…<Alt-9>`. `<Prefix>` (default `Ctrl+\`) then `:` opens the Pipist command line (13C). The game's own vi mode and leader menu are bypassed by default (`[host.web].bypass_game_input = true`); set it to false to forward raw keys to the page.
**GUI Game view (terminal).** Renders the same screen in a `TerminalView` fed by the host's ANSI stream, plus clickable buttons from `game.buttons`.

## B1.10 Browser backend differences
`pipist-host-browser` serves the project directory and rewrites each HTML response: (a) inject `<script src="/__pipist/agent.js">` first in `<head>`; (b) replace each script (block or `src` response) with the `index.transform` output; (c) add a `Content-Security-Policy`-compatible nonce when needed. The agent is the same adapter logic in JS: registry reader, walker (byte-identical output to the C++ walker on the corpus), fingerprint/delta, tick wrappers, quiescence (wrapping `setTimeout/setInterval/requestAnimationFrame/fetch` to count pending work), DOM capture (B1.5), input observation (capture-phase listeners on `[adapter.input].target`), output observation (`MutationObserver` on the log region), `game.hello` over WebSocket. `restore` = save snapshot document to the daemon → `location.reload()` → agent reconnects → boot → apply (B1.3.5 `reboot` semantics); `in-place` is also available. DOM node refs in state are stored as `{"$t":"dom","sel":"<css path>"}` (best effort). Screenshots, console capture and real canvas/WebGL are the reasons to use this backend.

## B1.11 Configuration schema and worked examples
Complete `[adapter]` and `[host.web]` keys (all optional; shown with defaults):
```toml
[adapter]
mode = "auto"                      # auto | config-only (no auto state) | manual (L2 file only)
file = ""                          # L2 adapter file
storage = true
restore = "reboot"                 # reboot | in-place
no_transform = ["node_modules/**", "**/*.min.js"]
[adapter.state]
include = ["*:*"]                  # globs over "<file>:<name>"
exclude = []
split_depth = 1
functions = "keep-live"            # keep-live | error
max_depth = 64
max_bytes = 8388608
extra = []                         # [{ name = "q", get = "queue.slice()", set = "queue.splice(0, queue.length, ...v)" }]
[adapter.tick]
unit = "auto"                      # auto | input | call | event | frame | interval | step
after = []                         # for unit = "call"
event = {}                         # for unit = "event": { target = "#go", type = "click" }
every_ticks = 0                    # 0 = unit default (frame: 6)
interval_ms = 1000
[adapter.quiesce]
mode = "auto"                      # auto | strict | frame | off
horizon_ms = 60000
max_wait_ms = 30000
interval_blocks = false
[adapter.input]
target = ""                        # text prompt; detected when empty (B1.4); no ids are ever guessed
submit = "keydown:Enter"           # keydown:Enter | form | call:<fn>
pointer_target = ""                # receives click/pointer events; default: largest <canvas>, else <body>
[adapter.dom]
capture = []
attrs = ["class", "style", "hidden"]
redraw = []
max_html_bytes = 524288
[adapter.smoke]
script = ""                        # explicit input script (path); wins over generation (B1.12)
clicks = 10                        # generated smoke: max distinct visible clickable elements to click
keys = ["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Space","Enter","KeyW","KeyA","KeyS","KeyD","KeyZ","KeyX"]   # held 30 frames each in frame games
probe_lines = ["help", "?"]        # last-resort lines for text-prompt games when the page offers no hints
[adapter.determinism]
rng = "pipist"                      # pipist | native
clock = "virtual"                  # virtual | native
[host.web]
shim = "lenient"                   # lenient | strict
mode = "realtime"                  # realtime | fast | stepped
cols = 100
rows = 40
watchdog_ms = 10000
memory_mb = 512
net = "deny"
dialogs = { confirm = true, prompt = "" }
bypass_game_input = true
render = { mode = "auto", auto_css = true, styles = {} }   # mode: auto | terminal | summary | none; + [[host.web.render.regions]]
```
**Worked example 1: Los Ciegos, a text-prompt game** (uses only generic settings; names come from the owner's handoffs and must be confirmed against the real files by `pipist adapter suggest`):
```toml
[[target]]
name = "play-text"
kind = "game"
host = "web-quickjs"
entry = "index.html"

[adapter]
mode = "auto"                         # module-level lets (combatState, replayRngQueue, dialogueSession, barterSession, ...) are found by the registry
restore = "reboot"
[adapter.state]
exclude = ["*:VERBS", "*:ITEM_DESC"]  # large constant tables the audit shows never change
[adapter.tick]
unit = "input"                        # one typed line (including ';' chains and async narration) = one tick
[adapter.input]
target = "#cmd-input"
submit = "keydown:Enter"
[adapter.dom]
capture = ["#output", "#hotbar", "#status", "#title-screen", "#name-screen", "#load-screen", "#game-screen"]
redraw = ["typeof refreshContextButtons === 'function' && refreshContextButtons()"]   # confirm real name with `adapter suggest`
[host.web]
shim = "lenient"
bypass_game_input = true              # the game's own vi mode / leader menu are bypassed in `pipist play`; Pipist's ViEngine edits the line instead
[[host.web.render.regions]]
selector = "#output"
kind = "log"
[[host.web.render.regions]]
selector = "#hotbar"
kind = "buttons"
[[host.web.render.regions]]
selector = "#cmd-input"
kind = "prompt"
```
Notes tied to that game (the config above is mostly redundant with auto-detection; it pins what `adapter suggest` would propose): its save/load is a replay of `G.eventLog` plus `rrand()` entries — Pipist snapshots are independent and never touch it; `G.eventLog` is a large append-only key, handled by key-level change tracking and chunk dedupe; boot-time and narration `setTimeout`s are separated by the boot/gameplay timer classes; dev-mode names (`ccpe`, …) are ordinary typed input and make good `adapter verify`/experiment fixtures.

**Worked example 2: a real-time canvas game with no text prompt** (only what differs from the defaults):
```toml
[[target]]
name = "play-web"
kind = "game"
host = "web-quickjs"
entry = "index.html"

[adapter.tick]
unit = "frame"             # also what `auto` picks when a requestAnimationFrame loop is found
every_ticks = 6            # one snapshot every 6 frames
[adapter.quiesce]
mode = "frame"
[adapter.input]
pointer_target = "#game"   # canvas element that receives pointer events
[host.web]
mode = "stepped"           # frames advance only on game.step or input, for deterministic experiments
render = { mode = "summary" }
```
State needs no configuration: module-level bindings are found by the registry, and a game with closure-hidden state is caught by `adapter verify`.

## B1.12 Tools
All run through the CLI (and GUI actions) and write reports under `.pipist/adapter/`.
- **`pipist adapter describe`** — effective config, registry table: `file, name, kind, classification (state|code|excluded), approx_bytes, scripts`, transform status per file, DOM capture list, tick/input resolution. Served by the host as `adapter.describe`.
- **`pipist adapter audit [--script inputs.txt]`** — boots the game under the `strict` shim, plays the smoke script (below) and reports: shim gaps by API with first stack; bindings not found by the transform (names referenced as globals but not registered); bindings skipped (accessors, symbols, opaque); registry errors (TDZ/missing); per-binding change frequency over the run (to drive `exclude` suggestions); estimated snapshot size and capture time; inert-control warnings; non-determinism sources (native RNG/Date use detected by wrapping).
- **Smoke script** (`pipist adapter audit|suggest`; `[adapter.smoke].script` wins when set). Generated from evidence on the page only: (1) click up to `clicks` distinct visible clickable elements in document order, one per tick; (2) if a text prompt exists, send an empty line, then up to 3 candidate lines harvested from the page (`<code>` text and backtick/quoted words near "type"/"try", the prompt's `placeholder`, `<datalist>` options, button labels), and only when nothing was harvested the `probe_lines`; (3) if the unit is `frame`, hold each key of `keys` for 30 frames, one at a time, then click and drag the pointer target at its centre and four quadrant points; (4) finish with 600 frames, or 10 s of virtual idle time.
- **`pipist adapter verify --script inputs.txt [--stride N]`** — restore-fidelity test (the main correctness check). In `fast` clock mode with fixed seed: play the script, taking a snapshot every `stride` ticks (default 5) and recording the transcript and a state hash per tick. For each snapshot `S_k`: restore (default `reboot`), replay inputs `k+1..n`, then compare per-tick state hashes and transcripts with the original run. Report PASS or the first divergence: tick, differing binding paths (state), or transcript line (hidden state outside the registry/DOM capture). Implemented by the `experiments` module (`exp.verify_adapter`, B1.13).
- **`pipist adapter suggest`** — plays the smoke script observing DOM mutations and function calls to propose: input target and submit style, log/status/buttons regions, `dom.capture` containers (elements whose descendants mutated most), `redraw` candidates (global functions that rebuild a captured container), and `exclude` candidates. Prints a ready-to-paste TOML block; never edits files unasked.
- **`pipist doctor --host-compat [--script inputs.txt]`** — runs the same script in the headless host and in Chromium (Playwright, via the browser backend) and diffs the whitespace-normalized `textContent` of the log region plus the final binding fingerprints; reports first divergence. Used to find shim bugs.

## B1.13 Protocol additions made by this appendix (already merged into A1/A2 in v1.2; kept as a change list)
1. **A1.4 Value tags:** add `{"$t":"dom","id":N}` and `{"$t":"dom","sel":"…"}`, `{"$t":"re","src":"…","flags":"…"}`, `{"$t":"same"}` (only inside deltas, below). `fn` markers are valid in snapshots when the adapter policy is `keep-live`; restore never replaces a live function.
2. **A2.2 `timeline.snapshot.put`:** add `base?: SnapshotId; unchanged?: string[]; format?: string` — `unchanged` lists StatePath prefixes (binding or binding.key) whose value equals the base snapshot's; the `timeline` module reconstructs full state on `timeline.get`. `state` may be a `BlobRef` created by `blob.put_path`.
3. **A2.2 `game.restore`:** add `mode: "reboot" | "in-place"` (kernel→host); host replies `rebooted: boolean`.
4. **A2.2 host notification `game.screen`:** `{ instance; tick; region: string; kind: "status"|"buttons"|"prompt"; text: string; ansi?: string; buttons?: { id; label; enabled }[] }` (in-place regions).
5. **A2.2 `game.output`:** add `ansi?: string` (styled text with escapes).
6. **New namespace `adapter` (served by hosts and browser agents):** `adapter.describe` and `adapter.fingerprint`, specified in A2.16.
7. **A2.9 new `index.transform`:** `{ path: Path; mode?: ("registry")[]; script_index?: number } -> { kind: "script"|"html"; blocks: { index: number; src?: Path; start: Pos; end: Pos; text: string }[]; cached: boolean }` — for `.js` files one block; for `.html` one block per inline script and the list of `src` scripts in document order with their transformed text.
8. **A2.8 new `exp.verify_adapter`:** `{ script: Path | string[]; stride?: number; seed?: number; instance?: InstanceId } -> { ok: boolean; checked: number; first_divergence?: { from_tick: number; tick: number; kind: "state"|"transcript"; paths?: string[]; expected?: string; actual?: string } }`.
9. **A2.2 `game.hello.meta.tick_unit`:** extend the allowed values to `"input" | "call" | "event" | "frame" | "interval" | "step"` (the old `"command"` is an alias of `"input"`).
10. **A2.2 `GameInput`:** add kinds `text`, `click`, `pointer`, `wheel` and `key` fields `code`, `hold_frames`, `hold_ms`; `game.hello.meta.input_kinds` lists what the host can perform; `game.buttons` entries gain `kind`; `HostKind` `"text"` is renamed `"web"`; `game.screen` gains `kind: "summary"`.
11. **Error codes:** add `E_SNAP_TOO_LARGE`, `E_CONST_DIFF`, `E_REG_TDZ`, `E_REG_MISSING` as `data.detail.code` values (not new JSON-RPC codes) and as warning codes in `adapter.describe` (plus `W_INERT_CONTROLS`, `W_TIMERS_DROPPED`, `W_SHIM_MISSING`).

## B1.14 Tests and done-when (additions to M4/M5)
- **Transform:** fixture corpus of ≥ 60 scripts (var/let/const/class/function, destructuring, comma declarators, ASI hazards, regex-vs-division, template literals with nesting, unicode identifiers, trailing `//` comments, `"use strict"`, `eval`, getters, ES module with exports) — transformed output parses, preserves every original line number, registers exactly the expected names, and **behaves identically** (each fixture prints a result to console; outputs compared with/without transform).
- **Shim differential tests:** ≥ 150 small scripts under `tests/dom-diff/` covering every **S** and **L** row of B1.8; each prints JSON; run in Chromium (Playwright) and in the host; outputs must be equal (documented allow-list of known differences, each with a reason).
- **Walker corpus:** ≥ 100 value graphs (cycles, shared refs, Map/Set/Date/RegExp/typed arrays, class instances, accessors, sparse arrays, Symbols, huge arrays, deep nesting to the limit); C++ walker and JS agent walker produce byte-identical Pipist Value JSON; encode → decode → sync round-trips preserve aliasing.
- **Fixtures** (written by the cloud run under `examples/`, each ≤ 600 lines, sharing no code): `hello-js` — text-prompt adventure (rooms, inventory `let`, a `const` state object, class instances, `setTimeout` narration beats, a boot-time `setInterval`, a `;` command chain, `localStorage`); `hello-ui` — ES-module app with buttons and forms and no text prompt (module-private `let` state, event delegation, dynamic controls rebuilt by a `render()` function, `fetch` of a local JSON file); `hello-canvas` — real-time canvas game (`requestAnimationFrame` loop, keyboard and pointer input, a frame-counter spawner, module-level state, seeded `Math.random`). The generic code and defaults must pass all three with no configuration beyond what B1.11 shows.
- **Restore fidelity:** `adapter verify` PASS on all three fixtures (stride 1 for the two input-driven ones, stride 6 frames for `hello-canvas`) and on the owner's Los Ciegos copy (or `UNVERIFIED: game not provided`).
- **Negative tests (each must FAIL, with the stated report):** (a) a `hello-js` variant that hides state in an IIFE closure → `verify` reports a transcript or state divergence; (b) a `hello-canvas` variant whose spawner uses a gameplay `setTimeout` → `W_TIMERS_DROPPED` and a `verify` failure; (c) a variant that stores state in a `#private` class field → reported by `audit` as unreachable state.
- **Performance:** host boot of a 25k-line, 29-script game ≤ 150 ms; fingerprint pass ≤ 10 ms and snapshot capture ≤ 50 ms at 5 MB of state; restore (`reboot`) ≤ 300 ms; host RSS ≤ 80 MB for that game; idle host 0% CPU.
- **Robustness:** random-HTML/JS fuzzing (50k cases) never crashes the host; infinite loop is interrupted by the watchdog and reported; `memory_mb` cap enforced; uncaught exceptions logged with `file:line` links.
- **Done-when (M4):** all three fixtures play through `pipist play` and `game.input` (text lines for `hello-js`; button and click inputs for `hello-ui`; held keys and pointer input for `hello-canvas`); `doctor --host-compat` reports no unexplained differences on all three; strict-mode `adapter audit` on all three reports zero unexplained gaps; region detection and tick-unit resolution give the expected answers on each fixture with no configuration.
- **Done-when (M5 additions):** `adapter verify` PASS on all three fixtures; every negative test above fails as specified, proving the checks have teeth; delta snapshots reduce stored bytes to ≤ 25% of full snapshots over a 200-tick playthrough of `hello-js`.

<!-- SOURCE-END: pipist-spec-b1b-web-host-ui.md -->

---

<!-- SOURCE-BEGIN: pipist-spec-c1-timeline-storage.md -->

# PIPIST SPEC — Appendix C1: Snapshot store and timeline storage (module `timeline`)

Part of Pipist spec v1.3. Makes exact sections 4.6 and 9.1–9.3 of the main spec. Where this appendix and those sections differ, **this appendix wins** (in particular the quota and thinning numbers in 9.1 and the `[snapshot]` table in section 14 are replaced by `[timeline]` in C1.11). Milestone: **M5**. Protocol shapes are in A2.5; additions made here are listed in C1.12. Third-party libraries: SQLite, zstd, xxHash (already admitted for `timeline` in section 15). No others.

## C1.0 Decisions fixed by the owner
1. **Persistence:** timelines persist on disk by default, per project, and survive game exit and daemon restart. Configurable: `[timeline].persist = "project" | "session" | "pinned"` (C1.8).
2. **Size:** the default quota is large enough for 3D/native games (**8 GiB**), configurable, with a free-disk guard (C1.7).
3. **Thinning:** when the quota is approached, **recent snapshots stay dense and older ones become sparse**; bookmarks, pins, fork points and branch heads are never thinned (C1.7).
4. **Branches** are kept until the owner archives or prunes them. Nothing deletes a branch automatically (C1.6).

## C1.1 Model and vocabulary
- **Snapshot:** the complete serialized state of one game instance at one tick, plus metadata. Logically always *full*: there are **no delta chains**. A snapshot is a *manifest* (an ordered list of chunk references); chunks are shared between snapshots by content hash. Deleting any snapshot never invalidates another. (The `base`/`unchanged` mechanism of A2.2 is only a transport optimisation between host and `timeline`; it is resolved at ingest, C1.4.)
- **Chunk:** an immutable byte string (raw length 1 B – 1 MiB), identified by its XXH3-128 hash, stored zstd-compressed (or raw) in a pack file.
- **Branch:** a named line of snapshots with increasing ticks. **Root branch:** no parent; a new one is created every time an instance registers without a restore point (a new *run*). **Fork:** a new branch whose parent is a snapshot of another branch.
- **Forest:** the set of all branches. Roots are grouped by run in the GUI; one project may hold many runs.
- **Protected snapshot:** never removed by automatic thinning (C1.7). Reasons (a snapshot may have several): `bookmark`, `pin`, `fork-root` (a branch was forked from it), `head` (newest snapshot of a branch), `root` (first snapshot of a root branch), `edit-state` (Studio, 13B), `golden` (referenced by an experiment golden or running experiment), `patch-base` (the snapshot taken `before_patch`, newest 20 per instance), `labelled` (has a user label).
- The store is **single-writer**: only the `timeline` module process writes. Other tools use the protocol; `pipist timeline fsck --offline` may open the store only when no daemon holds the lock.

## C1.2 On-disk layout
Default directory `.pipist/timeline/` (override: `[timeline].dir`, absolute or project-relative; `persist = "session"` default is `$XDG_CACHE_HOME/pipist/<project-hash>/timeline/` or `/tmp/pipist-<uid>/<project-hash>/timeline/` if `XDG_CACHE_HOME` is unset). `.pipist/` is added to the project's `.gitignore` by `pipist init` (never edited otherwise).
```
timeline/
  FORMAT            text: "pipist-timeline 1\n"   (reader refuses a higher major, upgrades a lower one with a backup)
  LOCK              flock(LOCK_EX|LOCK_NB) held by the module while running; contents: pid + start time
  meta.db           SQLite 3, WAL mode, synchronous=NORMAL, page_size 4096, application_id 0x50495054 ("PIPT")
  packs/
    pack-000001.pk  append-only chunk containers (C1.3)
    pack-000002.pk
  tmp/              ingest scratch, emptied on start
```
Nothing else is created. All paths inside `meta.db` are relative to the timeline directory.

## C1.3 Pack files and chunks
**Pack file:** header `"PIPK" u8 version=1 u8 reserved[3] u64 pack_id` (16 bytes), then records back to back, no padding. A pack is closed and a new one opened when it reaches `pack_target_mb` (default 256 MiB) or at the first record that would exceed 512 MiB.
**Record:**
```
u32  magic 0x4B484350 ("PCHK")
u8   codec        0 = raw, 1 = zstd
u8   flags        bit0 = dead (set by compaction tombstone; readers ignore bit)
u16  reserved
u32  raw_len      1 .. 1048576
u32  comp_len     bytes of payload (== raw_len when codec 0)
u8[16] hash       XXH3-128 of the raw bytes, little endian
u32  crc32c       of the payload as stored
u8[comp_len] payload
```
All integers little endian. A record is 36 bytes plus payload.
**Compression:** `codec 1` with zstd level `compress_level` (default 3, range 1–19) when `raw_len >= 256`; if the compressed size is `>= 95%` of `raw_len`, store raw. Compression runs on a worker pool (`threads`, default `min(4, cores/2)`, minimum 1). No zstd dictionaries in v1.
**Chunk table (SQLite):**
```sql
CREATE TABLE chunks(
  id      INTEGER PRIMARY KEY,         -- dense, never reused within a store
  hash    BLOB NOT NULL UNIQUE,        -- 16 bytes
  pack    INTEGER NOT NULL,
  off     INTEGER NOT NULL,            -- byte offset of the record header
  raw_len INTEGER NOT NULL,
  comp_len INTEGER NOT NULL,
  created INTEGER NOT NULL             -- unix ms
);
```
**Dedupe:** before writing a chunk the module looks its hash up; a hit with equal `raw_len` is a dedupe (no data written). XXH3-128 is not cryptographic; the 2^-128 collision risk is accepted; `[timeline].verify_dedupe = true` additionally compares the stored crc32c of the existing payload with a fresh one (cheap) for chunks smaller than 64 KiB.
**Read path:** `pread` the record, check `magic`, `crc32c`, lengths, decompress. A mismatch marks the chunk `damaged` (in memory and in `meta.db`) and the snapshots referencing it `damaged` (C1.10). Reads use a 256 MiB chunk LRU cache (`cache_mb`, default 128).

## C1.4 Snapshot formats and chunking
A snapshot's `format` (A2.2 `timeline.snapshot.put.format`; default `web/1` for `kind` `web`/`browser` hosts, `raw/1` for everything else) selects how the state bytes become chunks. The host delivers state either inline (≤ 256 KiB) or as a `BlobRef` created with `blob.put_path`; `timeline` reads the blob, chunks it, then calls `blob.unref` (the store never depends on `.pipist/blobs` afterwards).
| Format | State bytes | Chunking |
|---|---|---|
| `web/1` | One JSON document (B1.3): `{ "format":"web/1", "bindings": { "<file>:<name>": <Value>, … }, "dom": {…}, "timers": […], "meta": {…} }` | **Unit-based.** The document is decomposed into *units*: every `bindings` entry is split one level (`split_depth`, B1.3) into units `("<file>:<name>", "<key>")`; `dom`, `timers`, `meta` are one unit each. Each unit is serialised to canonical JSON (keys sorted, no whitespace, `$t` tags as in A1.4). A unit ≤ 64 KiB is one chunk; a larger unit is cut with content-defined chunking (below, min 2 KiB / avg 8 KiB / max 64 KiB). An unchanged key therefore costs zero stored bytes and zero CPU beyond its hash. |
| `raw/1` | Opaque bytes (native runtimes, FPS state dumps) | **Content-defined chunking** (FastCDC, normalisation level 2): min 16 KiB, avg 64 KiB, max 256 KiB; gear table generated from splitmix64 seeded with `0x9E3779B97F4A7C15` (so chunk boundaries are reproducible across machines). |
| `pages/1` | Fixed-layout memory image (state size is a multiple of `page_kib`, declared in `put.format_args = { page_kib: 4 }`) | **Fixed-size chunks** of `chunk_kib` (default 64 KiB, must be a multiple of `page_kib`); best when a runtime dumps arenas/ECS tables at stable offsets. |
Unknown formats are stored as `raw/1` and keep their `format` string verbatim. `[timeline].format_overrides = { "<host kind>" = "<format>" }` may force a chunker per host kind.
**Manifest.** The result of ingest is a manifest:
```
MF1 := "MF1" u8 version=1 u32 entry_count  entry*
entry := varint path_len, path bytes (UTF-8; "" for raw/pages), varint raw_len, varint chunk_count, varint chunk_id{chunk_count}   (chunk ids as deltas from the previous id in the entry, zigzag-encoded)
```
Stored zstd-compressed in `snapshots.manifest`. `web/1` entries are ordered by `path` (bytewise); `raw/pages` have one entry with empty path. Reassembly concatenates chunks (raw/pages) or rebuilds the JSON document from units in the original order, recorded in a final entry `"$order"` (list of unit paths), so `timeline.get` returns byte-identical state to what was put (a property test checks this).
**Delta transport resolution.** For `put` with `base`/`unchanged`: the module loads the base manifest, copies every entry whose path equals or is under an `unchanged` prefix verbatim, and ingests only the units present in `state`. If the base snapshot is missing/damaged the put fails with `-32002`, and the host (which keeps its last full snapshot id) must resend full state; the host sends a full snapshot every `full_every` puts (default 50) regardless.

## C1.5 Ingest pipeline, backpressure, budgets
1. `timeline.snapshot.put` arrives (kernel forwards from the host). The module checks instance, branch, tick monotonicity (a tick ≤ the branch head's tick → `-32004 invalid_state {state:"tick_not_increasing"}`; the host must have forked first).
2. State bytes are read (blob or inline), chunked, hashed, deduped, compressed and appended to the open pack by the worker pool; the main thread allocates chunk ids and builds the manifest.
3. **Group commit:** the pack is `fdatasync`'d, then one SQLite transaction inserts the new `chunks` rows, the `snapshots` row and updates the branch head. A put is acknowledged **after** the commit. Commits are batched at most every `commit_ms` (default 50 ms) when several puts are in flight; a single put never waits longer than that.
4. Events `timeline.snapshot` (and `timeline.branch` on a new branch) are published after commit.
**Backpressure (the game is never blocked).** The ingest queue holds at most `queue_mb` (default 128 MiB of unprocessed state) and 64 puts. When full, the oldest *policy* snapshot waiting in the queue that is not requested/protected is dropped and counted (`timeline.stats.dropped`); one `timeline.dropped {count, since_tick}` event is emitted per burst. Requested snapshots (reason `request`, `before_patch`, bookmarks, Studio `edit-state`) wait instead of being dropped, up to `put_timeout_ms` (default 20 000), then fail with `-32009`.
**Policy cadence (host side, reported in `game.hello` result):** `every_ticks` is chosen by the host adapter. The module additionally enforces `min_interval_ms` between policy snapshots of one instance (wall-clock; defaults: 0 for `web/1`, 1000 for `raw/1` and `pages/1`); requested snapshots ignore it. A policy put arriving too early is refused with `{accepted:false}` in the result (not an error).
**Size limits:** `max_state_mb` per snapshot (default 2048); above → `-32008 too_large` for that put and a `W_SNAP_TOO_LARGE` warning event, nothing stored.
**Performance budgets (tests, C1.13):** ingest of a 5 MB `web/1` state with 2% of units changed ≤ 30 ms of module CPU and ≤ 40 ms put round-trip; 100 MB `raw/1` with 5% bytes changed ≤ 350 ms with 2 worker threads; `timeline.get` (include `state`) of a 5 MB `web/1` snapshot ≤ 25 ms warm / 80 ms cold; goto resolution (excluding the host's restore) ≤ 50 ms; module idle RSS ≤ 40 MB, RSS during 100 MB ingest ≤ 400 MB; zero CPU when idle.

## C1.6 Metadata schema, tree operations, branches
```sql
CREATE TABLE meta(key TEXT PRIMARY KEY, value);                  -- schema_version, next_branch, next_chunk_pack, last_branch, store_uuid, created
CREATE TABLE runs(id INTEGER PRIMARY KEY, started INTEGER, target TEXT, host TEXT, project_revision TEXT, label TEXT);
CREATE TABLE branches(
  id INTEGER PRIMARY KEY,                       -- BranchId is "b<id>"; never reused
  run INTEGER NOT NULL REFERENCES runs(id),
  parent_snapshot TEXT,                         -- NULL for root branches; kept even if that snapshot is later deleted
  parent_branch INTEGER, parent_tick INTEGER,
  parent_missing INTEGER NOT NULL DEFAULT 0,    -- 1 when the parent snapshot was pruned (tombstone)
  head_snapshot TEXT, head_tick INTEGER,
  created INTEGER NOT NULL, label TEXT, archived INTEGER NOT NULL DEFAULT 0,
  flags TEXT NOT NULL DEFAULT '[]'              -- JSON array: shape-mismatch, studio-play, experiment
);
CREATE TABLE snapshots(
  id TEXT PRIMARY KEY,                          -- "s_" + 16 base32 chars (C1.6.1)
  branch INTEGER NOT NULL REFERENCES branches(id),
  tick INTEGER NOT NULL, parent TEXT,           -- previous snapshot on the same branch (or the fork-root for a branch's first snapshot)
  ts INTEGER NOT NULL, instance TEXT, host TEXT,
  source_revision TEXT, adapter_version TEXT, format TEXT NOT NULL,
  raw_bytes INTEGER NOT NULL, new_bytes INTEGER NOT NULL,   -- new_bytes: compressed bytes of chunks first written by this snapshot
  quiescent INTEGER NOT NULL, shape_hash TEXT, label TEXT, pinned INTEGER NOT NULL DEFAULT 0,
  damaged INTEGER NOT NULL DEFAULT 0, reason TEXT,          -- reason: policy|request|before_patch|bookmark|studio|experiment
  screen_text TEXT, thumb BLOB,                             -- optional: last rendered screen text (<= 4 KiB), PNG thumbnail (<= 64 KiB)
  manifest BLOB NOT NULL                                    -- zstd(MF1)
);
CREATE INDEX snap_branch_tick ON snapshots(branch, tick);
CREATE TABLE bookmarks(name TEXT PRIMARY KEY, snapshot TEXT NOT NULL REFERENCES snapshots(id), note TEXT, created INTEGER);
CREATE TABLE revisions(hash TEXT PRIMARY KEY, created INTEGER, manifest BLOB);   -- source capture (C1.9)
```
**C1.6.1 Snapshot id.** `s_` + first 80 bits of `XXH3-128(branch_id, tick, parent_id, manifest_hash)` base32-encoded (RFC 4648 lower-case, no padding). Identical puts therefore produce the same id; a repeated `put` with the same id is idempotent (returns the existing row). A colliding id with different content (never expected) appends `x` and retries.
**Branch creation rules.**
- `game.hello` without `restore`: new run and new root branch `b<N>`, label `run@<ISO time> <target>`.
- `timeline.goto` with `fork:true` (default): new branch whose parent is the target snapshot; label `fork@t<tick>`; the instance continues on it. With `fork:false`: allowed only when the target is on the instance's current branch and an ancestor of its head (the head pointer is **not** rewound; the next put on that branch would violate monotonic ticks, so the module creates a fork automatically at the next put and labels it `rewind@t<tick>` — the owner never loses the old head).
- A branch gets its first snapshot immediately after restore (reason `request`, `quiescent` as reported), so every branch has ≥ 1 snapshot.
**Current branch.** Per live instance, the branch it is writing to. `timeline.branches.current` returns the branch of the current instance, else `meta.last_branch`. With no live instance, `timeline.goto` starts the branch's target (A2.5 semantics).
**Archive / delete.**
- `timeline.branch.archive {archived:true}`: hidden from default views; its snapshots are still restorable; for thinning purposes its tier schedule is evaluated as if it were the oldest tier (C1.7), still keeping protected snapshots.
- `timeline.branch.delete {branch, cascade?:false}` (new): deletes the branch's snapshots except those that are fork roots of other branches (they stay, protected `fork-root`, owned by their branch tombstone) unless `cascade:true`, which deletes descendants as well. Always ends with GC (C1.7.5). Requires `confirm:true` from clients (the GUI/CLI show the byte count first via `dry_run:true`).
- `timeline.prune {ids}` of a fork-root snapshot is refused (`-32009`, `reason:"fork_root"`) unless `force:true`; with force, child branches get `parent_missing = 1` (tombstone), keeping `parent_snapshot/tick` for display.
**Queries.** `timeline.list` (A2.5) is served from `snapshot_branch_tick`; pagination cursor is `"<branch>:<tick>:<id>"` base64url. `timeline.get {branch, tick}` returns the nearest snapshot **at or before** the tick (`tick` equal preferred), `-32002` if the branch has none. `timeline.diff` loads two manifests and compares unit by unit by chunk id (identical chunk lists ⇒ unchanged without decoding); changed units are decoded and compared structurally to `depth`/`limit`, `web/1` only (`raw/pages` → `-32005 {capability:"structural_diff"}`; they offer byte-range diffs `{ranges:[[off,len]…]}` instead).

## C1.7 Quota, thinning and garbage collection
**C1.7.1 Accounting.** *Usage* = total size of all pack files on disk + `meta.db` + WAL. Dead bytes (unreferenced chunks not yet compacted) count as usage until compaction removes them. The effective quota is
`quota = min(quota_mb, usage_now + free_disk_bytes * max_free_fraction)` where `max_free_fraction` defaults to 0.5, and `free_disk_bytes` is rechecked every 60 s and before large ingests. If free space is below `min_free_mb` (default 1024) the store acts as if usage were at 100% of quota (level L2 below).
**C1.7.2 Defaults** (all in `[timeline]`, C1.11): `quota_mb = 8192`, `thin_start_pct = 80`, `thin_target_pct = 60`, and the tier schedule
```toml
tiers = [
  { within_ticks = 300,    every = 1    },   # newest 300 ticks of each branch: keep everything
  { within_ticks = 3000,   every = 10   },
  { within_ticks = 30000,  every = 100  },
  { within_ticks = 0,      every = 1000 },   # within_ticks = 0 means "everything older"
]
```
*within_ticks* is measured back from the branch head's tick. The ticks of different hosts mean different things (inputs vs frames), so the schedule is per host kind and can be overridden: `[timeline.tiers.frame]` and `[timeline.tiers.input]` (the tick unit reported at `game.hello`; `input`/`call`/`event`/`step` use the default above, `frame` and `interval` default to `[{within_ticks=1800,every=6},{within_ticks=18000,every=60},{within_ticks=0,every=600}]`).
**C1.7.3 Thinning algorithm.** Runs in the module's idle time (at most one run per `thin_interval_s`, default 30, and never while the ingest queue is non-empty), only when usage > `thin_start_pct` of the effective quota, until usage ≤ `thin_target_pct`. Within a run it escalates by levels, re-measuring after each level (after the GC of C1.7.5):
- **L1 — schedule.** For every branch, for every unprotected snapshot, compute its tier by distance from the head. A tier with `every = E` keeps, per bucket `floor(tick / E)`, exactly one snapshot: the one with the **lowest tick in the bucket** (deterministic; running the algorithm twice removes nothing more). Archived branches use the last (oldest) tier for everything beyond their protected snapshots.
- **L2 — coarsen.** Multiply every `every` of every tier by 2, then 4, 8 … up to ×1024, applying L1 again after each step, until usage ≤ target.
- **L3 — drop oldest.** Remove unprotected snapshots in ascending `ts` order (oldest first; ties by tick) in batches of ≤ 5% of snapshots, GC after each batch. One `timeline.quota` event `{level:3, usage, quota}` is emitted per run; a visible warning is raised in the GUI.
- **L4 — hard limit.** If only protected snapshots remain and usage is still > 100% of the effective quota: policy snapshots are refused (`put` returns `{accepted:false, reason:"quota"}`), the event `timeline.quota {level:4}` is emitted, the GUI shows an error badge; requested snapshots and bookmarks still succeed until the physical disk is full (then `-32009`).
Thinning never removes a protected snapshot, never changes a manifest, and is idempotent. A dry run is available: `timeline.prune {dry_run:true}` returns the ids and bytes it would free (estimated from `new_bytes`, exact after GC).
**C1.7.4 Manual prune.** `timeline.prune {policy?, ids?, branch?, dry_run?, force?}` (A2.5): `ids` removes exactly those (unless protected: `-32009` listing the reasons, `force` overrides every reason except `head`, `root` of the current branch); `branch` applies the tier schedule to one branch immediately regardless of usage; `policy` overrides `tiers`/`keep_full` for this call.
**C1.7.5 Garbage collection and compaction.**
- **Mark:** build an in-memory bitmap over `chunks.id` from the manifests of all non-deleted snapshots (decoding MF1 streams; manifests of 100 000 snapshots decode in ≲ 2 s).
- **Sweep:** unmarked chunks younger than `gc_grace_s` (default 600) are kept (in-flight ingests); the others are deleted from `chunks`, and their bytes added to the pack's `dead_bytes` counter (table `packs(id, size, dead_bytes, closed)`).
- **Compact:** a closed pack whose `dead_bytes / size > 0.4` is rewritten (live records copied into the open pack, `chunks.pack/off` updated in one transaction, old file unlinked after commit). At most one pack is compacted per idle period and compaction yields to ingest. `timeline compact --all` forces it.
- GC runs after any prune/thin/delete, once on start when the previous exit was unclean, and when usage exceeds `thin_start_pct` with dead bytes > 10%. It never runs while `put_in_flight > 0`.
**C1.7.6 Per-instance guard.** One instance cannot consume more than `instance_quota_pct` (default 100, i.e. off) of the quota; useful for experiments: experiment runs use their own `experiment_quota_mb` (default 1024) and their branches (flag `experiment`) are deleted automatically when the run is `done` unless `[experiments].keep_branches = true`. (This is the only automatic branch deletion in Pipist, and it applies only to experiment branches.)

## C1.8 Persistence modes and lifecycle
| `persist` | Directory | At daemon/module start | At clean exit | At unclean exit |
|---|---|---|---|---|
| `project` (default) | `.pipist/timeline/` | open, recover (C1.10), continue | flush, close | recovered next start |
| `session` | cache dir (C1.2) | create fresh; any older session dir for this project is deleted | delete directory | deleted at next start |
| `pinned` | `.pipist/timeline/` | open, recover | **prune everything unprotected** (as `timeline.prune` with an empty tier list), GC, compact | recovered; pruned at next clean exit |
- The module starts lazily (3A), so a project that never takes a snapshot never creates the directory. `pipist timeline status` works without loading the module when the directory exists (reads `meta.db` read-only).
- **Projects moved or copied:** `store_uuid` in `meta` identifies the store; `source_revision` and `host` are informational, so a copied `.pipist/timeline/` opens fine on another machine (the store contains no absolute paths).
- **Switching modes** at runtime (`:set timeline.persist=session`) takes effect at the next module start; changing `dir` migrates nothing and warns.
- **Reset:** `pipist timeline reset [--yes]` deletes the store (confirmation required unless `--yes`).

## C1.9 Source capture (what code ran at each snapshot)
Every snapshot records `source_revision` (A1.6 `project.revision`). By default (`capture_source = true`) the module also stores, the first time it sees a revision, a **source manifest**: for every tracked source file (the `index` module's file set, or `[project].sources` globs) its path and the chunk list of its content (same chunk store, `raw/1` chunking; text files below 64 KiB are one chunk), stored zstd-compressed in `revisions.manifest`. Dedupe makes a new revision cost only the changed files. Limits: total tracked source ≤ `source_cap_mb` (default 64); above that capture is skipped for that revision with a one-time `W_SOURCE_TOO_LARGE`. Assets (images, models, audio) are never captured; only files whose extension is in `[timeline].source_exts` (default: `js mjs html css json toml lua c h cpp hpp cc cxx glsl wgsl py md txt`).
This makes the owner's "what code was running back then" answerable without git: `timeline.source.list {snapshot}`, `timeline.source.read {snapshot, path}`, `timeline.source.diff {a, b|"working"}` (unified diff between the sources of two snapshots or against the working tree), and the GUI Timeline panel's "Code at this point" diff. **Pipist never writes old sources back into the working tree by itself**; `pipist timeline source-restore <snapshot> <path>... ` copies selected files out (to the working tree only with `--in-place`; otherwise into a given directory). Revisions are protected from GC while any snapshot references them.

## C1.10 Crash safety, recovery, integrity
- **Write order:** (1) append chunk records to the pack, (2) `fdatasync` the pack, (3) one SQLite transaction (WAL) with chunk rows + snapshot row + branch head. A crash between 2 and 3 leaves unreferenced records (garbage), never dangling references.
- **Start-up recovery:** acquire `LOCK`; if the previous run did not exit cleanly (`meta.clean_exit = 0`): open `meta.db` (SQLite recovers the WAL); for the newest open pack scan records from `packs.verified_off` forward, verifying `magic/crc32c/hash`; truncate the file at the first bad record; delete chunk rows whose record lies beyond the truncation point and mark snapshots referencing them `damaged`; set `clean_exit = 1` only at orderly shutdown (and `0` immediately at start). Recovery of a store with 100 000 chunks must complete ≤ 3 s.
- **`damaged` snapshots:** shown in lists with a flag; `timeline.get`/`goto` on them return `-32004 invalid_state {state:"snapshot_damaged", chunks:[…]}`; they are never used as delta bases; thinning removes them first (L1 treats them as lowest priority). `timeline.fsck {deep?:bool, repair?:bool}` (new): shallow = every manifest decodes and every chunk id exists with an in-bounds record; deep = also reads every record and verifies `crc32c` and `XXH3` of the decompressed data; `repair` marks damaged snapshots, removes dangling rows and compacts. Result: `{ snapshots, chunks, bad_chunks, damaged_snapshots, repaired }`.
- **Disk full (ENOSPC):** the put fails with `-32009 busy {reason:"disk_full"}`, the open pack is truncated to its last good record, and the module enters level L4 (C1.7.3) until space appears. The game is unaffected.
- **Corrupt `meta.db`:** `PRAGMA integrity_check` failure → the module refuses to start (`-32010 module_unavailable {reason:"timeline_store_corrupt"}`), leaves the files untouched, and tells the owner to run `pipist timeline fsck --offline --rebuild`, which reconstructs chunk and snapshot rows from the packs only if a `meta.db.bak` (written at every clean exit and at most hourly while running, kept: last 2) exists; otherwise the packs are reported as unrecoverable data and the owner may `reset`.

## C1.11 Configuration (`[timeline]`, replaces `[snapshot]`)
`[snapshot]` is accepted as an alias for one release and logs a deprecation warning. All keys optional; defaults shown.
```toml
[timeline]
persist = "project"                  # project | session | pinned
dir = ""                             # empty = default for the mode
quota_mb = 8192                      # large enough for native/3D runtimes; raise or lower freely
max_free_fraction = 0.5              # never plan to use more than this fraction of free disk
min_free_mb = 1024
thin_start_pct = 80
thin_target_pct = 60
thin_interval_s = 30
tiers = [ {within_ticks = 300, every = 1}, {within_ticks = 3000, every = 10}, {within_ticks = 30000, every = 100}, {within_ticks = 0, every = 1000} ]
# [timeline.tiers.frame] = [ ... ]   per tick-unit overrides (C1.7.2)
min_interval_ms = { web = 0, raw = 1000, pages = 1000 }
max_state_mb = 2048
full_every = 50                      # host must send a full (non-delta) put at least this often
compress_level = 3
threads = 0                          # 0 = min(4, cores/2), at least 1
pack_target_mb = 256
cache_mb = 128
queue_mb = 128
commit_ms = 50
put_timeout_ms = 20000
verify_dedupe = false
gc_grace_s = 600
instance_quota_pct = 100
experiment_quota_mb = 1024
capture_source = true
source_cap_mb = 64
source_exts = ["js","mjs","html","css","json","toml","lua","c","h","cpp","hpp","cc","cxx","glsl","wgsl","py","md","txt"]
thumbnails = true                    # keep host-supplied thumbnails (PNG <= 64 KiB)
format_overrides = {}
```
Config changes apply live except `persist` and `dir` (next start). `quota_mb = 0` means unlimited (thinning off; the free-disk guard still applies, as does `min_free_mb`).

## C1.12 Protocol additions (to be merged into A2.2 and A2.5)
1. **`timeline.snapshot.put`** gains `format_args?: object` (`{page_kib}` for `pages/1`), `reason?: "policy"|"request"|"before_patch"|"bookmark"|"studio"|"experiment"`, `thumb?: BlobRef` (PNG ≤ 64 KiB) and its result gains `accepted: boolean; reason?: string` (`"quota"|"too_early"`) — `snapshot` and `branch` are present only when `accepted`.
2. **`timeline.branch.delete { branch: BranchId; cascade?: boolean; dry_run?: boolean; confirm?: boolean } -> { removed: number; bytes_freed: number; kept_fork_roots: SnapshotId[] }`.
3. **`timeline.prune`** params gain `dry_run?: boolean; force?: boolean`; result gains `would_remove?: SnapshotId[]` when dry run. **Errors:** `-32009 busy` with `data.reason ∈ {"fork_root","protected","disk_full","quota"}` and `data.protected: {id, reasons[]}[]`.
4. **`timeline.fsck { deep?: boolean; repair?: boolean } -> { snapshots: number; chunks: number; bad_chunks: number; damaged_snapshots: SnapshotId[]; repaired: boolean }`**, **`timeline.compact {} -> { packs: number; bytes_freed: number }`**, **`timeline.reset { confirm: true } -> {}`**.
5. **Source capture:** `timeline.source.list { snapshot } -> { revision: Hash; files: { path: Path; size: number }[] }`, `timeline.source.read { snapshot; path: Path } -> { text: string }` (≤ 4 MiB else `-32008`), `timeline.source.diff { a: SnapshotId; b: SnapshotId | "working"; path?: Path } -> { diff: string; files_changed: number }`.
6. **`SnapshotMeta`** gains `format: string; reasons: string[]` (protection reasons) `; damaged: boolean; has_thumb: boolean; new_bytes: number`; **`BranchInfo`** gains `run: number; parent_missing: boolean; snapshot_count: number; archived: boolean` (replacing the `"archived"` flag).
7. **`timeline.stats`** result gains `dropped: number; dead_bytes: number; usage_bytes: number; effective_quota_bytes: number; level: 0|1|2|3|4; packs: number; persist: string; dir: AbsPath`.
8. **New events:** `timeline.dropped { count, since_tick, instance }`, `timeline.quota { level: 1|2|3|4, usage_bytes, quota_bytes }`, `timeline.pruned { removed: number, bytes_freed: number, cause: "thin"|"manual"|"branch-delete"|"experiment" }`, `timeline.damaged { snapshots: SnapshotId[] }`.
9. **New warning codes** in `data.detail.code` / events: `W_SNAP_TOO_LARGE`, `W_SOURCE_TOO_LARGE`.
10. **CLI:** `pipist timeline status|list|tree|show <id>|goto <id|b:tick>|bookmark|pin|diff|prune [--dry-run]|branch delete|archive|compact|fsck [--deep] [--repair] [--offline]|reset|source ls|cat|diff|source-restore`. All map 1:1 to the methods above; `status` prints usage, quota, level, counts, dedupe ratio, path.

## C1.13 Tests and done-when (additions to M5)
- **Unit — chunkers:** FastCDC boundaries reproducible (golden vectors for three fixed inputs); average chunk size within ±25% of the target on 100 MB of random data; an insertion of 1 byte near the start of a 64 MB buffer changes ≤ 3 chunks; `pages/1` with a single changed page changes exactly one chunk.
- **Unit — store:** round-trip property test (random `web/1` documents and random byte buffers, encode → store → read → byte-identical); dedupe (storing the same state twice adds 0 chunk bytes); manifest encode/decode fuzz; pack record corruption (flip one bit anywhere in a record) detected by `crc32c` and reported as `damaged`, never a crash; truncated pack tail recovered; ENOSPC simulated via a failing writer.
- **Crash tests:** a harness that kills the module (`SIGKILL`) at random points during 500 puts (including between pack sync and SQLite commit) and then restarts it; invariants after every restart: no manifest references a missing chunk, all acknowledged puts are present, unacknowledged ones are absent or complete, `fsck --deep` passes.
- **Thinning:** table-driven tests of the tier schedule (input: list of ticks, tiers, head → expected kept set; including bucket boundaries, protected snapshots, archived branches, idempotence); an escalation test that fills a 64 MB test quota with synthetic snapshots and checks levels L1→L4, that protected snapshots survive every level, that usage ends ≤ `thin_target_pct` when possible, and that the game-side `put` is never blocked more than 5 ms by thinning running in the idle window.
- **Tree:** fork/rewind/archive/delete/prune semantics including tombstoned parents, cascade deletes, `fork:false` auto-fork at next put, concurrent instances on separate branches, experiment-branch auto-delete.
- **Persistence:** `project` mode: kill daemon, restart, list/goto old snapshots (the target game restarts with `restore`); `session`: directory gone after clean exit; `pinned`: only protected snapshots remain after clean exit.
- **Source capture:** two revisions differing in one file add ≤ one file's compressed chunks; `source.diff` equals `diff -u` of the two trees (on text fixtures); cap behaviour; `source-restore` never touches the working tree without `--in-place`.
- **Scale test (nightly, not in the default run):** synthetic 3D-style `raw/1` state of 200 MB with 3% change per snapshot, 1 000 snapshots under a 8 GiB quota: ingest stays within budgets (C1.5), thinning keeps usage under quota, `timeline.get` of any snapshot ≤ 1 s cold, module RSS ≤ 600 MB.
- **Protocol:** all new methods/events have schemas and examples (A2.17).
- **Done-when (M5, storage part):** all tests above pass under ASan/UBSan (except the scale test, which runs once and is reported in `STATUS.md`); `pipist timeline status` and `fsck --deep` pass after the E2E restore/fork suites on all three fixtures; the delta-snapshot size target of B1.14 holds on the stored bytes (`new_bytes` totals); idle CPU 0%.

<!-- SOURCE-END: pipist-spec-c1-timeline-storage.md -->

---

<!-- SOURCE-BEGIN: pipist-spec-d1-gui-framework.md -->

# PIPIST SPEC — Appendix D1: GUI framework (window anatomy, chrome, theme, workspaces, common patterns)

Part of Pipist spec v1.3. Makes exact sections 13.3–13.5 and 13.9 of the main spec for everything that is **not** one specific panel. Appendix D2 and D3 specify every panel one by one and **depend on the patterns defined here**. Input handling is 13C (normative); protocol is Appendix A; viewport is 13A; Studio is 13B. Where this appendix and section 13 differ, **this appendix wins**. Milestone: **M6** (Studio panels in M9, as in section 17).

## D1.0 Decisions fixed by the owner
1. **Visual style:** two themes sharing identical layouts. The first one built, and the framework everything else is tuned on, is **`term`** (terminal-flavoured: monospace everywhere, flat, dense, thin borders, mode-coloured status bar). The second, **`ide`** (proportional UI font, tab icons, more padding), is a *theme-only* addition: it may change tokens (D1.9) and font choice, never panel structure or key bindings. `ide` is built only after every M6 done-when item passes with `term`; if budget runs short it is cut and listed under "Not done" in `STATUS.md`.
2. **Timeline:** a slim always-on strip above the status bar in every workspace (D1.5); the full Timeline panel opens from it.
3. **Default `edit` workspace:** editor left, game right, bottom drawer below (D1.7.1).
4. **Detail:** every panel gets a wireframe, widgets, data source, keys, and empty/loading/error states (D2, D3).

## D1.1 Metrics: the cell grid
The `term` theme is laid out on a **cell grid** so that wireframes in this spec are exact.
- `cell_w` = advance width of `0` in the monospace font; `cell_h` = font line height (font size × 1.25 rounded up to a whole pixel, default font size 14 px → `cell_h` 18 px, `cell_w` ≈ 8 px). All paddings, panel title bars, tab rows, list rows and the status bar are whole multiples of `cell_h`/`cell_w`.
- **Row heights:** panel title bar 1 row; tab strip 1 row (merged into the title bar when a dock area has more than one tab); list/table row 1 row; toolbar 1 row; status bar 1 row; timeline strip 1 row; command line 1 row; filter row 1 row.
- **Borders:** 1 px lines in `border` colour; the focused panel's border uses the current mode colour (D1.3). No shadows, no rounded corners (`rounding = 0` in `term`), no gradients, no animations except the terminal cursor blink and the busy spinner (a 4-frame ASCII spinner `|/-\`, advanced at 8 Hz **only while something is pending**).
- **Padding:** content padding inside panels is `0.5 cell_w` horizontally and 0 vertically, except forms (Inspector, dialogs), which use 1 `cell_w` / 0.25 `cell_h` item spacing.
- **DPI:** `[gui].scale` (default 1.0, or `SDL_GetWindowDisplayScale`) multiplies the font size; the grid scales with it. Minimum main window size 640×360 px; below that the layout stays but docks collapse to tabs (D1.7.4).
- The `ide` theme sets `cell`-based snapping off (`grid = false`) and uses 1.15× row height; panels must not assume the grid except where this spec states cell counts.

## D1.2 Main window anatomy
```
+--------------------------------------------------------------------------------------------+
| [editor] [game]*              | tab strips are per dock area, merged with panel title bars    |
+--------------------------------------------------------------------------------------------+
|                          DOCK SPACE (panels, splits, tab groups)                           |
|                                                                                            |
+--------------------------------------------------------------------------------------------+
| : command line / message area (1 row; hidden unless active or a message is showing)        |
| TL b3 fork@t200 [|---*-----B-----@=======>|] t412/980 q  3bm         (timeline strip, 1 row)|
| NORMAL  edit | b3 t412 | hello-js running | E0 W2 | mods 3 41MB                  12:04       |
+--------------------------------------------------------------------------------------------+
```
- **No menu bar and no toolbar at window level** (keyboard- and command-driven). Every action is reachable through `:` commands, the leader menu and the command palette (13.3). A **hamburger glyph `≡`** at the right end of each panel title bar opens that panel's context menu (D1.3).
- The vertical order is fixed: dock space, command line row, timeline strip, status bar. The command line row is **collapsed to 0 rows** when idle; opening it pushes the dock space up by one row (no overlay) so nothing is hidden. Messages replace it for 4 s (13C.3).
- **Pop-out windows** (OS windows) have the same anatomy minus the timeline strip and status bar: a pop-out shows a 1-row **mini status** with the mode indicator at left, the panel title, and a `dock back` hint at right; its command line row opens at its bottom (13C.3).
- `[gui].timeline_strip = true|false` and `[gui].statusbar = true|false` hide the strips (`focus-game` hides both, D1.7.1).

## D1.3 Panel chrome
**Title bar** (1 row), left to right: `<icon> <title>` · `<state badge>` · spacer · `[⧉] [≡] [✕]`.
- `icon`: one cell; in `term` an ASCII/Unicode glyph from the table in each panel (e.g. `λ` editor, `▶` game, `≡` log); in `ide` an icon-font glyph. Icons are never required to understand a panel (the title says everything).
- `state badge`: short coloured text drawn from the panel's own state: e.g. `follow`, `paused`, `filtered 12/340`, `stale`, `not loaded`, `disconnected`, `viewing s_ab12 (not live)`.
- `[⧉]` pop out / dock back, `[≡]` context menu, `[✕]` close. Double-clicking the title bar toggles pop-out (13.3).
- When a dock area holds several panels, the title bar becomes a **tab strip**: each tab is ` <title> ` with the active tab drawn in `tab_active` colours; the three buttons stay at the right; a tab shows a `●` after its title when the panel has unseen changes that matter (new error in Log, new problem), a `!` for a failed state. Middle-click closes a tab; dragging reorders or tears it off.
- **Focus indication:** the focused panel's 1 px border and its title-bar background use the current **mode colour** (D1.9); unfocused panels use `border`. Exactly one panel is focused per OS window.
- **Context menu (`≡`)** items common to all panels: `Pop out / Dock back`, `Duplicate` (only if `allow_multiple`), `Move to window ▸`, `Close`, then panel-specific items (listed per panel in D2/D3), then `Help for this panel` (opens `:help panel <id>`).
- Tooltips appear after 600 ms of hover, one row, never for items whose label already says the same.

## D1.4 Status bar
One row, three zones. Segments are separated by ` | ` in `term` (thin vertical rules in `ide`). Segments, left to right; each is clickable (the click action is listed):
| # | Segment | Content | Click |
|---|---|---|---|
| 1 | Mode | ` NORMAL `/` PASSTHROUGH `/` COMMAND `/… on a mode-coloured background (13C.1) | Opens `:help keys` |
| 2 | Workspace | `edit` | Opens the workspace switcher |
| 3 | Timeline | `b3 t412` (branch, tick of current instance; `—` when none) | Opens the Timeline panel |
| 4 | Instance | `<name> <state>`, state coloured: running green, paused yellow, restoring cyan, crashed red; `no game` dim | Opens the Game view; right-click → instance list |
| 5 | Diagnostics | `E2 W5` (counts from `diag`; hidden if module not loaded and no data) | Opens Problems |
| 6 | Patch | `patch:T1` last tier, `held` if a patch is pending, hidden otherwise | Opens Patches |
| 7 | Modules | `mods 3 41MB` (loaded modules, total RSS of kernel + modules) | Opens Modules |
| 8 | Messages | the most recent warning/error message for 10 s, then empty | Opens `:messages` |
| 9 | Clock | `HH:MM` | none |
Truncation (narrow windows): drop in this order 9, 7, 6, 3, 2, 5, 8; segments 1 and 4 are never dropped. Segment 4 shortens to `<state>` only before it is dropped. A `quota` warning (C1.7) or a failing module adds a red `!` at the very right, which opens the Modules panel.

## D1.5 Timeline strip
One row above the status bar (D1.2). Content, left to right: label `TL`, branch name (`b3`, plus label if any, truncated to 14 cells), `[` scrub bar `]`, `t<tick>/<head tick>`, quiescence marker, bookmark count.
```
TL b3 fork@t200 [|---*-----B----@========>|] t412/980 q 3bm
```
- **Scrub bar**: fills the remaining width (min 20 cells; below that, hidden). Left end = first snapshot on this branch, right end = head. Glyphs: `-` snapshot density (one cell per equal tick range), `*` snapshot at which a patch was applied, `B` bookmark, `|` fork point (a child branch begins there), `@` the **live** tick of the current instance, `=` ticks between the live position and the head when the instance is behind it (after a rewind), `x` a damaged snapshot. In `ide` the same markers are drawn as small shapes.
- **Mouse:** hover shows a tooltip `t<tick> · s_ab12 · 14:03:21 · bookmark "pre-fight"`; **click** sets a *preview* position (below); **double-click** or `Enter` = `timeline.goto` with fork and reload `auto`, after a confirmation toast `Fork at t300? [Enter] yes [Esc] no` when `[timeline].confirm_goto = true` (default true); **right-click** → menu: `Bookmark here…`, `Pin`, `Fork here and run with current code`, `Diff with live`, `Show in Timeline`; **drag the `@`** = scrub; **wheel** = ±1 snapshot.
- **Preview** = viewing a snapshot without restoring. While a preview position is set, the strip shows `PREVIEW s_ab12 t300 · Enter goto · Esc back`, the State inspector shows that snapshot (badge `viewing s_ab12 (not live)`), Where shows its trace if available, and the Game view is untouched. `Esc` clears the preview.
- **Keys** (gui-normal, global): `<Leader>tt` open Timeline panel; `t[` / `t]` previous/next snapshot (sets preview and moves it); `<Leader>tg` prompts `:goto t`; `<Leader>tb` bookmark prompt; `<Leader>tf` fork here (uses preview position if set, else live tick).
- States: no timeline module loaded and no store → strip shows `TL (no snapshots)` dim; module loading → spinner; `quota` level ≥ 3 → the label turns `warn`, level 4 → `error` with `FULL` text.

## D1.6 The bottom drawer and the console drawer
- The **bottom drawer** is simply a dock area at the bottom of the main window holding tabbed panels (default Log, Problems, Search). Height persists per workspace; default 26% of the window height, min 3 rows, max 70%. Toggle: action `drawer.toggle` (`<Leader>dd`); focus drawer: `<Leader>df`; `<Leader>dl/dp/ds/dc` activate the Log/Problems/Search/Console tabs, opening the drawer if collapsed. A collapsed drawer shows a 1-row stub with its tab names and unseen-change dots.
- The **Console drawer** (backtick key, D2.5) is an overlay on top of whatever is focused, 40% of window height, anchored at the bottom above the command-line row; it never changes the dock layout. Closing it restores focus to the previously focused panel.
- Two drawers never stack: opening the Console drawer while the bottom drawer is expanded draws the console over it.

## D1.7 Workspaces and the layout file
A **workspace** is a named dock layout plus per-workspace settings. Shipped files: `layouts/edit.toml`, `debug.toml`, `play.toml`, `studio.toml`, `experiment.toml`, `focus-game.toml`. User/project overrides live in `~/.config/pipist/layouts/` and `<project>/.pipist/layouts/` (later wins by name); `:ws save <name>` writes the current arrangement to the project layer.
```toml
name = "edit"
title = "Edit"
statusbar = true
timeline_strip = true
[[window]]                           # first window is always "main"
id = "main"
rect = []                            # empty = default maximised-ish size; else [x, y, w, h] in px
[window.dock]                        # a dock NODE; recursive
split = "v"                          # "h" = a left | b right, "v" = a top / b bottom
ratio = 0.74                         # fraction of the space given to a
a = { split = "h", ratio = 0.55, a = { tabs = ["editor"] }, b = { tabs = ["game"] } }
b = { tabs = ["log", "problems", "search"], active = 0, drawer = true }
[[window]]                           # optional extra OS windows (pop-outs), same shape
id = "win2"
rect = [1920, 0, 1000, 700]
[window.dock]
tabs = ["state"]
[panel.editor]                       # per-panel saved settings (opaque to the layout loader; panels read their table)
files = []
```
- **Dock node** grammar: `node := { tabs = [panel-id, …], active = <index> , drawer? = bool } | { split = "h"|"v", ratio = <0.05..0.95>, a = node, b = node }`. `drawer = true` marks the node that `drawer.toggle` collapses (at most one per window).
- Panel ids that are not available (module not installed) load as stubs (3A.11). Unknown ids are dropped with a warning in Problems (`source = layout`). The loader rejects: ratios outside 0.05–0.95, tabs lists that are empty, depth > 8, duplicate panel ids in one layout unless the panel has `allow_multiple` (then `id#2`).
- Saved geometry: sizes are stored as ratios (not pixels), so layouts survive resolution changes; OS window rects are stored per monitor name and clamped to visible monitors on load.
- **Switching** workspaces keeps panel *instances* alive (editor PTY, terminal, game view) when the same panel id is present in the target layout; panels not present are hidden (not destroyed) for `[gui].hidden_panel_ttl_s` (default 300), then destroyed.

### D1.7.1 Shipped layouts (wireframes at ~120×34 cells)
**edit** (default):
```
+--------------------------------------+--------------------------------------+
| λ editor  [⧉≡✕]                      | ▶ game: hello-js  running  [⧉≡✕]     |
|                                      |                                      |
|   nvim in a terminal pane (55%)      |   game view (45%)                    |
|                                      |                                      |
+--------------------------------------+--------------------------------------+
| Log | Problems● | Search     drawer 26%                              [⧉≡✕]   |
|   log lines …                                                                |
+------------------------------------------------------------------------------+
| (cmdline) / TL strip / status bar                                            |
```
**debug** — left column game (top) over `where`/`log` tabs (bottom); right column `state` (top, 55%) over `timeline`/`patches` tabs (bottom); no drawer:
`{split="h", ratio=0.45, a={split="v", ratio=0.5, a={tabs=["game"]}, b={tabs=["where","log"]}}, b={split="v", ratio=0.55, a={tabs=["state"]}, b={tabs=["timeline","patches"]}}}`
**play** — the game fills the window; the drawer is collapsed (stub row visible); Console drawer is the main interaction besides the game:
`{split="v", ratio=0.96, a={tabs=["game"]}, b={tabs=["log","problems"], drawer=true}}` with the drawer collapsed at load (`collapsed = true` is a valid key on a `drawer` node).
**studio** (Studio, 13B) — hierarchy left, viewport centre, inspector/tweakables/definitions right, assets/log/problems bottom:
`{split="v", ratio=0.72, a={split="h", ratio=0.18, a={tabs=["hierarchy"]}, b={split="h", ratio=0.78, a={tabs=["viewport"]}, b={tabs=["inspector","tweakables","definitions"]}}}, b={tabs=["assets","log","problems"], drawer=true}}`
**experiment** — experiments left (60%); right column log (top) over timeline (bottom):
`{split="h", ratio=0.6, a={tabs=["experiments"]}, b={split="v", ratio=0.5, a={tabs=["log"]}, b={tabs=["timeline"]}}}`
**focus-game** — one panel, `statusbar = false`, `timeline_strip = false`, the title bar collapsed to a 1-row mini bar that appears only while the pointer is within 1 row of the top edge or the mode is not `viewport-play`/`passthrough`; `<Leader>wf` toggles, `<Esc><Esc>` or the release hotkey (13A.5) leaves `viewport-play` first.

### D1.7.2 Panel visibility rules
Opening a panel that is not in the current layout (`:panel <id>`): if it has a `default_dock` (D2/D3 headers) it is added as a tab to the dock area of the node holding the panel named by `default_dock` (e.g. `drawer`, `main-right`, `main-left`); otherwise to the focused dock area. `allow_multiple` panels (Terminal, Log, Search, Game view) open a new `id#n` each time.

### D1.7.3 Focus movement
`<C-w>h/j/k/l` (13C.5) moves focus to the geometrically nearest dock area in that direction (distance = centre-to-centre along the axis, tie → the area containing the previously focused panel's last row); wraps never. `<Leader><Leader>` (alternate panel) swaps between the last two focused panels. A pop-out window is reachable by `<C-w>w` (cycle) or the switcher.

### D1.7.4 Small windows
Below 100×30 cells the dock tree is unchanged, but panels with fewer than 20×5 cells show a single-row stub `<title> (too small)`. Below 640×360 px a banner row says `window too small` and keys still work.

## D1.8 Common panel patterns (D2/D3 refer to these by name)
**P1 Panel header rows.** Most list panels have, under the title bar: an optional **toolbar row** (buttons as `[ label ]`, toggles as `[x] label`, drop-downs as `label▾`; keyboard-reachable through the panel's keys; the toolbar never wraps — items that do not fit move to the `≡` menu in order of right-to-left) and an optional **filter row** (a single-line `ViInput` shown after `/` is pressed, with the prompt `/` and a match count at the right `12/340`; `Esc` clears; the filter text is saved per panel).
**P2 Lists and tables** are virtualised (100k+ rows), one row per item, selected row in `selection` colours, keyboard navigation per 13C.9; columns have fixed or percentage widths declared per panel; a table header row (1 row, `header` colours) is clickable to sort where the panel says so (sorted column shows `▲`/`▼`); column separators are a single space plus `│` in `border_dim`. Long text is truncated with `…` at the right (middle for paths: `src/…/combat.js`); the full text is in the tooltip and in `yy`/`yp` copy.
**P3 Trees** use `▸`/`▾` (ASCII `>`/`v` when `[gui].ascii = true`), two cells of indent per level, the 13C.9 keys, and lazy-load children on first expand.
**P4 Link text.** Text of the form `path:line[:col]` is a **link** (underlined on hover; `<CR>` or click → `editor.goto`). `0x…`/URLs follow the same rule (URLs open via `[gui].open_url` command). Links are produced by Log, Problems, Search, Where, Console output, Patches, Timeline source diff.
**P5 Standard states.** Every panel implements these, drawn centred in the panel body, dim, one to three rows:
| State | Text (template) | Actions |
|---|---|---|
| `module-not-loaded` | `<Title> — module <name> not loaded` + `[Load] [Always load]` | `<CR>` loads, `a` always-load (3A.11) |
| `loading` | `<spinner> loading …` (spinner only after 150 ms) | none |
| `empty` | the panel's own empty text + one hint line | as listed per panel |
| `no-instance` | `no game running` + `[Run target…]` | `<CR>` opens `:run ` prefilled |
| `disconnected` | `daemon disconnected — reconnecting (attempt n)` | automatic every 1 s up to 60 s, then `[Retry]` |
| `unsupported` | `<feature> not supported by this host (<capability>)` | none |
| `error` | the error message from the protocol error (`data.kind` + `message`), red, plus `[Retry]` (`r`) and `[Copy error]` (`yy`) | `r` retries |
`no-instance` applies to panels whose data needs a running instance; panels that can show stored data (Timeline, State with snapshot preview, Log) show stored data instead and put `(no live game)` in the badge.
**P6 Selection and copy.** Mouse drag selects text in text-like panels (Log, Console, Output peek, Game view terminal); `y` in list panels copies per 13C.9. Copy always goes to the `"+` register and the system clipboard.
**P7 Context menus** are lists of `label  key-hint`, opened by right-click or `m` (list panels); `j/k/<CR>/<Esc>`; the key-hint column shows the leader or panel key for that action.
**P8 Confirmation** for destructive actions (delete branch, revert patch, clear log): a one-row inline prompt at the bottom of the panel `Delete branch b3 (412 snapshots, 38 MB)? [y/N]`; any key other than `y` cancels. No modal dialogs for confirmations.
**P9 Modals** exist only for: first-run welcome, errors needing acknowledgement (crash report), file-conflict resolution (`file changed on disk`), and the quit prompt when processes with `tags = ["keep"]` are running. A modal dims the window, takes focus, closes with `Esc`.
**P10 Toasts**: top-right stack of ≤ 4 one-row notifications (info 3 s, warn 6 s, error stays until dismissed with `x` or click), from `gui.notify` and from events (patch applied/failed, module crashed, quota level ≥ 3). Never steal focus.
**P11 Busy indicators**: a request pending > 250 ms shows the ASCII spinner in the panel title bar badge; > `timeout_ms` shows the error state.
**P12 Persistence**: each panel persists its UI state (filters, sort, expanded nodes up to 200, scroll anchor) through `onSerialize` into the layout file's `[panel.<id>]` table; restoring on load must not trigger protocol calls beyond the panel's normal refresh.

## D1.9 Theme tokens and the `term` palette
A theme file (`themes/<name>.toml`) defines `[meta]`, `[font]`, `[metrics]`, `[colors]` and `[glyphs]`. **Every colour in the GUI comes from a token**; hard-coded colours are forbidden outside the theme loader (a lint test greps for `ImColor(`/hex literals outside `pipist-ui/theme`).
Tokens (all required): `bg`, `bg_alt` (inactive panels, stripes), `bg_input`, `fg`, `fg_dim`, `fg_bright`, `border`, `border_dim`, `selection_bg`, `selection_fg`, `header_bg`, `header_fg`, `tab_active_bg`, `tab_active_fg`, `tab_inactive_bg`, `tab_inactive_fg`, `accent`, `link`, `ok`, `warn`, `error`, `info`, `hint`, `diff_add`, `diff_del`, `diff_change`, `match_bg` (search match), `cursor`, `scrollbar`, `scrollbar_hover`, the eight mode colours `mode_normal`, `mode_passthrough`, `mode_command`, `mode_search`, `mode_leader`, `mode_insert`, `mode_viewport_edit`, `mode_viewport_play`, the log level colours `log_trace`…`log_error`, and the 16 ANSI colours `ansi_0`…`ansi_15` plus `ansi_fg`, `ansi_bg` used by `TerminalView`.
**`term` default palette** (dark; chosen for contrast ≥ 4.5:1 between `fg` and `bg`, checked by a unit test):
| Token | Hex | Token | Hex |
|---|---|---|---|
| `bg` | `#1b1d1f` | `fg` | `#d4d0c8` |
| `bg_alt` | `#222527` | `fg_dim` | `#8a877f` |
| `bg_input` | `#15171a` | `fg_bright` | `#f2eee6` |
| `border` | `#4a4e52` | `border_dim` | `#2f3336` |
| `selection_bg` | `#3a4a5a` | `selection_fg` | `#f2eee6` |
| `header_bg` | `#2a2d30` | `header_fg` | `#bdb9b0` |
| `accent` | `#7aa2d0` | `link` | `#7fb8c8` |
| `ok` | `#8fb573` | `warn` | `#d9a441` |
| `error` | `#d9605a` | `info` | `#7aa2d0` |
| `mode_normal` | `#7aa2d0` | `mode_passthrough` | `#8fb573` |
| `mode_command` | `#d9a441` | `mode_search` | `#b784c9` |
| `mode_leader` | `#d9824a` | `mode_insert` | `#6fb8a8` |
| `mode_viewport_edit` | `#9a86d0` | `mode_viewport_play` | `#d9605a` |
Status-bar mode segments use `mode_*` as background with `bg` as text. The 16 ANSI colours follow the usual xterm-like dark mapping chosen by the implementer and recorded in the theme file. `light` and `high-contrast` themes keep the same token names; `ide` adds `[font].ui` (proportional) and `[metrics].row_scale = 1.15`, `rounding = 3`.
**Fonts:** `term` uses only the monospace font for everything, regular and bold weights (italic optional); fallback chain for missing glyphs: monospace → a symbols font subset (box drawing, arrows, geometric shapes, `⧉ ≡ ✕ ▸ ▾ ● ▶ ⏸` etc.). `[gui].ascii = true` forces ASCII-only glyphs (`[glyphs]` table maps each symbolic glyph name — `expand`, `collapse`, `close`, `popout`, `menu`, `dot`, `play`, `pause`, `warn`, `check`, `cross`, `arrow_right` — to a Unicode and an ASCII form). Glyph names, not literal characters, are used in code.

## D1.10 Overlays: switcher, which-key, palette, output peek, help
Specified behaviourally in 13C; their **geometry** here:
- **Which-key popup:** anchored bottom-centre above the command-line row, width = min(window − 4 cells, 100 cells), columns of `key  label` at 28 cells each, up to 6 rows, border in `mode_leader`, header row `LEADER  g  game`.
- **Buffer switcher:** centred, width min(80% of window, 100 cells), height min(60% of window, 24 rows): input row, category chips row, result list with the columns of 13C.5; border `mode_search`.
- **Command palette** (`<C-S-p>`): same geometry as the switcher with a mode-leader border; rows `title  [key hint]  (kind)`; kinds: action, file, symbol, entity, bookmark, experiment, module, panel, setting.
- **Output peek:** bottom dock-independent panel above the command-line row, height ≤ 40% (13C.3), border `info`.
- **Completion popup** (command line): above the command-line row, left-aligned to the start of the argument being completed, ≤ 10 rows, shows `candidate  detail` with the typed prefix highlighted in `accent`.
- **Help** (`:help …`): a normal panel `help` (id `help`, `allow_multiple` false) with `CodeView`-style rendering of Markdown subset (headings, lists, tables, code spans); content comes from `docs/help/*.md` plus generated pages for keys/commands/actions (13C.7).

## D1.11 Notifications from the daemon, reconnects and crashes
- GUI ↔ daemon: if the connection drops, every panel shows state `disconnected` (P5) and the status bar shows `OFFLINE` in `error` in segment 4; the GUI keeps its layout and local state and reconnects with exponential backoff 250 ms → 4 s (cap), replaying subscriptions with `since_seq` (A1.5) so panels catch up without a full reload.
- If the daemon is not running at GUI start: `pipist-gui` starts it (`pipistd --project <dir>`, detached) unless `--no-daemon`; the first-run flow shows a one-time welcome modal listing the profile in use and how to open the command line.
- Module crash: toast `module <name> crashed — restarting (2/5)`; the panels of that module show `error` state until it is `ready` again; after `failed`, the panel shows `module <name> failed: <last_error>` with `[Retry load]`.
- GUI crash: the next start offers `Restore last layout` (default) — the layout file is written atomically every time the layout changes, debounced 2 s.

## D1.12 GUI testing hooks (all panels must work with them)
- `--dump-layout` prints the dock tree as the TOML grammar of D1.7. `--dump-ui` prints, per visible panel, rows of visible text (post-truncation) and widget kinds; `gui.dump {what:"ui"}` returns the same. Golden dumps live under `tests/gui/golden/<workspace>.<state>.txt`.
- `--fake-daemon <fixtures dir>` replays recorded JSON-RPC fixtures (`*.jsonl`: request pattern → response, plus timed events) so every panel can be rendered in every state of P5 without a game. Each panel ships fixtures for: normal, empty, loading (response delayed 5 s), error (`-32011`), no-instance, module-not-loaded, disconnected.
- `--script <file>` drives keys (`gui.keys`) and actions; `--screenshot out.png --after-frames N`; `--video offscreen` for CI. A screenshot test passes when the image is non-blank, has ≥ 3 distinct colours inside the dock area, and the text dump matches the golden.
- **Idle test:** after layout load and 2 s settle, no frame is drawn in 10 s with a fixture daemon streaming nothing; with the strip showing a live tick, frames are drawn only when the tick changes (≤ 30/s).
- **Contrast test:** `fg` over `bg`, `fg_dim` over `bg`, every `mode_*` over its status-bar text (`bg`) all ≥ 4.5:1; `border` over `bg` ≥ 1.8:1.

## D1.13 Config keys added
```toml
[gui]
theme = "term"                    # term | ide | light | high-contrast | <user>
workspace = "edit"                # initial workspace (also [startup].workspace)
scale = 0                         # 0 = from display, else multiplier
ascii = false
font_size = 14
timeline_strip = true
statusbar = true
confirm_goto = true               # (also [timeline].confirm_goto)
hidden_panel_ttl_s = 300
drawer_height_pct = 26
open_url = "xdg-open"
focus_hide_chrome = true
popout = "os_window"              # os_window | floating (13.3)
```

<!-- SOURCE-END: pipist-spec-d1-gui-framework.md -->

---

<!-- SOURCE-BEGIN: pipist-spec-d2-panels-work.md -->

# PIPIST SPEC — Appendix D2: Panels, part 1 (writing, running and finding things)

Part of Pipist spec v1.3. Continues Appendix D1 (read it first: cell grid D1.1, chrome D1.3, patterns P1–P12 in D1.8, states in P5, theme tokens D1.9). Each panel below has: **header** (id, module, icon glyph, default dock, `allow_multiple`), **wireframe**, **contents**, **data**, **keys** (scope `panel:<id>`; list navigation keys of 13C.9 are implied for every list/tree panel and are not repeated), **context menu**, **states**, **tests**. Panels: Editor, Game (terminal), Game (viewport), Game (browser), Console drawer, Log, Problems, Search, Files, Outline, Terminal, Processes. Appendix D3 covers the rest.

Conventions: `→` means "calls"; events are listed under *data*; "refresh" means re-call after any listed event, coalesced to ≤ 10 Hz. Key notation is 13C.8. All default keys below are ordinary keymap entries (mode `gui-normal`, scope `panel:<id>`), so they are remappable and appear in `:help keys`.

---
## D2.1 Editor
**Header:** id `editor` · module builtin `editor` · icon `λ` · default dock `main-left` · `allow_multiple` false.
```
+- λ editor  main.js [+]  tab 1/2 ----------------------------------- [⧉][≡][✕] -+
| (libvterm terminal running nvim; nvim draws its own tabline/statusline/cmdline)  |
|  12  function attack(src, dst) {                                                  |
|  13    const roll = rrand(20);                                                    |
+----------------------------------------------------------------------------------+
```
- **Contents:** one `TerminalView` filling the panel (no extra rows) attached to the nvim PTY (13.6). The **title bar badge** shows the current file (project-relative, middle-truncated), `[+]` when modified, and `tab i/n` when nvim has several tabpages. GUI tabs mirror nvim tabpages only when `[editor].mirror_tabs = true` (default false; nvim's own tabline is authoritative).
- **Focus:** clicking or activating the panel enters `passthrough` (13C.2). Every key goes to nvim except the prefix.
- **Data:** `editor.start`, `editor.attach`; events `editor.cursor` (status badge), `editor.saved`, `editor.buffers`, `editor.attached/detached`; `proc.exited` for the nvim process.
- **Behaviours:** `editor.goto` from any panel focuses the Editor panel, opens the file at line:col, and flashes the target line with `match_bg` for 600 ms via the injected Lua (`nvim_buf_add_highlight`). If the Editor panel is not open it is opened in `main-left` first. File changed on disk while the buffer is clean → nvim `:checktime` (the `watcher` event triggers it); while dirty → a P9 modal is **not** used; nvim's own prompt handles it.
- **Keys (gui-normal only, since terminal keys go to nvim):** `<CR>` enter passthrough; `r` restart nvim (keeps the buffer list via `:mksession` to `.pipist/editor/session.vim` when `[editor].restore_session = true`, default true); `o` open file prompt (`:e `).
- **Context menu:** `Restart editor`, `Open session file`, `Copy current path`, `Reveal in Files`.
- **States:** `nvim-missing` (nvim not on `PATH`): body shows `nvim not found` + the install hint for the detected distro + `[Use $EDITOR]` and a read-only `CodeView` fallback of the last focused file; `exited` (nvim quit): `editor exited (code n)` + `[Restart] r`; `starting` spinner; `error`.
- **Tests:** fake-PTY test that the grid size passed to the PTY equals `floor(panel_px / cell)`; `editor.goto` flash; nvim missing path; `restart` restores buffers (needs nvim; Unverified if absent).

## D2.2 Game view (terminal)
**Header:** id `game` · module `game` + host · icon `▶` · default dock `main-right` · `allow_multiple` true (`game#2` for a second instance).
```
+- ▶ game: hello-js  running  t412 ---------------------------------- [⧉][≡][✕] -+
| [ Pause ] [ Step ] [ Reload ] speed 1.0x▾  [Edit|Play]     <- toolbar (P1)       |
| HP 14/20  Day 3  $ 41                                      <- status regions      |
| You enter the cellar. It smells of rust.                   <- log region          |
| > look                                                                            |
| 1:Look 2:Inventory 3:Search 4:Leave                        <- buttons bar         |
| > _                                                        <- prompt line         |
+----------------------------------------------------------------------------------+
```
- **Contents:** (1) toolbar row; (2) `TerminalView` rendering the host's screen model (B1.9): status regions on top, scrollback in the middle (scrollable with the wheel, `<C-u>/<C-d>`, `gg/G` in gui-normal), buttons bar (clickable; numbered `1`–`9`), prompt line when a text prompt exists. For summary-mode games (canvas) the terminal shows the summary block and the toolbar adds `Hold key▾` and a `Pointer` box (D2.2.1).
- **Prompt line input:** a `ViInput` (13C.4) styled as the terminal prompt; `<CR>` → `game.input {kind:"line"}`; history per instance in `.pipist/history/game-<target>` (max 1000, `<Up>/<Down>`). While focused the mode is `insert`-like but shown as `GAME` in the status bar with `mode_insert` colour; `<Esc>` leaves to `gui-normal` (13C.1). `<A-1>…<A-9>` press numbered buttons. Raw keys to the page are only sent with `[host.web].bypass_game_input=false`.
- **Toolbar:** `[ Pause ]/[ Resume ]` (toggle), `[ Step ]` (`game.step 1`; shift-click `game.step 10`), `[ Reload ]` (`game.reload auto`; badge shows the tier used), `speed` drop-down (0.25×, 0.5×, 1×, 2×, 4×, 8×, fast), `[Edit|Play]` only for Studio-capable hosts. Items disabled (dim) when the host lacks the cap (`pause`, `step`, `speed`, `reload`).
- **Badge:** `<state> t<tick>`; `restoring` in `info`, `crashed` in `error`.
- **Data:** `game.list`, `game.screen.get` (initial), events `game.output`, `game.screen`, `game.tick` (badge only; throttled 4 Hz), `game.state`, `game.crash`; calls `game.input`, `game.buttons`, `game.pause/resume/step/speed/reload`.
- **Keys (gui-normal):** `i` or `<CR>` focus the prompt; pause/resume, step and reload use the leader keys of 13C.6 (`<Leader>gp`, `<Leader>gn`, `<Leader>gR`); `[` / `]` previous/next instance when several; `c` clear the visible scrollback view (does not touch the host); `y` copy visible screen text.
- **Context menu:** `Copy screen text`, `Save transcript…` (writes the full `game.output.tail` to a file), `Open in external browser` (browser backend only), `Restart game`, `Stop game`, `Show adapter info` (opens `adapter.describe` in the Output peek).
- **States:** `no-instance` (with `[Run target…]`); `starting` (host booting, spinner + boot log lines streamed); `restoring` (dims the screen, badge `restoring t300`); `crashed` (red banner row with the message and `[Show log] [Restart] r`); `unsupported` for hosts without text output (then the panel shows the Viewport variant D2.3 automatically when `viewport` cap exists, else a summary).
- **D2.2.1 Canvas summary extras:** `Hold key▾` lists `adapter.smoke.keys`; choosing one sends a `key` input with `hold_frames = 30`. `Pointer` accepts `x,y` and sends `click`/`pointer`. Both only exist in summary mode.
- **Tests:** with the fixtures `hello-js`, `hello-ui`, `hello-canvas` through `--fake-daemon` recordings and, where the host runs, live: prompt send, button press, pause/resume badges, restore dimming, crash banner; golden text dump per state.

## D2.3 Game view (viewport)
**Header:** id `game` (same id; the factory picks the variant by instance `caps`) · icon `▶` · default dock `main-right`.
```
+- ▶ game: fps-test  running  60fps  t90211 ------------------------- [⧉][≡][✕] -+
| [ Pause ] [ Step ] [ Reload ] speed 1.0x▾   view: lit▾   [Edit|Play]  FPS 60      |
|                                                                                    |
|                         (ViewportImage, aspect-preserving)                         |
|                                                                                    |
| capture: click to capture · Ctrl+Alt+G to release                  1280x720 shm    |
+------------------------------------------------------------------------------------+
```
- **Contents:** toolbar row; `ViewportImage` (13A.4: letterboxed, nearest-neighbour when integer-scaled else bilinear, resolution policy from `[viewport]`); 1-row footer: capture hint / `CAPTURED — Ctrl+Alt+G to release` in `mode_viewport_play` colours, resolution, transport (`shm`/`dmabuf`), dropped-frame count when > 0.
- **Input:** 13A.5 capture/release; in `viewport-edit` the Studio tool keys of 13B.7 apply. The panel title shows `FPS` from `viewport` stats at 1 Hz (frame arrival drives redraws; no fixed timer).
- **Toolbar extras:** `view:` drop-down from `viewport.modes`; `1:1` toggle (native pixels, scroll if larger); `Screenshot` (`:screenshot`-like: saves the current frame to `.pipist/screenshots/<tick>.png`).
- **Data:** `viewport.list/attach/detach/modes/set_mode`, events `viewport.offered/lost/fallback`, `game.*` as in D2.2; frames via the side channel (13A.2).
- **States:** `connecting` (spinner, `waiting for first frame`), `fallback` badge `shm (dmabuf unavailable)`, `lost` (`viewport lost — runtime exited` + `[Restart]`), `no-instance`, `stale` (no new frame for 2 s while the game is `running`: badge `stale` in `warn`).
- **Context menu:** `Pop out`, `Fullscreen (F11)`, `Reset camera`, `Copy frame to clipboard (PNG)`, `Capture input`, `Show viewport stats`.
- **Tests:** shm round-trip golden image; capture/release; resize debounce 100 ms; dmabuf marked Unverified if no GPU; `lost` handling when the runtime is killed.

## D2.4 Game view (browser)
**Header:** id `game` · icon `▶` · variant chosen when `kind == "browser"`.
```
+- ▶ game: hello-ui (browser)  running  t77 ------------------------- [⧉][≡][✕] -+
| [ Pause ] [ Reload ] [ Open browser ]     connected: Chromium 127  127.0.0.1:5173 |
| console (captured): 3 errors, 12 warnings                         <- badges       |
|   TypeError: x is undefined   js/combat.js:88:12                  <- links (P4)   |
| (page itself is shown in the external browser window)                              |
+------------------------------------------------------------------------------------+
```
- **Contents:** toolbar with `Open browser` (runs the target's `browser_command` or `xdg-open <url>`), connection line (agent name/UA, URL, WebSocket state), captured console as a `LogView` (levels coloured, link text P4, last 2 000 lines), and a one-line summary of `adapter.describe` warnings (`W_*`, clickable → Output peek).
- **Data:** `game.*`, `log.query` with `source = "game:<instance>"`, `adapter.describe`.
- **States:** `waiting for browser` (`open http://127.0.0.1:<port>/ — [Open browser]`), `disconnected` (agent socket closed; auto-reconnect indicator).
- **Tests:** fake-agent fixtures; link activation opens the editor.

## D2.5 Console drawer (overlay) and Console panel
**Header:** id `console` · module kernel · icon `>` · opens as the **Console drawer overlay** (backtick `` ` `` or `<Leader>dc`) and can be docked as a normal panel (`allow_multiple` true).
```
+- > console ----------------------------------------------------------------[⧉][≡][✕] -+
| pipist> where "dress code"                                                           |
|   hit  js/08-dialogue.js:211:5   "…you break the dress code…"                        |
|   hit  data/npcs.toml:40:3       dress_code = "formal"                               |
| pipist> goto t300 | run hello-js                                                      |
|   forked b4 @ t300 (T1)                                                              |
| pipist> _                                                      (vi insert; multi-line)|
+--------------------------------------------------------------------------------------+
```
- **Contents:** scrollback `LogView` (selectable; output lines are links per P4) over a multi-line `ViInput` (13C.4, vi insert first; `<S-CR>` newline, `<CR>` submit). Prompt `pipist> `. The grammar is the **CLI command grammar** (`pipist <subcommand> …` without the leading word) plus `:`-commands (a line starting with `:` is a command-line command, 13C.3) plus raw JSON-RPC when the line starts with `{` or `rpc `. `|` chaining as in 13C.3.
- **Completion:** same engine and sources as the command line (13C.3), popup above the input.
- **History:** shared with the command line (`.pipist/history/cmdline`), `<C-r>` reverse search.
- **Output rules:** one result block per command, prefixed by the echoed command in `fg_dim`; results > 500 lines are truncated with `… 4 213 more (use :messages or yy to copy all)`; structured results (tables) are laid out with P2 column rules; errors in `error`.
- **Keys (gui-normal, overlay open):** `` ` `` or `<Esc><Esc>` close; `<C-l>` clear scrollback; `<C-c>` cancel a running command (cancels the request via `session.cancel`); `<C-w>` window commands still work.
- **States:** `disconnected`; a running command shows a spinner in the title badge; long commands (`exp run`) stream progress lines from events.
- **Tests:** command parsing table (≥ 80 lines mixing CLI and `:` forms), completion fixtures, cancel path, history persistence.

## D2.6 Log
**Header:** id `log` · module kernel ring / `logdb` · icon `≡` · default dock `drawer` · `allow_multiple` true.
```
+- ≡ log  follow  filtered 214/9 031 -------------------------------- [⧉][≡][✕] -+
| [x] follow  lvl:info▾  src:all▾  ch:all▾  [ pin tick ]  [ clear ]  [ export ]   |
| / dress.*code                                                    214/9031        |
| 12:04:11 INFO  game  t412  You enter the cellar.                                 |
| 12:04:12 WARN  game  t412  rrand queue empty        js/04-rng.js:33:7            |
| 12:04:12 ERROR proc:build  error: 'x' undeclared     src/main.c:88:12             |
+----------------------------------------------------------------------------------+
```
- **Columns:** time `HH:MM:SS` (fixed 8), level (5, coloured by `log_*`), source (up to 10, truncated), tick `t<n>` (6, only when present), message (rest), link (right-aligned, `file:line:col`, P4). Multi-line messages show the first line plus `⏎ n more` (expand with `o`).
- **Toolbar:** follow toggle (auto-scroll to newest; any manual scroll up turns it off and shows `paused (n new)`), level threshold drop-down, source and channel multi-select, `pin tick` (restricts to the tick range ± 5 of the live tick or of the previewed snapshot), clear (`log.clear` after P8 confirm), export (writes the **filtered** records as JSONL or text to a file, prompting for a path via the command line `:w `).
- **Filter row:** `/` text or `/re:` prefix for regex; `n/N` jump between matches while the full list stays visible with matches highlighted (`match_bg`); `<CR>` in the filter converts matches to filtering (hide non-matching) — toggled by `f`.
- **Data:** `log.query` (paged 500 rows around the viewport, cursor-based), `log.levels.set`, event `log.record` (subscribed only while the panel is visible; when hidden, a counter of unseen errors on the tab `●`), `proc.output` is **not** shown here (see Processes).
- **Keys:** `f` toggle filter-vs-highlight; `F` toggle follow; `l` cycle level threshold (trace→error→trace); `s` open the source filter menu; `t` pin to live tick; `c` clear (P8); `e` export; `<CR>` activate link or, on a game record with a tick, **preview that tick** (D1.5) — `<C-CR>` instead goes (fork) via the confirm toast.
- **Context menu:** `Copy line`, `Copy as JSON`, `Only this source`, `Hide this source`, `Show context (±20 lines)`, `Preview tick`, `Fork at tick…`.
- **Perf rule:** 100 000 rows scroll at one frame per event; ≥ 5 000 records/s ingest keeps the GUI under 8 ms per frame by batching to ≤ 30 updates/s.
- **States:** `empty` (`no log records yet — logs from the game, builds and the daemon show up here`), `loading`, `error`. Level threshold changes are `log.levels.set` only when the user picks **Set as source minimum** in the menu (the toolbar threshold is view-only).
- **Tests:** 100k-row virtualisation, filter/regex correctness table, follow/pause behaviour, export golden, link activation.

## D2.7 Problems
**Header:** id `problems` · module `diag` · icon `!` · default dock `drawer`.
```
+- ! problems  E2 W5 I0 --------------------------------------------- [⧉][≡][✕] -+
| [x] E  [x] W  [ ] I  src:all▾  scope: workspace▾  [ run checks ]                  |
| ▾ js/13-combat.js (2)                                                              |
|     E 88:12  'x' is not defined               engine                                |
|     W 14:3   unreachable code after return   lint:unreachable    [fix]            |
| ▸ data/npcs.toml (3)                                                               |
+------------------------------------------------------------------------------------+
```
- **Tree:** file nodes (count) → diagnostic rows `<sev> <line:col> <message> <source> [fix]`. Sort: files by worst severity then path; rows by line. Severity filters via toolbar toggles; `scope`: `workspace` (all), `open files`, `current file`. `source` multi-select (syntax, engine, lsp, lint, build, schema, keymap, layout).
- **Data:** `diag.list` (initial, paged), event `diag.updated` (replace semantics per file+source; the panel replaces exactly that bucket), `diag.run`, `diag.fix`. The count in the tab and status bar come from the same data.
- **Keys:** `<CR>` jump to `editor.goto`; `a` apply the first fix of the row (`diag.fix apply`), `A` apply all fixes in the file (P8 confirm); global keys `]d` / `[d` (gui-normal) jump to the next/previous problem from anywhere (new actions `problem.next`/`problem.prev`); `R` run checks (`diag.run`).
- **Context menu:** `Go to`, `Apply fix`, `Copy message`, `Ignore this rule in project` (writes to `pipist.toml [lint]`, via `config.set`), `Show rule docs`.
- **States:** `module-not-loaded` (stub with `[Load]`), `empty` (`no problems`, green `✓`), `running` badge `checking…`.
- **Tests:** replace semantics; fix application via `editor.apply` buffer-aware path (mock); counts match status bar.

## D2.8 Search
**Header:** id `search` · module `index` · icon `?` · default dock `drawer` · `allow_multiple` true.
```
+- ? search  text  "dress code"  14 hits ------------------------------- [⧉][≡][✕] -+
| [text|symbol|string|entity|where]  [x] smart-case  [ ] regex  globs: **/*.js        |
| / dress code                                                                        |
| js/08-dialogue.js                                                                   |
|   211:5   …you break the dress code and are…                                        |
|   340:9   …dress code violations carry a…                                           |
| data/npcs.toml                                                                      |
|   40:3    dress_code = "formal"                                                     |
| preview: js/08-dialogue.js:205-217 (CodeView, highlighted)                           |
+-------------------------------------------------------------------------------------+
```
- **Layout:** query row (the filter-row `ViInput`, always visible here), mode chips (`text`, `symbol`, `string`, `entity`, `where`) switched with `<Tab>` in the query or `1`–`5` in gui-normal, options row, results tree (file → hit) in the top 65%, **preview** `CodeView` (read-only, tree-sitter spans from `index.spans`) in the bottom 35% with the hit highlighted; preview toggled with `p`.
- **Behaviour:** incremental: the query runs 150 ms after the last keystroke; a new query cancels the old (`session.cancel`); `limit` 500 with `truncated` marker row `… more (refine the query)`. `where` mode shows the merged ranking with kind icons (`ƒ` function, `"` string, `@` entity, `¶` text, `f` file).
- **Data:** `search.text/symbols/strings/entities/where`, `index.status` (badge `indexing…`), event `index.updated` (re-run the current query when files in the results changed).
- **Keys:** `<CR>` open hit (editor); `<C-v>/<C-s>` open in a split of the editor (nvim `:vsplit`/`:split`); `<C-q>` send all hits to nvim's quickfix list (`editor.command 'cexpr …'`); `]s`/`[s` global next/previous search hit (works while the editor is focused).
- **States:** `module-not-loaded` (index is heavy: stub offers `[Load] [Always load]`), `indexing` (progress `files n/N`; text search still works through `rg` fallback with a `(basic search)` badge), `empty` (`no matches`), `error`.
- **Tests:** per-mode golden results on a fixture tree; cancellation under typing; quickfix export.

## D2.9 Files
**Header:** id `files` · module kernel (`project.files`) · icon `/` · default dock `main-left` (not in the shipped layouts; opened by `:panel files` or the switcher).
```
+- / files  hello-js ------------------------------------------------- [⧉][≡][✕] -+
| ▾ js/                                                                             |
|     01-core.js      12 KB                                                         |
|   * 13-combat.js    38 KB   (modified since snapshot)                             |
| ▸ data/                                                                           |
|   index.html   pipist.toml                                                        |
+-----------------------------------------------------------------------------------+
```
- **Tree** of `project.files` (respecting `.gitignore` and `[watcher].ignore`), directories first, sizes at right, badges: `*` modified since the displayed snapshot's `source_revision` (compared via `timeline.source.list`, only when a preview/live snapshot exists), `E`/`W` counts from Problems, `T` tracked by the index. Lazy-loaded per directory (`project.files {glob: "dir/*"}`); updates from `file.created/deleted/renamed`.
- **Keys:** `<CR>` open in editor, `o` expand/collapse, `a` new file prompt (`:e <dir>/`), `r` rename and `d` delete never act directly: Files does not modify the file system itself, so they prefill the command line with `:!mv <path> <path>` / `:!rm -i <path>` for the owner to review and run; `.` toggle hidden files; `/` filter (fuzzy); `yp` copy path.
- **States:** `empty` (cannot happen: root always exists), `loading`, `error`.
- **Tests:** big tree virtualisation (50k files), gitignore handling.

## D2.10 Outline
**Header:** id `outline` · module `index` · icon `#` · default dock `main-left` (hidden by default).
- **Contents:** tree from `search.outline {file}` of the file shown in the Editor (follows `editor.cursor` events; debounced 300 ms; a pin toggle `p` freezes it). Rows `<kind glyph> name  line`; the row containing the cursor is highlighted; clicking/`<CR>` → `editor.goto`.
- **Filters:** `/` fuzzy, `K` toggle kinds (functions/classes/variables/keys).
- **States:** `module-not-loaded`, `no file` (`open a file in the editor`), `unsupported language` (`no outline for .md`).
- **Tests:** follow-cursor with fixtures; kinds filter.

## D2.11 Terminal
**Header:** id `terminal` · module kernel · icon `$` · default dock `drawer` (tabs of shells) · `allow_multiple` true.
- **Contents:** `TerminalView` on a `$SHELL` PTY with cwd = project root (13.6). Title badge: process state and cwd basename. Passthrough on focus (13C.2).
- **Keys (gui-normal):** `<CR>` enter passthrough; `r` restart shell; `n` new terminal tab (`proc.start` with `pty`); `x` close if exited.
- **Behaviour:** output matching problem matchers is **not** auto-parsed here (that is the build target's job); links `path:line:col` are clickable with `<C-click>` (plain click selects). Scrollback 10 000 lines. On shell exit the panel keeps the last screen and shows `[exited n] r restart`.
- **States:** `starting`, `exited`, `error` (cannot spawn).
- **Tests:** PTY size sync, bracketed paste, link detection table, exit code display.

## D2.12 Processes
**Header:** id `processes` · module kernel · icon `⚙` · default dock `drawer` (not in default tab set; `:panel processes`).
```
+- ⚙ processes  4 running, 1 exited ---------------------------------- [⧉][≡][✕] -+
| id    state    pid     cmd                         started   restarts  tags        |
| p1    running  3811    nvim --listen …             12:01     0         editor      |
| p2    running  3902    node host-web …             12:04     0         game        |
| p3    exited(1) 3977   ninja -C build              12:07     0         build       |
| ── output of p3 (TerminalView) ──────────────────────────────────────────────────── |
+-------------------------------------------------------------------------------------+
```
- **Table** (P2) of `proc.list`, sortable; selecting a row shows its output below in a `TerminalView` (PTY processes: `proc.attach_pty`; others: `proc.output.tail` then live `proc.output`).
- **Keys:** `K` stop (TERM), `X` kill (P8 confirm), `R` restart, `t` filter by tag, `<CR>` focus output, `w` write to stdin prompt (single line), `x` dismiss exited rows.
- **Data:** `proc.list`, events `proc.started/exited/crashed`, `proc.output`/`proc.pty`.
- **States:** `empty` (`no supervised processes`), `error`.
- **Tests:** crash/restart policy display, tail replay, PTY fd passing path.

<!-- SOURCE-END: pipist-spec-d2-panels-work.md -->

---

<!-- SOURCE-BEGIN: pipist-spec-d3-panels-inspect.md -->

# PIPIST SPEC — Appendix D3: Panels, part 2 (time, state, code changes, experiments, system, Studio) and GUI done-when

Part of Pipist spec v1.3. Continues Appendix D2 (same conventions and header fields; patterns P1–P12 and states from D1.8; theme tokens D1.9). Panels: Timeline, State inspector, Where, Patches, Experiments, Modules, Bus monitor, Perf, Help, Declarative panels, and the Studio set (Viewport, Hierarchy, Inspector, Assets, Definitions, Tweakables). The last sections give the complete panel registry, new actions and keys, and the GUI milestone checklist.

---
## D3.1 Timeline
**Header:** id `timeline` · module `timeline` · icon `⌛` (`T`) · default dock `main-right-bottom` (debug layout) · `allow_multiple` false.
```
+- T timeline  run 2 · 3 branches · 1 204 snapshots · 38 MB / 8 GB ----------------- [⧉][≡][✕] -+
| [ Fork here ] [ Bookmark ] [ Diff ▸ ] [ Prune… ]   show: [x] archived  [ ] non-quiescent       |
| branches                                     | snapshots on b3  (selected)                      |
| ▾ run 2  hello-js  14:02                    |  tick  time      reason   size   marks            |
|   ▾ b1  run@14:02                  t0–t980  |  t412  14:07:41  policy   1.2 KB  B pre-fight    |
|     ├─ b3 fork@t200 *           t200–t412   |  t411  14:07:40  policy   0.1 KB                  |
|     └─ b4 fork@t300 (arch)      t300–t350   |  t400  14:07:31  request  1.3 KB  patch          |
| ▸ run 1  hello-js  yesterday                |                                                   |
+---------------------------------------------+---------------------------------------------------+
| [|---*-----B----@======>|]  scrubber (same as strip, full width)  t412 / 980  q                  |
| detail: s_ab12cdef34567890  b3 t412  src rev 9f2c…  host web  format web/1  raw 5.1 MB new 12 KB |
+--------------------------------------------------------------------------------------------------+
```
- **Layout:** left **branch tree** (P3: runs → branches as a tree by fork parent; each row `b<N> <label> t<first>–t<head>` with `*` for the branch of the live instance, `(arch)` archived, `!` for flags `shape-mismatch`/`damaged`); right **snapshot table** (P2; columns tick, time, reason, size (raw → new bytes tooltip), marks: `B` bookmark, `P` pinned, `patch`, `x` damaged, `~` non-quiescent); bottom **scrubber** (same widget as the strip, full width, with bookmarks labelled) and a **detail** area (2–3 rows). Splitter between left/right persists.
- **Toolbar:** `Fork here` (uses selected snapshot → `timeline.goto` fork, reload `auto`, confirm toast per D1.5), `Bookmark` (prompt for name/note via the command line), `Diff ▸` (menu: *vs live*, *vs previous*, *vs bookmark…*, *code only*), `Prune…` (opens the P8 prompt flow: `dry_run` first showing `Remove 380 snapshots (14 MB)? [y/N]`), toggles for archived and non-quiescent.
- **Selecting** a snapshot sets the **preview** (D1.5); the State inspector follows it. Selecting a branch selects its head. `<CR>` on a snapshot = goto (with confirm toast); on a branch = goto its head.
- **Diff view:** `Diff` replaces the right pane with a two-column tree diff (state: `timeline.diff`, up to 500 changes, expandable; code: `timeline.source.diff` rendered in a `CodeView` with `diff_add/diff_del` colours). `Esc` returns.
- **Keys:** `f` fork here; `b` bookmark; `p` pin/unpin; `d` diff menu; `a` archive/unarchive branch (`timeline.branch.archive`); `D` delete branch (P8 confirm, `dry_run` first; shows `kept fork roots`); `l` label branch (prompt); `[`/`]` previous/next branch; `S` show "code at this point" (source list and diff for the snapshot); `<Tab>` swaps focus between the branch tree and the table.
- **Data:** `timeline.branches`, `timeline.list` (paged, per selected branch), `timeline.get {include:"meta"}`, `timeline.bookmarks`, `timeline.stats`, `timeline.diff`, `timeline.source.*`; events `timeline.snapshot`, `timeline.branch`, `timeline.goto`, `timeline.pruned`, `timeline.quota`, `timeline.damaged`.
- **Badge/title:** run count, branch count, snapshot count, `usage / quota`; the usage part turns `warn` at level ≥ 2 and `error` at level 4 with `FULL`.
- **States:** `module-not-loaded`; `empty` (`no snapshots yet — run a game with snapshots enabled`); `no-instance` is **not** an error here (stored data shows; `Fork here` starts the target automatically as in A2.5, toolbar shows `will start <target>`); `damaged` rows disabled for goto.
- **Context menu (snapshot):** `Preview`, `Go to (fork)`, `Go to without fork` (only if allowed), `Bookmark…`, `Pin`, `Diff with live`, `Copy id`, `Export…` (reserved). **(branch):** `Go to head`, `Label…`, `Archive`, `Delete…`, `Copy id`.
- **Tests:** tree building from fixtures with tombstoned parents; preview does not call `game.restore`; confirm flow; prune dry-run text; 10 000-snapshot virtualisation; golden dumps.

## D3.2 State inspector
**Header:** id `state` · module `timeline` + host · icon `{}` · default dock `main-right` (debug layout) · `allow_multiple` true (to compare two views).
```
+- {} state  live t412  [viewing s_ab12 t300 (not live)] ------------------------- [⧉][≡][✕] -+
| [ live | snapshot ]  vs: [ none | previous | s_… ]   watch: 3     / flags                     |
| ▾ G                                                          object   18 keys               |
|   ▾ flags                                                    object    4 keys               |
|       chuyRep      3        (was 2)                                    <- changed (diff_change)|
|       metBoss      true                                                                       |
|   ▸ inventory                                                array    7                      |
|   ▸ npcs                                                     Map(12)                         |
|   eventLog         [summary array 5 210]                                                      |
| ── watch ──   G.flags.chuyRep = 3    player.hp = 14                                          |
+---------------------------------------------------------------------------------------------+
```
- **Source switch:** `live` (the current instance via `game.state.get`) or `snapshot` (the previewed or selected snapshot via `game.state.get {snapshot}` / `timeline.get`); the title badge states which, always with `(not live)` for snapshots.
- **Tree (P3):** rows `name  value  type  size`. Values render from the Pipist Value encoding (A1.4): primitives inline (strings truncated to 60 cells with `…`), `undefined`, `NaN`, `Infinity` as such, `BigInt` as `123n`, `Date` as ISO, `Map(n)`/`Set(n)`, typed arrays `u8[512]`, class instances `Foo {…}`, functions `ƒ name` (dim), DOM nodes `<div#id>` (dim), `ref` as `↪ G.player` (activate to jump), `summary` as `[summary object 120]` (activate to load deeper with a larger `depth`/`max_bytes`, ≤ 16 deep). Lazy: children load on expand (`depth` 3 per request).
- **Diff mode (`vs`):** rows that differ from the comparison are coloured (`diff_add`, `diff_del`, `diff_change`) and the previous value is shown dim at the right (`(was 2)`); unchanged subtrees are collapsed unless `u` (show unchanged) is on. In live mode the comparison `previous` is the value at the previous tick (kept from the last two `game.state.changed` updates of the watch set; for the full tree, from the previous snapshot).
- **Watch list:** `w` on a row adds its path to the watch list shown in the bottom strip (`game.state.watch` with `interval_ticks = 1`); watches persist per project in the layout file; a watch whose path no longer exists shows `(missing)`.
- **Edit (live only):** `e` edits the selected primitive/JSON value in a one-row `ViInput` (initial text = JSON of the value); `<CR>` → `game.state.set` after P8-style inline confirm only if the value is not a primitive; the result's `old` is shown in a toast `G.flags.chuyRep: 3 → 5 (undo: u)`; `u` re-sets the old value (last 20 edits). Edits to snapshot views are refused (`viewing a snapshot — go to it first`). Functions and DOM nodes are read-only.
- **Keys:** `/` filter by path/name (fuzzy over loaded nodes; `?` searches values), `yp` copy state path (A1.4 grammar), `yy` copy JSON of the node (≤ 1 MiB), `w` watch, `W` remove watch, `s` toggle snapshot/live, `v` pick comparison, `u` toggle unchanged, `e` edit, `Y` open a node in a read-only `CodeView` as pretty JSON.
- **Data:** `game.state.get/set/watch/unwatch`, `timeline.get`, `timeline.diff`, event `game.state.changed`, `adapter.fingerprint` (to skip refresh when unchanged).
- **States:** `no-instance` (live mode only: switches to snapshot mode if a preview exists, else empty hint `run a game or preview a snapshot`), `unsupported` (host lacks `state.get`), `loading`, `error`, `truncated` marker rows.
- **Tests:** Value-encoding rendering table (all tags), lazy loading depth, diff colouring on fixtures, edit/undo cycle against a fake host, 50k-key object performance (virtualised, ≤ 8 ms/frame).

## D3.3 Where
**Header:** id `where` · modules `trace` + `index` · icon `?` (`W`) · default dock `drawer` (a tab next to Log in the `debug` layout) · `allow_multiple` false.
```
+- W where  t412  tracing: functions+provenance  window 200 ---------------------- [⧉][≡][✕] -+
| [ Tracing: on ]  mode▾  window 200  [ ◀ older ]  t412  [ newer ▶ ]   [ who wrote… ]        |
| functions run this tick (14)                                                                 |
|   1  handleInput           js/09-input.js:44                      x1                         |
|   2  attack                js/13-combat.js:12                     x2                         |
| strings shown (3)                                                                           |
|   "You swing at the guard."  js/13-combat.js:20:9  in attack                               |
| entities involved (2)    npc:guard_01  data/npcs.toml:40    item:sword  data/items.toml:7   |
+---------------------------------------------------------------------------------------------+
```
- **Contents:** three sections (functions in call order, strings/dialogue with their source ranges, entities); every row is a link (P4). Navigation `◀ older / newer ▶` (`trace.back`) within the window; the displayed tick follows the **preview** position when set (only if inside the traced window; else `tick outside trace window`).
- **Tracing toggle:** `Tracing: on/off` calls `trace.start/stop`. Starting tracing reloads scripts instrumented (T4-like): before the first start in a session the toggle shows an inline P8 prompt `Tracing reloads the game scripts and restores state. Continue? [y/N]`. `mode` = functions | provenance | both.
- **Who wrote:** `who wrote…` prompts a state path (completion from the State inspector paths) → `trace.who_wrote` → results list `tick  function  file:line  old → new` replacing the lower sections until `Esc`.
- **Data:** `trace.start/stop/now/back/who_wrote`, event `trace.updated`, `search.where` for the optional `/` query (jump-to-definition via `index`).
- **Keys:** `t` toggle tracing, `h`/`l` older/newer (also `[`/`]` as in D3.1), `m` mode menu, `w` who wrote, `<CR>` follow link.
- **States:** `module-not-loaded`, `tracing-off` (`tracing is off — [t] to start`), `unsupported` (host lacks `trace`), `empty` (`nothing ran this tick`), `loading`.
- **Tests:** link activation, window navigation, instrumented-reload prompt, `who_wrote` result table golden.

## D3.4 Patches
**Header:** id `patches` · module `patch` · icon `Δ` · default dock `main-right-bottom` (debug, as a tab with timeline) · `allow_multiple` false.
```
+- Δ patches  auto: on  pending: js/13-combat.js (T1)  last: p7 T1 ok ------------ [⧉][≡][✕] -+
| [ Preview ] [ Apply ] [ Revert last ]   auto [x]   auto-restore [ ]                          |
| id  time      tier  result    paths                           note                            |
| p7  14:07:12  T1    applied   js/13-combat.js attack          function-body                  |
| p6  14:05:40  T3    fellback  data/items.js                   T3→T4: side-effect statement   |
| ── preview: plan T1, 1 item ─────────────────────────────────────────────────────────────── |
| (unified diff in CodeView, + and - lines coloured)                                            |
+----------------------------------------------------------------------------------------------+
```
- **Header line** shows `patch.status` (auto on/off, pending paths with their planned tier, last id); the pending tier is coloured (`T1`/`T2` ok, `T3+` warn).
- **Table:** `patch.history` rows; selecting a row shows its plan and diff (`patch.preview` for pending, stored diff for history). `result` coloured: applied ok, fellback warn, failed error, reverted dim; failed rows expand to show diagnostics (links).
- **Toolbar:** `Preview` (`patch.preview` for changed tracked files → plan + diff), `Apply` (`patch.apply` tier `auto`; disabled with reason when no instance), `Revert last` (P8 confirm → `patch.revert`), `auto` toggle (`patch.auto`), `auto-restore` toggle (config `[patch].auto_restore`).
- **Keys:** `p` preview, `a` apply, `R` revert selected (P8), `A` toggle auto, `<CR>` open the first path in the editor, `t` force tier menu (T1…T5, requires confirm for T4/T5 `This restarts the game from the nearest snapshot`).
- **Data:** `patch.status/history/preview/apply/revert/auto`, events `patch.pending/applied/failed/fellback`.
- **States:** `module-not-loaded` (the status-bar segment 6 stays hidden), `empty` (`no patches yet — edit a source file while a game runs`), `no-instance` (preview works, apply disabled), `error`.
- **Tests:** plan rendering from the A2.6 fixtures, fallback display, revert flow, tier menu confirm.

## D3.5 Experiments
**Header:** id `experiments` · module `experiments` · icon `⚗` (`X`) · default dock `main` in `experiment` layout · `allow_multiple` false.
```
+- X experiments  2 defined  run e3: 41/120 (2 failed)  eta 00:36 ------------------ [⧉][≡][✕] -+
| definitions            | results  e3  combat-balance                                          |
| ▸ combat-balance (120) | variant            seed  hp_end  win   asserts                       |
| ▸ economy (12)         | dmg=3,armor=1      11    14      yes   2/2                            |
|                        | dmg=5,armor=1      11    9       yes   2/2                            |
| [ Run ] [ Cancel ]     | dmg=9,armor=4      12    -       FAIL  0/2  timeout   [transcript]    |
| [ Check goldens ]      | ── compare: e2 vs e3 ─────────────────────────────────────────────── |
+----------------------------------------------------------------------------------------------+
```
- **Layout:** left definitions list (`exp.list`; each with variant count, file link), centre/right **results table** (P2; columns from `exp.results.columns`, sortable, filter `/` supports `col:value` and `failed`), failed rows highlighted; a progress bar row (`41/120`, `eta`) while running; a `compare` strip to pick another run and show per-column deltas (mean/min/max of numeric `collected` columns, flip counts for booleans).
- **Drill-down:** `<CR>` on a row opens its transcript (file link, opens in the editor as a text file) and offers `Replay in Game view` (`pipist exp try`: starts a live instance at the variant's start state, interactive variant of 12).
- **Toolbar:** `Run` (selected definition, `exp.run`), `Cancel` (`exp.cancel`), `Check goldens` (`exp.check`; shows pass/fail with first divergence), `Record golden…` (prompts name → `exp.golden.record`), `Verify adapter…` (prompts script → `exp.verify_adapter`; result in the Output peek).
- **Keys:** `r` run, `c` cancel, `g` check goldens, `G` record golden, `v` verify adapter, `f` toggle failed-only, `x` compare, `e` export table (CSV/TSV to a file via the command line).
- **Data:** `exp.list/run/status/cancel/results/golden.record/check/verify_adapter`, events `exp.progress`, `exp.done`.
- **States:** `module-not-loaded`, `empty` (`no experiments — create experiments/<name>.toml`), `running`, `error`.
- **Tests:** progress/ETA rendering, result paging (cursor), compare computation table, failed-row drill-down, golden fail display.

## D3.6 Modules
**Header:** id `modules` · module kernel · icon `▦` · default dock `main-right` (not in default layouts; `<Leader>mm`) · `allow_multiple` false.
```
+- ▦ modules  profile: dev  3 loaded of 11 · 41 MB ------------------------------- [⧉][≡][✕] -+
| name        state    kind     rss     cpu ms  calls  errors  always  provides             |
| editor      ready    builtin  —       —       88     0       [x]     editor.*              |
| index       ready    process  38 MB   1 204   310    0       [ ]     search.*, index.*     |
| timeline    starting process  —       —       0      0       [ ]     timeline.*            |
| diag        registered                                                                    |
+--------------------------------------------------------------------------------------------+
```
- **Table** from `module.list` + `module.stats` (refresh every 2 s while visible, no polling when hidden). States coloured; `failed` rows expand to `last_error`. Cold modules are dim.
- **Keys:** `l` load, `u` unload (`!` variant `U` for force, P8 confirm), `R` reload, `a` toggle always-load (`module.always`), `P` switch profile (menu from `module.profile.get`; `now` or `next`), `<CR>` expand details (requires, provides, version, pid, uptime, restarts).
- **States:** `error`, `disconnected`. Never `module-not-loaded` (kernel).
- **Tests:** load/unload against a fake kernel, dependency-refusal message, profile switch.

## D3.7 Bus monitor
**Header:** id `bus` · kernel · icon `~` · default dock none (`:panel bus`) · `allow_multiple` true.
- **Contents:** virtualised list of raw events `seq  time  topic  data(one-line JSON, truncated)`; toolbar `pause` (buffers up to 10 000 events), topic filter (globs per A1.5, default `**`), `rate` indicator (events/s), `dropped` counter from `bus.dropped`. `<CR>` expands the JSON (pretty, `CodeView`); `yy` copies the event as an NDJSON line.
- **Keys:** `p` pause, `c` clear, `/` filter (topic glob or `text:` substring of the JSON), `e` export visible as JSONL.
- **Data:** `session.subscribe {topics:["**"]}` only while the panel is visible and unpaused (it can be heavy; shows a warning badge `high volume` > 500 events/s and auto-pauses at > 5 000/s with a toast).
- **States:** `empty`, `disconnected`. **Tests:** pause buffering, auto-pause, glob filter table.

## D3.8 Perf
**Header:** id `perf` · kernel + hosts · icon `∿` · default dock none · `allow_multiple` false.
```
+- ∿ perf  window 60 s ------------------------------------------------------------ [⧉][≡][✕] -+
| tick/frame time (ms)  ▁▂▃▅▂▁▁▂▃▁   avg 6.2  p95 11  max 24      (ImPlot line; term: block chars) |
| host memory (MB)      ▁▁▂▂▃▃▃▄▄▅   132                                                          |
| timeline usage        38 MB / 8 192 MB   dedupe 7.4×   snapshots 1 204   level 0               |
| module RSS            kernel 6 · index 38 · timeline 22 · gui 54 MB      total 120 MB            |
| gui frames            idle 0/s  (last redraw 3.2 s ago)                                         |
+------------------------------------------------------------------------------------------------+
```
- **Plots** use ImPlot in `ide` and in `term` (consistent look: no grid fill, 1 px lines, axis labels in `fg_dim`); fall back to block-character sparklines when `[gui].ascii = true`. Window length 60 s default (`[perf].window_s`).
- **Data:** `module.stats`, `timeline.stats`, `game.tick` timestamps (frame-time estimate), host-reported `perf` runtime stats via `runtime.perf` if the host advertises it, GUI's own frame counter. Sampling only while visible.
- **Keys:** `w` cycle window (30 s/60 s/5 min), `p` pause, `r` reset. **States:** partial data shows `—`. **Tests:** sampler logic with fake time; sparkline rendering.

## D3.9 Help
**Header:** id `help` · GUI · icon `?` · default dock none (`:help`) · `allow_multiple` false.
- **Contents:** a read-only scrolling document view with a left **topic list** (keys, commands, actions, panels, config, workflow guides from `docs/help/`). The `keys`, `commands`, `actions`, `panels` pages are generated at runtime (13C.7, 13C.8) from the live registries; `:help panel <id>` shows the panel's section from this spec (the cloud run extracts D2/D3 headers, keys and states into `docs/help/panels/<id>.md`).
- **Keys:** `/` search in page, `n/N`, `<CR>` follow link, `<BS>` back, `gt`/`gT` next/previous topic. **Tests:** generated pages complete (every registered action appears), link validity (no dead internal links).

## D3.10 Declarative panels (module-defined UI, M14)
**Header:** id `ui:<module>:<panel-id>` · module any · icon from `ui.panel.set` (default `◇`) · default dock from `dock` hint (`left|right|bottom|center` → `main-left`, `main-right`, `drawer`, `main`).
- **Rendering rules** for the widget set of A2.13 in cell layout: `row` places children left-to-right with `gap` cells (default 1), `col` stacks them; `text`/`heading` (heading bold + `fg_bright`); `button` renders `[ label ]`, disabled dim; `input` renders `label [____value____]` with `kind` validation (invalid → `error` border + tooltip); `checkbox` `[x] label`; `select` `label▾`; `table` as P2 (selectable rows emit `ui.event select`); `tree` as P3; `plot` as ImPlot/sparkline; `progress` as `[#####-----] 50% label` ; `separator` a `border_dim` line; `code` as `CodeView`. Keyboard: `<Tab>`/`<S-Tab>` move between interactive widgets, `<CR>`/`<Space>`(widget focus only) activate. Everything emits `ui.event` to the owning module.
- **Limits/behaviour:** over 10 000 widgets or > 5 updates/s → the update is dropped and a one-line warning is shown in the panel footer. A module that unloads closes its panels (or turns them into `module-not-loaded` stubs if pinned in a layout).
- **Tests:** a sample module renders every widget kind (golden dump); event round-trip; limit handling.

---
## D3.11 Studio panels (13B; milestone M9)
All Studio panels require module `studio` and a runtime with the `scene` cap (13B.8); without it they show `unsupported` (`this runtime has no scene support — [Learn more]` → `:help studio`). Their layout lives in the `studio` workspace (D1.7.1). Behaviour and protocol are normative in 13B; the GUI specifics are here.

### D3.11.1 Viewport
**Header:** id `viewport` · icon `◫` · default dock `main` (studio) · a variant of D2.3 with the Studio toolbar.
```
+- ◫ viewport  EDIT  scene: arena.toml  dirty: 2 ------------------------------------ [⧉][≡][✕] -+
| [Edit|Play] [Pause] [Step]  tools: [Q sel][W move][E rot][R scale]  local▾ snap:[x] 0.25   |
| view: lit▾  persp▾  grid [x]  stats [ ]  cam speed 8▾  focus F                           |
|                       (ViewportImage with GUI-drawn gizmos/outlines)                       |
| selection: 2 entities    x 12.00  y 0.00  z -3.50              1280x720 shm                |
+---------------------------------------------------------------------------------------------+
```
- Two toolbar rows (wraps into the `≡` menu on narrow panels per P1); the footer shows selection summary and cursor world position (when the runtime supplies depth picks). Edit/Play badge uses `mode_viewport_edit` / `mode_viewport_play` colours; in Play the title shows `PLAY (transient — changes not saved)` and `studio.changes` count.
- **Keys** (mode `viewport-edit`, 13B.7): `q w e r` tools, `x` toggle local/world, `g` toggle snap, `f` focus selected, `Delete` delete selection, `<C-d>` duplicate, `<C-z>`/`<C-y>` studio undo/redo (global in this mode), `<Esc>` clear selection, `1`–`9` camera bookmarks (`<C-1…9>` set), `<Tab>` toggle Edit/Play only when `[studio].tab_toggles_play = true`.
- **States:** inherits D2.3; plus `read-only scene` (runtime reports not editable: tools dim).

### D3.11.2 Hierarchy
**Header:** id `hierarchy` · icon `▤` · default dock `main-left` (studio).
- **Tree** (P3, virtualised) from `scene.tree` with kind glyphs; toggles `v` (visible) and `L` (locked) shown as two fixed columns at the right; selected entities sync both ways with the Viewport (`scene.select`, event `scene.selection` with `origin` to avoid echo). Drag to reparent (`scene.reparent`); `r` rename inline (a `ViInput`).
- **Keys:** `a` add (menu of prefabs/definitions from `asset.list`), `D`/`Delete` delete (P8), `R` reveal in file (opens the editor at `source.range`), `H` toggle visibility, `L` toggle lock, `/` filter; `<C-d>` duplicates.
- **States:** `empty` (`empty scene`), `unsupported`, `loading`, `stale` (scene `version` bumped while editing: auto-refresh).
- **Tests:** two-way selection echo suppression, reparent via drag (script mode), 50k-node virtualisation.

### D3.11.3 Inspector (Studio)
**Header:** id `inspector` · icon `✎` · default dock `main-right` (studio).
- **Contents:** schema-driven `PropertyGrid` (13B.6) grouped by `group` with collapsible headers, one row per field: label (left, `fg_dim`, 40% width), editor (right). Editors per `SchemaField.type`: bool `[x]`, int/float drag + `ViInput`, vec2/3/4/euler as 2–4 aligned inputs, color swatch + hex input, enum `▾`, string/text `ViInput`, asset/ref picker (opens a `FuzzyList`), list/map with `+`/`−`/reorder. Changed-from-file fields show a `●` and `revert` (`<C-r>` on the field), defaults show `reset`. Multi-select shows `—` for mixed values. Footer: `source: data/enemies.toml:40` link; `raw` toggle shows the exact text block read-only with `[Edit in nvim]`.
- **Edits:** live preview while dragging (`scene.set {preview:true}`), commit on release/`<CR>`/250 ms idle (13B.5) via `studio.edit`; conflicts (`-32003`) show an inline banner `file changed on disk — [Reload] [Overwrite…]`.
- **Keys:** `j/k` field navigation, `<CR>`/`i` edit field, `<Esc>` leave field, `<C-r>` revert field, `<C-0>` reset to default, `zo/zc` groups.
- **States:** `nothing selected`, `unsupported`, `read-only` (field-level when `readonly`), validation errors on a field (red border + message row, nothing written).
- **Tests:** per-type editor golden dumps; preview vs commit protocol sequence against a fake runtime; conflict banner; undo/redo integration.

### D3.11.4 Assets
**Header:** id `assets` · icon `▣` · default dock `drawer` (studio).
- **Contents:** left type tree (models, textures, audio, prefabs, scripts, schemas), right **grid** of tiles (cell-based: 12×6 cells per tile in `term`, thumbnail via `asset.thumbnail`, falling back to a type glyph) or list view (`v` toggles). Search `/` (`asset.list {query}`). Drag a tile into the Viewport = `scene.spawn` at the ray hit; onto an asset field in the Inspector = assign.
- **Keys:** `<CR>` open (text assets → editor; others → reveal info), `y` copy asset path, `v` grid/list, `+`/`-` tile size (cell-snapped).
- **States:** `empty`, `loading` (thumbnails fill in lazily; placeholders first), `unsupported` (no `asset` cap → falls back to plain file listing from `project.files`).

### D3.11.5 Definitions
**Header:** id `definitions` · icon `§` · default dock `main-right` tab with Inspector.
- **Tree** grouped by schema (Weapons, Enemies, Items …) of files matched by `schema.for_file`; `n` new from template (`templates/<schema>.toml`, prompts id), `<CR>` select → Inspector, `d` duplicate, `D` delete file (P8; prefills `:!rm -i`, never deletes itself), `v` validate (`schema.validate`; errors become Problems with `source = schema`).
- **States:** `empty` (`no schemas — add schemas/*.schema.toml`), `module-not-loaded`.

### D3.11.6 Tweakables
**Header:** id `tweakables` · icon `≈` · default dock `main-right` tab with Inspector.
```
+- ≈ tweakables  player (6)  changed: 2 ------------------------------------------- [⧉][≡][✕] -+
| group▾  / filter    [ presets▾ ] [ commit all ] [ reset all ]                              |
| player.speed      [=======o----] 8.0  m/s  (default 6.0)  ●  [commit] [reset]              |
| player.jump_h     [====o-------] 1.2                                                       |
+--------------------------------------------------------------------------------------------+
```
- **Rows** for `tweak.list`: slider (min/max/step) + numeric `ViInput`, `bool` checkbox, `enum` select, `color` swatch, `vec3` three inputs. Changing sends `tweak.set {preview:true}` at ≤ 60 Hz while dragging, final non-preview `tweak.set` on release; `commit` → `tweak.commit` (writes the literal in source; disabled with tooltip `no literal source` when `-32005`); `●` marks `changed`. Presets: `tweak.preset.save/load/list`.
- **Keys:** `h/l` nudge by step (`H/L` ×10), `0` reset, `c` commit, `C` commit all (P8), `p` preset menu.
- **States:** `unsupported` (host lacks `tweak`), `empty`, `no-instance`.
- **Tests:** rate limiting of preview calls (≤ 60/s), commit conflict handling, preset round trip.

---
## D3.12 Panel registry (complete list)
| id | Title | Module | Icon (term) | Default dock | Multi | Shipped in layouts |
|---|---|---|---|---|---|---|
| `editor` | Editor | builtin editor | `λ` | main-left | no | edit |
| `game` | Game | game + host | `▶` | main-right | yes | edit, debug, play, focus-game |
| `console` | Console | kernel | `>` | overlay | yes | (drawer) |
| `log` | Log | kernel / logdb | `≡` | drawer | yes | edit, debug, play, studio, experiment |
| `problems` | Problems | diag | `!` | drawer | no | edit, play, studio |
| `search` | Search | index | `?` | drawer | yes | edit |
| `files` | Files | kernel | `/` | main-left | no | — |
| `outline` | Outline | index | `#` | main-left | no | — |
| `terminal` | Terminal | kernel | `$` | drawer | yes | — |
| `processes` | Processes | kernel | `⚙` | drawer | no | — |
| `timeline` | Timeline | timeline | `T` | main-right-bottom | no | debug, experiment |
| `state` | State | timeline + host | `{}` | main-right | yes | debug |
| `where` | Where | trace + index | `W` | drawer | no | debug |
| `patches` | Patches | patch | `Δ` | main-right-bottom | no | debug |
| `experiments` | Experiments | experiments | `X` | main | no | experiment |
| `modules` | Modules | kernel | `▦` | main-right | no | — |
| `bus` | Bus | kernel | `~` | — | yes | — |
| `perf` | Perf | kernel + hosts | `∿` | — | no | — |
| `help` | Help | GUI | `?` | main | no | — |
| `viewport` | Viewport | studio + runtime | `◫` | main | no | studio |
| `hierarchy` | Hierarchy | studio | `▤` | main-left | no | studio |
| `inspector` | Inspector | studio | `✎` | main-right | no | studio |
| `assets` | Assets | studio | `▣` | drawer | no | studio |
| `definitions` | Definitions | studio | `§` | main-right | no | studio |
| `tweakables` | Tweakables | studio | `≈` | main-right | no | studio |
| `ui:*` | (module-defined) | any | `◇` | per hint | per module | — |
**Dock names** used in `default_dock`: `main` (the central/first area), `main-left`, `main-right`, `main-right-bottom`, `drawer`, `overlay`. They resolve against the current layout by the rules of D1.7.2 (the nearest dock area containing a panel from that group, else the focused area).

## D3.13 New actions, keys and config introduced by D1–D3
- **Actions** (ids registered in `pipist-ui/actions`, each with `cmd` aliases): `drawer.toggle` (`:drawer`), `drawer.focus`, `drawer.tab <log|problems|search|console>`, `console.toggle`, `problem.next` (`]d`), `problem.prev` (`[d`), `search.next` (`]s`), `search.prev` (`[s`), `timeline.preview.next/prev` (`t]`/`t[`), `timeline.preview.clear`, `workspace.switch <name>`, `panel.help <id>`, `state.watch`, `game.prompt.focus`.
- **Leader additions** (13C.6 tree): `d` drawer group — `dd` toggle, `df` focus, `dl` log, `dp` problems, `ds` search, `dc` console.
- **Layouts shipped:** `edit`, `debug`, `play`, `studio`, `experiment`, `focus-game` (D1.7.1). Themes shipped: `term` (M6), `light`, `high-contrast` (token-only), `ide` (stretch).
- **Config keys:** `[gui]` additions in D1.13; `[timeline].confirm_goto = true`; `[editor].mirror_tabs`, `[editor].restore_session`; `[perf].window_s = 60`; `[studio].tab_toggles_play = false`.

## D3.14 Panel and GUI tests, and M6 done-when additions
- **Per panel:** fixtures for the seven states of D1.12, a golden `--dump-ui` text per state, and the panel-specific tests listed in each section. A meta-test enumerates the registry (D3.12) and fails if a panel lacks fixtures, a header, or a golden for any state.
- **Cross-panel scenarios (scripted, `--fake-daemon` and, where the host runs, live with the `hello-js` fixture):** (1) edit → game → log: send a line in Game, a record appears in Log with a tick link, activating it previews that tick (strip shows `PREVIEW`, State shows `viewing s_… (not live)`), `Esc` clears; (2) fork: preview → `<Enter>` in the strip → confirm toast → branch appears in Timeline, Game shows `restoring` then `running`; (3) patch: modify a function in a fixture file → Patches shows pending T1 → apply → badge `patch:T1` in the status bar; (4) problems: inject a diagnostic event → counts in tab, status bar and panel agree; `]d` jumps; (5) layout: `:pop log` → second OS window, `:dock log` → same slot, `:ws save t1` / `:ws edit` round-trip; (6) module stub: load `index` from the Search stub; (7) disconnect: kill the fake daemon → every panel shows `disconnected`, reconnect restores subscriptions without duplicate rows.
- **Performance:** idle 0 frames in 10 s (D1.12); Log 100k rows ≤ 8 ms/frame; State 50k keys ≤ 8 ms/frame; startup of the GUI to first frame ≤ 400 ms with the `edit` workspace against a fake daemon; RSS ≤ 120 MB with all shipped panels constructed (lazy panel construction: a panel is constructed on first show).
- **Done-when (M6, GUI part):** the checklist of 13C.12 and the milestone text for M6, plus: all panels of D3.12 marked "Shipped in layouts" or "M6" construct and pass the seven-state tests; the seven cross-panel scenarios pass offscreen; `--dump-layout` of every shipped workspace parses back to an identical tree; contrast test passes for `term`; no hard-coded colour outside the theme loader (lint test). Studio panels pass their own tests at M9; `ide` theme is optional.

<!-- SOURCE-END: pipist-spec-d3-panels-inspect.md -->

---

<!-- SOURCE-BEGIN: pipist-spec-e1-test-framework.md -->

# PIPIST SPEC — Appendix E1: Test framework, gates, evidence and cost control

Part of Pipist spec v1.3. Makes exact section 16 of the main spec and the "Done when" lines of section 17. Appendix E2 lists the concrete suites for each milestone M0–M14 and **depends on the rules defined here**. Where this appendix and section 16 differ, **this appendix wins**. Subsystem-specific test lists already defined elsewhere (B1.14, C1.13, D1.12/D3.14, 13C.12, A2.17, 3A.12, 13A) are *referenced*, not repeated; E2 assigns each of them to a milestone gate.

## E1.0 Principles
1. **A milestone is done only when its gate command exits 0 and its report is committed** (E1.4). Prose claims are worthless; `reports/gate-m<N>.json` is the evidence.
2. **Tests are written with, or before, the code** they cover. A pull of code without its listed tests may not be committed as a milestone commit.
3. **Tests must have teeth.** Every gate includes *teeth checks*: deliberately broken inputs, mutated builds or seeded faults that **must** make the relevant test fail (E1.7). A test that cannot fail does not count.
4. **No silent skips.** A test that cannot run in the sandbox is registered as `unverified` (E1.8) with the exact command the owner runs, never skipped, never deleted, never "passing" because it asserts nothing.
5. **Deterministic by construction.** Fixed seeds, virtual clocks, no wall-clock sleeps longer than 50 ms in unit tests, no network, no dependence on test order, no dependence on the machine's file-system timing beyond what is stated (watcher debounce).
6. **Cheap by default, thorough on demand.** The unattended run pays for compute: tiers (E1.2) keep the inner loop fast; the expensive suites run at gates and once at the end.
7. **Generality is tested.** Every web-adapter and GUI feature is exercised on all three fixtures; no test may depend on Los Ciegos being present (E1.9).
8. **No attribution trailers.** Commits must not contain `Co-Authored-By:` or tool-attribution trailers or text (owner's standing rule); `scripts/check-commits.sh` enforces it at every gate (E1.6).

## E1.1 Layout and naming
```
tests/
  gates.toml                 milestone gate definitions (E1.3) — single source of truth
  unverified.toml            registry of tests that cannot run here (E1.8)
  quarantine.toml            known-flaky tests with owner decision (E1.5)
  lib/                       shared harness: pipist_client.py (socket client), fake_clock.h, golden.py, procwatch.py, perf.py, fixtures.py
  unit/                      Catch2 C++ tests: <area>_<topic>.cpp
  integration/               Python (pytest) tests driving a real pipistd over its socket: test_<area>.py
  e2e/                       headless-game and GUI end-to-end: test_<fixture>_<scenario>.py
  protocol/                  schemas, examples/*.jsonl, fuzz (A2.17)
  perf/                      perf tests + budgets.toml (E1.7)
  chaos/                     kill/flood/truncate tests
  gui/                       *.script, golden/, fixtures/ (fake-daemon), screenshot helpers
  dom-diff/, transform/, walker/   Appendix B1.14 corpora
  gen/                       generators: refgame.py (synthetic game of N scripts / M lines), refproject.py, statebig.py, randtree.py
  fixtures/                  data/ (toml, json, lua), schemas/, broken-projects/, scenes/
examples/                    hello-js, hello-ui, hello-canvas, hello-lua, runtime-demo (and los-ciegos if supplied)
```
- **Test ids** are `M<milestone>.<n>` registered in `gates.toml`; the test source carries the id in its name or tag (`[M4.7]` in Catch2, `@pytest.mark.gate("M4.7")` in pytest). The meta-test `tests/unit/gates_consistency` fails if an id in `gates.toml` has no test or a gate-tagged test has no id.
- **Goldens** live next to their tests (`*.golden.txt`/`.json`). Goldens are updated only by running the test with `UPDATE_GOLDEN=1` **and** adding a line to `docs/DECISIONS.md` (`golden <path>: <reason>`). `scripts/ci.sh` fails if a golden changed in the working tree without a matching DECISIONS line since the last commit.
- Test programs print machine-readable result lines (`GATE_RESULT <id> pass|fail|unverified <ms>`); `scripts/ci.sh` collects them into `reports/`.

## E1.2 Tiers and commands
| Tier | Command | What runs | Budget (wall, 4 cores) | When |
|---|---|---|---|---|
| `quick` | `scripts/ci.sh quick` | Build (incremental, `debug`), all unit tests, protocol schema/example validation, lint checks (E1.6), integration smoke subset (tag `quick`), `deps-check` | ≤ 90 s | Before every commit; the inner loop |
| `milestone N` | `scripts/ci.sh milestone N` (alias `scripts/gate.sh N`) | Everything `gates.toml` lists for M0…N cumulatively: full unit/integration/e2e for milestone N; **regression subset** (tag `reg`) of all earlier milestones; sanitizer subset (tag `san`) under `asan` and, for threaded code, `tsan`; perf tests with `PIPIST_PERF_STRICT=1`; teeth checks (E1.7); commit hygiene | ≤ 20 min for M0–M6, ≤ 30 min for M7+ | Once to close a milestone (plus re-runs of failing suites only) |
| `full` | `scripts/ci.sh full` | All suites of all milestones, long fuzz (50k HTML/JS cases, protocol fuzz 10 min), crash-injection 500 iterations, full sanitizer matrix, DOM-diff 150+ scripts, **scale tests** (C1.13 scale, viewport 1080p soak 60 s), docs build | ≤ 2 h | At M5, M8 (subset), M14, and before the final tag |
| `nightly` | alias of `full` plus repeated-run stability (E1.5) | | | Only on the owner's machine/CI; the cloud run does not schedule it |
- **Re-run discipline (cost control):** after a failed gate, `scripts/ci.sh milestone N --only-failed` re-runs only the suites that failed (plus a final complete run once all pass). A complete gate run is expected **at most twice** per milestone; a third complete run requires a `DECISIONS.md` line explaining why.
- **Build presets used by tiers:** `debug` (quick), `release` (perf), `asan` (ASan+UBSan), `tsan`, `headless` (`-DPIPIST_GUI=OFF`), `min` (kernel only, size/RSS checks). Presets are built once per gate and reused; the gate script prints the preset build time so cost is visible in the report.
- **Parallelism:** unit and integration tests run with `ctest -j` / `pytest -n` up to `min(cores, 8)`; tests that bind sockets use per-test runtime dirs (`$XDG_RUNTIME_DIR/pipist-test-<pid>-<n>`) so they never collide; perf tests run **serially** after everything else, with other test processes absent.

## E1.3 `tests/gates.toml` — the gate definition
```toml
[milestone.M0]
required = ["M0.1", "M0.2", "M0.3", "M0.4", "M0.5", "M0.6"]   # all must pass
teeth    = ["M0.T1", "M0.T2"]                                 # seeded-failure checks, must FAIL as designed (reported as pass when they do)
unverified_allowed = []                                       # ids permitted to be reported 'unverified' for this milestone
perf     = ["P.ping_rtt", "P.kernel_cold_start"]              # performance gates (E1.7)
sanitizers = { asan = ["M0.1"], tsan = [] }
est_minutes = 3

[test."M0.1"]
title = "NDJSON framing and JSON wrapper"
kind  = "unit"                                                # unit | integration | e2e | protocol | perf | chaos | gui | lint
cmd   = "ctest --preset debug -R framing"
tags  = ["quick", "reg", "san"]
timeout_s = 60
```
- `scripts/gate.sh N` computes the cumulative set, runs `cmd`s in dependency order (unit → integration → e2e → perf), enforces `timeout_s` (kill + fail), checks `unverified_allowed`, and writes **`reports/gate-m<N>.json`** (per test: id, status, duration, stdout tail 40 lines, golden changes) and **`reports/gate-m<N>.md`** (human summary). It exits 0 only if every `required` test passed, every `teeth` check behaved as designed, every `perf` entry is within budget (strict mode), no test outside `unverified_allowed` was unverified, and no gate-tagged test was skipped.
- **Cumulative regression:** milestone N's gate runs tag `reg` tests of M0…N-1. A regression failing in an earlier area is fixed in that area before the milestone can close; the report lists it under `regressions`.
- **`STATUS.md`** is regenerated from `reports/` by `scripts/status.py` at the end of every gate: milestone table (state: `not started | in progress | done | done-with-unverified`), failing tests, budgets table (measured vs budget), unverified list with owner commands, decisions count, spend estimate. It is never hand-edited except the "Notes" section.

## E1.4 What "done" means and what gets committed
A milestone commit contains: the code, the tests, updated goldens (with DECISIONS lines), `reports/gate-m<N>.json|md`, regenerated `STATUS.md`, and tag `m<N>-done` created by `scripts/gate.sh N --tag` **only** after exit 0. If the gate cannot reach exit 0 within the budget rules of E1.9, the milestone is tagged `m<N>-partial`, `STATUS.md` states what fails and why, and work proceeds only if the failure does not block the next milestone (stated in the report); otherwise the run stops and reports (E1.9).

## E1.5 Determinism, flakiness and quarantine
- **Randomness:** every randomized test (property, fuzz, chaos) prints its seed (`SEED=…`) and accepts `PIPIST_TEST_SEED`; failures print a one-line repro command. Default seed in the gate is derived from the commit hash so reruns are reproducible; `full` additionally runs 3 other seeds.
- **Time:** C++ code under test takes a clock interface; tests use `FakeClock`. Integration tests that must wait poll with a deadline (never fixed sleeps): `wait_until(pred, timeout=5 s, interval=10 ms)`. Debounce/timeouts are tested through the fake clock where possible; the real-time ones (watcher debounce, 150 ms edit→event) are marked `rt` and given 3× headroom in non-strict mode.
- **A new e2e/integration/GUI test must pass 5 consecutive runs** (loop run by `scripts/ci.sh stable <id> 5`) before its id may be added to `required`. This is recorded in `reports/stability.json`.
- **No automatic retries.** A flaky test is fixed, or quarantined: an entry in `tests/quarantine.toml` (`id`, `reason`, `date`, `owner_decision`) removes it from `required` **and** requires a DECISIONS line; quarantined tests still run and are reported. More than 3 quarantined tests at a gate blocks the tag.
- **Leak detection (every integration/e2e test, automatic):** after each test the harness verifies that no child process of the test daemon survives (`procwatch`: process-group check), no fds remain open in the daemon beyond its baseline (`/proc/<pid>/fd` count), runtime dirs/sockets are removed, and no file outside the test's temp directory changed. A leak fails the test.

## E1.6 Cross-cutting automatic checks (part of `quick` and every gate)
| Check | Command | Fails when |
|---|---|---|
| Dependency policy | `scripts/deps-check.sh` | A library outside the admitted list (2A) is linked/vendored; the kernel links anything beyond libuv, yyjson, tomlc17; a module links GUI code; license file missing in `third_party/` |
| Layering | `scripts/layer-check.sh` | `pipistd` sources include headers from `modules/`, `pipist-ui/` or `pipist-gui/`; a module includes another module's private headers |
| Formatting/lint | `clang-format --dry-run`, `clang-tidy` (curated set), `ruff` on Python tests, `shellcheck` on `scripts/` | any diagnostic in the enabled set |
| No hard-coded colours | `scripts/lint-colours.sh` | an ImGui colour literal or hex colour outside `pipist-ui/theme` (D1.9) |
| Commit hygiene | `scripts/check-commits.sh` | any commit since the last tag has a `Co-Authored-By:` line, a tool/model attribution line, or `Generated with` text; subject longer than 72 chars; empty body for non-trivial diffs (> 200 lines) |
| Protocol schemas | `tests/protocol` (A2.17 #1) | schema missing, example missing, example invalid, or schema/example drift from the spec tables |
| Docs links | `scripts/docs-check.sh` | internal link or `docs/help` panel page missing |
| Secrets/paths | `scripts/hygiene.sh` | absolute home paths, tokens, or `.pipist/` runtime files in the tree |
| Performance baseline | `tests/perf` (E1.7) | any measurement worse than budget × 1.25 (strict) or × 2.0 (non-strict) |
`scripts/ci.sh` prints each check's result in one line (`ok`/`FAIL` + one-line cause) so a failing run is understandable from the last 30 lines.

## E1.7 Performance testing method, and teeth checks
**Method.** Perf tests live in `tests/perf/` and use `tests/lib/perf.py`/`perf.h`: warm-up 3 iterations (discarded), measure ≥ 15 iterations (≥ 1000 for round-trip latency), report median and p99 (latency budgets use p99; throughput/time budgets use median). Each result is appended to `reports/perf-<preset>.json` with machine info (cores, model, kernel, governor if readable, load average before/after). Budgets come from 3A.12, 13A.2, B1.14, C1.5, D3.14 and E2; they are stored once in `tests/perf/budgets.toml` (id, metric, budget, kind `latency|time|rss|rate`, strict_factor 1.25, hard_factor 2.0). A perf test fails when `measured > budget × factor` where factor is 1.25 in `PIPIST_PERF_STRICT=1` (milestone gates) and 2.0 otherwise (`quick`). If load average during the run exceeded the core count, the test re-runs once automatically (the only permitted retry) and the report notes `noisy`. Software-rendered GPU numbers are measured and **reported**; a budget that depends on a real GPU is `unverified` when only llvmpipe is available (E1.8).
**Teeth checks** (`M<N>.T<k>`): scripted negative experiments proving that a gate can fail. Each runs the real test against a seeded fault and passes only if the test fails with the expected message:
- `M0.T1` inject a banned header include → `deps-check` fails; `M0.T2` seed a commit with a `Co-Authored-By` trailer in a temp repo → `check-commits` fails.
- `M1.T1` build the kernel with `PIPIST_SELFTEST_BUSYLOOP=1` (spins 5% CPU on a timer) → the idle-CPU test fails; `M1.T2` module that ignores `mod.shutdown` → unload test fails with SIGKILL escalation reported.
- `M5.T1`–`T3` the three negative adapter fixtures of B1.14; `M5.T4` flip one byte in a pack → fsck/`damaged` detection fires.
- Later milestones list their own in E2. Teeth checks run in the gate but are excluded from `quick`.

## E1.8 The `unverified` registry
Anything that depends on hardware or software the cloud sandbox lacks (real GPU, dma-buf, tiling window manager, HiDPI, a specific nvim/clangd version, the owner's own game copy (if supplied), IME, audio) is declared in `tests/unverified.toml`:
```toml
[[unverified]]
id = "M8.dmabuf"
tests = ["M8.10"]
reason = "no dma-buf capable GPU in the cloud sandbox"
owner_command = "pipist-vp-test --dmabuf && pipist-gui --video x11 --script tests/gui/viewport.script --screenshot out.png"
expect = "exit 0; out.png shows the moving test pattern"
```
Rules: (1) the test still **exists and compiles**, and runs in a degraded form where possible (e.g. dma-buf negotiation unit-tested with mocks; the GL-dependent half is unverified); (2) the gate reports it as `unverified`, not `pass`; (3) a milestone with unverified items ends as `done-with-unverified` and `STATUS.md` lists each with its owner command; (4) a test may only be registered unverified if the reason is environmental — "too slow", "hard to write" or "flaky" are not reasons; (5) `scripts/verify-owner.sh` (generated from the registry) runs every owner command on the owner's machine and prints a pass/fail table; the owner's results can be pasted back to close items.

## E1.9 Handling failure in an unattended run, and the spending guard
1. **Red gate:** read the first failing test's output; fix the code (or the test if the test is wrong, with a DECISIONS line); re-run `--only-failed`. Never delete or weaken an assertion to make a gate pass without a DECISIONS line stating the spec text that justifies it.
2. **Stuck test:** if one test fails after 3 distinct fix attempts, bisect with `scripts/bisect.sh <id>` (git bisect over the tests only). If still stuck after the 4th attempt: quarantine only if the test is not in the milestone's `required` core list (E2 marks core tests with ★); a ★ test that cannot pass stops the milestone: tag `m<N>-partial`, write the blocker in `STATUS.md` under "Blocked", and continue **only** with work that does not depend on it.
3. **Budget guard:** after each gate the run records an estimate of spend so far in `STATUS.md` (tokens/compute seconds as measured by the run) and compares to the plan in the launch prompt. Cut order if short: M14, M13, M12, M10, M11 (docs/templates first), then Studio polish; never cut the tests of milestones that remain, and never leave the tree red: the last commit always passes `quick`.
4. **Los Ciegos absent:** tests that reference the real game are registered `unverified` with reason `game not provided` and owner command `scripts/verify-owner.sh lc`; the generated `refgame` fixtures (E2.0) stand in for performance and scale gates. No test may fail because the game is missing.
5. **Sandbox limits:** when a tool needed by a test cannot be installed (no network beyond package registries), the test is `unverified` per E1.8, not removed.

## E1.10 Shared fixtures and generators (created at M0–M4, used throughout)
| Fixture | Created at | Purpose |
|---|---|---|
| `examples/hello-js` | M0 (grows at M4) | Text-prompt adventure (B1.14): rooms, inventory `let`, `const` state, class instances, `setTimeout` beats, `;` chain, `localStorage`; includes a **dress-check NPC** (a gated interaction whose outcome depends on an inventory item) so M2/M13 acceptance does not need Los Ciegos |
| `examples/hello-ui` | M4 | ES-module button/form app (B1.14) |
| `examples/hello-canvas` | M4 | rAF canvas game (B1.14) |
| `examples/hello-lua` | M0 | Lua native toy used by process/target tests |
| `examples/runtime-demo` | M8 | SDL3 + Lua entity world implementing the runtime contract |
| `tests/gen/refgame.py --scripts 29 --lines 25000 --seed S` | M2 | Synthetic classic-script game with module-level `let`s, a global state object, timers, DOM updates; used for index/transform/boot/snapshot performance and scale gates |
| `tests/gen/refproject.py` | M2 | Mixed-language tree (js/html/css/lua/c/cpp/py/toml/json/md) for index tests |
| `tests/gen/statebig.py --mb N --change-pct P` | M5 | Synthetic `web/1` and `raw/1` states with controlled change rate |
| `tests/gen/randtree.py` | M9 | Random TOML/JSON/Lua-data trees and random edit scripts for `fmtedit` property tests |
| `tests/fixtures/broken-projects/*` | M2/M12 | Projects with seeded syntax errors, load-order bugs, lint violations, each with an `expected.json` of diagnostics |
Generators are deterministic given `--seed` and print a content hash; the tests assert the hash so a generator change is noticed.

<!-- SOURCE-END: pipist-spec-e1-test-framework.md -->

---

<!-- SOURCE-BEGIN: pipist-spec-e2-milestone-tests.md -->

# PIPIST SPEC — Appendix E2: Per-milestone test plans (M0–M14)

Part of Pipist spec v1.3. Uses the framework of Appendix E1 (ids, tiers, gates, teeth, unverified registry, generators). Each milestone lists: **Suites** (`M<N>.<k>`, ★ = core: a failing ★ test stops the milestone, E1.9), **Teeth** (`M<N>.T<k>`), **Perf** (ids in `tests/perf/budgets.toml`), **Unverified** (E1.8) and **Gate time**. "Reg" marks suites that also run in later gates as regression tests. Counts such as "≥ 60 cases" are minimums enforced by a count check in the test. Specs referenced (B1.14, C1.13, D3.14, 13C.12, A2.17, 3A.12) are authoritative for *what* the suite contains; this appendix assigns *when* and *how it is judged*.

## E2.0 Conventions used below
- "**oracle**" = an independent implementation compared against (e.g. `rg`, Python's `tomllib`, Chromium, a naive reference model); "**golden**" = committed expected output; "**property**" = randomized test with a printed seed.
- "**fixture games**" = `hello-js`, `hello-ui`, `hello-canvas` (after M4). Any suite said to run "on fixtures" runs on all three unless the feature obviously applies to one (stated).
- Timing tests state the budget; strict gates apply ×1.25 (E1.7).
- "**ref game**" = `tests/gen/refgame.py --scripts 29 --lines 25000 --seed 1`; "**ref project**" = `tests/gen/refproject.py --seed 1`.

---
## M0 — Skeleton and policy tooling
**Suites**
- ★M0.1 *Framing and JSON wrapper* (unit): NDJSON split at every byte offset of a 40-message stream reassembles; CRLF accepted; lone `\n` inside strings escaped; message of 16 MiB + 1 byte → error `-32008` and connection closed; top-level array → `-32600`; invalid UTF-8 → `-32700`; 10 000-deep nesting rejected without stack overflow (ASan clean). ≥ 60 table rows.
- ★M0.2 *Hello/ping end to end* (integration): `pipistd --project <tmp>` starts, `session.hello` → result matches the A1.5 schema, `session.ping` works, requests before hello → `-32600`, protocol `"2"` → `-32013`; `pipist ping` CLI exits 0.
- ★M0.3 *Policy tooling* (lint): `deps-check.sh` accepts the clean tree; `layer-check.sh` accepts it; the kernel binary's dynamic dependencies (`ldd`) contain only libc/libstdc++/libm/libpthread plus libuv if dynamic.
- ★M0.4 *Presets* (build): each of `min debug release asan tsan headless` configures and builds; `min` produces only `pipistd` and `pipist`; `headless` has no GUI targets.
- ★M0.5 *Gate tooling self-test* (unit/py): `gates.toml` consistency meta-test; `gate.sh` returns nonzero when a required test is missing, skipped, over its timeout, or its id is untagged; `status.py` regenerates `STATUS.md` deterministically (second run byte-identical).
- M0.6 *Fixtures sanity*: `hello-js` loads under Node (oracle) and prints the expected transcript of a scripted 12-line session (the golden later reused by M4); `hello-lua` runs under the system Lua.
**Teeth:** T1 seeded banned include → `deps-check` fails; T2 seeded `Co-Authored-By` trailer in a scratch repo → `check-commits` fails.
**Perf:** `P.ping_rtt` < 2 ms p99 over 1000 pings; `P.kernel_cold_start` < 40 ms (exec → first ping reply).
**Unverified:** none. **Gate time:** ≈ 3 min.

## M1 — Kernel, modules, targets
**Suites**
- ★M1.1 *Router and requests* (integration+unit): unknown method `-32601`; `_meta.timeout_ms` expiry `-32006` and the target receives `session.cancel`; `session.cancel` of an in-flight request → `-32007`; duplicate in-flight id `-32600`; request-id reuse after completion allowed; response ordering independent of request order; forwarded ids are `k:<n>`; rate limit 2000 req/s → `-32009`.
- ★M1.2 *Bus* (unit+integration): topic glob matching table (≥ 40 rows incl. `*` vs `**`); `since_seq` replay delivers exactly the missed events in order; `gap` flagged when the ring overflowed; slow-client overflow yields exactly one `bus.dropped` per burst and never drops requests (client with 1 s-delayed reads under a 20 000-event flood); `seq` strictly increasing.
- ★M1.3 *Config and profiles*: layer precedence builtin < user < project < local < cli < env (≥ 40 cases), comment-preserving `config.set` (diff of the TOML shows only the changed line), `config.reload` events, profile resolution (`min` default; unknown profile error), `[startup].autoload`.
- ★M1.4 *Module manager state machine*: table of transitions (unavailable→registered→starting→ready→stopping, failed, degraded); lazy activation: 100 concurrent callers to a cold module cause exactly 1 spawn and all get correct results; calls during `starting` queue and flush in order; crash during a call → `-32011` for that call, restart with backoff `[250, 1000, 4000]` ms measured on the fake clock, `failed` after `max_restarts` → `-32010`; dependency ordering and cycle rejection; `module.unload` refuses when depended upon unless `force`; unload frees the process (pid gone, within 2× `grace_ms`); manifest parse errors list file and key.
- ★M1.5 *Process supervisor*: `proc.start` argv and shell forms; env scrubbing (only the A1.7 list + `[env]` + request env); process-group kill reaps grandchildren; `restart` policies `never|on-failure|always` with backoff; PTY processes: `proc.attach_pty` returns a master fd via `SCM_RIGHTS`, the test client writes `echo hi` and reads it back; resize via `proc.resize` changes `stty size` seen by the child; WebSocket attach → `-32005`; `proc.output` batching ≤ 50 ms; killing a child → `proc.crashed`.
- M1.6 *Log ring and blobs*: ring of 20 000 with `log.query` filters (level, source, text, regex, tick range, cursor pagination stable across inserts); blob put/get/stat, `put_path` hardlink vs copy, `blob.gc` keeps referenced blobs, 8 MiB limit.
- ★M1.7 *Targets and problem matchers*: `target.run` for build/test/game, `depends` order and abort on failure, `wait` form; matcher goldens for gcc, clang, cmake, ninja, node, lua, python tracebacks (≥ 8 sample outputs each with expected `target.problem` events).
- ★M1.8 *Watcher*: edit → `file.changed` with hash; 1000 writes within 50 ms collapse to ≤ 3 events per file; rename/delete/create; ignore rules (`.gitignore`, config); symlink escape not followed; unreadable dir does not crash.
- M1.9 *WebSocket endpoint*: missing/wrong token → `-32001` + close; bad `Origin` rejected; agent method set enforced (a `proc.start` over WebSocket → `-32601`/`-32001`); frames ≤ 16 MiB.
- ★M1.10 *Discovery/autostart/lock*: two simultaneous `pipist up` yield one daemon; stale lock/socket after `SIGKILL` recovered; `pipist down` clean; socket dir mode 0700 / socket 0600; peer uid check.
- ★M1.11 *CLI*: `up/down/status/doctor/build/run/test/modules/load/unload` exit codes and JSON output mode (`--json`) validated against schemas; `doctor` prints missing tools and Gentoo hints.
- ★M1.12 *Protocol fuzz and chaos*: A2.17 #2 fuzz for 60 s (gate) / 10 min (full); chaos: kill a child mid-call, truncate a module reply, flood events to a stalled client — daemon stays up, no fd leak (fd count back to baseline ±2), no zombie.
- ★M1.13 *Budgets*: kernel idle RSS < 8 MB and 0% CPU over 10 s; process list after `up --profile min` is exactly `pipistd`; builtin module first-use < 5 ms; `pipist run` overhead < 30 ms; file edit → event < 150 ms (`rt`).
**Sanitizers:** ASan+UBSan on M1.1–M1.5, M1.8, M1.12; TSan on M1.2, M1.4, M1.5 (threads: IO, watcher).
**Teeth:** T1 busy-loop build fails idle-CPU; T2 module that ignores shutdown → unload escalates and the test records `SIGKILL`; T3 a seeded fd leak (`PIPIST_SELFTEST_LEAKFD=1`) fails the leak detector.
**Perf:** `P.idle_rss_min`, `P.idle_cpu`, `P.module_first_use`, `P.run_overhead`, `P.watch_latency`.
**Unverified:** none (inotify available). **Gate time:** ≈ 12 min.

## M2 — Index and syntax diagnostics
**Suites**
- ★M2.1 *Text search vs oracle*: 500 random queries (literal, regex, case modes, globs) over the ref project and the three fixtures; result sets equal `rg --json` output as (file, line, col) sets; `truncated` correct at `limit`.
- ★M2.2 *Symbols/outline goldens*: one golden JSON outline per language file in `tests/fixtures/langs/` (js, html with inline scripts, css, lua, c, cpp, python, json, toml, markdown); tolerance none.
- ★M2.3 *HTML inline-script offsets*: for 30 HTML files with multiple/nested-looking `<script>` blocks, every symbol/diagnostic position maps to the exact file line/column (checked by extracting the byte at the reported range).
- ★M2.4 *Strings and entities*: `search.strings` finds quoted strings across `.js`, `.lua`, `.toml`; entity extraction from `data/*.toml`/`*.json` keys according to the configured pack; `search.where` ranking golden (≥ 20 queries incl. the dress-check scenario on `hello-js`: query "dress code" returns the function and the turn-away string, ranked function-first).
- ★M2.5 *Syntax/engine diagnostics*: 40 seeded errors (js, inline html script, lua, c, cpp, python, json, toml) each reported with exact `file:line:col`, severity and source (`syntax` or `engine`); no false positives on the clean fixtures; `diag.updated` replace semantics (fixing the error clears it).
- ★M2.6 *Incremental indexing*: edit a file → `index.updated` within 300 ms (`rt`); only that file reparsed (instrumented counter); delete/rename handled; index DB survives restart (warm open) and is rebuilt if the schema version differs or the DB is corrupted (truncate test).
- M2.7 *Laziness*: after `pipist up` no `index`/`diag` process; the first `search.text` spawns exactly one `index`; `module.unload index` frees it; grammar libraries load lazily (counter) — using only js does not load the lua grammar.
- ★M2.8 *Large-file handling*: a 2.1k-line script and a 20 000-line generated file index within budget; a 5 MB minified file is skipped with a warning (not a crash).
- M2.9 *Acceptance on the real game*: if `examples/los-ciegos` exists, `pipist where "dress code"` returns `laSenoraDressCheck` and the turn-away string; otherwise the same assertions run on the `hello-js` dress-check NPC (unverified registry entry `M2.lc`).
**Sanitizers:** ASan on M2.1–M2.5 (parsers). **Teeth:** T1 truncate a grammar file → the test reports `grammar_load_failed` and diagnostics still work for other languages.
**Perf:** `P.index_cold_25k` < 2 s (ref game), `P.index_warm_open` < 250 ms, `P.query_text_p99` < 30 ms on 25k lines, `P.incremental_reindex` < 300 ms.
**Unverified:** `M2.lc` (real game). **Gate time:** ≈ 10 min.

## M3 — Editor integration
**Suites**
- ★M3.1 *msgpack codec*: round-trip of every type (nil, bool, ints at all width boundaries, floats, str, bin, array, map, ext), property test with random nested values, malformed-input fuzz (no crash, bounded memory), conformance vectors from the msgpack spec embedded in the test.
- ★M3.2 *nvim attach*: with a real `nvim --headless --listen`: `editor.attach`, `editor.open` (all modes), `editor.goto` (cursor read back through `nvim_win_get_cursor`), `editor.current`, `editor.buffers`, `editor.command` output, `editor.save`.
- ★M3.3 *Notifier*: BufWritePost → `editor.saved`; cursor moves → debounced `editor.cursor` (≤ 20/s); buffer list changes → `editor.buffers`; the injected Lua is idempotent across re-attach; nvim exit → `editor.detached` and `editor.*` calls give `-32004 no_editor`.
- ★M3.4 *`editor.apply` write path (13B.4 cases)*: clean open buffer → applied through `nvim_buf_set_text` and written; dirty buffer → buffer-only, reported `unsaved`; closed file → atomic disk write (tmp+rename; permissions preserved); overlapping edits rejected; undo in nvim reverts an applied edit.
- ★M3.5 *Index integration*: saving in nvim triggers `file.changed` and an index update (end to end).
- M3.6 *Fallbacks*: `nvim` missing → `editor.start` returns `-32010` with install hint; `[editor].command` override; PTY size passed to nvim equals requested.
- ★M3.7 *`pipist edit` / `pipist goto`*: CLI starts or reuses nvim, opens `file:line:col`; second invocation reuses the same nvim.
**Teeth:** T1 kill nvim mid-request → request fails with `-32011`-class error (not a hang), daemon keeps running.
**Perf:** `P.edit_open` < 150 ms warm.
**Unverified:** if nvim cannot be installed in the sandbox: M3.2–M3.7 `unverified` with `reason = "nvim not installable"`, owner command `scripts/verify-owner.sh m3`; M3.1 still runs. **Gate time:** ≈ 5 min.

## M4 — Headless web host
**Suites** (B1.14 defines contents; E2 assigns)
- ★M4.1 *Transform corpus* (≥ 60 scripts): output parses, preserves every line number, registers exactly the expected names, behaves identically with/without transform (console outputs equal).
- ★M4.2 *HTML loading*: script order (classic, defer, async, module), inline vs `src`, `DOMContentLoaded`/`load` ordering, `document.write` in the allowed forms, missing `src` → clear error with file:line; ≥ 40 pages.
- ★M4.3 *DOM/Web API shim differential* (≥ 150 scripts, S and L rows of B1.8): host output equals Chromium (Playwright) output; the allow-list of known differences is explicit (each entry has a reason) and ≤ 10 entries.
- ★M4.4 *Virtual clock, timers, RNG*: timer ordering table (≥ 60 cases: nested `setTimeout(0)`, `setInterval` drift, rAF ordering, microtask vs timer), `Date`/`performance.now` virtual, `xoshiro128**` golden vectors for 10 seeds, `Math.random` determinism across runs, boot/gameplay timer classification.
- ★M4.5 *Input kinds*: each of `line/text/key (hold)/button/click/pointer/wheel` verified on the fixture that uses it, with DOM event sequences compared to Chromium for key/click/pointer sequences (event types and order).
- ★M4.6 *Regions and tick unit*: with **no configuration**, region detection and tick-unit resolution give the expected answers per fixture (`hello-js`: log+status+buttons+prompt, unit `input`; `hello-ui`: buttons, no prompt, unit `input`; `hello-canvas`: summary mode, unit `frame`).
- ★M4.7 *Renderer goldens*: screen model output (`game.screen.get`) goldens for ≥ 20 states across fixtures; ANSI stripped and ANSI-bearing variants; `game.output`/`game.screen` event goldens.
- ★M4.8 *Determinism*: each fixture, fixed seed, scripted inputs → transcript and per-tick state-hash sequence identical across 3 runs and across `realtime|fast|stepped` modes (modulo documented differences).
- ★M4.9 *Strict shim audit*: `pipist adapter audit` under the strict shim: zero unexplained gaps on all three fixtures; `adapter describe|suggest` output goldens; `suggest` proposes the config that B1.11 worked examples show for the corresponding fixture (diffed).
- ★M4.10 *Host robustness*: infinite loop interrupted by the watchdog (≤ `watchdog_ms` + 200 ms) and reported with a stack; `memory_mb` cap → clean crash event; uncaught exceptions logged with `file:line` links; `net=deny` enforced; 10 000 random HTML/JS cases (gate) / 50 000 (full) never crash the host.
- ★M4.11 *`pipist play` and CLI*: scripted PTY session drives `hello-js` through `pipist play` (prompt via ViEngine line, buttons via `<Alt-n>`); `pipist adapter describe|audit|suggest` exit codes and JSON.
- M4.12 *`doctor --host-compat`*: agrees with Chromium on all three fixtures or lists only allow-listed differences.
- M4.13 *Los Ciegos acceptance*: boots, accepts a name, runs a scripted 30-input playthrough with a stable golden transcript — or `unverified` (`M4.lc`).
**Sanitizers:** ASan+UBSan on M4.1–M4.5, M4.10 (QuickJS embedding, parser); TSan not applicable (single-threaded host).
**Teeth:** T1 strict shim: delete one shim function → audit reports the gap by API name with a stack; T2 introduce a nondeterminism (`Date.now` native) in a test fixture → M4.8 fails.
**Perf:** `P.host_boot_25k` ≤ 150 ms (ref game), `P.host_rss_25k` ≤ 80 MB, host idle CPU 0%, `P.transform_25k` ≤ 120 ms.
**Unverified:** `M4.lc`. **Gate time:** ≈ 18 min (DOM-diff dominates; Chromium is preinstalled).

## M5 — Adapter, snapshots, timeline, fork
**Suites** (B1.14 and C1.13 define contents)
- ★M5.1 *Walker corpus* (≥ 100 value graphs): C++ and JS-agent walkers produce byte-identical Pipist Value JSON; encode→decode→sync round-trips preserve aliasing, cycles, Maps/Sets, typed arrays, class instances with known classes; functions rejected with the offending path unless `keep-live`.
- ★M5.2 *Value encoding property tests* (A2.17 #8): random Values round-trip in C++ and JS, `$t` escaping.
- ★M5.3 *Chunkers and store* (C1.13 unit — chunkers, store, corruption): FastCDC golden vectors; insert-1-byte locality; pack record bit-flip detection; truncated pack recovery; ENOSPC simulation.
- ★M5.4 *Crash consistency* (C1.13): SIGKILL during 100 puts (gate) / 500 (full); invariants hold after each restart; `fsck --deep` passes.
- ★M5.5 *Thinning and quota* (C1.13): tier schedule table (≥ 40 rows), escalation L1→L4 on a 64 MB test quota, protected snapshots survive, idempotence, put never blocked > 5 ms by thinning.
- ★M5.6 *Tree semantics* (C1.13): fork/rewind/archive/delete/prune incl. tombstones, `fork:false` auto-fork, concurrent instances, experiment-branch auto-delete (stubbed experiment flag).
- ★M5.7 *Persistence modes* (C1.13).
- ★M5.8 *Delta transport*: delta puts reconstruct byte-identical state; missing base → `-32002` and the host resends full; `full_every` honoured.
- ★M5.9 *Restore on fixtures*: snapshot at K, continue, restore K, continue differently → branch tree correct, state equals original at K (hash), screen redrawn; in-flight narration timers cancelled on restore (`hello-js`); a mid-combat-equivalent state (`hello-js` fight scene, module-level `let`) restored correctly; `reboot` and `in-place` both pass on all three fixtures; `timeline.goto` fork/no-fork rules.
- ★M5.10 *`adapter verify`*: PASS on all three fixtures with the strides of B1.14.
- ★M5.11 *Negative adapter fixtures* (teeth): the three variants of B1.14 fail with the stated reports (IIFE closure state → divergence; gameplay-`setTimeout` spawner → `W_TIMERS_DROPPED` + verify failure; `#private` field → audit reports unreachable state).
- M5.12 *Source capture* (C1.13): revision manifests, `source.diff` equals `diff -u`, caps, `source-restore` never touches the tree without `--in-place`.
- ★M5.13 *Delta size target*: stored bytes ≤ 25% of full over a 200-tick `hello-js` playthrough.
- M5.14 *Protocol additions*: all new `timeline.*` methods/events (C1.12) have schemas and examples; A2.17 #9 adapter formats validate.
- M5.15 *Real-game restore*: Los Ciegos copy restore incl. mid-combat snapshot — or `unverified` (`M5.lc`).
**Sanitizers:** ASan+UBSan on M5.1–M5.8; TSan on M5.3–M5.5 (ingest worker pool).
**Teeth:** T1–T3 are M5.11; T4 flip one byte in a pack → `fsck --deep` and read path report `damaged`; T5 disable chunk dedupe via `PIPIST_SELFTEST_NODEDUPE=1` → M5.13 fails.
**Perf:** `P.ingest_5mb_web` ≤ 30 ms CPU / 40 ms round-trip, `P.ingest_100mb_raw` ≤ 350 ms, `P.get_5mb_warm` ≤ 25 ms, `P.get_5mb_cold` ≤ 80 ms, `P.restore_reboot` ≤ 300 ms, `P.snapshot_capture_5mb` ≤ 50 ms, `P.fingerprint_5mb` ≤ 10 ms, `P.timeline_spawn` < 100 ms, module RSS idle ≤ 40 MB.
**Scale (full tier only, run once at M5):** C1.13 scale test (200 MB × 1000 snapshots); results reported in `STATUS.md`.
**Unverified:** `M5.lc`. **Gate time:** ≈ 20 min (+ ≈ 25 min full-tier scale run once).

## M6 — GUI shell v1
**Suites** (D1.12, D3.14, 13C.12 define contents)
- ★M6.1 *ViEngine* (13C.12): `vi_engine_table` ≥ 300 rows, fuzz under ASan/UBSan (invariants: cursor in bounds, UTF-8 valid, undo restores).
- ★M6.2 *Keymap/leader/layout loaders*: valid and invalid files with line-accurate golden errors (keymap duplicates, leader depth > 4, layout ratio out of range, depth > 8, empty tabs, duplicate panel ids), precedence layers, conflict report to Problems.
- ★M6.3 *Action registry and command line*: every registered action has title, id, `cmd` where applicable; command-line grammar table (≥ 80 lines: quoting, `|` chains, `!`, `%` expansion, errors `E492` with suggestions); completion fixtures for every argument kind; history persistence and dedupe.
- ★M6.4 *Theme*: all tokens present in `term`, `light`, `high-contrast`; contrast test (D1.12); lint-colours passes; glyph names resolve in Unicode and ASCII forms.
- ★M6.5 *Layouts*: shipped layouts load, `--dump-layout` parses back to an identical tree, save/restore round-trip, workspace switch keeps panel instances, hidden-panel TTL.
- ★M6.6 *Panel state tests* (D3.14): for each panel in the registry that is in scope for M6 (Editor, Game (terminal), Console, Log, Search, Problems, Timeline, State, Processes, Modules, Bus, Perf, Help, Patches/Where/Experiments as stubs, Files/Outline/Terminal): seven-state fixtures with goldens; meta-test fails on any missing combination. Studio panels are out of M6 scope (M9).
- ★M6.7 *Cross-panel scenarios* 1–7 (D3.14) with `--fake-daemon`; scenarios 1, 2, 4, 5, 7 also against a real daemon with `hello-js`.
- ★M6.8 *Input modes and passthrough*: scripted key tests of 13C.12 (cmdline, switcher, which-key, prefix, pop-out windows), `cat -v` passthrough byte-exactness incl. `<Prefix><Prefix>` = 0x1c, terminal bracketed paste.
- ★M6.9 *Idle and redraw policy*: 0 frames in 10 s idle; frame count bounded under a 5 000 events/s Log flood (≤ 30 updates/s); GUI first frame < 600 ms (software GL).
- M6.10 *Pop-out*: second OS window appears (`--video x11` under Xvfb) with the panel; re-dock restores the slot; `popout = floating` variant stays in one window.
- ★M6.11 *Screenshots*: non-blank, ≥ 3 distinct colours in the dock area, text dump equals golden for the six shipped workspaces.
- M6.12 *Performance*: Log 100k rows and State 50k keys ≤ 8 ms/frame (measured with the frame timer in `--script` mode).
**Sanitizers:** ASan on M6.1–M6.3, M6.8; UBSan on the GUI offscreen run.
**Teeth:** T1 hard-code a colour literal in a scratch commit → lint-colours fails; T2 make a panel draw on a timer (`PIPIST_SELFTEST_ANIMATE=1`) → M6.9 idle test fails.
**Perf:** `P.gui_first_frame_sw` < 600 ms, `P.gui_idle_frames` = 0, `P.log_100k_frame`, `P.state_50k_frame`.
**Unverified (if GL/Xvfb unavailable → whole GUI set; otherwise the following):** `M6.gpu` real GPU first-frame < 400 ms; `M6.wm` pop-out behaviour under the owner's tiling window manager; `M6.hidpi` scale 2.0 rendering; `M6.ime` — owner commands in `unverified.toml`.
**Gate time:** ≈ 20 min.

## M7 — Hot patch (JS and data)
**Suites**
- ★M7.1 *Classification table*: ≥ 150 before/after source pairs → expected tier and item kinds (function-body, function-added/removed, data-literal, declaration-added/removed, side-effect, signature, class-shape, unparseable), including closure capture, `const`/`let` in lexical scope, top-level statements with calls, `if (...) {` anchor-hazard warnings, getter/setter changes, generator/async changes, HTML inline script changes, whitespace/comment-only changes (tier `none`).
- ★M7.2 *Differential equivalence*: for each of 40 scripted edits on the fixtures, **patch-then-continue** transcript equals **reload-restore-then-continue** transcript (and state hashes equal) whenever the patcher chose T1/T2; when it chose T4/T5 it must be because the classification table says so.
- ★M7.3 *Transactions*: a patch that fails midway (injected failure on the 3rd item) leaves the running code unchanged and reports `-32015` with diagnostics; `patch.revert` restores the pre-patch behaviour; history records every outcome.
- ★M7.4 *Quiescence*: T1/T2 applied only at quiescent points (a patch requested mid-narration waits and applies after); T3+ held until `patch.apply` unless `auto_restore`; `patch.pending` event content.
- ★M7.5 *Config*: `no_hotpatch` globs force T4; `rerun_ok` accepted for listed side-effect statements; `[patch].auto` persisted.
- ★M7.6 *Behavioural acceptance*: edit a function mid-run on `hello-js` → behaviour changes, state preserved; `const` table edit merges in place (T2) with removed keys handled per spec; side-effect edit → T4 fallback event naming the statement and line.
- M7.7 *Patches panel*: seven states, tier menu confirm, revert prompt.
- M7.8 *Large files*: classification of a 2.1k-line script ≤ 150 ms; patch apply ≤ 100 ms.
**Sanitizers:** ASan on M7.1–M7.4. **Teeth:** T1 mutate the classifier to treat side-effect statements as T1 (`PIPIST_SELFTEST_BADCLASS=1`) → M7.2 fails (shows the differential test catches unsafe patches).
**Perf:** `P.classify_2k_lines`, `P.patch_apply`. **Unverified:** none. **Gate time:** ≈ 10 min.

## M8 — Native runtime path and viewport bridge
**Suites**
- ★M8.1 *Runtime conformance*: `runtime-demo` registers (`game.hello`), implements pause/step/speed/snapshot/restore/state.get; raw/1 and pages/1 snapshot round-trips byte-identical; `runtime.*` pass-through fidelity (A2.17 #6).
- ★M8.2 *`pipist-vp-test` conformance* (13A): handshake, caps negotiation, resize (debounced, frames at new size), input forwarding (kbd/mouse), capture/release and relative mouse, **slot starvation** (GUI withholds slot acks → runtime skips frames, never blocks, frame counter shows drops), runtime crash → overlay + `Restart & restore`, GUI crash → runtime keeps running and re-attaches.
- ★M8.3 *Pixel exactness*: test pattern frame arriving through shm equals the reference image byte-for-byte; in a docked panel and in a popped-out window at exact panel size (screenshot crop compare, tolerance 0 for integer scale; ≤ 2/255 for bilinear).
- ★M8.4 *Lua hot reload (T3)*: edit a weapon definition → live demo changes without state loss (entity positions unchanged); syntax error in the Lua file → reload refused, previous code still running, diagnostic shown.
- ★M8.5 *C++ build + restart-restore (T5)*: modifying a C++ source triggers the supervised build; failure shows problems and keeps the old binary running; success restarts and restores the latest snapshot.
- M8.6 *C++ gameplay-module swap demo (13B.12)*: build `.so`, swap with state preserved, ABI version mismatch refused.
- ★M8.7 *Multiple instances*: two `runtime-demo` instances with separate viewports and branches; `game.select`; ambiguous call → `-32012` with candidates.
- ★M8.8 *Resource hygiene*: shm segments/memfds/sockets cleaned after crash and normal exit (leak detector); no fd growth over 1000 resize cycles.
- M8.9 *Throughput*: 1080p shm hand-off < 3 ms/frame and ≥ 60 fps sustained for 20 s with llvmpipe-rendered demo (measured and reported; if the sandbox cannot reach it, the *measurement tool* must run and the budget is `unverified`).
- M8.10 *dma-buf*: negotiation and fallback logic unit-tested with mocks (fallback event on failure); real import `unverified`.
- ★M8.11 *Snapshot of native state*: raw/1 dedupe ratio on the demo world ≥ 3× over 200 snapshots; restore returns identical entity state (hash).
**Sanitizers:** ASan+UBSan on runtime-demo, SDK, bridge; TSan on bridge threads (reader thread per viewport).
**Teeth:** T1 make the runtime block on a full slot (`PIPIST_SELFTEST_BLOCK=1`) → M8.2 starvation test fails; T2 shm size mismatch injected → GUI shows error state not a crash.
**Perf:** `P.vp_handoff_1080p` < 3 ms, `P.vp_fps_1080p` ≥ 60 (see M8.9), `P.vp_resize_to_frame` ≤ 250 ms.
**Unverified:** `M8.dmabuf`, `M8.gpu_fps` (real GPU numbers). **Gate time:** ≈ 25 min.

## M9 — Studio
**Suites**
- ★M9.1 *`fmtedit` property tests* (per format TOML, JSON, Lua-data): ≥ 1 000 random edit scripts per format in the gate (5 000 full): bytes outside the edited range identical, re-parse equals the intended tree, idempotent when re-applied, comments/ordering/indentation/line endings preserved; oracle: Python `tomllib`/`json` and a Lua data loader for tree equality.
- ★M9.2 *Fixture edits*: hand-written cases for tricky TOML (dotted keys, inline tables, arrays of tables, multi-line strings), JSON with unusual whitespace, Lua tables with comments and trailing commas.
- ★M9.3 *Write path*: `studio.edit` conflict (`-32003`) when the file changed; failed re-parse check aborts with nothing written (`edit_rejected`); nvim buffer coordination for the 3 cases (clean/dirty/closed) with a real nvim (or unverified like M3).
- ★M9.4 *Schemas*: loader errors golden, `validate` diagnostics (`source = schema`) with correct ranges, `schema infer` golden outputs for 5 sample data sets, `visible_if` evaluation table.
- ★M9.5 *Scene protocol in `runtime-demo`*: tree/get/set/spawn/delete/duplicate/reparent/select/pick/bounds; version counter increments; `scene.changed` events with cause.
- ★M9.6 *Gizmo edit acceptance*: scripted drag of an entity in the viewport changes **exactly one line** (`pos`) in the scene file (`git diff --numstat` = `1 1`) while nvim has the file open and sees the update.
- ★M9.7 *Edit/Play/Keep*: Play → modify → Stop restores the edit-state snapshot; `studio.changes` lists diffs; `studio.keep` writes only selected values; branch flagged `studio-play`; the edit-state snapshot is protected from thinning (C1.1).
- ★M9.8 *Tweakables*: slider applies live (`preview` ≤ 60/s); `commit` edits the literal at `source` range; no literal source → `-32005`; presets save/load round trip.
- ★M9.9 *Undo/redo*: random operation sequences compared with a reference model (stack semantics, file contents after each undo equal the pre-edit bytes).
- M9.10 *Studio panels*: seven-state fixtures for Viewport, Hierarchy, Inspector, Assets, Definitions, Tweakables; echo suppression of selection; reparent; per-type Inspector editor goldens.
**Sanitizers:** ASan+UBSan on M9.1–M9.5, M9.9. **Teeth:** T1 break `fmtedit` to rewrite whole files (`PIPIST_SELFTEST_REWRITE=1`) → M9.1/M9.6 fail.
**Perf:** `P.fmtedit_1mb` ≤ 40 ms per edit, `P.scene_pick` ≤ 5 ms for 10 000 entities.
**Unverified:** GPU-dependent picking (ID-buffer) variant (`M9.gpu_pick`); software path runs. **Gate time:** ≈ 15 min.

## M10 — Browser backend
**Suites**
- ★M10.1 *Agent parity*: the shared walker corpus (M5.1) run in Chromium via the injected agent produces byte-identical Value JSON to the C++ walker; fingerprints/deltas equal.
- ★M10.2 *Serve and inject*: static server serves the project; HTML responses rewritten with agent first in `<head>`; scripts replaced by `index.transform` output; ranges/caching headers sane; path traversal attempts rejected.
- ★M10.3 *Reload/restore loop* (Playwright): edit a file → page reloads → agent reconnects → state restored through the same adapter (`reboot`); `in-place` variant; all three fixtures.
- ★M10.4 *Security*: WebSocket token and Origin enforcement; agent method set only; cross-origin page cannot connect (test from a second origin).
- M10.5 *Console capture and screenshot*: captured console lines appear in `log.query`; `game.screen.get` returns a PNG blob for canvas games.
- M10.6 *Parity with headless*: `adapter verify` PASS via the browser backend on the three fixtures; `doctor --host-compat` unchanged.
**Teeth:** T1 serve a page without the injected agent → clear error state (`waiting for browser` + timeout), no hang. **Perf:** `P.browser_restore` ≤ 1.5 s. **Unverified:** non-Chromium browsers (`M10.firefox`). **Gate time:** ≈ 10 min.

## M11 — Experiments
**Suites**
- ★M11.1 *Definition parsing*: TOML schema goldens, errors with line numbers, variant expansion counts (grids, lists, zip), seeds.
- ★M11.2 *Analytic sweep*: `hello-js` sweep over a parameter with a closed-form expected result matches exactly; aggregation columns (mean/min/max) correct.
- ★M11.3 *Parallel isolation*: 20 variants with `jobs = 8` produce the same results as `jobs = 1` (bit-identical collected values), distinct state dirs, no shared sockets/ports, no cross-talk (each variant's secret token appears only in its own transcript).
- ★M11.4 *Assertions and failures*: seeded failing assertion reported with transcript path and first divergence; variant timeouts; host crash in one variant does not stop the run.
- ★M11.5 *Goldens*: `exp.golden.record` + `exp.check` pass; a one-character code change that alters behaviour makes `check` fail with the first divergent tick.
- M11.6 *Experiment branches and quota*: experiment branches flagged and removed at `done` unless `keep_branches`; `experiment_quota_mb` enforced.
- M11.7 *Panel and CLI*: Experiments panel states (D3.5); `pipist exp run|list|try`; `Sweep…` from Tweakables.
- M11.8 *Real-game variants*: 20 Los Ciegos variants in parallel without cross-talk — or `hello-js`, with `unverified` `M11.lc`.
**Sanitizers:** TSan on the job scheduler. **Teeth:** T1 force shared state between variants (`PIPIST_SELFTEST_SHARE=1`) → M11.3 fails. **Perf:** `P.exp_throughput` ≥ 40 variants/min on `hello-js` with 4 jobs. **Unverified:** `M11.lc`. **Gate time:** ≈ 8 min.

## M12 — Diagnostics+
**Suites**
- ★M12.1 *LSP client protocol*: against a **mock LSP server** (scripted JSON-RPC over stdio): initialize, didOpen/didChange/didClose, publishDiagnostics mapping to `Diagnostic`, code actions → `fixes`, shutdown; malformed server messages tolerated; server crash → restart with backoff.
- M12.2 *Real servers*: when `clangd`, `lua-language-server`, `ruff` are installed, broken fixtures produce the expected diagnostics (goldens); otherwise `unverified` per server.
- ★M12.3 *Problem matchers*: extended goldens for ninja/cmake/clang/gcc multi-line diagnostics, node stack traces, lua errors, python tracebacks, ruff/clang-tidy formats.
- ★M12.4 *Lint rules*: each rule (`load-order`, `determinism`, `unlogged-state`, `unreachable`, `shadowed-global`, `long-function`, `todo-fixme`, plus those added by packs) has ≥ 3 positive and ≥ 3 negative fixtures with exact ranges; rule config (`severity`, `ignore`) honoured.
- ★M12.5 *`load-order` reproduces `tests/loadcheck.js`*: on a broken-project fixture with scripts out of order, the lint rule and a bundled equivalent of `loadcheck.js` report the same missing/out-of-order symbols; clean fixture → none.
- ★M12.6 *Quick fixes*: each fix kind applied through `editor.apply` yields the expected text (goldens); fixes never produce a file that fails the syntax check.
- M12.7 *Problems integration*: counts consistent across panel, tab, status bar; `]d`/`[d` actions.
**Teeth:** T1 a lint rule with a seeded false positive on a clean fixture → fixture test fails. **Perf:** `P.lint_25k` ≤ 1.5 s. **Unverified:** `M12.clangd`, `M12.lua_ls`, `M12.ruff` if not installable. **Gate time:** ≈ 7 min.

## M13 — Where-tracing
**Suites**
- ★M13.1 *Semantics preserved*: the transform corpus and fixtures produce identical outputs with instrumentation on (functions mode and provenance mode) and off; every original line number preserved (same-line `__f(id)` insertion).
- ★M13.2 *Per-tick function sets*: golden sets and order per tick for scripted sessions on `hello-js` and `hello-ui`; `trace.now/back(n)` within the window; window eviction at `window_ticks`.
- ★M13.3 *Strings and entities mapping*: a talk interaction on `hello-js` (the dress-check NPC with and without the required item) shows the dress-check function and the turn-away string with exact file lines; entities map to their data-file ranges.
- ★M13.4 *Provenance*: `trace.who_wrote path` returns the last N writes with function, file:line, old and new values for a set of scripted state changes.
- ★M13.5 *Overhead*: with tracing on, a CPU-bound fixture loop slows < 25%; with tracing off there is no wrapper (module not loaded; sources not instrumented; byte-identical to untraced).
- M13.6 *Enable/disable flow*: `trace.start` reloads instrumented scripts and restores state (state hash before = after); `trace.stop` restores clean scripts.
- M13.7 *Where panel*: seven states, who-wrote prompt, window navigation.
- M13.8 *Real game*: `talk la senora` with and without a suit — or `unverified` (`M13.lc`).
**Teeth:** T1 drop one instrumentation id (`PIPIST_SELFTEST_DROPID=1`) → M13.2 golden fails. **Perf:** `P.trace_overhead` < 25%. **Unverified:** `M13.lc`. **Gate time:** ≈ 7 min.

## M14 — Polish and extras
**Suites**
- M14.1 *DAP*: against a mock DAP server (launch, breakpoints, stack, vars, eval, stepping, terminate); real `lldb-dap`/`gdb`/`node`/`debugpy` smoke if installed, else `unverified` each.
- ★M14.2 *Replay tier (flagged)*: a recorded session replays identically; an edit that changes the number of RNG draws is detected as divergence by the periodic state hash, stops with the report, and the result is labelled `replay (may diverge)`.
- M14.3 *Declarative panels*: a sample module renders every widget kind (golden dump), event round-trip, limits (10 000 widgets, 5 updates/s) enforced with a footer warning.
- M14.4 *`plugins` module*: a sample plugin loads, registers a method and a panel, is unloaded cleanly; a crashing plugin does not affect the kernel.
- M14.5 *`logdb`*: SQLite-backed `log.query` equals the ring implementation on a 100k-record random corpus for all filter combinations (oracle test).
- M14.6 *Python host/pack smoke*: a tiny Python sim registers as a runtime, snapshots/restores state, runs under `experiments`.
- ★M14.7 *Docs*: docs build with no broken links; every protocol method and event has a reference entry; every config key has an entry; panel help pages complete (D3.9); `docs-check` passes.
- ★M14.8 *Templates*: `pipist init text-js|lua-native|cpp-native|python-sim` each create a project that passes its own smoke target (build/run/test) in a temp dir.
- M14.9 *Ebuild stub*: syntax-checked (`bash -n`, `pkgcheck scan` if available); Gentoo specifics `unverified` (`M14.gentoo`).
- ★M14.10 *Final full tier*: `scripts/ci.sh full` passes (long fuzz, 500 crash iterations, DOM-diff, scale tests, all sanitizers) or each failure is listed in `STATUS.md` with the reason; final `STATUS.md` has an owner checklist built from the unverified registry.
**Teeth:** T1 a doc link to a missing page → docs-check fails. **Unverified:** `M14.gentoo`, real DAP backends, anything left from earlier milestones. **Gate time:** ≈ 15 min (+ ≈ 2 h full tier once).

---
## E2.1 Gate time and cost summary
| Milestone | Gate (min) | Full-tier extras | Notes |
|---|---|---|---|
| M0 | 3 | — | |
| M1 | 12 | fuzz 10 min | |
| M2 | 10 | — | |
| M3 | 5 | — | nvim availability decides verified/unverified |
| M4 | 18 | 50k fuzz cases | Chromium differential suite dominates |
| M5 | 20 | scale ≈ 25 min once | |
| M6 | 20 | — | GL availability decides GUI verified/unverified |
| M7 | 10 | — | |
| M8 | 25 | 60 s soak | |
| M9 | 15 | 5 000-edit property runs | |
| M10 | 10 | — | |
| M11 | 8 | — | |
| M12 | 7 | — | |
| M13 | 7 | — | |
| M14 | 15 | ≈ 2 h full tier once | |
Total gate time ≈ 3 h across the run if each gate passes on its first or second complete run (E1.2). If the plan's compute budget cannot afford all gates, shorten by (1) skipping `full`-tier extras (record as not run), (2) cutting milestones from the end (E1.9), never by weakening a gate.

## E2.2 Owner verification checklist (generated at the end into `STATUS.md`)
The final report lists, with one command each (from `tests/unverified.toml`): GUI on the owner's GPU and window manager (`M6.gpu`, `M6.wm`, `M6.hidpi`); viewport dma-buf and real-GPU frame rate (`M8.dmabuf`, `M8.gpu_fps`); Los Ciegos acceptance items (`M2.lc`, `M4.lc`, `M5.lc`, `M11.lc`, `M13.lc`, run by `scripts/verify-owner.sh lc` once the game is placed at `examples/los-ciegos/`); nvim-dependent suites if nvim was missing (`scripts/verify-owner.sh m3`); LSP/DAP backends; Gentoo ebuild; Firefox for the browser backend. Each owner command prints `PASS`/`FAIL` and the owner can paste the table back to the next session to close the items.

<!-- SOURCE-END: pipist-spec-e2-milestone-tests.md -->

---
