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
refactor(editor): EditorSession boundary (REARCH_EDITOR_MODEL P2-core)
esengine797ff2f1a815
diff --git a/desktop/src/engine/EditorControlSurface.ts b/desktop/src/engine/EditorControlSurface.tsindex 0bb752e33..5fb7a9ed0 100644--- a/desktop/src/engine/EditorControlSurface.ts+++ b/desktop/src/engine/EditorControlSurface.ts@@ -1,16 +1,18 @@/*** @file EditorControlSurface.ts- * @brief The single canonical programmatic entry to the editor — lifecycle,- * commands, queries, and observation — composed over the existing+ * @brief The single canonical programmatic entry to a session — lifecycle,+ * commands, queries, and observation — composed over the session's* engine modules. One surface, three consumers: the React UI, the* headless verification host, and (later) the editor MCP server, which* is a transport adapter over this object rather than a parallel API.*- * Design and phasing: docs/REARCH_EDITOR_AUTOMATION.md. This adds no new truth —- * commands route through SceneCommands (the model write boundary), reads through+ * Design and phasing: docs/REARCH_EDITOR_AUTOMATION.md + REARCH_EDITOR_MODEL.md+ * (P2: the session boundary). This adds no new truth — commands route through+ * the session's SceneCommands (the model write boundary), reads through its* SceneQuery / SceneModel (the model is the source of truth; the World is a- * derived projection), and observation reads the live canvas/World. Ids are- * stable source ids (REARCH_EDITOR_MODEL.md).+ * derived projection), and observation reads the live canvas/World (process-+ * level engine). Ids are stable source ids. The surface is an instance over a+ * session; `EditorControlSurface` is the app's default-session one.*/import type {EntityId,@@ -22,10 +24,10 @@ import type {} from '@/types';import type { SceneData } from 'esengine';import { EngineHost } from './EngineHost';-import { SceneCommands } from './SceneCommands';-import { SceneQuery } from './SceneQuery';-import { SceneModel } from './SceneModel';-import { EditorHistory } from './EditorHistory';+import { SceneCommands, type SceneCommandsImpl } from './SceneCommands';+import { SceneQuery, type SceneQueryImpl } from './SceneQuery';+import { SceneModel, type SceneModelImpl } from './SceneModel';+import { EditorHistory, type EditorHistoryImpl } from './EditorHistory';/** A captured viewport frame: raw RGBA pixels (GL order: bottom-up rows). */export interface ViewportCapture {@@ -34,9 +36,20 @@ export interface ViewportCapture {height: number;}-export const EditorControlSurface = {+/** The session parts the surface needs (the EditorSession satisfies this). */+export interface SurfaceSession {+ model: SceneModelImpl;+ history: EditorHistoryImpl;+ commands: SceneCommandsImpl;+ query: SceneQueryImpl;+}++export class EditorControlSurfaceImpl {+ constructor(private readonly s: SurfaceSession) {}+// =========================================================================- // Lifecycle — drive the engine deterministically and switch run mode+ // Lifecycle — drive the engine deterministically and switch run mode.+ // The engine (wasm / canvas / World) is process-level — shared via EngineHost.// =========================================================================/**@@ -46,16 +59,16 @@ export const EditorControlSurface = {*/async loadScene(sceneUrl: string, manifestUrl?: string): Promise<number> {return EngineHost.loadScene(sceneUrl, manifestUrl);- },+ }/**- * Switch edit↔play. Play snapshots the scene; Stop restores it (gameplay never- * dirties the edit scene). Returns true if a play→edit restore happened (entity- * ids changed — drop any cached selection).+ * Switch edit↔play. Play runs gameplay against the live World; Stop rebuilds it+ * from the untouched edit model (gameplay never dirties the edit scene). Returns+ * true if a play→edit rebuild happened. Selection survives it (stable source ids).*/setRunMode(playing: boolean, paused = false): boolean {return EngineHost.setRunMode(playing, paused);- },+ }/*** Advance the engine by exactly `frames` fixed-delta ticks — no rAF, no@@ -65,37 +78,37 @@ export const EditorControlSurface = {*/async step(frames = 1, dt = 1 / 60): Promise<void> {for (let i = 0; i < frames; i++) await EngineHost.tick(dt);- },+ }undo(): void {- EditorHistory.undo();- },+ this.s.history.undo();+ }redo(): void {- EditorHistory.redo();- },+ this.s.history.redo();+ }canUndo(): boolean {- return EditorHistory.canUndo();- },+ return this.s.history.canUndo();+ }canRedo(): boolean {- return EditorHistory.canRedo();- },+ return this.s.history.canRedo();+ }// =========================================================================// Commands — mutations, all undoable, through the SceneCommands write door// =========================================================================addEntity(): EntityId | null {- return SceneCommands.addEntity();- },+ return this.s.commands.addEntity();+ }deleteEntity(id: EntityId): void {- SceneCommands.deleteEntity(id);- },+ this.s.commands.deleteEntity(id);+ }duplicateEntity(id: EntityId): EntityId | null {- return SceneCommands.duplicateEntity(id);- },+ return this.s.commands.duplicateEntity(id);+ }renameEntity(id: EntityId, name: string): void {- SceneCommands.renameEntity(id, name);- },+ this.s.commands.renameEntity(id, name);+ }setField(entity: EntityId,component: string,@@ -103,42 +116,42 @@ export const EditorControlSurface = {type: InspectorFieldType,value: InspectorFieldValue,): void {- SceneCommands.setField(entity, component, key, type, value);- },+ this.s.commands.setField(entity, component, key, type, value);+ }setEntityXY(id: EntityId, x: number, y: number): void {- SceneCommands.setEntityXY(id, x, y);- },+ this.s.commands.setEntityXY(id, x, y);+ }/** Coalesce a burst of setField writes (a drag) into one undo step. */beginGesture(label: string): void {- SceneCommands.beginGesture(label);- },+ this.s.commands.beginGesture(label);+ }endGesture(): void {- SceneCommands.endGesture();- },+ this.s.commands.endGesture();+ }// =========================================================================- // Queries — read-only reflection of the scene model (the source of truth)+ // Queries — read-only reflection of the session's scene model (the truth)// =========================================================================worldVersion(): number {- return SceneQuery.worldVersion();- },+ return this.s.query.worldVersion();+ }getSceneTree(): SceneNode[] {- return SceneQuery.readSceneTree();- },+ return this.s.query.readSceneTree();+ }getEntity(id: EntityId): { name: string; kind: NodeKind; components: string[] } | null {- return SceneQuery.readEntity(id);- },+ return this.s.query.readEntity(id);+ }getInspector(entity: EntityId): InspectorComponent[] {- return SceneQuery.readInspector(entity);- },+ return this.s.query.readInspector(entity);+ }getFieldValue(entity: EntityId, component: string, key: string): InspectorFieldValue | null {- return SceneQuery.getFieldValue(entity, component, key);- },+ return this.s.query.getFieldValue(entity, component, key);+ }/** The lossless JSON-first scene truth (deep clone), or null if none loaded. */serializeScene(): SceneData | null {- return SceneModel.serialize();- },+ return this.s.model.serialize();+ }// =========================================================================// Observation — runtime evidence for verification (the headless-gap closer)@@ -165,12 +178,20 @@ export const EditorControlSurface = {const rgba = new Uint8Array(width * height * 4);gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, rgba);return { rgba, width, height };- },+ }/** Live counts for quick assertions (entity count is headless-friendly). */getStats(): { entities: number } {return { entities: EngineHost.world?.getAllEntities().length ?? 0 };- },-};+ }+}++/** The app's default-session control surface. */+export const EditorControlSurface = new EditorControlSurfaceImpl({+ model: SceneModel,+ history: EditorHistory,+ commands: SceneCommands,+ query: SceneQuery,+});-export type EditorControlSurfaceT = typeof EditorControlSurface;+export type EditorControlSurfaceT = EditorControlSurfaceImpl;diff --git a/desktop/src/engine/EditorHistory.ts b/desktop/src/engine/EditorHistory.tsindex c27b3d598..7f7132f70 100644--- a/desktop/src/engine/EditorHistory.ts+++ b/desktop/src/engine/EditorHistory.ts@@ -9,7 +9,7 @@ import { TransactionManager } from 'esengine';* before/after and calls {@link record} so the pair becomes undoable without* re-running the forward closure. Panels subscribe for undo/redo availability.*/-class EditorHistoryImpl {+export class EditorHistoryImpl {private readonly tm = new TransactionManager({ historyLimit: 200 });private readonly store = createStore<{ version: number }>(() => ({ version: 0 }));@@ -59,4 +59,5 @@ class EditorHistoryImpl {getVersion = (): number => this.store.getState().version;}+/** The app's default-session history. Other sessions construct their own EditorHistoryImpl. */export const EditorHistory = new EditorHistoryImpl();diff --git a/desktop/src/engine/EditorSession.ts b/desktop/src/engine/EditorSession.tsnew file mode 100644index 000000000..6b9a00c9c--- /dev/null+++ b/desktop/src/engine/EditorSession.ts@@ -0,0 +1,93 @@+import { SceneModel, SceneModelImpl } from './SceneModel';+import { EditorHistory, EditorHistoryImpl } from './EditorHistory';+import { SceneStore, SceneStoreImpl } from './SceneStore';+import { Reconciler, ReconcilerImpl } from './Reconciler';+import { SceneCommands, SceneCommandsImpl } from './SceneCommands';+import { SceneQuery, SceneQueryImpl } from './SceneQuery';+import { useSelection, createSelectionStore, type SelectionStore } from '@/store/selectionStore';+import { EditorControlSurface, EditorControlSurfaceImpl } from './EditorControlSurface';++/**+ * The single editor boundary (REARCH_EDITOR_MODEL.md §3.5, P2). One instance owns+ * the whole editor-state graph — {model, history, store (reactivity), reconciler+ * (model→World), selection, commands, query} — and exposes one façade+ * ({@link EditorControlSurface}) for the UI, the headless host, and the MCP server.+ *+ * Wiring is explicit (constructor injection), not implicit global coupling, so a+ * session is instantiable in isolation: {@link EditorSession.create} builds a+ * fresh, independent graph for a headless host, the MCP server, or a test —+ * without touching the app's default-session singletons.+ *+ * The engine (wasm module / WebGL canvas / one World) is process-level and shared+ * via EngineHost; genuine multi-World sessions await the engine-instancing pillar.+ */+export class EditorSession {+ readonly model: SceneModelImpl;+ readonly history: EditorHistoryImpl;+ readonly store: SceneStoreImpl;+ readonly reconciler: ReconcilerImpl;+ readonly selection: SelectionStore;+ readonly commands: SceneCommandsImpl;+ readonly query: SceneQueryImpl;+ readonly surface: EditorControlSurfaceImpl;++ private constructor(parts: {+ model: SceneModelImpl;+ history: EditorHistoryImpl;+ store: SceneStoreImpl;+ reconciler: ReconcilerImpl;+ selection: SelectionStore;+ commands: SceneCommandsImpl;+ query: SceneQueryImpl;+ surface?: EditorControlSurfaceImpl;+ }) {+ this.model = parts.model;+ this.history = parts.history;+ this.store = parts.store;+ this.reconciler = parts.reconciler;+ this.selection = parts.selection;+ this.commands = parts.commands;+ this.query = parts.query;+ this.surface = parts.surface ?? new EditorControlSurfaceImpl(this);+ // Wire reactivity + projection to this session's model (idempotent — the+ // default session's parts may already be wired by EngineHost boot).+ this.store.install();+ this.reconciler.attach();+ }++ /**+ * Build an isolated session: a fresh model/history/store/reconciler/selection/+ * commands/query graph, independent of the app's default-session singletons.+ * The reconciler still projects to the process-level EngineHost World.+ */+ static create(): EditorSession {+ const model = new SceneModelImpl();+ const history = new EditorHistoryImpl();+ const store = new SceneStoreImpl(model);+ const reconciler = new ReconcilerImpl(model);+ const selection = createSelectionStore(model);+ const commands = new SceneCommandsImpl(model, history);+ const query = new SceneQueryImpl(model, store);+ return new EditorSession({ model, history, store, reconciler, selection, commands, query });+ }++ /** Tear down this session's reconciler subscription (for a disposed session). */+ dispose(): void {+ this.reconciler.detach();+ }++ /** The app's default session — wraps the engine-layer singletons. */+ static readonly default = new EditorSession({+ model: SceneModel,+ history: EditorHistory,+ store: SceneStore,+ reconciler: Reconciler,+ selection: useSelection,+ commands: SceneCommands,+ query: SceneQuery,+ surface: EditorControlSurface,+ });+}++/** The app's default editor session (the one the UI drives). */+export const defaultSession = EditorSession.default;diff --git a/desktop/src/engine/Reconciler.ts b/desktop/src/engine/Reconciler.tsindex aa6abbee0..f689dea6b 100644--- a/desktop/src/engine/Reconciler.ts+++ b/desktop/src/engine/Reconciler.ts@@ -2,7 +2,7 @@ import { Name, Parent, resetWorldTo } from 'esengine';import type { SceneData } from 'esengine';import type { EntityId } from '@/types';import { EngineHost } from './EngineHost';-import { SceneModel, type ModelEvent } from './SceneModel';+import { SceneModel, SceneModelImpl, type ModelEvent } from './SceneModel';import { componentByName, componentDefaults, type AnyComp, type WorldT } from './schema';/**@@ -14,7 +14,7 @@ import { componentByName, componentDefaults, type AnyComp, type WorldT } from '.* response. There is no other path from a command to the World, so the two* cannot diverge.*- * It owns the source↔runtime entity binding (via SceneModel.bindRuntime/+ * It owns the source↔runtime entity binding (via this.model.bindRuntime/* unbindRuntime) since it is what spawns and despawns. Components the engine* doesn't know stay in the model only — the World is a lossy render projection,* so unknown components / schema-extra fields / `@uuid:` refs never reach it.@@ -27,14 +27,16 @@ const STRUCTURAL = new Set(['Name', 'Parent', 'Children']);type AssetResolver = (uuid: string) => number;const UNRESOLVED: AssetResolver = () => 0;-class ReconcilerImpl {+export class ReconcilerImpl {private unsubscribe: (() => void) | null = null;private resolveAsset: AssetResolver = UNRESOLVED;+ constructor(private readonly model: SceneModelImpl) {}+/** Begin projecting model changes to the World. Idempotent. */attach(): void {if (this.unsubscribe) return;- this.unsubscribe = SceneModel.subscribe((ev) => this.onEvent(ev));+ this.unsubscribe = this.model.subscribe((ev) => this.onEvent(ev));}detach(): void {@@ -55,14 +57,14 @@ class ReconcilerImpl {/*** Bulk path (boot / project load / play-stop): build the World from a resolved* scene and adopt the raw scene as the model. `resetWorldTo` returns source-id- * → runtime; SceneModel.adopt records the map and announces a `reset`. This+ * → runtime; this.model.adopt records the map and announces a `reset`. This* reconciler ignores its own `reset` (the World is already built here).*/adopt(rawData: SceneData, resolvedData: SceneData): void {const world = EngineHost.mutableWorld();if (!world) return;const map = resetWorldTo(world, resolvedData as never) as Map<number, EntityId>;- SceneModel.adopt(rawData, map);+ this.model.adopt(rawData, map);}/**@@ -73,11 +75,11 @@ class ReconcilerImpl {*/rebuildWorld(): void {const world = EngineHost.mutableWorld();- const data = SceneModel.current;+ const data = this.model.current;if (!world || !data) return;const resolved = this.resolveRefs(data) as SceneData;const map = resetWorldTo(world, resolved as never) as Map<number, EntityId>;- SceneModel.adopt(data, map);+ this.model.adopt(data, map);}// ── Event projection ──────────────────────────────────────────────────────@@ -104,40 +106,40 @@ class ReconcilerImpl {private spawnEntity(sourceId: number): void {const world = EngineHost.mutableWorld();- const entity = SceneModel.entityBySource(sourceId);+ const entity = this.model.entityBySource(sourceId);if (!world || !entity) return;const rt = world.spawn();- SceneModel.bindRuntime(sourceId, rt);+ this.model.bindRuntime(sourceId, rt);if (entity.name) world.insert(rt, Name, { value: entity.name } as never);for (const comp of entity.components) {this.insertComponent(world, rt, comp.type, comp.data as Record<string, unknown>);}// Link to a parent that is already spawned…if (entity.parent != null) {- const pr = SceneModel.runtimeFor(entity.parent);+ const pr = this.model.runtimeFor(entity.parent);if (pr != null) world.insert(rt, Parent, { entity: pr } as never);}// …and re-link any already-spawned children (undo-of-delete restores a// parent after its children, so the children await this re-parent).for (const childId of entity.children) {- const cr = SceneModel.runtimeFor(childId);+ const cr = this.model.runtimeFor(childId);if (cr != null) world.insert(cr, Parent, { entity: rt } as never);}}private despawnEntity(sourceId: number): void {const world = EngineHost.mutableWorld();- const rt = SceneModel.runtimeFor(sourceId);+ const rt = this.model.runtimeFor(sourceId);if (world && rt != null && world.valid(rt)) world.despawn(rt);- SceneModel.unbindRuntime(sourceId);+ this.model.unbindRuntime(sourceId);}private projectComponent(sourceId: number, type: string): void {if (STRUCTURAL.has(type)) return; // identity/structure handled by name/parentconst world = EngineHost.mutableWorld();- const rt = SceneModel.runtimeFor(sourceId);- const entity = SceneModel.entityBySource(sourceId);+ const rt = this.model.runtimeFor(sourceId);+ const entity = this.model.entityBySource(sourceId);if (!world || rt == null || !entity) return;const def = componentByName(type);if (!def) return; // unknown component — lives in the model only@@ -151,7 +153,7 @@ class ReconcilerImpl {private removeComponent(sourceId: number, type: string): void {if (STRUCTURAL.has(type)) return;const world = EngineHost.mutableWorld();- const rt = SceneModel.runtimeFor(sourceId);+ const rt = this.model.runtimeFor(sourceId);if (!world || rt == null) return;const def = componentByName(type);if (def && world.has(rt, def)) world.remove(rt, def);@@ -159,18 +161,18 @@ class ReconcilerImpl {private projectParent(sourceId: number): void {const world = EngineHost.mutableWorld();- const rt = SceneModel.runtimeFor(sourceId);- const entity = SceneModel.entityBySource(sourceId);+ const rt = this.model.runtimeFor(sourceId);+ const entity = this.model.entityBySource(sourceId);if (!world || rt == null || !entity) return;- const pr = entity.parent != null ? SceneModel.runtimeFor(entity.parent) : undefined;+ const pr = entity.parent != null ? this.model.runtimeFor(entity.parent) : undefined;if (pr != null) world.insert(rt, Parent, { entity: pr } as never);else if (world.has(rt, Parent)) world.remove(rt, Parent);}private projectName(sourceId: number): void {const world = EngineHost.mutableWorld();- const rt = SceneModel.runtimeFor(sourceId);- const entity = SceneModel.entityBySource(sourceId);+ const rt = this.model.runtimeFor(sourceId);+ const entity = this.model.entityBySource(sourceId);if (!world || rt == null || !entity) return;world.insert(rt, Name, { value: entity.name } as never);}@@ -218,4 +220,5 @@ class ReconcilerImpl {}}-export const Reconciler = new ReconcilerImpl();+/** The app's default-session reconciler. Other sessions construct their own ReconcilerImpl(model). */+export const Reconciler = new ReconcilerImpl(SceneModel);diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex 6bf585bd1..d80a91e58 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -1,7 +1,7 @@import type { SceneData } from 'esengine';import type { EntityId, InspectorFieldType, InspectorFieldValue } from '@/types';-import { EditorHistory } from './EditorHistory';-import { SceneModel } from './SceneModel';+import { EditorHistory, EditorHistoryImpl } from './EditorHistory';+import { SceneModel, SceneModelImpl } from './SceneModel';import {componentByName,componentDefaults,@@ -16,15 +16,16 @@ type SceneComponent = SceneEntity['components'][number];// — Model-authoritative commands (REARCH_EDITOR_MODEL.md) —//-// Every mutation edits the SceneModel ONLY (the single source of truth). The+// Every mutation edits the SceneModel ONLY (the session's source of truth). The// model emits a change event; the Reconciler projects it to the World. Nothing// here touches the World — so the World is a pure derived projection that cannot// desync. Undo records MODEL operations (lossless by construction: the model// holds every component, incl. unknown ones + @uuid: refs + the parent link).//// All ids are stable **source ids** — the editor's id space (the viewport-// resolves a runtime pick to its source id before calling in). A source id-// survives undo/redo recreates, where the runtime World id changes.+// resolves a runtime pick to its source id before calling in). Commands are an+// instance bound to a session's model + history (EditorSession), so they can be+// isolated per session/test; `SceneCommands` is the app's default-session one.const DEFAULT_TRANSFORM = {position: { x: 0, y: 0, z: 0 },@@ -32,50 +33,12 @@ const DEFAULT_TRANSFORM = {scale: { x: 1, y: 1, z: 1 },};-// True if walking up from `nodeSrc` reaches `ancestorSrc` — used to reject-// re-parenting an entity under one of its own descendants (a cycle). Reads the-// model hierarchy (the truth), not the World.-function isModelAncestor(nodeSrc: number, ancestorSrc: number): boolean {- let cur: number | null = nodeSrc;- const seen = new Set<number>();- while (cur != null) {- if (cur === ancestorSrc) return true;- if (seen.has(cur)) break;- seen.add(cur);- cur = SceneModel.entityBySource(cur)?.parent ?? null;- }- return false;-}--// — Field-edit gesture: coalesce a focus→blur / drag into a single undo step. —-//-// Undo recording is INTERNAL: the only public write door is `setField` (and-// `setEntityXY`, which routes through it), and it always records. Outside a-// gesture, one `setField` = one undo step. Inside a gesture, writes coalesce —-// the BEFORE model value is captured on first touch of each field, the AFTER-// value read at `endGesture`, and the pair recorded as one model-op step.--interface FieldEdit {- sourceId: number;- comp: string;- key: string;- before: unknown; // model (SceneData-format) value before the gesture-}--let gesture: { label: string; touched: Map<string, FieldEdit> } | null = null;-const editKey = (sourceId: number, comp: string, key: string) => `${sourceId}|${comp}|${key}`;// Value equality over the SceneData-format shapes a field can hold (number /// bool / string / vec / quat / color object). JSON compare is exact for these.const valueEqual = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);-/** The current model value of one field, or undefined. */-function modelFieldValue(sourceId: number, comp: string, key: string): unknown {- const c = SceneModel.entityBySource(sourceId)?.components.find((c) => c.type === comp);- return c ? (c.data as Record<string, unknown>)[key] : undefined;-}-/*** Convert an inspector control value to its SceneData-format model value,* merging into the current value where the control edits a slice (vec@@ -114,32 +77,72 @@ function toModelValue(}}-export const SceneCommands = {+interface FieldEdit {+ sourceId: number;+ comp: string;+ key: string;+ before: unknown; // model (SceneData-format) value before the gesture+}++export class SceneCommandsImpl {+ // — Field-edit gesture: coalesce a focus→blur / drag into a single undo step. —+ // Undo recording is INTERNAL: the only public write door is `setField` (and+ // `setEntityXY`, which routes through it), and it always records. Outside a+ // gesture, one `setField` = one undo step. Inside a gesture, writes coalesce —+ // the BEFORE model value is captured on first touch of each field, the AFTER+ // value read at `endGesture`, and the pair recorded as one model-op step.+ private gesture: { label: string; touched: Map<string, FieldEdit> } | null = null;++ constructor(+ private readonly model: SceneModelImpl,+ private readonly history: EditorHistoryImpl,+ ) {}++ /** The current model value of one field, or undefined. */+ private modelFieldValue(sourceId: number, comp: string, key: string): unknown {+ const c = this.model.entityBySource(sourceId)?.components.find((c) => c.type === comp);+ return c ? (c.data as Record<string, unknown>)[key] : undefined;+ }++ // True if walking up from `nodeSrc` reaches `ancestorSrc` — rejects re-parenting+ // an entity under its own descendant (a cycle). Reads the model hierarchy.+ private isModelAncestor(nodeSrc: number, ancestorSrc: number): boolean {+ let cur: number | null = nodeSrc;+ const seen = new Set<number>();+ while (cur != null) {+ if (cur === ancestorSrc) return true;+ if (seen.has(cur)) break;+ seen.add(cur);+ cur = this.model.entityBySource(cur)?.parent ?? null;+ }+ return false;+ }+/*** Open a coalescing edit gesture. Every `setField` until {@link endGesture}* folds into one undo step. Idempotent-safe: a dangling gesture is committed* before a new one opens.*/beginGesture(label: string): void {- if (gesture) this.endGesture();- gesture = { label, touched: new Map() };- },+ if (this.gesture) this.endGesture();+ this.gesture = { label, touched: new Map() };+ }/** Close the current gesture, recording all coalesced field edits as one undo step. */endGesture(): void {- const g = gesture;- gesture = null;+ const g = this.gesture;+ this.gesture = null;if (!g || g.touched.size === 0) return;const edits = [...g.touched.values()]- .map((e) => ({ ...e, after: structuredClone(modelFieldValue(e.sourceId, e.comp, e.key)) }))+ .map((e) => ({ ...e, after: structuredClone(this.modelFieldValue(e.sourceId, e.comp, e.key)) })).filter((e) => !valueEqual(e.before, e.after));if (edits.length === 0) return;- EditorHistory.record(+ this.history.record(g.label,- () => edits.forEach((e) => SceneModel.setField(e.sourceId, e.comp, e.key, e.after)),- () => edits.forEach((e) => SceneModel.setField(e.sourceId, e.comp, e.key, e.before)),+ () => edits.forEach((e) => this.model.setField(e.sourceId, e.comp, e.key, e.after)),+ () => edits.forEach((e) => this.model.setField(e.sourceId, e.comp, e.key, e.before)),);- },+ }/*** Write a single inspector field to the model (the Reconciler re-projects it@@ -152,77 +155,77 @@ export const SceneCommands = {type: InspectorFieldType,value: InspectorFieldValue,): void {- const e = SceneModel.entityBySource(sourceId);+ const e = this.model.entityBySource(sourceId);if (!e) return;const cur = (e.components.find((c) => c.type === compName)?.data as Record<string, unknown>) ?? {};const k = editKey(sourceId, compName, key);- const firstTouch = !gesture || !gesture.touched.has(k);+ const firstTouch = !this.gesture || !this.gesture.touched.has(k);const before = firstTouch ? structuredClone(cur[key]) : undefined;const after = toModelValue(cur, type, key, value);- SceneModel.setField(sourceId, compName, key, after);+ this.model.setField(sourceId, compName, key, after);- if (gesture) {- if (firstTouch) gesture.touched.set(k, { sourceId, comp: compName, key, before });+ if (this.gesture) {+ if (firstTouch) this.gesture.touched.set(k, { sourceId, comp: compName, key, before });return;}// No open gesture → this edit is its own undo step.if (valueEqual(before, after)) return;- EditorHistory.record(+ this.history.record(`Edit ${prettyLabel(key)}`,- () => SceneModel.setField(sourceId, compName, key, after),- () => SceneModel.setField(sourceId, compName, key, before),+ () => this.model.setField(sourceId, compName, key, after),+ () => this.model.setField(sourceId, compName, key, before),);- },+ }/** Move an entity to a world position (keeps Z). Undoable like any field edit. */setEntityXY(sourceId: EntityId, x: number, y: number): void {- const pos = modelFieldValue(sourceId, 'Transform', 'position') as { z?: number } | undefined;- if (pos === undefined && !SceneModel.entityBySource(sourceId)) return;+ const pos = this.modelFieldValue(sourceId, 'Transform', 'position') as { z?: number } | undefined;+ if (pos === undefined && !this.model.entityBySource(sourceId)) return;this.setField(sourceId, 'Transform', 'position', 'vec3', [x, y, pos?.z ?? 0]);- },+ }// — Undoable entity lifecycle (model ops; the Reconciler re-spawns/-despawns) —/** Spawn a new empty entity (with a Transform). Returns its source id. */addEntity(): EntityId | null {- if (!SceneModel.current) return null;- const sourceId = SceneModel.addEntity('Entity', [+ if (!this.model.current) return null;+ const sourceId = this.model.addEntity('Entity', [{ type: 'Transform', data: structuredClone(DEFAULT_TRANSFORM) } as SceneComponent,]);let record: SceneEntity | undefined;- EditorHistory.record(+ this.history.record('Add Entity',() => {- if (record) SceneModel.restoreEntity(record);+ if (record) this.model.restoreEntity(record);},() => {- record = SceneModel.removeEntityBySource(sourceId);+ record = this.model.removeEntityBySource(sourceId);},);return sourceId;- },+ }/** Delete an entity (undo re-creates it, losslessly, from the model record). */deleteEntity(sourceId: EntityId): void {- const name = SceneModel.entityBySource(sourceId)?.name || 'Entity';- let record = SceneModel.removeEntityBySource(sourceId);+ const name = this.model.entityBySource(sourceId)?.name || 'Entity';+ let record = this.model.removeEntityBySource(sourceId);if (!record) return;- EditorHistory.record(+ this.history.record(`Delete ${name}`,() => {- record = SceneModel.removeEntityBySource(record!.id) ?? record;+ record = this.model.removeEntityBySource(record!.id) ?? record;},() => {- SceneModel.restoreEntity(record!);+ this.model.restoreEntity(record!);},);- },+ }/** Duplicate an entity (offset slightly, as a sibling). Returns the new source id. */duplicateEntity(sourceId: EntityId): EntityId | null {- const src = SceneModel.entityBySource(sourceId);+ const src = this.model.entityBySource(sourceId);if (!src) return null;// Clone the SOURCE record (preserves unknown components/fields + @uuid: refs// the World projection can't carry), with the standard paste offset.@@ -234,52 +237,52 @@ export const SceneCommands = {pos.x += 24;pos.y -= 24;}- const newSourceId = SceneModel.addEntity(src.name, components, src.parent ?? null);+ const newSourceId = this.model.addEntity(src.name, components, src.parent ?? null);let record: SceneEntity | undefined;- EditorHistory.record(+ this.history.record(`Duplicate ${src.name || 'Entity'}`,() => {- if (record) SceneModel.restoreEntity(record);+ if (record) this.model.restoreEntity(record);},() => {- record = SceneModel.removeEntityBySource(newSourceId);+ record = this.model.removeEntityBySource(newSourceId);},);return newSourceId;- },+ }/** Rename an entity (undoable). */renameEntity(sourceId: EntityId, name: string): void {- const before = SceneModel.entityBySource(sourceId)?.name;+ const before = this.model.entityBySource(sourceId)?.name;if (before === undefined || before === name) return;- SceneModel.setName(sourceId, name);- EditorHistory.record(+ this.model.setName(sourceId, name);+ this.history.record(`Rename ${name || 'Entity'}`,- () => SceneModel.setName(sourceId, name),- () => SceneModel.setName(sourceId, before),+ () => this.model.setName(sourceId, name),+ () => this.model.setName(sourceId, before),);- },+ }/*** Re-parent an entity (drag-reparent). Undoable. Rejects self-parenting and* cycles (parenting under its own descendant); `parent: null` un-parents.*/setParent(sourceId: EntityId, parent: EntityId | null): void {- if (!SceneModel.entityBySource(sourceId)) return;- if (parent != null && (parent === sourceId || isModelAncestor(parent, sourceId))) return;- const before = SceneModel.entityBySource(sourceId)?.parent ?? null;+ if (!this.model.entityBySource(sourceId)) return;+ if (parent != null && (parent === sourceId || this.isModelAncestor(parent, sourceId))) return;+ const before = this.model.entityBySource(sourceId)?.parent ?? null;if (before === parent) return;- SceneModel.setParent(sourceId, parent);- EditorHistory.record(+ this.model.setParent(sourceId, parent);+ this.history.record('Reparent',- () => SceneModel.setParent(sourceId, parent),- () => SceneModel.setParent(sourceId, before),+ () => this.model.setParent(sourceId, parent),+ () => this.model.setParent(sourceId, before),);- },+ }/** Add a component (with its registered/schema defaults) to an entity. Undoable. */addComponent(sourceId: EntityId, compName: string): void {- const entity = SceneModel.entityBySource(sourceId);+ const entity = this.model.entityBySource(sourceId);if (!entity || entity.components.some((c) => c.type === compName)) return;const def = componentByName(compName);// Builtins default from the engine registry; user/script components from the@@ -287,27 +290,27 @@ export const SceneCommands = {const data = def? structuredClone(componentDefaults(def)): structuredClone(userSchema(compName)?.default ?? {});- SceneModel.setComponent(sourceId, compName, data);- EditorHistory.record(+ this.model.setComponent(sourceId, compName, data);+ this.history.record(`Add ${prettyLabel(compName)}`,- () => SceneModel.setComponent(sourceId, compName, structuredClone(data)),- () => SceneModel.removeComponent(sourceId, compName),+ () => this.model.setComponent(sourceId, compName, structuredClone(data)),+ () => this.model.removeComponent(sourceId, compName),);- },+ }/** Remove a component from an entity (Transform / Name are protected). Undoable. */removeComponent(sourceId: EntityId, compName: string): void {if (compName === 'Transform' || compName === 'Name') return;- const comp = SceneModel.entityBySource(sourceId)?.components.find((c) => c.type === compName);+ const comp = this.model.entityBySource(sourceId)?.components.find((c) => c.type === compName);if (!comp) return;const data = structuredClone(comp.data);- SceneModel.removeComponent(sourceId, compName);- EditorHistory.record(+ this.model.removeComponent(sourceId, compName);+ this.history.record(`Remove ${prettyLabel(compName)}`,- () => SceneModel.removeComponent(sourceId, compName),- () => SceneModel.setComponent(sourceId, compName, structuredClone(data)),+ () => this.model.removeComponent(sourceId, compName),+ () => this.model.setComponent(sourceId, compName, structuredClone(data)),);- },+ }/*** Toggle an entity's editor visibility by flipping the `enabled` field of each@@ -315,7 +318,7 @@ export const SceneCommands = {* persisted; SceneQuery reflects it as the row's visibility.*/setEntityVisible(sourceId: EntityId, visible: boolean): void {- const entity = SceneModel.entityBySource(sourceId);+ const entity = this.model.entityBySource(sourceId);if (!entity) return;this.beginGesture(visible ? 'Show' : 'Hide');for (const comp of entity.components) {@@ -325,5 +328,8 @@ export const SceneCommands = {}}this.endGesture();- },-};+ }+}++/** The app's default-session commands. Other sessions construct their own SceneCommandsImpl(model, history). */+export const SceneCommands = new SceneCommandsImpl(SceneModel, EditorHistory);diff --git a/desktop/src/engine/SceneModel.ts b/desktop/src/engine/SceneModel.tsindex bb3f819a9..adbcd751a 100644--- a/desktop/src/engine/SceneModel.ts+++ b/desktop/src/engine/SceneModel.ts@@ -38,7 +38,7 @@ type Listener = (ev: ModelEvent) => void;* but only the Reconciler writes it — via {@link bindRuntime}/{@link unbindRuntime}* as it spawns/despawns — so the map can never go stale against the World.*/-class SceneModelImpl {+export class SceneModelImpl {private data: SceneData | null = null;/** runtime World entity → source entity id (Reconciler-maintained). */private readonly runtimeToSource = new Map<EntityId, number>();@@ -274,4 +274,5 @@ class SceneModelImpl {}}+/** The app's default-session model. Other sessions construct their own SceneModelImpl. */export const SceneModel = new SceneModelImpl();diff --git a/desktop/src/engine/SceneQuery.ts b/desktop/src/engine/SceneQuery.tsindex 8b112f5f8..63f82f79c 100644--- a/desktop/src/engine/SceneQuery.ts+++ b/desktop/src/engine/SceneQuery.ts@@ -1,6 +1,6 @@import type { SceneNode, NodeKind, EntityId, InspectorComponent, InspectorFieldValue } from '@/types';-import { SceneStore } from './SceneStore';-import { SceneModel } from './SceneModel';+import { SceneStore, SceneStoreImpl } from './SceneStore';+import { SceneModel, SceneModelImpl } from './SceneModel';import {inspectorFields,inferField,@@ -18,16 +18,24 @@ import {* still reads the World for camera-derived screen geometry (pick / gizmo /* selection outline) via ViewportController; that is rendering, the engine's* domain. All ids here are stable **source ids**.+ *+ * An instance bound to a session's model + store; `SceneQuery` is the app's+ * default-session one.*/-export const SceneQuery = {+export class SceneQueryImpl {+ constructor(+ private readonly model: SceneModelImpl,+ private readonly store: SceneStoreImpl,+ ) {}+/** Monotonic counter; bump means the scene structure changed (for observers). */worldVersion(): number {- return SceneStore.getStructureRevision();- },+ return this.store.getStructureRevision();+ }/** Build the outliner tree from the model, nesting via parent/children links. */readSceneTree(): SceneNode[] {- const data = SceneModel.current;+ const data = this.model.current;if (!data) return [];const byId = new Map(data.entities.map((e) => [e.id, e]));@@ -48,22 +56,20 @@ export const SceneQuery = {};// Roots = entities with no parent, or whose parent no longer exists.- return data.entities- .filter((e) => e.parent == null || !byId.has(e.parent))- .map(build);- },+ return data.entities.filter((e) => e.parent == null || !byId.has(e.parent)).map(build);+ }/** Inspect a single source entity (name, kind, which components it carries). */readEntity(id: EntityId): { name: string; kind: NodeKind; components: string[] } | null {- const e = SceneModel.entityBySource(id);+ const e = this.model.entityBySource(id);if (!e) return null;const kind = modelKindOf(e);return { name: modelNameOf(e, kind), kind, components: modelInspectableComponents(e).map((c) => c.label) };- },+ }/** Full editable inspector model for a source entity — fields resolved per component. */readInspector(id: EntityId): InspectorComponent[] {- const e = SceneModel.entityBySource(id);+ const e = this.model.entityBySource(id);if (!e) return [];const out: InspectorComponent[] = [];for (const { name, label } of modelInspectableComponents(e)) {@@ -71,14 +77,17 @@ export const SceneQuery = {out.push({ name, label, fields: inspectorFields(name, data) });}return out;- },+ }/** Read one inspector field's current value (for undo before/after capture). */getFieldValue(id: EntityId, compName: string, key: string): InspectorFieldValue | null {- const comp = SceneModel.entityBySource(id)?.components.find((c) => c.type === compName);+ const comp = this.model.entityBySource(id)?.components.find((c) => c.type === compName);if (!comp) return null;const data = comp.data as Record<string, unknown>;const f = inferField(key, data[key], isColorKey(compName, key));return f ? f.value : null;- },-};+ }+}++/** The app's default-session query surface. Other sessions construct their own SceneQueryImpl(model, store). */+export const SceneQuery = new SceneQueryImpl(SceneModel, SceneStore);diff --git a/desktop/src/engine/SceneStore.ts b/desktop/src/engine/SceneStore.tsindex 6260acbe9..25ea07d0b 100644--- a/desktop/src/engine/SceneStore.ts+++ b/desktop/src/engine/SceneStore.ts@@ -1,5 +1,5 @@import { createStore } from 'zustand/vanilla';-import { SceneModel, type ModelEvent } from './SceneModel';+import { SceneModel, SceneModelImpl, type ModelEvent } from './SceneModel';/*** Reactive mirror of the editor scene — the model-change bus.@@ -16,18 +16,20 @@ import { SceneModel, type ModelEvent } from './SceneModel';* (The engine's EditorBridge — the old push source — is retired: the World is a* derived projection now, so there is nothing to push back.)*/-class SceneStoreImpl {+export class SceneStoreImpl {private installed = false;private readonly store = createStore<{ revision: number; structureRevision: number }>(() => ({revision: 1,structureRevision: 1,}));+ constructor(private readonly model: SceneModelImpl) {}+/** Subscribe to the model as the change source. Idempotent. */install() {if (this.installed) return;this.installed = true;- SceneModel.subscribe((ev) => this.bump(isStructural(ev)));+ this.model.subscribe((ev) => this.bump(isStructural(ev)));}private bump(structural: boolean) {@@ -47,4 +49,5 @@ function isStructural(ev: ModelEvent): boolean {return ev.kind !== 'componentChanged';}-export const SceneStore = new SceneStoreImpl();+/** The app's default-session store. Other sessions construct their own SceneStoreImpl(model). */+export const SceneStore = new SceneStoreImpl(SceneModel);diff --git a/desktop/src/store/selectionStore.ts b/desktop/src/store/selectionStore.tsindex 13498efd5..83ab1039f 100644--- a/desktop/src/store/selectionStore.ts+++ b/desktop/src/store/selectionStore.ts@@ -1,5 +1,5 @@import { create } from 'zustand';-import { SceneModel } from '@/engine/SceneModel';+import { SceneModel, SceneModelImpl } from '@/engine/SceneModel';import type { EntityId } from '@/types';/**@@ -28,43 +28,55 @@ interface SelectionState {dropId: (id: EntityId) => void;}-export const useSelection = create<SelectionState>((set) => ({- selectedId: null,- selectedIds: new Set<EntityId>(),+export type SelectionStore = ReturnType<typeof createSelectionStore>;- select: (selectedId) =>- set({ selectedId, selectedIds: selectedId != null ? new Set([selectedId]) : new Set() }),+/**+ * Build a selection store bound to a model. Model-anchored self-healing: when an+ * entity is removed from the model (delete, undo-of-create), it drops from the+ * selection by source id — no manual deselect. Wholesale scene swaps (open+ * project, reload) clear selection explicitly (the bulk path), since source ids+ * restart with the incoming scene. One per EditorSession.+ */+export function createSelectionStore(model: SceneModelImpl) {+ const useStore = create<SelectionState>((set) => ({+ selectedId: null,+ selectedIds: new Set<EntityId>(),++ select: (selectedId) =>+ set({ selectedId, selectedIds: selectedId != null ? new Set([selectedId]) : new Set() }),- toggleSelect: (id) =>- set((s) => {- const next = new Set(s.selectedIds);- if (next.has(id)) {+ toggleSelect: (id) =>+ set((s) => {+ const next = new Set(s.selectedIds);+ if (next.has(id)) {+ next.delete(id);+ const primary =+ s.selectedId === id ? (next.size ? [...next][next.size - 1] : null) : s.selectedId;+ return { selectedIds: next, selectedId: primary };+ }+ next.add(id);+ return { selectedIds: next, selectedId: id };+ }),++ selectMany: (ids, primary) => set({ selectedIds: new Set(ids), selectedId: primary }),++ dropId: (id) =>+ set((s) => {+ if (s.selectedId !== id && !s.selectedIds.has(id)) return s;+ const next = new Set(s.selectedIds);next.delete(id);const primary =s.selectedId === id ? (next.size ? [...next][next.size - 1] : null) : s.selectedId;return { selectedIds: next, selectedId: primary };- }- next.add(id);- return { selectedIds: next, selectedId: id };- }),+ }),+ }));- selectMany: (ids, primary) => set({ selectedIds: new Set(ids), selectedId: primary }),+ model.subscribe((ev) => {+ if (ev.kind === 'entityRemoved') useStore.getState().dropId(ev.sourceId);+ });- dropId: (id) =>- set((s) => {- if (s.selectedId !== id && !s.selectedIds.has(id)) return s;- const next = new Set(s.selectedIds);- next.delete(id);- const primary =- s.selectedId === id ? (next.size ? [...next][next.size - 1] : null) : s.selectedId;- return { selectedIds: next, selectedId: primary };- }),-}));+ return useStore;+}-// Model-anchored self-healing: when an entity is removed from the model (delete,-// undo-of-create), drop it from the selection by source id — no manual deselect.-// Wholesale scene swaps (open project, reload) emit `reset` and clear selection-// explicitly (the bulk path), since source ids restart with the incoming scene.-SceneModel.subscribe((ev) => {- if (ev.kind === 'entityRemoved') useSelection.getState().dropId(ev.sourceId);-});+/** The app's default-session selection. Other sessions build their own via createSelectionStore. */+export const useSelection = createSelectionStore(SceneModel);diff --git a/desktop/tests/editor-control-surface.test.ts b/desktop/tests/editor-control-surface.test.tsindex 40330e938..cb3ce5332 100644--- a/desktop/tests/editor-control-surface.test.ts+++ b/desktop/tests/editor-control-surface.test.ts@@ -1,14 +1,15 @@/*** @file Regression net for EditorControlSurface — the one canonical- * programmatic entry to the editor (docs/REARCH_EDITOR_AUTOMATION.md).- * Proves the surface delegates correctly to the command/query core and- * that step() drives deterministic ticks, all against a real headless- * World. captureViewport needs a WebGL2 canvas, so here we only assert it- * fails clearly without a render host (covered end-to-end by the headless- * editor window, not the pure-node harness).+ * programmatic entry to a session (REARCH_EDITOR_MODEL.md P2 ++ * docs/REARCH_EDITOR_AUTOMATION.md). Proves the surface delegates to its+ * session's command/query core and that step() drives deterministic ticks,+ * all against a real headless World. captureViewport needs a WebGL2 canvas,+ * so here we only assert it fails clearly without a render host (covered+ * end-to-end by the headless editor window, not the pure-node harness).*- * EngineHost (the boot singleton that needs a canvas) is mocked to a per-test- * headless World; tick() drives the real App so step() exercises the engine.+ * Each test uses its own isolated EditorSession; the engine (boot singleton that+ * needs a canvas) is mocked to a per-test headless World; tick() drives the real+ * App so step() exercises the engine.*/import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';import { App, Transform } from 'esengine';@@ -46,10 +47,7 @@ vi.mock('@/engine/EngineHost', () => ({},}));-import { EditorControlSurface as API } from '@/engine/EditorControlSurface';-import { EditorHistory } from '@/engine/EditorHistory';-import { SceneModel } from '@/engine/SceneModel';-import { Reconciler } from '@/engine/Reconciler';+import { EditorSession } from '@/engine/EditorSession';import type { SceneData } from 'esengine';const emptyScene = (): SceneData =>@@ -57,6 +55,7 @@ const emptyScene = (): SceneData =>describe.skipIf(!HAS_WASM)('EditorControlSurface (headless World)', () => {let module: ESEngineModule;+ let S: EditorSession;beforeAll(async () => {module = await loadWasmModule();});@@ -68,42 +67,39 @@ describe.skipIf(!HAS_WASM)('EditorControlSurface (headless World)', () => {host.app = app;host.ticks = 0;host.runMode = null;- EditorHistory.clear();- SceneModel.clear();- // Commands edit the model; the Reconciler projects to the World.- Reconciler.attach();- SceneModel.adopt(emptyScene(), new Map());+ S = EditorSession.create();+ S.model.adopt(emptyScene(), new Map());});- afterEach(() => Reconciler.detach());+ afterEach(() => S.dispose());it('addEntity surfaces through the scene tree and stats', () => {- const id = API.addEntity();+ const id = S.surface.addEntity();expect(id).not.toBeNull();- expect(API.getSceneTree().length).toBe(1);- expect(API.getStats().entities).toBe(1);+ expect(S.surface.getSceneTree().length).toBe(1);+ expect(S.surface.getStats().entities).toBe(1);});it('setField writes a component field; surface undo reverts it', () => {- const id = API.addEntity()!; // source id- const e = SceneModel.runtimeFor(id)!; // runtime World entity- API.setField(id, 'Transform', 'position', 'vec3', [10, 20, 30]);+ const id = S.surface.addEntity()!; // source id+ const e = S.model.runtimeFor(id)!; // runtime World entity+ S.surface.setField(id, 'Transform', 'position', 'vec3', [10, 20, 30]);expect(host.world.get(e, Transform).position).toMatchObject({ x: 10, y: 20, z: 30 });- API.undo();+ S.surface.undo();expect(host.world.get(e, Transform).position).toMatchObject({ x: 0, y: 0, z: 0 });});it('step(n) drives exactly n deterministic ticks', async () => {- await API.step(3, 1 / 60);+ await S.surface.step(3, 1 / 60);expect(host.ticks).toBe(3);});it('setRunMode delegates play/pause state to the host', () => {- API.setRunMode(true, true);+ S.surface.setRunMode(true, true);expect(host.runMode).toEqual([true, true]);});it('captureViewport fails clearly without a render host', () => {- expect(() => API.captureViewport()).toThrow(/render host/);+ expect(() => S.surface.captureViewport()).toThrow(/render host/);});});diff --git a/desktop/tests/engine-commands.test.ts b/desktop/tests/engine-commands.test.tsindex 47e834dc4..671bcd7e2 100644--- a/desktop/tests/engine-commands.test.ts+++ b/desktop/tests/engine-commands.test.ts@@ -5,10 +5,11 @@* the Reconciler projects into the World, undo replays model ops — and the* World, a derived projection, reflects every step.*- * EngineHost (the engine-boot singleton that needs a canvas + WebGL) is mocked- * to return a per-test headless World built from the WASM SDK; the rest of the- * editor logic (SceneModel, Reconciler, EditorHistory, schema) runs for real.- * Commands return SOURCE ids; the World is asserted via SceneModel.runtimeFor.+ * Each test runs in its OWN isolated EditorSession (REARCH_EDITOR_MODEL P2) — a+ * fresh model/history/reconciler graph, no shared-singleton state to clear. The+ * engine (wasm World) is process-level: EngineHost is mocked to a per-test+ * headless World the session's reconciler projects into. Commands return SOURCE+ * ids; the World is asserted via session.model.runtimeFor.*/import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';import { App, Transform, Parent, Sprite } from 'esengine';@@ -28,21 +29,18 @@ vi.mock('@/engine/EngineHost', () => ({},}));-import { SceneCommands } from '@/engine/SceneCommands';-import { SceneQuery } from '@/engine/SceneQuery';-import { SceneModel } from '@/engine/SceneModel';-import { Reconciler } from '@/engine/Reconciler';-import { EditorHistory } from '@/engine/EditorHistory';+import { EditorSession } from '@/engine/EditorSession';import type { SceneData } from 'esengine';const emptyScene = (): SceneData =>({ version: '1.0', name: 'test', entities: [] }) as unknown as SceneData;-/** Resolve a source id to its current runtime World entity (for World asserts). */-const rt = (sourceId: number): number => SceneModel.runtimeFor(sourceId)!;-describe.skipIf(!HAS_WASM)('SceneCommands / SceneQuery (headless World)', () => {let module: ESEngineModule;+ let S: EditorSession;+ /** Resolve a source id to its current runtime World entity (for World asserts). */+ const rt = (sourceId: number): number => S.model.runtimeFor(sourceId)!;+beforeAll(async () => {module = await loadWasmModule();});@@ -51,133 +49,130 @@ describe.skipIf(!HAS_WASM)('SceneCommands / SceneQuery (headless World)', () =>const registry = new module.Registry();app.connectCpp(registry as never, module);host.world = app.world;- EditorHistory.clear();- SceneModel.clear();- // Commands edit the model; the Reconciler projects to the World. Adopt an- // empty scene so the model has a current document for commands to grow.- Reconciler.attach();- SceneModel.adopt(emptyScene(), new Map());+ // A fresh, isolated session; its reconciler projects to the (mocked) World.+ S = EditorSession.create();+ S.model.adopt(emptyScene(), new Map());});- afterEach(() => Reconciler.detach());+ afterEach(() => S.dispose());it('addEntity spawns an entity with a Transform; undo/redo round-trips', () => {- const id = SceneCommands.addEntity();+ const id = S.commands.addEntity();expect(id).not.toBeNull();expect(host.world.valid(rt(id!))).toBe(true);expect(host.world.has(rt(id!), Transform)).toBe(true);expect(host.world.getAllEntities().length).toBe(1);- EditorHistory.undo();+ S.history.undo();expect(host.world.getAllEntities().length).toBe(0);- EditorHistory.redo();+ S.history.redo();expect(host.world.getAllEntities().length).toBe(1);});it('setField writes a component field; undo reverts to the prior value', () => {- const id = SceneCommands.addEntity()!;+ const id = S.commands.addEntity()!;const e = rt(id);- SceneCommands.setField(id, 'Transform', 'position', 'vec3', [10, 20, 30]);+ S.commands.setField(id, 'Transform', 'position', 'vec3', [10, 20, 30]);expect(host.world.get(e, Transform).position).toMatchObject({ x: 10, y: 20, z: 30 });- EditorHistory.undo();+ S.history.undo();expect(host.world.get(e, Transform).position).toMatchObject({ x: 0, y: 0, z: 0 });- EditorHistory.redo();+ S.history.redo();expect(host.world.get(e, Transform).position).toMatchObject({ x: 10, y: 20, z: 30 });});it('a gesture coalesces multiple setField writes into one undo step', () => {- const id = SceneCommands.addEntity()!;+ const id = S.commands.addEntity()!;const e = rt(id);- SceneCommands.beginGesture('Drag');- SceneCommands.setField(id, 'Transform', 'position', 'vec3', [1, 0, 0]);- SceneCommands.setField(id, 'Transform', 'position', 'vec3', [2, 0, 0]);- SceneCommands.setField(id, 'Transform', 'position', 'vec3', [3, 0, 0]);- SceneCommands.endGesture();+ S.commands.beginGesture('Drag');+ S.commands.setField(id, 'Transform', 'position', 'vec3', [1, 0, 0]);+ S.commands.setField(id, 'Transform', 'position', 'vec3', [2, 0, 0]);+ S.commands.setField(id, 'Transform', 'position', 'vec3', [3, 0, 0]);+ S.commands.endGesture();expect(host.world.get(e, Transform).position.x).toBe(3);- EditorHistory.undo(); // one step undoes the whole drag+ S.history.undo(); // one step undoes the whole dragexpect(host.world.get(e, Transform).position.x).toBe(0);});it('deleteEntity removes the entity; undo re-creates it', () => {- const id = SceneCommands.addEntity()!;+ const id = S.commands.addEntity()!;expect(host.world.getAllEntities().length).toBe(1);- SceneCommands.deleteEntity(id);+ S.commands.deleteEntity(id);expect(host.world.getAllEntities().length).toBe(0);- EditorHistory.undo();+ S.history.undo();expect(host.world.getAllEntities().length).toBe(1);});it('SceneQuery.readInspector lists the entity\'s editable components', () => {- const id = SceneCommands.addEntity()!;- const comps = SceneQuery.readInspector(id);+ const id = S.commands.addEntity()!;+ const comps = S.query.readInspector(id);const transform = comps.find((c) => c.name === 'Transform');expect(transform).toBeDefined();expect(transform!.fields.some((f) => f.key === 'position')).toBe(true);});it('SceneQuery.readSceneTree returns a node per root entity', () => {- SceneCommands.addEntity();- SceneCommands.addEntity();- const tree = SceneQuery.readSceneTree();+ S.commands.addEntity();+ S.commands.addEntity();+ const tree = S.query.readSceneTree();expect(tree.length).toBe(2);});it('setParent parents an entity (Parent component); undo un-parents it', () => {- const parent = SceneCommands.addEntity()!;- const child = SceneCommands.addEntity()!;+ const parent = S.commands.addEntity()!;+ const child = S.commands.addEntity()!;const childRt = rt(child);const parentRt = rt(parent);- SceneCommands.setParent(child, parent);+ S.commands.setParent(child, parent);expect(host.world.has(childRt, Parent)).toBe(true);expect((host.world.get(childRt, Parent) as { entity: number }).entity).toBe(parentRt);- EditorHistory.undo();+ S.history.undo();expect(host.world.has(childRt, Parent)).toBe(false);- EditorHistory.redo();+ S.history.redo();expect(host.world.has(childRt, Parent)).toBe(true);});it('setParent rejects a cycle (parenting under a descendant)', () => {- const a = SceneCommands.addEntity()!;- const b = SceneCommands.addEntity()!;+ const a = S.commands.addEntity()!;+ const b = S.commands.addEntity()!;const aRt = rt(a);const bRt = rt(b);- SceneCommands.setParent(b, a); // b under a- SceneCommands.setParent(a, b); // a under b would cycle — rejected+ S.commands.setParent(b, a); // b under a+ S.commands.setParent(a, b); // a under b would cycle — rejectedexpect(host.world.has(aRt, Parent)).toBe(false);expect((host.world.get(bRt, Parent) as { entity: number }).entity).toBe(aRt);});it('addComponent inserts a component (with defaults); undo/redo round-trips', () => {- const id = SceneCommands.addEntity()!;+ const id = S.commands.addEntity()!;const e = rt(id);expect(host.world.has(e, Sprite)).toBe(false);- SceneCommands.addComponent(id, 'Sprite');+ S.commands.addComponent(id, 'Sprite');expect(host.world.has(e, Sprite)).toBe(true);- EditorHistory.undo();+ S.history.undo();expect(host.world.has(e, Sprite)).toBe(false);- EditorHistory.redo();+ S.history.redo();expect(host.world.has(e, Sprite)).toBe(true);});it('removeComponent removes a component; undo restores it; Transform is protected', () => {- const id = SceneCommands.addEntity()!;+ const id = S.commands.addEntity()!;const e = rt(id);- SceneCommands.addComponent(id, 'Sprite');- SceneCommands.removeComponent(id, 'Sprite');+ S.commands.addComponent(id, 'Sprite');+ S.commands.removeComponent(id, 'Sprite');expect(host.world.has(e, Sprite)).toBe(false);- EditorHistory.undo();+ S.history.undo();expect(host.world.has(e, Sprite)).toBe(true);- SceneCommands.removeComponent(id, 'Transform');+ S.commands.removeComponent(id, 'Transform');expect(host.world.has(e, Transform)).toBe(true);});});diff --git a/desktop/tests/engine-model-sync.test.ts b/desktop/tests/engine-model-sync.test.tsindex 8eb919fd1..fba23f78a 100644--- a/desktop/tests/engine-model-sync.test.ts+++ b/desktop/tests/engine-model-sync.test.ts@@ -4,9 +4,12 @@* so the World stays a faithful derived projection while the model* serializes LOSSLESSLY — unknown components/fields the World drops* survive an edit→save round trip, and delete→undo restores them.+ *+ * Runs in an isolated EditorSession (P2): the session's reconciler bulk-adopts+ * the scene into the (mocked) headless World; commands flow model→World through it.*/import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';-import { App, Transform, Parent, resetWorldTo } from 'esengine';+import { App, Transform, Parent } from 'esengine';import type { ESEngineModule, SceneData } from 'esengine';import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';@@ -21,10 +24,7 @@ vi.mock('@/engine/EngineHost', () => ({},}));-import { SceneCommands } from '@/engine/SceneCommands';-import { SceneModel } from '@/engine/SceneModel';-import { Reconciler } from '@/engine/Reconciler';-import { EditorHistory } from '@/engine/EditorHistory';+import { EditorSession } from '@/engine/EditorSession';function sceneWithUnknown(): SceneData {return {@@ -52,8 +52,9 @@ function sceneWithUnknown(): SceneData {} as unknown as SceneData;}-describe.skipIf(!HAS_WASM)('JSON-first dual-write + lossless save (L3/L4)', () => {+describe.skipIf(!HAS_WASM)('Model-authoritative projection + lossless save', () => {let module: ESEngineModule;+ let S: EditorSession;let runtime1: number;beforeAll(async () => {module = await loadWasmModule();@@ -62,29 +63,25 @@ describe.skipIf(!HAS_WASM)('JSON-first dual-write + lossless save (L3/L4)', () =const app = App.new();app.connectCpp(new module.Registry() as never, module);host.world = app.world;- EditorHistory.clear();- SceneModel.clear();- // The Reconciler projects model → World; attach it so commands reach the- // World (attach is idempotent across the suite, and reads the live world).- Reconciler.attach();- // Project the scene into the World (lossy) and adopt it as the model (lossless).- const map = resetWorldTo(host.world, structuredClone(sceneWithUnknown()) as never);- SceneModel.adopt(structuredClone(sceneWithUnknown()), map as Map<number, number>);- runtime1 = map.get(1)!;+ S = EditorSession.create();+ // Bulk path: build the World (lossy) and adopt the raw scene (lossless).+ // No @uuid: refs here, so resolved === raw.+ S.reconciler.adopt(sceneWithUnknown(), sceneWithUnknown());+ runtime1 = S.model.runtimeFor(1)!;// The World dropped the unknown component; the model kept it.expect(host.world.has(runtime1, Transform)).toBe(true);});- afterEach(() => Reconciler.detach());+ afterEach(() => S.dispose());it('setField edits the World AND the model, preserving the unknown component', () => {- SceneCommands.setField(1, 'Transform', 'position', 'vec3', [9, 8, 7]); // by source id+ S.commands.setField(1, 'Transform', 'position', 'vec3', [9, 8, 7]); // by source id// World reflects the edit:expect(host.world.get(runtime1, Transform).position).toMatchObject({ x: 9, y: 8, z: 7 });// Model (the save truth) reflects the edit AND still has the unknown component:- const saved = SceneModel.serialize()!;+ const saved = S.model.serialize()!;const hero = saved.entities.find((e) => e.id === 1)!;const t = hero.components.find((c) => c.type === 'Transform')!.data as {position: { x: number };@@ -96,9 +93,9 @@ describe.skipIf(!HAS_WASM)('JSON-first dual-write + lossless save (L3/L4)', () =});it('undo of a field edit reverts the model too', () => {- SceneCommands.setField(1, 'Transform', 'position', 'vec3', [9, 0, 0]); // by source id- EditorHistory.undo();- const hero = SceneModel.serialize()!.entities.find((e) => e.id === 1)!;+ S.commands.setField(1, 'Transform', 'position', 'vec3', [9, 0, 0]); // by source id+ S.history.undo();+ const hero = S.model.serialize()!.entities.find((e) => e.id === 1)!;const t = hero.components.find((c) => c.type === 'Transform')!.data as {position: { x: number };};@@ -106,19 +103,19 @@ describe.skipIf(!HAS_WASM)('JSON-first dual-write + lossless save (L3/L4)', () =});it('addEntity / undo is reflected in the model', () => {- const before = SceneModel.serialize()!.entities.length;- SceneCommands.addEntity();- expect(SceneModel.serialize()!.entities.length).toBe(before + 1);- EditorHistory.undo();- expect(SceneModel.serialize()!.entities.length).toBe(before);+ const before = S.model.serialize()!.entities.length;+ S.commands.addEntity();+ expect(S.model.serialize()!.entities.length).toBe(before + 1);+ S.history.undo();+ expect(S.model.serialize()!.entities.length).toBe(before);});it('delete then undo preserves the unknown component (lossless undo)', () => {- SceneCommands.deleteEntity(1); // by source id- expect(SceneModel.serialize()!.entities.length).toBe(0);+ S.commands.deleteEntity(1); // by source id+ expect(S.model.serialize()!.entities.length).toBe(0);- EditorHistory.undo();- const saved = SceneModel.serialize()!;+ S.history.undo();+ const saved = S.model.serialize()!;expect(saved.entities.length).toBe(1);// the restored entity still carries the unknown component:expect(saved.entities[0].components.some((c) => c.type === 'WaveMotion')).toBe(true);@@ -126,28 +123,28 @@ describe.skipIf(!HAS_WASM)('JSON-first dual-write + lossless save (L3/L4)', () =it('delete of a parented entity with an unknown component → undo restores model + World + parent link', () => {// Add a child of Hero (source 1) carrying an unknown component.- const childSrc = SceneModel.addEntity(+ const childSrc = S.model.addEntity('Child',[{ type: 'WaveMotion', data: { amplitude: 3 } }] as never,1,);- const childRt = SceneModel.runtimeFor(childSrc)!;+ const childRt = S.model.runtimeFor(childSrc)!;expect(host.world.valid(childRt)).toBe(true);// The World got the parent link (unknown WaveMotion stays model-only).expect(host.world.has(childRt, Parent)).toBe(true);expect((host.world.get(childRt, Parent) as { entity: number }).entity).toBe(runtime1);- SceneCommands.deleteEntity(childSrc);- expect(SceneModel.entityBySource(childSrc)).toBeUndefined();+ S.commands.deleteEntity(childSrc);+ expect(S.model.entityBySource(childSrc)).toBeUndefined();expect(host.world.valid(childRt)).toBe(false);- EditorHistory.undo();+ S.history.undo();// Model: child is back, with its parent link AND its unknown component.- const restored = SceneModel.entityBySource(childSrc)!;+ const restored = S.model.entityBySource(childSrc)!;expect(restored.parent).toBe(1);expect(restored.components.some((c) => c.type === 'WaveMotion')).toBe(true);// World: child re-spawned and re-parented to Hero's runtime entity.- const newChildRt = SceneModel.runtimeFor(childSrc)!;+ const newChildRt = S.model.runtimeFor(childSrc)!;expect(host.world.has(newChildRt, Parent)).toBe(true);expect((host.world.get(newChildRt, Parent) as { entity: number }).entity).toBe(runtime1);});diff --git a/desktop/tests/inspector-model.test.ts b/desktop/tests/inspector-model.test.tsindex d30b5ce14..6726b3974 100644--- a/desktop/tests/inspector-model.test.ts+++ b/desktop/tests/inspector-model.test.ts@@ -4,16 +4,15 @@* know them — their field shapes come from `schemas.json`. The inspector* reads the MODEL, so it lists + edits them and the model round-trips* losslessly. No World / wasm needed: unknown components are model-only- * (the Reconciler skips projecting them), so this is a pure model+schema- * test — SceneCommands/SceneQuery don't even import EngineHost.+ * (the Reconciler skips projecting them; the session's World is null here).+ *+ * Runs in an isolated EditorSession (P2) — fresh model/query/commands/history,+ * no shared-singleton state to clear.*/import { describe, it, expect, beforeEach } from 'vitest';import type { SceneData } from 'esengine';-import { SceneModel } from '@/engine/SceneModel';-import { SceneQuery } from '@/engine/SceneQuery';-import { SceneCommands } from '@/engine/SceneCommands';+import { EditorSession } from '@/engine/EditorSession';import { setUserSchemas } from '@/engine/schema';-import { EditorHistory } from '@/engine/EditorHistory';const WAVE_SCHEMA = {name: 'WaveMotion',@@ -49,27 +48,27 @@ function sceneWithWave(): SceneData {}describe('Unknown-component inspector (schemas.json consumer)', () => {+ let S: EditorSession;beforeEach(() => {- SceneModel.clear();- EditorHistory.clear();setUserSchemas([WAVE_SCHEMA]);+ S = EditorSession.create();// Bind source id 1 to a placeholder runtime id; unknown components are never- // projected, so the value is irrelevant — the model is the truth here.- SceneModel.adopt(sceneWithWave(), new Map([[1, 1]]));+ // projected (and the session's World is null), so the model is the truth here.+ S.model.adopt(sceneWithWave(), new Map([[1, 1]]));});it('lists an unknown component with its schema fields', () => {- const wave = SceneQuery.readInspector(1).find((c) => c.name === 'WaveMotion');+ const wave = S.query.readInspector(1).find((c) => c.name === 'WaveMotion');expect(wave).toBeDefined();expect(wave!.fields.map((f) => f.key).sort()).toEqual(['amplitude', 'phase']);expect(wave!.fields.find((f) => f.key === 'amplitude')!.value).toBe(5);});it('edits an unknown component field; the model round-trips losslessly', () => {- SceneCommands.setField(1, 'WaveMotion', 'amplitude', 'number', 9);- expect(SceneQuery.getFieldValue(1, 'WaveMotion', 'amplitude')).toBe(9);+ S.commands.setField(1, 'WaveMotion', 'amplitude', 'number', 9);+ expect(S.query.getFieldValue(1, 'WaveMotion', 'amplitude')).toBe(9);- const saved = SceneModel.serialize()!;+ const saved = S.model.serialize()!;const wave = saved.entities[0].components.find((c) => c.type === 'WaveMotion')!.data as {amplitude: number;phase: number;@@ -79,16 +78,16 @@ describe('Unknown-component inspector (schemas.json consumer)', () => {});it('undo reverts an unknown-component edit', () => {- SceneCommands.setField(1, 'WaveMotion', 'amplitude', 'number', 9);- EditorHistory.undo();- expect(SceneQuery.getFieldValue(1, 'WaveMotion', 'amplitude')).toBe(5);+ S.commands.setField(1, 'WaveMotion', 'amplitude', 'number', 9);+ S.history.undo();+ expect(S.query.getFieldValue(1, 'WaveMotion', 'amplitude')).toBe(5);});it('infers editable fields from the data even without a schema', () => {setUserSchemas([]); // no schemas.json for this component- SceneModel.clear();- SceneModel.adopt(sceneWithWave(), new Map([[1, 1]]));- const wave = SceneQuery.readInspector(1).find((c) => c.name === 'WaveMotion');+ const fresh = EditorSession.create();+ fresh.model.adopt(sceneWithWave(), new Map([[1, 1]]));+ const wave = fresh.query.readInspector(1).find((c) => c.name === 'WaveMotion');expect(wave).toBeDefined();expect(wave!.fields.find((f) => f.key === 'amplitude')!.value).toBe(5);});diff --git a/desktop/tests/selection-store.test.ts b/desktop/tests/selection-store.test.tsindex b36340430..ca02a474e 100644--- a/desktop/tests/selection-store.test.ts+++ b/desktop/tests/selection-store.test.ts@@ -1,17 +1,18 @@/**- * @file SelectionStore — engine-anchored entity selection.+ * @file SelectionStore — model-anchored entity selection.** Covers the pure selection ops and, crucially, the SELF-HEALING property that- * lets every call site stop hand-clearing selection: when an entity is despawned- * the scene bridge carries its id to the store, which drops it — no manual- * deselect, no world.valid() race (the despawn notify fires before removal).+ * lets every call site stop hand-clearing selection: when an entity is removed+ * from the model the selection store drops it — no manual deselect. The+ * self-healing test runs in its own isolated EditorSession (REARCH_EDITOR_MODEL+ * P2): the session's selection self-heals on its own model's `entityRemoved`.** EngineHost is mocked to a headless World built from the WASM SDK (same harness- * as engine-commands.test.ts); SceneStore + SceneCommands run for real.+ * as engine-commands.test.ts); the session's reconciler projects into it.*/import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';import { App } from 'esengine';-import type { ESEngineModule } from 'esengine';+import type { ESEngineModule, SceneData } from 'esengine';import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';const host = vi.hoisted(() => ({ world: null as unknown as App['world'] }));@@ -26,18 +27,13 @@ vi.mock('@/engine/EngineHost', () => ({}));import { useSelection } from '@/store/selectionStore';-import { SceneStore } from '@/engine/SceneStore';-import { SceneCommands } from '@/engine/SceneCommands';-import { SceneModel } from '@/engine/SceneModel';-import { Reconciler } from '@/engine/Reconciler';-import type { SceneData } from 'esengine';--const sel = () => useSelection.getState();+import { EditorSession } from '@/engine/EditorSession';const emptyScene = (): SceneData =>({ version: '1.0', name: 'test', entities: [] }) as unknown as SceneData;describe('SelectionStore — pure selection ops', () => {+ const sel = () => useSelection.getState();beforeEach(() => sel().select(null));it('select / toggleSelect / selectMany maintain the set + primary', () => {@@ -83,42 +79,40 @@ describe('SelectionStore — pure selection ops', () => {});});-describe.skipIf(!HAS_WASM)('SelectionStore — engine-anchored self-healing', () => {- // One World + one bridge install for the whole block, so the default context- // (which notifyBridge reads) stays consistent across tests.+describe.skipIf(!HAS_WASM)('SelectionStore — model-anchored self-healing', () => {+ let S: EditorSession;+ const sel = () => S.selection.getState();+ // One World for the block; a fresh session per test isolates selection + model.beforeAll(async () => {const module: ESEngineModule = await loadWasmModule();const app = App.new();const registry = new module.Registry();app.connectCpp(registry as never, module);host.world = app.world;- SceneStore.install();- // Commands edit the model → Reconciler despawns the World entity → the engine- // bridge carries the despawn to the selection store (the self-heal path).- Reconciler.attach();- SceneModel.adopt(emptyScene(), new Map());});- beforeEach(() => sel().select(null));+ beforeEach(() => {+ S = EditorSession.create();+ S.model.adopt(emptyScene(), new Map());+ });- it('a deleted entity auto-drops from the selection via the scene bridge', () => {- const id = SceneCommands.addEntity()!;+ it('a deleted entity auto-drops from the selection via the model', () => {+ const id = S.commands.addEntity()!;sel().select(id);expect(sel().selectedId).toBe(id);- // Delete via the command path → world.despawn → onEntityDespawned bridge →- // SelectionStore.dropId. The selection clears itself, no manual deselect.- SceneCommands.deleteEntity(id);+ // Delete via the command path → model entityRemoved → selection.dropId.+ S.commands.deleteEntity(id);expect(sel().selectedId).toBeNull();expect(sel().selectedIds.size).toBe(0);});it('deleting one of a multi-selection keeps the survivors selected', () => {- const a = SceneCommands.addEntity()!;- const b = SceneCommands.addEntity()!;+ const a = S.commands.addEntity()!;+ const b = S.commands.addEntity()!;sel().selectMany([a, b], b);expect(sel().selectedIds.size).toBe(2);- SceneCommands.deleteEntity(b); // bridge drops b; a survives and becomes primary+ S.commands.deleteEntity(b); // model drops b; a survives and becomes primaryexpect(sel().selectedIds.has(b)).toBe(false);expect(sel().selectedIds.has(a)).toBe(true);expect(sel().selectedId).toBe(a);diff --git a/docs/REARCH_EDITOR_MODEL.md b/docs/REARCH_EDITOR_MODEL.mdindex d40ca8945..1a484ec72 100644--- a/docs/REARCH_EDITOR_MODEL.md+++ b/docs/REARCH_EDITOR_MODEL.md@@ -1,11 +1,26 @@# REARCH — Model-Authoritative Editor (unidirectional data flow)-Status: **P1 implemented** (2026-06-20); P2/P3 proposed. Authoritative plan for-inverting the editor's data flow from *dual-write* to a single source of truth-with derived projections. This is the natural completion of+Status: **P1 + P2-core implemented** (2026-06-20); P3 proposed. Authoritative+plan for inverting the editor's data flow from *dual-write* to a single source of+truth with derived projections. This is the natural completion of`REARCH_SERIALIZATION.md` (JSON-first model) and the prerequisite for`REARCH_EDITOR_REALM.md` (isolated play).+**P2-core done** — the engine-state singletons are now instance classes wired by+constructor injection (`SceneModelImpl`/`EditorHistoryImpl`/`SceneStoreImpl`/+`ReconcilerImpl`/`SceneCommandsImpl`/`SceneQueryImpl` + `createSelectionStore`).+A new `desktop/src/engine/EditorSession.ts` owns the whole graph as ONE instance;+`EditorControlSurface` is its façade (`EditorControlSurfaceImpl(session)`).+`EditorSession.create()` builds an isolated session (fresh model/history/.../World+projection) for a headless host, the MCP server, or a test — proven by migrating+every wasm test to a per-test session (no shared-singleton `clear()`). The app's+default-session singletons are preserved, so the UI/EngineHost are unchanged.+**Remaining P2 (gradual):** route the UI through `session`/the surface (full H2+closure) and decouple EngineHost from the default-session reconciler — these need+no new design, just mechanical migration; genuine multi-World sessions await the+engine-instancing pillar. RESUME: finish P2 UI-routing **or** start **P3**+(isolated play realm).+**P1 done** — commands mutate the `SceneModel` (by stable source id) only; a new`desktop/src/engine/Reconciler.ts` projects model→World (the World is now a purederived projection); `SceneStore` is a model-change bus (the engine `editorBridge`