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
feat(editor): model-authoritative data flow (REARCH_EDITOR_MODEL P1)
esenginefe2697a67996
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsxindex 6f408dec4..4f6197b45 100644--- a/desktop/src/App.tsx+++ b/desktop/src/App.tsx@@ -7,7 +7,6 @@ import { EngineHost } from '@/engine/EngineHost';import { Launcher } from '@/launcher/Launcher';import { Toaster } from '@/components/Toaster';import { useEditorStore } from '@/store/editorStore';-import { useSelection } from '@/store/selectionStore';import { commands } from '@/commands';// The editor shell: fixed menu + toolbar on top, dockable workspace in the@@ -33,14 +32,13 @@ export function App() {}, []);// Drive engine edit/play mode from the toolbar's play/pause state. Edit mode- // (the default) freezes gameplay systems so they don't fight scene edits;- // Stop restores the pre-play scene snapshot. A restore re-spawns entities- // with new ids, so any selection pointing at the played scene is now stale.+ // (the default) freezes gameplay systems so they don't fight scene edits; Stop+ // rebuilds the World from the untouched edit model (model-authoritative). The+ // selection holds stable source ids, so it survives the rebuild — no clear.const isPlaying = useEditorStore((s) => s.isPlaying);const isPaused = useEditorStore((s) => s.isPaused);useEffect(() => {- const restored = EngineHost.setRunMode(isPlaying, isPaused);- if (restored) useSelection.getState().select(null);+ EngineHost.setRunMode(isPlaying, isPaused);}, [isPlaying, isPaused]);// The editor opens on the launcher (project browser); the shell + engine mountdiff --git a/desktop/src/engine/EditorControlSurface.ts b/desktop/src/engine/EditorControlSurface.tsindex a88fc9cf2..0bb752e33 100644--- a/desktop/src/engine/EditorControlSurface.ts+++ b/desktop/src/engine/EditorControlSurface.ts@@ -7,8 +7,10 @@* 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 undoable write boundary), reads- * through SceneQuery / SceneModel, and observation reads the live canvas/World.+ * commands route through SceneCommands (the model write boundary), reads through+ * 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).*/import type {EntityId,@@ -115,7 +117,7 @@ export const EditorControlSurface = {},// =========================================================================- // Queries — read-only reflection of the live World / scene truth+ // Queries — read-only reflection of the scene model (the source of truth)// =========================================================================worldVersion(): number {diff --git a/desktop/src/engine/EngineHost.ts b/desktop/src/engine/EngineHost.tsindex b16480d8e..f767d3c46 100644--- a/desktop/src/engine/EngineHost.ts+++ b/desktop/src/engine/EngineHost.ts@@ -10,11 +10,10 @@ import {EditorView,setEditorMode,setPlayMode,- serializeScene,- resetWorldTo,} from 'esengine';-import type { App, ESEngineModule, SceneData, ResourceDef } from 'esengine';+import type { App, ESEngineModule, ResourceDef } from 'esengine';import { SceneStore } from './SceneStore';+import { Reconciler } from './Reconciler';import { SceneLoader } from './SceneLoader';import { checkEngineBuild } from './EngineGuard';import type { ReadonlyWorldT, WorldT } from './schema';@@ -49,9 +48,9 @@ class EngineHostImpl {private readonly statusStore = createStore<EngineSnapshot>(() => ({ status: 'idle', error: null }));- // Play-state isolation: the scene captured when entering play, restored on stop.+ // Play-state isolation: Stop rebuilds the World from the untouched edit model+ // (model-authoritative), so no snapshot is needed — the model IS the truth.private playing_ = false;- private playSnapshot_: SceneData | null = null;// What to load once the engine is ready. Set by ProjectStore when a project// is opened from the launcher; absent → the in-repo placeholder scene (dev).@@ -129,27 +128,25 @@ class EngineHostImpl {/*** Map the editor's play/pause UI state onto the engine, with play-state- * isolation: entering play snapshots the scene; Stop despawns the played- * scene and restores the snapshot, so try-playing never dirties the edit- * scene. Not playing ⇒ edit mode (gameplay frozen via env.playModeOnly, scene- * still rendered/editable); playing ⇒ gameplay runs; paused-while-playing- * halts every schedule. No-op until booted.+ * isolation: entering play runs gameplay against the live World; Stop discards+ * those mutations by rebuilding the World from the untouched edit MODEL+ * (model-authoritative, REARCH_EDITOR_MODEL.md) — no snapshot, no stale id map.+ * Not playing ⇒ edit mode (gameplay frozen via env.playModeOnly, scene still+ * rendered/editable); playing ⇒ gameplay runs; paused-while-playing halts every+ * schedule. No-op until booted.*- * @returns true if a play→edit restore happened (the caller should clear any- * stale selection, since entity ids change on restore).+ * @returns true if a play→edit rebuild happened. Selection survives it (source+ * ids are stable across the rebuild), so the caller need not clear it.*/setRunMode(isPlaying: boolean, isPaused: boolean): boolean {const app = this.app_;if (!app) return false;let restored = false;- if (isPlaying && !this.playing_) {- // edit → play: capture the scene so Stop can restore it.- this.playSnapshot_ = serializeScene(app.world);- } else if (!isPlaying && this.playing_ && this.playSnapshot_) {- // play → edit (Stop): restore the pre-play scene (snapshot is reusable).- resetWorldTo(app.world, this.playSnapshot_);- this.playSnapshot_ = null;+ if (!isPlaying && this.playing_) {+ // play → edit (Stop): rebuild the World from the untouched edit model,+ // discarding everything gameplay did to the World during play.+ Reconciler.rebuildWorld();restored = true;}this.playing_ = isPlaying;@@ -340,8 +337,11 @@ class EngineHostImpl {setEditorMode(true);setPlayMode(false);- // Register the reactive bridge before the scene spawns so the initial- // entities push through too.+ // Model-authoritative data flow (REARCH_EDITOR_MODEL.md): commands mutate+ // the SceneModel; the Reconciler is the single writer that follows into the+ // World, and SceneStore turns model changes into panel reactivity. Attach+ // the Reconciler FIRST so the World is projected before reactivity fires.+ Reconciler.attach();SceneStore.install();if (opts.loadInitialScene) {diff --git a/desktop/src/engine/EntityHandles.ts b/desktop/src/engine/EntityHandles.tsdeleted file mode 100644index 185997e37..000000000--- a/desktop/src/engine/EntityHandles.ts+++ /dev/null@@ -1,43 +0,0 @@-import type { EntityId } from '@/types';--/**- * Stable editor handles for entities.- *- * The engine frees an entity id on despawn and hands out a fresh one on the- * next spawn, so undo/redo that re-creates an entity changes its live id. Undo- * closures therefore can't capture a raw id — they capture a stable handle and- * resolve it to the current live id at run time. `acquire` returns the SAME- * handle for an id that already has one, so commands acting on the same entity- * (e.g. duplicate then delete) share a handle and stay consistent across- * re-creates.- */-class EntityHandlesImpl {- private next = 1;- private readonly toId = new Map<number, EntityId | null>();- private readonly toHandle = new Map<EntityId, number>();-- /** Get the handle for an entity, creating one if needed. */- acquire(id: EntityId): number {- const existing = this.toHandle.get(id);- if (existing != null) return existing;- const handle = this.next++;- this.toId.set(handle, id);- this.toHandle.set(id, handle);- return handle;- }-- /** Current live entity id for a handle, or null if it's deleted. */- liveId(handle: number): EntityId | null {- return this.toId.get(handle) ?? null;- }-- /** Point a handle at a new live id (or null when the entity is deleted). */- rebind(handle: number, newId: EntityId | null): void {- const old = this.toId.get(handle);- if (old != null) this.toHandle.delete(old);- this.toId.set(handle, newId);- if (newId != null) this.toHandle.set(newId, handle);- }-}--export const EntityHandles = new EntityHandlesImpl();diff --git a/desktop/src/engine/Reconciler.ts b/desktop/src/engine/Reconciler.tsnew file mode 100644index 000000000..aa6abbee0--- /dev/null+++ b/desktop/src/engine/Reconciler.ts@@ -0,0 +1,221 @@+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 { componentByName, componentDefaults, type AnyComp, type WorldT } from './schema';++/**+ * Projects the model into the World (REARCH_EDITOR_MODEL.md §3.3).+ *+ * The invariant the whole rearchitecture rests on: **the World is a pure+ * function of the Model.** Commands mutate the model only; the model emits a+ * change event; this reconciler is the SINGLE place that writes the World in+ * 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/+ * 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.+ */++const UUID_PREFIX = '@uuid:';+/** Structural/identity components projected explicitly (name, parent), not as data. */+const STRUCTURAL = new Set(['Name', 'Parent', 'Children']);++type AssetResolver = (uuid: string) => number;+const UNRESOLVED: AssetResolver = () => 0;++class ReconcilerImpl {+ private unsubscribe: (() => void) | null = null;+ private resolveAsset: AssetResolver = UNRESOLVED;++ /** Begin projecting model changes to the World. Idempotent. */+ attach(): void {+ if (this.unsubscribe) return;+ this.unsubscribe = SceneModel.subscribe((ev) => this.onEvent(ev));+ }++ detach(): void {+ this.unsubscribe?.();+ this.unsubscribe = null;+ }++ /**+ * Install the `@uuid:` → GL-handle resolver. ProjectStore sets this after+ * loading a scene's textures, so entities recreated incrementally (duplicate,+ * undo-of-delete) re-resolve their asset refs the same way load does. Defaults+ * to "unresolved" (blank to 0) — fine for tests and ref-free scenes.+ */+ setAssetResolver(fn: AssetResolver | null): void {+ this.resolveAsset = fn ?? UNRESOLVED;+ }++ /**+ * 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+ * 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);+ }++ /**+ * Rebuild the entire World from the current model (play-stop): resolve the+ * model's `@uuid:` refs, reset the World to it, and rebind the source↔runtime+ * map. The model is the untouched edit scene, so this discards whatever+ * gameplay did to the World during play. No-op if no scene/world.+ */+ rebuildWorld(): void {+ const world = EngineHost.mutableWorld();+ const data = SceneModel.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);+ }++ // ── Event projection ──────────────────────────────────────────────────────++ private onEvent(ev: ModelEvent): void {+ switch (ev.kind) {+ case 'reset':+ return; // bulk path already built the World+ case 'entityAdded':+ return this.spawnEntity(ev.sourceId);+ case 'entityRemoved':+ return this.despawnEntity(ev.sourceId);+ case 'componentAdded':+ case 'componentChanged':+ return this.projectComponent(ev.sourceId, ev.type);+ case 'componentRemoved':+ return this.removeComponent(ev.sourceId, ev.type);+ case 'parentChanged':+ return this.projectParent(ev.sourceId);+ case 'nameChanged':+ return this.projectName(ev.sourceId);+ }+ }++ private spawnEntity(sourceId: number): void {+ const world = EngineHost.mutableWorld();+ const entity = SceneModel.entityBySource(sourceId);+ if (!world || !entity) return;++ const rt = world.spawn();+ SceneModel.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);+ 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);+ 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);+ if (world && rt != null && world.valid(rt)) world.despawn(rt);+ SceneModel.unbindRuntime(sourceId);+ }++ private projectComponent(sourceId: number, type: string): void {+ if (STRUCTURAL.has(type)) return; // identity/structure handled by name/parent+ const world = EngineHost.mutableWorld();+ const rt = SceneModel.runtimeFor(sourceId);+ const entity = SceneModel.entityBySource(sourceId);+ if (!world || rt == null || !entity) return;+ const def = componentByName(type);+ if (!def) return; // unknown component — lives in the model only+ const comp = entity.components.find((c) => c.type === type);+ if (!comp) return;+ const data = this.projectData(def, comp.data as Record<string, unknown>);+ if (world.has(rt, def)) world.set(rt, def, data as Parameters<WorldT['set']>[2]);+ else world.insert(rt, def, data as never);+ }++ private removeComponent(sourceId: number, type: string): void {+ if (STRUCTURAL.has(type)) return;+ const world = EngineHost.mutableWorld();+ const rt = SceneModel.runtimeFor(sourceId);+ if (!world || rt == null) return;+ const def = componentByName(type);+ if (def && world.has(rt, def)) world.remove(rt, def);+ }++ private projectParent(sourceId: number): void {+ const world = EngineHost.mutableWorld();+ const rt = SceneModel.runtimeFor(sourceId);+ const entity = SceneModel.entityBySource(sourceId);+ if (!world || rt == null || !entity) return;+ const pr = entity.parent != null ? SceneModel.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);+ if (!world || rt == null || !entity) return;+ world.insert(rt, Name, { value: entity.name } as never);+ }++ // ── Data projection (model SceneData shape → World component data) ─────────++ private insertComponent(+ world: WorldT,+ rt: EntityId,+ type: string,+ data: Record<string, unknown>,+ ): void {+ if (STRUCTURAL.has(type)) return;+ const def = componentByName(type);+ if (!def) return; // unknown — model only+ world.insert(rt, def, this.projectData(def, data) as never);+ }++ /**+ * Build the World-facing component data from the model's record: keep only the+ * fields the engine component knows (the World is lossy — schema-extra fields+ * stay in the model), and resolve `@uuid:` asset refs to live GL handles.+ */+ private projectData(def: AnyComp, data: Record<string, unknown>): Record<string, unknown> {+ const defaults = componentDefaults(def);+ const out: Record<string, unknown> = {};+ for (const key of Object.keys(defaults)) {+ out[key] = key in data ? this.resolveRefs(data[key]) : defaults[key];+ }+ return out;+ }++ /** Recursively replace `@uuid:<id>` strings with resolved asset handles. */+ private resolveRefs(value: unknown): unknown {+ if (typeof value === 'string') {+ return value.startsWith(UUID_PREFIX) ? this.resolveAsset(value.slice(UUID_PREFIX.length)) : value;+ }+ if (Array.isArray(value)) return value.map((v) => this.resolveRefs(v));+ if (value && typeof value === 'object') {+ const out: Record<string, unknown> = {};+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) out[k] = this.resolveRefs(v);+ return out;+ }+ return value;+ }+}++export const Reconciler = new ReconcilerImpl();diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex d28e71fb5..6bf585bd1 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -1,57 +1,30 @@-import { Transform, Name, Parent, getAllRegisteredComponents } from 'esengine';+import type { SceneData } from 'esengine';import type { EntityId, InspectorFieldType, InspectorFieldValue } from '@/types';-import { EngineHost } from './EngineHost';import { EditorHistory } from './EditorHistory';-import { EntityHandles } from './EntityHandles';import { SceneModel } from './SceneModel';-import { SceneQuery } from './SceneQuery';-import { componentByName, inspectableComponents, angleZToQuat, hexToRgb, prettyLabel, type WorldT } from './schema';--// — Entity snapshot capture/restore for undoable create/delete —-// Parent/Children carry entity-id references that go stale on re-create, so-// hierarchy links aren't restored here (flat re-spawn). Refinement: remap ids.-const STRUCTURAL_SKIP = new Set(['Parent', 'Children']);--interface CapturedEntity {- name: string;- comps: Array<{ name: string; data: unknown }>;-}--function captureEntity(world: WorldT, id: EntityId): CapturedEntity | null {- if (!world.valid(id)) return null;- let name = '';- const comps: Array<{ name: string; data: unknown }> = [];- for (const [compName, def] of getAllRegisteredComponents()) {- if (STRUCTURAL_SKIP.has(compName) || !world.has(id, def)) continue;- const data = structuredClone(world.get(id, def));- if (compName === 'Name') name = (data as { value?: string }).value ?? '';- comps.push({ name: compName, data });- }- return { name, comps };-}--function recreateEntity(world: WorldT, cap: CapturedEntity): EntityId {- const e = world.spawn();- for (const c of cap.comps) {- const def = componentByName(c.name);- if (def) world.insert(e, def, c.data as never);- }- return e;-}--// True if `ancestor` is `node` or sits above it (walking up Parent links) — used-// to reject re-parenting an entity under one of its own descendants (a cycle).-function isDescendant(world: WorldT, node: EntityId, ancestor: EntityId): boolean {- let cur: EntityId | null = node;- const seen = new Set<EntityId>();- while (cur != null && world.valid(cur)) {- if (cur === ancestor) return true;- if (seen.has(cur) || !world.has(cur, Parent)) break;- seen.add(cur);- cur = (world.get(cur, Parent) as unknown as { entity: EntityId }).entity;- }- return false;-}+import {+ componentByName,+ componentDefaults,+ userSchema,+ angleZToQuat,+ hexToRgb,+ prettyLabel,+} from './schema';++type SceneEntity = SceneData['entities'][number];+type SceneComponent = SceneEntity['components'][number];++// — Model-authoritative commands (REARCH_EDITOR_MODEL.md) —+//+// Every mutation edits the SceneModel ONLY (the single 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.const DEFAULT_TRANSFORM = {position: { x: 0, y: 0, z: 0 },@@ -59,90 +32,86 @@ 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 to this module: the only public write door is-// `setField` (and `setEntityXY`, which routes through it), and it always-// records. The raw, non-recording writer `applyFieldWrite` is module-private,-// so no caller can mutate a field while skipping undo. Outside a gesture, one-// `setField` = one undo step. Inside a gesture, writes coalesce — the BEFORE-// value is captured on first touch of each field, the AFTER value read at-// `endGesture`, and the pair recorded as one 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 {- entity: EntityId;+ sourceId: number;comp: string;key: string;- type: InspectorFieldType;- before: InspectorFieldValue;+ before: unknown; // model (SceneData-format) value before the gesture}let gesture: { label: string; touched: Map<string, FieldEdit> } | null = null;-const editKey = (entity: EntityId, comp: string, key: string) => `${entity}|${comp}|${key}`;+const editKey = (sourceId: number, comp: string, key: string) => `${sourceId}|${comp}|${key}`;-function fieldEqual(a: InspectorFieldValue, b: InspectorFieldValue): boolean {- if (Array.isArray(a) && Array.isArray(b)) {- return a.length === b.length && a.every((v, i) => v === b[i]);- }- return a === b;+// 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;}-// Raw write straight through to the engine World — NO undo recording, NOT-// exported. Besides `setField`, the only callers are the undo/redo closures-// (which must re-apply without re-recording).-function applyFieldWrite(- entity: EntityId,- compName: string,- key: string,+/**+ * Convert an inspector control value to its SceneData-format model value,+ * merging into the current value where the control edits a slice (vec+ * components keep the untouched axis; color keeps alpha). 2D rotation is stored+ * as a quaternion; angle controls convert degrees↔quat.+ */+function toModelValue(+ cur: Record<string, unknown>,type: InspectorFieldType,+ key: string,value: InspectorFieldValue,-): void {- const world = EngineHost.mutableWorld();- if (!world || !world.valid(entity)) return;- const def = componentByName(compName);- if (!def) return;-- const cur = world.get(entity, def) as unknown as Record<string, unknown>;- const next: Record<string, unknown> = { ...cur };-+): unknown {switch (type) {case 'number':- next[key] = Number(value);- break;+ return Number(value);case 'bool':- next[key] = Boolean(value);- break;+ return Boolean(value);case 'string':- next[key] = String(value);- break;+ return String(value);case 'vec2': {const [x, y] = value as [number, number];- next[key] = { ...(cur[key] as object), x, y };- break;+ return { ...(cur[key] as object), x, y };}case 'vec3': {const [x, y, z] = value as [number, number, number];- next[key] = { ...(cur[key] as object), x, y, z };- break;+ return { ...(cur[key] as object), x, y, z };}case 'angle':- next[key] = angleZToQuat(Number(value));- break;+ return angleZToQuat(Number(value));case 'color': {const a = (cur[key] as { a?: number } | undefined)?.a ?? 1;- next[key] = { ...(cur[key] as object), ...hexToRgb(String(value)), a };- break;+ return { ...(cur[key] as object), ...hexToRgb(String(value)), a };}+ default:+ return value;}-- world.set(entity, def, next as unknown as Parameters<WorldT['set']>[2]);- // Dual-write to the source-of-truth model (JSON-first L3). next[key] is the- // SceneData-format value for this key; writing just the key preserves the- // model component's other fields — including @uuid: asset refs and- // schema-extra fields the World can't hold. Every field edit AND its undo/redo- // route through here, so the model stays in sync for free.- SceneModel.setField(entity, compName, key, next[key]);}export const SceneCommands = {@@ -162,288 +131,199 @@ export const SceneCommands = {gesture = null;if (!g || g.touched.size === 0) return;const edits = [...g.touched.values()]- .map((e) => ({ ...e, after: SceneQuery.getFieldValue(e.entity, e.comp, e.key) }))- .filter((e) => e.after != null && !fieldEqual(e.before, e.after as InspectorFieldValue));+ .map((e) => ({ ...e, after: structuredClone(modelFieldValue(e.sourceId, e.comp, e.key)) }))+ .filter((e) => !valueEqual(e.before, e.after));if (edits.length === 0) return;EditorHistory.record(g.label,- () =>- edits.forEach((e) =>- applyFieldWrite(e.entity, e.comp, e.key, e.type, e.after as InspectorFieldValue),- ),- () => edits.forEach((e) => applyFieldWrite(e.entity, e.comp, e.key, e.type, e.before)),+ () => 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)),);},/**- * Write a single inspector field back to the engine (re-renders next frame).- * Always undoable: coalesced into an open gesture, else recorded as its own step.+ * Write a single inspector field to the model (the Reconciler re-projects it+ * to the World). Always undoable: coalesced into an open gesture, else its own step.*/setField(- entity: EntityId,+ sourceId: EntityId,compName: string,key: string,type: InspectorFieldType,value: InspectorFieldValue,): void {- const world = EngineHost.mutableWorld();- if (!world || !world.valid(entity) || !componentByName(compName)) return;+ const e = SceneModel.entityBySource(sourceId);+ if (!e) return;+ const cur = (e.components.find((c) => c.type === compName)?.data as Record<string, unknown>) ?? {};- const k = editKey(entity, compName, key);+ const k = editKey(sourceId, compName, key);const firstTouch = !gesture || !gesture.touched.has(k);- const before = firstTouch ? SceneQuery.getFieldValue(entity, compName, key) : null;+ const before = firstTouch ? structuredClone(cur[key]) : undefined;- applyFieldWrite(entity, compName, key, type, value);+ const after = toModelValue(cur, type, key, value);+ SceneModel.setField(sourceId, compName, key, after);if (gesture) {- if (firstTouch && before != null) {- gesture.touched.set(k, { entity, comp: compName, key, type, before });- }+ if (firstTouch) gesture.touched.set(k, { sourceId, comp: compName, key, before });return;}// No open gesture → this edit is its own undo step.- if (before == null) return;- const after = SceneQuery.getFieldValue(entity, compName, key);- if (after == null || fieldEqual(before, after)) return;+ if (valueEqual(before, after)) return;EditorHistory.record(`Edit ${prettyLabel(key)}`,- () => applyFieldWrite(entity, compName, key, type, after),- () => applyFieldWrite(entity, compName, key, type, before),+ () => SceneModel.setField(sourceId, compName, key, after),+ () => SceneModel.setField(sourceId, compName, key, before),);},/** Move an entity to a world position (keeps Z). Undoable like any field edit. */- setEntityXY(id: EntityId, x: number, y: number): void {- const world = EngineHost.mutableWorld();- if (!world || !world.valid(id) || !world.has(id, Transform)) return;- const z = world.get(id, Transform).position.z;- this.setField(id, 'Transform', 'position', 'vec3', [x, y, z]);+ 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;+ this.setField(sourceId, 'Transform', 'position', 'vec3', [x, y, pos?.z ?? 0]);},- // — Undoable entity lifecycle. Re-creating an entity changes its engine id,- // so closures track a stable EntityHandle and resolve it live. —-- // Each lifecycle op dual-writes the source-of-truth model (JSON-first L3),- // keyed by a stable source id so undo/redo (which re-create entities under new- // runtime ids) keep the model in sync. The model holds the lossless record;- // the World is the projection.+ // — Undoable entity lifecycle (model ops; the Reconciler re-spawns/-despawns) —- /** Spawn a new empty entity (with a Transform). Returns its id. */+ /** Spawn a new empty entity (with a Transform). Returns its source id. */addEntity(): EntityId | null {- const world = EngineHost.mutableWorld();- if (!world) return null;- const e = world.spawn('Entity');- world.insert(e, Transform, DEFAULT_TRANSFORM);- const cap = captureEntity(world, e);- const handle = EntityHandles.acquire(e);- const sourceId = SceneModel.addEntity(e, 'Entity', [- { type: 'Transform', data: structuredClone(DEFAULT_TRANSFORM) },+ if (!SceneModel.current) return null;+ const sourceId = SceneModel.addEntity('Entity', [+ { type: 'Transform', data: structuredClone(DEFAULT_TRANSFORM) } as SceneComponent,]);- let modelCap: ReturnType<typeof SceneModel.removeEntityBySource>;+ let record: SceneEntity | undefined;EditorHistory.record('Add Entity',() => {- if (!cap) return;- const nw = recreateEntity(world, cap);- EntityHandles.rebind(handle, nw);- if (modelCap) SceneModel.restoreEntity(modelCap, nw);+ if (record) SceneModel.restoreEntity(record);},() => {- despawnHandle(world, handle);- modelCap = SceneModel.removeEntityBySource(sourceId);+ record = SceneModel.removeEntityBySource(sourceId);},);- return e;+ return sourceId;},- /** Delete an entity (undo re-creates it under the same stable handle). */- deleteEntity(id: EntityId): void {- const world = EngineHost.mutableWorld();- if (!world || !world.valid(id)) return;- const cap = captureEntity(world, id);- if (!cap) return;- const handle = EntityHandles.acquire(id);- const sourceId = SceneModel.sourceFor(id);- // Capture the FULL model record (incl. unknown components) for lossless undo.- const modelCap = sourceId !== undefined ? SceneModel.removeEntityBySource(sourceId) : undefined;- world.despawn(id);- EntityHandles.rebind(handle, null);+ /** 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);+ if (!record) return;EditorHistory.record(- `Delete ${cap.name || 'Entity'}`,+ `Delete ${name}`,() => {- despawnHandle(world, handle);- if (sourceId !== undefined) SceneModel.removeEntityBySource(sourceId);+ record = SceneModel.removeEntityBySource(record!.id) ?? record;},() => {- const nw = recreateEntity(world, cap);- EntityHandles.rebind(handle, nw);- if (modelCap) SceneModel.restoreEntity(modelCap, nw);+ SceneModel.restoreEntity(record!);},);},- /** Duplicate an entity (offset slightly). Returns the new id. */- duplicateEntity(id: EntityId): EntityId | null {- const world = EngineHost.mutableWorld();- if (!world || !world.valid(id)) return null;- const cap = captureEntity(world, id);- if (!cap) return null;- const t = cap.comps.find((c) => c.name === 'Transform');- const pos = t && (t.data as { position?: { x: number; y: number } }).position;+ /** Duplicate an entity (offset slightly, as a sibling). Returns the new source id. */+ duplicateEntity(sourceId: EntityId): EntityId | null {+ const src = SceneModel.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.+ const components = structuredClone(src.components) as SceneComponent[];+ const pos = (components.find((c) => c.type === 'Transform')?.data as+ | { position?: { x: number; y: number } }+ | undefined)?.position;if (pos) {pos.x += 24;pos.y -= 24;}- const dup = recreateEntity(world, cap);- const handle = EntityHandles.acquire(dup);- // The model copy is from the SOURCE model entity (preserves unknown- // components/fields the World cap can't carry), with the same offset.- const srcId = SceneModel.sourceFor(id);- const srcEntity = srcId !== undefined- ? SceneModel.current?.entities.find((e) => e.id === srcId)- : undefined;- const dupComponents = srcEntity- ? (structuredClone(srcEntity.components) as typeof srcEntity.components)- : cap.comps.map((c) => ({- type: c.name,- data: structuredClone(c.data) as Record<string, unknown>,- }));- const mpos = (dupComponents.find((c) => c.type === 'Transform')?.data as- | { position?: { x: number; y: number } }- | undefined)?.position;- if (mpos) {- mpos.x += 24;- mpos.y -= 24;- }- const newSourceId = SceneModel.addEntity(dup, srcEntity?.name ?? cap.name, dupComponents);- let modelCap: ReturnType<typeof SceneModel.removeEntityBySource>;+ const newSourceId = SceneModel.addEntity(src.name, components, src.parent ?? null);+ let record: SceneEntity | undefined;EditorHistory.record(- `Duplicate ${cap.name || 'Entity'}`,+ `Duplicate ${src.name || 'Entity'}`,() => {- const nw = recreateEntity(world, cap);- EntityHandles.rebind(handle, nw);- if (modelCap) SceneModel.restoreEntity(modelCap, nw);+ if (record) SceneModel.restoreEntity(record);},() => {- despawnHandle(world, handle);- modelCap = SceneModel.removeEntityBySource(newSourceId);+ record = SceneModel.removeEntityBySource(newSourceId);},);- return dup;+ return newSourceId;},- /** Rename an entity via its Name component (undoable). */- renameEntity(id: EntityId, name: string): void {- const world = EngineHost.mutableWorld();- if (!world || !world.valid(id)) return;- const before = world.has(id, Name) ? world.get(id, Name).value : '';- if (before === name) return;- const handle = EntityHandles.acquire(id);- const setName = (value: string) => {- const live = EntityHandles.liveId(handle);- if (live != null && world.valid(live)) {- world.insert(live, Name, { value });- SceneModel.setName(live, value);- }- };- setName(name);- EditorHistory.record(`Rename ${name || 'Entity'}`, () => setName(name), () => setName(before));+ /** Rename an entity (undoable). */+ renameEntity(sourceId: EntityId, name: string): void {+ const before = SceneModel.entityBySource(sourceId)?.name;+ if (before === undefined || before === name) return;+ SceneModel.setName(sourceId, name);+ EditorHistory.record(+ `Rename ${name || 'Entity'}`,+ () => SceneModel.setName(sourceId, name),+ () => SceneModel.setName(sourceId, before),+ );},/**- * Re-parent an entity (drag-reparent): set/remove its Parent component on the- * World and mirror it in the source model. Undoable. Rejects self-parenting and- * cycles (parenting an entity under its own descendant); `parent: null` un-parents.+ * Re-parent an entity (drag-reparent). Undoable. Rejects self-parenting and+ * cycles (parenting under its own descendant); `parent: null` un-parents.*/- setParent(id: EntityId, parent: EntityId | null): void {- const world = EngineHost.mutableWorld();- if (!world || !world.valid(id)) return;- if (parent != null && (parent === id || !world.valid(parent) || isDescendant(world, parent, id))) return;-- const cur = world.has(id, Parent) ? (world.get(id, Parent) as unknown as { entity: EntityId }).entity : null;- const before = cur != null && cur !== id && world.valid(cur) ? cur : null;+ 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 (before === parent) return;-- const apply = (p: EntityId | null) => {- if (!world.valid(id)) return;- if (p != null && world.valid(p)) {- world.insert(id, Parent, { entity: p } as never);- SceneModel.setParent(id, p);- } else {- if (world.has(id, Parent)) world.remove(id, Parent);- SceneModel.setParent(id, null);- }- };- apply(parent);- EditorHistory.record('Reparent', () => apply(parent), () => apply(before));+ SceneModel.setParent(sourceId, parent);+ EditorHistory.record(+ 'Reparent',+ () => SceneModel.setParent(sourceId, parent),+ () => SceneModel.setParent(sourceId, before),+ );},- /** Add a component (with its registered defaults) to an entity. Undoable. */- addComponent(id: EntityId, compName: string): void {- const world = EngineHost.mutableWorld();- if (!world || !world.valid(id)) return;+ /** Add a component (with its registered/schema defaults) to an entity. Undoable. */+ addComponent(sourceId: EntityId, compName: string): void {+ const entity = SceneModel.entityBySource(sourceId);+ if (!entity || entity.components.some((c) => c.type === compName)) return;const def = componentByName(compName);- if (!def || world.has(id, def)) return;- const data = structuredClone((def as unknown as { _default: unknown })._default);- const apply = () => {- if (world.valid(id) && !world.has(id, def)) {- world.insert(id, def, data as never);- SceneModel.setComponent(id, compName, data);- }- };- const undo = () => {- if (world.valid(id) && world.has(id, def)) {- world.remove(id, def);- SceneModel.removeComponent(id, compName);- }- };- apply();- EditorHistory.record(`Add ${prettyLabel(compName)}`, apply, undo);+ // Builtins default from the engine registry; user/script components from the+ // schemas.json shape; an unknown-but-named component starts empty.+ const data = def+ ? structuredClone(componentDefaults(def))+ : structuredClone(userSchema(compName)?.default ?? {});+ SceneModel.setComponent(sourceId, compName, data);+ EditorHistory.record(+ `Add ${prettyLabel(compName)}`,+ () => SceneModel.setComponent(sourceId, compName, structuredClone(data)),+ () => SceneModel.removeComponent(sourceId, compName),+ );},/** Remove a component from an entity (Transform / Name are protected). Undoable. */- removeComponent(id: EntityId, compName: string): void {- const world = EngineHost.mutableWorld();- if (!world || !world.valid(id) || compName === 'Transform' || compName === 'Name') return;- const def = componentByName(compName);- if (!def || !world.has(id, def)) return;- const data = structuredClone(world.get(id, def));- const remove = () => {- if (world.valid(id) && world.has(id, def)) {- world.remove(id, def);- SceneModel.removeComponent(id, compName);- }- };- const restore = () => {- if (world.valid(id) && !world.has(id, def)) {- world.insert(id, def, data as never);- SceneModel.setComponent(id, compName, data);- }- };- remove();- EditorHistory.record(`Remove ${prettyLabel(compName)}`, remove, restore);+ removeComponent(sourceId: EntityId, compName: string): void {+ if (compName === 'Transform' || compName === 'Name') return;+ const comp = SceneModel.entityBySource(sourceId)?.components.find((c) => c.type === compName);+ if (!comp) return;+ const data = structuredClone(comp.data);+ SceneModel.removeComponent(sourceId, compName);+ EditorHistory.record(+ `Remove ${prettyLabel(compName)}`,+ () => SceneModel.removeComponent(sourceId, compName),+ () => SceneModel.setComponent(sourceId, compName, structuredClone(data)),+ );},/*** Toggle an entity's editor visibility by flipping the `enabled` field of each* of its components that has one (coalesced into one undo step). Lossless +- * persisted; SceneQuery.readSceneTree reflects it as the row's visibility.+ * persisted; SceneQuery reflects it as the row's visibility.*/- setEntityVisible(id: EntityId, visible: boolean): void {- const world = EngineHost.mutableWorld();- if (!world || !world.valid(id)) return;+ setEntityVisible(sourceId: EntityId, visible: boolean): void {+ const entity = SceneModel.entityBySource(sourceId);+ if (!entity) return;this.beginGesture(visible ? 'Show' : 'Hide');- for (const { name, def } of inspectableComponents(world, id)) {- const data = world.get(id, def) as unknown as Record<string, unknown>;- if ('enabled' in data) this.setField(id, name, 'enabled', 'bool', visible);+ for (const comp of entity.components) {+ const data = comp.data as Record<string, unknown>;+ if (data && typeof data === 'object' && 'enabled' in data) {+ this.setField(sourceId, comp.type, 'enabled', 'bool', visible);+ }}this.endGesture();},};--// Despawn the entity a handle currently points at (no-op if already deleted).-function despawnHandle(world: WorldT, handle: number): void {- const id = EntityHandles.liveId(handle);- if (id != null && world.valid(id)) world.despawn(id);- EntityHandles.rebind(handle, null);-}diff --git a/desktop/src/engine/SceneLoader.ts b/desktop/src/engine/SceneLoader.tsindex d293667b3..a271539ae 100644--- a/desktop/src/engine/SceneLoader.ts+++ b/desktop/src/engine/SceneLoader.ts@@ -1,5 +1,8 @@import { loadSceneData, Assets } from 'esengine';-import type { App } from 'esengine';+import type { App, SceneData } from 'esengine';+import { SceneModel } from './SceneModel';+import { Reconciler } from './Reconciler';+import { EditorHistory } from './EditorHistory';type SceneDataArg = Parameters<typeof loadSceneData>[1];@@ -37,13 +40,20 @@ export const SceneLoader = {/*** Fetch an `.esscene` (SceneData JSON), resolve its `@uuid:` texture refs to* live texture handles via the engine Assets system + a uuid→url manifest,- * and spawn it into the world. Returns the entity count. Refs without a- * manifest entry (or a failed load) blank to 0 (solid-color sprite).+ * spawn it into the world, and adopt the RAW scene as the editor model (the+ * source of truth). Returns the entity count. Refs without a manifest entry+ * (or a failed load) blank to 0 (solid-color sprite).+ *+ * Model-authoritative (REARCH_EDITOR_MODEL.md): the World is built directly+ * here (the bulk projection), and the raw scene — with `@uuid:` refs + any+ * components/fields the World drops — becomes the model. SceneModel.adopt+ * emits `reset`; the Reconciler ignores it (the World is already built), while+ * SceneStore bumps and panels re-read from the model.*/async loadInto(app: App, sceneUrl: string, manifestUrl?: string): Promise<number> {const res = await fetch(sceneUrl);if (!res.ok) throw new Error(`scene fetch failed: ${res.status} ${sceneUrl}`);- const raw = await res.json();+ const raw = (await res.json()) as SceneData;const uuidToHandle = await loadTextures(app, raw, manifestUrl);@@ -51,7 +61,11 @@ export const SceneLoader = {s.startsWith(UUID_PREFIX) ? (uuidToHandle.get(s.slice(UUID_PREFIX.length)) ?? 0) : s,) as SceneDataArg;- return loadSceneData(app.world, sceneData).size;+ const map = loadSceneData(app.world, sceneData);+ EditorHistory.clear();+ Reconciler.setAssetResolver((uuid) => uuidToHandle.get(uuid) ?? 0);+ SceneModel.adopt(raw, map as Map<number, number>);+ return map.size;},};diff --git a/desktop/src/engine/SceneModel.ts b/desktop/src/engine/SceneModel.tsindex 6f1f8a744..bb3f819a9 100644--- a/desktop/src/engine/SceneModel.ts+++ b/desktop/src/engine/SceneModel.ts@@ -5,31 +5,72 @@ type SceneEntity = SceneData['entities'][number];type SceneComponent = SceneEntity['components'][number];/**- * The editor's source-of-truth scene data model — JSON-first (REARCH_SERIALIZATION.md, L1).+ * A fine-grained change to the model. The {@link Reconciler} projects each event+ * to the World; SceneStore turns them into reactivity bumps; selection+ * self-heals on `entityRemoved`. `reset` means the whole model was replaced+ * (load/clear) — consumers rebuild from scratch.+ */+export type ModelEvent =+ | { kind: 'reset' }+ | { kind: 'entityAdded'; sourceId: number }+ | { kind: 'entityRemoved'; sourceId: number }+ | { kind: 'componentAdded'; sourceId: number; type: string }+ | { kind: 'componentChanged'; sourceId: number; type: string }+ | { kind: 'componentRemoved'; sourceId: number; type: string }+ | { kind: 'parentChanged'; sourceId: number }+ | { kind: 'nameChanged'; sourceId: number };++type Listener = (ev: ModelEvent) => void;++/**+ * The editor's single source of truth — the JSON-first scene document+ * (REARCH_EDITOR_MODEL.md). Holds the COMPLETE SceneData: components/fields the+ * live World drops on projection (unknown component types, schema-extra fields,+ * `visible:false` entities) and portable `@uuid:` asset refs, all verbatim.*- * Holds the COMPLETE loaded SceneData: components/fields/entities the live World- * drops on projection (unknown component types, schema-extra fields,- * `visible:false` entities) and portable `@uuid:` asset refs, all preserved here- * verbatim. The World is a lossy render projection of this model; lossless save- * serializes THIS, not the World.+ * Model-authoritative data flow: commands mutate THIS (by stable **source id**),+ * the model emits a change event, and the {@link Reconciler} projects it to the+ * World. The World is a pure derived projection — it never writes back here, so+ * the two cannot diverge. Save serializes THIS, not the World (lossless).*- * L1 (this step): adopt + retain the model and the model⇄runtime-entity- * correspondence on load. L3 will route edits through here; L4 will save from- * here (and retire the editor's `lossy` refuse-to-save guard).+ * The source↔runtime entity map lives here (so the Viewport can resolve a+ * selected source id to its runtime World entity for picking/gizmo geometry),+ * 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 {private data: SceneData | null = null;- /** runtime World entity → this scene's source entity id. */+ /** runtime World entity → source entity id (Reconciler-maintained). */private readonly runtimeToSource = new Map<EntityId, number>();- /** source entity id → runtime World entity (absent for visible:false / unspawned). */+ /** source entity id → runtime World entity (absent for unknown/unspawned). */private readonly sourceToRuntime = new Map<number, EntityId>();- /** Allocator for source ids of entities created after load (added/duplicated). */+ /** Allocator for source ids of entities created after load (add/duplicate). */private nextSourceId = 1;+ private readonly listeners = new Set<Listener>();++ // ── Change bus ───────────────────────────────────────────────────────────++ /** Subscribe to model changes. Returns an unsubscribe fn. */+ subscribe(fn: Listener): () => void {+ this.listeners.add(fn);+ return () => {+ this.listeners.delete(fn);+ };+ }++ private emit(ev: ModelEvent): void {+ for (const l of this.listeners) l(ev);+ }++ // ── Lifecycle ────────────────────────────────────────────────────────────/**- * Adopt a freshly-loaded scene as the editor truth.+ * Adopt a freshly-loaded scene as the editor truth. The World is expected to+ * already be built (the Reconciler's bulk path calls resetWorldTo, then this),+ * so adopt only records the model + the source↔runtime map and announces a+ * wholesale `reset` for reactivity / selection.* @param loaded the complete SceneData (with `@uuid:` refs + unknown components)- * @param entityMap source-id → runtime entity, as returned by resetWorldTo / loadSceneData+ * @param entityMap source-id → runtime entity, as returned by resetWorldTo*/adopt(loaded: SceneData, entityMap: Map<number, EntityId>): void {this.data = loaded;@@ -42,6 +83,7 @@ class SceneModelImpl {this.sourceToRuntime.set(sourceId, runtime);this.runtimeToSource.set(runtime, sourceId);}+ this.emit({ kind: 'reset' });}clear(): void {@@ -49,22 +91,22 @@ class SceneModelImpl {this.runtimeToSource.clear();this.sourceToRuntime.clear();this.nextSourceId = 1;+ this.emit({ kind: 'reset' });}- // ── Mutations (JSON-first L3) ────────────────────────────────────────────- // SceneCommands dual-writes here alongside the World so the model stays the- // lossless truth. Field edits address the live runtime entity; entity- // lifecycle addresses the stable source id (survives undo/redo recreates,- // where the runtime id changes). All are no-ops if no scene is loaded.+ // ── Mutations (the ONLY writers; each emits a change event) ───────────────+ // Keyed by stable source id (survives undo/redo recreates, where the runtime+ // id changes). All are no-ops if no scene is loaded. Values are SceneData-+ // format — the command layer converts inspector controls to this shape, the+ // reconciler projects this shape to the World./**- * Update one field of a component on a runtime entity's source record.- * Preserves every other field — including `@uuid:` asset refs and schema-extra- * fields the World can't hold — so the model stays lossless. Mirrors the- * per-key value SceneCommands writes to the World.+ * Update one field of a component on a source entity. Preserves every other+ * field — including `@uuid:` asset refs and schema-extra fields the World+ * can't hold — so the model stays lossless. Creates the component if absent.*/- setField(runtime: EntityId, compType: string, key: string, value: unknown): void {- const e = this.sourceEntity(runtime);+ setField(sourceId: number, compType: string, key: string, value: unknown): void {+ const e = this.entityBySource(sourceId);if (!e) return;let comp = e.components.find((c) => c.type === compType);if (!comp) {@@ -72,102 +114,160 @@ class SceneModelImpl {e.components.push(comp);}(comp.data as Record<string, unknown>)[key] = value;+ this.emit({ kind: 'componentChanged', sourceId, type: compType });+ }++ /**+ * Add or replace a whole component's data on a source entity. Adding a new+ * component changes the entity's component SET (structural — affects the tree's+ * kind/add-menu), so it emits `componentAdded`; replacing existing data is a+ * value change (`componentChanged`).+ */+ setComponent(sourceId: number, compType: string, data: unknown): void {+ const e = this.entityBySource(sourceId);+ if (!e) return;+ const existing = e.components.find((c) => c.type === compType);+ if (existing) {+ existing.data = data as Record<string, unknown>;+ this.emit({ kind: 'componentChanged', sourceId, type: compType });+ } else {+ e.components.push({ type: compType, data: data as Record<string, unknown> } as SceneComponent);+ this.emit({ kind: 'componentAdded', sourceId, type: compType });+ }}- /** Set a runtime entity's name (stored top-level in SceneData, not as a component). */- setName(runtime: EntityId, name: string): void {- const e = this.sourceEntity(runtime);- if (e) e.name = name;+ /** Remove a component from a source entity. */+ removeComponent(sourceId: number, compType: string): void {+ const e = this.entityBySource(sourceId);+ if (!e) return;+ e.components = e.components.filter((c) => c.type !== compType);+ this.emit({ kind: 'componentRemoved', sourceId, type: compType });}- /** Add a new source entity (for a freshly-spawned runtime entity). Returns its source id. */- addEntity(runtime: EntityId, name: string, components: SceneComponent[]): number {+ /** Set a source entity's name (stored top-level in SceneData, not as a component). */+ setName(sourceId: number, name: string): void {+ const e = this.entityBySource(sourceId);+ if (!e) return;+ e.name = name;+ this.emit({ kind: 'nameChanged', sourceId });+ }++ /**+ * Add a new source entity. Returns its source id. The Reconciler spawns ++ * binds a runtime entity in response to the emitted `entityAdded`.+ */+ addEntity(name: string, components: SceneComponent[], parent: number | null = null): number {const id = this.nextSourceId++;- if (this.data) this.data.entities.push({ id, name, parent: null, children: [], components });- this.bindRuntime(id, runtime);+ if (this.data) {+ this.data.entities.push({ id, name, parent, children: [], components });+ if (parent != null) {+ const p = this.data.entities.find((e) => e.id === parent);+ if (p && !p.children.includes(id)) p.children.push(id);+ }+ }+ this.emit({ kind: 'entityAdded', sourceId: id });return id;}- /** Remove + return a source entity by id (kept by undo closures to restore later). */+ /**+ * Remove + return a source entity by id (kept by undo closures to restore+ * later). Scrubs the child id from its parent's `children[]` so the saved+ * hierarchy stays consistent. The source↔runtime map is left to the Reconciler+ * to unbind on the emitted `entityRemoved`.+ */removeEntityBySource(sourceId: number): SceneEntity | undefined {- const rt = this.sourceToRuntime.get(sourceId);- if (rt !== undefined) this.runtimeToSource.delete(rt);- this.sourceToRuntime.delete(sourceId);if (!this.data) return undefined;const idx = this.data.entities.findIndex((e) => e.id === sourceId);- return idx >= 0 ? this.data.entities.splice(idx, 1)[0] : undefined;- }-- /** Re-insert a previously-removed source entity, bound to a (re-created) runtime entity. */- restoreEntity(entity: SceneEntity, runtime: EntityId): void {- if (this.data) this.data.entities.push(entity);- this.bindRuntime(entity.id, runtime);+ if (idx < 0) return undefined;+ const [removed] = this.data.entities.splice(idx, 1);+ if (removed.parent != null) {+ const p = this.data.entities.find((e) => e.id === removed.parent);+ if (p) p.children = p.children.filter((c) => c !== sourceId);+ }+ this.emit({ kind: 'entityRemoved', sourceId });+ return removed;}- /** Point a source id at its current runtime entity (call after a recreate). */- bindRuntime(sourceId: number, runtime: EntityId): void {- this.sourceToRuntime.set(sourceId, runtime);- this.runtimeToSource.set(runtime, sourceId);+ /**+ * Re-insert a previously-removed source entity (undo of delete). Restores its+ * link in the parent's `children[]`. The Reconciler respawns + binds a fresh+ * runtime entity on the emitted `entityAdded`.+ */+ restoreEntity(entity: SceneEntity): void {+ if (!this.data) return;+ this.data.entities.push(entity);+ if (entity.parent != null) {+ const p = this.data.entities.find((e) => e.id === entity.parent);+ if (p && !p.children.includes(entity.id)) p.children.push(entity.id);+ }+ this.emit({ kind: 'entityAdded', sourceId: entity.id });}/**- * Re-parent a runtime entity in the source model (mirrors the World's Parent- * component). Keeps both the child's `parent` link and the old/new parents'- * `children` arrays consistent so the saved scene's hierarchy stays correct.+ * Re-parent a source entity. Keeps both the child's `parent` link and the+ * old/new parents' `children[]` consistent so the saved hierarchy is correct.+ * `parent: null` un-parents to the scene root.*/- setParent(runtimeChild: EntityId, runtimeParent: EntityId | null): void {- const child = this.sourceEntity(runtimeChild);+ setParent(sourceId: number, parent: number | null): void {+ const child = this.entityBySource(sourceId);if (!child || !this.data) return;- const newParentId = runtimeParent != null ? this.sourceFor(runtimeParent) ?? null : null;- if (child.parent === newParentId) return;+ if (child.parent === parent) return;if (child.parent != null) {const old = this.data.entities.find((e) => e.id === child.parent);- if (old) old.children = old.children.filter((c) => c !== child.id);+ if (old) old.children = old.children.filter((c) => c !== sourceId);}- child.parent = newParentId;- if (newParentId != null) {- const np = this.data.entities.find((e) => e.id === newParentId);- if (np && !np.children.includes(child.id)) np.children.push(child.id);+ child.parent = parent;+ if (parent != null) {+ const np = this.data.entities.find((e) => e.id === parent);+ if (np && !np.children.includes(sourceId)) np.children.push(sourceId);}+ this.emit({ kind: 'parentChanged', sourceId });}- /** Remove a component from a runtime entity's source record. */- removeComponent(runtime: EntityId, compType: string): void {- const e = this.sourceEntity(runtime);- if (e) e.components = e.components.filter((c) => c.type !== compType);+ // ── Source↔runtime map (Reconciler-only writers) ─────────────────────────++ /** Bind a source id to its current runtime entity (Reconciler, on spawn). */+ bindRuntime(sourceId: number, runtime: EntityId): void {+ this.sourceToRuntime.set(sourceId, runtime);+ this.runtimeToSource.set(runtime, sourceId);}- /** Add or replace a whole component's data on a runtime entity's source record. */- setComponent(runtime: EntityId, compType: string, data: unknown): void {- const e = this.sourceEntity(runtime);- if (!e) return;- const existing = e.components.find((c) => c.type === compType);- if (existing) existing.data = data as Record<string, unknown>;- else e.components.push({ type: compType, data: data as Record<string, unknown> } as SceneComponent);+ /** Drop a source id's runtime binding (Reconciler, on despawn). */+ unbindRuntime(sourceId: number): void {+ const rt = this.sourceToRuntime.get(sourceId);+ if (rt !== undefined) this.runtimeToSource.delete(rt);+ this.sourceToRuntime.delete(sourceId);}+ // ── Reads ────────────────────────────────────────────────────────────────+/** The current scene truth, or null if none loaded. */get current(): SceneData | null {return this.data;}- /** A deep clone of the scene truth, for lossless save (JSON-first L4). */+ /** A deep clone of the scene truth, for lossless save. */serialize(): SceneData | null {return this.data ? (JSON.parse(JSON.stringify(this.data)) as SceneData) : null;}+ /** The source entity record for a source id. */+ entityBySource(sourceId: number): SceneEntity | undefined {+ return this.data?.entities.find((e) => e.id === sourceId);+ }+/** The source entity record backing a runtime World entity, if tracked. */sourceEntity(runtime: EntityId): SceneEntity | undefined {const sourceId = this.runtimeToSource.get(runtime);- if (sourceId === undefined || !this.data) return undefined;- return this.data.entities.find((e) => e.id === sourceId);+ return sourceId === undefined ? undefined : this.entityBySource(sourceId);}/** Runtime World entity for a source id (if currently spawned). */runtimeFor(sourceId: number): EntityId | undefined {return this.sourceToRuntime.get(sourceId);}+/** Source id for a runtime World entity (if tracked). */sourceFor(runtime: EntityId): number | undefined {return this.runtimeToSource.get(runtime);diff --git a/desktop/src/engine/SceneQuery.ts b/desktop/src/engine/SceneQuery.tsindex bca6dc87e..8b112f5f8 100644--- a/desktop/src/engine/SceneQuery.ts+++ b/desktop/src/engine/SceneQuery.ts@@ -1,104 +1,84 @@-import { Parent } from 'esengine';import type { SceneNode, NodeKind, EntityId, InspectorComponent, InspectorFieldValue } from '@/types';-import { EngineHost } from './EngineHost';+import { SceneStore } from './SceneStore';+import { SceneModel } from './SceneModel';import {- inspectableComponents,- componentFields,+ inspectorFields,inferField,- kindOf,- nameOf,- componentByName,- type ReadonlyWorldT,+ isColorKey,+ modelInspectableComponents,+ modelKindOf,+ modelNameOf,+ modelIsVisible,} from './schema';-// An entity reads as hidden if any of its components is explicitly disabled-// (`enabled: false`) — the editor's visibility toggle flips those.-function isVisible(world: ReadonlyWorldT, id: EntityId): boolean {- for (const { def } of inspectableComponents(world, id)) {- const data = world.get(id, def) as unknown as Record<string, unknown>;- if ('enabled' in data && data.enabled === false) return false;- }- return true;-}--// Read-only reflection of the live engine World into editor view-models.+/**+ * Read-only projection of the editor's source-of-truth model into view-models+ * (REARCH_EDITOR_MODEL.md §3.4). The outliner tree, inspector, and field reads+ * all come from the MODEL — the single truth — never the World. The Viewport+ * 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**.+ */export const SceneQuery = {- /** Monotonic counter; bump means the entity set / structure changed. */+ /** Monotonic counter; bump means the scene structure changed (for observers). */worldVersion(): number {- return EngineHost.world?.getWorldVersion() ?? -1;+ return SceneStore.getStructureRevision();},- /** Build the outliner tree from the live World, nesting via the Parent component. */+ /** Build the outliner tree from the model, nesting via parent/children links. */readSceneTree(): SceneNode[] {- const world = EngineHost.world;- if (!world) return [];-- const ids = world.getAllEntities();- const idSet = new Set<EntityId>(ids);- const childrenOf = new Map<EntityId, EntityId[]>();- const roots: EntityId[] = [];+ const data = SceneModel.current;+ if (!data) return [];+ const byId = new Map(data.entities.map((e) => [e.id, e]));- for (const e of ids) {- let parent: EntityId | null = null;- if (world.has(e, Parent)) {- const p = world.get(e, Parent).entity;- if (p !== e && idSet.has(p)) parent = p;- }- if (parent === null) {- roots.push(e);- } else {- const arr = childrenOf.get(parent);- if (arr) arr.push(e);- else childrenOf.set(parent, [e]);- }- }-- const build = (e: EntityId): SceneNode => {- const kind = kindOf(world, e);- const kids = childrenOf.get(e);+ const build = (e: (typeof data.entities)[number]): SceneNode => {+ const kind = modelKindOf(e);+ const kids = e.children+ .map((cid) => byId.get(cid))+ .filter((c): c is typeof e => c != null)+ .map(build);return {- id: e,- name: nameOf(world, e, kind),+ id: e.id,+ name: modelNameOf(e, kind),kind,- visible: isVisible(world, e),+ visible: modelIsVisible(e),locked: false,- children: kids?.map(build),+ children: kids.length ? kids : undefined,};};- return roots.map(build);+ // 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);},- /** Inspect a single live entity (name, kind, which components it carries). */+ /** Inspect a single source entity (name, kind, which components it carries). */readEntity(id: EntityId): { name: string; kind: NodeKind; components: string[] } | null {- const world = EngineHost.world;- if (!world || !world.valid(id)) return null;- const kind = kindOf(world, id);- const components = inspectableComponents(world, id).map((c) => c.label);- return { name: nameOf(world, id, kind), kind, components };+ const e = SceneModel.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 an entity — components from the engine registry. */- readInspector(entity: EntityId): InspectorComponent[] {- const world = EngineHost.world;- if (!world || !world.valid(entity)) return [];-+ /** Full editable inspector model for a source entity — fields resolved per component. */+ readInspector(id: EntityId): InspectorComponent[] {+ const e = SceneModel.entityBySource(id);+ if (!e) return [];const out: InspectorComponent[] = [];- for (const { def, label } of inspectableComponents(world, entity)) {- const data = world.get(entity, def) as unknown as Record<string, unknown>;- out.push({ name: def._name, label, fields: componentFields(def, data) });+ for (const { name, label } of modelInspectableComponents(e)) {+ const data = (e.components.find((c) => c.type === name)?.data as Record<string, unknown>) ?? {};+ out.push({ name, label, fields: inspectorFields(name, data) });}return out;},/** Read one inspector field's current value (for undo before/after capture). */- getFieldValue(entity: EntityId, compName: string, key: string): InspectorFieldValue | null {- const world = EngineHost.world;- if (!world || !world.valid(entity)) return null;- const def = componentByName(compName);- if (!def || !world.has(entity, def)) return null;- const data = world.get(entity, def) as unknown as Record<string, unknown>;- const f = inferField(key, data[key], new Set<string>(def.colorKeys).has(key));+ getFieldValue(id: EntityId, compName: string, key: string): InspectorFieldValue | null {+ const comp = SceneModel.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;},};diff --git a/desktop/src/engine/SceneStore.ts b/desktop/src/engine/SceneStore.tsindex 73c1e6e48..6260acbe9 100644--- a/desktop/src/engine/SceneStore.ts+++ b/desktop/src/engine/SceneStore.ts@@ -1,18 +1,20 @@import { createStore } from 'zustand/vanilla';-import { getDefaultContext } from 'esengine';-import type { EditorBridge } from 'esengine';+import { SceneModel, type ModelEvent } from './SceneModel';/**- * Reactive mirror of the engine scene.+ * Reactive mirror of the editor scene — the model-change bus.*- * Registers an {@link EditorBridge} so the engine pushes every mutation- * (spawn/despawn/parent/component add/remove/change) instead of the editor- * polling. Panels subscribe via `useSyncExternalStore` and re-read through- * `EngineHost`; this store only carries revision counters that say *what kind*- * of thing changed:+ * Model-authoritative data flow (REARCH_EDITOR_MODEL.md): the editor reacts to+ * **model** events, not engine-pushed World mutations. This subscribes to the+ * SceneModel and turns each change into a revision bump; panels subscribe via+ * `useSyncExternalStore` and re-read through SceneQuery (which reads the model).*- * - `structureRevision` bumps on entity/parent/component add+remove (tree shape)- * - `revision` bumps on any change, incl. component-data edits (inspector values)+ * - `structureRevision` bumps when the tree shape / names / kinds change+ * (entity add+remove, parent, component add+remove, rename, reset)+ * - `revision` bumps on any change, incl. component-data field edits+ *+ * (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 {private installed = false;@@ -20,34 +22,12 @@ class SceneStoreImpl {revision: 1,structureRevision: 1,}));- private readonly despawnListeners = new Set<(id: number) => void>();- /** Register the bridge on the engine's default context. Idempotent. */+ /** Subscribe to the model as the change source. Idempotent. */install() {if (this.installed) return;this.installed = true;- const bridge: EditorBridge = {- registerComponent: () => {},- onEntitySpawned: () => this.bump(true),- onEntityDespawned: (e) => {- // Carry the dead id so consumers (SelectionStore) can drop references- // precisely. Fires BEFORE the entity is fully removed, so re-validating- // by world.valid() here would race — dropping by id is exact.- this.despawnListeners.forEach((l) => l(e as unknown as number));- this.bump(true);- },- onComponentAdded: () => this.bump(true),- onComponentRemoved: () => this.bump(true),- onParentChanged: () => this.bump(true),- onComponentChanged: () => this.bump(false),- };- getDefaultContext().editorBridge = bridge;- }-- /** Subscribe to entity despawns by id (the self-healing hook for selection). */- onEntityDespawn(fn: (id: number) => void): () => void {- this.despawnListeners.add(fn);- return () => this.despawnListeners.delete(fn);+ SceneModel.subscribe((ev) => this.bump(isStructural(ev)));}private bump(structural: boolean) {@@ -62,4 +42,9 @@ class SceneStoreImpl {getStructureRevision = (): number => this.store.getState().structureRevision;}+/** A change affects the tree (shape / name / kind / add-menu), not just a field value. */+function isStructural(ev: ModelEvent): boolean {+ return ev.kind !== 'componentChanged';+}+export const SceneStore = new SceneStoreImpl();diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.tsindex 2a52ebc35..06c96eada 100644--- a/desktop/src/engine/schema.ts+++ b/desktop/src/engine/schema.ts@@ -1,20 +1,8 @@-import {- getAllRegisteredComponents,- getUserComponents,- getComponent,- Sprite,- Camera,- Name,- Children,- ShapeRenderer,- Canvas,- BitmapText,- SpineAnimation,- TilemapLayer,- ParticleEmitter,-} from 'esengine';-import type { App } from 'esengine';-import type { NodeKind, EntityId, InspectorField } from '@/types';+import { getAllRegisteredComponents, getUserComponents, getComponent } from 'esengine';+import type { App, SceneData } from 'esengine';+import type { NodeKind, InspectorField } from '@/types';++type SceneEntityLike = SceneData['entities'][number];// Shared engine-schema utilities. The set of components and their data shape are// owned by the ENGINE: `getComponentRegistry()` enumerates every registered@@ -56,24 +44,9 @@ export function componentByName(name: string): AnyComp | undefined {return registryDef(name);}-/** Every editable component the entity currently carries, in display order. */-export function inspectableComponents(- world: ReadonlyWorldT,- entity: EntityId,-): Array<{ name: string; def: AnyComp; label: string }> {- const out: Array<{ name: string; def: AnyComp; label: string }> = [];- for (const [name, rawDef] of getAllRegisteredComponents()) {- if (HIDDEN_COMPONENTS.has(name)) continue;- const def = rawDef as unknown as AnyComp;- if (!world.has(entity, def)) continue;- out.push({ name, def, label: prettyLabel(name) });- }- out.sort((a, b) => {- const ai = ORDER.indexOf(a.name);- const bi = ORDER.indexOf(b.name);- return (ai === -1 ? ORDER.length : ai) - (bi === -1 ? ORDER.length : bi);- });- return out;+/** A component's registered default field values (the `_default` describing its shape). */+export function componentDefaults(def: AnyComp): Record<string, unknown> {+ return (def as unknown as { _default: Record<string, unknown> })._default;}// Add-Component picker categories, in display order (UE5 groups the picker by@@ -123,38 +96,6 @@ export function componentCategory(name: string, isUser = false): string {return 'Other';}-/**- * The Add-Component candidates as picker entries (name + label + category),- * resolving user-vs-builtin once via the engine registry. One place owns the- * category assignment so the panel stays presentation-only.- */-export function addableComponentEntries(- world: ReadonlyWorldT,- entity: EntityId,-): Array<{ name: string; label: string; category: string }> {- const userNames = new Set(getUserComponents().keys());- return addableComponents(world, entity).map((c) => ({- name: c.name,- label: c.label,- category: componentCategory(c.name, userNames.has(c.name)),- }));-}--/** Registered components NOT yet on an entity — the "Add Component" candidates. */-export function addableComponents(- world: ReadonlyWorldT,- entity: EntityId,-): Array<{ name: string; def: AnyComp; label: string }> {- const out: Array<{ name: string; def: AnyComp; label: string }> = [];- for (const [name, rawDef] of getAllRegisteredComponents()) {- if (HIDDEN_COMPONENTS.has(name) || name === 'Transform') continue;- const def = rawDef as unknown as AnyComp;- if (world.has(entity, def)) continue;- out.push({ name, def, label: prettyLabel(name) });- }- return out.sort((a, b) => a.label.localeCompare(b.label));-}-/** The editable fields of one component (its live data introspected by shape). */export function componentFields(def: AnyComp, data: Record<string, unknown>): InspectorField[] {const colorKeys = new Set<string>(def.colorKeys);@@ -219,23 +160,126 @@ export function inferField(key: string, v: unknown, isColor: boolean): Inspectorreturn null; // unknown shape — not editable here}-// — Outliner kind/name (presentation; uses specific defs for icon mapping) —+// — User-component schemas (the `schemas.json` consumer; REARCH_EDITOR_MODEL.md) —+//+// Project/script components never run in the editor realm, so they're absent+// from the engine registry. Their field shapes come from `.esengine/cache/+// schemas.json` (built by electron/extractSchemas.ts). The inspector resolves a+// component's fields from the engine registry (builtins) or, failing that, this+// schema source — and, failing both, infers controls from the stored data+// values themselves so even schema-less components stay editable.++/** A project component's field schema, as serialized in `schemas.json`. */+export interface UserComponentSchema {+ name: string;+ isTag: boolean;+ default: Record<string, unknown>;+ colorKeys: string[];+}++const userSchemas = new Map<string, UserComponentSchema>();++/** Replace the user-component schema source (called on project open). */+export function setUserSchemas(schemas: UserComponentSchema[]): void {+ userSchemas.clear();+ for (const s of schemas) userSchemas.set(s.name, s);+}++/** The user schema for a component name, if any. */+export function userSchema(name: string): UserComponentSchema | undefined {+ return userSchemas.get(name);+}++/** Whether a component field renders as a color (registry colorKeys, then schema). */+export function isColorKey(compType: string, key: string): boolean {+ const def = componentByName(compType);+ if (def) return new Set<string>(def.colorKeys).has(key);+ return new Set(userSchema(compType)?.colorKeys ?? []).has(key);+}++/**+ * The editable fields of a component from the MODEL's stored data, resolving the+ * field shape from (in order): the engine registry, the user schema, or — as a+ * best-effort fallback — the data values themselves. `DERIVED_FIELDS` are skipped.+ */+export function inspectorFields(compType: string, data: Record<string, unknown>): InspectorField[] {+ const def = componentByName(compType);+ if (def) return componentFields(def, data);++ const schema = userSchema(compType);+ const colorKeys = new Set(schema?.colorKeys ?? []);+ const keys = schema ? Object.keys(schema.default) : Object.keys(data);+ const fields: InspectorField[] = [];+ for (const key of keys) {+ if (DERIVED_FIELDS.has(key)) continue;+ const v = key in data ? data[key] : schema?.default[key];+ const f = inferField(key, v, colorKeys.has(key));+ if (f) fields.push(f);+ }+ return fields;+}++// — Model-based reflection (the editor reads the model, not the World) —++const orderIndex = (name: string): number => {+ const i = ORDER.indexOf(name);+ return i === -1 ? ORDER.length : i;+};++/** A source entity's editable component types (name + label), in display order. */+export function modelInspectableComponents(+ entity: SceneEntityLike,+): Array<{ name: string; label: string }> {+ return entity.components+ .filter((c) => !HIDDEN_COMPONENTS.has(c.type))+ .map((c) => ({ name: c.type, label: prettyLabel(c.type) }))+ .sort((a, b) => orderIndex(a.name) - orderIndex(b.name));+}++/**+ * Add-Component candidates for a source entity: registered components not yet on+ * it, plus user (schemas.json) components absent from both the entity and the+ * engine registry. Transform / structural components are excluded.+ */+export function modelAddableComponentEntries(+ entity: SceneEntityLike,+): Array<{ name: string; label: string; category: string }> {+ const present = new Set(entity.components.map((c) => c.type));+ const userNames = new Set(getUserComponents().keys());+ const out: Array<{ name: string; label: string; category: string }> = [];+ for (const [name] of getAllRegisteredComponents()) {+ if (HIDDEN_COMPONENTS.has(name) || name === 'Transform' || present.has(name)) continue;+ out.push({ name, label: prettyLabel(name), category: componentCategory(name, userNames.has(name)) });+ }+ for (const name of userSchemas.keys()) {+ if (present.has(name) || componentByName(name)) continue;+ out.push({ name, label: prettyLabel(name), category: 'Scripts' });+ }+ return out.sort((a, b) => a.label.localeCompare(b.label));+}-export function kindOf(world: ReadonlyWorldT, e: EntityId): NodeKind {- if (world.has(e, Camera)) return 'camera';- if (world.has(e, SpineAnimation)) return 'spine';- if (world.has(e, Canvas) || world.has(e, BitmapText)) return 'ui';- if (world.has(e, Sprite) || world.has(e, ShapeRenderer) || world.has(e, TilemapLayer))- return 'sprite';- if (world.has(e, ParticleEmitter)) return 'sprite';- if (world.has(e, Children)) return 'group';+/** Outliner icon kind for a source entity (which components it carries). */+export function modelKindOf(entity: SceneEntityLike): NodeKind {+ const types = new Set(entity.components.map((c) => c.type));+ if (types.has('Camera')) return 'camera';+ if (types.has('SpineAnimation')) return 'spine';+ if (types.has('Canvas') || types.has('BitmapText')) return 'ui';+ if (types.has('Sprite') || types.has('ShapeRenderer') || types.has('TilemapLayer')) return 'sprite';+ if (types.has('ParticleEmitter')) return 'sprite';+ if (entity.children.length > 0) return 'group';return 'empty';}-export function nameOf(world: ReadonlyWorldT, e: EntityId, kind: NodeKind): string {- if (world.has(e, Name)) {- const v = world.get(e, Name).value;- if (v) return v;+/** Display name for a source entity (its name, or a kind-derived fallback). */+export function modelNameOf(entity: SceneEntityLike, kind: NodeKind): string {+ return entity.name || `${cap(kind)} ${entity.id}`;+}++/** A source entity reads as hidden if any component is explicitly disabled. */+export function modelIsVisible(entity: SceneEntityLike): boolean {+ for (const c of entity.components) {+ const d = c.data as Record<string, unknown>;+ if (d && typeof d === 'object' && 'enabled' in d && d.enabled === false) return false;}- return `${cap(kind)} ${e}`;+ return true;}diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex 3ea32c78b..b90ffb9de 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -4,8 +4,9 @@ import { useSelection } from '@/store/selectionStore';import { EngineHost } from '@/engine/EngineHost';import { SceneStore } from '@/engine/SceneStore';import { SceneQuery } from '@/engine/SceneQuery';+import { SceneModel } from '@/engine/SceneModel';import { SceneCommands } from '@/engine/SceneCommands';-import { addableComponentEntries } from '@/engine/schema';+import { modelAddableComponentEntries } from '@/engine/schema';import { ContextMenu } from '@/components/Menu';import { AddComponentMenu } from '@/components/AddComponentMenu';import type { InspectorComponent, InspectorField, EntityId } from '@/types';@@ -345,7 +346,7 @@ export function Details() {);}- const world = EngineHost.world;+ const modelEntity = SceneModel.entityBySource(selectedId);return (<div className="panel">@@ -412,11 +413,11 @@ export function Details() {onClose={() => setCompMenu(null)}/>)}- {addMenu && world && (+ {addMenu && modelEntity && (<AddComponentMenux={addMenu.x}y={addMenu.y}- entries={addableComponentEntries(world, selectedId)}+ entries={modelAddableComponentEntries(modelEntity)}onAdd={(name) => SceneCommands.addComponent(selectedId, name)}onClose={() => setAddMenu(null)}/>diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsxindex e8329094a..3eeb0ef12 100644--- a/desktop/src/panels/Viewport.tsx+++ b/desktop/src/panels/Viewport.tsx@@ -11,6 +11,7 @@ import { EngineHost } from '@/engine/EngineHost';import { ViewportController } from '@/engine/ViewportController';import { SceneCommands } from '@/engine/SceneCommands';import { SceneQuery } from '@/engine/SceneQuery';+import { SceneModel } from '@/engine/SceneModel';import { SceneStore } from '@/engine/SceneStore';import { StatsStore } from '@/engine/StatsStore';import type { ToolMode } from '@/types';@@ -152,11 +153,14 @@ export function Viewport() {const g = gizmoRef.current;const sel = selectionRef.current;if (!g || !sel) return;- const id = useSelection.getState().selectedId;+ // Selection is a source id; the gizmo/outline reads World geometry, so+ // resolve it to the runtime entity (absent if not currently spawned).+ const sid = useSelection.getState().selectedId;+ const rt = sid != null ? SceneModel.runtimeFor(sid) : undefined;const ready = EngineHost.getSnapshot().status === 'ready';const showG = useEditorStore.getState().showGizmos;- const pos = ready && id != null ? ViewportController.getEntityXY(id) : null;+ const pos = ready && rt != null ? ViewportController.getEntityXY(rt) : null;const sc = pos ? ViewportController.worldToClient(pos.x, pos.y) : null;if (sc && showG) {g.style.transform = `translate(${sc.x}px, ${sc.y}px)`;@@ -165,7 +169,7 @@ export function Viewport() {g.style.opacity = '0';}- const rect = ready && id != null ? ViewportController.getEntityScreenRect(id) : null;+ const rect = ready && rt != null ? ViewportController.getEntityScreenRect(rt) : null;if (rect) {sel.style.transform = `translate(${rect.x}px, ${rect.y}px)`;sel.style.width = `${rect.w}px`;@@ -212,37 +216,41 @@ export function Viewport() {}if (e.button !== 0) return;- const id = ViewportController.pickEntity(e.clientX, e.clientY);- useSelection.getState().select(id);- if (id == null) return;+ // Pick returns a runtime World entity (rendering domain); the editor selects+ // and commands by stable source id. Resolve once: source id drives selection+ // + SceneCommands; the runtime id drives ViewportController screen geometry.+ const rtId = ViewportController.pickEntity(e.clientX, e.clientY);+ const sourceId = rtId != null ? SceneModel.sourceFor(rtId) ?? null : null;+ useSelection.getState().select(sourceId);+ if (rtId == null || sourceId == null) return;if (tool === 'rotate') {- const c = entityClientCenter(id);- const startRot = (SceneQuery.getFieldValue(id, 'Transform', 'rotation') as number) ?? 0;+ const c = entityClientCenter(rtId);+ const startRot = (SceneQuery.getFieldValue(sourceId, 'Transform', 'rotation') as number) ?? 0;if (!c) return;SceneCommands.beginGesture('Rotate');dragRef.current = {- kind: 'rotate', id, cx: c.cx, cy: c.cy,+ kind: 'rotate', id: sourceId, cx: c.cx, cy: c.cy,startAngle: Math.atan2(e.clientY - c.cy, e.clientX - c.cx), startRot,};stageRef.current?.setPointerCapture(e.pointerId);} else if (tool === 'scale') {- const c = entityClientCenter(id);- const s = (SceneQuery.getFieldValue(id, 'Transform', 'scale') as number[]) ?? [1, 1, 1];+ const c = entityClientCenter(rtId);+ const s = (SceneQuery.getFieldValue(sourceId, 'Transform', 'scale') as number[]) ?? [1, 1, 1];if (!c) return;SceneCommands.beginGesture('Scale');dragRef.current = {- kind: 'scale', id, cx: c.cx, cy: c.cy,+ kind: 'scale', id: sourceId, cx: c.cx, cy: c.cy,startDist: Math.max(1, Math.hypot(e.clientX - c.cx, e.clientY - c.cy)),sx: s[0] ?? 1, sy: s[1] ?? 1, sz: s[2] ?? 1,};stageRef.current?.setPointerCapture(e.pointerId);} else {const wp = ViewportController.canvasToWorld(e.clientX, e.clientY);- const ep = ViewportController.getEntityXY(id);+ const ep = ViewportController.getEntityXY(rtId);if (wp && ep) {SceneCommands.beginGesture('Move');- dragRef.current = { kind: 'move', id, dx: ep.x - wp.x, dy: ep.y - wp.y };+ dragRef.current = { kind: 'move', id: sourceId, dx: ep.x - wp.x, dy: ep.y - wp.y };stageRef.current?.setPointerCapture(e.pointerId);}}diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 81ecf6291..493be8d57 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -1,10 +1,14 @@import { createStore } from 'zustand/vanilla';-import { resetWorldTo, getComponent, Assets } from 'esengine';+import { getComponent, Assets } from 'esengine';import type { SceneData } from 'esengine';import { EngineHost } from '@/engine/EngineHost';import { SceneModel } from '@/engine/SceneModel';+import { Reconciler } from '@/engine/Reconciler';+import { EditorHistory } from '@/engine/EditorHistory';+import { setUserSchemas, type UserComponentSchema } from '@/engine/schema';+import { useSelection } from '@/store/selectionStore';import { Toasts } from '@/store/Toasts';-import { resolveLayout, type OpenedProject, type ProjectLayout, type WorkspaceState } from './format';+import { resolveLayout, WORKSPACE_DIR, type OpenedProject, type ProjectLayout, type WorkspaceState } from './format';/*** Editor-side project/workspace model (RC12 §E7-3 / §E6-1).@@ -78,6 +82,10 @@ function mapAssetRefs(value: unknown, resolve: (uuid: string) => number): unknowclass ProjectStoreImpl {private readonly store = createStore<{ project: ProjectState | null }>(() => ({ project: null }));+ /** Resolved `@uuid:` → GL handle map for the current scene's textures; the+ * Reconciler reads it (via the registered resolver) when projecting entities+ * recreated incrementally (duplicate, undo-of-delete) back into the World. */+ private readonly uuidToHandle = new Map<string, number>();/** Read accessor so existing `this.state` reads stay unchanged after the move. */private get state(): ProjectState | null {return this.store.getState().project;@@ -124,10 +132,27 @@ class ProjectStoreImpl {private async adopted(opened: OpenedProject): Promise<void> {this.adopt(opened);await window.estella.recents.add(opened.root, opened.manifest.name);+ await this.loadUserSchemas();EngineHost.setSceneBootstrap(() => this.loadCurrentScene());if (EngineHost.world) await this.loadCurrentScene();}+ /**+ * Load the project's component field schemas (`.esengine/cache/schemas.json`,+ * built by extractSchemas) so the inspector can list + edit user/script+ * components — which never run in the editor realm, so the engine registry+ * doesn't know them. Missing/invalid cache → builtins only (run "Extract+ * Schemas"); the components still round-trip losslessly through the model.+ */+ private async loadUserSchemas(): Promise<void> {+ try {+ const json = await window.estella.fs.read(`${WORKSPACE_DIR}/cache/schemas.json`);+ setUserSchemas(JSON.parse(json) as UserComponentSchema[]);+ } catch {+ setUserSchemas([]);+ }+ }+private adopt(opened: OpenedProject) {this.store.setState({project: {@@ -162,15 +187,16 @@ class ProjectStoreImpl {);}const data = await this.resolveTextures(raw);- const world = EngineHost.mutableWorld();- if (world) {- // resetWorldTo returns source-id → runtime entity. Adopt the raw scene- // (with @uuid: refs + any components/fields/invisible entities the World- // drops) as the editor's source of truth (REARCH_SERIALIZATION.md L1).- // The World is a lossy projection; the model is what save() serializes.- const entityMap = resetWorldTo(world, data);- SceneModel.adopt(raw, entityMap);- }+ // A scene is a session document: replacing it clears the editor history ++ // selection so undo closures can't reference the previous scene's entities+ // (REARCH_EDITOR_MODEL.md §6). The Reconciler bulk path then builds the World+ // from the resolved scene and adopts the raw scene (with @uuid: refs + any+ // components/fields/invisible entities the World drops) as the source of+ // truth. The World is a lossy projection; the model is what save() serializes.+ EditorHistory.clear();+ useSelection.getState().select(null);+ Reconciler.setAssetResolver((uuid) => this.uuidToHandle.get(uuid) ?? 0);+ Reconciler.adopt(raw, data);EngineHost.syncEditorViewToScene();this.store.setState({ project: { ...st, currentScene: rel } });}@@ -184,6 +210,7 @@ class ProjectStoreImpl {private async resolveTextures(raw: SceneData): Promise<SceneData> {const st = this.state;const bridge = window.estella;+ this.uuidToHandle.clear();if (!st) return raw;const referenced = new Set<string>();@@ -211,18 +238,17 @@ class ProjectStoreImpl {}const assets = EngineHost.getResource(Assets) as unknown as AssetsLike | undefined;- const uuidToHandle = new Map<string, number>();if (assets) {for (const [uuid, rel] of uuidToPath) {try {const { handle } = await assets.loadTexture(`estella://project/${rel}`);- uuidToHandle.set(uuid, handle);+ this.uuidToHandle.set(uuid, handle);} catch (err) {console.warn('[project] texture load failed', rel, err);}}}- return mapAssetRefs(raw, (uuid) => uuidToHandle.get(uuid) ?? 0) as SceneData;+ return mapAssetRefs(raw, (uuid) => this.uuidToHandle.get(uuid) ?? 0) as SceneData;}/**diff --git a/desktop/src/store/selectionStore.ts b/desktop/src/store/selectionStore.tsindex bddc47124..13498efd5 100644--- a/desktop/src/store/selectionStore.ts+++ b/desktop/src/store/selectionStore.ts@@ -1,15 +1,16 @@import { create } from 'zustand';-import { SceneStore } from '@/engine/SceneStore';+import { SceneModel } from '@/engine/SceneModel';import type { EntityId } from '@/types';/**- * Entity selection — engine-anchored.+ * Entity selection — model-anchored (REARCH_EDITOR_MODEL.md).*- * Selection holds ids, but the entities live in the engine World, so a selected- * id can be destroyed out from under us (delete, undo-of-create, scene teardown).- * Instead of scattering defensive `select(null)` after every such op, this store- * listens for entity despawns and drops the dead id by hand — selection- * self-heals, and stale-selection bugs become structurally impossible.+ * Selection holds stable **source ids** (they survive undo/redo recreates, where+ * the runtime World id changes). A selected entity can still be removed out from+ * under us (delete, undo-of-create, scene reload). Instead of scattering+ * defensive `select(null)` after every such op, this store listens for the+ * model's `entityRemoved` event and drops the dead id — selection self-heals, and+ * stale-selection bugs become structurally impossible.** `selectedId` is the primary/active entity (drives the Details panel + viewport* gizmo); `selectedIds` is the full multi-selection set.@@ -60,8 +61,10 @@ export const useSelection = create<SelectionState>((set) => ({}),}));-// Engine-anchored self-healing: when an entity is despawned (delete, undo-of-create,-// scene teardown), drop it from the selection by id — no manual deselect, no-// validity race. Wholesale scene swaps (open project, play-stop) still call-// select(null) explicitly, since ids can be reused by the incoming scene.-SceneStore.onEntityDespawn((id) => useSelection.getState().dropId(id));+// 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);+});diff --git a/desktop/tests/editor-control-surface.test.ts b/desktop/tests/editor-control-surface.test.tsindex c4c8705e9..40330e938 100644--- a/desktop/tests/editor-control-surface.test.ts+++ b/desktop/tests/editor-control-surface.test.ts@@ -10,7 +10,7 @@* 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.*/-import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';+import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';import { App, Transform } from 'esengine';import type { ESEngineModule } from 'esengine';import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';@@ -48,6 +48,12 @@ 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 type { SceneData } from 'esengine';++const emptyScene = (): SceneData =>+ ({ version: '1.0', name: 'test', entities: [] }) as unknown as SceneData;describe.skipIf(!HAS_WASM)('EditorControlSurface (headless World)', () => {let module: ESEngineModule;@@ -63,8 +69,14 @@ describe.skipIf(!HAS_WASM)('EditorControlSurface (headless World)', () => {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());});+ afterEach(() => Reconciler.detach());+it('addEntity surfaces through the scene tree and stats', () => {const id = API.addEntity();expect(id).not.toBeNull();@@ -73,11 +85,12 @@ describe.skipIf(!HAS_WASM)('EditorControlSurface (headless World)', () => {});it('setField writes a component field; surface undo reverts it', () => {- const id = API.addEntity()!;+ const id = API.addEntity()!; // source id+ const e = SceneModel.runtimeFor(id)!; // runtime World entityAPI.setField(id, 'Transform', 'position', 'vec3', [10, 20, 30]);- expect(host.world.get(id, Transform).position).toMatchObject({ x: 10, y: 20, z: 30 });+ expect(host.world.get(e, Transform).position).toMatchObject({ x: 10, y: 20, z: 30 });API.undo();- expect(host.world.get(id, Transform).position).toMatchObject({ x: 0, y: 0, z: 0 });+ expect(host.world.get(e, Transform).position).toMatchObject({ x: 0, y: 0, z: 0 });});it('step(n) drives exactly n deterministic ticks', async () => {diff --git a/desktop/tests/engine-commands.test.ts b/desktop/tests/engine-commands.test.tsindex d0f822d1b..47e834dc4 100644--- a/desktop/tests/engine-commands.test.ts+++ b/desktop/tests/engine-commands.test.ts@@ -1,14 +1,16 @@/*** @file Regression net for the editor's read/write/undo core (SceneCommands +- * SceneQuery) against a real headless World. This is the safety net for- * the JSON-first rewrite (REARCH_SERIALIZATION.md), which re-targets these- * modules from the live World to the data model.+ * SceneQuery) against a real headless World. Proves the model-authoritative+ * flow (REARCH_EDITOR_MODEL.md): commands edit the SceneModel by source id,+ * 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 (EditorHistory, EntityHandles, schema) runs for real.+ * editor logic (SceneModel, Reconciler, EditorHistory, schema) runs for real.+ * Commands return SOURCE ids; the World is asserted via SceneModel.runtimeFor.*/-import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';+import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';import { App, Transform, Parent, Sprite } from 'esengine';import type { ESEngineModule } from 'esengine';import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';@@ -28,7 +30,16 @@ 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 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;@@ -41,13 +52,20 @@ describe.skipIf(!HAS_WASM)('SceneCommands / SceneQuery (headless World)', () =>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());});+ afterEach(() => Reconciler.detach());+it('addEntity spawns an entity with a Transform; undo/redo round-trips', () => {const id = SceneCommands.addEntity();expect(id).not.toBeNull();- expect(host.world.valid(id!)).toBe(true);- expect(host.world.has(id!, Transform)).toBe(true);+ 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();@@ -59,27 +77,29 @@ describe.skipIf(!HAS_WASM)('SceneCommands / SceneQuery (headless World)', () =>it('setField writes a component field; undo reverts to the prior value', () => {const id = SceneCommands.addEntity()!;+ const e = rt(id);SceneCommands.setField(id, 'Transform', 'position', 'vec3', [10, 20, 30]);- expect(host.world.get(id, Transform).position).toMatchObject({ x: 10, y: 20, z: 30 });+ expect(host.world.get(e, Transform).position).toMatchObject({ x: 10, y: 20, z: 30 });EditorHistory.undo();- expect(host.world.get(id, Transform).position).toMatchObject({ x: 0, y: 0, z: 0 });+ expect(host.world.get(e, Transform).position).toMatchObject({ x: 0, y: 0, z: 0 });EditorHistory.redo();- expect(host.world.get(id, Transform).position).toMatchObject({ x: 10, y: 20, z: 30 });+ 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 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();- expect(host.world.get(id, Transform).position.x).toBe(3);+ expect(host.world.get(e, Transform).position.x).toBe(3);EditorHistory.undo(); // one step undoes the whole drag- expect(host.world.get(id, Transform).position.x).toBe(0);+ expect(host.world.get(e, Transform).position.x).toBe(0);});it('deleteEntity removes the entity; undo re-creates it', () => {@@ -111,47 +131,53 @@ describe.skipIf(!HAS_WASM)('SceneCommands / SceneQuery (headless World)', () =>it('setParent parents an entity (Parent component); undo un-parents it', () => {const parent = SceneCommands.addEntity()!;const child = SceneCommands.addEntity()!;+ const childRt = rt(child);+ const parentRt = rt(parent);SceneCommands.setParent(child, parent);- expect(host.world.has(child, Parent)).toBe(true);- expect((host.world.get(child, Parent) as { entity: number }).entity).toBe(parent);+ expect(host.world.has(childRt, Parent)).toBe(true);+ expect((host.world.get(childRt, Parent) as { entity: number }).entity).toBe(parentRt);EditorHistory.undo();- expect(host.world.has(child, Parent)).toBe(false);+ expect(host.world.has(childRt, Parent)).toBe(false);EditorHistory.redo();- expect(host.world.has(child, Parent)).toBe(true);+ 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 aRt = rt(a);+ const bRt = rt(b);SceneCommands.setParent(b, a); // b under aSceneCommands.setParent(a, b); // a under b would cycle — rejected- expect(host.world.has(a, Parent)).toBe(false);- expect((host.world.get(b, Parent) as { entity: number }).entity).toBe(a);+ expect(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()!;- expect(host.world.has(id, Sprite)).toBe(false);+ const e = rt(id);+ expect(host.world.has(e, Sprite)).toBe(false);SceneCommands.addComponent(id, 'Sprite');- expect(host.world.has(id, Sprite)).toBe(true);+ expect(host.world.has(e, Sprite)).toBe(true);EditorHistory.undo();- expect(host.world.has(id, Sprite)).toBe(false);+ expect(host.world.has(e, Sprite)).toBe(false);EditorHistory.redo();- expect(host.world.has(id, Sprite)).toBe(true);+ expect(host.world.has(e, Sprite)).toBe(true);});it('removeComponent removes a component; undo restores it; Transform is protected', () => {const id = SceneCommands.addEntity()!;+ const e = rt(id);SceneCommands.addComponent(id, 'Sprite');SceneCommands.removeComponent(id, 'Sprite');- expect(host.world.has(id, Sprite)).toBe(false);+ expect(host.world.has(e, Sprite)).toBe(false);EditorHistory.undo();- expect(host.world.has(id, Sprite)).toBe(true);+ expect(host.world.has(e, Sprite)).toBe(true);SceneCommands.removeComponent(id, 'Transform');- expect(host.world.has(id, Transform)).toBe(true);+ 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 f1f83e220..8eb919fd1 100644--- a/desktop/tests/engine-model-sync.test.ts+++ b/desktop/tests/engine-model-sync.test.ts@@ -1,11 +1,12 @@/**- * @file JSON-first L3/L4 payoff: SceneCommands dual-write keeps the source-of-- * truth model in sync with the World, and the model serializes LOSSLESSLY- * — unknown components/fields the World drops survive an edit→save round- * trip (the case the old `lossy` flag refused to save).+ * @file Model-authoritative payoff (REARCH_EDITOR_MODEL.md): SceneCommands edit+ * the SceneModel ONLY; the Reconciler projects the model into the World,+ * 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.*/-import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';-import { App, Transform, resetWorldTo } from 'esengine';+import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';+import { App, Transform, Parent, resetWorldTo } from 'esengine';import type { ESEngineModule, SceneData } from 'esengine';import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';@@ -22,6 +23,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';function sceneWithUnknown(): SceneData {@@ -62,6 +64,9 @@ describe.skipIf(!HAS_WASM)('JSON-first dual-write + lossless save (L3/L4)', () =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>);@@ -70,8 +75,10 @@ describe.skipIf(!HAS_WASM)('JSON-first dual-write + lossless save (L3/L4)', () =expect(host.world.has(runtime1, Transform)).toBe(true);});+ afterEach(() => Reconciler.detach());+it('setField edits the World AND the model, preserving the unknown component', () => {- SceneCommands.setField(runtime1, 'Transform', 'position', 'vec3', [9, 8, 7]);+ SceneCommands.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 });@@ -89,7 +96,7 @@ describe.skipIf(!HAS_WASM)('JSON-first dual-write + lossless save (L3/L4)', () =});it('undo of a field edit reverts the model too', () => {- SceneCommands.setField(runtime1, 'Transform', 'position', 'vec3', [9, 0, 0]);+ SceneCommands.setField(1, 'Transform', 'position', 'vec3', [9, 0, 0]); // by source idEditorHistory.undo();const hero = SceneModel.serialize()!.entities.find((e) => e.id === 1)!;const t = hero.components.find((c) => c.type === 'Transform')!.data as {@@ -107,7 +114,7 @@ describe.skipIf(!HAS_WASM)('JSON-first dual-write + lossless save (L3/L4)', () =});it('delete then undo preserves the unknown component (lossless undo)', () => {- SceneCommands.deleteEntity(runtime1);+ SceneCommands.deleteEntity(1); // by source idexpect(SceneModel.serialize()!.entities.length).toBe(0);EditorHistory.undo();@@ -116,4 +123,32 @@ describe.skipIf(!HAS_WASM)('JSON-first dual-write + lossless save (L3/L4)', () =// the restored entity still carries the unknown component:expect(saved.entities[0].components.some((c) => c.type === 'WaveMotion')).toBe(true);});++ 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(+ 'Child',+ [{ type: 'WaveMotion', data: { amplitude: 3 } }] as never,+ 1,+ );+ const childRt = SceneModel.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();+ expect(host.world.valid(childRt)).toBe(false);++ EditorHistory.undo();+ // Model: child is back, with its parent link AND its unknown component.+ const restored = SceneModel.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)!;+ 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.tsnew file mode 100644index 000000000..d30b5ce14--- /dev/null+++ b/desktop/tests/inspector-model.test.ts@@ -0,0 +1,95 @@+/**+ * @file Unknown / user-component inspector (REARCH_EDITOR_MODEL.md E1). Project+ * components never run in the editor realm, so the engine registry doesn't+ * 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.+ */+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 { setUserSchemas } from '@/engine/schema';+import { EditorHistory } from '@/engine/EditorHistory';++const WAVE_SCHEMA = {+ name: 'WaveMotion',+ isTag: false,+ default: { amplitude: 5, phase: 1.5 },+ colorKeys: [],+};++function sceneWithWave(): SceneData {+ return {+ version: '1.0',+ name: 'waves',+ entities: [+ {+ id: 1,+ name: 'Hero',+ parent: null,+ children: [],+ components: [+ {+ type: 'Transform',+ data: {+ position: { x: 0, y: 0, z: 0 },+ rotation: { w: 1, x: 0, y: 0, z: 0 },+ scale: { x: 1, y: 1, z: 1 },+ },+ },+ { type: 'WaveMotion', data: { amplitude: 5, phase: 1.5 } }, // unknown to the engine+ ],+ },+ ],+ } as unknown as SceneData;+}++describe('Unknown-component inspector (schemas.json consumer)', () => {+ beforeEach(() => {+ SceneModel.clear();+ EditorHistory.clear();+ setUserSchemas([WAVE_SCHEMA]);+ // 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]]));+ });++ it('lists an unknown component with its schema fields', () => {+ const wave = SceneQuery.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);++ const saved = SceneModel.serialize()!;+ const wave = saved.entities[0].components.find((c) => c.type === 'WaveMotion')!.data as {+ amplitude: number;+ phase: number;+ };+ expect(wave.amplitude).toBe(9);+ expect(wave.phase).toBe(1.5); // untouched field preserved verbatim+ });++ it('undo reverts an unknown-component edit', () => {+ SceneCommands.setField(1, 'WaveMotion', 'amplitude', 'number', 9);+ EditorHistory.undo();+ expect(SceneQuery.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');+ 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 37061eeb4..b36340430 100644--- a/desktop/tests/selection-store.test.ts+++ b/desktop/tests/selection-store.test.ts@@ -28,9 +28,15 @@ 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();+const emptyScene = (): SceneData =>+ ({ version: '1.0', name: 'test', entities: [] }) as unknown as SceneData;+describe('SelectionStore — pure selection ops', () => {beforeEach(() => sel().select(null));@@ -87,6 +93,10 @@ describe.skipIf(!HAS_WASM)('SelectionStore — engine-anchored self-healing', ()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));diff --git a/docs/REARCH_EDITOR_MODEL.md b/docs/REARCH_EDITOR_MODEL.mdnew file mode 100644index 000000000..d40ca8945--- /dev/null+++ b/docs/REARCH_EDITOR_MODEL.md@@ -0,0 +1,217 @@+# 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+`REARCH_SERIALIZATION.md` (JSON-first model) and the prerequisite for+`REARCH_EDITOR_REALM.md` (isolated play).++**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 pure+derived projection); `SceneStore` is a model-change bus (the engine `editorBridge`+is retired as the editor reactivity source); `SceneQuery` reads the model;+selection is source ids self-healing on the model's `entityRemoved`; the+`schemas.json` consumer (`schema.ts`) makes unknown/user components inspectable ++editable; `setRunMode` Stop rebuilds the World from the untouched model (no+snapshot/restore); scene load clears history + selection. 64 desktop vitest pass+(+ `inspector-model.test.ts`, hierarchy/unknown lossless-undo). RESUME: **P2**+(EditorSession instance + EditorControlSurface as its façade), then **P3**+(isolated play realm).++## 1. Problem: dual-write desyncs++Today every mutation **writes the World AND the `SceneModel`** (the JSON-first+truth), kept in sync by `runtimeToSource`/`sourceToRuntime` entity-id maps. The+World is a lossy render projection; the model is the lossless truth. This is+correct in steady state but the binding goes stale on any *wholesale* World+change, and the World capture is lossy on recreate. The consequences (all+observed):++- **Play→Stop model desync.** `EngineHost.setRunMode` does+ `serializeScene(world)` then `resetWorldTo(world, snapshot)`; the new runtime+ ids are never re-`adopt`ed, so the model maps go dead → post-Stop edits resolve+ to `undefined` and silently never reach the model → lost on save.+- **Scene reload leaves stale history/model.** `ProjectStore.loadCurrentScene`+ re-`adopt`s a new model but never clears `EditorHistory`/`SceneModel`, so undo+ closures reference dead entities from the previous scene.+- **Lossy undo-recreate.** `SceneCommands` captures recreated entities from the+ registry-only World (`STRUCTURAL_SKIP = {Parent, Children}`), so delete→undo+ drops hierarchy AND unknown/project components from the World projection.+- **Unknown/project components are invisible.** The inspector enumerates the live+ engine registry; project code never runs in the editor realm, so user+ components (which the loader SKIPs into the model only) can't be inspected or+ edited. `schemas.json` was built to fix this but has no consumer.+- **Reads leak into the raw World.** `Details.tsx` reads `EngineHost.world`+ directly; the outliner derives hierarchy from World `Parent`. The truth (the+ model) is bypassed for reads.++These are **one root cause**: two sources of truth synchronized by convention.++## 2. Principle: unidirectional, model-authoritative++```+ ┌──────────── single source of truth ────────────┐+ Command ──write│ Document Model (SceneModel) │── change events ─┐+ (only writer) │ lossless JSON: entities / components (incl. │ │+ │ unknown) / hierarchy / @uuid refs │ │+ └─────────────────────────────────────────────────┘ ▼+ ▲ │ read ┌────────────────────┐+ │ ├──▶ Inspector / Outliner (read MODEL) │ Reconciler │+ Undo = model ops ├──▶ Selection (MODEL source ids) │ model → World │+ (TransactionManager over the │ │ spawn/set/despawn │+ model; lossless by record) └──────────────────────────────────────── │ (known comps; │+ │ │ unknown stay model)+ └──────────────────────────────────────────────────────────────────└─────────┬──────────┘+ ▼+ World (pure projection; read only for+ camera-derived geometry: pick / gizmo)+```++**Invariant: the World is a pure function of the Model.** Commands mutate the+Model only; a Reconciler projects Model→World. There is no path that writes the+World directly (except the Reconciler), so they cannot diverge.++This is the pattern mature editors converge on: UE (UObject graph is truth, the+world is constructed from it), Unity (serialized objects are truth), Figma /+VS Code (the document is truth; the scene graph / view is derived).++## 3. Target architecture (6 layers)++1. **Document Model** — `SceneModel` upgraded to the sole truth; addressed by+ **stable source id**; emits fine-grained change events. Holds unknown+ components + `@uuid:` refs + invisible entities verbatim.+2. **Commands + Transactions** — every mutation is a command that edits the+ model; `EditorHistory` records **model operations** (not World re-spawns), so+ undo restores the full model record → lossless by construction.+3. **Reconciler** — subscribes to model changes; projects to the World+ (spawn/despawn/insert/remove/set) for components the engine knows; leaves+ unknown components in the model only. Owns the source↔runtime id map; rebuilds+ it on a wholesale model load (bulk path = `resetWorldTo(world, model.data)`).+4. **Selectors / Queries** — `SceneQuery`, inspector, outliner read the **Model**.+ The Viewport reads the **World** only for camera-derived screen geometry+ (pick, gizmo, selection outline) via the engine `CameraView` — that is+ rendering, the engine's domain.+5. **EditorSession (single boundary)** — owns {model, history, selection,+ reconciler, App/World, handles} as an **instance**; the one API for UI,+ headless host, and MCP. `EditorControlSurface` becomes its façade. (Phase 2.)+6. **Isolated Play Realm** — Play runs the scene in an iframe/worker loading the+ built `scripts.mjs` + the model's scene data. The editor realm never runs+ project code; Stop destroys the realm; the editor model/World are untouched.+ `play == ship`. (Phase 3.)++## 4. How each problem dissolves (structural, not patched)++| Problem | Why it cannot happen |+|---|---|+| Play→Stop model desync | Play is isolated (P3); the editor model never participates, so there is no snapshot/restore and no stale map. Until P3, Stop just re-reconciles the World from the untouched model. |+| Scene reload stale history | A scene = a session document; replacing it clears the model + history; the reconciler rebuilds the World + binding. |+| Lossy undo-recreate | Undo replays the **model op**; the model record holds every component + the parent link → reconciler re-projects → lossless. |+| Unknown components invisible | Inspector reads the **model** (+ `schemas.json` for field shapes); unknown components live in the model and are editable, just not projected to the World. |+| `Details` reads raw World | No UI reads the World; it is only read for camera geometry. |+| `EditorControlSurface` bypassed | One `EditorSession` boundary; UI / headless / MCP all go through it. |+| Singletons assume one window | `EditorSession` is an instance → multi-scene / multi-window are natural. |++## 5. Phased migration (reuse-heavy, not a rewrite)++- **P1 — Data-flow inversion** (highest ROI; kills the data-bug class #1–#4 + the+ raw-World read leak). Pure editor-side TS, unit-testable, no engine change.+- **P2 — Session scoping.** Collapse the engine-layer singletons into one+ `EditorSession` instance; `EditorControlSurface` becomes its façade; the UI+ routes through it (closes H2).+- **P3 — Isolated play realm.** Build the `scripts.mjs` / `schemas.json` realm+ loader + iframe play; delete `setRunMode`'s snapshot/restore entirely.+- **Cross-cutting (fold in anytime):** SDK type exports (kill shadow-typing),+ jsdom interaction tests, error boundaries + failure toasts, command-registry+ extension points + persisted keymap, multi-entity transform.++## 6. P1 — detailed implementation checklist++Goal: commands mutate the model (by source id); a Reconciler projects to the+World; reads come from the model; undo records model ops.++**New — `src/engine/Reconciler.ts`**+- Subscribes to model change events; projects each to the World:+ - entity added → `world.spawn()` + `SceneModel.bindRuntime(sourceId, runtime)`;+ insert each component the registry knows (`getComponent(type)`); skip unknown.+ - entity removed → `world.despawn(runtime)`.+ - field/component set → `world.set/insert` for known types; no-op for unknown.+ - component removed → `world.remove`.+ - parent changed → World `Parent` insert/remove.+- Bulk path (load): `resetWorldTo(world, model.current)` → returns entityMap →+ `SceneModel.adopt(model, entityMap)` (reuses the engine loader; no per-entity+ spawn loop). Used by boot + project load + (until P3) play-stop.+- Owns nothing the model already owns — it drives `SceneModel.bindRuntime`.++**Change — `SceneModel`** (truth + event source)+- Add a change emitter (or reuse `SceneStore` as the bus): emit+ `entityAdded(sourceId)`, `entityRemoved(sourceId)`, `componentChanged(sourceId,+ type)`, `parentChanged(sourceId)`. Mutations key off **source id** (overloads+ that take `runtime` resolve via `sourceFor` and stay for the gizmo path).+- `setField`/`setComponent`/`removeComponent`/`addEntity`/`removeEntityBySource`/+ `restoreEntity`/`setParent` already exist — they become the *only* writers and+ emit events. `removeEntityBySource` must also scrub the child id from its+ parent's `children[]`.++**Change — `SceneCommands`** (single model write, no dual-write)+- `setField` → `SceneModel.setField` (model emits → reconciler projects). Delete+ the `applyFieldWrite` World write.+- `addEntity` → `SceneModel.addEntity` (allocate source id, no runtime) → emit →+ reconciler spawns + binds. Return the **source id**.+- `deleteEntity` → `SceneModel.removeEntityBySource`; undo = `restoreEntity(full+ record)` → reconciler respawns. Delete `captureEntity`/`recreateEntity` (the+ lossy World capture).+- `addComponent`/`removeComponent`/`setParent`/`duplicateEntity` → model ops only.+- `beginGesture`/`endGesture` unchanged (still coalesce into one undo step).++**Change — `EditorHistory`** records model ops. `forward`/`reverse` mutate the+model; the reconciler follows via events. (TransactionManager unchanged.)++**Change — `SceneQuery`** reads the Model+- `readSceneTree` from `SceneModel.current.entities` (hierarchy from+ `parent`/`children`), not World `Parent`.+- `readInspector`/`readEntity`/`getFieldValue` from the model entity's+ `components` (incl. unknown) + field shapes from the registry (builtin) or+ `schemas.json` (user). The Viewport's pick/gizmo/`worldToClient` keep reading+ the World via `CameraView`.++**New — `schemas.json` consumer** in `schema.ts`+- Load `.esengine/cache/schemas.json` (via the fs IPC bridge) on project open;+ merge as a field-shape source for component names absent from the engine+ registry. `inspectableComponents` enumerates the **model entity's** component+ types, resolving each shape from registry-or-schemas.json. (Closes rearch E1.)++**Change — Selection** references **source ids** (stable, survive recreate);+self-heal on `entityRemoved`. The Viewport resolves source→runtime+(`SceneModel.runtimeFor`) for the gizmo/outline.++**Change — `ProjectStore.loadCurrentScene` / `EngineHost` boot** call+`EditorHistory.clear()` + `SceneModel.clear()` before adopting, and use the+Reconciler's bulk path.++**Delete (eventually):** the engine `editorBridge` as the editor's reactivity+source — the editor now reacts to **model** events, not engine-pushed mutations+(the World is derived). Keep the bridge only if other consumers need it.++**Tests (P1 acceptance):**+- Round-trip stability: load → batch of edits (field/color/angle, add/remove+ component, reparent, add/delete/duplicate) → `serialize()` → reload → re-serialize+ → assert identical.+- Lossless undo: delete a parented entity carrying an unknown component → undo →+ assert the World projection AND the model both have it back, with the parent+ link restored.+- Scene reload: open scene B after A, then undo → assert no-op on B's world (no+ dead-handle mutation).+- Unknown-component inspector: load a scene with an unknown component + its+ `schemas.json` → inspector lists + edits its fields → model round-trips.+- Extend `engine-model-sync.test.ts` / `scene-model.test.ts`.++## 7. Open decisions++- **Selection id space.** Recommend **source ids** (stable). Requires migrating+ `selectionStore` + the Viewport's resolve. Alternative (runtime ids) keeps the+ current code but re-introduces self-heal-on-respawn complexity.+- **Reconciler granularity.** Per-change incremental for edits; bulk+ (`resetWorldTo`) for load. A "dirty set + flush per frame" batcher is a later+ optimization, not needed for P1.+- **SceneStore vs a new emitter.** Reuse `SceneStore` as the model-change bus+ (it already drives panel reactivity) rather than adding a parallel emitter.