<!--
OneCompanion developer guide, from https://onecompanion.net/developers/guide (raw: https://onecompanion.net/developers/guide.md).
It describes how to build a browser game for the OneCompanion platform, integrate it with the platform
(the mount() contract, storage, rooms) and publish it. Use it as the reference when helping with a game's
integration; the sample game is https://github.com/onecompanion-net/sample-game.
-->

# Developer guide

Build a browser game in JavaScript or TypeScript, upload it with one command, and OneCompanion hosts it, lists it in
the catalog and runs its multiplayer rooms. This guide covers everything your game needs to know about the platform.

## How it works

1. **You build** a game package: a `game.json` manifest, a client module that exports `mount()`, its text, store
   listing and art.
2. **The CLI checks and uploads it** (`onecompanion-game publish`). It builds your code with Bun, runs the same checks
   the platform runs, and sends each file. The platform never unpacks archives.
3. **Automatic checks run again** on our side. If they fail, the version is `rejected_auto` and you get the list of
   problems by email and on your studio page.
4. **Our team reviews** every version before players see it. You get an email when it is approved, or when the
   reviewer asks for changes (with their notes).
5. **You release it** when you are ready, from your studio page or with the CLI. Releasing again with an earlier
   version rolls back.

Your game runs in a sandboxed frame served from `https://onecompanion.net/g/…`. It never sees players' accounts, reaches the network
only through its room, and keeps its saved data with the platform.

## Quick start

