@plupin/cli 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,334 @@
1
+ # CLI
2
+
3
+ Status: `dev`, `create`, `up`, `deploy`, `login`, `status` and `mcp` **shipped**. A creator builds
4
+ anywhere, then `plupin up ./dist` publishes the result to `<id>.plupin.com` and proves the address
5
+ answers; the platform never runs a build. `up` measures the build before it goes anywhere, so there
6
+ is no separate check to remember.
7
+
8
+ ## Install
9
+
10
+ Requires Bun 1.3 or newer: the `plupin` bin runs on Bun (`#!/usr/bin/env bun`), it is not a Node
11
+ program.
12
+
13
+ ```sh
14
+ bun add -d @plupin/cli
15
+ bunx @plupin/cli --help
16
+ ```
17
+
18
+ There is no unscoped `plupin` package on npm: `bunx plupin` is a 404, and `npx @plupin/cli` works
19
+ when Bun is on `PATH`.
20
+
21
+ A game that imports the SDK installs it beside the CLI:
22
+
23
+ ```sh
24
+ bun add @plupin/game-sdk
25
+ ```
26
+
27
+ Both tarballs carry no runtime dependencies: the CLI's `dist` bundles the production room and these
28
+ chapters, and the SDK's `dist` is one ESM file plus its declarations.
29
+
30
+ ## `plupin dev [dir]`
31
+
32
+ Serves a built game folder and hosts its room on the same origin.
33
+
34
+ | | |
35
+ |---|---|
36
+ | `dir` | build output (default `./dist`) |
37
+ | `--port` | port for the game and its room, default `8787` |
38
+ | `--manifest` | read `plupin.json` from here instead of `<dir>/plupin.json` |
39
+ | `--seed` | fix the seeded leaderboard, default `1` |
40
+ | `--ledger` | stream every test-mode debit as it happens |
41
+
42
+ Prints the game URL and the admission URL. One origin serves the build **and** hosts the room, the
43
+ way production does, and the room is the production `RelayRoom` class bundled with a two-line
44
+ `cloudflare:workers` shim — never a reimplementation. A path with no file extension falls back to
45
+ the manifest entry; a missing file is a 404 so a broken build is visible.
46
+
47
+ ### Money and leaderboard in test mode
48
+
49
+ `plupin dev` prints `money: test mode (no gateway)`. Each dev player starts from a fixed 100 Sigma
50
+ and the server exposes the wallet and leaderboard the SDK v0.2 surface calls:
51
+
52
+ | route | SDK method |
53
+ |---|---|
54
+ | `POST /_dev/auth/sign-in` | `auth.signIn()` |
55
+ | `GET /_dev/wallet` | `balance()` |
56
+ | `POST /_dev/wallet/spend` `{ sku, amount, idempotencyKey }` | `spend({ sku, amount, idempotencyKey })` |
57
+ | `GET /_dev/wallet/entitlements` | `entitlements()` |
58
+ | `GET /_dev/ledger` | ledger read (dev only) |
59
+ | `GET /_dev/leaderboard/<boardId>` | `top()` |
60
+ | `POST /_dev/leaderboard/<boardId>` `{ score }` | `submit()` |
61
+
62
+ The same `idempotencyKey` is one debit; two keys are two debits. `--seed` fills each board declared
63
+ in `plupin.json` with five reproducible rows. `bun packages/cli/scripts/local-money-check.ts` is the
64
+ runnable acceptance transcript.
65
+
66
+ ## `plupin emote new | preview | push`
67
+
68
+ An emote or wearable you sell is one file, `emote.json`, and one folder:
69
+
70
+ ```bash
71
+ plupin emote new my-emote --id emote-ngakak --name Ngakak --face teriak --clip jump --price 25
72
+ plupin emote import walk-cycle.json my-emote # optional: put a baked animation on it
73
+ plupin emote preview my-emote
74
+ plupin emote push my-emote
75
+ ```
76
+
77
+ `emote new [dir] [--id <id>] [--name <n>] [--slot emote|outfit|hair|accessory] [--price <n>]`
78
+ writes `emote.json` and an `assets/` folder. The composition is validated before anything is
79
+ written, with the shared character package the server uses, so an unknown face or clip fails here
80
+ and names the ones that exist. `--glyph`, `--face`, `--clip` fill an emote; `--color` fills a
81
+ wearable; `--price 0` is a giveaway. It refuses to overwrite an existing manifest.
82
+ `emote import <clip.json> [dir] [--fps <n>]` then puts your own animation on the emote (see "Animated
83
+ emotes" in the character guide); it scaffolds the folder first when there is no manifest yet.
84
+
85
+ `emote preview [dir] [--out <file>]` renders the composition and writes the SVG to
86
+ `<dir>/.plupin/emote-preview.svg` (or `--out`). No network, no upload: the bytes on disk are the
87
+ bytes the moderator will decide on, because the platform renders with the same function.
88
+
89
+ `emote push [dir] [--api <url>]` sends `emote.json` to `POST /api/items` with the token
90
+ `plupin login` stored, and prints the listing id, its `pending` state and the fee. Refusals are the
91
+ server's own sentence and exit 3: `DAILY_LISTING_LIMIT` (5 per 24 hours), `ACTIVE_LISTING_CAP`
92
+ (12 pending or live), `DUPLICATE_CONTENT` (the same manifest is already listed), or the manifest
93
+ field and the values it accepts. Publishing a rejected id again does not charge the fee twice; a
94
+ rejection itself does not refund it.
95
+
96
+ Only `push` needs an account. `new` and `preview` write files and nothing else.
97
+
98
+ ## `plupin up [dir]`
99
+
100
+ The one command: measure the build, create the game if it does not exist, deploy the bundle, wait for
101
+ the live pointer to move, then ask `https://<id>.plupin.com/` whether it answers `200`.
102
+
103
+ | | |
104
+ |---|---|
105
+ | `dir` | build output (default `./dist`) |
106
+ | `--title` | title used only when the game is created (default `plupin.json` → `name`) |
107
+ | `--visibility` | `public`, `restricted` or `draft`, used only on create (default `public`) |
108
+ | `--engine` | `2d` or `3d`; must agree with `plupin.json → engine` (default: the manifest's, `3d` when omitted) |
109
+ | `--dry-run` | run the checks, hash the folder, print the revision and the URL, publish nothing |
110
+ | `--skip-checks` | publish without measuring the build first |
111
+ | `--api <url>` | talk to this API instead of the one `login` stored (also `$PLUPIN_API_URL`) |
112
+ | `--game-origin <url>` | print and probe this URL instead of `https://<id>.plupin.com` |
113
+
114
+ Before anything is published, `up` plays the build locally in Chromium headless at `390x844` on fast
115
+ 3G: the over-the-wire megabytes against `plupin.json` → `budget`, whether the page loads, the seconds
116
+ until a real tap is accepted, and console errors / unhandled rejections / lost WebGL contexts. A
117
+ failure is exit `5` with every crossed metric named, and no request has been made. It needs Playwright's
118
+ Chromium. Results go to `.plupin/checks.json` and `.plupin/checks.png` beside the build, never inside it,
119
+ because everything inside the folder is the bundle. Full page: [checks.md](checks.md).
120
+
121
+ `up` is not a third publish path: it is `create` when the registry row is missing plus `deploy`,
122
+ and the only thing it adds is the check nobody made — that the address serves the bundle. It prints
123
+ the game, the revision, the bytes, the URL, and the status the host answered, in that order.
124
+
125
+ ```
126
+ $ plupin up ./dist
127
+ upload 475 B ...
128
+ game dude-theft (host, created)
129
+ revision r2:bundles/dude-theft/c0c802d9db82...
130
+ bytes 475 (3 files)
131
+ url https://dude-theft.plupin.com
132
+ HTTP 200
133
+ ```
134
+
135
+ A second run uploads a new revision to the same game: the row is read, never created twice, so no
136
+ `already exists` and no duplicate. The exit codes are the same as everywhere: `1` a folder or a
137
+ manifest the platform would refuse (checked before anything is written), `2` not signed in, `3` the
138
+ platform refused, `4` the host never answered `200` within 15 s — in which case the last status and
139
+ the deployed revision are printed and nothing is called a success — and `5` the build failed its checks.
140
+
141
+ ## Publish locally, no credentials
142
+
143
+ The same `create` + upload path runs against a local API, so the whole publish flow is provable on
144
+ one machine with no platform account and no Cloudflare credential. The host is
145
+ `http://<game>.localhost:3001`, served by `apps/web`'s dev server (`bun run dev` there): vite on
146
+ `:3001` forwards that host to the production worker under `wrangler dev` on `:3002`, which reads the
147
+ same local R2 bucket the API worker wrote.
148
+
149
+ ```
150
+ bun run db:seed # the creator plupin login --dev signs in as
151
+ bun run dev:server # API on :3000
152
+ plupin login --dev --api http://localhost:3000
153
+ plupin up ./dist --api http://localhost:3000 # prints http://<id>.localhost:3001
154
+ ```
155
+
156
+ `up` is not weakened here: it still measures the build into `.plupin/checks.json` and still polls the
157
+ address until it returns the entry file it just uploaded, byte for byte.
158
+
159
+ ## `plupin deploy [dir]`
160
+
161
+ | | |
162
+ |---|---|
163
+ | `dir` | build output (default `./dist`) |
164
+ | `--dry-run` | hash and print the manifest, upload nothing |
165
+ | `--rollback <bundleRef>` | move the live pointer to a bundle this game already deployed, no upload |
166
+ | `--api <url>` | talk to this API instead of the one `login` stored (also `$PLUPIN_API_URL`) |
167
+ | `--game-origin <url>` | print this URL instead of `https://<id>.plupin.com` (for a local preview) |
168
+
169
+ Reads `plupin.json` from `dir` and rejects exactly what the platform rejects (`@plupin/game-manifest`),
170
+ hashes every file with sha256, and prints one line per file plus the bundle hash. The bundle hash is
171
+ sha256 over the sorted `path\nsha256\n` lines — the same algorithm the server runs, so the CLI knows
172
+ the prefix before it uploads anything.
173
+
174
+ Uploads `N` multipart parts in one request: the part **name** is the file's path, because that is
175
+ the one string a multipart parser cannot rewrite. If the live pointer already equals the prefix this
176
+ tree hashes to, nothing is sent and the command says so. `node_modules/` and `.git/` are never part
177
+ of a bundle. The caps are the platform's: 200 files, 8 MiB per file, 25 MiB total.
178
+
179
+ On success it prints the pointer and the URL; the game is at `<id>.plupin.com` immediately, with no
180
+ build step on the platform.
181
+
182
+ `--rollback` takes the full pointer (`r2:bundles/<gameId>/<sha256>`) and moves it back in one
183
+ statement. Only a bundle this game deployed can be selected, and the old prefixes are never deleted,
184
+ so the bytes are guaranteed to still exist.
185
+
186
+ ```
187
+ $ plupin deploy ./dist
188
+ game dude-theft (host)
189
+ bundle 3 files, 475 B, c0c802d9db82
190
+ app.js 175 B a1b7b14b
191
+ index.html 219 B 5f6eb1d6
192
+ style.css 81 B ebca1488
193
+ upload 475 B ...
194
+ live r2:bundles/dude-theft/c0c802d9db827dc15b9b4c1c2344f4f077cfbd46433826c0173ae7bbec1cb0b9
195
+ url https://dude-theft.plupin.com
196
+ done 3 files, 475 bytes
197
+ ```
198
+
199
+ ## `plupin login`
200
+
201
+ Writes `~/.config/plupin/credentials.json` with mode `600`. Reads the token from standard input so it
202
+ never appears in a command line transcript; `--token <token>` exists for scripts that already keep
203
+ the secret out of the transcript, and `--token -` reads stdin explicitly.
204
+
205
+ The token is an OAuth 2.1 access token (PKCE, loopback redirect) minted for the `/mcp` resource with
206
+ `mcp:read` and `mcp:deploy`, which is what the hosted surface and the plain upload routes verify.
207
+ `--token` is the escape hatch for a machine with no browser: it reads the shape of what it was given,
208
+ so a pasted browser session token is stored as a session (sent as a cookie) and an OAuth token as a
209
+ bearer, instead of being sent the wrong way and answering 401. Either way it is a full account
210
+ credential: treat it like a password, and do not commit it.
211
+
212
+ ## `plupin status [dir]`
213
+
214
+ Prints the live pointer, the live bundle's byte size and file count, and when the pointer last
215
+ moved. `--game <id>` reads that game instead of the `plupin.json` in `dir`.
216
+
217
+ ```
218
+ $ plupin status
219
+ game dude-theft
220
+ bundle r2:bundles/dude-theft/c0c802d9...
221
+ size 475 bytes (3 files)
222
+ deployed 2026-10-22T07:26:00.000Z
223
+ ```
224
+
225
+ A game deployed before the platform recorded bundle sizes reports `unknown`, never `0`.
226
+
227
+ ## Exit codes
228
+
229
+ | | |
230
+ |---|---|
231
+ | `0` | done |
232
+ | `1` | invalid `plupin.json`, bad argument, or a bundle that cannot be what the platform accepts |
233
+ | `2` | not signed in, or the token was refused |
234
+ | `3` | the platform refused the bundle (path, entry, size, missing game) |
235
+ | `4` | the API could not be reached |
236
+
237
+ ## `plupin mcp`
238
+
239
+ Runs the MCP server over stdio. See [mcp.md](mcp.md).
240
+
241
+ ## `plupin connect claude | codex`
242
+
243
+ One command per agent CLI, so an assistant gets both Plupin surfaces without anyone editing JSON:
244
+
245
+ ```sh
246
+ plupin login # once: the access token the hosted surface verifies
247
+ plupin connect claude # ~/.claude.json
248
+ plupin connect codex # ~/.codex/config.toml
249
+ ```
250
+
251
+ | server | transport | tools |
252
+ |---|---|---|
253
+ | `plupin` | stdio, `bunx -y @plupin/cli mcp` | `manifest_check`, `dev_start`, `dev_status`, `dev_stop`, `docs` |
254
+ | `plupin-hosted` | streamable HTTP, `<api>/mcp` | the hosted surface: `emote_new`, `emote_preview`, `emote_push`, `deploy`, `game_*`, `rooms_*`, `docs`, `whoami` |
255
+
256
+ The config is the **user-level** file, not a project one: the hosted entry carries a bearer token and
257
+ a project config is a file that gets committed. Nothing else in that file changes — another server
258
+ added by hand keeps its entry, and Codex's `[mcp_servers.plupin]` table (plus a stale `.env`
259
+ sub-table, plus a copy someone pasted) is replaced in place rather than duplicated. The token is
260
+ written into the file, mode `600`, and never printed.
261
+
262
+ `--api <url>` points the hosted entry somewhere else (dev, a local worker). `CLAUDE_CONFIG_DIR` and
263
+ `CODEX_HOME` move the two files, which is how the tests drive this without touching a real config.
264
+
265
+ After writing, the command asks the hosted surface for `tools/list` with the token it just wrote and
266
+ prints what answered:
267
+
268
+ ```
269
+ $ plupin connect claude
270
+ agent claude
271
+ config /Users/you/.claude.json
272
+ mode 600
273
+ server plupin, plupin-hosted (stdio: bunx -y @plupin/cli mcp)
274
+ hosted https://api.plupin.com/mcp — token written, never printed
275
+ tools 14 from the hosted surface: docs, whoami, manifest_check, ...
276
+ done restart claude so it loads the servers
277
+ ```
278
+
279
+ A refused token is printed as the status the server answered and the config stays written; `401`
280
+ means the token expired, so `plupin login` and run it again. Signed out, or signed in with a pasted
281
+ browser session rather than the OAuth token, only the stdio server is written and the receipt says
282
+ which command to run.
283
+
284
+ ## Releasing
285
+
286
+ Two packages, one order: **the SDK first, the CLI second.** The CLI bundles these chapters and the
287
+ production room, and its own release is what a creator runs against the SDK version named in these
288
+ docs, so a CLI published first would point at an SDK that does not exist yet.
289
+
290
+ Both manifests are written for `bun install` (`workspace:*`, `catalog:`), which npm cannot resolve.
291
+ `npm pack` publishes `package.json` byte for byte, so `prepack` runs
292
+ [`scripts/publish-manifest.ts`](../../scripts/publish-manifest.ts): it builds `dist`, rewrites the
293
+ manifest to the whitelisted publish shape (no `devDependencies`, no repo scripts, no `workspace:` or
294
+ `catalog:` ranges) and `postpack` restores the source manifest. A pack that dies halfway leaves
295
+ `package.json.workspace` behind; `bun scripts/publish-manifest.ts restore` puts it back.
296
+
297
+ From a clean `dev` where both packages pass `bun run check-types` and `bun run test:unit`:
298
+
299
+ ```sh
300
+ cd packages/game-sdk
301
+ bun run build && npm pack # -> plupin-game-sdk-0.2.0.tgz
302
+ npm publish --access public plupin-game-sdk-0.2.0.tgz
303
+
304
+ cd ../cli
305
+ bun run build && npm pack # -> plupin-cli-0.2.0.tgz
306
+ npm publish --access public plupin-cli-0.2.0.tgz
307
+ ```
308
+
309
+ `npm pack` prints every file that goes in. The list must be `dist/` only: `src/` is not packed, and
310
+ that is why the manifest drops the `bun` export condition (it points at `src/index.ts`).
311
+
312
+ Prove the published pair from an empty directory, never from the monorepo:
313
+
314
+ ```sh
315
+ cd "$(mktemp -d)" && npm init -y
316
+ npm install @plupin/game-sdk@0.2.0 @plupin/cli@0.2.0
317
+ ./node_modules/.bin/plupin --help
318
+ node --input-type=module -e 'import { Room } from "@plupin/game-sdk"; console.log(typeof Room)'
319
+ ```
320
+
321
+ ### Rollback
322
+
323
+ `npm unpublish` is the only way to remove a version, and npm allows it **only within 72 hours** of
324
+ the publish (and only while nothing else depends on it). After that the version is permanent:
325
+
326
+ | situation | command | what it does |
327
+ |---|---|---|
328
+ | published minutes ago, wrong files | `npm unpublish @plupin/cli@0.2.0 --force` | deletes the version; every lockfile pinning it breaks |
329
+ | published, then a bug found | `npm deprecate @plupin/cli@0.2.0 "broken, use 0.2.1"` | keeps the tarball installable, prints the warning on every install |
330
+ | always | publish a fixed patch, `npm deprecate` the old one | the only lane that stays open after 72 hours |
331
+
332
+ Deprecate rather than unpublish once anyone may have installed it: an unpublish turns their build
333
+ into a 404, a deprecation tells them what to move to. A published version number is never reused,
334
+ even after an unpublish.
@@ -0,0 +1,42 @@
1
+ # Errors
2
+
3
+ Every failure the platform reports to a game arrives as one object, never as a string and never as a
4
+ stack trace:
5
+
6
+ ```ts
7
+ { code: "BOARD_NOT_FOUND", message: "unknown_board", fix: "Add this board id to `leaderboards` …", retryable: false }
8
+ ```
9
+
10
+ - `code` is a typed value (`ErrorCode`, listed in `ERROR_CODES`) exported by `@plupin/game-sdk`, as is
11
+ the `AppError` class, so `error instanceof AppError` holds. Compare against it; do not parse `message`.
12
+ - `message` says what happened, in the platform's own words.
13
+ - `fix` is one sentence: the change that makes the same call work.
14
+ - `retryable` is true only for the three failures where an unchanged retry can succeed
15
+ (`TOO_MANY_REQUESTS`, `SERVER_UNAVAILABLE`, `NETWORK_UNREACHABLE`).
16
+ - `retryAfterSeconds` is the wait the platform named, from the body or the `Retry-After` header, and is
17
+ absent when it named none.
18
+
19
+ A game shows `message` to a person and acts on `code` and `retryable`. Logging `JSON.stringify(error)`
20
+ is safe: it carries no stack, no path and no secret.
21
+
22
+ ## Codes
23
+
24
+ | code | fix |
25
+ |---|---|
26
+ | `NOT_FOUND` | Name something that exists: publish the game first (`plupin up`) and pass the id from its plupin.json. |
27
+ | `CONFLICT` | Read the current state and retry with the value it now holds; this call lost a race with another write. |
28
+ | `TOO_MANY_REQUESTS` | Wait the error's `retryAfterSeconds` (a few seconds when it has none), then retry; this client is calling faster than its limit allows. |
29
+ | `FORBIDDEN` | Do not retry: this origin or account may not make this call, so change where it runs or who is signed in. |
30
+ | `UNAUTHENTICATED` | Sign in at https://plupin.com in the same browser, then retry; a game page holds no session cookie of its own. |
31
+ | `BOARD_NOT_FOUND` | Add this board id to `leaderboards` in plupin.json and deploy again; the platform ranks only boards a game declared. |
32
+ | `WINDOW_INVALID` | Pass the key the board's window produces (`2026-10-31` for daily, `2026-W44` for weekly) or omit `window` to read the current one. |
33
+ | `INPUT_INVALID` | Fix the argument the message names before retrying; the platform refused to read the request at all. |
34
+ | `SERVER_UNAVAILABLE` | Retry once after a short delay; if it persists the platform is down, so report it instead of changing the game. |
35
+ | `NETWORK_UNREACHABLE` | Check that the page is online and that the SDK's `url` points at the platform (`https://api.plupin.com`), then retry. |
36
+ | `RESPONSE_INVALID` | Do not retry blindly: the endpoint answered something this SDK cannot read, so the SDK and the platform are different versions. |
37
+
38
+ ## What is not an error code
39
+
40
+ A refused claim inside a room (`stale_claim`, `out_of_range`, `cooldown`, …) is a game event, not a
41
+ failure: it arrives on `room.on("error", …)` while the match keeps running, and the SDK's method
42
+ calls do not throw for it. The codes above are what a promise rejects with.
@@ -0,0 +1,120 @@
1
+ # Putting an existing Three.js game online
2
+
3
+ This is the path for a game that already exists on a laptop — a Vite + Three.js build, a canvas 2D
4
+ game, anything that ends up as static files. It does not assume the game was written for Plupin.
5
+
6
+ The target is concrete: `~/Code/dude-theft-three` (Vite, Three.js, procedural city, `src/main.ts`
7
+ running the frame loop).
8
+
9
+ ## 1. Install the client library
10
+
11
+ `@plupin/game-sdk` has three exports and no engine dependency:
12
+
13
+ ```ts
14
+ import { Room, Peers, Interpolator } from "@plupin/game-sdk"
15
+ ```
16
+
17
+ It is not on the public registry yet. Two ways in until it is:
18
+
19
+ ```bash
20
+ # local tarball (what scripts/verify-sdk-package.sh builds and checks)
21
+ npm pack packages/game-sdk && npm install ./plupin-game-sdk-0.1.0.tgz
22
+
23
+ # or a git dependency, pinned to a tag
24
+ npm install "github:himanusia/plupin#v0.3.51" --workspace=packages/game-sdk
25
+ ```
26
+
27
+ ## 2. Describe the game
28
+
29
+ `plupin.json` sits next to the built bundle (`dist/plupin.json`), because the platform reads it, never
30
+ the game:
31
+
32
+ ```json
33
+ {
34
+ "id": "dude-theft",
35
+ "name": "Dude Theft",
36
+ "entry": "index.html",
37
+ "authority": "host",
38
+ "maxPlayers": 8,
39
+ "renderer": "3d"
40
+ }
41
+ ```
42
+
43
+ `authority` is the one decision that matters:
44
+
45
+ | | who simulates | pick it when |
46
+ |---|---|---|
47
+ | `host` | one player's client; the room relays its frames | physics worlds, driving, ragdolls — anything where rewriting the sim as a server tick is not worth it |
48
+ | `server` | the platform | turn-based, score-based, referee'd PvP where a client must not be believed |
49
+
50
+ Dude Theft is `host`. The room still elects the host and stamps `from` on every frame, so no player can
51
+ speak as another.
52
+
53
+ ## 3. Wire the frame loop
54
+
55
+ `packages/game-sdk/examples/net.ts` is the adapter — copy it, do not re-derive it. In a game with one
56
+ player object and a car, the integration is four hooks:
57
+
58
+ 1. **Broadcast at a fixed rate, not per frame.** 15 Hz for a car is plenty; 60 Hz of JSON is what makes
59
+ a room feel laggy. Keep a `lastSent` timestamp in the animate loop.
60
+ 2. **Render remotes on a delay.** `Peers` buffers ~120 ms and blends, so a remote car moves smoothly
61
+ instead of teleporting. One `sample(now)` per rendered frame.
62
+ 3. **Send a pose, not the world.** `{ p: [x, y, z], yaw, speed }` is enough for a body or a car. Do not
63
+ ship meshes, materials or the ragdoll skeleton.
64
+ 4. **Own only what you own.** Local input drives the local body immediately; the remote bodies are
65
+ read-only copies.
66
+
67
+ ## 4. Run it locally, the way production runs it
68
+
69
+ ```bash
70
+ npm run build # → dist/
71
+ bun packages/cli/src/bin.ts dev ./dist --port 8787
72
+ ```
73
+
74
+ One origin serves the bundle and hosts the room, exactly as `<id>.plupin.com` does. Open two tabs. That
75
+ is the whole local loop; there is no separate socket server to run.
76
+
77
+ ## 5. Read the board
78
+
79
+ A board you declared in `plupin.json` is read with the SDK, not with a hand-written path:
80
+
81
+ ```ts
82
+ import { Leaderboard } from "@plupin/game-sdk"
83
+
84
+ const board = new Leaderboard({ gameId: "dude-theft", board: "distance" })
85
+ const page = await board.top(10, { around: 3 })
86
+ scoreboard.render(page.entries, page.me)
87
+ ```
88
+
89
+ There is no `submit`: the room records the score of the match it finished, and the platform refuses a
90
+ number that arrives from a client. `page.me` is your own row, so a rank outside the top ten still
91
+ reads correctly. A failure arrives as a typed `AppError` with a `fix` sentence
92
+ ([errors.md](./errors.md)); nothing in this path is a raw `fetch`.
93
+
94
+ ## 6. Let an agent drive the loop
95
+
96
+ `plupin mcp` is a stdio MCP server with `manifest_check`, `dev_start`, `dev_status`, `dev_stop` and
97
+ `docs`. Point an MCP client at `bun packages/cli/src/bin.ts mcp` and an assistant can validate the
98
+ manifest and manage the dev server without shell access.
99
+
100
+ ## 7. Go live
101
+
102
+ `plupin deploy` is written but gated on Cloudflare R2 activation (`BUNDLES` binding). Until the bucket
103
+ exists the command cannot upload a bundle, so there is no half-truth to tell here: live multiplayer is
104
+ blocked on that account switch, not on the SDK, the room, or the CLI.
105
+
106
+ ## What is proven, and how
107
+
108
+ | claim | evidence |
109
+ |---|---|
110
+ | An outside game gets a room from `plupin dev` | `packages/game-sdk/tests/net.test.ts` boots the real server for a game that has only `index.html` + `plupin.json` |
111
+ | Two clients exchange poses and despawn | same test: spawn, interpolated updates, removal after the timeout |
112
+ | The published package installs cleanly | `scripts/verify-sdk-package.sh` packs, installs into an empty project, asserts the exports |
113
+ | Remote bodies move smoothly | `Peers` + `Interpolator`, 120 ms buffer; the example passes arrival time as the sample clock |
114
+
115
+ ## The trap that cost a bug
116
+
117
+ `frame.ts` is the **room's** clock. Compare it with `performance.now()` and every timeout comparison is
118
+ false, so remote peers never despawn — the test above failed for exactly that reason until the call
119
+ site switched to arrival time. If you need real timestamps (replay, lag compensation), measure an
120
+ offset once and pass `stamp`.
@@ -0,0 +1,135 @@
1
+ # Leaderboards
2
+
3
+ A board is a ranking the platform keeps for a game: a top list, plus every player's own place in
4
+ it. The platform stores numbers it was given and never guesses what they mean, so one game can
5
+ declare several boards with different directions and different time windows.
6
+
7
+ ## Declare it
8
+
9
+ In `plupin.json` (a bundle) or in the document manifest (a studio game):
10
+
11
+ ```json
12
+ {
13
+ "leaderboards": [
14
+ { "id": "score", "sort": "desc", "aggregate": "best", "window": "all" },
15
+ { "id": "fastest", "sort": "asc", "aggregate": "best", "window": "weekly" },
16
+ { "id": "distance", "sort": "desc", "aggregate": "sum", "window": "daily" }
17
+ ]
18
+ }
19
+ ```
20
+
21
+ | field | values | default | meaning |
22
+ |---|---|---|---|
23
+ | `id` | lowercase letters, digits, dashes | — | your name for the board. The platform never maps it to anything |
24
+ | `sort` | `"desc"` \| `"asc"` | `"desc"` | which end of the numbers is better. `"asc"` for a duration where smaller is better |
25
+ | `aggregate` | `"best"` \| `"last"` \| `"sum"` | `"best"` | how repeated runs fold into one place |
26
+ | `window` | `"all"` \| `"daily"` \| `"weekly"` | `"all"` | the stretch of time one board covers |
27
+
28
+ At most eight boards. An id outside the character set is a manifest error, so a game never
29
+ publishes with a board nobody can address.
30
+
31
+ ### Aggregates
32
+
33
+ | `aggregate` | one place per player per window holds | runs are |
34
+ |---|---|---|
35
+ | `best` | the number that wins the board's direction | folded: a worse run changes nothing |
36
+ | `sum` | the total of every run in the window | folded: each run adds its number |
37
+ | `last` | the newest run's number | kept: every run stays readable |
38
+
39
+ `best` follows `sort`: on a `"desc"` board it keeps the highest number, on an `"asc"` board the
40
+ lowest.
41
+
42
+ ### Windows
43
+
44
+ Windows are UTC. `daily` is one UTC day, keyed `2026-10-23`; `weekly` is an ISO week (Monday
45
+ 00:00 UTC, keyed `2026-W43`). A run is bucketed by **when it was played**, taken from the room's
46
+ own clock when the match ended — not from the request that delivered it, and never from the
47
+ client's clock. A run that finished at 23:59 and was stored at 00:02 still belongs to the day it
48
+ was played.
49
+
50
+ ## Where the number comes from
51
+
52
+ The room produces it. When a match ends, the room reads the document's `outcome` — the same value
53
+ that already arrives in the final snapshot — and for each declared board takes one number per
54
+ seat:
55
+
56
+ ```json
57
+ {
58
+ "kind": "win",
59
+ "standings": [{ "playerId": "<seat>", "rank": 1, "score": 1200 }],
60
+ "scores": { "fastest": { "<seat>": 61_400 } }
61
+ }
62
+ ```
63
+
64
+ - `scores[boardId][seatId]` is the explicit form. Use it when two boards disagree about a run.
65
+ - `standings[].score` is used for every declared board when the result carries no `scores` at
66
+ all. That is the shape a document already produces, so a game with one board needs no extra
67
+ field.
68
+ - A board with no number for a seat simply has no row for that seat. A missing number is never
69
+ read as `0`.
70
+
71
+ There is **no client endpoint for a score**. A browser cannot submit one, and there is nothing to
72
+ spoof: the only writer is the room that played the match.
73
+
74
+ ## Read it
75
+
76
+ ```
77
+ GET /api/games/:gameId/leaderboards/:boardId?window=&limit=&around=
78
+ ```
79
+
80
+ | query | default | meaning |
81
+ |---|---|---|
82
+ | `limit` | `10` | how many top rows to return, 1–100 |
83
+ | `window` | the current window | read a past window by its key (`2026-10-23`, `2026-W43`, `all`) |
84
+ | `around` | off | also return this many rows above and below the caller (0–50) |
85
+
86
+ ```json
87
+ {
88
+ "gameId": "my-game",
89
+ "revision": "<revision>",
90
+ "board": { "id": "score", "sort": "desc", "aggregate": "best", "window": "daily" },
91
+ "window": { "key": "2026-10-23", "start": 1792723200000 },
92
+ "total": 812,
93
+ "entries": [
94
+ { "rank": 1, "name": "Rina", "score": 1200, "submittedAt": 1792730496123, "you": false }
95
+ ],
96
+ "me": { "rank": 147, "name": "Budi", "score": 430, "submittedAt": 1792740000000, "you": true },
97
+ "around": [
98
+ { "rank": 146, "name": "Sari", "score": 432, "submittedAt": 1792739000000, "you": false },
99
+ { "rank": 147, "name": "Budi", "score": 430, "submittedAt": 1792740000000, "you": true },
100
+ { "rank": 148, "name": "Tono", "score": 429, "submittedAt": 1792741000000, "you": false }
101
+ ]
102
+ }
103
+ ```
104
+
105
+ - `me` is always present when the caller has a row, even when they are nowhere near the top.
106
+ - `around` is a contiguous slice centred on the caller and includes them, so a place outside the
107
+ top hundred is still readable. It is `[]` when the caller has no row, and `null` when `around`
108
+ was not asked for.
109
+ - `total` is how many players have a row in this window.
110
+ - Names and numbers only: the identity behind a row is never returned, and neither is the room.
111
+
112
+ ## What is refused
113
+
114
+ | situation | result |
115
+ |---|---|
116
+ | a client posts a score | no such route exists; the request is a 404 |
117
+ | the room is not finished | nothing is written |
118
+ | the seat was not in that room, or is a bot | nothing is written for it |
119
+ | the seat has no identity (neither signed in nor counted as a guest) | nothing is written for it |
120
+ | the same room retries its submission | one row: the claim is keyed on (room, revision, board, seat) |
121
+ | the game is a draft, unlisted-and-unpublished, or unknown | the read answers 404, never an empty board |
122
+
123
+ ## Limits
124
+
125
+ - Eight boards per game.
126
+ - `limit` is capped at 100 and `around` at 50.
127
+ - Scores are numbers (integers or decimals); a non-finite value is refused.
128
+ - Names are the seat names a player already chose, capped at 24 characters.
129
+
130
+ ## Status
131
+
132
+ Implemented and covered by local tests: the manifest field in both schemas, the ranking tables,
133
+ the room's submission path, and the read route. Not yet deployed, and no editor surface shows a
134
+ board to a creator yet. A `host`-authority game has no server-side result, so its boards stay
135
+ empty by construction — a client-reported score is exactly what this primitive refuses.