Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Rebuild Game Master as an original tabletop game workshop (#153)

Dee1dee0b702895
diff --git a/.github/workflows/experience-checks.yml b/.github/workflows/experience-checks.yml
index c4cb750fb..2b13e4d84 100644
--- a/.github/workflows/experience-checks.yml
+++ b/.github/workflows/experience-checks.yml
@@ -23,6 +23,7 @@ jobs:
run: |
sh store/agents/voxel-worlds/toolchain/setup.sh
sh store/agents/drone-pilot/toolchain/setup.sh
+ sh store/agents/game-master/toolchain/setup.sh
node store/tools/build-experiences.mjs --check
- name: Verify packaged branding matches desktop assets
run: node store/tools/build-experience-branding.mjs --check
@@ -89,6 +90,19 @@ jobs:
python3 -m venv /tmp/vector-geometry-reader
/tmp/vector-geometry-reader/bin/pip install shapely==2.0.7 numpy==1.26.4
/tmp/vector-geometry-reader/bin/python store/agents/drone-pilot/test/verify-delivery.py work/experience-evidence/vector-acceptance
+ - name: Install print verification tools
+ run: |
+ sudo apt-get update -qq
+ sudo apt-get install -y poppler-utils
+ - name: Create, play, revise and print original tabletop games
+ env:
+ GAME_QA_ROOT: work/experience-evidence/relay-browser
+ GAME_ACCEPTANCE_ROOT: work/experience-evidence/relay-acceptance
+ run: |
+ npm ci --prefix store/agents/game-master/toolchain --ignore-scripts --no-audit --no-fund
+ node store/agents/game-master/test/browser.mjs
+ node store/agents/game-master/test/acceptance.mjs
+ python3 store/agents/game-master/test/verify-delivery.py work/experience-evidence/relay-acceptance
- name: Verify MIDI and aligned audio with independent readers
run: |
python3 -m venv /tmp/music-delivery-reader
@@ -103,7 +117,5 @@ jobs:
run: python3 store/agents/data-studio/test/verify-exports.py work/data-studio-evidence
- name: Revise three brand briefs and verify real print deliveries
run: |
- sudo apt-get update -qq
- sudo apt-get install -y poppler-utils
node store/agents/creative-direction/test/acceptance.mjs
python3 store/agents/creative-direction/test/verify-delivery.py work/experience-evidence/forme-acceptance/run-*/acceptance.json
diff --git a/desktop/lib/widgets/engine_identity.dart b/desktop/lib/widgets/engine_identity.dart
index a3c6d4b67..66d990411 100644
--- a/desktop/lib/widgets/engine_identity.dart
+++ b/desktop/lib/widgets/engine_identity.dart
@@ -342,7 +342,7 @@ const _harnesses = <String, EngineIdentity>{
id: 'autonomous/game-master',
label: 'Game Master',
category: 'Games',
- tagline: 'Design and compare strategies in a seeded arena',
+ tagline: 'Create a game. Play it. Put it on the table.',
creator: 'Autonomous',
color: Color(0xffed9075),
asset: 'assets/engine-icons/game-master.png',
diff --git a/store/agents/game-master/.gitignore b/store/agents/game-master/.gitignore
new file mode 100644
index 000000000..b1df3fe62
--- /dev/null
+++ b/store/agents/game-master/.gitignore
@@ -0,0 +1,3 @@
+template/.harness/
+template/delivery/
+toolchain/browsers/
diff --git a/store/agents/game-master/AGENTS.md b/store/agents/game-master/AGENTS.md
index c1162f68e..4c1ba9339 100644
--- a/store/agents/game-master/AGENTS.md
+++ b/store/agents/game-master/AGENTS.md
@@ -1,66 +1,58 @@
-# Game Master / AI-vs-AI Arena harness
-
-You turn a plain-English description into a **deterministic, seedable arena game**
-rendered in one self-contained `game/index.html`. The pane runs the match live, so
-the person watches two AIs (or plays against one) — and a re-seed — as you work.
-
-## What a good game is
-
-- **One file, offline.** All logic, AI and rendering inline. No CDN at runtime. A
- `?seed=` query param selects the version: the same seed always plays the same
- match on this machine.
-- **Determinism is the product.** Seed a PRNG and name sub-streams (per player, per
- move roll, per map layout) so tuning one doesn't reshuffle the rest. Same seed →
- same arena, same openings, same match.
-- **Visible, not just automatic.** Keep the rules legible (a grid or board that
- reads clearly), give the match a start/middle/end, and expose a live scoreline so
- the pane is fun to watch. Player-vs-AI modes should take real input.
-- **Be honest about verification.** Same-machine playback is checkable. Timing-based
- AI or animation is not bit-identical across machines — say so in the verdict
- rather than overclaiming.
-
-## How to work so the pane moves
-
-1. **Save within a minute.** Materialize `game/index.html` that runs a trivial seeded
- arena (a grid, two tokens that each move a tick, a scoreline), so the header has
- a state and the pane can play it.
-2. **Build the engine, then the match.** Get the seeded board + turn loop + AI
- policies right first; only then tune pacing, visuals, and player controls.
-3. **Verify like a spectator:** run a few seeds in the pane, watch the scoreline,
- check no side stalls, re-run the same seed and confirm it is identical.
-4. **Update `.harness/verdict.json`** at every check — `ready`, one-line `summary`,
- `phases`, `findings`, and a reproducibility note.
-
-## Rules
-
-- A game is only "ready" when every seed in the range you promise plays clean: no
- stuck AI, no deadlock, no infinite match. Sample a grid of seeds.
-- Tag every crafted decision USER vs AI in `game/DESIGN.md`
- (`YYYY-MM-DD | USER|AI | topic | decision | still in build?`).
-- The `summary` says plainly what is reproducible now and what is not.
-
-## Shipped experience and operating standard
-
-The workspace starts with **Relay**, a working experience, not an empty placeholder.
-Finite 72-turn matches, two policies, pathfinding, relay control, combat/respawn, replay timeline, 32-match tournament, full replay JSON.
-
-- Read the existing artifact before replacing it. The useful model boundaries are arenaMap, arenaPath, arenaMatch, arenaTournament.
-- Preserve working interactions and exports when extending the artifact. Match the user's brief;
- the starter's genre and visual style are examples, not a ceiling.
-- Expose meaningful domain controls and outputs. Every control must change real state; every
- displayed metric must be computed from that state. Never invent model activity or test results.
-- Use named random streams and a fixed simulation/score clock. Sample seeds, repeat the same
- seed, inspect exported data, and verify keyboard/touch controls in the actual viewer.
-- This HTML runs with same-origin APIs in the shared viewer. Sibling fetches, localStorage,
- downloads and pointer lock are available. Keep files portable and support direct opening.
-- Do not equate an existing HTML file, a successful reload, or a source-string test with a usable
- result. `seed-verdict.sh` deliberately keeps `ready:false`; write `ready:true` only after your
- checks establish it. Record exact commands, sampled seeds, observations and limitations.
-- Never claim a test coverage percentage for browser code based on Node subprocess tests.
-
-## Check your actual edited model
-
-Run `node tools/check.mjs --seeds 100` in the workspace. It reads the pure model from
-`<script id="harness-model">` in the artifact, checks domain invariants, repeats each seed, and
-writes `.harness/model-check.json`. Preserve that script boundary when editing. Model checks are
-followed by browser interaction, exported-output inspection, and visual or listening review.
+# Game Master / Relay
+
+Turn a person's idea into an original **board or card game they can actually play, revise and
+print**. The coding agent authors mechanics; the studio does not pretend a list of presets is
+creation. Pocket Conservatory is a complete example and a starting point, not a genre limit.
+Phaser and Godot harnesses cover video-game engine workflows; this package specializes in tabletop
+rules, human playtesting and physical delivery.
+
+## Work from the person's game
+
+1. Identify players, decisions, goals, hidden information, components and a complete ending. Ask
+ only for decisions that change the work; choose reasonable defaults and record them.
+2. Author `game/project.json` and the full `game/rules.mjs`. Read the [contract](skills/game/references/project.md).
+ Rules are ordinary import-free JavaScript: no fixed list of genres or mechanics. Component
+ designs, original face artwork, quantities, boards, scoring values and rulebook stay in source.
+3. Build with `node tools/build.mjs`. Play the actual legal choices in the viewer. Make the first
+ playable version early, then improve it against the brief. Do not replace source with one
+ manually edited generated HTML; source saves must continue to work.
+4. Revise only what the person asked to change. Locked components represent approved work.
+ Preserve their ids, values and face artwork unless a requested change requires otherwise.
+ Browser drafts and running games are distinct editions; keep old rules and replays.
+5. Deliver `node tools/export.mjs delivery`: playable offline HTML, complete source, individual
+ SVG components, A4 sheets, board sheets, PDF rulebook/components and ZIP. Open the offline game,
+ perform real inputs, inspect every unique printed design and read the rulebook against the rules.
+
+`GAME_DSH_DIR` points to the installed package. Setup supplies Node and pinned local build/browser
+utilities. If Node is not on the host PATH, run `bash "$GAME_DSH_DIR/toolchain/node.sh" tools/build.mjs`
+from the workspace. Doctor checks the actual tools. Do not ask a nonprogrammer to install runtimes
+manually when setup can do it.
+
+## What counts as verification
+
+- `node tools/check.mjs --seeds 80` samples uniform legal choices, repeats exact seeds, detects
+ illegal actions/dead ends/turn caps and reconstructs every replay. Add an observation-only `bot`
+ for a clearly named strategy. Do not call sampled policy win rates human balance or fun.
+- Actually play through beginning, decisions, scoring and a final outcome. Exercise losing paths
+ where the game has them; restart, undo a testing move and reopen a saved replay.
+- Keep rulebook, printed values and executable rules in agreement. The physical game must specify
+ setup, every legal decision, chance procedure, turn order, scoring, ties and how it ends.
+- Export after revisions. Independently inspect ZIP/JSON/SVG/PDF files, physical sizes, inventory
+ counts, text legibility and cut guides. Custom artwork owns its printed text: revise it when
+ the mechanics change. Use local, original or user-supplied artwork and retain its provenance.
+- Record exact commands, seeds, user inputs, observations and limits in `game/DESIGN.md` and
+ `.harness/verdict.json`. A build or helper never sets `ready:true`. Mark readiness only after
+ the promised game and delivery checks actually pass. No invented customer or installed-agent
+ trial, synthetic feedback, play counts, or test-coverage percentages.
+
+## Boundaries to keep visible
+
+One browser supports local human play and pass-and-play. Its curtain conceals casual views, not
+source/state from a browser owner. Replays contain the full deterministic state. There is no
+network multiplayer, account, cloud service or game-engine import promise. Rules must use seeded
+context randomness and remain self-contained; do not use network requests, clock time, globals
+for mutable game state or unseeded randomness. A worker time limit keeps bad rules from freezing
+editing; it does not prove every game will terminate.
+
+The old arena source remains under `store/tools/experiences/game-master.*`. Never erase existing
+legacy workspaces or force them into the new project format.
diff --git a/store/agents/game-master/README.md b/store/agents/game-master/README.md
index 298298cd9..2c662912a 100644
--- a/store/agents/game-master/README.md
+++ b/store/agents/game-master/README.md
@@ -1,60 +1,75 @@
-# Game Master — Relay
+# Game Master · Relay
-> Withdrawn from Store discovery on 2026-09-20: the current starter does not meet our
-> standard for an open-ended tool that completes real user work. Existing projects and
-> source remain available. See [the product review](../../../work/SUPERPOWERS.md).
+![Relay logo](brand/logo.svg)
-![Game Master logo](brand/logo.svg)
+Turn an idea into a board or card game people can play. Author original rules, design the cards
+and pieces, test real decisions, and keep a complete offline game and physical print-and-play kit.
+The agent writes the mechanics from your brief; you can edit the resulting game directly.
-Design and compare strategies in a seeded arena. Watch two squads compete for relays, inspect decisions, step and rewind matches, and run a 32-map tournament.
-
-## Try it
+## What you can do
-> Create a capture arena where patient defenders face aggressive hunters. Show every decision and compare their win rates over 32 maps.
+- Create new mechanics in an editable rules module. Drafting, cooperative routing and
+ push-your-luck are verified examples, not the available genres in a menu.
+- Play legal choices, see scores and outcomes, pass a private hand between local players,
+ undo a testing move, save a replay and reconstruct it against the same rules.
+- Edit components, copies, values, colors and original or supplied SVG/PNG/JPEG/WebP face artwork.
+ Lock approved pieces, undo edits, revise the rulebook and keep the complete source.
+- Apply a new edition while retaining the old playable game and replay. Workspace source saves
+ use revision checks and history; concurrent agent/browser revisions remain recoverable.
+- Run repeatable games under uniform choices or a named authored policy. Inspect errors, turn
+ caps and outcome distributions, with seeds and replays for the actual runs.
+- Export an offline editable/playable HTML, JSON and JavaScript source, individual SVG pieces,
+ A4 print sheets, boards, rulebook, PDFs and ZIP. You can play and print without Harness running.
-The starter already works before the first prompt. Change it with the agent, interact with the
-result in the pane, and keep the output. Everything needed at runtime is in `game/index.html`.
-It works offline and can be opened outside Harness.
+## Try a brief
-## What you can do
+> I want a tiny two-player game about growing a garden. Let us choose plants from hands we pass,
+> with points for flower-and-water pairs. Make cards we can actually print. After we play, help
+> me change the scoring while keeping the artwork I approve.
-Finite 72-turn matches, two policies, pathfinding, relay control, combat/respawn, replay timeline, 32-match tournament, full replay JSON.
+The workspace begins with **Pocket Conservatory**, a complete original drafting game. The
+[acceptance record](test/ACCEPTANCE.md) also covers **Signal Garden**, a routing puzzle, and
+**Night Ferry**, a push-your-luck card game, each with a targeted revision and physical delivery.
-## Build on the starter
+## Build and keep the work
-The model functions `arenaMap`, `arenaPath`, `arenaMatch` and `arenaTournament` are the starting points for substantive changes. Preserve seed
-reproducibility and user controls while changing the domain behavior. A different brief can replace
-this starter's entire visual language. Keep the artifact self-contained and test the actual result.
+Setup resolves Node, installs pinned local tools and reuses Chrome/Chromium or installs its local
+browser. `GAME_DSH_DIR` locates those tools from an installed workspace.
-The source checkout builds these starters with `node store/tools/build-experiences.mjs`. Installed
-workspaces are editable HTML; no build tool, network dependency or paid service is required.
+```sh
+node tools/build.mjs
+node tools/check.mjs --seeds 80
+node tools/export.mjs delivery
+```
-## Verification
+The [source contract](skills/game/references/project.md) explains how to author mechanics and
+components. The browser also exports a complete kit and opens print views; use the print dialog
+for PDF. Print at 100% / actual size, without browser headers or footers, and check the 50 mm line.
+Backs are supplied separately for gluing or opaque sleeves; no duplex alignment is assumed.
-Model census: `node --test store/tools/experience-tests/models.test.mjs` from the source checkout.
-Browser interactions, exports, same-origin APIs and manifest routing: see
-[`store/tools/experience-tests`](../../tools/experience-tests/README.md).
+## Scope and evidence
-`seed-verdict.sh` establishes only artifact presence and keeps `ready:false`. The agent must run
-and record real domain and browser checks before writing a ready verdict. No cross-device pixel or
-audio equality is promised. The research is inspiration; this is original code, not a wrapper of
-any cited third-party engine.
+This is local human play and game design for 1–6 players, with an explicit finite project/state
+size and turn budget. The pass-and-play curtain hides casual views; source and replay files are
+not secret from the browser owner. There is no network multiplayer or native game-engine import.
+Rules run in a worker so a broken module can be stopped while source remains editable.
-## Check your actual edited model
+Simulations measure the named policy, seeds and authored rules. They do not establish fun, human
+balance or commercial quality. Authored acceptance fixtures are not customer or installed-agent
+prompt trials. Helpers keep `ready:false` until actual requested play and delivery are reviewed.
-Run `node tools/check.mjs --seeds 100` in the workspace. It reads the pure model from
-`<script id="harness-model">` in the artifact, checks domain invariants, repeats each seed, and
-writes `.harness/model-check.json`. Preserve that script boundary when editing. Model checks are
-followed by browser interaction, exported-output inspection, and visual or listening review.
+The original arena source remains under `store/tools/experiences/game-master.*`; existing legacy
+workspaces are not automatically migrated or overwritten.
## Logo and icon
-The original identity ships in `brand/`: [vector icon](brand/icon.svg),
-[256px PNG](brand/icon.png), [light logo](brand/logo.svg) and
-[dark logo](brand/logo-dark.svg). The same mark appears in the starter header,
-its offline favicon and the desktop Store/picker/tabs. MIT, by OpenHarness contributors.
+The original Relay identity remains in `brand/`: [vector icon](brand/icon.svg), [PNG](brand/icon.png),
+[light logo](brand/logo.svg) and [dark logo](brand/logo-dark.svg). The mark also appears in the
+studio, offline favicon and desktop Store/picker/tabs.
## Credit and stewardship
-Original implementation and visual identity by OpenHarness contributors, maintained by
-Autonomous under the [MIT license](LICENSE). Report issues in the OpenHarness repository.
+Original implementation, game fixtures and visual identity by OpenHarness contributors,
+maintained by Autonomous under the [MIT license](LICENSE). The offline runtime has no third-party
+code dependency. Package-local build tools are esbuild 0.27.2 (MIT) and Playwright Core 1.63.0
+(Apache-2.0); their licenses remain in the installed packages. No third-party game design is copied.
diff --git a/store/agents/game-master/harness.json b/store/agents/game-master/harness.json
index e7080ccb2..a4dcd75eb 100644
--- a/store/agents/game-master/harness.json
+++ b/store/agents/game-master/harness.json
@@ -4,7 +4,7 @@
"name": "Game Master",
"category": "Games",
"author": "Autonomous",
- "description": "Design and compare strategies in a seeded arena. Watch two squads compete for relays, inspect decisions, step and rewind matches, and run a 32-map tournament.",
+ "description": "Create original board and card games from an idea. Play the rules, edit components, inspect reproducible playtests and export an offline game plus a physical print-and-play kit.",
"engine": "claude",
"workspace": {
"template": "template",
@@ -15,18 +15,21 @@
"instructions": "AGENTS.md",
"skills": [
"skills"
- ]
+ ],
+ "env": {
+ "GAME_DSH_DIR": "${dsh}"
+ }
},
"toolchain": {
"setup": "toolchain/setup.sh",
"doctor": "toolchain/doctor.sh"
},
"viewer": {
- "use": "autonomous/web-viewer",
+ "command": "toolchain/viewer.sh",
"artifactExtensions": [
".html"
],
- "url": "http://127.0.0.1:${port}/?file=${artifact}"
+ "url": "http://127.0.0.1:${port}/"
},
"verdict": ".harness/verdict.json"
}
diff --git a/store/agents/game-master/skills/game/SKILL.md b/store/agents/game-master/skills/game/SKILL.md
index 0bb2cec20..8a03703e5 100644
--- a/store/agents/game-master/skills/game/SKILL.md
+++ b/store/agents/game-master/skills/game/SKILL.md
@@ -1,76 +1,37 @@
---
name: game
-description: Build a deterministic, seedable arena game in one HTML file from a plain-English description. Use whenever the user asks for an AI-vs-AI duel, a player-vs-AI game, a board bout, a race, a chase, or prompt-to-game.
+description: Create and revise original board or card games from a person's idea, with editable mechanics and components, real human playtests, reproducible simulations and a complete playable and printable kit. Use for tabletop game design, card drafting, cooperative puzzles, push-your-luck systems and new rules beyond the example game.
---
-# game
-
-Take the user's description and produce a **single self-contained `game/index.html`**
-that runs a **deterministic, seedable** arena game — two AIs competing, or the
-player plus an AI — loading the seed from a `?seed=` query param so the web-viewer
-can preview the current seed and re-seed live.
-
-## The floor (in order)
-
-1. **Seeded PRNG.** A small seeded PRNG derived from the hash of the seed string.
- Nothing may call a non-seeded random — the match must be reproducible.
-2. **Arena + turn loop.** A seeded board/layout and a turn loop where each side
- picks a legal move; player-vs-AI reads real input.
-3. **`?seed=` plumbing.** Reading the param, plus a tiny UI (input + "re-seed"
- button, and play/step controls) so the person can browse seeds in the pane.
-4. **Named sub-streams.** One PRNG sub-stream per concern (map layout, move rolls,
- AI policy) so tuning one doesn't reshuffle the other.
-
-## The gold checklist
-
-- **Trait tables that survive an edition**: seed → match (map, matchup, outcome),
- and a census that shows no stuck or degenerate match in the range you claim.
-- **Rules discipline**: every move is legal and state is consistent; a visible
- scoreline and turn indicator that read clearly.
-- **Style range**: a capture duel, a race to a goal, a chase-and-tag, a turn-based
- knock-out — matched to the brief, not all at once.
-- **Export route**: expose a "watch" mode that plays the seeded match end-to-end
- and a rewind/step control.
-
-## Verify like a spectator, not a compiler
-
-Run a grid of seeds — actually watch the matches — and read the scorelines.
-Two hard checks before "ready":
-- **Re-run same-seed** — it must be identical on this machine.
-- **Census the seed range you promise** (e.g. 0–99); reject any stuck AI,
- deadlock, or infinite match.
-
-Be explicit in the verdict about the reproducibility guarantee: same-machine yes;
-timing-based AI or animation you cannot prove bit-identical — say so.
-
-## Verdict feed
-
-Write `.harness/verdict.json` at every change:
-
-```json
-{ "spec": 1, "ready": false, "summary": "seeded capture duel · re-seed live · census 0–99 clean",
- "findings": [{ "severity": "info", "kind": "reproducibility", "message": "same-machine verification pending; timing-based animation not provable bit-identical" }],
- "artifact": "game/index.html",
- "phases": [{ "id": "seed", "name": "Seeded core", "state": "done" },
- { "id": "game", "name": "The game", "state": "active" },
- { "id": "edition", "name": "Edition", "state": "pending" }],
- "updatedAt": "2026-09-18T00:00:00Z" }
-```
-
-## Starting from Relay
-
-The template is functional: Finite 72-turn matches, two policies, pathfinding, relay control, combat/respawn, replay timeline, 32-match tournament, full replay JSON.
-
-Keep its useful controls and exports when making a user's creation. Test the behavioral core
-(arenaMap, arenaPath, arenaMatch, arenaTournament) as well as the visible result. A self-contained HTML file can still have well-separated
-model, rendering, input and export functions. Do not turn a finished starter into a waiting screen.
-
-Presence-only helpers do not prove correctness or reproducibility. Record actual evidence before
-marking the result ready. Export and reopen the result as part of the handoff to the user.
-
-## Check your actual edited model
-
-Run `node tools/check.mjs --seeds 100` in the workspace. It reads the pure model from
-`<script id="harness-model">` in the artifact, checks domain invariants, repeats each seed, and
-writes `.harness/model-check.json`. Preserve that script boundary when editing. Model checks are
-followed by browser interaction, exported-output inspection, and visual or listening review.
+# Create a game people can play
+
+Read the workspace and [project contract](references/project.md). Preserve working source,
+approved components and the person's decisions. Use the coding agent to author original mechanics
+in `game/rules.mjs` and their physical components/rulebook in `game/project.json`.
+
+Build an end-to-end game: setup, meaningful choices, chance if any, visible consequences, scoring,
+ties and an ending. Any style of self-contained component face can be embedded as original or
+supplied SVG/PNG/JPEG/WebP artwork. Numeric settings are explicitly authored design parameters;
+there is no fixed genre enum or fake generation button. Do not make people write the JavaScript.
+
+Run `node tools/build.mjs`, then play the actual game in the viewer. The person can edit cards,
+quantities, values, color, artwork and rulebook; lock approved components; save source; undo edits;
+and apply a new edition while retaining the old playable game and replay. Keep these capabilities
+when adapting the renderer for the user's brief. For a different presentation, change the studio
+source deliberately and recheck its exports and accessibility.
+
+Run `node tools/check.mjs --seeds 80`. Its uniform-choice simulations measure only the supplied
+seeds and policy. An optional authored bot receives observations and legal actions, not hidden
+state. Compare distributions with clear policy names; never imply that automated play proves fun,
+fairness, human strategy or commercial quality.
+
+Play real decisions to an outcome, including losing paths if present. Test restart, saved replay,
+a targeted revision and preserved approved material. Export with `node tools/export.mjs delivery`.
+Open the offline HTML and print outputs independently. Check every physical design, dimensions,
+copy count, text, actual-size calibration and rulebook agreement. PDFs come from the same SVG
+sheets; print at 100%, without browser headers or footers. Backs are separate for gluing/sleeves.
+
+Record observed evidence and remaining scope in `game/DESIGN.md` and `.harness/verdict.json`.
+Presence/build helpers keep `ready:false`. Write `ready:true` only after the user's promised
+workflow and actual delivery checks pass. Do not claim installed-agent or customer trials unless
+those exact trials occurred. Preserve the original arena code and existing workspaces.
diff --git a/store/agents/game-master/skills/game/references/project.md b/store/agents/game-master/skills/game/references/project.md
new file mode 100644
index 000000000..beef09c92
--- /dev/null
+++ b/store/agents/game-master/skills/game/references/project.md
@@ -0,0 +1,91 @@
+# Relay source contract
+
+`game/project.json` stores the project without `rules`; `game/rules.mjs` stores the full import-free
+ES module. Downloaded `.relay.json` bundles them into one source file. `tools/build.mjs` bundles the
+studio and a worker into `game/index.html`, with all game data and original embedded artwork.
+The offline HTML still plays, edits and exports. The server viewer adds optimistic source saves
+and `.harness/history/*.relay.json` backups of both data and rules.
+
+## Project
+
+Version 1: `spec`, stable `id`, `title`, `subtitle`, `players` (1–6), `rulebook` sections
+(`heading`, `body`), `settings`, `components`, `boards`. In the bundled form, also `rules` text.
+`revision` is a derived SHA-256 of canonical complete source, never an authored identifier.
+
+Settings have a stable `id`, `label`, numeric `value`, `min`, `max`, `step`. Rules must validate
+integers when required. Components have `id`, `name`, `body`, `kind` (`card`, `token`, `tile`),
+`widthMm`, `heightMm`, `quantity`, hex `color` and `ink`, `symbol`, a plain `values` object of
+numbers/text/booleans, optional `locked`, and optional embedded image `face`. The renderer uses
+component values for human-readable captions and the printed inventory; rules choose their
+meaning. Quantity controls real physical copies. Rules must conserve pieces/decks as appropriate.
+
+`face` is a base64 `data:image/png|jpeg|webp|svg+xml` URL (one actual MIME type). It renders as an
+image, never inline supplied SVG markup. It owns the entire printed face, including text. Keep
+original artwork provenance. Without custom artwork, cards have a generated face; tiles with a
+`values.ports` string of `N`, `E`, `S`, `W` have connecting paths. This is an optional rendering
+convention, not a gameplay constraint. The agent can extend source rendering for other designs.
+
+Boards have `id`, `name`, `widthMm`, `heightMm`, `cols`, `rows`, and a row-major array of
+`{label,color}` cells. The studio uses their coordinates; SVG/PDF exports retain physical sizes. Printed boards reserve
+12 mm at the top for the title: each cell measures `widthMm / cols` by `(heightMm - 12) / rows`.
+For edge-to-edge tile connections, make those dimensions equal to the physical tile size.
+There is no claim that an arbitrary large board fits a phone at playable scale.
+
+Limits: 3 MB complete project; 200 KB rules; 160 designs / 600 physical pieces; 1–100 copies/design;
+12–190 mm width and 12–273 mm height; eight A4 landscape boards with up to 20 rows/columns;
+30 settings; 40 rulebook sections. Imported artwork is at most 500 KB per file. A component whose
+text does not fit must be shortened/enlarged or given an appropriate original face. Generated cards reject overflowing text. Tokens show a name/symbol; connecting tiles show the
+name/ports. Their remaining values stay in the printed inventory. Use a custom face when the
+piece itself needs additional instructions.
+
+## Rules exports
+
+Every state is plain finite JSON with `player` (zero-based active player). Every hook is synchronous.
+State/project inputs are frozen copies. Do not mutate module globals, use time/network/unseeded
+randomness, or import dependencies. Use `ctx.shuffle(array, streamName)` or `ctx.random(streamName)`;
+keep the returned generator for successive draws. Reopening the same named stream starts it again.
+Context seeds include the game seed and action index; give independent concerns distinct names.
+
+```js
+export function initial(project, ctx) { return {player: 0, /* own state */}; }
+export function legal(state, project) { return [{id: 'draw', label: 'Draw a card'}]; }
+export function apply(state, action, project, ctx) { /* return a new changed state */ }
+export function observe(state, player, project) {
+ return {
+ title: 'Your turn', message: 'Choose a card.', private: true,
+ scores: [{label: 'Points', value: 0}],
+ zones: [{id:'hand', label:'Your hand', items:[
+ {key:'copy-1', component:'card-id', action:'draw'}
+ ]}]
+ };
+}
+export function outcome(state, project) { return null; /* or {title,winners:[0],...} */ }
+export function validate(state, project) { return true; /* or a readable error */ }
+export function bot(observation, legalActions, {random}) { return legalActions[0].id; }
+```
+
+Optional zone `board` refers to a board id. Items use `cell` (row-major index), `rotation` in
+clockwise degrees, optional `badge`, `faceDown`. Card actions must refer to a current legal id.
+Keep observation-only views honest: do not put other players' private hands in them. The current
+legal actions must themselves be safe to show to that player. The policy only receives the
+observation and actions, but package code is not a hostile-code security sandbox.
+
+Finished games return an outcome and no legal actions. Active games must offer 1–500 unique,
+readable legal actions. A playtest has at most 2,000 actions. State and observation each stay below
+1 MB. Rule invocation has a browser worker time limit; simulation has a 30-second limit. Node
+checks have a 60-second worker budget. Limits produce errors; they do not justify claiming all
+possible games or all seeds terminate.
+
+## Editions, checks and delivery
+
+The table retains its running edition while source drafts change. Applying edits downloads the
+prior playable game/replay before starting the new one. Replay files bind actions, seed and exact
+final state to the complete source revision; changed source cannot silently reinterpret a replay.
+A replay carries full state, including hidden information. Undo is a testing affordance.
+
+`tools/check.mjs` runs uniform-choice simulations twice, checks outcomes/turn caps/errors and
+rebuilds every replay. `tools/export.mjs destination` checks an initial rules state, builds source,
+produces SVG/HTML/PDF files and ZIP. This export check does not establish human playability.
+The browser exports the current validated edition and its actual session replay; its print views
+support the browser's Save PDF. Custom source changes also need actual human-input and physical
+rulebook review. Do not claim PDF export, passing simulations, or a screenshot proves a good game.
diff --git a/store/agents/game-master/store.json b/store/agents/game-master/store.json
index bf8e4d1bd..e147369ad 100644
--- a/store/agents/game-master/store.json
+++ b/store/agents/game-master/store.json
@@ -1,16 +1,28 @@
{
- "listed": false,
+ "listed": true,
"homepage": "https://github.com/autonomous-ai/openharness/tree/main/store/agents/game-master",
"license": "MIT",
- "tagline": "Design and compare strategies in a seeded arena",
+ "tagline": "Create a game. Play it. Put it on the table.",
"screenshots": [
- "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/game-master/starter.jpg"
+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/game-master/starter.jpg",
+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/game-master/signal-garden.jpg",
+ "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/game-master/night-ferry.jpg"
],
"examples": [
{
- "prompt": "Create a capture arena where patient defenders face aggressive hunters. Show every decision and compare their win rates over 32 maps.",
- "caption": "Relay · interactive offline starter",
+ "prompt": "Make a two-player garden drafting game we can play without knowing game design. Let us pass private hands, reward flower-and-water pairs, revise the scoring and print the full deck. Keep approved artwork when we change the rules.",
+ "caption": "Pocket Conservatory \u00b7 original drafting rules, editable cards and printable kit",
"image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/game-master/starter.jpg"
+ },
+ {
+ "prompt": "Invent a solo routing puzzle with nine rotating tiles. Let me solve it by clicking the tiles, make a harder edition with fewer moves, and give me correctly sized board and tile sheets to play on paper.",
+ "caption": "Signal Garden \u00b7 human-playable spatial puzzle and physical tiles",
+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/game-master/signal-garden.jpg"
+ },
+ {
+ "prompt": "Design a small push-your-luck game about night ferries. Let us choose to draw cargo or dock, lose only unbanked cargo in a storm, and compare repeated playtests. Then revise the valuable cargo while preserving the approved tea card.",
+ "caption": "Night Ferry \u00b7 original risk/reward rules with editable source",
+ "image": "https://raw.githubusercontent.com/autonomous-ai/openharness/main/store/showcase/game-master/night-ferry.jpg"
}
]
}
diff --git a/store/agents/game-master/template/game/index.html b/store/agents/game-master/template/game/index.html
index 8e109081f..2c92ea0c2 100644
--- a/store/agents/game-master/template/game/index.html
+++ b/store/agents/game-master/template/game/index.html
@@ -1,551 +1,13 @@
-<!doctype html>
-<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
-<meta name="color-scheme" content="dark light"><title>RELAY — Game Master</title>
-<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22256%22%20height%3D%22256%22%20viewBox%3D%220%200%2096%2096%22%3E%0A%20%20%3Ctitle%3EGame%20Master%20%E2%80%94%20opposing%20teams%2C%20one%20relay%3C%2Ftitle%3E%0A%20%20%3Crect%20x%3D%224%22%20y%3D%224%22%20width%3D%2288%22%20height%3D%2288%22%20rx%3D%2223%22%20fill%3D%22%231d2d37%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m19%2031%2013-13%2024%2024-13%2013Z%22%20fill%3D%22%23ed9075%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m40%2054%2013-13%2024%2024-13%2013Z%22%20fill%3D%22%2381c8c4%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m48%2036%2012%2012-12%2012-12-12Z%22%20fill%3D%22%231d2d37%22%20stroke%3D%22%23eed5a0%22%20stroke-width%3D%224%22%2F%3E%0A%20%20%3Ccircle%20cx%3D%2224%22%20cy%3D%2270%22%20r%3D%225%22%20fill%3D%22%23ed9075%22%2F%3E%0A%20%20%3Ccircle%20cx%3D%2272%22%20cy%3D%2226%22%20r%3D%225%22%20fill%3D%22%2381c8c4%22%2F%3E%0A%3C%2Fsvg%3E">
-<!-- Built by store/tools/build-experiences.mjs. Edit this file freely in your workspace. -->
-<style>:root {
- color-scheme: dark;
- --bg: #111414;
- --panel: #191e1c;
- --line: #ffffff1c;
- --ink: #f4f2e9;
- --muted: #a1aaa4;
- --accent: #d0f28a;
- font:
- 14px/1.5 -apple-system,
- BlinkMacSystemFont,
- "Segoe UI",
- sans-serif;
-}
-* {
- box-sizing: border-box;
-}
-body {
- margin: 0;
- background: var(--bg);
- color: var(--ink);
-}
-button,
-input,
-select {
- font: inherit;
-}
-button,
-a,
-input,
-select {
- -webkit-tap-highlight-color: transparent;
-}
-button,
-a {
- touch-action: manipulation;
-}
-button {
- cursor: pointer;
-}
-button:disabled {
- opacity: 0.45;
- cursor: wait;
-}
-button:focus-visible,
-input:focus-visible,
-select:focus-visible,
-a:focus-visible {
- outline: 2px solid var(--accent);
- outline-offset: 4px;
-}
-button,
-input,
-select {
- color: inherit;
- background: transparent;
- border: 1px solid var(--line);
- border-radius: 5px;
- padding: 9px 13px;
-}
-button:hover {
- background: #ffffff0c;
- border-color: var(--muted);
-}
-button.primary {
- background: var(--accent);
- color: #142015;
- border-color: transparent;
- font-weight: 650;
-}
-button[aria-pressed="true"] {
- border-color: var(--accent);
- color: var(--accent);
-}
-input[type="range"] {
- accent-color: var(--accent);
- padding: 0;
- min-width: 0;
-}
-input[type="number"] {
- width: 80px;
-}
-select {
- background: var(--panel);
-}
-label {
- cursor: pointer;
-}
-a {
- color: inherit;
-}
-h1,
-h2,
-h3,
-p {
- margin: 0;
-}
-h1 {
- font-size: clamp(32px, 5vw, 64px);
- line-height: 1.02;
- letter-spacing: -0.055em;
- font-weight: 550;
-}
-h2 {
- font-weight: 550;
- letter-spacing: -0.03em;
-}
-h3 {
- font-size: 14px;
- font-weight: 550;
-}
-.mono,
-.eyebrow {
- font-family: ui-monospace, "SFMono-Regular", Consolas, monospace;
-}
-.eyebrow {
- font-size: 10px;
- letter-spacing: 0.16em;
- text-transform: uppercase;
- color: var(--muted);
-}
-.muted {
- color: var(--muted);
-}
-.small {
- font-size: 12px;
-}
-.masthead {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 20px;
- padding: 19px 28px;
- border-bottom: 1px solid var(--line);
-}
-.identity {
- display: flex;
- gap: 12px;
- align-items: center;
- white-space: nowrap;
- font-size: 12px;
- font-weight: 600;
- letter-spacing: 0.04em;
-}
-.mark {
- width: 28px;
- height: 28px;
- flex: 0 0 28px;
- display: grid;
- place-items: center;
-}
-.mark svg {
- display: block;
- width: 100%;
- height: 100%;
-}
-.seed-form {
- display: flex;
- align-items: center;
- gap: 6px;
-}
-.seed-form label {
- font:
- 10px ui-monospace,
- monospace;
- text-transform: uppercase;
- letter-spacing: 0.12em;
- color: var(--muted);
- margin-right: 4px;
-}
-.seed-form input {
- width: 74px;
- padding: 6px 8px;
- font:
- 12px ui-monospace,
- monospace;
-}
-.seed-form button {
- padding: 6px 10px;
- font-size: 12px;
-}
-.intro {
- padding: 32px 28px;
- display: flex;
- align-items: flex-end;
- justify-content: space-between;
- gap: 20px;
-}
-.intro p {
- max-width: 440px;
- color: var(--muted);
- margin-top: 14px;
-}
-.intro .eyebrow {
- margin-bottom: 12px;
-}
-.actions {
- display: flex;
- align-items: center;
- gap: 8px;
- flex-wrap: wrap;
-}
-.workspace {
- display: grid;
- grid-template-columns: minmax(0, 1fr) 270px;
- gap: 22px;
- padding: 0 28px 28px;
-}
-.panel {
- background: var(--panel);
- border: 1px solid var(--line);
- border-radius: 8px;
- overflow: hidden;
-}
-.panel-head {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 16px 20px;
- border-bottom: 1px solid var(--line);
- gap: 10px;
-}
-.side {
- display: flex;
- flex-direction: column;
- gap: 20px;
-}
-.section {
- border-top: 1px solid var(--line);
- padding-top: 18px;
-}
-.section h3 {
- margin-bottom: 15px;
-}
-.field {
- display: grid;
- gap: 7px;
- margin: 14px 0;
-}
-.field > span {
- display: flex;
- justify-content: space-between;
- font-size: 12px;
- color: var(--muted);
-}
-.metrics {
- display: grid;
- grid-template-columns: repeat(3, 1fr);
- gap: 1px;
- background: var(--line);
- border: 1px solid var(--line);
- border-radius: 6px;
- overflow: hidden;
-}
-.metric {
- background: var(--bg);
- padding: 13px 15px;
-}
-.metric strong {
- display: block;
- font:
- 24px ui-monospace,
- monospace;
- letter-spacing: -0.06em;
-}
-.metric span {
- font-size: 10px;
- color: var(--muted);
- text-transform: uppercase;
- letter-spacing: 0.09em;
-}
-canvas {
- display: block;
- max-width: 100%;
-}
-.status-line {
- display: flex;
- justify-content: space-between;
- gap: 20px;
- padding: 14px 28px;
- border-top: 1px solid var(--line);
- font:
- 10px ui-monospace,
- monospace;
- color: var(--muted);
-}
-.dot {
- width: 6px;
- height: 6px;
- display: inline-block;
- background: var(--accent);
- border-radius: 50%;
- margin-right: 6px;
-}
-.toast {
- position: fixed;
- z-index: 99;
- left: 50%;
- bottom: 22px;
- transform: translateX(-50%);
- max-width: 90vw;
- background: var(--ink);
- color: var(--bg);
- padding: 11px 18px;
- border-radius: 6px;
- box-shadow: 0 3px 30px #0004;
- font-size: 12px;
-}
-.toast:empty {
- display: none;
-}
-[hidden] {
- display: none !important;
-}
-.sr-only {
- position: absolute;
- width: 1px;
- height: 1px;
- padding: 0;
- margin: -1px;
- overflow: hidden;
- clip-path: inset(50%);
- white-space: nowrap;
- border: 0;
-}
-@media (max-width: 800px) {
- .workspace {
- grid-template-columns: 1fr;
- }
- .side {
- display: grid;
- grid-template-columns: repeat(2, minmax(0, 1fr));
- }
- .intro {
- align-items: flex-start;
- flex-direction: column;
- }
- .intro h1 {
- font-size: 44px;
- }
-}
-@media (max-width: 480px) {
- .masthead {
- padding: 13px 16px;
- gap: 8px;
- flex-wrap: wrap;
- }
- .intro {
- padding: 26px 16px;
- }
- .intro h1 {
- font-size: 38px;
- }
- .workspace {
- padding: 0 16px 20px;
- gap: 18px;
- }
- .side {
- grid-template-columns: 1fr;
- }
- .seed-form label {
- display: none;
- }
- .status-line {
- padding: 12px 16px;
- }
- .status-line span:last-child {
- display: none;
- }
- .metrics .metric {
- padding: 12px 10px;
- }
- .panel-head {
- padding: 12px;
- }
- .actions {
- gap: 6px;
- }
-}
-@media (prefers-reduced-motion: reduce) {
- *,
- *::before,
- *::after {
- scroll-behavior: auto !important;
- animation: none !important;
- transition: none !important;
- }
-}
+<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Relay — Game Master</title><link rel="icon" href="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22256%22%20height%3D%22256%22%20viewBox%3D%220%200%2096%2096%22%3E%0A%20%20%3Ctitle%3EGame%20Master%20%E2%80%94%20opposing%20teams%2C%20one%20relay%3C%2Ftitle%3E%0A%20%20%3Crect%20x%3D%224%22%20y%3D%224%22%20width%3D%2288%22%20height%3D%2288%22%20rx%3D%2223%22%20fill%3D%22%231d2d37%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m19%2031%2013-13%2024%2024-13%2013Z%22%20fill%3D%22%23ed9075%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m40%2054%2013-13%2024%2024-13%2013Z%22%20fill%3D%22%2381c8c4%22%2F%3E%0A%20%20%3Cpath%20d%3D%22m48%2036%2012%2012-12%2012-12-12Z%22%20fill%3D%22%231d2d37%22%20stroke%3D%22%23eed5a0%22%20stroke-width%3D%224%22%2F%3E%0A%20%20%3Ccircle%20cx%3D%2224%22%20cy%3D%2270%22%20r%3D%225%22%20fill%3D%22%23ed9075%22%2F%3E%0A%20%20%3Ccircle%20cx%3D%2272%22%20cy%3D%2226%22%20r%3D%225%22%20fill%3D%22%2381c8c4%22%2F%3E%0A%3C%2Fsvg%3E%0A"><style>:root{font-family:Inter,ui-sans-serif,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#213c34;background:#f3f0e7;font-synthesis:none}*{box-sizing:border-box}body{margin:0}button,input,textarea,select{font:inherit}button{border:1px solid #c3cbbf;border-radius:7px;padding:9px 12px;background:#fffcf5;color:inherit;cursor:pointer;font-size:12px;font-weight:600}button:hover{background:#e7eddf}button:disabled{opacity:.45;cursor:default}button.primary{background:#284d3d;border-color:#284d3d;color:#fff8e9}input,textarea,select{max-width:100%;border:1px solid #c7cec1;border-radius:5px;padding:8px;background:#fffdf7;color:inherit}input[type=number]{width:85px}textarea{width:100%;resize:vertical}label{font-size:12px;display:block}label>input,label>textarea,label>select{display:block;width:100%;margin-top:5px}h1,h2,h3,p{margin-top:0}h1{font-family:Georgia,serif;font-weight:400;font-size:42px;letter-spacing:-1px;margin-bottom:10px}h2{font-size:20px}h3{font-size:16px}p{line-height:1.55}small,.muted{color:#69776b}.eyebrow{font-size:10px;letter-spacing:1.5px;font-weight:700;color:#718169;margin-bottom:15px}.row{display:flex;gap:7px;align-items:end;flex-wrap:wrap}[hidden]{display:none!important}.top{display:flex;align-items:center;justify-content:space-between;gap:20px;padding:18px 28px;border-bottom:1px solid #cdd3c4;background:#faf7ef}.brand{display:flex;gap:10px;align-items:center;font-size:20px;letter-spacing:3px;font-weight:800}.brand small{display:block;font-size:8px;letter-spacing:1.7px;margin-top:4px}.logo{display:block;width:35px}.logo svg{width:35px;height:35px}.top nav,.top-actions{display:flex;gap:5px}.top nav button{border-color:transparent;background:none;color:#73806e}.top nav button.active{color:#284d3d;border-bottom-color:#284d3d;border-radius:0}.workspace{display:grid;grid-template-columns:235px minmax(400px,1fr) 255px;min-height:calc(100vh - 78px)}.library,.inspector{padding:27px 20px;border-right:1px solid #d1d6c9;min-width:0}.inspector{border-right:0;border-left:1px solid #d1d6c9}.library h2{font-family:Georgia,serif;font-size:23px;font-weight:400}.library p{font-size:12px}.library .row{margin-bottom:22px}.component-row{width:100%;display:flex;align-items:center;gap:10px;text-align:left;padding:10px 8px;margin:6px 0;background:none;border-color:transparent}.component-row.active{background:#e1e8d9;border-color:#b4c2a7}.component-row .swatch{width:26px;height:35px;border-radius:3px;display:grid;place-content:center;flex-shrink:0}.component-row small{display:block;font-size:10px;margin-top:4px}.rule-settings{border-top:1px solid #cdd3c4;margin-top:24px;padding-top:20px}.rule-settings label{margin:12px 0}.rule-settings input{width:100%}.table-area{padding:28px;min-width:0}.game-heading{display:flex;gap:20px;justify-content:space-between}.game-heading p{font-size:13px;max-width:440px;color:#6d7b6b}.edition{font-size:10px;flex-shrink:0;text-align:right;color:#6d7b6b}.edition .row{margin-top:12px;justify-content:end}.edition button{padding:6px;font-size:10px}.play-toolbar{display:flex;gap:7px;align-items:end;flex-wrap:wrap;margin:17px 0}.play-toolbar input{width:145px;font-size:12px}.play-toolbar label{font-size:10px}.tabletop{position:relative;border-radius:16px;background:#e3e9d9;border:1px solid #c6d1ba;padding:25px;min-height:445px;overflow:hidden;box-shadow:0 12px 30px #344f3210}.turn-heading{display:flex;justify-content:space-between;gap:10px;margin:22px 0}.turn-heading h2{font-family:Georgia,serif;font-weight:400;font-size:25px;margin:0 0 8px}.turn-heading p{font-size:12px;max-width:510px;margin:0}.turn-heading span{font-size:10px;white-space:nowrap}#scores{display:flex;gap:10px;flex-wrap:wrap}#scores>div{background:#f4f6eb;border:1px solid #ccd5bf;padding:9px 15px;border-radius:8px;min-width:110px;font-size:10px;color:#5d6e58}#scores strong{font-size:22px;display:block;color:#28452e;margin-top:5px}.zone{border-top:1px solid #c4ceb7;padding-top:15px;margin-top:20px}.zone h3{font-size:11px;text-transform:uppercase;letter-spacing:1px;color:#65735c;margin:0 0 13px}.cards{display:flex;flex-wrap:wrap;gap:10px;min-height:35px}.game-piece{border:0;padding:0;background:transparent;position:relative;border-radius:7px;transition:transform .15s;box-shadow:0 3px 5px #1b3b3019;width:98px;max-width:100%}.game-piece svg{display:block;width:100%;height:auto;border-radius:5px}.game-piece[data-move]:hover{transform:translateY(-6px);background:transparent;box-shadow:0 6px 9px #1b3b3030}.badge{position:absolute;bottom:2px;right:2px;background:#fff8e6;color:#213c34;padding:2px 4px;font-size:10px;border-radius:3px}.board{display:grid;gap:4px;max-width:410px;padding:8px;background:#d8ddcb;border:1px solid #9ba98e;border-radius:7px}.board-cell{min-width:0;aspect-ratio:1;display:flex;flex-direction:column;align-items:center;justify-content:center;position:relative;border:1px solid #c3cbbb;border-radius:4px}.board-cell>small{font-size:9px;position:absolute;top:3px;left:4px}.board .game-piece{width:85%;box-shadow:none}.board .game-piece svg{border-radius:0}.rotation{position:relative}.rotation .turn-arrow{font-size:11px;display:block}#actions{display:flex;gap:6px;flex-wrap:wrap;margin-top:22px}#actions button{background:#fff8e9;font-size:11px}#curtain{position:absolute;inset:0;background:#244b3e;z-index:5;color:#fff7e6;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding:30px}#curtain h2{font:32px Georgia,serif}#curtain p{max-width:330px;font-size:13px}#curtain .eyebrow{color:#b2c6a3}#curtain .primary{background:#dce7c7;color:#244b3e}#curtain small{margin-top:28px;color:#b4c4ad;max-width:350px;font-size:10px}.playtesting{margin-top:27px;border-top:1px solid #cdd3c4;padding-top:24px}.playtesting .eyebrow{margin-bottom:8px}.playtesting h3{margin:0 0 6px}.playtesting p{font-size:12px;margin:0 0 12px}.playtesting label{font-size:10px}.playtesting .row{align-items:end}.playtesting select{font-size:12px}.simulation-stats{display:flex;gap:18px;flex-wrap:wrap;padding:15px 0;font-size:12px}.simulation-stats strong{display:block;font-size:21px}.inspector #component-preview{max-width:140px;margin:20px auto 24px}.inspector svg{width:100%;height:auto;filter:drop-shadow(0 8px 8px #263d2a30)}#component-form label{margin:13px 0}#component-form .row>label{flex:1}#component-form input{width:100%}#component-form textarea{font-size:12px;line-height:1.5}.danger{color:#9b4d40}.document-view{max-width:1050px;padding:48px 35px;margin:0 auto}.document-view textarea{margin:6px 0 18px;line-height:1.6}.rule-section{border-bottom:1px solid #cdd3c4;margin-bottom:25px;padding-bottom:10px}.lead{font-family:Georgia,serif;font-size:21px}.delivery-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:20px;margin:35px 0}.delivery-grid article{background:#fffcf4;border:1px solid #c8d1bd;border-radius:10px;padding:24px}.delivery-grid article>span{font-size:10px;letter-spacing:1px;color:#6b7d5d}.delivery-grid h2{font:26px Georgia,serif;margin:20px 0 12px}.delivery-grid p{font-size:13px}.delivery-grid button{margin:4px 0}#print-preview{display:flex;gap:15px;overflow:auto;margin-bottom:25px;padding-bottom:20px}#print-preview svg{width:210px;height:297px;flex-shrink:0;border:1px solid #d1d6c9;background:white}#notice{position:fixed;bottom:22px;left:50%;transform:translateX(-50%);max-width:90vw;background:#244b3e;color:white;padding:13px 22px;font-size:13px;border-radius:10px;z-index:50;box-shadow:0 6px 30px #0003}#notice.error{background:#913f32}.source-notice,#edition-notice{background:#f5deb0;padding:13px 20px;display:flex;align-items:center;gap:10px;flex-wrap:wrap;font-size:12px}#edition-notice{margin-bottom:12px;border-radius:8px}dialog{width:min(820px,92vw);max-height:85vh;overflow:auto;background:#faf7ed;border:1px solid #b7c3ac;border-radius:15px;padding:30px;color:#213c34}dialog::backdrop{background:#142c2490}.close{float:right;border:0;background:none;font-size:24px;padding:0}dialog h2{font:28px Georgia,serif}dialog label{margin:15px 0}dialog textarea.code{font-family:ui-monospace,monospace;font-size:12px;white-space:pre;min-height:360px}dialog p{font-size:12px}#editor-apply{margin-top:15px}
+@media(min-width:1550px){.workspace{grid-template-columns:255px minmax(450px,1fr) 295px}.table-area{padding:38px}.tabletop{padding:30px}.game-piece{width:113px}}
+@media(max-width:1180px){.workspace{grid-template-columns:205px minmax(340px,1fr)}.inspector{grid-column:1/-1;border-top:1px solid #cdd3c4;display:grid;grid-template-columns:180px 1fr;gap:20px}.inspector .eyebrow{grid-column:1/-1}.inspector #component-preview{margin:0 auto}#component-form{display:grid;grid-template-columns:1fr 1fr;gap:0 20px}.top{flex-wrap:wrap}.game-heading{display:block}.edition{text-align:left}.edition .row{justify-content:start}.table-area{padding:23px}}
+@media(max-width:720px){.top{padding:15px;gap:15px;display:grid;grid-template-columns:1fr}.top nav{order:3;overflow:auto}.top-actions{flex-wrap:wrap}.workspace{display:block}.library{padding:20px;border-right:0;border-bottom:1px solid #cdd3c4}.library .muted,.library>h2{display:none}#component-list{display:flex;overflow:auto;gap:5px}.component-row{width:145px;flex-shrink:0}.rule-settings{margin-top:15px}.rule-settings #settings{display:flex;gap:12px;flex-wrap:wrap}.rule-settings label{max-width:140px}.table-area{padding:22px 15px}h1{font-size:35px}.tabletop{padding:18px;min-height:430px}.game-piece{width:85px}.inspector{display:block;padding:22px}.inspector #component-preview{max-width:140px;margin-bottom:20px}#component-form{display:block}.document-view{padding:30px 18px}.delivery-grid{grid-template-columns:1fr}.play-toolbar button{font-size:10px}.turn-heading{flex-wrap:wrap}#curtain h2{font-size:27px}.cards{gap:8px}.board{max-width:100%}}
-:root {
- --bg: #161c23;
- --panel: #1d2731;
- --ink: #e7e8e3;
- --muted: #99a7b3;
- --line: #7c90a42b;
- --accent: #aadad1;
-}
-.workspace {
- grid-template-columns: minmax(0, 1fr) 235px;
- gap: 26px;
-}
-.scoreboard {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: 20px 25px;
- border: 1px solid var(--line);
- border-bottom: 0;
- border-radius: 8px 8px 0 0;
- background: #1b242d;
-}
-.team {
- display: flex;
- align-items: center;
- gap: 20px;
-}
-.team .eyebrow {
- color: inherit;
- font-size: 9px;
-}
-.team strong {
- font:
- 44px ui-monospace,
- monospace;
- letter-spacing: -0.08em;
-}
-.ember {
- color: #df896f;
-}
-.tide {
- color: #74c8c2;
- flex-direction: row-reverse;
-}
-.match-state {
- text-align: center;
- font:
- 9px/1.8 ui-monospace,
- monospace;
- color: var(--muted);
- letter-spacing: 0.1em;
-}
-.match-state p {
- color: var(--ink);
-}
-.arena-stage {
- background: radial-gradient(ellipse at center, #273743, #111a22);
- border: 1px solid var(--line);
- border-top: 0;
- border-radius: 0 0 8px 8px;
-}
-.arena-stage canvas {
- width: 100%;
- height: 445px;
-}
-.arena-legend {
- display: flex;
- justify-content: center;
- gap: 20px;
- font:
- 10px ui-monospace,
- monospace;
- padding: 12px;
- color: var(--muted);
-}
-.arena-legend i {
- display: inline-block;
- width: 6px;
- height: 6px;
- border-radius: 50%;
- margin-right: 5px;
-}
-.replay-controls {
- display: flex;
- align-items: center;
- gap: 8px;
- margin: 16px 0;
-}
-.replay-controls input {
- flex: 1;
- width: 50px;
-}
-.replay-controls button,
-.replay-controls select {
- font-size: 11px;
- padding: 7px 9px;
-}
-.event-log {
- padding: 16px 0;
- border-top: 1px solid var(--line);
-}
-#events {
- margin-top: 8px;
- min-height: 108px;
- font:
- 10px/1.8 ui-monospace,
- monospace;
- color: var(--muted);
-}
-#events p {
- overflow-wrap: anywhere;
-}
-.tournament-result {
- font:
- 12px/1.8 ui-monospace,
- monospace;
- color: var(--accent);
- margin-top: 14px;
-}
-@media (max-width: 800px) {
- .workspace {
- grid-template-columns: 1fr;
- }
- .arena-stage canvas {
- height: 420px;
- }
-}
-@media (max-width: 480px) {
- .scoreboard {
- padding: 12px;
- }
- .team {
- gap: 8px;
- flex-direction: column;
- }
- .team strong {
- font-size: 33px;
- }
- .arena-stage canvas {
- height: 320px;
- }
- .arena-legend {
- font-size: 8px;
- gap: 10px;
- }
- .replay-controls {
- gap: 5px;
- }
- .replay-controls button {
- padding: 7px;
- }
-}
+.game-piece:disabled{opacity:1;cursor:default}
+
+.table-piece{width:125px;min-width:0}.table-piece .game-piece{width:100%}.piece-label{font-size:12px;line-height:1.35;display:block;margin-top:8px;font-weight:600}.piece-label small{font-weight:400;font-size:11px;display:block;margin-top:4px}.table-piece details{font-size:11px;margin-top:5px}.table-piece details p{background:#f6f7ef;border-radius:5px;padding:8px;margin-top:6px}.table-piece summary{cursor:pointer;color:#5c7252}.board .table-piece{width:88%}.board .game-piece{width:100%}@media(max-width:720px){.table-piece{width:95px}.piece-label{font-size:11px}.piece-label small{font-size:10px}}
</style></head><body>
-<header class="masthead"><div class="identity"><span class="mark" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 96 96">
+<header class="top"><div class="brand"><span class="logo"><svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 96 96">
<title>Game Master — opposing teams, one relay</title>
<rect x="4" y="4" width="88" height="88" rx="23" fill="#1d2d37"/>
<path d="m19 31 13-13 24 24-13 13Z" fill="#ed9075"/>
@@ -553,590 +15,35 @@ canvas {
<path d="m48 36 12 12-12 12-12-12Z" fill="#1d2d37" stroke="#eed5a0" stroke-width="4"/>
<circle cx="24" cy="70" r="5" fill="#ed9075"/>
<circle cx="72" cy="26" r="5" fill="#81c8c4"/>
-</svg></span>RELAY / ARENA</div>
-<form class="seed-form" id="seed-form"><label for="seed">Seed</label><input id="seed" aria-label="Seed" maxlength="128" autocomplete="off" spellcheck="false"><button type="submit">Apply</button><button id="next-seed" type="button" title="Next seed">↗ Next</button></form></header>
-<section class="intro">
- <div>
- <p class="eyebrow">A contest of strategies / No reflexes required</p>
- <h1>Think in moves.</h1>
- <p>
- Two squads. Three relays. Change the policies, watch the consequences, and
- test your theory across an entire tournament.
- </p>
- </div>
- <button id="export-replay">Export replay ↗</button>
-</section>
-<main class="workspace">
- <div>
- <div class="scoreboard">
- <div class="team ember">
- <span class="eyebrow">EMBER / CORAL</span
- ><strong id="score-ember">0</strong>
- </div>
- <div class="match-state">
- <p id="match-state">THE OPENING</p>
- <span id="turn">Turn 00 / 72</span>
- </div>
- <div class="team tide">
- <span class="eyebrow">TIDE / TEAL</span
- ><strong id="score-tide">0</strong>
- </div>
- </div>
- <section class="arena-stage">
- <canvas
- id="arena"
- aria-label="Strategy arena showing two squads competing for three relays"
- ></canvas>
- <div class="arena-legend">
- <span><i style="background: #df896f"></i>Ember</span
- ><span><i style="background: #74c8c2"></i>Tide</span
- ><span>◇ Hold a relay: +1 / turn</span>
- </div>
- </section>
- <div class="replay-controls">
- <button id="play-match" class="primary">Ⅱ Pause</button
- ><button id="rewind" aria-label="Rewind match">↤</button
- ><button id="step" aria-label="Next turn">→</button
- ><input
- id="timeline"
- aria-label="Replay turn"
- type="range"
- min="0"
- max="72"
- value="0"
- /><select id="speed" aria-label="Playback speed">
- <option value="600">1×</option>
- <option value="250">2×</option>
- <option value="80">4×</option>
- </select>
- </div>
- <section class="event-log">
- <p class="eyebrow">Decisions at this turn / Heuristic policies</p>
- <div id="events" role="log"></div>
- </section>
- </div>
- <aside class="side">
- <div>
- <p class="eyebrow">The matchup</p>
- <label class="field"
- ><span>Ember policy</span
- ><select id="coral-policy">
- <option value="control">Control / hold the relays</option>
- <option value="hunt">Hunt / pressure opponents</option>
- </select></label
- ><label class="field"
- ><span>Tide policy</span
- ><select id="teal-policy">
- <option value="hunt">Hunt / pressure opponents</option>
- <option value="control">Control / hold the relays</option>
- </select></label
- >
- <p class="small muted">
- Control defends captured relays. Hunt trades position for attacks. Each
- knockout scores two points, followed by a three-turn respawn.
- </p>
- </div>
- <div class="section">
- <h3>Put your theory to the test.</h3>
- <p class="small muted">
- Run both policies over 32 seeded maps. Find out whether a convincing win
- survives a different board.
- </p>
- <button id="tournament" style="width: 100%; margin-top: 14px">
- Run 32-match tournament
- </button>
- <div id="tournament-result" class="tournament-result" role="status"></div>
- </div>
- <div class="section small muted">
- All decisions are local, inspectable rules. Replays record every turn,
- position, score and decision. No hidden model calls.
- </div>
- </aside>
-</main>
-<footer class="status-line">
- <span><i class="dot"></i>DETERMINISTIC MATCH ENGINE</span
- ><span>CHANGE A RULE. WATCH A WORLD CHANGE.</span>
-</footer>
-<div class="toast" id="toast" role="status"></div>
-<script id="harness-model">
-'use strict';
-// Shared deterministic primitives. Domain models use named streams so unrelated edits stay stable.
-function hash(value) {
- let h = 2166136261;
- for (const c of String(value)) h = Math.imul(h ^ c.charCodeAt(0), 16777619);
- return h >>> 0;
-}
-function random(seed, stream = "main") {
- let a = hash(`${seed}:${stream}`);
- return () => {
- a = (a + 0x6d2b79f5) | 0;
- let t = Math.imul(a ^ (a >>> 15), 1 | a);
- t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
- };
-}
-const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));
-const lerp = (a, b, t) => a + (b - a) * t;
-const pick = (items, rng) => items[Math.floor(rng() * items.length)];
-function normal(rng) {
- return (
- Math.sqrt(-2 * Math.log(Math.max(1e-9, rng()))) *
- Math.cos(2 * Math.PI * rng())
- );
-}
+</svg>
+</span><span>RELAY<small>GAME WORKSHOP</small></span></div><nav aria-label="Workspace"><button data-tab="workbench" class="active">Workbench</button><button data-tab="rules">Rulebook</button><button data-tab="print">Print &amp; keep</button></nav><div class="top-actions"><button id="open-project">Open game</button><button id="save-source">Save source</button><button class="primary" id="export-kit">Export kit ↗</button></div></header>
+<div id="notice" role="status" hidden></div><div id="source-notice" class="source-notice" hidden><span>The source changed while this edition was open.</span><button id="keep-draft">Download my draft</button><button id="load-source">Keep both &amp; load source</button></div>
+<main id="workbench" class="workspace"><aside class="library"><div class="eyebrow">YOUR GAME / COMPONENTS</div><h2 id="library-title"></h2><p class="muted">Edit the things people hold.</p><div class="row"><button id="add-component">+ Component</button><button id="edit-metadata">Game details</button></div><div id="component-list"></div><div class="rule-settings"><h3>Rule settings</h3><div id="settings"></div><button id="edit-rules">Edit rules module</button></div></aside>
+<section class="table-area"><div class="game-heading"><div><div class="eyebrow">PLAY YOUR CREATION</div><h1 id="game-title"></h1><p id="game-subtitle"></p></div><div class="edition"><span id="source-state">Opening…</span><div class="row"><button id="undo-edit">Undo edit</button><button id="redo-edit">Redo</button></div></div></div><div class="play-toolbar"><label>Seed <input id="seed" value="first-game" maxlength="128"></label><button id="restart">Restart</button><button id="undo-turn">Undo turn</button><button id="save-replay">Save replay</button><button id="open-replay">Open replay</button></div><div id="edition-notice" hidden><span>The table is playing the previous edition.</span><button id="apply-edition">Keep playtest &amp; apply edits</button></div><div class="tabletop"><div id="scores"></div><div class="turn-heading"><div><h2 id="turn-title"></h2><p id="turn-message"></p></div><span id="turn-count"></span></div><div id="zones"></div><div id="actions" aria-label="Legal moves"></div><div id="curtain" hidden><div class="eyebrow">PASS THE TABLE</div><h2 id="curtain-title"></h2><p>Hand the screen to the next player before revealing their view.</p><button class="primary" id="reveal">I’m ready · reveal my turn</button><small>This curtain conceals casual views. Source files and replays contain the game.</small></div></div><section class="playtesting"><div><div class="eyebrow">CHECK THE RULES</div><h3>What happens over many games?</h3><p>Find dead ends and compare outcomes under a named policy.</p></div><div class="row"><label>Games<input id="simulation-count" type="number" min="1" max="200" value="50"></label><label>Policy<select id="policy"><option value="uniform">Uniform legal choices</option><option value="authored">Authored policy</option></select></label><button id="simulate">Run playtest</button></div><div id="simulation-report"></div></section></section>
+<aside class="inspector"><div class="eyebrow">COMPONENT STUDIO</div><div id="component-preview"></div><form id="component-form"></form></aside></main>
+<main id="rules" class="document-view" hidden><div class="eyebrow">THE GAME PEOPLE WILL PLAY</div><h1>Write the rulebook</h1><p class="muted">Explain setup, each decision, scoring and the end of the game. Keep these words in step with your rules module.</p><div id="rulebook-editor"></div><button id="add-section">+ Section</button><button id="print-rules">Open printable rulebook</button></main>
+<main id="print" class="document-view" hidden><div class="eyebrow">FROM SCREEN TO TABLE</div><h1>Keep the whole game.</h1><p class="lead">A playable file, editable source, and the things you can print and hold.</p><div class="delivery-grid"><article><span>01 / PLAY</span><h2>Offline game</h2><p>Open it in a browser. Play, edit components and save your edition.</p><button id="export-html">Download game HTML</button><button id="export-project">Download project</button></article><article><span>02 / MAKE</span><h2>Print &amp; play</h2><p>A4 component sheets at physical size, separate SVGs and board sheets. Print at 100% and check the calibration line.</p><button id="print-components">Open component sheets</button><button id="print-rulebook">Open rulebook</button></article><article><span>03 / KEEP</span><h2>Complete kit</h2><p>Game, source, rulebook, components, boards and the current playtest replay in one ZIP.</p><button id="export-kit-secondary">Download complete kit</button></article></div><div id="print-preview"></div><p class="muted">Card backs are supplied separately for gluing or opaque sleeves. No duplex alignment is assumed. Save PDF from the print dialog; command-line export also produces PDFs.</p></main>
+<dialog id="editor-dialog"><form method="dialog"><button class="close" aria-label="Close editor">×</button></form><h2 id="editor-title"></h2><div id="editor-content"></div><button id="editor-apply" class="primary">Apply changes</button></dialog>
+<input id="face-file" type="file" accept="image/png,image/jpeg,image/webp,image/svg+xml" hidden><input id="project-file" type="file" accept=".json,.relay.json" hidden><input id="replay-file" type="file" accept=".json" hidden>
+<script id="relay-data" type="application/json">{"project":{"spec":1,"id":"pocket-conservatory","title":"Pocket Conservatory","subtitle":"Grow a garden. Pass a possibility. A tiny drafting game for two.","players":2,"settings":[{"id":"rounds","label":"Cards in each starting hand","value":6,"min":3,"max":8,"step":1},{"id":"pair_bonus","label":"Flower + water pair bonus","value":4,"min":0,"max":10,"step":1},{"id":"variety_bonus","label":"Points per different plant group","value":1,"min":0,"max":5,"step":1}],"components":[{"id":"fern","name":"Silver fern","body":"A quiet beginning.","kind":"card","widthMm":63,"heightMm":88,"quantity":4,"color":"#244c40","ink":"#fff8e9","symbol":"✦","values":{"group":"leaf","points":2},"locked":false},{"id":"poppy","name":"Coral poppy","body":"Pairs with water for a flourishing garden.","kind":"card","widthMm":63,"heightMm":88,"quantity":4,"color":"#a44736","ink":"#fff8e9","symbol":"✿","values":{"group":"flower","points":2},"locked":false},{"id":"pond","name":"Rain pool","body":"Each flower + water pair earns the pair bonus.","kind":"card","widthMm":63,"heightMm":88,"quantity":4,"color":"#365e7a","ink":"#fff8e9","symbol":"≈","values":{"group":"water","points":1},"locked":false},{"id":"herb","name":"Wild thyme","body":"A little color and a different kind of leaf.","kind":"card","widthMm":63,"heightMm":88,"quantity":4,"color":"#62642f","ink":"#fff8e9","symbol":"❋","values":{"group":"herb","points":3},"locked":false},{"id":"aster","name":"Evening aster","body":"A second flower for a generous garden.","kind":"card","widthMm":63,"heightMm":88,"quantity":4,"color":"#795c79","ink":"#fff8e9","symbol":"✳","values":{"group":"flower","points":3},"locked":false},{"id":"moss","name":"Velvet moss","body":"Make room for small beginnings.","kind":"card","widthMm":63,"heightMm":88,"quantity":4,"color":"#3e6d53","ink":"#fff8e9","symbol":"⋆","values":{"group":"moss","points":1},"locked":false}],"boards":[],"rulebook":[{"heading":"A garden for two","body":"Pocket Conservatory is a two-player drafting game. Build a little garden by choosing one card at a time from a hand that you will pass to the other gardener. You need the printed deck and a way to note scores."},{"heading":"Set up","body":"Shuffle all printed cards. Deal each gardener the number of cards shown in the rule settings. Put the rest aside face down without looking. Each gardener keeps their hand private. Gardener 1 chooses first each round."},{"heading":"Plant and pass","body":"Each round, Gardener 1 chooses one card and places it face up in their garden, then Gardener 2 does the same. Neither gardener takes another card until both have planted. Swap the remaining hands. Begin the next round. When both hands are empty, the game ends."},{"heading":"Score your garden","body":"Add each planted card’s printed points. Earn the flower + water pair bonus for every pair you can make; each card counts in one pair. Add the variety bonus once per distinct group in your garden. The gardener with the highest score wins; tied scores share the win. The settings and component values printed with this rulebook define this edition."},{"heading":"At the same screen","body":"The hand curtain lets gardeners pass the computer between turns. It conceals the hand from casual view; the offline file and replay are not secret from someone who can inspect the browser or source. Undo is a playtesting tool: it can reveal previous hands. For physical play, reveal only each planted card."}],"rules":"// Pocket Conservatory: original two-player simultaneous-hand drafting rules.\nconst setting=(p,id)=>p.settings.find(s=>s.id===id).value;\nconst component=(p,id)=>p.components.find(c=>c.id===id);\nexport function score(cards,p){let points=cards.reduce((n,id)=>n+component(p,id).values.points,0);const counts={};for(const id of cards){const group=component(p,id).values.group;counts[group]=(counts[group]??0)+1;}points+=Math.min(counts.water??0,counts.flower??0)*setting(p,'pair_bonus');points+=Object.keys(counts).length*setting(p,'variety_bonus');return points;}\nexport function initial(p,ctx){const rounds=setting(p,'rounds'),deck=p.components.flatMap(c=>Array(c.quantity).fill(c.id));if(deck.length\u003crounds*2)throw new Error('Print enough cards to deal both hands.');const shuffled=ctx.shuffle(deck,'deal');return{player:0,round:1,done:false,hands:[shuffled.slice(0,rounds),shuffled.slice(rounds,rounds*2)],tableaux:[[],[]],picked:[false,false]};}\nexport function legal(s,p){return s.done?[]:s.hands[s.player].map((id,i)=>({id:'draft-'+i,label:'Plant '+component(p,id).name,index:i}));}\nexport function apply(s,a,p){const n=JSON.parse(JSON.stringify(s)),who=n.player,[card]=n.hands[who].splice(a.index,1);n.tableaux[who].push(card);n.picked[who]=true;if(n.picked.every(Boolean)){if(!n.hands[0].length)n.done=true;else{n.hands.reverse();n.round++;n.picked=[false,false];}n.player=0;}else n.player=1;return n;}\nexport function observe(s,player,p){return{title:'Round '+s.round+' · Gardener '+(player+1),message:s.done?'Compare your planted gardens.':'Choose one plant, then pass the remaining hand after both gardeners choose.',private:!s.done,scores:s.tableaux.map((cards,i)=>({label:'Gardener '+(i+1),value:score(cards,p)})),zones:[...(!s.done?[{id:'hand',label:'Your hand · choose a plant below',items:s.hands[player].map((id,i)=>({key:'hand-'+i,component:id,action:'draft-'+i}))}]:[]),...s.tableaux.map((cards,i)=>({id:'garden-'+i,label:'Gardener '+(i+1)+' · planted',items:cards.map((id,j)=>({key:i+'-'+j,component:id}))}))]};}\nexport function outcome(s,p){if(!s.done)return null;const scores=s.tableaux.map(c=>score(c,p)),high=Math.max(...scores),winners=scores.flatMap((n,i)=>n===high?[i]:[]);return{title:winners.length===2?'Both gardens flourish':'Gardener '+(winners[0]+1)+' wins',winners,scores};}\nexport function validate(s,p){if(p.players!==2||!Number.isInteger(setting(p,'rounds')))return 'This game needs two players and a whole number of cards per hand.';if(!Array.isArray(s.hands)||s.hands.length!==2||!Array.isArray(s.tableaux)||s.tableaux.length!==2)return'Keep both hands and gardens.';if(s.hands.flat().length+s.tableaux.flat().length!==setting(p,'rounds')*2)return'Card conservation failed.';const counts={};for(const id of [...s.hands.flat(),...s.tableaux.flat()]){const c=component(p,id);if(!c)return'Unknown card.';counts[id]=(counts[id]??0)+1;if(counts[id]>c.quantity)return'Too many copies of a card.';}return true;}\nexport function bot(view,actions){return actions[0].id;}\n","revision":"2f4205c5e659441828f3a6a45906052be2a2846d458a5791518c3f4d7eae2961"},"worker":"(()=>{var c=n=>JSON.parse(JSON.stringify(n)),f=(n,e=160)=>typeof n==\"string\"&&n.length>0&&n.length\u003c=e,v=n=>typeof n==\"string\"&&/^[a-z][a-z0-9_-]{0,63}$/.test(n),N=n=>typeof n==\"string\"&&/^#[a-f0-9]{6}$/i.test(n),m=(n,e,s)=>Number.isFinite(n)&&n>=e&&n\u003c=s;function o(n,e){if(!n)throw new Error(e)}function U(n){o(n&&JSON.stringify(n).length\u003c=3e6,\"Keep the project below 3 MB.\");let e=c(n);o(e.spec===1&&v(e.id)&&f(e.title)&&f(e.subtitle,400),\"Use a version 1 Relay project with an id, title and subtitle.\"),o(Number.isInteger(e.players)&&e.players>=1&&e.players\u003c=6,\"Choose 1\\u20136 players.\"),o(f(e.rules,2e5),\"Include the complete rules module.\"),o(Array.isArray(e.rulebook)&&e.rulebook.length>=1&&e.rulebook.length\u003c=40,\"Include 1\\u201340 rulebook sections.\");for(let t of e.rulebook)o(f(t.heading)&&f(t.body,1e4),\"Rulebook sections need a heading and body.\");o(Array.isArray(e.components)&&e.components.length>0&&e.components.length\u003c=160,\"Create 1\\u2013160 component designs.\");let s=new Set,r=0;for(let t of e.components){o(v(t.id)&&!s.has(t.id),\"Component ids must be unique.\"),s.add(t.id),o(f(t.name,80)&&typeof t.body==\"string\"&&t.body.length\u003c=700,\"Use short, readable component names and text.\"),o([\"card\",\"token\",\"tile\"].includes(t.kind),\"Component kind must be card, token or tile.\"),o(m(t.widthMm,12,190)&&m(t.heightMm,12,273),\"Component dimensions must fit A4 within 10 mm margins.\"),o(Number.isInteger(t.quantity)&&t.quantity>=1&&t.quantity\u003c=100,\"Component quantity must be 1\\u2013100.\"),r+=t.quantity,o(N(t.color)&&N(t.ink),\"Use six-digit hex colors.\"),o(typeof t.symbol==\"string\"&&t.symbol.length\u003c=8,\"Use a short symbol.\"),t.face!==void 0&&o(typeof t.face==\"string\"&&t.face.length\u003c=7e5&&/^data:image\\/(png|jpeg|webp|svg\\+xml);base64,[A-Za-z0-9+/=]+$/.test(t.face),\"Use an embedded PNG, JPEG, WebP or SVG face below 700 KB.\"),o(t.values&&typeof t.values==\"object\"&&!Array.isArray(t.values),\"Component values must be an object.\");for(let[u,a]of Object.entries(t.values))o(v(u)&&(typeof a==\"number\"&&Number.isFinite(a)||typeof a==\"boolean\"||typeof a==\"string\"&&a.length\u003c160),\"Values must be finite numbers, short text or booleans.\");o(Object.keys(t.values).length\u003c=20,\"Keep at most 20 values per component.\")}o(r\u003c=600,\"Keep the kit within 600 physical components.\"),o(Array.isArray(e.settings)&&e.settings.length\u003c=30,\"Keep at most 30 rule settings.\");let i=new Set;for(let t of e.settings)o(v(t.id)&&!i.has(t.id)&&f(t.label),\"Settings need unique ids and labels.\"),i.add(t.id),o(m(t.min,-1e4,1e4)&&m(t.max,t.min,1e4)&&m(t.value,t.min,t.max)&&m(t.step,.001,1e3),\"Setting values must lie inside their declared bounds.\");o(Array.isArray(e.boards)&&e.boards.length\u003c=8,\"Keep at most eight board sheets.\");let l=new Set;for(let t of e.boards){o(v(t.id)&&!l.has(t.id)&&f(t.name),\"Boards need unique ids and names.\"),l.add(t.id),o(m(t.widthMm,30,277)&&m(t.heightMm,30,190),\"Boards must fit landscape A4 within 10 mm margins.\"),o(Number.isInteger(t.cols)&&t.cols>0&&t.cols\u003c=20&&Number.isInteger(t.rows)&&t.rows>0&&t.rows\u003c=20,\"Boards support 1\\u201320 rows and columns.\"),o(Array.isArray(t.cells)&&t.cells.length===t.cols*t.rows,\"Define every board cell.\");for(let u of t.cells)o(typeof u.label==\"string\"&&u.label.length\u003c=30&&N(u.color),\"Board cells need a short label and hex color.\")}return delete e.revision,e}function R(n){let e=c(n);return delete e.rules,delete e.revision,e}function g(n){return n===null||typeof n!=\"object\"?JSON.stringify(n):Array.isArray(n)?\"[\"+n.map(g).join(\",\")+\"]\":\"{\"+Object.keys(n).sort().map(e=>JSON.stringify(e)+\":\"+g(n[e])).join(\",\")+\"}\"}async function q(n){let e=new TextEncoder().encode(typeof n==\"string\"?n:g(n));return[...new Uint8Array(await crypto.subtle.digest(\"SHA-256\",e))].map(s=>s.toString(16).padStart(2,\"0\")).join(\"\")}function y(n){return n&&typeof n==\"object\"&&(Object.values(n).forEach(y),Object.freeze(n)),n}function S(n,e){let s=new Set;function r(i){typeof i==\"number\"?o(Number.isFinite(i),e+\" has a non-finite number.\"):i&&typeof i==\"object\"?(o(!s.has(i),e+\" contains a cycle.\"),s.add(i),o(Array.isArray(i)||Object.getPrototypeOf(i)===Object.prototype,e+\" must be plain JSON.\"),Object.values(i).forEach(r),s.delete(i)):o(i===null||[\"string\",\"boolean\"].includes(typeof i),e+\" must be plain JSON.\")}return r(n),o(JSON.stringify(n).length\u003c1e6,e+\" exceeds 1 MB.\"),n}function k(n){let e=2166136261;for(let s of String(n))e^=s.codePointAt(0),e=Math.imul(e,16777619);return()=>{e+=1831565813;let s=e;return s=Math.imul(s^s>>>15,s|1),s^=s+Math.imul(s^s>>>7,s|61),((s^s>>>14)>>>0)/4294967296}}function x(n,e){return Object.freeze({random:s=>k(n+\"|\"+e+\"|\"+String(s)),shuffle:(s,r)=>{let i=c(s),l=k(n+\"|\"+e+\"|\"+r);for(let t=i.length-1;t>0;t--){let u=Math.floor(l()*(t+1));[i[t],i[u]]=[i[u],i[t]]}return i}})}var b=class{constructor(e,s,r=\"first-game\"){for(let l of[\"initial\",\"legal\",\"apply\",\"observe\",\"outcome\",\"validate\"])o(typeof s[l]==\"function\",\"Rules must export \"+l+\"().\");o(typeof r==\"string\"&&r.length\u003c=128,\"Use a seed of at most 128 characters.\"),this.project=y(R(e)),this.rules=s,this.seed=r,this.actions=[],this.states=[];let i=s.initial(this.project,x(r,0));this.check(i),this.states.push(c(i)),this.verifyTurn()}get state(){return y(c(this.states.at(-1)))}check(e){S(e,\"Game state\"),o(Number.isInteger(e.player)&&e.player>=0&&e.player\u003cthis.project.players,\"State must identify the current player.\");let s=this.rules.validate(y(c(e)),this.project);o(s===!0,typeof s==\"string\"?s:\"Rule validation failed.\")}outcome(){let e=this.rules.outcome(this.state,this.project);return o(e===null||e&&typeof e==\"object\"&&typeof e.title==\"string\"&&Array.isArray(e.winners)&&e.winners.every(s=>Number.isInteger(s)&&s>=0&&s\u003cthis.project.players),\"Outcome must be null or {title,winners,...}.\"),e===null?null:S(e,\"Outcome\")}legal(){let e=this.rules.legal(this.state,this.project);o(Array.isArray(e)&&e.length\u003c=500,\"Rules must offer at most 500 legal actions.\"),S(e,\"Legal actions\");let s=new Set;for(let r of e)o(r&&typeof r.id==\"string\"&&r.id.length\u003c=180&&!s.has(r.id)&&typeof r.label==\"string\"&&r.label.length\u003c=200,\"Legal actions need unique ids and readable labels.\"),s.add(r.id);return c(e)}verifyTurn(){let e=this.outcome(),s=this.legal();return o(e!==null||s.length>0,\"Dead end: the game has no legal action and no outcome.\"),o(e===null||s.length===0,\"Finished games must not offer actions.\"),{end:e,a:s}}view(){let{end:e,a:s}=this.verifyTurn(),r=this.rules.observe(this.state,this.state.player,this.project);return S(r,\"Observation\"),o(r&&typeof r.title==\"string\"&&Array.isArray(r.zones)&&Array.isArray(r.scores),\"Observation needs title, zones and scores.\"),{view:r,actions:s,outcome:e,player:this.state.player,step:this.actions.length,seed:this.seed}}step(e){o(this.actions.length\u003c2e3,\"This playtest reached the 2,000-turn limit. Save its replay and revise the rules.\");let s=this.legal().find(l=>l.id===e);o(s&&!this.outcome(),\"That action is not legal now.\");let r=this.state,i=this.rules.apply(r,y(c(s)),this.project,x(this.seed,this.actions.length+1));this.check(i),o(g(r)!==g(i),\"An action must change the game state.\"),this.states.push(c(i)),this.actions.push(e);try{this.verifyTurn()}catch(l){throw this.states.pop(),this.actions.pop(),l}return this.view()}undo(){return this.actions.length&&(this.states.pop(),this.actions.pop()),this.view()}replay(){return{spec:1,seed:this.seed,actions:c(this.actions),state:g(this.state)}}restore(e){o(e?.spec===1&&Array.isArray(e.actions)&&e.actions.length\u003c=2e3,\"Use a version 1 replay within 2,000 turns.\"),o(e.seed===this.seed,\"Replay seed differs.\");for(let s of e.actions)this.step(s);return o(g(this.state)===e.state,\"Replay state does not match its actions and rules.\"),this.view()}};function I(n,e,{count:s=50,start:r=0,policy:i=\"uniform\",maxTurns:l=400}={}){o(Number.isInteger(s)&&s>=1&&s\u003c=200,\"Simulate 1\\u2013200 games.\"),o(Number.isInteger(l)&&l>=1&&l\u003c=2e3,\"Use a 1\\u20132,000 turn cap.\"),o([\"uniform\",\"authored\"].includes(i),\"Select uniform or authored policy.\"),i===\"authored\"&&o(typeof e.bot==\"function\",\"This rules module has no authored policy.\");let t=[];for(let a=0;a\u003cs;a++){let p=\"playtest-\"+(r+a);try{let h=new b(n,e,p),M=k(p+\"|policy\");for(;!h.outcome()&&h.actions.length\u003cl;){let O=h.view(),J=i===\"uniform\"?O.actions[Math.floor(M()*O.actions.length)].id:e.bot(y(c(O.view)),y(c(O.actions)),{random:M});h.step(J)}t.push({seed:p,turns:h.actions.length,outcome:h.outcome(),capped:!h.outcome(),replay:h.replay()})}catch(h){t.push({seed:p,error:h.message})}}let u=Array(n.players).fill(0);for(let a of t)for(let p of a.outcome?.winners??[])u[p]++;return{spec:1,policy:i,count:s,start:r,maxTurns:l,wins:u,completed:t.filter(a=>a.outcome).length,capped:t.filter(a=>a.capped).length,errors:t.filter(a=>a.error).length,meanTurns:t.reduce((a,p)=>a+(p.turns??0),0)/s,scope:\"Outcomes under the named policy and seeds. These simulations do not establish fun, fairness or human play balance.\",games:t}}var w,j,d,A;self.onmessage=async({data:{id:n,type:e,payload:s}})=>{try{let r;if(e===\"load\"){w=U(s.project),A=await q(w);let i=URL.createObjectURL(new Blob([w.rules],{type:\"text/javascript\"}));try{j=await import(i)}finally{URL.revokeObjectURL(i)}d=new b(w,j,s.seed??\"first-game\"),r={...d.view(),revision:A}}else{if(!d)throw new Error(\"Open a game first.\");if(e===\"step\")r=d.step(s.id);else if(e===\"undo\")r=d.undo();else if(e===\"restart\")d=new b(w,j,s.seed),r=d.view();else if(e===\"replay\")r={...d.replay(),revision:A};else if(e===\"restore\"){if(s.revision!==A)throw new Error(\"This replay belongs to different rules or components. Open its matching game file.\");let i=new b(w,j,s.seed);r=i.restore(s),d=i}else if(e===\"simulate\")r={...I(w,j,s),revision:A};else throw new Error(\"Unknown game operation.\")}self.postMessage({id:n,result:r})}catch(r){self.postMessage({id:n,error:r.message})}};})();\n"}</script><script>(()=>{var $=e=>JSON.parse(JSON.stringify(e)),U=(e,t=160)=>typeof e=="string"&&e.length>0&&e.length<=t,_=e=>typeof e=="string"&&/^[a-z][a-z0-9_-]{0,63}$/.test(e),ae=e=>typeof e=="string"&&/^#[a-f0-9]{6}$/i.test(e),C=(e,t,n)=>Number.isFinite(e)&&e>=t&&e<=n;function p(e,t){if(!e)throw new Error(t)}function v(e){p(e&&JSON.stringify(e).length<=3e6,"Keep the project below 3 MB.");let t=$(e);p(t.spec===1&&_(t.id)&&U(t.title)&&U(t.subtitle,400),"Use a version 1 Relay project with an id, title and subtitle."),p(Number.isInteger(t.players)&&t.players>=1&&t.players<=6,"Choose 1\u20136 players."),p(U(t.rules,2e5),"Include the complete rules module."),p(Array.isArray(t.rulebook)&&t.rulebook.length>=1&&t.rulebook.length<=40,"Include 1\u201340 rulebook sections.");for(let i of t.rulebook)p(U(i.heading)&&U(i.body,1e4),"Rulebook sections need a heading and body.");p(Array.isArray(t.components)&&t.components.length>0&&t.components.length<=160,"Create 1\u2013160 component designs.");let n=new Set,r=0;for(let i of t.components){p(_(i.id)&&!n.has(i.id),"Component ids must be unique."),n.add(i.id),p(U(i.name,80)&&typeof i.body=="string"&&i.body.length<=700,"Use short, readable component names and text."),p(["card","token","tile"].includes(i.kind),"Component kind must be card, token or tile."),p(C(i.widthMm,12,190)&&C(i.heightMm,12,273),"Component dimensions must fit A4 within 10 mm margins."),p(Number.isInteger(i.quantity)&&i.quantity>=1&&i.quantity<=100,"Component quantity must be 1\u2013100."),r+=i.quantity,p(ae(i.color)&&ae(i.ink),"Use six-digit hex colors."),p(typeof i.symbol=="string"&&i.symbol.length<=8,"Use a short symbol."),i.face!==void 0&&p(typeof i.face=="string"&&i.face.length<=7e5&&/^data:image\/(png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/=]+$/.test(i.face),"Use an embedded PNG, JPEG, WebP or SVG face below 700 KB."),p(i.values&&typeof i.values=="object"&&!Array.isArray(i.values),"Component values must be an object.");for(let[c,u]of Object.entries(i.values))p(_(c)&&(typeof u=="number"&&Number.isFinite(u)||typeof u=="boolean"||typeof u=="string"&&u.length<160),"Values must be finite numbers, short text or booleans.");p(Object.keys(i.values).length<=20,"Keep at most 20 values per component.")}p(r<=600,"Keep the kit within 600 physical components."),p(Array.isArray(t.settings)&&t.settings.length<=30,"Keep at most 30 rule settings.");let o=new Set;for(let i of t.settings)p(_(i.id)&&!o.has(i.id)&&U(i.label),"Settings need unique ids and labels."),o.add(i.id),p(C(i.min,-1e4,1e4)&&C(i.max,i.min,1e4)&&C(i.value,i.min,i.max)&&C(i.step,.001,1e3),"Setting values must lie inside their declared bounds.");p(Array.isArray(t.boards)&&t.boards.length<=8,"Keep at most eight board sheets.");let s=new Set;for(let i of t.boards){p(_(i.id)&&!s.has(i.id)&&U(i.name),"Boards need unique ids and names."),s.add(i.id),p(C(i.widthMm,30,277)&&C(i.heightMm,30,190),"Boards must fit landscape A4 within 10 mm margins."),p(Number.isInteger(i.cols)&&i.cols>0&&i.cols<=20&&Number.isInteger(i.rows)&&i.rows>0&&i.rows<=20,"Boards support 1\u201320 rows and columns."),p(Array.isArray(i.cells)&&i.cells.length===i.cols*i.rows,"Define every board cell.");for(let c of i.cells)p(typeof c.label=="string"&&c.label.length<=30&&ae(c.color),"Board cells need a short label and hex color.")}return delete t.revision,t}function N(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(N).join(",")+"]":"{"+Object.keys(e).sort().map(t=>JSON.stringify(t)+":"+N(e[t])).join(",")+"}"}function X(e,t=80){let n=[$(e)],r=0;return{get value(){return $(n[r])},get canUndo(){return r>0},get canRedo(){return r<n.length-1},push(o){return n=n.slice(0,r+1),n.push($(o)),n.length>t&&n.shift(),r=n.length-1,this.value},undo(){return r=Math.max(0,r-1),this.value},redo(){return r=Math.min(n.length-1,r+1),this.value}}}var d=e=>String(e??"").replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t]),E=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,70)||"game",re=(e,t)=>{let n=[];for(let r of String(e).split(`
+`)){let o="";for(let s of r.split(/\s+/))if(s)if(s.length>t){o&&n.push(o);for(let i=0;i<s.length;i+=t)n.push(s.slice(i,i+t));o=""}else(o+" "+s).trim().length>t?(n.push(o),o=s):o=(o+" "+s).trim();n.push(o)}return n},se=(e,t,n,r,o)=>e.map((s,i)=>`<text x="${t}" y="${n+i*r*1.35}" font-size="${r}" fill="${o}">${d(s)}</text>`).join("");function be(e,{back:t=!1}={}){let n=e.widthMm,r=e.heightMm,o=Math.min(5,n*.08),s=e.kind==="card"?3:e.kind==="token"?Math.min(n,r)/2:1;if(t)return`<rect width="${n}" height="${r}" rx="${s}" fill="#203a34"/><path d="M${n*.2} ${r*.5}h${n*.6}M${n*.5} ${r*.2}v${r*.6}" stroke="#e2bd74" stroke-width="1"/><text x="${n/2}" y="${r*.84}" text-anchor="middle" font-size="${Math.min(4,n*.1)}" fill="#fff7e7">RELAY</text>`;if(e.face)return`<rect width="${n}" height="${r}" fill="${e.color}"/><image width="${n}" height="${r}" preserveAspectRatio="xMidYMid meet" href="${d(e.face)}"/>`;let i=n-o*2,c=Math.min(5,n*.075),u=re(e.name,Math.floor(i/(c*.57))),b=Object.entries(e.values).map(([Y,K])=>Y.replace(/_/g," ")+": "+K).join(" \xB7 "),y=Math.min(3.1,n*.048),A=re(e.body,Math.floor(i/(y*.56))),f=Math.min(3,n*.05),H=re(b,Math.floor(i/(f*.56))),w=o+c,B=Math.max(r*.3,w+u.length*c*1.35+2),g=B+Math.min(r*.13,12)+y+2,ee=r-o-H.length*f*1.35+f;p(g+Math.max(0,A.length-1)*y*1.35+2<ee||e.kind!=="card","Text does not fit "+e.name+". Shorten it or enlarge the card.");let z=`<text x="${n/2}" y="${B+Math.min(r*.1,9)}" text-anchor="middle" font-size="${Math.min(r*.23,22)}" fill="${e.ink}">${d(e.symbol)}</text>`;if(e.kind==="tile"&&typeof e.values.ports=="string"){let Y=n/2,K=r/2;return z='<g stroke="'+e.ink+'" stroke-width="'+Math.min(n,r)*.14+'" stroke-linecap="round">'+[...e.values.ports].map(Te=>{let ie={N:[Y,0],E:[n,K],S:[Y,r],W:[0,K]}[Te];return ie?`<path d="M${Y} ${K}L${ie[0]} ${ie[1]}"/>`:""}).join("")+"</g>",`<rect width="${n}" height="${r}" rx="1" fill="${e.color}"/>${z}<text x="3" y="${r-3}" font-size="2.5" fill="${e.ink}">${d(e.name)}</text>`}return e.kind==="token"?`<rect width="${n}" height="${r}" rx="${s}" fill="${e.color}"/>${z}<text x="${n/2}" y="${r*.85}" text-anchor="middle" font-size="${Math.min(3,n*.07)}" fill="${e.ink}">${d(e.name)}</text>`:`<rect width="${n}" height="${r}" rx="${s}" fill="${e.color}"/><rect x="1.5" y="1.5" width="${n-3}" height="${r-3}" rx="${Math.max(0,s-1)}" fill="none" stroke="${e.ink}" stroke-opacity=".3" stroke-width=".25"/>${se(u,o,w,c,e.ink)}${z}${se(A,o,g,y,e.ink)}${se(H,o,ee,f,e.ink)}`}function te(e,t={}){return`<svg xmlns="http://www.w3.org/2000/svg" width="${e.widthMm}mm" height="${e.heightMm}mm" viewBox="0 0 ${e.widthMm} ${e.heightMm}" font-family="Arial, sans-serif" role="img" aria-label="${d(t.back?"Card back":e.name)}">${be(e,t)}</svg>`}function Ae(e,t,n,r){return[[e,t],[e+n,t],[e,t+r],[e+n,t+r]].map(([i,c])=>`<path d="M${i-2.2-1.2} ${c}h${2.2}M${i+1.2} ${c}h${2.2}M${i} ${c-2.2-1.2}v${2.2}M${i} ${c+1.2}v${2.2}"/>`).join("")}function Q(e){v(e);let t=[],n=[],r=10,o=14,s=0,i=()=>{n.length&&t.push(n),n=[],r=10,o=14,s=0};for(let c of e.components)for(let u=0;u<c.quantity;u++)r+c.widthMm>200&&(r=10,o+=s+6,s=0),o+c.heightMm>287&&i(),p(o+c.heightMm<=287,"Component too tall for the print sheet."),n.push({id:c.id,copy:u+1,x:r,y:o,width:c.widthMm,height:c.heightMm}),r+=c.widthMm+6,s=Math.max(s,c.heightMm);return i(),t}function Z(e,t,n,{back:r=!1}={}){return`<svg xmlns="http://www.w3.org/2000/svg" width="210mm" height="297mm" viewBox="0 0 210 297" font-family="Arial, sans-serif"><rect width="210" height="297" fill="white"/><text x="10" y="7" font-size="2.6">${d(e.title)} \xB7 ${r?"optional backs":"components"} \xB7 sheet ${n+1} \xB7 actual size</text>${t.map(o=>{let s=e.components.find(c=>c.id===o.id),i="clip-"+e.id+"-"+n+"-"+o.id+"-"+o.copy+"-"+r;return`<defs><clipPath id="${i}"><rect width="${o.width}" height="${o.height}"/></clipPath></defs><g transform="translate(${o.x} ${o.y})" clip-path="url(#${i})">${be(s,{back:r})}</g>`}).join("")}<g fill="none" stroke="#333" stroke-width=".15">${t.map(o=>Ae(o.x,o.y,o.width,o.height)).join("")}</g><path d="M10 293h50m-50-1v2m50-2v2" stroke="#333" stroke-width=".2"/><text x="65" y="294" font-size="2.2">50 mm calibration \xB7 cut along component edges</text></svg>`}function le(e){let t=e.widthMm,n=e.heightMm,r=t/e.cols,o=(n-12)/e.rows;return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}mm" height="${n}mm" viewBox="0 0 ${t} ${n}" font-family="Arial, sans-serif"><rect width="${t}" height="${n}" fill="#f5eedf"/><text x="4" y="8" font-size="4">${d(e.name)}</text>${e.cells.map((s,i)=>`<g transform="translate(${i%e.cols*r} ${12+Math.floor(i/e.cols)*o})"><rect x=".2" y=".2" width="${r-.4}" height="${o-.4}" fill="${s.color}" stroke="#637669" stroke-width=".3"/><text x="${r/2}" y="${o/2}" text-anchor="middle" font-size="${Math.min(3.5,r/8)}" fill="#203a34">${d(s.label)}</text></g>`).join("")}</svg>`}function ce(e){let t=Q(e);return`<!doctype html><html><head><meta charset="utf-8"><title>${d(e.title)} \u2014 print components</title><style>@page{size:A4;margin:0}body{margin:0;font-family:Arial,sans-serif}.screen{padding:20px;background:#f4efe4}.page{width:210mm;height:297mm;break-after:page;overflow:hidden}.page:last-child{break-after:auto}.page>svg{display:block;width:210mm;height:297mm}@media print{.screen{display:none}}</style></head><body><div class="screen"><h1>${d(e.title)}</h1><p>Print at 100% / actual size on A4. Disable browser headers and footers. Check the 50 mm calibration line. Print card backs separately and glue them to fronts or use opaque sleeves; duplex alignment is not assumed. The separate SVG files keep exact physical dimensions.</p><button onclick="print()">Print components / save PDF</button></div>${t.map((n,r)=>`<section class="page">${Z(e,n,r)}</section>`).join("")}</body></html>`}function de(e){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${d(e.title)} \u2014 rulebook</title><style>@page{size:A4;margin:17mm;@bottom-center{content:counter(page);font-size:9pt}}body{font:11pt/1.5 Arial,sans-serif;color:#203a34;max-width:760px;margin:35px auto}h1{font-size:28pt;line-height:1.1}h2{font-size:15pt;break-after:avoid}p{white-space:pre-line;orphans:3;widows:3}table{border-collapse:collapse;width:100%;font-size:10pt}td,th{padding:6px;border-bottom:1px solid #b6c8b8;text-align:left;vertical-align:top}tr,li{break-inside:avoid}.settings{break-inside:avoid}.print{background:#edf3e7;padding:15px}@media print{body{margin:0;max-width:none}.print{display:none}}</style></head><body><div class="print"><button onclick="print()">Print rulebook / save PDF</button></div><h1>${d(e.title)}</h1><p>${d(e.subtitle)}</p><p>${e.players} player${e.players===1?"":"s"} \xB7 ${e.components.reduce((t,n)=>t+n.quantity,0)} physical components</p>${e.rulebook.map(t=>`<h2>${d(t.heading)}</h2><p>${d(t.body)}</p>`).join("")}<section class="settings"><h2>This edition\u2019s rule settings</h2><table>${e.settings.map(t=>`<tr><th>${d(t.label)}</th><td>${t.value}</td></tr>`).join("")}</table></section><h2>Component inventory and values</h2><table><thead><tr><th>Component</th><th>Copies / size</th><th>Rules values</th></tr></thead><tbody>${e.components.map(t=>`<tr><td>${d(t.name)}</td><td>${t.quantity} \xD7 ${t.widthMm} \xD7 ${t.heightMm} mm</td><td>${Object.entries(t.values).map(([n,r])=>d(n)+": "+d(r)).join("<br>")}</td></tr>`).join("")}</tbody></table><h2>Print and keep</h2><p>Print components at actual size on A4 and check the 50 mm calibration line. Cut at the component edges. Optional backs can be printed separately and glued on or used in opaque sleeves; duplex alignment is not assumed. Board SVGs preserve their dimensions. The kit includes the editable JSON project and complete rules module, plus a playable offline HTML file. Rule or component revisions create a new edition: recheck the physical rulebook when mechanics change.</p></body></html>`}function ye(e,t,n=null,r=null){let o=v(e),s=$(o);delete s.rules;let i={"game.html":t,"project.relay.json":JSON.stringify(o,null,2),"source/project.json":JSON.stringify(s,null,2),"source/rules.mjs":o.rules,"print/components.html":ce(o),"print/rulebook.html":de(o),"README.txt":`${o.title}
+
+Open game.html in a modern desktop browser to play and edit without a server. Open project.relay.json within Relay to restore its source. The source/rules.mjs file defines this game\u2019s mechanics. Project files contain gameplay JavaScript; open work you intend to run.
+
+Print print/components.html at 100% / actual size on A4, no browser headers or footers. Check the 50 mm calibration line. Board SVGs have explicit physical sizes. Optional card backs are separate for gluing or opaque sleeves; no duplex alignment is assumed.
+
+Pass-and-play conceals private views from casual observation, not from browser inspection or saved source/replays. Simulations measure the named policy and seeds, not fun or human balance. No online multiplayer or native game-engine importer is claimed.
+
+Relay source and original artwork: Autonomous, MIT license.
+`,"LICENSE.txt":`MIT License
-const arenaSize = { w: 11, h: 9 };
-function arenaMap(seed) {
- const r = random(seed, "terrain"),
- walls = [];
- for (let y = 1; y < 8; y++)
- if (y !== 4 && r() > 0.48) {
- walls.push([3, y], [7, 8 - y]);
- }
- return {
- ...arenaSize,
- walls,
- relays: [
- { x: 5, y: 1, name: "NORTH" },
- { x: 5, y: 4, name: "CORE" },
- { x: 5, y: 7, name: "SOUTH" },
- ],
- };
-}
-function arenaPath(map, from, target, occupied = []) {
- const blocked = new Set(
- [...map.walls, ...occupied].map(([x, y]) => `${x},${y}`),
- );
- blocked.delete(`${target.x},${target.y}`);
- const queue = [{ x: from.x, y: from.y, path: [] }],
- seen = new Set([`${from.x},${from.y}`]);
- for (let i = 0; i < queue.length; i++) {
- const p = queue[i];
- if (p.x === target.x && p.y === target.y) return p.path;
- for (const [dx, dy] of [
- [1, 0],
- [0, -1],
- [-1, 0],
- [0, 1],
- ]) {
- const x = p.x + dx,
- y = p.y + dy,
- key = `${x},${y}`;
- if (
- x < 0 ||
- y < 0 ||
- x >= map.w ||
- y >= map.h ||
- seen.has(key) ||
- blocked.has(key)
- )
- continue;
- seen.add(key);
- queue.push({ x, y, path: [...p.path, { x, y }] });
- }
- }
- return [];
-}
-function arenaMatch(
- seed,
- { coral = "control", teal = "hunt", rounds = 72 } = {},
-) {
- const map = arenaMap(seed),
- rng = random(seed, "decisions"),
- units = [];
- for (let team = 0; team < 2; team++)
- for (let i = 0; i < 3; i++)
- units.push({
- id: team * 3 + i,
- team,
- x: team ? 10 : 0,
- y: 2 + i * 2,
- hp: 3,
- wait: 0,
- });
- let score = [0, 0],
- owners = [-1, -1, -1];
- const history = [];
- const snapshot = (turn, log) => ({
- turn,
- score: [...score],
- owners: [...owners],
- units: units.map((u) => ({ ...u })),
- log,
- });
- history.push(
- snapshot(0, ["Three relays. Seventy-two turns. Hold ground to score."]),
- );
- for (let turn = 1; turn <= rounds; turn++) {
- const log = [];
- const order = turn % 2 ? [0, 3, 1, 4, 2, 5] : [3, 0, 4, 1, 5, 2];
- for (const index of order) {
- const u = units[index];
- if (u.wait) {
- u.wait--;
- if (!u.wait) {
- u.hp = 3;
- u.x = u.team ? 10 : 0;
- u.y = 2 + (u.id % 3) * 2;
- }
- continue;
- }
- const opponents = units.filter((v) => v.team !== u.team && !v.wait),
- adjacent = opponents.find(
- (v) => Math.abs(v.x - u.x) + Math.abs(v.y - u.y) === 1,
- );
- const name = u.team ? "Tide" : "Ember";
- if (adjacent) {
- adjacent.hp--;
- log.push(
- `${name} ${(u.id % 3) + 1} tags ${adjacent.team ? "Tide" : "Ember"} ${(adjacent.id % 3) + 1}.`,
- );
- if (adjacent.hp === 0) {
- adjacent.wait = 3;
- score[u.team] += 2;
- log.push(`${name} scores a knockout (+2).`);
- }
- continue;
- }
- const policy = u.team ? teal : coral;
- const occupied = units
- .filter((v) => v !== u && !v.wait)
- .map((v) => [v.x, v.y]);
- let target;
- const onRelay = map.relays.findIndex((r) => r.x === u.x && r.y === u.y);
- if (onRelay !== -1 && policy === "control") {
- log.push(
- `${name} ${(u.id % 3) + 1} holds ${map.relays[onRelay].name}.`,
- );
- continue;
- }
- if (policy === "hunt" && opponents.length && rng() < 0.56)
- target = [...opponents].sort(
- (a, b) =>
- Math.abs(a.x - u.x) +
- Math.abs(a.y - u.y) -
- (Math.abs(b.x - u.x) + Math.abs(b.y - u.y)),
- )[0];
- else {
- const candidates = map.relays.map((r, i) => ({
- ...r,
- index: i,
- cost:
- Math.abs(r.x - u.x) +
- Math.abs(r.y - u.y) +
- (owners[i] === u.team ? 7 : 0) +
- rng() * 2,
- }));
- target = candidates.sort((a, b) => a.cost - b.cost)[0];
- }
- const path = arenaPath(map, u, target, occupied);
- const next = path[0];
- if (next && !occupied.some(([x, y]) => x === next.x && y === next.y)) {
- u.x = next.x;
- u.y = next.y;
- log.push(
- `${name} ${(u.id % 3) + 1} → ${target.name || "opponent"} (${policy}).`,
- );
- }
- }
- owners = map.relays.map((r) => {
- const u = units.find((u) => !u.wait && u.x === r.x && u.y === r.y);
- return u ? u.team : -1;
- });
- owners.forEach((owner) => {
- if (owner !== -1) score[owner]++;
- });
- history.push(snapshot(turn, log.slice(-6)));
- }
- return {
- seed: String(seed),
- map,
- policies: { coral, teal },
- history,
- winner: score[0] === score[1] ? -1 : score[0] > score[1] ? 0 : 1,
- };
-}
-function arenaTournament(seed, options, count = 32) {
- const wins = [0, 0, 0];
- let margins = 0;
- for (let i = 0; i < count; i++) {
- const match = arenaMatch(`${seed}/match/${i}`, options);
- wins[match.winner === -1 ? 2 : match.winner]++;
- const last = match.history.at(-1);
- margins += last.score[0] - last.score[1];
- }
- return {
- count,
- ember: wins[0],
- tide: wins[1],
- draws: wins[2],
- meanMargin: margins / count,
- };
-}
+Copyright (c) 2026 Autonomous
-</script>
-<script>
-'use strict';
-const $ = (s) => document.querySelector(s);
-const $$ = (s) => [...document.querySelectorAll(s)];
-const params = new URLSearchParams(location.search);
-let seed = (params.get("seed") || "42").slice(0, 128);
-const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;
-const parentMessage = (message) => {
- if (parent !== window) parent.postMessage(message, "*");
-};
-function toast(message) {
- $("#toast").textContent = message;
- clearTimeout(toast.timer);
- toast.timer = setTimeout(() => {
- $("#toast").textContent = "";
- }, 3500);
-}
-function saveFile(name, content, type = "application/json") {
- const blob =
- content instanceof Blob ? content : new Blob([content], { type });
- const url = URL.createObjectURL(blob),
- a = document.createElement("a");
- a.href = url;
- a.download = name;
- document.body.append(a);
- a.click();
- a.remove();
- setTimeout(() => URL.revokeObjectURL(url), 30000);
-}
-function canvasPNG(canvas, name) {
- canvas.toBlob((blob) => {
- if (blob) saveFile(name, blob);
- else toast("Image export failed. Please try again.");
- });
-}
-function setSeed(value) {
- seed = String(value).trim().slice(0, 128) || "42";
- $("#seed").value = seed;
- const url = new URL(location.href);
- url.searchParams.set("seed", seed);
- try {
- history.replaceState(null, "", url);
- } catch {
- /* Opaque-origin iframe: the shell owns its URL. */
- }
- parentMessage({ type: "harness:state", seed });
- dispatchEvent(new CustomEvent("seedchange", { detail: seed }));
-}
-$("#seed").value = seed;
-$("#seed-form").addEventListener("submit", (e) => {
- e.preventDefault();
- setSeed($("#seed").value);
-});
-$("#next-seed").addEventListener("click", () =>
- setSeed(/^\d{1,9}$/.test(seed) ? Number(seed) + 1 : hash(seed)),
-);
-function fitCanvas(canvas, draw, maxDpr = 2) {
- const observer = new ResizeObserver(() => {
- const box = canvas.getBoundingClientRect(),
- dpr = Math.min(devicePixelRatio || 1, maxDpr);
- canvas.width = Math.max(1, Math.round(box.width * dpr));
- canvas.height = Math.max(1, Math.round(box.height * dpr));
- draw?.();
- });
- observer.observe(canvas);
- return observer;
-}
-const editable = (target) =>
- target instanceof Element &&
- !!target.closest("input,textarea,select,[contenteditable=true]");
-addEventListener("error", (e) =>
- parentMessage({ type: "harness:error", message: e.message }),
-);
-addEventListener("unhandledrejection", (e) =>
- parentMessage({
- type: "harness:error",
- message: String(e.reason?.message || e.reason),
- }),
-);
-function ready() {
- document.body.dataset.ready = "true";
- parentMessage({ type: "harness:ready", title: document.title, seed });
-}
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-let match,
- turn = 0,
- running = !reducedMotion,
- lastTurnTime = 0;
-const policyOptions = () => ({
- coral: $("#coral-policy").value,
- teal: $("#teal-policy").value,
-});
-function drawArena() {
- if (!match) return;
- const c = $("#arena"),
- ctx = c.getContext("2d"),
- w = c.width,
- h = c.height,
- state = match.history[turn],
- unit = Math.min(w / 13, h / 11),
- left = (w - match.map.w * unit) / 2,
- top = (h - match.map.h * unit) / 2;
- ctx.clearRect(0, 0, w, h);
- const pos = (x, y) => ({
- x: left + (x + 0.5) * unit,
- y: top + (y + 0.5) * unit,
- });
- for (let y = 0; y < match.map.h; y++)
- for (let x = 0; x < match.map.w; x++) {
- const p = pos(x, y),
- wall = match.map.walls.some((v) => v[0] === x && v[1] === y);
- ctx.fillStyle = wall ? "#405262" : (x + y) % 2 ? "#24333f" : "#263743";
- ctx.strokeStyle = "#475d6e33";
- ctx.lineWidth = 1;
- ctx.beginPath();
- ctx.roundRect(
- p.x - unit * 0.46,
- p.y - unit * 0.46,
- unit * 0.92,
- unit * 0.92,
- unit * 0.08,
- );
- ctx.fill();
- ctx.stroke();
- if (wall) {
- ctx.fillStyle = "#536573";
- ctx.fillRect(
- p.x - unit * 0.3,
- p.y - unit * 0.3,
- unit * 0.6,
- unit * 0.12,
- );
- }
- }
- match.map.relays.forEach((r, i) => {
- const p = pos(r.x, r.y),
- owner = state.owners[i];
- ctx.strokeStyle = owner === -1 ? "#d6c69a" : owner ? "#74c8c2" : "#df896f";
- ctx.lineWidth = 2;
- ctx.save();
- ctx.translate(p.x, p.y);
- ctx.rotate(Math.PI / 4);
- ctx.strokeRect(-unit * 0.3, -unit * 0.3, unit * 0.6, unit * 0.6);
- ctx.restore();
- ctx.fillStyle = ctx.strokeStyle;
- ctx.font = `${unit * 0.16}px monospace`;
- ctx.textAlign = "center";
- ctx.fillText(r.name, p.x, p.y + unit * 0.47);
- });
- state.units
- .filter((u) => !u.wait)
- .forEach((u) => {
- const p = pos(u.x, u.y),
- color = u.team ? "#74c8c2" : "#df896f";
- ctx.shadowColor = color;
- ctx.shadowBlur = 10;
- ctx.fillStyle = color;
- ctx.beginPath();
- ctx.arc(p.x, p.y, unit * 0.25, 0, Math.PI * 2);
- ctx.fill();
- ctx.shadowBlur = 0;
- ctx.fillStyle = "#162129";
- ctx.textAlign = "center";
- ctx.textBaseline = "middle";
- ctx.font = `bold ${unit * 0.24}px monospace`;
- ctx.fillText((u.id % 3) + 1, p.x, p.y);
- ctx.fillStyle = color;
- for (let i = 0; i < u.hp; i++)
- ctx.fillRect(
- p.x - unit * 0.19 + i * unit * 0.14,
- p.y - unit * 0.39,
- unit * 0.1,
- unit * 0.055,
- );
- });
- ctx.textBaseline = "alphabetic";
-}
-function showTurn() {
- const state = match.history[turn];
- $("#score-ember").textContent = state.score[0];
- $("#score-tide").textContent = state.score[1];
- $("#turn").textContent = `Turn ${String(turn).padStart(2, "0")} / 72`;
- $("#timeline").value = turn;
- $("#match-state").textContent =
- turn === 72
- ? match.winner === -1
- ? "DRAW"
- : match.winner
- ? "TIDE WINS"
- : "EMBER WINS"
- : turn < 12
- ? "THE OPENING"
- : turn < 50
- ? "THE CONTEST"
- : "THE ENDGAME";
- $("#events").replaceChildren();
- state.log.forEach((line) => {
- const p = document.createElement("p");
- p.textContent = line;
- $("#events").append(p);
- });
- $("#play-match").textContent = running
- ? "Ⅱ Pause"
- : turn === 72
- ? "↻ Replay"
- : "▶ Play";
- drawArena();
-}
-function newMatch() {
- match = arenaMatch(seed, policyOptions());
- turn = 0;
- $("#tournament-result").textContent = "";
- showTurn();
-}
-$("#play-match").onclick = () => {
- if (turn === 72) turn = 0;
- running = !running;
- lastTurnTime = performance.now();
- showTurn();
-};
-$("#step").onclick = () => {
- running = false;
- turn = Math.min(72, turn + 1);
- showTurn();
-};
-$("#rewind").onclick = () => {
- running = false;
- turn = 0;
- showTurn();
-};
-$("#timeline").oninput = () => {
- running = false;
- turn = +$("#timeline").value;
- showTurn();
-};
-for (const id of ["coral-policy", "teal-policy"])
- $("#" + id).onchange = newMatch;
-$("#export-replay").onclick = () =>
- saveFile(`relay-${hash(seed)}.json`, JSON.stringify(match, null, 2));
-$("#tournament").onclick = async () => {
- const b = $("#tournament");
- b.disabled = true;
- $("#tournament-result").textContent = "Playing 32 independent maps…";
- await new Promise((r) => setTimeout(r, 30));
- const result = arenaTournament(seed, policyOptions());
- $("#tournament-result").textContent =
- `Ember ${result.ember} · Tide ${result.tide} · Draws ${result.draws}. Mean Ember margin: ${result.meanMargin.toFixed(1)} points.`;
- b.disabled = false;
-};
-function arenaFrame(time) {
- if (running && time - lastTurnTime > +$("#speed").value) {
- turn = Math.min(72, turn + 1);
- if (turn === 72) running = false;
- lastTurnTime = time;
- showTurn();
- }
- requestAnimationFrame(arenaFrame);
-}
-fitCanvas($("#arena"), drawArena);
-addEventListener("seedchange", newMatch);
-newMatch();
-requestAnimationFrame(arenaFrame);
-ready();
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+`};Q(o).forEach((c,u)=>{i[`print/sheet-${u+1}.svg`]=Z(o,c,u),i[`print/backs-${u+1}.svg`]=Z(o,c,u,{back:!0})});for(let c of o.components)i[`components/${c.id}.svg`]=te(c);for(let c of o.boards)i[`boards/${c.id}.svg`]=le(c);return n&&(i["playtest/replay.json"]=JSON.stringify(n,null,2)),r&&(i["playtest/simulation.json"]=JSON.stringify(r,null,2)),i}function pe(e){Array.isArray(e)||(e=Object.entries(e));let t=new TextEncoder,n=[],r=[],o=0;for(let[u,b]of e){let y=t.encode(u),A=typeof b=="string"?t.encode(b):new Uint8Array(b),f=4294967295;for(let ee of A){f^=ee;for(let z=0;z<8;z++)f=f>>>1^3988292384&-(f&1)}f=(f^4294967295)>>>0;let H=new Uint8Array(30+y.length),w=new DataView(H.buffer);w.setUint32(0,67324752,!0),w.setUint16(4,20,!0),w.setUint16(6,2048,!0),w.setUint16(12,33,!0),w.setUint32(14,f,!0),w.setUint32(18,A.length,!0),w.setUint32(22,A.length,!0),w.setUint16(26,y.length,!0),H.set(y,30);let B=new Uint8Array(46+y.length),g=new DataView(B.buffer);g.setUint32(0,33639248,!0),g.setUint16(4,20,!0),g.setUint16(6,20,!0),g.setUint16(8,2048,!0),g.setUint16(14,33,!0),g.setUint32(16,f,!0),g.setUint32(20,A.length,!0),g.setUint32(24,A.length,!0),g.setUint16(28,y.length,!0),g.setUint32(42,o,!0),B.set(y,46),n.push(H,A),r.push(B),o+=H.length+A.length}let s=r.reduce((u,b)=>u+b.length,0),i=new Uint8Array(22),c=new DataView(i.buffer);return c.setUint32(0,101010256,!0),c.setUint16(8,e.length,!0),c.setUint16(10,e.length,!0),c.setUint32(12,s,!0),c.setUint32(16,o,!0),new Blob([...n,...r,i],{type:"application/zip"})}var a=e=>document.getElementById(e),ne=JSON.parse(a("relay-data").textContent),Oe=`<!doctype html>
+`+document.documentElement.outerHTML,l=v(ne.project),F=ne.project.revision,ue=!1,J=!1,I=null,L=X(l),x=l.components[0].id,O=$(l),ve="",h=null,k=null,q=null,Ne=0,R=new Map,G=!1,we,ke,Ee,oe="relay-draft:"+location.href,P=(e,t,n="application/octet-stream")=>{let r=URL.createObjectURL(t instanceof Blob?t:new Blob([t],{type:n})),o=document.createElement("a");o.href=r,o.download=e,o.click(),setTimeout(()=>URL.revokeObjectURL(r),1e4)};function M(e,t=!1){clearTimeout(we),a("notice").textContent=e,a("notice").hidden=!1,a("notice").classList.toggle("error",t),we=setTimeout(()=>a("notice").hidden=!0,t?14e3:6500)}var m=e=>async(...t)=>{try{return await e(...t)}catch(n){M(n.message,!0)}};function V(){try{localStorage.setItem(oe,JSON.stringify({baseRevision:F,project:l}))}catch{M("Browser draft storage is full. Download the project to keep this edition.",!0)}}function Re(){q&&q.terminate();for(let t of R.values())clearTimeout(t.timer),t.reject(new Error("The previous rules worker stopped."));R.clear();let e=URL.createObjectURL(new Blob([ne.worker],{type:"text/javascript"}));q=new Worker(e),URL.revokeObjectURL(e),q.onmessage=({data:t})=>{let n=R.get(t.id);n&&(R.delete(t.id),clearTimeout(n.timer),t.error?n.reject(new Error(t.error)):n.resolve(t.result))},q.onerror=t=>{for(let n of R.values())clearTimeout(n.timer),n.reject(new Error(t.message||"Rules worker failed."));R.clear()}}function T(e,t={}){return new Promise((n,r)=>{let o=++Ne,s=setTimeout(()=>{q.terminate(),J=!1,S();for(let i of R.values())clearTimeout(i.timer),i.reject(new Error("Rules exceeded the time limit. Your source is kept; revise it and apply again."));R.clear()},e==="simulate"?3e4:4e3);R.set(o,{resolve:n,reject:r,timer:s}),q.postMessage({id:o,type:e,payload:t})})}function me(e){let t=JSON.stringify({project:e,worker:ne.worker}).replace(/</g,"\\u003c");return Oe.replace(/(<script id="relay-data" type="application\/json">)[\s\S]*?(<\/script>)/,(n,r,o)=>r+t+o)}async function he(e,{seed:t=a("seed").value,curtain:n=!0}={}){J=!1,S(),Re();let r=await T("load",{project:e,seed:t});J=!0,O=$(e),ve=r.revision,h=r,k=null,a("simulation-report").replaceChildren(),W(n),S()}async function fe(){if(!h)return;let e=null;try{e=await T("replay")}catch{}P(E(O.title)+"-previous-playtest.zip",pe({"game.html":me(O),"project.relay.json":JSON.stringify(O,null,2),"replay.json":JSON.stringify(e,null,2)}))}function j(e){let t=$(l);e(t),l=v(t),L.push(l),V(),D(),S()}function S(){let e=N(l)!==N(O);a("edition-notice").hidden=!e&&J,a("restart").disabled=!J,a("edition-notice").querySelector("span").textContent=J?"The table is playing the previous edition.":"Apply a valid edition to start the table.",a("game-title").textContent=l.title,a("game-subtitle").textContent=l.subtitle,a("source-state").textContent=(ue?"Workspace source":"Portable game")+(I?" \xB7 source changed":e?" \xB7 draft edition":" \xB7 playing current edition"),a("undo-edit").disabled=!L.canUndo,a("redo-edit").disabled=!L.canRedo,a("save-source").disabled=!ue,document.title=l.title+" \u2014 Relay"}function D(){a("library-title").textContent=l.title,a("component-list").innerHTML=l.components.map(n=>`<button class="component-row ${n.id===x?"active":""}" data-component="${d(n.id)}"><span class="swatch" style="background:${n.color};color:${n.ink}">${d(n.symbol)}</span><span>${d(n.name)}${n.locked?" \xB7 locked":""}<small>${n.quantity} ${d(n.kind)}${n.quantity===1?"":"s"} \xB7 ${n.widthMm} \xD7 ${n.heightMm} mm</small></span></button>`).join(""),a("component-list").querySelectorAll("button").forEach(n=>n.onclick=()=>{x=n.dataset.component,D()}),a("settings").innerHTML=l.settings.map(n=>`<label>${d(n.label)}<input data-setting="${n.id}" type="number" min="${n.min}" max="${n.max}" step="${n.step}" value="${n.value}"></label>`).join(""),a("settings").querySelectorAll("input").forEach(n=>n.onchange=m(()=>j(r=>r.settings.find(o=>o.id===n.dataset.setting).value=Number(n.value))));let e=l.components.find(n=>n.id===x)??l.components[0];x=e.id;try{a("component-preview").innerHTML=te(e)}catch(n){a("component-preview").textContent=n.message}let t=e.locked?"disabled":"";a("component-form").innerHTML=`<label>Name<input name="name" maxlength="80" value="${d(e.name)}" ${t}></label><label>Card text<textarea name="body" rows="4" maxlength="700" ${t}>${d(e.body)}</textarea></label><div class="row"><label>Color<input name="color" type="color" value="${e.color}" ${t}></label><label>Ink<input name="ink" type="color" value="${e.ink}" ${t}></label></div><label>Symbol<input name="symbol" maxlength="8" value="${d(e.symbol)}" ${t}></label><div class="row"><label>Width \xB7 mm<input name="widthMm" type="number" min="12" max="190" step=".5" value="${e.widthMm}" ${t}></label><label>Height \xB7 mm<input name="heightMm" type="number" min="12" max="273" step=".5" value="${e.heightMm}" ${t}></label></div><label>Copies<input name="quantity" type="number" min="1" max="100" value="${e.quantity}" ${t}></label><div class="row"><button type="button" id="import-face" ${t}>Import face artwork</button>${e.face?`<button type="button" id="reset-face" ${t}>Use generated face</button>`:""}</div>${e.face?'<p class="muted" style="font-size:11px">Custom artwork owns the printed face. Update its text when you change rules values.</p>':""}<h3>Rules values</h3>${Object.entries(e.values).map(([n,r])=>`<label>${d(n)}<input data-value="${d(n)}" data-type="${typeof r}" value="${d(r)}" ${t}></label>`).join("")}<div class="row"><button type="button" id="lock-component">${e.locked?"Unlock":"Lock"} component</button><button type="button" id="duplicate-component">Duplicate</button></div><p class="muted" style="font-size:10px;margin-top:14px">Rules read component ids and values. Editing this draft keeps the running playtest intact until you apply it.</p>`,a("component-form").onsubmit=n=>n.preventDefault(),a("component-form").querySelectorAll("input,textarea").forEach(n=>n.onchange=m(()=>j(r=>{let o=r.components.find(s=>s.id===x);if(o.locked)throw new Error("Unlock this approved component before editing.");if(n.dataset.value){let s=n.dataset.type;if(s==="boolean"&&!["true","false"].includes(n.value))throw new Error("Enter true or false.");o.values[n.dataset.value]=s==="number"?Number(n.value):s==="boolean"?n.value==="true":n.value}else o[n.name]=["widthMm","heightMm","quantity"].includes(n.name)?Number(n.value):n.value}))),a("import-face").onclick=()=>a("face-file").click(),a("reset-face")&&(a("reset-face").onclick=m(()=>j(n=>delete n.components.find(r=>r.id===x).face))),a("lock-component").onclick=m(()=>j(n=>n.components.find(r=>r.id===x).locked=!e.locked)),a("duplicate-component").onclick=m(()=>{let n=$(e);n.id="piece-"+Date.now().toString(36),n.name=e.name+" copy",n.locked=!1,x=n.id,j(r=>r.components.push(n))})}function W(e=!1){if(!h)return;let t=O;a("scores").innerHTML=h.view.scores.map(o=>`<div>${d(o.label)}<strong>${d(o.value)}</strong></div>`).join(""),a("turn-title").textContent=h.outcome?.title??h.view.title,a("turn-message").textContent=h.view.message??"",a("turn-count").textContent="Turn "+h.step,a("undo-turn").disabled=!h.step;let n=o=>{let s=t.components.find(i=>i.id===o.component);if(o={...o,action:h.actions.some(i=>i.id===o.action)?o.action:null},!s)throw new Error("Observation refers to unknown component "+o.component);return`<div class="table-piece"><button class="game-piece" ${o.action?`data-move="${d(o.action)}"`:""} aria-label="${d(o.faceDown?"Face-down piece":s.name)}" ${o.action?"":"disabled"}><div style="transform:rotate(${Number(o.rotation)||0}deg)">${te(s,{back:!!o.faceDown})}</div>${o.badge!==void 0?`<span class="badge">${d(o.badge)}</span>`:""}</button>${s.kind==="card"&&!o.faceDown?`<span class="piece-label">${d(s.name)}<small>${Object.entries(s.values).map(([i,c])=>d(i)+": "+d(c)).join(" \xB7 ")}</small></span><details><summary>Read card</summary><p>${d(s.body)}</p></details>`:""}</div>`};a("zones").innerHTML=h.view.zones.map(o=>{let s;if(o.board){let i=t.boards.find(c=>c.id===o.board);if(!i)throw new Error("Unknown board "+o.board);s=`<div class="board" style="grid-template-columns:repeat(${i.cols},1fr)">${i.cells.map((c,u)=>`<div class="board-cell" style="background:${c.color}"><small>${d(c.label)}</small>${o.items.filter(b=>b.cell===u).map(n).join("")}</div>`).join("")}</div>`}else s=`<div class="cards">${o.items.map(n).join("")||"<small>No components here yet.</small>"}</div>`;return`<section class="zone"><h3>${d(o.label)}</h3>${s}</section>`}).join(""),a("actions").innerHTML=h.actions.map(o=>`<button data-move="${d(o.id)}">${d(o.label)}</button>`).join(""),document.querySelectorAll("[data-move]").forEach(o=>o.onclick=m(()=>Ue(o.dataset.move)));let r=!h.outcome&&!!h.view.private;a("curtain").hidden=!(e&&r);for(let o of["scores","zones","actions"])a(o).inert=!a("curtain").hidden;a("curtain-title").textContent="Player "+(h.player+1)+", your turn."}async function Ue(e){if(!G){G=!0;try{let t=h.player;h=await T("step",{id:e}),W(h.player!==t),xe()}finally{G=!1}}}async function xe(){try{let e=await T("replay");localStorage.setItem(oe+":replay",JSON.stringify({project:O,replay:e}))}catch{}}function je(){a("rulebook-editor").innerHTML=l.rulebook.map((e,t)=>`<section class="rule-section"><label>Section heading<input data-heading="${t}" maxlength="160" value="${d(e.heading)}"></label><label>Instructions<textarea data-body="${t}" rows="5" maxlength="10000">${d(e.body)}</textarea></label></section>`).join(""),a("rulebook-editor").querySelectorAll("input,textarea").forEach(e=>e.onchange=m(()=>j(t=>{let n=Number(e.dataset.heading??e.dataset.body);t.rulebook[n][e.dataset.heading===void 0?"body":"heading"]=e.value})))}function Se(e){let t=URL.createObjectURL(new Blob([e],{type:"text/html"}));window.open(t,"_blank","noopener"),setTimeout(()=>URL.revokeObjectURL(t),6e4)}function ge(e,t,n){a("editor-title").textContent=e,a("editor-content").innerHTML=t,ke=n,a("editor-dialog").showModal()}a("editor-apply").onclick=m(()=>{ke(),a("editor-dialog").close()});a("edit-rules").onclick=()=>ge("Author this game\u2019s rules",`<p>The complete JavaScript module defines mechanics. Export initial, legal, apply, observe, outcome and validate; optional bot supplies a named policy. Use only local code. An edited module becomes a new edition when you apply it to the table.</p><textarea id="rules-code" class="code" spellcheck="false">${d(l.rules)}</textarea>`,()=>j(e=>e.rules=a("rules-code").value));a("edit-metadata").onclick=()=>ge("Game details",`<label>Title<input id="game-name-edit" value="${d(l.title)}" maxlength="160"></label><label>Subtitle<textarea id="game-subtitle-edit" maxlength="400">${d(l.subtitle)}</textarea></label><label>Players<input id="game-players-edit" type="number" min="1" max="6" value="${l.players}"></label><p>Player count must match the authored rules.</p>`,()=>j(e=>{e.title=a("game-name-edit").value,e.subtitle=a("game-subtitle-edit").value,e.players=Number(a("game-players-edit").value)}));a("add-component").onclick=()=>ge("Add a component",'<label>Name<input id="new-name" value="New card" maxlength="80"></label><label>Kind<select id="new-kind"><option value="card">Card</option><option value="tile">Tile</option><option value="token">Token</option></select></label><p>Adding a design does not invent its behavior. Reference its id and values in the rules module.</p>',()=>{let e="piece-"+Date.now().toString(36),t=a("new-kind").value;x=e,j(n=>n.components.push({id:e,name:a("new-name").value,body:"",kind:t,widthMm:t==="card"?63:35,heightMm:t==="card"?88:35,quantity:1,color:"#365948",ink:"#fff8e9",symbol:"\u2726",values:{},locked:!1}))});a("undo-edit").onclick=()=>{l=L.undo(),V(),D(),S()};a("redo-edit").onclick=()=>{l=L.redo(),V(),D(),S()};a("apply-edition").onclick=m(async()=>{await fe(),await he(l),M("Previous game and replay downloaded. Playing the edited edition.")});a("restart").onclick=m(async()=>{await fe(),h=await T("restart",{seed:a("seed").value}),W(!0),M("A fresh playtest is ready. The previous game was kept.")});a("undo-turn").onclick=m(async()=>{h=await T("undo"),W(!0),xe()});a("reveal").onclick=()=>{a("curtain").hidden=!0;for(let e of["scores","zones","actions"])a(e).inert=!1};a("save-replay").onclick=m(async()=>P(E(O.title)+"-replay.json",JSON.stringify(await T("replay"),null,2),"application/json"));a("open-replay").onclick=()=>a("replay-file").click();a("replay-file").onchange=m(async e=>{let t=e.target.files[0];if(t){if(t.size>5e6)throw new Error("Choose a replay below 5 MB.");h=await T("restore",JSON.parse(await t.text())),a("seed").value=h.seed,W(!0),M("Replay verified against its rules and actions."),e.target.value=""}});a("simulate").onclick=m(async()=>{if(!G){G=!0,a("simulate").disabled=!0,a("simulate").textContent="Testing\u2026";try{k=await T("simulate",{count:Number(a("simulation-count").value),policy:a("policy").value,maxTurns:400}),a("simulation-report").innerHTML=`<div class="simulation-stats"><span><strong>${k.completed}/${k.count}</strong>completed</span><span><strong>${k.errors}</strong>errors</span><span><strong>${k.capped}</strong>turn caps</span><span><strong>${k.meanTurns.toFixed(1)}</strong>mean turns</span>${k.wins.map((e,t)=>`<span><strong>${e}</strong>Player ${t+1} wins</span>`).join("")}</div><p>${d(k.scope)}</p><button id="save-simulation">Download seeds, outcomes &amp; replays</button>`,a("save-simulation").onclick=()=>P(E(O.title)+"-simulation.json",JSON.stringify(k,null,2),"application/json")}finally{G=!1,a("simulate").disabled=!1,a("simulate").textContent="Run playtest"}}});async function Me(){if(v(l),Q(l),!(N(l)===N(O))||!J)throw new Error("Apply this edition to the table before exporting its complete kit. Your draft project can always be downloaded.");let t=await T("replay");P(E(l.title)+"-print-and-play.zip",pe(ye(l,me(l),t,k))),M("Complete playable and printable game exported.")}a("export-kit").onclick=m(Me);a("export-kit-secondary").onclick=m(Me);a("export-html").onclick=m(()=>P(E(l.title)+".html",me(v(l)),"text/html"));a("export-project").onclick=()=>P(E(l.title)+".relay.json",JSON.stringify(l,null,2),"application/json");a("print-components").onclick=m(()=>Se(ce(l)));a("print-rulebook").onclick=a("print-rules").onclick=m(()=>Se(de(l)));a("add-section").onclick=m(()=>{j(e=>e.rulebook.push({heading:"New section",body:"Describe the next part of the game."})),je()});a("face-file").onchange=m(async e=>{let t=e.target.files[0];if(!t)return;if(!["image/png","image/jpeg","image/webp","image/svg+xml"].includes(t.type)||t.size>5e5)throw new Error("Use a PNG, JPEG, WebP or SVG face below 500 KB.");let r=new Uint8Array(await t.arrayBuffer()),o="";for(let c of r)o+=String.fromCharCode(c);let s="data:"+t.type+";base64,"+btoa(o),i=new Image;i.src=s,await i.decode(),j(c=>{let u=c.components.find(b=>b.id===x);if(u.locked)throw new Error("Unlock the component before replacing its artwork.");u.face=s}),e.target.value=""});a("open-project").onclick=()=>a("project-file").click();a("project-file").onchange=m(async e=>{let t=e.target.files[0];if(!t)return;if(t.size>3e6)throw new Error("Choose a game project below 3 MB.");let n=v(JSON.parse(await t.text()));await fe(),l=n,L=X(l),x=l.components[0].id,V(),D(),S(),await he(l),e.target.value="",M("Game source opened. Save source to replace the workspace edition.")});async function Ce(){let e=await fetch("/api/project",{method:"PUT",headers:{"content-type":"application/json","if-match":F},body:JSON.stringify(l)}),t=await e.json();if(e.status===409)throw I=t.project,a("source-notice").hidden=!1,new Error("The agent changed the source. Keep both editions before choosing.");if(!e.ok)throw new Error(t.error);F=t.project.revision,I=null,a("source-notice").hidden=!0,V(),S(),M("Source saved with the previous edition in workspace history.")}a("save-source").onclick=m(Ce);a("keep-draft").onclick=()=>P(E(l.title)+"-draft.relay.json",JSON.stringify(l,null,2),"application/json");a("load-source").onclick=m(async()=>{I&&(P(E(l.title)+"-before-source.relay.json",JSON.stringify(l,null,2),"application/json"),l=v(I),F=I.revision,I=null,a("source-notice").hidden=!0,L=X(l),V(),D(),S(),M("Both source editions kept. Apply the new edition when ready to restart the playtest."))});async function $e(){try{let e=await fetch("/api/project",{cache:"no-store"});if(!e.ok)return;let t=await e.json();ue=!0,t.project.revision!==F&&(I=t.project,a("source-notice").hidden=!1),S()}catch{}}for(let e of document.querySelectorAll("[data-tab]"))e.onclick=m(()=>{for(let t of["workbench","rules","print"])a(t).hidden=t!==e.dataset.tab;document.querySelectorAll("[data-tab]").forEach(t=>t.classList.toggle("active",t===e)),e.dataset.tab==="rules"&&je(),e.dataset.tab==="print"&&(a("print-preview").innerHTML=Q(l).slice(0,8).map((t,n)=>Z(l,t,n)).join("")+l.boards.map(le).join(""))});try{let e=JSON.parse(localStorage.getItem(oe)??"null");e?.project&&N(e.project)!==N(l)&&(l=v(e.project),F=e.baseRevision,L=X(l),M("Restored the last browser draft."))}catch{}D();S();m(async()=>{await he(l),["http:","https:"].includes(location.protocol)&&(await $e(),Ee=setInterval($e,5e3));let e=JSON.parse(localStorage.getItem(oe+":replay")??"null");e?.replay&&e.replay.revision===ve&&(h=await T("restore",e.replay),W(!0),M("Restored and verified the previous playtest."))})();})();
</script></body></html>
diff --git a/store/agents/game-master/template/game/project.json b/store/agents/game-master/template/game/project.json
new file mode 100644
index 000000000..7efe5a95e
--- /dev/null
+++ b/store/agents/game-master/template/game/project.json
@@ -0,0 +1,160 @@
+{
+ "spec": 1,
+ "id": "pocket-conservatory",
+ "title": "Pocket Conservatory",
+ "subtitle": "Grow a garden. Pass a possibility. A tiny drafting game for two.",
+ "players": 2,
+ "settings": [
+ {
+ "id": "rounds",
+ "label": "Cards in each starting hand",
+ "value": 6,
+ "min": 3,
+ "max": 8,
+ "step": 1
+ },
+ {
+ "id": "pair_bonus",
+ "label": "Flower + water pair bonus",
+ "value": 4,
+ "min": 0,
+ "max": 10,
+ "step": 1
+ },
+ {
+ "id": "variety_bonus",
+ "label": "Points per different plant group",
+ "value": 1,
+ "min": 0,
+ "max": 5,
+ "step": 1
+ }
+ ],
+ "components": [
+ {
+ "id": "fern",
+ "name": "Silver fern",
+ "body": "A quiet beginning.",
+ "kind": "card",
+ "widthMm": 63,
+ "heightMm": 88,
+ "quantity": 4,
+ "color": "#244c40",
+ "ink": "#fff8e9",
+ "symbol": "✦",
+ "values": {
+ "group": "leaf",
+ "points": 2
+ },
+ "locked": false
+ },
+ {
+ "id": "poppy",
+ "name": "Coral poppy",
+ "body": "Pairs with water for a flourishing garden.",
+ "kind": "card",
+ "widthMm": 63,
+ "heightMm": 88,
+ "quantity": 4,
+ "color": "#a44736",
+ "ink": "#fff8e9",
+ "symbol": "✿",
+ "values": {
+ "group": "flower",
+ "points": 2
+ },
+ "locked": false
+ },
+ {
+ "id": "pond",
+ "name": "Rain pool",
+ "body": "Each flower + water pair earns the pair bonus.",
+ "kind": "card",
+ "widthMm": 63,
+ "heightMm": 88,
+ "quantity": 4,
+ "color": "#365e7a",
+ "ink": "#fff8e9",
+ "symbol": "≈",
+ "values": {
+ "group": "water",
+ "points": 1
+ },
+ "locked": false
+ },
+ {
+ "id": "herb",
+ "name": "Wild thyme",
+ "body": "A little color and a different kind of leaf.",
+ "kind": "card",
+ "widthMm": 63,
+ "heightMm": 88,
+ "quantity": 4,
+ "color": "#62642f",
+ "ink": "#fff8e9",
+ "symbol": "❋",
+ "values": {
+ "group": "herb",
+ "points": 3
+ },
+ "locked": false
+ },
+ {
+ "id": "aster",
+ "name": "Evening aster",
+ "body": "A second flower for a generous garden.",
+ "kind": "card",
+ "widthMm": 63,
+ "heightMm": 88,
+ "quantity": 4,
+ "color": "#795c79",
+ "ink": "#fff8e9",
+ "symbol": "✳",
+ "values": {
+ "group": "flower",
+ "points": 3
+ },
+ "locked": false
+ },
+ {
+ "id": "moss",
+ "name": "Velvet moss",
+ "body": "Make room for small beginnings.",
+ "kind": "card",
+ "widthMm": 63,
+ "heightMm": 88,
+ "quantity": 4,
+ "color": "#3e6d53",
+ "ink": "#fff8e9",
+ "symbol": "⋆",
+ "values": {
+ "group": "moss",
+ "points": 1
+ },
+ "locked": false
+ }
+ ],
+ "boards": [],
+ "rulebook": [
+ {
+ "heading": "A garden for two",
+ "body": "Pocket Conservatory is a two-player drafting game. Build a little garden by choosing one card at a time from a hand that you will pass to the other gardener. You need the printed deck and a way to note scores."
+ },
+ {
+ "heading": "Set up",
+ "body": "Shuffle all printed cards. Deal each gardener the number of cards shown in the rule settings. Put the rest aside face down without looking. Each gardener keeps their hand private. Gardener 1 chooses first each round."
+ },
+ {
+ "heading": "Plant and pass",
+ "body": "Each round, Gardener 1 chooses one card and places it face up in their garden, then Gardener 2 does the same. Neither gardener takes another card until both have planted. Swap the remaining hands. Begin the next round. When both hands are empty, the game ends."
+ },
+ {
+ "heading": "Score your garden",
+ "body": "Add each planted card’s printed points. Earn the flower + water pair bonus for every pair you can make; each card counts in one pair. Add the variety bonus once per distinct group in your garden. The gardener with the highest score wins; tied scores share the win. The settings and component values printed with this rulebook define this edition."
+ },
+ {
+ "heading": "At the same screen",
+ "body": "The hand curtain lets gardeners pass the computer between turns. It conceals the hand from casual view; the offline file and replay are not secret from someone who can inspect the browser or source. Undo is a playtesting tool: it can reveal previous hands. For physical play, reveal only each planted card."
+ }
+ ]
+}
diff --git a/store/agents/game-master/template/game/rules.mjs b/store/agents/game-master/template/game/rules.mjs
new file mode 100644
index 000000000..d25b7b303
--- /dev/null
+++ b/store/agents/game-master/template/game/rules.mjs
@@ -0,0 +1,11 @@
+// Pocket Conservatory: original two-player simultaneous-hand drafting rules.
+const setting=(p,id)=>p.settings.find(s=>s.id===id).value;
+const component=(p,id)=>p.components.find(c=>c.id===id);
+export function score(cards,p){let points=cards.reduce((n,id)=>n+component(p,id).values.points,0);const counts={};for(const id of cards){const group=component(p,id).values.group;counts[group]=(counts[group]??0)+1;}points+=Math.min(counts.water??0,counts.flower??0)*setting(p,'pair_bonus');points+=Object.keys(counts).length*setting(p,'variety_bonus');return points;}
+export function initial(p,ctx){const rounds=setting(p,'rounds'),deck=p.components.flatMap(c=>Array(c.quantity).fill(c.id));if(deck.length<rounds*2)throw new Error('Print enough cards to deal both hands.');const shuffled=ctx.shuffle(deck,'deal');return{player:0,round:1,done:false,hands:[shuffled.slice(0,rounds),shuffled.slice(rounds,rounds*2)],tableaux:[[],[]],picked:[false,false]};}
+export function legal(s,p){return s.done?[]:s.hands[s.player].map((id,i)=>({id:'draft-'+i,label:'Plant '+component(p,id).name,index:i}));}
+export function apply(s,a,p){const n=JSON.parse(JSON.stringify(s)),who=n.player,[card]=n.hands[who].splice(a.index,1);n.tableaux[who].push(card);n.picked[who]=true;if(n.picked.every(Boolean)){if(!n.hands[0].length)n.done=true;else{n.hands.reverse();n.round++;n.picked=[false,false];}n.player=0;}else n.player=1;return n;}
+export function observe(s,player,p){return{title:'Round '+s.round+' · Gardener '+(player+1),message:s.done?'Compare your planted gardens.':'Choose one plant, then pass the remaining hand after both gardeners choose.',private:!s.done,scores:s.tableaux.map((cards,i)=>({label:'Gardener '+(i+1),value:score(cards,p)})),zones:[...(!s.done?[{id:'hand',label:'Your hand · choose a plant below',items:s.hands[player].map((id,i)=>({key:'hand-'+i,component:id,action:'draft-'+i}))}]:[]),...s.tableaux.map((cards,i)=>({id:'garden-'+i,label:'Gardener '+(i+1)+' · planted',items:cards.map((id,j)=>({key:i+'-'+j,component:id}))}))]};}
+export function outcome(s,p){if(!s.done)return null;const scores=s.tableaux.map(c=>score(c,p)),high=Math.max(...scores),winners=scores.flatMap((n,i)=>n===high?[i]:[]);return{title:winners.length===2?'Both gardens flourish':'Gardener '+(winners[0]+1)+' wins',winners,scores};}
+export function validate(s,p){if(p.players!==2||!Number.isInteger(setting(p,'rounds')))return 'This game needs two players and a whole number of cards per hand.';if(!Array.isArray(s.hands)||s.hands.length!==2||!Array.isArray(s.tableaux)||s.tableaux.length!==2)return'Keep both hands and gardens.';if(s.hands.flat().length+s.tableaux.flat().length!==setting(p,'rounds')*2)return'Card conservation failed.';const counts={};for(const id of [...s.hands.flat(),...s.tableaux.flat()]){const c=component(p,id);if(!c)return'Unknown card.';counts[id]=(counts[id]??0)+1;if(counts[id]>c.quantity)return'Too many copies of a card.';}return true;}
+export function bot(view,actions){return actions[0].id;}
diff --git a/store/agents/game-master/template/studio/app.js b/store/agents/game-master/template/studio/app.js
new file mode 100644
index 000000000..2808fd02f
--- /dev/null
+++ b/store/agents/game-master/template/studio/app.js
@@ -0,0 +1,71 @@
+import {clone,validateProject,history,digest,canonical} from './project.mjs';
+import {esc,slug,componentSVG,boardSVG,sheets,sheetSVG,rulebookHTML,printHTML,kitFiles} from './formats.mjs';
+import {zipFiles} from './archive.mjs';
+const $=id=>document.getElementById(id),boot=JSON.parse($('relay-data').textContent),bootHTML='<!doctype html>\n'+document.documentElement.outerHTML;
+let project=validateProject(boot.project),baseRevision=boot.project.revision,sourceConnected=false,engineReady=false,sourcePending=null,edits=history(project),selected=project.components[0].id,runningProject=clone(project),runRevision='',view=null,report=null,worker=null,sequence=0,pending=new Map(),busy=false,noticeTimer,editorApply,sourceTimer;
+const storageKey='relay-draft:'+location.href;
+const download=(name,body,type='application/octet-stream')=>{const u=URL.createObjectURL(body instanceof Blob?body:new Blob([body],{type})),a=document.createElement('a');a.href=u;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(u),10000);};
+function notify(message,error=false){clearTimeout(noticeTimer);$('notice').textContent=message;$('notice').hidden=false;$('notice').classList.toggle('error',error);noticeTimer=setTimeout(()=>$('notice').hidden=true,error?14000:6500);}
+const guard=fn=>async(...args)=>{try{return await fn(...args);}catch(e){notify(e.message,true);}};
+function remember(){try{localStorage.setItem(storageKey,JSON.stringify({baseRevision,project}));}catch{notify('Browser draft storage is full. Download the project to keep this edition.',true);}}
+function makeWorker(){if(worker)worker.terminate();for(const p of pending.values()){clearTimeout(p.timer);p.reject(new Error('The previous rules worker stopped.'));}pending.clear();const u=URL.createObjectURL(new Blob([boot.worker],{type:'text/javascript'}));worker=new Worker(u);URL.revokeObjectURL(u);worker.onmessage=({data})=>{const p=pending.get(data.id);if(!p)return;pending.delete(data.id);clearTimeout(p.timer);data.error?p.reject(new Error(data.error)):p.resolve(data.result);};worker.onerror=e=>{for(const p of pending.values()){clearTimeout(p.timer);p.reject(new Error(e.message||'Rules worker failed.'));}pending.clear();};}
+function call(type,payload={}){return new Promise((resolve,reject)=>{const id=++sequence;const timer=setTimeout(()=>{worker.terminate();engineReady=false;renderEdition();for(const p of pending.values()){clearTimeout(p.timer);p.reject(new Error('Rules exceeded the time limit. Your source is kept; revise it and apply again.'));}pending.clear();},type==='simulate'?30000:4000);pending.set(id,{resolve,reject,timer});worker.postMessage({id,type,payload});});}
+function portable(p){const payload=JSON.stringify({project:p,worker:boot.worker}).replace(/</g,'\\u003c');return bootHTML.replace(/(<script id="relay-data" type="application\/json">)[\s\S]*?(<\/script>)/,(_,a,b)=>a+payload+b);}
+async function start(p,{seed=$('seed').value,curtain=true}={}){engineReady=false;renderEdition();makeWorker();const next=await call('load',{project:p,seed});engineReady=true;runningProject=clone(p);runRevision=next.revision;view=next;report=null;$('simulation-report').replaceChildren();renderPlay(curtain);renderEdition();}
+async function preservePlaytest(){if(!view)return;let replay=null;try{replay=await call('replay');}catch{}download(slug(runningProject.title)+'-previous-playtest.zip',zipFiles({'game.html':portable(runningProject),'project.relay.json':JSON.stringify(runningProject,null,2),'replay.json':JSON.stringify(replay,null,2)}));}
+function edit(mutator){const next=clone(project);mutator(next);project=validateProject(next);edits.push(project);remember();renderEditor();renderEdition();}
+function renderEdition(){const changed=canonical(project)!==canonical(runningProject);$('edition-notice').hidden=!changed&&engineReady;$('restart').disabled=!engineReady;$('edition-notice').querySelector('span').textContent=engineReady?'The table is playing the previous edition.':'Apply a valid edition to start the table.';$('game-title').textContent=project.title;$('game-subtitle').textContent=project.subtitle;$('source-state').textContent=(sourceConnected?'Workspace source':'Portable game')+(sourcePending?' · source changed':changed?' · draft edition':' · playing current edition');$('undo-edit').disabled=!edits.canUndo;$('redo-edit').disabled=!edits.canRedo;$('save-source').disabled=!sourceConnected;document.title=project.title+' — Relay';}
+function renderEditor(){
+ $('library-title').textContent=project.title;
+ $('component-list').innerHTML=project.components.map(c=>`<button class="component-row ${c.id===selected?'active':''}" data-component="${esc(c.id)}"><span class="swatch" style="background:${c.color};color:${c.ink}">${esc(c.symbol)}</span><span>${esc(c.name)}${c.locked?' · locked':''}<small>${c.quantity} ${esc(c.kind)}${c.quantity===1?'':'s'} · ${c.widthMm} × ${c.heightMm} mm</small></span></button>`).join('');
+ $('component-list').querySelectorAll('button').forEach(b=>b.onclick=()=>{selected=b.dataset.component;renderEditor();});
+ $('settings').innerHTML=project.settings.map(s=>`<label>${esc(s.label)}<input data-setting="${s.id}" type="number" min="${s.min}" max="${s.max}" step="${s.step}" value="${s.value}"></label>`).join('');
+ $('settings').querySelectorAll('input').forEach(el=>el.onchange=guard(()=>edit(p=>p.settings.find(s=>s.id===el.dataset.setting).value=Number(el.value))));
+ const c=project.components.find(c=>c.id===selected)??project.components[0];selected=c.id;
+ try{$('component-preview').innerHTML=componentSVG(c);}catch(e){$('component-preview').textContent=e.message;}
+ const disabled=c.locked?'disabled':'';
+ $('component-form').innerHTML=`<label>Name<input name="name" maxlength="80" value="${esc(c.name)}" ${disabled}></label><label>Card text<textarea name="body" rows="4" maxlength="700" ${disabled}>${esc(c.body)}</textarea></label><div class="row"><label>Color<input name="color" type="color" value="${c.color}" ${disabled}></label><label>Ink<input name="ink" type="color" value="${c.ink}" ${disabled}></label></div><label>Symbol<input name="symbol" maxlength="8" value="${esc(c.symbol)}" ${disabled}></label><div class="row"><label>Width · mm<input name="widthMm" type="number" min="12" max="190" step=".5" value="${c.widthMm}" ${disabled}></label><label>Height · mm<input name="heightMm" type="number" min="12" max="273" step=".5" value="${c.heightMm}" ${disabled}></label></div><label>Copies<input name="quantity" type="number" min="1" max="100" value="${c.quantity}" ${disabled}></label><div class="row"><button type="button" id="import-face" ${disabled}>Import face artwork</button>${c.face?`<button type="button" id="reset-face" ${disabled}>Use generated face</button>`:''}</div>${c.face?'<p class="muted" style="font-size:11px">Custom artwork owns the printed face. Update its text when you change rules values.</p>':''}<h3>Rules values</h3>${Object.entries(c.values).map(([k,v])=>`<label>${esc(k)}<input data-value="${esc(k)}" data-type="${typeof v}" value="${esc(v)}" ${disabled}></label>`).join('')}<div class="row"><button type="button" id="lock-component">${c.locked?'Unlock':'Lock'} component</button><button type="button" id="duplicate-component">Duplicate</button></div><p class="muted" style="font-size:10px;margin-top:14px">Rules read component ids and values. Editing this draft keeps the running playtest intact until you apply it.</p>`;
+ $('component-form').onsubmit=e=>e.preventDefault();
+ $('component-form').querySelectorAll('input,textarea').forEach(el=>el.onchange=guard(()=>edit(p=>{const target=p.components.find(x=>x.id===selected);if(target.locked)throw new Error('Unlock this approved component before editing.');if(el.dataset.value){const type=el.dataset.type;if(type==='boolean'&&!['true','false'].includes(el.value))throw new Error('Enter true or false.');target.values[el.dataset.value]=type==='number'?Number(el.value):type==='boolean'?el.value==='true':el.value;}else target[el.name]=['widthMm','heightMm','quantity'].includes(el.name)?Number(el.value):el.value;})));
+ $('import-face').onclick=()=>$('face-file').click();if($('reset-face'))$('reset-face').onclick=guard(()=>edit(p=>delete p.components.find(c=>c.id===selected).face));
+ $('lock-component').onclick=guard(()=>edit(p=>p.components.find(x=>x.id===selected).locked=!c.locked));
+ $('duplicate-component').onclick=guard(()=>{const copy=clone(c);copy.id='piece-'+Date.now().toString(36);copy.name=c.name+' copy';copy.locked=false;selected=copy.id;edit(p=>p.components.push(copy));});
+}
+function renderPlay(curtain=false){if(!view)return;
+ const p=runningProject;$('scores').innerHTML=view.view.scores.map(s=>`<div>${esc(s.label)}<strong>${esc(s.value)}</strong></div>`).join('');$('turn-title').textContent=view.outcome?.title??view.view.title;$('turn-message').textContent=view.view.message??'';$('turn-count').textContent='Turn '+view.step;$('undo-turn').disabled=!view.step;
+ const piece=item=>{const c=p.components.find(c=>c.id===item.component);item={...item,action:view.actions.some(a=>a.id===item.action)?item.action:null};if(!c)throw new Error('Observation refers to unknown component '+item.component);return`<div class="table-piece"><button class="game-piece" ${item.action?`data-move="${esc(item.action)}"`:''} aria-label="${esc(item.faceDown?'Face-down piece':c.name)}" ${item.action?'':'disabled'}><div style="transform:rotate(${Number(item.rotation)||0}deg)">${componentSVG(c,{back:!!item.faceDown})}</div>${item.badge!==undefined?`<span class="badge">${esc(item.badge)}</span>`:''}</button>${c.kind==='card'&&!item.faceDown?`<span class="piece-label">${esc(c.name)}<small>${Object.entries(c.values).map(([k,v])=>esc(k)+': '+esc(v)).join(' · ')}</small></span><details><summary>Read card</summary><p>${esc(c.body)}</p></details>`:''}</div>`;};
+ $('zones').innerHTML=view.view.zones.map(z=>{let content;if(z.board){const b=p.boards.find(b=>b.id===z.board);if(!b)throw new Error('Unknown board '+z.board);content=`<div class="board" style="grid-template-columns:repeat(${b.cols},1fr)">${b.cells.map((cell,i)=>`<div class="board-cell" style="background:${cell.color}"><small>${esc(cell.label)}</small>${z.items.filter(item=>item.cell===i).map(piece).join('')}</div>`).join('')}</div>`;}else content=`<div class="cards">${z.items.map(piece).join('')||'<small>No components here yet.</small>'}</div>`;return`<section class="zone"><h3>${esc(z.label)}</h3>${content}</section>`;}).join('');
+ $('actions').innerHTML=view.actions.map(a=>`<button data-move="${esc(a.id)}">${esc(a.label)}</button>`).join('');
+ document.querySelectorAll('[data-move]').forEach(b=>b.onclick=guard(()=>move(b.dataset.move)));
+ const privateTurn=!view.outcome&&!!view.view.private;$('curtain').hidden=!(curtain&&privateTurn);for(const id of ['scores','zones','actions'])$(id).inert=!$('curtain').hidden;$('curtain-title').textContent='Player '+(view.player+1)+', your turn.';
+}
+async function move(id){if(busy)return;busy=true;try{const before=view.player;view=await call('step',{id});renderPlay(view.player!==before);rememberReplay();}finally{busy=false;}}
+async function rememberReplay(){try{const replay=await call('replay');localStorage.setItem(storageKey+':replay',JSON.stringify({project:runningProject,replay}));}catch{}}
+function renderRules(){$('rulebook-editor').innerHTML=project.rulebook.map((s,i)=>`<section class="rule-section"><label>Section heading<input data-heading="${i}" maxlength="160" value="${esc(s.heading)}"></label><label>Instructions<textarea data-body="${i}" rows="5" maxlength="10000">${esc(s.body)}</textarea></label></section>`).join('');$('rulebook-editor').querySelectorAll('input,textarea').forEach(el=>el.onchange=guard(()=>edit(p=>{const i=Number(el.dataset.heading??el.dataset.body);p.rulebook[i][el.dataset.heading===undefined?'body':'heading']=el.value;})));}
+function openPrint(html){const url=URL.createObjectURL(new Blob([html],{type:'text/html'}));window.open(url,'_blank','noopener');setTimeout(()=>URL.revokeObjectURL(url),60000);}
+function dialog(title,content,apply){$('editor-title').textContent=title;$('editor-content').innerHTML=content;editorApply=apply;$('editor-dialog').showModal();}
+$('editor-apply').onclick=guard(()=>{editorApply();$('editor-dialog').close();});
+$('edit-rules').onclick=()=>dialog('Author this game’s rules',`<p>The complete JavaScript module defines mechanics. Export initial, legal, apply, observe, outcome and validate; optional bot supplies a named policy. Use only local code. An edited module becomes a new edition when you apply it to the table.</p><textarea id="rules-code" class="code" spellcheck="false">${esc(project.rules)}</textarea>`,()=>edit(p=>p.rules=$('rules-code').value));
+$('edit-metadata').onclick=()=>dialog('Game details',`<label>Title<input id="game-name-edit" value="${esc(project.title)}" maxlength="160"></label><label>Subtitle<textarea id="game-subtitle-edit" maxlength="400">${esc(project.subtitle)}</textarea></label><label>Players<input id="game-players-edit" type="number" min="1" max="6" value="${project.players}"></label><p>Player count must match the authored rules.</p>`,()=>edit(p=>{p.title=$('game-name-edit').value;p.subtitle=$('game-subtitle-edit').value;p.players=Number($('game-players-edit').value);}));
+$('add-component').onclick=()=>dialog('Add a component',`<label>Name<input id="new-name" value="New card" maxlength="80"></label><label>Kind<select id="new-kind"><option value="card">Card</option><option value="tile">Tile</option><option value="token">Token</option></select></label><p>Adding a design does not invent its behavior. Reference its id and values in the rules module.</p>`,()=>{const id='piece-'+Date.now().toString(36),kind=$('new-kind').value;selected=id;edit(p=>p.components.push({id,name:$('new-name').value,body:'',kind,widthMm:kind==='card'?63:35,heightMm:kind==='card'?88:35,quantity:1,color:'#365948',ink:'#fff8e9',symbol:'✦',values:{},locked:false}));});
+$('undo-edit').onclick=()=>{project=edits.undo();remember();renderEditor();renderEdition();};$('redo-edit').onclick=()=>{project=edits.redo();remember();renderEditor();renderEdition();};
+$('apply-edition').onclick=guard(async()=>{await preservePlaytest();await start(project);notify('Previous game and replay downloaded. Playing the edited edition.');});
+$('restart').onclick=guard(async()=>{await preservePlaytest();view=await call('restart',{seed:$('seed').value});renderPlay(true);notify('A fresh playtest is ready. The previous game was kept.');});
+$('undo-turn').onclick=guard(async()=>{view=await call('undo');renderPlay(true);rememberReplay();});$('reveal').onclick=()=>{$('curtain').hidden=true;for(const id of ['scores','zones','actions'])$(id).inert=false;};
+$('save-replay').onclick=guard(async()=>download(slug(runningProject.title)+'-replay.json',JSON.stringify(await call('replay'),null,2),'application/json'));
+$('open-replay').onclick=()=>$('replay-file').click();$('replay-file').onchange=guard(async e=>{const f=e.target.files[0];if(!f)return;if(f.size>5000000)throw new Error('Choose a replay below 5 MB.');view=await call('restore',JSON.parse(await f.text()));$('seed').value=view.seed;renderPlay(true);notify('Replay verified against its rules and actions.');e.target.value='';});
+$('simulate').onclick=guard(async()=>{if(busy)return;busy=true;$('simulate').disabled=true;$('simulate').textContent='Testing…';try{report=await call('simulate',{count:Number($('simulation-count').value),policy:$('policy').value,maxTurns:400});$('simulation-report').innerHTML=`<div class="simulation-stats"><span><strong>${report.completed}/${report.count}</strong>completed</span><span><strong>${report.errors}</strong>errors</span><span><strong>${report.capped}</strong>turn caps</span><span><strong>${report.meanTurns.toFixed(1)}</strong>mean turns</span>${report.wins.map((n,i)=>`<span><strong>${n}</strong>Player ${i+1} wins</span>`).join('')}</div><p>${esc(report.scope)}</p><button id="save-simulation">Download seeds, outcomes &amp; replays</button>`;$('save-simulation').onclick=()=>download(slug(runningProject.title)+'-simulation.json',JSON.stringify(report,null,2),'application/json');}finally{busy=false;$('simulate').disabled=false;$('simulate').textContent='Run playtest';}});
+async function exportKit(){validateProject(project);sheets(project);const same=canonical(project)===canonical(runningProject);if(!same||!engineReady)throw new Error('Apply this edition to the table before exporting its complete kit. Your draft project can always be downloaded.');const replay=await call('replay');download(slug(project.title)+'-print-and-play.zip',zipFiles(kitFiles(project,portable(project),replay,report)));notify('Complete playable and printable game exported.');}
+$('export-kit').onclick=guard(exportKit);$('export-kit-secondary').onclick=guard(exportKit);
+$('export-html').onclick=guard(()=>download(slug(project.title)+'.html',portable(validateProject(project)),'text/html'));$('export-project').onclick=()=>download(slug(project.title)+'.relay.json',JSON.stringify(project,null,2),'application/json');
+$('print-components').onclick=guard(()=>openPrint(printHTML(project)));$('print-rulebook').onclick=$('print-rules').onclick=guard(()=>openPrint(rulebookHTML(project)));
+$('add-section').onclick=guard(()=>{edit(p=>p.rulebook.push({heading:'New section',body:'Describe the next part of the game.'}));renderRules();});
+$('face-file').onchange=guard(async e=>{const f=e.target.files[0];if(!f)return;const types=['image/png','image/jpeg','image/webp','image/svg+xml'];if(!types.includes(f.type)||f.size>500000)throw new Error('Use a PNG, JPEG, WebP or SVG face below 500 KB.');const bytes=new Uint8Array(await f.arrayBuffer());let binary='';for(const byte of bytes)binary+=String.fromCharCode(byte);const face='data:'+f.type+';base64,'+btoa(binary),img=new Image();img.src=face;await img.decode();edit(p=>{const c=p.components.find(c=>c.id===selected);if(c.locked)throw new Error('Unlock the component before replacing its artwork.');c.face=face;});e.target.value='';});
+$('open-project').onclick=()=>$('project-file').click();$('project-file').onchange=guard(async e=>{const f=e.target.files[0];if(!f)return;if(f.size>3000000)throw new Error('Choose a game project below 3 MB.');const next=validateProject(JSON.parse(await f.text()));await preservePlaytest();project=next;edits=history(project);selected=project.components[0].id;remember();renderEditor();renderEdition();await start(project);e.target.value='';notify('Game source opened. Save source to replace the workspace edition.');});
+async function saveSource(){const response=await fetch('/api/project',{method:'PUT',headers:{'content-type':'application/json','if-match':baseRevision},body:JSON.stringify(project)}),body=await response.json();if(response.status===409){sourcePending=body.project;$('source-notice').hidden=false;throw new Error('The agent changed the source. Keep both editions before choosing.');}if(!response.ok)throw new Error(body.error);baseRevision=body.project.revision;sourcePending=null;$('source-notice').hidden=true;remember();renderEdition();notify('Source saved with the previous edition in workspace history.');}
+$('save-source').onclick=guard(saveSource);$('keep-draft').onclick=()=>download(slug(project.title)+'-draft.relay.json',JSON.stringify(project,null,2),'application/json');
+$('load-source').onclick=guard(async()=>{if(!sourcePending)return;download(slug(project.title)+'-before-source.relay.json',JSON.stringify(project,null,2),'application/json');project=validateProject(sourcePending);baseRevision=sourcePending.revision;sourcePending=null;$('source-notice').hidden=true;edits=history(project);remember();renderEditor();renderEdition();notify('Both source editions kept. Apply the new edition when ready to restart the playtest.');});
+async function pollSource(){try{const response=await fetch('/api/project',{cache:'no-store'});if(!response.ok)return;const body=await response.json();sourceConnected=true;if(body.project.revision!==baseRevision){sourcePending=body.project;$('source-notice').hidden=false;}renderEdition();}catch{}}
+for(const b of document.querySelectorAll('[data-tab]'))b.onclick=guard(()=>{for(const id of ['workbench','rules','print'])$(id).hidden=id!==b.dataset.tab;document.querySelectorAll('[data-tab]').forEach(x=>x.classList.toggle('active',x===b));if(b.dataset.tab==='rules')renderRules();if(b.dataset.tab==='print')$('print-preview').innerHTML=sheets(project).slice(0,8).map((items,i)=>sheetSVG(project,items,i)).join('')+project.boards.map(boardSVG).join('');});
+try{const saved=JSON.parse(localStorage.getItem(storageKey)??'null');if(saved?.project&&canonical(saved.project)!==canonical(project)){project=validateProject(saved.project);baseRevision=saved.baseRevision;edits=history(project);notify('Restored the last browser draft.');}}catch{}
+renderEditor();renderEdition();guard(async()=>{await start(project);if(['http:','https:'].includes(location.protocol)){await pollSource();sourceTimer=setInterval(pollSource,5000);}const saved=JSON.parse(localStorage.getItem(storageKey+':replay')??'null');if(saved?.replay&&saved.replay.revision===runRevision){view=await call('restore',saved.replay);renderPlay(true);notify('Restored and verified the previous playtest.');}})();
diff --git a/store/agents/game-master/template/studio/archive.mjs b/store/agents/game-master/template/studio/archive.mjs
new file mode 100644
index 000000000..0a71dae99
--- /dev/null
+++ b/store/agents/game-master/template/studio/archive.mjs
@@ -0,0 +1,21 @@
+// ZIP STORE: portable editable delivery without a runtime dependency or a cloud service.
+export function zipFiles(files) {
+ if (!Array.isArray(files)) files = Object.entries(files);
+ const enc = new TextEncoder(), chunks = [], central = []; let offset = 0;
+ for (const [name, body] of files) {
+ const path = enc.encode(name), bytes = typeof body === 'string' ? enc.encode(body) : new Uint8Array(body);
+ let crc = 0xffffffff;
+ for (const b of bytes) { crc ^= b; for (let i = 0; i < 8; i++) crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1)); }
+ crc = (crc ^ 0xffffffff) >>> 0;
+ const header = new Uint8Array(30 + path.length), v = new DataView(header.buffer);
+ v.setUint32(0, 0x04034b50, true); v.setUint16(4, 20, true); v.setUint16(6, 0x800, true); v.setUint16(12, 33, true);
+ v.setUint32(14, crc, true); v.setUint32(18, bytes.length, true); v.setUint32(22, bytes.length, true); v.setUint16(26, path.length, true); header.set(path, 30);
+ const row = new Uint8Array(46 + path.length), c = new DataView(row.buffer);
+ c.setUint32(0, 0x02014b50, true); c.setUint16(4, 20, true); c.setUint16(6, 20, true); c.setUint16(8, 0x800, true); c.setUint16(14, 33, true);
+ c.setUint32(16, crc, true); c.setUint32(20, bytes.length, true); c.setUint32(24, bytes.length, true); c.setUint16(28, path.length, true); c.setUint32(42, offset, true); row.set(path, 46);
+ chunks.push(header, bytes); central.push(row); offset += header.length + bytes.length;
+ }
+ const length = central.reduce((n, row) => n + row.length, 0), end = new Uint8Array(22), e = new DataView(end.buffer);
+ e.setUint32(0, 0x06054b50, true); e.setUint16(8, files.length, true); e.setUint16(10, files.length, true); e.setUint32(12, length, true); e.setUint32(16, offset, true);
+ return new Blob([...chunks, ...central, end], { type: 'application/zip' });
+}
diff --git a/store/agents/game-master/template/studio/engine.mjs b/store/agents/game-master/template/studio/engine.mjs
new file mode 100644
index 000000000..8a0a1d7b6
--- /dev/null
+++ b/store/agents/game-master/template/studio/engine.mjs
@@ -0,0 +1,29 @@
+import {assert,clone,canonical,projectData} from './project.mjs';
+function freeze(o){if(o&&typeof o==='object'){Object.values(o).forEach(freeze);Object.freeze(o);}return o;}
+function finiteJSON(x,label){const seen=new Set();function visit(v){if(typeof v==='number')assert(Number.isFinite(v),label+' has a non-finite number.');else if(v&&typeof v==='object'){assert(!seen.has(v),label+' contains a cycle.');seen.add(v);assert(Array.isArray(v)||Object.getPrototypeOf(v)===Object.prototype,label+' must be plain JSON.');Object.values(v).forEach(visit);seen.delete(v);}else assert(v===null||['string','boolean'].includes(typeof v),label+' must be plain JSON.');}visit(x);assert(JSON.stringify(x).length<1000000,label+' exceeds 1 MB.');return x;}
+export function rng(seed){let n=2166136261;for(const c of String(seed)){n^=c.codePointAt(0);n=Math.imul(n,16777619);}return()=>{n+=0x6D2B79F5;let t=n;t=Math.imul(t^t>>>15,t|1);t^=t+Math.imul(t^t>>>7,t|61);return((t^t>>>14)>>>0)/4294967296;};}
+export function context(seed,step){return Object.freeze({random:stream=>rng(seed+'|'+step+'|'+String(stream)),shuffle:(items,stream)=>{const a=clone(items),r=rng(seed+'|'+step+'|'+stream);for(let i=a.length-1;i>0;i--){const j=Math.floor(r()*(i+1));[a[i],a[j]]=[a[j],a[i]];}return a;}});}
+export class Game {
+ constructor(project,rules,seed='first-game'){
+ for(const name of ['initial','legal','apply','observe','outcome','validate'])assert(typeof rules[name]==='function','Rules must export '+name+'().');
+ assert(typeof seed==='string'&&seed.length<=128,'Use a seed of at most 128 characters.');
+ this.project=freeze(projectData(project));this.rules=rules;this.seed=seed;this.actions=[];this.states=[];
+ const s=rules.initial(this.project,context(seed,0));this.check(s);this.states.push(clone(s));this.verifyTurn();
+ }
+ get state(){return freeze(clone(this.states.at(-1)));}
+ check(s){finiteJSON(s,'Game state');assert(Number.isInteger(s.player)&&s.player>=0&&s.player<this.project.players,'State must identify the current player.');const valid=this.rules.validate(freeze(clone(s)),this.project);assert(valid===true,typeof valid==='string'?valid:'Rule validation failed.');}
+ outcome(){const end=this.rules.outcome(this.state,this.project);assert(end===null||(end&&typeof end==='object'&&typeof end.title==='string'&&Array.isArray(end.winners)&&end.winners.every(n=>Number.isInteger(n)&&n>=0&&n<this.project.players)),'Outcome must be null or {title,winners,...}.');return end===null?null:finiteJSON(end,'Outcome');}
+ legal(){const a=this.rules.legal(this.state,this.project);assert(Array.isArray(a)&&a.length<=500,'Rules must offer at most 500 legal actions.');finiteJSON(a,'Legal actions');const ids=new Set();for(const x of a){assert(x&&typeof x.id==='string'&&x.id.length<=180&&!ids.has(x.id)&&typeof x.label==='string'&&x.label.length<=200,'Legal actions need unique ids and readable labels.');ids.add(x.id);}return clone(a);}
+ verifyTurn(){const end=this.outcome(),a=this.legal();assert(end!==null||a.length>0,'Dead end: the game has no legal action and no outcome.');assert(end===null||a.length===0,'Finished games must not offer actions.');return{end,a};}
+ view(){const {end,a}=this.verifyTurn(),view=this.rules.observe(this.state,this.state.player,this.project);finiteJSON(view,'Observation');assert(view&&typeof view.title==='string'&&Array.isArray(view.zones)&&Array.isArray(view.scores),'Observation needs title, zones and scores.');return{view,actions:a,outcome:end,player:this.state.player,step:this.actions.length,seed:this.seed};}
+ step(id){assert(this.actions.length<2000,'This playtest reached the 2,000-turn limit. Save its replay and revise the rules.');const a=this.legal().find(x=>x.id===id);assert(a&&!this.outcome(),'That action is not legal now.');const previous=this.state,next=this.rules.apply(previous,freeze(clone(a)),this.project,context(this.seed,this.actions.length+1));this.check(next);assert(canonical(previous)!==canonical(next),'An action must change the game state.');this.states.push(clone(next));this.actions.push(id);try{this.verifyTurn();}catch(e){this.states.pop();this.actions.pop();throw e;}return this.view();}
+ undo(){if(this.actions.length){this.states.pop();this.actions.pop();}return this.view();}
+ replay(){return{spec:1,seed:this.seed,actions:clone(this.actions),state:canonical(this.state)};}
+ restore(replay){assert(replay?.spec===1&&Array.isArray(replay.actions)&&replay.actions.length<=2000,'Use a version 1 replay within 2,000 turns.');assert(replay.seed===this.seed,'Replay seed differs.');for(const a of replay.actions)this.step(a);assert(canonical(this.state)===replay.state,'Replay state does not match its actions and rules.');return this.view();}
+}
+export function simulate(project,rules,{count=50,start=0,policy='uniform',maxTurns=400}={}){
+ assert(Number.isInteger(count)&&count>=1&&count<=200,'Simulate 1–200 games.');assert(Number.isInteger(maxTurns)&&maxTurns>=1&&maxTurns<=2000,'Use a 1–2,000 turn cap.');assert(['uniform','authored'].includes(policy),'Select uniform or authored policy.');if(policy==='authored')assert(typeof rules.bot==='function','This rules module has no authored policy.');
+ const games=[];for(let i=0;i<count;i++){const seed='playtest-'+(start+i);try{const g=new Game(project,rules,seed),choose=rng(seed+'|policy');while(!g.outcome()&&g.actions.length<maxTurns){const v=g.view();const id=policy==='uniform'?v.actions[Math.floor(choose()*v.actions.length)].id:rules.bot(freeze(clone(v.view)),freeze(clone(v.actions)),{random:choose});g.step(id);}games.push({seed,turns:g.actions.length,outcome:g.outcome(),capped:!g.outcome(),replay:g.replay()});}catch(e){games.push({seed,error:e.message});}}
+ const wins=Array(project.players).fill(0);for(const g of games)for(const n of g.outcome?.winners??[])wins[n]++;
+ return{spec:1,policy,count,start,maxTurns,wins,completed:games.filter(g=>g.outcome).length,capped:games.filter(g=>g.capped).length,errors:games.filter(g=>g.error).length,meanTurns:games.reduce((n,g)=>n+(g.turns??0),0)/count,scope:'Outcomes under the named policy and seeds. These simulations do not establish fun, fairness or human play balance.',games};
+}
diff --git a/store/agents/game-master/template/studio/formats.mjs b/store/agents/game-master/template/studio/formats.mjs
new file mode 100644
index 000000000..81bbbeaf8
--- /dev/null
+++ b/store/agents/game-master/template/studio/formats.mjs
@@ -0,0 +1,29 @@
+import {assert,validateProject,clone} from './project.mjs';
+export const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
+export const slug=s=>s.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'').slice(0,70)||'game';
+const wrap=(s,width)=>{const lines=[];for(const paragraph of String(s).split('\n')){let row='';for(const word of paragraph.split(/\s+/)){if(!word)continue;if(word.length>width){if(row)lines.push(row);for(let i=0;i<word.length;i+=width)lines.push(word.slice(i,i+width));row='';}else if((row+' '+word).trim().length>width){lines.push(row);row=word;}else row=(row+' '+word).trim();}lines.push(row);}return lines;};
+const linesSVG=(lines,x,y,size,fill)=>lines.map((s,i)=>`<text x="${x}" y="${y+i*size*1.35}" font-size="${size}" fill="${fill}">${esc(s)}</text>`).join('');
+export function componentInner(c,{back=false}={}){
+ const w=c.widthMm,h=c.heightMm,pad=Math.min(5,w*.08),round=c.kind==='card'?3:c.kind==='token'?Math.min(w,h)/2:1;
+ if(back)return`<rect width="${w}" height="${h}" rx="${round}" fill="#203a34"/><path d="M${w*.2} ${h*.5}h${w*.6}M${w*.5} ${h*.2}v${h*.6}" stroke="#e2bd74" stroke-width="1"/><text x="${w/2}" y="${h*.84}" text-anchor="middle" font-size="${Math.min(4,w*.1)}" fill="#fff7e7">RELAY</text>`;
+ if(c.face)return`<rect width="${w}" height="${h}" fill="${c.color}"/><image width="${w}" height="${h}" preserveAspectRatio="xMidYMid meet" href="${esc(c.face)}"/>`;
+ const textW=w-pad*2,headSize=Math.min(5,w*.075),headLines=wrap(c.name,Math.floor(textW/(headSize*.57))),foot=Object.entries(c.values).map(([k,v])=>k.replace(/_/g,' ')+': '+v).join(' · ');
+ const bodySize=Math.min(3.1,w*.048),bodyLines=wrap(c.body,Math.floor(textW/(bodySize*.56))),footSize=Math.min(3,w*.05),footLines=wrap(foot,Math.floor(textW/(footSize*.56)));
+ const titleY=pad+headSize,artY=Math.max(h*.30,titleY+headLines.length*headSize*1.35+2),bodyY=artY+Math.min(h*.13,12)+bodySize+2,footY=h-pad-footLines.length*footSize*1.35+footSize;
+ assert(bodyY+Math.max(0,bodyLines.length-1)*bodySize*1.35+2<footY||c.kind!=='card','Text does not fit '+c.name+'. Shorten it or enlarge the card.');
+ let symbol=`<text x="${w/2}" y="${artY+Math.min(h*.1,9)}" text-anchor="middle" font-size="${Math.min(h*.23,22)}" fill="${c.ink}">${esc(c.symbol)}</text>`;
+ if(c.kind==='tile'&&typeof c.values.ports==='string'){
+ const cx=w/2,cy=h/2;symbol='<g stroke="'+c.ink+'" stroke-width="'+Math.min(w,h)*.14+'" stroke-linecap="round">'+[...c.values.ports].map(d=>{const v={N:[cx,0],E:[w,cy],S:[cx,h],W:[0,cy]}[d];return v?`<path d="M${cx} ${cy}L${v[0]} ${v[1]}"/>`:'';}).join('')+'</g>';
+ return`<rect width="${w}" height="${h}" rx="1" fill="${c.color}"/>${symbol}<text x="3" y="${h-3}" font-size="2.5" fill="${c.ink}">${esc(c.name)}</text>`;
+ }
+ if(c.kind==='token')return`<rect width="${w}" height="${h}" rx="${round}" fill="${c.color}"/>${symbol}<text x="${w/2}" y="${h*.85}" text-anchor="middle" font-size="${Math.min(3,w*.07)}" fill="${c.ink}">${esc(c.name)}</text>`;
+ return`<rect width="${w}" height="${h}" rx="${round}" fill="${c.color}"/><rect x="1.5" y="1.5" width="${w-3}" height="${h-3}" rx="${Math.max(0,round-1)}" fill="none" stroke="${c.ink}" stroke-opacity=".3" stroke-width=".25"/>${linesSVG(headLines,pad,titleY,headSize,c.ink)}${symbol}${linesSVG(bodyLines,pad,bodyY,bodySize,c.ink)}${linesSVG(footLines,pad,footY,footSize,c.ink)}`;
+}
+export function componentSVG(c,options={}){return`<svg xmlns="http://www.w3.org/2000/svg" width="${c.widthMm}mm" height="${c.heightMm}mm" viewBox="0 0 ${c.widthMm} ${c.heightMm}" font-family="Arial, sans-serif" role="img" aria-label="${esc(options.back?'Card back':c.name)}">${componentInner(c,options)}</svg>`;}
+function cuts(x,y,w,h){const g=1.2,l=2.2;return[[x,y],[x+w,y],[x,y+h],[x+w,y+h]].map(([cx,cy])=>`<path d="M${cx-l-g} ${cy}h${l}M${cx+g} ${cy}h${l}M${cx} ${cy-l-g}v${l}M${cx} ${cy+g}v${l}"/>`).join('');}
+export function sheets(project){validateProject(project);const pages=[];let items=[],x=10,y=14,row=0;const flush=()=>{if(items.length)pages.push(items);items=[];x=10;y=14;row=0;};for(const c of project.components)for(let n=0;n<c.quantity;n++){if(x+c.widthMm>200){x=10;y+=row+6;row=0;}if(y+c.heightMm>287){flush();}assert(y+c.heightMm<=287,'Component too tall for the print sheet.');items.push({id:c.id,copy:n+1,x,y,width:c.widthMm,height:c.heightMm});x+=c.widthMm+6;row=Math.max(row,c.heightMm);}flush();return pages;}
+export function sheetSVG(p,items,index,{back=false}={}){return`<svg xmlns="http://www.w3.org/2000/svg" width="210mm" height="297mm" viewBox="0 0 210 297" font-family="Arial, sans-serif"><rect width="210" height="297" fill="white"/><text x="10" y="7" font-size="2.6">${esc(p.title)} · ${back?'optional backs':'components'} · sheet ${index+1} · actual size</text>${items.map(i=>{const c=p.components.find(c=>c.id===i.id);const clip='clip-'+p.id+'-'+index+'-'+i.id+'-'+i.copy+'-'+back;return`<defs><clipPath id="${clip}"><rect width="${i.width}" height="${i.height}"/></clipPath></defs><g transform="translate(${i.x} ${i.y})" clip-path="url(#${clip})">${componentInner(c,{back})}</g>`;}).join('')}<g fill="none" stroke="#333" stroke-width=".15">${items.map(i=>cuts(i.x,i.y,i.width,i.height)).join('')}</g><path d="M10 293h50m-50-1v2m50-2v2" stroke="#333" stroke-width=".2"/><text x="65" y="294" font-size="2.2">50 mm calibration · cut along component edges</text></svg>`;}
+export function boardSVG(b){const w=b.widthMm,h=b.heightMm,cw=w/b.cols,ch=(h-12)/b.rows;return`<svg xmlns="http://www.w3.org/2000/svg" width="${w}mm" height="${h}mm" viewBox="0 0 ${w} ${h}" font-family="Arial, sans-serif"><rect width="${w}" height="${h}" fill="#f5eedf"/><text x="4" y="8" font-size="4">${esc(b.name)}</text>${b.cells.map((c,i)=>`<g transform="translate(${i%b.cols*cw} ${12+Math.floor(i/b.cols)*ch})"><rect x=".2" y=".2" width="${cw-.4}" height="${ch-.4}" fill="${c.color}" stroke="#637669" stroke-width=".3"/><text x="${cw/2}" y="${ch/2}" text-anchor="middle" font-size="${Math.min(3.5,cw/8)}" fill="#203a34">${esc(c.label)}</text></g>`).join('')}</svg>`;}
+export function printHTML(p){const pages=sheets(p);return`<!doctype html><html><head><meta charset="utf-8"><title>${esc(p.title)} — print components</title><style>@page{size:A4;margin:0}body{margin:0;font-family:Arial,sans-serif}.screen{padding:20px;background:#f4efe4}.page{width:210mm;height:297mm;break-after:page;overflow:hidden}.page:last-child{break-after:auto}.page>svg{display:block;width:210mm;height:297mm}@media print{.screen{display:none}}</style></head><body><div class="screen"><h1>${esc(p.title)}</h1><p>Print at 100% / actual size on A4. Disable browser headers and footers. Check the 50 mm calibration line. Print card backs separately and glue them to fronts or use opaque sleeves; duplex alignment is not assumed. The separate SVG files keep exact physical dimensions.</p><button onclick="print()">Print components / save PDF</button></div>${pages.map((items,i)=>`<section class="page">${sheetSVG(p,items,i)}</section>`).join('')}</body></html>`;}
+export function rulebookHTML(p){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${esc(p.title)} — rulebook</title><style>@page{size:A4;margin:17mm;@bottom-center{content:counter(page);font-size:9pt}}body{font:11pt/1.5 Arial,sans-serif;color:#203a34;max-width:760px;margin:35px auto}h1{font-size:28pt;line-height:1.1}h2{font-size:15pt;break-after:avoid}p{white-space:pre-line;orphans:3;widows:3}table{border-collapse:collapse;width:100%;font-size:10pt}td,th{padding:6px;border-bottom:1px solid #b6c8b8;text-align:left;vertical-align:top}tr,li{break-inside:avoid}.settings{break-inside:avoid}.print{background:#edf3e7;padding:15px}@media print{body{margin:0;max-width:none}.print{display:none}}</style></head><body><div class="print"><button onclick="print()">Print rulebook / save PDF</button></div><h1>${esc(p.title)}</h1><p>${esc(p.subtitle)}</p><p>${p.players} player${p.players===1?'':'s'} · ${p.components.reduce((n,c)=>n+c.quantity,0)} physical components</p>${p.rulebook.map(s=>`<h2>${esc(s.heading)}</h2><p>${esc(s.body)}</p>`).join('')}<section class="settings"><h2>This edition’s rule settings</h2><table>${p.settings.map(s=>`<tr><th>${esc(s.label)}</th><td>${s.value}</td></tr>`).join('')}</table></section><h2>Component inventory and values</h2><table><thead><tr><th>Component</th><th>Copies / size</th><th>Rules values</th></tr></thead><tbody>${p.components.map(c=>`<tr><td>${esc(c.name)}</td><td>${c.quantity} × ${c.widthMm} × ${c.heightMm} mm</td><td>${Object.entries(c.values).map(([k,v])=>esc(k)+': '+esc(v)).join('<br>')}</td></tr>`).join('')}</tbody></table><h2>Print and keep</h2><p>Print components at actual size on A4 and check the 50 mm calibration line. Cut at the component edges. Optional backs can be printed separately and glued on or used in opaque sleeves; duplex alignment is not assumed. Board SVGs preserve their dimensions. The kit includes the editable JSON project and complete rules module, plus a playable offline HTML file. Rule or component revisions create a new edition: recheck the physical rulebook when mechanics change.</p></body></html>`;}
+export function kitFiles(project,html,replay=null,report=null){const p=validateProject(project),source=clone(p);delete source.rules;const files={'game.html':html,'project.relay.json':JSON.stringify(p,null,2),'source/project.json':JSON.stringify(source,null,2),'source/rules.mjs':p.rules,'print/components.html':printHTML(p),'print/rulebook.html':rulebookHTML(p),'README.txt':`${p.title}\n\nOpen game.html in a modern desktop browser to play and edit without a server. Open project.relay.json within Relay to restore its source. The source/rules.mjs file defines this game’s mechanics. Project files contain gameplay JavaScript; open work you intend to run.\n\nPrint print/components.html at 100% / actual size on A4, no browser headers or footers. Check the 50 mm calibration line. Board SVGs have explicit physical sizes. Optional card backs are separate for gluing or opaque sleeves; no duplex alignment is assumed.\n\nPass-and-play conceals private views from casual observation, not from browser inspection or saved source/replays. Simulations measure the named policy and seeds, not fun or human balance. No online multiplayer or native game-engine importer is claimed.\n\nRelay source and original artwork: Autonomous, MIT license.\n`,'LICENSE.txt':'MIT License\n\nCopyright (c) 2026 Autonomous\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n'};sheets(p).forEach((items,i)=>{files[`print/sheet-${i+1}.svg`]=sheetSVG(p,items,i);files[`print/backs-${i+1}.svg`]=sheetSVG(p,items,i,{back:true});});for(const c of p.components)files[`components/${c.id}.svg`]=componentSVG(c);for(const b of p.boards)files[`boards/${b.id}.svg`]=boardSVG(b);if(replay)files['playtest/replay.json']=JSON.stringify(replay,null,2);if(report)files['playtest/simulation.json']=JSON.stringify(report,null,2);return files;}
diff --git a/store/agents/game-master/template/studio/icon.svg b/store/agents/game-master/template/studio/icon.svg
new file mode 100644
index 000000000..b4172956f
--- /dev/null
+++ b/store/agents/game-master/template/studio/icon.svg
@@ -0,0 +1,9 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 96 96">
+ <title>Game Master — opposing teams, one relay</title>
+ <rect x="4" y="4" width="88" height="88" rx="23" fill="#1d2d37"/>
+ <path d="m19 31 13-13 24 24-13 13Z" fill="#ed9075"/>
+ <path d="m40 54 13-13 24 24-13 13Z" fill="#81c8c4"/>
+ <path d="m48 36 12 12-12 12-12-12Z" fill="#1d2d37" stroke="#eed5a0" stroke-width="4"/>
+ <circle cx="24" cy="70" r="5" fill="#ed9075"/>
+ <circle cx="72" cy="26" r="5" fill="#81c8c4"/>
+</svg>
diff --git a/store/agents/game-master/template/studio/project.mjs b/store/agents/game-master/template/studio/project.mjs
new file mode 100644
index 000000000..6707115d0
--- /dev/null
+++ b/store/agents/game-master/template/studio/project.mjs
@@ -0,0 +1,40 @@
+// Portable source schema. Gameplay is authored in rules.mjs, independently of the renderer.
+export const clone=x=>JSON.parse(JSON.stringify(x));
+export const text=(x,max=160)=>typeof x==='string'&&x.length>0&&x.length<=max;
+const id=x=>typeof x==='string'&&/^[a-z][a-z0-9_-]{0,63}$/.test(x);
+const color=x=>typeof x==='string'&&/^#[a-f0-9]{6}$/i.test(x);
+const number=(x,a,b)=>Number.isFinite(x)&&x>=a&&x<=b;
+export function assert(ok,message){if(!ok)throw new Error(message);}
+export function validateProject(raw){
+ assert(raw&&JSON.stringify(raw).length<=3000000,'Keep the project below 3 MB.');const p=clone(raw);
+ assert(p.spec===1&&id(p.id)&&text(p.title)&&text(p.subtitle,400),'Use a version 1 Relay project with an id, title and subtitle.');
+ assert(Number.isInteger(p.players)&&p.players>=1&&p.players<=6,'Choose 1–6 players.');
+ assert(text(p.rules,200000),'Include the complete rules module.');
+ assert(Array.isArray(p.rulebook)&&p.rulebook.length>=1&&p.rulebook.length<=40,'Include 1–40 rulebook sections.');
+ for(const s of p.rulebook)assert(text(s.heading)&&text(s.body,10000),'Rulebook sections need a heading and body.');
+ assert(Array.isArray(p.components)&&p.components.length>0&&p.components.length<=160,'Create 1–160 component designs.');
+ const ids=new Set();let quantity=0;
+ for(const c of p.components){
+ assert(id(c.id)&&!ids.has(c.id),'Component ids must be unique.');ids.add(c.id);
+ assert(text(c.name,80)&&typeof c.body==='string'&&c.body.length<=700,'Use short, readable component names and text.');
+ assert(['card','token','tile'].includes(c.kind),'Component kind must be card, token or tile.');
+ assert(number(c.widthMm,12,190)&&number(c.heightMm,12,273),'Component dimensions must fit A4 within 10 mm margins.');
+ assert(Number.isInteger(c.quantity)&&c.quantity>=1&&c.quantity<=100,'Component quantity must be 1–100.');quantity+=c.quantity;
+ assert(color(c.color)&&color(c.ink),'Use six-digit hex colors.');
+ assert(typeof c.symbol==='string'&&c.symbol.length<=8,'Use a short symbol.');
+ if(c.face!==undefined)assert(typeof c.face==='string'&&c.face.length<=700000&&/^data:image\/(png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/=]+$/.test(c.face),'Use an embedded PNG, JPEG, WebP or SVG face below 700 KB.');
+ assert(c.values&&typeof c.values==='object'&&!Array.isArray(c.values),'Component values must be an object.');
+ for(const [k,v] of Object.entries(c.values))assert(id(k)&&((typeof v==='number'&&Number.isFinite(v))||typeof v==='boolean'||(typeof v==='string'&&v.length<160)),'Values must be finite numbers, short text or booleans.');
+ assert(Object.keys(c.values).length<=20,'Keep at most 20 values per component.');
+ }
+ assert(quantity<=600,'Keep the kit within 600 physical components.');
+ assert(Array.isArray(p.settings)&&p.settings.length<=30,'Keep at most 30 rule settings.');
+ const settings=new Set();for(const s of p.settings){assert(id(s.id)&&!settings.has(s.id)&&text(s.label),'Settings need unique ids and labels.');settings.add(s.id);assert(number(s.min,-10000,10000)&&number(s.max,s.min,10000)&&number(s.value,s.min,s.max)&&number(s.step,.001,1000),'Setting values must lie inside their declared bounds.');}
+ assert(Array.isArray(p.boards)&&p.boards.length<=8,'Keep at most eight board sheets.');
+ const boards=new Set();for(const b of p.boards){assert(id(b.id)&&!boards.has(b.id)&&text(b.name),'Boards need unique ids and names.');boards.add(b.id);assert(number(b.widthMm,30,277)&&number(b.heightMm,30,190),'Boards must fit landscape A4 within 10 mm margins.');assert(Number.isInteger(b.cols)&&b.cols>0&&b.cols<=20&&Number.isInteger(b.rows)&&b.rows>0&&b.rows<=20,'Boards support 1–20 rows and columns.');assert(Array.isArray(b.cells)&&b.cells.length===b.cols*b.rows,'Define every board cell.');for(const c of b.cells)assert(typeof c.label==='string'&&c.label.length<=30&&color(c.color),'Board cells need a short label and hex color.');}
+ delete p.revision;return p;
+}
+export function projectData(p){const q=clone(p);delete q.rules;delete q.revision;return q;}
+export function canonical(x){if(x===null||typeof x!=='object')return JSON.stringify(x);return Array.isArray(x)?'['+x.map(canonical).join(',')+']':'{'+Object.keys(x).sort().map(k=>JSON.stringify(k)+':'+canonical(x[k])).join(',')+'}';}
+export async function digest(x){const bytes=new TextEncoder().encode(typeof x==='string'?x:canonical(x));return [...new Uint8Array(await crypto.subtle.digest('SHA-256',bytes))].map(b=>b.toString(16).padStart(2,'0')).join('');}
+export function history(initial,limit=80){let states=[clone(initial)],at=0;return{get value(){return clone(states[at]);},get canUndo(){return at>0;},get canRedo(){return at<states.length-1;},push(x){states=states.slice(0,at+1);states.push(clone(x));if(states.length>limit)states.shift();at=states.length-1;return this.value;},undo(){at=Math.max(0,at-1);return this.value;},redo(){at=Math.min(states.length-1,at+1);return this.value;}};}
diff --git a/store/agents/game-master/template/studio/shell.html b/store/agents/game-master/template/studio/shell.html
new file mode 100644
index 000000000..151c352e3
--- /dev/null
+++ b/store/agents/game-master/template/studio/shell.html
@@ -0,0 +1,11 @@
+<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Relay — Game Master</title><!-- FAVICON --><style>/* STUDIO_CSS */</style></head><body>
+<header class="top"><div class="brand"><span class="logo"><!-- RELAY_ICON --></span><span>RELAY<small>GAME WORKSHOP</small></span></div><nav aria-label="Workspace"><button data-tab="workbench" class="active">Workbench</button><button data-tab="rules">Rulebook</button><button data-tab="print">Print &amp; keep</button></nav><div class="top-actions"><button id="open-project">Open game</button><button id="save-source">Save source</button><button class="primary" id="export-kit">Export kit ↗</button></div></header>
+<div id="notice" role="status" hidden></div><div id="source-notice" class="source-notice" hidden><span>The source changed while this edition was open.</span><button id="keep-draft">Download my draft</button><button id="load-source">Keep both &amp; load source</button></div>
+<main id="workbench" class="workspace"><aside class="library"><div class="eyebrow">YOUR GAME / COMPONENTS</div><h2 id="library-title"></h2><p class="muted">Edit the things people hold.</p><div class="row"><button id="add-component">+ Component</button><button id="edit-metadata">Game details</button></div><div id="component-list"></div><div class="rule-settings"><h3>Rule settings</h3><div id="settings"></div><button id="edit-rules">Edit rules module</button></div></aside>
+<section class="table-area"><div class="game-heading"><div><div class="eyebrow">PLAY YOUR CREATION</div><h1 id="game-title"></h1><p id="game-subtitle"></p></div><div class="edition"><span id="source-state">Opening…</span><div class="row"><button id="undo-edit">Undo edit</button><button id="redo-edit">Redo</button></div></div></div><div class="play-toolbar"><label>Seed <input id="seed" value="first-game" maxlength="128"></label><button id="restart">Restart</button><button id="undo-turn">Undo turn</button><button id="save-replay">Save replay</button><button id="open-replay">Open replay</button></div><div id="edition-notice" hidden><span>The table is playing the previous edition.</span><button id="apply-edition">Keep playtest &amp; apply edits</button></div><div class="tabletop"><div id="scores"></div><div class="turn-heading"><div><h2 id="turn-title"></h2><p id="turn-message"></p></div><span id="turn-count"></span></div><div id="zones"></div><div id="actions" aria-label="Legal moves"></div><div id="curtain" hidden><div class="eyebrow">PASS THE TABLE</div><h2 id="curtain-title"></h2><p>Hand the screen to the next player before revealing their view.</p><button class="primary" id="reveal">I’m ready · reveal my turn</button><small>This curtain conceals casual views. Source files and replays contain the game.</small></div></div><section class="playtesting"><div><div class="eyebrow">CHECK THE RULES</div><h3>What happens over many games?</h3><p>Find dead ends and compare outcomes under a named policy.</p></div><div class="row"><label>Games<input id="simulation-count" type="number" min="1" max="200" value="50"></label><label>Policy<select id="policy"><option value="uniform">Uniform legal choices</option><option value="authored">Authored policy</option></select></label><button id="simulate">Run playtest</button></div><div id="simulation-report"></div></section></section>
+<aside class="inspector"><div class="eyebrow">COMPONENT STUDIO</div><div id="component-preview"></div><form id="component-form"></form></aside></main>
+<main id="rules" class="document-view" hidden><div class="eyebrow">THE GAME PEOPLE WILL PLAY</div><h1>Write the rulebook</h1><p class="muted">Explain setup, each decision, scoring and the end of the game. Keep these words in step with your rules module.</p><div id="rulebook-editor"></div><button id="add-section">+ Section</button><button id="print-rules">Open printable rulebook</button></main>
+<main id="print" class="document-view" hidden><div class="eyebrow">FROM SCREEN TO TABLE</div><h1>Keep the whole game.</h1><p class="lead">A playable file, editable source, and the things you can print and hold.</p><div class="delivery-grid"><article><span>01 / PLAY</span><h2>Offline game</h2><p>Open it in a browser. Play, edit components and save your edition.</p><button id="export-html">Download game HTML</button><button id="export-project">Download project</button></article><article><span>02 / MAKE</span><h2>Print &amp; play</h2><p>A4 component sheets at physical size, separate SVGs and board sheets. Print at 100% and check the calibration line.</p><button id="print-components">Open component sheets</button><button id="print-rulebook">Open rulebook</button></article><article><span>03 / KEEP</span><h2>Complete kit</h2><p>Game, source, rulebook, components, boards and the current playtest replay in one ZIP.</p><button id="export-kit-secondary">Download complete kit</button></article></div><div id="print-preview"></div><p class="muted">Card backs are supplied separately for gluing or opaque sleeves. No duplex alignment is assumed. Save PDF from the print dialog; command-line export also produces PDFs.</p></main>
+<dialog id="editor-dialog"><form method="dialog"><button class="close" aria-label="Close editor">×</button></form><h2 id="editor-title"></h2><div id="editor-content"></div><button id="editor-apply" class="primary">Apply changes</button></dialog>
+<input id="face-file" type="file" accept="image/png,image/jpeg,image/webp,image/svg+xml" hidden><input id="project-file" type="file" accept=".json,.relay.json" hidden><input id="replay-file" type="file" accept=".json" hidden>
+<script id="relay-data" type="application/json">RELAY_DATA</script><script>/* RELAY_APP */</script></body></html>
diff --git a/store/agents/game-master/template/studio/style.css b/store/agents/game-master/template/studio/style.css
new file mode 100644
index 000000000..e2a2fd460
--- /dev/null
+++ b/store/agents/game-master/template/studio/style.css
@@ -0,0 +1,8 @@
+:root{font-family:Inter,ui-sans-serif,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#213c34;background:#f3f0e7;font-synthesis:none}*{box-sizing:border-box}body{margin:0}button,input,textarea,select{font:inherit}button{border:1px solid #c3cbbf;border-radius:7px;padding:9px 12px;background:#fffcf5;color:inherit;cursor:pointer;font-size:12px;font-weight:600}button:hover{background:#e7eddf}button:disabled{opacity:.45;cursor:default}button.primary{background:#284d3d;border-color:#284d3d;color:#fff8e9}input,textarea,select{max-width:100%;border:1px solid #c7cec1;border-radius:5px;padding:8px;background:#fffdf7;color:inherit}input[type=number]{width:85px}textarea{width:100%;resize:vertical}label{font-size:12px;display:block}label>input,label>textarea,label>select{display:block;width:100%;margin-top:5px}h1,h2,h3,p{margin-top:0}h1{font-family:Georgia,serif;font-weight:400;font-size:42px;letter-spacing:-1px;margin-bottom:10px}h2{font-size:20px}h3{font-size:16px}p{line-height:1.55}small,.muted{color:#69776b}.eyebrow{font-size:10px;letter-spacing:1.5px;font-weight:700;color:#718169;margin-bottom:15px}.row{display:flex;gap:7px;align-items:end;flex-wrap:wrap}[hidden]{display:none!important}.top{display:flex;align-items:center;justify-content:space-between;gap:20px;padding:18px 28px;border-bottom:1px solid #cdd3c4;background:#faf7ef}.brand{display:flex;gap:10px;align-items:center;font-size:20px;letter-spacing:3px;font-weight:800}.brand small{display:block;font-size:8px;letter-spacing:1.7px;margin-top:4px}.logo{display:block;width:35px}.logo svg{width:35px;height:35px}.top nav,.top-actions{display:flex;gap:5px}.top nav button{border-color:transparent;background:none;color:#73806e}.top nav button.active{color:#284d3d;border-bottom-color:#284d3d;border-radius:0}.workspace{display:grid;grid-template-columns:235px minmax(400px,1fr) 255px;min-height:calc(100vh - 78px)}.library,.inspector{padding:27px 20px;border-right:1px solid #d1d6c9;min-width:0}.inspector{border-right:0;border-left:1px solid #d1d6c9}.library h2{font-family:Georgia,serif;font-size:23px;font-weight:400}.library p{font-size:12px}.library .row{margin-bottom:22px}.component-row{width:100%;display:flex;align-items:center;gap:10px;text-align:left;padding:10px 8px;margin:6px 0;background:none;border-color:transparent}.component-row.active{background:#e1e8d9;border-color:#b4c2a7}.component-row .swatch{width:26px;height:35px;border-radius:3px;display:grid;place-content:center;flex-shrink:0}.component-row small{display:block;font-size:10px;margin-top:4px}.rule-settings{border-top:1px solid #cdd3c4;margin-top:24px;padding-top:20px}.rule-settings label{margin:12px 0}.rule-settings input{width:100%}.table-area{padding:28px;min-width:0}.game-heading{display:flex;gap:20px;justify-content:space-between}.game-heading p{font-size:13px;max-width:440px;color:#6d7b6b}.edition{font-size:10px;flex-shrink:0;text-align:right;color:#6d7b6b}.edition .row{margin-top:12px;justify-content:end}.edition button{padding:6px;font-size:10px}.play-toolbar{display:flex;gap:7px;align-items:end;flex-wrap:wrap;margin:17px 0}.play-toolbar input{width:145px;font-size:12px}.play-toolbar label{font-size:10px}.tabletop{position:relative;border-radius:16px;background:#e3e9d9;border:1px solid #c6d1ba;padding:25px;min-height:445px;overflow:hidden;box-shadow:0 12px 30px #344f3210}.turn-heading{display:flex;justify-content:space-between;gap:10px;margin:22px 0}.turn-heading h2{font-family:Georgia,serif;font-weight:400;font-size:25px;margin:0 0 8px}.turn-heading p{font-size:12px;max-width:510px;margin:0}.turn-heading span{font-size:10px;white-space:nowrap}#scores{display:flex;gap:10px;flex-wrap:wrap}#scores>div{background:#f4f6eb;border:1px solid #ccd5bf;padding:9px 15px;border-radius:8px;min-width:110px;font-size:10px;color:#5d6e58}#scores strong{font-size:22px;display:block;color:#28452e;margin-top:5px}.zone{border-top:1px solid #c4ceb7;padding-top:15px;margin-top:20px}.zone h3{font-size:11px;text-transform:uppercase;letter-spacing:1px;color:#65735c;margin:0 0 13px}.cards{display:flex;flex-wrap:wrap;gap:10px;min-height:35px}.game-piece{border:0;padding:0;background:transparent;position:relative;border-radius:7px;transition:transform .15s;box-shadow:0 3px 5px #1b3b3019;width:98px;max-width:100%}.game-piece svg{display:block;width:100%;height:auto;border-radius:5px}.game-piece[data-move]:hover{transform:translateY(-6px);background:transparent;box-shadow:0 6px 9px #1b3b3030}.badge{position:absolute;bottom:2px;right:2px;background:#fff8e6;color:#213c34;padding:2px 4px;font-size:10px;border-radius:3px}.board{display:grid;gap:4px;max-width:410px;padding:8px;background:#d8ddcb;border:1px solid #9ba98e;border-radius:7px}.board-cell{min-width:0;aspect-ratio:1;display:flex;flex-direction:column;align-items:center;justify-content:center;position:relative;border:1px solid #c3cbbb;border-radius:4px}.board-cell>small{font-size:9px;position:absolute;top:3px;left:4px}.board .game-piece{width:85%;box-shadow:none}.board .game-piece svg{border-radius:0}.rotation{position:relative}.rotation .turn-arrow{font-size:11px;display:block}#actions{display:flex;gap:6px;flex-wrap:wrap;margin-top:22px}#actions button{background:#fff8e9;font-size:11px}#curtain{position:absolute;inset:0;background:#244b3e;z-index:5;color:#fff7e6;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding:30px}#curtain h2{font:32px Georgia,serif}#curtain p{max-width:330px;font-size:13px}#curtain .eyebrow{color:#b2c6a3}#curtain .primary{background:#dce7c7;color:#244b3e}#curtain small{margin-top:28px;color:#b4c4ad;max-width:350px;font-size:10px}.playtesting{margin-top:27px;border-top:1px solid #cdd3c4;padding-top:24px}.playtesting .eyebrow{margin-bottom:8px}.playtesting h3{margin:0 0 6px}.playtesting p{font-size:12px;margin:0 0 12px}.playtesting label{font-size:10px}.playtesting .row{align-items:end}.playtesting select{font-size:12px}.simulation-stats{display:flex;gap:18px;flex-wrap:wrap;padding:15px 0;font-size:12px}.simulation-stats strong{display:block;font-size:21px}.inspector #component-preview{max-width:140px;margin:20px auto 24px}.inspector svg{width:100%;height:auto;filter:drop-shadow(0 8px 8px #263d2a30)}#component-form label{margin:13px 0}#component-form .row>label{flex:1}#component-form input{width:100%}#component-form textarea{font-size:12px;line-height:1.5}.danger{color:#9b4d40}.document-view{max-width:1050px;padding:48px 35px;margin:0 auto}.document-view textarea{margin:6px 0 18px;line-height:1.6}.rule-section{border-bottom:1px solid #cdd3c4;margin-bottom:25px;padding-bottom:10px}.lead{font-family:Georgia,serif;font-size:21px}.delivery-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:20px;margin:35px 0}.delivery-grid article{background:#fffcf4;border:1px solid #c8d1bd;border-radius:10px;padding:24px}.delivery-grid article>span{font-size:10px;letter-spacing:1px;color:#6b7d5d}.delivery-grid h2{font:26px Georgia,serif;margin:20px 0 12px}.delivery-grid p{font-size:13px}.delivery-grid button{margin:4px 0}#print-preview{display:flex;gap:15px;overflow:auto;margin-bottom:25px;padding-bottom:20px}#print-preview svg{width:210px;height:297px;flex-shrink:0;border:1px solid #d1d6c9;background:white}#notice{position:fixed;bottom:22px;left:50%;transform:translateX(-50%);max-width:90vw;background:#244b3e;color:white;padding:13px 22px;font-size:13px;border-radius:10px;z-index:50;box-shadow:0 6px 30px #0003}#notice.error{background:#913f32}.source-notice,#edition-notice{background:#f5deb0;padding:13px 20px;display:flex;align-items:center;gap:10px;flex-wrap:wrap;font-size:12px}#edition-notice{margin-bottom:12px;border-radius:8px}dialog{width:min(820px,92vw);max-height:85vh;overflow:auto;background:#faf7ed;border:1px solid #b7c3ac;border-radius:15px;padding:30px;color:#213c34}dialog::backdrop{background:#142c2490}.close{float:right;border:0;background:none;font-size:24px;padding:0}dialog h2{font:28px Georgia,serif}dialog label{margin:15px 0}dialog textarea.code{font-family:ui-monospace,monospace;font-size:12px;white-space:pre;min-height:360px}dialog p{font-size:12px}#editor-apply{margin-top:15px}
+@media(min-width:1550px){.workspace{grid-template-columns:255px minmax(450px,1fr) 295px}.table-area{padding:38px}.tabletop{padding:30px}.game-piece{width:113px}}
+@media(max-width:1180px){.workspace{grid-template-columns:205px minmax(340px,1fr)}.inspector{grid-column:1/-1;border-top:1px solid #cdd3c4;display:grid;grid-template-columns:180px 1fr;gap:20px}.inspector .eyebrow{grid-column:1/-1}.inspector #component-preview{margin:0 auto}#component-form{display:grid;grid-template-columns:1fr 1fr;gap:0 20px}.top{flex-wrap:wrap}.game-heading{display:block}.edition{text-align:left}.edition .row{justify-content:start}.table-area{padding:23px}}
+@media(max-width:720px){.top{padding:15px;gap:15px;display:grid;grid-template-columns:1fr}.top nav{order:3;overflow:auto}.top-actions{flex-wrap:wrap}.workspace{display:block}.library{padding:20px;border-right:0;border-bottom:1px solid #cdd3c4}.library .muted,.library>h2{display:none}#component-list{display:flex;overflow:auto;gap:5px}.component-row{width:145px;flex-shrink:0}.rule-settings{margin-top:15px}.rule-settings #settings{display:flex;gap:12px;flex-wrap:wrap}.rule-settings label{max-width:140px}.table-area{padding:22px 15px}h1{font-size:35px}.tabletop{padding:18px;min-height:430px}.game-piece{width:85px}.inspector{display:block;padding:22px}.inspector #component-preview{max-width:140px;margin-bottom:20px}#component-form{display:block}.document-view{padding:30px 18px}.delivery-grid{grid-template-columns:1fr}.play-toolbar button{font-size:10px}.turn-heading{flex-wrap:wrap}#curtain h2{font-size:27px}.cards{gap:8px}.board{max-width:100%}}
+
+.game-piece:disabled{opacity:1;cursor:default}
+
+.table-piece{width:125px;min-width:0}.table-piece .game-piece{width:100%}.piece-label{font-size:12px;line-height:1.35;display:block;margin-top:8px;font-weight:600}.piece-label small{font-weight:400;font-size:11px;display:block;margin-top:4px}.table-piece details{font-size:11px;margin-top:5px}.table-piece details p{background:#f6f7ef;border-radius:5px;padding:8px;margin-top:6px}.table-piece summary{cursor:pointer;color:#5c7252}.board .table-piece{width:88%}.board .game-piece{width:100%}@media(max-width:720px){.table-piece{width:95px}.piece-label{font-size:11px}.piece-label small{font-size:10px}}
diff --git a/store/agents/game-master/template/studio/worker.js b/store/agents/game-master/template/studio/worker.js
new file mode 100644
index 000000000..532285fe9
--- /dev/null
+++ b/store/agents/game-master/template/studio/worker.js
@@ -0,0 +1,23 @@
+import {Game,simulate} from './engine.mjs';
+import {validateProject,digest} from './project.mjs';
+let project,rules,game,revision;
+self.onmessage=async({data:{id,type,payload}})=>{try{
+ let result;
+ if(type==='load'){
+ project=validateProject(payload.project);revision=await digest(project);
+ const url=URL.createObjectURL(new Blob([project.rules],{type:'text/javascript'}));try{rules=await import(url);}finally{URL.revokeObjectURL(url);}
+ game=new Game(project,rules,payload.seed??'first-game');result={...game.view(),revision};
+ }else{
+ if(!game)throw new Error('Open a game first.');
+ if(type==='step')result=game.step(payload.id);
+ else if(type==='undo')result=game.undo();
+ else if(type==='restart'){game=new Game(project,rules,payload.seed);result=game.view();}
+ else if(type==='replay')result={...game.replay(),revision};
+ else if(type==='restore'){
+ if(payload.revision!==revision)throw new Error('This replay belongs to different rules or components. Open its matching game file.');
+ const candidate=new Game(project,rules,payload.seed);result=candidate.restore(payload);game=candidate;
+ }else if(type==='simulate')result={...simulate(project,rules,payload),revision};
+ else throw new Error('Unknown game operation.');
+ }
+ self.postMessage({id,result});
+}catch(error){self.postMessage({id,error:error.message});}};
diff --git a/store/agents/game-master/template/tools/build.mjs b/store/agents/game-master/template/tools/build.mjs
new file mode 100644
index 000000000..4716f4e60
--- /dev/null
+++ b/store/agents/game-master/template/tools/build.mjs
@@ -0,0 +1,18 @@
+#!/usr/bin/env node
+import {readFile,writeFile,mkdir,realpath,access} from 'node:fs/promises';
+import {resolve,join,sep,dirname} from 'node:path';
+import {fileURLToPath,pathToFileURL} from 'node:url';
+import {validateProject,digest} from '../studio/project.mjs';
+export async function readProject(workspace){const root=await realpath(workspace);const files=await Promise.all(['project.json','rules.mjs'].map(async n=>{const f=await realpath(join(root,'game',n));if(!f.startsWith(join(root,'game')+sep))throw new Error('Keep source inside game/.');return readFile(f,'utf8');}));return validateProject({...JSON.parse(files[0]),rules:files[1]});}
+export async function toolsDirectory(){for(const path of [process.env.GAME_DSH_DIR&&join(process.env.GAME_DSH_DIR,'toolchain'),fileURLToPath(new URL('../../toolchain/',import.meta.url))].filter(Boolean)){try{await access(join(path,'node_modules/esbuild/lib/main.js'));return path;}catch{}}throw new Error('Run Game Master setup. Set GAME_DSH_DIR when building an installed workspace.');}
+export async function buildGame(workspace,{check=false,project:provided}={}){
+ const root=resolve(workspace),project=provided?validateProject(provided):await readProject(root);project.revision=await digest(project);
+ const tools=await toolsDirectory(),{build}=await import(pathToFileURL(join(tools,'node_modules/esbuild/lib/main.js')).href);
+ await build({logLevel:'silent',stdin:{contents:project.rules,sourcefile:'rules.mjs',loader:'js'},bundle:true,write:false,format:'esm',plugins:[{name:'offline-rules',setup(b){b.onResolve({filter:/.*/},()=>({errors:[{text:'Rules must be self-contained: imports are not supported.'}]}));}}]});
+ const worker=await build({entryPoints:[join(root,'studio/worker.js')],bundle:true,write:false,format:'iife',minify:true,target:'es2022'});
+ const app=await build({entryPoints:[join(root,'studio/app.js')],bundle:true,write:false,format:'iife',minify:true,target:'es2022'});
+ const [shell,css,icon]=await Promise.all(['shell.html','style.css','icon.svg'].map(n=>readFile(join(root,'studio',n),'utf8')));
+ const html=shell.replace('/* STUDIO_CSS */',()=>css).replace('<!-- RELAY_ICON -->',()=>icon).replace('<!-- FAVICON -->',()=>`<link rel="icon" href="data:image/svg+xml,${encodeURIComponent(icon)}">`).replace('RELAY_DATA',()=>JSON.stringify({project,worker:worker.outputFiles[0].text}).replace(/</g,'\\u003c')).replace('/* RELAY_APP */',()=>app.outputFiles[0].text.replace(/<\/script/gi,'<\\/script'));
+ if(provided)return{html,project};const target=join(root,'game/index.html');if(check){if(await readFile(target,'utf8')!==html)throw new Error('Game studio is stale. Run node tools/build.mjs.');}else{await writeFile(target,html);await mkdir(join(root,'.harness'),{recursive:true});await writeFile(join(root,'.harness/verdict.json'),JSON.stringify({spec:1,ready:false,artifact:'game/index.html',summary:project.title+' built; actual play and physical delivery review pending'})+'\n');}return{title:project.title,revision:project.revision};
+}
+if(process.argv[1]&&await realpath(process.argv[1]).catch(()=>null)===fileURLToPath(import.meta.url))console.log(JSON.stringify(await buildGame(resolve(dirname(fileURLToPath(import.meta.url)),'..'),{check:process.argv.includes('--check')})));
diff --git a/store/agents/game-master/template/tools/check.mjs b/store/agents/game-master/template/tools/check.mjs
index 11c7c02b3..43f5b1171 100644
--- a/store/agents/game-master/template/tools/check.mjs
+++ b/store/agents/game-master/template/tools/check.mjs
@@ -1,75 +1,8 @@
-const CONFIG = {"id":"game-master","artifact":"game/index.html"};
-// Compiled into each workspace's tools/check.mjs. Tests the model in the ACTUAL edited HTML.
-import { readFile, mkdir, writeFile } from "node:fs/promises";
-import { createHash } from "node:crypto";
-import vm from "node:vm";
-import { resolve, dirname } from "node:path";
-
-const args = process.argv.slice(2),
- i = args.indexOf("--seeds");
-const count = i === -1 ? 32 : Number(args[i + 1]);
-if (!Number.isInteger(count) || count < 1 || count > 1000)
- throw new Error("--seeds must be an integer from 1 to 1000");
-const artifact = resolve(CONFIG.artifact);
-const html = await readFile(artifact, "utf8");
-const script = html.match(
- /<script id="harness-model">([\s\S]*?)<\/script>/,
-)?.[1];
-if (!script)
- throw new Error(
- 'Keep the pure model in <script id="harness-model"> so this checker can exercise the actual artifact.',
- );
-const expressions = {
- "generative-art": `const m=artModel(SEED);const p=artPaths(m);({state:m,valid:p.length>0&&p.flat().every(([x,y])=>Number.isFinite(x)&&Number.isFinite(y)),metrics:{paths:p.length,palette:m.palette}})`,
- "creative-direction": `const m=directionModel(SEED);const ratio=contrast(m.colors[0],m.colors[1]);({state:m,valid:ratio>=4.5,metrics:{direction:m.name,contrast:ratio}})`,
- "lab-bench": `const p=experiment(SEED),e=treatmentEffect(p);({state:p,valid:p.length>1&&p.every(p=>Number.isFinite(p.x)&&Number.isFinite(p.y))&&Number.isFinite(e.low)&&e.low<=e.high,metrics:{samples:p.length,effect:e.difference,interval:[e.low,e.high]}})`,
- "music-studio": `const s=musicScore(SEED),r=renderMusic(s);({state:Array.from(r.samples),valid:r.peak>.001&&r.peak<=.95&&r.samples.every(Number.isFinite),metrics:{seconds:r.duration,peak:r.peak,rms:r.rms}})`,
- "game-master": `const m=arenaMatch(SEED),s=m.history.at(-1);({state:m,valid:m.history.length>1&&m.history.length<=10000&&s.units.every(u=>u.hp>=0&&u.x>=0&&u.x<m.map.w&&u.y>=0&&u.y<m.map.h),metrics:{turns:s.turn,score:s.score,winner:m.winner}})`,
- "drone-pilot": `const s=flyAutopilot(SEED);({state:s,valid:s.finished&&!s.crashed&&s.passed===flightCourse(SEED).length,metrics:{seconds:s.time,passed:s.passed,missed:s.missed}})`,
- "voxel-worlds": `const w=voxelWorld(SEED);let p={...w.spawn,vy:0,grounded:true};const clear=playerFits(w,p.x,p.y,p.z);for(let t=0;t<120;t++)p=movePlayer(w,p,{forward:1});({state:Array.from(w.blocks),valid:clear&&playerFits(w,p.x,p.y,p.z),metrics:{blocks:w.blocks.filter(Boolean).length,walkDistance:Math.hypot(p.x-w.spawn.x,p.z-w.spawn.z)}})`,
-};
-const expression = expressions[CONFIG.id];
-const digest = (value) =>
- createHash("sha256").update(JSON.stringify(value)).digest("hex");
-const results = [];
-for (let seed = 0; seed < count; seed++) {
- const run = () =>
- vm.runInNewContext(
- `${script}\n${expression}`,
- { SEED: String(seed) },
- { timeout: 10000 },
- );
- try {
- const first = run(),
- second = run(),
- signature = digest(first.state),
- repeat = digest(second.state);
- results.push({
- seed,
- ok: first.valid && signature === repeat,
- signature,
- metrics: first.metrics,
- });
- } catch (error) {
- results.push({ seed, ok: false, error: error.message });
- }
-}
-const passed = results.filter((r) => r.ok).length;
-const report = {
- spec: 1,
- harness: CONFIG.id,
- artifact: CONFIG.artifact,
- checkedAt: new Date().toISOString(),
- modelChecks: { passed, total: count },
- scope:
- "Pure model invariants and same-process repeatability. Browser interaction, layout, listening and export review still required.",
- results,
-};
-const out = resolve(".harness/model-check.json");
-await mkdir(dirname(out), { recursive: true });
-await writeFile(out, JSON.stringify(report, null, 2) + "\n");
-console.log(
- `${CONFIG.id}: ${passed}/${count} model checks passed. Report: ${out}`,
-);
-console.log(report.scope);
-if (passed !== count) process.exitCode = 1;
+#!/usr/bin/env node
+import {Worker} from 'node:worker_threads';
+import {mkdir,writeFile,realpath} from 'node:fs/promises';
+import {resolve,dirname,join} from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {readProject} from './build.mjs';
+export function checkRules(project,options={},operation='check'){return new Promise((resolve,reject)=>{const worker=new Worker(new URL('./rules-runner.mjs',import.meta.url),{workerData:{project,options,operation}}),timer=setTimeout(()=>{worker.terminate();reject(new Error('Rule check exceeded 60 seconds. Revise the rules or reduce the sample.'));},60000);worker.once('message',m=>{clearTimeout(timer);worker.terminate();m.ok?resolve(m):reject(new Error(m.error));});worker.once('error',e=>{clearTimeout(timer);reject(e);});worker.once('exit',code=>{clearTimeout(timer);if(code!==0)reject(new Error('Rule check stopped.'));});});}
+if(process.argv[1]&&await realpath(process.argv[1]).catch(()=>null)===fileURLToPath(import.meta.url)){const root=resolve(dirname(fileURLToPath(import.meta.url)),'..'),at=process.argv.indexOf('--seeds'),count=at>=0?Number(process.argv[at+1]):50;const p=await readProject(root),{report}=await checkRules(p,{count});await mkdir(join(root,'.harness'),{recursive:true});await writeFile(join(root,'.harness/game-check.json'),JSON.stringify(report,null,2)+'\n');console.log(JSON.stringify({completed:report.completed,errors:report.errors,capped:report.capped,repeated:report.repeated,scope:report.scope}));}
diff --git a/store/agents/game-master/template/tools/export.mjs b/store/agents/game-master/template/tools/export.mjs
new file mode 100644
index 000000000..8b046352c
--- /dev/null
+++ b/store/agents/game-master/template/tools/export.mjs
@@ -0,0 +1,20 @@
+#!/usr/bin/env node
+import {mkdir,writeFile,readFile,realpath} from 'node:fs/promises';
+import {resolve,join,dirname} from 'node:path';
+import {fileURLToPath,pathToFileURL} from 'node:url';
+import {readProject,buildGame,toolsDirectory} from './build.mjs';
+import {kitFiles,boardSVG,esc} from '../studio/formats.mjs';
+import {zipFiles} from '../studio/archive.mjs';
+import {checkRules} from './check.mjs';
+export async function exportGame(workspace,destination,{project:provided,pdf=true}={}){
+ const root=resolve(workspace),out=resolve(destination),project=provided??await readProject(root);await checkRules(project,{},'initial');const {html}=await buildGame(root,{project});const files=kitFiles(project,html);await mkdir(out,{recursive:true});
+ for(const [name,body] of Object.entries(files)){const file=join(out,name);await mkdir(dirname(file),{recursive:true});await writeFile(file,body);}
+ if(pdf){
+ const tools=await toolsDirectory(),{chromium}=await import(pathToFileURL(join(tools,'node_modules/playwright-core/index.mjs')).href),{browserPath}=await import(pathToFileURL(join(tools,'browser.mjs')).href);const browser=await chromium.launch({executablePath:await browserPath(),headless:true});
+ try{const page=await browser.newPage();for(const name of ['components','rulebook']){await page.goto(pathToFileURL(join(out,'print',name+'.html')).href);await page.pdf({path:join(out,'print',name+'.pdf'),printBackground:true,preferCSSPageSize:true});files['print/'+name+'.pdf']=await readFile(join(out,'print',name+'.pdf'));}
+ for(const b of project.boards){const board=`<!doctype html><html><head><style>@page{size:A4 landscape;margin:10mm}body{margin:0}</style><title>${esc(b.name)}</title></head><body>${boardSVG(b)}</body></html>`;const path=join(out,'boards',b.id+'.html');await writeFile(path,board);files['boards/'+b.id+'.html']=board;await page.goto(pathToFileURL(path).href);await page.pdf({path:join(out,'boards',b.id+'.pdf'),printBackground:true,preferCSSPageSize:true});files['boards/'+b.id+'.pdf']=await readFile(join(out,'boards',b.id+'.pdf'));}
+ }finally{await browser.close();}
+ }
+ await writeFile(join(out,'game-kit.zip'),new Uint8Array(await zipFiles(files).arrayBuffer()));return{title:project.title,destination:out,files:Object.keys(files)};
+}
+if(process.argv[1]&&await realpath(process.argv[1]).catch(()=>null)===fileURLToPath(import.meta.url)){const root=resolve(dirname(fileURLToPath(import.meta.url)),'..');console.log(JSON.stringify(await exportGame(root,process.argv[2]??join(root,'delivery'))));}
diff --git a/store/agents/game-master/template/tools/rules-runner.mjs b/store/agents/game-master/template/tools/rules-runner.mjs
new file mode 100644
index 000000000..a4743e404
--- /dev/null
+++ b/store/agents/game-master/template/tools/rules-runner.mjs
@@ -0,0 +1,14 @@
+import {parentPort,workerData} from 'node:worker_threads';
+import {Game,simulate} from '../studio/engine.mjs';
+import {canonical,validateProject,digest} from '../studio/project.mjs';
+try{
+ const project=validateProject(workerData.project),rules=await import('data:text/javascript;base64,'+Buffer.from(project.rules).toString('base64'));
+ if(workerData.operation==='initial'){const game=new Game(project,rules);parentPort.postMessage({ok:true,view:game.view()});}
+ else{
+ const options=workerData.options??{},a=simulate(project,rules,options),b=simulate(project,rules,options);
+ if(canonical(a)!==canonical(b))throw new Error('The same rules, policy and seeds produced different outcomes.');
+ if(a.errors||a.capped)throw new Error(`${a.errors} rule errors and ${a.capped} games reached the turn cap.`);
+ for(const row of a.games){const game=new Game(project,rules,row.seed);game.restore(row.replay);}
+ parentPort.postMessage({ok:true,report:{...a,revision:await digest(project),repeated:true,replaysVerified:true}});
+ }
+}catch(error){parentPort.postMessage({ok:false,error:error.message});}
diff --git a/store/agents/game-master/test/ACCEPTANCE.md b/store/agents/game-master/test/ACCEPTANCE.md
new file mode 100644
index 000000000..984dc8391
--- /dev/null
+++ b/store/agents/game-master/test/ACCEPTANCE.md
@@ -0,0 +1,73 @@
+# Relay acceptance — 2026-09-20
+
+This rebuild gives a person an original tabletop game: authored mechanics, human legal choices,
+edits to components and rules, reproducible playtests and a physical/portable delivery. The old
+spectator arena and original logos/icons remain in the repository. These are authored acceptance
+briefs, not customer feedback, installed-agent prompt completions, or proof of fun/human balance.
+
+## Observed workflows
+
+- Actual Chrome input: private-hand turns, meaningful choices and outcomes, card text inspection,
+ locks, undo/redo, an original imported SVG face, source save and prior-edition history.
+- Running playtests retain their original rules when the draft changes. Applying a new edition
+ keeps the old offline game and replay. Concurrent browser/agent edits remain downloadable.
+- Simulations export the actual named policy, seeds, outcomes and action/state replays. Reopening a
+ replay checks its source revision and every legal choice; modified state is rejected.
+- Complete ZIP and offline HTML export reopen outside Harness and take real input. The 390px
+ browser layout has no horizontal document overflow. This is emulation, not an actual-phone test.
+- Invalid and nonterminating rules produce a recoverable error. The editor remains usable; a
+ repaired module starts a working game again. No hostile-code sandbox claim is made.
+- Setup and doctor use managed Node and pinned local build/browser tools, with no manual runtime
+ installation step. Package/source-conformance and the 421 CLI Store/check tests pass locally.
+
+## Three original briefs, six delivered editions
+
+| Game | Mechanics | Targeted revision | Approved material | Winning human-input path |
+| --- | --- | --- | --- | ---: |
+| Pocket Conservatory | Two-player hand drafting, public gardens, pair/variety scoring | Pair bonus 4 → 6; poppy name/color | Unchanged original component ids and remaining designs | 12 turns before / 12 after |
+| Signal Garden | Solo tile rotation and spatial connectivity | Rotation budget 24 → 18; entrance color | Center tile design and values | 11 turns before / 11 after |
+| Night Ferry | Two-player draw-or-bank, storms, finite voyages | Voyages 3 → 4; silk cargo 4 → 5 | Moon tea design and values | 21 turns before / 27 after |
+
+Each edition was exported, reopened and played through real browser buttons to its computed
+outcome. The spatial puzzle also has an actual losing path after exhausting the rotation budget.
+Rulebook edits from the reopened offline game remain source. Every edition runs 80 uniform-choice
+simulations twice with matching results, no rule errors or turn caps; package tests reconstruct
+every sampled replay. Uniform play frequently loses the puzzle, as expected from blind choices.
+
+`test/verify-delivery.py` uses independent Python stdlib ZIP/JSON/XML and Poppler PDF readers.
+It checks archive integrity, source equality, component and board dimensions, all physical copies,
+A4 page sizes, readable PDF text within page bounds, printed inventory and approved hashes.
+The six deliveries contain **14 PDFs / 36 pages**, visually reviewed through Poppler page images.
+A print review caught and corrected oversized puzzle cells relative to tiles; the independent
+reader now checks that printed ports can meet. Printed card values were enlarged and component
+art is clipped at its physical edge. Cards, rulebook, settings and executable rules were compared.
+
+Browser test evidence: `/private/tmp/relay-browser-final/report.json`. Final six-delivery evidence
+is under `/private/tmp/relay-acceptance-release/`; final print pages are under `/private/tmp/relay-print-release/`. All 36 pages were reviewed;
+34 stayed pixel-identical after clipping, and the two changed tile sheets were reviewed again. CI repeats package/browser/six-delivery/independent-reader tests.
+Store screenshots are captured from actual games, not mockups.
+A real materialized-workspace check caught silent CLI entry skips through symlinked temporary
+paths. Build/check/export/viewer entry checks now resolve real paths; the entry-point regression
+executes the actual build and rule-check commands through a workspace symlink.
+The shared browser-runner integration was corrected after CI caught an illegal `continue`;
+its Game Master dispatch and sibling-fetch/storage/module viewer regression then passed.
+
+## Reproduce
+
+```sh
+sh store/agents/game-master/toolchain/setup.sh
+node --test store/agents/game-master/test/*.test.mjs
+node store/agents/game-master/test/browser.mjs
+node store/agents/game-master/test/acceptance.mjs
+python3 store/agents/game-master/test/verify-delivery.py work/experience-evidence/relay-acceptance
+node store/agents/game-master/test/showcase.mjs work/experience-evidence/relay-acceptance
+```
+
+## Remaining scope
+
+No native tabletop-simulator import, network multiplayer, commercial-print certification, real
+printer/cutting trial, customer playtest or installed-agent prompt trial is claimed. Chrome on
+this Mac and the CI browser are covered; other browsers and physical phones are unmeasured.
+Print at actual size and check calibration. Optional backs are separate for gluing/sleeves, not
+an assumed duplex registration. The package enforces finite project/state/action/time limits;
+it does not promise arbitrary complexity, every possible seed, fun, fairness or human balance.
diff --git a/store/agents/game-master/test/acceptance.mjs b/store/agents/game-master/test/acceptance.mjs
new file mode 100644
index 000000000..01f21dada
--- /dev/null
+++ b/store/agents/game-master/test/acceptance.mjs
@@ -0,0 +1,24 @@
+import assert from 'node:assert/strict';import {mkdir,cp,mkdtemp,readFile,writeFile} from 'node:fs/promises';import {tmpdir} from 'node:os';import {join,resolve} from 'node:path';import {fileURLToPath,pathToFileURL} from 'node:url';
+import {fixtures,revise} from './fixtures.mjs';import {exportGame} from '../template/tools/export.mjs';import {Game,simulate} from '../template/studio/engine.mjs';import {digest,canonical} from '../template/studio/project.mjs';import {browserPath} from '../toolchain/browser.mjs';import {chromium} from '../toolchain/node_modules/playwright-core/index.mjs';
+const pkg=fileURLToPath(new URL('..',import.meta.url)),out=resolve(process.env.GAME_ACCEPTANCE_ROOT??'work/experience-evidence/relay-acceptance');await mkdir(out,{recursive:true});const root=await mkdtemp(join(tmpdir(),'relay-acceptance-'));await cp(join(pkg,'template'),root,{recursive:true});process.env.GAME_DSH_DIR=pkg;const browser=await chromium.launch({executablePath:await browserPath(),headless:true}),results=[];
+try{for(const initial of await fixtures())for(const [stage,p] of [['before',initial],['after',revise(initial)]]){
+ const folder=join(out,p.id,stage),delivery=await exportGame(root,folder,{project:p});const rules=await import('data:text/javascript;base64,'+Buffer.from(p.rules).toString('base64'));const model=new Game(p,rules,'route-proof');const context=await browser.newContext({viewport:{width:1512,height:1080},acceptDownloads:true});const page=await context.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(pathToFileURL(join(folder,'game.html')).href);await page.waitForFunction(()=>document.querySelector('#turn-title').textContent.length>0);
+ // Change the actual UI seed and keep the prior game. Every following move is a real button click.
+ await page.locator('#seed').fill('route-proof');const keep=page.waitForEvent('download');await page.locator('#restart').click();await(await keep).saveAs(join(folder,'initial-playtest.zip'));await page.waitForFunction(()=>document.querySelector('#notice').textContent.includes('fresh playtest'));
+ const click=async id=>{if(await page.locator('#curtain').isVisible())await page.locator('#reveal').click();const action=model.legal().find(a=>a.id===id);model.step(id);await page.locator('#actions button[data-move="'+id+'"]').click();await page.waitForFunction(n=>document.querySelector('#turn-count').textContent==='Turn '+n,model.actions.length);};
+ if(p.id==='signal-garden'){for(let i=0;i<9&&!model.outcome();i++)while(model.state.rotations[i]&&!model.outcome())await click('rotate-'+i);assert.deepEqual(model.outcome().winners,[0]);}
+ else{while(!model.outcome()){let id=model.legal()[0].id;if(p.id==='night-ferry')id=rules.bot(model.view().view,model.legal());await click(id);}}
+ assert.equal(await page.locator('#turn-title').textContent(),model.outcome().title);await page.screenshot({path:join(folder,'played.png'),fullPage:true});const replayDownload=page.waitForEvent('download');await page.locator('#save-replay').click();await(await replayDownload).saveAs(join(folder,'human-input-replay.json'));const replay=JSON.parse(await readFile(join(folder,'human-input-replay.json'),'utf8'));assert.equal(replay.state,canonical(model.state));assert.deepEqual(replay.actions,model.actions);
+
+ let lossTurns=null;
+ if(p.id==='signal-garden'){
+ const losing=new Game(p,rules,'route-proof'),kept=page.waitForEvent('download');await page.locator('#restart').click();await(await kept).saveAs(join(folder,'winning-playtest.zip'));await page.waitForFunction(()=>document.querySelector('#turn-count').textContent==='Turn 0');
+ while(!losing.outcome()){losing.step('rotate-0');await page.locator('#actions button[data-move="rotate-0"]').click();await page.waitForFunction(n=>document.querySelector('#turn-count').textContent==='Turn '+n,losing.actions.length);}
+ assert.deepEqual(losing.outcome().winners,[]);assert.equal(await page.locator('#turn-title').textContent(),losing.outcome().title);lossTurns=losing.actions.length;const saved=page.waitForEvent('download');await page.locator('#save-replay').click();await(await saved).saveAs(join(folder,'losing-path-replay.json'));await page.screenshot({path:join(folder,'losing-path.png'),fullPage:true});
+ }
+ // A browser revision remains authored source and can be kept without replacing the edition on the table.
+ await page.locator('[data-tab=rules]').click();const body=page.locator('[data-body="0"]');await body.fill(initial.rulebook[0].body+' Playtest note: review the physical kit with new players.');await body.blur();await page.locator('[data-tab=print]').click();const save=page.waitForEvent('download');await page.locator('#export-project').click();await(await save).saveAs(join(folder,'reopened-edited.relay.json'));assert.match(JSON.parse(await readFile(join(folder,'reopened-edited.relay.json'),'utf8')).rulebook[0].body,/Playtest note/);
+ const simulation=simulate(p,rules,{count:80}),repeated=simulate(p,rules,{count:80});assert.deepEqual(simulation,repeated);assert.equal(simulation.errors,0);await writeFile(join(folder,'simulation.json'),JSON.stringify(simulation,null,2));assert.deepEqual(errors,[]);
+ const approved=initial.components.filter(c=>c.locked);for(const c of approved)assert.deepEqual(c,p.components.find(x=>x.id===c.id));results.push({id:p.id,stage,title:p.title,folder,revision:await digest(p),approved:await Promise.all(approved.map(async c=>({id:c.id,sha256:await digest(c)}))),humanTurns:model.actions.length,lossTurns,outcome:model.outcome(),simulation:{games:simulation.count,completed:simulation.completed,errors:simulation.errors,capped:simulation.capped,wins:simulation.wins},files:delivery.files,errors});console.log('ok '+p.title+' '+stage+' · '+model.actions.length+' human-input turns');await context.close();
+ }}finally{await browser.close();}
+await writeFile(join(out,'acceptance.json'),JSON.stringify({scope:'Six authored game deliveries and targeted revisions, exercised through real browser inputs. Not a customer or installed-agent prompt trial.',results},null,2));console.log(out);
diff --git a/store/agents/game-master/test/browser.mjs b/store/agents/game-master/test/browser.mjs
new file mode 100644
index 000000000..def1c63ab
--- /dev/null
+++ b/store/agents/game-master/test/browser.mjs
@@ -0,0 +1,22 @@
+import assert from 'node:assert/strict';import {mkdtemp,mkdir,cp,readFile,writeFile,readdir} from 'node:fs/promises';import {tmpdir} from 'node:os';import {join,resolve} from 'node:path';import {fileURLToPath,pathToFileURL} from 'node:url';
+import {createGameViewer} from '../viewer/viewer.mjs';import {buildGame,readProject} from '../template/tools/build.mjs';import {browserPath} from '../toolchain/browser.mjs';import {chromium} from '../toolchain/node_modules/playwright-core/index.mjs';
+const pkg=fileURLToPath(new URL('..',import.meta.url)),out=resolve(process.env.GAME_QA_ROOT??'work/experience-evidence/relay-browser');await mkdir(out,{recursive:true});const root=await mkdtemp(join(tmpdir(),'relay-browser-'));await cp(join(pkg,'template'),root,{recursive:true});process.env.GAME_DSH_DIR=pkg;await buildGame(root);const server=await createGameViewer(root);await new Promise(r=>server.listen(0,'127.0.0.1',r));const browser=await chromium.launch({executablePath:await browserPath(),headless:true}),context=await browser.newContext({viewport:{width:1512,height:1080},acceptDownloads:true}),page=await context.newPage(),errors=[],checks=[];page.on('pageerror',e=>errors.push(e.message));page.on('console',m=>{if(m.type()==='error'&&!m.text().includes('409'))errors.push(m.text());});const origin='http://127.0.0.1:'+server.address().port;
+async function record(name,fn){await fn();checks.push({name,ok:true});console.log('ok '+name);}
+async function reveal(){await page.waitForFunction(()=>document.querySelector('#turn-title').textContent.length>0);if(await page.locator('#curtain').isVisible())await page.locator('#reveal').click();}
+async function download(click,name){const result=page.waitForEvent('download');await click();const d=await result;await d.saveAs(join(out,name));return join(out,name);}
+async function notice(text){await page.waitForFunction(t=>document.querySelector('#notice').textContent.includes(t),text);}
+try{
+ await page.goto(origin);await page.waitForFunction(()=>document.querySelector('#source-state').textContent.includes('Workspace source'));
+ await record('private view curtain and real human legal choices',async()=>{assert.equal(await page.locator('#curtain').isVisible(),true);assert.equal(await page.locator('#actions').evaluate(e=>e.inert),true);await reveal();await page.locator('#zones details').first().locator('summary').click();assert.ok((await page.locator('#zones details').first().textContent()).includes('A little'));await page.locator('#actions button').first().click();await page.waitForFunction(()=>document.querySelector('#turn-count').textContent==='Turn 1');assert.equal(await page.locator('#curtain').isVisible(),true);await reveal();await page.locator('#actions button').first().click();await page.waitForFunction(()=>document.querySelector('#turn-count').textContent==='Turn 2');await reveal();await page.screenshot({path:join(out,'play.png'),fullPage:true});});
+ await record('component changes, locks, undo and redo preserve the playing edition',async()=>{await page.locator('#component-form input[name=name]').fill('Silver fern revised');await page.locator('#component-form input[name=name]').blur();assert.equal(await page.locator('#edition-notice').isVisible(),true);await page.locator('#undo-edit').click();assert.equal(await page.locator('#component-form input[name=name]').inputValue(),'Silver fern');await page.locator('#redo-edit').click();assert.equal(await page.locator('#component-form input[name=name]').inputValue(),'Silver fern revised');await page.locator('#lock-component').click();assert.equal(await page.locator('#component-form input[name=name]').isDisabled(),true);await page.locator('#lock-component').click();});
+ await record('original SVG face import stays editable and embedded',async()=>{const artwork='<svg xmlns="http://www.w3.org/2000/svg" width="630" height="880" viewBox="0 0 630 880"><rect width="630" height="880" fill="#183e42"/><circle cx="315" cy="380" r="210" fill="#d8c992"/><path d="M315 580V200M315 280L200 200M315 350L440 270M315 430L180 340" stroke="#183e42" stroke-width="20" fill="none"/><text x="45" y="75" fill="#f9edcd" font-size="40">SILVER FERN</text><text x="45" y="800" fill="#f9edcd" font-size="28">2 points · leaf</text></svg>';await writeFile(join(out,'original-face.svg'),artwork);await page.locator('#face-file').setInputFiles(join(out,'original-face.svg'));await page.locator('#reset-face').waitFor();assert.equal(await page.locator('#component-preview image').count(),1);});
+ await record('applying an edition keeps the previous playable game and replay',async()=>{await download(()=>page.locator('#apply-edition').click(),'previous-playtest.zip');await notice('Previous game and replay');await reveal();assert.equal(await page.locator('#turn-count').textContent(),'Turn 0');await page.locator('#save-source').click();await notice('Source saved');const p=await readProject(root);assert.equal(p.components[0].name,'Silver fern revised');assert.match(p.components[0].face,/^data:image\/svg/);assert.ok((await readdir(join(root,'.harness/history'))).length>0);});
+ await record('concurrent source changes keep both editions',async()=>{await page.locator('#component-form input[name=quantity]').fill('5');await page.locator('#component-form input[name=quantity]').blur();const raw=JSON.parse(await readFile(join(root,'game/project.json'),'utf8'));raw.title='Agent revision';await writeFile(join(root,'game/project.json'),JSON.stringify(raw));await page.locator('#save-source').click();await notice('changed the source');assert.equal(await page.locator('#source-notice').isVisible(),true);await download(()=>page.locator('#keep-draft').click(),'browser-draft.relay.json');await download(()=>page.locator('#load-source').click(),'before-source.relay.json');assert.equal((await readProject(root)).title,'Agent revision');await download(()=>page.locator('#apply-edition').click(),'before-agent.zip');await notice('Previous game and replay');await reveal();assert.equal(await page.locator('#game-title').textContent(),'Agent revision');});
+ await record('simulation exports contain actual policy outcomes and replays',async()=>{await page.locator('#simulation-count').fill('20');await page.locator('#simulate').click();await page.locator('#save-simulation').waitFor();await download(()=>page.locator('#save-simulation').click(),'simulation.json');const data=JSON.parse(await readFile(join(out,'simulation.json'),'utf8'));assert.equal(data.completed,20);assert.equal(data.errors,0);assert.equal(data.games[0].replay.actions.length,12);assert.match(data.scope,/do not establish/);});
+ await record('replay verifies actions, rejects tampering and survives reload',async()=>{await page.locator('#actions button').first().click();await page.waitForFunction(()=>document.querySelector('#turn-count').textContent==='Turn 1');await reveal();await download(()=>page.locator('#save-replay').click(),'replay.json');const replay=JSON.parse(await readFile(join(out,'replay.json'),'utf8'));const bad={...replay,state:'{}'};await writeFile(join(out,'bad-replay.json'),JSON.stringify(bad));await page.locator('#replay-file').setInputFiles(join(out,'bad-replay.json'));await notice('does not match');assert.equal(await page.locator('#turn-count').textContent(),'Turn 1');await page.reload();await page.waitForFunction(()=>document.querySelector('#turn-count').textContent==='Turn 1');await reveal();});
+ await record('complete kit and offline game reopen with real input',async()=>{await download(()=>page.locator('#export-kit').click(),'complete-kit.zip');await page.locator('[data-tab=print]').click();await download(()=>page.locator('#export-html').click(),'offline.html');await page.goto(pathToFileURL(join(out,'offline.html')).href);await reveal();await page.locator('#actions button').first().click();await page.waitForFunction(()=>document.querySelector('#turn-count').textContent==='Turn 1');assert.equal(await page.locator('#save-source').isDisabled(),true);await page.setViewportSize({width:390,height:844});await reveal();await page.screenshot({path:join(out,'mobile.png'),fullPage:true});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);});
+ await record('invalid rule modules keep source editable and a new module recovers',async()=>{await page.setViewportSize({width:1512,height:1080});await page.locator('#edit-rules').click();const old=await page.locator('#rules-code').inputValue();await page.locator('#rules-code').fill('export const incomplete = true;');await page.locator('#editor-apply').click();await download(()=>page.locator('#apply-edition').click(),'before-invalid.zip');await notice('Rules must export');await page.locator('#edit-rules').click();await page.locator('#rules-code').fill(old);await page.locator('#editor-apply').click();await download(()=>page.locator('#apply-edition').click(),'before-recovery.zip');await notice('Previous game and replay');await reveal();assert.equal(await page.locator('#actions button').count(),6);});
+
+ await record('a nonterminating module stops without freezing the editor',async()=>{await page.locator('#edit-rules').click();const old=await page.locator('#rules-code').inputValue();await page.locator('#rules-code').fill('export function initial(){while(true){}}; export function legal(){}; export function apply(){}; export function observe(){}; export function outcome(){}; export function validate(){}');await page.locator('#editor-apply').click();await download(()=>page.locator('#apply-edition').click(),'before-timeout.zip');await notice('exceeded the time limit');await page.locator('#edit-rules').click();await page.locator('#rules-code').fill(old);await page.locator('#editor-apply').click();await download(()=>page.locator('#apply-edition').click(),'before-timeout-recovery.zip');await notice('Previous game and replay');await reveal();assert.equal(await page.locator('#actions button').count(),6);});
+ await page.screenshot({path:join(out,'final.png'),fullPage:true});assert.deepEqual(errors,[]);await writeFile(join(out,'report.json'),JSON.stringify({checks,errors},null,2));console.log(JSON.stringify({out,checks:checks.length,errors}));
+}finally{await browser.close();server.closeAllConnections();await new Promise(r=>server.close(r));}
diff --git a/store/agents/game-master/test/engine.test.mjs b/store/agents/game-master/test/engine.test.mjs
new file mode 100644
index 000000000..59320ac3a
--- /dev/null
+++ b/store/agents/game-master/test/engine.test.mjs
@@ -0,0 +1,13 @@
+import {test} from 'node:test';import assert from 'node:assert/strict';
+import {fixtures,conservatory,signalGarden,nightFerry,revise} from './fixtures.mjs';
+import {Game,simulate} from '../template/studio/engine.mjs';
+import {validateProject,clone,canonical,history,digest} from '../template/studio/project.mjs';
+import {componentSVG,sheets,kitFiles} from '../template/studio/formats.mjs';
+const moduleFor=p=>import('data:text/javascript;base64,'+Buffer.from(p.rules).toString('base64'));
+for(const p of await fixtures())test(p.title+' repeats, conserves game state and reopens every recorded playtest',async()=>{const rules=await moduleFor(p),a=simulate(p,rules,{count:80}),b=simulate(p,rules,{count:80});assert.deepEqual(a,b);assert.equal(a.completed,80);assert.equal(a.errors,0);assert.equal(a.capped,0);for(const row of a.games){const replay=new Game(p,rules,row.seed);replay.restore(row.replay);assert.equal(canonical(replay.state),row.replay.state);}const q=revise(p);assert.notEqual(await digest(p),await digest(q));for(const c of p.components.filter(c=>c.locked))assert.deepEqual(q.components.find(x=>x.id===c.id),c);});
+test('only legal choices transition; undo and replay recover exact states',async()=>{const p=await conservatory(),rules=await moduleFor(p),g=new Game(p,rules),state=g.state;assert.throws(()=>g.step('invented'),/not legal/);assert.deepEqual(g.state,state);g.step(g.legal()[0].id);const replay=g.replay();g.undo();assert.deepEqual(g.state,state);g.restore(replay);assert.equal(canonical(g.state),replay.state);replay.state='{}';assert.throws(()=>new Game(p,rules,replay.seed).restore(replay),/does not match/);});
+test('private observation contains only current hand and public gardens',async()=>{const p=await conservatory(),rules=await moduleFor(p),g=new Game(p,rules);const v=g.view();assert.equal(v.view.private,true);assert.equal(v.view.zones[0].items.length,g.state.hands[0].length);assert.equal(v.view.zones.flatMap(z=>z.items).length,g.state.hands[0].length);const seen=new Set();const bot={...rules,bot(view,actions){assert.equal(view.hands,undefined);seen.add(view.title);return actions[0].id;}};simulate(p,bot,{count:2,policy:'authored'});assert.ok(seen.size>1);});
+test('the spatial puzzle has reachable win and loss states from legal human choices',async()=>{const p=signalGarden(),rules=await moduleFor(p),g=new Game(p,rules,'route-proof');for(let i=0;i<9&&!g.outcome();i++)while(g.state.rotations[i]&&!g.outcome())g.step('rotate-'+i);assert.deepEqual(g.outcome().winners,[0]);const lose=new Game(p,rules,'route-proof');while(!lose.outcome())lose.step('rotate-0');assert.deepEqual(lose.outcome().winners,[]);});
+test('push-your-luck docking banks cargo and storms lose only the active voyage',async()=>{const p=nightFerry(),rules=await moduleFor(p),g=new Game(p,rules,'cargo-proof');while(g.state.cargo===0)g.step('draw');const who=g.state.player,cargo=g.state.cargo;g.step('dock');assert.equal(g.state.scores[who],cargo);const old=g.state.scores;while(g.state.player!==who)g.step('draw');assert.deepEqual(g.state.scores,old);});
+test('dead ends, mutated inputs, invalid output and action no-ops are caught',async()=>{const p=await conservatory(),rules=await moduleFor(p);assert.throws(()=>new Game(p,{...rules,legal:()=>[]}),/Dead end/);const mut=new Game(p,{...rules,apply:s=>{s.player=1;return s;}});assert.throws(()=>mut.step(mut.legal()[0].id),/read only|readonly/);const noop=new Game(p,{...rules,apply:s=>clone(s)});assert.throws(()=>noop.step(noop.legal()[0].id),/must change/);assert.throws(()=>new Game(p,{...rules,initial:()=>({player:0,bad:Infinity})}),/non-finite/);});
+test('source schema, edition history and printable inventory reject damaged input',async()=>{const p=await conservatory();for(const mutate of [q=>q.components[0].quantity=0,q=>q.components.push(q.components[0]),q=>q.settings[0].value=Infinity,q=>q.components[0].color='url(https://bad)',q=>q.components[0].face='javascript:bad']){const q=clone(p);mutate(q);assert.throws(()=>validateProject(q));}const h=history(p);h.push(revise(p));assert.deepEqual(h.undo(),p);assert.deepEqual(h.redo(),revise(p));const pages=sheets(p);assert.equal(pages.flat().length,p.components.reduce((n,c)=>n+c.quantity,0));for(const i of pages.flat()){assert.ok(i.x>=10&&i.y>=10&&i.x+i.width<=200&&i.y+i.height<=287);}const files=kitFiles(p,'<!doctype html>');assert.equal(files['source/rules.mjs'],p.rules);assert.deepEqual(JSON.parse(files['project.relay.json']),p);const custom=clone(p.components[0]);custom.face='data:image/svg+xml;base64,'+Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"><text>Original artwork</text></svg>').toString('base64');assert.match(componentSVG(custom),/<image/);assert.doesNotMatch(componentSVG(custom),/<text>Original artwork/);});
diff --git a/store/agents/game-master/test/entrypoints.test.mjs b/store/agents/game-master/test/entrypoints.test.mjs
new file mode 100644
index 000000000..ac272d9f6
--- /dev/null
+++ b/store/agents/game-master/test/entrypoints.test.mjs
@@ -0,0 +1,3 @@
+import {test} from 'node:test';import assert from 'node:assert/strict';import {mkdtemp,cp,symlink,readFile,rm} from 'node:fs/promises';import {join} from 'node:path';import {tmpdir} from 'node:os';import {fileURLToPath} from 'node:url';import {execFileSync} from 'node:child_process';
+const pkg=fileURLToPath(new URL('..',import.meta.url));
+test('real command entry points run through a symlinked workspace path',async()=>{const dir=await mkdtemp(join(tmpdir(),'relay-entry-')),root=join(dir,'real'),link=join(dir,'shortcut');await cp(join(pkg,'template'),root,{recursive:true});await symlink(root,link,'dir');const env={...process.env,GAME_DSH_DIR:pkg};try{const built=JSON.parse(execFileSync(process.execPath,[join(link,'tools/build.mjs')],{cwd:link,env,encoding:'utf8'}));assert.equal(built.title,'Pocket Conservatory');const checked=JSON.parse(execFileSync(process.execPath,[join(link,'tools/check.mjs'),'--seeds','2'],{cwd:link,env,encoding:'utf8'}));assert.equal(checked.completed,2);assert.equal(checked.repeated,true);assert.equal(JSON.parse(await readFile(join(root,'.harness/game-check.json'),'utf8')).games.length,2);}finally{await rm(dir,{recursive:true,force:true});}});
diff --git a/store/agents/game-master/test/fixtures.mjs b/store/agents/game-master/test/fixtures.mjs
new file mode 100644
index 000000000..2ba9f5bf8
--- /dev/null
+++ b/store/agents/game-master/test/fixtures.mjs
@@ -0,0 +1,34 @@
+import {readFile} from 'node:fs/promises';
+import {validateProject,clone} from '../template/studio/project.mjs';
+const root=new URL('../template/game/',import.meta.url);
+export async function conservatory(){return validateProject({...JSON.parse(await readFile(new URL('project.json',root),'utf8')),rules:await readFile(new URL('rules.mjs',root),'utf8')});}
+export function signalGarden(){
+ const actual=['EW','EW','SW','ES','EW','NW','NE','EW','EW'];
+ const p={spec:1,id:'signal-garden',title:'Signal Garden',subtitle:'Turn nine tiles into one unbroken path. A solo tabletop routing puzzle.',players:1,settings:[{id:'turn_limit',label:'Rotation budget','min':1,'max':60,'step':1,'value':24}],components:actual.map((port,i)=>({id:'tile-'+i,name:String(i+1),body:'',kind:'tile',widthMm:45,heightMm:45,quantity:1,color:i%2?'#a1ad87':'#536f62',ink:'#fff5d4',symbol:'',values:{ports:port},locked:i===4})),boards:[{id:'garden',name:'Signal Garden · west entrance / east exit',widthMm:135,heightMm:147,cols:3,rows:3,cells:Array.from({length:9},(_,i)=>({label:String(i+1),color:'#e3e7d6'}))}],rulebook:[{heading:'Connect the garden','body':'Place the nine numbered tiles on the matching board cells. The entrance is west of tile 1; the exit is east of tile 9. Rotate each tile clockwise any number of quarter-turns to choose a starting puzzle. Begin with the rotation budget shown below.'},{heading:'One decision at a time','body':'On each turn, rotate any tile 90 degrees clockwise and spend one rotation. Water can flow only when the ports on neighboring tiles face each other. You win as soon as a connected path reaches from the west entrance to the east exit. You lose when the rotation budget reaches zero with no connected path. The digital edition rotates each tile by a seeded number of quarter-turns at setup.'},{heading:'Physical edition','body':'Print the numbered tiles and board at actual size. Keep tiles in their numbered cells; rotate them in place. Mark remaining rotations with a pencil. To create a different route or larger game, edit the tile ports and the authored rules; this edition uses a 3 × 3 board.'}],rules:`
+const dirs=['N','E','S','W'],vectors=[[0,-1],[1,0],[0,1],[-1,0]];
+const ports=(s,p,i)=>[...p.components[i].values.ports].map(d=>(dirs.indexOf(d)+s.rotations[i])%4);
+export function connected(s,p){const first=ports(s,p,0);if(!first.includes(3))return false;const seen=new Set([0]),todo=[0];while(todo.length){const i=todo.shift();if(i===8&&ports(s,p,i).includes(1))return true;for(const d of ports(s,p,i)){const [dx,dy]=vectors[d],x=i%3+dx,y=Math.floor(i/3)+dy,j=y*3+x;if(x>=0&&x<3&&y>=0&&y<3&&!seen.has(j)&&ports(s,p,j).includes((d+2)%4)){seen.add(j);todo.push(j);}}}return false;}
+export function initial(p,ctx){const r=ctx.random('tile-rotation');return{player:0,rotations:p.components.map(()=>Math.floor(r()*4)),remaining:p.settings.find(s=>s.id==='turn_limit').value};}
+export function outcome(s,p){return connected(s,p)?{title:'The garden is connected',winners:[0]}:s.remaining===0?{title:'The water has run out',winners:[]}:null;}
+export function legal(s,p){return outcome(s,p)?[]:p.components.map((c,i)=>({id:'rotate-'+i,label:'Rotate tile '+(i+1)+' ↻',index:i}));}
+export function apply(s,a){const n=JSON.parse(JSON.stringify(s));n.rotations[a.index]=(n.rotations[a.index]+1)%4;n.remaining--;return n;}
+export function observe(s,player,p){return{title:'Find an unbroken path',message:'Connect the west of tile 1 to the east of tile 9. Each click rotates a tile clockwise.',scores:[{label:'Rotations left',value:s.remaining}],zones:[{id:'garden',label:'Nine tiles · one connected garden',board:'garden',items:p.components.map((c,i)=>({key:c.id,component:c.id,cell:i,rotation:s.rotations[i]*90,action:'rotate-'+i}))}]};}
+export function validate(s,p){return p.players===1&&p.components.length===9&&s.rotations.length===9&&s.rotations.every(n=>Number.isInteger(n)&&n>=0&&n<4)&&Number.isInteger(s.remaining)&&s.remaining>=0||'Use nine tiles, one player and a nonnegative integer rotation budget.';}
+export function bot(view,actions){return actions[0].id;}
+`};return validateProject(p);
+}
+export function nightFerry(){return validateProject({spec:1,id:'night-ferry',title:'Night Ferry',subtitle:'Carry a little more, or come safely home. A push-your-luck game for two.',players:2,settings:[{id:'voyages',label:'Voyages per player',min:1,max:8,step:1,value:3},{id:'storm_limit',label:'Storms before cargo is lost',min:1,max:4,step:1,value:2}],components:[{id:'tea',name:'Moon tea',body:'Add the printed cargo value to this voyage.',kind:'card',widthMm:63,heightMm:88,quantity:6,color:'#48645c',ink:'#fff4df',symbol:'☾',values:{cargo:2,storm:0},locked:true},{id:'silk',name:'Ember silk',body:'Add the printed cargo value to this voyage.',kind:'card',widthMm:63,heightMm:88,quantity:4,color:'#9b5445',ink:'#fff4df',symbol:'✦',values:{cargo:4,storm:0},locked:false},{id:'storm',name:'Crosswind',body:'Add one storm. At the storm limit, this voyage loses all unbanked cargo.',kind:'card',widthMm:63,heightMm:88,quantity:5,color:'#354b6a',ink:'#fff4df',symbol:'≈',values:{cargo:0,storm:1},locked:false}],boards:[],rulebook:[{heading:'On the river','body':'Two ferry captains take turns carrying cargo along a night river. Each player makes the number of voyages listed in the rule settings. The highest banked cargo value wins; tied captains share the win.'},{heading:'Set up each voyage','body':'Shuffle the complete deck, including all cargo and storm cards. The active captain starts with no unbanked cargo or storms. Begin with Player 1, alternating captains after every voyage. Reshuffle all cards between voyages.'},{heading:'Draw or dock','body':'Draw reveals the next card: add its cargo value and storm value to the current voyage. If your storms reach the storm limit, lose this voyage’s unbanked cargo and end the voyage. Dock ends the voyage and adds its unbanked cargo to your banked score. You may dock before drawing. If the deck runs out after a safe draw, automatically bank the cargo and end the voyage.'},{heading:'Keep the score','body':'Record each captain’s banked cargo after every voyage. After both have made all their voyages, compare totals. The digital game uses a seeded shuffle for each voyage so a replay can be checked; physical play uses a normally shuffled deck.'}],rules:`
+const setting=(p,id)=>p.settings.find(x=>x.id===id).value;
+const comp=(p,id)=>p.components.find(c=>c.id===id);
+function fresh(p,ctx){return ctx.shuffle(p.components.flatMap(c=>Array(c.quantity).fill(c.id)),'voyage');}
+export function initial(p,ctx){return{player:0,round:1,scores:[0,0],cargo:0,storms:0,drawn:[],deck:fresh(p,ctx),done:false,last:'Choose whether to draw or dock.'};}
+export function legal(s){return s.done?[]:[{id:'draw',label:'Draw · carry a little more'},{id:'dock',label:'Dock · bank '+s.cargo}];}
+function finish(n,p,ctx,bank){if(bank)n.scores[n.player]+=n.cargo;const old=n.player;n.player=1-old;if(old===1)n.round++;if(n.round>setting(p,'voyages')){n.done=true;return;}n.cargo=0;n.storms=0;n.drawn=[];n.deck=fresh(p,ctx);}
+export function apply(s,a,p,ctx){const n=JSON.parse(JSON.stringify(s));if(a.id==='dock'){n.last='Player '+(s.player+1)+' docked with '+s.cargo+' cargo.';finish(n,p,ctx,true);}else{const id=n.deck.shift(),c=comp(p,id);n.drawn.push(id);n.cargo+=c.values.cargo;n.storms+=c.values.storm;if(n.storms>=setting(p,'storm_limit')){n.last='Player '+(s.player+1)+' lost the unbanked cargo in a storm.';finish(n,p,ctx,false);}else if(!n.deck.length){n.last='The deck is empty; cargo was banked.';finish(n,p,ctx,true);}else n.last='You drew '+c.name+'.';}return n;}
+export function outcome(s){if(!s.done)return null;const high=Math.max(...s.scores),winners=s.scores.flatMap((n,i)=>n===high?[i]:[]);return{title:winners.length===2?'The captains share the river':'Captain '+(winners[0]+1)+' wins',winners,scores:s.scores};}
+export function observe(s,who,p){return{title:'Voyage '+Math.min(s.round,setting(p,'voyages'))+' · Captain '+(who+1),message:s.last,scores:[...s.scores.map((n,i)=>({label:'Captain '+(i+1)+' bank',value:n})),{label:'On the ferry',value:s.cargo},{label:'Storms',value:s.storms}],zones:[{id:'cargo',label:'This voyage · revealed cards',items:s.drawn.map((id,i)=>({key:'draw-'+i,component:id}))}]};}
+export function validate(s,p){if(p.players!==2||!Number.isInteger(s.round)||s.round<1||s.cargo<0||s.storms<0||s.scores.some(n=>n<0))return'Invalid voyage state.';const used=[...s.deck,...s.drawn];for(const c of p.components)if(used.filter(id=>id===c.id).length!==c.quantity)return'Cards disappeared from the deck.';return true;}
+export function bot(view,actions){return view.scores.find(x=>x.label==='On the ferry').value>=6?'dock':'draw';}
+`});}
+export async function fixtures(){return[await conservatory(),signalGarden(),nightFerry()];}
+export function revise(p){const n=clone(p);if(p.id==='pocket-conservatory'){n.settings.find(s=>s.id==='pair_bonus').value=6;n.components.find(c=>c.id==='poppy').name='Golden poppy';n.components.find(c=>c.id==='poppy').color='#a8762d';}else if(p.id==='signal-garden'){n.settings[0].value=18;n.components[0].color='#276d7a';}else{n.settings.find(s=>s.id==='voyages').value=4;n.components.find(c=>c.id==='silk').values.cargo=5;n.components.find(c=>c.id==='silk').name='Festival silk';}return validateProject(n);}
diff --git a/store/agents/game-master/test/showcase.mjs b/store/agents/game-master/test/showcase.mjs
new file mode 100644
index 000000000..972eb2639
--- /dev/null
+++ b/store/agents/game-master/test/showcase.mjs
@@ -0,0 +1,2 @@
+import {mkdir} from 'node:fs/promises';import {join,resolve} from 'node:path';import {fileURLToPath,pathToFileURL} from 'node:url';import {chromium} from '../toolchain/node_modules/playwright-core/index.mjs';import {browserPath} from '../toolchain/browser.mjs';
+const input=resolve(process.argv[2]??'work/experience-evidence/relay-acceptance'),out=fileURLToPath(new URL('../../../showcase/game-master/',import.meta.url));await mkdir(out,{recursive:true});const browser=await chromium.launch({executablePath:await browserPath(),headless:true});try{for(const [id,name] of [['pocket-conservatory','starter'],['signal-garden','signal-garden'],['night-ferry','night-ferry']]){const context=await browser.newContext({viewport:{width:1512,height:1080},deviceScaleFactor:1}),page=await context.newPage();await page.goto(pathToFileURL(join(input,id,'after','game.html')).href);await page.waitForFunction(()=>document.querySelector('#turn-title').textContent.length>0);for(let n=1;n<=2;n++){if(await page.locator('#curtain').isVisible())await page.locator('#reveal').click();await page.locator('#actions button').first().click();await page.waitForFunction(n=>document.querySelector('#turn-count').textContent==='Turn '+n,n);}if(id==='night-ferry'){for(let n=3;n<=12;n++){await page.locator('#actions button[data-move=draw]').click();await page.waitForFunction(n=>document.querySelector('#turn-count').textContent==='Turn '+n,n);if(await page.locator('#zones .game-piece').count()>=2)break;}}if(await page.locator('#curtain').isVisible())await page.locator('#reveal').click();await page.evaluate(()=>scrollTo(0,0));await page.screenshot({path:join(out,name+'.jpg'),type:'jpeg',quality:90,fullPage:false});await context.close();}}finally{await browser.close();}console.log(out);
diff --git a/store/agents/game-master/test/toolchain.test.mjs b/store/agents/game-master/test/toolchain.test.mjs
index 13d000986..24e5bcfc7 100644
--- a/store/agents/game-master/test/toolchain.test.mjs
+++ b/store/agents/game-master/test/toolchain.test.mjs
@@ -28,8 +28,10 @@ test('every script the manifest names is in the folder and executable', () => {
}
})
-test('setup installs nothing and succeeds quietly', () => {
- assert.deepEqual(run(manifest.toolchain.setup), { code: 0, stdout: '', stderr: '' })
+test('setup pins local tools and resolves its managed Node runtime', () => {
+ const pkg=JSON.parse(readFileSync(join(here,'toolchain/package.json'),'utf8'));
+ assert.deepEqual(pkg.dependencies,{'esbuild':'0.27.2','playwright-core':'1.63.0'});
+ assert.match(readFileSync(join(here,'toolchain/install.sh'),'utf8'),/harness_node 20/);
})
test('doctor says ok when sh is on PATH', () => {
@@ -44,7 +46,7 @@ test('init lays out a workspace and seeds a not-ready verdict', () => {
})
test('the manifest names a viewer package and an HTML artifact', () => {
- assert.equal(manifest.viewer.use, 'autonomous/web-viewer')
+ assert.equal(manifest.viewer.command, 'toolchain/viewer.sh')
assert.deepEqual(manifest.viewer.artifactExtensions, ['.html'])
})
@@ -61,6 +63,7 @@ test('seed-verdict reflects whether a game exists', () => {
test('the manifest routes the actual nested artifact through the shared viewer', () => {
- assert.equal(manifest.viewer.url, 'http://127.0.0.1:${port}/?file=${artifact}')
+ assert.equal(manifest.viewer.url, 'http://127.0.0.1:${port}/')
+ assert.deepEqual(manifest.agent.env,{GAME_DSH_DIR:'${dsh}'})
assert.ok(manifest.workspace.marker.endsWith('/index.html'))
})
diff --git a/store/agents/game-master/test/verify-delivery.py b/store/agents/game-master/test/verify-delivery.py
new file mode 100644
index 000000000..e3619a6c0
--- /dev/null
+++ b/store/agents/game-master/test/verify-delivery.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python3
+"""Independent stdlib ZIP/XML/JSON plus Poppler PDF verification; no Relay imports."""
+import json,sys,re,hashlib,subprocess,zipfile
+from pathlib import Path
+from xml.etree import ElementTree as ET
+root=Path(sys.argv[1]);report=json.loads((root/'acceptance.json').read_text());results=[]
+ns={'s':'http://www.w3.org/2000/svg'}
+def canonical(x): return json.dumps(x,sort_keys=True,separators=(',',':'),ensure_ascii=False)
+def fail(ok,message):
+ if not ok: raise AssertionError(message)
+for row in report['results']:
+ folder=Path(row['folder']);project=json.loads((folder/'project.relay.json').read_text());source=json.loads((folder/'source/project.json').read_text());fail(project['rules']==(folder/'source/rules.mjs').read_text(),'Rules source changed');fail({k:v for k,v in project.items() if k!='rules'}==source,'Bundled source differs')
+ with zipfile.ZipFile(folder/'game-kit.zip') as archive:
+ fail(archive.testzip() is None,'ZIP CRC failure')
+ for name in archive.namelist(): fail(not Path(name).is_absolute() and '..' not in Path(name).parts,'Unsafe archive path')
+ fail(archive.read('source/rules.mjs').decode()==project['rules'],'ZIP rules differ')
+ for name in ['game.html','print/components.pdf','print/rulebook.pdf','project.relay.json']: fail(archive.read(name)==(folder/name).read_bytes(),'ZIP delivery differs: '+name)
+ svg_count=0;copy_count=0
+ for c in project['components']:
+ svg=ET.parse(folder/'components'/f"{c['id']}.svg").getroot();fail(svg.attrib['width']==f"{c['widthMm']}mm" and svg.attrib['height']==f"{c['heightMm']}mm",'Component physical size differs');svg_count+=1
+ for path in sorted((folder/'print').glob('sheet-*.svg')):
+ svg=ET.parse(path).getroot();fail(svg.attrib['width']=='210mm' and svg.attrib['height']=='297mm','Print sheet is not A4')
+ for group in svg.findall('s:g',ns):
+ if 'transform' not in group.attrib: continue
+ m=re.fullmatch(r'translate\(([\d.]+) ([\d.]+)\)',group.attrib['transform']);fail(m is not None,'Unknown component placement');x,y=map(float,m.groups());rect=group.find('s:rect',ns);w,h=float(rect.attrib['width']),float(rect.attrib['height']);fail(x>=10 and y>=10 and x+w<=200.001 and y+h<=287.001,'Component extends outside page');copy_count+=1
+ fail(copy_count==sum(c['quantity'] for c in project['components']),'Printed inventory differs')
+ if project['id']=='signal-garden':
+ b=project['boards'][0]
+ for c in project['components']:fail(b['widthMm']/b['cols']==c['widthMm'] and (b['heightMm']-12)/b['rows']==c['heightMm'],'Printed tile ports cannot meet across board cells')
+ for b in project['boards']:
+ svg=ET.parse(folder/'boards'/f"{b['id']}.svg").getroot();fail(svg.attrib['width']==f"{b['widthMm']}mm" and svg.attrib['height']==f"{b['heightMm']}mm",'Board size differs')
+ pdfs=[]
+ for path in sorted(folder.rglob('*.pdf')):
+ info=subprocess.check_output(['pdfinfo',str(path)],text=True);pages=int(re.search(r'Pages:\s+(\d+)',info).group(1));fail(pages>0,'Empty PDF');box=subprocess.check_output(['pdftotext','-bbox-layout',str(path),'-']);doc=ET.fromstring(box)
+ words=0
+ for page in doc.iter():
+ if page.tag.split('}')[-1]!='page':continue
+ width,height=float(page.attrib['width']),float(page.attrib['height']);fail(abs(width-595.28)<1 and abs(height-841.89)<1 or abs(width-841.89)<1 and abs(height-595.28)<1,'Unexpected PDF paper size')
+ for word in page.iter():
+ if word.tag.split('}')[-1]!='word':continue
+ words+=1;fail(float(word.attrib['xMin'])>=-.1 and float(word.attrib['yMin'])>=-.1 and float(word.attrib['xMax'])<=width+.1 and float(word.attrib['yMax'])<=height+.1,'PDF text outside page')
+ fail(words>0,'PDF has no readable text');plain=subprocess.check_output(['pdftotext','-layout',str(path),'-'],text=True);flat=' '.join(plain.split())
+ if path.name=='components.pdf':
+ for c in project['components']:fail(c['name'] in flat,'Missing printed component '+c['name'])
+ if path.name=='rulebook.pdf':
+ for section in project['rulebook']:fail(section['heading'] in flat,'Missing rulebook section')
+ for c in project['components']:fail(c['name'] in flat,'Missing inventory row')
+ pdfs.append({'file':str(path.relative_to(folder)),'pages':pages,'words':words})
+ replay=json.loads((folder/'human-input-replay.json').read_text());fail(replay['revision']==row['revision'],'Replay revision differs');fail(len(replay['actions'])==row['humanTurns'],'Human-input count differs');fail(json.loads(replay['state'])['player']<project['players'],'Invalid final player')
+ for approved in row['approved']:
+ c=next(c for c in project['components'] if c['id']==approved['id']);fail(hashlib.sha256(canonical(c).encode()).hexdigest()==approved['sha256'],'Approved component changed')
+ results.append({'id':row['id'],'stage':row['stage'],'componentDesigns':svg_count,'physicalCopies':copy_count,'pdfs':pdfs,'verified':True})
+for game,edited in [('pocket-conservatory','poppy'),('signal-garden','tile-0'),('night-ferry','silk')]:
+ before=json.loads((root/game/'before/project.relay.json').read_text());after=json.loads((root/game/'after/project.relay.json').read_text())
+ for c in before['components']:
+ if c['id']!=edited:fail(c==next(x for x in after['components'] if x['id']==c['id']),'A targeted revision changed an unrelated component')
+(root/'independent-verification.json').write_text(json.dumps({'reader':'Python stdlib ZIP/XML/JSON and Poppler pdfinfo/pdftotext','scope':'File integrity, source retention, print inventory/dimensions, PDF text bounds and approved component hashes. Does not measure fun or human balance.','results':results},indent=2)+'\n');print(json.dumps({'deliveries':len(results),'pdfs':sum(len(r['pdfs']) for r in results),'pages':sum(p['pages'] for r in results for p in r['pdfs']),'verified':True}))
diff --git a/store/agents/game-master/test/viewer.test.mjs b/store/agents/game-master/test/viewer.test.mjs
new file mode 100644
index 000000000..c03a01425
--- /dev/null
+++ b/store/agents/game-master/test/viewer.test.mjs
@@ -0,0 +1,14 @@
+import {test} from 'node:test';import {get as httpGet} from 'node:http';import assert from 'node:assert/strict';
+import {mkdtemp,cp,rm,readFile,readdir,writeFile,mkdir} from 'node:fs/promises';import {tmpdir} from 'node:os';import {join} from 'node:path';import {fileURLToPath} from 'node:url';
+import {createGameViewer} from '../viewer/viewer.mjs';
+import {buildGame} from '../template/tools/build.mjs';
+const packageRoot=fileURLToPath(new URL('..',import.meta.url));
+test('source saves preserve both files and a full prior edition; stale or foreign writes cannot replace it',async()=>{const scratch=await mkdtemp(join(tmpdir(),'relay-viewer-')),root=join(scratch,'workspace');process.env.GAME_DSH_DIR=packageRoot;await cp(join(packageRoot,'template'),root,{recursive:true});const s=await createGameViewer(root,{home:scratch});await new Promise(r=>s.listen(0,'127.0.0.1',r));const url='http://127.0.0.1:'+s.address().port;try{
+ const get=()=>fetch(url+'/api/project').then(r=>r.json()),original=(await get()).project;assert.ok(original.revision);const next={...original,title:'Changed original game',rules:original.rules+'\n// revised rules source\n'};
+ const put=(p,origin=url,rev=original.revision)=>fetch(url+'/api/project',{method:'PUT',headers:{origin,'content-type':'application/json','if-match':rev},body:JSON.stringify(p)});
+ assert.equal((await put(next,'https://other.example')).status,403);assert.equal((await put(next)).status,200);const saved=(await get()).project;assert.equal(saved.title,next.title);assert.equal(saved.rules,next.rules);assert.equal(JSON.parse(await readFile(join(root,'game/project.json'),'utf8')).rules,undefined);assert.equal(await readFile(join(root,'game/rules.mjs'),'utf8'),next.rules);
+ const previous=JSON.parse(await readFile(join(root,'.harness/history',(await readdir(join(root,'.harness/history')))[0]),'utf8'));assert.equal(previous.rules,original.rules);assert.equal(previous.title,original.title);assert.equal((await put(original)).status,409);assert.equal((await get()).project.title,next.title);
+ const broken={...saved,rules:'export function initial( {'};assert.equal((await put(broken,url,saved.revision)).status,400);assert.equal((await get()).project.revision,saved.revision);
+ const html=await fetch(url).then(r=>r.text());assert.match(html,/Changed original game/);assert.equal((await fetch(url+'/files/.harness/history')).status,404);assert.equal(await new Promise((resolve,reject)=>{httpGet(url+'/api/project',{headers:{host:'other.example'}},res=>{res.resume();resolve(res.statusCode);}).on('error',reject);}),403);
+ }finally{s.closeAllConnections();await new Promise(r=>s.close(r));await rm(scratch,{recursive:true,force:true});}});
+test('build rejects imported dependencies so a game source remains self-contained',async()=>{const scratch=await mkdtemp(join(tmpdir(),'relay-build-'));process.env.GAME_DSH_DIR=packageRoot;await cp(join(packageRoot,'template'),scratch,{recursive:true});try{const raw=JSON.parse(await readFile(join(scratch,'game/project.json'),'utf8'));await assert.rejects(buildGame(scratch,{project:{...raw,rules:"import x from 'https://example.org/rules.js'; export {x}"}}),/self-contained/);}finally{await rm(scratch,{recursive:true,force:true});}});
diff --git a/store/agents/game-master/toolchain/browser.mjs b/store/agents/game-master/toolchain/browser.mjs
new file mode 100755
index 000000000..38e617337
--- /dev/null
+++ b/store/agents/game-master/toolchain/browser.mjs
@@ -0,0 +1,18 @@
+import { access, writeFile, readFile } from 'node:fs/promises';
+import { execFileSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { join } from 'node:path';
+const dir = fileURLToPath(new URL('.', import.meta.url));
+export async function browserPath({ install = false } = {}) {
+ const candidates = [process.env.BROWSER_EXECUTABLE, '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser', process.env.PROGRAMFILES && join(process.env.PROGRAMFILES, 'Google/Chrome/Application/chrome.exe')].filter(Boolean);
+ for (const path of candidates) { try { await access(path); return path; } catch {} }
+ process.env.PLAYWRIGHT_BROWSERS_PATH = join(dir, 'browsers');
+ const { chromium } = await import('./node_modules/playwright-core/index.mjs');
+ const path = chromium.executablePath();
+ try { await access(path); return path; } catch {}
+ if (!install) throw new Error('Browser missing. Run the Game Master setup script.');
+ execFileSync(process.execPath, [join(dir, 'node_modules/playwright-core/cli.js'), 'install', 'chromium'], { stdio: 'inherit', env: process.env });
+ await access(path); return path;
+}
+if (process.argv.includes('--install')) console.log(`ok export browser: ${await browserPath({ install: true })}`);
+if (process.argv.includes('--check')) console.log(`ok export browser: ${await browserPath()}`);
diff --git a/store/agents/game-master/toolchain/doctor.sh b/store/agents/game-master/toolchain/doctor.sh
index 6f335fdc8..5fed35185 100755
--- a/store/agents/game-master/toolchain/doctor.sh
+++ b/store/agents/game-master/toolchain/doctor.sh
@@ -1,3 +1,6 @@
-#!/usr/bin/env bash
-# Doctor: the game is just a file served by the shared web-viewer; no extra runtime needed.
-exit 0
+#!/bin/sh
+set -eu
+here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+cd "$here"
+bash node.sh --input-type=module -e 'if(Number(process.versions.node.split(".")[0])<20)process.exit(1);await import("esbuild");console.log("ok Node and offline board-game build tools")'
+bash node.sh browser.mjs --check
diff --git a/store/agents/game-master/toolchain/init-workspace.sh b/store/agents/game-master/toolchain/init-workspace.sh
index deb30ed6e..f0350de74 100755
--- a/store/agents/game-master/toolchain/init-workspace.sh
+++ b/store/agents/game-master/toolchain/init-workspace.sh
@@ -1,12 +1,12 @@
#!/bin/sh
-# Harness copies the template before this runs. Preserve the user's design log on repeat calls.
+# Preserve the person's source and design log on repeat initialization.
set -eu
ws="${1:-$PWD}"
mkdir -p "$ws/game" "$ws/.harness"
if [ ! -f "$ws/game/DESIGN.md" ]; then
- printf '# Design log — Game Master\n\nRecord date, USER or AI, decision, rationale, and whether it remains in the build.\n' > "$ws/game/DESIGN.md"
+ printf '# Game decisions — Relay\n\nRecord date, USER or AI, supplied evidence, assumptions, decisions and approved rules, components and artwork.\n' > "$ws/game/DESIGN.md"
fi
cat > "$ws/.harness/verdict.json" <<JSON
-{"spec":1,"ready":false,"summary":"Relay starter available — describe what you want to create","artifact":"game/index.html","findings":[{"severity":"info","kind":"review_pending","message":"Starter provided; personalized changes need browser verification."}],"phases":[{"id":"build","name":"Build","state":"active"},{"id":"verify","name":"Verify","state":"pending"}],"updatedAt":"$(date -u +%Y-%m-%dT%H:%M:%SZ)"}
+{"spec":1,"ready":false,"summary":"Relay game workshop — turn your idea into a game people can play","artifact":"game/index.html","findings":[{"severity":"info","kind":"review_pending","message":"Pocket Conservatory is an example game. Author the person’s mechanics and components, then play the actual game and review its physical kit."}],"phases":[{"id":"build","name":"Plan","state":"active"},{"id":"verify","name":"Verify","state":"pending"}]}
JSON
printf 'initialized by %s\n' "${HARNESS_DSH:-autonomous/game-master}" > "$ws/.harness-initialized"
diff --git a/store/agents/game-master/toolchain/install.sh b/store/agents/game-master/toolchain/install.sh
new file mode 100755
index 000000000..8ce792060
--- /dev/null
+++ b/store/agents/game-master/toolchain/install.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+set -euo pipefail
+here="$(cd "$(dirname "$0")" && pwd)"
+. "$here/runtimes.sh"
+harness_node 20 || exit 1
+cd "$here"
+npm ci --ignore-scripts --no-audit --no-fund
+node browser.mjs --install
+node --input-type=module -e 'await import("esbuild");console.log("ok offline board-game build tools")'
diff --git a/store/agents/game-master/toolchain/node.sh b/store/agents/game-master/toolchain/node.sh
new file mode 100755
index 000000000..a527a9f1d
--- /dev/null
+++ b/store/agents/game-master/toolchain/node.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+set -euo pipefail
+here="$(cd "$(dirname "$0")" && pwd)"
+. "$here/runtimes.sh"
+harness_node 20 || exit 1
+exec node "$@"
diff --git a/store/agents/game-master/toolchain/package-lock.json b/store/agents/game-master/toolchain/package-lock.json
new file mode 100644
index 000000000..ce62e899b
--- /dev/null
+++ b/store/agents/game-master/toolchain/package-lock.json
@@ -0,0 +1,483 @@
+{
+ "name": "relay-game-tools",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "relay-game-tools",
+ "dependencies": {
+ "esbuild": "0.27.2",
+ "playwright-core": "1.63.0"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz",
+ "integrity": "sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==",
+ "cpu": [
+ "ppc64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.2.tgz",
+ "integrity": "sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.2.tgz",
+ "integrity": "sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.2.tgz",
+ "integrity": "sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.2.tgz",
+ "integrity": "sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.2.tgz",
+ "integrity": "sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.2.tgz",
+ "integrity": "sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.2.tgz",
+ "integrity": "sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.2.tgz",
+ "integrity": "sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.2.tgz",
+ "integrity": "sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.2.tgz",
+ "integrity": "sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==",
+ "cpu": [
+ "ia32"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.2.tgz",
+ "integrity": "sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==",
+ "cpu": [
+ "loong64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.2.tgz",
+ "integrity": "sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==",
+ "cpu": [
+ "mips64el"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.2.tgz",
+ "integrity": "sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.2.tgz",
+ "integrity": "sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.2.tgz",
+ "integrity": "sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==",
+ "cpu": [
+ "s390x"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.2.tgz",
+ "integrity": "sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.2.tgz",
+ "integrity": "sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.2.tgz",
+ "integrity": "sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.2.tgz",
+ "integrity": "sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.2.tgz",
+ "integrity": "sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.2.tgz",
+ "integrity": "sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.2.tgz",
+ "integrity": "sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.2.tgz",
+ "integrity": "sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.2.tgz",
+ "integrity": "sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.2.tgz",
+ "integrity": "sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/esbuild": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.2.tgz",
+ "integrity": "sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.27.2",
+ "@esbuild/android-arm": "0.27.2",
+ "@esbuild/android-arm64": "0.27.2",
+ "@esbuild/android-x64": "0.27.2",
+ "@esbuild/darwin-arm64": "0.27.2",
+ "@esbuild/darwin-x64": "0.27.2",
+ "@esbuild/freebsd-arm64": "0.27.2",
+ "@esbuild/freebsd-x64": "0.27.2",
+ "@esbuild/linux-arm": "0.27.2",
+ "@esbuild/linux-arm64": "0.27.2",
+ "@esbuild/linux-ia32": "0.27.2",
+ "@esbuild/linux-loong64": "0.27.2",
+ "@esbuild/linux-mips64el": "0.27.2",
+ "@esbuild/linux-ppc64": "0.27.2",
+ "@esbuild/linux-riscv64": "0.27.2",
+ "@esbuild/linux-s390x": "0.27.2",
+ "@esbuild/linux-x64": "0.27.2",
+ "@esbuild/netbsd-arm64": "0.27.2",
+ "@esbuild/netbsd-x64": "0.27.2",
+ "@esbuild/openbsd-arm64": "0.27.2",
+ "@esbuild/openbsd-x64": "0.27.2",
+ "@esbuild/openharmony-arm64": "0.27.2",
+ "@esbuild/sunos-x64": "0.27.2",
+ "@esbuild/win32-arm64": "0.27.2",
+ "@esbuild/win32-ia32": "0.27.2",
+ "@esbuild/win32-x64": "0.27.2"
+ }
+ },
+ "node_modules/playwright-core": {
+ "version": "1.63.0",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
+ "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
+ "license": "Apache-2.0",
+ "bin": {
+ "playwright-core": "cli.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ }
+ }
+}
diff --git a/store/agents/game-master/toolchain/package.json b/store/agents/game-master/toolchain/package.json
new file mode 100644
index 000000000..7526915c2
--- /dev/null
+++ b/store/agents/game-master/toolchain/package.json
@@ -0,0 +1,9 @@
+{
+ "name": "relay-game-tools",
+ "private": true,
+ "type": "module",
+ "dependencies": {
+ "esbuild": "0.27.2",
+ "playwright-core": "1.63.0"
+ }
+}
diff --git a/store/agents/game-master/toolchain/runtimes.sh b/store/agents/game-master/toolchain/runtimes.sh
new file mode 100755
index 000000000..7223c78dc
--- /dev/null
+++ b/store/agents/game-master/toolchain/runtimes.sh
@@ -0,0 +1,192 @@
+# shellcheck shell=bash
+# runtimes.sh — the interpreters a store package runs on, found on this machine or fetched, never
+# asked of the person who pressed Get.
+#
+# Sourced (not run) by a package's setup, doctor and viewer scripts. A new Mac has Apple's Python 3.9,
+# no Homebrew and, for most people, no Node on PATH; a package that answers "brew install [email protected]"
+# has failed its install. So:
+#
+# harness_node 18 node >= 18 on PATH, with npm: the machine's own, else the Node Harness
+# itself runs on (~/.harness/runtime/current-node, laid down with the CLI)
+# harness_uv uv on PATH: the machine's own, else a pinned, checksummed release
+# fetched into ~/.harness/runtime
+# harness_venv DIR 3.12 [MIN [BELOW]]
+# DIR is a venv on CPython 3.12, which uv downloads when the machine
+# has none. A venv already there on a Python in [MIN, BELOW) is kept.
+# harness_pip DIR PKG… install into that venv, through uv
+# harness_micromamba micromamba, pinned and checksummed, for native libraries PyPI has
+# no wheel for (pycairo on macOS)
+# harness_conda_env DIR SPEC… DIR is a conda-forge environment with those packages
+#
+# Every function prints `miss …` and returns 1 when it cannot deliver, so `harness_node 18 || exit 1`
+# reads like the rest of a setup script. Nothing here touches the user's shell profile; what it
+# installs lands in ~/.harness/runtime or the package's own directory (uv keeps its download cache
+# where it always does, which a venv does not depend on).
+#
+# ONE copy is written by hand: store/tools/runtimes.sh in the OpenHarness repository. Each package
+# carries an identical copy (a package installs alone, so it cannot reach this one);
+# `node store/tools/sync-runtimes.mjs` rewrites them and the CLI's store spec fails when one drifts.
+
+HARNESS_RUNTIME="${ADAPTER_RUNTIME_DIR:-${HOME:-}/.harness/runtime}"
+# The Pythons uv downloads live with Harness's other runtimes, not in uv's own ~/.local/share/uv:
+# a package's venv points at its interpreter, and `uv python uninstall` there must not break it.
+UV_PYTHON_INSTALL_DIR="${UV_PYTHON_INSTALL_DIR:-$HARNESS_RUNTIME/python}"
+export UV_PYTHON_INSTALL_DIR
+HARNESS_UV_VERSION=0.12.15
+HARNESS_MICROMAMBA_VERSION=2.9.0-0
+
+_harness_platform() {
+ case "$(uname -s)-$(uname -m)" in
+ Darwin-arm64) echo darwin-arm64 ;;
+ Darwin-x86_64) echo darwin-x64 ;;
+ Linux-x86_64) echo linux-x64 ;;
+ Linux-aarch64 | Linux-arm64) echo linux-arm64 ;;
+ *) return 1 ;;
+ esac
+}
+
+_harness_sha256() {
+ if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | cut -d' ' -f1
+ else sha256sum "$1" | cut -d' ' -f1; fi
+}
+
+# _harness_fetch URL DEST SHA256 — DEST exists only if what arrived matches the pinned checksum.
+_harness_fetch() {
+ local part="$2.part.$$"
+ if ! curl -fsSL --retry 3 --connect-timeout 20 --max-time 900 -o "$part" "$1"; then
+ rm -f "$part"; echo "miss could not download $1 — check this machine's internet connection"; return 1
+ fi
+ if [ "$(_harness_sha256 "$part")" != "$3" ]; then
+ rm -f "$part"; echo "miss $1 did not match its pinned checksum; nothing was installed"; return 1
+ fi
+ mv -f "$part" "$2"
+}
+
+_harness_node_at_least() {
+ command -v node >/dev/null 2>&1 || return 1
+ node -e '
+ const [a, b = 0] = process.argv[1].split(".").map(Number)
+ const [x, y] = process.versions.node.split(".").map(Number)
+ process.exit(x > a || (x === a && y >= b) ? 0 : 1)
+ ' "$1" >/dev/null 2>&1
+}
+
+harness_node() {
+ local min="${1:-18}" recorded saved="$PATH" own=0
+ _harness_node_at_least "$min" && own=1
+ # A node without npm beside it (a distro's nodejs package) cannot run a setup's `npm ci`.
+ if [ "$own" = 1 ] && command -v npm >/dev/null 2>&1; then return 0; fi
+ recorded="$(cat "$HARNESS_RUNTIME/current-node" 2>/dev/null || true)"
+ # Already Harness's own (a second call, or a wrapper calling a script that asks again): nothing to add.
+ if [ "$own" = 1 ] && [ -n "$recorded" ] && [ "$(command -v node)" = "${recorded%/*}/node" ]; then return 0; fi
+ if [ -n "$recorded" ] && [ -x "${recorded%/*}/node" ]; then
+ PATH="${recorded%/*}:$PATH"; export PATH; hash -r 2>/dev/null || true
+ _harness_node_at_least "$min" && return 0
+ PATH="$saved"; export PATH; hash -r 2>/dev/null || true
+ [ "$own" = 1 ] && return 0
+ echo "miss node >= $min — this machine's newest is $("${recorded%/*}/node" -v), Harness's own; update Harness"
+ return 1
+ fi
+ [ "$own" = 1 ] && return 0
+ echo "miss node >= $min, and Harness's own Node is not in $HARNESS_RUNTIME — run \`harness start\` once to lay it down"
+ return 1
+}
+
+harness_uv() {
+ local dir asset sum tmp
+ command -v uv >/dev/null 2>&1 && return 0
+ for dir in "${HOME:-}/.local/bin" "${HOME:-}/.cargo/bin"; do
+ [ -n "${HOME:-}" ] || break
+ if [ -x "$dir/uv" ]; then PATH="$dir:$PATH"; export PATH; return 0; fi
+ done
+ dir="$HARNESS_RUNTIME/uv-$HARNESS_UV_VERSION"
+ if [ ! -x "$dir/uv" ]; then
+ case "$(_harness_platform)" in
+ darwin-arm64) asset=uv-aarch64-apple-darwin sum=dc304b9ed1b24174572290fba60ac3f6fe63c73a671f0439e62a91375841964d ;;
+ darwin-x64) asset=uv-x86_64-apple-darwin sum=e9ca61775532368fe518ab03e7a354c7ecab8ccb3c7d941c775fcc4a362b801b ;;
+ linux-x64) asset=uv-x86_64-unknown-linux-gnu sum=f97935763c04be3e692460a7aaeaaab8fc3b78fcf8b389da820b38ae7423a638 ;;
+ linux-arm64) asset=uv-aarch64-unknown-linux-gnu sum=0e9a3499b0587d449c9ff684c0160da607826e4af1cee220bc87f378702d3e08 ;;
+ *) echo "miss uv — there is no uv release for $(uname -s) $(uname -m); install it from https://docs.astral.sh/uv/"; return 1 ;;
+ esac
+ echo " fetching uv $HARNESS_UV_VERSION into $HARNESS_RUNTIME (it brings Python and the packages)"
+ mkdir -p "$HARNESS_RUNTIME" || { echo "miss cannot write $HARNESS_RUNTIME"; return 1; }
+ tmp="$(mktemp -d "$HARNESS_RUNTIME/.uv.XXXXXX")" || { echo "miss cannot write $HARNESS_RUNTIME"; return 1; }
+ if ! _harness_fetch "https://github.com/astral-sh/uv/releases/download/$HARNESS_UV_VERSION/$asset.tar.gz" "$tmp/uv.tar.gz" "$sum"; then
+ rm -rf "$tmp"; return 1
+ fi
+ tar -xzf "$tmp/uv.tar.gz" -C "$tmp" && chmod +x "$tmp/$asset/uv" "$tmp/$asset/uvx" \
+ || { rm -rf "$tmp"; echo "miss the uv archive would not unpack"; return 1; }
+ # Two installs at once both get here; whichever renames first wins and the other's copy goes.
+ # (mv onto a directory that exists would nest the copy inside it, hence the test.)
+ [ -e "$dir" ] || mv "$tmp/$asset" "$dir" 2>/dev/null || true
+ rm -rf "$tmp"
+ [ -x "$dir/uv" ] || { echo "miss uv did not land in $dir"; return 1; }
+ fi
+ PATH="$dir:$PATH"; export PATH
+}
+
+# harness_venv DIR VERSION [MIN [BELOW]] — MIN defaults to VERSION; BELOW is exclusive and optional.
+harness_venv() {
+ local dir="${1:?harness_venv needs a directory}" want="${2:?harness_venv needs a Python version}"
+ local min="${3:-$2}" below="${4:-}"
+ if [ -x "$dir/bin/python" ] && "$dir/bin/python" -c '
+import sys
+at = lambda s: tuple(int(p) for p in s.split("."))
+v = sys.version_info[:2]
+sys.exit(0 if v >= at(sys.argv[1]) and (not sys.argv[2] or v < at(sys.argv[2])) else 1)
+' "$min" "$below" 2>/dev/null; then
+ echo "ok $("$dir/bin/python" --version) in $dir"
+ return 0
+ fi
+ harness_uv || return 1
+ echo " python $want in $dir (uv downloads it when this machine has none)"
+ rm -rf "$dir"
+ # only-managed: the same python-build-standalone interpreter on every machine, so a package tested
+ # once is tested everywhere — not whichever Homebrew or pyenv Python happened to be first on PATH.
+ uv venv --quiet --seed --python "$want" --python-preference only-managed "$dir" \
+ || { echo "miss could not make a Python $want environment in $dir"; return 1; }
+ echo "ok $("$dir/bin/python" --version) in $dir"
+}
+
+harness_pip() {
+ local dir="${1:?harness_pip needs a venv}"
+ shift
+ harness_uv || return 1
+ # uv's own error comes first; the miss line is last, so it is the line the store shows.
+ uv pip install --quiet --python "$dir/bin/python" "$@" \
+ || { echo "miss could not install $* into $dir"; return 1; }
+}
+
+harness_micromamba() {
+ local dir asset sum
+ dir="$HARNESS_RUNTIME/micromamba-$HARNESS_MICROMAMBA_VERSION"
+ if [ ! -x "$dir/micromamba" ]; then
+ case "$(_harness_platform)" in
+ darwin-arm64) asset=micromamba-osx-arm64 sum=ec2a072f028e1a7cf20f3e2e74d5a8127cf5a5f27636375b5359811565f4e5be ;;
+ darwin-x64) asset=micromamba-osx-64 sum=1e71054bb3ac9a076e21f7ec48acfef536f9b3f1408f371a942784bf5ef83d8a ;;
+ linux-x64) asset=micromamba-linux-64 sum=366cd9cd8be14df1ab8ed50352a82111082a36686b2d389fdb79a92c3fafb3e3 ;;
+ linux-arm64) asset=micromamba-linux-aarch64 sum=9f93b974adcb4d166996af969b6cd371287d1a3e52733704727884d9b74cb7a7 ;;
+ *) echo "miss micromamba — there is no release for $(uname -s) $(uname -m)"; return 1 ;;
+ esac
+ echo " fetching micromamba $HARNESS_MICROMAMBA_VERSION into $HARNESS_RUNTIME (native libraries PyPI has no wheel for)"
+ mkdir -p "$dir" || { echo "miss cannot write $dir"; return 1; }
+ _harness_fetch "https://github.com/mamba-org/micromamba-releases/releases/download/$HARNESS_MICROMAMBA_VERSION/$asset" "$dir/micromamba.$$" "$sum" || return 1
+ chmod +x "$dir/micromamba.$$" && mv -f "$dir/micromamba.$$" "$dir/micromamba" \
+ || { rm -f "$dir/micromamba.$$"; echo "miss micromamba would not install into $dir"; return 1; }
+ fi
+ HARNESS_MICROMAMBA="$dir/micromamba"
+ export HARNESS_MICROMAMBA
+}
+
+# harness_conda_env DIR SPEC… — conda-forge only, packages cached under ~/.harness/runtime/mamba.
+harness_conda_env() {
+ local dir="${1:?harness_conda_env needs a directory}"
+ shift
+ # micromamba takes a relative --prefix as a name under its root prefix and "succeeds" there.
+ case "$dir" in /*) ;; *) dir="$PWD/$dir" ;; esac
+ harness_micromamba || return 1
+ MAMBA_ROOT_PREFIX="$HARNESS_RUNTIME/mamba" "$HARNESS_MICROMAMBA" create --yes --quiet \
+ --prefix "$dir" --override-channels --channel conda-forge "$@" >/dev/null \
+ && [ -d "$dir/conda-meta" ] \
+ || { echo "miss could not make the conda-forge environment in $dir ($*)"; return 1; }
+}
diff --git a/store/agents/game-master/toolchain/setup.sh b/store/agents/game-master/toolchain/setup.sh
index 19d2dfc73..7ccd3d7a1 100755
--- a/store/agents/game-master/toolchain/setup.sh
+++ b/store/agents/game-master/toolchain/setup.sh
@@ -1,3 +1,4 @@
-#!/usr/bin/env bash
-# Game Master has no toolchain: everything is inline HTML + a turn loop. Nothing to install.
-exit 0
+#!/bin/sh
+set -eu
+here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+exec bash "$here/install.sh"
diff --git a/store/agents/game-master/toolchain/viewer.sh b/store/agents/game-master/toolchain/viewer.sh
new file mode 100755
index 000000000..c2afe7493
--- /dev/null
+++ b/store/agents/game-master/toolchain/viewer.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+set -eu
+here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+exec bash "$here/node.sh" "$here/../viewer/viewer.mjs"
diff --git a/store/agents/game-master/viewer/viewer.mjs b/store/agents/game-master/viewer/viewer.mjs
new file mode 100644
index 000000000..b6976f1a4
--- /dev/null
+++ b/store/agents/game-master/viewer/viewer.mjs
@@ -0,0 +1,60 @@
+// Local workspace bridge: explicit project saves, optimistic revision checks, recoverable history.
+import { createServer } from 'node:http';
+import { readFile,writeFile,mkdir,rename,realpath,stat } from 'node:fs/promises';
+import { resolve,join,relative,sep,extname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { randomUUID } from 'node:crypto';
+import { readProject,buildGame } from '../template/tools/build.mjs';
+import { validateProject,digest } from '../template/studio/project.mjs';
+export async function createGameViewer(workspace){
+ const root=await realpath(workspace);let saving=false;
+ async function current(){const project=await readProject(root);delete project.revision;project.revision=await digest(project);return project;}
+ const server=createServer(async(req,res)=>{
+ res.setHeader('cache-control','no-store');res.setHeader('x-content-type-options','nosniff');
+ const send=(code,body,type='application/json')=>{res.writeHead(code,{'content-type':type});res.end(type==='application/json'?JSON.stringify(body):body);};
+ if(!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(req.headers.host??''))return send(403,{error:'Loopback only.'});
+ const origin='http://'+req.headers.host;
+ if((req.headers.origin&&req.headers.origin!==origin)||req.headers['sec-fetch-site']==='cross-site')return send(403,{error:'Same-origin requests only.'});
+ let path;try{path=decodeURIComponent(new URL(req.url,origin).pathname);}catch{return send(400,{error:'Invalid path.'});}
+ const mutation=['PUT','POST'].includes(req.method);
+ if(mutation&&(req.headers.origin!==origin||!String(req.headers['content-type']).startsWith('application/json')))return send(403,{error:'Use the local studio to save or open a project.'});
+ async function body(){let size=0;const chunks=[];for await(const chunk of req){size+=chunk.length;if(size>3000000)throw new Error('Request exceeds 3 MB.');chunks.push(chunk);}return JSON.parse(Buffer.concat(chunks));}
+ try{
+ if(path==='/api/project'&&req.method==='GET')return saving?send(503,{error:'Source save in progress.'}):send(200,{project:await current()});
+ if(path==='/api/project'&&req.method==='PUT'){
+ if(saving)return send(409,{project:await current(),error:'Another save is in progress.'});
+ const project=validateProject(await body());delete project.revision;saving=true;
+ try{
+ const before=await current();if(req.headers['if-match']!==before.revision)return send(409,{project:before,error:'The source changed. Keep both versions until you choose.'});
+ const built=await buildGame(root,{project});
+ const latest=await current();if(latest.revision!==before.revision)return send(409,{project:latest,error:'The source changed during the build. Keep both versions until you choose.'});
+ const history=join(root,'.harness/history');await mkdir(history,{recursive:true});
+ await writeFile(join(history,new Date().toISOString().replace(/[:.]/g,'-')+'-'+randomUUID()+'.relay.json'),JSON.stringify(before));
+ const target=join(root,'game/project.json'),temporary=target+'.'+randomUUID()+'.tmp';
+ const source={...project};delete source.rules;delete source.revision;
+ await writeFile(temporary,JSON.stringify(source,null,2)+'\n');
+ const ruleTarget=join(root,'game/rules.mjs'),ruleTemporary=ruleTarget+'.'+randomUUID()+'.tmp';await writeFile(ruleTemporary,project.rules);
+ const preview=join(root,'game/index.html'),previewTemporary=preview+'.'+randomUUID()+'.tmp';await writeFile(previewTemporary,built.html);
+ await rename(ruleTemporary,ruleTarget);await rename(temporary,target);await rename(previewTemporary,preview);
+ await writeFile(join(root,'.harness/verdict.json'),JSON.stringify({spec:1,ready:false,artifact:'game/index.html',summary:'Source saved; playtest and physical delivery review pending'}));
+ return send(200,{project:await current()});
+ }finally{saving=false;}
+ }
+ if(req.method!=='GET'&&req.method!=='HEAD')return send(405,{error:'Method not allowed.'});
+ if(path==='/'){const html=await readFile(join(root,'game/index.html'));return send(200,req.method==='HEAD'?'':html,'text/html; charset=utf-8');}
+ if(!path.startsWith('/files/'))return send(404,{error:'Not found.'});
+ const name=path.slice(7);if(name.split(/[\\/]/).some(s=>s.startsWith('.')||s==='node_modules'))return send(404,{error:'Not found.'});
+ const file=await realpath(join(root,name));if(!file.startsWith(root+sep)||relative(root,file).split(sep).some(s=>s.startsWith('.')))return send(404,{error:'Not found.'});
+ const info=await stat(file);if(!info.isFile()||info.size>48000000)return send(413,{error:'File unavailable or too large.'});
+ const mime={'.html':'text/html; charset=utf-8','.svg':'image/svg+xml','.png':'image/png','.pdf':'application/pdf','.json':'application/json','.ttf':'font/ttf'}[extname(file)]??'application/octet-stream';
+ return send(200,req.method==='HEAD'?'':await readFile(file),mime==='application/json'?'application/json; charset=utf-8':mime);
+ }catch(error){return send(400,{error:error.code==='ENOENT'?'That file is not available.':error.message});}
+ });
+ return server;
+}
+if(process.argv[1]&&await realpath(process.argv[1]).catch(()=>null)===fileURLToPath(import.meta.url)){
+ if(!process.env.HARNESS_WORKSPACE)throw new Error('HARNESS_WORKSPACE is required.');
+ const port=Number(process.env.HARNESS_VIEWER_PORT);if(!Number.isInteger(port)||port<1||port>65535)throw new Error('HARNESS_VIEWER_PORT must be valid.');
+ const server=await createGameViewer(process.env.HARNESS_WORKSPACE);server.listen(port,'127.0.0.1',()=>console.log(`[relay] http://127.0.0.1:${port}/`));
+ for(const signal of ['SIGINT','SIGTERM'])process.once(signal,()=>{server.closeAllConnections();server.close();});
+}
diff --git a/store/showcase/game-master/night-ferry.jpg b/store/showcase/game-master/night-ferry.jpg
new file mode 100644
index 000000000..27bedeecb
Binary files /dev/null and b/store/showcase/game-master/night-ferry.jpg differ
diff --git a/store/showcase/game-master/signal-garden.jpg b/store/showcase/game-master/signal-garden.jpg
new file mode 100644
index 000000000..e780bf553
Binary files /dev/null and b/store/showcase/game-master/signal-garden.jpg differ
diff --git a/store/showcase/game-master/starter.jpg b/store/showcase/game-master/starter.jpg
index 58e6fff42..7b15da8f1 100644
Binary files a/store/showcase/game-master/starter.jpg and b/store/showcase/game-master/starter.jpg differ
diff --git a/store/tools/build-experiences.mjs b/store/tools/build-experiences.mjs
index 88aa65c52..7e39c17d2 100644
--- a/store/tools/build-experiences.mjs
+++ b/store/tools/build-experiences.mjs
@@ -8,6 +8,7 @@ import { buildMusic } from "../agents/music-studio/template/tools/build.mjs";
import { buildBrand } from "../agents/creative-direction/template/tools/build.mjs";
import { buildWorld } from "../agents/voxel-worlds/template/tools/build.mjs";
import { buildFlight } from "../agents/drone-pilot/template/tools/build.mjs";
+import { buildGame } from "../agents/game-master/template/tools/build.mjs";
const source = new URL("./experiences/", import.meta.url);
export const experiences = [
{
@@ -63,7 +64,7 @@ export async function build({ check = false } = {}) {
]);
let drift = false;
for (const exp of experiences) {
- if (["generative-art", "music-studio", "creative-direction", "voxel-worlds", "drone-pilot"].includes(exp.id)) {
+ if (["generative-art", "music-studio", "creative-direction", "voxel-worlds", "drone-pilot", "game-master"].includes(exp.id)) {
try {
const packageRoot = new URL(`../agents/${exp.id}/`, import.meta.url);
const icon = await readFile(new URL('brand/icon.svg', packageRoot), 'utf8');
@@ -71,7 +72,7 @@ export async function build({ check = false } = {}) {
if (check) {
if (await readFile(studioIcon, 'utf8') !== icon) throw new Error(`${exp.id}: packaged studio icon is out of date.`);
} else await writeFile(studioIcon, icon);
- const builder = { 'generative-art': buildArt, 'music-studio': buildMusic, 'creative-direction': buildBrand, 'voxel-worlds': buildWorld, 'drone-pilot': buildFlight }[exp.id];
+ const builder = { 'generative-art': buildArt, 'music-studio': buildMusic, 'creative-direction': buildBrand, 'voxel-worlds': buildWorld, 'drone-pilot': buildFlight, 'game-master': buildGame }[exp.id];
await builder(fileURLToPath(new URL(`../agents/${exp.id}/template/`, import.meta.url)), { check });
} catch (error) {
if (!check) throw error;
diff --git a/store/tools/experience-tests/browser.mjs b/store/tools/experience-tests/browser.mjs
index ab88fc488..d7ef45f34 100644
--- a/store/tools/experience-tests/browser.mjs
+++ b/store/tools/experience-tests/browser.mjs
@@ -109,6 +109,11 @@ async function shellRegression() {
}
async function one(exp) {
+ if (exp.id === 'game-master') {
+ const result = execFileSync(process.execPath, [join(repo, 'store/agents/game-master/test/browser.mjs')], { env: { ...process.env, GAME_QA_ROOT: join(output, 'relay-browser') }, encoding: 'utf8', timeout: 180000 });
+ results.push({name:'game-master-studio',ok:true,output:result.trim()});
+ return;
+ }
if (exp.id === 'drone-pilot') {
const result = execFileSync(process.execPath, [join(repo, 'store/agents/drone-pilot/test/browser.mjs')], { env: { ...process.env, DRONE_QA_ROOT: join(output, 'vector-browser') }, encoding: 'utf8', timeout: 180000 });
results.push({name:'drone-pilot-studio',ok:true,output:result.trim()});
diff --git a/work/DRONE-REBUILD.md b/work/DRONE-REBUILD.md
index b86e0b2b3..8abefe62c 100644
--- a/work/DRONE-REBUILD.md
+++ b/work/DRONE-REBUILD.md
@@ -1,6 +1,6 @@
# Drone Pilot — field-survey rebuild
-The implementation is complete and locally reviewed; publication is the next step. The old
+Published via PR #151 at 8e8d73ba52c789e236409cbc293acc272ec11cc3. CI and Store publisher passed. The public catalog and studio bytes match; the normal installer and doctor passed on this Mac using the explicit repository path because the CLI id lookup retained an older catalog. The old
canyon implementation remains under `store/tools/experiences/drone-pilot.*`. The rebuilt package
restores listing only for an editable planning/data/delivery workflow.
@@ -22,8 +22,7 @@ page splitting. Original UTF-8 CSV bytes (including BOM) are preserved and verif
The required credit section was restored in Voxel Worlds while running the full Store tests;
no Voxel runtime change is included here. Source conformance and all 416 CLI Store/check tests pass.
-Existing branding remains, with new actual Store screenshots. Publishing still needs the PR,
-required CI, merge, catalog publication, public byte checks and normal install verification.
+Existing branding remains, with new actual Store screenshots. Public package revision: 0e77a2b9b87d7433f61a921de28c253073dd2ae4. Store catalog snapshot: `/private/tmp/drone-published-catalog.json`.
Next after Drone publication: Game Master, then Lab Bench. Keep each unlisted until its own
useful workflow and outputs are verified. User has authorized sequential rebuild and publication.
diff --git a/work/FIVE-REBUILDS.md b/work/FIVE-REBUILDS.md
index a6e8694cf..290b14cf3 100644
--- a/work/FIVE-REBUILDS.md
+++ b/work/FIVE-REBUILDS.md
@@ -10,9 +10,9 @@ so the user can test it, then move to the next. Do not claim a subjective “wow
2. **Voxel Worlds — published (#146), normal Store install verified on this Mac.** Named object editing, sculpting, source saves,
physical walking, VOX import and independent GLB/VOX/offline delivery. See
[the acceptance evidence](../store/agents/voxel-worlds/test/ACCEPTANCE.md).
-3. **Drone Pilot — in progress.** [Survey planning and post-flight evidence](DRONE-REBUILD.md), with actual inputs and explicit simulation
+3. **Drone Pilot — published (#151), installed readiness verified on this Mac.** [Survey planning and post-flight evidence](DRONE-REBUILD.md), with actual inputs and explicit simulation
boundaries. No claim that a simulation authorizes or validates a real flight.
-4. **Game Master — pending.** Create and revise original playable games, then deliver working builds.
+4. **Game Master — in progress.** Original board/card games: authored rules, human play, component editing, reproducible playtests and printable kits.
5. **Lab Bench — pending.** Analyze the person's observations with reproducible methods and outputs.
## Creative Direction acceptance
diff --git a/work/GAME-REBUILD.md b/work/GAME-REBUILD.md
new file mode 100644
index 000000000..8ee8b6419
--- /dev/null
+++ b/work/GAME-REBUILD.md
@@ -0,0 +1,25 @@
+# Game Master — original tabletop-game workshop
+
+Implementation complete; final checks and publication are in progress. The prior arena remains
+under `store/tools/experiences/game-master.*`. Relay branding is preserved. The new package uses
+ordinary authored JavaScript rules and editable component/board data to produce playable tabletop
+games and physical kits. Phaser/Godot already cover video-game engine creation in the Store.
+
+The human can take legal actions, see actual outcomes, pass private views locally, inspect card
+text, undo testing turns, save/reopen source and replays, import original face artwork, lock
+approved components, revise rules/values, inspect sampled policies and keep an offline game plus
+SVG/HTML/PDF source and print kit. No fixed genre menu or pretend prompt-to-game button.
+
+See [acceptance evidence](../store/agents/game-master/test/ACCEPTANCE.md). Three original games and
+six before/after editions cover drafting, spatial routing and push-your-luck. Real browser inputs
+reach outcomes; independent readers check the actual physical files. Review found and fixed ZIP
+input handling, rule-worker recovery, private-view keyboard access, small printed values, and
+puzzle tiles that did not fit the original board cells. Browser source conflicts preserve both
+editions. Nonterminating rules can be stopped and repaired. Actual workspace materialization found a
+symlinked-path CLI entry bug; the tools now resolve real paths and a regression runs actual
+build/check commands through a workspace symlink.
+
+No customer/installed-agent prompt trial, fun/balance result, printer trial, native tabletop
+simulator import or network multiplayer is claimed. Game Master stays unlisted until publication.
+After its tested PR is merged, verify public catalog/artifact/screenshots and normal setup/doctor,
+then begin Lab Bench. Do not delete old code or change other sessions' worktrees.
diff --git a/work/SUPERPOWERS.md b/work/SUPERPOWERS.md
index c09bb7871..7cbb0813a 100644
--- a/work/SUPERPOWERS.md
+++ b/work/SUPERPOWERS.md
@@ -13,7 +13,7 @@ trials with real user briefs are still outstanding; listing does not claim those
**Next user direction:** improve the other five sequentially. Creative Direction has now been
rebuilt and relisted; see [FORME-REBUILD.md](FORME-REBUILD.md) and the
[sequential plan](FIVE-REBUILDS.md). Voxel Worlds is also rebuilt and published (#146);
-Drone Pilot is in progress. The original withdrawal table below
+Drone Pilot is published (#151), and Game Master is in progress. The original withdrawal table below
is retained as history, not a description of the rebuilt Forme product.
## Original review of our seven
@@ -29,7 +29,7 @@ is retained as history, not a description of the rebuilt Forme product.
| Lab Bench | Inspect one synthetic experiment | Cannot do useful analysis on the person's own observations | Withdraw; stop parallel development |
All seven initially received `listed:false`. Art and Music have since been rebuilt and relisted
-for user testing, followed by Creative Direction and Voxel Worlds. The other three remain unlisted. Source, logos,
+for user testing, followed by Creative Direction, Voxel Worlds and Drone Pilot. Game Master and Lab Bench remain unlisted. Source, logos,
tests and workspaces stay intact.
The shared web viewer remains available: it is infrastructure used by other harnesses.
Other sessions' harnesses are outside this withdrawal.