A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(sdk): a reloaded bundle addresses the world it is reloading into
esenginef7e1d0554aad
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1fbfd73e9..ca6a43816 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -173,6 +173,31 @@ published separately; it ships inside the editor.Skinned meshes take no bake: bones move a character, and a bake cannot hold onestill long enough to light it.+### Fixed++- **A hot reload no longer empties the running game of every resource**+ ([#60](https://github.com/esengine/estella/issues/60)). Edit a script while the+ game is playing and the editor re-imports the bundle and swaps the system+ bodies in place, keeping the live World. The re-imported `defineResource`+ minted a *fresh* identity, so every swapped system addressed a slot nothing had+ filled — and a resource read that misses does not fail, it materialises the+ default, which for the usual `defineResource<T>(null!, 'Name')` is `null`. The+ symptom was the whole project throwing `Cannot read properties of null` from+ every system, every frame, one edit after Play, until something forced a full+ restart. `defineEvent` had the same flaw: its re-import wrote to a bus nothing+ resolving the event by name could reach, and left the old one behind.++ Both are now interned by NAME, module-globally, the way component identity+ already was — so two declarations of one name are one resource (one event), and+ a re-evaluated bundle lands on the live world's storage. A name was already the+ address a compiled manifest, `getResourceByName` and the editor's resource list+ used; the symbol was the one door that disagreed, which is why `declaredResource`+ needed an "ambiguous" state to cope. That state is gone with the disagreement.++ `check-reload-identity` is the gate: every public `define*` door owes an answer+ about what its *second* evaluation addresses — read from its source, not from a+ list — so a door added later cannot be silent about it.+## [0.66.0] - 2026-09-14### Addeddiff --git a/sdk/src/ecs/event.ts b/sdk/src/ecs/event.tsindex b8f127230..65c898dca 100644--- a/sdk/src/ecs/event.ts+++ b/sdk/src/ecs/event.ts@@ -47,17 +47,27 @@ export interface EventDef<T> {*/export function defineEvent<T>(name: string, payload?: T & object): EventDef<T> {const def: EventDef<T> = {- _id: Symbol(`Event_${name}`),+ _id: eventId(name),_name: name,...(payload === undefined ? {} : { _default: payload as object }),};- // By name as well, because a compiled module's manifest carries names. The- // FIRST wins: a second event of the same name is a different event, and- // quietly rebinding the name would deliver one system's payloads to another.- if (!byName.has(name)) byName.set(name, def as EventDef<unknown>);+ byName.set(name, def as EventDef<unknown>);return def;}+// Interned by NAME, like component and resource identity. A manifest addresses+// an event by name, so a fresh symbol per call made the two doors disagree: a+// hot reload's systems wrote to a bus nothing resolving by name could reach.+const eventIdRegistry = new Map<string, symbol>();+function eventId(name: string): symbol {+ let id = eventIdRegistry.get(name);+ if (id === undefined) {+ id = Symbol(`Event_${name}`);+ eventIdRegistry.set(name, id);+ }+ return id;+}+const byName = new Map<string, EventDef<unknown>>();/**diff --git a/sdk/src/ecs/resource.ts b/sdk/src/ecs/resource.tsindex f98e1f6f7..4af57b7be 100644--- a/sdk/src/ecs/resource.ts+++ b/sdk/src/ecs/resource.ts@@ -30,29 +30,39 @@ export interface ResourceDef<T> {let resourceCounter = 0;+// Interned by NAME, module-globally, like component identity (component.ts). A+// hot reload re-evaluates this declaration, and a fresh symbol would address a+// slot nothing filled — which `get` answers with the DEFAULT, not a failure.+const resourceIdRegistry = new Map<string, symbol>();+function resourceId(name: string): symbol {+ let id = resourceIdRegistry.get(name);+ if (id === undefined) {+ id = Symbol(`Resource_${name}`);+ resourceIdRegistry.set(name, id);+ }+ return id;+}+/**- * Declare a resource: one value the whole world shares, addressed by the- * definition rather than by a name. `name` is for diagnostics and the editor- * only — two calls answer two distinct resources however they are named.+ * Declare a resource: one value the whole world shares. A NAMED one is addressed+ * by its name, so two declarations of one name are one resource; an unnamed one+ * is addressed by the definition, and two calls answer two.+ *+ * An empty slot materialises the LATEST declaration's `defaultValue`.** @public*/export function defineResource<T>(defaultValue: T, name?: string): ResourceDef<T> {- const id = ++resourceCounter;+ const anonymous = `Resource_${++resourceCounter}`;const def: ResourceDef<T> = {- _id: Symbol(`Resource_${id}_${name ?? ''}`),- _name: name ?? `Resource_${id}`,+ _id: name === undefined ? Symbol(anonymous) : resourceId(name),+ _name: name ?? anonymous,_default: defaultValue};// The engine's own resources answer to their NAME too, because a compiled- // module's manifest carries names. Only the DECLARED ones: a project's- // resource is identified by reference, and two may share a name.+ // module's manifest carries names.if (name && RESOURCE_SHAPES[name]) builtinByName.set(name, def as ResourceDef<unknown>);- else if (name !== undefined) {- // Two declarations of one name cannot both be what a manifest means.- if (declaredByName.has(name)) ambiguousNames.add(name);- declaredByName.set(name, def as ResourceDef<unknown>);- }+ else if (name !== undefined) declaredByName.set(name, def as ResourceDef<unknown>);return def;}@@ -60,7 +70,6 @@ export function defineResource<T>(defaultValue: T, name?: string): ResourceDef<Tconst builtinByName = new Map<string, ResourceDef<unknown>>();/** And for the names a PROJECT declares, which a manifest also carries. */const declaredByName = new Map<string, ResourceDef<unknown>>();-const ambiguousNames = new Set<string>();/*** The engine resource a manifest's NAME refers to, or undefined when the module@@ -78,13 +87,12 @@ export function builtinResource(name: string): ResourceDef<unknown> | undefined* A named resource a project DECLARED, whether or not anything has inserted one.** The storage learns a name on INSERT, so a resource nothing had touched was- * invisible to the AOT handshake. Undefined for an AMBIGUOUS name: two- * declarations sharing one is a project no manifest can describe.+ * invisible to the AOT handshake.** @internal*/export function declaredResource(name: string): ResourceDef<unknown> | undefined {- return ambiguousNames.has(name) ? undefined : declaredByName.get(name);+ return declaredByName.get(name);}// =============================================================================diff --git a/sdk/tests/ecs-vocabulary.test.ts b/sdk/tests/ecs-vocabulary.test.tsindex a56ad60eb..dda013ff4 100644--- a/sdk/tests/ecs-vocabulary.test.ts+++ b/sdk/tests/ecs-vocabulary.test.ts@@ -216,12 +216,19 @@ describe('resource vocabulary', () => {expect(descriptor._resource).toBe(Score);});- it('two definitions are two resources however they are named', () => {- // The name is diagnostics, not identity: a project that reuses one must- // still get its own value rather than silently sharing.+ it('a name IS the identity: two declarations of one name are one resource', () => {+ // Every other door already addressed a resource by name (a compiled+ // manifest, getResourceByName, the editor's list). The symbol was the one+ // that did not, so a re-imported bundle addressed a slot nothing filled.const a = defineResource(0, 'VocabDuplicate');const b = defineResource(0, 'VocabDuplicate');- expect(a._id).not.toBe(b._id);+ expect(a._id).toBe(b._id);+ });++ it('and only within one name — the sabotage that makes the above mean something', () => {+ expect(defineResource(0, 'VocabA')._id).not.toBe(defineResource(0, 'VocabB')._id);+ // An UNNAMED resource has no address to share, so each call is its own.+ expect(defineResource(0)._id).not.toBe(defineResource(0)._id);});});diff --git a/sdk/tests/event.test.ts b/sdk/tests/event.test.tsindex 1c2f1cc7e..55bf0d34c 100644--- a/sdk/tests/event.test.ts+++ b/sdk/tests/event.test.ts@@ -30,10 +30,13 @@ describe('defineEvent', () => {expect(a._id).not.toBe(b._id);});- it('should create unique ids even for same name', () => {+ it('answers the same id for the same name, so a re-imported bundle rebinds', () => {+ // A hot reload re-evaluates the project bundle, so this declaration runs+ // again; a fresh id would give the new systems a bus of their own while+ // everything addressing the event by name still answered the old one.const a = defineEvent('Same');const b = defineEvent('Same');- expect(a._id).not.toBe(b._id);+ expect(a._id).toBe(b._id);});});diff --git a/sdk/tests/hot-reload-resource-identity.test.ts b/sdk/tests/hot-reload-resource-identity.test.tsnew file mode 100644index 000000000..e3fc51eef--- /dev/null+++ b/sdk/tests/hot-reload-resource-identity.test.ts@@ -0,0 +1,108 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file hot-reload-resource-identity.test.ts+ * @brief A re-imported bundle's resources must address the live World's, the+ * way its components already do.+ *+ * @details Issue #60. A hot-swap reload keeps the live World and its+ * ResourceStorage but installs system bodies from a re-EVALUATED+ * module. Every module-level identity that re-evaluation mints again+ * must therefore be stable by name, or the new bodies address slots+ * nothing ever filled — and a resource read that misses does not+ * throw, it materialises the DEFAULT, which for the+ * `defineResource<T>(null!, 'Name')` idiom is null.+ */+import { describe, it, expect, beforeEach } from 'vitest';+import { App } from '../src/app/app';+import { defineSystem, Schedule, addSystemToSchedule } from '../src/ecs/system';+import { defineResource, declaredResource, Res, type ResourceDef } from '../src/ecs/resource';+import { defineEvent, eventNamed, EventRegistry } from '../src/ecs/event';+import { setDefaultContext, AppContext, getDefaultContext } from '../src/ecs/context';+import { probeRegistrations } from '../src/hotReload';++interface MatchState { phase: string }++describe('a project resource across a bundle re-import', () => {+ beforeEach(() => setDefaultContext(new AppContext()));++ it('survives the whole reload chain: probe, hot-swap, next frame', async () => {+ // The chain playHost.ts runs on a script edit while the game is live —+ // and issue #60 in one test: every system began reading null from every+ // resource, one frame after the edit, and the game just stopped being it.+ const app = App.new();+ let seen: MatchState | null | undefined;+ const body = (state: MatchState): void => { seen = state; };+ // Read through a typed accessor: the assignment happens inside a system+ // the type checker cannot see run, so a direct read narrows to `undefined`.+ const read = (): MatchState | null | undefined => seen;++ // Evaluation #1 — the bundle as the running session imported it.+ const declare = (): ResourceDef<MatchState> => {+ const MatchState = defineResource<MatchState>(null!, 'MatchState');+ addSystemToSchedule(Schedule.Update, defineSystem([Res(MatchState)], body, { name: 'match-flow' }));+ return MatchState;+ };+ const evaluation1 = declare();+ const live = getDefaultContext().drainPendingSystems();+ app.addBundleSystems(live as Parameters<App['addBundleSystems']>[0]);+ app.insertResource(evaluation1, { phase: 'playing' });+ await app.tick(1 / 60);+ expect(read()?.phase).toBe('playing');++ // Evaluation #2 — the same source, re-imported under a cache-busted URL,+ // in the throwaway context the probe installs.+ seen = undefined;+ const { pending } = await probeRegistrations(async () => { declare(); });+ expect(app.hotSwapSystems(pending as Parameters<App['hotSwapSystems']>[0])).toBe(true);+ await app.tick(1 / 60);++ expect(read()).not.toBeNull();+ expect(read()?.phase).toBe('playing');+ });++ it('a write through the re-imported def lands on the live slot', () => {+ const app = App.new();+ const V1 = defineResource<MatchState>(null!, 'MatchState2');+ app.insertResource(V1, { phase: 'playing' });+ const V2 = defineResource<MatchState>(null!, 'MatchState2');++ app.insertResource(V2, { phase: 'won' });++ expect(app.getResource(V1).phase).toBe('won');+ });++ it('stays addressable by name — a re-import is not an ambiguous declaration', () => {+ defineResource<MatchState>(null!, 'MatchState3');+ defineResource<MatchState>(null!, 'MatchState3');++ expect(declaredResource('MatchState3')).toBeDefined();+ });+});++describe('a project event across a bundle re-import', () => {+ it('keeps one identity, so the name door and the running systems agree', () => {+ const registry = new EventRegistry();+ registry.register(defineEvent<{ amount: number }>('Damage'));++ // Evaluation #2 — the same declaration, re-imported.+ const DamageV2 = defineEvent<{ amount: number }>('Damage');+ registry.getBus(DamageV2).send({ amount: 7 });+ registry.swapAll();++ // Whoever resolves the event by NAME — the AOT manifest handshake — must+ // land on the bus the live systems actually write.+ expect(eventNamed('Damage')?._id).toBe(DamageV2._id);+ expect(registry.busNamed('Damage')?.getReadBuffer()).toEqual([{ amount: 7 }]);+ });++ it('does not mint a fresh bus per reload', () => {+ const registry = new EventRegistry();+ const buses = (registry as unknown as { buses_: Map<symbol, unknown> }).buses_;+ registry.register(defineEvent('Healed'));+ const after1 = buses.size;+ registry.register(defineEvent('Healed'));++ expect(buses.size).toBe(after1);+ });+});diff --git a/sdk/tests/native-module-identity.test.ts b/sdk/tests/native-module-identity.test.tsindex e55c35423..eb67822f6 100644--- a/sdk/tests/native-module-identity.test.ts+++ b/sdk/tests/native-module-identity.test.ts@@ -4,16 +4,18 @@* @file native-module-identity.test.ts — a subpath a native game imports and* the graph the runtime installs from are ONE module.*- * `Res` is keyed by identity, so a separately bundled `esengine/physics3d`- * mints a second `Physics3D`: the runtime installs a resource under the first,- * the game asks with the second, and the two halves miss each other with no- * error anywhere. `Physics3D !== undefined` cannot see that — the last case- * here is the sabotage, and it is what makes the assertion above mean something.+ * A separately bundled `esengine/physics3d` mints a second `Physics3D`, and+ * everything it carries is then a second copy: the plugin, the queries object,+ * the bridge to the module. The RESOURCE token survives that — identity is+ * interned by name (resource.ts) — but nothing else does, so the namespace still+ * has to hand back this graph's exports rather than a rival's.+ * `Physics3D !== undefined` cannot see any of it; the last cases here are the+ * sabotage, and they are what make the assertions above mean something.*/import { describe, it, expect } from 'vitest';import { App } from '../src/app/app';import { defineResource } from '../src/ecs/resource';-import { Physics3D } from '../src/physics3d/Physics3DPlugin';+import { Physics3D, Physics3DPlugin } from '../src/physics3d/Physics3DPlugin';import { Physics2D } from '../src/physics/Physics2DPlugin';import { Spine } from '../src/spine/SpinePlugin';import {@@ -66,14 +68,27 @@ describe('identity, which is the whole point', () => {expect(app.hasResource(asTheGameImportsIt)).toBe(true);});- it('a second bundle of the same module is NOT found — the failure this prevents', () => {+ it('a second bundle of the same module still addresses the one slot', () => {const app = App.new();app.insertResource(Physics3D, null);- // Byte-for-byte what Physics3DPlugin.ts declares. Same name, same default,- // different object — which is all a separately bundled subpath would be.+ // Byte-for-byte what Physics3DPlugin.ts declares: same name, different+ // object — a separately bundled subpath, and equally a hot reload.const rival = defineResource<unknown>(null, 'Physics3D');- expect(app.hasResource(rival)).toBe(false);expect(rival).not.toBe(Physics3D);+ expect(app.hasResource(rival)).toBe(true);+ });++ it('and a DIFFERENT name is a different slot — the sabotage', () => {+ const app = App.new();+ app.insertResource(Physics3D, null);+ expect(app.hasResource(defineResource<unknown>(null, 'Physics3DRival'))).toBe(false);+ });++ it('but the namespace must still hand back THIS graph\'s plugin, not a rival\'s', () => {+ // The name rescues the resource TOKEN and nothing else: a rival bundle's+ // plugin would install a rival's queries against a rival's wasm module,+ // and no name anywhere would reconcile the two.+ expect(imported('esengine/physics3d').Physics3DPlugin).toBe(Physics3DPlugin);});});diff --git a/tools/check-native-subpath-imports.mjs b/tools/check-native-subpath-imports.mjsindex c10fb5b89..1b75035a8 100644--- a/tools/check-native-subpath-imports.mjs+++ b/tools/check-native-subpath-imports.mjs@@ -11,9 +11,9 @@** Each subpath is represented by an export the CORE namespace does not have, so* a regression that quietly re-flattens subpaths onto `globalThis.ESEngine`- * fails here instead of on a phone. physics3d carries the identity claim, since- * `Res` is keyed by object identity and a second copy is invisible to any check- * that only asks whether a name is defined.+ * fails here instead of on a phone. physics3d carries the identity claim: a+ * resource token answers to its NAME (resource.ts), so a second copy resolves —+ * but a token by another name must not, or the claim asks nothing.** node tools/check-native-subpath-imports.mjs*/@@ -97,7 +97,7 @@ function exportNative(dir, name) {}// 2. The host's own bundle publishes what those scripts will ask for, and the-// token is the one the runtime installs under — not a same-named twin.+// token a script holds reaches the slot the runtime installs under.{const harness = path.join(WORK, 'harness.mjs');writeFileSync(harness, `@@ -114,7 +114,8 @@ const { App } = globalThis.ESEngine;const app = App.new();app.insertResource(p3, null);out.identity = app.hasResource(p3) === true;-out.rivalRejected = app.hasResource(globalThis.ESEngine.defineResource(null, 'Physics3D')) === false;+out.rivalResolves = app.hasResource(globalThis.ESEngine.defineResource(null, 'Physics3D')) === true;+out.strangerRejected = app.hasResource(globalThis.ESEngine.defineResource(null, 'Physics3DStranger')) === false;console.log(JSON.stringify(out));`);const r = spawnSync(process.execPath, [harness], { encoding: 'utf8', cwd: ROOT });@@ -131,8 +132,10 @@ console.log(JSON.stringify(out));}check('a resource installed by the runtime answers to the imported token',seen.identity === true, 'Res(Physics3D) resolves');- check('a same-named token from a second bundle does NOT',- seen.rivalRejected === true, 'identity, not the name, is the key');+ check('a same-named token from a second bundle reaches the same slot',+ seen.rivalResolves === true, 'the name is the address — a re-import lands on it');+ check('and a token by another name does NOT',+ seen.strangerRejected === true, 'the sabotage: without it the claim above asks nothing');}}diff --git a/tools/check-reload-identity.mjs b/tools/check-reload-identity.mjsnew file mode 100644index 000000000..31ec0dbe3--- /dev/null+++ b/tools/check-reload-identity.mjs@@ -0,0 +1,242 @@+#!/usr/bin/env node+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file check-reload-identity.mjs — what a project DECLARES is addressed by name.+ *+ * A hot reload re-EVALUATES the project bundle, so every `define*` at its module+ * level runs a second time. Whatever those calls mint is an address into a World+ * that is still alive, so the second evaluation has to land on the first one's+ * storage — which it can only do if the address is derived from the declared+ * NAME rather than minted fresh.+ *+ * Components were interned that way from the start. Resources and events were+ * not, and issue #60 is what that looks like from the outside: one edit to a+ * script while the game was running, and every system in the project began+ * reading `null` from every resource, every frame — because a resource read that+ * MISSES does not throw, it materialises the default. Nothing failed; the game+ * just stopped being the game.+ *+ * So the rule guarded here is not "resources are interned" — it is that every+ * public `define*` door has an ANSWER about the second evaluation:+ *+ * 1. Every `define*` on the governed public surface appears below. A new door+ * is a new address a project can mint, and it does not get to be silent.+ * 2. A door dispositioned `interned` routes its `_id` through a name-keyed+ * `Map<string, symbol>` — read from its source, not from this table.+ * 3. A door dispositioned `fresh` does the opposite, and owes the reason why+ * re-evaluating it is supposed to produce a new thing.+ * 4. A door dispositioned `delegates` mints nothing of its own; it must call+ * one of the interned doors, or it is minting an address unexamined.+ *+ * The behaviour itself is held by sdk/tests/hot-reload-resource-identity.test.ts,+ * which re-declares each door and reads the live value back. This gate is the+ * half a test cannot do: notice a door that does not exist yet.+ *+ * Run: node tools/check-reload-identity.mjs (exit 1 on violation)+ */+import { readFileSync, readdirSync, statSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const SRC = path.join(ROOT, 'sdk', 'src');+const ETC = path.join(ROOT, 'sdk', 'etc');++/**+ * What each public declaration door does about a second evaluation.+ *+ * `interned` — the id comes from the name, so the re-imported declaration is the+ * same declaration. `fresh` — a new one every call, and `why` says what makes+ * that right. `delegates` — no id of its own; `via` is the door it mints through.+ */+const DISPOSITIONS = {+ defineComponent: { kind: 'interned' },+ defineTag: { kind: 'interned' },+ defineResource: { kind: 'interned' },+ defineEvent: { kind: 'interned' },+ defineSystem: {+ kind: 'fresh',+ why: 'a system IS the code being replaced — App.hotSwapSystems swaps the bodies '+ + 'wholesale, so a stable id would only let a stale body be mistaken for a live one',+ },+ defineSystemSet: { kind: 'no-id', why: 'a set is addressed by its _name; it mints no symbol' },+ defineInputMap: { kind: 'no-id', why: 'a plain action table — nothing addresses a World through it' },+ defineBehavior: { kind: 'delegates', via: 'defineComponent' },+};++const problems = [];++// ---------------------------------------------------------------------------+// 1. The doors, from the governed surface rather than from a list here.+// ---------------------------------------------------------------------------+const publicDoors = new Set();+for (const file of readdirSync(ETC).filter((f) => f.endsWith('.api.md'))) {+ const text = readFileSync(path.join(ETC, file), 'utf8');+ for (const m of text.matchAll(/^## (define[A-Za-z0-9_]*) — function/gm)) publicDoors.add(m[1]);+}+if (publicDoors.size === 0) {+ console.error('check-reload-identity: read no define* doors out of sdk/etc/*.api.md — '+ + 'the snapshot moved or changed shape, and this gate was passing on an empty world.');+ process.exit(1);+}+for (const door of publicDoors) {+ if (!DISPOSITIONS[door]) {+ problems.push(`${door} is public and has no disposition. A project can declare one at module `+ + 'level, so a hot reload re-runs it: say whether its address is derived from the name '+ + '(interned), deliberately new each time (fresh, with why), or not an address at all.');+ }+}+for (const door of Object.keys(DISPOSITIONS)) {+ if (!publicDoors.has(door)) {+ problems.push(`${door} has a disposition here but is no longer on the public surface — `+ + 'drop the entry rather than leave this gate guarding something that left.');+ }+}++// ---------------------------------------------------------------------------+// 2-4. …held against what the source actually does.+// ---------------------------------------------------------------------------+const files = [];+(function walk(dir) {+ for (const entry of readdirSync(dir)) {+ const full = path.join(dir, entry);+ if (statSync(full).isDirectory()) walk(full);+ else if (entry.endsWith('.ts')) files.push(full);+ }+})(SRC);++/**+ * The block a function signature starting at `at` opens.+ *+ * Not "the next `{`": a return type can carry one (`ComponentDef<{}>`), and+ * taking that as the body read defineTag as a function that does nothing — a+ * gate reporting a clean door because it never saw the door.+ */+function braced(text, at) {+ let i = text.indexOf('(', at);+ if (i < 0) return null;+ for (let depth = 0; i < text.length; i++) {+ if (text[i] === '(') depth++;+ else if (text[i] === ')' && --depth === 0) { i++; break; }+ }+ let angle = 0;+ for (; i < text.length; i++) {+ if (text[i] === '<') angle++;+ else if (text[i] === '>') angle--;+ else if (text[i] === '{' && angle === 0) break;+ }+ const open = i;+ if (open >= text.length) return null;+ let depth = 0;+ for (let j = open; j < text.length; j++) {+ if (text[j] === '{') depth++;+ else if (text[j] === '}' && --depth === 0) return text.slice(open, j + 1);+ }+ return null;+}++/** The body of a function declared in `source`, exported or not. */+function functionBody(source, name) {+ const at = source.search(new RegExp(`^(export )?function ${name}\\b`, 'm'));+ return at < 0 ? null : braced(source, at);+}++/** The body of `export function <name>`, and the file it lives in. */+function bodyOf(name) {+ for (const file of files) {+ const whole = readFileSync(file, 'utf8');+ const at = whole.search(new RegExp(`^export function ${name}\\b`, 'm'));+ if (at < 0) continue;+ const text = braced(whole, at);+ if (text) return { text, file, whole };+ }+ return null;+}++const idsIn = (body) => [...body.matchAll(/_id:\s*([^,\n]+)/g)].map((m) => m[1].trim());++/**+ * Every `_id` expression this door can mint. A door usually hands the work to a+ * local factory (`createComponentDef`), so following one hop is what makes the+ * question "what address does `defineComponent` mint" answerable at all.+ */+function mintSites(found) {+ const direct = idsIn(found.text);+ if (direct.length > 0) return direct;+ const out = [];+ for (const call of new Set([...found.text.matchAll(/\b([a-z][A-Za-z0-9_]*)\s*\(/g)].map((m) => m[1]))) {+ const body = functionBody(found.whole, call);+ if (body) out.push(...idsIn(body));+ }+ return out;+}++/** Does `fn`, declared in `source`, hand back a symbol it keeps in a name-keyed map? */+function isNameInterner(fn, source) {+ const at = source.search(new RegExp(`function ${fn}\\s*\\(`, 'm'));+ if (at < 0) return false;+ const open = source.indexOf('{', at);+ let depth = 0;+ let body = '';+ for (let i = open; i < source.length; i++) {+ if (source[i] === '{') depth++;+ else if (source[i] === '}' && --depth === 0) { body = source.slice(open, i + 1); break; }+ }+ const registry = body.match(/([A-Za-z0-9_]+)\.get\(name\)/)?.[1];+ if (!registry) return false;+ return body.includes(`${registry}.set(name,`)+ && new RegExp(`(const|let) ${registry}\\s*(:[^=]*)?=\\s*new Map<string, symbol>`).test(source);+}++for (const [door, disposition] of Object.entries(DISPOSITIONS)) {+ if (!publicDoors.has(door)) continue;+ const found = bodyOf(door);+ if (!found) {+ problems.push(`${door} is dispositioned here but no 'export function ${door}' was found under sdk/src.`);+ continue;+ }+ const assignments = mintSites(found);++ if (disposition.kind === 'no-id' || disposition.kind === 'delegates') {+ if (assignments.length > 0) {+ problems.push(`${door} is dispositioned '${disposition.kind}' but assigns _id: ${assignments.join(' / ')}. `+ + 'It mints an address of its own — say how that address survives a re-import.');+ }+ if (disposition.kind === 'delegates' && !new RegExp(`\\b${disposition.via}\\b`).test(found.text)) {+ problems.push(`${door} is dispositioned 'delegates' via ${disposition.via}, which it does not call.`);+ }+ continue;+ }++ if (assignments.length === 0) {+ problems.push(`${door} is dispositioned '${disposition.kind}' but assigns no _id at all — `+ + "either it delegates (say so) or this gate is reading the wrong function.");+ continue;+ }+ // A ternary is two answers; both halves are an address somebody can hold.+ const branches = assignments.flatMap((a) => a.split(/[?:]/).map((b) => b.trim()).filter(Boolean));+ for (const branch of branches) {+ const bare = /^Symbol\s*\(/.test(branch);+ const helper = branch.match(/^([A-Za-z0-9_]+)\s*\(/)?.[1];+ const interned = !bare && helper !== undefined && isNameInterner(helper, found.whole);+ // A `fresh` door may mint anonymously; an `interned` one may too, but only+ // where there is no name to intern by (an unnamed resource has no address).+ if (disposition.kind === 'interned' && !interned && !/name === undefined/.test(assignments.join(' '))) {+ problems.push(`${door} is dispositioned 'interned' but its _id comes from \`${branch}\`, which is not a `+ + 'name-keyed symbol registry. A re-imported bundle would address storage nothing ever filled, '+ + 'and a miss materialises the DEFAULT rather than failing.');+ }+ if (disposition.kind === 'fresh' && interned) {+ problems.push(`${door} is dispositioned 'fresh' (${disposition.why}) but its _id is interned by name.`);+ }+ }+}++if (problems.length > 0) {+ console.error('check-reload-identity: what a project declares must survive a re-import.\n');+ for (const p of problems) console.error(` - ${p}`);+ console.error(`\n${problems.length} problem(s).`);+ process.exit(1);+}+console.log(`check-reload-identity: ${publicDoors.size} public declaration door(s), each with an answer about a second evaluation.`);diff --git a/tools/gates.mjs b/tools/gates.mjsindex 4b624fa9b..83ee786bd 100644--- a/tools/gates.mjs+++ b/tools/gates.mjs@@ -173,6 +173,10 @@ export const GATES = [// A field declares that it carries an asset in one place; everything that acts// on live assets has to read THAT rather than keep a list of components beside it.{ id: 'live-asset-rebind', run: 'node tools/check-live-asset-rebind.mjs' },+ // A hot reload re-evaluates the project bundle against a World still alive, so+ // every public `define*` door owes an answer about what its second evaluation+ // addresses — resources and events answered wrong, and every system read null.+ { id: 'reload-identity', run: 'node tools/check-reload-identity.mjs' },// A scene that unloads and a load that failed halfway own the same things;// two implementations of giving them back is how one came to miss four steps.{ id: 'scene-teardown', run: 'node tools/check-scene-teardown.mjs' },diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 2501f9fdf..cf3ebc115 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,9 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'fix(sdk): a reloaded bundle addresses the world it is reloading into':+ { note: 'A hot reload no longer empties the running game of every resource' },+'feat(corpus): a room that is actually lit, and a gate that keeps it lit':{ note: 'A room in the corpus is actually lit.' },'refactor(engine): the collector composes a transform through the SDK\'s own':