@typetorch/framework 0.5.4 → 0.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +534 -532
  2. package/out/analytics/SCHEMA.md +245 -245
  3. package/package.json +53 -53
package/README.md CHANGED
@@ -1,532 +1,534 @@
1
- # @typetorch/framework
2
-
3
- The roblox-ts framework of [TypeTorch](https://github.com/typetorch): hot-swappable modules (dependency injection,
4
- lifecycle, troves), guarded networking over the kernel's stable remotes, UI helpers and the in-game dev menu.
5
-
6
- It ships **inside every artifact**, so each generation runs its own fresh copy and framework fixes hot-swap like game
7
- code. It needs the TypeTorch kernel in the place (`@typetorch/kernel`), which calls your `Server/boot` and
8
- `Client/boot` modules.
9
-
10
- ## Install
11
-
12
- ```sh
13
- npm i @typetorch/framework
14
- npm i -D @typetorch/transformer
15
- ```
16
-
17
- (`bun add @typetorch/framework` and `bun add -d @typetorch/transformer` work the same.) The framework is a roblox-ts 3
18
- package; `@typetorch/transformer` is its compiler plugin: it generates the network guards, the constructor dependency
19
- ids of `@Service` / `@Controller` and your own macros. Nothing from Flamework is needed: `Modding`, `Reflect` and `t`
20
- come from this package. The starter game ([template](https://github.com/typetorch/template)) has it all set up: clone
21
- it and run `bun install`.
22
-
23
- `tsconfig.json`:
24
-
25
- ```jsonc
26
- {
27
- "compilerOptions": {
28
- "experimentalDecorators": true,
29
- // Every npm scope the game imports from must be a type root (roblox-ts rule).
30
- "typeRoots": ["node_modules/@rbxts", "node_modules/@typetorch"],
31
- "types": ["types", "compiler-types"],
32
- "plugins": [
33
- // Optional, first when present: $print/$warn with file and line (what every TypeTorch repo uses).
34
- { "transform": "rbxts-transform-debug", "environmentRequires": {} },
35
- { "transform": "@typetorch/transformer" }
36
- ]
37
- }
38
- }
39
- ```
40
-
41
- The payload is a Rojo `Model` project. Map only this package from the `@typetorch` scope (the transformer is Node code
42
- and the kernel lives in the place):
43
-
44
- ```json
45
- "include": {
46
- "$path": "include",
47
- "node_modules": {
48
- "$className": "Folder",
49
- "@rbxts": { "$path": "node_modules/@rbxts" },
50
- "@typetorch": { "$className": "Folder", "framework": { "$path": "node_modules/@typetorch/framework" } }
51
- }
52
- }
53
- ```
54
-
55
- Each generation requires its own copy of the payload, so the framework and its `Reflect` registry start fresh on every
56
- swap. It needs the TypeTorch kernel in the place (`@typetorch/kernel`).
57
-
58
- ### Coming from Flamework
59
-
60
- Game code only changes imports: `@Service`, `@Controller`, constructor injection, `Dependency<T>()`, the lifecycle
61
- interfaces and `createNetwork` are the same.
62
-
63
- | Flamework | TypeTorch |
64
- |---|---|
65
- | `rbxts-transformer-flamework` plugin, `node_modules/@flamework` type root | `@typetorch/transformer` plugin, `node_modules/@typetorch` type root |
66
- | `import { Modding, Reflect } from "@flamework/core"` | `import { Modding, Reflect } from "@typetorch/framework"` |
67
- | `import { Dependency } from "@flamework/core"` | `import { Dependency } from "@typetorch/framework"` (from onInit/onStart on, not in constructors) |
68
- | `import type` + `Dependency<T>()` to break a cycle | the same, or `Lazy<T>` (below) |
69
- | `ClientEvents.x.predict(...)` | `network.client.x.emit(...)` |
70
- | `invokeWithTimeout(timeout, ...)` | `invokeWithTimeout(seconds, ...)` (seconds, 0.5 to 120) |
71
- | `Observers.observeCharacter` / `observeLocalCharacter` (@rbxts/observers) | still fine: put the stop function in the trove, `this.trove.add(observeCharacter(...))` |
72
- | `import { t } from "@rbxts/t"` (still fine) | also `import { t } from "@typetorch/framework"` |
73
- | `@metadata flamework:parameters` keys, `"flamework:parameters"` metadata | `@metadata typetorch:parameters`, `"typetorch:parameters"` |
74
- | `flamework.build`, `include/flamework`, the `@flamework` Rojo mapping | gone; delete them |
75
- | `Networking.createEvent` / `createFunction` and their call sites | `createFlameworkCompat` (below) keeps every call site; `createNetwork` is the native API |
76
-
77
- `typetorch migrate --from flamework` (CLI) does most of this, and the docs' `guides/from-flamework.md` has the whole
78
- mapping.
79
-
80
- ## Usage
81
-
82
- ```ts
83
- // src/server/boot.ts
84
- import { startServer, type ServerKernel } from "@typetorch/framework";
85
- import { BUILD } from "../shared/build";
86
- export function boot(kernel: ServerKernel) {
87
- return startServer(kernel, { modules: [script.Parent!.FindFirstChild("services")!], build: BUILD });
88
- }
89
-
90
- // src/shared/net.ts
91
- import { createNetwork, type ProperReturns } from "@typetorch/framework";
92
- interface ClientToServer { coins: { collect(coinId: string): void; balance(): ProperReturns<number> } }
93
- interface ServerToClient { coins: { changed(total: number): void } }
94
- export const network = createNetwork<ClientToServer, ServerToClient>();
95
-
96
- // src/server/services/coin.service.ts
97
- @Service()
98
- export class CoinService extends Module implements OnStart {
99
- constructor(private readonly score: ScoreService) { // injected
100
- super();
101
- }
102
- onStart() {
103
- this.trove.add(network.server.coins.collect.on((player, coinId) => this.score.add(player, 1)));
104
- }
105
- }
106
- ```
107
-
108
- - **Modules:** `@Service()` (server) and `@Controller()` (client) classes extending `Module`. Constructor parameters
109
- are other modules, injected by type. Lifecycle: `OnInit` (sequential, dependencies first), `OnStart` (spawned),
110
- `OnStop` (reverse order), `OnTick`, `OnPhysics`, `OnRender`, `OnPlayerAdded` (replays players already in the server).
111
- - **Modules outside the constructor:** `Dependency<T>()` (or `TypeTorch.module<T>()`) returns the running module of
112
- type T from anywhere: a method, a plain class a module built, a command handler. `TypeTorch.tryModule<T>()` returns
113
- undefined instead of throwing. They work once every module is constructed (from onInit on); in a constructor, a
114
- field initializer or module top-level code they throw `"ShopService isn't constructed yet: ..."`. Only this realm's
115
- modules, and per generation: after a swap they return the new generation's instance. An `import type` of the class is
116
- enough (no require cycle).
117
- - **Cycles:** two modules that need each other take one side as `Lazy<T>`, resolved on first use:
118
- `constructor(private readonly team: Lazy<TeamService>)` (needs `@typetorch/transformer` 0.2.1+) or a field,
119
- `private readonly team = Lazy<TeamService>()` (any transformer). `this.team.get()` works from onInit on (in a
120
- constructor it throws), and the start order ignores lazy edges. A cycle error names the cycle and suggests this.
121
- - **Per-player state:** `this.ctx.playerState("cooldowns.v1", (player) => init)` (or `TypeTorch.playerState`) returns
122
- `{ get, set, has, delete }` keyed by UserId. It survives swaps (persist), and a player's entry goes when they really
123
- leave, never on a swap. The dev menu shows it under Modules > State > persist, `__playerState`.
124
- - **Bad deploys roll back (kernel 0.3.2):** a server `onStart` that throws is reported to the kernel, which rolls the
125
- server back to its last known good artifact when it happens within 30 s of start (so do 3 errors from the new
126
- code's scripts in that time). On a real shutdown every module's `onStop` runs too (the kernel's BindToClose).
127
- - **Troves:** every module gets `this.trove`; everything it creates or connects goes there, so a swap leaves nothing
128
- behind. `TypeTorch.persist(key, init)` (or `this.ctx.persist`) keeps plain data across swaps.
129
- - **Network:** `createNetwork<C2S, S2C>()` with nested namespaces. The server checks rate limits, shape limits and the
130
- generated type guard on every client message. `setNetworkLimits({ "chat.say": { maxString: 200 } })` tunes a leaf.
131
- Requests wait 15 s for the answer: `invokeWithTimeout(5, ...args)` sets it per call, and a leaf's `timeout`
132
- (`setNetworkLimits({ "vc.spawn": { timeout: 30 } })`, read by the client, so set it in shared code) per leaf; both in
133
- seconds, 0.5 to 120. `network.client.x.emit(...args)` runs this client's own `on` handlers for a server -> client
134
- leaf right away, with no traffic (Flamework's `predict`); `network.server.x.emit(player, ...args)` does the same on
135
- the server, for tests. A request handler may return a Promise: the answer waits for it.
136
- - **Flamework networking names:** `createFlameworkCompat<C2SEvents, S2CEvents, C2SFunctions, S2CFunctions>()` returns
137
- `{ ServerEvents, ClientEvents, ServerFunctions, ClientFunctions, GlobalEvents, GlobalFunctions }` with
138
- `@flamework/networking` 1.x's methods (`connect` returning a connection, `fire(player | players)`, `broadcast`,
139
- `except`, `predict`, `setCallback`, `invoke`, `invokeWithTimeout`, calling a leaf directly) on this same network:
140
- same guards, limits and swap rules, so a Flamework game's call sites compile unchanged. Listeners run on their own
141
- thread each, like Flamework's, and belong to the running generation (no trove needed). Not carried over: server ->
142
- client requests, middleware, `Networking.Unreliable`. `typetorch build` notes a game still using it.
143
- Across a swap (0.3.0): what the server sends a player waits until that player's client runs the new generation
144
- (reliable messages are queued, unreliable ones dropped), and on kernel 0.3.2 a request the server can no longer
145
- answer fails at once ("The game is updating, try again.") instead of timing out.
146
- - **Macros:** `Modding` (from this package) declares compile-time macros that `@typetorch/transformer` fills in:
147
- `/** @metadata macro */ export function guardOf<T>(guard?: Modding.Generic<T, "guard">) { return guard!; }` makes
148
- `guardOf<Shape>()` compile to a `t` guard. `Modding.Generic<T, "id" | "text">`, `Many`, `Caller` and `TupleLabels`
149
- work the same way; see the transformer's README.
150
- - **UI:** `observeElement(trove, tag, (instance, elementTrove) => ...)`, `isRealFrame`, `popIn` / `popOut` / `bump`
151
- (UIScale, never Size tweens) and `PopupQueue` (one modal at a time).
152
- - **Dev menu:** devs (Studio, project members, dev badge) get a DEV button, `Ctrl+Shift+D` and `/tt dev`: artifact
153
- (with how long the server and client generations have run, the server's uptime and the build's age), server status,
154
- logs (server, own client, other players' clients), client and server dex, network stats, module state, a branch and
155
- build picker (Server > Branch) and a Claude prompt. The sidebar, top to bottom: Artifact, Server, Network, Modules,
156
- Manage, Logs, Dex, Claude. The window can be dragged by its header and resized from its corner (double-tap the
157
- header to reset).
158
- - **Server TPS (framework 0.4.2, kernel 0.4.2):** Server > Status has a *TPS* line next to Memory and Lua heap: the
159
- last minute's average, its slowest second and the physics FPS (`59.9 avg, 52.0 min, physics 60`; the warning colour
160
- under 50 on average). Older kernels show `needs kernel 0.4.2`. The same numbers ride on fleet heartbeats (the
161
- explorer's fleet table).
162
- - **Dev-only tools (framework 0.4.1, `devtools/access.ts`):** Claude, Logs > Upload, Dex edits on the server, Network
163
- packet blocking and the hot-swap sound work under dev rules (private, reserved and Studio servers on a dev branch)
164
- for every dev, and on a public server an owner switched to a dev branch (Server > Branch) for owners only. Everywhere
165
- else the menu is read-only, with a short reason: "Dev branch only", "Owners only on public servers", "Owner-switched
166
- servers only". The rules themselves don't change (`TypeTorch.channel`, signatures, owner-only rollbacks).
167
- - **Panes and windows (dev menu):** every page shows in a pane with a small header: tap the title to pick another
168
- page, or use Split right, Split down, Open in new window and Close. Drag the line between two panes to resize them.
169
- The sidebar opens pages in the focused pane (the highlighted one; tap a pane to focus it). Floating windows move by
170
- their title bar and resize from their corner (double-tap the title bar to maximise); their title bar also has
171
- Minimise, Dock (back into the main panel) and Close. Windows can be split too. The layout, the windows and each
172
- pane's own settings (for example the open nodes of two Modules > State panes) survive swaps; a fresh join starts
173
- with one pane. Claude, Server > Branch and the Manage pages open once (picking them again focuses their pane); every
174
- other page can be open several times. Panes nobody sees (menu closed, window minimised) stop refreshing, and panes
175
- on the same data share one request (Status, Overview, Assets, Network > Stats, server Logs, Packets); State panes
176
- share one query budget. On phones and small screens panes only stack (two at most), and windows open maximised with
177
- one pane each.
178
- - **State explorer (Modules > State, Server | Client):** every live module of the running generation (services on the
179
- server, controllers on the client) and the persist store. Tap a row to open it: the module's own fields (not its
180
- methods), then tables, arrays, Maps and Sets, 100 entries per page (Prev / Next). Each value has a short preview:
181
- strings (cut), numbers, booleans, nil, datatypes through `tostring`, an Instance as its full path, a Player as its
182
- name, `function`, `thread`, buffer sizes. Nothing is ever called (raw reads only: no metamethods, no getters); a
183
- value that is its own ancestor shows as a cycle. A key filter (open nodes stay listed), Refresh and Auto (every 2 s).
184
- Server state comes from the op `state.inspect` (rate-limited, size-capped): owners everywhere, other devs where the
185
- dev-only tools are open to them, since server state can hold player data.
186
- - **Logs > Upload:** sends the logs shown (Server: this server's log ring; Client: your own client's; Others: the
187
- picked player's client) to the dev PC paired in the Claude tab, which saves them under `<repo>/.typetorch/logs/`.
188
- No Claude run, no prompt quota. Not paired: "Pair in the Claude tab first".
189
- - **Switch a live server (kernel 0.3.4):** owners switch any server and load builds on it, public and prod ones too:
190
- Server > Branch, "Switch" on a branch or "Load here" on a build, then the green Confirm. Everyone stays. These are
191
- ordinary switches and pins: Reload and Rollback keep working, and going back to prod is Switch on the prod row (its
192
- verified head). A public switch lasts for that server's lifetime and is never stored, so new servers still boot the
193
- signed prod head. Others see "Join", which moves only them to a reserved server. Manage > Servers "Load a build..."
194
- does the same for this server, the ticked servers or a share of one branch (A/B pins), with one status line under
195
- the list. A public server an owner switched to a dev branch opens the dev-only tools (Claude too) to owners.
196
- - **Owners and devs:** two roles (no admins: an older kernel's or typetorch.json's "admin" counts as a dev). The Manage
197
- group (Players, Servers, Bans) is for owners only.
198
- - **Remote Claude** (a dev-only tool: dev rules, or owners on a public server an owner switched to a dev branch):
199
- while `typetorch remote-claude` (`@typetorch/dev-server`) runs on a dev's machine, allowlisted devs prompt Claude
200
- Code from the Claude tab. Each dev pairs once by pasting the pairing code printed by
201
- typetorch-dev-server; the game server keeps the session URL and the tokens in memory and never sends them to clients.
202
- No Roblox secret is needed.
203
-
204
- ## Runtime API: `TypeTorch`
205
-
206
- `import { TypeTorch } from "@typetorch/framework"` works on the server and the client. It describes the running
207
- generation and raises events that belong to it: every listener is dropped when the generation stops, so a swap never
208
- leaves one behind. Each `on*` returns a disconnect function, which a trove can own.
209
-
210
- ```ts
211
- // Identity
212
- TypeTorch.artifact; // { id, commit, commitHash, branch, channel, builtAt, seq, assetId }
213
- TypeTorch.generation; // 1, 2, 3... per server (or client)
214
- TypeTorch.branch; TypeTorch.channel; TypeTorch.serverType; // "public" | "private" | "reserved" | "studio"
215
- // Kernel 0.3.9: `channel` is the RULES this server runs under ("prod" on every public server; split data stores by it);
216
- // `branchChannel` is what the branch IS ("prod" for the default branch or one configured prod, else "dev");
217
- // `rules` is the same as `channel`, by name.
218
- TypeTorch.branchChannel; TypeTorch.rules;
219
- TypeTorch.isPinned(); TypeTorch.kernelVersion; TypeTorch.kernelApi; TypeTorch.jobId; TypeTorch.isStudio;
220
-
221
- // How this generation started: a branch change starts a new generation.
222
- const start = TypeTorch.startInfo; // { kind: "boot" | "swap", reason, previous?, branchChanged, requestedBy?, loadSeconds? }
223
- if (start.reason === "auto_rollback") warn("the last deploy failed to start");
224
- this.trove.add(TypeTorch.onBranchChanged(({ from, to }) => resetBranchData(from, to)));
225
-
226
- // Before this generation stops (runs before every onStop; keep it short)
227
- this.trove.add(TypeTorch.onSwapOut((info) => this.saveRound(info.reason)));
228
-
229
- // A swap is coming: show a small hint, hide it if it's called off
230
- this.trove.add(TypeTorch.onUpdatePending((update) => (hint.Visible = !update.cancelled)));
231
-
232
- // State that survives swaps (plain data only)
233
- const scores = TypeTorch.persist("scores.v1", () => new Map<number, number>());
234
- // Per player, removed when the player really leaves (same as this.ctx.playerState)
235
- const cooldowns = TypeTorch.playerState("cooldowns.v1", () => ({ lastUse: 0 }));
236
- cooldowns.get(player).lastUse = os.clock();
237
-
238
- // The running module of a type (same as Dependency<T>()), from onInit/onStart on
239
- TypeTorch.module<ShopService>().open(player);
240
- TypeTorch.tryModule<ShopService>()?.open(player); // undefined instead of an error
241
-
242
- // Dev and roles (server: the kernel decides; client: only the local player, cosmetic)
243
- if (TypeTorch.isOwner(player)) showOwnerPanel(player);
244
- TypeTorch.onPlayerDevChanged((player, info) => setDevTools(player, info.dev));
245
-
246
- // Server only
247
- TypeTorch.status(); // uptime, players, memory, history: cheap
248
- TypeTorch.branches(); TypeTorch.artifacts(); // registry reads, cached ~30 s: may yield, don't call per frame
249
- TypeTorch.requestReload(player); // owners only, checked by the kernel
250
-
251
- // Logs (the kernel's ring buffer)
252
- TypeTorch.logs(0, 50);
253
- TypeTorch.onLog((entry) => errors.push(entry)); // don't print from inside it
254
-
255
- // Hot assets (below): same as hotAsset(...)
256
- const shop = TypeTorch.asset("ui/shop");
257
-
258
- // Live values, server only (kernel 0.3.8): the signed settings record's `game` field (`typetorch settings set game.<key> <json>`).
259
- const price = TypeTorch.liveConfig("shop.price", { default: 50, parse: (raw) => (typeIs(raw, "number") ? raw : 50) });
260
- price.get();
261
- this.trove.add(price.onChanged((value) => this.reprice(value)));
262
-
263
- // Cross-server, server only. Kernel 0.3.8: game topics over ONE kernel-held MessagingService topic; listeners hear
264
- // prod servers and this branch by default (dev branches never reach prod); publish queues and retries, max 1 KiB.
265
- this.trove.add(TypeTorch.messaging.subscribe<Ban>("1guard", (ban, meta) => applyBan(ban, meta.jobId)));
266
- TypeTorch.messaging.publish("1guard", { kind: "ban", userId }, { to: "prod" });
267
-
268
- // The universe's live servers (the roll call; cached per server, yields up to ~3 s when stale) and this server's public fields
269
- TypeTorch.setServerInfo({ region: "eu", vc: true }); // JSON, at most 400 bytes, kept across swaps
270
- const list = TypeTorch.servers(); // [{ jobId, placeVersion, players, maxPlayers, serverType, branch, channel, uptime, here, info }]
271
-
272
- // A library call a swap must not cut off halfway (kernel 0.3.8): runs on a kernel thread; write what must survive into persist.
273
- TypeTorch.runDetached(() => store.StartSessionAsync(`Player_${userId}`)).then((profile) => attach(player, profile));
274
- ```
275
-
276
- - **`startInfo.reason`:** `boot`, `deploy`, `rollback`, `branch`, `pin`, `reload`, `server_rollback`,
277
- `auto_rollback` or `unknown`. A client's first generation is always `boot`. `requestedBy` (a user id), `loadSeconds`,
278
- `stopSeconds` and `swapSeconds` are server-only; `swapSeconds` appears once the swap has finished.
279
- - **`persist(key, init)`** keeps a table in the kernel's memory for the server's lifetime; every later generation gets
280
- the same table back. Store plain data only: tables, arrays, Maps and Sets of strings, numbers, booleans, and
281
- Players. Never store functions, class instances, Promises, threads, connections, charm atoms or instances this
282
- generation created: they keep the old generation's code alive or are destroyed by its trove. Version the key when
283
- the shape changes. Keys starting with `__` are reserved.
284
- - **`onSwapOut`** runs synchronously before every module's `onStop`, so modules can still save into `persist`. It
285
- doesn't run on server shutdown (kernel 0.3.2 runs `onStop` then; on older kernels use `game.BindToClose`).
286
- - **Kernel versions:** `TypeTorch.features` says what the running kernel supports. Kernel 0.2.2 adds the start
287
- reason and timings, the next artifact in `onSwapOut`, `onUpdatePending`, server-side `onPlayerDevChanged` and
288
- `requestReload`. On older kernels `startInfo` still knows boot vs swap, the previous artifact and branch (the
289
- framework records them), `onBranchChanged` still fires, and the reason of a swap is `unknown`.
290
- - **`messaging`** (kernel 0.3.8): `subscribe(topic, (data, meta) => ...)` returns a disconnect; `meta` = `{ channel,
291
- branch, jobId, serverType, placeVersion, sentAt, self, replayed? }`; `{ from: "all" | "prod" | "branch" }` changes
292
- who it hears. `publish(topic, data, { to })` throws on a bad topic, non-JSON data or a message over 1 KiB (with its
293
- size), returns false when dropped at once (queue full). Studio loops back; the cloud test publishes nothing; older
294
- kernels throw "needs kernel 0.3.8". `servers()` works on every kernel (0.3.8 holds the roll call topic, so a swap
295
- doesn't subscribe again).
296
- - **`liveConfig(key, { default, parse? })`** (kernel 0.3.8, plans/20): reads `game[key]` of the signed settings record the
297
- kernel verified (signed by both prod keys, so game code can't forge it); `get()` and `onChanged(fn)` (only on real
298
- changes; generation-scoped). The default without a record or key, when `parse` throws (warned per value), and on older
299
- kernels (warned once: "needs kernel 0.3.8"; no ConfigService fallback). `TypeTorch.settings()` is the whole copy
300
- (`seq`, `at`, `game`, `analytics`, `fleet`, ...): server only, it holds tokens.
301
- - **`runDetached(fn)`** (kernel 0.3.8, server only): runs `fn` on a thread the kernel owns, so a deploy's hard stop
302
- (which kills this generation's threads mid-call) can't cut it off: for ProfileStore / ProfileService loads, saves and
303
- releases. Returns a Promise that settles while this generation runs; after a swap the result is dropped, so a job
304
- whose result must survive writes it into `persist` itself. The job keeps this generation's closures alive until it
305
- ends. Errors reject it and go to the kernel's log with the generation's name (never the health window); at most 256
306
- run at once per server (then it throws); one past 60 s is logged and flagged in Server > Status. Older kernels
307
- throw "needs kernel 0.3.8; use the DataHost job queue (Player data guide)": the other option, which works on every
308
- kernel. `features.runDetached` tells which one this server has.
309
- - **Edit mode** (UI Labs stories, no kernel): `running` is false, identity has defaults, `persist` keeps a local table,
310
- events never fire, and the server-only reads throw.
311
-
312
- ## Player data
313
-
314
- Saving player data is game code: pick any library (ProfileStore, DataStore2, your own). TypeTorch only gives you the
315
- pieces that keep it safe across swaps:
316
-
317
- - **The library lives in the place**, outside the payload, and a small place Script requires it first. Its open
318
- sessions, autosave loop and shutdown hook then survive every swap (a swap stops the generation's scripts).
319
- - **Session handles live in `persist`**, keyed by `UserId`. `onPlayerAdded` replays everyone after a swap, so it
320
- re-attaches to the open session instead of loading again.
321
- - **Release only on `Players.PlayerRemoving`**, never in `onStop` or `onSwapOut`.
322
- - **Library calls can't be cut off by a swap:** run them as DataHost jobs (any kernel) or with
323
- `TypeTorch.runDetached` (kernel 0.3.8).
324
- - **Split store names by channel** (`TypeTorch.channel === "prod" ? "PlayerData" : "PlayerData_dev"`).
325
-
326
- Full example with ProfileStore: [Player data guide](https://github.com/typetorch/docs/blob/main/guides/player-data.md).
327
-
328
- ## Hot assets: `hotAsset`
329
-
330
- Builders mark models and UI templates in the place with the attribute `TypeTorchAsset` (a key such as `"ui/shop"`),
331
- `typetorch assets sync` uploads them, and the deploy puts the asset manifest in the artifact. Running servers then get
332
- new versions live, with no restart.
333
-
334
- ```ts
335
- import { hotAsset } from "@typetorch/framework"; // or TypeTorch.asset("ui/shop")
336
-
337
- // In a controller's onStart: rebuild clones the template.
338
- const shop = hotAsset("ui/shop");
339
- shop.changed(rebuild, this.trove); // a new version went live
340
- rebuild(shop.get());
341
- ```
342
-
343
- - **`hotAsset(keyOrId, fallback?)`** works on the server and the client. A number is the Roblox asset id, resolved
344
- through the manifest (server) or the live copy's `TypeTorchAssetId` attribute (client).
345
- - `get()` returns the live copy now. With none, it returns `fallback` (an instance you already hold, such as the
346
- template in the place) if it is still parented, else `undefined`. **Clone it; don't parent or edit it:** a new
347
- version destroys it.
348
- - `wait(timeout?)` is `get()` that waits for a live copy (forever without a timeout).
349
- - `changed(fn, trove?)` calls `fn(instance)` each time a new copy replaces the live one: a new version, a rollback,
350
- or the first copy reaching a client. It returns a disconnect function. Pass the module's trove so the connection
351
- ends with it (`shop.changed(rebuild, this.trove)` or `this.trove.add(shop.changed(rebuild))`). Without a trove it
352
- ends when the generation stops.
353
- - `key` and `version` (the live copy's `TypeTorchAssetVersion`, an assetVersionId).
354
- - **Clients never request anything.** They read the CollectionService tag `__typetorch_asset:<key>`, and replicated
355
- assets arrive through replication. Assets under ServerStorage stay server-only.
356
- - **AssetSync** is a server built-in. It runs on every generation start, before any module loads (top-level code
357
- included). For each manifest key:
358
- 1. it keeps the live copy that already has the manifest's version;
359
- 2. else it adopts the place's own copy, if its `TypeTorchAssetHash` matches (or if the manifest's optional
360
- `placeVersion` is this server's place version);
361
- 3. else it runs `InsertService:LoadAssetVersion(ver)` (all loads in parallel), strips any scripts, places the copy
362
- at its path (creating missing Folders), tags it, then destroys the copy it replaces.
363
-
364
- It holds the start for at most 8 s. Loads still running after that keep going, swap in when done and fire
365
- `changed`. A failed load keeps the old copy (on a new server, the place's copy) and shows under Server > Status >
366
- Attention.
367
- - **Hot assets persist across swaps.** They aren't in any trove. A swap changes them only when the manifest changes,
368
- and a rollback brings back the older versions. **Keys the manifest doesn't name are left as they are:** AssetSync
369
- never deletes builders' content. A key dropped from the manifest keeps its last live copy.
370
- - **Clones never count.** A clone keeps the tag and the attributes, but only the copy whose parent is its
371
- `TypeTorchAssetPath` (stamped by AssetSync) is the live one. So a template cloned into PlayerGui never shows up in
372
- `get()`, and AssetSync never destroys it.
373
- - **Dev menu:** Modules > Assets (Server | Client) lists each key's source (kept, baked, loaded, failed), version,
374
- load time and last error.
375
-
376
- ## Analytics: `AnalyticsEngine`
377
-
378
- Optional, and all ours: the game server sends rows to the backend the dev picked (Cloudflare Basin streams, or a
379
- self-hosted DuckDB analytics server). Nothing runs until an engine is created: no connections, threads or requests.
380
-
381
- ```ts
382
- import { AnalyticsEngine } from "@typetorch/framework";
383
-
384
- // A server module (onInit): the sink comes from the signed settings' `analytics` (kernel 0.3.8).
385
- const analytics = new AnalyticsEngine();
386
- analytics.track(player, "quest_done", { quest: "tutorial" }); // custom
387
- analytics.step(player, "onboarding", 3, "opened_shop"); // funnels
388
- analytics.purchase(player, { product: 1234, robux: 99, where: "shop" }); // after the receipt is granted
389
- analytics.currency(player, "coins", 50, "round_reward"); // economy in (+) and out (-)
390
- analytics.state("round"); // every player's activity; analytics.state(player, "shop") for one
391
- const variant = analytics.experiment(player, "onboarding", ["short", "long"]); // first = control
392
-
393
- // A client controller (onStart): everything goes through the server, never to the internet.
394
- const analytics = new AnalyticsEngine();
395
- analytics.track("opened_map");
396
- analytics.screen("Inventory"); // for UIs that aren't separate ScreenGuis
397
- const variant = analytics.experiment("onboarding", ["short", "long"]); // same answer as the server's
398
- ```
399
-
400
- - **One engine per generation and realm.** Every `new AnalyticsEngine()` joins the one already running (the first one's
401
- options win), so any module can create its own. It stops with the generation; its unsent rows wait in `persist`
402
- and the next generation sends them. In edit mode (UI Labs) it is inert.
403
- - **Server calls take the player first** (`track(player, ...)`); without one an event is server-only (no player id).
404
- Client calls are always about the local player and are marked `src = "client"` (a client can lie). The server
405
- checks their shape, size (props at most 4 KB) and rate. `purchase` and `currency` are server-only (revenue and the
406
- economy are server-authoritative): on the client they warn once and send nothing, and the server refuses them from
407
- clients.
408
- - **Options** (all on by default): `sessions` (joins, leaves, device, join source, account age bucket, Premium,
409
- country, friends in the server, first-ever vs returning, days since the last visit), `tech` (FPS, ping, memory, load
410
- time, client and server errors, swaps and rollbacks, leaves within 60 s of a swap), `zones` (parts or models tagged
411
- `TTZone`, named by a `Name` attribute or the instance name), `screens` (ScreenGuis in PlayerGui, GuiObjects tagged
412
- `TTScreen`), `recording` (the first-ever session in detail), `fleet` (kernel 0.3.2 heartbeats and deploy reports),
413
- `identity` (one `{ pid, uid }` row per session to the dev's own server, below). `settings` (server only) replaces the
414
- signed settings' `analytics`, for tests, Studio and kernels before 0.3.8.
415
- - **Every row** carries the time (server clock), a random player id (never the UserId), the session, the server
416
- (JobId, type, place), the artifact (id, seq, branch, channel), the device, new vs returning, the player's state
417
- (`zone:Lobby|screen:Shop|activity:round`) and experiment variants. The exact rows: `src/analytics/SCHEMA.md`.
418
- - **Experiments:** `experiment(...)` is deterministic per player and name (they keep their variant in every session),
419
- may yield briefly the first time (until the player's id loads), and stamps the variant on the player's later events.
420
- The settings turn one off (`active: false`: everyone gets the first variant), sets `weights` or forces a
421
- `variant`, live.
422
- - **First-ever session:** for new players (a share of them, `recordShare`), the client records character and camera
423
- about 10 times a second, every input (never while a TextBox or the chat has focus; text boxes only say which box was
424
- used), buttons pressed and hovered, screens, prompts and deaths, from the join until 60 s after the first input.
425
- Packed into small binary chunks (10-20 KB a player) and sent through the server.
426
- - **Never collected:** chat or anything typed, usernames and display names (error texts have them replaced). No event
427
- row carries a UserId.
428
- - **Identities** (option `identity`, default on): once the pid is known, one row `{ pid, uid, t }` (the UserId, nothing
429
- else) per session goes to the dev's own server only, never into the events: duckdb games in the batch body, Basin
430
- games to the backend (the record's `backend` url + `/v1/identity`, or the `identity` / `identityToken` settings). The
431
- analytics server keeps pid -> UserId in a deletable table (support lookups, Right to Erasure).
432
- - **Player ids:** DataStore `TypeTorchAnalytics`, key `p/<UserId>` -> `{ pid, first, last }`: one read per join, a
433
- write on the first join and at leave. Deleting the key (Right to Erasure) leaves that player's rows anonymous.
434
- - **Sending:** one queue on the server (10,000 events; over that the oldest are dropped and counted), a flush every
435
- `flushSeconds` (15) or at 500 rows, at most ~10 HttpService requests a minute, retries with backoff, and a last
436
- flush on shutdown (kernel 0.3.2). Delivery is at least once (a swap mid-request sends that batch again).
437
- `analytics.stats()` (server) has the counters; `flush()` sends soon.
438
- - **When uploads fail** (a stale quick-tunnel URL, the dev PC's server or tunnel down, a wrong token, HttpService off;
439
- Roblox reports most network problems as `HttpError: NetFail`, `DnsResolve` or `ConnectFail`): the server backs off
440
- with jitter (5, 10, 20 ... 300 s, spread +-25% so a fleet of servers doesn't retry in step; a wrong token or URL waits
441
- about 5 minutes, and a settings change retries at once), keeps the rows, and logs at most ONE line a minute: the
442
- reason and the fix (`analytics upload failed 5 times in a row: NetFail: the connection broke mid-request. ... Retrying
443
- in 80 s.`, with "(+N more in the last minute)" for the lines it held back) and one line when uploads work again.
444
- `stats()` also has `failures` (in a row), `failed` (since the server started), `lastError`, `lastStatus`
445
- (0 = no answer), `lastErrorAt` / `lastOkAt` (`os.time()`), `retryIn`, and, while failing, `reason` and `fix`. The dev
446
- menu shows them: **Server > Status** has an *Analytics* line (queued, sent, `FAILING x5: ... retry in 80 s`) and a
447
- *Fleet API* line (the kernel's sender: sent, failed, last error and its age), and **Attention** lists the reason and
448
- the fix; `typetorch doctor` tests the address and token in the settings record.
449
- - **The cloud test sends nothing.** `typetorch test --cloud` boots the payload headless in a Luau Execution task where
450
- HttpService works; there the engine (stub kernel `test = true`, or `workspace:GetAttribute("TypeTorchTest")`) collects
451
- as usual but never uploads: no event rows, no identity rows, no HTTP request, so a prod deploy never puts a fake
452
- server session into your analytics.
453
- - **Bounds on what a client can cause:** at most 32 experiments per session (each is stamped on every later row), and
454
- a client's `exp` messages count against its event budget (120 a minute, 5,000 a session). Clients can't send
455
- `purchase` or `currency` rows; the analytics server's ingest also refuses client-marked ones (older engines) and its
456
- revenue queries count `purchase` rows the server sent.
457
- - **Friends in the server** (the join's `friends`): one `Players:GetFriendsAsync` per join (at most 10 pages, none
458
- when the player is alone) intersected with the players there, not a web call per player.
459
-
460
- **Settings, framework 0.4.0 / kernel 0.4.0 (plans/21):** the record's `backend` = `{ url, key, analytics?: { flushSeconds,
461
- recordShare } }` (`typetorch backend setup`) is the whole sink: DuckDB at `<url>/v1/ingest` with the one key (Basin
462
- identities to `<url>/v1/identity`). The old `analytics` value below is read while `backend` is missing, and stays the
463
- way to a Basin sink. The engine also tells the kernel each player's pid (`setAnalyticsId`: the kernel's error reports
464
- count affected players by pid, never by name) and counts its own DataStore and HTTP requests for the budget view (dev
465
- menu **Server > Budget**: bars per Roblox limit for the player count, who spends it, the DataStore budget left, memory).
466
-
467
- **Settings** (server only, never sent to clients): the signed settings record's `analytics` field (kernel 0.3.8,
468
- plans/20), derived from `backend` by `typetorch backend setup` (`writeBackendSettings()` in `@typetorch/backend` runs it, and
469
- `bun run local` too). Every new copy applies live within seconds (the CLI pings servers). A Basin sink has no CLI writer
470
- since CLI 0.9: `backend setup` replaces it. Before kernel 0.3.8
471
- there are no settings unless the game passes `new AnalyticsEngine({ settings })`:
472
-
473
- ```json
474
- { "backend": "basin", "events": "https://<stream-id>.ingest.cloudflare.com",
475
- "recordings": "https://<stream-id>.ingest.cloudflare.com", "token": "<write-only token>",
476
- "flushSeconds": 15, "recordShare": 1, "techEvery": 60,
477
- "experiments": { "onboarding": { "weights": [1, 1] } } }
478
- ```
479
-
480
- - `basin`: a JSON array per stream (`events`, `recordings`), `Authorization: Bearer <token>` when set (a token with
481
- Basin Pipelines Send permission, if the stream requires authentication). Without `recordings` nothing is recorded.
482
- The streams' schemas must match SCHEMA.md exactly: Basin drops rows that don't, silently.
483
- - `duckdb`: one `POST <events>` with `{"events":[...],"recordings":[...]}`, gzip, `Authorization: Bearer <token>`.
484
- - The token is write-only and never logged. Needs **Allow HTTP Requests** (Game Settings > Security). No key: the
485
- engine collects but keeps only the newest 1,000 rows until settings appear. Removing the key stops sending, live.
486
-
487
- ## Develop
488
-
489
- ```sh
490
- bun install
491
- bun run build # rbxtsc --type package -> out/
492
- ```
493
-
494
- - **Runtime of the transformer:** `src/reflection/` (`Reflect`, `Modding`, `t`) is a copy of
495
- `@typetorch/transformer`'s `runtime-kit/`; keep the two identical.
496
- - **Tests (Lune, offline):** `scripts/test-*.luau`; each file's header has its command (Lune is pinned in the
497
- kernel's and the template's `rokit.toml`). `scripts/test-generations.luau` takes a game's built payload:
498
- `cd ../template && bun run payload && lune run ../framework/scripts/test-generations.luau build/payload.rbxm` boots
499
- two generations in one VM and checks fresh registries, DI and generated guards, then runs the real `startServer`
500
- with stub kernels (onStart failures reported to kernel 0.3.2, raised on older ones; onClose), the health lines and
501
- the Branch tab / "Load a build" rules (`devtools/build-actions.ts`).
502
- To test framework changes before the template takes them, build the payload from a copy of the template whose
503
- `node_modules/@typetorch/framework/out` is this repo's `out/`.
504
- `scripts/test-state-inspect.luau` checks the state explorer's core (previews, raw reads only, cycles, paging,
505
- Maps/Sets with Instance keys, the depth limit, filters, request validation) and that `src/version.ts` matches
506
- package.json.
507
- `scripts/test-layout.luau` checks the dev menu's pane layout core (`devtools/layout.ts`: splits and their limits,
508
- closing, pop out and dock, singleton pages, ratios, focus, and cleaning a remembered layout).
509
- `scripts/test-modules.luau` runs the real `startServer`/`startClient` of `out/` (with RuntimeLib, Promise, trove and
510
- t from node_modules) over several generations that share a persist store: `Dependency<T>()`, `TypeTorch.module` /
511
- `tryModule` and their errors, `Lazy<T>` (parameters and fields, cycles, start order), network `emit` and request
512
- timeouts and `playerState` (swaps, leaves).
513
- `scripts/test-flamework-compat.luau` (same harness) drives `createFlameworkCompat` through each generation's
514
- dispatcher: connect (one thread per call, guards, Disconnect, troves), fire / except / broadcast / the call
515
- shorthand, setCallback with values and Promises, predict, a swap, and the client side (invoke, invokeWithTimeout,
516
- `createClient({ defaultTimeout })`).
517
- `scripts/test-analytics.luau` checks the analytics engine's pure parts (experiment assignment, settings, the queue
518
- and HTTP budget, tt-rec-1, the sink request bodies, the failure help); `test-analytics-server.luau` and
519
- `test-analytics-client.luau` run the compiled server and client cores against mocked services (sessions, intake,
520
- retries, a NetFail streak and its one log line a minute, a swap with a request in flight, shutdown; the recorder,
521
- screens, batching). `scripts/test-net-health.luau` checks the dev menu's Fleet API / Analytics status lines and
522
- Attention issues.
523
- - **Publishing:** `npm publish` runs `prepublishOnly` (clean + build). The package ships only `out/` (no
524
- `.tsbuildinfo`), `README.md` and `LICENSE`; check with `bun pm pack --dry-run`.
525
-
526
- - **Explorer class icons:** `assets/class-icons.png` (kept locally, not in the repo: it is Roblox's own texture) is
527
- the client's `content/textures/ClassImages.PNG` (a 2352x16 strip) repacked into a 32-column grid, because live
528
- clients downscale textures wider than 1024 px:
529
- `ffmpeg -i ClassImages.PNG -vf "untile=147x1,tile=32x5:color=0x00000000" class-icons.png`. It is uploaded as image
530
- `rbxassetid://97389585475400`; `scripts/gen-explorer-icons.ts` generates the index table.
531
-
532
- MIT licensed.
1
+ <img src="https://raw.githubusercontent.com/typetorch/docs/main/brand/typetorch.svg" width="64" alt="TypeTorch logo">
2
+
3
+ # @typetorch/framework
4
+
5
+ The roblox-ts framework of [TypeTorch](https://github.com/typetorch): hot-swappable modules (dependency injection,
6
+ lifecycle, troves), guarded networking over the kernel's stable remotes, UI helpers and the in-game dev menu.
7
+
8
+ It ships **inside every artifact**, so each generation runs its own fresh copy and framework fixes hot-swap like game
9
+ code. It needs the TypeTorch kernel in the place (`@typetorch/kernel`), which calls your `Server/boot` and
10
+ `Client/boot` modules.
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ npm i @typetorch/framework
16
+ npm i -D @typetorch/transformer
17
+ ```
18
+
19
+ (`bun add @typetorch/framework` and `bun add -d @typetorch/transformer` work the same.) The framework is a roblox-ts 3
20
+ package; `@typetorch/transformer` is its compiler plugin: it generates the network guards, the constructor dependency
21
+ ids of `@Service` / `@Controller` and your own macros. Nothing from Flamework is needed: `Modding`, `Reflect` and `t`
22
+ come from this package. The starter game ([template](https://github.com/typetorch/template)) has it all set up: clone
23
+ it and run `bun install`.
24
+
25
+ `tsconfig.json`:
26
+
27
+ ```jsonc
28
+ {
29
+ "compilerOptions": {
30
+ "experimentalDecorators": true,
31
+ // Every npm scope the game imports from must be a type root (roblox-ts rule).
32
+ "typeRoots": ["node_modules/@rbxts", "node_modules/@typetorch"],
33
+ "types": ["types", "compiler-types"],
34
+ "plugins": [
35
+ // Optional, first when present: $print/$warn with file and line (what every TypeTorch repo uses).
36
+ { "transform": "rbxts-transform-debug", "environmentRequires": {} },
37
+ { "transform": "@typetorch/transformer" }
38
+ ]
39
+ }
40
+ }
41
+ ```
42
+
43
+ The payload is a Rojo `Model` project. Map only this package from the `@typetorch` scope (the transformer is Node code
44
+ and the kernel lives in the place):
45
+
46
+ ```json
47
+ "include": {
48
+ "$path": "include",
49
+ "node_modules": {
50
+ "$className": "Folder",
51
+ "@rbxts": { "$path": "node_modules/@rbxts" },
52
+ "@typetorch": { "$className": "Folder", "framework": { "$path": "node_modules/@typetorch/framework" } }
53
+ }
54
+ }
55
+ ```
56
+
57
+ Each generation requires its own copy of the payload, so the framework and its `Reflect` registry start fresh on every
58
+ swap. It needs the TypeTorch kernel in the place (`@typetorch/kernel`).
59
+
60
+ ### Coming from Flamework
61
+
62
+ Game code only changes imports: `@Service`, `@Controller`, constructor injection, `Dependency<T>()`, the lifecycle
63
+ interfaces and `createNetwork` are the same.
64
+
65
+ | Flamework | TypeTorch |
66
+ |---|---|
67
+ | `rbxts-transformer-flamework` plugin, `node_modules/@flamework` type root | `@typetorch/transformer` plugin, `node_modules/@typetorch` type root |
68
+ | `import { Modding, Reflect } from "@flamework/core"` | `import { Modding, Reflect } from "@typetorch/framework"` |
69
+ | `import { Dependency } from "@flamework/core"` | `import { Dependency } from "@typetorch/framework"` (from onInit/onStart on, not in constructors) |
70
+ | `import type` + `Dependency<T>()` to break a cycle | the same, or `Lazy<T>` (below) |
71
+ | `ClientEvents.x.predict(...)` | `network.client.x.emit(...)` |
72
+ | `invokeWithTimeout(timeout, ...)` | `invokeWithTimeout(seconds, ...)` (seconds, 0.5 to 120) |
73
+ | `Observers.observeCharacter` / `observeLocalCharacter` (@rbxts/observers) | still fine: put the stop function in the trove, `this.trove.add(observeCharacter(...))` |
74
+ | `import { t } from "@rbxts/t"` (still fine) | also `import { t } from "@typetorch/framework"` |
75
+ | `@metadata flamework:parameters` keys, `"flamework:parameters"` metadata | `@metadata typetorch:parameters`, `"typetorch:parameters"` |
76
+ | `flamework.build`, `include/flamework`, the `@flamework` Rojo mapping | gone; delete them |
77
+ | `Networking.createEvent` / `createFunction` and their call sites | `createFlameworkCompat` (below) keeps every call site; `createNetwork` is the native API |
78
+
79
+ `typetorch migrate --from flamework` (CLI) does most of this, and the docs' `guides/from-flamework.md` has the whole
80
+ mapping.
81
+
82
+ ## Usage
83
+
84
+ ```ts
85
+ // src/server/boot.ts
86
+ import { startServer, type ServerKernel } from "@typetorch/framework";
87
+ import { BUILD } from "../shared/build";
88
+ export function boot(kernel: ServerKernel) {
89
+ return startServer(kernel, { modules: [script.Parent!.FindFirstChild("services")!], build: BUILD });
90
+ }
91
+
92
+ // src/shared/net.ts
93
+ import { createNetwork, type ProperReturns } from "@typetorch/framework";
94
+ interface ClientToServer { coins: { collect(coinId: string): void; balance(): ProperReturns<number> } }
95
+ interface ServerToClient { coins: { changed(total: number): void } }
96
+ export const network = createNetwork<ClientToServer, ServerToClient>();
97
+
98
+ // src/server/services/coin.service.ts
99
+ @Service()
100
+ export class CoinService extends Module implements OnStart {
101
+ constructor(private readonly score: ScoreService) { // injected
102
+ super();
103
+ }
104
+ onStart() {
105
+ this.trove.add(network.server.coins.collect.on((player, coinId) => this.score.add(player, 1)));
106
+ }
107
+ }
108
+ ```
109
+
110
+ - **Modules:** `@Service()` (server) and `@Controller()` (client) classes extending `Module`. Constructor parameters
111
+ are other modules, injected by type. Lifecycle: `OnInit` (sequential, dependencies first), `OnStart` (spawned),
112
+ `OnStop` (reverse order), `OnTick`, `OnPhysics`, `OnRender`, `OnPlayerAdded` (replays players already in the server).
113
+ - **Modules outside the constructor:** `Dependency<T>()` (or `TypeTorch.module<T>()`) returns the running module of
114
+ type T from anywhere: a method, a plain class a module built, a command handler. `TypeTorch.tryModule<T>()` returns
115
+ undefined instead of throwing. They work once every module is constructed (from onInit on); in a constructor, a
116
+ field initializer or module top-level code they throw `"ShopService isn't constructed yet: ..."`. Only this realm's
117
+ modules, and per generation: after a swap they return the new generation's instance. An `import type` of the class is
118
+ enough (no require cycle).
119
+ - **Cycles:** two modules that need each other take one side as `Lazy<T>`, resolved on first use:
120
+ `constructor(private readonly team: Lazy<TeamService>)` (needs `@typetorch/transformer` 0.2.1+) or a field,
121
+ `private readonly team = Lazy<TeamService>()` (any transformer). `this.team.get()` works from onInit on (in a
122
+ constructor it throws), and the start order ignores lazy edges. A cycle error names the cycle and suggests this.
123
+ - **Per-player state:** `this.ctx.playerState("cooldowns.v1", (player) => init)` (or `TypeTorch.playerState`) returns
124
+ `{ get, set, has, delete }` keyed by UserId. It survives swaps (persist), and a player's entry goes when they really
125
+ leave, never on a swap. The dev menu shows it under Modules > State > persist, `__playerState`.
126
+ - **Bad deploys roll back (kernel 0.3.2):** a server `onStart` that throws is reported to the kernel, which rolls the
127
+ server back to its last known good artifact when it happens within 30 s of start (so do 3 errors from the new
128
+ code's scripts in that time). On a real shutdown every module's `onStop` runs too (the kernel's BindToClose).
129
+ - **Troves:** every module gets `this.trove`; everything it creates or connects goes there, so a swap leaves nothing
130
+ behind. `TypeTorch.persist(key, init)` (or `this.ctx.persist`) keeps plain data across swaps.
131
+ - **Network:** `createNetwork<C2S, S2C>()` with nested namespaces. The server checks rate limits, shape limits and the
132
+ generated type guard on every client message. `setNetworkLimits({ "chat.say": { maxString: 200 } })` tunes a leaf.
133
+ Requests wait 15 s for the answer: `invokeWithTimeout(5, ...args)` sets it per call, and a leaf's `timeout`
134
+ (`setNetworkLimits({ "vc.spawn": { timeout: 30 } })`, read by the client, so set it in shared code) per leaf; both in
135
+ seconds, 0.5 to 120. `network.client.x.emit(...args)` runs this client's own `on` handlers for a server -> client
136
+ leaf right away, with no traffic (Flamework's `predict`); `network.server.x.emit(player, ...args)` does the same on
137
+ the server, for tests. A request handler may return a Promise: the answer waits for it.
138
+ - **Flamework networking names:** `createFlameworkCompat<C2SEvents, S2CEvents, C2SFunctions, S2CFunctions>()` returns
139
+ `{ ServerEvents, ClientEvents, ServerFunctions, ClientFunctions, GlobalEvents, GlobalFunctions }` with
140
+ `@flamework/networking` 1.x's methods (`connect` returning a connection, `fire(player | players)`, `broadcast`,
141
+ `except`, `predict`, `setCallback`, `invoke`, `invokeWithTimeout`, calling a leaf directly) on this same network:
142
+ same guards, limits and swap rules, so a Flamework game's call sites compile unchanged. Listeners run on their own
143
+ thread each, like Flamework's, and belong to the running generation (no trove needed). Not carried over: server ->
144
+ client requests, middleware, `Networking.Unreliable`. `typetorch build` notes a game still using it.
145
+ Across a swap (0.3.0): what the server sends a player waits until that player's client runs the new generation
146
+ (reliable messages are queued, unreliable ones dropped), and on kernel 0.3.2 a request the server can no longer
147
+ answer fails at once ("The game is updating, try again.") instead of timing out.
148
+ - **Macros:** `Modding` (from this package) declares compile-time macros that `@typetorch/transformer` fills in:
149
+ `/** @metadata macro */ export function guardOf<T>(guard?: Modding.Generic<T, "guard">) { return guard!; }` makes
150
+ `guardOf<Shape>()` compile to a `t` guard. `Modding.Generic<T, "id" | "text">`, `Many`, `Caller` and `TupleLabels`
151
+ work the same way; see the transformer's README.
152
+ - **UI:** `observeElement(trove, tag, (instance, elementTrove) => ...)`, `isRealFrame`, `popIn` / `popOut` / `bump`
153
+ (UIScale, never Size tweens) and `PopupQueue` (one modal at a time).
154
+ - **Dev menu:** devs (Studio, project members, dev badge) get a DEV button, `Ctrl+Shift+D` and `/tt dev`: artifact
155
+ (with how long the server and client generations have run, the server's uptime and the build's age), server status,
156
+ logs (server, own client, other players' clients), client and server dex, network stats, module state, a branch and
157
+ build picker (Server > Branch) and a Claude prompt. The sidebar, top to bottom: Artifact, Server, Network, Modules,
158
+ Manage, Logs, Dex, Claude. The window can be dragged by its header and resized from its corner (double-tap the
159
+ header to reset).
160
+ - **Server TPS (framework 0.4.2, kernel 0.4.2):** Server > Status has a *TPS* line next to Memory and Lua heap: the
161
+ last minute's average, its slowest second and the physics FPS (`59.9 avg, 52.0 min, physics 60`; the warning colour
162
+ under 50 on average). Older kernels show `needs kernel 0.4.2`. The same numbers ride on fleet heartbeats (the
163
+ explorer's fleet table).
164
+ - **Dev-only tools (framework 0.4.1, `devtools/access.ts`):** Claude, Logs > Upload, Dex edits on the server, Network
165
+ packet blocking and the hot-swap sound work under dev rules (private, reserved and Studio servers on a dev branch)
166
+ for every dev, and on a public server an owner switched to a dev branch (Server > Branch) for owners only. Everywhere
167
+ else the menu is read-only, with a short reason: "Dev branch only", "Owners only on public servers", "Owner-switched
168
+ servers only". The rules themselves don't change (`TypeTorch.channel`, signatures, owner-only rollbacks).
169
+ - **Panes and windows (dev menu):** every page shows in a pane with a small header: tap the title to pick another
170
+ page, or use Split right, Split down, Open in new window and Close. Drag the line between two panes to resize them.
171
+ The sidebar opens pages in the focused pane (the highlighted one; tap a pane to focus it). Floating windows move by
172
+ their title bar and resize from their corner (double-tap the title bar to maximise); their title bar also has
173
+ Minimise, Dock (back into the main panel) and Close. Windows can be split too. The layout, the windows and each
174
+ pane's own settings (for example the open nodes of two Modules > State panes) survive swaps; a fresh join starts
175
+ with one pane. Claude, Server > Branch and the Manage pages open once (picking them again focuses their pane); every
176
+ other page can be open several times. Panes nobody sees (menu closed, window minimised) stop refreshing, and panes
177
+ on the same data share one request (Status, Overview, Assets, Network > Stats, server Logs, Packets); State panes
178
+ share one query budget. On phones and small screens panes only stack (two at most), and windows open maximised with
179
+ one pane each.
180
+ - **State explorer (Modules > State, Server | Client):** every live module of the running generation (services on the
181
+ server, controllers on the client) and the persist store. Tap a row to open it: the module's own fields (not its
182
+ methods), then tables, arrays, Maps and Sets, 100 entries per page (Prev / Next). Each value has a short preview:
183
+ strings (cut), numbers, booleans, nil, datatypes through `tostring`, an Instance as its full path, a Player as its
184
+ name, `function`, `thread`, buffer sizes. Nothing is ever called (raw reads only: no metamethods, no getters); a
185
+ value that is its own ancestor shows as a cycle. A key filter (open nodes stay listed), Refresh and Auto (every 2 s).
186
+ Server state comes from the op `state.inspect` (rate-limited, size-capped): owners everywhere, other devs where the
187
+ dev-only tools are open to them, since server state can hold player data.
188
+ - **Logs > Upload:** sends the logs shown (Server: this server's log ring; Client: your own client's; Others: the
189
+ picked player's client) to the dev PC paired in the Claude tab, which saves them under `<repo>/.typetorch/logs/`.
190
+ No Claude run, no prompt quota. Not paired: "Pair in the Claude tab first".
191
+ - **Switch a live server (kernel 0.3.4):** owners switch any server and load builds on it, public and prod ones too:
192
+ Server > Branch, "Switch" on a branch or "Load here" on a build, then the green Confirm. Everyone stays. These are
193
+ ordinary switches and pins: Reload and Rollback keep working, and going back to prod is Switch on the prod row (its
194
+ verified head). A public switch lasts for that server's lifetime and is never stored, so new servers still boot the
195
+ signed prod head. Others see "Join", which moves only them to a reserved server. Manage > Servers "Load a build..."
196
+ does the same for this server, the ticked servers or a share of one branch (A/B pins), with one status line under
197
+ the list. A public server an owner switched to a dev branch opens the dev-only tools (Claude too) to owners.
198
+ - **Owners and devs:** two roles (no admins: an older kernel's or typetorch.json's "admin" counts as a dev). The Manage
199
+ group (Players, Servers, Bans) is for owners only.
200
+ - **Remote Claude** (a dev-only tool: dev rules, or owners on a public server an owner switched to a dev branch):
201
+ while `typetorch remote-claude` (`@typetorch/dev-server`) runs on a dev's machine, allowlisted devs prompt Claude
202
+ Code from the Claude tab. Each dev pairs once by pasting the pairing code printed by
203
+ typetorch-dev-server; the game server keeps the session URL and the tokens in memory and never sends them to clients.
204
+ No Roblox secret is needed.
205
+
206
+ ## Runtime API: `TypeTorch`
207
+
208
+ `import { TypeTorch } from "@typetorch/framework"` works on the server and the client. It describes the running
209
+ generation and raises events that belong to it: every listener is dropped when the generation stops, so a swap never
210
+ leaves one behind. Each `on*` returns a disconnect function, which a trove can own.
211
+
212
+ ```ts
213
+ // Identity
214
+ TypeTorch.artifact; // { id, commit, commitHash, branch, channel, builtAt, seq, assetId }
215
+ TypeTorch.generation; // 1, 2, 3... per server (or client)
216
+ TypeTorch.branch; TypeTorch.channel; TypeTorch.serverType; // "public" | "private" | "reserved" | "studio"
217
+ // Kernel 0.3.9: `channel` is the RULES this server runs under ("prod" on every public server; split data stores by it);
218
+ // `branchChannel` is what the branch IS ("prod" for the default branch or one configured prod, else "dev");
219
+ // `rules` is the same as `channel`, by name.
220
+ TypeTorch.branchChannel; TypeTorch.rules;
221
+ TypeTorch.isPinned(); TypeTorch.kernelVersion; TypeTorch.kernelApi; TypeTorch.jobId; TypeTorch.isStudio;
222
+
223
+ // How this generation started: a branch change starts a new generation.
224
+ const start = TypeTorch.startInfo; // { kind: "boot" | "swap", reason, previous?, branchChanged, requestedBy?, loadSeconds? }
225
+ if (start.reason === "auto_rollback") warn("the last deploy failed to start");
226
+ this.trove.add(TypeTorch.onBranchChanged(({ from, to }) => resetBranchData(from, to)));
227
+
228
+ // Before this generation stops (runs before every onStop; keep it short)
229
+ this.trove.add(TypeTorch.onSwapOut((info) => this.saveRound(info.reason)));
230
+
231
+ // A swap is coming: show a small hint, hide it if it's called off
232
+ this.trove.add(TypeTorch.onUpdatePending((update) => (hint.Visible = !update.cancelled)));
233
+
234
+ // State that survives swaps (plain data only)
235
+ const scores = TypeTorch.persist("scores.v1", () => new Map<number, number>());
236
+ // Per player, removed when the player really leaves (same as this.ctx.playerState)
237
+ const cooldowns = TypeTorch.playerState("cooldowns.v1", () => ({ lastUse: 0 }));
238
+ cooldowns.get(player).lastUse = os.clock();
239
+
240
+ // The running module of a type (same as Dependency<T>()), from onInit/onStart on
241
+ TypeTorch.module<ShopService>().open(player);
242
+ TypeTorch.tryModule<ShopService>()?.open(player); // undefined instead of an error
243
+
244
+ // Dev and roles (server: the kernel decides; client: only the local player, cosmetic)
245
+ if (TypeTorch.isOwner(player)) showOwnerPanel(player);
246
+ TypeTorch.onPlayerDevChanged((player, info) => setDevTools(player, info.dev));
247
+
248
+ // Server only
249
+ TypeTorch.status(); // uptime, players, memory, history: cheap
250
+ TypeTorch.branches(); TypeTorch.artifacts(); // registry reads, cached ~30 s: may yield, don't call per frame
251
+ TypeTorch.requestReload(player); // owners only, checked by the kernel
252
+
253
+ // Logs (the kernel's ring buffer)
254
+ TypeTorch.logs(0, 50);
255
+ TypeTorch.onLog((entry) => errors.push(entry)); // don't print from inside it
256
+
257
+ // Hot assets (below): same as hotAsset(...)
258
+ const shop = TypeTorch.asset("ui/shop");
259
+
260
+ // Live values, server only (kernel 0.3.8): the signed settings record's `game` field (`typetorch settings set game.<key> <json>`).
261
+ const price = TypeTorch.liveConfig("shop.price", { default: 50, parse: (raw) => (typeIs(raw, "number") ? raw : 50) });
262
+ price.get();
263
+ this.trove.add(price.onChanged((value) => this.reprice(value)));
264
+
265
+ // Cross-server, server only. Kernel 0.3.8: game topics over ONE kernel-held MessagingService topic; listeners hear
266
+ // prod servers and this branch by default (dev branches never reach prod); publish queues and retries, max 1 KiB.
267
+ this.trove.add(TypeTorch.messaging.subscribe<Ban>("1guard", (ban, meta) => applyBan(ban, meta.jobId)));
268
+ TypeTorch.messaging.publish("1guard", { kind: "ban", userId }, { to: "prod" });
269
+
270
+ // The universe's live servers (the roll call; cached per server, yields up to ~3 s when stale) and this server's public fields
271
+ TypeTorch.setServerInfo({ region: "eu", vc: true }); // JSON, at most 400 bytes, kept across swaps
272
+ const list = TypeTorch.servers(); // [{ jobId, placeVersion, players, maxPlayers, serverType, branch, channel, uptime, here, info }]
273
+
274
+ // A library call a swap must not cut off halfway (kernel 0.3.8): runs on a kernel thread; write what must survive into persist.
275
+ TypeTorch.runDetached(() => store.StartSessionAsync(`Player_${userId}`)).then((profile) => attach(player, profile));
276
+ ```
277
+
278
+ - **`startInfo.reason`:** `boot`, `deploy`, `rollback`, `branch`, `pin`, `reload`, `server_rollback`,
279
+ `auto_rollback` or `unknown`. A client's first generation is always `boot`. `requestedBy` (a user id), `loadSeconds`,
280
+ `stopSeconds` and `swapSeconds` are server-only; `swapSeconds` appears once the swap has finished.
281
+ - **`persist(key, init)`** keeps a table in the kernel's memory for the server's lifetime; every later generation gets
282
+ the same table back. Store plain data only: tables, arrays, Maps and Sets of strings, numbers, booleans, and
283
+ Players. Never store functions, class instances, Promises, threads, connections, charm atoms or instances this
284
+ generation created: they keep the old generation's code alive or are destroyed by its trove. Version the key when
285
+ the shape changes. Keys starting with `__` are reserved.
286
+ - **`onSwapOut`** runs synchronously before every module's `onStop`, so modules can still save into `persist`. It
287
+ doesn't run on server shutdown (kernel 0.3.2 runs `onStop` then; on older kernels use `game.BindToClose`).
288
+ - **Kernel versions:** `TypeTorch.features` says what the running kernel supports. Kernel 0.2.2 adds the start
289
+ reason and timings, the next artifact in `onSwapOut`, `onUpdatePending`, server-side `onPlayerDevChanged` and
290
+ `requestReload`. On older kernels `startInfo` still knows boot vs swap, the previous artifact and branch (the
291
+ framework records them), `onBranchChanged` still fires, and the reason of a swap is `unknown`.
292
+ - **`messaging`** (kernel 0.3.8): `subscribe(topic, (data, meta) => ...)` returns a disconnect; `meta` = `{ channel,
293
+ branch, jobId, serverType, placeVersion, sentAt, self, replayed? }`; `{ from: "all" | "prod" | "branch" }` changes
294
+ who it hears. `publish(topic, data, { to })` throws on a bad topic, non-JSON data or a message over 1 KiB (with its
295
+ size), returns false when dropped at once (queue full). Studio loops back; the cloud test publishes nothing; older
296
+ kernels throw "needs kernel 0.3.8". `servers()` works on every kernel (0.3.8 holds the roll call topic, so a swap
297
+ doesn't subscribe again).
298
+ - **`liveConfig(key, { default, parse? })`** (kernel 0.3.8, plans/20): reads `game[key]` of the signed settings record the
299
+ kernel verified (signed by both prod keys, so game code can't forge it); `get()` and `onChanged(fn)` (only on real
300
+ changes; generation-scoped). The default without a record or key, when `parse` throws (warned per value), and on older
301
+ kernels (warned once: "needs kernel 0.3.8"; no ConfigService fallback). `TypeTorch.settings()` is the whole copy
302
+ (`seq`, `at`, `game`, `analytics`, `fleet`, ...): server only, it holds tokens.
303
+ - **`runDetached(fn)`** (kernel 0.3.8, server only): runs `fn` on a thread the kernel owns, so a deploy's hard stop
304
+ (which kills this generation's threads mid-call) can't cut it off: for ProfileStore / ProfileService loads, saves and
305
+ releases. Returns a Promise that settles while this generation runs; after a swap the result is dropped, so a job
306
+ whose result must survive writes it into `persist` itself. The job keeps this generation's closures alive until it
307
+ ends. Errors reject it and go to the kernel's log with the generation's name (never the health window); at most 256
308
+ run at once per server (then it throws); one past 60 s is logged and flagged in Server > Status. Older kernels
309
+ throw "needs kernel 0.3.8; use the DataHost job queue (Player data guide)": the other option, which works on every
310
+ kernel. `features.runDetached` tells which one this server has.
311
+ - **Edit mode** (UI Labs stories, no kernel): `running` is false, identity has defaults, `persist` keeps a local table,
312
+ events never fire, and the server-only reads throw.
313
+
314
+ ## Player data
315
+
316
+ Saving player data is game code: pick any library (ProfileStore, DataStore2, your own). TypeTorch only gives you the
317
+ pieces that keep it safe across swaps:
318
+
319
+ - **The library lives in the place**, outside the payload, and a small place Script requires it first. Its open
320
+ sessions, autosave loop and shutdown hook then survive every swap (a swap stops the generation's scripts).
321
+ - **Session handles live in `persist`**, keyed by `UserId`. `onPlayerAdded` replays everyone after a swap, so it
322
+ re-attaches to the open session instead of loading again.
323
+ - **Release only on `Players.PlayerRemoving`**, never in `onStop` or `onSwapOut`.
324
+ - **Library calls can't be cut off by a swap:** run them as DataHost jobs (any kernel) or with
325
+ `TypeTorch.runDetached` (kernel 0.3.8).
326
+ - **Split store names by channel** (`TypeTorch.channel === "prod" ? "PlayerData" : "PlayerData_dev"`).
327
+
328
+ Full example with ProfileStore: [Player data guide](https://github.com/typetorch/docs/blob/main/guides/player-data.md).
329
+
330
+ ## Hot assets: `hotAsset`
331
+
332
+ Builders mark models and UI templates in the place with the attribute `TypeTorchAsset` (a key such as `"ui/shop"`),
333
+ `typetorch assets sync` uploads them, and the deploy puts the asset manifest in the artifact. Running servers then get
334
+ new versions live, with no restart.
335
+
336
+ ```ts
337
+ import { hotAsset } from "@typetorch/framework"; // or TypeTorch.asset("ui/shop")
338
+
339
+ // In a controller's onStart: rebuild clones the template.
340
+ const shop = hotAsset("ui/shop");
341
+ shop.changed(rebuild, this.trove); // a new version went live
342
+ rebuild(shop.get());
343
+ ```
344
+
345
+ - **`hotAsset(keyOrId, fallback?)`** works on the server and the client. A number is the Roblox asset id, resolved
346
+ through the manifest (server) or the live copy's `TypeTorchAssetId` attribute (client).
347
+ - `get()` returns the live copy now. With none, it returns `fallback` (an instance you already hold, such as the
348
+ template in the place) if it is still parented, else `undefined`. **Clone it; don't parent or edit it:** a new
349
+ version destroys it.
350
+ - `wait(timeout?)` is `get()` that waits for a live copy (forever without a timeout).
351
+ - `changed(fn, trove?)` calls `fn(instance)` each time a new copy replaces the live one: a new version, a rollback,
352
+ or the first copy reaching a client. It returns a disconnect function. Pass the module's trove so the connection
353
+ ends with it (`shop.changed(rebuild, this.trove)` or `this.trove.add(shop.changed(rebuild))`). Without a trove it
354
+ ends when the generation stops.
355
+ - `key` and `version` (the live copy's `TypeTorchAssetVersion`, an assetVersionId).
356
+ - **Clients never request anything.** They read the CollectionService tag `__typetorch_asset:<key>`, and replicated
357
+ assets arrive through replication. Assets under ServerStorage stay server-only.
358
+ - **AssetSync** is a server built-in. It runs on every generation start, before any module loads (top-level code
359
+ included). For each manifest key:
360
+ 1. it keeps the live copy that already has the manifest's version;
361
+ 2. else it adopts the place's own copy, if its `TypeTorchAssetHash` matches (or if the manifest's optional
362
+ `placeVersion` is this server's place version);
363
+ 3. else it runs `InsertService:LoadAssetVersion(ver)` (all loads in parallel), strips any scripts, places the copy
364
+ at its path (creating missing Folders), tags it, then destroys the copy it replaces.
365
+
366
+ It holds the start for at most 8 s. Loads still running after that keep going, swap in when done and fire
367
+ `changed`. A failed load keeps the old copy (on a new server, the place's copy) and shows under Server > Status >
368
+ Attention.
369
+ - **Hot assets persist across swaps.** They aren't in any trove. A swap changes them only when the manifest changes,
370
+ and a rollback brings back the older versions. **Keys the manifest doesn't name are left as they are:** AssetSync
371
+ never deletes builders' content. A key dropped from the manifest keeps its last live copy.
372
+ - **Clones never count.** A clone keeps the tag and the attributes, but only the copy whose parent is its
373
+ `TypeTorchAssetPath` (stamped by AssetSync) is the live one. So a template cloned into PlayerGui never shows up in
374
+ `get()`, and AssetSync never destroys it.
375
+ - **Dev menu:** Modules > Assets (Server | Client) lists each key's source (kept, baked, loaded, failed), version,
376
+ load time and last error.
377
+
378
+ ## Analytics: `AnalyticsEngine`
379
+
380
+ Optional, and all ours: the game server sends rows to the backend the dev picked (Cloudflare Basin streams, or a
381
+ self-hosted DuckDB analytics server). Nothing runs until an engine is created: no connections, threads or requests.
382
+
383
+ ```ts
384
+ import { AnalyticsEngine } from "@typetorch/framework";
385
+
386
+ // A server module (onInit): the sink comes from the signed settings' `analytics` (kernel 0.3.8).
387
+ const analytics = new AnalyticsEngine();
388
+ analytics.track(player, "quest_done", { quest: "tutorial" }); // custom
389
+ analytics.step(player, "onboarding", 3, "opened_shop"); // funnels
390
+ analytics.purchase(player, { product: 1234, robux: 99, where: "shop" }); // after the receipt is granted
391
+ analytics.currency(player, "coins", 50, "round_reward"); // economy in (+) and out (-)
392
+ analytics.state("round"); // every player's activity; analytics.state(player, "shop") for one
393
+ const variant = analytics.experiment(player, "onboarding", ["short", "long"]); // first = control
394
+
395
+ // A client controller (onStart): everything goes through the server, never to the internet.
396
+ const analytics = new AnalyticsEngine();
397
+ analytics.track("opened_map");
398
+ analytics.screen("Inventory"); // for UIs that aren't separate ScreenGuis
399
+ const variant = analytics.experiment("onboarding", ["short", "long"]); // same answer as the server's
400
+ ```
401
+
402
+ - **One engine per generation and realm.** Every `new AnalyticsEngine()` joins the one already running (the first one's
403
+ options win), so any module can create its own. It stops with the generation; its unsent rows wait in `persist`
404
+ and the next generation sends them. In edit mode (UI Labs) it is inert.
405
+ - **Server calls take the player first** (`track(player, ...)`); without one an event is server-only (no player id).
406
+ Client calls are always about the local player and are marked `src = "client"` (a client can lie). The server
407
+ checks their shape, size (props at most 4 KB) and rate. `purchase` and `currency` are server-only (revenue and the
408
+ economy are server-authoritative): on the client they warn once and send nothing, and the server refuses them from
409
+ clients.
410
+ - **Options** (all on by default): `sessions` (joins, leaves, device, join source, account age bucket, Premium,
411
+ country, friends in the server, first-ever vs returning, days since the last visit), `tech` (FPS, ping, memory, load
412
+ time, client and server errors, swaps and rollbacks, leaves within 60 s of a swap), `zones` (parts or models tagged
413
+ `TTZone`, named by a `Name` attribute or the instance name), `screens` (ScreenGuis in PlayerGui, GuiObjects tagged
414
+ `TTScreen`), `recording` (the first-ever session in detail), `fleet` (kernel 0.3.2 heartbeats and deploy reports),
415
+ `identity` (one `{ pid, uid }` row per session to the dev's own server, below). `settings` (server only) replaces the
416
+ signed settings' `analytics`, for tests, Studio and kernels before 0.3.8.
417
+ - **Every row** carries the time (server clock), a random player id (never the UserId), the session, the server
418
+ (JobId, type, place), the artifact (id, seq, branch, channel), the device, new vs returning, the player's state
419
+ (`zone:Lobby|screen:Shop|activity:round`) and experiment variants. The exact rows: `src/analytics/SCHEMA.md`.
420
+ - **Experiments:** `experiment(...)` is deterministic per player and name (they keep their variant in every session),
421
+ may yield briefly the first time (until the player's id loads), and stamps the variant on the player's later events.
422
+ The settings turn one off (`active: false`: everyone gets the first variant), sets `weights` or forces a
423
+ `variant`, live.
424
+ - **First-ever session:** for new players (a share of them, `recordShare`), the client records character and camera
425
+ about 10 times a second, every input (never while a TextBox or the chat has focus; text boxes only say which box was
426
+ used), buttons pressed and hovered, screens, prompts and deaths, from the join until 60 s after the first input.
427
+ Packed into small binary chunks (10-20 KB a player) and sent through the server.
428
+ - **Never collected:** chat or anything typed, usernames and display names (error texts have them replaced). No event
429
+ row carries a UserId.
430
+ - **Identities** (option `identity`, default on): once the pid is known, one row `{ pid, uid, t }` (the UserId, nothing
431
+ else) per session goes to the dev's own server only, never into the events: duckdb games in the batch body, Basin
432
+ games to the backend (the record's `backend` url + `/v1/identity`, or the `identity` / `identityToken` settings). The
433
+ analytics server keeps pid -> UserId in a deletable table (support lookups, Right to Erasure).
434
+ - **Player ids:** DataStore `TypeTorchAnalytics`, key `p/<UserId>` -> `{ pid, first, last }`: one read per join, a
435
+ write on the first join and at leave. Deleting the key (Right to Erasure) leaves that player's rows anonymous.
436
+ - **Sending:** one queue on the server (10,000 events; over that the oldest are dropped and counted), a flush every
437
+ `flushSeconds` (15) or at 500 rows, at most ~10 HttpService requests a minute, retries with backoff, and a last
438
+ flush on shutdown (kernel 0.3.2). Delivery is at least once (a swap mid-request sends that batch again).
439
+ `analytics.stats()` (server) has the counters; `flush()` sends soon.
440
+ - **When uploads fail** (a stale quick-tunnel URL, the dev PC's server or tunnel down, a wrong token, HttpService off;
441
+ Roblox reports most network problems as `HttpError: NetFail`, `DnsResolve` or `ConnectFail`): the server backs off
442
+ with jitter (5, 10, 20 ... 300 s, spread +-25% so a fleet of servers doesn't retry in step; a wrong token or URL waits
443
+ about 5 minutes, and a settings change retries at once), keeps the rows, and logs at most ONE line a minute: the
444
+ reason and the fix (`analytics upload failed 5 times in a row: NetFail: the connection broke mid-request. ... Retrying
445
+ in 80 s.`, with "(+N more in the last minute)" for the lines it held back) and one line when uploads work again.
446
+ `stats()` also has `failures` (in a row), `failed` (since the server started), `lastError`, `lastStatus`
447
+ (0 = no answer), `lastErrorAt` / `lastOkAt` (`os.time()`), `retryIn`, and, while failing, `reason` and `fix`. The dev
448
+ menu shows them: **Server > Status** has an *Analytics* line (queued, sent, `FAILING x5: ... retry in 80 s`) and a
449
+ *Fleet API* line (the kernel's sender: sent, failed, last error and its age), and **Attention** lists the reason and
450
+ the fix; `typetorch doctor` tests the address and token in the settings record.
451
+ - **The cloud test sends nothing.** `typetorch test --cloud` boots the payload headless in a Luau Execution task where
452
+ HttpService works; there the engine (stub kernel `test = true`, or `workspace:GetAttribute("TypeTorchTest")`) collects
453
+ as usual but never uploads: no event rows, no identity rows, no HTTP request, so a prod deploy never puts a fake
454
+ server session into your analytics.
455
+ - **Bounds on what a client can cause:** at most 32 experiments per session (each is stamped on every later row), and
456
+ a client's `exp` messages count against its event budget (120 a minute, 5,000 a session). Clients can't send
457
+ `purchase` or `currency` rows; the analytics server's ingest also refuses client-marked ones (older engines) and its
458
+ revenue queries count `purchase` rows the server sent.
459
+ - **Friends in the server** (the join's `friends`): one `Players:GetFriendsAsync` per join (at most 10 pages, none
460
+ when the player is alone) intersected with the players there, not a web call per player.
461
+
462
+ **Settings, framework 0.4.0 / kernel 0.4.0 (plans/21):** the record's `backend` = `{ url, key, analytics?: { flushSeconds,
463
+ recordShare } }` (`typetorch backend setup`) is the whole sink: DuckDB at `<url>/v1/ingest` with the one key (Basin
464
+ identities to `<url>/v1/identity`). The old `analytics` value below is read while `backend` is missing, and stays the
465
+ way to a Basin sink. The engine also tells the kernel each player's pid (`setAnalyticsId`: the kernel's error reports
466
+ count affected players by pid, never by name) and counts its own DataStore and HTTP requests for the budget view (dev
467
+ menu **Server > Budget**: bars per Roblox limit for the player count, who spends it, the DataStore budget left, memory).
468
+
469
+ **Settings** (server only, never sent to clients): the signed settings record's `analytics` field (kernel 0.3.8,
470
+ plans/20), derived from `backend` by `typetorch backend setup` (`writeBackendSettings()` in `@typetorch/backend` runs it, and
471
+ `bun run local` too). Every new copy applies live within seconds (the CLI pings servers). A Basin sink has no CLI writer
472
+ since CLI 0.9: `backend setup` replaces it. Before kernel 0.3.8
473
+ there are no settings unless the game passes `new AnalyticsEngine({ settings })`:
474
+
475
+ ```json
476
+ { "backend": "basin", "events": "https://<stream-id>.ingest.cloudflare.com",
477
+ "recordings": "https://<stream-id>.ingest.cloudflare.com", "token": "<write-only token>",
478
+ "flushSeconds": 15, "recordShare": 1, "techEvery": 60,
479
+ "experiments": { "onboarding": { "weights": [1, 1] } } }
480
+ ```
481
+
482
+ - `basin`: a JSON array per stream (`events`, `recordings`), `Authorization: Bearer <token>` when set (a token with
483
+ Basin Pipelines Send permission, if the stream requires authentication). Without `recordings` nothing is recorded.
484
+ The streams' schemas must match SCHEMA.md exactly: Basin drops rows that don't, silently.
485
+ - `duckdb`: one `POST <events>` with `{"events":[...],"recordings":[...]}`, gzip, `Authorization: Bearer <token>`.
486
+ - The token is write-only and never logged. Needs **Allow HTTP Requests** (Game Settings > Security). No key: the
487
+ engine collects but keeps only the newest 1,000 rows until settings appear. Removing the key stops sending, live.
488
+
489
+ ## Develop
490
+
491
+ ```sh
492
+ bun install
493
+ bun run build # rbxtsc --type package -> out/
494
+ ```
495
+
496
+ - **Runtime of the transformer:** `src/reflection/` (`Reflect`, `Modding`, `t`) is a copy of
497
+ `@typetorch/transformer`'s `runtime-kit/`; keep the two identical.
498
+ - **Tests (Lune, offline):** `scripts/test-*.luau`; each file's header has its command (Lune is pinned in the
499
+ kernel's and the template's `rokit.toml`). `scripts/test-generations.luau` takes a game's built payload:
500
+ `cd ../template && bun run payload && lune run ../framework/scripts/test-generations.luau build/payload.rbxm` boots
501
+ two generations in one VM and checks fresh registries, DI and generated guards, then runs the real `startServer`
502
+ with stub kernels (onStart failures reported to kernel 0.3.2, raised on older ones; onClose), the health lines and
503
+ the Branch tab / "Load a build" rules (`devtools/build-actions.ts`).
504
+ To test framework changes before the template takes them, build the payload from a copy of the template whose
505
+ `node_modules/@typetorch/framework/out` is this repo's `out/`.
506
+ `scripts/test-state-inspect.luau` checks the state explorer's core (previews, raw reads only, cycles, paging,
507
+ Maps/Sets with Instance keys, the depth limit, filters, request validation) and that `src/version.ts` matches
508
+ package.json.
509
+ `scripts/test-layout.luau` checks the dev menu's pane layout core (`devtools/layout.ts`: splits and their limits,
510
+ closing, pop out and dock, singleton pages, ratios, focus, and cleaning a remembered layout).
511
+ `scripts/test-modules.luau` runs the real `startServer`/`startClient` of `out/` (with RuntimeLib, Promise, trove and
512
+ t from node_modules) over several generations that share a persist store: `Dependency<T>()`, `TypeTorch.module` /
513
+ `tryModule` and their errors, `Lazy<T>` (parameters and fields, cycles, start order), network `emit` and request
514
+ timeouts and `playerState` (swaps, leaves).
515
+ `scripts/test-flamework-compat.luau` (same harness) drives `createFlameworkCompat` through each generation's
516
+ dispatcher: connect (one thread per call, guards, Disconnect, troves), fire / except / broadcast / the call
517
+ shorthand, setCallback with values and Promises, predict, a swap, and the client side (invoke, invokeWithTimeout,
518
+ `createClient({ defaultTimeout })`).
519
+ `scripts/test-analytics.luau` checks the analytics engine's pure parts (experiment assignment, settings, the queue
520
+ and HTTP budget, tt-rec-1, the sink request bodies, the failure help); `test-analytics-server.luau` and
521
+ `test-analytics-client.luau` run the compiled server and client cores against mocked services (sessions, intake,
522
+ retries, a NetFail streak and its one log line a minute, a swap with a request in flight, shutdown; the recorder,
523
+ screens, batching). `scripts/test-net-health.luau` checks the dev menu's Fleet API / Analytics status lines and
524
+ Attention issues.
525
+ - **Publishing:** `npm publish` runs `prepublishOnly` (clean + build). The package ships only `out/` (no
526
+ `.tsbuildinfo`), `README.md` and `LICENSE`; check with `bun pm pack --dry-run`.
527
+
528
+ - **Explorer class icons:** `assets/class-icons.png` (kept locally, not in the repo: it is Roblox's own texture) is
529
+ the client's `content/textures/ClassImages.PNG` (a 2352x16 strip) repacked into a 32-column grid, because live
530
+ clients downscale textures wider than 1024 px:
531
+ `ffmpeg -i ClassImages.PNG -vf "untile=147x1,tile=32x5:color=0x00000000" class-icons.png`. It is uploaded as image
532
+ `rbxassetid://97389585475400`; `scripts/gen-explorer-icons.ts` generates the index table.
533
+
534
+ MIT licensed.