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(ai): an FSM or tree belongs to the realm that loaded it
esengineedbbba678c09
diff --git a/sdk/src/ai/bt/BehaviorTreeAgent.ts b/sdk/src/ai/bt/BehaviorTreeAgent.tsindex 7e01ff79a..15c265927 100644--- a/sdk/src/ai/bt/BehaviorTreeAgent.ts+++ b/sdk/src/ai/bt/BehaviorTreeAgent.ts@@ -47,11 +47,6 @@ export function registerBt(key: string, def: BtDefinition): BtDefinition {return def;}-/** @internal Take a name back out; the slot that published it has no holders. */-export function unregisterBt(key: string): void {- btStore.delete(key);-}-export function getBt(key: string): BtDefinition | undefined {return btStore.get(key);}diff --git a/sdk/src/ai/bt/BtPlugin.ts b/sdk/src/ai/bt/BtPlugin.tsindex 86499a342..e7260f68e 100644--- a/sdk/src/ai/bt/BtPlugin.ts+++ b/sdk/src/ai/bt/BtPlugin.ts@@ -20,13 +20,12 @@ import { defineResource } from '../../ecs/resource';import { Commands, type CommandsInstance } from '../../ecs/commands';import { playModeOnly } from '../../ecs/env';import type { AnyComponentDef, ComponentData } from '../../ecs/component';-import { Assets } from '../../asset/AssetPlugin';-import { resolveAssetKey } from '../../asset/resolveAssetKey';import { Blackboard } from '../fsm/Blackboard';import { aiRegistry, type AiContext } from '../fsm/AiContext';import { tickBt, createBtRunState, type BtRunState } from './BtRunner';import { BehaviorTreeAgent, getBt, allBts } from './BehaviorTreeAgent';-import type { BtNode } from './types';+import { appRegistryAsset, appRegistryAssets } from '../../asset/registryLookup';+import type { BtNode, BtDefinition } from './types';import { TouchesBuilder, touchesOfLeaves, type LeafRef } from '../worldView';import { ensureBuiltinAiRegistrations } from '../builtins';@@ -66,7 +65,7 @@ export function stepBehaviorTrees(// A `.esbt` asset registers under its resolved path; the agent holds the// authored ref, so resolve before lookup (falls back to the raw ref for// `registerBt` code names). Optional so tests need no realm.- resolveKey?: (ref: string) => string,+ resolveTree?: (ref: string) => BtDefinition | undefined,): void {if (dt <= 0) return;@@ -84,7 +83,7 @@ export function stepBehaviorTrees(for (const entity of world.getEntitiesWithComponents([BehaviorTreeAgent])) {const agent = world.get(entity, BehaviorTreeAgent);if (!agent.bt) continue;- const def = getBt(resolveKey ? resolveKey(agent.bt) : agent.bt) ?? getBt(agent.bt);+ const def = resolveTree?.(agent.bt) ?? getBt(agent.bt);if (!def) continue;let st = states.get(entity);@@ -134,9 +133,12 @@ export function* btLeaves(node: BtNode): Iterable<LeafRef> {}/** What the BT system reaches for: the union over every loaded tree. */-export function btTouches(): SystemTouches {+/** The union over the trees THIS app has: its realm's, plus code-registered+ * ones. Per app, because a schedule is per app. */+export function btTouches(app: App): SystemTouches {const builder = new TouchesBuilder().writing(BehaviorTreeAgent._name);- for (const tree of allBts()) touchesOfLeaves(aiRegistry, btLeaves(tree.root), builder);+ const loaded = [...appRegistryAssets<BtDefinition>(app, 'behaviortree'), ...allBts()];+ for (const tree of loaded) touchesOfLeaves(aiRegistry, btLeaves(tree.root), builder);return builder.build();}@@ -151,19 +153,20 @@ export class BtPlugin implements Plugin {app.world.onDespawn((entity: Entity) => states.delete(entity));app.insertResource(AiBt, new BehaviorTrees(states));- const resolveKey = (ref: string): string =>- resolveAssetKey(app.hasResource(Assets) ? app.getResource(Assets) : null, ref);+ // This realm's publication first, then a code registration keyed verbatim.+ const resolveTree = (ref: string): BtDefinition | undefined =>+ appRegistryAsset<BtDefinition>(app, 'behaviortree', ref);app.addSystemToSchedule(Schedule.Update,defineSystem([Res(Time), Commands(), GetWorld()],(time: TimeData, commands: CommandsInstance, world) => {- stepBehaviorTrees(world as AiWorldView, commands, time.delta, states, resolveKey);+ stepBehaviorTrees(world as AiWorldView, commands, time.delta, states, resolveTree);},// See fsmTouches: the reach is the union over the loaded trees,// which is why it is asked for rather than stated.- { name: 'BehaviorTreeSystem', touches: btTouches },+ { name: 'BehaviorTreeSystem', touches: () => btTouches(app) },),{ runIf: playModeOnly },);diff --git a/sdk/src/ai/fsm/FsmPlugin.ts b/sdk/src/ai/fsm/FsmPlugin.tsindex ee5c997c5..d640fe08d 100644--- a/sdk/src/ai/fsm/FsmPlugin.ts+++ b/sdk/src/ai/fsm/FsmPlugin.ts@@ -20,12 +20,11 @@ import { defineResource } from '../../ecs/resource';import { Commands, type CommandsInstance } from '../../ecs/commands';import { playModeOnly } from '../../ecs/env';import type { AnyComponentDef, ComponentData } from '../../ecs/component';-import { Assets } from '../../asset/AssetPlugin';-import { resolveAssetKey } from '../../asset/resolveAssetKey';import { Blackboard } from './Blackboard';import { createFsmRunState, stepFsm, type CompiledFsm, type FsmRunState } from './FsmRunner';import { aiRegistry, type AiContext } from './AiContext';import { StateMachineAgent, getFsm, allFsms } from './StateMachineAgent';+import { appRegistryAsset, appRegistryAssets } from '../../asset/registryLookup';import { actionRefName, actionRefArg, actionRefParams } from './types';import { TouchesBuilder, touchesOfLeaves, type LeafRef } from '../worldView';import { ensureBuiltinAiRegistrations } from '../builtins';@@ -69,7 +68,7 @@ export function stepStateMachines(// maps a plain/`@uuid:` ref to that key); the agent still holds the authored// ref, so resolve before lookup. Falls back to the raw ref for `registerFsm`// code names, which are keyed verbatim. Optional so tests need no realm.- resolveKey?: (ref: string) => string,+ resolveFsm?: (ref: string) => CompiledFsm | undefined,): void {if (dt <= 0) return;@@ -87,7 +86,7 @@ export function stepStateMachines(for (const entity of world.getEntitiesWithComponents([StateMachineAgent])) {const agent = world.get(entity, StateMachineAgent);if (!agent.fsm) continue;- const fsm = getFsm(resolveKey ? resolveKey(agent.fsm) : agent.fsm) ?? getFsm(agent.fsm);+ const fsm = resolveFsm?.(agent.fsm) ?? getFsm(agent.fsm);if (!fsm) continue;let st = states.get(entity);@@ -131,10 +130,17 @@ export function* fsmLeaves(fsm: CompiledFsm): Iterable<LeafRef> {}}-/** What the FSM system reaches for: the union over every loaded graph. */-export function fsmTouches(): SystemTouches {+/**+ * What the FSM system reaches for: the union over the graphs THIS app has —+ * the ones its realm published, plus the ones code registered.+ *+ * Read per app, because a schedule is per app: a module-global store had one+ * app's asset deciding what another app's system declares it touches.+ */+export function fsmTouches(app: App): SystemTouches {const builder = new TouchesBuilder().writing(StateMachineAgent._name);- for (const fsm of allFsms()) touchesOfLeaves(aiRegistry, fsmLeaves(fsm), builder);+ const loaded = [...appRegistryAssets<CompiledFsm>(app, 'statemachine'), ...allFsms()];+ for (const fsm of loaded) touchesOfLeaves(aiRegistry, fsmLeaves(fsm), builder);return builder.build();}@@ -168,20 +174,22 @@ export class FsmPlugin implements Plugin {app.world.onDespawn((entity: Entity) => states.delete(entity));app.insertResource(AiFsm, new StateMachines(states));- const resolveKey = (ref: string): string =>- resolveAssetKey(app.hasResource(Assets) ? app.getResource(Assets) : null, ref);+ // This realm's publication first; `stepStateMachines` falls back to a+ // code registration, which is keyed verbatim and has no realm.+ const resolveFsm = (ref: string): CompiledFsm | undefined =>+ appRegistryAsset<CompiledFsm>(app, 'statemachine', ref);app.addSystemToSchedule(Schedule.Update,defineSystem([Res(Time), Commands(), GetWorld()],(time: TimeData, commands: CommandsInstance, world) => {- stepStateMachines(world as FsmWorldView, commands, time.delta, states, resolveKey);+ stepStateMachines(world as FsmWorldView, commands, time.delta, states, resolveFsm);},// Asked per analysis, not once: a graph loaded later changes the// answer, and no graph at all means this system touches only the// agent component.- { name: 'StateMachineSystem', touches: fsmTouches },+ { name: 'StateMachineSystem', touches: () => fsmTouches(app) },),{ runIf: playModeOnly },);diff --git a/sdk/src/ai/fsm/StateMachineAgent.ts b/sdk/src/ai/fsm/StateMachineAgent.tsindex 46a892c17..2922ec99a 100644--- a/sdk/src/ai/fsm/StateMachineAgent.ts+++ b/sdk/src/ai/fsm/StateMachineAgent.ts@@ -51,19 +51,6 @@ export function registerFsm(key: string, def: FsmDefinition): CompiledFsm {return compiled;}-/**- * @internal Publish an already-compiled FSM under `key` — the asset door, where- * one era compiles once however many names it answers to.- */-export function publishFsm(key: string, compiled: CompiledFsm): void {- fsmStore.set(key, compiled);-}--/** @internal Take a name back out; the slot that published it has no holders. */-export function unregisterFsm(key: string): void {- fsmStore.delete(key);-}-export function getFsm(key: string): CompiledFsm | undefined {return fsmStore.get(key);}diff --git a/sdk/src/asset/loaders/BtAssetLoader.ts b/sdk/src/asset/loaders/BtAssetLoader.tsindex b5dffa451..ab20bf6fb 100644--- a/sdk/src/asset/loaders/BtAssetLoader.ts+++ b/sdk/src/asset/loaders/BtAssetLoader.ts@@ -11,7 +11,6 @@import type { AssetLoader, LoadContext, BtResult, RegistryAssetLoader } from '../AssetLoader';import type { RegistryEra } from '../registryAssets';import { AssetScope } from '../AssetLease';-import { registerBt, unregisterBt, getBt } from '../../ai/bt/BehaviorTreeAgent';import type { BtDefinition } from '../../ai/bt/types';export class BtAssetLoader implements AssetLoader<BtResult> {@@ -27,13 +26,10 @@ export class BtAssetLoader implements AssetLoader<BtResult> {dependencies: new AssetScope(),};},- publish: (names, published) => {- for (const name of names) registerBt(name, published as BtDefinition);- },- unpublish: (names, published) => {- for (const name of names) {- if (getBt(name) === published) unregisterBt(name);- }- },+ // Nothing: the slot holds the era, and this realm's lookup reads it+ // there. Writing a module-global store as well is what let one app+ // answer with another's asset.+ publish: () => {},+ unpublish: () => {},};}diff --git a/sdk/src/asset/loaders/FsmAssetLoader.ts b/sdk/src/asset/loaders/FsmAssetLoader.tsindex 34d83a367..612da1004 100644--- a/sdk/src/asset/loaders/FsmAssetLoader.ts+++ b/sdk/src/asset/loaders/FsmAssetLoader.ts@@ -12,8 +12,7 @@import type { AssetLoader, LoadContext, FsmResult, RegistryAssetLoader } from '../AssetLoader';import type { RegistryEra } from '../registryAssets';import { AssetScope } from '../AssetLease';-import { publishFsm, unregisterFsm, getFsm } from '../../ai/fsm/StateMachineAgent';-import { compileFsm, type CompiledFsm } from '../../ai/fsm/FsmRunner';+import { compileFsm } from '../../ai/fsm/FsmRunner';import type { FsmDefinition } from '../../ai/fsm/types';export class FsmAssetLoader implements AssetLoader<FsmResult> {@@ -28,13 +27,10 @@ export class FsmAssetLoader implements AssetLoader<FsmResult> {// machine, and two compilations of it are two machines.return { published: compileFsm(def), value: { fsmId: path }, dependencies: new AssetScope() };},- publish: (names, published) => {- for (const name of names) publishFsm(name, published as CompiledFsm);- },- unpublish: (names, published) => {- for (const name of names) {- if (getFsm(name) === published) unregisterFsm(name);- }- },+ // Nothing: the slot holds the era, and this realm's lookup reads it+ // there. Writing a module-global store as well is what let one app+ // answer with another's asset.+ publish: () => {},+ unpublish: () => {},};}diff --git a/sdk/src/asset/registryLookup.ts b/sdk/src/asset/registryLookup.tsnew file mode 100644index 000000000..e85fba291--- /dev/null+++ b/sdk/src/asset/registryLookup.ts@@ -0,0 +1,31 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file registryLookup.ts+ * @brief What THIS app's realm publishes for a ref-bound asset.+ *+ * @details The Assets instance is the realm: its slot table holds the current+ * era of everything it loaded, and nothing else can see it. A subsystem+ * that keeps asset publications in a module-global map instead answers+ * with whichever app loaded last — and an editor world beside a play+ * world in one process is two apps.+ *+ * Code registrations stay where they are. `registerFsm('patrol', def)`+ * is not an asset and has no realm; a domain registry holding those and+ * only those is a single source of truth, not a mirror.+ */+import type { App } from '../app/app';+import { Assets } from './AssetPlugin';++/** The current era of one ref-bound asset in `app`'s realm. */+export function appRegistryAsset<T>(app: App, type: string, ref: string): T | undefined {+ return app.hasResource(Assets)+ ? app.getResource(Assets).resolveRegistryAsset<T>(type, ref)+ : undefined;+}++/** Every ref-bound asset of one type this realm publishes — what a schedule+ * analysis reads, so it sees the graphs THIS app loaded and no others. */+export function appRegistryAssets<T>(app: App, type: string): T[] {+ return app.hasResource(Assets) ? app.getResource(Assets).publishedRegistryAssets<T>(type) : [];+}diff --git a/sdk/tests/ai-world-view.test.ts b/sdk/tests/ai-world-view.test.tsindex c3e265113..d0d1bef6a 100644--- a/sdk/tests/ai-world-view.test.ts+++ b/sdk/tests/ai-world-view.test.ts@@ -12,6 +12,7 @@ import { aiRegistry } from '../src/ai/fsm/AiContext';import { registerFsm, clearFsmStore, StateMachineAgent } from '../src/ai/fsm/StateMachineAgent';import { registerBt, clearBtStore, BehaviorTreeAgent } from '../src/ai/bt/BehaviorTreeAgent';import { fsmTouches } from '../src/ai/fsm/FsmPlugin';+import type { App } from '../src/app/app';import { btTouches } from '../src/ai/bt/BtPlugin';import { ensureBuiltinAiRegistrations } from '../src/ai/builtins';import { TouchesBuilder } from '../src/ai/worldView';@@ -25,20 +26,24 @@ beforeEach(() => {ensureBuiltinAiRegistrations();});+/** An app with no Assets: what a graph declares is being tested here, not which+ * realm published it. */+const NO_REALM = { hasResource: () => false } as unknown as App;+describe('an FSM system, asked what it touches', () => {it('names only its own component when no graph is loaded', () => {- expect(fsmTouches()).toEqual({ reads: [], writes: [StateMachineAgent._name] });+ expect(fsmTouches(NO_REALM)).toEqual({ reads: [], writes: [StateMachineAgent._name] });});it('answers from the graph that is loaded, not from the registry', () => {// `spriteAnim.*` is registered either way; what puts SpriteAnimator in// the answer is a graph that names it.- expect(fsmTouches().writes).not.toContain('SpriteAnimator');+ expect(fsmTouches(NO_REALM).writes).not.toContain('SpriteAnimator');registerFsm('run', {initial: 'idle',states: [{ name: 'idle', onEnter: 'spriteAnim.play' }],});- expect(fsmTouches().writes).toContain('SpriteAnimator');+ expect(fsmTouches(NO_REALM).writes).toContain('SpriteAnimator');});it('includes what a transition condition reads', () => {@@ -49,7 +54,7 @@ describe('an FSM system, asked what it touches', () => {{ name: 'done' },],});- expect(fsmTouches().reads).toContain('TimelinePlayer');+ expect(fsmTouches(NO_REALM).reads).toContain('TimelinePlayer');});it('reads the component out of a property.set path', () => {@@ -60,8 +65,8 @@ describe('an FSM system, asked what it touches', () => {onEnter: { name: 'property.set', params: { path: 'UIVisual.color.a', value: '0.5' } },}],});- expect(fsmTouches().writes).toContain('UIVisual');- expect(fsmTouches().opaque).toBeUndefined();+ expect(fsmTouches(NO_REALM).writes).toContain('UIVisual');+ expect(fsmTouches(NO_REALM).opaque).toBeUndefined();});it('reads it out of the canonical string form too', () => {@@ -69,7 +74,7 @@ describe('an FSM system, asked what it touches', () => {initial: 'hit',states: [{ name: 'hit', onEnter: { name: 'property.set', arg: 'Sprite.color.r=1' } }],});- expect(fsmTouches().writes).toContain('Sprite');+ expect(fsmTouches(NO_REALM).writes).toContain('Sprite');});// The whole point of declaring: a union that quietly dropped the leaf it@@ -80,7 +85,7 @@ describe('an FSM system, asked what it touches', () => {initial: 'a',states: [{ name: 'a', onEnter: 'spriteAnim.play', onUpdate: 'game.mystery' }],});- const touches = fsmTouches();+ const touches = fsmTouches(NO_REALM);expect(touches.opaque).toBe(true);// Still says what it DOES know — a bad claim is not a reason to say nothing.expect(touches.writes).toContain('SpriteAnimator');@@ -89,14 +94,14 @@ describe('an FSM system, asked what it touches', () => {it('takes a declaring registration at its word', () => {aiRegistry.registerAction('game.hurt', { run: noop, touches: { writes: ['Health'] } });registerFsm('fight', { initial: 'a', states: [{ name: 'a', onEnter: 'game.hurt' }] });- expect(fsmTouches()).toMatchObject({ writes: ['Health', StateMachineAgent._name] });+ expect(fsmTouches(NO_REALM)).toMatchObject({ writes: ['Health', StateMachineAgent._name] });});// A name nothing registered is a no-op at run time, so counting it as// unknown would make one typo hide the reach of an entire project.it('ignores a leaf no registration answers to', () => {registerFsm('typo', { initial: 'a', states: [{ name: 'a', onEnter: 'spriteAnim.paly' }] });- expect(fsmTouches().opaque).toBeUndefined();+ expect(fsmTouches(NO_REALM).opaque).toBeUndefined();});});@@ -111,7 +116,7 @@ describe('a behaviour-tree system, asked what it touches', () => {],},});- const touches = btTouches();+ const touches = btTouches(NO_REALM);expect(touches.reads).toContain('TimelinePlayer');expect(touches.writes).toContain('SpriteAnimator');expect(touches.writes).toContain(BehaviorTreeAgent._name);@@ -124,7 +129,7 @@ describe('a behaviour-tree system, asked what it touches', () => {root: { type: 'action', name: 'spriteAnim.stop' },orphans: [{ type: 'action', name: 'timeline.play' }],});- expect(btTouches().writes).not.toContain('TimelinePlayer');+ expect(btTouches(NO_REALM).writes).not.toContain('TimelinePlayer');});});diff --git a/sdk/tests/play-realm-asset-ref.test.ts b/sdk/tests/play-realm-asset-ref.test.tsindex 078276879..f2fc152b5 100644--- a/sdk/tests/play-realm-asset-ref.test.ts+++ b/sdk/tests/play-realm-asset-ref.test.ts@@ -4,13 +4,15 @@* Regression for the enemy-ai "enemies never chase" bug: play-realm asset refs* are resolved once during preload (to bucket by type) and again by the loader,* so `resolvePlayAssetRef` must be idempotent or a plain path gains the origin- * twice (estella://…/estella://…/404). And because a `.esfsm`/`.esbt` registers- * under its resolved path while the agent still holds the authored ref, the FSM- * step must resolve the ref before lookup.+ * twice (estella://…/estella://…/404). And because the agent holds the authored+ * ref while the asset loaded under a resolved path, the FSM step looks the graph+ * up through its realm — which answers to both spellings — rather than through a+ * store keyed one way.*/import { describe, it, expect, beforeEach } from 'vitest';import { resolvePlayAssetRef } from '../src/runtime/playRealmRuntime';-import { registerFsm, getFsm, clearFsmStore, StateMachineAgent } from '../src/ai/fsm/StateMachineAgent';+import { clearFsmStore, StateMachineAgent } from '../src/ai/fsm/StateMachineAgent';+import { compileFsm, type CompiledFsm } from '../src/ai/fsm/FsmRunner';import { stepStateMachines } from '../src/ai/fsm/FsmPlugin';const BASE = 'estella://project';@@ -34,13 +36,17 @@ describe('resolvePlayAssetRef idempotency', () => {});});-describe('FSM step resolves the agent ref before lookup', () => {+describe('FSM step looks the graph up through its realm', () => {beforeEach(() => clearFsmStore());- it('runs an FSM registered under the resolved key while the agent holds the raw ref', () => {+ it('runs the graph the realm publishes for the ref the agent holds', () => {const resolved = `${BASE}/assets/ai/enemy.esfsm`;- // The loader registers under the resolved path (what preload keys it by).- registerFsm(resolved, { initial: 'Idle', states: [{ name: 'Idle' }] });+ const compiled = compileFsm({ initial: 'Idle', states: [{ name: 'Idle' }] });+ // A realm publishes under the load path AND the authored ref: both are+ // names of the one slot.+ const realm = new Map<string, CompiledFsm>([+ [resolved, compiled], ['assets/ai/enemy.esfsm', compiled],+ ]);const store = new Map<number, Record<string, unknown>>([[1, { fsm: 'assets/ai/enemy.esfsm', current: '' }]]);const world = {@@ -50,12 +56,11 @@ describe('FSM step resolves the agent ref before lookup', () => {has: () => false,};- // Without a resolver the raw ref misses the resolved key → no state entered.+ // No realm: only a code registration could answer, and there is none.stepStateMachines(world as never, null as never, 1 / 60, new Map());expect(store.get(1)!.current).toBe('');- // With the realm resolver (raw → resolved), the agent finds its FSM.- stepStateMachines(world as never, null as never, 1 / 60, new Map(), (ref) => resolvePlayAssetRef(ref, {}, BASE));+ stepStateMachines(world as never, null as never, 1 / 60, new Map(), (ref) => realm.get(ref));expect(store.get(1)!.current).toBe('Idle');});});diff --git a/sdk/tests/preload-ai-assets.test.ts b/sdk/tests/preload-ai-assets.test.tsindex 719ec8a31..e67b168cd 100644--- a/sdk/tests/preload-ai-assets.test.ts+++ b/sdk/tests/preload-ai-assets.test.ts@@ -75,23 +75,27 @@ describe('preloadSceneAssets — AI brains', () => {});});- it('loads .esfsm / .esbt referenced by agents into the AI store', async () => {+ it('loads .esfsm / .esbt referenced by agents into the realm that preloaded them', async () => {const assets = Assets.create({ backend: aiBackend(), catalog: Catalog.empty(), module: null as never });- expect(getFsm(FSM_PATH)).toBeUndefined();- expect(getBt(BT_PATH)).toBeUndefined();+ expect(assets.resolveRegistryAsset('statemachine', FSM_PATH)).toBeUndefined();+ expect(assets.resolveRegistryAsset('behaviortree', BT_PATH)).toBeUndefined();const result = await assets.preloadSceneAssets(scene, undefined, { skipSpine: true });expect(result.missing).toEqual([]);- expect(getFsm(FSM_PATH)).toBeDefined();- expect(getBt(BT_PATH)).toBeDefined();+ expect(assets.resolveRegistryAsset('statemachine', FSM_PATH)).toBeDefined();+ expect(assets.resolveRegistryAsset('behaviortree', BT_PATH)).toBeDefined();+ // The code-registration store is not where an asset lands any more: an+ // app's assets are its own, and that map has no realm.+ expect(getFsm(FSM_PATH)).toBeUndefined();+ expect(getBt(BT_PATH)).toBeUndefined();});- it('keys the store by the resolved ref when a realm resolver is set', async () => {+ it('answers to the authored ref and to the path a realm resolved it to', async () => {// Mirrors the play realm: the ref resolver prefixes the origin, so the- // FSM/BT register under the resolved path — the key FsmPlugin/BtPlugin's- // resolveKey reproduces from the agent's authored ref.+ // load path is not the spelling the agent carries. Both are names of the+ // one slot, so no lookup site has to re-derive the resolved key.const base = 'estella://project';const assets = Assets.create({ backend: aiBackend(), catalog: Catalog.empty(), module: null as never });assets.setAssetRefResolver((ref) => (ref.includes('://') ? ref : `${base}/${ref}`));@@ -99,8 +103,12 @@ describe('preloadSceneAssets — AI brains', () => {const result = await assets.preloadSceneAssets(scene, undefined, { skipSpine: true });expect(result.missing).toEqual([]);- expect(getFsm(`${base}/${FSM_PATH}`)).toBeDefined();- expect(getBt(`${base}/${BT_PATH}`)).toBeDefined();- expect(getFsm(FSM_PATH)).toBeUndefined(); // NOT keyed by the raw ref+ expect(assets.resolveRegistryAsset('statemachine', `${base}/${FSM_PATH}`)).toBeDefined();+ expect(assets.resolveRegistryAsset('statemachine', FSM_PATH)).toBeDefined();+ expect(assets.resolveRegistryAsset('behaviortree', `${base}/${BT_PATH}`)).toBeDefined();++ // And another realm in the same process has none of it.+ const other = Assets.create({ backend: aiBackend(), catalog: Catalog.empty(), module: null as never });+ expect(other.resolveRegistryAsset('statemachine', FSM_PATH)).toBeUndefined();});});diff --git a/sdk/tests/realm-registry-isolation.test.ts b/sdk/tests/realm-registry-isolation.test.tsnew file mode 100644index 000000000..93eb1ffe1--- /dev/null+++ b/sdk/tests/realm-registry-isolation.test.ts@@ -0,0 +1,118 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file realm-registry-isolation.test.ts+ * @brief An asset belongs to the realm that loaded it — including in what a+ * schedule says its systems touch.+ *+ * @details An editor world beside a play world is two Apps in one process. The+ * asset-backed definitions lived in module-global maps, so the second+ * app to load a key overwrote the first's value: both then ran the same+ * graph, and one app's asset even decided what the OTHER app's system+ * declared it reaches for.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { App } from '../src/app/app';+import { Assets } from '../src/asset/Assets';+import { Catalog } from '../src/asset/Catalog';+import { Assets as AssetsResource } from '../src/asset/AssetPlugin';+import { fsmTouches } from '../src/ai/fsm/FsmPlugin';+import { btTouches } from '../src/ai/bt/BtPlugin';+import { clearFsmStore } from '../src/ai/fsm/StateMachineAgent';+import { clearBtStore } from '../src/ai/bt/BehaviorTreeAgent';+import { ensureBuiltinAiRegistrations } from '../src/ai/builtins';+import type { Backend } from '../src/asset/Backend';++vi.mock('../src/wasm/resourceManager', () => ({+ requireResourceManager: () => ({}),+ getResourceManager: () => null,+ evictTextureDimensions: vi.fn(),+}));++const KEY = 'assets/ai/enemy.esfsm';+const BT_KEY = 'assets/ai/enemy.esbt';++/** An FSM whose one state writes `component` through the built-in property.set. */+const fsmWriting = (component: string): string => JSON.stringify({+ initial: 'Act',+ states: [{+ name: 'Act',+ onEnter: { name: 'property.set', params: { path: `${component}.enabled`, value: 'true' } },+ }],+});+const btWriting = (component: string): string => JSON.stringify({+ root: {+ type: 'action', id: 'n0', name: 'property.set',+ params: { path: `${component}.enabled`, value: 'true' },+ },+});++function realm(text: (url: string) => string): { app: App; assets: Assets } {+ const app = App.new();+ const assets = Assets.create({+ backend: {+ fetchBinary: vi.fn(async () => new ArrayBuffer(0)),+ fetchText: vi.fn(async (url: string) => text(url)),+ resolveUrl: (p: string) => p,+ } as unknown as Backend,+ catalog: Catalog.empty(),+ module: null as never,+ });+ app.insertResource(AssetsResource, assets as never);+ return { app, assets };+}++describe('two realms in one process do not share an asset', () => {+ beforeEach(() => { clearFsmStore(); clearBtStore(); ensureBuiltinAiRegistrations(); });++ it('the same key loads a different graph in each, and each keeps its own', async () => {+ const a = realm(() => fsmWriting('Sprite'));+ const b = realm(() => fsmWriting('Velocity'));++ await a.assets.acquireTyped('statemachine', KEY);+ await b.assets.acquireTyped('statemachine', KEY); // loads second — used to win++ const inA = a.assets.resolveRegistryAsset('statemachine', KEY);+ const inB = b.assets.resolveRegistryAsset('statemachine', KEY);+ expect(inA).toBeDefined();+ expect(inB).toBeDefined();+ expect(inA, 'the app that loaded last answered for both').not.toBe(inB);+ });++ it('what a schedule says the FSM system touches is its own realm\'s', async () => {+ // Worse than reading the wrong graph: one app's asset deciding what+ // another app's system declares it reaches for.+ const a = realm(() => fsmWriting('Sprite'));+ const b = realm(() => fsmWriting('Velocity'));+ await a.assets.acquireTyped('statemachine', KEY);+ await b.assets.acquireTyped('statemachine', KEY);++ expect(fsmTouches(a.app).writes).toContain('Sprite');+ expect(fsmTouches(a.app).writes, 'B\'s graph is in A\'s declaration').not.toContain('Velocity');+ expect(fsmTouches(b.app).writes).toContain('Velocity');+ expect(fsmTouches(b.app).writes).not.toContain('Sprite');+ });++ it('and the same holds for behaviour trees', async () => {+ const a = realm(() => btWriting('Sprite'));+ const b = realm(() => btWriting('Velocity'));+ await a.assets.acquireTyped('behaviortree', BT_KEY);+ await b.assets.acquireTyped('behaviortree', BT_KEY);++ expect(btTouches(a.app).writes).toContain('Sprite');+ expect(btTouches(a.app).writes).not.toContain('Velocity');+ expect(btTouches(b.app).writes).toContain('Velocity');+ expect(btTouches(b.app).writes).not.toContain('Sprite');+ });++ it('a code registration has no realm, and every app still sees it', async () => {+ // The other half of the rule: `registerFsm('patrol', …)` is not an asset.+ const { registerFsm } = await import('../src/ai/fsm/StateMachineAgent');+ const a = realm(() => fsmWriting('Sprite'));+ const b = realm(() => fsmWriting('Sprite'));+ registerFsm('patrol', JSON.parse(fsmWriting('Camera')) as never);++ expect(fsmTouches(a.app).writes).toContain('Camera');+ expect(fsmTouches(b.app).writes).toContain('Camera');+ });+});