# TypeTorch docs (full)
> Update live Roblox games without restarting their servers. Every page of https://www.typetorch.dev in one file, in the sidebar's order. Index: https://www.typetorch.dev/llms.txt
---
# TypeTorch docs
TypeTorch updates live Roblox games **without restarting their servers**. You write the game in
[roblox-ts](https://roblox-ts.com). Each build becomes one artifact (an uploaded, private Model asset), and every live
server hot-swaps to it in a few seconds while players stay in the game.
These docs are also a website: **[www.typetorch.dev](https://www.typetorch.dev)**.
> **Status: early.** The core loop runs on live Roblox servers today. APIs and commands still change. These docs
> describe the code as it is now. Features that don't exist yet are marked **planned**.
> **Your game never builds or deploys in CI.** TypeTorch ships no workflows for games, and nothing needs your Open Cloud
> key or signing keys in a hosted CI: builds, cloud tests, signing and deploys run on your own machine. (TypeTorch's own
> packages are released from a version tag by a GitHub workflow with npm trusted publishing; see
> [Releases](https://www.typetorch.dev/docs.md#releases).)
## Get started
Not sure TypeTorch fits you or your game? Read **[Is TypeTorch for me?](https://www.typetorch.dev/getting-started/is-it-for-me.md)** first
(short answer: it's built for AI agents and for developers who know git).
Pick one path:
| You have | Start here | Time |
|---|---|---|
| Nothing yet: a new game | **[Fresh setup](https://www.typetorch.dev/getting-started/fresh-setup.md)**: `bunx @typetorch/cli init` in an empty folder, or every step by hand; from zero to a live hot-swap | under an hour with `init` |
| A roblox-ts game | **[Migrate an existing game](https://www.typetorch.dev/getting-started/migrate.md)**: services, swap safety, networking, data, UI; with live players, inside the [go-live checklist](https://www.typetorch.dev/guides/go-live-checklist.md) | a few hours to days; about a week with live players |
| An AI coding agent | **[Agent playbook](https://www.typetorch.dev/agents/AGENTS.md)**: tell your agent "migrate this project to typetorch" | |
TypeTorch is **roblox-ts only**. A plain Luau game has to move to roblox-ts first.
The template's package versions are behind npm. After cloning it (or after `init`), take the newest `@typetorch/*`
packages: [Take the newest versions](https://www.typetorch.dev/getting-started/fresh-setup.md#take-the-newest-versions).
## How it works
```mermaid
flowchart LR
A[typetorch deploy] --> B[build: roblox-ts -> payload.rbxm]
B --> C[upload as a private Model asset
moderation check]
C --> T[cloud test
prod: always]
T --> D[approve y/N
prod: signed]
D --> E[deploy message
MessagingService]
E --> F[live servers: the kernel loads the payload]
F --> G[old version stops, new one starts
server + clients, no restart]
G --> R[reports to the fleet API
bad build: automatic rollback]
```
- **Kernel:** a small Luau loader baked into the place. It picks each server's branch, loads payloads and swaps them.
It is the only part that needs a place publish and a server restart to change.
- **Payload:** your compiled game code (ModuleScripts only), uploaded once per build.
- **Framework:** `@typetorch/framework`, the roblox-ts library your game uses: modules with dependency injection and
lifecycle hooks, troves for cleanup, guarded networking, UI helpers, hot assets and the in-game dev menu. It ships
inside every payload, so it hot-swaps too.
- **Branches:** public servers run `prod`. Any other branch (`dev`, `feature-x`) runs in private or reserved servers of
the same game.
- **CLI:** `typetorch` (or the short alias `tt`) builds, uploads, tests, approves, signs and deploys, rolls back, shows
live servers and alerts, patches the kernel into the place, and runs the Studio loop (`typetorch serve`).
`typetorch update` keeps it current.
- **Studio plugin:** attaches Studio to `typetorch serve` by itself, reloads a running playtest on save, publishes hot
assets from a panel, and has a Claude tab for `typetorch serve --claude` (it needs `@typetorch/dev-server` 0.4.0,
which is not on npm yet; see [remote-claude](https://www.typetorch.dev/guides/remote-claude.md#from-studio)).
- **Safe deploys:** a cloud test before every prod publish; on each server a health window that rolls a failing build
back; `deploy --wait`, which rolls the branch back when a build fails on 20% of servers; a new server plays within
15 s.
- **Backend (optional, self-hosted):** live server status, deploy reports and history, alerts, error logs and debug
bundles from the kernel, read-only remote and live debug of one live server, your own analytics (experiments,
funnels, player journeys, first-session recordings on your maps), experience notifications, player feedback, live
events, and the web explorer that shows all of it. It runs from a checkout or its Docker image.
## Guides
**Build your game**
| Guide | What it covers |
|---|---|
| [Runtime API](https://www.typetorch.dev/guides/runtime-api.md) | `TypeTorch.*`: identity, start info, swap events, persist, playerState, `Dependency()`, roles, logs, messaging, detached jobs, live settings and live events, live debug (`remoteDebug`, `fleet`), notifications and feedback |
| [State with charm](https://www.typetorch.dev/guides/state.md) | charm atoms across swaps: server atoms from `persist`, charm-sync over `createNetwork`, the client's hydrate request |
| [Networking](https://www.typetorch.dev/guides/networking.md) | `createNetwork`, guards, limits, requests, timeouts, `emit` |
| [Cross-server messages](https://www.typetorch.dev/guides/messaging.md) | `TypeTorch.messaging` (one kernel-held topic, dev branches kept off prod, limits), `TypeTorch.servers()` |
| [Player data](https://www.typetorch.dev/guides/player-data.md) | the swap-safe data pattern (library writes as DataHost jobs or `TypeTorch.runDetached`), ProfileStore and ProfileService examples, the cloud test and developer product receipts |
| [Loading screens](https://www.typetorch.dev/guides/loading-screen.md) | your own loading screen: `ClientReady`, `Holding`, `TypeTorchBootScreen`, `TypeTorchKernelScreen` |
| [Hot assets](https://www.typetorch.dev/guides/hot-assets.md) | models and UI templates from the place, updated live with `hotAsset()`; from the CLI or the Studio plugin |
| [The dev menu](https://www.typetorch.dev/guides/dev-menu.md) | every tab, owners and devs, the dev-only tools, the command palette, the `/tt` commands |
| [Player feedback](https://www.typetorch.dev/guides/feedback.md) | `TypeTorch.feedback().submit(player, { rating, text, topic, ctx })`, rating scales (thumbs, stars, a labelled scale) in `game.feedback`, rate limits, the Feedback page, moving from a custom event |
| [Coming from Flamework](https://www.typetorch.dev/guides/from-flamework.md) | `typetorch migrate --from flamework` (the codemod and its report), `createFlameworkCompat`, the mapping |
**Deploy**
| Guide | What it covers |
|---|---|
| [Deploy and rollback](https://www.typetorch.dev/guides/deploy-and-rollback.md) | deploy, the compiler (goblox or rbxtsc), the production pack (darklua), approval, safe deploys (cloud test, health window, `--wait` and automatic rollback, reports), promote, rollback, deploy marks on the backend, the backup build (automatic refresh, `--reupload`), the build cache, pins, kernel updates |
| [Branches and channels](https://www.typetorch.dev/guides/branches-and-channels.md) | `prod` and `dev`, private servers on a branch, `/tt new`, owners switching any server in place, `branch rm` |
| [Prod signing](https://www.typetorch.dev/guides/prod-signing.md) | the Root Key and Fallback Key, `typetorch keys`, kernel 0.3 verification, bootstrap heads, the boot fail-safe |
| [Settings](https://www.typetorch.dev/guides/settings.md) | the signed settings record: dev access, backend, the analytics dials, your own live values (`liveConfig`), the reserved game keys (`tt.events`, `feedback`), `typetorch settings` |
| [Go-live checklist](https://www.typetorch.dev/guides/go-live-checklist.md) | moving a game with live players: prepare, a copy, a dev-branch soak, live tests, cut-over, what to do if it goes wrong |
**Operate** (the self-hosted backend)
| Guide | What it covers |
|---|---|
| [Live servers and alerts](https://www.typetorch.dev/guides/fleet-and-alerts.md) | the fleet API, `typetorch servers`, `report`, `alerts`, server lost and stuck, backend alerts, the deploy history, webhooks, error logs, debug bundles, remote debug, debugging endpoints |
| [Live debug](https://www.typetorch.dev/guides/live-debug.md) | game-declared read-only commands, streams and Fleet columns, the live map of one server or all of them, limits and safety rules |
| [The explorer](https://www.typetorch.dev/guides/explorer.md) | the backend's web app: sign-in and roles, every page, the filter bar, the command palette, compare and explain, deploy markers, saved queries |
| [Analytics](https://www.typetorch.dev/guides/analytics.md) | `AnalyticsEngine`, the event format, positions, the join row and its raw join data (`jd`), DuckDB or Basin, the analytics dials, experiments and live overrides (`typetorch experiment`), queries, node graphs, privacy, a local quick start |
| [Recordings and maps](https://www.typetorch.dev/guides/recordings-and-maps.md) | first-session recordings and positioned events on each map's real geometry: map export, replay, quit autopsy, first actions |
| [Live events](https://www.typetorch.dev/guides/live-events.md) | scheduled changes of live values ("double cash this weekend"), signed once with `typetorch settings set game.tt.events -`, and the lift report |
| [Notifications](https://www.typetorch.dev/guides/notifications.md) | native Roblox experience notifications: kinds in `typetorch.json`, `TypeTorch.notifications()` (`want`, `drop`, `setOff`, `onOpen`, `promptOptIn`), templates made by hand (`typetorch notify templates`), signed taps, the funnel, `typetorch notify` |
| [Running the backend](https://www.typetorch.dev/guides/backend-operations.md) | runtime settings, backend alerts, the audit log, backups and restore, disk space, moving the backend, backend stats, deploys on Coolify, API docs for agents, Open Cloud key scopes |
| [Emergency backend scale-ups](https://www.typetorch.dev/guides/emergency-scale-ups.md) | a sudden surge: what keeps working (the busy 503), how much one backend takes, shed load from the CLI, resize the VPS and tune DuckDB, move to another server, analytics to Basin and back, several ingest servers |
| [API keys](https://www.typetorch.dev/guides/api-keys.md) | named backend keys with roles (`game`, `lookup`, `support`, `analyst`, `admin`) and scopes, `typetorch keys create/list/revoke` (CLI 0.19.0+), the per-player support endpoints, the event allow-list, per-key rate limit and audit, built-in env tokens; the export API and migration take the env admin token only |
| [Security model](https://www.typetorch.dev/guides/security.md) | who can do what, dev access (`access push`), the backend, devtools for devs only, keys, signing, remote Studios, never publish secrets |
| [Troubleshooting](https://www.typetorch.dev/guides/troubleshooting.md) | real errors and their fixes |
**Tooling**
| Guide | What it covers |
|---|---|
| [Testing in Studio](https://www.typetorch.dev/guides/studio-testing.md) | `typetorch serve` and the Studio plugin: your local code with the real kernel, live reload in a playtest, agents driving Studio, a Studio on another machine |
| [remote-claude](https://www.typetorch.dev/guides/remote-claude.md) | prompt Claude Code from inside a dev server or from Studio (`serve --claude`): Live and Code modes, screenshots, Toolbox |
**Mobile app** (Android, early; the APK is not on Play yet)
| Guide | What it covers |
|---|---|
| [The mobile app](https://www.typetorch.dev/guides/mobile-app.md) | install, sign-in to a backend, the Open Cloud key and its scopes, Projects, analytics and tools, the TypeTorch pages, exports, backend requirements |
| [Mobile widgets](https://www.typetorch.dev/guides/mobile-widgets.md) | home-screen widgets: sizes, Stats and Releases, the release garden, All games with a tap filter, health |
| [Mobile notifications](https://www.typetorch.dev/guides/mobile-notifications.md) | CCU milestone pushes, the live watch, Xiaomi and HyperOS battery settings |
| [For maintainers](https://www.typetorch.dev/guides/mobile-maintainers.md) | editing the widget HTML and widget program over the air: build, check, preview, `eas update` |
## For agents
- [agents/AGENTS.md](https://www.typetorch.dev/agents/AGENTS.md): the migration and setup playbook for any coding agent (Claude Code, Codex,
Cursor and others).
- [agents/skills/typetorch-migrate/SKILL.md](https://www.typetorch.dev/agents/skills/typetorch-migrate/SKILL.md): the same playbook as a Claude
Code skill.
- Claude Code plugin ([typetorch/claude-plugin](https://github.com/typetorch/claude-plugin)):
```text
/plugin marketplace add typetorch/claude-plugin
/plugin install typetorch@typetorch
```
Then say "migrate this project to typetorch", or run `/typetorch:typetorch-migrate`.
- [llms.txt](https://www.typetorch.dev/llms.txt): an index of these docs for LLMs, served at
[www.typetorch.dev/llms.txt](https://www.typetorch.dev/llms.txt) with every link pointing at a Markdown page.
[www.typetorch.dev/llms-full.txt](https://www.typetorch.dev/llms-full.txt) is every page in one file.
- Every page of the site is also Markdown: add `.md` to its URL
([/guides/analytics.md](https://www.typetorch.dev/guides/analytics.md)), or request the page with
`Accept: text/markdown`. Each page also has **Copy page as Markdown** and **View as Markdown** buttons.
## Repositories
| Repository | What it is |
|---|---|
| [kernel](https://github.com/typetorch/kernel) | the Luau loader baked into the place |
| [framework](https://github.com/typetorch/framework) | `@typetorch/framework`, the roblox-ts framework (ships in every payload) |
| [cli](https://github.com/typetorch/cli) | `@typetorch/cli`: `typetorch` (alias `tt`), the command line tool |
| [studio-plugin](https://github.com/typetorch/studio-plugin) | the TypeTorch Studio plugin (`TypeTorchSync.rbxm` on GitHub releases; not on npm) |
| [template](https://github.com/typetorch/template) | the starter game (Target Rush), also the reference setup |
| [transformer](https://github.com/typetorch/transformer) | `@typetorch/transformer`, the compiler plugin for guards and dependency injection |
| [dev-server](https://github.com/typetorch/dev-server) | `@typetorch/dev-server`, `remote-claude`: Claude Code on your PC, prompted from inside a dev server or from Studio |
| [backend](https://github.com/typetorch/backend) | the backend: analytics (DuckDB, or Basin), the fleet API (SQLite), error logs, debug bundles, remote and live debug, notifications, feedback, live events and the web explorer (run from a checkout or its Docker image; not on npm) |
| [claude-plugin](https://github.com/typetorch/claude-plugin) | the Claude Code plugin marketplace with the `typetorch-migrate` skill |
| dash (private) | [dash.typetorch.dev](https://dash.typetorch.dev): one Roblox sign-in for every backend you own or view (optional) |
## Conventions in these docs
- Commands work in PowerShell 5.1 and bash unless a block says otherwise.
- `bun run typetorch ` runs the CLI: `@typetorch/cli` from npm, in the game's dev dependencies with the
script `"typetorch": "typetorch"` (the template has both; see
[fresh setup](https://www.typetorch.dev/getting-started/fresh-setup.md#2-get-the-code)). Without it, `npx @typetorch/cli ` does the
same. Installed globally (`npm i -g @typetorch/cli`), it is `typetorch ` or `tt `.
- Ids in examples are fake: universe `1234567890`, place `9876543210`, group `1234567`, user `111111111`.
## Releases
The npm packages (`@typetorch/cli`, `kernel`, `framework`, `transformer`, `dev-server`) are published only from a
version tag: a maintainer runs `npm version -m "release %s" && git push origin main --follow-tags`, and the
repo's `publish.yml` workflow checks that the tag matches `package.json`, runs the package's `prepublishOnly` checks,
publishes with provenance through npm trusted publishing (`x.y.z-next.N` goes to the `next` dist-tag, anything else to
`latest`) and makes the GitHub release. The workflows still accept an `NPM_TOKEN` repository secret as a fallback. No
workflow runs on pull requests except the CLI's tests (`ci.yml`).
The Studio plugin is released the same way, from a tag, as `TypeTorchSync.rbxm` on its GitHub release. Roblox doesn't
accept plugin uploads through Open Cloud yet (the release job warns and skips that step), so the Creator Store copy is
published by hand in Studio with **Publish as Plugin**. Install from the GitHub release
([Testing in Studio](https://www.typetorch.dev/guides/studio-testing.md#set-up-once)).
## The docs site
These Markdown files are also the site at [www.typetorch.dev](https://www.typetorch.dev) (and `typetorch.dev`): VitePress,
served by a Cloudflare Worker. `bun install`, then `bun run docs:dev` for a live preview, `bun run docs:build` to build
(dead links fail it). New pages go into `.vitepress/sidebar.ts`. `bun run sync:reference` copies the public package
READMEs into `reference/`; `bun run sync:whats-new` writes `whats-new.md` (the What's new page) from each package
checkout's release tags next to this repo (`git fetch --tags` there first). `bun run deploy` builds and deploys with the Cloudflare CLI (`cf deploy`, config in
`cloudflare.config.ts`; needs `cf auth login` and Node 22.18+); `bun run deploy:check` is the dry run.
## Logo
The TypeTorch logo, its PNG and favicon exports, colours and usage rules are in [brand/](https://www.typetorch.dev/brand/README.md).
## License
MIT
---
# Is TypeTorch for me?
TypeTorch is built by agents, for agents: you describe what you want, and an AI coding agent (Claude Code, Codex,
Cursor and others) writes the roblox-ts code, runs the CLI and follows these docs. Find yourself below.
| You are... | TypeTorch? | Why |
|---|---|---|
| A developer comfortable with git, who knows what a branch is | **Yes, you'll love it** | Every build hot-swaps live servers in seconds, `dev` and `feature-x` branches run in the real game, bad builds roll back on their own. This is who it's made for. |
| A non-technical creator | **Yes** | TypeTorch is agents-first. Your agent does the setup and the code; you approve the steps only you can do (Roblox keys, publishing, prod deploys). Start with the [agent playbook](https://www.typetorch.dev/agents/AGENTS.md). |
| Starting a new game, or one that hasn't launched yet | **Yes** | The easiest way in: [fresh setup](https://www.typetorch.dev/getting-started/fresh-setup.md) (`bunx @typetorch/cli init`) gives you a working game with live updates from day one. |
| Writing every line of code by hand | **No** | TypeTorch is by agents, for agents. Its conventions (swap-safe modules, troves, guarded networking) and its docs are written for agents to follow. By hand it's a lot of rules to keep in your head. |
| Only after analytics | **Probably not** | The whole toolchain is a lot to adopt for one feature. Let your agent fork the analytics instead: the engine is in [`@typetorch/framework`](https://github.com/typetorch/framework/tree/main/src/analytics) and the server and explorer are in [typetorch/backend](https://github.com/typetorch/backend). Or try the [live demo](https://demo.typetorch.dev) first. |
| A Luau-first developer | **Maybe** | The framework is TypeScript (roblox-ts), and the docs assume it. The kernel that loads and swaps builds is plain Luau, so an agent can find its way around: fork the framework and drive the kernel from Luau. That path is not supported. |
| Adding live updates to a game that's already out | **Not unless you're technical** | Moving a live game is real work: every module has to become stoppable and restartable, and players' data must survive the move. It's doable ([migrate](https://www.typetorch.dev/getting-started/migrate.md), then the [go-live checklist](https://www.typetorch.dev/guides/go-live-checklist.md)), but if you're not technical, use TypeTorch for your next game instead. |
## Next
- New game: [Fresh setup](https://www.typetorch.dev/getting-started/fresh-setup.md).
- Existing roblox-ts game: [Migrate an existing game](https://www.typetorch.dev/getting-started/migrate.md).
- Using an agent: point it at [llms.txt](https://www.typetorch.dev/llms.txt) or the [agent playbook](https://www.typetorch.dev/agents/AGENTS.md).
- Just looking: the [live demo](https://demo.typetorch.dev) of the backend explorer, with anonymized sample data.
---
# Fresh setup: from zero to a live hot-swap
This guide sets up a new TypeTorch game from the starter template and ends with a live server that hot-swaps while you
play. Every step ends with **Check**: what you should see when it worked.
## The quick way: `typetorch init`
With Bun installed, run this in an empty folder (CLI 0.10+; with the CLI installed globally, `typetorch init` or
`tt init`):
```sh
bunx @typetorch/cli init
```
It asks one question at a time and walks through steps 1 to 11 below. It does the terminal work itself, and for the
parts that happen in Creator Hub (creating the experience, the API key) it links the exact page and checks the result.
Each step says why it exists, links the section below that it replaces, and checks its result the way
`typetorch doctor` would. Every upload, deploy and SSH session gets its own y/N.
| Step | What it does |
|---|---|
| 1. tools | checks Bun, git and Rokit (offers to run Bun's install script) |
| 2. project | clones the template (into this folder when it is empty, else into a new subfolder named after the project), drops the template's `origin`, runs `bun install`, `rokit install` and a first `typetorch build` |
| 3. roblox | reads your experience from its Creator Hub URL (the creator comes from Roblox), probes the Open Cloud key and writes it to `.env`, finds your user id from your Roblox username (a group game; a user-owned game takes the creator), then shows and writes `typetorch.json` and commits it |
| 4. keys | `keys init` and `keys init --fallback` (step 7), then commits `typetorch.json` |
| 5. kernel | an empty place: `kernel deploy --dry-run`, then `--replace-place --yes`; a place with Studio content: `kernel deploy --install` (a patch, which needs the place setting "Allow place to be updated using Save Place API") |
| 6. backend | optional, below |
| 7. deploy | commits, deploys `main` (prod), offers a `dev` branch and deploys it, then `access push` |
| 8. agent | writes `AGENT_PROMPT.md` |
The `typetorch.json` it writes maps git `main` to `prod` and git `dev` to `dev`, sets `"approval": "prod"`, and makes
you the only member, as `owner`. A folder that already holds a roblox-ts game stops at step 2: moving a game is a
[migration](https://www.typetorch.dev/getting-started/migrate.md).
The scope list `init` shows for the Open Cloud key leaves out `universe.place:write`, but `--replace-place` in its kernel step
publishes a place file and needs it. Add it to the key for an empty place (the full scope list is in
[step 6 below](https://www.typetorch.dev/getting-started/fresh-setup.md#6-the-open-cloud-api-key-owner)).
- **Optional backend.** The backend step can set one up for you: on a VPS with Coolify, on a VPS without Docker (a
systemd service with Caddy in front, your domain or a free sslip.io name), or on this PC behind a free Cloudflare
quick tunnel. It can also point the game at a backend you already run, or skip it. `typetorch init --teardown`
removes what that step installed. See [Live servers and alerts](https://www.typetorch.dev/guides/fleet-and-alerts.md).
- **Agent prompt.** The last step asks what your game is, then writes `AGENT_PROMPT.md`: what is set up and the rules
from the [agent playbook](https://www.typetorch.dev/agents/AGENTS.md), for your coding agent's first message. `typetorch init --agent`
prints it again. When `claude` is on your PATH, it offers to add the `typetorch/claude-plugin` marketplace and start
Claude Code with that prompt.
- **Package versions.** `init` itself runs the CLI you started it with, but the game gets the versions the template
pins, which are behind npm today ([take the newest versions](https://www.typetorch.dev/getting-started/fresh-setup.md#take-the-newest-versions)). Afterwards `bun run typetorch ...` runs the
game's own CLI.
- **Stopped half way?** Run it again. It continues at the first unfinished step (progress is in `.typetorch/init.json`,
which never holds a secret).
- **Already set up?** In a game that already has `typetorch.json`, `bun run typetorch init` checks what each step left
behind (tools, dependencies, the Open Cloud key, the key files, the backend, the dev branch). It lists what is missing
or broken and offers to run that step again. `--phase ` runs again from that step (`preflight`, `project`,
`roblox`, `keys`, `kernel`, `backend`, `deploy`, `agent`).
- **Scripts and tests.** `--answers ` replays the answers from a JSON array of strings. Secrets never come from
that file: they come from the environment or `.env`. `--dir ` starts somewhere other than the working
directory.
The steps below are what `init` does, by hand. Use them as the reference when a step fails, or to set things up
yourself.
## By hand
You need about an hour. Steps 3 to 9 are done once per game.
**Who does what.** Some steps need the account that owns the experience. For a group-owned game that is the **group
owner** (or a member whose group role may create assets and publish places). They are marked **(owner)**.
## 1. Install the tools
| Tool | Why | Install |
|---|---|---|
| [Bun](https://bun.sh) 1.3+ | package manager; runs the builds | PowerShell: `powershell -c "irm bun.sh/install.ps1 \| iex"`; bash: `curl -fsSL https://bun.sh/install \| bash` |
| [git](https://git-scm.com) | every build is identified by its commit | your OS package manager |
| [Rokit](https://github.com/rojo-rbx/rokit) | pins Rojo and Lune per project | the Rokit releases page, then `rokit self-install` |
| Roblox Studio | creating the experience, settings, testing | [create.roblox.com](https://create.roblox.com) |
| TypeTorch Studio plugin (optional) | only for [testing in Studio](https://www.typetorch.dev/guides/studio-testing.md) with `typetorch serve` | `TypeTorchSync.rbxm` from the [studio-plugin releases](https://github.com/typetorch/studio-plugin/releases/latest) into Studio's plugins folder |
roblox-ts, Rojo and Lune are installed per project in step 2. Two more per-project tools, added in the game folder
after step 2:
| Tool | Why | Install |
|---|---|---|
| darklua | the [production pack](https://www.typetorch.dev/guides/deploy-and-rollback.md#production-pack) (CLI 0.17+): strips comments and whitespace from the payload that `build`, `upload` and `deploy` make. Without it every build warns `darklua not found: this payload isn't minified` and uploads the unpacked code | `rokit add seaofvoices/darklua` (the template's `rokit.toml` doesn't list it yet) |
| goblox (optional) | a Go port of roblox-ts, several times faster; `typetorch build` uses it when it is installed (CLI 0.16+, [Compiler](https://www.typetorch.dev/guides/deploy-and-rollback.md#compiler)). The template's `build` script ends with `rbxtsc`, so each build then warns and runs goblox directly; end the script with `goblox` instead. goblox doesn't run the template's `rbxts-transform-debug` plugin: move the macros first ([Debug macros](https://www.typetorch.dev/getting-started/migrate.md#debug-macros)) | `bun add -d goblox` |
**Check:**
```sh
bun --version
git --version
rokit --version
```
Each prints a version (Bun 1.3 or newer).
## 2. Get the code
Clone the template and install:
```sh
git clone https://github.com/typetorch/template my-game
cd my-game
git remote remove origin
bun install
rokit install
```
- `bun install` gets every TypeTorch package from npm: `@typetorch/framework` and `@typetorch/kernel`, and as dev
dependencies `@typetorch/transformer`, `@typetorch/cli` and `@typetorch/dev-server`. It also installs roblox-ts.
- `rokit install` installs Rojo and Lune at the versions pinned in `rokit.toml`.
- `bun run typetorch ` runs the CLI (the template's `"typetorch": "typetorch"` script). Without installing,
`npx @typetorch/cli ` runs the same CLI. The CLI runs on Node 20+ or Bun; builds still need Bun.
- Run the compiler through `bun run build` (or `bunx rbxtsc`). In a Bun project on Windows, `npx rbxtsc` runs an
unrelated placeholder package.
**Check:**
```sh
rojo --version
bun run build
bun run typetorch build
```
- `rojo --version` prints `7.7.0-rc.1` inside `my-game`.
- `bun run build` compiles with no errors.
- `bun run typetorch build` prints a `built (branch ..., channel ...)` line, then
`.typetorch/payload.rbxm ... modules`, and `sources template , framework v, kernel v` (the
npm versions you installed). A newer CLI also prints a `compiler` line (`rbxtsc ` or `goblox `).
### Take the newest versions
The template's versions are behind. Its `bun.lock` installs these, not the newest on npm:
| Package | The template installs | npm (2026-11-16) |
|---|---|---|
| `@typetorch/framework` | 0.5.0 | 0.7.2 |
| `@typetorch/kernel` | 0.5.1 | 0.5.7 |
| `@typetorch/cli` | 0.9.1 | 0.19.0 |
| `@typetorch/transformer` | 0.2.1 | 0.3.2 |
| `@typetorch/dev-server` | 0.2.3 | 0.3.3 |
Many commands in these docs need a newer CLI (`typetorch serve` needs 0.11+), live reload in Studio needs kernel
0.5.4+, and step 8 publishes the kernel from `node_modules/@typetorch/kernel`. So update before step 8:
```sh
bun add @typetorch/framework@latest @typetorch/kernel@latest
bun add -d @typetorch/cli@latest @typetorch/transformer@latest @typetorch/dev-server@latest
rokit add seaofvoices/darklua
bun run build
```
The template's `studio.project.json` (Studio testing) doesn't map the kernel's `RemoteDebug`, `Bundle` and `LiveDebug`
modules, so a playtest warns `TypeTorchKernel. is missing` and runs without them. Add them under
`ServerScriptService.TypeTorchKernel` as `node_modules/@typetorch/kernel/place.project.json` maps them.
Commit the changed `package.json`, `bun.lock` and `rokit.toml`. Later, `bun run typetorch update` moves the CLI alone
to the newest version (it asks first; `--check` only shows the versions).
A game set up with `typetorch init` already has the template's kernel in its place. After the update,
`bun run typetorch kernel deploy --dry-run`, then `bun run typetorch kernel deploy`, patches the newer kernel in
([Kernel updates](https://www.typetorch.dev/guides/deploy-and-rollback.md#kernel-updates)). The patch needs the place setting **Allow place
to be updated using Save Place API** on and no Team Create session.
### Unreleased framework or kernel changes (optional)
Skip this unless you need a framework, kernel or transformer change that isn't on npm yet. Clone those repos **next
to** your game:
```text
games/ any folder
my-game/ your game
framework/ https://github.com/typetorch/framework
kernel/ https://github.com/typetorch/kernel
transformer/ https://github.com/typetorch/transformer
```
From the `games` folder:
```sh
git clone https://github.com/typetorch/framework
git clone https://github.com/typetorch/kernel
git clone https://github.com/typetorch/transformer
cd framework
bun install
cd ../transformer
bun install
cd ../my-game
bun run packages
bun run build
```
- `bun run packages` builds `../framework` and `../transformer`, packs all three into `.typetorch/packages/`, and
extracts them over `node_modules/@typetorch`: a local override of the npm versions. Run it again after you pull or
change a checkout.
- The override stays on across `bun install` until `bun run packages --off`, which deletes it and reinstalls the npm
versions.
- With the override, `typetorch build` stamps the checkouts' commits as the payload's sources
(`framework , kernel `) instead of the npm versions.
- On Windows with git's `core.autocrlf` on, `--off` can rewrite `bun.lock` with other line endings, so the next build
id ends in `-dirty`. `git checkout -- bun.lock` makes the tree clean again.
## 3. Create the group and the experience (owner)
A group-owned game is the usual setup: the payloads, the key asset and the hot assets are uploaded to the group, and
`LoadAsset` only loads assets that the experience's owner owns.
1. Create a group on Roblox, or use your existing one.
2. In Studio: **File > New > Baseplate**, then **File > Publish to Roblox As...**. Pick the group as the creator and
create a new experience. (The kernel deploy in step 8 replaces this baseplate.)
3. In [Creator Hub](https://create.roblox.com/dashboard/creations), open the experience's "..." menu and use
**Copy Universe ID** and **Copy Start Place ID**.
**Check:** you have two numbers, the universe id and the place id, and the experience shows the group as its creator.
## 4. Experience settings (owner)
In Studio, with the place open: **File > Game Settings > Security**.
| Setting | Value | Why |
|---|---|---|
| Allow HTTP Requests | on | the kernel's live server reports ([fleet API](https://www.typetorch.dev/guides/fleet-and-alerts.md)), [analytics](https://www.typetorch.dev/guides/analytics.md), and the Claude tab (remote-claude). The kernel place file turns it on too |
| Enable Studio Access to API Services | on | Studio playtests read branch heads and DataStores |
| Allow Mesh / Image APIs | optional | only for images Claude shows in the chat; the owner must be 13+ and ID-verified |
| Allow Loading Third Party Assets | optional | only for remote-claude Toolbox inserts. It applies to every server of the experience |
`ServerScriptService.LoadStringEnabled` (not in Game Settings, in Studio's Properties) turns `loadstring` on for the
whole place. Only remote-claude's `run_luau` needs it, on dev servers. **Turn it on only in a place where you want
`run_luau` (a test place); keep it off in a live game.**
- `kernel deploy` patches (`--place-file`, CLI 0.7.3+) leave your place's value as it is.
- `kernel deploy --replace-place` (step 8) publishes it **off** (CLI 0.7.5+; older CLIs with a kernel up to 0.3.5
publish it on: turn it off in Studio afterwards if this place won't use `run_luau`).
- `kernel deploy --loadstring` (CLI 0.7.5+) turns it on on purpose, in both modes: use it for a test place where you
want `run_luau`.
- `bun run typetorch doctor` reports it (`loadstring`).
**Check:** the settings stay on after you reopen Game Settings.
## 5. typetorch.json
The template's `typetorch.json` belongs to the template's own test game. Replace it with yours:
```json
{
"project": "my-game",
"universeId": 1234567890,
"placeId": 9876543210,
"creator": { "groupId": 1234567 },
"defaultBranch": "prod",
"branches": { "main": "prod" },
"channels": { "prod": "prod" },
"members": { "111111111": "owner" },
"devBadgeId": null,
"approval": "prod",
"kernel": "node_modules/@typetorch/kernel"
}
```
Remove the template's `signingPublicKeys`, `keyAssetId` and `fallbackPublicKey`: step 7 writes yours.
| Field | Meaning |
|---|---|
| `project` | a short name, used in asset names |
| `universeId`, `placeId` | your experience (step 3) |
| `creator` | the experience owner: `{ "groupId": … }` or `{ "userId": … }`. Payloads are uploaded to it |
| `defaultBranch` | the branch public servers run (`prod`) |
| `branches` | git branch → TypeTorch branch. Unlisted git branches map to their own name, lowercased, `/` → `-` |
| `channels` | TypeTorch branch → `prod` or `dev`. Unlisted: `prod` for `defaultBranch`, `dev` for everything else |
| `members` | Roblox user id → `owner` or `dev` (who gets the dev menu; see step 11). The old role `admin` counts as `dev`. Servers see it after `typetorch access push` |
| `revoked` | optional: user ids that lose dev access |
| `devBadgeId` | optional badge id; its holders are devs |
| `approval` | `all` (default): every deploy waits for your y/N; `prod`: only prod-channel deploys do; `none` |
| `kernel` | the kernel folder for `kernel deploy` (`node_modules/@typetorch/kernel`, or a kernel checkout) |
| `signingPublicKeys`, `revokedKeys`, `fallbackPublicKey`, `keyAssetId` | written by `typetorch keys` (step 7). Don't edit by hand |
| `backend` | optional, `{ "url": ... }`: written by `typetorch backend setup` ([Live servers and alerts](https://www.typetorch.dev/guides/fleet-and-alerts.md)); CLI 0.8's `fleet` key is read once, with a warning |
| `health` | optional, `{ "errors": 3, "window": 30, "rollback": true }`, with `"prod"` / `"dev"` overrides: when a server rolls a new build back (kernel 0.3.7+; [Set the health window](https://www.typetorch.dev/guides/deploy-and-rollback.md#set-the-health-window)) |
| `autoRollback` | optional, `{ "failedPct": 20 }`: `deploy --wait` rolls the branch back at this % of failed servers (1-100; [Wait and automatic rollback](https://www.typetorch.dev/guides/deploy-and-rollback.md#wait-and-automatic-rollback)) |
| `backup` | optional, `{ "refresh": "auto", "healthyHours": 3 }` (the defaults): a prod deploy or promote at your terminal makes the build it replaced the place's backup build, once that build ran `healthyHours` (0-168) with no failure; `"off"` leaves it to `kernel deploy` and `typetorch backup refresh` ([The backup build](https://www.typetorch.dev/guides/deploy-and-rollback.md#the-backup-build)) |
| `compiler` | optional, `"goblox"` or `"rbxtsc"`. Unset: goblox when it is installed, else rbxtsc; `TYPETORCH_COMPILER` overrides it ([Compiler](https://www.typetorch.dev/guides/deploy-and-rollback.md#compiler)) |
| `notifications` | optional: the experience notification kinds and caps that `typetorch notify push` sends to the backend ([Notifications](https://www.typetorch.dev/guides/notifications.md)) |
Unknown keys are ignored with a warning (`unknown key "..." (ignored)`). That includes `minify`, which the darklua
warning suggests: CLI 0.19.0 doesn't read it yet, so use `--no-minify` on `build`, `upload` or `deploy` to skip the
production pack.
Commit it:
```sh
git add typetorch.json
git commit -m "My game"
```
**Check:** `bun run typetorch doctor` lists `typetorch.json` as `ok` with your universe and place (key checks fail
until step 6).
## 6. The Open Cloud API key (owner)
Create it in [Creator Hub](https://create.roblox.com/dashboard/credentials) > **Open Cloud > API Keys > Create API Key**,
as the group owner (or a member allowed to upload and publish for the group). A key acts with its owner's permissions.
Add these permissions and select your experience where asked:
| CLI job | Commands | Scopes |
|---|---|---|
| assets | `deploy`, `upload`, `promote` (of an unfinished upload), `test --cloud`, `keys init` / `rotate` (the key asset), `assets sync` / `status`, `doctor` | `asset:read`, `asset:write`; Luau Execution `universe.place.luau-execution-session:read` and `:write` (the cloud test that runs before every prod deploy, hot assets, doctor's place check) |
| deploy | `deploy`, `rollback`, `promote`, `approve`, `pin`, `keys rotate` / `resign`, `deployments`, `report`; `settings`, `backend setup`, `access push` | `universe-messaging-service:publish`; DataStore `universe-datastores.objects:read`, plus `:create` and `:update` (the shared deploy number and the [signed settings](https://www.typetorch.dev/guides/settings.md), below) |
| place | `kernel deploy`, `kernel restore` | Luau Execution (`universe.place.luau-execution-session:read` and `:write`: the place is patched in a task, no download), and `asset:read` to record the place version; `universe.place:write` to publish a place file: `--replace-place` (step 8), a `--place-file` copy, `kernel restore ` |
- **The shared deploy number.** Every machine that deploys (your PC, a second PC, remote-claude) takes the next
deploy number (`#seq`) from the game's DataStore: the kernel's records of past deploys, and a counter the CLI claims
atomically. That's what the DataStore scopes are for. Without them a deploy uses only your PC's log (fine while you
deploy from one machine), and the deploy warns and uses this machine's log only.
- **Not needed:** `universe:write` and `universe:read` (ConfigService). Since kernel 0.3.8 TypeTorch keeps no
ConfigService keys: dev access, the fleet API and the analytics settings live in one
[signed settings record](https://www.typetorch.dev/guides/settings.md) in the game's DataStore.
- **Not available to API keys today:** `legacy-asset:manage`, the download of a place file. `kernel deploy` doesn't need it:
the default engine patches the place through Luau Execution. A copy (`--place-file`) is the fallback, see step 8. Creator
Hub doesn't offer it for API keys.
- Set an expiry date, and add your IP under accepted IP addresses if you can.
- Everything runs from your machine. TypeTorch ships no CI for games, so the key never has to leave your PC.
**Put the keys in the game repo's `.env`.** It's gitignored by the template, and it's where the CLI reads secrets
(`typetorch.json` holds everything else, CLI 0.9). Add one line, then save:
```text
OPENCLOUD_API_KEY=
```
With the TypeTorch backend, two more lines go there: `TYPETORCH_API_KEY=` and
`TYPETORCH_ADMIN_TOKEN=` (then `bun run typetorch backend setup --url `).
`--env-file ` or `TYPETORCH_ENV_FILE` (real environment) read another file instead of `.env`.
- One shared key (`OPENCLOUD_API_KEY`) is the simple setup. You may split it per job instead:
`OPENCLOUD_ASSETS_KEY`, `OPENCLOUD_DEPLOY_KEY` and `OPENCLOUD_PLACE_KEY` (each falls back to the shared key).
- remote-claude reads the key the same way (environment, then the game repo's `.env`) and needs the shared key (`OPENCLOUD_API_KEY`);
see [remote-claude](https://www.typetorch.dev/guides/remote-claude.md).
- Never commit a key, never paste it into chat or an issue, and never give it to an agent.
**Check:** `bun run typetorch doctor`. The `key assets`, `key deploy` and `key place` lines are `ok` (or `warn` with
"shared"), and each `scope ...` probe is `ok` for the scopes you added. The messaging probe publishes one harmless
message to the topic `TypeTorch/doctor`.
## 7. Prod signing keys
With kernel 0.3, public servers only run prod builds that you signed. Two key pairs do it: the **main key** (shown as
**Root Key** in the dev menu) and the **Fallback Key**. Details: [Prod signing](https://www.typetorch.dev/guides/prod-signing.md).
```sh
bun run typetorch keys init
bun run typetorch keys init --fallback
git add typetorch.json
git commit -m "Prod signing keys"
```
- `keys init` writes the main key file `~/.config/typetorch/keys/.key`, creates the **key asset** (a small
group-owned Model that lists the trusted public keys) and writes `signingPublicKeys` and `keyAssetId` into
`typetorch.json`.
- `keys init --fallback` writes `~/.config/typetorch/keys/.fallback.key` and `fallbackPublicKey`.
- **Back up both key files and the game repo's `.env`** offline (an encrypted USB stick, or a password manager). They are
plaintext and never leave your PC. Never put them in a repo. Before a live game depends on them, also split off an
`asset:write` key and plan a rotation drill ([Prod signing: back up and drill](https://www.typetorch.dev/guides/prod-signing.md#back-up-and-drill)).
**Check:** `bun run typetorch doctor` shows both key files `ok` and matching `typetorch.json`, and the key asset as
Approved.
## 8. Publish the kernel place (owner)
The kernel is the only TypeTorch code in the place. Today `kernel deploy` publishes the **whole** place from the
kernel's place file: a baseplate, a spawn and the kernel. That is right for this fresh place.
```sh
bun run typetorch kernel deploy --dry-run
bun run typetorch kernel deploy --replace-place --yes
```
- The dry run runs the kernel's Lune syntax check, prints the kernel version and hash, and builds
`.typetorch/place.rbxl` with your trust roots stamped: `KeyAssetId`, `FallbackPublicKey` and `BootstrapHeads`. Check
the `keys` line shows your key asset id.
- `--replace-place --yes` publishes it. It refuses without the keys from step 7.
- **Never use `--replace-place` on a place with Studio-built content**: it wipes it (it stays in the place's version
history). For such places `kernel deploy` patches only the kernel into the live place, with no download, when the place allows saving
through the API (Creator Hub > Permissions); otherwise into a Studio copy. See
[migrate: install the kernel](https://www.typetorch.dev/getting-started/migrate.md#9-install-the-kernel-in-your-place).
- Studio must not have the place open in Team Create while you publish: that returns 409.
**Check:** join the game from the Roblox app. Open the Developer Console (F9) > **Server**. You should see:
```text
[TypeTorch] kernel (API 1) on a public server, branch prod, signed deploys only (keys: key asset)
[TypeTorch] branch prod: nothing loaded (no verified, bootstrap or usable stored head); peers and the backup next, and waiting for a signed deploy
```
(`` is the kernel you installed, for example `0.5.7`. A kernel from the
[local override](https://www.typetorch.dev/getting-started/fresh-setup.md#unreleased-framework-or-kernel-changes-optional) shows its commit: `kernel @`.)
Type `/tt status` in chat: it answers (you are the owner, so you are a dev).
## 9. First deploy
Commit everything, stay in the game (keep that server running), then deploy from the `main` branch:
```sh
git status
bun run typetorch deploy --dry-run
bun run typetorch deploy
```
- `main` maps to the TypeTorch branch `prod` (prod channel), so the CLI builds a clean prod build (debug prints
removed; packed with darklua when it is installed), uploads it, waits for moderation, runs the **cloud test** (the build boots headless in your place, about
11 s), then asks **y/N**. Answer `y`: it signs the message with both keys and publishes it.
- Then it waits up to 90 s for the servers' reports, and rolls the branch back by itself if the build fails on them
([safe deploys](https://www.typetorch.dev/guides/deploy-and-rollback.md#safe-deploys)). That needs the fleet API; until you set it up, the
wait is skipped with a note.
- The CLI also stores the head in the game's DataStore (the **durable head**; it needs the deploy key's DataStore
scopes from step 6), so servers that start later boot it even if none was running. Without those scopes only running
servers get the deploy: keep one open for the first deploy.
**Check:**
- The CLI prints `deployed #1 prod@ -> (asset ) in ...`.
- In game, within a few seconds, the Target Rush pad and the lobby coins appear. You stay connected.
- `/tt status` shows the generation. The dev menu (step 11) shows your artifact with two verified badges.
- `bun run typetorch deployments` lists `#1` with `*` (live).
## 10. A dev branch
```sh
git switch -c dev
bun run typetorch deploy
```
- `dev` is a dev-channel branch: unsigned, and with `"approval": "prod"` it publishes without a y/N.
- Public servers ignore it. In game, type `/tt new dev`: you are teleported to a new reserved server running `dev`.
**Check:** `/tt status` in the new server says `reserved server, branch dev (dev)`. Change a value in
`src/shared/rush/config.ts` (for example `TARGET_SIZE`), commit, deploy again, and watch the targets change while you
play. More in [Branches and channels](https://www.typetorch.dev/guides/branches-and-channels.md).
## 11. The dev menu and who gets it
Devs open the dev menu with the **DEV** button, `Ctrl+Shift+D` or `/tt dev`. A player is a dev when they are:
- the experience owner (the user creator, or rank 255 in the owning group): always;
- in `members` (`owner` or `dev`; an old `admin` counts as `dev`), once you published the lists (below);
- a holder of the `devBadgeId` badge (published the same way; awarding the badge in game is **planned**);
- anyone in a Studio playtest;
and not in `revoked`. **Owners** are the experience's creator (or the owning group's owner) and `members` with the role
`owner`: they also get the Manage tab and can switch any server in place. Prod-channel servers (every public server)
show the menu read-only. Tabs: [The dev menu](https://www.typetorch.dev/guides/dev-menu.md).
**Publish the lists** after every change to `members`, `revoked` or `devBadgeId`:
```sh
bun run typetorch access push
```
- It writes the `access` field of the game's [signed settings record](https://www.typetorch.dev/guides/settings.md) (DataStore `TypeTorch`,
key `settings`), signed with both prod keys (step 7), then pings the servers. Game code can write DataStores but
can't sign, and servers refuse a record that doesn't verify, so nothing in your game can make itself a dev.
`--dry-run` shows the lists first.
- Servers need **kernel 0.3.8+** to read it. Running servers apply a push within seconds (the ping), or within about a
minute without it.
- Before the first push, only the experience owner is a dev. After a change, servers keep the old lists until the
next push (a revoked dev stays a dev). `deploy` and `doctor` (`dev access`) warn about both;
`bun run typetorch access status` compares `typetorch.json` with the last push.
**Check:** as the owner you see the DEV button in game. After `access push`, a member sees it too.
## 12. `/tt` chat commands
Devs only. They work even when a build is broken, so they are the fallback when the dev menu can't open.
| Command | What it does | Who |
|---|---|---|
| `/tt status` | branch, channel, artifact, kernel build, signing mode | dev |
| `/tt branch ` | switch this server to a branch | devs on private or reserved servers; owners on any server |
| `/tt new [assetId]` | open a reserved server on a branch (pinned to an artifact if given) and teleport you | dev |
| `/tt reload` | load the branch head again | dev |
| `/tt rollback` | swap this server back to its previous artifact | dev; owners on prod-channel servers |
| `/tt pin ` / `/tt unpin` | hold this server on a known artifact / release it | devs on dev servers; owners on any server |
| `/tt bundle` | send a debug bundle of this server to the backend (kernel 0.5.3+) | dev |
| `/tt dev` | open the dev menu | dev |
`/tt grant` and `/tt revoke` are **planned**.
## 13. Roll back
```sh
bun run typetorch rollback --branch prod
```
It points `prod` back to the previous different build. Nothing is rebuilt or uploaded, so it takes about 1 to 2 seconds.
`--to ` picks a build. It asks y/N and signs like a deploy. More in
[Deploy and rollback](https://www.typetorch.dev/guides/deploy-and-rollback.md).
**Check:** `bun run typetorch deployments` shows a `rollback` row marked live; in game the previous version runs.
## Next steps
- [Testing in Studio](https://www.typetorch.dev/guides/studio-testing.md): run your local code with `bun run typetorch serve` (CLI 0.11+) and
the Studio plugin; saves reload a running playtest (kernel 0.5.4+).
- [Live servers and alerts](https://www.typetorch.dev/guides/fleet-and-alerts.md): `typetorch servers`, deploy reports, alerts, and the
automatic rollback after a bad deploy.
- [Analytics](https://www.typetorch.dev/guides/analytics.md): your own analytics, experiments and player journeys (the template already
creates the engine).
- [Player data](https://www.typetorch.dev/guides/player-data.md) before you save anything for players.
- [Hot assets](https://www.typetorch.dev/guides/hot-assets.md): let builders update models and UI live.
- [remote-claude](https://www.typetorch.dev/guides/remote-claude.md): prompt Claude Code from inside a dev server.
- [Troubleshooting](https://www.typetorch.dev/guides/troubleshooting.md) when something doesn't match a **Check**.
---
# Migrate an existing roblox-ts game
This guide moves a roblox-ts game to TypeTorch: the method, the rules every module must follow, and before/after code
for each pattern. An AI agent can do most of it for you with the [agent playbook](https://www.typetorch.dev/agents/AGENTS.md); this page is
what it follows.
**TypeTorch is roblox-ts only.** A game written in plain Luau has to move to roblox-ts first.
## What changes
| | Before | After |
|---|---|---|
| Where code lives | Scripts and ModuleScripts in the place, published with the place | a **payload** (ModuleScripts only) uploaded per build; the place holds only the **kernel** |
| How updates ship | publish the place, restart or migrate servers | `typetorch deploy`: live servers swap in seconds, players stay |
| Entry points | `*.server.ts`, `*.client.ts` | `src/server/boot.ts`, `src/client/boot.ts`, called by the kernel |
| Services | Flamework, Knit or singleton modules | `@Service()` / `@Controller()` classes that extend `Module` |
| Lifetime | the whole server | one **generation**: started, stopped and replaced on every deploy |
| Remotes | RemoteEvents/RemoteFunctions you create | `createNetwork` over the kernel's two stable remotes, with generated guards |
| State | module variables | the module instance, or `persist` when it must survive a swap |
The big idea: **every module must be stoppable and restartable.** A deploy stops the running code and starts a fresh
copy in the same server. Whatever a module made or connected must go away with it, and whatever must survive goes in
`persist`.
## Before you start
- Install the tools from [Fresh setup](https://www.typetorch.dev/getting-started/fresh-setup.md) step 1 (Bun, git, Rokit).
- Keep a copy of the [template](https://github.com/typetorch/template) next to your game as the reference
(`git clone https://github.com/typetorch/template ../template`). When in doubt, copy what the template does.
- Work on a branch: `git switch -c typetorch-migration`. Commit after every step that builds.
- Keep a list of what you change and what's left (`MIGRATION_NOTES.md`).
- Don't change DataStore names or the shape of saved data during the migration.
- **A live game with players?** This page is the code part. Do it inside the
[go-live checklist](https://www.typetorch.dev/guides/go-live-checklist.md): a copy of the game, a dev-branch soak, then a cut-over.
## 1. Take inventory
Find these in your code (`git grep` works in PowerShell and bash):
```sh
git grep -nE "PlayerAdded|PlayerRemoving|CharacterAdded" -- src
git grep -nE "RemoteEvent|RemoteFunction|OnServerEvent|OnClientEvent|InvokeServer|@rbxts/net|@flamework/networking" -- src
git grep -nE "CollectionService|GetInstanceAddedSignal|@flamework/components" -- src
git grep -nE "while \(true\)|task\.(spawn|delay|defer)|\bspawn\(|\bdelay\(|Heartbeat|RenderStepped" -- src
git grep -nE "_G\b|\bshared\." -- src
git grep -nE "DataStoreService|ProfileStore|ProfileService|MemoryStoreService|BindToClose" -- src
git grep -nE "@rbxts/react|@rbxts/roact|@rbxts/vide|PlayerGui|StarterGui|ScreenGui" -- src
```
Also list every `*.server.ts` / `*.client.ts`, the folders in `default.project.json`, and what the place contains that
isn't code (maps, StarterGui layouts, models, tools, scripts inside models).
## 2. Add the toolchain
Do these in order; the [agent playbook](https://www.typetorch.dev/agents/AGENTS.md#step-3-add-the-typetorch-toolchain) has the exact file
contents for each.
1. **Bun** as the package manager (delete other lockfiles after `bun install`).
2. **`rokit.toml`**: `rojo = "rojo-rbx/rojo@7.7.0-rc.1"` and `lune = "lune-org/lune@0.10.5"`, then `rokit install`.
Add darklua for the [production pack](https://www.typetorch.dev/guides/deploy-and-rollback.md#production-pack) (CLI 0.17+):
`rokit add seaofvoices/darklua`. Without it every `typetorch build`, `upload` and `deploy` warns that the payload isn't
minified.
3. **`package.json`**: the template's dependencies (`@typetorch/framework`, `@typetorch/kernel`, `@rbxts/t`,
`@rbxts/trove`), dev dependencies (`@typetorch/transformer`, `@typetorch/cli`, `@typetorch/dev-server`, roblox-ts 3,
TypeScript 5.5.3, `@rbxts/types`, `@rbxts/compiler-types`), `overrides`, and its scripts `build`, `watch`, `studio`
and `"typetorch": "typetorch"`. All `@typetorch/*` packages come from npm. The template's version pins are behind
npm today (CLI 0.9.1, transformer 0.2.1, framework 0.5.0), so take the newest:
```sh
bun add @typetorch/framework@latest @typetorch/kernel@latest
bun add -d @typetorch/transformer@latest @typetorch/cli@latest @typetorch/dev-server@latest
```
Leave out the template's `rbxts-transform-debug`: `@typetorch/transformer` 0.3+ has the debug macros itself
([Debug macros](https://www.typetorch.dev/getting-started/migrate.md#debug-macros) below). Copy `scripts/build-info.ts` from the template (`build` and `watch` run it)
and change its import line to `@typetorch/transformer/macros`, then `bun install`.
4. **`tsconfig.json`**: `include` only `src`; `"typeRoots": ["node_modules/@rbxts", "node_modules/@typetorch"]`;
`"types": ["types", "compiler-types"]`; `plugins`: only `{ "transform": "@typetorch/transformer" }` (transformer
0.3+; with 0.2, `rbxts-transform-debug` came first).
5. Optional: **goblox**, a Go port of roblox-ts that compiles several times faster. `bun add -d goblox`, and
`typetorch build` (CLI 0.16+) uses it from then on ([Compiler](https://www.typetorch.dev/guides/deploy-and-rollback.md#compiler)). It runs
only `@typetorch/transformer` and ignores every other tsconfig plugin. End the `build` script with `goblox` instead
of `rbxtsc`; otherwise each build warns and runs goblox directly, without the script's other steps.
6. **`default.project.json`** becomes the **payload**: a Rojo `Model` with `Server`, `Shared`, `Client` and `include`
(copy the template's; it maps `@rbxts` and only `@typetorch/framework`). Keep your old project as
`legacy.project.json` until the migration is done.
7. **`studio.project.json`** from the template, for [testing in Studio](https://www.typetorch.dev/guides/studio-testing.md).
8. **`.gitignore`**: `out/`, `include/`, `.typetorch/`, `src/shared/build.ts`, `.payload.gen.project.json`,
`.tsconfig.typetorch.json`, `.env`, `.env.*`.
9. **`typetorch.json`**: see [fresh setup step 5](https://www.typetorch.dev/getting-started/fresh-setup.md#5-typetorchjson). After you add or change
`members`, `revoked` or `devBadgeId`, run `bun run typetorch access push`: servers (kernel 0.3.8+) see the lists only
after that ([who gets the dev menu](https://www.typetorch.dev/getting-started/fresh-setup.md#11-the-dev-menu-and-who-gets-it)).
You don't need `scripts/packages.ts` or the template's `packages` and `postinstall` scripts. They are only for
building with framework or kernel changes that aren't on npm yet; to use that, copy the script and both entries too
([fresh setup: unreleased changes](https://www.typetorch.dev/getting-started/fresh-setup.md#unreleased-framework-or-kernel-changes-optional)).
**Check:** `bun run build` compiles. A Flamework game doesn't yet: every `@flamework/core` import fails with "You can
only use npm scopes that are listed in your typeRoots". That's expected; section 4 fixes it.
### Debug macros
`$print`, `$warn`, `$error`, `$assert` and `$dbg` add the source position (`[src/file.ts:12]`) in dev builds. Prod
builds compile them out: `$print`, `$warn` and `$dbg` to nothing (`$dbg(x)` to `x`), `$assert` and `$error` to the
plain call without the position. `$nameof`, `$file`, `$package`, `$git` and `$compileTime` always expand.
```ts
import { $print, $warn, $assert } from "@typetorch/transformer/macros";
```
- They come from `@typetorch/transformer` 0.3+. The transformer drops the import, so nothing reaches the Luau output.
- Every `typetorch build` sets `TYPETORCH_DEBUG_MACROS` (`1` for dev, `0` for prod) and `TYPETORCH_CHANNEL` in the
compile environment. The plugin option `debugMacros: false` turns the debug macros off too.
- The CLI (0.12.2+) writes `src/shared/build.ts` with `import { $compileTime, $git } from "@typetorch/transformer/macros"`
when the installed transformer has them, else from `rbxts-transform-debug`. The template's `scripts/build-info.ts`
(what `bun run build` and `watch` run without the CLI) still writes the `rbxts-transform-debug` import: change that
one line in your copy.
- Plain `print` and `warn` keep working, and reach prod builds as they are.
**A game already on `rbxts-transform-debug`** (the setup before transformer 0.3) moves in three steps:
1. Remove the `rbxts-transform-debug` plugin from `tsconfig.json`. The transformer also expands calls imported from
`rbxts-transform-debug`, so the build still works.
2. Rewrite the imports: `"rbxts-transform-debug"` to `"@typetorch/transformer/macros"`, in `src/` and in
`scripts/build-info.ts`.
3. `bun remove rbxts-transform-debug`. While it is installed, prod builds with rbxtsc add the CLI's own strip
transformer (`.typetorch/strip-debug-macros.cjs`); without it the transformer strips its own macros.
Not carried over from `rbxts-transform-debug`: `$dbg`'s custom handler and `$keysof`.
### Coming from Flamework
TypeTorch doesn't use Flamework any more: its own `@typetorch/transformer` generates the guards and dependency ids, and
`Modding`, `Reflect` and `t` come from `@typetorch/framework`. For a Flamework game the migration is mostly a swap:
- `@Service`, `@Controller`, constructor injection, `OnInit`/`OnStart`/`OnTick`/`OnPhysics`/`OnRender` keep their names:
change the imports to `@typetorch/framework`, and add `extends Module` and `super()` (section 4).
- `Modding`, `Reflect`, `t` from `@flamework/core` → the same from `@typetorch/framework`. Custom decorators use
`@metadata typetorch:parameters injectable`.
- `Flamework.addPaths` / `ignite` → the boot modules (section 3). `@flamework/networking` → `createNetwork`
(section 6: `predict` → `emit`, `invokeWithTimeout` takes seconds). `@flamework/components` → observers (rule 4).
- `Dependency()` stays: import it from `@typetorch/framework`. It works from `onInit`/`onStart` on, not in a
constructor, a field initializer or at the top level of a module (section 4). It is also the cycle breaker, with
`Lazy`.
- Remove `@flamework/*` and `rbxts-transformer-flamework` from `package.json`, `node_modules/@flamework` from
`typeRoots` and the Rojo projects; delete `flamework.build`, `flamework.json` and `include/flamework`.
- Type ids changed format (`@typetorch/framework:decorators@Service`): anything saved under Flamework ids
(`Flamework.id()`) won't match.
- Then the swap-safety rules (section 5). That part is the real work.
**Let the CLI do the mechanical part.** Once the toolchain builds, `bun run typetorch migrate --from flamework`
(`--dry-run` first) makes the changes above, turns the ignite files into boot modules, keeps every
`@flamework/networking` call site through the framework's `createFlameworkCompat`, and writes
`typetorch-migrate-report.md` listing each swap-safety item with its file and line. Details and the full mapping:
[Coming from Flamework](https://www.typetorch.dev/guides/from-flamework.md).
## 3. Entry points become boot modules
The payload holds **only ModuleScripts**: a Script or LocalScript fails `typetorch build`. The kernel calls two
modules instead.
Before:
```ts
// src/server/main.server.ts
import { Flamework } from "@flamework/core";
Flamework.addPaths("src/server/services");
Flamework.ignite();
```
After:
```ts
// src/server/boot.ts
import { startServer, type ServerKernel } from "@typetorch/framework";
import { BUILD } from "../shared/build";
export function boot(kernel: ServerKernel) {
return startServer(kernel, { modules: [script.Parent!.FindFirstChild("services")!], build: BUILD });
}
```
```ts
// src/client/boot.ts
import { startClient, type ClientKernel } from "@typetorch/framework";
import { BUILD } from "../shared/build";
export function boot(kernel: ClientKernel) {
return startClient(kernel, { modules: [script.Parent!.FindFirstChild("controllers")!], build: BUILD });
}
```
- `modules` lists folders. Every ModuleScript under them is required, so their top-level code must have no side
effects (helpers are fine).
- `src/shared/build.ts` is generated before every compile (git identity of the build). Don't edit or commit it.
- Delete the old `*.server.ts` / `*.client.ts` once their work moved into modules.
## 4. Services and controllers become modules
| Old | TypeTorch |
|---|---|
| Flamework `@Service()` / `@Controller()` | `@Service()` / `@Controller()` from `@typetorch/framework`, class `extends Module` |
| Flamework `OnInit`, `OnStart`, `OnTick`, `OnPhysics`, `OnRender` | the same names from `@typetorch/framework` |
| Flamework constructor injection | constructor injection (call `super()`) |
| Flamework `Dependency()` | `Dependency()` from `@typetorch/framework`, from `onInit`/`onStart` on (below) |
| Flamework `@Component` | a module using `observeElement` or `@rbxts/observers` (rule 4) |
| Knit `CreateService({ Name, Client, KnitInit, KnitStart })` | `@Service()` class; `KnitInit` → `onInit`, `KnitStart` → `onStart`, `Client` → network leaves |
| Knit `Knit.GetService("X")` | constructor injection, or `Dependency()` in a method |
| singleton module with top-level state | a `@Service()` / `@Controller()` class |
| shutdown cleanup | `onStop` and the module trove |
Lifecycle:
- `onInit`: in dependency order, one at a time; may yield briefly. A swap gives the generation about 20 s to become
ready, but a new server's first boot only about 6 s (kernel 0.3.2 starts a playable build within 15 s of a server
starting, whatever fails). Keep `onInit` short; slow loading belongs in `onStart`.
- `onStart`: spawned per module after every `onInit`; runs inside the module's trove.
- `onStop`: reverse order, before the trove is cleaned. The kernel gives a stopping generation 5 s.
- `onTick` (Heartbeat), `onPhysics` (PreSimulation), `onRender` (client RenderStepped): connected through the trove.
- `onPlayerAdded(player, playerTrove)`: every player, including the ones already in the server when the generation
starts.
### Flamework
Before:
```ts
import { OnStart, Service } from "@flamework/core";
import { ScoreService } from "./score";
@Service()
export class CoinService implements OnStart {
constructor(private readonly score: ScoreService) {}
onStart() {
// ...
}
}
```
After:
```ts
import { Module, Service, type OnStart } from "@typetorch/framework";
import { ScoreService } from "./score.service";
@Service()
export class CoinService extends Module implements OnStart {
constructor(private readonly score: ScoreService) {
super();
}
onStart() {
// ...
}
}
```
Don't do work in the constructor: `this.trove` and `this.ctx` are attached right after it.
### Modules outside the constructor: `Dependency()`
Plain classes a module builds (UI helpers), command handlers and methods reach other modules with `Dependency()`
(or `TypeTorch.module()`; `TypeTorch.tryModule()` returns `undefined` instead of throwing):
```ts
import { Dependency } from "@typetorch/framework";
import type { CharacterController } from "../controllers/character.controller"; // `import type`: no require cycle
export class SidebarHelper {
open() {
Dependency().freeze();
}
}
```
- It works once every module is constructed: from `onInit` on. In a constructor, a field initializer or at the top
level of a module it throws "ShopService isn't constructed yet: ...". Move such calls into a method, or into `onInit`.
- Only this realm's modules: a `@Service` on the server, a `@Controller` on the client.
- It returns the running generation's module, so after a swap it returns the new one.
### Dependency cycles: `Lazy`
Two modules that need each other (A injects B, B injects A) are a startup error ("dependency cycle: A -> B -> A"). Take
one side lazily; it resolves on first use, and the start order ignores it:
```ts
import { Lazy, Module, Service } from "@typetorch/framework";
import type { TeamService } from "./team.service";
@Service()
export class ItemService extends Module {
private readonly team = Lazy(); // a field works with every transformer
// or a constructor parameter (needs @typetorch/transformer 0.2.1+):
// constructor(private readonly team: Lazy) { super(); }
give(player: Player) {
if (this.team.get().isGuard(player)) return; // from onInit on; in a constructor it throws
}
}
```
`Dependency()` inside a method breaks a cycle too, the Flamework way.
### Knit
Before (typical shape):
```ts
import { KnitServer as Knit } from "@rbxts/knit";
const PointsService = Knit.CreateService({
Name: "PointsService",
Client: {
GetPoints(player: Player) {
return PointsService.getPoints(player);
},
},
points: new Map(),
getPoints(player: Player) {
return this.points.get(player) ?? 0;
},
KnitStart() {
// ...
},
});
```
After:
```ts
import { Module, Service, type OnInit, type OnStart } from "@typetorch/framework";
import { network } from "../../shared/net";
@Service()
export class PointsService extends Module implements OnInit, OnStart {
private points = new Map();
onInit() {
this.points = this.ctx.persist("points.v1", () => new Map());
this.trove.add(network.server.points.get.handle((player) => [this.getPoints(player)]));
}
onStart() {
// was KnitStart
}
getPoints(player: Player) {
return this.points.get(player.UserId) ?? 0;
}
}
```
with `points: { get(): ProperReturns }` in `ClientToServer` (see [Networking](https://www.typetorch.dev/getting-started/migrate.md#6-networking)).
### Plain singleton modules
Before:
```ts
// src/server/shop.ts
const prices = new Map([["sword", 100]]);
const owned = new Map();
Players.PlayerAdded.Connect((player) => owned.set(player, []));
export function buy(player: Player, item: string) {
/* ... */
}
```
After:
```ts
// src/server/services/shop.service.ts
const PRICES = new Map([["sword", 100]]); // constants may stay at the top level
@Service()
export class ShopService extends Module implements OnInit, OnPlayerAdded {
private owned = new Map();
onInit() {
this.owned = this.ctx.persist("shop.owned.v1", () => new Map());
}
onPlayerAdded(player: Player) {
if (!this.owned.has(player.UserId)) this.owned.set(player.UserId, []);
}
buy(player: Player, item: string) {
/* ... */
}
}
```
Other modules get it by constructor injection: `constructor(private readonly shop: ShopService) { super(); }`.
## 5. The swap-safety rules
Every rule has the same reason: the code is stopped and started again in the same server, many times.
### Rule 1: everything goes in the module's trove
Before:
```ts
RunService.Heartbeat.Connect((dt) => this.tick(dt));
const folder = new Instance("Folder");
folder.Parent = Workspace;
```
After:
```ts
this.trove.connect(RunService.Heartbeat, (dt) => this.tick(dt)); // or implement OnTick
const folder = this.trove.add(new Instance("Folder"));
folder.Parent = Workspace;
```
Connections, Instances you create, threads, and the disconnect functions TypeTorch returns
(`this.trove.add(network.server.x.y.on(...))`, `this.trove.add(TypeTorch.onSwapOut(...))`) all go in the trove.
**Cleanups must not touch a trove.** Never call `trove.remove`, `add` or `extend` from inside a cleanup function:
Trove throws "Cannot call trove.remove() while cleaning". The natural line to write is the broken one:
```ts
this.trove.add(() => this.trove.remove(this.flight)); // throws when the generation stops
```
A child trove from `this.trove.extend()` is cleaned by its parent anyway, so the line isn't needed. Call
`trove.remove(child)` only from normal code (a new character, a round that ends), as in rule 4.
- **Framework 0.5.2+:** a generation stop cleans each module's trove object by object, each cleanup in its own pcall.
A cleanup that throws warns ` cleanup threw: ...` and the rest still runs; the network stop, the unbind and
the generation's root trove are each guarded too.
- **Older frameworks:** one throwing cleanup aborts the whole stop. Later modules' troves, the network stop and the
dev menu's cleanup never run. The old dev menu stays on screen, dead, over the new one; the dead generation stays in
memory (several MB per swap); Instances it made keep acting (a `LinearVelocity` that pins the player). Until you
upgrade, fix every such cleanup, and see [Troubleshooting](https://www.typetorch.dev/guides/troubleshooting.md#live-servers) for a sweeper.
### Rule 2: no module-level state; persist only plain data
Every generation requires fresh copies of every module, so module-level variables start over on each swap, and
module-level code runs outside any trove.
Before:
```ts
const cooldowns = new Map(); // lost on every deploy
```
After, when it may start over on a deploy:
```ts
private cooldowns = new Map(); // on the instance
```
After, when it must survive a deploy:
```ts
private cooldowns = new Map();
onInit() {
this.cooldowns = this.ctx.persist("cooldowns.v1", () => new Map());
}
```
`persist` keeps the same table for the server's whole life. Store plain data: tables, arrays, Maps and Sets of
strings, numbers, booleans and Players. Never store functions, class instances, Promises, threads, connections, charm
atoms or Instances the generation created: they keep the old code alive or get destroyed by its trove. Change the key
(`"cooldowns.v2"`) when the shape changes. (Handles from a library that lives outside the payload are the one
exception; see [Player data](https://www.typetorch.dev/guides/player-data.md).)
`this.ctx` and `this.trove` are attached right after the constructor, so `this.ctx.persist`, `this.ctx.playerState`
and `Dependency()` fail in a field initializer (`private state = this.ctx.persist(...)`) or a constructor. Declare
the field, then assign it in `onInit` (or `onStart`), as above.
Per-player maps (cooldowns, states, sessions) use `playerState`: persisted, keyed by UserId, and a player's entry is
removed when they really leave (never on a swap), so nothing leaks:
```ts
private cooldowns!: PlayerState<{ lastUse: number }>; // import type { PlayerState } from "@typetorch/framework"
onInit() {
this.cooldowns = this.ctx.playerState("cooldowns.v1", () => ({ lastUse: 0 }));
}
use(player: Player) {
this.cooldowns.get(player).lastUse = os.clock(); // also set, has, delete
}
```
### Rule 3: players through `onPlayerAdded` or `observePlayers`
Before:
```ts
Players.PlayerAdded.Connect((player) => this.setup(player));
```
After:
```ts
onPlayerAdded(player: Player, playerTrove: Trove) {
this.setup(player, playerTrove); // playerTrove is cleaned when the player leaves or the generation stops
}
```
or, anywhere: `observePlayers(this.trove, (player, playerTrove) => ...)`.
- `Players.PlayerAdded` doesn't fire again for players already in the server, so a new generation would miss them.
These replay them.
- **Join handlers must be idempotent**, because they run again for everyone on every deploy. Guard one-time effects
(join rewards, welcome popups, analytics "joined" events) with a persisted set:
```ts
onPlayerAdded(player: Player) {
if (this.welcomed.has(player.UserId)) return; // this.welcomed = this.ctx.persist("welcomed.v1", () => new Set())
this.welcomed.add(player.UserId);
this.giveJoinReward(player);
}
```
- For work on a real leave only (not on a swap), connect `Players.PlayerRemoving` through the trove:
`this.trove.connect(Players.PlayerRemoving, (player) => ...)`. Per-player state in `playerState` is removed on a
real leave by itself (rule 2).
### Rule 4: tags and characters through observers
Before:
```ts
CollectionService.GetInstanceAddedSignal("Lava").Connect((part) => setupLava(part));
player.CharacterAdded.Connect((character) => setupCharacter(character));
```
After, with the framework's `observeElement` (tag + `isRealFrame` + one trove per instance; it skips copies under
ReplicatedStorage and StarterGui):
```ts
observeElement(this.trove, "Lava", (part, partTrove) => {
partTrove.connect(part.Touched, (hit) => this.burn(hit));
});
```
Characters, with [`@rbxts/observers`](https://www.npmjs.com/package/@rbxts/observers) (each observer returns a stop
function for the trove):
```ts
import Observers from "@rbxts/observers";
this.trove.add(
Observers.observeCharacter((player, character) => {
const humanoid = character.WaitForChild("Humanoid") as Humanoid;
humanoid.WalkSpeed = 20;
return () => print(`${player.Name}'s character is gone`);
}),
);
```
Characters without extra packages:
```ts
onPlayerAdded(player: Player, playerTrove: Trove) {
let characterTrove: Trove | undefined;
const onCharacter = (character: Model) => {
if (characterTrove) playerTrove.remove(characterTrove);
const trove = playerTrove.extend();
characterTrove = trove;
const humanoid = character.WaitForChild("Humanoid") as Humanoid;
trove.connect(humanoid.Died, () => print(`${player.Name} died`));
};
if (player.Character) task.spawn(onCharacter, player.Character);
playerTrove.connect(player.CharacterAdded, onCharacter);
}
```
### Rule 5: no global connections or loops outside troves
Before:
```ts
task.spawn(() => {
while (true) {
task.wait(30);
this.announce();
}
});
```
After: a loop directly in `onStart` is fine (it runs inside the module's trove):
```ts
onStart() {
while (true) {
task.wait(30);
this.announce();
}
}
```
Anywhere else: `this.trove.add(task.spawn(() => { ... }))`.
### Rule 6: no `_G` or `shared`
Before:
```ts
_G.coinsCollected += 1;
```
After: share through constructor injection (call a method on the other module), or keep the value in `persist`:
```ts
private stats = { collected: 0 };
onInit() {
this.stats = this.ctx.persist("coins.stats.v1", () => ({ collected: 0 }));
}
```
### Rule 7: `task.spawn`, `task.delay`, `task.defer` only through troves
Before:
```ts
task.delay(5, () => this.respawnCoin(id));
```
After:
```ts
this.trove.add(task.delay(5, () => this.respawnCoin(id)));
```
Replace the deprecated `spawn`, `delay` and `wait` with `task.*` while you are there.
### Rule 8: shutdown
On kernel 0.3.2+, a server shutdown runs every module's `onStop` (the kernel's own `BindToClose` calls the running
generation, for at most 20 s). Keep `onStop` short. `TypeTorch.onSwapOut` runs before a swap, never on shutdown.
On a swap the order is: every `onSwapOut` listener (every module still runs, no trove has been cleaned), then each
module's `onStop` and trove in reverse start order, then the network and the dev menu. So `onSwapOut` is the place for
last-resort work that must happen even if a later cleanup throws: saving into `persist`, flushing, tagging Instances
the next generation should find.
**Don't rely on `onStop` for saves.** A server that shuts down in the middle of a swap (the old build stopped, the new
one not running yet) has no running generation, so no `onStop` runs at all. Player data goes through a library in the
place that saves on close by itself ([Player data](https://www.typetorch.dev/guides/player-data.md#shutdown)), or is written as it changes.
Use `onStop` for short extras.
On older kernels, `game.BindToClose` can't be unbound, so bind it at most once per server (guard it with a persisted
flag).
### Rule 9: packages and libraries follow the same rules
It doesn't matter who wrote the code: a package from npm or a vendored library that runs inside a generation is
stopped and loaded again on every swap, like your own modules. The same two rules apply to it:
- what must survive a swap goes in `persist`;
- everything it creates (Instances, ScreenGuis, RenderStep bindings, connections, loops) is destroyed through a trove
when the generation stops.
Examples:
- **TopbarPlus:** destroy your icons in the trove: `const icon = new Icon(); this.trove.add(() => icon.destroy());`.
- **CameraShaker:** it binds a fixed RenderStep name, so stop it on stop: `this.trove.add(() => shaker.Stop());`
(or `this.trove.add(() => RunService.UnbindFromRenderStep("CameraShaker"))`).
- **A library with its own registry** (zones, hitboxes): destroy what you registered through the trove, and keep only
what must outlive the swap (plain data such as ids or settings) in `persist`, then hand it back in `onInit`.
**Libraries with module-level setup.** Every generation requires a fresh copy of every module in the payload,
libraries included. Whatever a library sets up when it is required, and never tears down, is kept for the server's (or
client's) whole life, once per swap: Vide's own `Heartbeat` stepper, TopbarPlus's overflow and gamepad connections and
its container ScreenGuis (about 3 MB per swap), a Promise library's pending chains. Look for top-level `Connect`,
`Instance.new`, `task.spawn` and `RunService` calls in each package you use. Two fixes work:
- **Drive it from the generation.** If the library lets you step it yourself, do that from the trove instead of letting
it connect its own: `this.trove.connect(RunService.Heartbeat, (dt) => vide.step(dt))`.
- **Load it once, outside the payload.** Keep one copy for the server's life: a place script requires it from
`ReplicatedStorage.lib` (like the [player data library](https://www.typetorch.dev/guides/player-data.md)), or the first generation clones the
bundled module there (outside the generation's folder, so it outlives the generation) and later generations require
that copy. Its state then survives swaps too, so each generation still removes what it registered through its trove.
## 6. Networking
Replace every RemoteEvent and RemoteFunction with one typed network. The kernel owns the only two remotes; a generation
must never create remotes.
Before:
```ts
// server
const remote = new Instance("RemoteEvent");
remote.Name = "CollectCoin";
remote.Parent = ReplicatedStorage;
remote.OnServerEvent.Connect((player, coinId) => {
if (!typeIs(coinId, "string")) return;
const total = this.score.add(player, 1);
remote.FireClient(player, total);
});
// client
const remote = ReplicatedStorage.WaitForChild("CollectCoin") as RemoteEvent;
remote.FireServer("coin-1");
remote.OnClientEvent.Connect((total: number) => print(total));
```
After:
```ts
// src/shared/net.ts
import { createNetwork, type ProperReturns } from "@typetorch/framework";
interface ClientToServer {
coins: {
collect(coinId: string): void;
balance(): ProperReturns;
};
}
interface ServerToClient {
coins: { changed(total: number): void };
}
export const network = createNetwork();
```
```ts
// server: in onStart
this.trove.add(
network.server.coins.collect.on((player, coinId) => {
const total = this.score.add(player, 1);
network.server.coins.changed.fire(player, total);
}),
);
this.trove.add(network.server.coins.balance.handle((player) => [this.score.get(player)]));
```
```ts
// client: in onStart
network.client.coins.collect.fire("coin-1");
this.trove.add(network.client.coins.changed.on((total) => print(total)));
this.trove.addPromise(
network.client.coins.balance.invoke().then(([value]) => {
if (typeIs(value, "number")) print(value);
}),
);
```
- The guards (`coinId` is a string) are generated from the types; the server also applies rate and shape limits and
kicks clients that flood it. Keep your own game checks (distance, ownership, cooldowns).
- RemoteFunctions become request leaves: `handle` on the server returns `[value]` or `[false, "reason"]`, `invoke` on
the client returns a Promise (15 s timeout; `invokeWithTimeout(seconds, ...args)` or a leaf's `timeout` in
`setNetworkLimits` changes it).
- `@rbxts/net`, `@flamework/networking`, Zap, Blink and ByteNet don't work inside a payload: convert them. From
Flamework: `connect` → `on` (in the trove), `setCallback` → `handle`, `broadcast` → `fireAll`, `except` →
`fireExcept`, `predict` → `emit` (runs the client's own `on` handlers, no traffic), `invokeWithTimeout(seconds, ...)`
keeps its name (seconds, 0.5 to 120).
- Remove RemoteEvents defined in the Rojo project or the place.
- More: [Networking](https://www.typetorch.dev/guides/networking.md).
## 7. UI
TypeTorch's UI workflow is observers + trove + charm atoms + `isRealFrame`. Two kinds of UI:
- **Built in code:** create it in a controller and put the ScreenGui in the trove, so a swap removes it and the new
code builds it again.
- **Built in Studio:** layouts stay in the place (StarterGui), or become [hot assets](https://www.typetorch.dev/guides/hot-assets.md).
Tag what code touches (`Element:.`) and drive it with `observeElement`; `isRealFrame` skips the StarterGui
templates. The payload can't carry ScreenGuis.
Before:
```ts
const button = Players.LocalPlayer.WaitForChild("PlayerGui").WaitForChild("Hud").WaitForChild("ShopButton") as TextButton;
button.Activated.Connect(() => (shopOpen = !shopOpen));
```
After:
```ts
import { atom, subscribe } from "@rbxts/charm";
private readonly ui = atom<{ open?: "shop" }>({});
onStart() {
// The open panel survives swaps as plain data; the atom itself is per generation.
const saved = this.ctx.persist("ui.v1", () => ({ open: undefined as "shop" | undefined }));
this.ui({ open: saved.open });
this.trove.add(subscribe(this.ui, (state) => (saved.open = state.open)));
observeElement(this.trove, "Element:HUD.ShopButton", (button, buttonTrove) => {
buttonTrove.connect(button.Activated, () => this.ui({ open: this.ui().open === "shop" ? undefined : "shop" }));
});
}
```
- Atoms synced from the server (charm-sync): [State with charm](https://www.typetorch.dev/guides/state.md).
- Pop in and out with `popIn` / `popOut` / `bump` (a UIScale; never tween `Size`). One `PopupQueue` for modals.
- React, Roact or Vide: mount the root in a controller and unmount it through the trove
(`this.trove.add(() => root.unmount())`).
### Animations, cutscenes and minigames across swaps
A client swap ends everything the old generation was playing. Players notice when something stops halfway, so resume
it from plain data instead of restarting it (or telling the player to start again).
- **Looped animations** die with the generation unless the next one plays them again; one-shot tracks are fine. Persist
`{ id, animationId, startedAt }` for each looped track and replay it in the next generation under the same `id`, so a
later "stop" message for that id still ends it.
- **State-driven effects** need no event at all: a tool's idle animation follows "this tool is a child of the character"
plus a synced atom ([State with charm](https://www.typetorch.dev/guides/state.md#patterns-that-survive-swaps)).
- **Cutscenes** are a track plus a camera. Persist `{ startedAt, endsAt }`, and on start resume with
`track.TimePosition = elapsed` (skip it when `endsAt` has passed). Players see one camera blip.
```ts
onStart() {
const cutscene = this.ctx.persist("cutscene.v1", () => ({ startedAt: 0, endsAt: 0 }));
const now = Workspace.GetServerTimeNow();
if (now < cutscene.endsAt) this.play(now - cutscene.startedAt); // sets track.TimePosition, then plays
}
```
- **Minigames:** a Tween can't be resumed at a phase. Persist the inputs so far (hits, answers, the current step) and
start the remaining part again.
## 8. Player data
Saving is game code; you pick the library. On TypeTorch the library must outlive the generations, so it lives in the
place, its session handles live in `persist`, sessions load on join and are released on a real leave. Read
[Player data](https://www.typetorch.dev/guides/player-data.md) before you migrate any data code, and test it on a dev branch first.
- Don't change store names, keys or the data format in the same step.
- Library calls that write (load, save, release) run as jobs of the place's `DataHost` script, so a deploy can't cut
one off ([why](https://www.typetorch.dev/guides/player-data.md#the-swap-safe-pattern)). ProfileService has its own example
([ProfileService](https://www.typetorch.dev/guides/player-data.md#example-profileservice)).
- The data code must not wait for place scripts in the cloud test ([why](https://www.typetorch.dev/guides/player-data.md#the-cloud-test)).
- Developer products: record the PurchaseId in the player's profile with the grant, and return `PurchaseGranted`
only after a save holds it ([Developer products](https://www.typetorch.dev/guides/player-data.md#developer-products)). `persist` alone
grants twice when Roblox retries on another server.
### Analytics (optional)
TypeTorch has its own analytics engine: joins, sessions, devices, tech health, zones and new players' first sessions are
logged for you, and your code adds funnels, purchases, currency and custom events
([Analytics](https://www.typetorch.dev/guides/analytics.md)). Nothing runs until you create an `AnalyticsEngine`, so create it in the
`onInit` of a module with a low `loadOrder` (server and client), not from a helper that first runs on some game event:
an idle server would send nothing. An analytics SDK you already use can stay; if it logs "joined" from a join handler,
guard it like any one-time effect (rule 3).
## 9. Install the kernel in your place
The place keeps your Studio content and gains the kernel. **Never run `kernel deploy --replace-place` on it:** that
publishes the whole place from the kernel's place file and wipes your maps and Studio UI.
First do [fresh setup](https://www.typetorch.dev/getting-started/fresh-setup.md) steps 4, 6 and 7 (settings, API key, signing keys). The kernel waits idle
until your first deploy, so your old scripts keep running meanwhile. Remove the old game scripts that the payload
replaces (keep the ones listed below) in Studio and publish just before the first deploy.
**With the CLI (patches only the kernel):** when the place allows saving through the API, nothing is downloaded: the CLI
patches the live place in a Luau Execution task. The place needs **Allow place to be updated using Save Place API** on
(Creator Hub > Creations > the experience > Places > the place > Permissions; off by default for places made in Studio) and no
Team Create session open.
1. Patch without publishing: `bun run typetorch kernel deploy --dry-run --install`. It adds the kernel folders (with your
trust roots `KeyAssetId`, `FallbackPublicKey` and `BootstrapHeads`) and the kernel's settings (`HttpService.HttpEnabled`),
checks that everything else is unchanged, and writes a report to `.typetorch/place-patches/`. Read the summary. It leaves
`ServerScriptService.LoadStringEnabled` as your place has it (`--loadstring` turns it on, for a test place only).
2. Publish it: the same command without `--dry-run`. It asks y/N and refuses if someone published meanwhile. Undo:
`bun run typetorch kernel restore --version `.
3. Move players to the new version (restart servers from Creator Hub, or the dev menu's **Migrate** on servers that still
run the old kernel).
If the place doesn't allow saving through the API (a Studio-made place with that setting off), use a copy: in Studio,
**File > Download a Copy** of the live place as a binary `.rbxl` file, and note its place version. Then
`bun run typetorch kernel deploy --dry-run --install --place-file --base `; the same command without
`--dry-run` publishes after a y/N, and `bun run typetorch kernel restore ` undoes it. The CLI can't download the copy
itself (`legacy-asset:manage` can't be given to API keys).
Later kernel updates work the same way, without `--install` ([Kernel updates](https://www.typetorch.dev/guides/deploy-and-rollback.md#kernel-updates)).
An agent can run them for you, with your OK before the publish.
**Or by hand in Studio:**
1. `bun run typetorch kernel deploy --dry-run` builds the kernel place with your trust roots stamped (it publishes
nothing) into `.typetorch/place.rbxl`.
2. Open it in Studio. Copy these three folders into your place, at the same spots:
`ServerScriptService.TypeTorchKernel` (it carries the `KeyAssetId`, `FallbackPublicKey` and `BootstrapHeads`
attributes), `ReplicatedStorage.TypeTorchKernelShared` and `ReplicatedFirst.TypeTorchKernelClient`.
3. Leave ServerScriptService's **LoadStringEnabled** off. Turn it on only in a place where you want remote-claude's
`run_luau` (a test place, never the live game): `loadstring` place-wide widens any future bug to running code.
4. **File > Publish to Roblox**, then move players to the new version.
`bun run typetorch doctor` reports what the kernel does with `LoadStringEnabled` (`loadstring`).
**Check:** the F9 server log shows `[TypeTorch] kernel (API 1) on a public server, branch prod, signed
deploys only (keys: key asset)`.
### What stays in the place
- the kernel (the three folders above);
- maps, terrain, lighting and settings;
- StarterGui layouts and other Studio content (or [hot assets](https://www.typetorch.dev/guides/hot-assets.md) for models and UI templates);
- StarterPlayer and StarterCharacter scripts (Animate, custom cameras);
- third-party Luau systems that can't be roblox-ts modules (admin panels, analytics SDKs);
- the player data library and its small host script ([Player data](https://www.typetorch.dev/guides/player-data.md)).
These change only with a place publish and a server restart. Prefer moving behavior out of scripts inside models into a
service that uses tags.
### Assets and builders
- Hard-coded asset ids keep working when the assets belong to (or are shared with) the experience owner.
- **Hot assets (built):** builders mark models and UI templates in the place with the `TypeTorchAsset` attribute,
`typetorch assets sync` (or the Studio plugin's Hot assets card, without a place publish) uploads them, and running
servers pick up new versions with no restart. `typetorch assets types` writes the keys as a typed map
(`src/shared/assets.gen.ts`). Code that clones
templates switches to `hotAsset(key, template)`. See [Hot assets](https://www.typetorch.dev/guides/hot-assets.md#migrating-existing-templates).
- **Builders** keep working in the place and publish from Studio: kernel deploys patch only the kernel, so they never
touch builders' content. Maps need a place publish and new servers (Manage > Servers > Migrate moves players to the
new version). A separate Build experience with pinned content packs is **planned**.
- The typed asset map from files (Asphalt) is **planned**.
## The cloud test runs your game code
> **Read this before your first prod deploy.** Every prod deploy and promote first boots your build in a headless
> Luau Execution task on your live place ([the cloud test](https://www.typetorch.dev/guides/deploy-and-rollback.md#the-cloud-test)). Your
> `onInit` and `onStart` run there against your **real DataStores, MemoryStores, MessagingService and HTTP
> endpoints**. No player joins, and place scripts don't run.
>
> `TypeTorch.channel` is `dev` in the test (CLI 0.7.3+; older CLIs report the branch's channel), so stores you
> split by channel point at dev data. Everything else is your live game's.
The test sets an attribute your code can check:
```ts
import { MessagingService, Workspace } from "@rbxts/services";
onStart() {
if (Workspace.GetAttribute("TypeTorchTest") === true) return; // the cloud test: no announcement from a headless task
MessagingService.PublishAsync("game/servers", `started ${game.JobId}`);
}
```
Guard only the side effects, so the test still boots your real code:
- **global resets and one-time jobs:** season rollovers, leaderboard wipes, migrations of shared keys;
- **raw MessagingService publishes:** cross-server announcements, "a server started" pings
(`TypeTorch.messaging.publish` already sends nothing from the test);
- **"server started" rows:** DataStore or MemoryStore writes, webhooks, your own HTTP APIs;
- **waits on place scripts:** they never run there, so the wait times out and the test fails
([the player data library](https://www.typetorch.dev/guides/player-data.md#the-cloud-test)).
## Cross-server messages
Move your MessagingService topics to **`TypeTorch.messaging`** (kernel 0.3.8+). The kernel holds one subscription
for all of them for the server's life, so a swap never subscribes again, and messages from dev branches don't reach
prod servers:
```ts
// before: MessagingService.SubscribeAsync("ban", (message) => kick(message.Data as BanMessage));
this.trove.add(TypeTorch.messaging.subscribe("ban", (data, meta) => kick(data)));
// before: pcall(() => MessagingService.PublishAsync("ban", data)), plus a TypeTorchTest guard
TypeTorch.messaging.publish("ban", data); // queued and retried; nothing is sent from the cloud test
```
Messages stay under 1 KiB, and the whole game gets about 80 messages a minute on one topic. Details, limits and the
server list (`TypeTorch.servers()`): [Cross-server messages](https://www.typetorch.dev/guides/messaging.md).
Roblox allows a server **20 + 8 × players** subscriptions. TypeTorch uses 5 (briefly 7), so raw MessagingService
topics you keep still fit, but each one subscribes again on every swap.
## 10. Verify, then ship
1. Local checks:
```sh
bun run build
bun run typetorch build
```
`typetorch build` refuses a payload with anything but Folders and ModuleScripts, and names the offending path.
2. [Test in Studio](https://www.typetorch.dev/guides/studio-testing.md): `bun run typetorch serve` with the Studio plugin, Play. Use the dev menu's Reload to
test a swap while you play.
3. Deploy a dev branch (`git switch -c dev`, `bun run typetorch deploy`), open it with `/tt new dev`, play, deploy
again while playing. Test player data across two deploys.
4. `bun run typetorch test --cloud` on the dev build passes: prod deploys run the same test.
5. Deploy `prod` from `main` ([fresh setup step 9](https://www.typetorch.dev/getting-started/fresh-setup.md#9-first-deploy)). A game with live players goes
through the [go-live checklist](https://www.typetorch.dev/guides/go-live-checklist.md) first.
### Count your errors before you ship
By default a server rolls a new build back when the build throws 3 errors in its first 30 s. An older game often
throws a few harmless ones. Then every server rolls back at once, and every deploy fails.
1. Deploy a dev branch and play it with a few people (a dev soak).
2. After each deploy, open the dev menu: **Server > Status** shows "Health window: 2/3 errors, 18 s left". Logs shows
the errors.
3. Fix what you can.
4. Still noisy? Set the limit a bit above what you saw, in `typetorch.json`:
```json
"health": { "errors": 10 }
```
Kernel 0.3.7+ reads it from each build. `bun run typetorch doctor` shows the values.
[More options](https://www.typetorch.dev/guides/deploy-and-rollback.md#set-the-health-window).
## Checklist
- [ ] roblox-ts project on Bun; `rokit.toml` pins Rojo 7.7.0-rc.1, Lune and darklua
- [ ] one compiler plugin, `@typetorch/transformer` 0.3+; debug macros imported from `@typetorch/transformer/macros`,
no `rbxts-transform-debug` left (also not in `scripts/build-info.ts`)
- [ ] `package.json`, `tsconfig.json`, `default.project.json` (payload), `studio.project.json`, `.gitignore` match the
template
- [ ] `typetorch.json` with your ids, `approval`, and (after `keys init`) the signing fields; `access push` after
every change to `members`, `revoked` or `devBadgeId`
- [ ] no `*.server.ts` / `*.client.ts` left; `src/server/boot.ts` and `src/client/boot.ts`
- [ ] every service/controller is a `@Service()` / `@Controller()` class extending `Module`
- [ ] no game code imports `@flamework/*`; no `@flamework/*` or `rbxts-transformer-flamework` in `package.json`
- [ ] `Dependency()` only in methods and `onInit`/`onStart` (never a constructor, field initializer or module top
level); cycles broken with `Lazy`
- [ ] connections, instances, threads in troves; loops only in `onStart` or the trove
- [ ] no cleanup function calls `trove.remove` / `add` / `extend` (child troves from `extend()` need no removal)
- [ ] `this.ctx.persist` / `playerState` and `Dependency()` assigned in `onInit` or `onStart`, never in field
initializers
- [ ] libraries with module-level setup (connections, ScreenGuis, steppers) driven from the trove or loaded once
outside the payload
- [ ] no module-level state; what must survive is in `persist` as plain data (per-player maps in `playerState`)
- [ ] players via `onPlayerAdded` / `observePlayers`; join handlers idempotent
- [ ] tags via `observeElement`, characters via `@rbxts/observers` (stop function in the trove)
- [ ] no `_G` / `shared`
- [ ] no RemoteEvent/RemoteFunction anywhere; one `createNetwork`
- [ ] UI: code-built in troves, Studio-built tagged and observed; looped animations and cutscenes resume after a swap
- [ ] `invokeWithTimeout` calls pass seconds (0.5 to 120), not milliseconds
- [ ] player data follows [the pattern](https://www.typetorch.dev/guides/player-data.md); store names split by channel
- [ ] developer product receipts recorded in the profile before `PurchaseGranted`; no saves only in `onStop`
- [ ] side effects guarded from the cloud test (`TypeTorchTest`); `typetorch test --cloud` passes
- [ ] MessagingService topics moved to `TypeTorch.messaging` (kernel 0.3.8), messages under 1 KiB
- [ ] kernel installed in the place; old game scripts removed
- [ ] `bun run build` and `bun run typetorch build` pass; a committed tree builds a clean id (no `-dirty`)
- [ ] a dev branch survived two deploys while you played
- [ ] errors in the first 30 s after a deploy counted; fixed, or `typetorch.json` `"health"` set above them
## Common pitfalls
| Pitfall | What happens | Fix |
|---|---|---|
| A `*.server.ts` left in `src/server` | `typetorch build`: "the payload may hold only Folders and ModuleScripts" | move its work into a module, delete it |
| `scripts/*.ts` compiled by rbxtsc | `Cannot find name 'console'` in `scripts/build-info.ts` | `"include": ["./src/**/*.ts"]` in tsconfig |
| Join reward in `onPlayerAdded` | everyone gets it again on every deploy | guard with a persisted set (rule 3) |
| `Players.PlayerRemoving` logic in a `playerTrove` cleanup | it also runs on every swap | connect `PlayerRemoving` through the trove for real leaves |
| A charm atom or a class instance in `persist` | the old generation's code stays alive | persist the plain value |
| Remotes created in `onStart` | duplicates on every swap; clients hold stale ones | `createNetwork` |
| `Players.LocalPlayer.PlayerGui.Hud` grabbed once | the reference breaks when the GUI resets | `observeElement` with a tag |
| Helper modules with side effects in `services/` | they run when `startServer` requires the folder | keep top-level code side-effect free |
| A Flamework import left (`@flamework/core` `OnStart`) | "You can only use npm scopes that are listed in your typeRoots" | import from `@typetorch/framework` |
| `Dependency()` in a constructor, a field initializer or at module top level (`const X = Dependency()`) | the start fails: "X isn't constructed yet" | call it in a method or `onInit` |
| Two modules that inject each other | the start fails: "dependency cycle: A -> B -> A" | `Lazy` on one side, or `Dependency()` in a method (section 4) |
| `invokeWithTimeout(5000)` kept from Flamework code that meant milliseconds | clamped to 120 s, with a warning (the codemod keeps arguments as they are) | seconds: `invokeWithTimeout(5)` |
| `this.trove.add(() => this.trove.remove(child))` | "Cannot call trove.remove() while cleaning"; before framework 0.5.2 the whole generation stop aborts and the old dev menu stays on screen | drop it: a child from `trove.extend()` is cleaned by its parent |
| `private state = this.ctx.persist(...)` as a field initializer | fails: `ctx` isn't attached yet | assign it in `onInit` |
| A library that connects or creates GUIs when required (Vide, TopbarPlus) | a copy leaks on every swap (MBs per swap) | step it from the trove, or load it once outside the payload (rule 9) |
| `new AnalyticsEngine()` only in a helper called on the first game event | an idle server sends nothing | create it in a low-`loadOrder` module's `onInit` |
| A looped animation started by an event | it stops on every client swap | persist it and replay it ([section 7](https://www.typetorch.dev/getting-started/migrate.md#animations-cutscenes-and-minigames-across-swaps)) |
| A per-player Map in `persist` with no leave cleanup | it grows with every player who ever joined the server | `this.ctx.playerState` (rule 2) |
| `rbxts-transform-debug` removed, `scripts/build-info.ts` unchanged | `bun run build` fails on the generated `src/shared/build.ts`, which still imports `rbxts-transform-debug` | change the import in `scripts/build-info.ts` to `@typetorch/transformer/macros` ([Debug macros](https://www.typetorch.dev/getting-started/migrate.md#debug-macros)) |
| `npx rbxtsc` in a Bun project on Windows | runs an unrelated placeholder package | `bun run build` or `bunx rbxtsc` |
| Dev branch writes prod data | real players' data changes from a test server | split store names by `TypeTorch.channel` |
| `kernel deploy --replace-place` on a real place | maps and Studio UI vanish from the live version | `kernel deploy --install` patches only the kernel (section 9) |
| Slow work in `onInit` | a new server waits only about 6 s at boot, then starts an older build and swaps yours in later | load in `onStart`; keep `onInit` short |
| Player data saved only in `onStop` or a generation's `game.BindToClose` | a shutdown in the middle of a swap can skip it (no generation runs then) | the data library in the place saves on close; `onStop` for short extras |
| `onInit` waits for a place script | the cloud test fails (place scripts don't run there), so every prod deploy is refused | skip the wait when `TypeTorchTest` is set ([Player data](https://www.typetorch.dev/guides/player-data.md#the-cloud-test)) |
| A global reset or a "server started" message in `onStart` | the cloud test runs it against your live game's stores and topics | guard it with `TypeTorchTest` |
| Receipt PurchaseIds kept only in `persist` | a receipt Roblox retries on another server is granted twice | record it in the profile before `PurchaseGranted` |
| Template-literal types in a network leaf | the guard can't be generated: compile error | use `string` and check it in the handler |
| Harmless errors right after start (a `WaitForChild` timeout) | every server rolls the new build back; `--wait` rolls the branch back | fix them, or set `"health"` ([count your errors](https://www.typetorch.dev/getting-started/migrate.md#count-your-errors-before-you-ship)) |
---
# Coming from Flamework
A Flamework 1.x game moves to TypeTorch in two parts:
1. **The mechanical part:** imports, `extends Module`, boot files and networking. `typetorch migrate --from flamework`
rewrites it for you, and the **compatibility layer** (`createFlameworkCompat`) keeps every `@flamework/networking`
call site as it is.
2. **The real work:** making every module stoppable and restartable (the
[swap-safety rules](https://www.typetorch.dev/getting-started/migrate.md#5-the-swap-safety-rules)). The codemod can't decide these, so it
lists each one, with its file and line, in a report.
This page covers both tools and the mapping. The rest of the migration (toolchain, data, UI, the kernel in your place)
is in [Migrate an existing game](https://www.typetorch.dev/getting-started/migrate.md).
## Steps
1. Switch the toolchain: [migrate step 2](https://www.typetorch.dev/getting-started/migrate.md#2-add-the-toolchain) (package.json
with the `@typetorch/*` packages and without `@flamework/*`, tsconfig.json, the payload project,
`scripts/build-info.ts`). Commit. `bun run build` now fails on every Flamework import; that's expected.
2. Preview, then run the codemod in the game folder:
```sh
bun run typetorch migrate --from flamework --dry-run # prints the diff, writes nothing
bun run typetorch migrate --from flamework # writes it, plus typetorch-migrate-report.md
```
3. `bun run build`. What still fails is in the report.
4. Work through the report's flagged items, top to bottom. Commit after each group that builds.
5. Later, at your own pace: move from the compatibility layer to `createNetwork`
(`typetorch migrate --from flamework --net native` on a clean tree does most of it).
On a real game (67 modules, about 470 network call sites), step 2 took the build from 292 TypeScript errors to none:
the build passes, and the report lists the swap-safety work.
## The codemod: `typetorch migrate --from flamework`
It runs on your machine only (no keys, nothing sent anywhere) and uses your game's own `node_modules/typescript`. It
refuses a working tree with uncommitted changes, so the whole migration is one diff you can review or undo
(`--allow-dirty` overrides that).
| Option | What it does |
|---|---|
| `--dry-run` | print the diff and the summary; write nothing (with `--report`, only the report) |
| `--net compat` | the default: networking through `createFlameworkCompat`, call sites unchanged |
| `--net native` | rewrite call sites to `createNetwork` (below) |
| `--report ` | where the Markdown report goes (default `typetorch-migrate-report.md`) |
| `--json` | the changed files, flags and counts as one JSON document |
**It rewrites:**
- `@flamework/core` imports to `@typetorch/framework` (`Service`, `Controller`, `OnInit`, `OnStart`, `OnTick`,
`OnPhysics`, `OnRender`, `Modding`, `Reflect`, `Dependency`). A name TypeTorch doesn't have (`Optional`,
`Flamework`) is dropped when the file doesn't use it, else kept and flagged.
- `@Service()` / `@Controller()` classes: `extends Module`, and `super()` as the first statement of their constructor.
When the class already extends a base class of your project, that base class gets `extends Module` instead.
- A module's own `private readonly trove = new Trove()` is removed, so `this.trove` is the module's trove (cleaned
when the generation stops). Any other member named `trove` or `ctx` is renamed (`ownTrove`) and flagged.
- `@metadata flamework:parameters` / `flamework:implements` JSDoc tags on your own decorators.
- **Ignite files** (`*.server.ts` / `*.client.ts` calling `Flamework.ignite()`) become `src/server/boot.ts` and
`src/client/boot.ts`, with the `Flamework.addPaths` folders as the module folders. Any other top-level code in them
moves into a generated module (`.service.ts` / `.controller.ts` in the first folder), inside `onStart`,
and is flagged for review: it now runs once per generation, and `script` is that ModuleScript.
- **Networking:** `Networking.createEvent()` becomes `createFlameworkCompat().GlobalEvents` and
`Networking.createFunction()` becomes `createFlameworkCompat<{}, {}, A, B>().GlobalFunctions`, so
`GlobalEvents.createServer({})` and everything after it stay. `Networking.Unreliable` becomes `T` (sent
reliably).
**It flags** (no rewrite, a line in the report each): module-level state, `Players.PlayerAdded.Connect`, `_G`, endless
loops outside `onStart`, `task.spawn` / `delay` / `defer` and `.Connect(...)` results not kept in a trove,
`@flamework/components`, `Dependency()` in a constructor, field initializer or at the top level, `loadstring`,
RemoteEvents and RemoteFunctions, MessagingService (move it to [`TypeTorch.messaging`](https://www.typetorch.dev/guides/messaging.md)), DataStore and
ProfileService code, `BindToClose`, Scripts left in
`src`, server -> client requests, `createServer` / `createClient` middleware, an event and a function with the same
path, and toolchain leftovers.
### `--net native`
Each file's `createEvent` and `createFunction` become one network:
```ts
export const network = createNetwork();
```
and every handler call site moves to it: `ServerEvents.x.connect(fn)` -> `this.trove.add(network.server.x.on(fn))` (in
a module method), `setCallback` -> `handle` (in the trove too), `broadcast` -> `fireAll`, `except(player)` ->
`fireExcept`, `fire(players[])` -> `fireList`, `predict` -> `emit`, `ClientFunctions.x(...)` -> `.invoke(...)`.
Handler files that only created handlers (Flamework's template `server/network.ts`) are deleted, and imports point at
the network. What it can't decide is flagged: a `connect` result used as a connection (`on` returns a function), a
leaf passed around as a value, `except` with a list, `predict` on a request.
## The compatibility layer: `createFlameworkCompat`
```ts
// src/shared/network.ts
import { createFlameworkCompat } from "@typetorch/framework";
export const { ServerEvents, ClientEvents, ServerFunctions, ClientFunctions } = createFlameworkCompat<
ClientToServerEvents,
ServerToClientEvents,
ClientToServerFunctions,
ServerToClientFunctions
>();
// or, for code written as GlobalEvents.createServer({}):
export const GlobalEvents = createFlameworkCompat().GlobalEvents;
export const GlobalFunctions = createFlameworkCompat<{}, {}, ClientToServerFunctions, ServerToClientFunctions>().GlobalFunctions;
```
It is built on `createNetwork`: the same generated guards (every client -> server leaf is checked on the server), rate
and shape limits (`setNetworkLimits` tunes the same dotted paths), the kernel's remotes, the dev menu's Network tab and
the swap rules. Only the names are Flamework's, so call sites compile unchanged:
| Flamework call | Does |
|---|---|
| `ServerEvents.x.fire(player \| players, ...)`, `ServerEvents.x(player, ...)` | send to one player or a list |
| `ServerEvents.x.broadcast(...)` / `except(player \| players, ...)` | everyone / everyone else |
| `ServerEvents.x.connect((player, ...) => ...)` | listen; returns a connection (`Disconnect()`, `Connected`; a trove takes it) |
| `ServerEvents.x.predict(player, ...)` | run the server's listeners as if `player` sent it (no guard) |
| `ClientEvents.x.fire(...)`, `ClientEvents.x(...)` | send to the server |
| `ClientEvents.x.connect((...) => ...)` / `predict(...)` | listen / run the client's listeners locally, no traffic |
| `ServerFunctions.x.setCallback((player, ...) => value \| Promise)` | the request's handler; a Promise is awaited |
| `ServerFunctions.x.predict(player, ...)` | run the handler here; returns a Promise |
| `ClientFunctions.x.invoke(...)`, `ClientFunctions.x(...)` | ask the server; a Promise |
| `ClientFunctions.x.invokeWithTimeout(seconds, ...)` | the same with a timeout in **seconds** (0.5 to 120) |
What differs from Flamework:
- **Connections belong to the running generation.** A swap drops every listener and handler with its generation, so
`connect` needs no trove (`Disconnect()` still ends one earlier).
- Each listener call runs on its own thread, as with Flamework; one that throws is warned (`[net] x listener threw`)
and counted in the dev menu, never a script error.
- Request timeouts: the leaf's `timeout` (`setNetworkLimits`), else `createClient({ defaultTimeout })`, else 30 s
(Flamework's client default; `createNetwork`'s own is 15 s). `invokeWithTimeout(10000)` meant as milliseconds is
clamped to 120 s with a warning (Flamework took seconds too). The codemod keeps the arguments as they are, so search
for them: `git grep -n "invokeWithTimeout(" -- src`.
- A rejected request rejects with TypeTorch's player-facing reasons ("The server didn't answer in time.", "Bad
request."), not `NetworkingFunctionError`.
- **Not supported:** server -> client requests (a leaf of `ServerToClientFunctions` has no methods: a client can't be
trusted to answer; use an event each way), middleware and `disableIncomingGuards` (warned, ignored),
`Networking.Unreliable` (sent reliably), `registerHandler`.
- Events and functions share one path space: `Spin.request` can't be both an event and a function (refused at start).
`typetorch build` warns while a game uses the layer, with its file and leaf count, so you can move to `createNetwork`
over time. New code should use `createNetwork` ([Networking](https://www.typetorch.dev/guides/networking.md)).
## Network leaves the transformer warns about
`@typetorch/transformer` names the leaf in every guard problem of `createNetwork` and `createFlameworkCompat`:
- **Generic or conditional leaves** (`(box: T, group: T extends Model ? string :
undefined) => void`): a warning. The guard checks `T` as its constraint and a conditional type as either branch, so
it can't enforce how the arguments go together. Declare a union of tuples,
`(...args: [box: Model, group: string] | [box: undefined]) => void`, or two leaves.
- **Values that never arrive:** functions, `thread`, `RBXScriptSignal`, `RBXScriptConnection` and `AnimationTrack`
(Roblox sends nil, so a client -> server guard refuses every message). A warning; send the data, or the Animation /
AnimationId and load the track on the other side.
- **No guard possible** (a class, a template literal type): an error naming the leaf.
Supported parameter types: string, number, boolean, undefined and optional, literals and TS enums, Enum items, Roblox
datatypes (Vector3, CFrame, Color3, UDim2, ...), Instances by class, arrays, tuples, Maps, Sets, plain objects and
interfaces, unions, `buffer`, and `unknown` / `any`.
## Mapping
| Flamework | TypeTorch |
|---|---|
| `rbxts-transformer-flamework`, the `node_modules/@flamework` type root | `@typetorch/transformer`, `node_modules/@typetorch` ([step 2](https://www.typetorch.dev/getting-started/migrate.md#2-add-the-toolchain)) |
| `Flamework.addPaths(...)` + `Flamework.ignite()` in `*.server.ts` / `*.client.ts` | `src/server/boot.ts` / `src/client/boot.ts` calling `startServer` / `startClient` |
| `@Service()`, `@Controller()`, constructor injection | the same names from `@typetorch/framework`, the class `extends Module`, `super()` |
| `OnInit`, `OnStart`, `OnTick`, `OnPhysics`, `OnRender` | the same; plus `OnStop` and `OnPlayerAdded` |
| `Dependency()` | the same, from `onInit` on (not in a constructor, field initializer or at the top level); `Lazy` breaks cycles |
| `@Optional()`, `Flamework.id()`, `Flamework.createGuard()`, `Flamework.implements()` | none: every module starts; write a user macro with `Modding.Generic` |
| `Modding`, `Reflect`, `@metadata flamework:parameters` | `Modding`, `Reflect` from `@typetorch/framework`, `@metadata typetorch:parameters` |
| `@flamework/components` (`@Component`, `BaseComponent`) | a module with `observeElement` or `@rbxts/observers` ([rule 4](https://www.typetorch.dev/getting-started/migrate.md#rule-4-tags-and-characters-through-observers)) |
| `Networking.createEvent` / `createFunction` | `createFlameworkCompat` (same call sites), or `createNetwork` |
| `connect` / `setCallback` / `broadcast` / `except` / `predict` | native: `on` / `handle` / `fireAll` / `fireExcept` / `emit` (in `this.trove`) |
| `invoke` / `invokeWithTimeout(seconds, ...)` | the same names, seconds |
| `Networking.Unreliable` | native: `fireUnreliable` / `fireAllUnreliable` |
| server -> client functions | an event each way |
| a module's own `new Trove()` | `this.trove` (cleaned when the generation stops) |
---
# Go-live checklist
For moving a game with live players to TypeTorch. Tick every box, in order. [Migrate](https://www.typetorch.dev/getting-started/migrate.md)
is the code part; this page is everything around it. Plan about a week, mostly testing.
Nothing here touches your live game until step 8, the cut-over.
## 1. Prepare
- [ ] **Keys:** an offline backup of `~/.config/typetorch/keys/*` and your env file, `asset:write` on its own
IP-limited key, and a rotation drill in your calendar ([how](https://www.typetorch.dev/guides/prod-signing.md#back-up-and-drill)).
- [ ] **The fleet API stays up:** a small VPS with a fixed domain ([set it up](https://www.typetorch.dev/guides/fleet-and-alerts.md#set-it-up)), with a
Discord or Slack [webhook](https://www.typetorch.dev/guides/fleet-and-alerts.md#webhooks). On your PC behind a quick tunnel it stops when your PC
does: no automatic rollback, no alerts. If you accept that for the first weeks, watch
`bun run typetorch servers --watch` yourself after every deploy.
- [ ] **Cross-server messages:** your topics moved to [`TypeTorch.messaging`](https://www.typetorch.dev/guides/messaging.md) (or counted next to
TypeTorch's: [Cross-server messages](https://www.typetorch.dev/getting-started/migrate.md#cross-server-messages)).
- [ ] **Who gets the dev menu:** `members` (and `revoked`, `devBadgeId`) in `typetorch.json`, then
`bun run typetorch access push`, for the copy and later for the live game. Servers need kernel 0.3.8+ to see them
([who gets it](https://www.typetorch.dev/getting-started/fresh-setup.md#11-the-dev-menu-and-who-gets-it)).
## 2. Copy the game
- [ ] Creator Hub: a new experience, `" (TypeTorch test)"`. In Studio: File > Download a Copy of the live place,
then publish it into the new experience.
- [ ] A second config for the copy, for example `typetorch.copy.json` with its ids. Pass `--config typetorch.copy.json`
to every command for the copy. Add the copy to your Open Cloud keys, and run `keys init` and
`keys init --fallback` for it (signing keys are per experience).
- [ ] Don't touch the live experience yet.
## 3. Convert the code
- [ ] On a branch `typetorch-migration`, follow [Migrate](https://www.typetorch.dev/getting-started/migrate.md) (or let an agent follow the
[playbook](https://www.typetorch.dev/agents/AGENTS.md)).
- [ ] Store names, keys and data shapes unchanged.
- [ ] [Player data](https://www.typetorch.dev/guides/player-data.md): the library and `DataHost` in the place; receipts recorded in the profile before
`PurchaseGranted`; no save only in `onStop`.
- [ ] Side effects guarded from the cloud test ([what to guard](https://www.typetorch.dev/getting-started/migrate.md#the-cloud-test-runs-your-game-code)).
- [ ] `bun run build` and `bun run typetorch build` pass; after a commit the id has no `-dirty`.
## 4. Test in Studio
- [ ] On the copy place: `bun run typetorch serve` with the Studio plugin, Play ([Testing in Studio](https://www.typetorch.dev/guides/studio-testing.md)).
- [ ] Dev menu > Reload, twice: `persist` state and player data survive.
## 5. Install the kernel in the copy
- [ ] `bun run typetorch kernel deploy --dry-run --install --config typetorch.copy.json`. Read the report: only the kernel
folders and the kernel's settings change. With the copy place's "Allow place to be updated using Save Place API" setting
on (Creator Hub > Permissions; off by default for places made in Studio) it patches through Luau Execution, with no
download. Otherwise: File > Download a Copy, note its version, and add `--place-file --base `.
If it refuses because the newest version is an unpublished Studio save, add `--base published` (or `--base latest`
to ship that save): [Kernel updates](https://www.typetorch.dev/guides/deploy-and-rollback.md#kernel-updates).
- [ ] The same command without `--dry-run` (y/N). Join: F9 shows `[TypeTorch] kernel `.
- [ ] `ServerScriptService.LoadStringEnabled` stays **off** in the live game: a patch keeps the place's own value and
sets it only with `--loadstring` (`bun run typetorch doctor` says what `kernel deploy` will do; check the place's
value in Studio). Only a test place where you want remote-claude's `run_luau` turns it on. CLIs up to 0.7.2 turn
it on during the install: check it in Studio, turn it off, publish.
- [ ] Remove the old game scripts in Studio, publish.
## 6. Soak on the copy (3 to 5 days)
- [ ] Deploy `dev` (`--branch dev`), open it with `/tt new dev`, and invite 5 to 10 real testers. Deploy every day while
they play. Deploy `prod` on the copy too (`--branch prod`).
- [ ] Keep `bun run typetorch servers --watch` and `alerts --follow` open.
- [ ] After each deploy, count your game's errors in the first 30 s (dev menu > Server > Status: "Health window:
n/3 errors"; Logs shows them). A server rolls back a new build at 3 errors from it within 30 s, so fix noisy
errors before the cut-over, or set `typetorch.json` `"health"` above your count (kernel 0.3.7+,
[Set the health window](https://www.typetorch.dev/guides/deploy-and-rollback.md#set-the-health-window)). `doctor` shows the values.
- [ ] Optional: `"autoRollback": { "failedPct": ... }` if 20% failed servers is too eager or too slow for your fleet.
Then run every live test on the copy:
- [ ] **Rollback:** `bun run typetorch rollback --branch prod` with 2+ players in. Players stay, data is intact, the dev
menu shows the older build.
- [ ] **Broken build:** a prod build whose `onStart` throws outside the cloud test
(`if (Workspace.GetAttribute("TypeTorchTest") !== true) error("drill")`). Every server rolls back within 30 s,
`deploy --wait` rolls the branch back, the webhook alert arrives, `typetorch report latest` exits 1.
- [ ] **Noisy build:** 3 harmless errors in `onStart` (guarded the same way). See what happens (today: the server
rolls back), so you know what your game's own errors would do.
- [ ] **Load failure** (optional, if you can make one): a build whose payload doesn't load. Servers retry it, a
`deploy_failed` alert arrives, and they keep the old build.
- [ ] **New server, fleet API down:** stop the fleet API, open a new server. Playable within 15 s; `/tt status` shows
the right build.
- [ ] **Player data:** join, earn, deploy twice while playing, leave, rejoin another server, shut that server down
from Manage > Servers, rejoin. Nothing lost. Then roll back to older code against data the newer code touched.
- [ ] **Dev data:** after a dev session and after a prod deploy's cloud test, Creator Hub's DataStore Manager shows
writes only in the `_dev` stores.
- [ ] **Dev access:** a member gets the dev menu; add one to `revoked`, `access push`, and within about a minute they
lose it.
- [ ] **Purchases:** open a developer product prompt, deploy, buy while the swap runs. One grant, saved; rejoin: no
second grant. Check a game pass after a swap.
- [ ] **Kernel undo:** `bun run typetorch kernel restore --version ` once, then install again.
- [ ] **Team Create:** with the copy open in Studio by someone else, `kernel deploy` fails at the save (the error
names the Team Create session; a `--place-file` publish gets a 409) and publishes nothing.
- [ ] **Slow phone, bad connection:** a client swap finishes, no stuck loading, `/tt status` in chat answers.
- [ ] **Fleet API restart** (and your PC, if it runs there): servers post again within 5 minutes
(`bun run typetorch servers`). A quick tunnel gets a new URL: run `backend setup` again.
- [ ] **Key rotation:** [the drill](https://www.typetorch.dev/guides/prod-signing.md#back-up-and-drill), on the copy.
- [ ] **2 hours of real players** on the dev branch: read the server logs (dev menu > Logs, or Logs > Upload) for
`[net]` rejections and kernel warnings.
## 7. Check the data
- [ ] Export a few real profiles from the copy (Creator Hub > DataStore Manager) before and after a swap, and after a
rollback. Field for field equal.
- [ ] Dev servers wrote only the `_dev` stores.
## 8. Cut-over (a quiet hour)
- [ ] 1. Announce a short maintenance window in the game.
- [ ] 2. In the live place: add the data library and `DataHost`, install the kernel by patch (step 5, with the live
config), check `LoadStringEnabled` is off, keep the old scripts, publish. Nothing changes for players: the
kernel waits, the old code runs. `bun run typetorch access push` with the live config.
- [ ] 3. In Studio, remove the old scripts. **Don't publish yet.**
- [ ] 4. `bun run typetorch deploy` from `main`: cloud test, y/N, signed. Servers on the old place version have no
kernel and ignore it.
- [ ] 5. Publish the place without the old scripts. New servers boot the kernel and the prod build. Move players off
the old servers from Creator Hub (migrate to the latest update).
- [ ] 6. Watch for 30 minutes: `servers --watch`, `report latest`, the webhook channel, the game. Keep the old place
file and its version number.
## If something goes wrong
| Problem | Do |
|---|---|
| A bad build | `bun run typetorch rollback --branch prod` (1 to 2 s). With the fleet API up, `deploy --wait` already does it |
| The kernel or the framework | `bun run typetorch kernel restore ` (or Creator Hub > Version History > Restore), then move players to the new version. The old code reads the same stores, because names and shapes didn't change. Budget 10 minutes |
| Player data | The library is the one you had before. Compare with the profiles you exported in step 7. Dev servers only write `_dev` stores |
---
# Runtime API: `TypeTorch`
`import { TypeTorch } from "@typetorch/framework"` works on the server and the client. It describes the running
**generation** (one build running in one server or client) and raises events that belong to it. Every listener is
dropped when the generation stops, so a swap never leaves one behind. Each `on*` returns a disconnect function: give it
to a trove.
Inside a module, `this.ctx` has the basics too: `realm`, `artifact`, `branch`, `channel`, `generation`, `build` (the
compiled-in git info), `kernel` (the raw generation API), `persist` and `playerState`. `this.ctx` is attached right
after the constructor: use it from `onInit` on, never in a field initializer (`private state = this.ctx.persist(...)`
fails).
## Modules: `TypeTorch.module` and `Dependency`
```ts
import { Dependency, TypeTorch } from "@typetorch/framework";
Dependency().open(player); // the running ShopService
TypeTorch.module().open(player); // the same
TypeTorch.tryModule()?.open(player); // undefined instead of an error
```
The running module of type T (a `@Service` on the server, a `@Controller` on the client), for code that isn't a
constructor: methods, plain classes a module built, command handlers. `@typetorch/transformer` fills in T's id; an
`import type` of the class is enough.
- From `onInit` on (and in `onStart`, `onStop` and later code). In a constructor, a field initializer or at the top level
of a module it throws "ShopService isn't constructed yet: ...". `tryModule` returns `undefined` then.
- The other realm's modules throw ("ShopService is a @Service: it runs on the server, not on the client").
- Per generation: after a swap they return the new generation's module, and code left over from the old generation
gets an error ("the generation that ran ShopService has stopped").
- To break a dependency cycle, take one side as `Lazy` (a constructor parameter with `@typetorch/transformer`
0.2.1+, or a field `= Lazy()`); `.get()` resolves on first use, and the start order ignores it. See
[Migrate](https://www.typetorch.dev/getting-started/migrate.md#dependency-cycles-lazyt).
## Identity
```ts
TypeTorch.realm; // "server" | "client"
TypeTorch.running; // false in edit mode (UI Labs stories): identity has defaults there
TypeTorch.artifact; // { id, commit, commitHash, branch, channel, builtAt, seq, assetId }
TypeTorch.generation; // 1, 2, 3... per server (or client)
TypeTorch.branch;
TypeTorch.channel; // the rules: "prod" on every public server, and where the branch or the build is prod
TypeTorch.rules; // kernel 0.3.9: the same value by name
TypeTorch.branchChannel; // kernel 0.3.9: what the branch itself is ("prod" or "dev"), for display
TypeTorch.serverType; // "public" | "private" | "reserved" | "studio"
TypeTorch.isPinned();
TypeTorch.kernelVersion;
TypeTorch.kernelApi;
TypeTorch.jobId;
TypeTorch.isStudio;
TypeTorch.features; // what the running kernel supports
```
`channel` and `rules` are what the server enforces: a dev branch on a public server is `"dev"` in `branchChannel` and
`"prod"` in `channel`. Split data store names by `channel`. On kernels before 0.3.9 `branchChannel` equals `channel`.
See [Branches and channels](https://www.typetorch.dev/guides/branches-and-channels.md).
`TypeTorch.features` has one boolean per kernel feature: `kernelStart`, `updatePending`, `devChanged`, `artifacts`,
`requestReload`, `messaging`, `settings`, `runDetached`, `liveDebug` and `reserveServer`. All are `false` outside a running kernel.
## How this generation started
```ts
const start = TypeTorch.startInfo;
// { kind: "boot" | "swap", reason, previous?, branchChanged, startedAt, requestedBy?, loadSeconds?, stopSeconds?, swapSeconds? }
if (start.reason === "auto_rollback") warn("the last deploy failed to start");
```
| Reason | The generation started because |
|---|---|
| `boot` | the server (or client) started; a client's first generation is always `boot` |
| `deploy` | a deploy, rollout or promote of this server's branch reached it (also when it caught up by polling) |
| `reload` | someone reloaded this server to its branch head, or ended its pin |
| `pin` | a pin: an A/B experiment, Load here, `/tt pin` |
| `rollback` | a branch rollback (`typetorch rollback`) |
| `server_rollback` | a rollback of this server only (`/tt rollback`, the dev menu) |
| `auto_rollback` | the last build failed on this server (load, `onStart` or the health window) and it went back |
| `branch` | the server switched branch; `branchChanged` is true |
| `unknown` | a kernel before 0.2.2, or a reason it doesn't name |
`branchChanged` is set whenever the branch moved, whatever the reason. `requestedBy`, `loadSeconds`, `stopSeconds` and
`swapSeconds` are server-only.
## Swap events
```ts
// Just before this generation stops, before any onStop. Synchronous: keep it short, don't yield.
this.trove.add(TypeTorch.onSwapOut((info) => this.saveRound(info.reason)));
// A deploy (or reload, branch switch, pin) is about to swap this server in about update.eta seconds.
this.trove.add(TypeTorch.onUpdatePending((update) => (hint.Visible = !update.cancelled)));
// Once, in a generation that started because the server's branch changed.
this.trove.add(TypeTorch.onBranchChanged(({ from, to }) => this.resetBranchData(from, to)));
```
- `onSwapOut` gets `{ reason, branch, next }` (the build that replaces this one). It doesn't run on server shutdown.
It runs while every module still runs, before any `onStop` or trove cleanup: the place for last-resort work (save
into `persist`, flush, tag Instances) that must happen even if a later cleanup throws.
- `onUpdatePending` fires again with `cancelled: true` when the new build failed to load. On public servers it can fire
twice for one deploy.
### What to tell players
A swap is a hot swap: players stay in the same server, with their character and position. It is not a teleport and
not a server migration.
- `onUpdatePending` fires before **every** swap, plain hot swaps included. A "migrating server, please wait" message
there is wrong. Show "updating in N s" (`update.eta`) or nothing, and hide it again on `cancelled`.
- Announce the result from the new generation: read `TypeTorch.startInfo` in `onStart`.
```ts
onStart() {
const start = TypeTorch.startInfo;
if (start.kind !== "swap") return;
if (start.reason === "deploy") this.toast("Updated to the latest version");
else if (start.reason === "auto_rollback") this.toast("An update didn't work; back on the previous version");
}
```
## State that survives swaps
```ts
const scores = TypeTorch.persist("scores.v1", () => new Map());
```
The first call in a server (or client) runs `init`; every later call and every later generation gets the same table.
It lives in memory until the server shuts down. Plain data only: tables, arrays, Maps and Sets of strings, numbers,
booleans, and Players. Never functions, class instances, Promises, threads, connections, charm atoms or Instances the
generation created. Version the key when the shape changes; keys starting with `__` are reserved. (`this.ctx.persist`
is the same.)
### Per player
```ts
const cooldowns = TypeTorch.playerState("cooldowns.v1", (player) => ({ lastUse: 0 })); // or this.ctx.playerState
cooldowns.get(player).lastUse = os.clock(); // the first get stores init(player)
cooldowns.set(player, { lastUse: 0 });
cooldowns.has(player);
cooldowns.delete(player);
```
Keyed by UserId and kept in `persist`, so it survives swaps. A player's entry is removed when they really leave (after
the game's own `PlayerRemoving` handlers ran), never on a swap; players who left between two generations are dropped
when the next one opens its first store. Same plain-data rules as `persist`. The dev menu shows every store under
Modules > State > persist, `__playerState`.
## Devs and roles
```ts
if (TypeTorch.isOwner(player)) this.showOwnerPanel(player);
TypeTorch.isDev(player);
TypeTorch.role(player); // "owner" | "dev" | undefined
TypeTorch.devInfo(player);
this.trove.add(TypeTorch.onPlayerDevChanged((player, info) => this.setDevTools(player, info.dev)));
```
Two roles (framework 0.3.2, kernel 0.3.4): **owner** (the experience creator, the owning group's owner, `members` with
role `"owner"`) and **dev**. There are no admins: a `members` entry with the old role `"admin"`, or an older kernel's
`"admin"`, counts as a dev. `TypeTorch.isAdmin` still exists as a deprecated alias of `isOwner`.
On the server the kernel decides (it may yield once per player for badge and group checks). On the client only the
local player is known, and only cosmetically: the server re-checks everything.
## Server-only reads
```ts
TypeTorch.status(); // uptime, players, memory, generation history, last deploy message, signing state: cheap
TypeTorch.branches(); // known branches and heads: cached, yields at most every 30 s
TypeTorch.artifacts(); // known deployments, newest first: cached, yields at most every 30 s
TypeTorch.requestReload(player); // owners only: reload this server to its branch head
```
Don't call `branches()` or `artifacts()` per player or per frame. A build's `channel` in these lists is the build's
own (a promoted build keeps it). On kernel 0.5.4+ each branch also carries `branchChannel`, the branch's own channel.
## Cross-server (server only)
```ts
this.trove.add(TypeTorch.messaging.subscribe("announce", (data, meta) => this.show(data, meta.branch)));
TypeTorch.messaging.publish("announce", { text: "Double coins!" }); // queued and retried, at most 1 KiB
TypeTorch.messaging.status(); // the kernel's counters: rate on the topic, queued, dropped
const servers = TypeTorch.servers(); // the game's live servers (cached; yields up to ~3 s when it asks)
TypeTorch.setServerInfo({ mode: "ranked" }); // public fields of this server, in every server's list
```
Kernel 0.3.8+. See [Cross-server messages and the server list](https://www.typetorch.dev/guides/messaging.md).
## Reserved servers for your own teleports (server only)
```ts
// Send a player to a fresh reserved server that runs THIS server's branch, with your own teleport data.
const reserved = TypeTorch.reserveServer();
if (reserved.ok) {
const options = new Instance("TeleportOptions");
options.ReservedServerAccessCode = reserved.accessCode!;
options.SetTeleportData({ ticket: makeTicket(reserved.privateServerId!) });
TeleportService.TeleportAsync(game.PlaceId, [player], options);
} else warn(`reserveServer: ${reserved.error}`);
```
- A plain `TeleportService:ReserveServer` server has no branch record, so it boots the universe's default (prod)
branch: players sent from a dev branch land on another build. `reserveServer` records the new server on this
server's branch, so it boots that branch's head. Kernel 0.5.9+ (`TypeTorch.features.reserveServer`); older kernels
return `{ ok: false, error: "kernel too old" }`.
- It doesn't teleport: you do, with your own `TeleportOptions`. `accessCode` is server-only data; never send it to a
client. Clients calling it throw.
- Always this server's branch: game code can't open another branch (prod code must not start dev builds).
- No dev check, at most 20 calls a minute per server (`"rate limited"`); it yields (ReserveServer and a DataStore
write). Other errors: `"studio"`, `"no kernel"` (edit mode), `"no artifact on branch "`, `"ReserveServer: ..."`,
`"could not save the branch: ..."`, `"kernel error: ..."`.
## Detached jobs (server only)
```ts
// A library call a deploy must not cut off halfway (a ProfileStore load, save or release).
const sessions = this.ctx.persist("data.sessions.v1", () => ({ profiles: new Map() }));
TypeTorch.runDetached(() => {
const profile = store.StartSessionAsync(`Player_${userId}`);
if (profile) sessions.profiles.set(userId, profile); // in persist: the next build finds it after a swap
return profile;
}).catch((err) => warn(`load failed: ${err}`));
```
- `fn` runs on a thread the kernel owns: this build's stop, and its hard stop, can't kill it. Kernel 0.3.8+
(`TypeTorch.features.runDetached`); older kernels throw "needs kernel 0.3.8; use the DataHost job queue".
- The Promise settles while this build runs. After a swap the result is dropped, so a job whose result must survive
writes it into `persist` itself.
- A job keeps this build's code and whatever its closures reference in memory until it ends. Keep jobs short; don't
use `this` or a trove inside them.
- Errors reject the Promise and appear in the dev menu's Logs with the build that started the job; they never count
toward the build's health window. At most 256 jobs run at once per server (then it throws); a job past 60 s is
logged and flagged in Server > Status ("Detached jobs").
See [Player data: two ways to run the jobs](https://www.typetorch.dev/guides/player-data.md#two-ways-to-run-the-jobs).
## Live settings (server only)
```ts
const price = TypeTorch.liveConfig("shop.price", { default: 50 }); // `typetorch settings set game.shop.price 75`
price.get();
this.trove.add(price.onChanged((value) => this.reprice(value)));
TypeTorch.settings(); // the whole verified settings record: holds tokens, never send it to a client
```
Kernel 0.3.8+. See [Settings](https://www.typetorch.dev/guides/settings.md).
### Live events
```ts
const events = TypeTorch.liveEvents();
events.active(); // LiveEvent[] running now: { id, name, startsAt, endsAt, set }
events.upcoming(); // not started yet, in start order
this.trove.add(events.onChanged((active) => this.showBanner(active)));
```
Framework 0.7.1, server only. A live event is a scheduled change of `game` values: the signed record's
`game["tt.events"]` (`{ v: 1, events: [{ id, name, start, end, set }] }`, unix seconds, UTC), made on the explorer's
Live events page and signed with `typetorch settings set game.tt.events -`. While an event runs (`start <= now < end`
on this server's clock) its `set` values replace the record's values for `liveConfig`, so `get()` and `onChanged` switch
at the start and end times by themselves. No message is needed, and an event still ends when the backend is down. Two
events that set the same key at once: the later start wins. At most 64 events are read. `liveEvents()` is for game UI
("Double cash ends in 3h"); `liveConfig` already follows the schedule. See [Live events](https://www.typetorch.dev/guides/live-events.md) and
[Reserved game keys](https://www.typetorch.dev/guides/settings.md#reserved-game-keys).
## Live debug (server only)
```ts
import { fleet, remoteDebug, TypeTorch } from "@typetorch/framework";
// A button on the explorer's server page (op game.round_state). It must be read-only.
this.trove.add(remoteDebug.command("round_state", () => ({ kind: "kv", items: { round: this.round } }), { label: "Round" }));
// A stream sampled while someone watches the server page; "points" draw on the live map.
this.trove.add(
remoteDebug.stream("loot", () => ({ points: this.chests.map((c) => ({ x: c.X, y: c.Y, z: c.Z })) }), { hz: 1, kind: "points" }),
);
// A custom column on the Fleet page, read on every heartbeat.
this.trove.add(fleet.column("current_map", () => this.mapName, { label: "Map", type: "string" }));
fleet.columnsChanged(); // a heartbeat soon (the kernel sends at most one per 10 s)
```
Framework 0.7.1 with kernel 0.5.7 (`TypeTorch.features.liveDebug`; `TypeTorch.remoteDebug` and `TypeTorch.fleet` are
the same objects).
- **Commands** run when an owner presses the button on `/servers/`, through remote debug's checks: owners only,
30 a minute, a 10 s deadline, args at most 2 KB of JSON, the answer at most 200 KB and scrubbed of secrets. The
kernel can't check what a handler does: read-only is your promise, and the explorer labels them game-defined. An
answer `{ kind: "table", columns, rows }` draws as a table, `{ kind: "kv", items }` as key-value pairs, anything
else as JSON.
- **Streams** are sampled at `hz` (0.2 to 4) only while someone watches the server page; a sample is at most 16 KB of
JSON. `kind: "points"` values (`{ points: [{ x, y, z, label?, color? }] }`) draw as markers on the live map.
- **Columns** ride every heartbeat: a string of at most 64 characters, a number, a boolean or nothing. They are stored
with the server row: never put player names, UserIds or other personal data in a column.
- Getters and samplers run on kernel threads under pcall with a short deadline: keep them cheap and don't yield.
- Names match `^[a-z][a-z0-9_]{0,31}$`. At most 16 columns, 32 commands and 8 streams; labels at most 40 characters,
descriptions 200. A bad name or option, a duplicate or one past a limit throws at once. Each call returns a remover
for the trove. A client throws.
- On older kernels, and in edit mode, every call is accepted and checked, and nothing reaches the backend.
See [Live debug](https://www.typetorch.dev/guides/live-debug.md) and
[Errors, debug bundles and remote debug](https://www.typetorch.dev/guides/fleet-and-alerts.md#errors-debug-bundles-and-remote-debug).
## Notifications and feedback
- `TypeTorch.notifications()`: native Roblox experience notifications through the backend (server: `want`, `drop`,
`setOff`, `onOpen`; client: `promptOptIn`). See [Notifications](https://www.typetorch.dev/guides/notifications.md).
- `TypeTorch.feedback()` (server only, framework 0.7.0): `submit(player, { rating?, text?, topic?, ctx? })` checks and
writes one `feedback` analytics row. See [Player feedback](https://www.typetorch.dev/guides/feedback.md).
## Loading screens
Your own loading screen (a place script in `ReplicatedFirst`) waits for `ClientReady` on
`ReplicatedFirst.TypeTorchKernelClient` (kernel 0.3.8). See [Loading screens](https://www.typetorch.dev/guides/loading-screen.md).
## Logs
```ts
TypeTorch.logs(0, 50); // the kernel's ring buffer (server 500 lines, client 300)
this.trove.add(TypeTorch.onLog((entry) => this.errors.push(entry))); // don't print from inside it
```
## Hot assets
```ts
const shop = TypeTorch.asset("ui/shop"); // the same as hotAsset("ui/shop")
```
See [Hot assets](https://www.typetorch.dev/guides/hot-assets.md).
## Example: an update toast
```ts
@Controller()
export class UpdateToastController extends Module implements OnStart {
onStart() {
this.trove.add(
TypeTorch.onUpdatePending((update) => {
if (update.cancelled) this.hideToast();
else this.showToast(`Updating ~${math.ceil(update.eta)}s`);
}),
);
const start = TypeTorch.startInfo;
if (start.kind === "swap") this.showToast(`Updated #${TypeTorch.artifact.seq ?? "?"}`);
}
private showToast(text: string) {
/* ... */
}
private hideToast() {
/* ... */
}
}
```
The template's `UpdateToastController` and `DevOverlayController` are complete examples.
---
# State with charm
[charm](https://github.com/littensy/charm) atoms are the state behind TypeTorch's UI workflow, and charm-sync sends the
server's atoms to clients. Both work as usual on TypeTorch. This page is the few lines that are TypeTorch's.
**Atoms are per generation.** A swap requires your modules again, so every atom is created again with its default
value, on the server and on every client. Three things keep state across swaps:
1. **The server's atoms start from `persist`** and write every change back.
2. **charm-sync goes over `createNetwork`**: one leaf with an `unknown` payload. No RemoteEvents.
3. **Each client asks for a full state in its controller's `onStart`**, so it hydrates after every join and after its
own swap. Until the answer arrives, its atoms keep the values it had before the swap (from its own `persist`).
Written for charm 0.10 and charm-sync 0.3, the pair most roblox-ts games use. charm-sync 0.4 (which needs charm 0.11)
replaced the `CharmSync.server(...)` / `CharmSync.client(...)` objects with module functions (`server.connect`,
`client.patch`, ...), so adapt the charm-sync calls below if you use it. With other versions, or another sync library,
the TypeTorch lines are the same.
Without charm-sync, the same rule holds: the [template](https://github.com/typetorch/template)'s
`RushStateController` keeps client atoms on the controller instance (fresh each generation), fills them from network
events, and asks the server for a snapshot after every join and after its own swap.
## The atoms
```ts
// src/shared/state/synced.ts
import { atom, subscribe, type Atom } from "@rbxts/charm";
import type { Trove } from "@rbxts/trove";
import { TypeTorch } from "@typetorch/framework";
export interface RoundState {
phase: "lobby" | "round";
endsAt: number;
}
export const roundAtom = atom({ phase: "lobby", endsAt: 0 });
/** UserId (as a string: string keys survive remotes) -> score. */
export const scoresAtom = atom>({});
/** Every atom the server syncs to clients: one list, used by both realms. */
export const SYNCED = { round: roundAtom, scores: scoresAtom };
/**
* Atoms are created again in every generation (this module is new after a swap). Starts them from the last
* generation's values and writes every change back, through `persist` (plain values, never the atoms).
*/
export function persistAtoms(trove: Trove, key: string) {
const saved = TypeTorch.persist(key, () => ({}) as Record);
const atoms = SYNCED as unknown as Record>;
for (const [name, value] of pairs(saved)) atoms[name]?.(value);
for (const [name, synced] of pairs(atoms)) trove.add(subscribe(synced, (value) => (saved[name] = value)));
}
```
The subscriptions go in the module's trove, so the old generation stops writing when it stops.
## The network
```ts
// src/shared/net.ts
import { createNetwork, setNetworkLimits } from "@typetorch/framework";
interface ClientToServer {
state: {
/** "Send me everything": after every join and every swap. */
hydrate(): void;
};
}
interface ServerToClient {
state: {
/** charm-sync payloads (init or patch), passed through as they are. */
sync(payloads: unknown): void;
/** This player's own state (a syncer per player, below). */
mine(payloads: unknown): void;
};
}
export const network = createNetwork();
// A client asks once per generation: a small bucket is plenty.
setNetworkLimits({ "state.hydrate": { rate: [3, 0.2] } });
```
`unknown` is right here: the server sends these, and clients trust the server. The only client -> server message is the
argument-free `hydrate`, which the server checks and rate-limits like any leaf.
## Server
```ts
// src/server/services/state.service.ts
import CharmSync from "@rbxts/charm-sync";
import { Module, Service, type OnInit } from "@typetorch/framework";
import { network } from "../../shared/net";
import { persistAtoms, SYNCED } from "../../shared/state/synced";
@Service({ loadOrder: -20 }) // before the modules that read or write the atoms
export class StateService extends Module implements OnInit {
onInit() {
// 1. The new generation's atoms start with the old generation's values.
persistAtoms(this.trove, "state.synced.v1");
// 2. charm-sync over the game's network: patches to every player, a full state to a player who asks.
const syncer = CharmSync.server({ atoms: SYNCED, interval: 0.2 });
this.trove.add(syncer.connect((player, ...payloads) => network.server.state.sync.fire(player, payloads)));
this.trove.add(network.server.state.hydrate.on((player) => syncer.hydrate(player)));
}
}
```
- `persistAtoms` runs before `CharmSync.server`, so the syncer starts from the restored values.
- `syncer.connect` returns its cleanup (the patch timer and subscriptions): in the trove, it ends with the generation.
- The server doesn't push a full state by itself: a swap restarts every client too, and each one asks.
## Client
```ts
// src/client/controllers/state.controller.ts
import CharmSync from "@rbxts/charm-sync";
import { Controller, Module, type OnInit, type OnStart } from "@typetorch/framework";
import { network } from "../../shared/net";
import { persistAtoms, SYNCED } from "../../shared/state/synced";
@Controller({ loadOrder: -20 }) // before the UI controllers that draw from the atoms
export class StateController extends Module implements OnInit, OnStart {
onInit() {
// The values this client had before its own swap: the UI keeps them (no flash of defaults) until the hydrate.
persistAtoms(this.trove, "state.synced.v1");
const syncer = CharmSync.client({ atoms: SYNCED });
this.trove.add(
network.client.state.sync.on((payloads) => syncer.sync(...(payloads as CharmSync.SyncPayload[]))),
);
}
onStart() {
// A full state after every join and every swap (charm-sync ignores patches until it has one).
network.client.state.hydrate.fire();
}
}
```
- The listener is registered in `onInit`, the request goes out in `onStart`: the answer can't arrive before anyone
listens.
- A client's `persist` is its own memory (the server never sees it). It lasts until the player leaves.
## Per player
charm-sync sends every player the same patches. **Don't filter a patch per player** (dropping keys from it): the client
applies it to what it has, and a filtered patch no longer matches. Give each player a syncer of their own over a
selector of their part instead:
```ts
// src/server/services/quest.service.ts
import { atom } from "@rbxts/charm";
import CharmSync from "@rbxts/charm-sync";
import type { Trove } from "@rbxts/trove";
import { Module, Service, type OnPlayerAdded } from "@typetorch/framework";
import { network } from "../../shared/net";
/** Server-only: every player's quests, by UserId as a string. */
const questsAtom = atom>({});
@Service()
export class QuestService extends Module implements OnPlayerAdded {
onPlayerAdded(player: Player, playerTrove: Trove) {
// One syncer per player, over a selector of that player's part: nobody else's data reaches them.
const key = tostring(player.UserId);
const syncer = CharmSync.server({ atoms: { quests: () => questsAtom()[key] }, interval: 0.2 });
playerTrove.add(
syncer.connect((target, ...payloads) => {
if (target === player) network.server.state.mine.fire(player, payloads);
}),
);
playerTrove.add(network.server.state.hydrate.on((from) => from === player && syncer.hydrate(player)));
}
}
```
On the client, a second `CharmSync.client({ atoms: { quests: myQuestsAtom } })` listens to `state.mine` the same way.
`onPlayerAdded` replays every player after a swap, and the player trove ends each syncer when the player leaves. Keep
the server-only atom's values across swaps the same way (`persistAtoms`-style, or `this.ctx.playerState`).
## Patterns that survive swaps
- **Derive from state, not from events.** Atoms that are synced and persisted (`persistAtoms`) keep their last values
across a client swap, and the server sends them again on the hydrate. A client that derives what should exist from
them (a held tool's idle animation, a flight effect, a mod flag) redraws it after every swap by itself. A
"play" / "stop" event pair breaks: the new generation never saw the "play".
- **Deleted keys travel as `None`.** Setting a key to `undefined` on the server reaches the client as charm-sync's
`None` marker. Code that reads raw payloads checks `isNone(value)` (from `@rbxts/charm-sync`), never `value ===
undefined`.
- **Prune per-player keys on a real leave.** A dictionary keyed by UserId keeps every player who ever joined. One server
module removes the key: `this.trove.connect(Players.PlayerRemoving, (player) => ...)`. Not a `playerTrove` cleanup,
which also runs on every swap.
- **Clients can't write synced atoms.** charm-sync goes server to client only. A client toggle other players must see
(an emote, a setting shown on the character) is a network leaf the server checks, then writes into the atom.
## Rules
- **`persist` holds values, never atoms:** an atom keeps the old generation's code alive.
- **Plain data in atoms you persist or sync:** tables, arrays, strings, numbers, booleans. Version the persist key
(`state.synced.v2`) when a shape changes in a way old values would break.
- **String keys for dictionaries you sync** (`tostring(userId)`): a table keyed by numbers that aren't 1, 2, 3... doesn't
cross a remote intact.
- **One `SYNCED` list for both realms**, and only atoms in it: `computed` values are derived again on each side.
- Draw UI from the atoms, never from a remote's answer (the TypeTorch UI workflow), so a swap's hydrate redraws it.
---
# Networking
One typed network replaces every RemoteEvent and RemoteFunction. Messages travel over the kernel's two stable remotes
(`ReplicatedStorage.TypeTorch.Net` and `NetU`), so a swap never breaks the network, and a generation never creates
remotes of its own.
## Declare
```ts
// src/shared/net.ts
import { createNetwork, type ProperReturns } from "@typetorch/framework";
/** Client -> server. Every leaf gets a generated type guard. */
interface ClientToServer {
shop: {
buy(itemId: string, amount: number): void;
price(itemId: string): ProperReturns;
};
}
/** Server -> client. */
interface ServerToClient {
shop: {
purchased(itemId: string): void;
};
}
export const network = createNetwork();
```
Namespaces nest as deep as you like. A leaf returning `ProperReturns` is a request: it answers `[value]` or
`[false, "reason"]` (the reason is player-facing text).
## Use
Server (in a service, with the trove):
```ts
this.trove.add(network.server.shop.buy.on((player, itemId, amount) => this.buy(player, itemId, amount)));
this.trove.add(network.server.shop.price.handle((player, itemId) => [this.priceOf(itemId)]));
network.server.shop.purchased.fire(player, "sword");
network.server.shop.purchased.fireAll("sword");
network.server.shop.purchased.fireExcept(player, "sword");
network.server.shop.purchased.fireList([a, b], "sword");
network.server.shop.purchased.fireUnreliable(player, "sword");
network.server.shop.purchased.fireAllUnreliable("sword");
```
Client (in a controller):
```ts
network.client.shop.buy.fire("sword", 1);
network.client.shop.buy.fireUnreliable("sword", 1); // over the unreliable remote: may be dropped, never resent
this.trove.add(network.client.shop.purchased.on((itemId) => this.showPurchased(itemId)));
this.trove.addPromise(
network.client.shop.price.invoke("sword").then((reply) => {
const [price] = reply;
if (typeIs(price, "number")) this.showPrice(price);
}),
);
```
- `on` registers a listener (several allowed); `handle` sets the one request handler of a leaf (a second `handle`
replaces the first, with a warning). Each returns a disconnect function, which the trove takes.
- A handler may return a Promise: the answer waits for it. A handler that throws or rejects makes the client's `invoke`
reject with "Something went wrong, try again.".
- `invoke` resolves with the handler's result or rejects after 15 s ("The server didn't answer in time."), or when the
generation stops ("This version of the game is shutting down.").
- A listener or handler that throws is warned (`[net] shop.buy listener threw: ...`) and counted in the dev menu; it
never breaks the other listeners.
### Timeouts
A button that must fail fast, or a call that takes long (a reserved server, a teleport), sets its own timeout in
seconds:
```ts
network.client.vc.spawn.invokeWithTimeout(30).then(([ok]) => ...); // this call
setNetworkLimits({ "vc.status": { timeout: 5 } }); // every invoke of this leaf
```
- `invokeWithTimeout(seconds, ...args)` wins over the leaf's `timeout`, which wins over the default 15 s.
- Both are in **seconds**, from 0.5 to 120. A value outside is clamped, with one warning (Flamework code that passed
`5000` meaning milliseconds gets 120 s; `typetorch migrate` doesn't change the arguments).
- The client reads the leaf's `timeout`, so call that `setNetworkLimits` in code both realms load (next to
`createNetwork` in `src/shared/net.ts`).
### Run local handlers: `emit`
`emit` runs this generation's own `on` handlers for a leaf, right now, as if the message had arrived. Nothing goes over
the network, and no guard runs. It is Flamework's `predict`: one handler for both server messages and local feedback.
```ts
// client: show an error toast through the same handler the server's notify.error uses
network.client.notify.error.emit("Not enough coins");
// server, for tests: run the shop.buy listeners as if the player had sent it
network.server.shop.buy.emit(player, "sword", 1);
```
Handlers run in order on the calling thread; one that throws is warned, and the others still run.
## Guards and limits
Every client → server message is checked on the server, in this order:
1. a per-player, per-leaf **rate limit** (token bucket, default 20 burst, 10 per second);
2. **shape limits**: finite numbers, strings up to 1000 characters, tables up to 300 entries and 4 levels deep;
3. the **generated type guard** for the leaf's parameters.
A client that keeps sending refused messages (300 within 10 s) is kicked. Tune a leaf:
```ts
import { setNetworkLimits } from "@typetorch/framework";
setNetworkLimits({
"chat.say": { maxString: 200, rate: [5, 1] },
"build.place": { maxEntries: 50 },
});
```
| Key | Default | Meaning |
|---|---|---|
| `rate` | `[20, 10]` | token bucket per player and leaf: burst, refill per second |
| `maxString` | `1000` | longest string, anywhere in the arguments |
| `maxEntries` | `300` | most entries in one table |
| `maxDepth` | `4` | deepest table nesting |
| `timeout` | `15` | requests only: seconds the client's `invoke` waits ([Timeouts](https://www.typetorch.dev/guides/networking.md#timeouts)) |
Keys are dotted leaf paths. A key you leave out keeps its default. Guards check shapes only. Keep your game's own
checks in the handler: distance, ownership, cooldowns, prices.
## Rules
- **Never create a RemoteEvent, RemoteFunction or UnreliableRemoteEvent** in game code or in the place. RemoteFunctions
become request leaves (`handle` / `invoke`).
- **Template literal types can't be guarded** (`` `item_${string}` ``): use `string` and check it in the handler.
- Classes can't be guarded either: send plain data.
- **Supported parameter types:** string, number, boolean, undefined and optional, literals and TS enums, Enum items,
Roblox datatypes (Vector3, CFrame, Color3, UDim2, ...), Instances by class, arrays, tuples, Maps, Sets, plain objects
and interfaces, unions, `buffer`, and `unknown` / `any`. The transformer names the leaf when a guard can't be built,
and warns about generic or conditional leaves (checked loosely: use a union of tuples) and about values that never
arrive (functions, threads, signals, connections, AnimationTracks).
- Register handlers through the trove, so a swap removes them.
- **Across a swap** (framework 0.3.0+): each client drops server messages from another generation than its own, so
the server holds what it sends a player until that player's client runs the new generation and says hello. Reliable
messages are queued (256 per player at most, sent anyway after 30 s); unreliable ones are dropped meanwhile.
- A message a client sends with the old generation's id is dropped by the server. On kernel 0.3.2+ an event (`fire`)
still reaches the new generation when the network's protocol hash didn't change; a request never does. For a dropped
message the kernel tells that client, and its pending `invoke`s fail at once with "The game is updating, try again."
(and so do new ones until its own swap). On a client's own swap, its pending `invoke`s reject with "This version of
the game is shutting down." (`typetorch build` stamps the protocol hash from your `createNetwork` declarations.)
- Third-party networking (`@rbxts/net`, `@flamework/networking`, Zap, Blink, ByteNet) doesn't run inside a payload.
From `@flamework/networking`: `connect` → `on`, `setCallback` → `handle`, `broadcast` → `fireAll`, `except` →
`fireExcept`, `predict` → `emit`, `invokeWithTimeout` keeps its name (seconds). Or keep Flamework's names for now
with `createFlameworkCompat` ([Coming from Flamework](https://www.typetorch.dev/guides/from-flamework.md)).
## Seeing the traffic
The dev menu's **Network > Packets** shows every message with its guard verdict and arguments; **Network > Stats**
counts them per leaf. See [The dev menu](https://www.typetorch.dev/guides/dev-menu.md#network).
---
# Cross-server messages and the server list
Your game talks to its other servers through **`TypeTorch.messaging`**: global announcements, cross-server bans,
"a boss spawned" events. **`TypeTorch.servers()`** lists the game's live servers. Both are server only.
- Needs **kernel 0.3.8+** in the place and a framework after 0.3.4. A place project that maps the kernel's files one
by one (like the template's `studio.project.json`) must map `Messaging` too. On an older kernel, `subscribe` and `publish` throw
"needs kernel 0.3.8": keep your MessagingService code until the kernel is updated.
- `TypeTorch.features.messaging` says whether this server can reach other servers.
## Send and receive
```ts
import { Players } from "@rbxts/services";
import { TypeTorch } from "@typetorch/framework";
interface BanMessage {
userId: number;
reason: string;
}
// in a server module
onStart() {
this.trove.add(
TypeTorch.messaging.subscribe("ban", (data, meta) => {
Players.GetPlayerByUserId(data.userId)?.Kick(data.reason);
}),
);
}
banEverywhere(userId: number, reason: string) {
TypeTorch.messaging.publish("ban", { userId, reason });
}
```
- **Topics** are names you choose: 1-64 characters of letters, digits and `_ - . : /` (`__` is reserved). They don't
cost subscriptions: the kernel carries every game topic on ONE MessagingService topic, `TypeTorch/game`.
- **`subscribe`** returns a disconnect: give it to the module's trove. Every server hears its own messages too
(`meta.self`).
- **Swaps:** the kernel subscribes once and keeps the subscription for the server's life, so a swap never subscribes
again. Your listeners belong to the running build and go with it. A message that arrives during a swap is kept and
handed to the new build's listeners (`meta.replayed`): messages up to 10 s old, at most 50.
- **`publish` never yields.** The kernel queues the message (at most 100 wait) and retries a failed send after 1, 3
and 9 s. It returns `false` when the message was dropped at once (the queue is full, the server is closing). It
throws right away on a bad topic, data that isn't plain JSON (strings, numbers, booleans, arrays, string-keyed
tables, nested at most 16 deep), or a message over the size limit, with its size.
- **The cloud test** publishes nothing, so you don't need a `TypeTorchTest` guard around `publish`.
- **Studio** never touches MessagingService: messages loop back to the session, so you can test a listener alone.
## Who hears what
Every message carries its sender's tags in `meta`: `jobId`, `branch`, `channel` (`prod` or `dev`), `serverType`,
`placeVersion`, `sentAt` (unix seconds) and `self`.
By default a listener hears **prod-channel servers and servers on its own branch**. A dev branch's test of a ban or an
announcement never reaches prod, and a dev server still hears prod.
```ts
TypeTorch.messaging.subscribe("chat", handler, { from: "all" }); // every server, dev branches too
TypeTorch.messaging.subscribe("chat", handler, { from: "prod" }); // prod-channel servers only
TypeTorch.messaging.subscribe("chat", handler, { from: "branch" }); // this branch only
TypeTorch.messaging.publish("event", data, { to: "branch" }); // only servers on the sender's branch hear it
TypeTorch.messaging.publish("event", data, { to: "prod" }); // only prod-channel servers hear it
TypeTorch.messaging.publish("event", data, { to: "all" }); // the default: each listener's `from` decides
```
The tags are for routing, not proof: anything that can publish to your universe's MessagingService can forge them.
Don't let a message grant anything a player couldn't already get.
## Limits
Roblox's [MessagingService limits](https://create.roblox.com/docs/reference/engine/classes/MessagingService) (checked
2026-10-06):
| Limit | Value |
|---|---|
| Message size | 1 KiB (1,024 characters) |
| Publishes per server | 600 + 240 × players a minute |
| Receives per topic, whole game | 40 + 80 × servers a minute |
| Receives, whole game | 400 + 200 × servers a minute |
| Subscriptions per server | 20 + 8 × players |
| Subscribe requests per server | 240 a minute |
What this means for you:
- **Size:** the kernel counts your message the way Roblox does: the whole envelope, JSON-escaped. About 850 bytes of
your data fit. Send ids, not whole objects.
- **Rate: the per-topic receive limit is the one that bites.** One message to every server counts once per server, so
the whole game can send only about **80 messages a minute on one topic**, however many servers it has. All your game
topics share `TypeTorch/game`, so keep them to a few a minute in total. Near 60 a minute the kernels hold publishes
back together and send them a little later (`TypeTorch.messaging.status()`: `rate`, `throttled`, `queued`); a message
that waits more than 30 s is dropped. Fast data (a leaderboard every second) belongs in a MemoryStore.
- **Per server,** the kernel sends at most 150 + 60 × players a minute (a quarter of Roblox's limit, leaving room for
deploys and roll calls).
`TypeTorch.messaging.status()` returns the kernel's counters: `state`, `received`, `delivered`, `published`, `failed`,
`dropped`, `throttled`, `queued`, `rate`. The dev menu warns "Messaging busy" or "Messages dropped" (Server > Status).
## TypeTorch's own topics
| Who | Topic | When |
|---|---|---|
| kernel | `TypeTorch/deploy`, `TypeTorch/pin`, `TypeTorch/rekey` | every server, always |
| kernel 0.3.6+ peers | `TypeTorch/peers/` | about 3 s, only while a server asks other servers for a build |
| kernel 0.3.8 | `TypeTorch/game` | from the first `subscribe`, for the server's life |
| kernel 0.3.8 | `TypeTorch/rollcall` | from the first build that runs, for the server's life (the server list) |
| framework roll call | one reply topic | about 3 s, while this server collects a server list |
| remote-claude (framework devtools) | `TypeTorch/remote-claude`, `TypeTorch/tool` | only where the dev tools are open: dev rules, or a public server an owner switched to a dev branch |
`TypeTorch/deploy` is also the kernel's control topic: the settings ping, the peers' ask, the remote debug wake (kernel
0.5.1) and the live map wake (kernel 0.5.7) ride it, so none of them adds a subscription.
So a server uses 5, briefly 7, of the 20 an empty server allows. Your own `SubscribeAsync` calls come on top: moving
them to `TypeTorch.messaging` frees them (and their re-subscribe on every swap).
## The server list
```ts
const servers = TypeTorch.servers(); // GameServer[]
for (const server of servers) {
print(server.jobId, server.players, server.maxPlayers, server.branch, server.uptime, server.info?.region);
}
TypeTorch.setServerInfo({ region: "eu", mode: "ranked" }); // this server's public fields, in every server's list
```
- Each row: `jobId`, `placeVersion`, `players`, `maxPlayers`, `serverType` (`public`, `private`, `reserved`, `studio`),
`branch`, `channel`, `uptime` (seconds), `here` (this server) and `info` (its `setServerInfo` fields).
- By default: prod-channel servers and servers on this server's branch. `{ includeDev: true }` lists every server;
`{ includeSelf: false }` leaves this one out.
- It is a roll call over MessagingService, the same one the dev menu's Manage > Servers uses: no MemoryStore, no
storage. **It yields** up to about 3 s when it asks; then the list is cached for 3 s per server in the game (at least
30 s, at most 10 minutes), so the whole game asks about 20 times a minute at most. Callers in the meantime get the
cached list at once. Fine for games of up to a few hundred servers; a bigger game wants its own MemoryStore registry.
- **`setServerInfo`** takes plain JSON, at most 400 bytes, kept across swaps; `undefined` clears it. Everyone's
`servers()` sees it, so never put a secret, an access code or a player's private data there.
- Rows never carry a reserved server's access code. To send players to another server, use the `jobId` with
`TeleportService:TeleportToPlaceInstance`.
- The cloud test and Studio list only this server.
## Moving from MessagingService
1. Find your topics: `git grep -nE "SubscribeAsync|PublishAsync" -- src`.
2. Replace each `MessagingService.SubscribeAsync(topic, (message) => ...)` with
`this.trove.add(TypeTorch.messaging.subscribe(topic, (data, meta) => ...))`. `data` is your message itself (no
`message.Data`), and `meta.sentAt` replaces `message.Sent`.
3. Replace `MessagingService.PublishAsync(topic, data)` with `TypeTorch.messaging.publish(topic, data)`. Drop your
retry loops, `pcall`s and `TypeTorchTest` guards around it: the kernel queues, retries and skips the cloud test.
4. Messages don't cross between a raw MessagingService topic and `TypeTorch.messaging`: switch the publishers and the
listeners of one topic in the same build.
5. A topic that needs every server, dev branches included, takes `{ from: "all" }`.
---
# Player data
**Player data is game code** (decision 2026-10-05). TypeTorch doesn't save player data for you, and the kernel holds no
data sessions. You pick the library: ProfileStore, ProfileService, DataStore2, your own. This page is the pattern that
keeps it safe across hot swaps, with a full example for [ProfileStore](https://www.typetorch.dev/guides/player-data.md#example-profilestore) and one for
[ProfileService](https://www.typetorch.dev/guides/player-data.md#example-profileservice).
## Why data needs care
A deploy stops your code and starts a fresh copy in the same server, with the same players. A data library that ships
inside the payload would be stopped too: its open sessions, its autosave loop and its shutdown hook would end with the
old generation, and the new one would load every profile again while the old session locks are still held.
## The swap-safe pattern
1. **The library lives in the place, outside the payload** (for example `ServerStorage.Packages.ProfileStore`), and a
small Script in the place, `DataHost`, requires it first. So the library, its open sessions and its background work
survive every swap.
2. **Session handles live in `persist`**, keyed by `UserId`. The next generation re-attaches to them instead of loading
again.
3. **Load on join, release on a real leave.** `onPlayerAdded` replays everyone after a swap, so it reuses a live
session. Release only on `Players.PlayerRemoving`, never on a swap.
4. **Library calls that write run where a deploy can't stop them:** starting or loading a session, `Save()`, ending or
releasing it. Your code hands them off as jobs, to DataHost's queue (any kernel) or to `TypeTorch.runDetached`
(kernel 0.3.8+), see [Two ways to run the jobs](https://www.typetorch.dev/guides/player-data.md#two-ways-to-run-the-jobs). A job puts its result into `persist`
itself.
5. **`onSwapOut` flushes only what the new code needs** (for example values you keep outside `profile.Data`). The
profiles stay open.
Why the host Script: Roblox ends the threads and connections that a script started when that script stops, and the
kernel stops a generation's script on every swap (that is how a swap cleans up). If a generation were the first to
require the library, the library's autosave loop and shutdown hook would belong to that generation and could stop at
the next deploy. Requiring it from a place Script first makes them belong to the place.
Why the jobs: the same rule ends a library call that is still running when a deploy lands. A load waits on the
DataStore, and `Save()`, `EndSession()` and `Release()` start their save on the calling thread's script. Cut off
halfway, both ProfileStore and ProfileService keep that call's bookkeeping for the key forever (checked under Lune
against both libraries' real code):
- a load cut off: every later load of that player on this server waits forever;
- a release cut off: the last save is lost, the session lock stays, and the player can't load on this server again;
- a `Save()` cut off: with ProfileStore, every later save of that profile waits forever, so the rest of the session is
lost; ProfileService does the same when the save was waiting out its 7 s write cooldown.
A job runs on a thread no deploy stops (DataHost's, or the kernel's). A job may finish after the generation that
queued it has stopped, so it uses only the library, `persist` tables and Roblox APIs (never a module's trove or
`this`).
`persist` normally takes plain data only. Handles from a library in the place are the exception: they don't belong to
a generation. Never store your own functions in them, and connect to their signals through a trove.
## Two ways to run the jobs
Both keep a library call running through a deploy. The examples below use **A**; switching to **B** changes two small
pieces of each example (shown after it).
| | A: DataHost's job queue | B: `TypeTorch.runDetached` |
|---|---|---|
| Kernel | any | 0.3.8+ |
| DataHost | requires the library **and** runs the queue (`library.TypeTorchJobs`) | only requires the library (no queue) |
| The job runs on | DataHost's thread, from the next frame | a kernel thread, at once |
| Errors | DataHost's script errors in the output | the dev menu's Logs, with the build that queued the job; the Promise rejects |
| Limits | none | 256 jobs at once per server; one past 60 s is logged and flagged in Server > Status |
| Costs | changing the queue is a place publish | a job keeps the old build's code in memory until it ends |
**Pick A** when your place may run a kernel before 0.3.8, or you already have DataHost's queue. **Pick B** when the
place runs kernel 0.3.8 or newer and you'd rather keep DataHost to its one `require`: no queue to maintain, and
failures show up next to the build that caused them. Either way DataHost still requires the library first (its
autosave loop and shutdown hook must belong to the place).
With B, the job is the same function, handed to the kernel instead of the queue:
```ts
/** Runs a library call that writes on a kernel thread: a deploy can't cut it off (kernel 0.3.8+). */
private onHost(job: () => void) {
TypeTorch.runDetached(job).catch((err) => warn(`[data] a data job failed: ${err}`));
}
```
`runDetached` returns a Promise that settles while this build runs; after a swap the result is dropped, which is why a
job writes what matters into `persist` itself (the examples' jobs already do). On a kernel before 0.3.8 it throws
"needs kernel 0.3.8; use the DataHost job queue". To support both, check `TypeTorch.features.runDetached` and fall
back to the queue.
## The DataHost script
One Script in the place, the same for every library (change the module's name). It requires the library and runs the
jobs your code queues:
```lua
-- ServerScriptService.DataHost
-- Requires the data library once at server start, so its autosave loop and shutdown hook belong to this script,
-- not to a generation (a swap stops a generation's scripts). It also runs the library calls the payload queues
-- (load, save, release) on this script's threads, so a deploy can't cut one off halfway.
local module = game:GetService("ServerStorage"):WaitForChild("Packages"):WaitForChild("ProfileStore")
local library = require(module)
local jobs = {}
library.TypeTorchJobs = jobs
game:GetService("RunService").Heartbeat:Connect(function()
while #jobs > 0 do
task.spawn(table.remove(jobs, 1))
end
end)
module:SetAttribute("Warm", true)
```
A job starts on the next frame. The payload finds the queue as `TypeTorchJobs` on the same library table (a module is
required once per server, so DataHost and every generation share it).
With [option B](https://www.typetorch.dev/guides/player-data.md#two-ways-to-run-the-jobs) (`TypeTorch.runDetached`, kernel 0.3.8+), DataHost only requires the
library:
```lua
-- ServerScriptService.DataHost (option B: the payload runs its library calls with TypeTorch.runDetached)
-- Requires the data library once at server start, so its autosave loop and shutdown hook belong to this script.
local module = game:GetService("ServerStorage"):WaitForChild("Packages"):WaitForChild("ProfileStore")
require(module)
module:SetAttribute("Warm", true)
```
## Example: ProfileStore
### In the place (Studio, once)
1. Put the ProfileStore ModuleScript at `ServerStorage.Packages.ProfileStore`.
2. Add the Script `ServerScriptService.DataHost` from [The DataHost script](https://www.typetorch.dev/guides/player-data.md#the-datahost-script).
3. Publish the place. (Changing the library later is a place publish and a restart, like the kernel.)
### In the payload
```ts
// src/server/services/data.service.ts
import { Players, ServerStorage, Workspace } from "@rbxts/services";
import type { Trove } from "@rbxts/trove";
import { Module, Service, TypeTorch, type OnInit, type OnPlayerAdded } from "@typetorch/framework";
/** What you save per player: plain data. */
export interface PlayerData {
coins: number;
inventory: string[];
/** The newest developer product PurchaseIds granted (see "Developer products"). */
purchaseIds: string[];
}
const TEMPLATE: PlayerData = { coins: 0, inventory: [], purchaseIds: [] };
// The part of ProfileStore's API this service uses. The library itself lives in the place, not in the payload.
interface Profile {
Data: T;
/** A copy of Data as of the last successful save (an older save may lack newer fields). */
LastSavedData: Partial;
IsActive(): boolean;
AddUserId(userId: number): void;
Reconcile(): void;
Save(): void;
EndSession(): void;
OnSessionEnd: { Connect(callback: () => void): { Disconnect(): void } };
}
interface Store {
StartSessionAsync(key: string, params?: { Cancel?: () => boolean }): Profile | undefined;
}
interface ProfileStoreModule {
// `this: void`: Luau calls it as ProfileStore.New(...), not ProfileStore:New(...).
New(this: void, name: string, template: T): Store;
/** Added by the place's DataHost script: it runs these on its own threads. */
TypeTorchJobs?: Array<() => void>;
}
/**
* The place's copy of ProfileStore, once the place's DataHost script has required it. Errors (so the deploy rolls
* back with a clear message) when the place doesn't have it. Undefined in the cloud test.
*/
function profileStore(): ProfileStoreModule | undefined {
const module = ServerStorage.FindFirstChild("Packages")?.FindFirstChild("ProfileStore");
if (!module || !module.IsA("ModuleScript")) error("ServerStorage.Packages.ProfileStore is missing (see the Player data guide)");
// The cloud test (`typetorch test --cloud`, before every prod deploy) runs this code in a headless task. Place
// scripts (DataHost) never run there and no player joins, so stop here. The check above still runs.
if (Workspace.GetAttribute("TypeTorchTest") === true) return undefined;
const deadline = os.clock() + 10;
while (module.GetAttribute("Warm") !== true) {
if (os.clock() > deadline) error("ServerScriptService.DataHost didn't require ProfileStore (see the Player data guide)");
task.wait(0.1);
}
const library = require(module) as ProfileStoreModule;
if (!library.TypeTorchJobs) error("ServerScriptService.DataHost has no job queue: update it (see the Player data guide)");
return library;
}
/** Lives in persist: the library, the store and one open session per player for the whole server life. */
interface Sessions {
library?: ProfileStoreModule;
store?: Store;
profiles: Map>;
/** Players whose session is starting (a DataHost job). */
starting: Set;
}
@Service({ loadOrder: -10 })
export class DataService extends Module implements OnInit, OnPlayerAdded {
private sessions!: Sessions;
onInit() {
this.sessions = this.ctx.persist("data.sessions.v1", () => ({ profiles: new Map(), starting: new Set() }));
this.sessions.starting ??= new Set(); // sessions kept by an older build of this service (same key: they're open)
this.sessions.library ??= profileStore();
if (!this.sessions.store) {
// Dev branches never touch prod data.
const name = TypeTorch.channel === "prod" ? "PlayerData" : "PlayerData_dev";
this.sessions.store = this.sessions.library?.New(name, TEMPLATE);
}
// A real leave (never a swap): end the session. ProfileStore saves and releases it.
this.trove.connect(Players.PlayerRemoving, (player) => this.release(player));
}
onPlayerAdded(player: Player, playerTrove: Trove) {
const sessions = this.sessions;
const store = sessions.store;
if (!store) return; // only in the cloud test, where nobody joins
const userId = player.UserId;
// Also runs for everyone already here after a swap: re-attach, or wait for the start that is still running.
if (!sessions.profiles.get(userId)?.IsActive() && !sessions.starting.has(userId)) {
sessions.starting.add(userId);
this.onHost(() => {
try {
const profile = store.StartSessionAsync(`Player_${userId}`, { Cancel: () => player.Parent !== Players });
if (!profile) return;
if (player.Parent !== Players) {
profile.EndSession();
return;
}
profile.AddUserId(userId);
profile.Reconcile();
sessions.profiles.set(userId, profile);
} finally {
sessions.starting.delete(userId);
}
});
}
while (sessions.starting.has(userId)) task.wait(0.1); // a swap ends this wait, not the start
const profile = sessions.profiles.get(userId);
if (!profile || !profile.IsActive()) {
if (player.Parent === Players) player.Kick("Your data didn't load. Please rejoin.");
return;
}
// This generation's code connected to the library goes in a trove, so a swap disconnects it.
const connection = profile.OnSessionEnd.Connect(() => {
sessions.profiles.delete(userId);
if (player.Parent === Players) player.Kick("Your data was opened on another server. Please rejoin.");
});
playerTrove.add(() => connection.Disconnect());
}
/** The player's data (the same table in every generation), or undefined while it loads. */
get(player: Player): PlayerData | undefined {
return this.sessions.profiles.get(player.UserId)?.Data;
}
/**
* Grants a developer product once. The PurchaseId goes into the profile together with the grant, and the answer is
* PurchaseGranted only once a save holds it. A receipt Roblox sends again (after a swap, a crash, or on another
* server) finds the id and grants nothing.
*/
grantOnce(receipt: ReceiptInfo, grant: (data: PlayerData) => void): Enum.ProductPurchaseDecision {
const profile = this.sessions.profiles.get(receipt.PlayerId);
// Not in this server, or still loading: Roblox sends the receipt again later.
if (!profile || !profile.IsActive()) return Enum.ProductPurchaseDecision.NotProcessedYet;
const ids = profile.Data.purchaseIds;
if (!ids.includes(receipt.PurchaseId)) {
grant(profile.Data); // first: if it throws, nothing is recorded
ids.push(receipt.PurchaseId);
if (ids.size() > 100) ids.shift();
}
// Answer only once a save holds the id. Cut off before that (a swap, a leave, a crash): Roblox sends the
// receipt again, and the id was saved together with the grant, or lost together with it.
let nextSave = 0;
for (;;) {
if (profile.LastSavedData.purchaseIds?.includes(receipt.PurchaseId) === true) return Enum.ProductPurchaseDecision.PurchaseGranted;
if (!profile.IsActive()) return Enum.ProductPurchaseDecision.NotProcessedYet;
if (os.clock() >= nextSave) {
nextSave = os.clock() + 10;
this.onHost(() => profile.Save()); // sooner than the autosave
}
task.wait(0.5);
}
}
private release(player: Player) {
const profile = this.sessions.profiles.get(player.UserId);
if (!profile) return; // still starting: that job sees the player left and ends the session
this.sessions.profiles.delete(player.UserId);
this.onHost(() => profile.EndSession());
}
/** Runs a library call that writes (start, save, end) on DataHost's thread: a deploy can't cut it off. */
private onHost(job: () => void) {
this.sessions.library?.TypeTorchJobs?.push(job);
}
}
```
Other services read and change `dataService.get(player)` directly; it's the same `profile.Data` table in every
generation, so a change made just before a swap is not lost.
- `loadOrder: -10` starts it before modules that read data in their own `onPlayerAdded`. They should still handle
`undefined` (the profile may still be loading).
- **Put the library and `DataHost` in the place before you deploy this code.** Without them `onInit` fails with a
clear error, the new build doesn't start, and the server rolls back to the previous one.
- The interfaces above describe only what this service calls. If your project has typings for the library, use
`import type` from them: a value import would require a second copy of the library inside the payload.
- A function the library calls with a dot (`ProfileStore.New`) needs `this: void` in its interface. Without it
roblox-ts emits `ProfileStore:New(...)`, and ProfileStore fails with `Invalid or missing "store_name"`.
- **Changing what you keep in `persist`:** keep the key while sessions are open under it (a new key would load every
profile again). Fill new fields in when they're missing, like `starting` and `library` above.
**With option B** ([`TypeTorch.runDetached`](https://www.typetorch.dev/guides/player-data.md#two-ways-to-run-the-jobs), kernel 0.3.8+), two changes: DataHost without
the queue (above), and in the service:
```ts
// profileStore(): drop the TypeTorchJobs check (the queue doesn't exist)
const library = require(module) as ProfileStoreModule;
return library;
// DataService: the jobs go to the kernel instead of DataHost's queue
private onHost(job: () => void) {
TypeTorch.runDetached(job).catch((err) => warn(`[data] a data job failed: ${err}`));
}
```
Everything else stays: the jobs, `starting`, `grantOnce` (its `Save()` request is a job too) and `release`.
### The cloud test
Every prod deploy first boots your build in a headless Luau Execution task, the
[cloud test](https://www.typetorch.dev/guides/deploy-and-rollback.md#the-cloud-test). Place scripts never run there, so `DataHost` never warms the
library, and no player joins. That is why `profileStore()` returns `undefined` when
`workspace:GetAttribute("TypeTorchTest")` is true. Without that line, `onInit` waits 10 s and fails, and every prod
deploy is refused. The check before it still runs: a place published without the library still fails the test.
The rest of your code runs there too, against your real DataStores:
[Migrate: the cloud test runs your game code](https://www.typetorch.dev/getting-started/migrate.md#the-cloud-test-runs-your-game-code).
### Developer products
Roblox calls `ProcessReceipt` until it gets `PurchaseGranted`, on whatever server the player is in. **Record the
PurchaseId in the player's profile, together with the grant, and return `PurchaseGranted` only after a save holds
it.** That is `grantOnce` above. `persist` is not enough: it is this server's memory, so a receipt sent again to
another server after the player left would be granted twice.
```ts
// src/server/services/receipt.service.ts
import { MarketplaceService } from "@rbxts/services";
import { Module, Service, type OnInit } from "@typetorch/framework";
import { DataService, type PlayerData } from "./data.service";
/** Developer product id -> what it gives. */
const PRODUCTS = new Map void>([
[1234567, (data) => (data.coins += 100)],
]);
@Service()
export class ReceiptService extends Module implements OnInit {
constructor(private readonly data: DataService) {
super();
}
onInit() {
MarketplaceService.ProcessReceipt = (receipt) => {
const grant = PRODUCTS.get(receipt.ProductId);
if (!grant) return Enum.ProductPurchaseDecision.NotProcessedYet;
return this.data.grantOnce(receipt, grant);
};
// The callback belongs to this generation. A receipt that arrives between two generations is sent again.
this.trove.add(() => {
(MarketplaceService as unknown as { ProcessReceipt?: unknown }).ProcessReceipt = undefined;
});
}
}
```
- The grant and the id change the same `profile.Data` table without yielding, so they are saved together.
- A swap while it waits for the save ends the wait without an answer. Roblox sends the receipt again, and the next
generation finds the id in `Data` and only waits for the save.
- It keeps the newest 100 ids. `Reconcile` adds the empty list to profiles saved before you added the field.
- The save it asks for is a DataHost job, again every 10 s while it waits.
### Shutdown
- ProfileStore saves and releases its sessions on server close by itself, because it runs in the place.
- **Don't rely on `onStop` for saves.** A server that shuts down in the middle of a swap (the old build stopped, the
new one not running yet) has no running generation, so no `onStop` runs. Keep the data in the library in the place,
or write each change as it happens. `onStop` is fine for short extras.
## Example: ProfileService
ProfileService is ProfileStore's older sibling (same author), and many games still use it. The pattern is the same;
the API differs: `GetProfileStore`, `LoadProfileAsync(key, "ForceLoad")`, `Release()`, `ListenToRelease`, and no
`LastSavedData` (receipts use `MetaData.MetaTagsLatest` instead, below).
### In the place (Studio, once)
1. Put the ProfileService ModuleScript at `ServerStorage.Packages.ProfileService`.
2. Add `ServerScriptService.DataHost` from [The DataHost script](https://www.typetorch.dev/guides/player-data.md#the-datahost-script), with `ProfileService` in place of
`ProfileStore` on the `WaitForChild` line.
3. Publish the place.
### In the payload
```ts
// src/server/services/data.service.ts
import { Players, ServerStorage, Workspace } from "@rbxts/services";
import type { Trove } from "@rbxts/trove";
import { Module, Service, TypeTorch, type OnInit, type OnPlayerAdded } from "@typetorch/framework";
/** What you save per player: plain data. */
export interface PlayerData {
coins: number;
inventory: string[];
}
const TEMPLATE: PlayerData = { coins: 0, inventory: [] };
/** Saved together with Data on every save. MetaTagsLatest is what the last save wrote (see "Developer products"). */
interface Tags {
purchaseIds?: string[];
}
// The part of ProfileService's API this service uses. The library itself lives in the place, not in the payload.
interface Profile {
Data: T;
MetaData: { MetaTags: Tags; MetaTagsLatest: Tags };
IsActive(): boolean;
AddUserId(userId: number): void;
Reconcile(): void;
Save(): void;
Release(): void;
ListenToRelease(listener: () => void): { Disconnect(): void };
}
interface Store {
LoadProfileAsync(key: string, notReleasedHandler: "ForceLoad" | "Steal"): Profile | undefined;
}
interface ProfileServiceModule {
// `this: void`: Luau calls it as ProfileService.GetProfileStore(...).
GetProfileStore(this: void, name: string, template: T): Store;
/** Added by the place's DataHost script: it runs these on its own threads. */
TypeTorchJobs?: Array<() => void>;
}
/** The place's copy of ProfileService, once DataHost required it. Errors when the place lacks it; undefined in the cloud test. */
function profileService(): ProfileServiceModule | undefined {
const module = ServerStorage.FindFirstChild("Packages")?.FindFirstChild("ProfileService");
if (!module || !module.IsA("ModuleScript")) error("ServerStorage.Packages.ProfileService is missing (see the Player data guide)");
if (Workspace.GetAttribute("TypeTorchTest") === true) return undefined; // the cloud test: DataHost never runs there
const deadline = os.clock() + 10;
while (module.GetAttribute("Warm") !== true) {
if (os.clock() > deadline) error("ServerScriptService.DataHost didn't require ProfileService (see the Player data guide)");
task.wait(0.1);
}
const library = require(module) as ProfileServiceModule;
if (!library.TypeTorchJobs) error("ServerScriptService.DataHost has no job queue: update it (see the Player data guide)");
return library;
}
/** Lives in persist: the library, the store and one loaded profile per player for the whole server life. */
interface Sessions {
library?: ProfileServiceModule;
store?: Store;
profiles: Map>;
/** Players whose profile is loading (a DataHost job). */
loading: Set;
}
@Service({ loadOrder: -10 })
export class DataService extends Module implements OnInit, OnPlayerAdded {
private sessions!: Sessions;
onInit() {
this.sessions = this.ctx.persist("data.sessions.v1", () => ({ profiles: new Map(), loading: new Set() }));
this.sessions.library ??= profileService();
if (!this.sessions.store) {
// Your live store name on prod, another one on dev branches.
const name = TypeTorch.channel === "prod" ? "PlayerData" : "PlayerData_dev";
this.sessions.store = this.sessions.library?.GetProfileStore(name, TEMPLATE);
}
// A real leave (never a swap): release the profile. ProfileService saves it and frees the session lock.
this.trove.connect(Players.PlayerRemoving, (player) => this.release(player));
}
onPlayerAdded(player: Player, playerTrove: Trove) {
const sessions = this.sessions;
const store = sessions.store;
if (!store) return; // only in the cloud test, where nobody joins
const userId = player.UserId;
// Also runs for everyone already here after a swap: re-attach, or wait for the load that is still running.
if (!sessions.profiles.get(userId)?.IsActive() && !sessions.loading.has(userId)) {
sessions.loading.add(userId);
this.onHost(() => {
try {
const profile = store.LoadProfileAsync(`Player_${userId}`, "ForceLoad");
if (!profile) return;
if (player.Parent !== Players) {
profile.Release();
return;
}
profile.AddUserId(userId);
profile.Reconcile();
sessions.profiles.set(userId, profile);
} finally {
sessions.loading.delete(userId);
}
});
}
while (sessions.loading.has(userId)) task.wait(0.1); // a swap ends this wait, not the load
const profile = sessions.profiles.get(userId);
if (!profile || !profile.IsActive()) {
if (player.Parent === Players) player.Kick("Your data didn't load. Please rejoin.");
return;
}
// Released by another server (ForceLoad there): through the player trove, so a swap disconnects it.
const connection = profile.ListenToRelease(() => {
sessions.profiles.delete(userId);
if (player.Parent === Players) player.Kick("Your data was opened on another server. Please rejoin.");
});
playerTrove.add(() => connection.Disconnect());
}
/** The player's data (the same table in every generation), or undefined while it loads. */
get(player: Player): PlayerData | undefined {
return this.sessions.profiles.get(player.UserId)?.Data;
}
/**
* Grants a developer product once. The PurchaseId goes into the profile's MetaTags together with the grant (the same
* save writes both), and the answer is PurchaseGranted only once MetaTagsLatest, the copy the last save wrote, holds
* it. A receipt Roblox sends again (after a swap, a crash, or on another server) finds the id.
*/
grantOnce(receipt: ReceiptInfo, grant: (data: PlayerData) => void): Enum.ProductPurchaseDecision {
const profile = this.sessions.profiles.get(receipt.PlayerId);
// Not in this server, or still loading: Roblox sends the receipt again later.
if (!profile || !profile.IsActive()) return Enum.ProductPurchaseDecision.NotProcessedYet;
const tags = profile.MetaData.MetaTags;
const ids = tags.purchaseIds ?? [];
tags.purchaseIds = ids;
if (!ids.includes(receipt.PurchaseId)) {
grant(profile.Data); // first: if it throws, nothing is recorded
ids.push(receipt.PurchaseId);
if (ids.size() > 100) ids.shift();
}
let nextSave = 0;
for (;;) {
if (profile.MetaData.MetaTagsLatest.purchaseIds?.includes(receipt.PurchaseId) === true) {
return Enum.ProductPurchaseDecision.PurchaseGranted;
}
// Released before a save held it: the id was saved with the grant, or lost with it. Roblox sends it again.
if (!profile.IsActive()) return Enum.ProductPurchaseDecision.NotProcessedYet;
if (os.clock() >= nextSave) {
nextSave = os.clock() + 10;
this.onHost(() => profile.Save()); // sooner than the 30 s autosave
}
task.wait(0.5);
}
}
private release(player: Player) {
const profile = this.sessions.profiles.get(player.UserId);
if (!profile) return; // still loading: that job sees the player left and releases it
this.sessions.profiles.delete(player.UserId);
this.onHost(() => profile.Release());
}
/** Runs a library call that writes (load, save, release) on DataHost's thread: a deploy can't cut it off. */
private onHost(job: () => void) {
this.sessions.library?.TypeTorchJobs?.push(job);
}
}
```
The [ProfileStore notes](https://www.typetorch.dev/guides/player-data.md#in-the-payload) apply here too (`loadOrder`, `import type`, `this: void`, the cloud test).
`profileService()` is the same getter as `profileStore()` with the other name: the module path, the `Warm` wait and
the `TypeTorchTest` line. **Option B** is the same two changes as for ProfileStore: DataHost without the queue (with
`ProfileService` on the `WaitForChild` line), no `TypeTorchJobs` check in `profileService()`, and `onHost` calling
`TypeTorch.runDetached(job)`.
### Developer products with ProfileService
The `ReceiptService` above works unchanged with this `DataService`. Its `grantOnce` is ProfileService's own documented
pattern for developer products:
- **The PurchaseId goes into `profile.MetaData.MetaTags`**, in the same step as the grant. ProfileService writes
`Data` and `MetaTags` in one `UpdateAsync`, so a save holds both or neither.
- **`PurchaseGranted` only once `MetaData.MetaTagsLatest` holds the id.** That is the copy of `MetaTags` the last
successful save wrote (ProfileService's stand-in for ProfileStore's `LastSavedData`). Until then it asks for a save
(a DataHost job) and waits; the 30 s autosave answers it too.
- **A receipt sent again** finds the id in `MetaTags`: after a swap, the next generation only waits for the save; on
another server, the loaded profile's `MetaTagsLatest` already has it, so the answer is immediate and nothing is
granted twice.
**Recommended over a separate receipts DataStore.** Recording the PurchaseId in its own DataStore with `UpdateAsync`
and granting into the profile (what the template's `ShopService` does for its coin pack) makes two separate writes. If
the server crashes after the record but before the profile's next save, the purchase is lost (the record says it was
granted); record after the grant instead and a crash in between grants it twice. A receipts DataStore is right only
for grants that don't live in a profile (the template's coins are server-session values; a donation board is global).
Older copies of ProfileService (before `Profile:Save()` existed) work without the `Save()` job: the autosave answers
within 30 s.
### Coming from `@rbxts/profileservice`
- **Keep your store name and profile key exactly as the live game has them** (what you pass to `GetProfileStore` and
`LoadProfileAsync`): a new name or key format starts every player from scratch. Pick a dev name only for non-prod
channels: `TypeTorch.channel === "prod" ? "" : "_dev"`. A name chosen by
`RunService.IsStudio()` doesn't tell a dev branch from prod.
- `ProfileService.GetProfileStore(...)` at module top level moves into `onInit`, kept in `persist` (a second store
object for the same name would load profiles this server already has).
- `Players.PlayerAdded.Connect` becomes `onPlayerAdded`; `Players.PlayerRemoving` releases through a job (DataHost or
`runDetached`).
- Delete `game.BindToClose` loops that release every profile: ProfileService releases them on close by itself (it runs
in DataHost), and a generation's `BindToClose` may not run at all.
- Other writes on leave (ordered DataStores for leaderboards, analytics) can stay in your code: a cut-off write is just
lost, it can't block the library.
- Keep the typings package for types only: `import type { Profile } from "@rbxts/profileservice/globals"` works, but the
local interfaces above also know `TypeTorchJobs`. Never a value import (`import ProfileService from ...`): it would
require the payload's own copy of the library.
- `GlobalUpdates`, `ListenToHopReady` and `ViewProfileAsync` work as before on the handle; run calls that write
(`GlobalUpdateProfileAsync`, `WipeProfileAsync`) as DataHost jobs too.
## Rules that apply to any library
- **Split store names by channel** (`PlayerData` / `PlayerData_dev`): dev branches run in the same universe.
- **Don't wait on place scripts in the cloud test** (`workspace:GetAttribute("TypeTorchTest")`): they never run there.
- **Run the library's writes where a deploy can't stop them** (DataHost jobs, or `TypeTorch.runDetached` on kernel
0.3.8+): sessions, saves, releases. A call cut off by a deploy can block the library for that player on this
server.
- **Don't rename stores or reshape saved data in a hot deploy** without a migration. Write migrations as code that
upgrades `Data` in place, keyed by a version field you store in it, and keep old fields readable: a rollback runs the
older code against data the newer code may already have touched.
- **Keep DataStore budgets in mind:** a swap must not trigger a reload of every player.
- **Receipts are recorded where the data is saved**, before `PurchaseGranted`, never only in `persist`.
- **Per-player values you don't save** (cooldowns, a round's checkpoint): `this.ctx.playerState("cooldowns.v1",
(player) => init)` (or `TypeTorch.playerState`) keeps them across swaps, keyed by UserId, and drops a player's entry
only when they really leave. Plain data only, like `persist` ([Runtime API](https://www.typetorch.dev/guides/runtime-api.md)).
- **Small data without sessions** works inside the payload too: read once per join, write with `UpdateAsync` when it
changes, and keep unfinished writes in `persist` so the next generation retries them. The template's `BestService`
(personal bests) does exactly this. Its `ShopService` records coin pack receipts in a DataStore before it grants
them.
## Test it on a dev branch first
1. Deploy to `dev` and open it with `/tt new dev`.
2. Change some data (earn coins).
3. Deploy again twice while you play. Your data must still be there and keep changing.
4. Leave, join a new `dev` server: the data loaded.
5. Deploy while a friend joins, and again while one leaves: both load normally afterwards (on that server too).
6. Shut a server down (dev menu > Manage > Servers > Shut down; "Admin" on older frameworks) and rejoin: nothing lost.
7. Buy a developer product while a deploy runs (open the prompt, deploy, then buy). One grant. Rejoin another server:
still one.
8. `bun run typetorch test --cloud` passes (on the `dev` git branch it tests the newest dev build; prod deploys run
the same test).
9. Only then ship it to `prod`.
---
# Loading screens
A joining player waits while the kernel loads your build. Kernel 0.3.6+ covers that wait with its own small screen
("Starting...", "Loading...", "Reconnecting..."). Kernel 0.3.8 lets your game show **its own loading screen** instead
and tells it when the game is ready.
Your loading screen lives in the place (`ReplicatedFirst`), not in the payload: the payload's client code isn't running
yet while the player waits.
## What the kernel tells you
The kernel's client script, `ReplicatedFirst.TypeTorchKernelClient`, sets these attributes on itself:
| Attribute | Value |
|---|---|
| `ClientReady` | `true` once this player's first client generation runs (your client code started). It stays `true`. |
| `ClientGeneration` | the running client generation's name; `nil` while none runs (during a swap) |
| `Holding` | why the player waits: `"start"` (the server is starting), `"load"` (this player's client code failed to start and the server sends it again), `"move"` (the player is being moved to another server); `nil` when nothing holds |
| `HoldReason` | kernel 0.3.9: the hold's reason in words, next to `Holding` (for logs, not for players) |
The game is ready when `ClientReady` is `true` and `Holding` is `nil`.
## Option 1: a picture (no script)
Put a `ScreenGui` in `ReplicatedFirst` (say `LoadingScreen`) and set an attribute on `ReplicatedFirst`:
| Attribute (on `ReplicatedFirst`) | Type | Value |
|---|---|---|
| `TypeTorchBootScreen` | string | `LoadingScreen` |
The kernel shows a copy of it at once, instead of its "Starting..." screen, and removes it when the game is ready (at
most after 60 s). Keep it simple: a background, a logo, a few words. Publish the place.
The name is at most 100 characters, and the object must be a `ScreenGui`. The kernel waits up to 5 s for it to reach
the client; a missing one, or one that isn't a `ScreenGui`, is skipped with a warning in the client log.
## Option 2: your own loading screen script
Set this attribute on `ReplicatedFirst`:
| Attribute (on `ReplicatedFirst`) | Type | Value |
|---|---|---|
| `TypeTorchKernelScreen` | boolean | `false` |
The kernel then never draws "Starting..." or "Loading..." before the game is ready. Your `LocalScript` in
`ReplicatedFirst` shows the screen and hides it when the game is ready:
```lua
-- ReplicatedFirst/LoadingScreen (a LocalScript, with a ScreenGui named LoadingGui inside it)
local Players = game:GetService("Players")
local ReplicatedFirst = game:GetService("ReplicatedFirst")
ReplicatedFirst:RemoveDefaultLoadingScreen()
local gui = script:WaitForChild("LoadingGui"):Clone()
gui.ResetOnSpawn = false
gui.Parent = Players.LocalPlayer:WaitForChild("PlayerGui")
local kernel = ReplicatedFirst:WaitForChild("TypeTorchKernelClient")
local function ready()
return kernel:GetAttribute("ClientReady") == true and kernel:GetAttribute("Holding") == nil
end
local function show()
local holding = kernel:GetAttribute("Holding")
gui.Status.Text = if holding == "load" then "Loading..." elseif holding == "move" then "Reconnecting..." else "Starting..."
end
show()
while not ready() do
kernel.AttributeChanged:Wait()
show()
end
gui:Destroy()
```
- With TypeScript, write it in Luau anyway: it is a place script, not part of the payload.
- Both options can be combined: the boot screen shows at once, your script takes over when it runs.
## After the first load
- **Swaps** (a deploy while the player plays) show no loading screen: the game keeps running.
- **Moves** ("Reconnecting...") always show the kernel's screen, with or without your settings.
- A later hold (rare: a build that failed to load) shows the kernel's screen too.
## Notes
- The server copies `TypeTorchBootScreen` and `TypeTorchKernelScreen` onto `TypeTorchKernelClient` (as `BootScreen`
and `KernelScreen`) when it starts, before anyone joins. Attributes `BootScreen` and `KernelScreen` on
`ServerScriptService.TypeTorchKernel` win over the ones on `ReplicatedFirst`.
- On kernels before 0.3.8 the attributes do nothing: the kernel shows its own screen, and `ClientReady` never appears.
A script that must also run there can wait for `ClientReady` with a timeout.
- Studio playtests run the same code.
---
# Hot assets
Builders edit models and UI templates in the real place and publish it as usual. New servers get them from the place.
**Running servers get the new versions live, with no restart.**
Try a new hot asset on a dev branch first.
| Hot | Not hot |
|---|---|
| models, props, effects, tools, UI templates (anything your code clones) | maps (a map change is a place publish and a restart), terrain, lighting and settings, scripts |
Hot assets contain **no scripts**: sync refuses them, and the runtime strips any it finds.
## 1. Mark them in the place
In Studio, give the instance an attribute `TypeTorchAsset` (string) with a short key:
- keys use `a-z 0-9 / - _`, at most 64 characters: `ui/shop`, `fx/coin-burst`, `tools/sword`;
- each key is used once;
- no hot asset inside another one, and never on a service itself;
- **where it sits decides who sees it:** under ServerStorage or ServerScriptService it is server-only; anywhere else
(ReplicatedStorage, Workspace...) it replicates to clients.
Publish the place. (Or skip the publish: [from Studio](https://www.typetorch.dev/guides/hot-assets.md#from-studio-no-publish) below.)
## 2. Sync
```sh
bun run typetorch assets status
bun run typetorch assets sync
git add typetorch.assets.lock.json
git commit -m "Hot assets"
bun run typetorch deploy
```
`assets sync`:
1. runs a Luau Execution task on the place's **latest published** version (`--place-version ` picks another) and
exports every marked instance;
2. compares each export's hash with `typetorch.assets.lock.json`;
3. uploads a new key as a new group-owned Model, and a changed key as a **new version of the same asset id**, then
waits for moderation (the place itself is never changed);
4. resolves each new version's id;
5. writes `typetorch.assets.lock.json` only when everything worked (commit it).
- `status` (or `sync --dry-run`) shows what changed without uploading. `list` prints the lockfile. With `--json`
(CLI 0.15.0+), `status` also gives a bounded diff per new, changed or removed asset (instances added, removed or
changed, with old and new property values), against the copy of the lockfile's version kept in the state dir
(`.typetorch/hot-assets/.rbxm`).
- Moderation waits up to 600 s (`--moderation-timeout `).
- Before any upload, every problem is listed at once: bad or duplicate keys, scripts (named), nesting, a marked service.
- `--deploy ` deploys right after (`--message`, `--propose`, `--proposed-by`, `--no-registry` and the key
file flags are passed on). For a prod-channel branch it is refused while the lockfile changes: sync, commit, then
deploy (prod takes only clean builds).
- Every deploy stamps the lockfile into the build, so the asset list is part of the artifact (signed on prod), and a
rollback brings back the older asset versions.
- Needs the assets key with `asset:read`, `asset:write` and Luau Execution
(`universe.place.luau-execution-session:read` and `:write`).
- `bun run typetorch assets types` writes `src/shared/assets.gen.ts`: every key with its class, and a `HotAssetKey`
type, from the lockfile. Once the file exists, every sync refreshes it.
### From Studio (no publish)
The TypeTorch Studio plugin's **Hot assets** card does the same from the open place, with
[`typetorch serve`](https://www.typetorch.dev/guides/studio-testing.md#hot-assets-from-the-panel) running: select an instance, **Add** (it sets
`TypeTorchAsset`), then **Check** (`assets status`), **Upload** (`assets sync`) or **Publish to dev** (`assets sync
--deploy dev`). The plugin exports the marked instances itself, so unpublished edits count (`--studio-export` on the
CLI). Those entries record place version 0 in the lockfile, so new servers load them instead of adopting the place's
copies, until a sync from a published place records a real version again. Commit the lockfile as usual. While the
panel is open the check repeats every 30 seconds, and each changed row has a **Diff** button (CLI 0.15.0+).
## 3. Use them in code
```ts
import { hotAsset } from "@typetorch/framework"; // or TypeTorch.asset("ui/shop")
const shop = hotAsset("ui/shop");
shop.changed(rebuild, this.trove); // a new version went live
rebuild(shop.get());
```
`hotAsset(keyOrId, fallback?)` works on the server and the client and returns a handle:
| Member | What it does |
|---|---|
| `get()` | the live copy now; else `fallback` if it is still parented; else `undefined`. **Clone it; don't parent or edit it** (a new version destroys it) |
| `wait(timeout?)` | `get()`, waiting for a live copy |
| `changed(fn, trove?)` | calls `fn(instance)` when a new copy replaces the live one (a new version, a rollback, the first copy reaching a client); returns a disconnect. Pass the module's trove |
| `key`, `version` | the key, and the live copy's version |
- On every generation start, before any module loads, the server keeps, adopts (the place's own copy, when the place
version matches the lockfile, or, framework 0.5.3+, when the place's backup build vouches for it after a backup
refresh or kernel deploy) or loads (`LoadAssetVersion`) each asset. A loaded version gets the place copy's
CollectionService tags back. It waits at most 8 s; slower loads finish in
the background and fire `changed`.
- Clients never request anything: they watch the live copy's tag, and replicated assets arrive by replication.
- **Clones never count and never update by themselves.** A clone in PlayerGui, a Backpack or Workspace keeps working
with the old version until your code replaces it.
### Updating tools players already hold
Tools in a Backpack or a character are clones. Replace them when a new version goes live:
```ts
import { Players } from "@rbxts/services";
import { hotAsset, Module, Service, type OnPlayerAdded, type OnStart } from "@typetorch/framework";
const KEY = "tools/sword";
@Service()
export class SwordService extends Module implements OnStart, OnPlayerAdded {
private readonly sword = hotAsset(KEY);
onStart() {
this.sword.changed(() => {
for (const player of Players.GetPlayers()) this.replaceHeld(player);
}, this.trove);
}
onPlayerAdded(player: Player) {
// Replays on every swap: give one only when the player has none.
if (this.held(player).size() > 0) return;
const template = this.sword.wait(10);
const backpack = player.FindFirstChildOfClass("Backpack");
if (template && backpack) template.Clone().Parent = backpack;
}
/** The copies the player holds, in the backpack or equipped. Clones keep the TypeTorchAsset attribute. */
private held(player: Player): Instance[] {
const copies: Instance[] = [];
for (const container of [player.FindFirstChildOfClass("Backpack"), player.Character]) {
if (!container) continue;
for (const child of container.GetChildren()) {
if (child.GetAttribute("TypeTorchAsset") === KEY) copies.push(child);
}
}
return copies;
}
private replaceHeld(player: Player) {
const template = this.sword.get();
if (!template) return;
for (const old of this.held(player)) {
const fresh = template.Clone();
fresh.Parent = old.Parent; // the character if it was equipped, else the backpack
old.Destroy();
}
}
}
```
If a tool keeps state (ammo, durability), copy it from `old` to `fresh` before you destroy `old`.
### UI templates
```ts
const template = hotAsset("ui/shop");
let window: Frame | undefined;
const rebuild = () => {
window?.Destroy();
window = undefined;
const source = template.get();
const hud = Players.LocalPlayer.FindFirstChildOfClass("PlayerGui")?.FindFirstChild("Hud");
if (!source || !hud) return;
window = source.Clone() as Frame;
window.Parent = hud;
};
this.trove.add(() => window?.Destroy());
template.changed(rebuild, this.trove);
rebuild();
```
## Migrating existing templates
Code that clones templates from the place today:
```ts
const sword = ReplicatedStorage.WaitForChild("Assets").WaitForChild("Sword") as Tool;
sword.Clone().Parent = backpack;
```
becomes:
```ts
const sword = hotAsset("tools/sword", ReplicatedStorage.WaitForChild("Assets").WaitForChild("Sword"));
const copy = sword.get()?.Clone();
if (copy) copy.Parent = backpack;
```
Then:
1. In Studio, add `TypeTorchAsset = "tools/sword"` to the template and publish the place.
2. `bun run typetorch assets sync`, commit the lockfile, deploy.
3. Code that keeps clones around (tools held, open UI) listens to `changed` and replaces them (above).
The `fallback` keeps the code working before the first sync and on a server where the asset failed to load.
## In the dev menu
**Modules > Assets**:
- Server: each key with its source (KEPT, BAKED, LOADED, FAILED, LOADING), version, load time and last error;
- Client: the live copies this client sees.
Failures also show on Server > Status > Attention: "Hot asset failed" (the old copy was kept), "Hot asset missing"
(nothing is live for the key), "Asset manifest" (the stamped list is unusable).
---
# The dev menu
Every TypeTorch game has an in-game developer menu. It ships in the framework, so it updates with every deploy.
- **Open it:** the **DEV** button (devs only), `Ctrl+Shift+D`, or `/tt dev` in chat. Framework 0.6.2+ puts the DEV
button in Roblox's top-bar row, right of Roblox's own buttons, so it never covers a game's top-left HUD (without a
top-bar inset it falls back to the old spot under the bar). A dot on it (and on the Server tab) shows while the
server has warnings (yellow) or errors (red).
- **Find anything:** the [command palette](https://www.typetorch.dev/guides/dev-menu.md#command-palette) (`Ctrl+K`, `Cmd+K` on a Mac, or the search button in the
menu header).
- **Who:** devs only. The server decides and re-checks every request: the experience owner, `members` from
`typetorch.json` (after `typetorch access push`; kernel 0.3.8+), dev-badge holders, anyone in a Studio playtest;
minus `revoked`. Until the server has read the settings record once, members and badge holders are not devs (the
owner and Studio are).
- **Only devs receive the code** (framework 0.5.6+ with kernel 0.5.6+): the kernel leaves the framework's `devtools`
folder off the client tree every player gets, and the server copies it into each dev's PlayerGui (on join, on every
generation, and when someone becomes a dev). Other players never download the menu. On older kernels the folder is in
the shared tree as before. A failed copy costs that dev the menu, with a warning, never the generation.
- **Two roles:** **owner** (the experience's creator or the owning group's owner, `members` with the role `"owner"`,
and anyone in a Studio playtest) and **dev**. A `members` entry with the old role `"admin"` counts as a dev.
- **Prod servers are read-only:** the [dev-only tools](https://www.typetorch.dev/guides/dev-menu.md#dev-only-tools) are off there. Owners can still switch the
server they are in ([Server > Branch](https://www.typetorch.dev/guides/dev-menu.md#server)).
- The window can be dragged by its header and resized from its corner (double-tap the header to reset). It remembers
its panes and windows across swaps.
- The sidebar, top to bottom: Artifact, Server, Network, Modules, Manage, Logs, Dex, Claude.
- The header reads ` #` (in a code font), so a screenshot says which build and generation it
came from. The menu is a ScreenGui named `TypeTorchDev` in PlayerGui. Framework 0.5.2+ stamps it with a
`TypeTorchGeneration` attribute and destroys any `TypeTorchDev` from an older generation when it starts; two menus
on screen on an older framework means the old generation didn't stop cleanly
([Troubleshooting](https://www.typetorch.dev/guides/troubleshooting.md#live-servers)).
- Roblox games can't write to the clipboard, so every **Copy** opens a small box with the text selected: press
`Ctrl+C`, or long-press > Copy on touch.
## Dev-only tools
Framework 0.5.0+. Claude, Logs > Upload, Dex edits, Network packet blocking, Server > Experiments and
Modules > State's server state for devs who aren't owners, and the hot-swap sound work only:
- under dev rules (private, reserved and Studio servers on a dev branch): for every dev;
- on a public server an owner switched to a dev branch ([Server > Branch](https://www.typetorch.dev/guides/dev-menu.md#server)): for owners only.
Everywhere else (every prod server, so every normal public server) they are read-only and say why: "Dev branch only",
"Owners only on public servers" or "Owner-switched servers only". Owners keep server state and Server > Experiments
everywhere. The rules themselves don't change: `TypeTorch.channel`, signatures and owner-only rollbacks stay as they
are.
## Panes and windows
Show two pages at once, for example **Network > Packets** next to **Modules > State** (framework after 0.3.2).
- **Every page sits in a pane** with a small header: the page's name (tap it to pick another page) and four buttons:
**Split right**, **Split down**, **Open in new window** and **Close**.
- **Split** adds a pane beside or under this one, on the same page. Drag the line between two panes to resize them.
- **The sidebar opens pages in the focused pane.** Tap a pane to focus it; with several panes, the focused one has an
orange outline.
- **Windows** float over the game. Drag one by its title bar and resize it from its corner; double-tap the title bar
to maximise it. The title bar has **Minimise**, **Dock** (back into the main panel, next to the focused pane) and
**Close**. A window can be split too. Tap a window to bring it to the front. Windows show and hide with the menu.
- **Some pages open once:** Claude, Server > Branch and the Manage pages. Picking one again focuses its pane. Every
other page can be open in several panes, each with its own settings (two State panes can show two modules).
- **The layout survives swaps:** panes, windows and each pane's settings come back after a hot swap. A fresh join
starts with one pane.
- **Panes you can't see don't refresh:** closing the menu or minimising a window stops their requests. Panes on the
same data share one request, so two panes don't hit the server's limits.
- **Limits:** 6 panes in the main panel, 4 per window, 6 windows. On phones and small screens panes only stack (two at
most), and windows (3 at most) open maximised with one pane each.
## Command palette
Framework 0.5.7+. `Ctrl+K` (`Cmd+K` on a Mac), or the search button in the menu header (touch has no keyboard), opens
the menu if it is closed and a search box over every command you may run right now. The same keys close it.
- **Search is fuzzy:** each word you type must match a command's title, a keyword or its group, letter by letter in
order (`swdev` finds *Switch to dev branch*, `srv rel` finds *Reload this server*). On an empty query your recent
commands come first (8 at most), then the rest. Some commands (single builds, servers, players, experiments) only
show when you type.
- **Keys:** Up / Down pick, Enter runs, Shift+Enter opens a page in a split, Escape closes. Clicking a row runs it
(Shift+click: in a split).
- **Never while typing:** the hotkey does nothing while chat or a text box has focus.
- **Two steps for anything that swaps what runs on the server** (reload, roll back, switch, load a build, migrate):
the first Enter or tap arms it and the status line says what will happen ("Reload this server (4 players) to its
branch head?"); a second one within 4 s runs it. The status line then follows the action.
- The palette shows only what you may do, but that is cosmetic: the kernel and the server re-check every request.
| Group | Commands | Who |
|---|---|---|
| Pages | open any page in the focused pane (Shift+Enter: in a split) | dev |
| Panes | Split right, Split down, Open pane in new window, Close pane, Dock all windows | dev |
| Server | Switch to dev branch (or Join a dev branch server; framework 0.6.1+), Reload this server, Roll back this server, Migrate all players to a new server (0.6.1+), New server on this branch (moves only you) | the Branch tab's and Server > Status' rules; New server: owners |
| Branches / Builds | one per [Server > Branch](https://www.typetorch.dev/guides/dev-menu.md#server) row with a button: Switch, Load here, Join, with the same words | the Branch tab's rules |
| Servers | Join server `` (a listed server) | owners |
| Players | a player by name, display name or UserId (opens them in Manage > Players), Kick / Ban (opens their card), Player: Teleport to / Bring / Respawn (0.6.1+; "Player: Respawn me" lists without typing) | owners |
| Experiments | Experiment ``: use ``, Experiment ``: clear my variant ([Server > Experiments](https://www.typetorch.dev/guides/dev-menu.md#server)) | devs where the dev-only tools are open; owners everywhere |
| Copy | job id, artifact id, commit, branch, place version (the copy box) | dev |
| Claude | Ask Claude: `` puts it in the [Claude tab](https://www.typetorch.dev/guides/dev-menu.md#claude)'s draft | dev |
"Switch to dev branch" is the branch named `dev`, else the only dev-channel branch; it doesn't show when the server
already runs it or when there are several dev branches and none is named `dev`.
## Tabs
### Artifact
- The build this client and this server run: artifact id, branch, channel, commit, build time, `#seq`, asset id, and
the notes ("what changed": your `--message` and the commits since the last deploy).
- **How long things have run:** "Running" for the client generation and for the server generation, "Server up" (the
server's uptime), and "Built" with the build's age ("2026-10-05 17:51:37 UTC (8m ago)"). They update every 5 s.
- The generation (`#`) and this server's history of swaps with their timings.
- **Verified badges:** two after the server artifact when both signatures check out (Root Key and Fallback Key), one
when only one does, none for unsigned dev builds.
- **Signing** (kernel 0.3): the mode ("Root Key", "Fallback Key only" or "No keys"), whether this server is
signed-only, the key asset and its version, the last key load and error, the last key change, "Rejected" (count and
last reason), the public, revoked and fallback keys by fingerprint (tap to copy), the bootstrap heads, and "No
trusted prod head" when there is none.
### Modules
A sidebar group with a **Server | Client** toolbar:
- **Overview:** every running module, its lifecycle hooks, dependencies and `onInit` time.
- **State** (framework 0.3.2): a live state explorer. The roots are every running module (services on the server,
controllers on the client) and the `persist` store. Tap a row to open it: a module's own fields, then tables, arrays,
Maps and Sets, 100 entries per page (Prev / Next).
- Each value has a short preview: strings, numbers, booleans, nil, datatypes, an Instance as its full path, a Player
as its name, `function`, `thread`, buffer sizes.
- Raw reads only: no metamethod, getter or function ever runs. A value that is its own ancestor shows as a cycle,
with its path.
- A key filter (open rows stay listed), Refresh, and Auto (every 2 s).
- Server state: owners everywhere, other devs only where the [dev-only tools](https://www.typetorch.dev/guides/dev-menu.md#dev-only-tools) are open to them
(server state can hold player data). Rate-limited and size-capped.
- **Assets:** [hot assets](https://www.typetorch.dev/guides/hot-assets.md): each key, its source (KEPT, BAKED, LOADED, FAILED, LOADING), version,
load time and last error; on the client, the live copies it sees.
### Server
- **Status:** JobId, server type, uptimes, the build's health window ("3 errors / 30 s"), place version, players,
memory, server TPS (kernel 0.4.2+), the last deploy message and how long it took to arrive, recent swaps, and (kernel
0.3.8) **Settings**: the [signed settings record](https://www.typetorch.dev/guides/settings.md) this server holds ("#12, 3m old (sig)"). The senders
to your backend each get a line: *Fleet API*, *Error reports* (kernel 0.4.0+) and *Analytics* (with an
`AnalyticsEngine`), plus *Detached jobs* (kernel 0.3.8+) and the kernel version with its API. **Attention** lists
what needs a look, and the tab shows a **badge** (red for errors, yellow for warnings):
| Attention item | Meaning |
|---|---|
| Kernel update (with **Migrate**) | this server's kernel is older than the newest kernel this framework release knows (0.5.3 in framework 0.7.1): republish the place with the new kernel, then Migrate moves everyone here to a fresh server |
| Kernel update required (with **Migrate**) | the kernel's API is too old for this framework (same fix) |
| No game running | no build is mounted on this server |
| Failed health check | a new build failed its health window here in the last 15 minutes and the server went back to the last good one ([safe deploys](https://www.typetorch.dev/guides/deploy-and-rollback.md#the-health-window-and-the-last-known-good-build)) |
| Errors n | the running build keeps erroring after its health window |
| Health window | the new build's window is open: its errors against its limit and the time left, e.g. "1/3 errors, 24 s left" (yellow once an error counted; "no rollback" when [`health`](https://www.typetorch.dev/guides/deploy-and-rollback.md#set-the-health-window) turns it off) |
| Health settings / No health window | the build's health values were out of range (defaults used) / the place doesn't map the kernel's Health module |
| Rolled back | an automatic or server rollback happened in the last 15 minutes |
| Clients failed n / Clients moved n | some players' client side of the build failed to start / those players were moved to another server because their game didn't load here |
| No fleet API / Fleet settings / Fleet API failing | the kernel can't send to the [fleet API](https://www.typetorch.dev/guides/fleet-and-alerts.md#in-the-dev-menu) |
| No deploy reports | the kernel is older than 0.3.2 |
| Booted an unverified prod head | the [boot fail-safe](https://www.typetorch.dev/guides/prod-signing.md#the-boot-fail-safe) ran an unsigned stored build |
| No trusted prod head | nothing verified for this branch; waiting for a signed deploy |
| Keys changed / Keys rotated / Fallback Key revoked / Fallback Key only / No signing keys / Rejected n | signing state ([Prod signing](https://www.typetorch.dev/guides/prod-signing.md)) |
| Hot asset failed / Hot asset missing / Asset manifest | [hot assets](https://www.typetorch.dev/guides/hot-assets.md) |
| Analytics failing xn / Analytics settings / Analytics dropped n | the [analytics](https://www.typetorch.dev/guides/analytics.md) uploads fail (with the reason, the fix and the next retry), its settings are invalid, or rows were lost |
| HTTP off | the Claude tab and the fleet API need Allow HTTP Requests |
| run_luau off | `LoadStringEnabled` is off (dev servers; right for a live game) |
| Pinned / A/B experiment | this server holds a pinned build |
| Studio: local payload | a Studio session runs your local code ([Testing in Studio](https://www.typetorch.dev/guides/studio-testing.md)) |
| Running the backup build / Moving players out / Backup build failed | [never an empty server](https://www.typetorch.dev/guides/deploy-and-rollback.md#never-an-empty-server): nothing else could run, the server runs the place's backup build, or moves players out |
| Detached job slow / Detached jobs near the cap | [`TypeTorch.runDetached`](https://www.typetorch.dev/guides/player-data.md) jobs run long or near the 256 cap |
| Registry, High memory | the settings record can't be read; the server uses a lot of memory |
| No settings / Settings refused / Settings unreadable / Settings copy refused | the [settings record](https://www.typetorch.dev/guides/settings.md) is missing, doesn't verify, can't be read, or a newer copy was refused while a good one is kept (`typetorch settings status`) |
| Messaging offline / Messaging busy / Messages dropped | [`TypeTorch.messaging`](https://www.typetorch.dev/guides/messaging.md): the kernel can't subscribe, the universe's topic is near its rate limit, or messages were given up |
- **Branch:** this server (type, branch, channel, the running build, whether it is pinned, and `switched by
` after an owner's switch), the known branches, and the deployed builds, newest first, grouped by branch (tap a
row to see what changed). Framework 0.5.2+ labels each group with the branch's own channel, plus ` artifact`
when the group's newest build has another one (a promoted prod build on a dev branch); older frameworks print the
channel of the group's first build. The full record per `#seq` (`action`, `channel`, `by`) is `deployments.jsonl`
([the deployment log](https://www.typetorch.dev/guides/deploy-and-rollback.md#the-deployment-log)). A row's button says what it does:
- **Switch** (a branch): this server follows that branch. **Load here** (a build): this server runs it (a pin).
Both take two taps: a green Confirm, then a locked "Switching..." or "Loading...". Everyone stays in the game.
- **Join:** moves only you to a reserved server on that branch or build. Devs who aren't owners get it on public
servers.
- **Owners** get Switch and Load here on every server, public and prod included (kernel 0.3.4 and framework 0.3.2).
On a public server a switch lasts for this server's lifetime only; new servers still boot `prod`. To go back,
switch to `prod`. Details: [Branches and channels](https://www.typetorch.dev/guides/branches-and-channels.md#owners-switch-any-server-in-place).
- **Devs** get them on private and reserved servers of dev branches.
- Reload and Rollback as before. The dev menu allows one swap (reload, switch, rollback, load) per server every 2 s.
- On older kernels, prod servers show "Use the CLI: typetorch pin" instead of in-place loads.
- **Budget** (kernel 0.4.0+): what TypeTorch spends of this server's DataStore, MemoryStore, HTTP and MessagingService
limits in the last minute, as bars against Roblox's limits for the player count; who spends it (kernel, devtools,
analytics, framework, game); the DataStore budget left (shared with your game's own requests); and memory. Older
kernels show one line.
- **Experiments** (framework 0.7.1+): pick your own variant of an [analytics](https://www.typetorch.dev/guides/analytics.md) experiment. The page lists
every experiment the game asked about for you (or that the settings name), the variant you're in and why ("random",
"forced by the settings", "your pick"), a button per variant and **Clear**. The palette has the same commands.
- It only ever changes your own variant, at most one change a second, and only to a variant the game passed to
`experiment(...)`. Owners everywhere; other devs where the [dev-only tools](https://www.typetorch.dev/guides/dev-menu.md#dev-only-tools) are open.
- The pick is stored in the analytics DataStore (`TypeTorchAnalytics`, key `dexp/`, 32 experiments at most),
so it follows you to every server. It wins over the signed settings (stop, settle, weights, `players`).
- Your experiment rows are stamped `forced` while it holds, so the backend leaves you out of the results.
- The game sees it the next time it asks for your variant, usually your next join ("Rejoin to see it if the game
asked already").
- While the rule doesn't allow you (a dev on a prod server, a revoked role), a stored pick is ignored. "Set for this
server only" means the DataStore write failed. Without an `AnalyticsEngine` the page says "Analytics isn't running
on this server."
### Manage
Owners only. (Called **Admin** before framework 0.3.2.) Players, Servers and Bans. Every action is re-checked on the
server, logged, and rate-limited.
- **Players:** each player's role, user id and ping, and the actions: Teleport to, Bring, Respawn, Kick (with a
reason), Ban (1 h, 1 d, 7 d or permanent; alt accounts too by default).
- **Servers:** the game's live servers (type, branch, channel, build, players, uptime), found by a MessagingService roll
call when you open the list (3 s, cached 15 s; no storage; game code gets the same list from
[`TypeTorch.servers()`](https://www.typetorch.dev/guides/messaging.md#the-server-list)). A summary line per build says how many servers and
players run it. Join a server, open a **New server** on this branch, **Shut down** a server, **Migrate** this server.
- **Load a build...:** pick a build, then where it runs:
- **This server** (players stay);
- **Selected servers** (tick them in the list);
- **Share of a branch's servers** (5, 10, 25 or 50%, stable per server).
One summary line says it ("Load #36 on 2 servers"), and the button says the action. A status line under the list
follows it ("Loading #36 on 2 servers", "Done: 2 switched"). Other servers on prod take only signed pins, so the card
says "Other prod servers: typetorch pin" ([pins](https://www.typetorch.dev/guides/deploy-and-rollback.md#pins-ab-experiments)).
- **Back to branch head:** ends the pins on the picked servers, or every A/B server of a branch.
- **Bans:** unban by user id, and a user's ban history.
### Logs
The server's log, your own client's log, and **Others** (another player's client log, fetched on demand). Filter by
level and text; errors are pinned. Dev builds carry `[file:line]` on `$print` lines. Kernel notes (`[TypeTorch] ...`
info lines) are dim.
**Upload** (framework 0.3.2) sends the log shown to the dev PC paired in the [Claude tab](https://www.typetorch.dev/guides/remote-claude.md), which
saves it under `/.typetorch/logs/` and prints one line. No Claude run, no prompt used. Not paired: "Pair in the
Claude tab first".
### Dex
A client and server explorer: the instance tree, properties (from `ReflectionService`), attributes and tags. Selecting an
instance highlights it in the world. Right-click or long-press a row for Copy value, Copy name or Copy path (a path you
can paste into code). Editing (properties, attributes, tags, delete, clone, move) is a
[dev-only tool](https://www.typetorch.dev/guides/dev-menu.md#dev-only-tools) and is logged.
### Network
- **Packets:** a remote spy for your `createNetwork` traffic: time, direction, path, kind (fire, invoke, response,
unreliable), player, size, the guard's verdict (accepted, or why it was rejected), and the decoded arguments. Filter,
pause, search, and (where the [dev-only tools](https://www.typetorch.dev/guides/dev-menu.md#dev-only-tools) are open) block one path on your client. Nothing is
captured while nobody watches.
- **Stats:** per network leaf, messages in and out, rejected and errors, for the server and your client.
### Claude
Chat with Claude Code running on your own PC, where the [dev-only tools](https://www.typetorch.dev/guides/dev-menu.md#dev-only-tools) are open:
[remote-claude](https://www.typetorch.dev/guides/remote-claude.md).
## `/tt` commands
They work even when a build is broken. Devs only.
| Command | What it does | Who |
|---|---|---|
| `/tt status` | branch, channel, generation, uptime, kernel build, signing mode | dev |
| `/tt branch ` | switch this server to a branch | devs on private or reserved servers; owners on any server |
| `/tt new [assetId]` | open a reserved server on a branch and teleport you | dev |
| `/tt reload` | load the branch head again | dev |
| `/tt rollback` | back to this server's previous build | dev; owners on prod-channel servers |
| `/tt pin ` / `/tt unpin` | hold this server on a known build / release it | devs on dev servers; owners on any server |
| `/tt bundle` | send a [debug bundle](https://www.typetorch.dev/guides/fleet-and-alerts.md#errors-debug-bundles-and-remote-debug) of this server to the backend (kernel 0.5.3+) | dev |
| `/tt dev` | open the dev menu | dev |
| `/tt` / `/tt help` | list the commands | dev |
---
# Player feedback
`TypeTorch.feedback()` takes a player's rating and/or text on the game server, checks it, and writes one analytics row
(`kind = "feedback"`, `name = "submit"`). The explorer's **Feedback** page reads those rows: the rating distribution
in the scale's own shape, the trend, and the list with the player, device and context. Framework **0.7.0** and later;
backend from `1484bd5` (plans/32).
You build the UI (a modal, faces, stars, a thumbs bar) and the remote. The framework does the rest: rating checks,
text sanitising and caps, per-player rate limits, and the row.
## Submit
```ts
import { TypeTorch } from "@typetorch/framework";
const feedback = TypeTorch.feedback(); // server only (throws on a client)
// Optional, once at start: the scale in code, used while the settings record has no game.feedback.
feedback.configure({
scale: { id: "faces5", type: "scale", steps: 5, labels: ["BAD", "MEH", "OK", "GOOD", "GREAT"] },
maxText: 1000,
rate: { perMinute: 2, perDay: 20 },
});
// In your remote's handler. The arguments come from a client: everything is checked here.
const result = feedback.submit(player, { rating, text, topic: "bug", ctx: { level: 12, map: "forest" } });
if (!result.ok) {
// "rate_limited" | "empty" | "bad_rating" | "no_session" | "disabled"
if (result.reason === "rate_limited") showTryAgain(result.retryIn ?? 60); // whole seconds
}
feedback.scale(); // the scale in effect, to send to clients for the UI (undefined while disabled)
```
| Input | Meaning |
|---|---|
| `rating?` | thumbs: `0` (down) / `1` (up); stars / scale: an integer `1..steps`. Leave it out for text-only feedback |
| `text?` | free text; control characters stripped, whitespace collapsed, trimmed, capped at `maxText` characters and 2000 UTF-8 bytes |
| `topic?` | a category, 1-32 of `[a-z0-9_]` (`bug`, `idea`); anything else is dropped with a warning |
| `ctx?` | your own context, at most 8 keys of 1-24 `[a-z0-9_]`, values a string (64 characters kept), number or boolean |
| Refusal | When |
|---|---|
| `rate_limited` | over the per-minute or per-day limit (`retryIn`: seconds until a submit fits again) |
| `empty` | no rating and no text left after sanitising |
| `bad_rating` | not an integer in the scale |
| `no_session` | no analytics engine runs, or the player has no session in this server |
| `disabled` | switched off, an invalid config, or edit mode |
`submit` never yields. Only accepted submits count against the limits. The limits are per player, in memory, and
reset when the player leaves the server.
## The scale
Declare the scale once. The settings record's `game.feedback` wins (live, no deploy:
`typetorch settings set game.feedback ''`); without it, the game's `configure(...)`; without that, the defaults.
```jsonc
// game.feedback: a 5-step faces scale
{
"scale": { "id": "faces5", "type": "scale", "steps": 5, "labels": ["BAD", "MEH", "OK", "GOOD", "GREAT"] },
"maxText": 1000,
"rate": { "perMinute": 2, "perDay": 20 }
}
```
| Field | Default | Meaning |
|---|---|---|
| `enabled` | `true` | `false`: every submit answers `disabled` |
| `scale.id` | `"stars5"` | 1-32 of `[a-z0-9_]`, stamped on every row |
| `scale.type` | `"stars"` | `thumbs` (0 / 1), `stars` or `scale` (1..steps) |
| `scale.steps` | `5` | 2..10; thumbs is always 2 |
| `scale.labels` | none | exactly one per step, lowest first, 1-32 characters each (thumbs: e.g. `["Down", "Up"]`) |
| `maxText` | `1000` | characters of text kept (1..2000) |
| `rate.perMinute` / `rate.perDay` | `2` / `20` | accepted submits per player (1..1000 each) |
`game.feedback` set to `false` turns feedback off, like `"enabled": false`. An invalid `game.feedback` disables
feedback and warns once (an invalid `configure` throws).
**Changing the scale later:** give the new scale a new `id`. Every row carries its own scale (`scale`, `type`, `steps`,
`label`), so old rows keep rendering as they were, and the page shows one distribution per scale. Averages and the
trend across scales use `norm` (the rating as 0..1).
## The row
| Prop | Meaning |
|---|---|
| `scale`, `type`, `steps` | the scale in effect |
| `r?` | the rating (left out for text-only) |
| `norm?` | `r` as 0..1: thumbs `r`, stars / scale `(r - 1) / (steps - 1)` |
| `label?` | the rated step's label |
| `text?`, `len` | the sanitised text, and the original length in characters (0 = none) |
| `topic?`, `ctx?` | as passed |
| `play_s` | seconds played in this session so far |
Device (`dev`), state (zone / screen / activity), session and the player's id come from the engine, as on every row.
The row has no UserId or username field, but it is not anonymous: the pid links it to the player's UserId, and the
explorer finds the player from it (the identity store). The text is what the player wrote. The full contract is
in the framework's `src/analytics/SCHEMA.md`.
## The Feedback page
In the [explorer](https://www.typetorch.dev/guides/explorer.md) next to Notifications. Like Notifications, it has its own range picker instead of the
shared filter bar:
- **Distribution** per scale: thumbs as up / down shares; stars and scales as a histogram with the step labels and the
average.
- **Trend**: the count and the average `norm`, per hour for ranges of 2 days or less, per UTC day otherwise.
- **List**, newest first: the rating in its scale's shape, the text, the player (opens the player panel), when, device,
play time, state, topic and context. Filters: rating, has text, device, text search.
- **Player panel**: a Feedback view with that player's feedback.
Queries for your own tools: `feedback-summary` and `feedback-list` (`POST /v1/query/`; the backend README lists
their options). A [support key](https://www.typetorch.dev/guides/api-keys.md) reads a player's feedback when `feedback` is in `players.supportEvents`
(not in the default list).
## Moving from a custom event
Games that wrote feedback as `kind = "custom"`, `name = "feedback"` with props `{ rating: 1..5, text, length }` don't
need a migration: the backend reads those rows as the scale `legacy_faces5` (BAD / MEH / OK / GOOD / GREAT), marked
legacy, next to the new rows. To switch: update to framework 0.7.0, replace the custom event with
`feedback().submit(...)` (and your own rate limiting with the config's `rate`), and use a new scale `id` (e.g.
`faces5`).
---
# Deploy and rollback
All commands run from your game folder. `bun run typetorch --help` shows every flag.
## Deploy
```sh
bun run typetorch deploy --dry-run
bun run typetorch deploy
```
What `deploy` does, in order:
1. **Clean build:** removes ignored files from `out/` and `include/`, puts the build cache back (below), writes
`src/shared/build.ts`, runs the [compiler](https://www.typetorch.dev/guides/deploy-and-rollback.md#compiler) (goblox or rbxtsc; prod channel: debug prints and source paths
removed), packs a [production copy](https://www.typetorch.dev/guides/deploy-and-rollback.md#production-pack) of the output, builds `.typetorch/payload.rbxm` with Rojo, and
checks it holds only Folders and ModuleScripts.
2. **Upload** as a new private Model asset owned by `creator`, and wait until moderation says Approved.
3. Log it as "uploaded" (`uploads.jsonl` in the state dir), so a later step can't lose it.
4. **Cloud test** (always for prod-channel branches; [below](https://www.typetorch.dev/guides/deploy-and-rollback.md#the-cloud-test)): the build boots headless in your place.
5. **Approval** (below): a y/N at your terminal, or a proposal.
6. **Sign** (prod-channel branches only; [Prod signing](https://www.typetorch.dev/guides/prod-signing.md)).
7. Take the next `#seq` (claimed from the game's DataStore), publish the deploy message, store the head in the game's
DataStore (the **durable head**, so servers that start later or missed the message boot it), log "published" in
`deployments.jsonl`.
8. **Wait for the servers' reports** (prod-channel branches, by default; [below](https://www.typetorch.dev/guides/deploy-and-rollback.md#wait-and-automatic-rollback)).
Live servers on that branch swap within about 1 to 2 seconds; public servers wait a random 0 to 10 s first so they
don't all load at once. Measured end to end: about 7 to 9 seconds from the command to players on the new build, plus
about 11 s for the cloud test on prod.
Useful flags: `--branch `, `--channel prod|dev`, `--message ` (shown in the dev menu), `--no-build` (deploy
the last build), `--force` (a dev-channel or dirty build to a prod-channel branch), `--test` /
`--skip-test ""`, `--wait [s]` / `--no-wait`, `--rollout <1-99>` (dev-channel branches), `--propose` (write a
proposal even at a terminal), `--no-minify` (skip the [production pack](https://www.typetorch.dev/guides/deploy-and-rollback.md#production-pack)), `--moderation-timeout `.
**Build cache.** After a clean build, `out/` and the compiler's `tsconfig.tsbuildinfo` are kept in
`.typetorch/build-cache//`, with a hash per file. The next clean build puts them back and the compiler
recompiles only what changed (seconds for a one-file edit). It is dropped when a file fails its hash or `tsconfig.json`,
`package.json` or a lockfile changed; dev and prod never share one. Switching to goblox, or to another goblox version, is
one full compile. It needs `"incremental": true` with the tsbuildinfo inside `outDir`. `TYPETORCH_BUILD_CACHE=0` turns
it off.
### Compiler
The build compiles with **goblox** (roblox-ts ported to Go: the same flags, `out/` layout and incremental builds, several
times faster) when it is installed in the game repo, else with **rbxtsc** (CLI 0.16.0+). goblox is optional:
```sh
bun add -d goblox
```
Which one runs, first match wins:
| Source | Value |
|---|---|
| `TYPETORCH_COMPILER` (environment or the game repo's `.env`) | `goblox` or `rbxtsc` |
| `typetorch.json` `"compiler"` | `goblox` or `rbxtsc` |
| `node_modules/.bin/goblox` exists | goblox |
| otherwise | rbxtsc |
- goblox asked for but not installed fails the build; it never falls back to rbxtsc. Any other value is an error.
- goblox runs `@typetorch/transformer` itself (from the same tsconfig `plugins` entry) and **ignores every other JS
tsconfig plugin**. Need one of those? Set `"compiler": "rbxtsc"`.
- `build`, `upload` and `deploy` print the compiler and its version (`compiler goblox `). `typetorch doctor`
shows which compiler runs and why, and warns when goblox would skip a plugin in your tsconfig.
### Production pack
`build`, `upload` and `deploy` don't upload the compiler's output as it is. The CLI packs a transformed copy into
`.typetorch/pack/` first, so the artifact id, the signature and the cloud test all cover the final bytes (CLI 0.17.0+,
both channels):
1. **Strip:** comments and whitespace go, but every line stays where it was, so error traces and analytics still point
at the right line. The compiler's header comment stays.
2. **Define:** `__DEV__` becomes `false` and its dead branches are removed, on dev-channel builds too. React reads
`__DEV__` (default `false`), so its dev-mode checks and warnings are gone from every uploaded build. If game code sets
it (`_G.__DEV__ =` or `ReactGlobals.__DEV__ =`), this step is skipped with a warning and your value stands. `--no-minify`
also leaves `__DEV__` to be read at runtime.
3. **Shake:** `*.story` modules that no other module names are left out. Packages are never shaken.
- It needs **darklua** (`rokit add seaofvoices/darklua`; `TYPETORCH_DARKLUA` in the environment names another binary).
Without it the build warns `darklua not found: this payload isn't minified` and uploads the unpacked output. A darklua
error fails the build.
- Each module's result is cached by content hash in `.typetorch/build-cache/pack/`, so an unchanged rebuild only hashes.
- `--no-minify` on `build`, `upload` or `deploy` turns it off. The darklua warning also suggests `"minify": false` in
`typetorch.json`, but the CLI (0.17.0 through 0.19.0) drops that key as unknown (`unknown key "minify" (ignored)`),
so it has no effect yet: use `--no-minify`.
- `typetorch serve` never packs: Studio syncs the compiler's output.
### Artifact ids and the deployment number
- **Artifact id:** `-`, for example `12b63b9-3fa91c`: the git commit plus the first 6 hex of the
payload's hash. A build from uncommitted changes is `-dirty-`. Same bytes, same id.
- **Deployment number:** `#seq`, one counter for the whole game. It's the handle to paste when something goes wrong.
Every machine takes it from the game's DataStore (a counter claimed atomically), so two machines never share one;
the deploy key needs the DataStore scopes for that ([fresh setup step 6](https://www.typetorch.dev/getting-started/fresh-setup.md#6-the-open-cloud-api-key-owner)).
Every release on every branch takes the next one (deploys, promotes, rollbacks, automatic rollbacks, `keys`
re-signs), so one branch's numbers jump: `#41` then `#47` is normal.
- The asset is named `tt--`. If Roblox's text filter censors the name to `####`, the CLI renames
it `TypeTorch payload`. The notes (your `--message`, the commits since the last deploy, and framework and kernel
changes: a new npm version, or the new commits when you build with the
[local override](https://www.typetorch.dev/getting-started/fresh-setup.md#unreleased-framework-or-kernel-changes-optional)) live in the
payload's `Notes` attribute, and the dev menu shows them.
- **Protocol:** `build` and `deploy` print `protocol unchanged since #N` or `protocol changed since #N`. The
`ProtocolHash` covers your `createNetwork` interfaces and the framework's wire format. When it is unchanged, kernel
0.3.2+ lets client messages sent during a swap reach the new build instead of dropping them.
## Approval and proposals
`typetorch.json` `"approval"` decides which deploys wait for a person:
| Value | Needs approval |
|---|---|
| `all` (default) | every deploy, rollback, promote and pin |
| `prod` | only those to prod-channel branches (the template's choice) |
| `none` | nothing |
- **You at a terminal:** `deploy` (or `rollback`, `promote`) goes straight to a **y/N** after the upload. One command.
- **Anyone else** (an agent, a script, the remote-claude dev-server, or `--propose`): the build is uploaded and a
**proposal** is written to `proposals.jsonl` in the state dir. Nothing is published. It expires after 24 hours.
```sh
bun run typetorch proposals
bun run typetorch approve
bun run typetorch approve 1a2b3c4d
bun run typetorch reject 1a2b3c4d --reason "wrong branch"
```
- **A proposal is a whole build, not a diff.** Each one is the full tree at its commit, so the newest proposal for a
branch already holds everything in the older ones. Approve the newest; approving an older one after a newer one went
out is a downgrade. Reject the older ones (`reject` works on pending proposals only: one already approved or
rejected says "already approved").
- With `"approval": "prod"`, dev-channel branches need no approval at all: a deploy from an agent or a script publishes
at once, with no proposal.
`approve` refuses unless it runs in an interactive terminal. It lists pending proposals, shows the branch, artifact,
notes, size, who proposed it and what it replaces, asks y/N, then publishes it like a deploy (and signs it for prod).
A prod proposal without a passed cloud test runs the test before the y/N. `--proposed-by ` (or
`TYPETORCH_PROPOSED_BY`) labels who prepared it.
Approval is enforced by the CLI. On dev-channel branches, anything holding a key with messaging publish could still send
a deploy message; prod is protected by the signatures ([Security model](https://www.typetorch.dev/guides/security.md)).
## Safe deploys
A bad build should never take a game down. Five layers catch it, from before the publish to after it.
### The cloud test
Before anything is published, the CLI boots the uploaded build in one Open Cloud **Luau Execution** task on your
place's latest published version (what live servers run): it loads it the way servers do, runs the kernel's mount
checks, boots the server side with a stub kernel (`onInit`, `onStart`), requires every Shared module, runs it for 5 s,
stops it, and boots it a second time as a swap would. Any error fails it. It takes about 11 s.
- **Always on for prod-channel deploys and promotes.** Elsewhere add `--test`. A pass of the same asset in the last 24
hours counts.
- `--skip-test ""` publishes without it; the reason goes into the deploy log.
- `bun run typetorch test --cloud []` runs it alone.
- **Your code runs against real data there:** DataStores, MemoryStores, MessagingService and HttpService work in a
task (with no players). Place scripts don't run. Code that must not run in the test can check
`workspace:GetAttribute("TypeTorchTest")`: [what to guard](https://www.typetorch.dev/getting-started/migrate.md#the-cloud-test-runs-your-game-code).
- **It runs as channel `dev`** (CLI 0.7.3+): the stub kernel reports `TypeTorch.channel = "dev"` (a reserved
server) whatever the branch, so stores you split by channel point at dev data. The payload's own `Channel` is still
checked (prod branches take only prod builds).
- **Analytics sends nothing from it** (framework after 0.3.2): the `AnalyticsEngine` collects as usual but never
uploads, so a prod deploy adds no fake server session.
- Needs the Luau Execution scopes on the assets key ([fresh setup step 6](https://www.typetorch.dev/getting-started/fresh-setup.md#6-the-open-cloud-api-key-owner)).
### The health window and the last known good build
On every server (kernel 0.3.2+):
- **Load retries:** a build that fails to load is retried after 5 s, 15 s, then three times a minute apart, and servers poll their branch's head
every 60 s, so a server that missed a message catches up.
- **Health window:** a new build is rolled back on that server when an `onStart` fails, or when its own scripts throw 3
errors within 30 s of starting. Errors from place scripts or the kernel never count. Later errors only mark the
server `degraded`. With kernel 0.3.7+ you can change both numbers, or turn the rollback off
([below](https://www.typetorch.dev/guides/deploy-and-rollback.md#set-the-health-window)).
- **Last known good:** the server then runs the newest build that worked: its own history first, then the branch's
deployments (on prod, only verified ones), skipping builds that already failed there. A failed build isn't retried on
that server; the next deploy is.
- **Boot budget:** a new server runs a playable build within **15 s** of starting, whatever fails (about 2 s
normally). Slow reads don't stack up; a head that runs out of boot time is skipped for the next good one, retried in
the background and swapped in when it works.
### Set the health window
Some games throw harmless errors all the time: a `WaitForChild` timeout, a nil index in a UI handler. With 40 players,
every server can hit 3 errors in the first 30 s. Then every server rolls the new build back, and `--wait` rolls the
branch back too. Every deploy fails.
Fix the errors if you can. If not, set the window in `typetorch.json` (CLI 0.7.5+, kernel 0.3.7+):
```json
"health": { "errors": 10, "window": 30 }
```
- `errors`: how many errors from the new build roll a server back. 1 to 100, default 3.
- `window`: seconds after the build starts. 5 to 300, default 30.
- `rollback`: `false` keeps a failing build running. The server only reports `degraded` (a `health_degraded`
warning). A failed `onStart` doesn't roll back either. Load and start failures still do.
- `prod` and `dev` change any of these for builds of that channel, for example
`"health": { "errors": 10, "dev": { "rollback": false } }`.
How it works:
- Every build carries its own values: `typetorch build` stamps them on the payload (`HealthErrors`, `HealthWindow`,
`HealthRollback`). A change needs a new build. `build` and `deploy` print them, `doctor` shows them.
- Values out of range stop the build. Kernels before 0.3.7 ignore them (3 errors, 30 s).
- In the dev menu, **Server > Status** shows the open window under Attention ("Health window: 1/10 errors, 24 s
left") and the build's values in the Server block.
Measure first: [count your errors on a dev soak](https://www.typetorch.dev/getting-started/migrate.md#count-your-errors-before-you-ship).
### Wait and automatic rollback
After the message, `--wait` follows the servers' deploy reports through the [fleet API](https://www.typetorch.dev/guides/fleet-and-alerts.md):
- **On by default for prod-channel branches** (90 s); off for dev (`--wait` turns it on, `--no-wait` off). It works on
`deploy`, `promote`, `rollback` and `approve`. Without the fleet API it is skipped with a note.
- It polls every 5 s until every live server on the branch has reported the new `#seq`.
- **Resend:** at about 30 s, if servers are still behind and silent, it sends the same message again (same `#seq` and
signature; servers ignore one they already applied).
- **Automatic rollback:** when 20% or more of the servers that tried the build report `failed` or `rolled_back` (at
least one), the CLI rolls the branch back to the previous build, the same way `typetorch rollback` does (signed on
prod), raises a critical `auto_rollback` alert, waits for the rollback's own reports, and exits 1. At a terminal it
first shows "rolling back ... in 10 s: Ctrl+C keeps the new build".
- **Change the threshold:** `"autoRollback": { "failedPct": 30 }` in `typetorch.json` sets it for every release (1 to
100). `--rollback-at ` changes it for one command; `--no-auto-rollback` turns it off. The output says which
one it uses ("auto-rollback at 30% ... (typetorch.json autoRollback.failedPct)").
- Failures below the threshold: a red summary, the rollback command, exit 1.
- **Servers that only stall never cause a rollback** (the build isn't proven bad): they are listed, a `server_stuck`
warning is raised, and the command exits 0 with a warning.
### Deploy reports
Every server reports what it did with each deploy: `booted`, `swapped`, `failed`, `rolled_back` or `skipped`.
```sh
bun run typetorch report latest
bun run typetorch report "#42"
bun run typetorch servers --branch prod
```
`report` shows the counts per result, the errors with the servers that hit them, and the servers still on an older
`#seq`; it exits 1 when one failed or rolled back. More in [Live servers and alerts](https://www.typetorch.dev/guides/fleet-and-alerts.md).
### Rollouts (dev branches)
`--rollout <1-99>` sends a dev-channel deploy to about that share of the branch's servers (stable per server);
`bun run typetorch deploy --widen <1-100>` sends the same `#seq` to more. Prod servers ignore it: to try a build on some
prod servers, use a signed [pin](https://www.typetorch.dev/guides/deploy-and-rollback.md#pins-ab-experiments).
## Never an empty server
Kernel 0.3.6+: **players never load into an empty baseplate**, even when no build can load (a Roblox asset outage,
every recent build broken).
**Players are held until a build runs.** From the kernel's first line, characters don't spawn and the kernel shows its
own holding screen ("Starting...", a progress bar). When the first build is ready, waiting players spawn and the screen
goes. A server joining takes about 2 s normally; the hold starts before any player can join. A swap of a running build
never holds anybody: players keep playing.
If your game spawns characters itself, set the attribute `TypeTorchHoldCharacters = false` on the `Players` service in
Studio (or keep `CharacterAutoLoads` off in the place): the kernel then never touches characters. Turning
`CharacterAutoLoads` off at runtime in your own code isn't enough, since the kernel turns it back on when it releases
the hold.
**When the head and the last known good build run nothing**, the server tries, in this order:
1. **A build the branch's other servers run fine.** It asks the live servers of its branch which build they run
healthy, and runs the most common one. Prod servers still run only builds they can verify (a valid signature, a
verified deployment entry, or the bootstrap head): other servers can't make a prod server run an unsigned build.
2. **The backup build baked into the place.** `typetorch kernel deploy` puts the current prod build into the place as
`ServerStorage.TypeTorchBackup` (below). It runs with the same checks as any build (prod channel, modules only), and
the server says so: "Running the backup build" in the dev menu's Attention, `h = backup` in `typetorch servers`, and
a critical `backup_build` alert.
3. **Retries in the background.** Whatever runs, the server keeps trying the real build, the last known good one and
the other servers' build (after 15 s, 30 s, then every minute) and swaps to the real one as soon as it loads, like a
normal deploy. Players stay.
4. **Moves.** If nothing runs at all after 15 s, waiting players (and anyone who joins) are moved to a healthy server
of the branch, else to a fresh one (private and reserved servers: a new reserved server on the same branch). A player
moved 3 times is kicked with "Servers are restarting. Please rejoin in a minute." instead of bouncing forever.
Alerts: `boot_failed_teleport` and `bounce_kick` (both critical).
The same happens when a swap fails halfway (the old build stopped and nothing could replace it): players see the holding
screen again until something runs.
**A player whose game code fails to start** (after its own retry) sees the holding screen; the server sends that
player the client code once more, and if that fails too, moves them to a healthy server of the branch (or back into
this one). `typetorch servers` counts them (`clients`), with a `client_failed` warning alert.
### The backup build
- Every `typetorch deploy` and `upload` keeps the uploaded payload on your machine (`.typetorch/payloads/`), because
API keys can't download it back from Roblox.
- Every `typetorch kernel deploy` bakes the current prod build's kept payload into the place, replacing the old
backup. Without a kept payload (prod was deployed from another machine, or before CLI support) it warns and the place
keeps the backup it has: deploy prod once from the machine that runs `kernel deploy`. `--no-backup` skips it.
- **Automatic refresh:** after `deploy`, `approve` or `promote` publishes build N+1 to the default (prod-channel) branch
at your terminal, the place's backup becomes build N once N is **proven healthy**: the fleet API has its reports with
no failure or rollback, no server running it is failed or degraded, and it went out at least `backup.healthyHours`
ago. It saves only the backup slot (a Luau Execution save, like a kernel deploy) and never blocks or fails the deploy:
when it can't (no fleet API, an unproven build, unpublished saves, Team Create, the Save Place API setting, no place
key, a non-interactive run) it prints one line, `backup not refreshed: ...`. A rollback never moves the backup.
Set it in `typetorch.json`: `"backup": { "refresh": "auto", "healthyHours": 3 }` (the defaults), or
`"refresh": "off"`.
- **Now:** `bun run typetorch backup refresh [--build ]` makes a proven-healthy prod build (default: the prod head)
the backup at once (y/N or `--yes`; `--dry-run`; an unproven build needs `--force`).
- **Hot assets:** each save publishes a new place version. When the place's hot-asset copies match the lockfile, the
save stamps the new backup so new servers (framework 0.5.3+) keep adopting the place's copies on that version;
when it can't, the automatic refresh is skipped with the fix (`typetorch assets sync --deploy `).
- `typetorch doctor` shows the backup in the place, with its age. It warns past 30 days.
- **Player data:** the backup is an older build. If your data has a schema version, your code must refuse (or migrate)
data written by a newer version, so a backup that runs against newer player data can't corrupt it.
### A build taken down by moderation
`bun run typetorch deploy --reupload [--branch ]` uploads the exact bytes kept at
upload (`.typetorch/payloads/`) as a **new** asset, waits for moderation and deploys it like any deploy (cloud test,
approval, a new `#seq`, signed on prod). The artifact id stays; servers on the old asset swap to the new copy. Then
`typetorch backup refresh` if the backup was that build.
## Promote
```sh
bun run typetorch promote prod 12b63b9-3fa91c
bun run typetorch promote prod "#42"
```
Points a branch at a build that was already uploaded and approved (from the deployment log, or `uploads.jsonl`), with a
new `#seq`. No rebuild. It finishes a deploy that stopped after the upload, or ships something you uploaded with
`typetorch upload`. A prod-channel branch only takes prod-channel builds, even with `--force` ("rebuild for prod").
**A promoted build keeps its own channel.** Promoting a prod-channel build to a dev branch is allowed, and the deploy is
recorded with `channel: "prod"`. Private and reserved servers on that branch then run prod rules (a server applies prod
rules when its branch **or** its running build is prod-channel): `TypeTorch.channel` is `"prod"` there, the dev menu is
read-only, and stores you split by channel point at prod data. That lasts until a dev-channel build replaces it (the
next `deploy --branch ` from a dev git branch). To test a prod build on a dev branch without that, deploy it with
`--channel dev`.
In PowerShell, quote `#42`: an unquoted `#` starts a comment.
## Roll back
Branch-wide, for every server:
```sh
bun run typetorch rollback --branch prod
bun run typetorch rollback --branch prod --to 12b63b9
bun run typetorch rollback --branch prod --to "#41"
```
Without `--to` it picks the newest earlier deployment whose build differs from the live one. `--to` takes a commit, an
artifact id, an asset id or `#seq`. Nothing is rebuilt, uploaded or moderated, so it takes about 1 to 2 seconds. It
follows the approval policy, is signed on prod, and waits for reports like a deploy. No cloud test unless `--test` (it
goes to an earlier build).
One server only, in game:
- `/tt rollback`, or the dev menu: this server goes back to its previous different build (its own history). Devs on
dev-channel servers; owners on prod-channel servers.
Automatic: see [Safe deploys](https://www.typetorch.dev/guides/deploy-and-rollback.md#safe-deploys).
## The deployment log
```sh
bun run typetorch deployments
bun run typetorch deployments --branch prod --limit 20
bun run typetorch branch ls
```
Every row has `#seq`, time, action (deploy, rollback, promote), `branch@commit`, artifact id, asset id and who; `*`
marks each branch's live head. Uploads that never went out are listed with their `promote` command.
- The logs live in the **state dir**: `.typetorch/` in the game, or `TYPETORCH_STATE_DIR`. Deploys from one machine
take a lock there, and the DataStore counter keeps `#seq` unique across machines.
- Every command takes `--json`.
- `deployments` shows **this machine's** log. `branch ls` also reads the kernel's DataStore heads, so it sees deploys
made on other machines.
- `deployments.jsonl` in the state dir is the full record, one JSON row per `#seq`, with `action`, `channel`, `branch`,
the artifact and `by`. It shows what `deployments` and the dev menu leave out, such as the channel a promote kept.
### Deploy marks on the backend
With a [backend](https://www.typetorch.dev/guides/fleet-and-alerts.md) set up (CLI 0.9.1+), the CLI tells it about each release and place publish, so the
explorer can show them:
| After | Request | Holds |
|---|---|---|
| `deploy`, `approve`, `promote`, `rollback` (an automatic one too), `keys rotate` / `keys resign` | `POST /v1/fleet/deploy` | `#seq`, branch, artifact, channel, the kind (`deploy`, `rollback`, `promote`, `resign`), the build it replaced, your `--message` |
| `kernel deploy`, `kernel restore` | `POST /v1/fleet/mark` | the kernel version, the new place version |
| `backup refresh` (manual or automatic) | `POST /v1/fleet/mark` | the build that became the backup, the new place version |
- They use the game key (`TYPETORCH_API_KEY`), like the CLI's alerts. Without `backend.url` in `typetorch.json` or a game
key, nothing is sent.
- Best effort: 5 s timeout, never fails or holds up the command. When one doesn't go through, the output has one line,
`mark no chart mark for ...`.
- The explorer shows them on the **Deploys** page (the release history) and as vertical markers on its charts. The
deploy mark is also the start time the backend's stuck-server check measures from.
## Pins (A/B experiments)
A pin holds chosen live servers on a known build, for a canary or an A/B test, until the next deploy that reaches them,
an unpin, or the server closing. Pins are never stored.
```sh
bun run typetorch pin 12b63b9-3fa91c --branch prod --pct 10
bun run typetorch pin 12b63b9-3fa91c --branch prod --servers ,
bun run typetorch pin --unpin --branch prod --all
```
- `--pct 1-99` picks about that share of the branch's servers (stable per server); `--servers` names JobIds.
- Pins sent to prod-channel branches are **signed** and need your y/N; prod servers refuse unsigned ones. A signed pin
may run a dev-channel build on public servers: your signature is the approval.
- In game: on dev servers, devs pin from the dev menu (Server > Branch, Manage > Servers) or `/tt pin `.
Owners can load a build on the server they are in, prod included
([Branches and channels](https://www.typetorch.dev/guides/branches-and-channels.md#owners-switch-any-server-in-place)).
- The pinner must be an owner: `--by `, else the single `owner` in `members`, else the creator.
- [Analytics](https://www.typetorch.dev/guides/analytics.md#experiments) compares pinned servers with the rest (per-server experiments).
## Kernel updates
Code and framework fixes never need a restart. A new **kernel** does: it lives in the place, so it changes with a place
publish, and only new servers run it. Kernel updates are manual (an agent can do them for you, with your OK:
[agent playbook](https://www.typetorch.dev/agents/AGENTS.md#updating-the-kernel-in-a-game-agents)):
1. `bun run typetorch kernel deploy --dry-run` patches the kernel folders and the kernel's settings into the place's newest
version (it must be published) and shows the summary: kernel old -> new, scripts changed per folder, settings, references.
Nothing is saved or published. A place without a kernel yet needs `--install`.
- **Unpublished Studio saves?** When the newest version is a save (Studio or Team Create) that was never published,
the command refuses and lists those versions. Pick a base with `--base`: `--base published` patches the last
published version (the saves stay only in version history), `--base latest` patches the newest save and so ships
that work with the kernel, `--base ` takes version `n`. Use the same `--base` for the real run.
2. `bun run typetorch kernel deploy --yes` (or the y/N prompt) saves and publishes it through a Luau Execution task, with no
download. It needs the place setting **Allow place to be updated using Save Place API** (Creator Hub > Creations > the
experience > Places > the place > Permissions; off by default for places made in Studio) and no active Team Create session.
It refuses if someone published meanwhile. Undo: `bun run typetorch kernel restore --version `.
3. Move players to new servers. The dev menu shows "Kernel update" on old servers, with a **Migrate** button that moves
everyone on that server to a fresh one.
If the place doesn't allow saving through the API (a Studio-made place with the setting off), use a copy instead. In Studio,
**File > Download a Copy** of the live place (a binary `.rbxl`), and note its place version. Then
`bun run typetorch kernel deploy --dry-run --place-file --base ` replaces only the kernel folders in that copy,
checks that everything else is unchanged, and writes the patched file and a report. The same command with `--yes` (or the
y/N prompt) publishes it, and refuses if someone published meanwhile. Keep the downloaded copy:
`bun run typetorch kernel restore ` publishes it back (undo). The CLI can't download the copy itself:
`legacy-asset:manage` can't be given to API keys.
A new, empty place takes `kernel deploy --replace-place --yes` instead
([fresh setup step 8](https://www.typetorch.dev/getting-started/fresh-setup.md#8-publish-the-kernel-place-owner)).
## Timings (measured)
| Step | Time |
|---|---|
| build | about 3.5 s |
| upload + moderation | 1.5 to 10 s |
| cloud test (prod) | about 11 s |
| message to live servers | 0.8 to 1.8 s |
| load + swap on the server | about 0.25 s |
| **command to players on the new build** | **about 7 to 9 s** (plus the cloud test on prod) |
| **rollback** | **about 1 to 2 s** |
| new server to a playable build | about 2 s, at most 15 s (players are held meanwhile) |
| kernel 0.3.6, nothing loads: to another server's build / the backup / the moves | about 5 s / 5 to 10 s / 15 s (simulated) |
## No CI for your game
TypeTorch ships no GitHub Actions or other hosted CI for games: hosted CI is a common supply-chain risk, and it would
need your keys. Builds, cloud tests and deploys run from your own machine. `approve --import ` exists for
automation you choose to run yourself. (TypeTorch's own packages are released by tag-triggered workflows:
[Releases](https://www.typetorch.dev/docs.md#releases).)
---
# Branches and channels
## Branches
A **branch** is a name that points at one build (an artifact): `prod`, `dev`, `feature-x`. Deploying a branch moves
the pointer and tells live servers on that branch to swap.
- The TypeTorch branch comes from your git branch: `typetorch.json` `branches` maps git names (`"main": "prod"`);
unlisted ones use their own name, lowercased, with `/` turned into `-` (`feature/Login` → `feature-login`).
`--branch ` overrides it.
- **Public servers run `defaultBranch`** (`prod`). New public servers always boot it.
- **Private and reserved servers can run any branch.** Their choice is stored and survives a restart.
- **Owners can switch any server in place**, public and prod ones included ([below](https://www.typetorch.dev/guides/branches-and-channels.md#owners-switch-any-server-in-place)).
| How | What happens |
|---|---|
| `/tt new ` | a new reserved server on that branch; you are teleported there |
| `/tt branch ` | this server switches: devs on private and reserved servers; owners on any server |
| Dev menu > Server > Branch > **Switch** | the same. On a public server, devs who aren't owners get **Join** instead: it moves only them to a reserved server on that branch |
| `ServerStorage.TypeTorchDev` `Branch` attribute | the branch a Studio playtest boots ([Testing in Studio](https://www.typetorch.dev/guides/studio-testing.md)) |
## Owners switch any server in place
Owners (see [roles](https://www.typetorch.dev/guides/security.md#who-can-do-what)) can change what the server they are in runs, prod included, while
everyone stays in the game. Needs kernel 0.3.4 and framework 0.3.2.
- **Switch** (Server > Branch, or `/tt branch `): this server follows that branch from now on, and takes its
deploys. On a public server this lasts only for this server's lifetime: new servers still boot the signed `prod`
build. On a private or reserved server the choice is stored, as before.
- **Load here** (Server > Branch, on a build, or `/tt pin `): this server runs that build. It is a normal pin:
it holds until the next deploy of the branch reaches the server, an unpin, or the server closing.
- **Reload** and **Rollback** work as usual.
- **To go back,** switch to `prod`.
- Each switch takes two taps (a green Confirm, then "Switching..."). The dev menu allows one swap per server every 2 s.
- It changes this server only. Other servers are moved by deploys, or by signed pins from the CLI
([pins](https://www.typetorch.dev/guides/deploy-and-rollback.md#pins-ab-experiments)).
## Channels
Every branch and every build has a **channel**: `prod` or `dev`. It is the security class.
- `typetorch.json` `channels` sets it per branch; unlisted branches are `prod` when they are `defaultBranch`, else `dev`.
The CLI reads it from there. Servers (kernel 0.3.8+) read `defaultBranch` and `channels` from the
[signed settings record](https://www.typetorch.dev/guides/settings.md): after changing either, run `bun run typetorch settings push`.
- A build gets the channel of the branch it was built for (`--channel` overrides it). Prod builds compile debug prints
away (`$print`, `$warn`) and strip source paths.
- A server's **effective channel** is the strictest of its branch's channel, its build's channel, and `prod` for every
public server.
| | prod channel | dev channel |
|---|---|---|
| Deploy messages | signed (kernel 0.3 verifies) | unsigned |
| Approval (`"approval": "prod"`) | y/N at your terminal | published at once |
| Cloud test before publishing | always | with `--test` |
| `deploy --wait` | on by default | with `--wait` |
| Dev menu | read-only: no Dex edits, no cheats. Owners can still switch the server they are in | edits allowed (audited) |
| remote-claude | refused | allowed for the users you list |
| Pins from the CLI or other servers | only signed ones (`typetorch pin`) | dev menu, `/tt pin` or `typetorch pin` |
- A prod-channel branch refuses a dev-channel or dirty build unless you pass `--force` to `deploy`. `promote` refuses
it even with `--force` ("rebuild for prod").
- The other way round is allowed, and the build keeps its channel: a prod-channel build promoted to a dev branch makes
that branch's private and reserved servers run prod rules (`TypeTorch.channel` is `"prod"`, read-only dev menu,
channel-split stores on prod data) until a dev-channel deploy replaces it
([Promote](https://www.typetorch.dev/guides/deploy-and-rollback.md#promote)).
- A public server stays effective `prod` whatever it runs: an A/B pin of a dev build, or an owner's switch to a dev
branch. Its dev menu stays read-only.
## A typical flow
```sh
git switch -c feature/shop
bun run typetorch deploy # branch feature-shop, dev channel
```
In game: `/tt new feature-shop`, test, then merge into `main` and deploy `prod` from there. Each deploy is logged with
its commit; `bun run typetorch branch ls` lists branches, their channels and live heads.
## Removing a branch
Servers record at most **32 branches** (`branch ls` warns from 28). Remove dev branches you are done with:
```sh
bun run typetorch branch rm feature-shop --dry-run
bun run typetorch branch rm feature-shop
```
- It removes the branch's head from the kernel's DataStore heads (y/N, or `--yes`) and hides it in this machine's log.
- It refuses the default branch and every prod-channel branch, a head that changed since it was read, and a branch live
servers still run (checked through the [fleet API](https://www.typetorch.dev/guides/fleet-and-alerts.md); without it, only with `--force`).
- Servers' MemoryStore copy keeps the branch until it expires (45 days after its last write). Deploying the branch
again recreates it.
## Data on dev branches
Dev branches run in the same universe, so they can reach the same DataStores. Split your store names by channel so a
test server never writes real players' data:
```ts
const name = TypeTorch.channel === "prod" ? "PlayerData" : "PlayerData_dev";
```
See [Player data](https://www.typetorch.dev/guides/player-data.md).
---
# Prod signing
**Goal:** nothing that runs inside your game (a dev branch, a free model, a Claude `run_luau`, a bad package) can make a
prod server load code. Only builds you approved on your own PC can.
- Releases to **prod-channel** branches (deploys, rollbacks, promotes, re-signs) and pins to them are signed with
Ed25519, automatically, when they are published.
- Dev-channel releases are never signed: dev servers stay fast and open.
- The same two keys sign the game's [settings record](https://www.typetorch.dev/guides/settings.md) (dev access, the backend address, live values) on
every write.
- **Kernel 0.3** checks the signatures on every prod-effective server: public servers, and private or reserved servers
on a prod branch.
## The two keys
| | Main key (**Root Key** in the dev menu) | **Fallback Key** |
|---|---|---|
| Key file (plaintext, outside every repo) | `~/.config/typetorch/keys/.key` | `~/.config/typetorch/keys/.fallback.key` |
| Other path | `--key-file`, or `TYPETORCH_KEY_FILE` | `--fallback-key-file`, or `TYPETORCH_FALLBACK_KEY_FILE` |
| Public key in `typetorch.json` | `signingPublicKeys` (+ `keyAssetId`, `revokedKeys`) | `fallbackPublicKey` |
| Where servers get the public key | the **key asset**: a group-owned Model with `PublicKeys` and `RevokedKeys` attributes | baked into the place as `FallbackPublicKey` |
| Signature field | `sig` | `sigF` |
| Replace it | `typetorch keys rotate` (no restart) | `typetorch keys init --fallback --force`, then `typetorch kernel deploy` (restart) |
- The key-path variables are read from the real environment only, never from an env file.
- No command prints a private key. A key file inside a git work tree is refused.
- **Back up both files** ([how](https://www.typetorch.dev/guides/prod-signing.md#back-up-and-drill)). Losing the main key costs a rotate; losing the fallback key
costs a kernel deploy.
### The rule servers follow (strict)
- Once the **key asset** has loaded on a server, only `sig` counts, checked against `PublicKeys` minus `RevokedKeys`.
- Until it has loaded (for example Roblox can't serve it at boot), only `sigF` counts, against the baked
`FallbackPublicKey`.
- Never "either one". That's why `keys rotate` re-signs the live heads.
Servers read the key asset at boot, on a `TypeTorch/rekey` hint (sent by `keys rotate`), every 10 minutes, and once
after a failed signature.
## Set up (once per game)
The order matters. Run these yourself (they need your Open Cloud key):
```sh
bun run typetorch keys init
bun run typetorch keys init --fallback
git add typetorch.json
git commit -m "Prod signing keys"
bun run typetorch kernel deploy --replace-place --yes
bun run typetorch doctor
```
1. `keys init`: the main pair and the key asset (created through Open Cloud with the assets key). It resumes a
half-finished run.
2. `keys init --fallback`: the fallback pair (no network).
3. Commit `typetorch.json`: the public keys and `keyAssetId` are not secret.
4. `kernel deploy` stamps three attributes on `ServerScriptService.TypeTorchKernel`: `KeyAssetId`,
`FallbackPublicKey` and `BootstrapHeads`. It refuses to publish without the keys. For a place with Studio content,
install the kernel [in Studio](https://www.typetorch.dev/getting-started/migrate.md#9-install-the-kernel-in-your-place) instead.
5. `doctor` checks both key files against `typetorch.json`, the key asset (Approved, owned by `creator`, same keys) and
the place (the stamped `KeyAssetId` and `FallbackPublicKey`, read with a Luau Execution task).
Then move players to servers on the new kernel (dev menu > Migrate, or restart servers).
**Check:** on a public server, the dev menu's **Artifact > Signing** shows mode "Root Key", the fingerprints you expect
(the first 8 hex of each key's SHA-256), no "Changed" line and Rejected 0. The running build has two verified badges.
## Day to day
Nothing changes: `bun run typetorch deploy` on `main` builds, uploads, asks y/N, then signs with both keys and
publishes. The key files are checked before the upload, so a missing key fails early. Dry runs never make a real
signature.
## Rotate or replace a key
| Situation | Do |
|---|---|
| Main key lost or leaked | `bun run typetorch keys rotate`: a new main pair; the key asset trusts only the new key and revokes the old one; servers are told to re-read it; then every prod branch's live head is **re-signed** (same build, new `#seq`, `r = "resign"`; servers move the head without a swap), and so is the settings record. No restart |
| A re-sign failed or was rejected | `bun run typetorch keys resign` (the live heads and the settings record) |
| Fallback key leaked or lost | `bun run typetorch keys init --fallback --force` (revokes the old one in the key asset first), then `bun run typetorch kernel deploy` |
## Back up and drill
Do these once, before players depend on the game. Losing both key files means a kernel deploy (a place publish and a
restart) before prod takes a deploy again. Losing the `.env` means new Open Cloud keys.
1. **An offline backup.** Copy every file in `~/.config/typetorch/keys/` and the game repo's `.env` to something offline: an encrypted USB stick, or a password manager's secure
notes. Not a synced cloud folder, not a repo, never a chat. Update it after every `keys rotate` and
`keys init --fallback --force`.
2. **A second Open Cloud key for uploads.** Any key with `asset:write` in your group can change the key asset (the
trusted signing keys) and upload builds. Give that to one key only:
- a new key with the assets job's scopes (`asset:read`, `asset:write`, Luau Execution read and write), limited to
your IP address in Creator Hub (update it when your IP changes), in the game repo's `.env` as `OPENCLOUD_ASSETS_KEY`;
- remove `asset:write` from the shared key (`OPENCLOUD_API_KEY`); it keeps the rest (messaging, DataStores, place
publishing);
- `bun run typetorch doctor`: `key assets` names `OPENCLOUD_ASSETS_KEY`, and every scope probe is `ok`.
3. **A dated rotation drill.** Put it in your calendar: once before go-live, then every 3 months, and the day anyone
with access to your keys leaves. On that date, in a quiet hour:
1. `bun run typetorch keys rotate`;
2. on a public server, **Artifact > Signing** shows the new Root Key fingerprint, the build still has two verified
badges, and no swap happened (the live head was re-signed);
3. deploy once: servers take it;
4. back up the new key file (step 1) and write down the date.
## Bootstrap heads
Builds deployed before signing existed have no signature. So `kernel deploy` stamps `BootstrapHeads`: the current prod
heads (`{"prod":{"a":,"s":,"i":""}}`), from your local deployment log. A prod server trusts
exactly those, unsigned; anything newer must be signed.
Run `kernel deploy` from the machine that has the latest deployment log. A prod deploy made elsewhere is missing from
`BootstrapHeads` and is refused until the next signed deploy.
## The boot fail-safe
"Never boot an empty game." When a prod server starts and nothing verifies (no signed head, no bootstrap head), it
boots the other stored heads **without verifying**, newest first, as long as each is a prod-channel payload of only
Folders and ModuleScripts. Such a server is flagged:
- `status().unverified`, a warning in the log, "UNVERIFIED boot (fail-safe)" in `/tt status`;
- the dev menu's Attention shows "Booted an unverified prod head" (red badge) and the build has no verified badge.
It is **only for the first boot**. Live deploy messages, the 60 s poll, pins, `/tt rollback` and reloads stay strictly
verified. The next signed deploy for the same build clears the flag without a swap; any other signed deploy replaces it.
If nothing verifies at all, the dev menu's Attention shows "No trusted prod head" until the next signed deploy. On
kernel 0.3.6+ the server still doesn't stay empty: it runs the backup build baked into the place, or moves players
([Never an empty server](https://www.typetorch.dev/guides/deploy-and-rollback.md#never-an-empty-server)).
**Accepted risk:** a server that boots while no trusted head exists can be steered by whoever can write the stored heads
(code running in your universe), within the limits above.
## Pins on prod
Prod servers take only signed pins: use `bun run typetorch pin ...` ([pins](https://www.typetorch.dev/guides/deploy-and-rollback.md#pins-ab-experiments)).
The dev menu shows "Use the CLI: typetorch pin" there.
## What stays open
- Dev-channel servers accept unsigned messages by design.
- Anyone with asset write access in your group (including an upload key) can change the key asset. Keep keys scoped.
- Experiment pins sent from the dev menu are unsigned and work only on dev servers.
The message format is in the [CLI README](https://github.com/typetorch/cli#deploy-message).
---
# Settings
Kernel 0.3.8 reads your game's live settings from **one signed record**: who is a dev, where the fleet API is, where
analytics go, and your own live values (flags, kill switches, prices). You change it with the CLI; running servers
apply a change within seconds, with no deploy and no place publish.
- It lives in the game's DataStore `TypeTorch`, key `settings`.
- The CLI signs it with your **two prod signing keys** ([Prod signing](https://www.typetorch.dev/guides/prod-signing.md)). Game code can write
DataStores but can't sign, and servers refuse a record that doesn't verify. So a free model or a dev branch can't
make itself a dev or point your servers somewhere else.
- **Server only.** It holds tokens; nothing in it reaches clients.
- It replaces every ConfigService key TypeTorch used before (`TypeTorch`, `TypeTorchAccess`, `TypeTorchFleet`,
`TypeTorchAnalytics`). Kernel 0.3.8 reads no ConfigService keys, and the API key needs no `universe:write`.
## What it holds
| Field | What | Written by |
|---|---|---|
| `access` | `members`, `revoked`, `devBadgeId` from `typetorch.json` ([who gets the dev menu](https://www.typetorch.dev/getting-started/fresh-setup.md#11-the-dev-menu-and-who-gets-it)) | `typetorch access push` |
| `defaultBranch`, `channels` | from `typetorch.json` | `typetorch settings push` |
| `fleet` | derived from `backend` for kernels before 0.4: `{ url, token }`, the [fleet API](https://www.typetorch.dev/guides/fleet-and-alerts.md) and its write-only ingest token | `typetorch backend setup` |
| `backend` | `{ url, key, ingest?, analytics?, notify? }`: the TypeTorch backend and its game key (CLI 0.9; kernels before 0.4 read the `fleet` and `analytics` sections it derives). `ingest` (framework 0.7.2+, CLI 0.19.0+) is the address of separate [ingest servers](https://www.typetorch.dev/guides/emergency-scale-ups.md#5-several-ingest-servers-optional): events go there, everything else stays on `url`. `analytics` holds the analytics dials and the experiment overrides. `notify` = `{ keys: { current, previous?, since } }`: the [notification](https://www.typetorch.dev/guides/notifications.md) launch-data signing keys (43-character base64url strings; `since` in unix seconds) | `typetorch backend setup` (`--ingest`); `typetorch experiment` for `backend.analytics.experiments` ([Analytics: experiments](https://www.typetorch.dev/guides/analytics.md#experiments)); `typetorch notify key rotate` for `backend.notify` ([Notifications: keys](https://www.typetorch.dev/guides/notifications.md#keys-and-the-signed-tap)) |
| `analytics` | the [analytics sink settings](https://www.typetorch.dev/guides/analytics.md#settings-the-analytics-field), derived from `backend`, or a Basin sink | `typetorch backend setup` (`--analytics basin\|duckdb` switches the sink) |
| `game` | your own live values, read with `TypeTorch.liveConfig`, plus two [reserved keys](https://www.typetorch.dev/guides/settings.md#reserved-game-keys) | `typetorch settings set game.` |
The whole record is at most 32 KB, `game` at most 16 KB.
## Commands
From the game folder:
```sh
bun run typetorch settings status # seq, age, whether your keys signed it, the fields (tokens hidden)
bun run typetorch settings get game.shop.price # one field as JSON; `get` alone prints all of them
bun run typetorch settings set game.shop.price 75 # change one game value
bun run typetorch settings set game.event '{"name":"halloween","ends":1793000000}'
bun run typetorch settings set game.event - < event.json # `-` reads the JSON from stdin
bun run typetorch settings unset game.event
bun run typetorch settings unset backend # drops backend and the fleet and analytics sections derived from it
bun run typetorch settings push # defaultBranch, channels and access from typetorch.json
bun run typetorch access push # access only
bun run typetorch backend setup --url https://backend.example.com
bun run typetorch experiment weights onboarding 3,1 # an analytics experiment override
```
Every write reads the record, checks that your keys signed it, changes one field, raises `seq` by one, signs it with
both keys and writes it back (if another machine wrote in between, it starts over on the newer record). Then it pings
the servers, and sends the record's owners to the backend (`PUT /v1/access` with `TYPETORCH_ADMIN_TOKEN`; only owners
may Sign in with Roblox there). A backend that is down or refuses is a warning, never a failed write:
`typetorch access push` sends the owners again.
- `settings set` takes `game.` only. The other fields have their own commands (table above).
- `--dry-run` shows the result without writing.
- `--no-ping`: servers still pick it up within about a minute.
- `--force` replaces a record your keys didn't sign (you lost both keys, or game code wrote junk). Its old fields are
dropped, never re-signed, so write them again afterwards. For `backend setup` it also
writes a value whose [endpoint checks](https://www.typetorch.dev/guides/settings.md#checked-before-it-is-signed) failed.
- Every write needs both signing key files (else: "run `typetorch keys init`") and the deploy key's DataStore scopes
(`universe-datastores.objects:read`, `:create`, `:update`) plus `universe-messaging-service:publish` for the ping.
- `typetorch keys rotate` and `keys resign` re-sign the record with the new keys.
- `typetorch notify key rotate` writes `backend.notify.keys` first, then sends the new key to the backend (the previous key stays valid 14 days). The keys are
secrets like the game key: `settings status` and `get` hide them, and `backend setup` keeps them.
- `typetorch doctor` reads it, checks the signature and tests the `backend` address and keys in it.
### Checked before it is signed
A wrong address or key in `backend` isn't rejected by anything else: game servers fail every request
(`NetFail`, HTTP 401, HTTP 530) until someone looks at the dev menu. So `backend setup` tests the value first (also with
`--dry-run`), and `typetorch doctor` runs the same tests against the live record:
1. **url**: it parses, is https (game servers accept nothing else), has no user info or query, uses only the characters
the kernel accepts, and is the server's base address (not a `/v1/...` path). `doctor` accepts http on localhost for
`typetorch.json` `backend.url`, which only the CLI reads.
2. **healthz**: `GET /healthz` answers `{"ok":true}` within 5 seconds.
3. **key and admin token**: `GET /v1/auth/check` (it changes nothing) says the game key has role `game` (write-only)
and that the fleet and analytics parts run, and the admin token has role `admin`. Refused even with `--force`: the admin
token in the game key's place, or the same value for both.
If one fails, the command prints it in red with a fix, writes nothing and exits 1; `--force` writes anyway. The checks need
a backend with `GET /v1/auth/check` (`@typetorch/backend`).
## Reserved game keys
Two `game` keys are read by TypeTorch itself. Write them with `settings set` like any other value.
| Key | What | Read by |
|---|---|---|
| `tt.events` | the scheduled live events: `{ "v": 1, "events": [{ "id", "name", "start", "end", "set": { "": } }] }`, times in unix seconds (UTC). While an event runs, its `set` values replace those `game` keys for `liveConfig`, switched on each server's own clock. The backend explorer's **Live events** page builds the schedule and gives the exact command: `typetorch settings set game.tt.events -` with the JSON on stdin. Cancelling an event is signing the schedule without it. Details and limits: [Live events](https://www.typetorch.dev/guides/live-events.md) | framework 0.7.1+ (`TypeTorch.liveEvents()`, `liveConfig`) |
| `feedback` | the player feedback rating scale ([Player feedback](https://www.typetorch.dev/guides/feedback.md)). It wins over the game's `configure(...)`; an invalid value turns feedback off | framework 0.7.0+ (`TypeTorch.feedback()`) |
## The analytics dials (`backend.analytics`)
Next to `url` and `key`, the record's `backend.analytics` holds the analytics dials. Frameworks 0.4+ read them; servers
apply a change within seconds. More in [Analytics](https://www.typetorch.dev/guides/analytics.md#settings-the-analytics-field).
| Field | What | Written by |
|---|---|---|
| `flushSeconds` | seconds between sends, 5-300 (default 15) | `backend setup --flush-seconds ` |
| `recordShare` | share (0-1) of new players whose first session is recorded (default 1) | `backend setup --record-share <0-1>` |
| `experiments` | the live experiment overrides | `typetorch experiment` |
| `extended` | the extended recording's dials (`seconds` 10-600, default 300; `hz`, `entMax`, `streams`, ...; framework 0.7.2+) | `typetorch analytics extended set ` (CLI 0.20.0+; [Analytics: extended recording](https://www.typetorch.dev/guides/analytics.md#extended-recording)) |
| `techEvery` | seconds between tech health samples, 15-3600 (default 60) | no command |
| `recordSeconds` | seconds a first-session recording runs after the first input, 10-600 (default 60; framework 0.7.1+) | no command |
| `positions` | up to 64 event names whose game-code events always carry the player's position (framework 0.7.1+) | no command |
| `joinData`, `joinLaunchPrefix` | how much join data the join row keeps (Join data, below) | no command |
No CLI command writes the last four yet. `backend setup` keeps whatever is already in `backend.analytics`.
## Join data (`backend.analytics.joinData`)
How much of Roblox's join data (`Player:GetJoinData()`) the analytics join row keeps. It sits in the record's
`backend.analytics` next to the other analytics dials (frameworks reading the old `analytics` field, and
`new AnalyticsEngine({ settings })` in tests, take the same value). Servers apply a change within seconds.
| Value | The join row keeps |
|---|---|
| `"full"` (default) | the summary props ([Analytics: the join row](https://www.typetorch.dev/guides/analytics.md#the-join-row)) **and** `jd`, a field-by-field copy of `GetJoinData()` ([`jd`](https://www.typetorch.dev/guides/analytics.md#jd-the-raw-join-data)) |
| `"summary"` | the summary props only, no `jd` |
| `"off"` | only what it kept before notifications (plans/29): `from`, `ctx`, `tp`, `party`, the age bucket, Premium, country, friends in the server, returning or not. No `jd`, and none of the newer join props |
Any other value is refused with a warning and read as `"full"`.
**Why `"full"` keeps LaunchData.** It is at most 200 bytes (Roblox's own limit), and it is the only way to debug
[notification](https://www.typetorch.dev/guides/notifications.md) and share-link routing: whether the launch data reached the server at all, and what it
was. A notification tap whose launch data never arrived looks like any direct join without it.
**What `jd` never holds,** in any mode:
- another player's UserId: party members, the referrer and the followed player are pids, or `"other"`;
- TeleportData's content: only its size, type and top-level key names;
- the value of a join-data key TypeTorch doesn't know: only its type.
**Personal data in your launch data?** If your game's share links or notifications put anything personal in the launch
data (a name, an email, an invite code tied to a person), set `"joinData": "summary"`.
**`joinLaunchPrefix` is separate.** It only decides whether the summary prop `launch` keeps the first 32 characters of
your game's own launch data (default off). `jd.LaunchData` follows `joinData` alone, so with `joinData: "full"` the launch
data is in `jd` even when `joinLaunchPrefix` is off.
No CLI command writes `joinData` yet: `backend setup` keeps any value already in `backend.analytics`.
## Live values in game code
```ts
import { t } from "@rbxts/t";
import { TypeTorch } from "@typetorch/framework";
// in a server module
private readonly price = TypeTorch.liveConfig("shop.price", {
default: 50,
parse: (raw) => (t.number(raw) && raw >= 0 ? raw : error("not a price")),
});
onStart() {
this.reprice(this.price.get());
this.trove.add(this.price.onChanged((value, previous) => this.reprice(value)));
}
```
- `get()` is cheap: call it whenever you need the value.
- `onChanged` fires only when this key's value really changes; it returns a disconnect for the trove.
- The default is used when there is no record or no such key, on kernels before 0.3.8 (with one warning), or when
`parse` throws (with one warning per bad value). The cloud test has no record either, so `liveConfig` gives defaults
there (frameworks before 0.5.2 also print the "needs kernel 0.3.8" warning in it, wrongly).
- Values are JSON. Keys are 1-64 characters of letters, digits and `_ . : / -`.
- **Server only.** A client needs a value? Send it through your own network.
- `TypeTorch.settings()` returns the whole verified record (server only; it holds tokens: never send it to a client).
## How servers read it
- **At boot**, alongside the other boot reads; it never holds up the 15 s boot budget.
- **About every minute**, and **within seconds of a ping** from the CLI.
- A server keeps the **last good copy**. It refuses a record that isn't signed, doesn't verify, is malformed, or has a
lower `seq` than the one it holds, and says why.
- Which signature counts: once the server loaded your key asset, only `sig` (the main key); before that, only `sigF`
(the fallback key). The same rule as prod deploys.
- **No record yet:** servers use the defaults: `defaultBranch` prod, only the experience owner is a dev, no fleet API,
no analytics sending.
## Check it in game
The dev menu's **Server > Status** shows "Settings #12, 3m old (sig)". Attention lists:
| Item | Meaning |
|---|---|
| No settings | there is no record: `typetorch settings push` |
| Settings refused | the record isn't signed or doesn't verify, and the server has no good copy |
| Settings unreadable | the DataStore read fails |
| Settings copy refused | a newer read was refused while a good copy is kept (game code wrote it, or an old copy was put back) |
## Moving from ConfigService (kernel 0.3.8)
Kernel 0.3.8 doesn't read the old ConfigService keys, and they can't be read back to copy them. After the place runs
kernel 0.3.8:
1. `bun run typetorch settings push` (defaultBranch, channels, dev access).
2. `bun run typetorch backend setup --url ` if you use one (or `bun run local -- --game ` in the
backend folder for a local test: it runs `backend setup` for you).
3. `bun run typetorch access push`: the owners also go to the backend (only they may Sign in with Roblox there).
4. `bun run typetorch settings status` to check. Then delete the old keys in Creator Hub (Configs) if you like.
Until step 1, only the experience owner is a dev on 0.3.8 servers.
---
# Live servers and alerts
See every live server of your game, what each one did with a deploy, and get an alert when something breaks, within
seconds. The **kernel** sends it, so it keeps working when a build is broken and the game's own code doesn't run.
- Needs kernel 0.3.2+ in the place (a place project that maps the kernel's files one by one must map `Fleet` too; the
template's `studio.project.json` does).
- Backend: the **fleet API**, a small server you host (SQLite inside). It is part of the
[backend](https://github.com/typetorch/backend) and runs in the same process as its DuckDB analytics part, or alone.
- Without it everything else still works: `servers`, `report` and `alerts` say "not configured" in one line, and
deploys skip their wait with a note.
## How it works
```mermaid
flowchart LR
K[kernel on each game server] -->|heartbeat, reports, alerts, closing| F[fleet API
SQLite]
F -->|server lost, server stuck, backend alerts| F
F -->|critical alerts| W[webhook
Discord, Slack, JSON]
C[typetorch servers, report, alerts, deploy --wait] -->|admin token| F
```
Each game server posts, with a write-only token:
| What | When |
|---|---|
| **Heartbeat** | every 30 s, and at once on a swap, a health change or a player count change. Branch, build, `#seq`, players, health (`ok`, `failed`, `unverified`, `degraded`, `backup`), kernel version, uptime, last error, the place version (`pv`, kernel 0.5.6+), the budget summary and TPS. Kernel 0.5.7+: the game's [live debug](https://www.typetorch.dev/guides/runtime-api.md#live-debug-server-only) declarations and column values |
| **Deploy report** | one per deploy outcome: `booted`, `swapped`, `failed`, `rolled_back` or `skipped`, with the error and the seconds it took |
| **Alert** | at once ([codes below](https://www.typetorch.dev/guides/fleet-and-alerts.md#alerts)) |
| **Closing notice** | when the server shuts down cleanly (so it isn't "lost") |
That is under about 6 requests a minute per server, capped at 30 (Roblox allows 500 a minute per server, shared with
your game). Failed posts are retried; a post never blocks a swap. The token is never logged.
**No MemoryStore for fleet data.** Heartbeats and reports never touch your experience's MemoryStore, whose quota your
game shares. (The kernel still keeps each branch's head there: one small key.)
## Set it up
`bun run typetorch init --phase backend` (CLI 0.10+) does steps 1 to 3 for you: on a VPS with Coolify, on a VPS
without Docker, or on your PC behind a quick tunnel. It makes the two keys, writes them to `.env`, and points the game
at the backend. The steps below do the same by hand.
1. **Run the backend.** On a VPS with a domain ([Deploy on Coolify](https://github.com/typetorch/backend#deploy-on-coolify)
or [run it on a VPS without Docker](https://github.com/typetorch/backend#run-it-on-a-vps-without-docker)), or on your PC
behind a quick tunnel for a test ([analytics quick start](https://www.typetorch.dev/guides/analytics.md#quick-start-a-local-test)). For a game on
Cloudflare Basin, run only its fleet part: `TYPETORCH_PARTS=fleet`. It needs two random values, 32+ characters each
and different: the game key `TYPETORCH_API_KEY` and the admin token `TYPETORCH_ADMIN_TOKEN`.
2. **Give the CLI the keys.** In the game repo's `.env` (gitignored):
```text
TYPETORCH_ADMIN_TOKEN=
TYPETORCH_API_KEY=
```
The game key only writes; the admin token reads and manages. The CLI never prints them or passes them to a child process.
3. **Point game servers at it:**
```sh
bun run typetorch backend setup --url https://backend.example.com
```
It writes `backend` = `{ url, key }` (the game key) into the game's [signed settings record](https://www.typetorch.dev/guides/settings.md), with the
`fleet` and `analytics` sections that kernels before 0.4 read derived from it, and `"backend": { "url": ... }` into
`typetorch.json`, then pings the servers and sends the owner list to the backend. It needs both prod signing keys (the record
is signed; servers refuse one that doesn't verify) and kernel 0.3.8+. `--dry-run` shows what it would write;
`bun run typetorch settings status` shows the record (the token hidden). Before it signs anything it
[checks](https://www.typetorch.dev/guides/settings.md#checked-before-it-is-signed) the address (https, `GET /healthz` within 5 s) and the game key (not
the admin token) and refuses a broken one with a fix; `--force` writes anyway.
4. **Check:** kernels read the record at boot, about every minute, and within seconds of a ping. Join a server, then
`bun run typetorch servers`.
- **On this PC:** `bun run typetorch backend run` starts a backend checkout behind a Cloudflare quick tunnel and runs
`backend setup --url ` each time the tunnel's address changes, so servers follow it within seconds (`init`
sets it up and registers it as a login task). The explorer is then `http://localhost:8787`.
- **Sign in with typetorch.dev:** a backend with a public https URL can let owners sign in through
[dash.typetorch.dev](https://dash.typetorch.dev) instead of a Roblox OAuth app per game. Owners get admin only
on a trusted browser (by default; the backend's `TYPETORCH_CENTRAL_LOGIN_UNBLESSED` decides):
`bun run typetorch backend bless` signs a one-time link with your main prod key and opens it in the browser to trust.
Details: the [backend README](https://github.com/typetorch/backend#sign-in-with-typetorchdev).
## Commands
```sh
bun run typetorch servers
bun run typetorch servers --branch prod --watch
bun run typetorch report latest
bun run typetorch report "#42"
bun run typetorch alerts --since 120
bun run typetorch alerts --follow --level critical
```
- **`servers [--branch ] [--watch]`:** every live server: JobId, branch, build, applied `#seq`, health, players,
kernel, uptime, last heartbeat. `--watch` redraws every 5 s. Reserved-server access codes are never shown.
- **`report [--branch ]`:** what the servers did with one deploy: counts per result, errors
grouped with the servers that hit them, and the servers still on an older `#seq`. It exits 1 when a server failed or
rolled back, and prints the rollback command.
- **`alerts [--follow] [--level info|warning|critical] [--since ]`:** the last 60 minutes by default;
`--follow` keeps printing new ones.
- **`deploy --wait`** reads the same reports: [Deploy and rollback](https://www.typetorch.dev/guides/deploy-and-rollback.md#wait-and-automatic-rollback).
In PowerShell, quote `"#42"`.
## Alerts
| Code | Level | From | Means |
|---|---|---|---|
| `deploy_failed` | critical | kernel | a deploy didn't load or start on a server |
| `health_rollback` | critical | kernel | a new build failed its health window and the server went back to the last good one |
| `lkg_exhausted` | critical | kernel | nothing known-good could run after a failure |
| `backup_build` | critical | kernel | 0.3.6: nothing else could run, so the backup build baked into the place runs ([never an empty server](https://www.typetorch.dev/guides/deploy-and-rollback.md#never-an-empty-server)) |
| `boot_failed_teleport` | critical | kernel | 0.3.6: nothing runs at all; players are being moved to another server |
| `bounce_kick` | critical | kernel | 0.3.6: a player was kicked after 3 moves (or failed teleports) |
| `client_failed` | warning | kernel | 0.3.6: a player's game code didn't start even after a re-send; they were moved |
| `health_failed`, `health_unverified` | critical | kernel | the server runs nothing, or booted an unverified prod build. Kernel 0.5.7+: no health tick counts while a swap or a last-known-good restore runs, and a worse state alerts only after 2 ticks (5 s apart) in a row; older kernels could raise a false `health_failed` mid-swap or during a slow boot that nothing cleared. A server where nothing can run still alerts, about 5 s later |
| `health_degraded` | warning | kernel | the running build keeps erroring, or a deploy failed here |
| `booted_unverified`, `no_trusted_head` | critical | kernel | [prod signing](https://www.typetorch.dev/guides/prod-signing.md) problems at boot |
| `kernel_api_mismatch`, `artifact_refused` | critical | kernel | a build the kernel can't or won't run |
| `error_spike` | warning | kernel | 20 or more errors a minute from the running build |
| `refused_deploy`, `refused_head`, `refused_pin`, `refused_swap` | warning | kernel | the kernel refused a message or a swap (for example an unsigned one on prod) |
| `branch_switch`, `build_load` | info | kernel | someone switched this server's branch or loaded a build on it (the dev menu, `/tt branch`, `/tt pin`) |
| `auto_rollback` | critical | CLI | `deploy --wait` rolled the branch back |
| `server_stuck` | warning | CLI and fleet API | servers didn't pick up a deploy (below) |
| `server_lost` | critical (3+ servers) or warning | fleet API | servers stopped reporting (below) |
| `fleet_flood` | critical | fleet API | too many never-seen JobIds in a minute (below) |
| `disk_low` | warning or critical | backend | the backend's data disk is under `TYPETORCH_DISK_WARN_PERCENT` (15) or `TYPETORCH_DISK_CRITICAL_PERCENT` (5) percent free |
| `backend_*` | below | backend | the backend's own checks of its data ([below](https://www.typetorch.dev/guides/fleet-and-alerts.md#backend-alerts)) |
The kernel sends each code at most once a minute per server (`error_spike` every 5 minutes; `branch_switch` and
`build_load` every time).
- **Server lost:** no heartbeat for 90 s and no closing notice. One alert per branch and build per sweep, with the
JobIds; critical when 3 or more servers are lost at once.
- **Server stuck:** 3 minutes after a deploy started, live servers on its branch are still below its `#seq` and haven't
reported anything for it. It lists them and says nothing about the build itself, so it never triggers a rollback.
- **Fleet flood:** the fleet API admits at most 2,000 JobIds it has never seen per minute (enough for a 1,250-server
fleet restarting at once). Past that, new ones get a 429 until the minute ends (they get in on their next
heartbeat), known servers keep working, and one `fleet_flood` alert is raised per minute. The cause is a huge fleet
restart or someone with the ingest token sending made-up JobIds. Raise `TYPETORCH_NEW_JOBS_PER_MINUTE` for a bigger
fleet.
Reports are kept 30 days, alerts 90 days, and the [deploy history](https://www.typetorch.dev/guides/fleet-and-alerts.md#deploy-history) 365 days.
### Backend alerts
The backend also watches its own data once a minute and raises alerts into the same list, stream and webhook (source
`server`). It needs the fleet part.
| Code | Default level | Fires when (defaults) |
|---|---|---|
| `backend_error_spike` | warning | one error kind's count in the last 10 min is 5x its usual rate (over 24 h), and at least 50 |
| `backend_error_new` | warning | an error kind never seen before reaches 20 within 30 min of the latest deploy |
| `backend_ccu_drop` | critical | players online fall 50% from the peak within 10 min (peak 20+) while servers still send heartbeats |
| `backend_fleet_silent` | critical | no heartbeat (and no analytics ingest, when it runs) for 10 min, after 10+ players were online in the hour before |
| `backend_ingest_stopped` | warning | no analytics rows for 10 min after steady traffic (100+ rows a minute) while players are online |
| `backend_latency` | warning | request p99 over 2,000 ms in every minute of 5 min |
| `backend_memory` | warning | the backend's RSS over 800 MB for 5 min |
| `backend_loop_lag` | warning | the event loop late by over 500 ms in every minute of 3 min |
| `backend_5xx` | warning | over 5% of requests answered 5xx in 5 min (100+ requests) |
| `backend_disk_low` | critical | under 10% or under 2 GB free on the data disk |
| `backend_disk_growth` | warning | at the recent growth, the data disk is full within 7 days |
Each rule, level and threshold is editable on the explorer's Settings page (runtime setting `backendAlerts`) or by
environment: `TYPETORCH_BACKEND_ALERTS=off` turns all off, `TYPETORCH_ALERT_=off` one rule (for example
`TYPETORCH_ALERT_CCU_DROP=off`). The same rule and subject is raised once per 180 minutes
(`TYPETORCH_BACKEND_ALERTS_REPEAT_MINUTES`), and at most 12 backend alerts an hour (`TYPETORCH_BACKEND_ALERTS_PER_HOUR`).
Two more come from the optional ingest queue, on the main server only (`TYPETORCH_ROLE=main`, [Several ingest servers](https://www.typetorch.dev/guides/emergency-scale-ups.md#5-several-ingest-servers-optional)):
`queue_bucket_down` (critical) when the queue bucket can't be reached for a minute, and `queue_file_bad` (warning) when a queued
file can't be loaded (that file is skipped for 10 minutes). They are not in the rules table above.
**Players online milestone** (`ccuMilestone`, level info; `TYPETORCH_ALERT_CCU_MILESTONE`, and the Settings page's
Backend alerts). Milestones start at `start` (10) and double each step (10, 20, 40, 80, ...). A milestone fires when the
fleet's players online first reach it, re-arms once they drop below `rearmPercent` (70%) of it, and fires at most once per
`cooldownMinutes` (30) per milestone. A jump past several fires only the highest, and the first sample after a start only
learns the level. Besides the alert webhook, it is a push to every [mobile app](https://www.typetorch.dev/guides/mobile-notifications.md) registration with
milestones on.
Rules that compare with "before" wait for enough volume, so a small test place stays quiet. Details:
[Running the backend](https://www.typetorch.dev/guides/backend-operations.md#backend-alerts) and the
[backend README](https://github.com/typetorch/backend#backend-alerts).
## Deploy history
The backend keeps every release as a row: the CLI posts each deploy, rollback, promote and re-sign
(`POST /v1/fleet/deploy`), and a `#seq` first heard of in a server's report is added as `inferred`. Each row has the
branch, build, channel, kind, the build before, the note, who started it, and how it went: servers per report result,
`ok`, `failed`, `stuck`, the most common deploy errors, and an `outcome` (`pending`, `ok`, `partial`, `failed`, `stuck`
or `no_reports`).
- The explorer's **Deploys** page (`/deploys`) lists them; `/deploys/` shows one with its report and alerts.
- `GET /v1/fleet/deploys?branch=&before=&limit=` answers `{ deploys, next }`, highest `#seq` first (`limit` 50, at
most 100; pass `next` as `before` for the next page). `GET /v1/fleet/deploys/` answers
`{ deploy, report, alerts, previous, next }`.
- Kept 365 days (`TYPETORCH_DEPLOY_KEEP_DAYS`, a runtime setting) and at most 10,000 rows. After 30 days, when the
reports go, the counts are frozen onto the row.
`typetorch deployments` is the other history: the kernel's own deployment log in the place's DataStore
([the deployment log](https://www.typetorch.dev/guides/deploy-and-rollback.md#the-deployment-log)).
## Webhooks
The fleet API can post alerts to Discord, Slack or any URL that takes JSON. In the backend's environment (Coolify's environment variables, or its env file):
```text
TYPETORCH_ALERT_WEBHOOK_URL=
TYPETORCH_ALERT_WEBHOOK_LEVELS=critical
```
- The format is detected from the URL (or set `TYPETORCH_ALERT_WEBHOOK_FORMAT` to `discord`, `slack` or `json`).
- Critical only by default (`TYPETORCH_ALERT_WEBHOOK_LEVELS=critical,warning` adds warnings).
- The same alert (code, branch, build) at most once per 10 minutes; at most 20 posts a minute.
- [Backend alerts](https://www.typetorch.dev/guides/fleet-and-alerts.md#backend-alerts) go to the same webhook with the same level filter.
- A webhook URL is a secret: keep it in the server's env file only.
The API also streams changes live (Server-Sent Events, `GET /v1/fleet/stream`, admin token) for your own tools; the
CLI polls for now.
## Errors, debug bundles and remote debug
The same backend shows more than the fleet list. Open its **web explorer** (the backend's URL in a browser; sign in with
the admin token, Sign in with Roblox, or typetorch.dev), with pages such as Overview, Players, Funnels, Experiments, Fleet,
Live map, Deploys, Errors, Performance, Query and Settings ([The explorer](https://www.typetorch.dev/guides/explorer.md)).
- **Error logs** (kernel 0.4.0+): every server's errors, server and client, with player names and ids replaced
(``), fingerprinted and counted per minute per branch and build, posted to `/v1/errors`. The
Errors page lists the kinds with the players and the servers that hit them; a player's page lists the errors they
hit (`GET /v1/players//errors`), and a server's page the errors it reported, live or gone, over 30 days
(`GET /v1/servers//errors`).
- **Error drop rules:** expressions such as `(message contains "asset" or message contains "mesh") and realm = "client"`
drop matching errors when they arrive, before anything is stored. Owners edit them on the Errors page (Drop rules), with
a preview of the stored kinds each would catch. The default comes from `TYPETORCH_ERROR_DROP_RULES` (a JSON list).
Routes: `GET /v1/errors/drop-rules`, `POST /v1/errors/drop-rules/preview { expr, days? }` (owners). Saving a rule
doesn't delete what is stored. Syntax: [backend README](https://github.com/typetorch/backend#error-logs).
- **Budget view** (kernel 0.4.0+): what TypeTorch spends of the server's DataStore, MemoryStore, HTTP and
MessagingService limits, per caller, and memory. In game: the dev menu's Server > Budget. Heartbeats carry a summary,
and (kernel 0.4.2+) the server's TPS, so the Fleet and Performance pages show TPS and memory.
- **Remote debug** (kernel 0.5.0+): every JobId on the Fleet page opens `/servers/`. While it is open, that live
server is read like the dev menu (tabs Status, Logs, Players, Game, Live map, State, Dex, Modules, Builds, Budget,
Errors, Network, Audit). The built-in ops are **read-only**: none kicks, bans, reloads, rolls back or edits anything.
A Roblox server can't be called into, so it pulls: the next heartbeat tells it it is watched, and it long-polls the
backend for allow-listed commands, owners only, answers scrubbed of secrets. Nothing is sent while nobody watches.
With an Open Cloud messaging key on the backend (`OPENCLOUD_API_KEY`, `TYPETORCH_UNIVERSE_ID`), the server wakes
within seconds instead of at its next heartbeat (kernel 0.5.1+).
- **Live debug** (kernel 0.5.7 and framework 0.7.1; guide: [Live debug](https://www.typetorch.dev/guides/live-debug.md); game code:
[`remoteDebug` and `fleet`](https://www.typetorch.dev/guides/runtime-api.md#live-debug-server-only)):
- The **Game** tab has a button per command the game declared (op `game.`) and the latest value of each stream.
These commands are labelled game-defined: they are read-only only because the game promises it. The kernel can't
check what a handler does, so review them like any owner-only code.
- The **Live map** tab draws the server's players (the kernel's built-in `positions` stream, 2 Hz, while watched) and
the game's `points` streams on the exported map ([Maps](https://github.com/typetorch/backend#maps)).
- **`/live`** is the live map of every server at once: while it is open, servers post only positions, one frame
every 3 s. Admin role only (`POST /v1/fleet/live-map/watch`, `GET /v1/fleet/live-map`).
- The Fleet page's **Columns** button shows the game's custom columns (`fleet.column`), hidden by default
(`GET /v1/fleet/columns`; the values come as `cv` on each server row). Framework 0.7.4+: the built-in
**Framework** column (`tt_framework`, each server's TypeTorch framework version) shows by default, and a deploy's
page lists its live servers by framework version.
- Positions and stream frames hold player names, UserIds and positions: the backend keeps the last 120 s per server
in memory only (never on disk or in a log) and drops them when the server closes or is lost.
- Routes (admin): `POST /v1/fleet/servers//commands` takes `game.` ops only when that server declared
them; `GET /v1/fleet/servers//streams?since=` answers `{ declared, frames }`.
- **Roblox server logs:** a server page's **Roblox logs** section shows the errors and warnings Roblox itself kept for
that JobId (Open Cloud server management, beta), about 3 minutes behind. It needs `OPENCLOUD_API_KEY` with the
`universe:read` scope on the game and `TYPETORCH_UNIVERSE_ID`. Roblox files the logs under the place version, which
kernels 0.5.6+ send in the heartbeat (`pv`); for older kernels the page asks for it. Route:
`GET /v1/roblox/servers//logs?severity=&search=&order=&pageToken=` (409 while the key or the version is
missing).
- **Server location:** the backend stores each server's public address (`ip`, `firstIp`, `ipChangedAt`) and looks up
its location in an offline DB-IP database (no address is sent anywhere; `TYPETORCH_GEOIP=off` turns it off). Roblox
servers leave through Roblox's own network, so it is the data center's region. The Fleet page has a Country column, a
Countries tile and a By country table. The location goes to every signed-in role; the address only to the admin
role (owners and the admin token). Behind a proxy, set `TYPETORCH_TRUST_PROXY` or every server shows the proxy's
address and no location.
- **Debug bundles** (kernel 0.5.3+): when a server fails (a critical alert, a generation that fails to start, players
moved off it, or shutting down soon after a failure), it posts what happened by itself: the failure, the deploy
state and swap reports, recent alerts, the last 300 server log lines, and the players with their client logs. A dev
can send one with `/tt bundle`. The alert names it (`d.bundle`). The server's page keeps its bundles, alerts, reports
and a timeline for 30 days after the server is gone (the Fleet page's **Recently gone** table).
Keep the backend current with the kernel: an older backend answers 404 to bundles, and the server then stops sending
them for its lifetime.
## Debugging endpoints
Two backend routes answer most "what is going on?" questions in seconds. Both take the admin token as
`Authorization: Bearer ` (never the game key).
```sh
curl -s -H "Authorization: Bearer $TYPETORCH_ADMIN_TOKEN" "$URL/v1/fleet/servers?branch=prod"
curl -s -X POST -H "Authorization: Bearer $TYPETORCH_ADMIN_TOKEN" -H "Content-Type: application/json" \
-d '{"sql": "SELECT count(*) FROM events WHERE t > epoch_ms(now()) - 600000"}' "$URL/v1/sql"
```
- **`GET /v1/fleet/servers?branch=&maxAge=`:** `{ servers, players, byArtifact, byHealth, geo }`. Each server has `job`,
`serverType`, `branch`, `channel`, `artifact`, `players`, `maxPlayers`, `placeId`, `placeVersion`, `experiment`,
`appliedSeq`, `generation`, `health`, `lastError`, `kernel`, `budget`, `tps`, `tpsMin`, `physFps`, `memMb`, `luaMb`,
`reasons` (why it needs a look), `location`, `ipChangedAt`, `cv` (the game's column values), `startedAt`, `lastSeen`
and `ageSeconds` (since the last heartbeat); the admin role also gets `ip` and `firstIp`. It is what
`typetorch servers` prints, with more fields. `?gone=1` lists servers that closed or were lost (kept 30 days).
`GET /v1/fleet/servers/` is one server of any age; `GET /v1/fleet/servers//metrics?since=