# 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 logo # 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=` is its TPS, memory and players history. - **`POST /v1/sql`** (DuckDB server, analytics part): `{ "sql": "...", "limit"?: n }`, one read-only `SELECT` or `WITH` over the views `events` and `recordings` (every day file plus today's live rows), at most 10,000 rows. The answer is `{ columns, rows, truncated, ms }`. `TYPETORCH_SQL=0` turns it off (404). It answers "is anything arriving?" long before a chart does. - **`GET /v1/identity/resolve?pid=...&uid=...`:** turns analytics pids into Roblox UserIds and back (ids only). A script or an LLM agent should use the backend's **lookup token** (`TYPETORCH_LOOKUP_TOKEN`), which works on this route only, instead of the admin token. - There is no `/v1/branches` or `/v1/registry` (404). Branch heads and the deployment history are in the CLI: `typetorch branch ls` and `typetorch deployments` ([the deployment log](https://www.typetorch.dev/guides/deploy-and-rollback.md#the-deployment-log)). ## In game: Manage > Servers The dev menu's server list (owners) doesn't use the fleet API or any storage. When you open it, your server asks every server over MessagingService (a roll call), collects the answers for 3 s and caches the list for 15 s. Each server answers with the same status the kernel sends as its heartbeat. See [The dev menu](https://www.typetorch.dev/guides/dev-menu.md#manage). Game code gets the same list, with public fields only, from [`TypeTorch.servers()`](https://www.typetorch.dev/guides/messaging.md#the-server-list). ## In the dev menu Server > Status shows these when the kernel's sender has a problem: | Attention item | Fix | |---|---| | No fleet API | the place's kernel lacks its `Fleet` module: map it in your place project (kernel 0.3.2+), then publish | | Fleet settings | the settings record's `backend` is invalid: run `backend setup` again | | No settings, Settings refused, Settings unreadable | the [settings record](https://www.typetorch.dev/guides/settings.md) is missing, unsigned or doesn't verify, or can't be read (`typetorch settings status`) | | Fleet API failing | the URL doesn't answer (a stopped server, a restarted quick tunnel) or the token is wrong | ## History The fleet API is the live view. The [AnalyticsEngine](https://www.typetorch.dev/guides/analytics.md) also forwards each server's status and deploy reports as `fleet` rows (option `fleet`, on by default), so the analytics queries `servers` and `deployReport` can look back further. --- # Live debug Your game declares what it wants to show on the backend explorer: read-only **commands** (buttons on a server's page), **streams** (values sampled while someone watches, `points` drawn on the live map) and **columns** on the Fleet page. The kernel also streams every player's position, so the explorer can draw a live map of one server or of all of them. - Framework **0.7.1**+ (`remoteDebug`, `fleet`) and kernel **0.5.7**+ in the place (a place project that maps the kernel's files one by one must map `LiveDebug`). Backend: main (unversioned). - It builds on [remote debug](https://www.typetorch.dev/guides/fleet-and-alerts.md#errors-debug-bundles-and-remote-debug) (kernel 0.5.0+): the same pull model, owner checks, limits and secret scrubbing. - The API reference is in [Runtime API: Live debug](https://www.typetorch.dev/guides/runtime-api.md#live-debug-server-only). ## In game code Server only (a client throws). Register in `onInit` or `onStart`, and hand each remover to the module's trove. ```ts import { fleet, remoteDebug, TypeTorch } from "@typetorch/framework"; // A button on /servers/ (op game.round_state). It must only read. this.trove.add( remoteDebug.command( "round_state", (args, caller) => ({ kind: "kv", items: { round: this.round, phase: this.phase, alive: this.alive.size() } }), { label: "Round", description: "The current round, its phase and how many are alive" }, ), ); // A table answer. this.trove.add( remoteDebug.command("spawners", () => ({ kind: "table", columns: ["name", "next", "active"], rows: this.spawners.map((s) => [s.name, s.nextAt, s.active]), })), ); // Sampled at 1 Hz only while someone watches this server; "points" draw as markers on the live map. this.trove.add( remoteDebug.stream("loot", () => ({ points: this.chests.map((c) => ({ x: c.X, y: c.Y, z: c.Z, label: "chest" })) }), { hz: 1, kind: "points", label: "Loot", }), ); // A Fleet page column, read whenever a heartbeat is built. this.trove.add(fleet.column("current_map", () => this.mapName, { label: "Map", type: "string" })); fleet.columnsChanged(); // after the map changed: a heartbeat soon (at most one per 10 s) remoteDebug.supported(); // true on a server whose kernel takes the declarations (also TypeTorch.features.liveDebug) ``` `TypeTorch.remoteDebug` and `TypeTorch.fleet` are the same objects. On older kernels and in edit mode every call is accepted and checked, and nothing reaches the backend. ## Limits | What | Limit | |---|---| | Names (commands, streams, columns) | `^[a-z][a-z0-9_]{0,31}$` | | Commands per server | 32 (label at most 40 characters, description at most 200) | | Streams per server | 8, at 0.2 to 4 Hz; `kind` `"points"` or `"json"` (default) | | Columns per server | 15 of your own (framework 0.7.4+: the built-in `tt_framework` takes the kernel's 16th; `tt_` names are reserved); a value is a string (at most 64 characters), a number, a boolean or nothing; `type` `"string"`, `"number"` or `"bool"` is a display hint | | Command args | an optional JSON object of at most 2 KB | | Command answer | at most 200 KB, scrubbed of the settings' keys and tokens | | Command calls | owners only; the backend takes 30 a minute per explorer user and 60 per server, the kernel runs 30 a minute, each with a 10 s deadline | | Stream sample | at most 16 KB of JSON (bigger samples are dropped and counted); `points`: `{ points: [{ x, y, z, label?, color? }] }`, `color` a CSS colour | | Getters and samplers | run on kernel threads under pcall with a short deadline: keep them cheap and never yield | A bad name or option, a duplicate, or one past a limit throws at once. ## What the explorer shows | Where | What | |---|---| | A server's **Game** tab (`/servers/`) | a button per declared command, labelled **game-defined**, with optional JSON args. `{ kind: "table", columns, rows }` draws as a table, `{ kind: "kv", items }` as key-value pairs, anything else as JSON. Below, each stream's latest value | | A server's **Live map** tab | the server's players on the [exported map](https://www.typetorch.dev/guides/recordings-and-maps.md#maps): positions at 2 Hz, a map switcher, 2D / 3D and the height band, the name on hover, a 20 s trail, your `points` streams as markers (each point in its `color`, else the stream's; a point's `label` isn't drawn). Click a dot or **Follow** to follow a player | | **Live map** (`/live`, next to Fleet) | every live server's players at once, coloured per server. While it is open, servers post only positions, one frame every 3 s | | **Fleet** page, **Columns** button | your custom columns (hidden until turned on), as the union of what the live servers declared. The **Framework** column (framework 0.7.4+, each server's TypeTorch framework version) shows by default | The server page's tabs only connect while it is open: the backend tells that server it is watched, and the server polls and posts. Nothing extra is sent while nobody watches. With the instant wake (an Open Cloud messaging key on the backend) a server answers within seconds; else at its next heartbeat (up to 30 s). ## Safety rules - **Commands must be read-only.** That is your promise: the kernel can't check what a handler does. The explorer labels them game-defined, and only owners can run them. Review a command like any owner-only code: no kicks, no data writes, no grants. - **No personal data in columns.** Column values are stored with the server row in the backend's database. Never put player names, UserIds or anything personal in one; game state only (map, round, mode, counts). - **Streams are kept in memory only.** Positions and stream frames hold player names, UserIds and positions: the backend keeps the last 120 s per server (bounded in size), never writes them to disk, a log or the event bus, and drops them the moment the server closes or is lost. The explorer keeps them in the page only. - Command args are audited by size only, never their values. Answers are never stored or logged. - The routes that run commands, watch servers and read streams or the live map are owners only; the read-only web role sees the Fleet columns. ## Routes | Route | Role | What | |---|---|---| | `POST /v1/fleet/servers//commands` | owners | `{ op: "game.", args? }`, taken only when that server declared the command (else 400) | | `GET /v1/fleet/servers//streams?since=` | owners | `{ declared: { streams, commands }, frames: [{ t, s }] }`, oldest first | | `POST /v1/fleet/live-map/watch` | owners | the `/live` page is open (sent every 20 s; lapses after 60 s) | | `GET /v1/fleet/live-map` | owners | each live server's latest positions frame of the last 15 s | | `GET /v1/fleet/columns` | owners, viewers | the declared columns of the live servers | | `POST /v1/fleet/streams` | game key | the kernel's samples (at most 64 KB and 32 frames a post, 90 posts a minute per server) | The wire format (heartbeat fields `xh`, `xd`, `cv`) is in the backend README's [Game-defined debug, streams and the live map](https://github.com/typetorch/backend#game-defined-debug-streams-and-the-live-map). --- # The explorer The explorer is the web app the [backend](https://github.com/typetorch/backend) serves at its own URL: your [analytics](https://www.typetorch.dev/guides/analytics.md), live servers, deploys, errors and the backend itself in one place. It reads the same routes as the CLI and your scripts, and it changes nothing on a game server. The [mobile app](https://www.typetorch.dev/guides/mobile-app.md) shows most of these pages natively on an Android phone. - The Docker image builds it. From a checkout: `bun run web:install` and `bun run web:build` (into `web/dist`). - `TYPETORCH_EXPLORER=off` serves the API only. - Everything below is on the backend's main branch (the backend is unversioned: it runs from a checkout or its image). - Try it without a backend: the [live demo](https://demo.typetorch.dev) runs the explorer in your browser on anonymized sample data, with you signed in as an owner. Changes stay in your browser. ![The Overview page: players, sessions, playtime and deploy markers](https://www.typetorch.dev/screenshots/overview.png) ![The Fleet page: live servers with their branch, build, players, health, TPS, memory and kernel](https://www.typetorch.dev/screenshots/fleet.png) Contents: [Sign in and roles](https://www.typetorch.dev/guides/explorer.md#sign-in-and-roles) · [Pages](https://www.typetorch.dev/guides/explorer.md#pages) · [The filter bar](https://www.typetorch.dev/guides/explorer.md#the-filter-bar) · [Command palette](https://www.typetorch.dev/guides/explorer.md#command-palette) · [Compare and explain](https://www.typetorch.dev/guides/explorer.md#compare-and-explain) · [Deploy markers](https://www.typetorch.dev/guides/explorer.md#deploy-markers) · [Saved queries](https://www.typetorch.dev/guides/explorer.md#saved-queries) · [Tables and links](https://www.typetorch.dev/guides/explorer.md#tables-and-links) · [Roblox parity](https://www.typetorch.dev/guides/explorer.md#roblox-parity) · [Working on it](https://www.typetorch.dev/guides/explorer.md#working-on-it) ## Sign in and roles | Who | Role | How they sign in | |---|---|---| | **Owners** (the access list in the game's [signed settings](https://www.typetorch.dev/guides/settings.md), sent by the CLI on every settings write) | admin | Sign in with Roblox (the backend's own OAuth app), Sign in with typetorch.dev, or the admin token | | **Viewers** (Roblox UserIds in `TYPETORCH_WEB_VIEWERS`, or on the Settings page) | web (read-only) | Sign in with Roblox or typetorch.dev; there is no token for this role | - The **web** role sees the game's data (queries, SQL, errors, fleet lists, server pages) but never the server's own configuration, and every write answers 403. Its sessions show **read-only** next to the name. The pages marked *owners* below are hidden from it. - A session lasts 3 days from sign-in (`TYPETORCH_SESSION_MAX_DAYS`) and survives backend deploys. - `TYPETORCH_TOKEN_LOGIN=off` hides the admin-token login in the browser (the CLI's Bearer token still works). - Details: [Security model](https://www.typetorch.dev/guides/security.md), [API keys](https://www.typetorch.dev/guides/api-keys.md), and the backend README's [Security](https://github.com/typetorch/backend#security). The sidebar has a place card on top (the game's name, live players and icon, `GET /v1/place`; also the tab title), and at its foot who is signed in, with Sign out. The header has the theme toggle (light, dark, system) and **Search...** (the [command palette](https://www.typetorch.dev/guides/explorer.md#command-palette)). ## Pages The sidebar groups them as below. Most pages use the shared [filter bar](https://www.typetorch.dev/guides/explorer.md#the-filter-bar); the ones marked *own range* or *own controls* leave it out and have their own controls instead. **Overview** | Page | What it shows | |---|---| | Overview | players, new and returning players, sessions, playtime, average session, playtime per player, per day (finer for a day or less); a Storage card; pinned [saved queries](https://www.typetorch.dev/guides/explorer.md#saved-queries) as tiles | **Players & gameplay** | Page | What it shows | |---|---| | Players | the players in the range with a churn **Risk** column and funnel columns, and a **Churn risk** section (active, at risk, lapsing, churned; for owners, how many at-risk players are subscribed to notifications). A player opens their detail: Roblox profile card, Spending, Playtime, Sessions, Timeline (with the raw join data `jd`), Errors, Feedback and Notifications views; a recorded first session links to its replay | | Events | the newest rows and the most logged names, by kind, name or player | | Funnels | logged funnels step by step, and the built-in **Playtime: total** and **Playtime: first session** funnels; Compare with another funnel; a step opens the players who reached it or dropped off there | | Flow | the merged [node graph](https://www.typetorch.dev/guides/analytics.md#node-graphs) of where players go next and where they quit | | Retention | two tabs over join-day cohorts: **Players back** (D1 to D30; today, UTC, as an orange partial cell) and **Revenue (LTV)** (revenue per player, Robux per player or payer share, D0 to D30). With the audience filters it answers "did this campaign pay back" | | Demographics | who plays: Roblox's own age, gender, language, country, platform and OS cards (needs the Open Cloud key, below), and from your join rows country, language, device, account age and Premium | | Notifications | [experience notifications](https://www.typetorch.dev/guides/notifications.md#the-funnel): the funnel, opt-in, the queue, one player's sends (*own range*) | | Feedback | [player feedback](https://www.typetorch.dev/guides/feedback.md): the distribution per scale, the trend and the list (*own range*) | | First session | the `confusion` signals: early leaves, screen loops, back-and-forth, idle spots, camera spins, repeated clicks; each links to its replays | | Recordings | first-session recordings on a map: layers, replay, quit autopsy, first actions ([Recordings and maps](https://www.typetorch.dev/guides/recordings-and-maps.md)) | | Maps | each map's exported geometry as a 2D minimap and a 3D map, with positioned events on it ([Recordings and maps](https://www.typetorch.dev/guides/recordings-and-maps.md#maps)) | | Economy | one currency at a time from server-sent `currency` rows: earned vs spent per day, the running balance, top sources and sinks | | Monetization | Robux from server-sent `purchase` rows: revenue (after Roblox's 30% cut, Robux paid next to it), purchases, payers, ARPDAU, revenue by product, payer conversion, ARPPU, repeat purchases, new players' first purchase; a product or a bar opens its buyers; Top buyers and Latest purchases | | Live events | scheduled live value changes and their lift reports ([Live events](https://www.typetorch.dev/guides/live-events.md); *own range*) | | Experiments | each experiment's state, weights, forced players and results per variant; the owners' **Run it** panel ([Experiments](https://www.typetorch.dev/guides/analytics.md#experiments)) | | Roblox | Creator Hub-style numbers (`benchmarks`, `realtime`, `trends`), concurrent players by device, and with the Open Cloud key the **Acquisition, from Roblox** section (Roblox's play-through rate and impressions) | **Observe & troubleshoot** | Page | What it shows | |---|---| | Fleet | (*own controls*) the live servers (TPS, memory, players; a Columns picker that also offers the game's [custom columns](https://www.typetorch.dev/guides/live-debug.md)) and the alerts. Every JobId opens `/servers/`: its history and, while it runs, the read-only remote debug tabs ([Live servers and alerts](https://www.typetorch.dev/guides/fleet-and-alerts.md#errors-debug-bundles-and-remote-debug)) | | Live map | (*own controls*) every live server's players on the exported map at once; its routes are owners only ([Live debug](https://www.typetorch.dev/guides/live-debug.md)) | | Deploys | (*own controls*) the deploy history, newest first; `/deploys/` shows one release with before vs after numbers ([Deploy history](https://www.typetorch.dev/guides/fleet-and-alerts.md#deploy-history)) | | Errors | (*own controls*) error kinds with their players and servers, drop rules (owners) | | Performance | client frame rate, memory and ping, server TPS and memory, by device, input, screen size, branch or build at p10 / p50 / p90 / p99, with problems flagged; Compare builds or before vs after a mark; Live servers | **Data** | Page | What it shows | |---|---| | Query | **Named query** (any [query](https://www.typetorch.dev/guides/analytics.md#queries) with its options) and **SQL** (one read-only `SELECT` over `events` and `recordings`, `POST /v1/sql`), with [saved queries](https://www.typetorch.dev/guides/explorer.md#saved-queries) | **Admin** (owners) | Page | What it shows | |---|---| | Settings | the runtime settings: alerts and backend alert rules, access (viewers, allow list, token login), rate limits, retention, API keys, notifications; Send test alert, backups and disk, recent changes ([Running the backend](https://www.typetorch.dev/guides/backend-operations.md)) | | Backend stats | the backend process itself: requests, queries and inserts per second, latency, memory, CPU, event loop lag, per route group | | Audit log | every state-changing admin action, filtered by actor, action and outcome | While Sign in with typetorch.dev is on, a **TypeTorch Dashboard** link sits at the bottom of the sidebar. ## The filter bar The shared filters live in the URL, so a view can be bookmarked or shared. | Filter | Values | |---|---| | Range | Last 1 hour, Last 6 hours, Today, Last 3 days, Last 7 / 30 / 90 days (30 by default), Since last prod deploy, Custom (dates) | | Branch, build, device | from the values seen in the range | | Players | new or returning | | Experiment | one experiment's variant | | **Audience** | country, language, account age, Premium, join source (URL `country`, `lang`, `age`, `prem`, `source`) | - Days are UTC. The hour presets send an exact instant; the day presets and custom ranges send dates. **Since last prod deploy** starts at the latest `prod` release in the deploy history (today when there is none). - Charts step by the window: per minute up to an hour, per 5 minutes up to 6 hours, per hour up to a day, else per day. - **Audience** filters are player-level: a player matches when one of their join rows in the range has the values, and then all their rows count ([Queries](https://www.typetorch.dev/guides/analytics.md#queries)). Countries and languages list what the range saw. The button names what is picked ("United States, Premium"). ## Command palette **Ctrl+K** (Cmd+K on a Mac, also from inside a text field) or the header's **Search...** button. - Fuzzy search over every page (the shared filters are kept; owner-only pages only for owners). - "Open player ``", the range presets, Clear filters, Copy link to this view, Refresh data, the theme, Sign out. Pages add their own (the Players page: Copy this player's pid). - Arrows and Enter run, Escape closes. An empty query lists your recent commands first (remembered in the browser). ## Compare and explain - **vs previous period**: a chip in the header of the Overview, Errors and Performance pages (`vs=prev` in the URL). The Overview's tiles get a change against the period before (same length, same filters; "7 days" compares with the 7 days before up to the same time of day), and each per-day chart a dashed previous-period line. - **Explain this change**: with the chip on, each Overview tile gets a **Why?** button, and the Retention page an **Explain the D1 change** button. A side panel runs the `explain` query: a plain headline ("D1 fell 4.1 points; 72% of it is phones (rate) ..."), both periods' values, the segments of one dimension (device, country, language, account age, Premium, join source, build, branch, new / returning) with their **rate** effect (the segment got better or worse) and **mix** effect (its share of players changed). Segments under 30 players are marked "few players". Click a segment to split it by the other dimensions. ## Deploy markers The time charts (Overview, error series, Performance, a server's graphs, Backend stats) carry a vertical line per release labelled `# `, plus kernel publishes, backup refreshes (`GET /v1/fleet/marks`) and each [live event](https://www.typetorch.dev/guides/live-events.md)'s start and end. Hover for details; a release opens its deploy page (Performance filters to that build instead). The **Deploys (n)** chip hides them on every chart (remembered in the browser). ## Saved queries On the Query page's SQL tab: - Pick a saved query to load and run it (`?saved=`, a shareable link). - Owners name and save it, choose a table, bar or line chart (the first column is the axis, up to four number columns the series), **Pin to Overview** (its own range, not the filter bar's), and delete it (for everyone). - Viewers list and run them. Saving never runs the query; each run is a normal `POST /v1/sql` with every check. - At most 200 queries and 12 pinned; the SQL of each at most 32 KB. Routes: `GET /v1/saved-queries`, `POST`, `PATCH /`, `DELETE /` (owners). ## Tables and links - Every table sorts (shift-click adds a column), searches, filters per column, has a **Columns** picker, resizable widths, pages, copy a cell or a row as JSON, and **Export** of the filtered view as CSV. Its view is remembered in the browser and written to the URL. - Entities link everywhere: a JobId opens its server page, a player their Players page, an error kind its side sheet, a build its errors and its Performance marks. - Hovering or focusing a player link opens a small card with the Roblox headshot, names, UserId and pid; a product id shows the product's name, icon and price. ## Roblox parity The Roblox page's `benchmarks`, `realtime` and `trends` follow Creator Hub's definitions: UTC days, full days only, a session counted on the day it started, DAU and MAU (30 days ending on the period's last day), new users as first-ever sessions, retention by first play date, ratios over several days as the mean of the daily values, revenue as Robux x 0.7, CCU as the peak minute. Studio play tests never count. What can't match is marked on the page: new users and retention are estimates (the first visit the SDK saw), revenue counts logged purchases only, CCU comes from heartbeats about once a minute, join sources are the game's own, and Creator Hub's numbers settle a day or more later. The full rules: the backend README's [Roblox parity](https://github.com/typetorch/backend#roblox-parity). **Roblox's own numbers** need `OPENCLOUD_API_KEY` with `universe.analytics:read` and `TYPETORCH_UNIVERSE_ID` on the backend: the Roblox page's Acquisition section (`GET /v1/roblox/analytics/acquisition`) and the Demographics page's Roblox cards (`GET /v1/roblox/demographics`). Without them the page says how to turn them on. Other scopes: [Open Cloud key scopes](https://www.typetorch.dev/guides/backend-operations.md#open-cloud-key-scopes). ## Working on it `bun run web:dev` in the backend repo (or `cd web && bun run dev -- --game `) starts Vite with a proxy to the backend, using the admin token from the game repo's `.env` (`TYPETORCH_ADMIN_TOKEN`) and the URL in `typetorch.json` (`backend.url`), or `--url http://127.0.0.1:8787`. The token never reaches the browser, and there is no login page. Adding a page: one line in `web/src/lib/nav.ts` and its route in `web/src/main.tsx`. --- # Analytics TypeTorch has its own analytics. It is optional and fully yours: your game logs what players do, your own backend stores it, and you query it yourself. It doesn't depend on Roblox's analytics (the explorer can show Roblox's own numbers next to yours when the backend has an Open Cloud key). Every event is labelled with the build (artifact) that was live, so you can compare builds, experiments and devices. - **Write side:** `AnalyticsEngine` in `@typetorch/framework` (0.3.0+), on the server and the client. - **Backend, your choice:** a self-hosted **DuckDB server** (one small VPS), or **Cloudflare Basin** (no server). - **Read side:** the [backend](https://github.com/typetorch/backend) (`@typetorch/backend`, run from a checkout or its Docker image; not on npm): the queries, the DuckDB server, the fleet API, `bun run report`, and the **web explorer** at the backend's URL ([The explorer](https://www.typetorch.dev/guides/explorer.md): its pages, filters and command palette). - **Live experiment overrides:** `typetorch experiment` (CLI 0.10.2+; [below](https://www.typetorch.dev/guides/analytics.md#experiments)), or prepared on the explorer's Experiments page. Contents: [Using it in a game](https://www.typetorch.dev/guides/analytics.md#using-it-in-a-game) · [What is collected](https://www.typetorch.dev/guides/analytics.md#what-is-collected) · [The event format](https://www.typetorch.dev/guides/analytics.md#the-event-format) · [Backends](https://www.typetorch.dev/guides/analytics.md#backends) · [Settings](https://www.typetorch.dev/guides/analytics.md#settings-the-analytics-field) · [Experiments](https://www.typetorch.dev/guides/analytics.md#experiments) · [Queries](https://www.typetorch.dev/guides/analytics.md#queries) · [Node graphs](https://www.typetorch.dev/guides/analytics.md#node-graphs) · [bun run report](https://www.typetorch.dev/guides/analytics.md#bun-run-report) · [Privacy](https://www.typetorch.dev/guides/analytics.md#privacy-and-right-to-erasure) · [Quick start: a local test](https://www.typetorch.dev/guides/analytics.md#quick-start-a-local-test) Related: [The explorer](https://www.typetorch.dev/guides/explorer.md) · [Recordings and maps](https://www.typetorch.dev/guides/recordings-and-maps.md) · [Live events](https://www.typetorch.dev/guides/live-events.md) · [Player feedback](https://www.typetorch.dev/guides/feedback.md) · [Notifications](https://www.typetorch.dev/guides/notifications.md) ## Using it in a game Nothing runs until you create an engine: no connections, threads or requests. Games that don't use it pay only the module load. ```ts // A server module (onInit) import { AnalyticsEngine } from "@typetorch/framework"; const analytics = new AnalyticsEngine(); analytics.track(player, "quest_done", { quest: "tutorial" }); // anything custom analytics.step(player, "onboarding", 3, "opened_shop"); // a funnel step: funnel, index, name analytics.purchase(player, { product: 1234, robux: 99, where: "shop" }); // after the receipt is granted analytics.currency(player, "coins", 50, "round_reward"); // economy: + in, - out analytics.state("round"); // every player's activity; analytics.state(player, "shop") for one const variant = analytics.experiment(player, "onboarding", ["short", "long"]); // the first is the control ``` ```ts // A client controller (onStart): everything goes through the server, never to the internet const analytics = new AnalyticsEngine(); analytics.track("opened_map"); analytics.screen("Inventory"); // for UIs that aren't separate ScreenGuis const variant = analytics.experiment("onboarding", ["short", "long"]); // the same answer as the server's ``` - **One engine per generation and realm.** Every `new AnalyticsEngine()` joins the one already running (the first one's options win), so any module can create its own. It stops with the generation. Unsent rows wait in `persist` and the next generation sends them, so a hot swap loses nothing. - **It starts on the first `new AnalyticsEngine()` of the generation**, not before. Create it in the `onInit` of a module with a low `loadOrder`. Created only from a helper that first runs on a game event, it doesn't start on an idle server, and that server sends nothing (no sessions, no tech rows). - **Server calls take the player first.** Without a player, an event is server-only (no player id). - **Client calls** are about the local player. They are marked `src = "client"` (a client can lie), and the server checks their shape, size (props at most 4 KB) and rate (120 a minute, 5,000 a session; a client's experiment calls count too). `purchase` and `currency` are server-only (revenue and the economy are server-authoritative): on the client they warn once and send nothing, and both the game server and the analytics server refuse them from clients. - **Revenue counts server-sent purchases only.** Payers and Robux come from `purchase` rows the server sent. Clients can't send `purchase` or `currency` at all (framework after 0.3.2; older engines' client rows are refused at ingest and never counted). Rows from before `src` existed still count. Call `analytics.purchase` on the server, after the receipt is granted. - **The cloud test sends nothing** (framework after 0.3.2). In `typetorch test --cloud` (before every prod deploy) the engine collects as usual but never uploads: no event rows, no identity rows, no HTTP request. A prod deploy never adds a fake server session. - **Options** (all on by default): `sessions`, `tech`, `zones`, `screens`, `recording`, `fleet`, `identity` ([privacy](https://www.typetorch.dev/guides/analytics.md#privacy-and-right-to-erasure)). `positions` (framework 0.7.1+) is a list of event names that always carry the player's position ([below](https://www.typetorch.dev/guides/analytics.md#positions)). `settings` (server only) replaces the [settings key](https://www.typetorch.dev/guides/analytics.md#settings-the-analytics-field), for tests. - `analytics.stats()` (server) returns the counters (queued, sent, dropped, refused); `analytics.flush()` sends soon. - In edit mode (UI Labs stories) it is inert. - The template has a complete example: `AnalyticsService` (server) and `AnalyticsController` (client). - Game settings: **Allow HTTP Requests** must be on (Game Settings > Security). ## What is collected **On every event:** the time, a random player id (never the UserId), the session, the server (JobId, type, place), the build (artifact id, `#seq`, branch, channel), the device, new vs returning, the player's experiment variants, and the player's state (`zone:Lobby|screen:Shop|activity:round`). **Automatic (the same in every game):** | Group | Option | Events | |---|---|---| | Sessions | `sessions` | join and leave, session length, where they came from (direct, teleport, friend follow, share link...), device and input type, screen size, account age bucket, Premium, country, language (`locale`), the player policy (ads, paid random items, trading, sharing, subscriptions, China, allowed links; framework 0.6.3), the device trust level (`Player.DeviceTrustLevel`, settled on the leave row; framework 0.6.3), friends in the server (one friend-list lookup per join), first visit or returning, days since the last visit | | Tech health | `tech` | server FPS and heartbeat, client FPS, ping, memory, load time, client and server errors, hot swaps and rollbacks, and who left within 60 s of a swap | | Zones | `zones` | entering and leaving zones: parts or models tagged `TTZone` in the place, named by a `Name` attribute or the instance name. The smallest zone around the player wins | | Screens | `screens` | ScreenGuis in PlayerGui, and GuiObjects tagged `TTScreen` | | First session | `recording` | [below](https://www.typetorch.dev/guides/analytics.md#the-first-ever-session-recorded-in-detail) | | Fleet | `fleet` | each server's status and deploy reports from the kernel, for history ([Fleet and alerts](https://www.typetorch.dev/guides/fleet-and-alerts.md) is the live view) | **From your code (game-specific):** funnels such as onboarding (`step`), purchases (`purchase`), currency in and out (`currency`), activities (`state`), and anything custom (`track`). **Player data collected.** The analytics are about identifiable players, not anonymous ones. Every row carries the pid, and the pid maps to the player's UserId (your DataStore link and your server's identity rows, under [Privacy](https://www.typetorch.dev/guides/analytics.md#privacy-and-right-to-erasure)), so every row, recording and feedback text can be traced to a Roblox account. The join row has the player's country, locale, account age, membership, policy flags, friends in the server and join data; the device row their device and screen size. The extended recording (framework 0.7.2, plans/36) stores the game's on-screen UI as drawn: usernames and display names (the player's and other players') wherever your UI shows them, and the text typed into TextBoxes (no privacy filters). Feedback rows keep the text the player wrote. **Not collected:** Roblox chat messages (CoreGui, which the recorders don't see). The first-ever session recording logs no keys while a TextBox or the chat has focus, and error texts have player names replaced with ``. ### The first-ever session, recorded in detail Only a player's first session in the game is recorded, from the start until `recordSeconds` after their first input (60 s by default, 10-600; at most 10 minutes from the start; framework 0.7.1+, older frameworks always use 60 s). About 10 times a second it samples the character position and facing and the camera. It also records each input (key, click, tap, gamepad button, thumbstick), each button pressed or hovered (by path, e.g. `Shop/Buy/Coins100`), screens opened and closed, proximity prompts, deaths and spawns, and your own `track()` events in that window. - Keys are never recorded while a TextBox or the chat has focus. A text box only says which box was used, never its text. - It is packed into small binary chunks (`tt-rec-1`), sent through the server: about 10-20 KB per new player at the default 60 s, about 55-70 KB at 300 s and 110-135 KB at 600 s. A recording also ends at 256 KB or 80 chunks. - `recordShare` (0 to 1) in the settings picks the share of new players who are recorded (stable per player). Turn it down first when volume spikes. - The explorer's **Recordings** page draws them on a map and replays them: [Recordings and maps](https://www.typetorch.dev/guides/recordings-and-maps.md). ### Extended recording Framework 0.7.2+ (plans/36) can also record poses, other characters and tracked models, animations and the UI tree (codec tt-ext-1) for some recorded sessions. Who gets it is the built-in experiment `tt_extended_recording` (variants `off`, `on`), only in sessions recorded in detail (`recordShare`) of players under `maxPlaytime` seconds of playtime: with no override nobody does. Its dials are `extended` in the settings, changed live with the CLI (0.20.0+), no deploy: ```sh bun run typetorch experiment weights tt_extended_recording 1,1 # half of the recorded sessions (settle ... on: all) bun run typetorch analytics extended show # each dial: the record's value or the default bun run typetorch analytics extended set seconds 600 --dry-run # before and after, nothing written bun run typetorch analytics extended set seconds 600 # 10 minutes after the first input, the most bun run typetorch analytics extended unset seconds # back to the default ``` | Dial | Range | Default | What | |---|---|---|---| | `seconds` | 10-600 | 300 | seconds an extended session records after the first input (its tt-rec-1 stream runs as long) | | `maxPlaytime` | 0-86400 | 60 | eligible while total playtime at the join is under this many seconds | | `afkSeconds` | 5-600 | 30 | no input and no movement this long = AFK | | `hz` | 1-10 | 3.33 | pose / move / UI polls a second | | `entMax` | 0-255 | 24 | the most entities recorded at once, nearest first | | `entRadius` | 10-2000 | 150 | entities farther from the camera (studs) aren't recorded | | `uiBudgetMs` | 0.05-4 | 0.25 | UI poll time per frame, ms (phones and tablets: 0.6 of it) | | `uiKeyframeSeconds` | 10-600 | 60 | seconds between UI keyframes | | `dryRun` | true / false | false | build everything, send nothing, report the counts | | `streams.pose`, `streams.ent`, `streams.ui`, `streams.view` | true / false | true | which streams run | The CLI refuses a value out of range (servers would clamp it), signs the record with both prod keys and writes the dials to `backend.analytics.extended` and the `analytics` field (a Basin sink reads that one); nothing else in the record changes. Don't set them from game code (`new AnalyticsEngine({ settings })`): that replaces the whole analytics config. ### Positions Framework 0.7.1+. Game-code events (`custom`, `funnel`, `purchase`, `currency`) can carry the player's character position as the props `px`, `py`, `pz` (studs, rounded to 0.1; the model's PrimaryPart, else `HumanoidRootPart`). The explorer's map layers read exactly these keys. ```ts // One event: the event's player (client: the local player), or any player analytics.track(player, "down", { cause: "fall" }, { position: true }); // Every event with one of these names, whichever call logs it (at most 64 names) const analytics = new AnalyticsEngine({ positions: ["down", "death_final", "round_result"] }); ``` - The settings' `positions` list ([below](https://www.typetorch.dev/guides/analytics.md#settings-the-analytics-field)) adds names live, without a deploy. A client event logged before the server's hello doesn't know that list yet; the engine option works from the start. - Nothing is added without a character or root part, and props the game set itself (`px`, `py` or `pz`) are never overwritten. - **Which map:** put the map's name in a `map` prop on some event (for example `track(player, "round_start", { map: "Forest" })`). The backend files each position under the latest map event before it, and exports the models that match those names ([Recordings and maps](https://www.typetorch.dev/guides/recordings-and-maps.md)). ## The event format Two tables of flat JSON rows. Every column is always present: a missing value is `""`, `0` or `false`. The full contract, with every event and its props, is [SCHEMA.md](https://github.com/typetorch/framework/blob/main/src/analytics/SCHEMA.md) in the framework. **events:** | Column | Meaning | |---|---| | `v` | format version, `1` | | `t` | unix ms, on the game server's clock (client events are corrected) | | `kind` | `session`, `tech`, `zone`, `funnel`, `purchase`, `currency`, `state`, `experiment`, `custom`, `recording_meta`, `fleet`, `notify` ([below](https://www.typetorch.dev/guides/analytics.md#notification-rows)), `feedback` ([Player feedback](https://www.typetorch.dev/guides/feedback.md)) | | `name` | the event name (1-64 characters) | | `pid`, `sid` | random player id and session id (`""` on server-only events) | | `job`, `srv`, `place` | JobId, server type (`public`, `private`, `reserved`, `studio`), PlaceId | | `art`, `seq`, `branch`, `channel` | the build that was live | | `dev` | `desktop`, `phone`, `tablet`, `console`, `vr`, `unknown` | | `newp` | part of the player's first-ever session | | `state` | the player's state after the event, `zone:\|screen:\|activity:` | | `exp` | the player's experiments as JSON, `{"onboarding":"short"}` | | `sexp` | the server's experiment: the artifact id of an A/B pin, or `""` | | `src` | `server` or `client` (`backend` on rows the backend writes itself: [notification rows](https://www.typetorch.dev/guides/analytics.md#notification-rows)) | | `props` | the event's own data as JSON text, at most 4096 bytes | **recordings** (first sessions): `v`, `t`, `pid`, `sid`, `job`, `art`, `chunk`, `codec` (`tt-rec-1`), `data` (base64), `n`. Delivery is at least once: a hot swap during a request sends that batch again. The DuckDB server drops exact duplicates when it writes each day's file. ### The join row The `session` row written when a player joins carries all of Roblox's join data and the player facts, in `props`: | Prop | From | Note | |---|---|---| | `from` | | `direct`, `teleport`, `teleport_game`, `referral`, `share`, `follow`, or `notification` (a [notification](https://www.typetorch.dev/guides/notifications.md) tap whose launch data verified) | | `nid`, `nk` | the launch data | the notification's send id and kind, only with `from = "notification"` | | `launch` | LaunchData | `notification` (verified), `tt_bad` (starts with `tt1n.` but fails the check; `launch_bad` says why: `sig`, `user`, `old`, `format`), or, for your game's own launch data, its first 32 characters only when the analytics setting `joinLaunchPrefix` is `true` (in the settings record's `backend.analytics`; default off, since launch data can hold anything). Its length is always kept as `launch_len` | | `src_place`, `src_game` | SourcePlaceId, SourceGameId | public ids | | `ref` | ReferredByPlayerId | the referrer's pid when this backend has seen them, else `"other"`; never a UserId | | `follow` | FollowUserId | the same treatment | | `party`, `party_pids` | Members | the party's size, and the pids of members seen before | | `ctx`, `ctx_item`, `ctx_asset`, `ctx_outfit`, `ctx_asset_type` | GameJoinContext | JoinSource, ItemType, AssetId, OutfitId, AssetType | | `tp`, `tp_bytes` | TeleportData | whether there is any, and its JSON size (never the content) | | `age_days` | AccountAge | exact days, next to the age bucket | | `locale` | Player.LocaleId | e.g. `en-us`; the explorer's language card and `lang` filter read it. Framework 0.7.1 writes it on every join row (also with `joinData` `"off"`); 0.6.0-0.7.0 wrote it with the rest of the join data, not with `"off"` | | `verified` | HasVerifiedBadge | | | `membership` | MembershipType | its name | No raw UserId of another player leaves the game: the row's own pid stays its only identity. Other players' pids (`ref`, `follow`, `party_pids`) cost a DataStore read each, so a join looks up at most 2 of them; the rest count as `"other"` or aren't listed. #### `jd`: the raw join data Next to the summary props above, the join row keeps a privacy-safe copy of `Player:GetJoinData()` itself as the prop `jd`, field by field, so you can see exactly what Roblox handed the server (for example, whether a notification's launch data arrived at all). It is on by default; [`backend.analytics.joinData`](https://www.typetorch.dev/guides/settings.md#join-data-backendanalyticsjoindata) turns it off (`"summary"`) or trims the join row further (`"off"`). | `jd` field | From `GetJoinData()` | What is kept | |---|---|---| | `keys` | the table's top-level keys | every key Roblox returned, sorted | | `LaunchData` | LaunchData | the string, cut to 200 bytes (Roblox's own limit) at a UTF-8 boundary. Present only when Roblox sent the key, even as `""` | | `LaunchDataLen` | LaunchData | its full length in bytes, before any cut | | `SourcePlaceId`, `SourceGameId` | the same | numbers (public ids), present only when Roblox sent them | | `GameJoinContext` | GameJoinContext | every field as a string (enum items by name). `{}` means Roblox sent the key with nothing in it; no `GameJoinContext` means it didn't send the key | | `TeleportData` | TeleportData | `{ bytes, type, keys }`: its JSON size, its Luau type and, for a table, its top-level keys (at most 20, each cut to 32 characters, sorted). **Never its content** | | `Members` | Members | `{ count, pids }`: each party member's pid, or `"other"`. Never a UserId | | `ReferredByPlayerId`, `FollowUserId` | the same | the player's pid, or `"other"`; absent when Roblox sent 0 or nothing. Never a UserId | | `other` | any key Roblox adds later | `{ "": "" }`: the type only, never the value | | `trunc` | | `true` only when `jd` was cut to fit its cap | - **Other players are pids or `"other"`.** Looking a player's pid up costs a DataStore read; `jd` and the summary props (`ref`, `follow`, `party_pids`) share the same budget of at most 2 reads per join, and one lookup per player serves both. Everyone past the budget, or never seen, is `"other"`. - **At most 1 KB.** When the JSON is bigger, it is cut in this order until it fits, and `trunc: true` is set: `TeleportData.keys` (then `TeleportData` itself), `Members.pids`, `LaunchData` (shortened; `LaunchDataLen` keeps the real length), each `GameJoinContext` value (to 64 characters), then `other`. - **Where you see it:** the explorer's player **Timeline** shows it on the join event (pretty-printed, collapsible, with a `trunc` badge when cut). The **Notifications** page's per-player view shows the opening session's `jd` next to each opened notification, where the backend provides it. Example: a player tapped a notification, but the launch data never reached the server (there is no `nid` / `nk`, and `from` isn't `notification`). The row's `jd` shows that the key arrived empty. (This was a real case: the send put `join_experience` at the top level of the Open Cloud body instead of inside `payload`, so Roblox ignored it; the backend since puts it inside `payload`.) ```json { "keys": ["GameJoinContext", "LaunchData"], "LaunchData": "", "LaunchDataLen": 0, "GameJoinContext": {} } ``` ### Notification rows [Notifications](https://www.typetorch.dev/guides/notifications.md) write rows with `kind = "notify"`. The game server writes the framework's; the backend writes its own with `src = "backend"`, `sid` empty, and `pid` from the UserId it has seen before (else empty: the row still counts). No row holds a UserId. | `name` | Written by | Props | |---|---|---| | `want` | game server | `k` (kind), `key` (the first 12 hex of the key's SHA-256), `at`, `until`, `offline` | | `drop` | game server | `k`, `key`, `why` (the game's) | | `optin_check` | game server (from the client) | `can`, `where`, `err` | | `optin_shown` | game server | `where` | | `optin_closed` | game server | `where`, `secs` (how long the prompt was up) | | `optin_inferred` | backend | `state`: `subscribed` (a first send was accepted) or `not_subscribed` (Roblox said "not opted in") | | `planned` | backend | `nid`, `k`, `for` (the send time), `why` (`asap` / `hour`) | | `skipped` | backend | `k`, `why` (`online`, `quiet`, `capped_day`, `capped_week`, `lapsed`, `muted`, `outranked`, `expired`, `dropped`, `pref_off` (the player switched the kind off: `setOff`), `repeat`) | | `sent` | backend | `nid`, `k`, `try`, `roblox_id`, `category` | | `failed` | backend | `nid`, `k`, `http`, `code` (e.g. `bad_template`, `daily_limit`, `dup_refused`), `final` | | `open` | game server | `nid`, `k`, `age` (seconds since sent), `first` | | `open_bad` | game server | `why` (`sig`, `user`, `old`, `format`) | | `played` | game server | `nid`, `k`, `secs` (the opened session's length) | Roblox doesn't tell the game whether a player accepted the opt-in prompt, so `optin_closed` never says; the backend's `optin_inferred` is the only answer. ## Backends The game speaks one event format. An adapter on each side translates it for the backend you pick: the framework's sink writes (`basin` or `duckdb`), and the read side's store renders each query as SQL for that backend. | | DuckDB server | Cloudflare Basin | |---|---|---| | What you run | one Bun process on a small VPS (1 GB is enough) | nothing: Cloudflare's pipelines into Iceberg tables on R2 | | Ingest | gzip batches, appended to raw files first | JSON arrays to two stream endpoints | | Delay | seconds | one roll interval (60 s minimum; expect 1-2 minutes) | | Queries | `bun run report`, the HTTP API, `createStore` | `createStore` (Basin SQL, read-only) | | Deleting a player's rows | yes | no (rows lose their UserId link but stay) | | Live server status | the fleet API runs in the same process | run the fleet API alone (`TYPETORCH_PARTS=fleet`) | ### The DuckDB server The backend's analytics part (`src/server/main.ts` in the [backend](https://github.com/typetorch/backend) repo): Bun or Node 20+, DuckDB inside the process (no database server). - **Raw files first.** Each accepted batch is appended to a raw file and answered at once. A loader moves raw files into DuckDB every 5 s. A spike fills files, never the database, and nothing accepted is lost on a restart. - **Busy answer.** While the loader is behind, an event batch gets `503` with a `Retry-After` of 10 to 30 s, before the body is read. Framework 0.7.2+ waits at least that long before it sends the batch again. The limits and the Settings page are in [Running the backend](https://www.typetorch.dev/guides/backend-operations.md#runtime-settings). - **One Parquet file per day.** After midnight UTC each finished day is written as a compressed Parquet file (exact duplicates dropped), then rollups run. Queries read today's DuckDB file plus the day files in range. Old data goes by deleting old day files (`TYPETORCH_KEEP_DAYS`, 400 by default). - **Fits in 1 GB:** DuckDB is capped at 400 MB and spills to disk. Measured on one core: 10,000 events/s at a p99 of 35 ms and about 300 MB of memory. 1,000 players online is about 10 million events a day, far below that. - **Tokens:** game servers send with the write-only game key (`TYPETORCH_API_KEY`); queries need the admin token (`TYPETORCH_ADMIN_TOKEN`), which stays on your PC. - **A 1 GB VPS:** the backend README has the full guide (swap file, firewall, a systemd service, Caddy for TLS, backups): [Run it on a VPS without Docker](https://github.com/typetorch/backend#run-it-on-a-vps-without-docker). Back up the day files and the raw archives off the VPS. ### Cloudflare Basin Done once, in your own Cloudflare account (Workers Paid plan and R2). The backend README has every prompt: [Cloudflare Basin setup](https://github.com/typetorch/backend#cloudflare-basin-setup). In short: 1. Create two pipelines, `typetorch_events` and `typetorch_recordings`, with `npx wrangler basin pipelines setup`. Load their schemas from the backend repo's generated files, `basin/events.schema.json` and `basin/recordings.schema.json`. HTTP endpoint on, authentication on, Data Catalog (Iceberg), roll interval 60 s. 2. Create a **send-only** API token (Basin Pipelines Send). Game servers get this one. 3. Keep the R2 token (for Basin SQL), your account id and the bucket on your PC only. 4. Point the game at it with CLI 0.19.0+: `bun run typetorch backend setup --analytics basin --events --recordings `, with the send token as `BASIN_SEND_TOKEN` in the game's `.env`. Switch back with `--analytics duckdb`. A `backend setup` without `--analytics` keeps the sink the record already has ([settings](https://www.typetorch.dev/guides/analytics.md#settings-the-analytics-field)). Moving the history between Basin and a server: [Analytics to Basin and back](https://www.typetorch.dev/guides/emergency-scale-ups.md#4-analytics-to-basin-and-back). Know these before you start: - **Rows that don't match the schema are dropped silently** (the endpoint still answers 2xx). The framework sends every column on every row, so use the generated schemas exactly. - **Schemas are fixed when a stream is created.** A new format version means new streams. - **Basin SQL is read-only.** There is no DELETE, and every query needs a `LIMIT` of at most 10,000 (the queries handle this). It is billed by data scanned. - Not yet tested against a live Basin account (the backend README lists the open points). ## Settings: the `analytics` field Game servers read their sink settings from the game's [signed settings record](https://www.typetorch.dev/guides/settings.md) (kernel 0.3.8+). It is server-only (never sent to clients), and a change reaches running servers within seconds, so you change dials live, with no deploy or place publish. - **DuckDB (framework 0.4+, kernel 0.4+):** the record's `backend` = `{ url, key, analytics? }` is the sink: events go to `/v1/ingest` with the game key, and the dials come from `backend.analytics` (`flushSeconds`, `recordShare`, `recordSeconds`, `positions`, `techEvery`, `experiments`, and the join data dials `joinData` and `joinLaunchPrefix`: [Settings](https://www.typetorch.dev/guides/settings.md#the-analytics-dials-backendanalytics)). - **Separate ingest servers (framework 0.7.2+):** with `backend.ingest` in the record, events go to `/v1/ingest` with the same key, and everything else stays on `backend.url`. Set it with `backend setup --ingest ` (CLI 0.19.0+). [Several ingest servers](https://www.typetorch.dev/guides/emergency-scale-ups.md#5-several-ingest-servers-optional). - **Basin, and older frameworks:** the `analytics` field below. `backend setup --analytics basin` writes a Basin sink there. Without that flag `backend setup` keeps the sink that is already in the record, and it keeps deriving the field from `backend` for frameworks before 0.4. A Basin sink is always read from this field. ```json { "backend": "duckdb", "events": "https://analytics.example.com/v1/ingest", "token": "", "flushSeconds": 15, "recordShare": 1, "techEvery": 60, "experiments": { "onboarding": { "weights": [1, 1] } } } ``` | Field | Meaning | |---|---| | `backend` | `duckdb` or `basin` | | `events` | DuckDB: the server's ingest URL. Basin: the events stream endpoint | | `recordings` | Basin: the recordings stream endpoint (without it nothing is recorded). DuckDB: unused | | `token` | the write-only token: the DuckDB ingest token, or the Basin send token. Never logged | | `flushSeconds` | seconds between sends, 5-300 (default 15) | | `recordShare` | share of new players recorded in detail, 0-1 (default 1) | | `recordSeconds` | seconds a first-session recording runs after the first input, 10-600 (default 60; framework 0.7.1+) | | `positions` | event names (1-64 characters, at most 64) whose game-code events always carry `px`, `py`, `pz`, added to the engine option ([Positions](https://www.typetorch.dev/guides/analytics.md#positions); framework 0.7.1+) | | `techEvery` | seconds between tech samples, 15-3600 (default 60) | | `experiments` | live dials per [experiment](https://www.typetorch.dev/guides/analytics.md#experiments) | | `extended` | the [extended recording](https://www.typetorch.dev/guides/analytics.md#extended-recording)'s dials (framework 0.7.2+) | **How to write it:** `backend setup` writes it from the game folder, after it checks the backend's address and both keys ([settings](https://www.typetorch.dev/guides/settings.md#checked-before-it-is-signed)): ```sh bun run typetorch backend setup --url https://backend.example.com --flush-seconds 15 --record-share 1 ``` It derives this section from `backend` and keeps the other fields (`techEvery`, `experiments`). With `--analytics basin --events --recordings ` it writes a Basin sink instead (`backend` = `basin`, the two stream URLs, and the send token from `BASIN_SEND_TOKEN`; the record's `backend` keeps pointing at the server for the fleet). `--analytics duckdb` writes the server sink back. `typetorch experiment` writes the experiment overrides ([below](https://www.typetorch.dev/guides/analytics.md#experiments)) and `typetorch analytics extended` the extended recording's dials ([below](https://www.typetorch.dev/guides/analytics.md#extended-recording)). No command sets `techEvery`, `recordSeconds`, `positions` or the join data dials yet (`backend setup` keeps whatever is already in `backend.analytics`), and `settings set analytics` only points to `backend setup`. Read it back with `bun run typetorch settings get analytics` (the token hidden), and stop sending with `bun run typetorch settings unset backend` (it drops `fleet` and `analytics` too). The CLI signs the record with both prod keys, and servers refuse one that doesn't verify. From code, `writeBackendSettings({ gameDir, url, apiKey, adminToken })` from `@typetorch/backend` runs the same command. Without settings the engine still collects, but keeps only the newest 1,000 rows until settings appear. Removing them stops sending, live. On a kernel before 0.3.8 the engine sends nothing and warns once (update the kernel). ## Experiments Our own A/B tests, per player or per server. **Per player:** `analytics.experiment(player, "onboarding", ["short", "long"])` returns the player's variant. It is fixed per player and experiment name, so they keep it in every session, and both groups play on the same servers. The first call may yield briefly (until the player's id loads). Later events carry the variant in `exp`. You write the code for each variant. A session holds at most **32 experiments** (framework after 0.3.2). A 33rd name isn't assigned: the call returns the first variant (the control), isn't stamped, and logs a warning. Change it live with `typetorch experiment`, no deploy. It writes the override into the signed settings record (the same signed write as `settings set`: read, verify, change, sign with both keys, ping), so servers pick it up within seconds: ```sh bun run typetorch experiment list # every override, with the variants the backend saw (7 days) bun run typetorch experiment weights onboarding 3,1 # 75% get the first variant, 25% the second bun run typetorch experiment settle onboarding long # everyone gets "long", stamped: make it final bun run typetorch experiment stop onboarding # everyone gets the control (the first variant), not stamped bun run typetorch experiment resume onboarding # drop stop / settle, keep the weights bun run typetorch experiment clear onboarding # remove the override: equal split again bun run typetorch experiment force onboarding 123456 long # one player (UserId or pid) gets "long", for QA bun run typetorch experiment unforce onboarding 123456 ``` | Dial (in the override) | Set by | Effect | |---|---|---| | `"active": false` | `stop` | everyone gets the first variant (not stamped) | | `"weights": [3, 1]` | `weights` | 75% / 25%, in the order the game lists the variants | | `"variant": "long"` | `settle` | one variant for everyone | | `"players": { "": "long" }` | `force` | those players get that variant over everything else (at most 200; needs a framework that reads `players`) | - The variants live in game code, so the CLI can't check them by itself: `--variants a,b` (the game's list, in order) makes `weights` and `settle` check the count and the name first. `--dry-run` shows the override before and after. - Weights move as few players as possible: a player only switches when the boundary moves past their hash. - It needs a backend in the record (`typetorch backend setup`) first. The overrides live in `backend.analytics.experiments` (framework 0.4+), mirrored into the old `analytics.experiments`. Every change is logged to `experiments.jsonl` in the state dir; `settings status` lists the overrides. - The explorer's Experiments page shows each experiment's state, weights and forced players, and opens the players of a variant (`GET /v1/experiments` lists the overrides the backend knows; `GET /v1/experiments//players` the players, at most 200, each `random` or `forced`). **Pick your own variant (framework 0.7.1+).** In game, the dev menu's **Server > Experiments** lists every experiment the game asked about for you, your variant and why (random, forced by the settings, or your pick). A button per variant picks it for you, Clear drops the pick; the command palette has the same as "Experiment : use ". Devs where the dev-only tools are open to them, owners everywhere ([the dev menu](https://www.typetorch.dev/guides/dev-menu.md)); at most one change a second, and only ever your own variant. The pick is stored in the analytics DataStore (`dexp/`), follows you to every server, wins over the settings (stop, settle, weights, `players`), and is stamped `forced` on the experiment row, so the results leave you out. The game sees it the next time it asks for your variant, usually your next join. **Run it from the explorer (owners).** Under an experiment's results, the **Run it** panel has Start, Stop, Clear override, Change split and Settle. The backend never holds the signing keys, so it can't apply the change: it checks it, logs it in the audit log (`experiment.prepare`) and answers the exact command to run in the game's folder, with its `--dry-run` twin (`POST /v1/experiments//change`): ```sh typetorch experiment weights onboarding 3,1 --variants short,long ``` Viewers see no controls, and the route answers them 403. **Per server:** a share of servers runs a different build: a kernel A/B pin (`bun run typetorch pin --branch prod --pct 10`, signed on prod; on dev branches also the dev menu's "Load a build" > Share of a branch). Events from those servers carry the pinned artifact in `sexp`. The `experiment` query with `scope: "server"` compares each pin with the unpinned servers. Whole-server changes need more players to show a difference. **Results** come per variant (players, returned, payers, playtime, Robux, sessions) with "how sure" in plain words: `long keeps more players: 99% sure` (a two-proportion test; bootstrap or Welch for averages). Per player they also: - **leave forced players out:** a player whose `experiment` row in the range is marked `forced` (settled, `force`, or a dev's own pick) didn't get a random variant; `forcedPlayers` counts them; - **check the split** (sample ratio mismatch): the random assignments per variant against the override's weights, or an even split, with a chi-square test. Below p = 0.001 (at least 5 players expected per variant) the page warns not to trust the numbers: a variant that crashes or loses its events, a bug in when the game asks, bots, or a split changed inside the range. Uneven weights need the variant's position on the rows (`vi`, framework 0.7.1+); older rows are checked against an even split only; - **correct for several variants:** each variant is compared with the control, and with more than two variants `sure` uses Holm-corrected p-values (`pAdjusted`; the test's own is `pValue`); - **say what the traffic can find:** `mde` / `mdeLift` (the smallest true difference these group sizes find 80% of the time at 5%, the 5% split over the variants when there are more than two), `needed` (players per group for the observed difference) and `days` (how long at the range's traffic until it is sure; 0 = now, `null` = no difference to find). ## Queries Every query works on both backends, with the same filters: `from`, `to` (a date, ISO time or unix ms; a date-only `to` includes that day), `art`, `branch`, `channel`, `dev`, `players` (`"new"` or `"returning"`), `variant` (`{ experiment, variant }`), `sexp`, `place`. Without `from`, a query covers its default range. **Audience filters** (player-level): `country` (ISO codes, `"US"`), `lang` (language codes without the region, `"en"`, from the join row's `locale`), `age` (account-age buckets `<1d`, `1-7d`, `7-30d`, `30-90d`, `90-365d`, `1-3y`, `3y+`), `prem` (`true` / `false`) and `source` (the join's `from`: `direct`, `teleport`, `referral`, ...). Each takes one value or a list. A player matches when one of their join rows in the range has all the set values, and then **all** their rows count, so "players from this campaign" works on every query. Queries over server or fleet rows (`perf-server`, `servers`, `deployReport`, the server parts of `benchmarks` and `realtime`) don't take them, as they don't take `dev`. | Query | What it answers | Default range | |---|---|---| | **Players and retention** | | | | `overview` | players, new players, sessions, playtime, in total and per day (per hour, 5 min or minute for windows of a day or less) | 30 days | | `roblox` | Roblox-style numbers: first-play bounce (first session under 60 s), qualified plays (sessions of 5 min or more), D1/D7, playtime and play days per user, payer conversion, Robux per user and per payer | 30 days | | `benchmarks`, `realtime`, `trends` | the Roblox page: headline numbers as Creator Hub defines them for the last full UTC days vs the days before; concurrent players (peak and average, by device); daily or 12 / 6-hour moving averages per join source | 7, 7, 28 days | | `retention` | retention by join-day cohort (`days`: up to 31 offsets from 1 to 90; default 1, 3, 7, 14, 30) | 30 days | | `ltv` | revenue per join-day cohort: cumulative Robux per player, revenue per player (after Roblox's 30%), payer share by D0 to D30 | 30 days | | `churn` | churn risk per player: `active`, `at_risk`, `lapsing`, `churned`, from days since the last play against their usual gap | 90 days | | `demographics` | who plays, from join rows: country, language, device, account age, Premium (share of players) | 28 days | | `explain` | why a metric moved between two windows: per segment (device, country, language, account age, Premium, join source, build, branch, new / returning), split into rate and mix effects | 7 days | | **Funnels and flow** | | | | `funnel` | one funnel step by step: reached, share of the start, from the step before, median time, the biggest drop. Without a name, the list of funnels | 30 days | | `funnel-progress` | how far given players (`pids`, at most 500) got in each funnel | 30 days | | `funnel-players` | the players who reached, or dropped off at, one step (at most 200) | 30 days | | `playtime-funnel` | players whose playtime reached 30 s, 1 m, 3 m, 5 m, 10 m, 30 m, 1 h, 2 h (`measure`: `total` or `first` session) | 30 days | | `flow` | the merged graph for a group: where most players go next, and where they quit | 7 days | | `confusion` | first-session signals per zone and button: early leaves, opening and closing the same screen, walking back and forth, and from the recordings idle spots (10 s without input or movement), camera spins (360 degrees in 6 s without moving), repeated clicks (3 presses of one button within 2 s) | 14 days | | **One player** | | | | `players` | players seen in the range, most recent first, or top spenders (`sort: "robux"`); `search` = part of a pid | 30 days | | `timeline` | one player's sessions and events (by `pid`) | 90 days | | `player-graph` | one player's [node graph](https://www.typetorch.dev/guides/analytics.md#node-graphs) over all their sessions, or one (`sid`) | 90 days | | `player-stats` | one player's Robux, purchases, sessions and playtime per day, with each session and purchase | 30 days | | `player-events`, `player-summary` | the [support key](https://www.typetorch.dev/guides/api-keys.md) views: one player's named events, and their counts and totals | 30 days | | **Experiments** | | | | `experiment` | per-variant numbers and how sure (`scope: "player"` or `"server"`), the split check and what the traffic can find | 30 days | | `experiment-players` | the players in one experiment: variant, `random` or `forced`, when assigned (at most 200) | 30 days | | **Recordings and maps** ([Recordings and maps](https://www.typetorch.dev/guides/recordings-and-maps.md)) | | | | `recording-layers` | first-session recordings on a top-down map: paths, idle spots, deaths, screens, buttons, prompts, quits and positioned events | 7 days | | `recording-sessions`, `recording-replay` | the recorded sessions (by map cell, ending or signal), and one for the replay | 7, 30 days | | `quit-autopsy` | why first-session players quit: their last seconds against the players who stayed | 7 days | | `first-action` | seconds from spawn to the first move, screen, button, prompt and round start | 7 days | | `map-positions` | map names from the events' `map` prop, and positioned events per map in 0.5-4 stud cells | 7 days | | **Economy and revenue** | | | | `economy` | one currency's earned vs spent per day, the running balance, top sources and sinks | 30 days | | `monetization` | Robux, purchases and payers per day, revenue by product, payer conversion, ARPPU, ARPDAU, repeat purchases, first purchase of new players | 30 days | | `monetization-players`, `monetization-purchases` | who bought a product (or anything), and the latest purchases (at most 200) | 30 days | | **Notifications, feedback, live events** | | | | `notify-funnel`, `notify-optin`, `notify-queue`, `notify-player` | [notifications](https://www.typetorch.dev/guides/notifications.md): the funnel per kind, the opt-in prompt, the sender per hour, one player's rows | 14, 30, 1, 400 days | | `feedback-summary`, `feedback-list` | [player feedback](https://www.typetorch.dev/guides/feedback.md): the distribution per scale and trend, and the rows | 30 days | | `live-event-lift` | the raw numbers of a [live event](https://www.typetorch.dev/guides/live-events.md)'s lift report | 7 days | | **Performance** | | | | `perf-client` | client fps, memory and ping over time (p10 / p50 / p90 / p99) by device, input, screen size, branch or build | 7 days | | `perf-server` | server TPS, physics FPS, memory and players over time, by branch or build | 7 days | | `perf-compare` | client and server numbers for builds side by side, or before vs after a moment | 7 days | | **Raw and fleet** | | | | `events` | the newest rows, optionally of one `kind`, `name` or `pid` (up to 1,000) | 7 days | | `top-events` | the most logged names per kind | 7 days | | `values` | the branches, builds, channels and devices seen (for filter pickers) | 30 days | | `servers`, `deployReport` | fleet history from `fleet` rows (the live view is [Fleet and alerts](https://www.typetorch.dev/guides/fleet-and-alerts.md)) | 1, 2 days | Each query's options are in the [backend README](https://github.com/typetorch/backend#queries); `GET /v1/queries` lists the names with a summary and the default range. Run them in three ways: - `bun run report` in the backend repo: the main ones in your terminal ([below](https://www.typetorch.dev/guides/analytics.md#bun-run-report)). - **HTTP** (DuckDB server): `POST /v1/query/` with `Authorization: Bearer ` and the body `{ "filters": { "from": "2026-09-01", "dev": "phone" }, "options": { "funnel": "onboarding" } }`. The answer is `{ result, ms }`. The explorer's read-only viewers and named [API keys](https://www.typetorch.dev/guides/api-keys.md) with the right scope can query too. - **Code**, on either backend (a `.ts` file in a folder with `@typetorch/backend` installed, run with `bun`): ```ts import { createStore } from "@typetorch/backend"; const store = await createStore({ backend: "duckdb", url: "https://analytics.example.com", token: process.env.TYPETORCH_ADMIN_TOKEN! }); // or: { backend: "basin", accountId, bucket: "typetorch-analytics", token: } const numbers = await store.query("roblox", { from: "2026-09-01", players: "new" }); const result = await store.query("experiment", {}, { experiment: "onboarding" }); ``` `store.render(name, filters, options)` returns the SQL without running it. Useful options: `funnel` (`funnel` name), `timeline` and `player-graph` (`pid`), `flow` and `player-graph` (`facet`: `all`, `zone`, `screen` or `activity`; `minCount`; `maxEdges`), `experiment` (`experiment`, `scope`, `control`, `weights` for the split check), `explain` (`metric`, `dimension`, `baseline`). **"Is anything arriving?"** Ask the DuckDB server directly instead of waiting for a chart: `POST /v1/sql` with the admin token and one read-only `SELECT` over `events` and `recordings` (today's live rows included) answers in seconds. Charts bucket by time, so their newest bucket can trail by a few minutes. See [Debugging endpoints](https://www.typetorch.dev/guides/fleet-and-alerts.md#debugging-endpoints). ## Node graphs A graph's nodes are states (zones, screens, activities) and its edges are moves between them, with how often and how long players stayed. `player-graph` builds one player's graph over all their sessions; `flow` merges a group (new players, a variant, a build, a device). Graphs come back as data, and `toMermaid()` turns one into a Mermaid diagram that any Markdown viewer renders (GitHub too), or paste it into mermaid.live: ```ts const graph = await store.query("flow", { players: "new" }, { facet: "zone" }); console.log(graph.toMermaid()); // or JSON.stringify(graph) ``` ```mermaid flowchart LR n0["Lobby
397 visits, 93 players"] n1["Arena
329 visits, 71 players"] n2["Forest
269 visits, 68 players"] n0 -->|"151 · 48s"| n1 n1 -->|"137 · 40s"| n0 n0 -->|"115 · 56s"| n2 ``` ## bun run report A quick look at your data in your terminal, from a checkout of the [backend](https://github.com/typetorch/backend) while its server runs (`bun run local`, or your own server): ```sh bun run report -- --game ../my-game bun run report -- --game ../my-game --pid ``` It asks the running backend (`http://127.0.0.1:8787` by default, `--url` changes it) with the admin token from the game repo's `.env`, and prints the overview, the Roblox-style numbers, the top events, the `onboarding` funnel, experiments, the live servers, and one player's timeline and node graph (Mermaid). Without `--pid` it picks the player seen last. It never prints tokens. ## Privacy and Right to Erasure - **Events carry a random player id** (`pid`, 32 hex characters) in place of the UserId; the pid is linked to the UserId, so the rows are personal data. The link lives in your game's DataStore `TypeTorchAnalytics`, key `p/` = `{ pid, first, last }` (one read per join, a write on the first join and at leave). `first` marks the first-ever session. - **Deleting that key unlinks the player's analytics from their UserId**, on both backends. Unlinked is not anonymous: rows that stay (Basin) keep what they hold, and an extended recording still shows any names that were on screen. - **Your own server also keeps pid -> UserId.** Once a player's pid is known, the game server sends one identity row `{ pid, uid, t }` (the UserId and nothing else) per session to your analytics server: DuckDB games in the upload batch, Basin games to the backend's `/v1/identity` (Basin rows can't be deleted, so they never go there). It lands in a deletable table next to the fleet data, never in the events, and lets you look a player up by UserId (the explorer's Players page, `GET /v1/identity?uid=`) and answer erasure requests without a DataStore read. Players who joined before this update are mapped only by a backfill from the DataStore links (`POST /v1/identity/backfill`, needs `OPENCLOUD_API_KEY` with `universe-datastores.objects:list` and `:read`). Turn it off with the framework option `identity: false`. - **The DuckDB server also deletes the rows.** In Creator Hub > Webhooks, add `https:///v1/erasure` for "Right to erasure request" with a secret (`ROBLOX_WEBHOOK_SECRET`). The server checks Roblox's signature, ignores other games (`TYPETORCH_UNIVERSE_ID`), and maps the UserId to its pids through the identity table, and through Open Cloud when `OPENCLOUD_API_KEY` is set (a key with `universe-datastores.objects:read`; add `:delete` and `TYPETORCH_ERASURE_DELETE_LINK=1` to also delete the link). The pids' rows leave the live file at once; day files, rollups and raw archives are rewritten in the background, and later rows of those pids are dropped. Then the UserId's identity rows are deleted (and refused afterwards). Its log keeps the notification id and outcome, never the UserId. The admin token can also erase by pid: `POST /v1/erasure` `{ "pid": "..." }`. - **Basin can't delete rows** (its SQL is read-only). Delete the `p/` link with the rest of the player's data: their rows stay, unlinked (not anonymous: see above). ## Quick start: a local test The backend on your own PC, reached by game servers through a free Cloudflare quick tunnel. For trying it out: the tunnel URL changes every time it starts. Needs Bun, git and [cloudflared](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/). The steps are the backend's [Quick start (local)](https://github.com/typetorch/backend#quick-start-local). In short: 1. **Get the backend** next to your game: `git clone https://github.com/typetorch/backend`, then in that folder `bun install`, `bun run web:install` and `bun run web:build` (the explorer, once). 2. **Make two keys**, 32+ random characters each and different (`openssl rand -hex 32` makes one), and put them in the game repo's `.env` (gitignored): `TYPETORCH_API_KEY` (the game servers' write-only key) and `TYPETORCH_ADMIN_TOKEN` (yours, for the CLI and the explorer). 3. **Run it**, from the backend folder, pointing at the game repo: ```sh bun run local -- --game ../my-game ``` It starts the backend, opens a quick tunnel and runs `typetorch backend setup` in the game. That writes the settings record (it needs the prod signing keys, [fresh setup step 7](https://www.typetorch.dev/getting-started/fresh-setup.md#7-prod-signing-keys), and kernel 0.3.8+ in the place) with the backend's URL, and sets `backend.url` in `typetorch.json`. That local edit changes with every tunnel, so don't commit it. 4. **Check it:** open `https://.trycloudflare.com/healthz` in a browser; it answers `{"ok":true}`. ### Play, then look 1. Make sure the game creates an `AnalyticsEngine` on the server and the client (the template does), and deploy it, for example to `dev`. 2. Join a server and play for a minute. Running servers switch to the new backend URL and analytics settings within seconds of the write (new servers at once). 3. `bun run typetorch servers` lists your server. 4. In the backend folder: `bun run report -- --game ../my-game`. **When the tunnel restarts,** its URL changes: run `bun run local -- --game ../my-game` again (it runs `backend setup` for the new URL). For a real game, use a VPS with your own domain instead ([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)). --- # Recordings and maps See what new players did, and where, without Roblox Studio. The explorer draws first-session recordings and your positioned events on each map's real geometry, replays one session at a time, and says why players quit. - **Recordings** page (`/recordings`): map layers, replay, quit autopsy, first actions. - **Maps** page (`/maps`): each map exported from the place, as a 2D minimap and a 3D map. - Game side: framework 0.7.1+ for positions and `recordSeconds`; older frameworks still send recordings, with a fixed 60 s window. Backend: main (unversioned). Contents: [What the game sends](https://www.typetorch.dev/guides/recordings-and-maps.md#what-the-game-sends) · [Maps](https://www.typetorch.dev/guides/recordings-and-maps.md#maps) · [The Recordings page](https://www.typetorch.dev/guides/recordings-and-maps.md#the-recordings-page) · [Quit autopsy](https://www.typetorch.dev/guides/recordings-and-maps.md#quit-autopsy) · [First actions](https://www.typetorch.dev/guides/recordings-and-maps.md#first-actions) · [Queries](https://www.typetorch.dev/guides/recordings-and-maps.md#queries) · [Limits and speed](https://www.typetorch.dev/guides/recordings-and-maps.md#limits-and-speed) ## What the game sends ```ts // Server: positions on the events you want on the map, and the map's name on some event const analytics = new AnalyticsEngine({ positions: ["down", "death_final"] }); analytics.track(player, "round_start", { map: "Forest" }); analytics.track(player, "down", { cause: "fall" }); // carries px, py, pz: its name is in `positions` ``` | What | Why | How | |---|---|---| | First-session recordings | the paths, idle spots, deaths, screens, buttons, prompts and the replay | on by default (engine option `recording`); `recordShare` picks the share of new players, `recordSeconds` how long after the first input (default 60, 10-600) ([the first-ever session](https://www.typetorch.dev/guides/analytics.md#the-first-ever-session-recorded-in-detail)) | | Positions (`px`, `py`, `pz`) | your events as points on the map, at any time, not only in the first session | `track(..., { position: true })`, or the event name in the engine option or settings `positions` ([Positions](https://www.typetorch.dev/guides/analytics.md#positions)) | | A `map` prop | which map a position belongs to, and which models to export | any event whose props have `map`, e.g. `round_start { map }` | **Which map a point is on.** A sample, input or positioned event belongs to the map of the latest event before it on the same server whose props have the map key; else the player's own latest such event. These go to the **`(lobby / unknown)`** layer instead: a zone matching `lobby`, an empty map value, no map event yet, or a position far outside the map's area (a stale map while the player waits in the lobby). The queries take `mapKey` for a game that uses another prop name. ## Maps ### Export An owner presses **Export** on the Maps page (`POST /v1/maps/export`, audited). The backend runs a read-only Luau script in the place through Open Cloud Luau Execution: no Studio, no game code. - **Needs** `OPENCLOUD_API_KEY` with `universe.place.luau-execution-session:read` and `:write`, and `TYPETORCH_UNIVERSE_ID`. The place is the universe's root place (else the place the fleet's servers report). Without them the route answers 409. `asset:read` on the key lets the page say when the export is out of date. - **Which models are maps.** The names come from the events' `map` prop over the last 30 days (`map-positions`), plus any `names` in the request body (at most 50) and the overrides. The script packs every Model or Folder in Workspace, ReplicatedStorage and ServerStorage whose name matches one, ignoring case and punctuation (`parking_garage` finds `ParkingGarage`). One model per name: an override's first, else the one with the most parts, then the shortest path (the others are listed as alternatives). Names with no model are listed as unmatched. - **The lobby** is everything else with geometry in Workspace (not Terrain, not the camera), listed as `(lobby)`. Terrain is skipped. - **Every part counts**, visible or not: parts at transparency 0.95 or more are flagged invisible, never dropped (invisible walls shape where players walk). MeshParts and unions are exported as boxes of their size. - **Limits:** one export at a time (409 while one runs), at most one every 30 s (429 with `Retry-After`). Roblox allows 5 task creations a minute per key owner: a 429 from Roblox waits and retries, up to 5 times. The task times out after 180 s. The page shows the step (creating the task, queued on Roblox, running in the place, downloading the geometry, storing) and, on failure, why. - **Storage:** `/maps/` (an index with the latest export, a 20-entry history and the overrides, and one geometry file per map named by its content hash). - **Out of date:** when the place's newest version (Assets API; else the newest place version the fleet's servers reported in the last day) is newer than the exported one, the page says "out of date, export again". ### Alignment and overrides For each map, the backend checks the positioned events on it (last 30 days) against the map's box: `aligned` (80% or more inside), `partial` (from 20%), `off` (with a suggested offset), or `unknown` under 10 events. When it is `unknown`, the page runs the same check on the recordings' positions on that map and says which source it used. An owner's **override** (`PUT /v1/maps//override { path?, offset? }`, audited; `DELETE` removes it) sets the model to export (an instance path such as `ReplicatedStorage.assets.maps.Mall`, used at the next export) and/or an offset (applied at once, to the geometry, never to the events). The alignment card applies the suggested offset in one click. ### The Maps page - An export card (last export, place version, out of date, the Export button with its progress, unmatched names), a map picker, **2D / 3D** (3D: orbit with the mouse, fly with W A S D Q E; 2D: the same scene from above, north up, pan and zoom). - A **Y band**: floors found in the geometry, or a free height range. Geometry above and below is cut away, so indoor floors show in 2D. - **Layers:** one per positioned event, as dots or heat cells of 0.5, 1 or 2 studs. The filter bar applies. - **What's drawn:** the collision geometry (every part that collides, visible or invisible, in its own colour; invisible ones see-through), plus small visible decoration. Off by default, each behind a toggle: decorative meshes (meshes and unions that don't collide; their boxes are only bounding volumes) and markers and triggers (invisible parts that don't collide). - The view is in the URL (`map`, `mode=3d`, `draw=points`, `cell`, `band`, `decor=1`, `markers=1`, `hide`), on both pages, so a view is shareable. Reads are open to every signed-in role: `GET /v1/maps` (the export, its state, the maps with bounds, part counts and alignment) and `GET /v1/maps//geometry` (one map's binary, with an `ETag`; `(lobby)` for the lobby). The binary format is in the backend README's [Maps](https://github.com/typetorch/backend#maps). ## The Recordings page Four tabs. Their state is in the URL next to the filter bar's (`tab`, `map`, `layers`, `view`, `sid`, `win`). ![The Map layers tab: new players' positions as a heatmap on the game's exported map](https://www.typetorch.dev/screenshots/recordings.png) Try it in the [live demo](https://demo.typetorch.dev/recordings). | Tab | What it shows | |---|---| | **Map layers** | pick a map and toggle layers: positions, idle spots, deaths, spawns, screens opened and closed, button presses, prompts, quits, and every positioned event kind in the range. Per-layer value chips (screen names, button paths, an event split by a prop such as `cause`), zone and screen filters, heatmap or dots. Click a cell for the sessions with a point of the first picked layer there | | **Replay** | the sessions by how they ended, an id, or a confusion signal; then one session: the path, a moving dot with the camera's direction, a timeline of clicks, buttons, screens, prompts, deaths, your events and confusion signals, play / pause at 0.5x to 8x; device, build and why it ended | | **Quit autopsy** | the last 5 / 10 / 20 / 30 s before quitting ([below](https://www.typetorch.dev/guides/recordings-and-maps.md#quit-autopsy)) | | **First actions** | seconds from spawn to the first move, screen, button, prompt and round start ([below](https://www.typetorch.dev/guides/recordings-and-maps.md#first-actions)) | - A map with an export is drawn on its real geometry, 2D or 3D, with a cell size of 0.5, 1 or 2 studs (default 2). Without an export, the page draws a silhouette: the density of every recorded position on the map. - The First session page links each idle, camera spin and repeated-click row to its replays. A player's first session on the Players page links to its replay. ## Quit autopsy For each recording that ended with the player leaving (`why = left`), the last `windowSeconds` (10 by default) get every reason that applies, so one session can count under several: | Reason | When | |---|---| | `screen` | a screen was open at the end | | `died` | a death, or a `down` / `death_final` event, within 20 s | | `idle` | no input and almost no movement | | `stuck` | movement keys or the stick, but almost no movement, no screen open | | `dead_clicks` | 2+ button presses with no screen change | | `tutorial` | the last step of a funnel matching `tutorial` or `onboard`, below the furthest step anyone reached | | `none` | none of the reasons above | | `place` | where the player stood: a cell of the map ("Forest · B3"), added to every session with a map | Each reason comes with its share among quitters, the same share among the players who played on (their last seconds), and the **lift** (over 1 = more common among quitters), with example sessions that open in the replay. So a reason shows as over-represented, not just common. ## First actions Per recorded first session: seconds from spawn to the first move (3 studs), the first screen the player opened (within 1.5 s of an input, so HUDs the game opens itself don't count), the first button press, the first prompt used, and the round start (from your events, default `round_start` or `phase`). Median, middle half, reached share and a histogram, in total, by device and by build. Move, screen, button and prompt are only seen inside the recording window. ## Queries All over `POST /v1/query/` with the usual filters ([Queries](https://www.typetorch.dev/guides/analytics.md#queries)): | Query | Default range | |---|---| | `recording-layers` | 7 days | | `recording-sessions` | 7 days | | `recording-replay` (`sid`) | 30 days | | `quit-autopsy` | 7 days | | `first-action` | 7 days | | `map-positions` | 7 days | Options (`mapKey`, `grid`, `cell`, `windowSeconds`, `downEvents`, `roundEvents`, ...): the backend README's [Recordings](https://github.com/typetorch/backend#recordings-maps-replays-quit-autopsy). ## Limits and speed - Recordings are decoded in the backend and cached in memory (96 MB). Past 3,000 sessions (`maxSessions`) a query samples them in a fixed order (the same range gives the same sample) and says so. - Positioned events are counted in SQL per 4-stud cell (the real-map view asks for finer cells). - Basin caps each statement at 10,000 rows; sessions are read in batches, and the answer says when the list hit the cap. - Recordings are keyed by the pid (linked to the UserId, like every row). The first-ever session recording holds no names; the extended recording (framework 0.7.2) stores the on-screen UI as drawn, so usernames, display names and TextBox text the game's UI shows are in it. Positioned events are ordinary event rows: erasure deletes them with the player's other rows ([Privacy](https://www.typetorch.dev/guides/analytics.md#privacy-and-right-to-erasure)). --- # Live events "Double cash, Saturday 12:00 to Sunday 23:59 UTC": schedule a change of your game's live values on the explorer's **Live events** page, sign it once with the CLI, and every game server switches it on and off at those times by itself. Afterwards the page reports whether the event raised playtime, revenue and so on, or only moved them in time. - Game side: framework 0.7.1+ (kernel 0.3.8+ for the signed settings record). Signing: any CLI with `typetorch settings set` (0.8+). - Backend: main (unversioned). The page lives under **Players & gameplay**. ## How it works ```mermaid sequenceDiagram participant O as Owner participant B as Backend (Live events page) participant C as CLI (your PC, prod keys) participant S as Game servers O->>B: schedule "Double cash" (keys, values, start, end) B-->>O: the schedule JSON and the exact command O->>C: typetorch settings set game.tt.events - C->>S: signed settings record (ping: read within seconds) Note over S: at start (server clock): liveConfig values switch on Note over S: at end: back to the record's own values B->>B: lift report after the event ``` - **The backend never signs.** Live values only reach servers through the signed settings record, and the prod keys stay on your machine. The backend keeps the schedule and prepares its JSON; you sign it like any other value. - **The times are inside the signed record** (`game["tt.events"]`, unix seconds, UTC). Each server switches on its own clock: no message at the start or end, a server that starts mid-event has it from its first read, and an event ends on time even when the backend is down. - **Cancelling** is signing the schedule without the event. Until you sign, servers still run it. ## Schedule one On the Live events page (owners): a name, 1-8 game keys with JSON values, and a start and end. The page then shows the command to sign the whole schedule (a bash / zsh one, a PowerShell one that reads `live-events.json`, and the JSON file). Run it in the game's folder: ```sh typetorch settings set game.tt.events - <<'TT_EVENTS' {"v":1,"events":[{"id":"ev_k3j9x0a1b2","name":"Double cash","start":1763812800,"end":1763942340,"set":{"cash.multiplier":2}}]} TT_EVENTS ``` The CLI reads the record, verifies it, sets the one key, signs it with both prod keys and pings servers ([Settings](https://www.typetorch.dev/guides/settings.md#reserved-game-keys)). **Checks** (the backend refuses anything else): | Rule | Limit | |---|---| | Name | 1-80 characters | | Values per event | 1-8 game keys (the CLI's key rule; not `tt.events` itself) | | A value | JSON, not `null`, at most 1 KB | | Start | ISO with a zone, or unix ms, whole seconds. Up to 5 minutes in the past starts now; never backdated | | Length | at most 31 days | | How far ahead | at most 366 days | | Overlap | no two events on the same key at the same time (409) | | Scheduled or live at once | at most 50 | | The schedule | at most 8 KB (the record's whole `game` field is 16 KB) | Servers read at most 64 events from a schedule. If two events set the same key at once, the later start wins. **Status:** `scheduled`, `live`, `ended` (from the times) or `cancelled`. Creating and cancelling are in the [audit log](https://www.typetorch.dev/guides/backend-operations.md#audit-log) (`live-events.create`, `live-events.cancel`), refused ones too. ## Do servers have it? With `OPENCLOUD_API_KEY` (`universe-datastores.objects:read`) and `TYPETORCH_UNIVERSE_ID`, the backend reads the signed record back (at most once a minute; **Check again**, `GET /v1/live-events?refresh=1`, at most every 10 s), checks its signature with the game's public keys when it knows them, and shows per event: | State | Meaning | |---|---| | `signed` | servers have this event as scheduled | | `outdated` | servers have it with other times or values: sign again | | `unsigned` | not in the signed record: servers won't run it | | `cancel-unsigned` | cancelled here but still signed: servers **will** run it until you sign | | `done` | ended, or cancelled and gone from the signed record | | `unknown` | the backend can't tell (no key, or signed by keys it doesn't know) | ## In game code `liveConfig` already follows the schedule: while an event runs, its values replace the record's `game[key]`, and `get()` and `onChanged` switch at the start and end. The game's `parse` still checks them. For UI ("Double cash ends in 3h"), `TypeTorch.liveEvents()` (server only): ```ts const multiplier = TypeTorch.liveConfig("cash.multiplier", { default: 1, parse: (raw) => (typeIs(raw, "number") ? raw : 1) }); multiplier.get(); // 2 while "Double cash" runs, else the record's value or 1 const events = TypeTorch.liveEvents(); events.active(); // [{ id, name, startsAt, endsAt, set }] running now events.upcoming(); // not started yet, in start order this.trove.add(events.onChanged((active) => this.showBanner(active))); ``` More in the [Runtime API](https://www.typetorch.dev/guides/runtime-api.md#live-events). A client throws; send what clients need through your own network. ## The lift report After an event (and while it runs, cut at now), the page compares it with normal weeks: `GET /v1/live-events//lift?weeks=3&afterDays=3`. - **Windows:** the event; the `afterDays` (default 3) after it, to see whether players only played earlier (pulled forward); and the baseline, the same weekdays and hours `weeks` weeks back (default 3, at most 8). A baseline week that overlaps another live event is skipped for an earlier one; a week with no players is dropped. - **Metrics per window:** players, playtime per player, sessions per player, Robux per player, payer conversion and new players (server-sent purchases only; Studio never counts). - **Math:** baseline = the mean of the baseline weeks; lift = event / baseline - 1. The range is how much a normal week moved (each baseline week against the mean of the others). Above the range is up, below is down, inside is no clear change; fewer than 2 weeks is "not enough baseline". A plain band you can check by hand, not a significance test. - **Net:** the event and after windows added up, for playtime, Robux, sessions and new players. Example: "+20% playtime per player (baseline range -5% to +5%) ... Dip after: -7% playtime per player ... part of it was pulled forward; net over the event and the 1 day after: +2% playtime." Each event's start and end are also dashed lines on every time chart in the explorer, next to the [deploy markers](https://www.typetorch.dev/guides/explorer.md#deploy-markers). The raw numbers are the `live-event-lift` query. ## Routes | Route | Role | What | |---|---|---| | `GET /v1/live-events` | every signed-in role | the events with their sync state, the schedule and the signing command | | `POST /v1/live-events` | owners | create one | | `POST /v1/live-events//cancel` | owners | cancel one (then sign the new schedule) | | `GET /v1/live-events//lift` | every signed-in role | the lift report (`weeks`, `afterDays`) | --- # Notifications Roblox experience notifications are the one push channel a game has: a short message on the player's phone or desktop that opens the game when tapped. TypeTorch runs them natively. **Your game says WHY a player should hear from it; the backend decides WHEN and WHAT and sends; the framework checks the tap and writes the rows.** You write no scheduler, no signer and no funnel. - Your game server queues **intents** (`want` / `drop`), also for players who are offline, and each player's switched-off kinds (`setOff`). - The [backend](https://github.com/typetorch/backend) plans each user's next send (**at most `dailyCap` a day per user**, 1 by default), sends it through Open Cloud with a **signed launch data token**, and retries. - When a player taps it, the framework verifies the token on the game server and calls your `onOpen`. These go to your players. The TypeTorch mobile app is different: it sends milestone pushes to you, the owner, about your game's live player count. See [Mobile app notifications](https://www.typetorch.dev/guides/mobile-notifications.md). - Every step is an analytics row (`kind = "notify"`), so the funnel (wanted, sent, opened, played) is on the explorer's **Notifications** page with no extra code. Roblox rules that shape all of this: only players who **opted in** (13 and over) get them; at most 1 per user per day per experience (refused at send time), plus an aggregate daily cap across experiences; TypeTorch's own `dailyCap` keeps you under it; delivery isn't guaranteed (Roblox scales reach with how often players engage with them); the message text is a **notification string** you create by hand in the Creator Dashboard, with `{placeholders}`. There is no API to create those strings: see [Templates](https://www.typetorch.dev/guides/notifications.md#templates). Adding them to a game for the first time? The [Playbook](https://www.typetorch.dev/guides/notifications.md#playbook-adding-notifications-to-a-game) walks through choosing kinds that pass Roblox's rules, testing the strings against Roblox's text filter, the game code pattern, preferences and the end-to-end check. ## Setup 1. **The backend** (`typetorch backend setup`, [Fleet and alerts](https://www.typetorch.dev/guides/fleet-and-alerts.md)) with an Open Cloud key that has the scope `user.user-notification:write`: `OPENCLOUD_NOTIFY_KEY` in the backend's environment, else its `OPENCLOUD_API_KEY`. `typetorch doctor` checks the scope on the same-named key in your game repo's `.env` (an empty request that can't send anything). 2. **The kinds** in `typetorch.json` (below), each with its `text`. 3. **The notification strings**: `typetorch notify templates`, make each one in the Creator Dashboard, then `typetorch notify templates set ` ([Templates](https://www.typetorch.dev/guides/notifications.md#templates)). Then `typetorch notify push`. 4. **The signing key**: `typetorch notify key rotate` (once; again whenever you want a new key). 5. **The game code**: `want` / `drop` (and `setOff` if players can switch kinds off) on the server, `promptOptIn` on the client, `onOpen` for taps. 6. **Turn off dry run** when the rows look right: the backend's Settings page, `notify.dryRun` (on by default). Updating: release the **backend first**, then the framework and the CLI (they need its routes). ## Kinds A kind is a reason to notify, declared once in `typetorch.json` and pushed to the backend: ```jsonc "notifications": { "dailyCap": 1, // ours; Roblox's is 1 too "quietAfterLeaveMinutes": 120, // nothing right after a session "lapse": [[14, 7], [30, 2], [60, 1]], // days since last seen -> max sends a week; past the last = stop "unopenedBackoff": { "after": 5, "factor": 0.5, "days": 14 }, "kinds": { "gift_new": { "text": "{sender} sent you {gift}!", "template": "", "priority": 10, "repeat": "per_key", "send": "preferred_hour", "maxWaitHours": 48 }, "gift_expiring": { "template": "", "priority": 20, "repeat": "per_key", "send": "asap" }, "day2": { "template": "", "priority": 30, "repeat": "once_ever" }, "streak": { "text": "Your {user-streak-remaining} day streak ends soon", "template": "", "priority": 60, "repeat": "daily" }, "daily": { "template": "", "priority": 70, "repeat": "daily", "perWeek": 3 } } } ``` | Field | Meaning | |---|---| | `text` | the notification string's text: at most 99 characters, `{placeholders}` named `a-z A-Z 0-9 _ -` (1-32 characters). You paste it into the Creator Dashboard ([Templates](https://www.typetorch.dev/guides/notifications.md#templates)); the backend checks each intent's `params` against its placeholders | | `template` | the notification string's message id. A kind without one is planned and counted, never sent | | `priority` | 0-1000, **lower wins** when several are due for one user on one day. Put event kinds (a new gift) above recurring ones (a streak reminder): a streak can go any day. The backend also **holds the day's slot**: when a send would fill `dailyCap` before a higher-priority intent's window opens (and the cap would not free again before that window ends), nothing is planned (skipped, why `held`) and the user is looked at again when that window opens | | `repeat` | `once_ever` (per user, forever), `per_key` (once per intent key, e.g. per gift id), `daily` (at most once a day) | | `send` | `preferred_hour` (default: the user's usual play hour inside the intent's window) or `asap` (the next sender tick) | | `perWeek` | 1-7: a cap for `daily` kinds | | `maxWaitHours` | how long a `preferred_hour` send may wait for that hour | | `category` | Roblox's dashboard groups impressions and clicks by it; default the kind name | | `allowTemplate` | `want(user, kind, { template })` may pick another message id for this kind. A game-supplied message id that Roblox doesn't know halts only that message id, not the kind | | `beats` | `{ "kinds": ["streak"], "withinHours": 4 }`: outranks those kinds only within its last N hours. Off by default | Top level: `dailyCap` 1-3 (only 1 matters while Roblox allows 1), `quietAfterLeaveMinutes`, `lapse` (in ascending days; players who drift away hear from you less, then not at all), `unopenedBackoff` (after N unopened sends in a row, send `factor` as often for `days`). Rules (the CLI checks them whenever it reads `typetorch.json`; the backend checks them again on push): kind names are 1-24 characters of `a-z 0-9 _`; `custom` is reserved for one-offs; template at most 128 characters; `text` at most 99 characters with every `{` closed and valid placeholder names; unknown fields are refused, so a typo can't silently do nothing. ## In game code ### Server: intents ```ts import { TypeTorch } from "@typetorch/framework"; const notify = TypeTorch.notifications(); // server // A gift to someone who may be offline: by UserId. notify.want(recipientUserId, "gift_new", { key: letterGuid, // one intent per key; want again = update it until: expiresAt, // unix seconds; default now + 7 days params: { sender: "Ava", gift: "5 Z-Coins" }, // exactly the text's {placeholders}: at most 8, values at most 64 characters data: "mail:" + letterGuid, // at most 64 bytes, handed back to onOpen on the tap }); // A streak about to break: not before 6 hours ahead of the deadline. notify.want(player, "streak", { key: "20034", at: deadline - 6 * 3600, until: deadline, params: { days: "5" } }); notify.drop(player, "streak", "20034"); // the reason is gone (they played) notify.drop(recipientUserId, "gift_new"); // every key of that kind // The player tapped a notification and joined. const disconnect = notify.onOpen((player, open) => { // open.nid, open.kind, open.data, open.ageSeconds, open.first (false when this tap was already counted) const [what, id] = open.data.split(":"); if (what === "mail" && id !== undefined) mailbox.open(player, id); }); ``` - `params` must name exactly the placeholders of the kind's `text` (dashes allowed: `{ "user-streak-remaining": "4" }`): the backend refuses a missing one (`missing_param`) or an extra one (`unknown_param`). A kind without `text` isn't checked. - `want` is an upsert per (user, kind, key): the last write wins. `at` is the earliest send time (default now), `until` the latest, and it must be after `at` (refused otherwise). Works for offline users. - Intents are batched like analytics (a swap-safe queue, flushed every `flushSeconds` and at 200 items) to the backend with the game key. Presence is added for you on join and leave, so nobody gets a notification while in the game or just after leaving. Game servers re-send "online" for every player still in the server every 3 hours; the backend treats an "online" older than `notify.presenceStaleHours` (default 6) as gone, so a server that crashed without its leave events doesn't block those players forever. - `onOpen` carries `data`, not the intent's `key` (the launch data has a 200-byte budget). Put what you need in `data`. - In Studio, or with no backend in the settings record, nothing is sent; the rows are still written. ### Server: kinds a player switched off If your settings let players switch notification kinds off, tell the backend with `setOff`. Checking the player's save before each `want` isn't enough: another server may `want` for this player while they are offline (a gift letter, a leaderboard pass), and it can't read their save. The backend keeps each user's off set and skips their intents of those kinds, whoever issued them. ```ts // Server. Signature: setOff(user: Player | number, kinds: string[]): boolean notify.setOff(player, ["daily", "quests"]); // the player's whole off set notify.setOff(player, []); // every kind on again ``` - It **replaces** the user's off set each time (not a toggle): send the full list whenever the setting changes, and once per join if your save is the source of truth (so a change made while the backend was unreachable catches up). - At most 32 kind names (1-24 of `[a-z0-9_]`); duplicates are ignored. A kind doesn't have to be pushed yet. - Ordered like `want` / `drop` (the item's `rev`: the latest call wins), batched and swap-safe through the same queue; `false` with a warning when the arguments are refused here. Server only. - The backend **keeps** the skipped intents (row `skipped` with `why = "pref_off"`): switching the kind back on resumes an intent whose window (`until`) is still open. A send already planned for a kind that is switched off is cancelled. - `typetorch notify test` sends ignore it, and so do custom one-offs (`typetorch notify send`). - The explorer's per-player view shows the kinds a player switched off. ### Client: the opt-in prompt ```ts const n = TypeTorch.notifications(); // client const result = n.promptOptIn("streak_2"); // yields: "shown" | "unavailable" | "error" | "busy" | "already" ``` - Show your own explainer first: Roblox's prompt text is fixed, and Roblox lets a game prompt a user at most once per 30 days. - `where` names the spot in your game (it lands in the rows, so you can compare spots). - One prompt at a time, at most once a session; a hot swap mid-prompt neither re-prompts nor loses the close row. - Roblox doesn't tell the game whether the player accepted. The backend learns it from its first send: accepted or "not opted in" (row `optin_inferred`). ## The funnel The explorer's **Notifications** page (backend) shows, per kind and day: wanted, planned, sent, opened, played 1 minute or more, back the next day; the opt-in funnel (checked, shown, closed, inferred subscribed) by `where`; the queue; and failures. Roblox's own impressions and clicks per category are in the Creator Dashboard only; TypeTorch doesn't import them. The page has tabs (the URL's `?tab=`): | Tab | Shows | |---|---| | Health | a status sentence, who can get notifications, opened and back next day per day, what needs attention | | Funnel | prompt shown, subscribed, sent, opened, played 1 minute+, back next day; sends per day; the opt-in prompt by spot | | Inbox (owners) | the newest sends of everyone, live, with filters, a side panel per send (its request, Roblox's answer, the join data) and the per-player view | | Subscribers (owners) | the opt-in list, with a CSV export | | Kinds | each kind's switch, by kind and day | | Queue & errors | the live queue, failures, planned and skipped by why, the history per hour | | Settings (owners) | the runtime settings `notify.*`, a test send, the pushed kinds | The read-only `web` role sees the analytics tabs only; the status, lists and controls are owner routes. **The opt-in list** (Subscribers tab; owners): Roblox has no list of opted-in players, so the backend keeps the answer it learned from each send. `GET /v1/notify/users?state=subscribed|not_subscribed|unknown|muted&q=&limit=&cursor=` answers one page (default 50, at most 200, newest first) plus the count of every state; `q` is a UserId or a name the profile cache knows. `format=csv` exports the filter (at most 10,000 rows, 6 exports a minute per owner). **Recent sends** (Inbox tab; owners): `GET /v1/notify/recent?limit=&kind=` answers the newest sends of everyone (default 100, at most 500), each with the player's opt-in state, the params and the name when the profile cache knows it. **Per player**: the page also looks up one player (by UserId, pid or username, owners only; the route is `GET /v1/notify/user?uid=|pid=|name=`): their consent (opt-in checks, prompts and the inferred answer, with dates), the kinds they switched off (`setOff`), the notifications they were sent (with opened / played, each send's request body and Roblox's refusal text) and their pending intents. The player page in the explorer has the same view (its **Notifications** button, owners only). A tap that verifies also marks the join row: `from = "notification"`, `nid`, `nk` (the kind). The session's `played` row gives its length, and every other row of that session shares its `sid`, so "what they did after the tap" is a join on `sid`. The rows are listed in [Analytics: notification rows](https://www.typetorch.dev/guides/analytics.md#notification-rows). ## Commands All of them use `typetorch.json` `backend.url` and `TYPETORCH_ADMIN_TOKEN` from the game repo's `.env`. ```sh bun run typetorch notify push # typetorch.json notifications -> the backend (checked first) bun run typetorch notify push --dry-run # show what would be pushed bun run typetorch notify templates # each kind's text to paste in the Creator Dashboard bun run typetorch notify templates set streak # write the new id into typetorch.json bun run typetorch notify status # on / paused, dry run, rate, keys (set or not), queue, 24 h, each kind bun run typetorch notify test 123456789 gift_new --param gift="5 Z-Coins" --data mail:42 bun run typetorch notify send 123456789 --param name=value bun run typetorch notify key rotate bun run typetorch notify pause # stop sending; intents keep queueing bun run typetorch notify resume bun run typetorch notify pause streak # one kind bun run typetorch notify resume streak ``` - `test` sends one notification of a kind now, **bypassing the caps** (marked `test`). Dry run still applies. - `send` is a one-off with any message id, as kind `custom` (the message id is its category). It **respects** the 1-a-day rule and mutes, so it may answer "not sent" with the reason. - `--param name=value` can be repeated (at most 8; names `a-z A-Z 0-9 _ -`, values at most 64 characters); `--data` is at most 64 bytes. - `pause` / `resume` set the backend's runtime setting `notify.enabled` (with a kind: `notify.kinds..enabled`), the same switches as its Settings page. Every change is audited. - `status` also says whether the pushed config matches `typetorch.json`. ## Dry run A new backend starts in **dry run** (`notify.dryRun`): it plans and counts everything and writes the rows, but never calls Roblox. Intents stay **pending** in dry run, so each one is really sent once dry run is off (if still in its window). Use it to check what would go out (`typetorch notify status`, the Notifications page), then turn it off on the backend's Settings page. Turn it back on any time; `notify pause` stops planning sends altogether. ## Templates Roblox has no API that creates notification strings (the Creator Dashboard's own endpoint needs a browser login), so each kind's string is made by hand once. `typetorch.json` holds its `text`; the CLI does the rest of the bookkeeping: 1. `bun run typetorch notify templates` prints every kind: its text on its own lines (copy it as it is, placeholders included), its placeholders, and whether it has a `template` id yet. It also prints the link to the experience in the Creator Dashboard. 2. There, open **Engagement > Notifications** and create a notification string per missing kind: paste the text. 3. Copy the new string's message id and run `bun run typetorch notify templates set `. It writes `notifications.kinds..template` into `typetorch.json` and changes nothing else in the file. 4. `bun run typetorch notify push`. Until then, `push` warns about every kind with a text but no template id: such a kind is planned and counted, never sent. Changed a text? Editing a string in the dashboard keeps its message id and changes what is sent at once (2026-11-07), so update the kind's `text` to the same words and push. For a different meaning, make a new string instead, `templates set` the new id, then push. Re-test with `typetorch notify test` either way: Roblox's text filter judges the whole rendered text ([Playbook](https://www.typetorch.dev/guides/notifications.md#2-make-the-strings-and-test-each-one)). ## A halted kind (bad template) If Roblox answers a send with **404 NOT_FOUND** ("Message id ... does not exist"), the kind's message id is wrong (a typo, or the string was deleted in the Creator Dashboard). That is a config error, not the player's: the backend - **stops that kind** (`notify.kinds..enabled = false`, audited) and shows it as `halted: "bad_template"` (`typetorch notify status`, the Notifications page's banner, a server log line); - **keeps the intents pending**: they go out once the kind is fixed; - **never mutes the player** (the answer even proves they opted in). To recover: 1. Fix the id: copy the message id again from Engagement > Notifications (or make the string again from `typetorch notify templates`), then `bun run typetorch notify templates set `. 2. `bun run typetorch notify push` 3. `bun run typetorch notify resume ` ## Other send failures - **403 from Roblox for one recipient** (an account Roblox won't notify): only that send fails for good (`failed`, code `forbidden`, `final`), and the player is muted for 7 days. Other sends go on. - **401, or 3 403s in a row** (with no 2xx, 400, 404 or 429 in between; the backend's Open Cloud key is wrong or lacks `user.user-notification:write`): the backend **halts all sending** and alerts; `typetorch notify status` shows `ALL SENDING HALTED (auth)`. The send that hit it is put back (`cancelled`), and intents keep queueing. Fix the key on the backend (`typetorch doctor` probes the same-named key here), then turn sending back on (`typetorch notify resume`, the Settings page's `notify.enabled`, or a `notify push`). - **400 other than "not opted in"** (a bad request for that one notification): it fails for good (`failed`, `final`), with no retry. - **400 `INVALID_ARGUMENT` "… contains words blocked by the text filter"**: Roblox filtered the rendered text (the template with its params). Also final. Common cause: marketing words such as "FREE" next to an item name; see the [Playbook](https://www.typetorch.dev/guides/notifications.md#2-make-the-strings-and-test-each-one). - **Network errors, 5xx and rate limits** are retried. A send that may have gone out before a crash and is refused as a repeat is coded `dup_refused`. ## Keys and the signed tap Anyone can make a deep link with launch data, so the backend signs every notification's launch data: ``` tt1n...... ``` The signature is the first 16 bytes of HMAC-SHA256 with the notify key. On join, the framework checks: the signature (the current key, or the previous one for 14 days after a rotation: the token's own lifetime), that the UserId is the joining player, and that it is under 14 days old; then the backend says whether this tap is the first. Launch data that doesn't start with `tt1n.` is yours and left alone. A bad one is ignored and counted (`open_bad`). `typetorch notify key rotate`: 1. makes a new key (32 random bytes, base64url); 2. signs it into the [settings record](https://www.typetorch.dev/guides/settings.md) first, as `backend.notify.keys = { current: new, previous: old, since }` with both prod keys, and pings the servers. Game servers are the only ones that verify taps, so they must know the new key before anything is signed with it; 3. then sends the same keys to the backend (`PUT /v1/notify/keys`), which signs with the new key from then on. If step 3 fails, nothing breaks: servers accept both keys and the backend keeps signing with the old one (still `previous`). Fix the cause and run `bun run typetorch notify key rotate --backend-only`, which sends the record's keys. With `--no-ping`, servers pick up the new key on their next settings read (within about a minute), so the CLI leaves step 3 to you: run `--backend-only` after that minute. The key is never printed: the CLI shows a fingerprint (the first 8 hex of its SHA-256). It lives only in the signed record (server only, never replicated) and the backend's key file. The previous key stays valid for 14 days. Rotating again within 14 days drops the older previous key, so taps on notifications signed with it fail (the CLI warns). Rotation needs the same keys and scopes as every settings write (both prod key files, the deploy key's DataStore scopes). ## Playbook: adding notifications to a game What we learned shipping them in a real game (Zomvival, 2026-11-07). Follow it in order and a new game needs about a day. ### 1. Pick the kinds (Roblox's rules first) Roblox reviews and throttles experiences by these ([guidelines](https://create.roblox.com/docs/production/promotion/experience-notifications)), so every kind must pass all of them: - **Personal.** About the player's own state: their gift, their streak, their unclaimed reward, someone passing *them* on a board. Never a broadcast ("Update out!", "Event live!"): those go everyone at once and are exactly what gets throttled. - **No ads, sales, Robux or purchases.** No "50 % off", no "buy", no streak-revive offers, no boost-expiry nags. - **No fake urgency, no "FREE".** "Claim before the daily reset" is fine when it is true. "FREE" next to an item name gets the whole message blocked by Roblox's text filter (below). - **Nothing to players who stopped playing.** Keep every intent's window short (hours to a few days) and let `lapse` taper the rest; a player gone for weeks is where "come back" spam starts. - **Fewer is better.** Roblox scales reach by how often players open them. One good kind beats five weak ones. A list that passed review, in priority order (lower wins on a day with several due): | Kind | Priority | When it is wanted | Window | Repeat | |---|---|---|---|---| | `gift_named` "{gift} is waiting for you in your mailbox!" | 10 | a gift letter written to an offline player; at every leave, each unopened gift | now .. 7 days | `per_key` (letter id) | | `streak_end` "Your {streak}-day streak ends soon. Play a round to keep it!" | 20 | at a leave, a streak of 3+ days | 3 h .. 15 min before the day to play on ends | `daily`, `asap` | | `lb_passed` "{name} passed you on the {board} leaderboard. Take your spot back!" | 30 | a board refresh where a top-10 user (not online) dropped a place to someone from below; never a Robux board | now .. 24 h, key = the board | `daily`, `perWeek` 2 | | `quests_ready` "Quest rewards are waiting: {count} finished. Claim them before the daily reset!" | 40 | at a leave, finished but unclaimed quests | now .. the reset | `daily`, `perWeek` 3 | | `daily_ready` "Your day {day} reward is ready. Join to claim it!" | 50 | at a leave, a player who claimed one in the last 3 days | from when it opens, 36 h | `daily`, `perWeek` 3 | ### 2. Make the strings and test each one 1. `typetorch notify templates`, paste each text into **Engagement > Notifications**, `templates set `, `typetorch notify push` ([Templates](https://www.typetorch.dev/guides/notifications.md#templates)). 2. **Send every kind once to yourself with realistic params**: `typetorch notify test --param name=value`. A test send skips the caps and goes out at once. Then check `GET /v1/notify/user?uid=` (admin token) or the explorer's player page: `sent` + `http 200`. 3. **Roblox's text filter runs on the whole rendered message, placeholders filled in.** A blocked one answers `400 INVALID_ARGUMENT` "######## contains words blocked by the text filter." The `#` mask is as long as the rendered text, so you can tell which variant it filtered. It is final (no retry), so a filtered notification is simply lost. Seen in practice: "FREE {gift} is waiting…" was blocked with `{gift}` = "Elite for 7 days" and "Elite", while the same gift passed without "FREE". Keep params plain nouns ("Elite for 7 days", "$500", "3"), never marketing words, and re-test after any text edit. 4. **Editing a string in the dashboard keeps its message id and takes effect at once.** Update the kind's `text` in `typetorch.json` to the same words and `notify push` (the backend checks params against it). 5. **Test on the owner's account only for content.** The universe owner skips Roblox's 1-a-day limit, so two sends a day reaching you prove nothing about the limit. ### 3. Game code: want from the save, drop when the reason is gone Keep the rules in a pure module (no services, no clock: pass `now`), so a bun sim can test them, and keep the service thin: ```ts // Each kind's reason from the player's own save: one want OR one drop per kind and key, so the backend's copy is exactly the save's export function planFromData(data: PlayerData, userId: number, now: number): { wants: Want[]; drops: Drop[] } // Server: at every leave (the profile's last write), plus when a preference changes playerData.ProfileReleasing.Connect((profile) => { const plan = planFromData(profile.Data, profile.UserId, os.time()); for (const d of plan.drops) notify.drop(profile.UserId, d.kind, d.key, d.why); for (const w of plan.wants) notify.want(profile.UserId, w.kind, { key: w.key, at: w.at, until: w.until, params: w.params }); }); ``` - **State kinds** (streak, quests, daily) come from the save at the leave. Use key `""` (one intent per kind, upserted), and `drop` when the reason is gone (streak too short, nothing to claim), so a stale reason never goes out. - **Event kinds** (a gift to an offline player, a leaderboard pass) are wanted where the event happens, by UserId, from any server. Use a stable key (the letter id, the board) so every server seeing the same event upserts one intent. - **No need to drop on join.** The backend never sends to a player who is online or within `quietAfterLeaveMinutes` of leaving, and the next leave re-plans everything. - **Windows**: `at` = the earliest moment it is true, `until` = when it stops being worth saying. A window under ~30 min isn't worth wanting. ### 4. Player preferences Give players a toggle per kind (Settings), stored in their save. Gate the save-planned kinds in `planFromData` (an off kind is dropped), **and** send the whole off set with `setOff(user, kinds)` at every join and every change: event kinds are wanted by servers that can't read the save, and the backend skips any intent of an off kind (`skipped`, why `pref_off`, kept, so switching it back on resumes it). ### 5. The opt-in prompt `promptOptIn(where)` shows Roblox's prompt, at most once a session; Roblox itself shows it at most once per 30 days and never to under-13s. Ask at a natural moment that explains the value (e.g. when the player closes their mailbox: "get told when a gift arrives"), plus a button in Settings. The answer is not told to the game: the backend learns it from its first send (`optin_inferred`). ### 6. Check it end to end 1. A test send reaches your device (`notify test`). 2. Tap it: an `open` row (the verified token, `onOpen` fires) and, after you play, `played`. 3. The explorer's **Notifications** page shows the funnel; the player page shows each send, its status, opened / played. 4. A gift to yourself while offline: the `want` row, then a `sent` after `quietAfterLeaveMinutes`. If you call Open Cloud yourself (outside TypeTorch): `join_experience` and `analytics_data` go **inside** `payload` (the API reference's `UserNotification_Payload`). At the top level, as the Open Cloud guide's curl example has it, Roblox answers 200 and silently drops both, so taps carry no launch data and the dashboard has no category. ## Open questions (spikes) What TypeTorch assumes until these are measured on a test universe: | # | Question | Assumed now | |---|---|---| | S4 | Does the launch data survive every path (phone app, web, first install)? | it does; expect some "clicked but no open row" | | S6 | What `JoinSource` does a notification tap have? | nothing depends on it; it is logged as `ctx` on the join row | | S3 (partly) | The exact refusal for a second send in a day, on a non-owner account | HTTP 429 `RESOURCE_EXHAUSTED` with "1 notification per recipient" (below) | Settled (measured on a test universe, 2026-11-07): - **S4, desktop**: the launch data arrives on a tap (desktop app and browser) once `join_experience` is inside `payload`; at the top level Roblox drops it silently (the backend sends the nested shape since 2026-11-07). - **S1, not opted in**: HTTP 400 `FAILED_PRECONDITION` "not opted in". The backend mutes the user for 7 days and writes `optin_inferred {state: "not_subscribed"}`. - **S1b, wrong message id**: HTTP 404 `NOT_FOUND`: [a halted kind](https://www.typetorch.dev/guides/notifications.md#a-halted-kind-bad-template). - **S2, rate limit**: 4000 requests a second per key. Every answer says so in its `x-ratelimit-limit`, `x-ratelimit-remaining` and `x-ratelimit-reset` headers, and the backend paces itself by them (never more in a window than the last `remaining`; it waits for the reset at 0). `notify.rate` is only an optional lower ceiling of our own. A `429` still halves the pace and honours `Retry-After`. - **S3, 1 a day (partly settled)**: Roblox refuses a user's second notification of the day at send time with HTTP 429, code `RESOURCE_EXHAUSTED`, a message containing "1 notification per recipient" ([devforum](https://devforum.roblox.com/t/issues-with-opencloud-experience-notifications/3874557)). Roblox also lists an aggregate daily cap across experiences. - **That refusal** is a "daily limit" for the backend: the send ends `failed` (code `daily_limit`) with no retry, and the notification is re-planned for the user's next day. - **Any other `429`** is rate limiting: the backoff above (`x-ratelimit-*`, `Retry-After`). - **`dailyCap` stays** our own guard, so the refusal should be rare. `notify.clock` picks its day: `rolling24` (default: the next send at least 24 h after the last) or `utc_day`. - **Don't test limits on the owner's account.** Test sends to the universe owner all answered 200: the owner most likely skips the throttle, so those sends say nothing about limits. - **Still open**: the exact message, until it is confirmed on a non-owner account. --- # Running the backend The day-to-day side of the self-hosted [backend](https://github.com/typetorch/backend): settings you change without a redeploy, its own alerts, the audit log, backups, disk space, its own performance, the API docs, and the Open Cloud key's scopes. Setting it up is in [Fresh setup](https://www.typetorch.dev/getting-started/fresh-setup.md) and the backend README ([Deploy on Coolify](https://github.com/typetorch/backend#deploy-on-coolify), [Run it on a VPS without Docker](https://github.com/typetorch/backend#run-it-on-a-vps-without-docker)). The backend is unversioned: it runs from a checkout or its Docker image, and this page follows its main branch. The explorer pages named here (Settings, Backend stats, Audit log) are under **Admin**, for owners only ([The explorer](https://www.typetorch.dev/guides/explorer.md)). Contents: [Environment](https://www.typetorch.dev/guides/backend-operations.md#environment) · [Runtime settings](https://www.typetorch.dev/guides/backend-operations.md#runtime-settings) · [Backend alerts](https://www.typetorch.dev/guides/backend-operations.md#backend-alerts) · [Audit log](https://www.typetorch.dev/guides/backend-operations.md#audit-log) · [Backups and restore](https://www.typetorch.dev/guides/backend-operations.md#backups-and-restore) · [Disk space](https://www.typetorch.dev/guides/backend-operations.md#disk-space) · [Moving the backend](https://www.typetorch.dev/guides/backend-operations.md#moving-the-backend) · [Backend stats](https://www.typetorch.dev/guides/backend-operations.md#backend-stats) · [Deploys on Coolify](https://www.typetorch.dev/guides/backend-operations.md#deploys-on-coolify) · [API docs for agents](https://www.typetorch.dev/guides/backend-operations.md#api-docs-for-agents) · [Open Cloud key scopes](https://www.typetorch.dev/guides/backend-operations.md#open-cloud-key-scopes) ## Environment Everything starts as an environment variable (Coolify's environment, a systemd `EnvironmentFile`, or `--env-file`). The server refuses to start without the two required ones: | Variable | What | |---|---| | `TYPETORCH_API_KEY` | the game key: game servers write with it, it reads nothing. 32+ characters | | `TYPETORCH_ADMIN_TOKEN` | the admin role, for the CLI and the explorer's token login. 32+ characters, different from the API key | The full list (public URL, proxies, sign-in, Open Cloud, retention, limits, DuckDB): the backend README's [Settings](https://github.com/typetorch/backend#settings). Values are never printed; the startup line and `/healthz` only say whether something is set. ## Runtime settings A running container can't re-read its environment, so the explorer's **Settings** page changes a short list of settings while the server runs. The environment gives the default, a value saved on the page wins, and **Reset to env** goes back. A change applies to the next request; nothing restarts. | Group | Settings | |---|---| | Alerts | the alert webhook (a secret: never shown again), its format, the levels sent; **Send test alert** (3 a minute) | | Backend alerts | the master switch, repeat window, hourly cap, and per rule on / off, level and thresholds ([below](https://www.typetorch.dev/guides/backend-operations.md#backend-alerts)) | | Access | viewers (Roblox UserIds with the read-only web role), the admin allow list, the admin token login | | Rate limits | ingest per address and per server, error logs per address, new servers per minute, and the busy 503's limits (raw backlog, requests in flight; [Emergency scale-ups](https://www.typetorch.dev/guides/emergency-scale-ups.md#first-the-game-keeps-running)) | | Retention | analytics history, raw archives, error logs, the audit log, the deploy history; error kinds and rows per day; error drop rules (the Errors page edits them) | | API keys | requests a minute per [named key](https://www.typetorch.dev/guides/api-keys.md), the events support keys may read | | Notifications | pause, dry run, the send rate, the daily cap clock, when presence goes stale, per-kind switches ([Notifications](https://www.typetorch.dev/guides/notifications.md)) | - **Lockout guards:** an allow list that wouldn't include your own address is refused (409); turning off the token login is refused (409) unless Sign in with Roblox is set up and you are signed in with Roblox right now. Locked out anyway: set `TYPETORCH_RUNTIME_SETTINGS=off` and redeploy (the saved file is kept but ignored, the page is read-only). - **Not editable** there (change the environment and redeploy): the keys and tokens, the OAuth client, the Open Cloud key, the public URL, the proxy settings, the data folder, the port. - Saved in `/runtime-settings.json` (mode 0600; it holds the webhook URL, so treat backups of it as secret). - API (admin): `GET /v1/admin/settings`, `PATCH /v1/admin/settings` (`{ "": value | null }`, null = back to the environment), `POST /v1/admin/settings/test-alert`. Every key and bound: the backend README's [Runtime settings](https://github.com/typetorch/backend#runtime-settings-the-settings-page). ## Backend alerts Next to the kernel's alerts, the backend watches its own data once a minute: error spikes, a new error after a deploy, a drop in players online, a players-online milestone (`ccuMilestone`, info), a silent fleet, stopped ingest, slow requests, memory, event loop lag, 5xx answers, low disk and a disk filling up. They go to the Fleet page's alerts and the same webhook. The rules, their defaults and the `TYPETORCH_ALERT_*` variables: [Live servers and alerts](https://www.typetorch.dev/guides/fleet-and-alerts.md#backend-alerts). - Edit them on the Settings page's **Backend alerts** section (each rule shows what it saw on its last run). - `GET /v1/admin/alert-rules` (admin) answers each rule's state (`ok`, `waiting`, `firing`, `off`, `unavailable`), when it last fired, and the raised, deduped and throttled counts since the start. - They need the fleet part (`TYPETORCH_PARTS` includes `fleet`, the default). - Two more come from the optional ingest queue, on the main server (`TYPETORCH_ROLE=main`): `queue_bucket_down` (critical, when the queue bucket can't be reached for a minute) and `queue_file_bad` (warning, a queued file that can't be loaded, skipped for 10 minutes). [Several ingest servers](https://www.typetorch.dev/guides/emergency-scale-ups.md#5-several-ingest-servers-optional). ## Audit log Every state-changing admin action is a row in the fleet SQLite file: sign-ins and failed sign-ins, sign-outs and lockouts, settings changes (old and new values; the webhook URL only as set / not set), the owner list, trusted browsers, alert acks, erasure (counts only), backups, live events, remote debug watches and commands, the CLI's release starts and marks, experiment changes prepared on the Experiments page, and any other write by a signed-in caller. - Each entry: the time, who (`admin token`, `roblox user ()`, `typetorch.dev user ()`, `api key`, ...), the role, how (`bearer` or `cookie`), the address, the action, the outcome (`ok`, `failed`, `refused`), the HTTP status and the details. - **Never a secret:** tokens, keys, secrets and the webhook URL become `[redacted]`. - Kept `TYPETORCH_AUDIT_KEEP_DAYS` days (365; the `auditKeepDays` runtime setting), at most 200,000 rows. - The **Audit log** page filters by actor, action and outcome; `GET /v1/admin/audit?actor=&action=&outcome=&since=&until=` (admin) pages through it. ## Backups and restore A backup is consistent and safe while the server runs: SQLite by `VACUUM INTO`, DuckDB copied and the Parquet day files hard-linked between the warehouse's jobs, the notifications database, plus the small state files (access list, runtime settings, trusted browsers, the settings copy, the instance key, the notification signing keys, erasure and audit folders). | Variable | Default | What | |---|---|---| | `TYPETORCH_BACKUP_HOURS` | `24` | hours between local backups (`0` = only on demand) | | `TYPETORCH_BACKUP_DIR` | `/backups` | where they go (the same volume by default: mount another one, or download) | | `TYPETORCH_BACKUP_KEEP` | `3` | how many are kept | - **Back up now** and **Download backup** are on the Settings page. `GET /v1/admin/backups` shows the schedule, the last outcome and the local backups; `POST` makes one now. - The download (`POST /v1/admin/backups/download`, admin) streams a tar of a fresh backup, without the alert webhook URL, the instance key and the notification signing keys (after restoring one, run `typetorch notify key rotate` again): ```sh curl -X POST -H "Authorization: Bearer $TYPETORCH_ADMIN_TOKEN" -o backup.tar https://backend.example.com/v1/admin/backups/download ``` - During a deploy handover a backup answers 503 (the other container holds DuckDB). - **Restore:** stop the app, move the old database files and day folders aside, copy the backup in, start the app. The exact steps: the backend README's [Backups and restore](https://github.com/typetorch/backend#backups-and-restore). ## Disk space The server measures the data folder's disk every 10 minutes. Under `TYPETORCH_DISK_WARN_PERCENT` (15) percent free it warns, under `TYPETORCH_DISK_CRITICAL_PERCENT` (5) it is critical (`0` turns a level off). The level shows on the Overview's Storage card and the Settings page's **Backups and disk** card, in `GET /v1/storage` and `GET /v1/admin/backups`, and in `/healthz` for the admin token. With the fleet part on, a `disk_low` alert goes out like any fleet alert. To make room: shorter retention on the Settings page, fewer local backups, or a bigger volume. ## Moving the backend The steps for a new server, moving analytics to Cloudflare Basin and back, and several ingest servers are in [Emergency scale-ups](https://www.typetorch.dev/guides/emergency-scale-ups.md#3-move-to-another-server). The operator facts: - **Export API** (`/v1/admin/export/*`): read-only, one export at a time, 120 requests a minute. It takes the env admin token as a Bearer only: no browser session, no web role, no named key, no game key. - **Migration** (`/v1/admin/migrate`): `GET` (the status) is for the admin role. Starting, pausing, resuming, cancelling or resolving a page is `POST`, and it takes the env admin token only (a named key gets `403`). - **Both servers run the same backend version**, because one version pins one DuckDB. Update the old server first. - **Never copy the data folder** to move a server. The move copies rows through the APIs, and a backup is the safe copy ([Backups and restore](https://www.typetorch.dev/guides/backend-operations.md#backups-and-restore)). ## Backend stats The **Backend stats** page (`GET /v1/admin/stats?window=1m|5m|15m|1h`, admin) shows the backend process itself, like Roblox's Performance tab for a game server: - tiles for the last 10 seconds: requests (and 5xx) per second, DuckDB queries per second, rows inserted per second, request latency p50 / p90 / p99, memory, CPU, event loop lag, uptime; - charts over the last 2 minutes (per second) or 60 minutes (per minute); - a table per route group (ingest, fleet, queries, SQL, sign-in, admin, explorer files, ...) over a picked window. It updates every 2 s (Pause stops it). Everything is in memory and bounded; long-held streams and long-polls are counted as requests but left out of the latency percentiles. The same numbers are in `GET /v1/admin/stats?window=1m|5m|15m|1h` (admin). Two blocks were added for the busy 503 and the ingest queue: - `ingest`: `busy` (refusals since the start), `inflight` (ingest requests being handled now) and `lastBusyAt`. - `queue` (only when `TYPETORCH_ROLE` isn't `all`): `role`, `pendingFiles`, `pendingBytes`, `lastLoadAt`, `files`, `errors`, `lastError`, `lastErrorAt`, `bucket`, `truncated`, `identities`. A node reports its own numbers in its `GET /healthz` with the admin token (`queue`, `ingest`). Details: [Several ingest servers](https://github.com/typetorch/backend#several-ingest-servers-optional) and [Limits and the busy 503](https://github.com/typetorch/backend#limits-and-the-busy-503) in the backend README. ## Deploys on Coolify Rolling updates work: deploy as usual. DuckDB lets one process open the database, so the two containers hand over: 1. The new container starts in **handover** while the old one holds the data folder. `/healthz` answers 200, the fleet API, error logs, sign-in and the explorer work; what needs DuckDB (ingest, queries, SQL, erasure) answers 503 with `Retry-After: 5`. It gives up after `TYPETORCH_HANDOVER_SECONDS` (600) and exits 1. 2. The old container stops within seconds on `SIGTERM`: running requests finish, raw files are synced, DuckDB and SQLite close. 3. The new container opens DuckDB within a second and takes over. Game servers ride over the gap: the framework re-sends a batch that got 503 after at least its `Retry-After` (framework 0.7.2+; older ones use their own backoff), and the kernel's fleet sender retries. Details: [Deploys on Coolify (rolling updates)](https://github.com/typetorch/backend#deploys-on-coolify-rolling-updates). ## API docs for agents | Route | What | |---|---| | `GET /openapi.json` | an OpenAPI 3.1 spec of every route (roles, parameters, bodies, the query names) | | `GET /docs` | Swagger UI over it; **Authorize** takes the admin, API or lookup token, or uses your explorer session | | `GET /llms.txt` | what this server is, for an LLM agent, with links to the spec, the backend README, these docs and the source | They hold no data or settings and need no credentials, but answer 404 outside `TYPETORCH_ADMIN_ALLOW_IPS` like the explorer. Point an agent at `https:///llms.txt`, and give it the narrowest key that does the job (a lookup token or a named [API key](https://www.typetorch.dev/guides/api-keys.md)), not the admin token. ## Open Cloud key scopes Every Roblox feature of the backend uses one Open Cloud key, `OPENCLOUD_API_KEY`, on the game's universe (`TYPETORCH_UNIVERSE_ID`). Give it only the scopes for the features you use; without a scope the feature is off, and its route or page says which scope is missing. | Feature | Scope | Also needs | |---|---|---| | Right to erasure: map a UserId to its pids | `universe-datastores.objects:read` | `ROBLOX_WEBHOOK_SECRET` ([Privacy](https://www.typetorch.dev/guides/analytics.md#privacy-and-right-to-erasure)) | | Right to erasure: delete the DataStore link too | `universe-datastores.objects:delete` | `TYPETORCH_ERASURE_DELETE_LINK=1` | | Identity backfill (`POST /v1/identity/backfill`) | `universe-datastores.objects:list` and `:read` | | | Live events: "Do servers have it?" | `universe-datastores.objects:read` | ([Live events](https://www.typetorch.dev/guides/live-events.md)) | | Remote debug instant wake, live map wake | `universe-messaging-service:publish` | kernel 0.5.1+ / 0.5.7+ ([Live debug](https://www.typetorch.dev/guides/live-debug.md)) | | Roblox server logs per JobId | `universe:read` | kernel 0.5.6+ sends the place version | | Roblox page acquisition, Demographics cards | `universe.analytics:read` | ([The explorer](https://www.typetorch.dev/guides/explorer.md#roblox-parity)) | | Map export | `universe.place.luau-execution-session:read` and `:write` | ([Recordings and maps](https://www.typetorch.dev/guides/recordings-and-maps.md#export)) | | Map "out of date" check | `asset:read` | falls back to the place version the fleet reports | | Experience notifications | `user.user-notification:write` | `OPENCLOUD_NOTIFY_KEY` if set, else `OPENCLOUD_API_KEY` ([Notifications](https://www.typetorch.dev/guides/notifications.md)) | The key is sent only in the `x-api-key` header to Roblox and never logged. The game repo's own Open Cloud key (deploys, the settings record) is separate: [Security model](https://www.typetorch.dev/guides/security.md#keys-and-tokens). The TypeTorch mobile app has its own Open Cloud key, kept only on the phone. The backend never receives it, and the app never sends its key to a backend: [The mobile app](https://www.typetorch.dev/guides/mobile-app.md#open-cloud-key). --- # Emergency backend scale-ups Your game took off overnight and the [backend](https://github.com/typetorch/backend) is falling behind. Two moves need no new code and no game deploy: | Move | Time | Downtime | What it buys | |---|---|---|---| | [1. Shed load](https://www.typetorch.dev/guides/emergency-scale-ups.md#1-shed-load) | 2 minutes, from your phone's terminal | none | about 4x fewer ingest requests, no new recordings | | [2. Resize the VPS in place](https://www.typetorch.dev/guides/emergency-scale-ups.md#2-resize-the-vps-in-place) | 5 to 10 minutes | a few minutes | DuckDB loads and queries use the bigger machine | | [3. Move to another server](https://www.typetorch.dev/guides/emergency-scale-ups.md#3-move-to-another-server) | the switch takes a minute; the history moves in the background | none for the game | a new machine or provider, with its history | | [4. Analytics to Basin and back](https://www.typetorch.dev/guides/emergency-scale-ups.md#4-analytics-to-basin-and-back) | a minute to switch the sink; the history moves in the background | none for the game | analytics leaves the server (or comes back) | | [5. Several ingest servers](https://www.typetorch.dev/guides/emergency-scale-ups.md#5-several-ingest-servers-optional) | set-up work, no game change | none | ingest past one core | Do 1 first, then 2. Moves 1 and 2 change neither the game nor its URL. Moves 3 to 5 do change where the backend or its analytics live, but the game only follows a settings change, not a deploy. **Versions.** Moves 3 to 5 need the backend from its main branch of 2026-11-15 or later, and the CLI 0.19.0 or later. The game needs framework 0.7.2 or later to wait for the backend's busy answer and to use `backend.ingest`. ## First: the game keeps running The backend is never on the players' path. When it is slow or down: - **Players:** nothing changes. Servers run their build as before. - **Deploys:** they work. `deploy --wait` and the health checks skip their wait with a note ([Live servers and alerts](https://www.typetorch.dev/guides/fleet-and-alerts.md)). - **Analytics:** each game server keeps a queue in memory: up to 10,000 event rows, 2,000 fleet rows and 300 recording chunks. A batch that gets `408`, `429`, `5xx` or no answer goes back in the queue and is sent again after about 5, 10, 20 s, doubling up to 5 minutes. Past the cap the oldest rows are dropped and counted (`analytics.stats().dropped`). - **The busy answer:** when the backend falls behind, it answers an event batch (`POST /v1/ingest`) with `503` and a `Retry-After` of 10 to 30 s, before it reads the batch. Framework 0.7.2 waits at least that long, so the servers don't all retry at once. Older frameworks ignore the header and use their own backoff. Only event ingest is refused this way: heartbeats, error logs, deploy reports and identities never are. - **On the backend:** a `202` from `POST /v1/ingest` means the rows are already in a raw file on disk. The loader puts them into DuckDB within seconds, or later when it is behind. Nothing it accepted is lost. How long a server can wait before it drops rows: 10,000 rows divided by its rows per second. At 0.2 to 0.6 events a second per player (two live games, November 2026), a 30-player server fills its queue in 10 to 30 minutes. **When the backend answers busy.** Two runtime settings decide it, both on the explorer's **Settings** page under **Rate limits**: | Setting | Variable | Default | When it answers busy | |---|---|---|---| | Busy: raw backlog (`busyBytes`) | `TYPETORCH_BUSY_BYTES` | 512 MB | the loader is behind: raw files waiting for it hold more than this | | Busy: requests in flight (`busyRequests`) | `TYPETORCH_BUSY_REQUESTS` | 256 | more ingest requests are being handled at once than this | `0` turns one off. Raise them when the disk and the loader can take more; lower `busyBytes` on a small disk. The explorer's Overview shows a note while the backend refused in the last minute, and **Backend stats** shows the counts. The full answer and its counters: the backend README's [Limits and the busy 503](https://github.com/typetorch/backend#limits-and-the-busy-503). ## How much one backend takes The [load test](https://github.com/typetorch/backend#load-tests) ingested **10,000 events a second on one core** without errors (the most it was tried at, not a ceiling). The backend answers HTTP on **one thread**, so a bigger machine doesn't raise this much. DuckDB, the loader and the queries do use every core you give them. | Your game's rate | One core is about | |---|---| | 0.2 events / s per player | 50,000 CCU | | 0.6 events / s per player | 17,000 CCU | Your rate, from the explorer's SQL page (event rows per second of play, last 7 days): ```sql SELECT count(*) / sum(CASE WHEN kind = 'session' AND name = 'leave' THEN TRY_CAST(json_extract(props, '$.secs') AS DOUBLE) END) AS events_per_player_second FROM events WHERE t >= epoch_ms(now() - INTERVAL 7 DAY) AND srv <> 'studio' AND channel = 'prod' ``` Requests: each game server sends about 0.07 ingest requests a second (one every 15 s), a heartbeat every 30 s and one more when its player count changes (at most every 5 s). That is about 0.1 to 0.3 requests a second per server. Disk: a row is about 500 bytes in the raw file, so each event a second costs about 43 MB of raw data a day (gzipped in `raw/archive/`, Parquet in `events/`). The backend raises a `disk_low` alert under 15 % free. ## 1. Shed load From the game folder: ```sh bun run typetorch backend setup --flush-seconds 60 --record-share 0 --force ``` - **`--flush-seconds 60`:** each server sends every 60 s instead of 15 s, so about 4x fewer requests. A busy server still sends early once it has 500 rows waiting (at most 10 requests a minute). The number of rows doesn't change, only how many requests carry them. - **`--record-share 0`:** no new player's first session is recorded. A recording chunk is much bigger than an event row. - **`--force`:** `backend setup` checks the backend first (`/healthz` within 5 s). A struggling backend can fail that check, so `--force` writes the record anyway. It is still signed with both prod keys. The URL comes from `typetorch.json` (`backend.url`). Running servers apply it within seconds: the CLI pings them, and every server reads the record at least every 55 s. No restart: `--flush-seconds` counts from the next send, and `--record-share` applies to sessions that start after it. **Analytics on Cloudflare Basin?** CLI 0.19.0+ keeps a Basin sink when you run `backend setup`. Older CLIs replace it with the backend, so use CLI 0.19.0 or later on a Basin game. A Basin game's backend only carries heartbeats and error logs, which are light. Basin scales by itself. **`429` in the backend's logs?** Roblox game servers share outgoing addresses, so many servers can hit the per-address limit. Raise **Ingest per address** (default 6,000 a minute) on the explorer's **Settings** page; it applies at once. The per-server limit (60 a minute) is far above what a server sends. **Last resort:** `bun run typetorch settings unset backend` stops all sending: analytics, heartbeats, error logs and identities. Servers stop queueing too, so this loses data until you run `backend setup` again. **Undo** once the backend keeps up: ```sh bun run typetorch backend setup --flush-seconds 15 --record-share 1 ``` What it costs: a server that crashes loses up to a minute of rows instead of 15 s, and new players aren't recorded while it lasts. ## 2. Resize the VPS in place Most providers can give a server more CPU and memory in place (Hetzner: **Rescale**, DigitalOcean: **Resize**). The machine restarts and keeps its IP address and disk, so DNS, the settings record and the game don't change. 1. **Back up.** Explorer > Settings > **Back up now** (or **Download backup**, [Backups and restore](https://www.typetorch.dev/guides/backend-operations.md#backups-and-restore)). 2. **Resize** in the provider's panel. Pick CPU and memory only (not a bigger disk) if you may want to go back down later: most providers can't shrink a disk. Add a bigger disk if the disk math above says you'll need it. 3. **Give DuckDB the machine.** The defaults suit a 1 GB server and leave a big one idle. In Coolify, set: | Variable | Default | On the bigger machine | |---|---|---| | `TYPETORCH_MEMORY_LIMIT` | `400MB` | about half the memory (`8GB` on 16 GB) | | `TYPETORCH_THREADS` | `2` | the number of vCPUs | | `TYPETORCH_QUERY_CONCURRENCY` | `2` | `4` (queries at once) | `compose.yaml` passes `TYPETORCH_MEMORY_LIMIT` and `TYPETORCH_THREADS` through. With the **Docker Compose** resource, add a line for `TYPETORCH_QUERY_CONCURRENCY` under `environment:` too, or it never reaches the container (the **Dockerfile** resource passes every variable). If you set a memory or CPU limit on the container in Coolify, raise it as well. 4. **Redeploy.** A rolling update is fine: the new container takes the data folder over within seconds. 5. **Check:** `curl https:///healthz` says `{"ok":true}`, `bun run typetorch servers` lists live servers, and the explorer's Overview shows new events. Game servers ride over the restart with the retries above: a few minutes down costs no rows. ## Copying the data folder **Don't copy the data folder to another machine** (rsync, a disk image) while it matters. A folder copied while the server writes, or a copy cut off halfway, can leave DuckDB or SQLite unreadable. Backups made by the server ([Backups and restore](https://www.typetorch.dev/guides/backend-operations.md#backups-and-restore)) are the safe copy. Move 3 below does not copy files either. ## 3. Move to another server Use this for a new machine or provider when a resize in place isn't enough or isn't possible. The new server is set up first, the game switches to it, and then the history moves over through the two servers' APIs, day by day. The old server is only read. Nothing is copied from its data folder. Both servers run the same backend version (the old one serves the export API, and one backend version pins one DuckDB). 1. **Update the old server** to this backend version. Then deploy the new server with **its own URL** and **the old keys**: `TYPETORCH_API_KEY` and `TYPETORCH_ADMIN_TOKEN`, the same values as the old server. Nothing else changes for the game yet. 2. **Switch the game** to the new server: ```sh bun run typetorch backend setup --url https://new.example.com ``` The keys come from the game repo's `.env`. Game servers follow the new record within a minute (they read it at least every 55 s). The old server keeps its address and takes in what servers had in flight. 3. **Point the Roblox erasure webhook** at `https://new.example.com/v1/erasure` (Creator Hub > Webhooks, same secret). From now on an erasure reaches the new server, and it covers rows that arrive by the move too. 4. **Start the move** on the new server. The old server's admin token goes in `TYPETORCH_OLD_ADMIN_TOKEN` (the environment or `.env`, never a flag): ```sh bun run typetorch backend migrate --from https://old.example.com bun run typetorch backend migrate status --watch ``` The Settings page's **Migration** card and `POST /v1/admin/migrate` start the same job. 5. **Turn the old server off** when every day says `match`. Keep a last [backup](https://www.typetorch.dev/guides/backend-operations.md#backups-and-restore) of it first. The public domain can move to the new server later. ### The move commands | Command | What | |---|---| | `backend migrate --from ` | Start: the old server's history into the server `backend.url` names | | `backend migrate status` | Steps, progress, rows a second, and the per-day report. `--watch` polls every 5 s | | `backend migrate pause` / `resume` / `cancel` | Cancel keeps what was already imported. A new start goes on from there | | `--rows-per-second ` | The speed cap (default 20,000, `TYPETORCH_MIGRATE_ROWS_PER_SECOND`) | | `--force` | Start although the old server's checks failed | ### What the move checks - **Erasures first.** The old server's erased players are applied before the import, so their rows are dropped. - **Every day, twice.** Each day before the cutover must have the same row count and hash as the old server (minus the players erased since). Days from the cutover on hold new rows as well, so every old row must be there. A day that fails is imported again once, then left for you. Each day's state is `match`, `missing` or `differs`. - **Live data last.** Once the old server has got nothing for 10 minutes, the days that changed since are imported again. - **Live ingest comes first.** The job waits while the loader is behind or a query runs. - **Survives restarts.** A crash or a redeploy of either server resumes at the last page. - **Old history.** Days older than the new server's `keepDays` (the analytics history setting) are skipped. The speed is about 5 minutes for 6 million rows at the default cap. ### Not moved These do not come across. Set them up again on the new server: | Not moved | On the new server | |---|---| | Raw archives | Nothing: the same rows are already in the day files | | Trusted browsers (`devices.json`) | `bun run typetorch backend bless` | | `instance.key` | Sign in with typetorch.dev: **Add project** again for the new fingerprint | | Alert webhook URL | Enter it again on the Settings page | | Admin allow list and token login | Set them again on the Settings page, on purpose | | Named API keys | `bun run typetorch keys create` again ([API keys](https://www.typetorch.dev/guides/api-keys.md)) | | Notifications (`notify.db`) | Not copied | ## 4. Analytics to Basin and back This moves the analytics history (events and recordings) between the server's day files and [Cloudflare Basin](https://www.typetorch.dev/guides/analytics.md#cloudflare-basin), row by row, and checks each day. The server keeps the fleet (heartbeats, deploys, error logs, identities, settings) either way, so a Basin game still has a backend. Nothing is deleted on either side. Basin can't delete rows. **Switch the sink first, then move the history.** The game sends each row to one sink: the one its signed record names when it flushes. A game server follows a new record within 5 to 55 s, and its queued rows go to the new sink. So the rows on the server and the rows in Basin never overlap, and the move takes every row the source holds, not a time range. Rows sent just before the switch come over with the rest. ### To Basin 1. Set up Basin ([Cloudflare Basin setup](https://www.typetorch.dev/guides/analytics.md#cloudflare-basin)): the two streams, the tables and a send token. 2. **Switch the sink:** ```sh bun run typetorch backend setup --analytics basin --events --recordings ``` Put the send token in the game repo's `.env` as `BASIN_SEND_TOKEN`. The record keeps `backend` pointed at this server for the fleet. From a minute later, analytics go to Basin. Rows that were in flight still reach the server. 3. **Optional, for the count check:** set `CLOUDFLARE_ACCOUNT_ID`, `BASIN_BUCKET` and `BASIN_SQL_TOKEN` (and `BASIN_NAMESPACE` if it isn't `typetorch`) on the server, then redeploy it. Without them the move still runs, but it can't compare counts in Basin. 4. **Start the move:** ```sh bun run typetorch backend migrate --to-basin bun run typetorch backend migrate status --watch ``` The job waits until the server has received no analytics row for 10 minutes and everything it received is loaded (state `waiting`, and it says so). A forgotten step 2 never sends half a day. 5. **If a page is cut off** mid-send, the job stops in `needs_decision`. Resolve it with `bun run typetorch backend migrate resolve resend` (Basin may then hold that page twice) or `skip` (its rows may be missing). The status names the page. 6. **When every day says `match`** (or `sent`, without the count check), keep a [backup](https://www.typetorch.dev/guides/backend-operations.md#backups-and-restore). Then turn the analytics part off with `TYPETORCH_PARTS=fleet`. The data folder stays. ### From Basin 1. The server runs with its analytics part (`TYPETORCH_PARTS=analytics,fleet`, the default). 2. **Switch the sink back:** ```sh bun run typetorch backend setup --analytics duckdb ``` The game's analytics go to the server within a minute. 3. **Start the move.** The Basin values (`CLOUDFLARE_ACCOUNT_ID`, `BASIN_BUCKET`, `BASIN_SQL_TOKEN`, `BASIN_NAMESPACE`) come from the game repo's `.env`. The token needs Basin SQL read, Basin Catalog read and R2 storage read: ```sh bun run typetorch backend migrate --from-basin bun run typetorch backend migrate status --watch ``` 4. **When every day says `match`,** the Basin tables can stay as a backup or go. The job only reads them. ### What is checked | Direction | Checked per day | Not checked | |---|---|---| | From Basin | The rows read equal Basin's count for the day, counted again at the end. Every row read is in the day file afterwards. A day before the server's own rows began holds no more rows than Basin has. Result: `match`, `missing` or `differs`. | A hash against Basin (Basin SQL can't compute DuckDB's hash). Exact duplicates in Basin collapse on arrival. | | To Basin, with the count settings | Basin's count for the day, minus what Basin held before the job sent anything, against the rows sent. Result: `match`, `missing ` or `duplicates` (more rows than were sent, for example after a resent page). | The row contents in Basin (counts only): which rows are missing or doubled. | | To Basin, without the count settings | Each page's `2xx`. The day ends `sent`. | Anything in Basin. | **Cost.** Basin SQL bills the bytes each query scans, with a 10 MB minimum per query. Check Cloudflare's current price. A move from Basin scans every row a few times (count queries, then pages of 10,000 events). A move to Basin pays Pipelines for what it sends, and the count check adds two count queries per check. The job's speed cap (`--rows-per-second`) paces it. Details and the exact statuses: the backend README's [Move analytics to Basin and back](https://github.com/typetorch/backend#move-analytics-to-basin-and-back). ## 5. Several ingest servers (optional) **Most games never need this.** One server (`TYPETORCH_ROLE` unset, which is `all`) runs ingest, DuckDB, the fleet and the explorer together. Nothing here changes it. Use it when one server's ingest isn't enough: past one core, which is about 17,000 to 60,000 players online at the rates in [How much one backend takes](https://www.typetorch.dev/guides/emergency-scale-ups.md#how-much-one-backend-takes). Past a few hundred thousand players online, move analytics to Basin instead ([section 4](https://www.typetorch.dev/guides/emergency-scale-ups.md#4-analytics-to-basin-and-back)). The shape: game servers send events to one address in front of several **ingest nodes**. Each node writes its rows to a Parquet file every few seconds and uploads it to a storage bucket (the S3 API, such as Cloudflare R2). The **main server** loads those files into its one DuckDB. Heartbeats, error logs and deploys still go to the main server. Setting it up: 1. **A bucket** with the S3 API (for example R2), and an API token with object read and write on it. 2. **The main server:** set `TYPETORCH_ROLE=main` and the four `TYPETORCH_QUEUE_*` bucket variables. Redeploy it first. 3. **Each ingest node:** the same image with its own volume, `TYPETORCH_ROLE=ingest`, the bucket variables, and `TYPETORCH_MAIN_URL` (the main server's address). Its `TYPETORCH_API_KEY` and `TYPETORCH_ADMIN_TOKEN` are the same values as the main server's. 4. **One address for the nodes:** a load balancer, or DNS round-robin, e.g. `https://ingest.example.com`. 5. **Point the game at it:** ```sh bun run typetorch backend setup --ingest https://ingest.example.com ``` The CLI checks the address and the game key there first. Game servers send events to it within a minute. Heartbeats and the rest stay on the main server. `--ingest none` moves events back to the main server. Watch the main server's **Backend stats** page (the queue tiles) and each node's `/healthz` with the admin token. If the bucket can't be reached, the main server raises a `queue_bucket_down` alert ([Live servers and alerts](https://www.typetorch.dev/guides/fleet-and-alerts.md#backend-alerts)). The full variable table for each role, and the rules for erasure on the nodes: [Several ingest servers](https://github.com/typetorch/backend#several-ingest-servers-optional) in the backend README. --- # API keys The [backend](https://github.com/typetorch/backend) can hand out **named API keys with roles**, so a tool gets exactly the access it needs and never holds the admin token. Typical case: a Discord support bot that looks up one player's anticheat rows by UserId. It gets a `support` key, which can read that and nothing else. - A key looks like `ttk__`. The `id` (10 characters of `0-9 a-z`) is public: lists and the audit log show it. The secret is shown **once**, when the key is made; the backend keeps only a SHA-256 hash of the whole key. - A key is a bearer token: `Authorization: Bearer ttk_...`. It never opens an explorer session; browser sign-in (owners as admins, viewers read-only) is unchanged ([The explorer: sign in and roles](https://www.typetorch.dev/guides/explorer.md#sign-in-and-roles)). - Each key has a name (`a-z 0-9 . _ -`, 1-48 characters, unique among active keys), a role, and an optional expiry (1 to 3650 days). An expired or revoked key answers 401, like an unknown one. - A backend keeps at most 1,000 keys, revoked ones included (a create past that answers 409). ## Roles and scopes A role is a fixed set of scopes: | Role | Scopes | For | |---|---|---| | `game` | `ingest:write` | what game servers do (the game key's job) | | `lookup` | `identity:resolve` | turning a UserId into its pids | | `support` | `identity:resolve`, `players:read` | support tools: one player's allowed rows and summary | | `analyst` | `analytics:sql`, `analytics:query`, `identity:resolve` | notebooks and dashboards over the analytics data | | `admin` | all | everything the admin token can do, except replacing the owner list (`PUT /v1/access`) and the trust-link signing keys (`PUT /v1/access/keys`): those stay with the admin token | A named `admin` key can't use two things. They take the backend's env admin token (`TYPETORCH_ADMIN_TOKEN`) only, and a named key gets `403`: - the **export API** (`/v1/admin/export/*`), which a new server reads from the old one, - starting or steering a **migration** (`POST /v1/admin/migrate`, `typetorch backend migrate`): see [Move to another server](https://www.typetorch.dev/guides/emergency-scale-ups.md#3-move-to-another-server). What each scope opens: | Scope | Routes | |---|---| | `ingest:write` | `POST /v1/ingest`, `/v1/identity`, `/v1/errors`, the game side of `/v1/fleet/*`, `/v1/notify/intents`, `opened`, `played` | | `identity:resolve` | `GET /v1/identity/resolve` | | `players:read` | `GET /v1/players/by-uid/{uid}/events` and `.../summary` ([below](https://www.typetorch.dev/guides/api-keys.md#per-player-endpoints)) | | `analytics:query` | the [named queries](https://www.typetorch.dev/guides/analytics.md#queries) | | `analytics:sql` | the free-form SQL route | | `settings:write` | `PATCH /v1/admin/settings` (runtime settings; only `admin` has it) | | `admin` | everything else that needs the admin token today, and managing keys | A request outside the key's scopes answers `403 { "error": "forbidden", "need": "" }`. ## The CLI The `keys create | list | revoke` commands need **CLI 0.19.0+**. The [HTTP routes](https://www.typetorch.dev/guides/api-keys.md#over-http) work today with any backend that has named keys. From the game folder, with `TYPETORCH_ADMIN_TOKEN` in its `.env` and `backend.url` in `typetorch.json`: ```sh bun run typetorch keys create --name standard-bot --role support --expires 365d bun run typetorch keys list # id, name, role, scopes, expires, last used, built-in / revoked bun run typetorch keys list --all # revoked keys too bun run typetorch keys revoke a1b2c3d4e5 ``` - `create` prints the key once, with "Store it now: it is not shown again". Put it straight into the tool's secret store or environment. Lost it? Revoke it and create another. - `--json` returns it in `key`, so a script can pipe it into a secret store without it ever showing on screen: `bun run typetorch keys create --name standard-bot --role support --expires 1y --json | jq -r .key | `. - `--expires` takes days or years: `90d`, `365d`, `1y` (1 to 3650 days). Without it the key never expires. - The CLI never writes the key to disk or a log, and hides it in its own error messages. - `revoke` takes the id (from `list`), never the key itself. A revoked key fails at once. - These sit next to the [prod signing key](https://www.typetorch.dev/guides/prod-signing.md) commands (`keys init`, `rotate`, `resign`); they share the `keys` command, nothing else. ### Over HTTP The same over HTTP (admin scope): | Request | Answer | |---|---| | `POST /v1/admin/keys` `{ name, role, expiresDays? }` | `201 { id, key, name, role, scopes, createdAt, expiresAt }`: `key` only here, once | | `GET /v1/admin/keys` (`?all=1`: revoked too) | `{ keys: [{ id, name, role, scopes, createdAt, createdBy, expiresAt, lastUsedAt, revokedAt, builtIn }] }`, never a hash or secret | | `DELETE /v1/admin/keys/{id}` | `{ ok: true, id, revokedAt }`; a built-in id answers 400 | ## Built-in keys: the env tokens The tokens in the backend's environment keep working unchanged, and `keys list` shows them as built-in keys: | Id | Variable | Role | |---|---|---| | `env:api` | `TYPETORCH_API_KEY` (the game key) | `game` | | `env:api-previous` | `TYPETORCH_API_KEY_PREVIOUS` (during a rotation) | `game` | | `env:admin` | `TYPETORCH_ADMIN_TOKEN` | `admin` | | `env:lookup` | `TYPETORCH_LOOKUP_TOKEN` | `lookup` | They can't be revoked through the API or the CLI: to retire one, change the variable in the backend's environment and restart it ([Running the backend: environment](https://www.typetorch.dev/guides/backend-operations.md#environment)). ## Per-player endpoints Scope `players:read` (the `support` role). The backend binds the player: the UserId comes from the path and every pid from its own `identities`, so a key can never widen the query. There is no free-form SQL behind them. ### `GET /v1/players/by-uid/{uid}/events` Query: `names=ac_flag,ac_action` (default: the whole allow-list), `since` and `before` (unix ms; default the last 30 days, and now), `limit` (1-100, default 50). Rows for every pid of that UserId, newest first: ```json { "uid": 123456789, "known": true, "pids": ["p_1a2b3c", "p_9z8y7x"], "rows": [ { "t": 1762876800123, "name": "ac_flag", "kind": "custom", "pid": "p_1a2b3c", "job": "e7873b84-…", "props": { "cat": "speed", "v": 42.1 } }, { "t": 1762876790000, "name": "join", "kind": "session", "pid": "p_1a2b3c", "job": "e7873b84-…", "props": { "from": "direct" } } ], "more": false } ``` `props` is always a JSON object. `more: true` means there are older rows: ask again with `before` = the last row's `t`. ### `GET /v1/players/by-uid/{uid}/summary` Query: `since` (unix ms, default the last 30 days). ```json { "uid": 123456789, "known": true, "pids": ["p_1a2b3c"], "since": 1760284800000, "byName": { "ac_flag": 12, "ac_action": 3, "ac_honeypot": 0 }, "byCategory": { "speed": 9, "fly": 3 }, "sessions": 41, "lastSeen": 1762876800123, "playtimeSecs": 51840, "robuxSpent": 1200, "purchases": 4 } ``` - `byName`: a count for every allow-listed name (0 when none). - `byCategory`: the `ac_flag` rows grouped by their `props.cat`. - `sessions`: distinct sessions. `lastSeen`: the newest row of any kind but `fleet` for those pids, or `null`. - `playtimeSecs`: each session's first to last row (any kind but `fleet`), summed, in seconds. - `robuxSpent` and `purchases`: the Robux and the count of the `purchase` rows (the framework's native purchase rows) in the range. For a UserId this backend has never seen, `events` answers `200 { "uid": …, "known": false, "pids": [], "rows": [], "more": false }`, and `summary` answers with `known: false` and every count 0. Both work on the DuckDB and the Basin backend, and answer 503 while analytics isn't open yet, like the other analytics reads. Example, from the bot's host: ```sh curl --max-time 30 -H "Authorization: Bearer $TYPETORCH_SUPPORT_KEY" \ "https://backend.example.com/v1/players/by-uid/123456789/summary" ``` ### The allow-list A support key reads only the event names in the runtime setting `players.supportEvents` (the backend's Settings page, or `TYPETORCH_PLAYERS_SUPPORT_EVENTS`, comma separated; at most 64 names; default `ac_flag,ac_action,ac_honeypot,join,leave`). Some names are special: | Name | Reads | |---|---| | `join`, `leave`, `device` | the `session` rows of that name (`device` is the player's device row; add it to the list to allow it) | | `feedback` | the player's [feedback](https://www.typetorch.dev/guides/feedback.md) rows (the `feedback` kind), reported with the name `feedback` | | any other name | rows of that name of any kind but `session`, `fleet` and `feedback` | Asking for any other name answers `403 { "error": "event_not_allowed", "name": "" }`. An `admin` key (or an owner's session or the admin token) isn't limited by it. Name your game's support-relevant [analytics](https://www.typetorch.dev/guides/analytics.md) events to match, or add them to the list. ## Rate limit Every named key (`ttk_...`) has its own token bucket: `keys.ratePerMinute` requests a minute (runtime setting or `TYPETORCH_KEYS_RATE_PER_MINUTE`, default 120). Over it the backend answers `429 { "error": "rate_limited" }` with `Retry-After` (seconds); wait that long. A key with the `game` role isn't limited by it: it keeps the ingest limits game servers have always had. The built-in env tokens keep their own checks. ## Audit Every `players:read` request writes an [audit](https://www.typetorch.dev/guides/security.md#the-backend) row (action `players.read`): the key's id, name and role, the route template (`/v1/players/by-uid/:uid/events`), the status, the time and the client's IP. It never holds the UserId (more people can read the audit log than the data), only a count of pids. Creating and revoking keys are audited too (`keys.create`, `keys.revoke`, never the secret). Other uses of a key only update its `last used` time (at most once a minute). --- # Security model ## Who can do what | Who | Can | |---|---| | **You at your terminal** (holding the Open Cloud key and the signing key files) | build, upload, approve, sign and deploy any branch; roll back; pin; publish the kernel; rotate keys | | **An agent, a script or the remote-claude dev-server** | build and upload, then only write a **proposal**; you approve it with `typetorch approve` (y/N). The dev-server never targets a prod-channel branch | | **Owner in game** | everything a dev can, plus the dev menu's Manage tab (kick, ban, bring, shut down and migrate servers, load a build on other dev servers), switching the server they are in to any branch or build (prod included), and rolling back prod-channel servers | | **Dev in game** | the dev menu and `/tt`: read everything; on dev-channel servers also cheats, pins and branch switches. The [dev-only tools](https://www.typetorch.dev/guides/dev-menu.md#dev-only-tools) (Claude, Logs > Upload, Dex edits, Network blocking, Server > Experiments) work under dev rules for every dev, and on a public server an owner switched to a dev branch for owners only | | **Player** | nothing beyond your game's own network leaves, which are rate-limited, shape-limited and type-guarded | - **Owners** are the experience's creator (or the owning group's owner) and `members` with the role `"owner"`. Everyone else in `members` is a dev; the old role `"admin"` counts as dev. - Dev status is decided on the server by the kernel: the experience owner, `members`, dev-badge holders, Studio; minus `revoked`. Every dev-menu request is re-checked on the server. - **`members`, `revoked` and `devBadgeId` reach servers only through `bun run typetorch access push`.** It writes them into the game's [signed settings record](https://www.typetorch.dev/guides/settings.md) (kernel 0.3.8+), signed with both prod keys. Game code can write the DataStore it lives in but can't sign, and servers refuse a record that doesn't verify: a backdoored model can't make itself an owner. Run it after every change. Revoking takes effect within seconds (the CLI pings the servers), or within about a minute. `deploy` and `doctor` warn when `typetorch.json` lists people that were never pushed, or changed since the last push (until then a revoked dev stays a dev). - **Public servers are always effective `prod`:** read-only dev menu, and (kernel 0.3) only signed deploys and signed pins from outside the server. ## What protects prod 1. **Approval:** deploys to branches your `approval` policy covers wait for your y/N at an interactive terminal. 2. **The cloud test:** a prod build boots in your place, headless, before it is published ([Deploy and rollback](https://www.typetorch.dev/guides/deploy-and-rollback.md#the-cloud-test)). 3. **Signatures:** every prod-channel release is signed with your two Ed25519 keys; kernel 0.3 servers verify it ([Prod signing](https://www.typetorch.dev/guides/prod-signing.md)). Code running inside your universe (a dev branch, `run_luau`, a free model, a package) can't make a prod server load anything new. 4. **Payload shape:** a payload holds only Folders and ModuleScripts under one Model, checked when it is built and again when a prod server mounts it; nothing in an upload runs by itself. 5. **Channels:** dev branches run only in private or reserved servers, or where you put them (signed A/B pins you approved, or an owner's switch of one server). 6. **Safe deploys:** a build that fails on a server is rolled back there, and `deploy --wait` rolls the branch back when it fails on many ([Safe deploys](https://www.typetorch.dev/guides/deploy-and-rollback.md#safe-deploys)). What stays open, by design or for now: - Dev-channel servers accept unsigned deploy messages: anything that can publish MessagingService messages in your universe can point a **dev** server at another build. - **An owner can run any known build on the prod server they are in.** Known builds come from the deployment list, which game code can write. It changes that one server only; the payload checks still apply. - **A public server an owner switched to a dev branch takes that branch's unsigned deploys** until it is switched back to `prod` or closes. - The [boot fail-safe](https://www.typetorch.dev/guides/prod-signing.md#the-boot-fail-safe) may boot an unverified stored head when nothing verifies. - Group members with asset write access can change the key asset. - The stored heads and the settings record live in your universe's MemoryStore and DataStores, which game code can write; prod servers re-verify everything they read there. - **Settings rollback by replay:** game code can't forge the settings record, but it can write back an *older* signed copy (say, from before you revoked someone). Running servers refuse a lower seq; a server that starts meanwhile takes the old copy until the next write. If you suspect it, write again (`typetorch access push` gives a new seq) and check `typetorch settings status`. - The game key in the settings record (`backend.key`) is readable by any server code in your universe, as the old ConfigService keys were. They are write-only tokens; never put a read token there. - **Cross-server messages** (`TypeTorch.messaging`): the sender tags (JobId, branch, channel) are for routing, not proof. Anything that can publish to your universe's MessagingService can forge them; check what a message asks for. ## The backend The [backend](https://github.com/typetorch/backend) is meant to sit on a public https address. Its full model is in the backend README's [Security](https://github.com/typetorch/backend#security) section, sign-in and the explorer's roles in [The explorer](https://www.typetorch.dev/guides/explorer.md#sign-in-and-roles), and the Open Cloud key's scopes per backend feature in [Running the backend](https://www.typetorch.dev/guides/backend-operations.md#open-cloud-key-scopes). The short version: | Who | How they get in | Can | |---|---|---| | Game servers | the game key (`TYPETORCH_API_KEY`) as a Bearer | write events, heartbeats, deploy reports, alerts, error logs, notification intents; read nothing | | Admin | the admin token (`TYPETORCH_ADMIN_TOKEN`; the CLI, or the explorer's token login), or an **owner** signing in with Roblox | read and manage everything | | Viewer (the `web` role) | Sign in with Roblox only, for the UserIds in `TYPETORCH_WEB_VIEWERS` (or the Settings page) | read the game's data; every write answers 403; never the server's configuration or game servers' IP addresses | | A named key | `ttk_...` as a Bearer, with a role (`game`, `lookup`, `support`, `analyst`, `admin`) | only its role's scopes ([API keys](https://www.typetorch.dev/guides/api-keys.md)); an `admin` key can't replace the owner list or the trust-link keys | | The lookup token | `TYPETORCH_LOOKUP_TOKEN` as a Bearer | `GET /v1/identity/resolve` only | - **Owners** are the access list the CLI sends with every settings write (`PUT /v1/access`, admin token only). Removing an owner or a viewer ends their sessions on their next request. Sign-in also works through [typetorch.dev](https://github.com/typetorch/backend#sign-in-with-typetorchdev), which only confirms who someone is: the role still comes from the backend's own lists. - **Sessions** are signed JWTs in an `HttpOnly`, `SameSite=Strict` cookie, valid 3 days from sign-in (`TYPETORCH_SESSION_MAX_DAYS`; no idle timeout). They survive restarts and deploys; changing the admin token ends them all. A cookie request that changes something also needs the `X-TypeTorch: 1` header and, when the browser sends an `Origin`, this site's. There is no CORS. - **Lockouts:** 5 failed logins or bad tokens in 15 minutes from one address get `429` until the oldest ages out (`TYPETORCH_LOGIN_MAX_FAILURES`, `TYPETORCH_LOGIN_WINDOW_MINUTES`). Wrong game keys are counted on their own, so a real game server behind a shared Roblox address is never blocked. - **Admin allow list:** `TYPETORCH_ADMIN_ALLOW_IPS` (addresses and CIDR ranges) makes the admin routes, the explorer and the login answer `404` to everyone else. Game routes stay open. `TYPETORCH_TOKEN_LOGIN=off` hides the token login in the browser (the CLI's Bearer still works). Both can be changed on the Settings page, behind guards that refuse to lock you out. - **Proxies:** client addresses come from `X-Forwarded-For` only with `TYPETORCH_TRUST_PROXY` (`1` behind Coolify or Caddy), and then the proxy must be the only way to the port (`TYPETORCH_TRUSTED_PROXIES` enforces it). Behind Cloudflare's proxy use `TYPETORCH_CLOUDFLARE=on` or a DNS-only record, or the allow list and the lockout see Cloudflare's address instead of yours. - **Audit log:** settings changes, key creates and revokes, per-player reads by API keys, remote debug commands and the other admin actions are written to the [audit log](https://github.com/typetorch/backend#audit-log) (the Audit page), never with a secret. ## Devtools reach devs only With kernel and framework 0.5.6+, the dev menu's client code (devtools) is not in the client tree every player gets. The server copies it into each dev's own `PlayerGui` when they join or become a dev; other players never receive it. Older kernels or frameworks ship it to every client as before (still gated on the server). ## Keys and tokens | Secret | Where it lives | Never | |---|---|---| | Open Cloud API key(s) | the game repo's `.env` (gitignored; CLI 0.9), or the real environment | in git, in chat, in an issue, in a screenshot, given to an agent | | Signing key files | `~/.config/typetorch/keys/.key` and `.fallback.key` | inside any git work tree (the CLI refuses), copied to another machine you don't control | | Backend admin token (`TYPETORCH_ADMIN_TOKEN`) | the game repo's `.env` and the backend's environment | anywhere a game server or a client can read it | | Mobile app tokens (`ttm_...`) and the mobile app's Open Cloud key | the phone's secure storage. The backend keeps only a SHA-256 of each mobile token | in git, in logs, in a game, or on a backend (the app's key goes only to `apis.roblox.com`) | | Named API keys (`ttk_...`) and the lookup token (`TYPETORCH_LOOKUP_TOKEN`) | the one tool that uses it (its secret store or environment) | in a game server, a client, or a shared chat | | Backend game key (`TYPETORCH_API_KEY`, write-only) | the game repo's `.env` and the backend's environment; the signed settings record's `backend` section (server only) | in code, in a payload, sent to a client | | Basin R2 token (SQL reads) | your PC only | in the game's settings | | Erasure webhook secret (`ROBLOX_WEBHOOK_SECRET`), alert webhook URL, the backend's Open Cloud keys (`OPENCLOUD_API_KEY`, `OPENCLOUD_NOTIFY_KEY`), the notification signing key (`TYPETORCH_NOTIFY_KEY` or `notify-keys.json`) | the backend's environment and data folder (the webhook URL in `runtime-settings.json` when saved on the Settings page) | in git; a downloaded backup leaves the webhook URL and `notify-keys.json` out | | remote-claude pairing codes | your terminal and clipboard | in a commit (they expire after one use or 3 hours) | | `typetorch serve --remote` pairing links | your terminal (`serve status`), then the person you send it to | in a public channel (one use, 15 minutes; paired devices are listed by `serve devices`) | - The CLI keeps keys and tokens in memory, gives each one only to the client for its job, never prints them, and redacts them from errors. Child processes (rbxtsc, rojo, lune, git) get an allowlisted environment without keys. - Game servers get only write-only tokens. They can send analytics and fleet data, never read it. - Prefer separate keys per job (`OPENCLOUD_ASSETS_KEY`, `OPENCLOUD_DEPLOY_KEY`, `OPENCLOUD_PLACE_KEY`), an expiry date and an IP allowlist. An `asset:write` key that leaks is as bad as code execution on your servers: keep `asset:write` on one IP-limited key. - **Before a live game depends on it:** an offline backup of the key files and the `.env`, the separate `asset:write` key, and a dated rotation drill ([Prod signing: back up and drill](https://www.typetorch.dev/guides/prod-signing.md#back-up-and-drill)). - A key acts with its owner's group permissions. Give builders and contractors no Edit access on the production experience. - If a key leaks: revoke it in Creator Hub at once and create a new one. If a signing key leaks: `typetorch keys rotate` (main) or `typetorch keys init --fallback --force` + `kernel deploy` (fallback). If a token leaks: rotate it. For the game key, put the new one in the backend's `TYPETORCH_API_KEY`, the old one in `TYPETORCH_API_KEY_PREVIOUS` (both accepted until you remove the old one), put the new one in the game repo's `.env`, and run `backend setup` again. For the admin token, change `TYPETORCH_ADMIN_TOKEN` on the backend (that ends every explorer session) and in the game repo's `.env`. For a named API key: revoke it (`DELETE /v1/admin/keys/`, or `typetorch keys revoke ` with CLI 0.19.0+) and create another ([API keys](https://www.typetorch.dev/guides/api-keys.md)). ## `typetorch serve` and remote Studios - The control API listens on `127.0.0.1` only. Every request needs `X-TypeTorch: 1`, a loopback `Host` and no `Origin`, and there is no CORS, so a web page can't call it. serve's children (rbxtsc, rojo, your `--with` scripts) get the CLI's minimal environment, without keys; the hot asset jobs run inside serve with your keys. - `--remote` opens a gateway (`127.0.0.1:34890`) behind a public tunnel. Only a paired device gets in: a one-time code (15 minutes; 5 wrong codes lock pairing until a new code), then a device token kept hashed in `.typetorch/serve-remote.json`, valid 30 days or until `serve unpair`. A remote Studio syncs code read-only (never Rojo's `write` or `open`), and its hot asset buttons upload with **your** keys and deploy only to the dev branch. Pair only people you would give that to. - `--claude` lets the Roblox users in `--claude-users` (default: the owners in `typetorch.json`) prompt Claude Code on your machine, in Code mode, with remote-claude's rules (below). Deploys from it follow your approval policy. ## No CI for your game TypeTorch ships no GitHub Actions or other hosted CI for games, and nothing in it needs your Open Cloud key or signing keys in a CI system: hosted CI is a common supply-chain risk, and it would need those keys. Builds, cloud tests, signing and deploys run on your own machine. `approve --import ` exists for automation you choose to run yourself. TypeTorch's own npm packages are released from a version tag by a GitHub workflow, with npm trusted publishing and provenance ([Releases](https://www.typetorch.dev/docs.md#releases)). That workflow holds no Roblox key and never touches a game. ## Never publish secrets - `.env`, `.env.*`, `.typetorch/` and the key files stay out of git (the template's `.gitignore` covers the first three; key files live outside the repo). The backend repo ignores `.env` files and `data/`. - Ids (universe, place, group, user, asset) are not secrets, but keep examples and docs on fake ones. - A quick tunnel URL is public while it runs: anything behind it must check its own tokens (the backend does). - Before you push or publish a package, search the change for anything that looks like a key. ## Agents The [agent playbook](https://www.typetorch.dev/agents/AGENTS.md) forbids agents to create, read or store keys, publish places or deploy. If an agent runs a deploy command anyway, the CLI only writes a proposal (it isn't an interactive terminal), but the build is still uploaded with your key: keep keys where agents can't read them (outside the repo, not in the agent's environment). --- # Troubleshooting Real errors seen while building and running TypeTorch, and what fixes them. Run `bun run typetorch doctor` first: it checks the tools, `typetorch.json`, every key and scope, the signing keys, the key asset and the place. ## Setup and builds **Rojo plugin refuses to connect, or a 7.6.1 server is refused.** The Studio plugin and `rojo serve` must speak the same protocol. Pin `rojo = "rojo-rbx/rojo@7.7.0-rc.1"` in `rokit.toml`, run `rokit install`, and check `rojo --version` inside the game folder (a global Rojo may be older). **`rojo` or `lune` is not found / the wrong version.** Run `rokit install` in the game folder. `kernel deploy` runs Lune inside the kernel folder, so the game's `rokit.toml` pins Lune too. **Bun fails with `EPERM` installing `file:../framework`.** Bun on Windows can't install a `file:` folder dependency. Use the npm versions (the template's `package.json`), or, for unreleased changes in a checkout, the template's local override: `bun run packages` ([fresh setup](https://www.typetorch.dev/getting-started/fresh-setup.md#unreleased-framework-or-kernel-changes-optional)). **`bun install` fails with `Module not found "scripts/packages.ts"`.** `package.json` has the template's `postinstall` script but not the script it runs. Copy `scripts/packages.ts` from the template, or delete the `postinstall` and `packages` scripts (you only need them for the local override). **The framework in `node_modules` is stale after you pulled a checkout.** With the local override, `bun install` re-extracts the old tarballs. Run `bun run packages` again (it rebuilds the framework and the transformer, repacks them and the kernel, and extracts them into `node_modules`). To go back to the npm versions: `bun run packages --off`. **The build id ends in `-dirty` right after `bun run packages --off`.** On Windows with git's `core.autocrlf` on, the reinstall can rewrite `bun.lock` with other line endings. `git checkout -- bun.lock`. **`TS2688: Cannot find type definition file for 'kernel'`** (or similar). `tsconfig.json` needs `"types": ["types", "compiler-types"]`; otherwise the `@typetorch` type root pulls in the kernel package, which has no typings. **`Cannot find name 'console'` in `scripts/build-info.ts`** (or another file under `scripts/`). rbxtsc compiles your scripts folder. Add `"include": ["./src/**/*.ts"]` to `tsconfig.json`. **`createNetwork: guards were not generated (is @typetorch/transformer in the tsconfig plugins?)`** The transformer isn't running. `tsconfig.json` `plugins` must list `{ "transform": "@typetorch/transformer" }`, and `@typetorch/transformer` must be in the devDependencies and installed (`bun install`). Since transformer 0.3.2 the debug macros (`$print`, `$warn`, `$dbg`, ...) are built in (`@typetorch/transformer/macros`), so it can be the only plugin; a project still on `rbxts-transform-debug` lists that one first. goblox runs only `@typetorch/transformer` and ignores other plugins. **`darklua not found: this payload isn't minified`.** A warning, not an error: the build still works, unminified. Add darklua with `rokit add seaofvoices/darklua` (or set `TYPETORCH_DARKLUA` to its path), or build with `--no-minify`. The warning also suggests `"minify": false` in `typetorch.json`, but the CLI (through 0.19.0) drops that key as unknown, so it doesn't silence anything yet ([Production pack](https://www.typetorch.dev/guides/deploy-and-rollback.md#production-pack)). **`compiler goblox was requested (...) but goblox is not installed`.** `TYPETORCH_COMPILER=goblox` or `typetorch.json` `"compiler": "goblox"` asks for goblox, and an explicit request never falls back to rbxtsc. Run `bun add -d goblox`, or remove the setting (without it, the build uses goblox only when `node_modules/.bin/goblox` exists, else rbxtsc). **`You can only use npm scopes that are listed in your typeRoots` on an `@flamework/core` import.** TypeTorch no longer uses Flamework. Import `Service`, `Controller`, the lifecycle interfaces, `Modding`, `Reflect` and `t` from `@typetorch/framework` ([Coming from Flamework](https://www.typetorch.dev/getting-started/migrate.md#coming-from-flamework)). **`npx rbxtsc` does something unexpected (Windows, Bun project).** `npx` resolves an unrelated placeholder package there. Use `bun run build`, `bunx rbxtsc`, or `node node_modules/roblox-ts/out/CLI/cli.js`. **`X needs Y, which is not a loaded @Service/@Controller`, or `dependency cycle: A -> B -> A`.** A constructor parameter is not a module of the same realm, its file isn't under the folders `boot.ts` passes in `modules`, or two modules need each other. For a cycle, take one side as `Lazy` (a field `= Lazy()`, or a constructor parameter with `@typetorch/transformer` 0.2.1+), call `Dependency()` inside a method, or move shared logic into a third module ([Dependency cycles](https://www.typetorch.dev/getting-started/migrate.md#dependency-cycles-lazyt)). **`ShopService isn't constructed yet: call Dependency() from onInit/onStart or later`.** `Dependency()`, `TypeTorch.module()` or `Lazy.get()` ran before every module was constructed: in a constructor, a field initializer, or at the top level of a module ("ran while the modules were loading"). Call it in a method or in `onInit`. **`X: constructor parameter 2 is a Lazy, but this build's @typetorch/transformer doesn't record T`.** `Lazy` constructor parameters need `@typetorch/transformer` 0.2.1 or later. Update it, or declare a field instead: `private readonly team = Lazy()`. **`the payload may hold only Folders and ModuleScripts under one Model root; found: ... (Script)`.** A `*.server.ts` / `*.client.ts` (or a model file) is in a synced folder. Move its work into a module and delete it. **`git-ignored files in the payload's source dirs would ship in a "clean" artifact`.** Something ignored sits under `src/` or another synced folder. Delete it, or stop ignoring it and commit it. **`compiled files that no tracked source explains`.** `out/` holds output from a deleted or untracked file. `bun run typetorch build --clean` (deploys always clean), and commit new files. **`... does not contain commit abc1234: rbxtsc kept a stale build.ts`.** Delete `out/` and build again. **The artifact id ends in `-dirty-...`.** Uncommitted changes. Commit, then build again for a clean id. Prod-channel branches refuse dirty builds without `--force`. ## Keys and scopes **`no Open Cloud API key for assets: set OPENCLOUD_ASSETS_KEY ... or OPENCLOUD_API_KEY ...`.** The CLI found no key. Check the game repo's `.env` (CLI 0.9: `OPENCLOUD_API_KEY`; `TYPETORCH_API_KEY` is the backend's key now, not a Roblox key). `doctor` prints which files it read. **A scope probe in `doctor` fails with 401/403.** Edit the key in Creator Hub and add the missing permission for this experience. **`refusing to publish a kernel that can't verify prod deploys`.** Run `bun run typetorch keys init` and `bun run typetorch keys init --fallback` first, commit `typetorch.json`, then `kernel deploy`. **`kernel deploy` says the place can't be patched through the API.** The default engine saves the place in a Luau Execution task. That 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), no active Team Create session, and the place key's Luau Execution scopes. Without the setting, download a copy in Studio (File > Download a Copy) and pass it: `--place-file --base ` ([Kernel updates](https://www.typetorch.dev/guides/deploy-and-rollback.md#kernel-updates)). **`backend setup`, `access push` or `settings ...` fails with 401/403.** The [settings record](https://www.typetorch.dev/guides/settings.md) is a DataStore entry: the deploy key needs `universe-datastores.objects:read`, `:create` and `:update` (the ping also needs `universe-messaging-service:publish`). `universe:write` isn't used any more. **`... signed with both prod keys: run typetorch keys init`.** Settings writes (`settings set`, `backend setup`, `access push`) sign the record with both prod keys. Set them up ([fresh setup step 7](https://www.typetorch.dev/getting-started/fresh-setup.md#7-prod-signing-keys)), or copy the key files from the machine that has them. **`the current settings record isn't signed by your keys`.** Someone else's keys (or game code) wrote it, or you rotated without `keys rotate` re-signing it. Check `bun run typetorch settings status`. `--force` replaces it: the old fields are dropped, never re-signed with your keys, so run `settings push`, `access push` and `backend setup` again afterwards. **`typetorch config push` is gone.** Kernel 0.3.8 reads no ConfigService keys. Use `typetorch settings push` (defaultBranch, channels, dev access), `typetorch backend setup` (CLI 0.9 also moved `fleet setup` and `settings set analytics` there). ## Deploys **`refusing to deploy a dev-channel artifact ... to prod-channel branch "prod"`.** You built on a dev branch. Deploy prod from the git branch mapped to it (`main`), or pass `--force` knowingly. `promote` refuses it even with `--force`: "rebuild for prod". **`refusing to deploy a dirty build to prod-channel branch "prod"` with nothing to commit.** Untracked files count as changes. Commit or delete them; `git status --porcelain --untracked-files=all` lists what the CLI sees. CLI 0.10.3+ ignores untracked editor swap and backup files (`*.swp`, `*.swo`, `*~`, `.#*`, `4913`); on an older CLI close the editor or delete them. **`typetorch reject` says `proposal ... is already approved`.** `reject` drops pending proposals only. An approved one has gone out: roll back or deploy again instead. Proposals are whole builds, so reject the older ones once a newer one is approved ([Approval and proposals](https://www.typetorch.dev/guides/deploy-and-rollback.md#approval-and-proposals)). **The cloud test prints `liveConfig("x") needs kernel 0.3.8 ... using the default` for every key.** Harmless: the cloud test has no signed settings record, so `liveConfig` gives its defaults there. Framework 0.5.2+ doesn't print it in `typetorch test --cloud`. **`approve` refuses to run.** It needs an interactive terminal (stdin and stderr). Run it yourself in a terminal, not through an agent or a pipe. **A deploy left only a proposal.** The CLI wasn't in an interactive terminal (an agent, CI, the dev-server) or you passed `--propose`. `bun run typetorch proposals`, then `bun run typetorch approve `. **Moderation times out.** The upload is recorded in `uploads.jsonl`. When Roblox approves it: `bun run typetorch promote `. `--moderation-timeout ` waits longer. **The cloud test fails.** Read its errors: they are your build's (an `onInit` or `onStart` that throws, a Shared module that errors, a stop that times out). Fix and deploy again. Game code that must not run in the test (it runs against real DataStores) can check `workspace:GetAttribute("TypeTorchTest")`. Place scripts never run there: code that waits for one (for example `DataHost didn't require ProfileStore` after 10 s) fails the test; see [Player data: the cloud test](https://www.typetorch.dev/guides/player-data.md#the-cloud-test). A missing Luau Execution scope fails it too: add `universe.place.luau-execution-session:read` and `:write` to the assets key. To publish anyway, knowingly: `--skip-test ""`. **`deploy --wait` rolled the branch back by itself (`auto_rollback`).** 20% or more of the servers that tried the build failed or rolled back (`"autoRollback": { "failedPct" }` in `typetorch.json` changes the 20). `bun run typetorch report "#"` shows the errors and the servers. Fix, then deploy again. `--no-auto-rollback` keeps a build that fails on some servers. **Every server rolls back every new build ("3 errors within 30 s of ready").** The game throws a few errors right after it starts, on every server. Fix them, or raise the limit in `typetorch.json` (kernel 0.3.7+): `"health": { "errors": 10 }`. See [Set the health window](https://www.typetorch.dev/guides/deploy-and-rollback.md#set-the-health-window). **`deploy --wait` warns about stuck servers (`server_stuck`).** Some servers didn't pick up the deploy in time and sent nothing. Nothing is rolled back. They poll the head every 60 s; check again with `bun run typetorch servers --branch `. **`the fleet API isn't configured` (from `servers`, `report`, `alerts`, or `--wait` skipped).** Set it up once: [Live servers and alerts](https://www.typetorch.dev/guides/fleet-and-alerts.md#set-it-up). The CLI needs `TYPETORCH_ADMIN_TOKEN` and `TYPETORCH_API_KEY` in the game repo's `.env`, and `typetorch.json` `backend.url`. **Asset names show up as `####` in Creator Hub.** Roblox's text filter censors some hex names unpredictably. The CLI renames censored payloads to `TypeTorch payload`; the build's identity is in its attributes, the notes and the deployment log. **`LoadAsset` fails with an ownership or "not trusted" error.** `typetorch.json` `creator` must be the experience owner (the group, for a group game). The key's owner needs permission to upload for that group. ## Live servers **Servers log `branch prod has no artifact yet; waiting for a deploy`, or (kernel 0.3) `nothing loaded (no verified, bootstrap or usable stored head); peers and the backup next, and waiting for a signed deploy`.** Nothing was deployed to that branch yet, or the head wasn't stored. Deploy again: the CLI stores the head in the game's DataStore when the deploy key has the DataStore scopes (`universe-datastores.objects:read`, `:create`, `:update`); without them it warns "the head isn't stored durably" and only running servers get it, so keep one open (join the game). **After a swap, the old dev menu stays on screen, dead, over the new one** (its header names an older ` #`), memory grows by several MB per swap, or something the old build made keeps acting. A cleanup threw while the old generation stopped, and before framework 0.5.2 that aborted the rest of the stop: later modules' troves, the network and the dev menu's own cleanup never ran, and the dead generation stayed in memory. The usual cause is `trove.remove(x)` inside a cleanup ("Cannot call trove.remove() while cleaning" in the client or server log); see [rule 1](https://www.typetorch.dev/getting-started/migrate.md#rule-1-everything-goes-in-the-modules-trove). Framework 0.5.2+ cleans every object in its own pcall (a throwing cleanup warns ` cleanup threw: ...`), stamps the `TypeTorchDev` ScreenGui with a `TypeTorchGeneration` attribute and destroys any menu from an older generation when it starts. On an older framework, fix the cleanup and add a sweeper to a client module: ```ts onInit() { const gui = Players.LocalPlayer.WaitForChild("PlayerGui"); for (const child of gui.GetChildren()) { if (child.Name === "TypeTorchDev" && child.GetAttribute("SweepMe") === true) child.Destroy(); } this.trove.add( TypeTorch.onSwapOut(() => { // Runs before any cleanup, so it happens even if one throws later. for (const child of gui.GetChildren()) if (child.Name === "TypeTorchDev") child.SetAttribute("SweepMe", true); }), ); } ``` **LuauHeap shows old generations' `RuntimeLib` (about 10 to 26 KB each).** Each past server generation's `include.RuntimeLib` stays referenced through a pending `TS.import` Promise. It is small and harmless (one per past generation, so a few dozen after a day of deploys). A whole generation kept in memory (MBs per swap) is the entry above. **A deploy doesn't reach Studio.** Deploy messages never reach Studio playtests. Use [the Studio local payload](https://www.typetorch.dev/guides/studio-testing.md) with `typetorch serve`. **Dev menu: "No trusted prod head".** The server has no signed head for its branch and no bootstrap head. The next signed prod deploy boots it. If you deployed prod from another machine before `kernel deploy`, run `kernel deploy` again from the machine with the latest log ([bootstrap heads](https://www.typetorch.dev/guides/prod-signing.md#bootstrap-heads)). **Dev menu: "Booted an unverified prod head".** The [boot fail-safe](https://www.typetorch.dev/guides/prod-signing.md#the-boot-fail-safe) ran a stored build it couldn't verify. Deploy (or re-sign with `bun run typetorch keys resign`) to replace it with a verified one. **Dev menu: "Keys changed" without a rotate.** The key asset changed and no `TypeTorch/rekey` hint came with it. If you didn't run `keys rotate`, someone with asset write access in your group changed it: check the key asset's versions in Creator Hub. **"Use the CLI: typetorch pin" or "Other prod servers: typetorch pin" in the dev menu.** Prod servers take only signed pins sent from outside, and on older kernels the dev menu can't load a build on a prod server at all. Use `bun run typetorch pin ...`. **Dev menu: "No fleet API".** The place's kernel has no `Fleet` module: a place project that maps the kernel's files one by one must map `Fleet` too (kernel 0.3.2+). Map it, then publish the place. **Dev menu: "Fleet API failing", or `servers` lists nothing.** The fleet URL doesn't answer or the token is wrong. Run `bun run typetorch doctor`: it tests the `backend` address and keys in the live settings record (the URL, `GET /healthz` within 5 s, and the keys) and prints a fix for each failure. A quick tunnel gets a new URL every time it starts: run `bun run typetorch backend setup --url ` again (or restart `bun run local -- --game ` in the backend folder). Running servers (kernel 0.3.8+) switch within seconds; new servers at once. **`backend setup` says "refusing to write ... nothing was signed or written".** Before it signs anything the CLI tests the address and the token, and one of them failed. The message lists each failing check with a `fix:` line: | Check | Meaning | |---|---| | `url` | not a URL, not https (game servers and the kernel only use https; http only on localhost, for this PC), user info in it, or not the server's base address | | `healthz` | `GET /healthz` didn't answer `{"ok":true}` within 5 s: a dead quick tunnel (start `bun run local` again; the URL changes every run), a stopped server, a wrong host, or something else answers there | | `key` | the server refused the game key (`TYPETORCH_API_KEY` in the game repo's `.env`), or that part of the server is off (`TYPETORCH_PARTS`), or it is the admin token (never put that in the record: every script in your game can read it) | | `admin` | `TYPETORCH_ADMIN_TOKEN` isn't the admin token (the server answers role `admin` for it), or it is the same value as the game key | Fix it and run the command again. `--force` writes the value anyway (the failures print as warnings), except an admin token in the key's place, which is always refused. `bun run local` prints the same message in red when the game's CLI refuses its tunnel, and keeps the tunnel running. **Server log (or Analytics / Fleet API line in the dev menu): `HttpError: NetFail`, `DnsResolve`, `ConnectFail`, HTTP 530.** The game servers can't reach your analytics / fleet server. Roblox names the failure: `NetFail` means the connection broke mid-request (the server or the tunnel on your PC restarted, dropped it or is overloaded; quick tunnels are for testing only), `DnsResolve` or HTTP 530 that the quick tunnel's address is gone (it changes on every start), `ConnectFail` that nothing accepts connections there, `TimedOut` that it never answers (the PC is asleep?). Run `bun run typetorch doctor`, then `bun run local -- --game ` in the backend folder if the address is stale. The engine keeps the rows and retries with a growing pause (5, 10, 20 ... 300 s, spread so servers don't retry together); it logs at most one line a minute with the reason and the fix, and one line when uploads work again. **Server > Status** shows the *Analytics* and *Fleet API* lines (queued, sent, `FAILING x5: ... retry in 80 s`, the last error and its age) and *Attention* lists the fix. **The quick tunnel answers 404 for everything.** Your `~/.cloudflared/config.yml` (a named tunnel) has a catch-all ingress rule, and it overrides `--url`. `bun run local` passes an empty config, so this happens only with a cloudflared you start yourself: give it an empty `--config` file. **Analytics: no rows arrive.** Check, in order: an `AnalyticsEngine` is created on the server (the client alone sends nothing), in a module's `onInit` (an engine first created on some game event never starts on an idle server); Allow HTTP Requests is on; the settings record has a valid `analytics` field (`bun run typetorch settings get analytics`; kernel 0.3.8+; without it the engine keeps only the newest 1,000 rows); `analytics.stats()` on the server shows what was sent, dropped or refused. Game servers send every 15 s (`flushSeconds`); a DuckDB server loads them a few seconds later, Basin after its roll interval (1-2 minutes). To see the raw rows without waiting for a chart: `POST /v1/sql` ([Debugging endpoints](https://www.typetorch.dev/guides/fleet-and-alerts.md#debugging-endpoints)). **Basin: rows are sent (2xx) but never show up.** Basin drops rows that don't match the stream's schema, silently. Create the streams from the backend repo's `basin/*.schema.json` exactly; a schema can't be changed after the stream exists. **Kernel updates fail with HTTP 409 when publishing the place.** An active Team Create session blocks publishing. Close Studio sessions on that place (everyone), then retry. **`StandardListGameServerThrottled ... ListKeysAsync` in server logs.** Kernels before 0.2.1 listed DataStore keys too often. Publish a newer kernel and migrate servers. **Dev menu: "Kernel update".** The place has a newer kernel than this server. Press **Migrate** (moves everyone on this server to a fresh one) or restart servers. **Dev menu: "HTTP off".** Turn on Allow HTTP Requests (Game Settings > Security), then publish. **Dev menu: "run_luau off".** `ServerScriptService.LoadStringEnabled` is off. That is right for a live game. Turn it on (Studio's Properties, then publish, or `kernel deploy --loadstring` with CLI 0.7.5+) only in a place where you want remote-claude's `run_luau`, such as a test place. **A member doesn't get the dev menu (or a revoked dev still does).** Servers see `members`, `revoked` and `devBadgeId` only after `bun run typetorch access push`, and only on kernel 0.3.8+ (0.3.6 and 0.3.7 read the old ConfigService key: push again after the kernel update). Run it after every change; `bun run typetorch access status` compares the settings record with `typetorch.json`. Running servers apply it within seconds. **`typetorch doctor` warns that the place holds `ServerStorage.TypeTorchDev`.** A Studio test session was published. Delete the folder in Studio and publish again (live servers ignore it). ## Studio and `typetorch serve` **The plugin's panel says "Waiting for typetorch serve" (or `serve status` lists no Studio).** Start `bun run typetorch serve` in the game folder, and allow the plugin's HTTP request to localhost when Studio asks (Studio asks per port; the plugin probes 34880-34887 one at a time). The plugin only syncs a place whose experience (`game.GameId`) is `typetorch.json`'s `universeId`: for another place or an unpublished file press **Connect anyway** (or `typetorch studio reconnect --anyway`). If the sync is paused, turn "Auto-connect" back on in the panel. **`typetorch studio ...` says no Studio is attached, but Studio is open.** The plugin may be stuck. In Studio's command bar (or the Roblox Studio MCP's `execute_luau`): `game:GetService("ServerStorage"):SetAttribute("TypeTorchReconnect", os.time())`. **`@typetorch/studio-plugin isn't installed` from `typetorch studio install-plugin`.** The plugin is not on npm. Download `TypeTorchSync.rbxm` from the [latest release](https://github.com/typetorch/studio-plugin/releases/latest) into Studio's plugins folder, or build a checkout: `bun run typetorch studio install-plugin --from ../studio-plugin`. **A save doesn't reach the running playtest.** Live reload needs kernel 0.5.4+ in `node_modules/@typetorch/kernel` (synced by `studio.project.json`) and the panel's "Live playtest: on". With an older kernel, Stop + Play. **`ServerStorage.TypeTorchDev.Payload has no Server.boot`** (or `Client.boot`; for an uploaded build ` has no Server.boot`). Kernel 0.5.6+ refuses a payload whose Server or Client half is empty, before it stops the running generation, so a live reload or Reload keeps the old code. In Studio it usually means Rojo lost `out/` (deleted and recreated, as a clean build does): `bun run typetorch serve restart rojo`. CLI 0.12.2+ restarts Rojo by itself when that happens. For an uploaded build, rebuild and deploy again. **Rojo moved to another port (`Rojo's port 34872 is taken by another process`).** Something else holds the port, often a Rojo that an earlier, killed serve left running. serve moves Rojo to the next free port and the plugin follows. The next `serve` stops such leftovers on Linux; on Windows and macOS it names them (`an earlier typetorch serve left rojo running (pid ...)`): stop that process. **Two sync plugins fight over the place.** Connect only one of the stock Rojo plugin and the TypeTorch plugin at a time. **The remote pairing link stopped working.** A quick tunnel's address changes whenever cloudflared restarts; serve prints a new link (`typetorch serve status`). Links last 15 minutes and work once; `typetorch serve pair` makes a new one. After 5 wrong codes pairing is locked until you make a new code. For a fixed address use your own tunnel with `serve --remote --url https://`. **The Studio Claude tab says "Claude isn't running" or "This typetorch serve is too old for Claude".** Start serve with `--claude`, with `@typetorch/dev-server` installed and Claude Code logged in with your Claude.ai account. "Not on the session's user list": add the Roblox user id with `--claude-users`. serve doesn't restart Claude when it exits: check `serve logs` for the reason, then `serve restart claude`. **`serve logs` shows `[claude] error: unexpected argument "dev"`** (or your `--dev-branch`). serve (CLI 0.12.2+) starts remote-claude with `--deploy-branch `, which dev-server 0.3.3 and older don't know. It needs dev-server 0.4.0, which isn't on npm yet: run a checkout through `TYPETORCH_DEV_SERVER` ([From Studio](https://www.typetorch.dev/guides/remote-claude.md#from-studio)). **Claude in the Studio tab can't see the open place (its `inspect` or `find` calls time out).** Expected for now: serve on CLI main doesn't relay those tool requests to the plugin yet (**planned**). Claude works from the files; Apply the change and look in Studio. ## remote-claude **Claude tab: "Not connected: start the dev server on this branch".** Start `remote-claude` on the git branch that maps to this server's branch, on a dev-channel server. It announces itself every 60 s; give a new server up to a minute. The dev-server needs an API key with messaging publish in the environment or a `.env` file. **"That code is for another tunnel: use the newest code" / "Wrong, used or expired code".** Codes are single-use and bound to the tunnel. Type `code` in the dev-server terminal and paste the newest one. **"Refused: Claude Code must use a subscription login" (`api_billing_refused`).** Run `claude auth login` with your Claude.ai account and remove `ANTHROPIC_*` variables from that terminal. **`branch ... is on the prod channel; remote-claude only runs on dev-channel branches here`.** Switch to a dev branch (`git switch dev`). Only a local session (`--no-tunnel --no-announce`, as `serve --claude` runs it, dev-server 0.4.0) may use a prod-channel branch, and then deploys only to `--deploy-branch`. **Images don't show in the chat (one dim line instead).** Turn on Allow Mesh / Image APIs; the experience owner must be 13+ and ID-verified. **Toolbox insert fails with `third_party_off`.** Turn on "Allow Loading Third Party Assets" (Studio > File > Experience Settings > Security). --- # The mobile app The TypeTorch app is a phone app for your Roblox experiences. It lists the experiences your Open Cloud key can reach, shows their analytics and tools, and shows your self-hosted backend's pages (live servers, deploys, errors, analytics) natively on the phone. It also has home-screen widgets for live numbers, milestone alerts and exports. > **Status: early, Android only.** The app ships as an APK for now. It is not on Google Play yet. The backend side > (sign-in, live numbers, widgets and milestone pushes) is on the backend's main branch. See > [Backend requirements](https://www.typetorch.dev/guides/mobile-app.md#backend-requirements). The app is open source (MIT) at [github.com/typetorch/mobile](https://github.com/typetorch/mobile), like the other TypeTorch repos. ## What you need | For | You need | |---|---| | Your experience list and Roblox analytics | an Android phone and an Open Cloud key ([below](https://www.typetorch.dev/guides/mobile-app.md#open-cloud-key)) | | The TypeTorch pages, live numbers, widgets, milestone alerts | a self-hosted [backend](https://www.typetorch.dev/guides/backend-operations.md) for the game and a sign-in to it from the app | | Widgets that show per-release health | a backend with health and a phone with the widget engine ([Widgets](https://www.typetorch.dev/guides/mobile-widgets.md#health)) | ## Install 1. Ask the maintainer for the APK link. Builds come from EAS (Expo's build service), as an internal APK. 2. Open the link on the phone and install. Android asks once to allow installs from that source. 3. The app checks for updates when it opens and applies them on the next start. **Restart to update** in the app applies one now. A store build (Google Play) comes later. It is built as an app bundle from the `production` profile and is not published. To build it yourself, clone [typetorch/mobile](https://github.com/typetorch/mobile) and build an APK with EAS from the `preview` profile (`eas build --profile preview --platform android`). Point it at your own Expo account first: set `owner` in `app.json` and run `eas init` for a new project id. Milestone pushes need your own Firebase project's `google-services.json` (see the repo's `docs/FIREBASE_SETUP.md`); without it the app works and only the pushes are off. Developers build a development client from the `development` profile. Expo Go is not enough for the widgets and the live watch, because they use the app's own native module. ## Backend requirements The app uses these backend routes. They are on the backend's main branch. | Feature | Backend routes | |---|---| | Browser sign-in, admin-token sign-in, refresh, sign-out, revoke | `/auth/mobile/*`, `/v1/auth/mobile/*` | | Live numbers, live watch and widgets | `GET /v1/mobile/live`, with `metrics=` for widget stats and the release garden | | Milestone pushes | `POST` and `DELETE /v1/mobile/push`, `POST /v1/mobile/push/test`, and the `ccuMilestone` alert rule | | TypeTorch pages | the explorer's `/v1/...` routes, called with the mobile token | The Projects, analytics and tools use Roblox's own APIs and do not need a backend. ## Sign in to a backend 1. Open **Backends** and choose **Add backend**. Type the backend's address (for example `https://backend.example.com`). A missing `https://` is added for you. `http://` is only accepted for `localhost`, LAN addresses and `.local` names, and the app marks it as not encrypted. 2. Pick a sign-in method: - **Sign in with the browser** (the default). The app opens the backend's sign-in page. You sign in with Roblox there, approve the consent page and come back to the app. - **Use the admin token.** Paste the backend's admin token once. The app trades it for a device token and forgets the admin token. Over `http://` the app asks first. 3. The sign-in gives a role. **admin** can use everything the admin token can. **web** is read-only, like the explorer's viewers. The phone keeps a mobile token (`ttm_...`) for each backend, in the phone's secure storage. The token lasts 60 days by default, and the backend can set 30 to 90. The app renews it when fewer than 15 days remain, and the old token is revoked at once. A renewed token keeps its sign-in's time: after 180 days from the sign-in (the backend's `TYPETORCH_MOBILE_TOKEN_MAX_DAYS`), the app must sign in again. To sign a phone out, use the app's sign-out. On the backend's Settings page, the **Mobile app sessions** card lists the sessions and revokes one, or every phone at once (**Revoke all**). A backend that rejects the token marks that backend as signed out. Changing the backend's admin token ends the tokens made with the admin token, but not the Roblox users' tokens: use **Revoke all** for those. ## Open Cloud key An Open Cloud key lets the app read your experiences from Roblox. Analytics, the Projects list and the Tools need it. - **Where to make it:** Creator Hub, Open Cloud, API Keys. Add each experience you want the app to reach. Group experiences need a key made under the group. - **Where it lives:** only on the phone, in the phone's secure storage. The app checks it with Roblox (`POST https://apis.roblox.com/api-keys/v1/introspect`) and sends it only to `apis.roblox.com`. - **Not the backend's key.** A TypeTorch backend keeps its own Open Cloud key (`OPENCLOUD_API_KEY`, see [Running the backend](https://www.typetorch.dev/guides/backend-operations.md#open-cloud-key-scopes)). The app never sends its key to a backend. - **Start read-only.** Settings lists which scopes the key is missing for each feature. Read-only scopes (enough to list experiences and see analytics): ```text universe:read universe.place:read universe.analytics:read group:read user.social:read user.advanced:read universe-datastores.control:list universe-datastores.objects:list universe-datastores.objects:read universe-datastores.versions:list universe-datastores.versions:read universe.ordered-data-store.scope.entry:read memory-store.sorted-map:read universe.user-restriction:read developer-product:read game-pass:read ``` Write scopes are needed only for the actions in the Tools tab. Every write asks you to confirm first. | Area | Scopes | |---|---| | Experience and places | `universe:write` (also restart servers), `universe.place:write`, `universe-places:write` (publish) | | Data stores | `universe-datastores.objects:create`, `:update`, `:delete`; `universe-datastores.control:delete`, `:snapshot` | | Ordered data stores | `universe.ordered-data-store.scope.entry:write` | | Memory stores | `memory-store.sorted-map:write`; `memory-store.queue:add`, `:dequeue`, `:discard`; `memory-store:flush` | | Messaging | `universe-messaging-service:publish` | | Bans | `universe.user-restriction:write` | | Products, passes, badges | `developer-product:write`, `game-pass:write`, `legacy-universe.badge:write`, `legacy-universe.badge:manage-and-spend-robux` | | Analytics extras | `universe.analytics:write`, `universe.analytics.dashboard:read` / `:write`, `universe.analytics.alert:read` / `:write` | | Engagement | `universe.event:read` / `:write`, `universe.notification-string:read` / `:write`, `universe.thumbnail:read` / `:write`, `user.user-notification:write` | | Servers and live tools | `universe.place.instance:read` / `:write`, `universe.place.luau-execution-session:read` / `:write` | | Secrets | `universe.secret:read` / `:write` | | Assets | `asset:read`, `asset:write`, `asset-permissions:write` | | Other | `ad.campaign:read` / `:write`, `extended-services:read` / `:write` | Optional legacy scopes (`legacy-universe:manage`, `legacy-game-pass:manage`, `legacy-developer-product:manage`, `legacy-badge:manage`, `legacy-group:manage`, `legacy-team-collaboration:manage`, `legacy-universe.following:read` / `:write`) are asked for only by the screens that use them. ## Projects The home screen lists only the experiences you added: **Pinned** first (tap the star), then **Projects**, in the order picked with the sort chips. Search filters by name, ID or creator. **Add projects** opens everything you can reach, in sections: the universes your Open Cloud key names and your own experiences, then one section per group where your rank is high enough (Settings picks which groups: owned, rank 200 and up, or all). You can also add an experience by place link or ID there. A connected backend's universe is always listed, even when it is private or unlisted. Pull to refresh, or search. ## An experience Each experience has these tabs. | Tab | What it shows | Needs | |---|---|---| | Overview | banner, playing, visits, favourites, likes, description, creator, dates, visibility, devices, private servers, places, public servers | Roblox's public APIs | | Analytics | Creator Hub's charts: players, sessions, retention, revenue, FPS and crashes, for 7, 28 or 90 days, with breakdowns | `universe.analytics:read` | | Thumbnails | a gallery of the experience's thumbnails | `universe.thumbnail:read` | | Ads | the Ads Manager (beta): campaigns and creatives. It has no impressions, clicks or spend yet | `ad.campaign:read` | | Tools | data stores, ordered and memory stores, MessagingService, restart servers, bans, passes, products and badges | each tool's scope | | TypeTorch | the backend's pages, for the universe the backend is connected to | a signed-in backend | Analytics reads are cached for an hour and at most two run at once, because Roblox limits queries per key. ### TypeTorch pages When a backend is connected to the experience, the **TypeTorch** tab shows the web explorer's pages, natively: Overview, Roblox, Demographics, Session time, Retention, Funnels, Players (and a player page), Flow, Experiments, Live events, Notifications, Feedback, First session, Events, Fleet (servers, with their offline history, debug bundles and, for owners, remote debug), Server history, Deploys, Errors (with drop rules), Performance, Economy, Monetization, Query and Settings. Owners also see the Audit log and Backend stats. The page list follows the web's sidebar. The filter bar (range, branch, artifact, device, new or returning, variant) is one state per backend. It stays the same as you move between pages. The header shows the server status dot, and every page has a command palette and a **Find player** search. Maps and recordings have their own pages. See [Recordings and maps](https://www.typetorch.dev/guides/recordings-and-maps.md) for what they show. ## Exports The export button makes a file on the phone and opens the share sheet, so you can send it to any app. | Format | What it exports | Notes | |---|---|---| | PDF | the whole page | made with the phone's print engine | | PNG | one block (a chart or a card) | 2x resolution | | CSV | one block's table | the same numbers as on screen | ## Settings - **Open Cloud key:** entered and checked here. - **Roblox user:** whose experiences the Projects list shows. - **Group filter:** which groups' experiences to list (owned, rank 200 and up, or all). - **Notifications:** per backend, the CCU milestone switch and the live watch. See [Notifications](https://www.typetorch.dev/guides/mobile-notifications.md). - **Widgets:** the widgets on the home screen, each with its game and its four stats. See [Widgets](https://www.typetorch.dev/guides/mobile-widgets.md). - **Appearance:** system, dark or light. ## Privacy The app keeps everything on the phone: the Open Cloud key and each backend token are in the phone's secure storage. The Open Cloud key is only sent to `apis.roblox.com`, and each backend token only to its own backend. The app has no analytics and no telemetry. ## Screenshots ![The Projects home: pinned experiences, then the rest of your projects](https://www.typetorch.dev/screenshots/mobile/projects.png) *A mockup with sample data (made in HTML from the app's screens), not a phone capture.* ![An experience's Analytics tab: the range, the granularity, the Engagement group and its metric cards](https://www.typetorch.dev/screenshots/mobile/analytics.png) *A mockup with sample data (made in HTML from the app's screens), not a phone capture.* ![The TypeTorch tab's Fleet page: live servers, players, versions and the servers table](https://www.typetorch.dev/screenshots/mobile/fleet.png) *A mockup with sample data (made in HTML from the app's screens), not a phone capture.* ## See also - [Widgets](https://www.typetorch.dev/guides/mobile-widgets.md): sizes, stats, the release garden, health and All games. - [Notifications](https://www.typetorch.dev/guides/mobile-notifications.md): milestone pushes, the live watch and battery settings on Xiaomi and HyperOS. - [For maintainers](https://www.typetorch.dev/guides/mobile-maintainers.md): how the app's screens and widgets ship over the air. --- # Mobile app widgets Home-screen widgets show your game's live numbers without opening the app. There are two styles: **Stats** (up to four numbers you pick) and **Releases** (a grid of your deploys, a release garden). A widget shows one game, or **All games** across every signed-in backend. > **Status: early.** The widgets read `GET /v1/mobile/live` on the backend (see > [Backend requirements](https://www.typetorch.dev/guides/mobile-app.md#backend-requirements)). The widget look and the data logic ship over the air, so > they can change without a new APK. ## Add a widget 1. Long-press the home screen, open **Widgets**, and choose **TypeTorch**. Pick a size. 2. Configure the widget: the game (or **All games**) and the style, **Stats** or **Releases**. 3. For Stats, pick the four numbers. The app's defaults are session length (last hour), DAU, D1 retention and revenue (last 72 hours). To change a widget later, open the app's **Settings**, then **Widgets**. Changes apply at once. ## Sizes The phone picks the layout from the size you give the widget. The release garden shows as many weeks as fit. | Size | Stats shown | Release garden | |---|---|---| | 4×2 | 4 | 14 weeks | | 4×1 | 4 | 12 weeks | | 2×2 | 4 | 11 weeks | | 2×1 | 3 (2 when very short) | 24 to 26 weeks | The garden has up to 182 days of history. Days before your backend's deploy history began show as no data, not as zero. ## Stats Each Stats widget shows up to four **slots**. A slot is a number and a small arrow comparing it with the period before. | Stat | What it shows | Window | |---|---|---| | CCU, servers, peak today | players online now, live servers, the highest CCU since 00:00 UTC | now | | DAU, WAU, MAU | unique players in the last 24 hours, 7 days, 30 days | fixed | | New players | players whose first-ever session is in the window | 1 to 72 hours, or 1 to 90 days | | D1 | retention so far today: yesterday's new players back today (grows through the day; the arrow compares with the last complete D1) | fixed | | D7 | retention of the latest complete cohort | fixed | | Session length | mean length of sessions that ended in the window | 1 to 72 hours, or 1 to 90 days | | Playtime | total time played in the window, including running sessions | 1 to 72 hours, or 1 to 90 days | | Sessions | sessions that ended in the window | 1 to 72 hours, or 1 to 90 days | | Revenue | Robux players paid in the window | 1 to 72 hours, or 1 to 90 days | | Payers | unique paying players in the window | 1 to 72 hours, or 1 to 90 days | - **Colours:** time units are orange, `%` is blue, `R$` is green. Values are white (dark on the day theme). - **Arrows:** ▲ and ▼ compare the number with the window before it. No arrow shows when that number is unknown. - **The 2×1** shows the first three slots in a short form. ## Release garden The garden draws one cell per UTC day, in columns of seven days. The newest day is in the bottom right and outlined. A release counts on the day it started. It is prod when its channel is `prod`; any other channel counts as dev. | Cell | Meaning | |---|---| | Green, darker for more | prod releases that day | | Blue, darker for more | dev releases that day | | Split green and blue | both on the same day (green top left, blue bottom right) | | Empty | no release | | No fill | no data (the backend has no history for that day) | Under the grid the widget shows the prod and dev counts for the period and **last prod**, for example "2 d ago". Each game's garden comes from its own deploy history. All games merges the days across games, so a day with a release in any game is coloured. ## All games An **All games** widget fetches every signed-in backend, up to eight at once, and draws the games together. - The widget lists up to six games as chips with their icons. - **Tap a chip** to filter the widget to that game. The other chips dim. - **Tap the picked chip again** to clear the filter. - The filter is saved for that widget. Tapping a chip redraws from what the widget already has, without a new fetch. Tap areas on individual parts of the widget need Android 12 or newer. On Android 11 and older, the whole widget opens the app and the refresh corner refreshes it. ## Health Health shows how the game is doing right now, next to the numbers. It appears on Stats widgets, on the All games 4×2 and on the release garden's today cell. It comes from the backend's health card, which is cached for a minute. | Part | Rule | Colour | |---|---|---| | Errors | the last 60 minutes against the 60 minutes before. ▲4× when errors are at least 1 and at least twice the earlier hour. ▲38% when they rose by more than 10%. ▼61% when they fell by more than 10%. Nothing within ±10%, or when there is no data. ▲ alone when the earlier hour had no errors | red when rising, green when falling | | Servers | a server is healthy when its Health badge on the Fleet page has no reasons: kernel ok, a heartbeat within 75 seconds, 50 or more TPS, memory 3,000 MB or less. A game with no servers counts as all healthy | amber when not all are healthy | | Alerts | fleet alerts from the last 24 hours that nobody has acknowledged. The All games list shows the newest three across games | amber when any is open | | Today's cell (garden) | red when errors are high (at least twice the earlier hour), or when a critical alert from the last hour is among the listed alerts. Amber when any alert is open. Otherwise no ring | red or amber ring | On the smallest sizes the errors part shows only the arrow. Health needs the widget program (see [For maintainers](https://www.typetorch.dev/guides/mobile-maintainers.md)). Phones without the widget engine, or with an older backend that sends no health, hide these parts. The numbers still show. ## When a widget updates - Every 30 minutes, on the phone's schedule. - When you tap the widget's refresh corner. - When you open the app. - On every live watch poll of the same game (see [Notifications](https://www.typetorch.dev/guides/mobile-notifications.md#live-watch)). A widget that cannot reach its backend keeps its last numbers and shows how old they are. A backend that rejects the token shows "Open TypeTorch to sign in". ## Limits - The widget program has 2 seconds and 16 MB per run. A run that fails shows the widget's unreachable state with the first line of the error, and keeps the last good drawing. - The program makes at most eight requests per widget and only to signed-in backends. The phone adds the token. The program never sees a token. - Phones without the widget engine keep the older native path. It draws the same widgets without health. ## Mockups These are HTML mockups with sample data, made to check the layouts. They are not phone screenshots. | Mockup | Shows | |---|---| | [CCU widgets with health](https://www.typetorch.dev/mobile/mockups/ccu-health.html) | the Stats widgets with health | | [All games 4×2, variant C](https://www.typetorch.dev/mobile/mockups/combo.html) | the All games release garden with health and the latest alerts | | [Release garden 4×1](https://www.typetorch.dev/mobile/mockups/garden-final.html) | the one-game release garden in a wide strip | | [Health 4×1](https://www.typetorch.dev/mobile/mockups/health4x1-final.html) | the 4×1 Stats widget with health | ![A home screen with a 4×2 Stats widget and a 4×2 All games widget](https://www.typetorch.dev/screenshots/mobile/widgets-home.png) *A mockup with sample data (the widgets drawn by the app's widget preview), not a phone capture.* ![Settings, Widgets: each widget's game, style and four stats](https://www.typetorch.dev/screenshots/mobile/widgets-settings.png) *A mockup with sample data (made in HTML from the app's screens), not a phone capture.* ## See also - [The mobile app](https://www.typetorch.dev/guides/mobile-app.md): install, sign-in and the Open Cloud key. - [Notifications](https://www.typetorch.dev/guides/mobile-notifications.md): the live watch and battery settings that keep widgets updating. - [For maintainers](https://www.typetorch.dev/guides/mobile-maintainers.md): how the widget look and logic are edited and shipped over the air. --- # Mobile app notifications The app has two kinds of phone notification for a game, and widgets keep the numbers on the home screen: | Feature | What it does | Needs | |---|---|---| | CCU milestone push | a push, such as "Reached 160 CCU", when the live player count first reaches a milestone | the backend's `ccuMilestone` rule, and a phone build with Firebase | | Live watch | one ongoing notification per game, with live numbers updated every 30 seconds | a signed-in backend | | Widgets | the same live numbers on the home screen ([Widgets](https://www.typetorch.dev/guides/mobile-widgets.md)) | a signed-in backend | > **Status: early.** The backend side is on the backend's main branch. The app side is built. Milestone pushes also need > Firebase in the phone's build. These are not the same as Roblox experience notifications, which go to your players. See [Notifications](https://www.typetorch.dev/guides/notifications.md) for those. ## CCU milestone pushes A milestone fires when the game's live player count (CCU) first reaches it. The milestones start at 10 and double each time: 10, 20, 40, 80, and so on. - **Re-arm:** a milestone fires again only after the CCU has dropped below 70% of it. - **Cooldown:** at most one alert per milestone every 30 minutes. - **One step at a time:** a jump past several milestones fires only the highest. The first reading after the backend starts only learns the level, so a restart never announces one. - **Where it goes:** the backend's alert webhook (for example Discord), and a push to each phone that turned milestones on. - **The rule:** the backend's **Settings** page, **Backend alerts** section, rule `ccuMilestone` (level info). Its start (10), re-arm (70%) and cooldown (30 minutes) can be changed there. The backend's rule must be on for any milestone to fire. Environment: `TYPETORCH_ALERT_CCU_MILESTONE`. To turn pushes on in the app: 1. Open **Settings**, then **Notifications**. 2. Turn on **CCU milestones** for the game. The app asks for notification permission. 3. Tap **Send a test push** next to the game to check that it arrives. A tapped milestone opens that backend's Fleet page in the app. If the phone's build has no Firebase setup, the switch stays off and the app says why. The live watch and the widgets still work. A push stops when the phone's registration is removed: you sign out, you revoke the session (or **Revoke all**), the token expires, or the push service reports that the device is no longer registered. ## Live watch The live watch shows a game's numbers in an ongoing notification until you stop it. - **Start:** the eye button in the header of a TypeTorch page starts the watch for that backend. Stop it from the same button or from the notification's **Stop** action. - **One notification per game.** It is silent and low importance, so it does not buzz. - **Collapsed:** for example "214 playing ▲12 · The Prison", with the average session and the server count. - **Expanded:** the big CCU and its change, a 30-minute CCU line, the average and median session length for the last hour, sessions that ended, servers and today's peak, and the time played in the last hour. **Open** opens the backend. - **Updates:** every 30 seconds. A network error keeps the last numbers and shows "offline, retrying". - **Signed out:** the notification shows "Signed out: open TypeTorch" and polling stops for that game. Open the app and sign in again. - **Swiped away:** on Android 14 and newer the notification comes back. Only **Stop** ends a watch. - **Reboot:** the watch is not restarted after a reboot. Open the app and start it again. ## Keeping it running on Xiaomi and HyperOS Phones with Xiaomi's HyperOS can stop background work, which stops the live watch and freezes the widgets. Check these once, after you install the app: 1. Settings, Apps, TypeTorch. 2. **Autostart:** on. 3. **Battery saver:** **No restrictions**. 4. **Notifications:** allowed. For the milestones channel, also allow **Lock screen** and **Floating** if you want heads-up alerts. ## For maintainers: Firebase The milestone push needs Firebase Cloud Messaging in the build, and it is set up once for the app, not per game. The app identity file (`google-services.json`) goes into the APK. The FCM service account key goes to Expo, and only to Expo. Never share either key in chat or in a repository. The steps are in the mobile repo's `docs/FIREBASE_SETUP.md`. The live watch and widgets do not need Firebase. --- # For maintainers: widgets over the air This page is for whoever maintains the TypeTorch app. It explains how the widgets' look and logic change without a new APK, and where the code is. Game developers do not need it. The app's widgets have three parts. Each has its own path to the phone: | Part | What it is | How it ships | |---|---|---| | Widget HTML (the spec) | the layout of each size, written as HTML and bindings | over the air, with the app's JavaScript (`setWidgetSpec`) | | Widget program | the logic that picks what to fetch, merges games, sets colours and handles taps | over the air, as JavaScript (`setWidgetProgram`) | | Native module | the widget provider, the live watch, the sandbox that runs the program, the drawing | a new APK. Changing it is a native build | The program runs on Android's JavaScript engine (`androidx.javascriptengine`). That engine is native code, so changing how it is used needs a new APK. ## Where the code is The TypeTorch mobile repo is not part of these docs. Its own docs, in `docs/`, are the reference: | File | What it covers | |---|---| | `docs/WIDGET_SPEC.md` | the spec format: elements, bindings, tokens, tap areas | | `docs/WIDGET_HTML.md` | how the widget HTML is written and the size classes | | `docs/WIDGET_PROGRAM.md` | the program's `plan`, `shape` and `tap` functions, the limits, the build and check steps | | `docs/WIDGET_STATS.md` | the metric ids and the windows | | `docs/WIDGET_RELEASES.md` | the release garden's cells and tokens | | `docs/PUSH_WATCH_WIDGETS.md` | the backend routes, the live watch and the push payload | | `docs/FIREBASE_SETUP.md` | the one-time Firebase setup for milestone pushes | | `docs/widgets-preview.html` | a generated preview of the widget HTML with sample data (see step 4) | In the code: | Path | What it is | |---|---| | `src/features/live/widgets/default-widget.ts` | the widget HTML (`DEFAULT_WIDGET_HTML`) | | `src/features/live/widgets/program/` | the program: `index.ts` (plan, shape, tap), `all-games.ts`, `releases.ts`, `health.ts`, `answers.ts` | | `src/features/live/widgets/program.generated.ts` | the built program (committed; generated, don't edit) | | `scripts/widgets/build-program.ts` | builds the program into `program.generated.ts` | | `scripts/widgets/check-program.ts` | runs the program against made-up answers and checks the results | | `scripts/widgets/check.ts` | checks the widget HTML against the reference spec | | `scripts/widgets/preview.ts` | builds `docs/widgets-preview.html` | ## Rules for the program The program runs in an isolated JavaScript engine with no app around it. - Plain JavaScript, ES2020. No imports at run time (the bundle inlines the files), no `fetch`, no timers, no `console`, no app globals. - No I/O. It gets JSON in and returns JSON out. The phone does the requests. - At most 2 seconds and 16 MB per call. Output is at most 256 KB. Widget state is at most 4 KB. - Requests are GET only, to signed-in backends, with a path that starts with `/v1/`. At most eight per widget. The program never sees a backend token. - Each behaviour you change gets a case in `check-program.ts`. Hermes compiles the app's functions to bytecode, so the program must be a string made at build time. Don't try to read a function's source at run time. ## Change a widget 1. Edit the HTML in `default-widget.ts`, or the logic in `src/features/live/widgets/program/`. 2. Rebuild the program. The output file is committed. ```sh timeout 60 bun scripts/widgets/build-program.ts timeout 60 bun scripts/widgets/build-program.ts --check # only reports whether the output is current ``` 3. Check it. ```sh timeout 60 bun scripts/widgets/check.ts timeout 60 bun scripts/widgets/check-program.ts timeout 400 npx tsc --noEmit -p . ``` 4. Preview it in a browser. The preview draws the widget HTML at the launcher's sizes, by day and by night, with sample data. It has an editor: changes redraw at once and are kept in the browser's storage. Copy the changes back into `default-widget.ts`. ```sh timeout 60 bun scripts/widgets/preview.ts ``` Then open `docs/widgets-preview.html`. 5. Ship it over the air. The `preview` channel is the testers' APK, and `production` is the store build (not published yet). ```sh bunx eas-cli update --channel preview --message "Widgets: " ``` An update reaches only builds on the same channel with the same native fingerprint. The app's `runtimeVersion` policy is `fingerprint`, so a native change needs a new APK before any update reaches it. 6. On the phone, open the app. It checks for the update on start and applies it on the next start. The widgets redraw from the new spec on the app's next foreground or refresh. Use `bunx eas-cli` in this Bun project. The app's `AGENTS.md` has the same rule. ## What not to change over the air - Anything in `modules/typetorch-live`: the widget provider, the live watch, the sandbox and the drawing. - Adding a new permission, a new native library or a new Expo native module. Those need a new APK. ## Related - [Widgets](https://www.typetorch.dev/guides/mobile-widgets.md): what a game developer sees, sizes, stats, health and All games. - [Notifications](https://www.typetorch.dev/guides/mobile-notifications.md): the live watch and the Firebase setup. --- # Testing in Studio Run your **local** code in Studio with the real kernel, the dev menu and DataStores, without uploading anything. `typetorch serve` runs the whole Studio loop in one process, and the **TypeTorch Studio plugin** attaches to it by itself: no Connect button, and a save reaches a running playtest without Stop + Play. - Needs kernel 0.3.1+ in `node_modules/@typetorch/kernel` for the local payload, and **kernel 0.5.4+** for live reload in a playtest. CLI 0.11+ for `typetorch serve` (0.12+ for the `--remote` tunnel and pairing link, 0.12.2+ for the `live` script default and Rojo's restarts below, 0.15+ for the hot asset Diff). The template's `@typetorch/cli` range (`^0.9.1`) stays on 0.9.x: `bun add -d @typetorch/cli@latest` gets the current release. Studio plugin 0.7.1 is the latest release. - Deploy messages never reach Studio playtests, so Studio doesn't follow your deploys. The kernel mounts your compiled code straight from `ServerStorage.TypeTorchDev.Payload`, which Rojo syncs. ## Set up (once) - **`studio.project.json`** from the template, next to `default.project.json`. It syncs the kernel from `node_modules/@typetorch/kernel`, your compiled payload (`out/`, `include/` and the packages) into `ServerStorage.TypeTorchDev.Payload`, and the kernel place's baseplate and spawn. - **The TypeTorch Studio plugin.** Download `TypeTorchSync.rbxm` from the [latest release](https://github.com/typetorch/studio-plugin/releases/latest) into Studio's plugins folder (Windows: `%LOCALAPPDATA%\Roblox\Plugins`), then restart Studio or reload plugins. From a checkout of [typetorch/studio-plugin](https://github.com/typetorch/studio-plugin): `bun run typetorch studio install-plugin --from ../studio-plugin` builds it into the same folder with Rojo. The plugin is not on npm. There is also a [Creator Store copy](https://create.roblox.com/store/asset/135066807179101/TypeTorch), but it is updated by hand and can lag behind the GitHub release. It carries Rojo's own sync (7.7.0-rc.1, the version `rokit.toml` pins), so you don't need the stock Rojo plugin; if you keep it, connect only one of the two at a time. - **Game Settings > Security > Enable Studio Access to API Services**, so DataStores work in a playtest. - The first time the plugin probes `typetorch serve`, Studio asks to allow its HTTP requests to localhost: allow it. ## Run it In the game folder: ```sh bun run typetorch serve ``` It starts, and restarts when they exit (after 0.5 s, doubling up to 10 s while a child keeps crashing): - **watch**: the game's `watch` script (else `rbxtsc -w`). Compile errors are kept for `serve status` and the plugin's panel. `--no-watch` leaves compiling to your editor. - **rojo**: `rojo serve studio.project.json` (else `default.project.json`; `--project `) on Rojo's port 34872 or the next free one (`--port`). If another process holds the port when Rojo (re)starts, Rojo moves to the next free one and the plugin follows. Rojo can't follow a `$path` folder (`out/server`, ...) that is deleted and recreated, as a deploy's clean build does, so serve restarts Rojo when that happens; `serve status` shows it. - **live**: the game's `live` script from `package.json`, when it has one. On by default; `--no-live` turns it off. - **extra scripts**: `--with ` runs those `package.json` scripts with `bun run`. - **the control API** on `127.0.0.1`, the first free port of 34880-34887 (loopback only, no browser can call it). `.typetorch/serve.json` (git-ignored) records the port, and the children's process ids, while it runs. A serve that was killed (kill -9, a closed SSH session) leaves its children running, and that Rojo keeps its port. The next `serve` (or `serve status`) stops them on Linux; on Windows and macOS it names them so you can stop them. Open a place of your experience in Studio. The plugin finds the serve whose `typetorch.json` `universeId` matches the place and syncs; another experience's place or an unpublished file syncs only after **Connect anyway** in its panel. Press **Play**. **Check:** the plugin's panel (the TypeTorch toolbar button) says "Synced", Server > Status in the dev menu shows "Studio: local payload", and `/tt status` says "local payload". The artifact id is `local-` on branch `dev` (or the `Branch` attribute of `ServerStorage.TypeTorchDev`), dev channel. Ctrl+C, or `bun run typetorch serve stop` from another terminal, stops everything. Other subcommands: `serve status` (children, attached Studios, sync state, compile errors), `serve restart ` and `serve logs [--studio] [--since ] [--limit ] [--follow]` (`--studio`: Studio's Output, as the plugin forwards it). The two-terminal loop still works: `bun run watch` and `bun run studio` (`rojo serve studio.project.json`) with the stock Rojo plugin, but nothing reloads a running playtest then. ## How it behaves - **A save reaches the running playtest.** In a playtest the plugin also runs in the server and syncs into the running game; it sets `LiveReload` on `ServerStorage.TypeTorchDev`, and the kernel (0.5.4+) reloads a fresh copy of the local payload about 0.4 s after the last change, server and client code, as Reload does. Turn it off in the panel's Playtest card ("Live playtest: on"). With an older kernel, code changes need Stop + Play. - **Reload tests swaps.** The dev menu's Reload (or `/tt reload`) remounts a fresh copy of the same code, so you can test `persist`, `onSwapOut`, update toasts and everything else a deploy does, while you play. - Deploys and the 60 s poll don't move a local session. A pin or a branch switch in the dev menu still loads an uploaded build; Reload comes back to the local copy. - To boot the branch head instead, delete `ServerStorage.TypeTorchDev.Payload` (with the sync disconnected). - In Studio everyone is a dev with the owner role, so kick and ban can't be tried there. - A dropped connection or a restarted `serve` reconnects with a full resync. Until then the panel says **Disconnected** (red) with how long ago, and keeps retrying. "Auto-connect: on" in the panel turns it off per place. - In a playtest the toolbar and the panel stay (on the client in Play, the server in Run), with only the status, playtest and compile cards: pairing and hot assets act on the edit session. ## Hot assets from the panel The plugin's **Hot assets** card does [hot assets](https://www.typetorch.dev/guides/hot-assets.md) without publishing the place first: select models or UI, **Add** marks them (`TypeTorchAsset`, a key from the name or the name box; with one hot asset selected, a new name turns Add into **Rename**), **Remove** unmarks them. Each marked instance shows as new, changed, up to date, or what a sync would refuse. - **Check** runs `typetorch assets status` on the plugin's export of the open place (locally, no key needed). - **Upload** runs `typetorch assets sync` on it. - **Publish to dev** runs `assets sync --deploy dev` (`serve --dev-branch ` picks another dev branch, and the button is named after it; a prod-channel branch is refused). The deploy follows your `approval` policy like any other: with `"approval": "all"` it becomes a proposal for `typetorch approve`. - **Diff** (CLI 0.15.0+), on each new, changed or removed row after a check: the instances added, removed or changed inside that asset, with old and new property values (at most 30 instances and 8 properties each). The old side is the copy of the lockfile's version that `assets status` and `sync` keep in the state dir (`.typetorch/hot-assets/.rbxm`); for a lockfile synced on another machine the diff only summarizes the new export, until a sync here. With an older CLI the button stays hidden. A button shows only when it has work. While the panel is open in edit mode and a serve is attached, the check also runs by itself every 30 seconds (never while a job runs, never with nothing marked), and once after every (re)connect. It sends a job to serve only when the place or the lockfile changed since the last check. They run inside `serve` with its keys from the game repo's `.env` (progress in `serve logs`). Because the export comes from the open place, the lockfile records place version 0 for changed entries; the next sync from a published place records a real version again. ## Agents and Studio `typetorch serve --detach` starts serve in the background (log: `.typetorch/serve.log`) and returns once it answers; every subcommand takes `--json`. An agent can then drive the Studio the plugin attached: ```sh bun run typetorch studio status # attached Studios (edit, playtest server and client), sync state bun run typetorch studio reconnect # resync from scratch, wait for the result (--anyway: another experience) bun run typetorch studio play # start a playtest (--run: Run mode, no player) bun run typetorch studio logs --follow # Studio's Output, edit and playtest bun run typetorch studio stop # end the playtest ``` `--target ` picks the Studio (default: the edit DataModel; `stop`: the playtest server), and `--timeout ` how long to wait for its answer (default 20). The plugin keeps listening for these while its sync is down, so an agent can always get Studio back. When no Studio is attached at all, run this in Studio's command bar (or the Roblox Studio MCP's `execute_luau`) and the plugin reconnects: ```lua game:GetService("ServerStorage"):SetAttribute("TypeTorchReconnect", os.time()) ``` `typetorch mcp` serves the same over stdio as MCP tools (`serve_status`, `serve_start`, `serve_stop`, `serve_logs`, `studio_logs`, `studio_reconnect`, `studio_play`, `studio_stop`). Claude Code, from the game repo: `claude mcp add typetorch -- bunx typetorch mcp`. ## A Studio on another machine `bun run typetorch serve --remote` lets someone else's Studio sync from your machine: 1. serve opens a gateway on `127.0.0.1:34890` (`--remote-port`) and a free Cloudflare quick tunnel to it (no account; `cloudflared` is installed when it's missing). 2. Once the tunnel answers, serve prints a **one-time pairing link** (valid 15 minutes): the tunnel URL with the code after a `#`. `serve status` shows it again; `typetorch serve pair` makes a new one. 3. The other person pastes the link into the plugin's **Server** card and presses **Pair**. Their Studio stays paired for 30 days (`serve devices` lists devices, `serve unpair --name ` or `--all` revokes them). **Use this computer's serve** goes back. - A quick tunnel's address changes when cloudflared restarts; serve then prints a new link. For a fixed address, run your own named tunnel to `http://localhost:34890` and pass `--url https://`; `--no-tunnel` opens none and leaves `typetorch serve pair --url ` to you (the URL is remembered). - A remote Studio syncs code read-only, reports its state and Output, and runs the Hot assets buttons (uploads with your keys, deploys only to the dev branch). It can't stop or restart serve, read serve's log or drive other Studios, and `typetorch studio ...` and the MCP tools never pick a remote Studio unless `--target` names it. - Every request but pairing needs that device's token (kept hashed in `.typetorch/serve-remote.json`). Five wrong codes lock pairing until you make a new code. ## Claude in Studio `bun run typetorch serve --claude` also runs [remote-claude](https://www.typetorch.dev/guides/remote-claude.md#from-studio) on this machine (no tunnel), and the plugin's **Claude** button opens a chat with Claude Code, like the in-game DEV > Claude tab. Code mode only: Claude edits a copy of your branch, and you **Apply** the change into this checkout (Rojo syncs it to Studio), **Deploy** it to the dev branch, or **Discard** it. With CLI 0.12.2+ this needs `@typetorch/dev-server` 0.4.0, which is not on npm yet (see [From Studio](https://www.typetorch.dev/guides/remote-claude.md#from-studio)). ## Don't publish that session Live servers ignore `ServerStorage.TypeTorchDev`, but it bloats the place, and `typetorch doctor` warns when the published place still holds it. Publish the place only through the kernel deploy (or your own clean Studio session). ## Without a local payload A Studio playtest with no `ServerStorage.TypeTorchDev.Payload` boots an uploaded build: the head of `ServerStorage.TypeTorchDev`'s `Branch` attribute, or of `defaultBranch`. It reads the stored heads from DataStores, so it also needs Studio API access. (Kernel 0.3.8 dropped the `BootAssetId` and `Registry` attributes, stand-ins for the old ConfigService registry.) --- # remote-claude Chat with **Claude Code running on your own PC** from the dev menu's **Claude** tab, inside a live dev-branch server. Claude can act on your running server ("jump me", "give me 100 coins") or change the code and propose a deploy. - Dev-channel servers only; prod branches are refused with no override. - Only the Roblox users you list can prompt, and only on servers on the session's branch. - **It runs on your Claude subscription only.** API keys, Bedrock, Vertex and Foundry logins are refused. ## Requirements - [Claude Code](https://claude.com/claude-code) installed and logged in with your Claude.ai account (`claude auth login`). - `cloudflared` (installed with winget on Windows when missing; macOS: `brew install cloudflared`). The tunnel is an account-free Cloudflare Quick Tunnel. - The [dev-server](https://github.com/typetorch/dev-server): Node 20+ or Bun 1.3+. The template has `@typetorch/dev-server` in its dev dependencies, so `bun install` gets it. Its range may hold you on an older minor version (`^0.2.3` stays on 0.2.x): `bun add -d @typetorch/dev-server@latest` gets the current release. Without it: npx (see below), or a checkout next to your game (`bun install` in it). - An Open Cloud key with `universe-messaging-service:publish`: `OPENCLOUD_DEPLOY_KEY`, else the shared `OPENCLOUD_API_KEY` (or `ROBLOX_API_KEY`, its alias). The dev-server tells game servers where the session is with it. It finds the key the same way the CLI does: the real environment, then the game repo's `.env` (next to `typetorch.json`; no parent folder's; `--env-file ` or `TYPETORCH_ENV_FILE` read another file instead). Keep the key in that `.env`, which is gitignored. The backend's keys (`TYPETORCH_API_KEY`, `TYPETORCH_ADMIN_TOKEN`) are never read here. When you play on another PC, screenshots arrive as CaptureService uploads, which `OPENCLOUD_ASSETS_KEY` (else the shared key) downloads. - Experience settings: **Allow HTTP Requests** on. `ServerScriptService.LoadStringEnabled` on for `run_luau`, only in a place where you want it (a test place: `kernel deploy --loadstring`, CLI 0.7.5+); keep it off in a live game. `kernel deploy` patches leave it as it is; `doctor` reports it. Optional: **Allow Mesh / Image APIs** (and an ID-verified 13+ owner) for images Claude shows in the chat; **Allow Loading Third Party Assets** for Toolbox inserts. Nothing else to set up in Roblox: no secrets. ## Start a session On a dev-channel git branch of your game: ```sh git switch dev bun run typetorch remote-claude --users 111111111 ``` `typetorch dev` is the same command, shorter (`bun run typetorch dev --users 111111111`, or `tt dev` with the CLI installed globally). - `--users`: the Roblox user ids allowed to prompt (no wildcard). It is remembered in `.typetorch/remote-claude.json` (git-ignored); omitted, the last list passed in this repo is used, else the owners in `typetorch.json` (`members` with the role `"owner"`; dev-server 0.3.3+). `typetorch remote-claude` runs the dev-server with the same arguments. It finds it in `TYPETORCH_DEV_SERVER`, the game's `node_modules` (where the template's `bun install` puts it), next to the CLI, or a sibling `../dev-server` checkout. Other ways to start it: ```sh npx @typetorch/dev-server remote-claude --users 111111111 # from npm npx -p @typetorch/cli -p @typetorch/dev-server typetorch remote-claude --users 111111111 bun ../dev-server/src/index.ts remote-claude --users 111111111 # a checkout ``` It prints a pairing code (and copies it to your clipboard): ```text pairing code: ABCD-EFGH-JKLM-NPQR-STUV-7QX2 (valid until 18:02, paste it into DEV > Claude in game) ``` In game: open a server on that branch (`/tt new dev`), open **DEV > Claude**, paste the code. That server is paired for up to 3 hours. Each code pairs one user on one server once; the next code prints right away. Useful flags: `--branch `, `--max-prompts ` (default 50), `--no-deploy`, `--protect ` (files Claude may not edit), `--code-ttl ` (default 180), `--model `, `--max-budget-usd ` (a cap per run on Claude Code's own cost estimate), `--cli ` (the TypeTorch CLI used for deploys), `--env-file `, `--repo `, `--port `, `--no-install` (no `bun install` in a fresh worktree), `--no-clipboard`, `--no-announce` (local testing), `--no-tunnel` (no Cloudflare tunnel, for a local client only; what `serve --claude` uses), and, in dev-server 0.4.0 (not on npm yet), `--deploy-branch ` (where Deploy goes: a dev-channel branch; default the session's branch). Terminal commands while it runs: `code`, `users`, `revoke `, `rotate`, `status`, `cancel `, `quit`. It also runs in Docker (locally or as a Coolify app): the dev-server repo's `Dockerfile` and `compose.yaml`, with the users in `TT_USERS` and `claude auth login` inside the container. See the [dev-server README](https://github.com/typetorch/dev-server#docker). **Check:** the Claude tab shows the session instead of "Not connected: start the dev server on this branch". ## Live and Code modes Pick the mode with the **Live / Code** pill next to "+". A conversation can switch modes; follow-ups continue the same Claude session. | | Live (default) | Code | |---|---|---| | What Claude does | acts on **your running server** | edits the branch in its own git worktree (`../-remote-claude`) | | Files | read only | edit, then `bun run build` | | Game tools | all: `run_luau` (you approve each snippet), `game_logs`, `inspect`, `find`, `game_status`, `screenshot` | read-only ones (no `run_luau`) | | Result | an answer, or a change on your server | a commit and a **deploy proposal** | - `run_luau` runs only on the server you prompted from, for you; you approve every snippet in the chat (once, always in this chat, or deny). Each run leaves an audit record. Prod servers never run it. - A code run that changed files is committed and shown as a card: files, lines added and removed, a summary. **Deploy** runs `typetorch deploy` and your server hot-swaps to it; **Discard** undoes the commit. Only you decide; after 15 minutes it is discarded. - If your `approval` policy needs a person for that branch (`"approval": "all"`), the deploy card says "Waiting for your approval on your PC": run `bun run typetorch approve ` in the game folder (the dev-server's terminal prints the id). With `"approval": "prod"` dev deploys go straight through. - The dev-server never deploys to a prod-channel branch. Commits stay on its worktree branch; bring them home with `git merge remote-claude/`. Nothing is pushed. ## Attach context The "+" menu: - **Dex path:** the instance selected in the Dex. - **My logs**, **Server logs**, **Player logs...**: log history (about 64 KB each), passed as untrusted data and never logged. - **Screenshot:** a capture of your screen, which you can **crop** and **draw** on before sending (pen in red, yellow, white or black, three sizes, Undo / Clear, `Ctrl+Z` / `Ctrl+Y`). When you play on the PC that runs the dev-server, it picks the capture file up directly. - **Toolbox:** see below. Tap any image in the chat to open it in **big picture** mode (zoom with the wheel or a pinch, drag to pan). ## Toolbox (Creator Store) Only when you ask for it. Pick **Toolbox** in the "+" menu: that one message lets Claude search the Creator Store (free assets, from your PC). The chip clears after you send; without it Claude has no Creator Store tools at all. - In **Live** mode Claude can insert an asset you picked into your server. Every insert shows an approval card (what loaded, what will be removed, Anchor, Keep scripts off by default) with Insert / Deny, and inserted assets get a Remove button. Scripts are stripped. Needs "Allow Loading Third Party Assets" (Studio > File > Experience Settings > Security; it applies to every server of the experience, prod included). - In **Code** mode it records the asset in `toolbox.lock.toml` instead. ## From Studio The TypeTorch Studio plugin has a **Claude** button that opens the same chat in Studio. It needs [`typetorch serve`](https://www.typetorch.dev/guides/studio-testing.md) with `--claude` on the machine with the game checkout: ```sh bun run typetorch serve --claude ``` **Versions.** serve from CLI 0.12.2+ starts remote-claude with `--deploy-branch`, which only `@typetorch/dev-server` 0.4.0 knows. 0.4.0 is not on npm yet (npm has 0.3.3, which exits with `unexpected argument`): until it is, set `TYPETORCH_DEV_SERVER` in the environment to a checkout's entry, for example `TYPETORCH_DEV_SERVER=../dev-server/src/index.ts` (run with Bun; the path is relative to the game folder) for a [typetorch/dev-server](https://github.com/typetorch/dev-server) checkout next to the game, with `bun install` run in it. Apply, Deploy to dev and the per-dev worktrees below are dev-server 0.4.0. - serve runs remote-claude on this machine without a tunnel (`remote-claude --no-tunnel --no-announce --no-clipboard --deploy-branch `) and pairs with it on the Studio user's behalf: nobody pastes a code. A remote-claude you start yourself in the repo works too (serve finds it through `.typetorch/remote-claude.session.json`). serve doesn't restart it when it exits: read `serve logs`, then `serve restart claude`. - `--claude-users `: the Roblox user ids allowed (remembered). Without it, the owners in `typetorch.json`. Studio prompts as the Roblox user it runs as. - **Code mode only.** Live mode works only from the in-game tab: Studio's Live pill says so. Claude edits a copy of the branch, then the tab shows a card with the summary and the changed files: - **Apply** puts the change into the checkout serve's Rojo syncs to Studio, uncommitted, so you review and commit it there. A change to lines that changed there too is refused, and the checkout stays as it was. - **Deploy to dev** runs `typetorch deploy` of that commit to serve's dev branch (`dev`, or `serve --dev-branch`). With `"approval": "all"` it waits for `typetorch approve` on your PC. - **Discard** drops the commit. With no answer in 15 minutes the change is discarded; only the dev who sent the prompt decides. - **Each dev gets their own worktree**, `../-remote-claude-` on `remote-claude/-`, so several devs use Claude at once: each dev's prompts run one at a time, but never wait for another dev's. Apply changes the checkout one change at a time. Each worktree is brought up to the branch before every run, so a change another dev applied reaches your runs once it is committed. - **A prod-channel checkout works too** (a local session only): Claude never commits to that branch itself, and Deploy goes to serve's dev branch. - **Claude reading the open place is planned.** dev-server 0.4.0 offers Studio prompts the game tools, and the plugin (0.7.1+) answers `inspect`, `find`, `game_logs` and `game_status` on the place open in Edit, read-only. It never runs code it receives: `run_luau` is answered "not available in Studio". serve on CLI main doesn't relay these requests to the plugin yet, so today those tool calls time out and Claude works from the files. - The "+" menu has Dex path (the Studio selection), My logs, Server logs and Screenshot (in Play only) and Toolbox. Recent chats are listed, and the chat follows you between Edit and Play. - Replies stream to the tab over a WebSocket (`/tt/claude/stream`), so they show as Claude writes them. - **A helper on another machine** pairs their Studio with `serve --remote` ([A Studio on another machine](https://www.typetorch.dev/guides/studio-testing.md#a-studio-on-another-machine)); add their user id to `--claude-users`. Pair again after updating the plugin, so serve knows their Roblox user. ## Security in short - The tunnel URL is public, so the dev-server authenticates everything: single-use pairing codes bound to the tunnel, 5-minute access tokens bound to one user and one game server, rotating refresh tokens, replay protection, and a loopback-only HTTP server. - Game servers keep the session URL and tokens in memory; no client ever receives them. - Claude runs with a tool allowlist in a separate worktree; it can't push, can't use the web, and never sees your Open Cloud key or `.env` values. Build and tool configuration files are protected. - Game data (names, logs, instance paths) reaches Claude labelled as untrusted data, never as instructions. Full details: the [dev-server README](https://github.com/typetorch/dev-server). --- # TypeTorch agent playbook For AI coding agents (Claude Code, Codex, Cursor, Copilot, Aider and others). Follow it when the user says "migrate this project to typetorch", "set up typetorch", "convert to typetorch", "add typetorch" or similar. **You** do every local step: read the project, plan, change code, build, check the payload. **The user** does every step that touches Roblox or secrets: API keys, signing keys, Creator Hub settings, publishing the place, deploying, approving. You finish with a numbered "What you need to do" list that tells them exactly how. - Human guides: [fresh setup](https://www.typetorch.dev/getting-started/fresh-setup.md), [migrate](https://www.typetorch.dev/getting-started/migrate.md) (before/after code for every pattern), [player data](https://www.typetorch.dev/guides/player-data.md), [hot assets](https://www.typetorch.dev/guides/hot-assets.md). - **Today** means it exists in the code now. **Planned** means it doesn't exist yet: never tell the user to use it. > **Validated on 2026-10-05** with framework `7510856` (0.2.0, no Flamework), transformer `8ab4dbc` (0.2.0), kernel > `422f95f` (0.3.1), cli `88f1766` (0.6.0) and template `6b628be`: a throwaway roblox-ts project with two Flamework > services, a controller, a raw RemoteEvent, a `Players.PlayerAdded` handler, `_G` state and a `task.spawn` loop was > migrated with this procedure (first on the Flamework-based toolchain, then moved to `@typetorch/transformer`) to a > clean `typetorch build` (dev and prod channel; only Folders and ModuleScripts; guards and DI ids generated, no > Flamework left in the output), and its `studio.project.json` built. The code samples in the guides it links (player > data, characters, hot-asset tools, UI) compiled in that project. Nothing that needs keys was run. > > **npm setup checked on 2026-10-05** with template `756e78c` (every `@typetorch/*` package from npm: framework 0.2.0, > kernel 0.3.1, transformer 0.2.0, cli 0.6.0, dev-server 0.2.0): a fresh clone built with `bun install`, > `bun run build` and `bun run typetorch build`, and so did a copy without `scripts/packages.ts` and its two scripts. > > **Updated on 2026-11-15 from the code, not re-run:** the toolchain steps now use `@typetorch/transformer` 0.3+ as > the only compiler plugin (its own debug macros, no `rbxts-transform-debug`), darklua for the production pack, and > the newest npm versions instead of the template's pins. ## Rules (read first, apply always) 1. **Never create, ask for, read, print or store a secret:** Open Cloud API keys, signing key files (`~/.config/typetorch/keys/*`), pairing codes, cookies, tokens. Don't open `.env` files or the file named by `TYPETORCH_ENV_FILE`. Don't put a key in chat, a file, a commit or a command line. If the user pastes a key into chat, tell them to revoke it in Creator Hub and make a new one. 2. **Never act on Roblox.** Don't publish or save a place, upload anything, or run: `typetorch upload`, `deploy` (also not `--dry-run`: it reads the game's DataStore with the user's key), `promote`, `rollback`, `approve`, `reject`, `pin`, `deployments`, `branch ls`, `settings ...`, `access push`, `kernel deploy` (also not `--dry-run`; the one exception is a kernel update the user asked for, see "Updating the kernel in a game"), `kernel restore`, `keys ...`, `assets sync|status`, `test --cloud`, `servers`, `report`, `alerts`, `backend setup`, `update`, `doctor` (it probes the key and publishes a test message). Don't start `remote-claude` (`typetorch dev`), the analytics server or a tunnel. These go in the final list. 3. **Never push.** Local commits on a new branch are fine. Don't rewrite history, don't force anything. 4. **Don't edit TypeTorch itself:** `node_modules/@typetorch/*`, the reference `../template`, or any other TypeTorch checkout. Copy from them. 5. **Don't weaken security to make something work:** no new RemoteEvents, `loadstring`, `_G` hooks, disabled guards, or settings changes. 6. **Don't change player data formats, DataStore names or keys.** Follow [Player data](https://www.typetorch.dev/guides/player-data.md) and flag everything for the user to test. 7. **Keep ids honest.** Never invent a universe, place, group or user id. Use the user's, or the placeholder `1`, and say so in the final list. 8. **Only promise what exists today.** On npm: `@typetorch/framework`, `transformer`, `kernel`, `cli` (also installed as `tt`) and `dev-server`; the template installs all five with `bun install` (`npx @typetorch/cli` works too). Not on npm: the Studio plugin (`TypeTorchSync.rbxm` from its GitHub releases) and the backend (a checkout or its Docker image). Built and usable: kernel deploys that patch only the kernel into the live place (Luau Execution, no download; a copy with `kernel deploy --place-file` when the place doesn't allow saving through the API), the cloud test (`typetorch test --cloud`, automatic before prod deploys), `onStop` at server shutdown (kernel 0.3.2), the fleet API (`typetorch servers`, `report`, `alerts`) and the optional `AnalyticsEngine` (framework 0.3.0; its backend is `@typetorch/backend`, a git repo, not on npm). The Studio loop: `typetorch serve` (CLI 0.11+) with the Studio plugin, live reload in a playtest (kernel 0.5.4+), `typetorch studio ...` and `typetorch mcp` for agents. The debug macros from `@typetorch/transformer/macros` (transformer 0.3+). Optional build tools: goblox (`bun add -d goblox`, CLI 0.16+) and darklua for the production pack (CLI 0.17+). Owners switching any server in place needs kernel 0.3.4 and framework 0.3.2 (both on npm). Dev access lists through `typetorch access push` need kernel 0.3.8 on the servers (the signed settings record; 0.3.6-0.3.7 read the old ConfigService key). Cross-server messages (`TypeTorch.messaging`), `TypeTorch.servers()`, `TypeTorch.liveConfig` and the loading screen signals need kernel 0.3.8. `typetorch init` (CLI 0.10) is the guided setup for a new game, and it repairs a game that is already set up. It publishes, deploys and asks for keys, so it is the user's to run, never yours: name it in "What you need to do". Planned: content packs, the typed asset map from files, `typetorch test --unit`, `/tt grant`/`revoke`. 9. **No CI for the game, ever** (the owner's rule: hosted CI is a supply-chain risk). Don't add `.github/workflows`, actions, or any hosted CI to the game repo, and don't suggest them. Builds, cloud tests and deploys run on the user's machine. (TypeTorch's own packages are released by tag-triggered workflows; that is not a pattern for games.) ## Step 1: Detect Read the project. Change nothing yet. Write down what you find. 1. **Is it roblox-ts?** `package.json` with `roblox-ts`, a `tsconfig.json`, `.ts` sources, a `*.project.json`. - **Plain Luau** (only `.lua`/`.luau`, Wally, Rojo): **stop.** Tell the user: "TypeTorch is roblox-ts only; there is no Luau framework. Port the game to roblox-ts first, or start a new game from the template (say 'set up typetorch' in an empty folder)." Do nothing else. - **Empty folder, no game** (the user said "set up typetorch"): follow [Fresh setup path](https://www.typetorch.dev/agents/AGENTS.md#fresh-setup-path). - **Not a Roblox project:** stop and say so. 2. **Toolchain:** lockfile (`bun.lock`, `package-lock.json`, `pnpm-lock.yaml`, `yarn.lock`), roblox-ts and TypeScript versions, `tsconfig.json` `plugins` and `include`, `rokit.toml`/`aftman.toml`/`foreman.toml`. 3. **Framework:** Flamework (`@flamework/core`, `Flamework.addPaths`/`ignite`, `@Service`, `@Controller`, `Dependency()`, `@flamework/networking`, `@flamework/components`, custom `Modding` macros), Knit (`KnitServer.CreateService`, `Knit.Start()`), plain singletons, or something else (describe it). 4. **Entry points:** every `*.server.ts` and `*.client.ts`. 5. **Layout:** the Rojo tree in `default.project.json`; which `src/` folders go where. 6. **Patterns** (`git grep` works in PowerShell and bash; no output means none): ```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|Stepped" -- src git grep -nE "_G\b|\bshared\." -- src git grep -nE "DataStoreService|ProfileStore|ProfileService|GetDataStore|MemoryStoreService" -- src git grep -nE "BindToClose|MessagingService|TeleportService" -- src git grep -nE "@rbxts/react|@rbxts/roact|@rbxts/vide|ScreenGui|PlayerGui|StarterGui" -- src git grep -nE "rbxassetid://|LoadAsset|:Clone\(\)|\.Clone\(\)" -- src ``` 7. **Place content:** what the old Rojo project puts in the place besides code (models, `.rbxm`/`.rbxmx`, `*.model.json`, StarterGui, StarterPlayer scripts). Studio-built content isn't in the repo: ask, or note it. 8. **Ids:** the universe, place and group ids, if the repo has them (`servePlaceIds`, deploy scripts, `mantle.yml`, CI files). Don't guess. ## Step 2: Plan and show the plan Create `MIGRATION_NOTES.md` at the repo root with the plan, and show it in chat. Continue unless the user asked you to wait. Always ask before deleting files the user wrote by hand. 1. **Inventory:** from Step 1, with file paths. 2. **Mapping:** each old thing and its TypeTorch replacement (Step 4 tables). 3. **Order of work:** the sub-steps of Steps 3 and 4, one commit each. 4. **Risks and decisions for the user:** player data (always), Studio content and scripts that stay in the place, third-party networking (Zap, Blink, ByteNet), MessagingService topics (move them to `TypeTorch.messaging`, see [migrate](https://www.typetorch.dev/getting-started/migrate.md#cross-server-messages)), anything you can't convert. 5. **User actions:** filled in at the end (Step 7). Log every step in `MIGRATION_NOTES.md` as you go: what changed, the build result, open questions. ## Step 3: Add the TypeTorch toolchain Work on a new branch: `git switch -c typetorch-migration`, from a clean tree (commit or stash the user's changes first; ask if unsure). ### 3.1 The template as reference Every TypeTorch package comes from npm; the only checkout you need is the template, **next to** the game repo, to copy files from: ```text / my-game/ the user's game (this repo) template/ https://github.com/typetorch/template (the reference: copy its files, never edit it) ``` If it is missing, clone it from the game folder (ask first if your environment needs approval for downloads): ```sh git clone https://github.com/typetorch/template ../template ``` **The template decides the file layout, npm decides the versions.** Copy its `default.project.json`, `studio.project.json`, `scripts/build-info.ts` and the shape of its `package.json` and `tsconfig.json`. Its version pins are behind npm today (framework 0.5.0, kernel 0.5.1, CLI 0.9.1, transformer 0.2.1, dev-server 0.2.3) and it still uses `rbxts-transform-debug`, so take the `@typetorch/*` versions from npm with `@latest` (3.3) and the compiler plugin from 3.4. Don't type versions from memory. - **Today:** no Flamework. `@typetorch/framework` and `@typetorch/kernel` are dependencies; `@typetorch/transformer` (the compiler plugin), `@typetorch/cli` and `@typetorch/dev-server` are devDependencies, all from npm. `Modding`, `Reflect` and `t` come from `@typetorch/framework`. - If the template you find still depends on `@flamework/core`, `rbxts-transformer-flamework` or `file:.typetorch/packages/*.tgz` entries (an older checkout), `git pull` it first. - The template's `scripts/packages.ts` (`bun run packages`, and the `packages` and `postinstall` scripts) is an optional local override for framework, kernel or transformer changes that aren't on npm yet. Don't copy it unless the user asks for that; see [fresh setup: unreleased changes](https://www.typetorch.dev/getting-started/fresh-setup.md#unreleased-framework-or-kernel-changes-optional). ### 3.2 Tools - **Bun 1.3+** is the package manager. If the project uses npm, pnpm or yarn, run `bun install`, then delete the old lockfile. Mixing package managers breaks `rbxtsc`. - The CLI and the dev-server need no separate install: they are devDependencies (3.3). Run the CLI with `bun run typetorch `. - **Rokit:** `rokit.toml` as in the template (keep the project's other tools; replace an old Rojo pin): ```toml [tools] rojo = "rojo-rbx/rojo@7.7.0-rc.1" lune = "lune-org/lune@0.10.5" ``` Run `rokit install`; check `rojo --version` prints `7.7.0-rc.1` inside the repo. Then `rokit add seaofvoices/darklua` (it pins the newest darklua in `rokit.toml`): `typetorch build`, `upload` and `deploy` pack the payload with it (CLI 0.17+) and warn `darklua not found: this payload isn't minified` without it. - **goblox** (optional, only if the user asks): `bun add -d goblox`. `typetorch build` then compiles with it instead of rbxtsc (CLI 0.16+); end the `build` script with `goblox` (3.3). It runs only `@typetorch/transformer` and ignores every other tsconfig plugin. ### 3.3 package.json Merge the template's `dependencies`, `devDependencies`, `overrides` and these scripts into the game's (keep the game's own packages): ```json "build": "bun scripts/build-info.ts && rbxtsc", "watch": "bun scripts/build-info.ts && rbxtsc -w", "studio": "rojo serve studio.project.json", "typetorch": "typetorch" ``` - `build` must end with the compiler, `rbxtsc` (or `goblox` when the game uses it): the CLI appends `-p ` for prod builds, and runs the compiler directly, with a warning, when the script ends with something else. - Dependencies: `@typetorch/framework`, `@typetorch/kernel`, `@rbxts/t` (generated guards import it), `@rbxts/trove`, `@rbxts/services`. devDependencies: `@typetorch/transformer`, `@typetorch/cli`, `@typetorch/dev-server`, roblox-ts 3, `@rbxts/types`, `@rbxts/compiler-types`, TypeScript `5.5.3` (also in `overrides`). Take the TypeTorch ones from npm, not the template's pins: ```sh bun add @typetorch/framework@latest @typetorch/kernel@latest bun add -d @typetorch/transformer@latest @typetorch/cli@latest @typetorch/dev-server@latest ``` - Don't add `rbxts-transform-debug` (the template still lists it): `@typetorch/transformer` 0.3+ declares the same macros in `@typetorch/transformer/macros`. If the game already uses it, see 4.9. - Leave out the template's `packages` and `postinstall` scripts (the optional local override, 3.1). A `postinstall` without `scripts/packages.ts` makes `bun install` fail. - Remove packages the migration replaces (Knit, `@rbxts/net`, all `@flamework/*`, `rbxts-transformer-flamework`) once no code imports them (Step 4.2). Copy the build script and the Studio project, then install: ```sh mkdir -p scripts cp ../template/scripts/build-info.ts scripts/build-info.ts cp ../template/studio.project.json studio.project.json bun install ``` PowerShell: `New-Item -ItemType Directory -Force scripts` and `Copy-Item ` instead of `mkdir -p` and `cp`. The template's `studio.project.json` lists the kernel's server files one by one and misses `RemoteDebug`, `Bundle` and `LiveDebug`: a playtest then warns `TypeTorchKernel. is missing` and runs without them. In the copy, add the three under `ServerScriptService.TypeTorchKernel` as `node_modules/@typetorch/kernel/place.project.json` maps them, with the `node_modules/@typetorch/kernel/` prefix. In the copied `scripts/build-info.ts`, change the one import line it writes into `src/shared/build.ts`: ```ts 'import { $compileTime, $git } from "@typetorch/transformer/macros";', ``` (the template's copy says `"rbxts-transform-debug"`; without that package `bun run build` and `watch` fail on `build.ts`). `typetorch build` writes `build.ts` itself and picks the import on its own (CLI 0.12.2+). **Check:** `node_modules/@typetorch/framework/out/init.luau`, `node_modules/@typetorch/kernel/place.project.json`, `node_modules/@typetorch/transformer/out/index.js` and `node_modules/@typetorch/transformer/macros.d.ts` exist, and `bun run typetorch --help` prints `typetorch : hot-swap roblox-ts game code on live Roblox servers`. ### 3.4 tsconfig.json Keep the project's options; take these from the template: - `"include": ["./src/**/*.ts"]`. Without it rbxtsc compiles `scripts/*.ts` and fails (`Cannot find name 'console'`). - `"experimentalDecorators": true`, `"rootDir": "src"`, `"outDir": "out"`. - `"typeRoots": ["node_modules/@rbxts", "node_modules/@typetorch"]` (drop `node_modules/@flamework`). - `"types": ["types", "compiler-types"]`. Without it the `@typetorch` type root pulls in the kernel package: TS2688. - `plugins`: `{ "transform": "@typetorch/transformer" }` first. Remove `rbxts-transformer-flamework` and `rbxts-transform-debug` (transformer 0.3+ expands its macros). Keep other transformers the project uses after it (goblox ignores them). ### 3.5 The payload project The game's code becomes a **payload**: a roblox-ts **Model** project. Keep the old project for reference: ```sh git mv default.project.json legacy.project.json cp ../template/default.project.json default.project.json ``` - The template's file is a `Model` with `Server` (`out/server`), `Shared` (`out/shared`), `Client` (`out/client`) and `include` (with `node_modules/@rbxts`, and `@typetorch/framework` only, never the kernel). - Sources must be in `src/server`, `src/shared`, `src/client`. Move other folders with `git mv` and fix imports. - Note in `MIGRATION_NOTES.md` the non-code content of `legacy.project.json` that must now live in the place. ### 3.6 .gitignore Add what's missing: ```gitignore node_modules/ out/ include/ *.tsbuildinfo src/shared/build.ts .typetorch/ .payload.gen.project.json .tsconfig.typetorch.json .env .env.* ``` If `out/` or `include/` were committed: `git rm -r --cached out include`. Delete Flamework leftovers: `flamework.build`, `flamework.json`, `include/flamework`. ### 3.7 typetorch.json At the repo root: ```json { "project": "my-game", "universeId": 1, "placeId": 1, "creator": { "groupId": 1 }, "defaultBranch": "prod", "branches": { "main": "prod" }, "channels": { "prod": "prod" }, "members": {}, "devBadgeId": null, "approval": "prod", "kernel": "node_modules/@typetorch/kernel" } ``` - `universeId`, `placeId`, `creator`: the user's (`{ "groupId": … }` or `{ "userId": … }`, the experience owner), or the placeholder `1`. - `branches`: map the repo's default git branch (`main` or `master`) to `prod`. - `members`: `{}` unless the user gave user ids; each is `"owner"` or `"dev"` (an old `"admin"` counts as dev). The experience's creator (or the owning group's owner) is always an owner. Servers see `members`, `revoked` and `devBadgeId` only after the user runs `bun run typetorch access push` (kernel 0.3.8+; it signs with the prod keys): put it in the user's list whenever you add or change them. - `approval: "prod"`: dev deploys go out at once, prod ones wait for the user's y/N. - Optional (kernel 0.3.7+), only after the dev soak in step 11 shows a need: - `"health": { "errors": 3, "window": 30 }`: a server rolls a new build back at `errors` (1-100) errors from it within `window` seconds (5-300) of start. `"rollback": false` turns that off; `"prod"` / `"dev"` override per channel. - `"autoRollback": { "failedPct": 20 }`: `deploy --wait` rolls the branch back at this % of failed servers (1-100). - Raise them only to match errors the user can't fix yet; say so in MIGRATION_NOTES.md. - Never copy the template's `signingPublicKeys`, `keyAssetId` or `fallbackPublicKey`: they belong to the template's game. `typetorch keys init` writes the user's. ### 3.8 Boot modules ```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 }); } ``` - Every ModuleScript under the `modules` folders is required: their top-level code must have no side effects. - `bun run build` now writes `src/shared/build.ts` (gitignored) and compiles. **Check:** run `bun run build`, then commit (`git add -A`, `git commit -m "TypeTorch toolchain"`). - Knit or plain projects: it passes (old code still compiles). - **Flamework projects: it fails** on every `@flamework/core` import with "You can only use npm scopes that are listed in your typeRoots". Expected: the toolchain no longer has Flamework. Note it in the log; Step 4.1 and 4.2 make it pass. - `bun run typetorch build` fails on the old entry scripts until Step 4.1. - Run the compiler only through `bun run build` or `bunx rbxtsc`. In a Bun project on Windows, `npx rbxtsc` runs an unrelated placeholder package. ## Step 4: Migrate the code in small verifiable steps One sub-step per commit. After each: `bun run build` must pass, then log it in `MIGRATION_NOTES.md`. (Flamework projects: do 4.1 and 4.2 together; the build passes once no `@flamework/*` import is left.) **Flamework projects: run the codemod first.** On a clean tree after Step 3, `bun run typetorch migrate --from flamework --dry-run`, then without `--dry-run`: it makes 4.1, 4.2 and the networking part of 4.4 (call sites stay, through `createFlameworkCompat`) and writes `typetorch-migrate-report.md`. Commit that as one step, then work through the report's flagged items with 4.3 and the rest of this step; keep the report's counts in `MIGRATION_NOTES.md`. Local only, no keys. See [Coming from Flamework](https://www.typetorch.dev/guides/from-flamework.md). ### 4.1 Entry points Move what each `*.server.ts` / `*.client.ts` does into modules, then delete the script (`git rm`). Delete `Flamework.addPaths(...)`, `Flamework.ignite()`, `Knit.Start()` and hand-written bootstrappers. A Script or LocalScript left in the payload fails `typetorch build` with "the payload may hold only Folders and ModuleScripts". ### 4.2 Services and controllers → modules | Old | TypeTorch | |---|---| | Flamework `@Service()` / `@Controller()` | `@Service()` / `@Controller()` from `@typetorch/framework`; the class `extends Module`; a constructor calls `super()` | | Flamework `OnInit`, `OnStart`, `OnTick`, `OnPhysics`, `OnRender` | the same names from `@typetorch/framework` | | Flamework `Dependency()` | constructor injection in a module; `Dependency()` from `@typetorch/framework` everywhere else (methods, plain classes, command handlers), from `onInit` on | | a dependency cycle (A injects B, B injects A) | `Lazy` on one side (a field `= Lazy()`, or a constructor parameter with transformer 0.2.1+), or `Dependency()` in a method | | `Modding`, `Reflect`, `t` from `@flamework/core` | the same names from `@typetorch/framework` | | custom decorators (`Modding.createDecorator`, `@metadata flamework:parameters injectable`) | `Modding.createDecorator` from `@typetorch/framework`, `@metadata typetorch:parameters injectable` | | Flamework `@Component` / `@flamework/components` | a module using `observeElement(this.trove, tag, …)` or `@rbxts/observers` | | Flamework `Flamework.createGuard()`, `Flamework.id()` | `t` guards written by hand, or a user macro (transformer README "Migrating from Flamework"); note it for the user | | Knit `CreateService({ Name, Client, KnitInit, KnitStart })` | `@Service()` class; `KnitInit` → `onInit`, `KnitStart` → `onStart`, `Client` → network leaves | | Knit `Knit.GetService("X")` / `GetController` | constructor injection, or `Dependency()` in a method | | singleton module with top-level state | a `@Service()` / `@Controller()` class; state on the instance or in `persist` | | shutdown cleanup | `onStop` (reverse order; the kernel gives a stopping generation 5 s) and the trove | - Server modules go in `src/server/services/`, client modules in `src/client/controllers/` (subfolders are fine); kebab-case names (`coin.service.ts`). - Import only from `@typetorch/framework`: `Module`, `Service`, `Controller`, `OnInit`, `OnStart`, `OnStop`, `OnTick`, `OnPhysics`, `OnRender`, `OnPlayerAdded`, `TypeTorch`, `Dependency`, `Lazy`, `createNetwork`, `observePlayers`, `observeElement`, `isRealFrame`, `popIn`, `popOut`, `bump`, `PopupQueue`, `hotAsset`, `setNetworkLimits`, and `Modding`, `Reflect`, `t` for your own macros and decorators. - **If the project uses Flamework,** the migration is mostly a swap: the decorators, constructor injection, `Dependency()` and the lifecycle interfaces keep their names, so change the imports to `@typetorch/framework`, add `extends Module` and `super()`, and do the swap-safety pass (4.3). The rest is the toolchain (Step 3), `createNetwork` for `@flamework/networking` (4.4) and observers for components. `Dependency()` is the cycle breaker (with `Lazy`) and the way plain classes reach modules; it works from `onInit` on, so move every call in a constructor, a field initializer or at the top level of a module (`const X = Dependency()` in a command file) into a method or `onInit`. Keep `import type` for the class. Then: - no file under `src/` imports `@flamework/*`: `git grep -n "@flamework/" -- src` prints nothing; - remove `@flamework/*` and `rbxts-transformer-flamework` from `package.json` (`bun remove ...`); - type ids changed format (`@typetorch/framework:decorators@Service`, `server/services/x@X`): anything the game saved under Flamework ids (`Flamework.id()`) won't match. Flag it under data. - No work in constructors (`this.trove` and `this.ctx` arrive right after). - `onInit` runs in dependency order and may yield briefly (a swap allows about 20 s for the whole generation to be ready, a new server's boot only about 6 s); move slow loading to `onStart`, which is spawned per module inside its trove. ### 4.3 Swap-safety pass (every module) Every module must be stoppable and restartable: a deploy stops it and starts a fresh copy in the same server. 1. **Everything in the trove:** `this.trove.connect(signal, fn)`, `this.trove.add(instance)`, `this.trove.add(network.server.x.y.on(...))`, `this.trove.add(TypeTorch.onSwapOut(...))`. **No cleanup touches a trove:** a function added to a trove must never call `trove.remove`, `add` or `extend` (Trove throws "Cannot call trove.remove() while cleaning"; before framework 0.5.2 that aborts the whole generation stop and leaves the old generation alive). Delete lines like `this.trove.add(() => this.trove.remove(child))`: a child from `trove.extend()` is cleaned by its parent anyway. Audit: `git grep -nE "trove\.add\(\(\) =>.*\.(remove|add|extend)\(" -- src`, then read every cleanup function by hand. 2. **No module-level state or side effects.** Constants may stay. Per-generation state goes on the instance. State that must survive a swap goes in `this.ctx.persist("key.v1", () => init)`, plain data only (tables, Maps, Sets of strings, numbers, booleans, Players); never functions, class instances, Promises, threads, connections, charm atoms or Instances the generation made. Version the key. Per-player maps (cooldowns, states, sessions): `this.ctx.playerState("key.v1", (player) => init)` (`get`/`set`/`has`/`delete`, persisted, removed on a real leave). **`this.ctx` and `Dependency()` only from `onInit` on:** a field initializer (`private state = this.ctx.persist(...)`) or a constructor fails, because `ctx` is attached after construction. Declare the field and assign it in `onInit`. 3. **Players through `onPlayerAdded(player, playerTrove)` or `observePlayers(this.trove, …)`**, never `Players.PlayerAdded.Connect`. They replay everyone on every swap, so **join handlers must be idempotent**: guard one-time effects (join rewards, welcome popups, "joined" analytics) with a persisted set. Work for real leaves only: `this.trove.connect(Players.PlayerRemoving, …)` (a `playerTrove` is also cleaned on every swap). 4. **Tags and characters through observers:** `observeElement(this.trove, tag, (instance, elementTrove) => …)`, or `@rbxts/observers` with its stop function in the trove (`this.trove.add(Observers.observeCharacter(…))`), or (characters, no extra package) `player.Character` plus `playerTrove.connect(player.CharacterAdded, …)`. 5. **No global connections or loops outside troves.** A loop directly in `onStart` is fine. Elsewhere: `this.trove.add(task.spawn(() => { … }))`. Prefer `onTick` for per-frame work. 6. **No `_G` or `shared`:** constructor injection, or `persist`. 7. **`task.spawn`/`delay`/`defer` only through the trove:** `this.trove.add(task.delay(5, fn))`. Replace deprecated `spawn`, `delay`, `wait` with `task.*`. 8. **Instances in the world** that a module creates go in its trove (or an observer's cleanup). **Libraries with module-level setup** (connections, ScreenGuis, steppers, pending Promise chains created when the module is required; Vide's Heartbeat stepper and TopbarPlus are known ones) leak one copy per swap. Check each package's top level. Fix: drive it from the trove (`this.trove.connect(RunService.Heartbeat, (dt) => vide.step(dt))`), or load it once outside the payload (a place script requires it from `ReplicatedStorage.lib`, or the first generation clones it there). See migrate rule 9. 9. **Looped animations and cutscenes** stop on every client swap. Persist plain data (`{ id, animationId, startedAt }`, `{ startedAt, endsAt }`) and resume in the next generation (`track.TimePosition = elapsed`); derive idles from synced state. Flag minigames for the user: persist their inputs, restart the rest. See migrate section 7. 10. **Shutdown:** kernel 0.3.2+ runs every module's `onStop` when the server shuts down, but not when it shuts down in the middle of a swap (no generation is running then). So `onStop` is for short extras, never the only place player data is saved: data goes through the library in the place (4.6), or is written as it changes. Remove `game.BindToClose` handlers that only did cleanup; any that must stay bind at most once per server (a persisted flag). On a swap, `TypeTorch.onSwapOut` runs first, before any `onStop` or trove cleanup: last-resort work (save into `persist`, flush) goes there. ### 4.4 Networking - One `src/shared/net.ts`: ```ts import { createNetwork, type ProperReturns } from "@typetorch/framework"; interface ClientToServer { shop: { buy(itemId: string): void; price(itemId: string): ProperReturns } } interface ServerToClient { shop: { purchased(itemId: string): void } } export const network = createNetwork(); ``` - Server: `this.trove.add(network.server.shop.buy.on((player, itemId) => …))`; requests: `this.trove.add(network.server.shop.price.handle((player, itemId) => [100]))` (`[value]` or `[false, "reason"]`); sends: `network.server.shop.purchased.fire(player, id)`, `fireAll`, `fireExcept`, `fireList`, `fireUnreliable`. - Client: `network.client.shop.buy.fire(id)`; `this.trove.addPromise(network.client.shop.price.invoke(id).then(…))`; `this.trove.add(network.client.shop.purchased.on((id) => …))`. - Delete every RemoteEvent/RemoteFunction/UnreliableRemoteEvent the game created, in code, the Rojo project or the place notes. RemoteFunctions become request leaves. - Template literal types can't be guarded: use `string`. Keep game checks (distance, ownership, cooldowns) in handlers. - `@rbxts/net`, `@flamework/networking`, Zap, Blink, ByteNet: convert to `createNetwork`. Flamework names: `connect` → `on`, `setCallback` → `handle`, `broadcast` → `fireAll`, `except` → `fireExcept`, `predict` → `emit` (runs the local `on` handlers, no traffic), `invokeWithTimeout(seconds, …)` keeps its name; check the unit (seconds, 0.5 to 120: a Flamework call with `5000` meant milliseconds by mistake). The codemod doesn't change the arguments: audit every call with `git grep -n "invokeWithTimeout(" -- src` and turn values above 120 into seconds. A leaf's default timeout: `setNetworkLimits({ "x.y": { timeout: 30 } })` in `src/shared/net.ts` (the client reads it). - A big Flamework network can stay on `createFlameworkCompat` (the codemod's default) and move to `createNetwork` later (`typetorch migrate --from flamework --net native`); `typetorch build` reminds you while it is in use. ### 4.5 UI - Code-built UI: build it in a controller; `this.trove.add(screenGui)`. - Studio-built UI stays in the place (StarterGui): tag what code touches (`Element:.`), drive it with `observeElement`. The payload can't carry ScreenGuis. - charm atoms live per generation; persist their plain values if they must survive a swap. charm-sync: the recipe in [State with charm](https://www.typetorch.dev/guides/state.md) (server atoms from persist, a `createNetwork` leaf, hydrate request in onStart). - React/Roact/Vide: mount in a controller, `this.trove.add(() => root.unmount())`. - `popIn`/`popOut`/`bump` (UIScale, never tweened `Size`); one `PopupQueue` for modals. - Update notices: `TypeTorch.onUpdatePending` fires before every hot swap, and players stay in the server. Never show "migrating server" there; show "updating in N s" or nothing, and announce the result from `TypeTorch.startInfo` in `onStart` ([Runtime API](https://www.typetorch.dev/guides/runtime-api.md#what-to-tell-players)). ### 4.6 Player data (always flag it) Player data is game code. The swap-safe pattern ([Player data](https://www.typetorch.dev/guides/player-data.md)): the library lives in the place (for example `ServerStorage.Packages.ProfileStore`) with a small host Script that requires it first; session handles live in `persist`; load on join (re-attach after a swap), release on a real leave. | The project uses | Do | |---|---| | ProfileStore / ProfileService | rewrite the data module as the guide's `DataService` for that library (same store names and keys, a `_dev` name for non-prod channels; loads, saves and releases as DataHost jobs, or with `TypeTorch.runDetached` on kernel 0.3.8+: the guide's two options); the place copy and the `DataHost` Script are **user steps** (Studio) | | plain DataStores, small per-player values | keep them in the payload: read once per join, `UpdateAsync` on change, pending writes in `persist` (like the template's `BestService`) | | anything else (DataStore2, Lapis, custom sessions) | wrap it in a `@Service()` unchanged, and write in `MIGRATION_NOTES.md` that it must move to the place and follow the pattern before prod | Never rename stores or change the data shape. Always put "test data across two deploys on a dev branch" in the user's list. - **The cloud test:** keep the guide's line `if (Workspace.GetAttribute("TypeTorchTest") === true) return undefined;` in `profileStore()`. The place's `DataHost` never runs in the test, so without it `onInit` waits 10 s, fails, and every prod deploy is refused. Wrapped libraries follow the same rule: never wait on a place script in the test. - **Developer products:** `ProcessReceipt` records the PurchaseId in the player's profile together with the grant and returns `PurchaseGranted` only once a save holds it (the guide's `grantOnce` and `ReceiptService`). Never only in `persist`. Put "buy a product while a deploy runs" in the user's list. **The cloud test runs game code against the live game's data.** Every prod deploy boots the build in a headless Luau Execution task: `onInit` and `onStart` of every module, with the real DataStores, MemoryStores, MessagingService and HTTP, no players, no place scripts. `TypeTorch.channel` is `dev` there (CLI 0.7.3+), so stores split by channel point at dev data; unsplit stores don't. The `AnalyticsEngine` sends nothing from the test (framework after 0.3.2). `workspace:GetAttribute("TypeTorchTest")` is true there. Guard with it, and list each guard in `MIGRATION_NOTES.md`: - global resets and one-time jobs (season rollovers, leaderboard wipes, shared-key migrations); - raw MessagingService publishes (cross-server announcements, "server started" pings; `TypeTorch.messaging.publish` already does nothing there); - "server started" rows in DataStores or MemoryStores, webhooks, the game's own HTTP APIs; - waits on place scripts. Guard only side effects; the test is useful because it boots the real code. Details: [migrate: the cloud test runs your game code](https://www.typetorch.dev/getting-started/migrate.md#the-cloud-test-runs-your-game-code). ### 4.7 Place content, assets and scripts that stay - The place keeps: the kernel, maps, terrain, lighting, StarterGui layouts, StarterPlayer/StarterCharacter scripts, third-party Luau systems, the data library and its host Script. They change with a place publish and a restart. - Hard-coded asset ids keep working (owned by or shared with the experience owner). - **Hot assets** (optional; only if the user asks, or mention it in the report): code that clones templates can use `hotAsset("tools/sword", template)` (the second argument keeps today's template as the fallback). Marking templates with `TypeTorchAsset` and `typetorch assets sync` are user steps. See [Hot assets](https://www.typetorch.dev/guides/hot-assets.md). - Never suggest `typetorch kernel deploy --replace-place` for a place with Studio content. The kernel goes in with `kernel deploy --install` (a user step, Step 7; with `--place-file ` when the place doesn't allow saving through the API) or by hand in Studio. ### 4.8 Analytics (optional) TypeTorch's own analytics ([Analytics](https://www.typetorch.dev/guides/analytics.md)) is optional: an `AnalyticsEngine` created on the server and the client logs sessions, devices, tech health, zones and new players' first sessions; game code adds `step`, `purchase`, `currency`, `state` and `track`. The engine starts on the first `new AnalyticsEngine()`: create it in a low-`loadOrder` module's `onInit`, not in a helper that first runs on a game event (an idle server would send nothing). Add it only if the user asks (or mention it in the report). Keep an existing analytics SDK as it is. Its backend (a DuckDB server or Cloudflare Basin, tokens, the settings key) is a user step. ### 4.9 Logging (optional) `$print`, `$warn`, `$error`, `$assert` and `$dbg` from `@typetorch/transformer/macros` add `[src/file.ts:line]` in dev builds; prod builds drop `$print`/`$warn`/`$dbg` and keep `$assert`/`$error` without the position. Plain `print`/`warn` keep working (and stay in prod builds). A game that already imports them from `rbxts-transform-debug`: remove that plugin from `tsconfig.json` (the transformer expands calls through its declarations too), rewrite the imports to `@typetorch/transformer/macros` (in `src/` and `scripts/build-info.ts`), then `bun remove rbxts-transform-debug`. `bun run build` after each. Details: [migrate: Debug macros](https://www.typetorch.dev/getting-started/migrate.md#debug-macros). ## Step 5: Run local checks All local; no key needed. ```sh bun run build bun run typetorch build ``` 1. `bun run build` has no errors. 2. `bun run typetorch build` prints `built (branch ..., channel ..., @, ...)` and `.typetorch/payload.rbxm modules`. It fails, naming the path, if the payload holds anything but Folders and ModuleScripts. 3. The guards were generated: `out/shared/net.luau` calls `createNetwork(` with `t.` guards (for example `t.strictArray(t.string)`). `createNetwork()` with no arguments means the transformer isn't running. 4. The pattern scan prints nothing (or only lines you checked and explain in the notes): ```sh git grep -nE "Players\.PlayerAdded\.Connect|PlayerRemoving\.Connect\(" -- src git grep -nE "new Instance\(\"(Remote|UnreliableRemote)(Event|Function)\"\)" -- src git grep -nE "_G\b|\bshared\." -- src git grep -nE "@flamework/|Flamework\.(ignite|addPaths)|Knit\.Start" -- src git grep -nE "^\s*task\.(spawn|delay|defer)\(|[^.]\bspawn\(|[^.]\bdelay\(" -- src ``` 5. Commit, then `bun run typetorch build` again: the id has no `-dirty`. Also try a prod build: `bun run typetorch build --branch prod` ("prod channel: $print/$warn removed"). 6. The Studio project builds: `rojo build studio.project.json -o .typetorch/studio-check.rbxl`, then delete that file. 7. Optional, only when the user has Studio open with the TypeTorch plugin: `bun run typetorch serve --detach`, then `bun run typetorch studio status --json`, `studio play`, `studio logs` (look for `[TypeTorch]` lines and errors) and `studio stop`; or the same through `typetorch mcp`. `serve status --json` lists compile errors. Plain `serve` runs no keys; never add `--remote` or `--claude`, and stop it (`serve stop`) when done. Fix, rebuild, log. ## Step 6: Stop at user actions Don't do these; list them in Step 7: - create the group, the experience, an API key; change Creator Hub or Game Settings; - write a key or token anywhere; run `typetorch keys ...`, `doctor`, `deploy`, `upload`, `approve`, `promote`, `rollback`, `pin`, `settings ...`, `access push`, `assets sync|status`, `kernel deploy`, `kernel restore`, `deployments`, `branch ls`, `test --cloud`, `servers`, `report`, `alerts`, `backend setup`, `update`; - publish a place; edit the place in Studio (kernel install, data library, `TypeTorchAsset` marks); - start `remote-claude`, the analytics server or a tunnel (including `typetorch serve --remote` or `--claude`); press the Studio plugin's Upload or Publish to dev; write the analytics settings; - push to a remote; add GitHub Actions or any CI workflow. ## Step 7: Finish with "What you need to do" End with this list, filled in for the project (drop what doesn't apply). Also append it to `MIGRATION_NOTES.md`. ```markdown ## What you need to do 1. **Fill in the ids** in `typetorch.json` (replace the placeholder `1`s): `universeId`, `placeId`, and `creator.groupId` (or `creator.userId`). Creator Hub > Creations > your experience > "..." > Copy Universe ID / Copy Start Place ID. Optional: other people's user ids in `members` (`"owner"` or `"dev"`; you, the experience owner, are always an owner), then `bun run typetorch access push` after step 5, and again after every change to `members`, `revoked` or `devBadgeId` (it needs the signing keys). Servers see the lists only after that, on kernel 0.3.8+; `deploy` and `doctor` warn when they were never pushed or changed since. 2. **Experience settings** (Studio > File > Game Settings > Security, as the owner): Allow HTTP Requests on; Enable Studio Access to API Services on. Optional: Allow Mesh / Image APIs (Claude images), Allow Loading Third Party Assets (Toolbox inserts). 3. **Create an Open Cloud API key** (Creator Hub > Open Cloud > API Keys, as the group owner or a member allowed to upload and publish for the group), for this experience: - `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) - `universe-messaging-service:publish` - DataStore `universe-datastores.objects:read`, `:create` and `:update` (the shared deploy number: every machine takes `#seq` from the game's DataStore; and the signed settings record: `access push`, `backend setup`, `settings ...`) - place publishing (`universe-places` write; the CLI says `universe.place:write`), only when `kernel deploy` publishes a file: `--replace-place` (a new place), `--place-file`, `kernel restore ` Set an expiry and, if you can, an IP allowlist. No `universe:write` / `universe:read` (TypeTorch keeps nothing in ConfigService since kernel 0.3.8). Don't ask for `legacy-asset:manage` (place downloads): Creator Hub doesn't offer it for API keys today. Deploys work without it: `kernel deploy` patches the place through Luau Execution when the place allows saving through the API, and takes a copy of the place otherwise (`--place-file`, see "Updating the kernel in a game"). 4. **Put it in the game repo's `.env`:** the line `OPENCLOUD_API_KEY=` (gitignored; CLI 0.9 reads the keys from there: `OPENCLOUD_API_KEY`, and `TYPETORCH_API_KEY` and `TYPETORCH_ADMIN_TOKEN` for the backend). Never commit it or paste it into chat. 5. **Check:** `bun run typetorch doctor`. Expect `ok` for the tools, `typetorch.json`, each key and the scopes you added. 6. **Prod signing keys:** `bun run typetorch keys init`, `bun run typetorch keys init --fallback`, commit `typetorch.json`. Back up `~/.config/typetorch/keys/.key`, `.fallback.key` and the game repo's `.env` offline, and plan a rotation drill ([Prod signing: back up and drill](https://github.com/typetorch/docs/blob/main/guides/prod-signing.md#back-up-and-drill)). 7. **Put the kernel in the place** (needs a place publish and a restart): - empty or new place: `bun run typetorch kernel deploy --dry-run`, then `bun run typetorch kernel deploy --replace-place --yes`; - place with Studio content (never `--replace-place`, it wipes the place): `bun run typetorch kernel deploy --dry-run --install` patches the live place through Luau Execution, with no download, when the place allows saving through the API (Creator Hub > Permissions: "Allow place to be updated using Save Place API"; off by default for places made in Studio). Read the summary (only the kernel folders and the kernel's settings may change), then the same command without `--dry-run` publishes after a y/N. Undo: `kernel restore --version `. Otherwise: File > Download a Copy (a binary `.rbxl`), note its place version, and run `bun run typetorch kernel deploy --dry-run --install --place-file --base `; the same command without `--dry-run` publishes after a y/N, and `kernel restore ` undoes it. (Or by hand: `kernel deploy --dry-run`, open `.typetorch/place.rbxl` in Studio, copy `ServerScriptService.TypeTorchKernel`, `ReplicatedStorage.TypeTorchKernelShared` and `ReplicatedFirst.TypeTorchKernelClient` into your place, File > Publish to Roblox.) The kernel waits idle until the first deploy. - `ServerScriptService.LoadStringEnabled`: keep it **off** in this game. Turn it on only in a test place where you want remote-claude's `run_luau` (`kernel deploy --loadstring`, CLI 0.7.5+). `kernel deploy` patches leave it as it is (older CLIs, up to 0.7.2, turn it on: check it in Studio); `doctor` reports it. - then, in Studio, remove the old scripts listed in MIGRATION_NOTES.md and publish, just before the first deploy. 8. **Player data** (if listed in MIGRATION_NOTES.md): in Studio put the library at `ServerStorage.Packages.` and add the `ServerScriptService.DataHost` Script from the Player data guide; publish. 9. **Test locally in Studio:** install the TypeTorch Studio plugin (`TypeTorchSync.rbxm` from github.com/typetorch/studio-plugin/releases into Studio's plugins folder), run `bun run typetorch serve`, open the place (the plugin attaches by itself), Play. Server > Status shows "Studio: local payload". Saves reload the running playtest (kernel 0.5.4+); the dev menu's Reload tests a swap. 10. **Check the kernel live:** join the game; F9 > Server shows `[TypeTorch] kernel (API 1) on a public server, branch prod, signed deploys only (keys: key asset)`. `/tt status` answers. 11. **Dev branch:** `git switch -c dev`, `bun run typetorch deploy`, then `/tt new dev` in game. Earn some data, deploy again twice while playing, rejoin: nothing lost. Developer products: buy one while a deploy runs; one grant, also after a rejoin. `bun run typetorch test --cloud` passes on the dev build (prod deploys run the same test). After each deploy, ask the user for the dev menu's Server > Status line "Health window: n/3 errors" (errors from the new build in its first 30 s). 3 rolls every server back: fix those errors, or set `typetorch.json` `"health"` above the count (3.7) and rebuild. 12. **First prod deploy:** a game with live players goes through the [go-live checklist](https://github.com/typetorch/docs/blob/main/guides/go-live-checklist.md) first (a copy of the game, a dev-branch soak, a planned cut-over). Merge into `main`, stay in the game, `bun run typetorch deploy` (the cloud test runs, then y/N, then signed). Expect `deployed #N prod@ -> `; the dev menu's Artifact tab shows two verified badges. 13. **Rollback drill:** `bun run typetorch rollback --branch prod`, check `bun run typetorch deployments`, deploy again. 14. Optional: [live servers and alerts](https://github.com/typetorch/docs/blob/main/guides/fleet-and-alerts.md) (`typetorch backend setup`, then `servers`, `report`, `alerts`, and automatic rollback after bad deploys); [analytics](https://github.com/typetorch/docs/blob/main/guides/analytics.md); [hot assets](https://github.com/typetorch/docs/blob/main/guides/hot-assets.md); [remote-claude](https://github.com/typetorch/docs/blob/main/guides/remote-claude.md) (in a test place: it needs `LoadStringEnabled` for `run_luau`). ``` ### Final report template ```markdown # TypeTorch migration report **Result:** builds: · branch `typetorch-migration` · commits · artifact `` ## What I changed - Toolchain: - Entry points: → `src/server/boot.ts`, `src/client/boot.ts` - Modules: ( → TypeTorch); Flamework imports left: - Networking: → `src/shared/net.ts` () - Swap safety: - UI: <...> - Player data: ## Checks - `bun run build`: - `bun run typetorch build`: , modules, clean id: ; prod build: - Guards generated: - Pattern scan: - `studio.project.json` builds: ## Needs your decision - Player data: - Place content and scripts that stay in the place: - Not converted: ## What you need to do Details: MIGRATION_NOTES.md ``` ## Updating the kernel in a game (agents) Only when the user asks for a kernel update (a new `@typetorch/kernel` version). Kernel updates stay manual: the kernel lives in the place, so it changes with a place publish and new servers. This is the one flow where you run `kernel deploy`, and you publish only after the user's OK in chat. 1. **You run a dry run:** `bun run typetorch kernel deploy --dry-run`. It patches only the kernel folders and the kernel's settings into the place's newest version (which must be published), checks that everything else is unchanged, and saves nothing. Read the summary (kernel old -> new, scripts changed per folder, settings, references); anything outside the kernel changing is a stop. 2. **Show the user the summary and ask.** After their yes: `bun run typetorch kernel deploy --yes`. It saves and publishes through Luau Execution, with no download. It needs the place setting "Allow place to be updated using Save Place API" on, and no Team Create session. It refuses if someone published meanwhile. Undo: `bun run typetorch kernel restore --version `. 3. **If the place doesn't allow saving through the API** (a Studio-made place with that setting off), the user downloads a copy in Studio (File > Download a Copy, a binary `.rbxl`) and tells you the file and the place version it came from. Run `bun run typetorch kernel deploy --dry-run --place-file --base `, and after the user's yes the same command without `--dry-run` plus `--yes`. Keep the copy: `bun run typetorch kernel restore ` publishes it back (undo). 4. **Or, with the Roblox Studio MCP and the place open:** replace the kernel instances in Studio (`ServerScriptService.TypeTorchKernel`, `ReplicatedStorage.TypeTorchKernelShared`, `ReplicatedFirst.TypeTorchKernelClient`, as `node_modules/@typetorch/kernel/place.project.json` lays them out, with the sources from `node_modules/@typetorch/kernel/src`; keep the folders' attributes such as `KeyAssetId`), then the user publishes from Studio (File > Publish to Roblox). 5. **Check a fresh server boots the new kernel:** the user joins a new server (old ones keep the old kernel until they close); F9 > Server shows `[TypeTorch] kernel ` and `/tt status` answers. ## Fresh setup path No game yet ("set up typetorch" in an empty folder). The user's own path is `bunx @typetorch/cli init` (it asks for keys and publishes, so it is never yours to run: name it in the final list). Without it: 1. From the workspace folder: ```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, at the template's (old) pins; the template already has the `typetorch` script. Then take the newest versions and darklua (3.2, 3.3): ```sh bun add @typetorch/framework@latest @typetorch/kernel@latest bun add -d @typetorch/transformer@latest @typetorch/cli@latest @typetorch/dev-server@latest rokit add seaofvoices/darklua ``` The template's code imports its macros from `rbxts-transform-debug` and its tsconfig runs that plugin before `@typetorch/transformer`; transformer 0.3 accepts both. Leave it, or move it as in 4.9. 2. In `typetorch.json`: the user's ids (or placeholders `1`), `members` `{}` unless given, and **delete** `signingPublicKeys`, `keyAssetId` and `fallbackPublicKey` (they are the template's). 3. Step 5 checks, commit. 4. Step 7 list (skip data, legacy and kernel-copy items: the new place takes `--replace-place`). ## Optional: Claude Code - Install the skill: `/plugin marketplace add typetorch/claude-plugin`, then `/plugin install typetorch@typetorch`. Run it with `/typetorch:typetorch-migrate`. `typetorch init` adds the marketplace itself when it starts Claude Code. - The CLI is also an MCP server for the Studio loop: `claude mcp add typetorch -- bunx typetorch mcp` in the game repo (tools: `serve_status`, `serve_start`, `serve_stop`, `serve_logs`, `studio_logs`, `studio_reconnect`, `studio_play`, `studio_stop`). Same limits as Step 5 item 7. - Plan mode fits Steps 1 and 2. Allow `bun run build` and `bun run typetorch build`; keep every Roblox-facing command on ask or deny. - remote-claude runs only on a Claude subscription login, never an API key. --- # TypeTorch migration The full playbook is `agents/AGENTS.md` in the TypeTorch docs repo (https://github.com/typetorch/docs/blob/main/agents/AGENTS.md). Read it when you can; this file carries the essentials. Before/after code for every pattern: https://github.com/typetorch/docs/blob/main/getting-started/migrate.md. ## Rules 1. Never create, ask for, read, print or store secrets: Open Cloud keys, signing key files (`~/.config/typetorch/keys/*`), pairing codes. Don't open `.env` or the file named by `TYPETORCH_ENV_FILE`. 2. Never act on Roblox: no `typetorch` upload, deploy (not even `--dry-run`), promote, rollback, approve, reject, pin, deployments, branch ls, settings, access push, kernel deploy (not even `--dry-run`, except a kernel update the user asked for: see "Kernel updates"), kernel restore, keys, assets sync/status, test --cloud, servers, report, alerts, backend setup, update, doctor; no place publish; no remote-claude (`typetorch dev`), analytics server or tunnel. These are user steps. 3. Never push. Commit locally on `typetorch-migration`. 4. Don't edit `node_modules/@typetorch/*`, the reference `../template` or any TypeTorch checkout: copy from them. 5. No new RemoteEvents, `loadstring`, `_G`, disabled guards or settings changes. 6. Don't change player data formats, store names or keys. 7. Never invent ids: the user's, or placeholder `1`. 8. On npm: `@typetorch/framework`, `kernel`, `transformer`, `cli` (alias `tt`) and `dev-server` (`bun install` in the template gets them; `npx @typetorch/cli` works too); not on npm: the backend and the Studio plugin (GitHub releases). Built: kernel patch deploys (`kernel deploy`, or `--place-file`), the cloud test before prod deploys, `onStop` at shutdown (kernel 0.3.2), the fleet API, the optional `AnalyticsEngine`, `typetorch access push` (CLI 0.7.3+; servers read it from kernel 0.3.8), `typetorch init` (CLI 0.10; a user step that sets up a new game or repairs one, never run it yourself), `typetorch serve` (CLI 0.11+) and `typetorch mcp` for the Studio loop, the debug macros in `@typetorch/transformer/macros` (transformer 0.3+), goblox (optional, CLI 0.16+) and the darklua production pack (CLI 0.17+). Planned, never promise: content packs, `typetorch test --unit`, `/tt grant`. 9. No CI for the game, ever (the owner's rule): never add `.github/workflows`, actions or hosted CI to the game repo, never suggest them. ## Procedure 1. **Detect.** roblox-ts? (`package.json` with `roblox-ts`, `tsconfig.json`, `.ts`). Plain Luau → stop: "TypeTorch is roblox-ts only." Empty folder → fresh setup (AGENTS.md "Fresh setup path"). Find: framework (Flamework, Knit, singletons), every `*.server.ts`/`*.client.ts`, the Rojo layout, and with `git grep -nE "" -- src`: `PlayerAdded|PlayerRemoving|CharacterAdded`, remotes (`RemoteEvent|RemoteFunction|OnServerEvent|@rbxts/net|@flamework/networking`), tags (`CollectionService|@flamework/components`), loops and threads (`while \(true\)|task\.(spawn|delay|defer)|Heartbeat`), `_G|shared\.`, data (`DataStoreService|ProfileStore|ProfileService`), `BindToClose`, UI, `:Clone()` of templates. 2. **Plan.** Write `MIGRATION_NOTES.md` (inventory, old → new mapping, order of commits, risks: player data always, place content, third-party networking), show it, continue unless told to wait. Log every step there. 3. **Toolchain** (branch `typetorch-migration`): - The reference template next to the game: `../template` (clone https://github.com/typetorch/template there if missing). Every `@typetorch/*` package comes from npm; no other checkouts. - **The template decides the files, npm the versions**: copy its `package.json` deps/devDeps/overrides (`@typetorch/framework`, `@typetorch/kernel`, devDependencies `@typetorch/transformer`, `@typetorch/cli`, `@typetorch/dev-server`; no Flamework) but take the `@typetorch/*` versions from npm (`bun add @latest`, `-d` for the dev ones: the template pins CLI 0.9.1, transformer 0.2.1, framework 0.5.0), and leave out its `rbxts-transform-debug`; `tsconfig.json` (`include` src only, `typeRoots` `@rbxts` + `@typetorch`, `types: ["types","compiler-types"]`, `plugins`: only `@typetorch/transformer`), `default.project.json` (payload: a `Model` with `Server`/`Shared`/`Client`/`include`, mapping `@rbxts` and only `@typetorch/framework`; keep the old one as `legacy.project.json`), `studio.project.json`, `rokit.toml` (rojo 7.7.0-rc.1, lune 0.10.5; then `rokit add seaofvoices/darklua` for the prod pack), `scripts/build-info.ts` (change its `rbxts-transform-debug` import line to `@typetorch/transformer/macros`). Compile only via `bun run build` or `bunx rbxtsc` (`npx rbxtsc` runs a placeholder package in Bun projects on Windows). goblox only if asked (`bun add -d goblox`; it ignores every tsconfig plugin but `@typetorch/transformer`). - Debug macros: `$print`/`$warn`/`$error`/`$assert`/`$dbg` from `@typetorch/transformer/macros`. A game on `rbxts-transform-debug`: drop its tsconfig plugin, rewrite the imports (also in `scripts/build-info.ts`), then `bun remove rbxts-transform-debug`. - Scripts: `build` = `bun scripts/build-info.ts && rbxtsc` (it must end with the compiler), `watch`, `studio` = `rojo serve studio.project.json`, `typetorch` = `typetorch`. Leave out `packages`, `postinstall` and `scripts/packages.ts` (an optional local override for unreleased framework/kernel changes; only if the user asks). - Bun only (delete other lockfiles). `rokit install`, then `bun install`. - `.gitignore`: `node_modules/ out/ include/ *.tsbuildinfo src/shared/build.ts .typetorch/ .payload.gen.project.json .tsconfig.typetorch.json .env .env.*`. - `typetorch.json`: `project`, `universeId`, `placeId`, `creator` (`{groupId}` or `{userId}`: the experience owner), `defaultBranch: "prod"`, `branches: {"main": "prod"}`, `channels: {"prod": "prod"}`, `members: {}`, `devBadgeId: null`, `approval: "prod"`, `kernel: "node_modules/@typetorch/kernel"`. Never copy the template's signing fields. Servers see `members`/`revoked`/`devBadgeId` only after the user's `typetorch access push` (kernel 0.3.8+): list it whenever they change. - `src/server/boot.ts` → `startServer(kernel, { modules: [script.Parent!.FindFirstChild("services")!], build: BUILD })`; `src/client/boot.ts` → `startClient(... "controllers" ...)`; `BUILD` from `../shared/build` (generated). - `bun run build`, commit. It passes for Knit/plain projects; a Flamework project fails on its `@flamework/core` imports ("only npm scopes listed in your typeRoots") until step 4 removes them: expected. 4. **Migrate**, one commit per step, `bun run build` after each: - Delete entry scripts, `Flamework.ignite/addPaths`, `Knit.Start`. The payload may hold only Folders and ModuleScripts. - Services/controllers → `@Service()`/`@Controller()` from `@typetorch/framework`, `extends Module`, constructor injection with `super()`. Knit `KnitInit/KnitStart` → `onInit/onStart`; `GetService` → injection. - **Flamework projects are mostly a swap:** same decorator and lifecycle names, imports from `@typetorch/framework` (also `Modding`, `Reflect`, `t`; custom decorators use `@metadata typetorch:parameters injectable`), `extends Module` + `super()`, `@flamework/networking` → `createNetwork` (`predict` → `emit`, `invokeWithTimeout` in seconds: the codemod keeps the arguments, so grep for it and turn millisecond values like `5000` into seconds), components → observers. `Dependency()` stays (from `@typetorch/framework`): the cycle breaker (with `Lazy`) and the way plain classes reach modules, from `onInit` on; move calls in constructors, field initializers and module top level into methods. Then `bun remove` every `@flamework/*` and `rbxts-transformer-flamework`, delete `flamework.build`, `flamework.json`, `include/flamework`. Type ids changed format: data saved under Flamework ids won't match (flag it). The swap-safety pass is the real work. - Swap safety: everything in `this.trove`, and no cleanup function calls `trove.remove`/`add`/`extend` (it throws while cleaning; before framework 0.5.2 that aborts the whole generation stop; a child from `trove.extend()` is cleaned by its parent anyway); `this.ctx.persist`/`playerState` and `Dependency()` assigned in `onInit` or `onStart`, never in field initializers or constructors; libraries with module-level setup (Vide's stepper, TopbarPlus, anything that connects or makes GUIs when required) stepped from the trove or loaded once outside the payload; looped animations and cutscenes persisted and resumed after a swap; `TypeTorch.onSwapOut` (runs before any cleanup) for last-resort saves; no module-level state (instance fields, or `this.ctx.persist("key.v1", () => init)` with plain data only; per-player maps via `this.ctx.playerState("key.v1", init)`, removed on a real leave); players via `onPlayerAdded(player, playerTrove)` / `observePlayers`, idempotent (persisted set for one-time effects), real leaves via `this.trove.connect(Players.PlayerRemoving, …)`; tags/characters via `observeElement` or `@rbxts/observers` (stop function in the trove); loops only in `onStart` or `this.trove.add(task.spawn(…))`; no `_G`/`shared`; `task.*` through the trove; `onStop` runs at shutdown (kernel 0.3.2) but not when a server closes mid-swap, so it is for short extras, never the only place data is saved (a `BindToClose` that must stay binds once per server); keep `onInit` short (a new server's boot waits about 6 s). - Networking: one `src/shared/net.ts` with `createNetwork()`; server `.on`/`.handle` (returns `[value]` or `[false, reason]`)/`.fire...`, client `.fire`/`.invoke`/`.on`; every disconnect into the trove; delete all remotes; no template literal types. - UI: code-built in the trove; Studio-built stays in StarterGui, tagged and driven by `observeElement`; charm atoms per generation (persist plain values); `popIn/popOut/bump`; one `PopupQueue`. - Player data: the library lives in the place (`ServerStorage.Packages.` + a `DataHost` Script, user steps), handles in `persist`, load on join, release on real leave, store names split by `TypeTorch.channel`. Library loads, saves and releases run as jobs on DataHost's thread (`library.TypeTorchJobs`), or with `TypeTorch.runDetached` when the place runs kernel 0.3.8+ (the guide's option B; DataHost then only requires the library): a deploy stops the generation's threads mid-call, which jams the library for that player. ProfileStore or ProfileService: use the Player data guide's `DataService` for that library (keep its `TypeTorchTest` line: place scripts never run in the cloud test, so waiting for `DataHost` there fails every prod deploy). Developer products: the PurchaseId goes into the profile with the grant, `PurchaseGranted` only after a save holds it (`grantOnce`), never only `persist`. Others: wrap unchanged and flag. - The cloud test runs `onInit`/`onStart` against the live game's data (real DataStores, MemoryStores, MessagingService, HTTP; no players; `TypeTorch.channel` is `dev` there with CLI 0.7.3 or newer, so only channel-split stores point at dev data; the `AnalyticsEngine` sends nothing): guard global resets, raw MessagingService publishes and "server started" rows with `workspace:GetAttribute("TypeTorchTest")`, and list the guards in `MIGRATION_NOTES.md`. Move MessagingService topics to `TypeTorch.messaging.subscribe/publish` (kernel 0.3.8; one kernel-held topic, no re-subscribe per swap, dev branches don't reach prod, a no-op in the cloud test); messages stay under 1 KiB. - Hot assets only if asked: `hotAsset(key, template)`. Analytics only if asked: `new AnalyticsEngine()` on server and client, in a low-`loadOrder` module's `onInit` (it starts on the first construction; its backend is a user step). 5. **Checks:** `bun run build`; `bun run typetorch build` (prints `built ... modules`); `out/shared/net.luau` has `t.` guards; the pattern scan prints nothing: `git grep -nE "Players\.PlayerAdded\.Connect|new Instance\(\"(Remote|UnreliableRemote)(Event|Function)\"\)|_G\b|@flamework/|Flamework\.(ignite|addPaths)|Knit\.Start" -- src`; review every hit of `git grep -nE "trove\.add\(\(\) =>.*\.(remove|add|extend)\(|invokeWithTimeout\(" -- src` by hand; commit, rebuild: no `-dirty`; `bun run typetorch build --branch prod`; `rojo build studio.project.json -o .typetorch/studio-check.rbxl`. 6. **Stop** at user actions (rule 2). 7. **Finish** with "What you need to do" (numbered, filled in): fill the ids; Game Settings (HTTP on, Studio API access on); create the Open Cloud key (`asset:read`, `asset:write`, Luau Execution read/write (the cloud test before every prod deploy), `universe-messaging-service:publish`, DataStore `universe-datastores.objects:read` + `:create` + `:update` (the shared deploy number and the signed settings: `access push`, `backend setup`), and the place key's Luau Execution scopes (`universe.place.luau-execution-session:read` and `:write`) plus `asset:read` for `kernel deploy` (`universe.place:write` only to publish a place file: `--replace-place`, `--place-file`, `kernel restore `); no `universe:write` / `universe:read`, and not `legacy-asset:manage`, which API keys can't get today; put `OPENCLOUD_API_KEY=` in the game repo's `.env` (gitignored); `bun run typetorch doctor`; `bun run typetorch keys init` + `keys init --fallback`, commit, back up the key files and the `.env` offline; members in `typetorch.json`, then `bun run typetorch access push` (again after every change); kernel into the place (new place: `kernel deploy --dry-run` then `--replace-place --yes`; place with content: `kernel deploy --dry-run --install` patches the live place with no download when its "Allow place to be updated using Save Place API" setting is on, else File > Download a Copy and `kernel deploy --dry-run --install --place-file --base `; check the summary, then the same without `--dry-run`; or copy the three kernel folders from `.typetorch/place.rbxl` in Studio and publish); `ServerScriptService.LoadStringEnabled` off in a live game (on only in a test place for remote-claude's `run_luau`; `doctor` reports it); remove the old scripts in Studio just before the first deploy; data library + `DataHost` in the place; test in Studio (the TypeTorch Studio plugin + `bun run typetorch serve`, Play); check F9 `[TypeTorch] kernel ...`; dev branch deploy + `/tt new dev` + two deploys while playing (+ a product bought during a deploy; after each deploy read Server > Status "Health window: n/3 errors": 3 errors in 30 s roll every server back, so fix them or set `typetorch.json` `"health": { "errors": ... }` above the count, kernel 0.3.7+); a game with live players: the go-live checklist (docs `guides/go-live-checklist.md`) before the first prod deploy; first prod deploy from `main` (cloud test, y/N, signed); rollback drill; optional: the fleet API and analytics. Then post the report (template in AGENTS.md). ## Kernel updates (only when the user asks) Manual, and the one flow where you run `kernel deploy`. Run `bun run typetorch kernel deploy --dry-run` (it patches the kernel folders and the kernel's settings into the place's newest published version and saves nothing), read the summary (only the kernel folders may change), show it and ask. After the user's yes, the same command without `--dry-run` plus `--yes` saves and publishes through Luau Execution, with no download; that needs the place's "Allow place to be updated using Save Place API" setting on. Undo: `bun run typetorch kernel restore --version `. If that setting is off (a Studio-made place), the user downloads a copy in Studio (File > Download a Copy) and gives you the file and its place version; then `kernel deploy --dry-run --place-file --base ` and, after the user's yes, the same with `--yes` (`kernel restore ` undoes it). Or, with the Roblox Studio MCP and the place open, replace the three kernel folders in Studio from `node_modules/@typetorch/kernel` and the user publishes from Studio. Then the user joins a fresh server: F9 shows `[TypeTorch] kernel `. Details: AGENTS.md "Updating the kernel in a game (agents)". --- # What's new Every TypeTorch package's recent releases, newest first. Each entry is a change that went into that version. Update a game's packages with `bun update @typetorch/framework` (it ships inside every build, so the next deploy carries it); a new **kernel** also needs `typetorch kernel deploy` and a place publish, since the kernel lives in the place. ## Latest versions | Package | Version | Released | | --- | --- | --- | | [@typetorch/framework](https://www.npmjs.com/package/@typetorch/framework) | [0.7.5](https://www.typetorch.dev/whats-new.md#framework-075) | 2026-11-30 | | [@typetorch/kernel](https://www.npmjs.com/package/@typetorch/kernel) | [0.5.9](https://www.typetorch.dev/whats-new.md#kernel-059) | 2026-11-30 | | [@typetorch/cli](https://www.npmjs.com/package/@typetorch/cli) | [0.19.0](https://www.typetorch.dev/whats-new.md#cli-0190) | 2026-11-15 | | [@typetorch/transformer](https://www.npmjs.com/package/@typetorch/transformer) | [0.3.2](https://www.typetorch.dev/whats-new.md#transformer-032) | 2026-10-27 | | [@typetorch/dev-server](https://www.npmjs.com/package/@typetorch/dev-server) | [0.3.3](https://www.typetorch.dev/whats-new.md#dev-server-033) | 2026-10-22 | | Studio plugin | [0.7.1](https://www.typetorch.dev/whats-new.md#studio-plugin-071) | 2026-10-28 | ## Recent releases | Date | Package | Version | Highlights | | --- | --- | --- | --- | | 2026-11-30 | Framework | [0.7.5](https://www.typetorch.dev/whats-new.md#framework-075) | TypeTorch.reserveServer: a reserved server on this server's branch for the game's own teleport (kernel 0.5.9) (+1 more) | | 2026-11-30 | Kernel | [0.5.9](https://www.typetorch.dev/whats-new.md#kernel-059) | api:reserveServer: the game's own reserved servers boot this server's branch (+1 more) | | 2026-11-18 | Framework | [0.7.3](https://www.typetorch.dev/whats-new.md#framework-073) | Extended recording 0.7.3: UIGradient transparency / offset, UIScale text sizes, CanvasGroup group ([#26](https://github.com/typetorch/framework/pull/26)) (+2 more) | | 2026-11-15 | CLI | [0.19.0](https://www.typetorch.dev/whats-new.md#cli-0190) | backend migrate status: the to-basin 'sent' day state, finish lines for the Basin directions ([#45](https://github.com/typetorch/cli/pull/45)) (+2 more) | | 2026-11-15 | Framework | [0.7.2](https://www.typetorch.dev/whats-new.md#framework-072) | Extended recording: tt-ext-1 recorder, replay API, tt_extended_recording experiment ([#24](https://github.com/typetorch/framework/pull/24)) (+1 more) | | 2026-11-15 | Framework | [0.7.1](https://www.typetorch.dev/whats-new.md#framework-071) | Live debug: remoteDebug.command / stream and fleet.column (+4 more) | | 2026-11-15 | Kernel | [0.5.7](https://www.typetorch.dev/whats-new.md#kernel-057) | Live debug: send the declarations as xd, not x (x = 1 is the A/B experiment flag) (+2 more) | | 2026-11-14 | Framework | [0.7.0](https://www.typetorch.dev/whats-new.md#framework-070) | TypeTorch.feedback: player feedback as a built-in ([#16](https://github.com/typetorch/framework/pull/16)) | | 2026-11-08 | Framework | [0.6.3](https://www.typetorch.dev/whats-new.md#framework-063) | Analytics: the player policy (pol_*) on the join row, Player.DeviceTrustLevel (trust) on the join and leave rows | | 2026-11-07 | CLI | [0.18.1](https://www.typetorch.dev/whats-new.md#cli-0181) | notify: say how to start when notifications or a kind are missing | | 2026-11-07 | CLI | [0.18.0](https://www.typetorch.dev/whats-new.md#cli-0180) | notify tests: config rules, each request, key rotate order and failure paths, templates, pause/resume (+2 more) | | 2026-11-07 | Framework | [0.6.2](https://www.typetorch.dev/whats-new.md#framework-062) | Devtools: the DEV toggle sits in Roblox's top bar row (GuiService.TopbarInset), not on a game's top-left HUD | | 2026-11-07 | Framework | [0.6.1](https://www.typetorch.dev/whats-new.md#framework-061) | notifications: setOff(user, kinds), a player's switched-off kinds (prefs) (+4 more) | | 2026-11-07 | Framework | [0.6.0](https://www.typetorch.dev/whats-new.md#framework-060) | Analytics join row: the full join metadata (+2 more) | | 2026-11-04 | Framework | [0.5.7](https://www.typetorch.dev/whats-new.md#framework-057) | Command palette: drop the hotkey's k if it lands in the search box (+1 more) | | 2026-11-02 | CLI | [0.17.1](https://www.typetorch.dev/whats-new.md#cli-0171) | Pack keeps the compiler's header comment | | 2026-11-02 | CLI | [0.17.0](https://www.typetorch.dev/whats-new.md#cli-0170) | Declare --no-minify on build, upload and deploy (+1 more) | | 2026-11-02 | Kernel | [0.5.6](https://www.typetorch.dev/whats-new.md#kernel-056) | Devtools reach devs only: leave the framework's devtools off the shared client tree (+2 more) | | 2026-10-30 | CLI | [0.16.0](https://www.typetorch.dev/whats-new.md#cli-0160) | Maintenance release | | 2026-10-28 | Studio plugin | [0.7.1](https://www.typetorch.dev/whats-new.md#studio-plugin-071) | Remove run_luau from the plugin: it never runs code it receives | ## Framework `@typetorch/framework` on [npm](https://www.npmjs.com/package/@typetorch/framework), [releases on GitHub](https://github.com/typetorch/framework/releases), [reference](https://www.typetorch.dev/reference/framework). ### Framework 0.7.5 {#framework-075} *2026-11-30* - TypeTorch.reserveServer: a reserved server on this server's branch for the game's own teleport (kernel 0.5.9) - Framework version everywhere it can be checked: a built-in Fleet column, ext_start's fw, the dev panel ### Framework 0.7.3 {#framework-073} *2026-11-18* - Extended recording 0.7.3: UIGradient transparency / offset, UIScale text sizes, CanvasGroup group ([#26](https://github.com/typetorch/framework/pull/26)) - Extended recording: the game's AFK flag pauses only until the next input; say plainly what player data is collected ([#25](https://github.com/typetorch/framework/pull/25)) - Command palette: Enter confirms two-step commands again ### Framework 0.7.2 {#framework-072} *2026-11-15* - Extended recording: tt-ext-1 recorder, replay API, tt_extended_recording experiment ([#24](https://github.com/typetorch/framework/pull/24)) - Analytics: honour Retry-After on 429/503, optional backend.ingest URL ([#23](https://github.com/typetorch/framework/pull/23)) ### Framework 0.7.1 {#framework-071} *2026-11-15* - Live debug: remoteDebug.command / stream and fleet.column - Experiments: pick your own variant in the dev menu, vi on experiment rows ([#19](https://github.com/typetorch/framework/pull/19)) - analytics: positions on events (px/py/pz) and a configurable recording window (recordSeconds) - Scheduled live events: liveConfig follows the signed game["tt.events"] schedule - Join events carry the player's language (Player.LocaleId as props.locale) ### Framework 0.7.0 {#framework-070} *2026-11-14* - TypeTorch.feedback: player feedback as a built-in ([#16](https://github.com/typetorch/framework/pull/16)) ### Framework 0.6.3 {#framework-063} *2026-11-08* - Analytics: the player policy (pol_*) on the join row, Player.DeviceTrustLevel (trust) on the join and leave rows ### Framework 0.6.2 {#framework-062} *2026-11-07* - Devtools: the DEV toggle sits in Roblox's top bar row (GuiService.TopbarInset), not on a game's top-left HUD ### Framework 0.6.1 {#framework-061} *2026-11-07* - notifications: setOff(user, kinds), a player's switched-off kinds (prefs) - SCHEMA.md and README: jd and the joinData setting - Analytics join row: the raw join data as jd, privacy-safe - Command palette: Migrate all players to a new server - Command palette: Switch to dev branch; Player: Teleport to, Bring, Respawn ### Framework 0.6.0 {#framework-060} *2026-11-07* - Analytics join row: the full join metadata - Native experience notifications: TypeTorch.notifications - Move SHA-256 / HMAC to util/sha256 (devtools re-exports it) ### Framework 0.5.7 {#framework-057} *2026-11-04* - Command palette: drop the hotkey's k if it lands in the search box - Dev menu command palette (Ctrl+K / Cmd+K) ## Kernel `@typetorch/kernel` on [npm](https://www.npmjs.com/package/@typetorch/kernel), [releases on GitHub](https://github.com/typetorch/kernel/releases), [reference](https://www.typetorch.dev/reference/kernel). ### Kernel 0.5.9 {#kernel-059} *2026-11-30* - api:reserveServer: the game's own reserved servers boot this server's branch - Fleet heartbeats carry region: game.ServerRegion, the data center's IATA code ([#17](https://github.com/typetorch/kernel/pull/17)) ### Kernel 0.5.7 {#kernel-057} *2026-11-15* - Live debug: send the declarations as xd, not x (x = 1 is the A/B experiment flag) - Live debug: game columns, commands, streams and the live map - No false health_failed alerts during swaps and slow boots ([#14](https://github.com/typetorch/kernel/pull/14)) ### Kernel 0.5.6 {#kernel-056} *2026-11-02* - Devtools reach devs only: leave the framework's devtools off the shared client tree - Refuse a payload without Server.boot / Client.boot - Heartbeat: send the place version (pv) ### Kernel 0.5.5 {#kernel-055} *2026-10-23* - Live reload: watch the local payload through each script's Changed signal ### Kernel 0.5.4 {#kernel-054} *2026-10-22* - 0.5.4: live reload in a Studio playtest - Kernel 0.5.3: debug bundles sent by the server itself - Kernel 0.5.2: boot waits for a running swap instead of failing every candidate - Branch list: each branch's own channel as branchChannel ### Kernel 0.5.1 {#kernel-051} *2026-10-09* - Kernel 0.5.1 README: remote debug and the instant wake, its tests - Kernel 0.5.1: instant remote debug wake ({ k = "rd", j = JobId } on TypeTorch/deploy starts the poll at once; other JobIds and malformed wakes ignored; one per RD_WAKE_GAP s; wakes counted in RemoteDebug.info) ### Kernel 0.5.0 {#kernel-050} *2026-10-09* - Kernel 0.5.0 remote debug tests: Lune test-remote-debug (55: allow-list, owners only, rate, secret scrub, plain data, session lifecycle, 401 hold, timeouts, client logs) and smoke --remote-debug (26); scrub covers both JSON escapes ### Kernel 0.4.2 {#kernel-042} *2026-10-09* - Kernel 0.4.2: README (server TPS, seq adoption, tests) and test headers ### Kernel 0.4.0 {#kernel-040} *2026-10-09* - Kernel 0.4.0: one backend (settings.backend), error reports, the budget view ### Kernel 0.3.9 {#kernel-039} *2026-10-09* - Kernel 0.3.9: stuck "Starting..." fixed, channel vs rules, /tt rollback on a fresh server, fleet backoff ## CLI `@typetorch/cli` on [npm](https://www.npmjs.com/package/@typetorch/cli), [releases on GitHub](https://github.com/typetorch/cli/releases), [reference](https://www.typetorch.dev/reference/cli). ### CLI 0.19.0 {#cli-0190} *2026-11-15* - backend migrate status: the to-basin 'sent' day state, finish lines for the Basin directions ([#45](https://github.com/typetorch/cli/pull/45)) - backend setup --analytics basin\|duckdb, --ingest, backend migrate ([#44](https://github.com/typetorch/cli/pull/44)) - typetorch keys create / list / revoke: named API keys with roles on the backend ([#42](https://github.com/typetorch/cli/pull/42)) ### CLI 0.18.1 {#cli-0181} *2026-11-07* - notify: say how to start when notifications or a kind are missing ### CLI 0.18.0 {#cli-0180} *2026-11-07* - notify tests: config rules, each request, key rotate order and failure paths, templates, pause/resume - typetorch notify: push, status, templates, test, send, key rotate, pause, resume; doctor's scope probe - Notifications config, backend.notify in the settings record, notify backend calls ### CLI 0.17.1 {#cli-0171} *2026-11-02* - Pack keeps the compiler's header comment ### CLI 0.17.0 {#cli-0170} *2026-11-02* - Declare --no-minify on build, upload and deploy - Production pack: strip, __DEV__ define and story shake before rojo ### CLI 0.16.0 {#cli-0160} *2026-10-30* - Maintenance release (packaging, docs or tests only). ### CLI 0.15.0 {#cli-0150} *2026-10-27* - Revert "release 0.12.2" - assets status --json: a bounded per-asset diff for the Studio plugin ### CLI 0.14.0 {#cli-0140} *2026-10-27* - Maintenance release (packaging, docs or tests only). ### CLI 0.12.2 {#cli-0122} *2026-10-27* - assets status --json: a bounded per-asset diff for the Studio plugin - Generate build.ts against @typetorch/transformer's own macros - serve: restart Rojo when a $path folder is deleted and recreated - serve: Rojo moves off a port another process took; a killed serve's leftover children are stopped by the next one - serve: the game's live script runs by default (when package.json has one); --no-live turns it off - serve --claude: Apply and Deploy to dev for the Studio Claude tab ### CLI 0.12.1 {#cli-0121} *2026-10-22* - serve --claude: document the owners default for --claude-users ## Transformer `@typetorch/transformer` on [npm](https://www.npmjs.com/package/@typetorch/transformer), [releases on GitHub](https://github.com/typetorch/transformer/releases), [reference](https://www.typetorch.dev/reference/transformer). ### Transformer 0.3.2 {#transformer-032} *2026-10-27* - Keep the comments of a dropped macro import (file headers) on the next statement - Built-in debug macros ($print, $warn, $git, ...) replacing rbxts-transform-debug ### Transformer 0.3.1 {#transformer-031} *2026-10-27* - Maintenance release (packaging, docs or tests only). ### Transformer 0.3.0 {#transformer-030} *2026-10-27* - Stop type-checking every file before transforming it ### Transformer 0.2.2 {#transformer-022} *2026-10-22* - Maintenance release (packaging, docs or tests only). ### Transformer 0.2.1 {#transformer-021} *2026-10-06* - 0.2.1: Lazy<T> constructor parameters, network leaf diagnostics - Network leaf diagnostics: @metadata macro network names the leaf in guard errors, warns on generic leaves and values that never arrive - Lazy<T> constructor parameters record lazy:<id of T> - Remove GitHub Actions: TypeTorch doesn't use them (owner decision: supply-chain risk) - 0.2.0: npm-ready; fixture mirrors the framework layout and runs under Lune - Strip down and retarget to TypeTorch (@typetorch/transformer 0.1.0) - Import kept sources from rbxts-transformer-flamework (MIT) ## Dev server `@typetorch/dev-server` on [npm](https://www.npmjs.com/package/@typetorch/dev-server), [releases on GitHub](https://github.com/typetorch/dev-server/releases), [reference](https://www.typetorch.dev/reference/dev-server). ### Dev server 0.3.3 {#dev-server-033} *2026-10-22* - remote-claude: default --users to the owners in typetorch.json ### Dev server 0.3.2 {#dev-server-032} *2026-10-22* - Maintenance release (packaging, docs or tests only). ### Dev server 0.3.1 {#dev-server-031} *2026-10-22* - Maintenance release (packaging, docs or tests only). ### Dev server 0.3.0 {#dev-server-030} *2026-10-22* - remote-claude: --no-clipboard - remote-claude: --no-tunnel, and a session file for local clients ### Dev server 0.2.3 {#dev-server-023} *2026-10-09* - 0.2.3: README examples without user-folder paths (the package check refuses them) ### Dev server 0.2.2 {#dev-server-022} *2026-10-09* - 0.2.2: Docker image files, keys from the game repo's .env - Read keys like the TypeTorch CLI 0.9: the game repo's .env (override: --env-file / TYPETORCH_ENV_FILE); TYPETORCH_API_KEY is no Open Cloud key - Docker image for remote-claude: one container for the dev-server ### Dev server 0.2.1 {#dev-server-021} *2026-10-06* - Logs > Upload: POST /v1/logs saves game logs to <repo>/.typetorch/logs (no Claude, no prompt quota) - Show the pairing code as soon as the tunnel URL exists; say when game servers were announced - 0.2.1: remember --users per game repo (.typetorch/remote-claude.json) - Remove GitHub Actions: TypeTorch doesn't use them (owner decision: supply-chain risk) - Run under plain Node: npm-ready build; read TYPETORCH_ENV_FILE - Screenshot marks: body cap 160 KB so any in-cap drawing fits - Scrub the CLI's signing key variables from every child env - Screenshot marks: strokes drawn before the crop and the downscale - Screenshot pickup: match script captures saved as wob-<n> - Deploy signing removed; the deploy card can say "waiting for approval" - Toolbox gate wired in: the chip on prompts, allow/deny rules, MCP list and per-call checks, insert requests ## Studio plugin [releases on GitHub](https://github.com/typetorch/studio-plugin/releases), [reference](https://www.typetorch.dev/reference/studio-plugin). ### Studio plugin 0.7.1 {#studio-plugin-071} *2026-10-28* - Remove run_luau from the plugin: it never runs code it receives ### Studio plugin 0.7.0 {#studio-plugin-070} *2026-10-27* - panel: a Diff button per changed hot asset, and an automatic check every 30 s - Show Disconnected after a drop, re-check hot assets on reconnect, clearer Server card - A copy of the plugin inside a place does nothing (no plugin global) instead of erroring - Claude tab: Claude reads and edits the open place (inspect, find, output, status, run_luau as one undo step) - Claude tab: Apply, Deploy to dev and Discard on a change; a change lost to a restart says so - Toolbar icons: the state icons and a Claude icon, plus an uploader - Update README.md ### Studio plugin 0.6.1 {#studio-plugin-061} *2026-10-22* - plugin: probe serve's control ports one at a time, so Studio asks for one HTTP permission, not eight ### Studio plugin 0.6.0 {#studio-plugin-060} *2026-10-22* - Claude window: Studio sends Code only; Live points to the in-game tab - Claude window: images, Play screenshots, closed TypeTorch panel in Play - Plugin: the Claude composer wraps and grows; playtest windows dock left at the last width - Plugin: Claude window shows Toolbox results and drops emojis - Plugin: Claude stream reconnects on its own loop - Plugin: Claude window lists recent chats and copies replies - Plugin: Claude window gets the Live/Code pill and the "+" menu - Plugin: Claude window streams the running prompt over serve's WebSocket - Plugin: playtest windows open docked on the right, connect within seconds - Claude window: use serve's chat API (conversation, prompt ids and texts) - Plugin: keep windows open and connected in Play; chat follows Edit/Play - Plugin: keep the toolbar and windows during Play - Claude window: port the in-game Claude tab 1:1; pairing link box --- > Synced from the [cli README](https://github.com/typetorch/cli/blob/main/README.md). TypeTorch logo # @typetorch/cli `typetorch` builds a roblox-ts game into a payload, uploads it to Roblox as a private Model asset, and hot-swaps it into live servers without a restart. It also promotes and rolls back already uploaded builds, lists deployments with their git identity, checks and publishes the kernel place, and syncs **hot assets** (models and UI templates that builders edit in the place) into the artifact. **Every deploy is approved by a person** (`typetorch approve`); agents and the remote-claude dev-server only prepare them. **Prod-channel deploys are signed** with two Ed25519 keys, so live prod servers only run what you published. **A cloud test gates prod deploys**: the uploaded payload boots headless in the place before anything is published. `typetorch servers` and `typetorch report` show the live fleet and what each server did with a deploy. Part of TypeTorch: the kernel (`@typetorch/kernel`) is baked into the place and swaps payloads; the framework (`@typetorch/framework`) ships inside every payload. ## Install The CLI runs on **Node 20+** (npm, npx) or **Bun 1.3+**; you don't need both to run it. ```sh npm i -g @typetorch/cli # then: typetorch (or the short alias: tt ) npx @typetorch/cli # no install bun add -d @typetorch/cli # in the game repo, then: bunx typetorch bun src/index.ts # from a checkout of this repo ``` The package installs two names for the same binary, `typetorch` and the short `tt` (CLI 0.12); every `typetorch` below works as `tt` too (`tt deploy`, `tt serve --remote`). The [template](https://github.com/typetorch/template) already has `@typetorch/cli` (and `@typetorch/dev-server`) in its devDependencies and the script `"typetorch": "typetorch"`: after `bun install`, `bun run typetorch ` runs it. What the commands call: - **git**, and **Rojo 7.7.x** (plus **Lune** for `kernel deploy`) through [Rokit](https://github.com/rojo-rbx/rokit): pin `rojo-rbx/rojo@7.7.0-rc.1` in the game's `rokit.toml`. **darklua** (`rokit add seaofvoices/darklua`) for the production pack of `build` / `deploy` / `upload` (see "Builds"); without it payloads go up unminified, with a warning. - **Bun** for `typetorch build` / `deploy` / `upload`: the game repo is a Bun project and the build runs `bun run build` (or `bun run rbxtsc`, or `bun run goblox`: see "Compiler") in it. Commands that don't build (`approve`, `promote`, `rollback`, `deployments`, `keys`, `pin`, `assets status`, `doctor`) don't need it. - **zstd** for hot assets (`assets sync` / `status`, which read Roblox-serialized exports): Bun, or Node 22.15+. `typetorch doctor` reports the runtime, Bun and zstd. ### `typetorch` on PATH (from a checkout) `bin/typetorch.cmd` (cmd.exe and PowerShell) and `bin/typetorch` (bash/zsh) run this checkout with Bun (`bin/tt.cmd` and `bin/tt` are the same, shorter). Add `bin/` to your user PATH once, then open a new terminal. PowerShell, for this machine's checkout: ```powershell [Environment]::SetEnvironmentVariable("Path", [Environment]::GetEnvironmentVariable("Path", "User") + ";\typetorch-cli\bin", "User") ``` Alternatively `bun link` in this folder, then `bun link @typetorch/cli` in a game repo (that puts it on the repo's `bunx typetorch`, not on PATH). ## Setup **New game: `bunx @typetorch/cli init` in an empty folder.** The guided setup asks one question at a time and does the rest: the tools, the starter template, your experience (paste its URL), the Open Cloud key (probed, written to the game repo's `.env`), the owner, `typetorch.json`, the two prod signing keys and the key asset, the kernel place, an optional backend (a VPS with Coolify or a plain systemd service with Caddy, over SSH; this PC behind a free Cloudflare quick tunnel, or one you already run), the first prod deploy and a dev branch, and `AGENT_PROMPT.md` for your coding agent. Each step says why it exists and which doc it replaces, and checks its result the way `typetorch doctor` would. Stopped half way? Run it again: `.typetorch/init.json` (never a secret) records what is done. `typetorch init --phase ` runs one step again; `--answers ` replays answers for scripts (a secret never comes from the file). By hand, a game repo has `typetorch.json` next to `default.project.json`: ```jsonc { "project": "my-game", "universeId": 123, "placeId": 456, "creator": { "groupId": 789 }, // or { "userId": 1 }: the experience owner (LoadAsset refuses other owners) "defaultBranch": "prod", "branches": { "main": "prod" }, // git branch -> TypeTorch branch (default: lowercased, "/" -> "-") "channels": { "prod": "prod" }, // branch -> "prod" | "dev" (default: prod for defaultBranch, else dev) "members": { "123456789": "owner" }, // userId -> owner | dev (owners also default remote-claude's --users) "revoked": { "987654321": true }, // userIds refused dev access whatever else says (`access push`) "devBadgeId": null, "kernel": "node_modules/@typetorch/kernel", "approval": "all", // "all" (default) | "prod" | "none": which deploys need `typetorch approve` // written by `typetorch keys ...` (public keys only; commit them): "signingPublicKeys": ["…"], // trusted main keys = the key asset's PublicKeys "revokedKeys": [], // = the key asset's RevokedKeys "fallbackPublicKey": "…", // baked into the place by `kernel deploy` "keyAssetId": 123, // the key asset; `kernel deploy` stamps it "backend": { "url": "https://backend.example.com" }, // the TypeTorch backend (`typetorch backend setup` writes it) // optional safety thresholds (see "Health window and auto-rollback settings"): "health": { "errors": 3, "window": 30, "rollback": true, "dev": { "rollback": false } }, "autoRollback": { "failedPct": 20 }, // optional: the place's backup build (see "Backup build"); these are the defaults "backup": { "refresh": "auto", "healthyHours": 3 }, // optional: "goblox" (needs `bun add -d goblox`) | "rbxtsc"; unset: goblox when installed, else rbxtsc (see "Compiler") "compiler": "goblox" } ``` Gitignore `.env`, `.typetorch/`, `src/shared/build.ts`, `.payload.gen.project.json` and `.tsconfig.typetorch.json`. **Secrets go in the game repo's `.env`, everything else in `typetorch.json`** (CLI 0.9, plans/21). `typetorch doctor` lists every value the CLI reads and where it came from (Config). ### Health window and auto-rollback settings - `"health"`: on each server a new build is rolled back when its own scripts throw `errors` errors (1-100, default 3) within `window` seconds of starting (5-300, default 30), or an `onStart` fails. `"rollback": false` keeps a failing build running: the server only reports `degraded` (a `health_degraded` alert). `"prod"` and `"dev"` override any of the three for builds of that channel. Per channel, not per branch: the values ride the build, and `promote` moves a build between branches without a rebuild. - Every build stamps the result on the payload root as `HealthErrors`, `HealthWindow` and `HealthRollback` (the defaults when unset). Kernel 0.3.7+ reads them when it mounts the build; older kernels ignore them (3, 30 s, on). Prod payloads are signed deploys of your own uploads, so the values are trusted like the code. - `"autoRollback": { "failedPct": 20 }`: `--wait` rolls the branch back when this % (1-100) of the servers that tried the build report `failed` or `rolled_back`. `--rollback-at ` overrides it for one command. - `build` and `deploy` print the health line; `deploy` prints the auto-rollback line; `doctor` shows both. - A noisy game: measure first. Deploy to a dev branch, play, and count your errors in the first 30 s (dev menu > Server > Status shows "Health window: errors / limit, time left"). Then set `errors` above that, or fix the errors. ### Keys Keys are read from, highest priority first: the real environment; the **game repo's `.env`** (next to typetorch.json: `--config`'s folder, else the nearest folder with typetorch.json at or above the working directory). No other `.env` is read (before CLI 0.9 every parent folder's `.env` counted). `--env-file ` or `TYPETORCH_ENV_FILE` (real environment) is an override: that file is read **instead of** `.env`. A `TYPETORCH_ENV_FILE=` line inside the game's `.env` (the CLI 0.8 layout) is still followed (through 0.19.0), with a warning: move the keys into `.env`. Values Bun auto-loads from `.env*` files count as that file, not as the environment. Nothing read from a file is copied into `process.env`, a key goes only into the client for its job, and child processes (rbxtsc, rojo, lune, bun scripts, git) get an allowlisted environment without any key. Keys are never printed. | Variable | Used for | Scopes | |---|---|---| | `OPENCLOUD_ASSETS_KEY` | payload uploads and moderation (`deploy`, `upload`); the cloud test (`test --cloud`, the prod gate); hot assets (`assets sync`, `assets status`); doctor's place check | `asset:read` (also on the place), `asset:write`; `universe.place.luau-execution-session:read` + `:write` for the cloud test, hot assets and doctor | | `OPENCLOUD_DEPLOY_KEY` | deploy messages and the shared seq (`deploy`, `rollback`, `promote`, `keys resign`); the signed settings record (`settings`, `access push`, `backend setup`, `keys rotate` / `resign`) | `universe-messaging-service:publish`; `universe-datastores.objects:read` (+ `:create` and `:update` to claim seqs, store the durable head and write the settings; see "The shared seq", "The durable head" and "Settings"). No `universe:write` / `universe:read`: nothing is kept in ConfigService since CLI 0.8 / kernel 0.3.8 | | `OPENCLOUD_PLACE_KEY` | `kernel deploy`, `kernel restore` (manual only) | `universe.place.luau-execution-session:read` + `:write` (the default luau engine: Luau Execution tasks patch and save the place) and `asset:read` (place versions); `universe.place:write` only to publish files (`--place-file`, `kernel restore `, `--replace-place`). **Roblox has no API-key route for downloading place files**: Asset Delivery needs `legacy-asset:manage`, which can't be granted to API keys, and `universe.place:read` shipped but only covers the place version history (`/place-version-history-api/v1/{placeId}/history`, `/contributors`; a key limited to one experience even gets 403 "Scope must be configured to allow all resources" there) | | `OPENCLOUD_API_KEY` (alias `ROBLOX_API_KEY`) | any job without its own key | all of the above | | `TYPETORCH_API_KEY` | the TypeTorch backend's **game key** (write-only): `backend setup` checks it and writes it into the settings record (game servers post heartbeats, events and errors with it); the CLI posts alerts and chart marks with it. **Since CLI 0.9 never a Roblox key**: an old value that still looks like one (the same as an Open Cloud variable, or the CLI 0.8 layout next to `TYPETORCH_FLEET_INGEST_TOKEN`) is refused with the rename to do | - | | `TYPETORCH_ADMIN_TOKEN` | the backend's **admin token**: `servers`, `report`, `alerts`, `--wait`, the owner list (`PUT /v1/access`), `notify`, `experiment list`, `keys create` / `list` / `revoke`, `backend migrate`; never goes into the record | - | | `BASIN_SEND_TOKEN` | (CLI 0.19) the Cloudflare API token that may send to the Basin streams: `backend setup --analytics basin` signs it into the record's `analytics` sink (game servers post with it); `backend migrate --to-basin` hands it to the backend's job | Pipelines Send | | `TYPETORCH_OLD_ADMIN_TOKEN` | (CLI 0.19) the OLD server's admin token for `backend migrate --from` (with the old keys reused, the same value as `TYPETORCH_ADMIN_TOKEN`); sent only to the new server, which stores it encrypted | - | | `BASIN_SQL_TOKEN`, with `CLOUDFLARE_ACCOUNT_ID`, `BASIN_BUCKET`, `BASIN_NAMESPACE` (default `typetorch`) | (CLI 0.19) `backend migrate --from-basin`: what the backend reads Basin's Iceberg tables in R2 with (the names the backend's Basin store uses); only the token is a secret | R2 Data Catalog read | Old names, still read (through 0.19.0) with a warning naming the new one: `TYPETORCH_FLEET_TOKEN` (= `TYPETORCH_ADMIN_TOKEN`), `TYPETORCH_FLEET_INGEST_TOKEN` (= `TYPETORCH_API_KEY`). Other settings: `TYPETORCH_STATE_DIR` (where the logs live, default `.typetorch/`), `TYPETORCH_PROPOSED_BY`, `TYPETORCH_ROJO` / `TYPETORCH_LUNE` (tool paths), `TYPETORCH_BUILD_CACHE=0` (turns the build cache off), `TYPETORCH_COMPILER=goblox|rbxtsc` (the compiler; see "Compiler"), `TYPETORCH_DARKLUA` (darklua's path for the production pack; real environment only), `TYPETORCH_DEBUG=1` (= `--verbose`), `TYPETORCH_UPDATE_CHECK=off` (no daily update check), `TYPETORCH_CHILD_ENV=NAME,NAME` (extra non-secret variables for child processes), `TYPETORCH_KEY_FILE` / `TYPETORCH_FALLBACK_KEY_FILE` (the signing key files; read from the real environment only, never from an env file, and never passed to a child process). The signing keys are not environment variables: they are key files (see "Signing prod deploys"). ### Approving deploys Every deploy, rollback and promote is approved by a person in their own terminal (`"approval": "all"`, the default; `"prod"` asks only for prod-channel branches, `"none"` never asks). No key or passphrase is involved: it is a y/N. 1. **You deploy:** `typetorch deploy` in a terminal builds, uploads and waits for moderation, then shows the details and asks y/N: one command. 2. **Anyone else deploys** (an agent, the remote-claude dev-server, a script, or you with `--propose`): the same build, upload and moderation, then a **proposal** in `proposals.jsonl` (state dir) and nothing published. It prints `approve with: typetorch approve `. Proposals expire after 24 h. `--proposed-by` / `TYPETORCH_PROPOSED_BY` names who prepared it (default: `cli` at a terminal, `agent` otherwise). 3. **`typetorch approve [id]`** lists the pending proposals (newest first), shows branch, artifact, notes, sources, size, proposer and age, asks y/N, then publishes and logs it. It refuses when stdin isn't an interactive terminal. `typetorch reject ` drops one; `typetorch proposals [--all]` lists them. Approval and signing are separate: whatever publishes a release to a prod-channel branch (your y/N, or `"approval": "none"`) signs it automatically. Approval itself is enforced by the CLI only, so for dev-channel branches (unsigned) anything that holds the Open Cloud deploy key, or runs code on any server of the universe, can still publish a deploy message. Keep the deploy key away from agents. ### Signing prod deploys Releases (deploy, rollback, promote, re-sign) and pins to a **prod-channel** branch are signed with two Ed25519 keys when they are published; dev-channel ones never are. Every prod message, durable head and the settings record carry `sig` (main key) and `sigF` (fallback key). The kernel's rule is strict: once the key asset has loaded on a server only `sig` counts; while it never loaded only `sigF` counts (rules: [Prod signing](https://github.com/typetorch/docs/blob/main/guides/prod-signing.md)). | | Main key | Fallback key | |---|---|---| | Key file (plaintext JSON, no passphrase: keep it safe and backed up) | `~/.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` | | Where servers get the public key | the **key asset** (a group-owned Model with `PublicKeys` / `RevokedKeys` attributes; its id is stamped on the kernel as `KeyAssetId`) | baked into the place as `FallbackPublicKey` | | Replace it | `typetorch keys rotate` (no restart; re-signs the live prod heads) | `typetorch keys init --fallback --force`, then `typetorch kernel deploy` | **Set up once, in this order:** 1. `typetorch keys init`: the main key file, `signingPublicKeys`, and the key asset (created through Open Cloud with the assets key; its id goes into `keyAssetId`). Running it again resumes or does nothing. 2. `typetorch keys init --fallback`: the fallback key file and `fallbackPublicKey` (no network). 3. Commit typetorch.json (public keys only). 4. `typetorch kernel deploy`: bakes `KeyAssetId`, `FallbackPublicKey` and `BootstrapHeads` (the current prod heads, which the kernel trusts unsigned: heads stored before signing have no signature) into the place's kernel (patched in; servers run it after a restart). It refuses to publish without the keys. Run it from the machine with the latest deployment log. 5. `typetorch doctor`: both key files exist and match typetorch.json, the key asset (Approved, right owner, same lists) and the place's kernel attributes; any mismatch is a warning. **Recovery:** a lost or leaked main key: `typetorch keys rotate`. The key asset trusts only the new key and revokes the old one, `TypeTorch/rekey` tells servers to re-read it, and then each prod-channel branch's live head is **re-signed**: the same artifact and asset as a fresh signed message with a new seq and `r` = `"resign"` (servers update the head, no swap), through the approval policy like any prod publish. `typetorch keys resign` does only that step (to retry it). A leaked or lost fallback key: `typetorch keys init --fallback --force` (adds the old key to the key asset's RevokedKeys first, then makes a new pair), then `typetorch kernel deploy`. **Signed pins (A/B experiments on prod):** `typetorch pin --branch (--servers | --pct <1-99>)` and `typetorch pin --unpin --branch (--servers ... | --all)` publish `TypeTorch/pin` (kernel 0.2.3 fields) with `sig`/`sigF` on prod-channel branches, after a y/N (the approval policy; pins can't be proposals because servers drop them after 120 s). `--by ` names the owner (default: the only "owner" in `members`, else the creator userId). Unsigned pins from the in-game Manage tab only work on dev-channel servers. No command prints a seed; a key file inside the repo or any git work tree is refused. The remote-claude dev-server only deploys dev-channel branches, never gets the key variables, and is refused if it ever tries to publish to prod. Dry runs show whether signing is ready, with placeholders instead of real signatures. Anyone who can write the group's assets (including the upload/CI key) can change the key asset: an accepted risk until the keys are split (D4). ## Commands | Command | Does | |---|---| | `typetorch init [--dir ] [--phase ] [--answers ] [--agent] [--teardown]` | the guided setup, from an empty folder to a live game (see "Setup"); `--agent` prints `AGENT_PROMPT.md` again; `--teardown` removes the backend step 6 installed (asks first; its data only when you say so) | | `typetorch build [--branch ] [--channel prod\|dev] [--clean] [--no-minify]` | writes `src/shared/build.ts`, runs the compiler (goblox when installed, else rbxtsc; `bun run build` if the repo has a build script), and rojo-builds `.typetorch/payload.rbxm` with the identity stamped on the root; checks it holds only Folders and ModuleScripts; writes `.typetorch/payload.json`. `--clean`: `git clean -fdX` out/ and include/ first, then restore the build cache | | `typetorch upload [--branch ] [--channel prod\|dev] [--no-build] [--no-minify] [--moderation-timeout ]` | clean build, upload as a new Model asset, wait for moderation; no deploy (then `promote` it) | | `typetorch deploy [--branch] [--channel] [--no-build] [--no-minify] [--dry-run] [--message ] [--force] [--propose] [--proposed-by ] [--moderation-timeout ] [--test] [--skip-test ] [--wait [s]] [--no-wait] [--no-auto-rollback] [--rollback-at ] [--rollout <1-99>]` | clean build, upload, wait until Approved, log "uploaded"; the cloud test (always for prod-channel branches); then approve here (a person at a terminal) or write a proposal; on approval: deploy message, durable head, log "published"; then (prod: by default) wait for the servers' reports. Per-stage timings | | `typetorch deploy --widen <1-100> [--branch]` | re-send the branch's live deploy (same seq) to more servers; dev-channel branches only (see "Rollouts") | | `typetorch promote [--force] [--dry-run] [--test] [--skip-test ] [--wait [s]] [--rollout <1-99>]` | point a branch at an already uploaded, approved payload (from the deployments or `uploads.jsonl`) with a new seq; no rebuild. A prod-channel branch only takes prod-channel artifacts, even with `--force` ("rebuild for prod"). `promote ` works too when only the second is a known branch | | `typetorch rollback [--branch] [--to ] [--force] [--dry-run] [--message ] [--propose] [--test] [--wait [s]]` | point the branch at an earlier, already approved asset (no build or upload) and tell its servers; no cloud test unless `--test` (it is an earlier build) | | `typetorch deployments [--branch] [--limit n]` | deployment history with git identity; `*` = each branch's live head; lists uploads that never went out | | `typetorch branch ls` | branches (the kernel's DataStore heads and this machine's log), channels, heads, signed or not, live servers per branch; warns from 28 of the kernel's 32 stored branches | | `typetorch branch rm ` | removes a dev branch's head from the DataStore heads (y/N or `--yes`; `--dry-run`). Refuses the default and prod-channel branches, a branch live servers run (the fleet API; without it only with `--force`), and a head that changed meanwhile. Servers' MemoryStore copy keeps it until it expires (up to 45 days) | | `typetorch settings status` / `get [field\|game.]` / `set game. ` / `unset ` / `push` | the signed settings record (see "Settings"); `push` writes `defaultBranch`, `channels` and dev access from typetorch.json. `--dry-run`, `--force`, `--no-ping` | | `typetorch experiment list` / `weights ` / `settle ` / `stop ` / `resume ` / `clear ` / `force ` / `unforce ` | live analytics experiment overrides in the signed settings record, no deploy (see "Experiments"). `--variants a,b`, `--dry-run`, `--force`, `--no-ping` | | `typetorch notify push [--dry-run]` / `status` / `templates` / `templates set ` / `test [--param k=v]... [--data x]` / `send