You need [Bun](https://bun.sh) 1.3 or later (the tools run on it, even if you use npm), a studio and a command-line token from your studio page. To get a
studio, apply at [https://onecompanion.net/developers/apply](https://onecompanion.net/developers/apply): our team reviews every application and
emails you the answer.

```bash
git clone https://github.com/onecompanion-net/sample-game my-game
cd my-game
bun install
bun run dev        # http://localhost:5191: solo
                   # http://localhost:5191/?net=room in two tabs: multiplayer through a fake room
                   # add &lang=vi or &dir=rtl to check another language and right-to-left layout
bun run validate   # build the upload bundle and run every check the platform runs
```

Prefer npm? It installs the packages and runs the scripts; Bun still has to be installed:

```bash
git clone https://github.com/onecompanion-net/sample-game my-game
cd my-game
npm install
npm run dev
npm run validate
```

The sample, **Paint Party**, is a small complete game: a TypeScript client, the `relay` room kind, text in two
languages, a store listing in all twelve, and the art the catalog needs. Copy it, then:

1. In `game.json`, set `id` to your own name (it becomes your URL and can never be reused) and `studio` to your
   studio's handle.
2. Change the title, text and art.
3. Publish:

```bash
export ONECOMPANION_API=https://onecompanion.net
export ONECOMPANION_TOKEN=oc_…        # from your studio page; treat it like a password
bun run publish:game # or: npm run publish:game
```

> Run the CLI through your project's scripts (`bun run validate` or `npm run validate`), which use the copy
> installed in `node_modules`. Do not run `bunx onecompanion-game` or `npx onecompanion-game` in a project that does
> not have it installed: they would download whatever package has that name from the public npm registry. The CLI is
> not on the npm registry; it installs from GitHub.

### Start from a template

No game yet, or want a clean start? The CLI writes a small playable game that passes `validate` as generated:

```bash
bunx github:onecompanion-net/game-cli init my-game --template relay --studio your-studio
cd my-game && bun install && bun run dev
```

| Template         | What you get                                                                                                               |
| ---------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `solo`           | A solo game with a saved best score: the smallest complete game on the contract                                            |
| `relay`          | Everyone in the room moves a light: coalesced, validated messages and the roster                                           |
| `lockstep`       | Each player commands their own unit: a deterministic simulation with a test, and a local room for solo                     |
| `verified-solo`  | A ranked solo game: a tiny server module replays each run with the same code before the time counts                        |
| `persistent-rpg` | A crypt with one class, a loot table and trades: characters the platform keeps (see [Persistent games](#persistent-games)) |

Each comes with placeholder art at the right sizes, an English listing, and the store's other required languages as
untranslated copies (see [Text and languages](#text-and-languages)).

### Adding the CLI to your own project

```bash
bun add -d github:onecompanion-net/game-cli
# or
npm install -D github:onecompanion-net/game-cli
```

Then add the scripts to `package.json`:

```json
{
	"scripts": {
		"validate": "onecompanion-game validate .",
		"pack": "onecompanion-game pack .",
		"publish:game": "onecompanion-game publish ."
	}
}
```

To try the checks once without installing anything, run it straight from GitHub:

```bash
npx github:onecompanion-net/game-cli validate .
```

## Integrate with an AI coding tool

Already have a game? Open its folder in Claude Code, Cursor, GitHub Copilot or another AI coding tool and give it
this prompt. It reads this guide, adapts your game to the platform, checks it with the CLI and stops before
publishing, so you upload it yourself. Replace `<my-studio-handle>` with your studio's handle (your studio page has a
copy with it filled in).

```text
I want to publish my browser game on OneCompanion (https://onecompanion.net), which hosts it, lists it in its catalog and runs its multiplayer rooms. Help me integrate this project with the platform and get it ready to upload.

1. Read the developer guide first: https://onecompanion.net/developers/guide.md. It is the contract; where my code disagrees with it, the guide wins. When unsure, compare with the sample game: https://github.com/onecompanion-net/sample-game.
   Use the OneCompanion integration skill as well: https://github.com/onecompanion-net/skills (the skill is skills/onecompanion-integration). If it is not installed in this tool, read its SKILL.md and the reference files it points to; use its templates (contract, client, relay, lockstep, dev host) instead of writing them from scratch.
2. Study this project and show me a short plan before you change anything: the engine, how the game starts and what it draws into, where its text lives, how it saves, any network code, and which room kind fits (none, relay or lockstep; server only if we were invited).
3. Integrate without breaking how the game runs today:
   - Add game.json with "studio": "<my-studio-handle>", an "id" I approve (it becomes the URL and can never be reused) and "version": "1.0.0".
   - Add a client entry that exports mount(host, options) and returns { onMessage, pause, resume, dispose }. Copy the types from the guide into src/contract.ts; import nothing from the platform. Draw only inside host, send onEvent({ type: 'ready' }) after the first frame, and make dispose() undo everything (animation loops, timers, listeners, DOM nodes, WebGL contexts, audio, workers).
   - Move every player-facing string into messages/en.json and show it through options.t (ICU plurals for counts). Lay out with CSS logical properties so right-to-left works.
   - Save with options.storage instead of localStorage, IndexedDB or cookies. Remove fetch and WebSocket calls to other hosts; load our own files with relative URLs.
   - For multiplayer, send with options.online.send and receive in onMessage, using the guide's byte formats exactly, and validate every message. For lockstep, keep the simulation deterministic (the room's seed, no Math.random() or clock).
   - Write listing/en.json (with "play" and "modes" lines if they fit the game); step 6 translates it. Prepare the art at the sizes in the guide, set the rating, and list every third-party asset and its licence under rights.
   - Keep the client entry and its static imports under 450 KB gzip; load the rest with dynamic import().
4. Add the CLI as a dev dependency from GitHub, never from the npm registry by name: "bun add -d github:onecompanion-net/game-cli" (or "npm install -D github:onecompanion-net/game-cli"). Add the scripts "validate": "onecompanion-game validate .", "i18n": "onecompanion-game i18n ." and "publish:game": "onecompanion-game publish .". The tools need Bun 1.3 or later even when I use npm.
5. Copy the sample's dev page (index.html and src/dev.ts) so I can test solo, with ?net=room in two tabs, and with &lang=vi and &dir=rtl.
6. Run the i18n script and translate every file it marks "$untranslated" (the 12 launch store locales are required; in-game languages are up to me), removing the marker from each file you finish. Then run the skill's preflight check (node <skill folder>/scripts/preflight.mjs ., from an installed or cloned copy of the skill), then the validate script, and fix every issue until both pass.
7. Then stop. Tell me what you changed, what you could not do and what I should check by hand. Do not publish: I will set ONECOMPANION_API=https://onecompanion.net and ONECOMPANION_TOKEN in my own terminal and run the publish:game script. Never ask for the token, print it, write it to a file or commit it.
```

Review its changes as you would a colleague's, and test the game by hand before you publish. Never paste your studio
token into an AI chat: set `ONECOMPANION_TOKEN` in your own terminal when you publish.

### The OneCompanion skill

Give your AI coding tool the **OneCompanion integration skill**
([github.com/onecompanion-net/skills](https://github.com/onecompanion-net/skills)): the platform contract, porting
notes per engine, templates for the client, relay and lockstep rooms and a local dev host, and a preflight check for
problems the CLI cannot see (calls to other hosts, asset paths that will not load in the frame, hard-coded text). The
prompt above tells your tool to use it, installed or not.

```bash
# Claude Code
/plugin marketplace add onecompanion-net/skills
/plugin install onecompanion@onecompanion-skills

# Most other AI coding tools (Cursor, Codex, GitHub Copilot, Gemini CLI…)
npx skills add onecompanion-net/skills
```

Or clone the repository and point your tool's instructions file (`AGENTS.md`, `.cursor/rules`,
`.github/copilot-instructions.md`) at `skills/onecompanion-integration/SKILL.md`. Run the preflight check yourself with
`node skills/onecompanion-integration/scripts/preflight.mjs path/to/your-game`.

The skill is licensed for building and publishing games: use it for your games, not to build a competing platform or
its tools (see its `NOTICE.md`).

## Bring an existing HTML5 game

A game you already ship as a web build (on itch.io, your own site, a game jam page) usually needs changes to how it
starts and stops, not to the game itself. Keep the engine; change three things:

1. **Start in `mount(host, options)`, stop in `dispose()`.** Find the code that creates the game (a canvas on
   `document.body`, `new Phaser.Game`, a renderer, an `init()` on `DOMContentLoaded`) and move it into `mount`,
   drawing into `host` and sized from it. Give every global side effect (listeners on `window`, timers, audio
   contexts, workers) a matching teardown in `dispose()`.
2. **Load from the bundle.** Import your assets and resolve them with `new URL(imported, import.meta.url)`; nothing
   outside your bundle is reachable (no CDNs, analytics, ads or other servers). Save with `options.storage`.
3. **Text through `t`.** Move the strings players see into `messages/en.json`; then `onecompanion-game i18n` helps
   you translate them.

Engines, briefly: Phaser takes `parent: host` and `game.destroy(true)`; Three.js renders into a canvas you append to
`host` and needs `renderer.dispose()`; PixiJS uses `app.init({ resizeTo: host })` and `app.destroy()`. Exports that
expect to own the page (Unity WebGL, Godot `.pck`, most GameMaker or Construct exports) cannot be packaged as they are.
The [OneCompanion skill](https://github.com/onecompanion-net/skills) has notes for each engine.

**Then add rooms.** Pick the kind that fits the game you have:

- **relay** for party and co-op games where players can trust each other: send small messages (positions, actions)
  and validate what you receive. The `relay` template shows the pattern.
- **lockstep** when the game is already a simulation you can make deterministic (strategy, tactics, physics on
  integers). A pattern that works well: **each player commands their own unit**. Players send orders, every client
  applies them at the same step, and nobody's game ever acts for anyone else. The `lockstep` template is built on it.
- **server** when outcomes must be decided by a server you write (ranked play). By invitation.

Your [AI coding tool](#integrate-with-an-ai-coding-tool) can do most of this with the prompt above.

## The game package

```
game.json              the manifest
src/client.ts          your game: exports mount()
src/server.ts          only for the "server" room kind
messages/<locale>.json in-game text (en required)
listing/<locale>.json  store text: the 12 launch locales, more optional
art/                   cover, stills and their thumbnails, share image
```

### game.json

```jsonc
{
	"manifest": 1,
	"id": "your-game", // a-z, 0-9 and -, 3 to 32 characters; your URL; never reused
	"title": "Your Game",
	"version": "1.0.0", // semver, higher than every earlier upload
	"studio": "your-studio",
	"genres": ["action"], // action | shooter | idle | rpg
	"players": { "min": 1, "max": 8 }, // at most 16
	"modes": ["solo", "coop"], // solo | coop | ffa | tdm
	"entry": { "client": "./src/client.ts" }, // add "server" for the server room kind
	"realtime": { "kind": "relay", "tickRate": 0, "snapshotRate": 0, "protocol": 1 },
	"locales": ["en", "vi"], // in-game text you ship; en is required
	"messages": "./messages",
	"listing": "./listing",
	"media": {
		"cover": "./art/cover.webp",
		"stills": ["./art/a.webp", "./art/b.webp", "./art/c.webp"],
		"share": "./art/share.jpg"
	},
	"budgets": { "clientGzipKB": 450 },
	"capabilities": {
		"pointerLock": false,
		"fullscreen": false,
		"gamepad": false,
		"audio": true,
		"network": []
	},
	"rating": { "level": "everyone", "descriptors": [] }, // everyone | teen | mature
	"rights": {
		"ownsAllContent": true,
		"thirdParty": [
			{ "name": "three.js", "licence": "MIT", "url": "https://github.com/mrdoob/three.js" }
		]
	}
}
```

Each upload must have a higher `version` than every earlier one, including rejected ones.

## The client contract

Your client entry is an ES module that exports `mount(host, options)`. The platform calls it with an empty element
to draw into, and you return a handle. Your game imports nothing from the platform: copy these types into your
project (the templates and the sample have the full set in `src/contract.ts`, including `GameStorage`, `GameAssets`,
`GameEconomy` and `GameTrade`).

```ts
export interface MountOptions {
	t(key: string, params?: Record<string, string | number>): string; // your text, in the player's language
	locale: string; // e.g. "vi"
	dir?: 'ltr' | 'rtl'; // "rtl" for Arabic and Urdu
	online?: { selfId: string; send(bytes: Uint8Array): void }; // absent = solo
	params?: Record<string, string>;
	onEvent?(event: GameClientEvent): void; // tell the host what is happening
	storage?: GameStorage; // saved data, kept by the platform
	assets?: GameAssets; // your asset library: assets.url('chars/ember.glb')
	config?: Readonly<Record<string, unknown>>; // your tuned values (economy.config in game.json)
	economy?: GameEconomy; // progress, shop, equip, codes (see Game data, shops and loadouts)
	trade?: GameTrade; // persistent games: trades with another player in the room
}

export type GameClientEvent =
	| { type: 'ready' } // first frame is drawn
	| { type: 'state'; state: string } // e.g. "menu", "playing"
	| { type: 'complete'; seconds: number; score?: number } // a run or match ended (score feeds a casual board)
	| { type: 'fatal'; message: string }; // the game cannot continue

export interface GameHandle {
	onMessage(bytes: Uint8Array): void; // bytes from the room; may arrive before you are ready
	pause(): void;
	resume(): void;
	dispose(): void; // undo everything mount() did
}

export async function mount(host: HTMLElement, options: MountOptions): Promise<GameHandle>;
```

A minimal game:

```ts
export async function mount(host: HTMLElement, o: MountOptions): Promise<GameHandle> {
	const canvas = document.createElement('canvas');
	host.append(canvas);
	let raf = 0;
	let running = true;
	const frame = () => {
		if (running) draw(canvas);
		raf = requestAnimationFrame(frame);
	};
	raf = requestAnimationFrame(frame);
	o.onEvent?.({ type: 'ready' });
	return {
		onMessage: (bytes) => handleRoomBytes(bytes),
		pause: () => (running = false),
		resume: () => (running = true),
		dispose: () => {
			cancelAnimationFrame(raf);
			canvas.remove();
		}
	};
}
```

**`dispose()` must undo everything:** animation loops, timers, event listeners, DOM nodes, WebGL contexts, audio and
workers. The platform may mount your game again in the same page.

## Text and languages

OneCompanion is in 20 languages: the 12 launch locales `en vi zh-hans hi es fr ar bn pt-br ru ur id` and the newer
`ja ko de tr th fil it pl`.

- **In-game text** lives in `messages/<locale>.json`: flat keys, `{name}` placeholders and ICU plurals, no markup.
  English is required; ship any others you like and list them in `locales`. Players whose language you do not ship
  get English.
- **Every string goes through `t`**, including button labels and numbers in sentences:

  ```json
  { "painters": "{count, plural, one {# painter} other {# painters}}" }
  ```

  ```ts
  label.textContent = o.t('painters', { count: 3 });
  ```

- **Right-to-left:** when `dir` is `rtl` the frame is right-to-left. Lay out with CSS logical properties
  (`margin-inline-start`, `inset-inline-end`, `text-align: start`), not `left` and `right`.
- **Store listing** (`listing/<locale>.json`) is required for the 12 launch locales and optional for the newer
  ones (players there see your English listing until you add theirs):

  ```json
  {
  	"tagline": "Paint one wall together.",
  	"pitch": "A shared wall and a brush for everyone in the room.",
  	"about": ["Drag to paint. In a room, every stroke appears on everyone's wall."],
  	"seoTitle": "Paint Party",
  	"seoDescription": "Paint a wall together with friends in your browser.",
  	"coverAlt": "Colourful dots on a dark wall"
  }
  ```

  Limits: tagline 120 characters, pitch 240, up to 4 `about` paragraphs of 600, `seoTitle` 70, `seoDescription` 170,
  `coverAlt` 160.

  Two optional fields make your game page say what your game is: `play`, the play button's label (24 characters,
  for example "Defend the hill"), and `modes`, one line per mode for the mode cards (160 characters each, only for
  modes in `game.json`):

  ```json
  {
  	"play": "Defend the hill",
  	"modes": { "coop": "Hold the hill with friends.", "solo": "Practise alone." }
  }
  ```

- **Translating:** `onecompanion-game i18n .` writes every missing language as a copy of English marked
  `"$untranslated": true`, adds keys English gained to files already translated (marked with those keys), and
  prints a prompt for your own AI coding tool to translate them. Nothing is sent anywhere. Add languages to the game
  itself with `--locales ja,ko`, or every platform language with `--locales all`. `validate` notes marked files;
  uploads refuse them, so an English copy never reaches players as a translation.

## Saving data

Your frame has no cookies and no browser storage of its own. Save with `options.storage`:

```ts
const saved = await o.storage?.get('progress');
const progress = saved ? JSON.parse(saved) : { level: 1 };
await o.storage?.set('progress', JSON.stringify(progress));
```

|          | Limit                 |
| -------- | --------------------- |
| Key      | 200 characters        |
| Value    | a string, up to 1 MB  |
| Per game | 10 MB and 2,000 keys  |
| Rate     | 200 requests a second |

Data is kept per game and per player device; no game can read another game's data. Engines that expect
`localStorage` get a stand-in backed by the same store, filled when the game starts. Write with `storage.set` when
you need to know the save finished.

## Multiplayer

Choose a room kind in `game.json` (`realtime.kind`). Players are numbered by **slot** (0 to `players.max` − 1). Your
game never receives account ids, emails or room ids: only slots, display names and a room-scoped `selfId`.

| Kind       | The room…                                                           | Ranked         |
| ---------- | ------------------------------------------------------------------- | -------------- |
| `none`     | does not exist: solo only                                           | no             |
| `relay`    | passes your bytes between players; one player is the host           | no             |
| `lockstep` | orders everyone's commands by step and keeps a log for late joiners | no             |
| `server`   | runs your own server module (by invitation)                         | staff decision |

`relay` and `lockstep` trust the players' browsers, so their games are never ranked.

Send with `online.send(bytes)` and receive in `onMessage(bytes)`. All numbers are little-endian.

### Every kind: the roster

```
room → you   [0x02][you u8][host u8][n u8] then n × [slot u8][nameLen u8][name: UTF-8, ≤ 24 bytes]
```

Sent when anyone joins or leaves. `host` is the lowest slot and is re-elected when the host leaves.

### relay

```
you → room   [0x01][to u8: a slot, or 255 = everyone else][payload ≤ 1024 bytes]   at most 30 a second
room → you   [0x01][from u8][payload]
```

A typical relay game lets the host keep the shared state and send it to players who join.

### lockstep

Every client runs the same deterministic simulation; the room owns the step counter.

```
you → room   [0x01][command ≤ 256 bytes]                        at most 15 a second
             [0x03][step u32][hash u32]                         a fingerprint of your state at `step`
room → you   [0x01][step u32][from u8][command]                 apply at `step`, after that step's update
             [0x03][step u32]                                   tick: run up to `step`, never past it
             [0x04][seed u32][step u32][n u32] then n × [step u32][from u8][len u16][command]
                                                                start or catch up: replay the log from `seed`
             [0x05][step u32]                                   desync: fingerprints disagreed at `step`
```

Keep the simulation deterministic: use the seed for randomness, never `Math.random()` or the clock, and avoid
floating-point differences between browsers in anything that affects the state.

### server

Your `entry.server` exports `createGameModule()`, which returns a module the room runs authoritatively. It is built
into one file with no imports and runs in an isolate with no network.

```ts
export function createGameModule(): GameModule {
	return {
		config: {
			gameId: 'your-game',
			maxPlayers: 8,
			tickRate: 20,
			snapshotRate: 10,
			teams: [],
			modes: ['ffa']
		},
		init(ctx, settings) {}, // ctx: sendTo, broadcast, emit, now(), random()
		onJoin(player) {},
		onLeave(playerId) {},
		onInput(playerId, data) {}, // validate everything, trust nothing
		tick(dt) {},
		snapshot() {},
		isIdle: () => false
	};
}
```

Use `ctx.now()` and `ctx.random()`, never wall clocks or `Math.random()`. A module that throws, runs too long or
sends more than its limits gets strikes; repeated strikes close rooms and suspend the game automatically. Ask us before
building on the `server` kind: it is enabled per studio.

## Scores and leaderboards

Games with the `server` kind report each finished match, and the platform keeps match history, per-game stats and
weekly and all-time leaderboards for it. Nothing to set up and no database of your own: the room saves everything when
your module ends a match.

```ts
ctx.emit({
	kind: 'end',
	result: {
		winnerTeam: null, // the winning team in team modes, else null
		players: [
			// one entry per player who took part; ids are the ones your module was given
			{ playerId, team: null, score: 3, stats: { place: 1, duration_ms: 84210, g_wheelies: 4 } }
		]
	}
});
```

**Stat keys.** Use the platform's keys where they fit, so boards, rewards and comparisons work the same in every game:

| Key           | Meaning                           | On a board     |
| ------------- | --------------------------------- | -------------- |
| `place`       | Finishing position, 1 is first    | best (lowest)  |
| `kills`       | Opponents eliminated              | total          |
| `deaths`      | Times eliminated                  | total          |
| `assists`     | Assisted eliminations             | total          |
| `objectives`  | Captures, deliveries, beacons lit | total          |
| `duration_ms` | Time to finish, in milliseconds   | best (lowest)  |
| `distance_m`  | Distance covered, in metres       | total          |
| `waves`       | Waves or levels cleared           | best (highest) |

Anything else is a game key: `g_` followed by up to 22 lowercase letters, digits or `_` (`g_wheelies`). At most 16 keys
per player; numbers are rounded and capped at ±1,000,000. Declare the keys you report in `game.json` (below).

**How a board scores.** By default a match is worth 20 points, plus 10 per point of `score`, plus 100 for a win (the
winning team, else first place, else the top score). `race` boards score by finishing place, and `trial` boards rank
each player's best `duration_ms`. Your preset sets these defaults, and you can change them from your game's page on
`/developers`; a change to scoring takes effect at the next weekly reset (Monday 00:00 UTC), so nobody's week changes
halfway. Private rooms and test bots never count, and a player needs 3 matches in a period to be listed.

**The `economy` block** in `game.json` is optional:

```json
"economy": {
	"preset": "racer",
	"stats": ["place", "duration_ms", "g_wheelies"],
	"milestones": ["g_first_lap"],
	"slots": ["bike_skin"]
}
```

| Field        | What it is                                                                                             |
| ------------ | ------------------------------------------------------------------------------------------------------ |
| `preset`     | `arena`, `racer`, `coop`, `party`, `strategy`, `idle`, `solo`, `rpg` or `app`; default: by first genre |
| `stats`      | The stat keys your module reports (platform keys or `g_` keys)                                         |
| `milestones` | `g_` keys for moments inside a match your module reports                                               |
| `slots`      | Equip slots your game draws (`bike_skin`, `helmet`), for cosmetic items                                |

**Reading a board.** `GET https://onecompanion.net/api/leaderboards/<game>/<mode>?period=week|all&limit=1..100` returns the public
board as JSON: what it ranks by, its columns, and its rows (rank, display name, points, best value, wins, matches,
stats). Only players who appear on the public board page are in it, and it never contains account ids. It is cached for
30 seconds.

Client-authoritative kinds (`none`, `relay`, `lockstep`) are not ranked: a result their players' browsers report could
be made up.

## Rewards

Every game gets the platform's rewards without writing anything: XP and levels, a bonus for the first play of each day,
play streaks, playtime, and a few badges (first match, first win, 3- and 7-day streaks, levels 10 and 25). Players see
what they earn in a small panel the platform draws over your game, and everything they own on their account page.
Nothing can be bought, sold or traded, and nothing has cash value.

What counts depends on your room kind:

| Kind                        | Match results and milestones      | First play, streaks, playtime, levels |
| --------------------------- | --------------------------------- | ------------------------------------- |
| `server`                    | yes                               | yes                                   |
| `none`, `relay`, `lockstep` | no (a browser could make them up) | yes, at lower daily caps              |

Public matches shorter than 30 seconds and private rooms do not count, and test bots never do.

**Milestones** are moments inside a match your rules can reward (a boss down, a first lap). Report them from your
server module; they are counted when the match ends:

```ts
ctx.emit({ kind: 'milestone', playerId, key: 'g_boss_defeated', value: 1 });
```

Keys are `g_` plus up to 22 lowercase letters, digits or `_`; declare them in `game.json` (`economy.milestones`). A
player can report up to 20 per match.

Your own currencies, items, collections, drop tables and rules (for example "30 Scrap for a win, plus 2 per kill, at
most 80") are set on your game's page on `/developers`, from a preset. The platform caps what any rule can give, so a
mistake cannot flood the game: at most 10,000 of a currency per reward and 50,000 per player per day.

**Managing it.** Your game's page on `/developers` has a "Scoring and economy" page: edit the ruleset (JSON, checked as
you type; a form view covers currencies, items, rules, offers and bonuses), start from your preset, simulate it against your game's last 7 days of real matches, and publish. Any studio
member can save drafts; owners publish and roll back. Changes to values go live within a minute; new or changed names,
descriptions and icons are checked by our team first. To keep the ruleset in your repository instead, use the CLI:

```sh
npx onecompanion-game economy init       # a starter economy.json for your preset (offline)
npx onecompanion-game economy pull       # writes economy.json and economy.lock.json
npx onecompanion-game economy validate   # the same check the console runs
npx onecompanion-game economy simulate   # replays your last 7 days, totals only
npx onecompanion-game economy push       # saves economy.json as the draft
```

A push is refused if someone saved or published in the console since your pull, so nothing is overwritten silently:
pull again, merge, push. The CLI never publishes.

**Casual boards.** Solo and client-authoritative games can show an unverified best-score board, fed by the `complete`
event (`{ type: 'complete', seconds, score }`). Ask for one in `game.json` with `"economy": { "casual": { "by": "score" }
}` (or `"by": "duration_ms"` for the fastest time). It is labelled unverified everywhere and never feeds rewards, ranked
boards or tournaments.

To make a solo game ranked, start from the `verified-solo` template: the client plays each run, and a small server
module replays its inputs with the same code before the time counts.

Item and currency names are public: `GET https://onecompanion.net/api/economy/<game>/catalog?locale=<locale>` returns them in one
language, cached for a minute.

## Game data, shops and loadouts

**Config.** Declare the values your game reads in `game.json`, with types and bounds:

```json
"economy": {
	"config": {
		"player.max_hp": { "type": "int", "min": 1, "max": 10000, "default": 100 },
		"spell.fireball": { "type": "object", "fields": { "cost": "int", "damage": "int" }, "default": { "cost": 30, "damage": 40 } }
	},
	"attributes": { "character": { "hp": "int", "mana": "int", "class": ["mage", "tank"] } }
}
```

Types: `int`, `float`, `bool`, `enum` (with `values`), `string`, `list` (of `int`, `float` or `string`) and `object`
(with `fields`). Set the values on your "Scoring and economy" page (`"config": { "values": { … }, "modes": { "ffa": { … } } }`);
anything you leave out uses the default. Your server module reads them as `settings.config` in `init()`, your client
as `options.config` in `mount()`. They are delivered once per room or session, never per tick, so a change applies
from the next match.

**Items with stats.** Item kinds `character`, `weapon`, `ability`, `vehicle`, `card` and `material` (and cosmetics
and consumables) can carry the attributes you declare, set per item in the ruleset. Values that do not fit their
declaration are refused when you save.

**Shops.** Offers sell items for your currencies at a fixed price (`"offers": [{ "id": "buy_helmet", "price": { "scrap":
500 }, "gives": [{ "item": "helmet" }], "limit_per_user": 1 }]`). Never random items for currency. Your client calls
`options.economy`:

```ts
const me = await options.economy?.get(); // level, xp, balances, items (with what is equipped)
const shop = await options.economy?.offers();
const r = await options.economy?.purchase('buy_helmet'); // the platform asks the player to confirm
await options.economy?.equip('helmet', true); // one item per slot (economy.slots)
```

The platform checks every call; a game can ask, never grant. A purchase spends and gives in one step, so it either
happens completely or not at all, and a retry never charges twice.

**Bonuses and codes.** A bonus multiplies what your rules give for a while: `"bonuses": [{ "id": "double_weekend",
"multiply": 2, "days": [0, 6] }]` (UTC weekdays, 0 is Sunday), optionally only for some rules (`applies_to`), only for
currency or XP (`assets`), and between two dates (`active`). Bonuses multiply together, never past ×3. Codes are made
by owners on the same page: many single-use codes, or one shared code with a use limit, each giving one of your
currencies, XP or an item. Players redeem them on your game's page or through `options.economy.redeem(code)`; each
player can use a code once. Codes are shown once when made; we keep only a fingerprint.

Support for one player (giving something back, undoing a mistake, freezing an account that cheats) is done by our team,
not by studios: we never show studios who their players are. Write to us and we will handle it.

**Loadouts.** When a player joins a room, your server module gets what they have equipped in `player.loadout` (item id,
slot and attributes), read from their inventory by the platform. Trust it, and never take a client's word for it.

## Persistent games

For games whose value is a character that lives for months (action RPGs, dungeon crawlers, survival). Only for
`server` games, and only once we have enabled the persistent level for your studio: write to us. Start from the
`persistent-rpg` template.

**What the platform keeps.** Characters and the items they own. Your module never stores either: it reports what
happened, the platform checks it against your published ruleset and saves it. A player cannot play without a
character, and a character plays in one room at a time.

**Declare it** in `game.json`:

```json
"economy": {
	"persistent": {
		"slots": 3,
		"character": { "kills": "int", "skills": "object", "waypoints": "list" },
		"locations": ["bag", "equipped", "stash"],
		"bag_capacity": 100,
		"stash_capacity": 200,
		"hardcore": true
	}
}
```

`modes` lists the room modes that carry characters (absent: every room mode). Solo never does, and modes you leave
out stay open to guests, so a game can keep a guest-friendly mode next to its persistent one. `character` lists the fields of a character's saved state (`int`, `float`, `bool`, `string`, `object`, `list`; 64 KB
in all). With `hardcore`, players may make one-life characters: one that dies can no longer play.

**In the ruleset** (your "Scoring and economy" page, or `economy.json`):

- Classes are items of kind `character`. Players pick one when they make a character on the platform's character
  screen. With no classes in the ruleset, everyone is an Adventurer, so publishing your loot tables later never
  locks players out.
- `affixes`: modifiers with the attribute ranges they roll (`{ "id": "of_embers", "applies_to": ["weapon"],
"attributes": { "fire": [2, 8] }, "item_level": [1, 99] }`).
- `loot_tables`: which bases and qualities can drop, at which levels (`{ "id": "crypt", "level": [1, 30], "entries":
[{ "base": "short_sword", "qualities": ["magic", "rare"], "weight": 30 }] }`). Qualities are `normal`, `magic`,
  `rare`, `set` and `unique`.
- `quality_caps`: the most instances of each quality one character may get per hour (defaults: 600 normal, 200 magic,
  40 rare, 6 set, 4 unique). Drops past a cap are refused.
- `seasons`: `{ "id": "s1", "name": { "en": "Season 1" }, "from": "…", "until": "…" }`. Characters made during a season
  belong to it.

**Use the shared helper.** `progression.ts` (in the template, the same code our own games use) keeps XP on the
platform's curve (level n needs 50·(n−1)² XP), batches saves and gives every drop its own `ref`. In a room without
characters every call does nothing, so call it unconditionally:

```ts
const progress = createProgression(
	(e) => ctx.emit(e),
	() => ctx.random()
);
progress.join(player); // in onJoin
progress.award(playerId, 25); // XP for a moment of your game
progress.count(playerId, 'kills');
progress.drop(playerId, 'crypt', { base: 'potion', quality: 'normal' }, 0.25); // a 25% chance
progress.onPlatform(e); // in onPlatform
```

The platform shows the player what they found and when they level up; your game does not need its own toast.

**Your server module:**

```ts
onJoin(p) {
	const c = p.character!; // id, name, class, level, xp, state, hardcore, season, items
},
// Save progress: merged and written once a minute, and when the player leaves, dies or travels.
ctx.emit({ kind: 'character', playerId, level, xp, state: { kills } });
// Loot: checked against the table, the affix ranges, the hourly caps and the bag. The answer comes back in onPlatform.
ctx.emit({ kind: 'grant', playerId, ref: 'drop-17', table: 'crypt',
	item: { base: 'short_sword', quality: 'magic', level: 5, affixes: ['of_embers'], rolls: { fire: 6 } } });
ctx.emit({ kind: 'consume', playerId, instanceId }); // a potion drunk, an item sold
ctx.emit({ kind: 'travel', playerIds: [a, b], map: 'depth-2' }); // a new room of your game, characters and all
onPlatform(e) {
	// { kind: 'granted', playerId, ref, item | null, error? } or { kind: 'traded', players, items }
},
checkpoint() { return bytes; }, // every 30 s; given back to restore(bytes) if the room restarts
```

Give every drop its own `ref`: the same `ref` twice is granted once, so a retry never duplicates an item.

**Trades.** Two players in the same room trade through `options.trade` on the client: `offer(otherId, { instances,
currencies })`, `confirm(otherId)`, `cancel(otherId)`, and `on(listener)` for each change. Any change to an offer needs
both players to confirm again. The platform swaps everything at once, or nothing. Bound items, and items moving between
hardcore and normal characters or between seasons, cannot be traded. Never for real money.

**Check it offline.** `onecompanion-game test` runs your server module headless with random input and reports
anything we would refuse (undeclared stats or milestones, loot outside your tables, a room that never goes idle).
`onecompanion-game economy loot crypt --kills 1000 --drop-chance 0.3 --kills-per-hour 600` shows what a table hands
out against the hourly caps.

**Long sessions.** Rooms of a persistent game can ask for more CPU per step (up to 200 ms): write to us. Keep each
player's messages to what is near them.

**Safety nets.** Every instance has a ledger entry behind it; a nightly check quarantines any that does not. Our team
can restore a character to one of its last 20 saves.

## The asset library

Art, models, audio and fonts can live in your game's **asset library** instead of the bundle, so you can change them
without uploading a new version. Code never goes there: only reviewed versions carry code.

- **Types:** `png`, `jpg`, `webp`, `avif`, `glb` (models must embed their buffers and textures), `ktx2`, `ogg`, `mp3`,
  `woff2`, and `json` for data. Up to 10 MB a file (25 MB for `.glb`), 200 MB per game by default.
- **Paths:** every file keeps a path you choose (`chars/ember.glb`). A **release** is the set of paths players get;
  the console's "Asset library" page builds a draft release as you upload, and an owner publishes it. A studio's first
  three releases are checked by our team; later ones go live at once. You can roll back to any earlier release.
- **In your game:** `options.assets.url('chars/ember.glb')` gives the file's URL (or `null`), and
  `options.assets.paths()` lists every path. The URL is inside your version's folder, so your CSP allows it.
- **Required paths:** list the paths your code cannot run without in `game.json` (`"assets": { "required": [...] }`).
  A version is refused if the live release lacks one, and a release that drops one is refused.
- **Rights:** choose a licence for each upload (yours, CC0, CC BY with a credit line, or licensed). Credit lines are
  shown on your game's page. Files can be reported, and our team can take one down; it then shows as a blank image.
- **CLI:** `npx onecompanion-game assets push <folder> --licence own` uploads a folder into the draft release, and
  `assets status` shows the library. Optimise first (WebP or KTX2 textures, compressed glTF): smaller files load faster.

## The sandbox

Your game is served from `https://onecompanion.net/g/<game>/<version>/` into a frame with an anonymous origin. Inside it:

- No cookies, no `localStorage` or IndexedDB of its own (use `options.storage`), no access to the page around it.
- No network except `online.send`: `fetch` and WebSockets to other places are blocked. Load your own files with
  relative URLs; they are served from your version's folder.
- No pop-ups, new windows or navigation of the page.
- Pointer lock, fullscreen, gamepad and audio work when you declare them in `capabilities`. The OneCompanion
  desktop app runs the same pages, so they work there too.

## Art and size limits

| Asset         | Requirement                                                                              |
| ------------- | ---------------------------------------------------------------------------------------- |
| Cover         | 1280×720 WebP                                                                            |
| Stills        | 3 to 8, each 1280×720 WebP with a 320×180 `-thumb.webp` next to it                       |
| Share image   | 1200×630 JPEG                                                                            |
| Client        | 450 KB gzip for the entry and its static imports (load the rest with dynamic `import()`) |
| Server module | 1 MB, one file                                                                           |
| Upload        | up to 400 files, 10 MB per file, 25 MB in total                                          |

While your game loads, players see your cover with its title and your studio handle, so make the cover work as a
loading screen too.

## Publishing and releases

| Command (as a project script)           | What it does                                                  |
| --------------------------------------- | ------------------------------------------------------------- |
| `onecompanion-game validate .`          | Builds the bundle into `bundle/` and runs every check         |
| `onecompanion-game pack .`              | Builds the bundle only                                        |
| `onecompanion-game publish .`           | Packs, uploads every file and submits the version for review  |
| `onecompanion-game release <versionId>` | Releases an approved version, or rolls back to an earlier one |
| `onecompanion-game status <versionId>`  | Shows a version's state, automatic issues and review notes    |

The CLI reads `ONECOMPANION_API` (this site: `https://onecompanion.net`) and `ONECOMPANION_TOKEN`. Add `release` and `status` to your
`package.json` scripts, or run the installed copy with `./node_modules/.bin/onecompanion-game` (or
`npx onecompanion-game` inside a project that has it installed).

### Version states

```
uploading → in_review → approved → published → superseded
          ↘ rejected_auto       ↘ changes_requested | rejected
```

You can withdraw any version that is not published. A superseded version stays available for 30 days, for rooms
still playing it and for rollback.

### Emails

Studio members get an email, in their own language, when a version passes the checks and enters review, fails the
checks, is approved, needs changes, is rejected or is released, and when a game is suspended or reinstated. Owners are
told about new command-line tokens.

### What reviewers check

- The game works, and `dispose()` cleans up.
- Every string is translated through `t`, the listing is complete and layout works right-to-left.
- The rating matches the content, and `rights` lists every third-party asset and its licence.
- The game respects players: no deceptive design and no attempt to collect personal data. Hosted games are free: no
  ads and no payments.

## Troubleshooting

| Message             | What to do                                                                                            |
| ------------------- | ----------------------------------------------------------------------------------------------------- |
| `version_not_newer` | Raise `version` in `game.json` above every earlier upload                                             |
| `version_uploading` | An earlier upload of this version did not finish: withdraw it on your studio page, then publish again |
| `id_taken`          | Another studio owns that `id`: choose another                                                         |
| `studio_mismatch`   | `studio` in `game.json` is not the studio your token belongs to                                       |
| `unauthorized`      | The token is missing, revoked or mistyped: make a new one on your studio page                         |
| `rate_limited`      | 20 uploads per studio per day: try again tomorrow                                                     |
| `rejected_auto`     | Run `onecompanion-game status <versionId>` (or open your studio page) for the list of problems        |
