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(agent): the running game, read by name
esengined9892e9add86
diff --git a/desktop/electron/agent/prompt.ts b/desktop/electron/agent/prompt.tsindex 778e5e6b5..61d900786 100644--- a/desktop/electron/agent/prompt.ts+++ b/desktop/electron/agent/prompt.ts@@ -34,6 +34,7 @@ Working style:- Look before you edit. get_scene_tree, get_inspector and get_document cost one round trip and are the difference between editing the right entity and editing a plausible one.- You can see the result: capture_viewport renders what the user is looking at, and screenshot takes in the whole window including a running game — as a picture, or, with \`format: 'grid'\`, as a coarse colour grid in TEXT, which is the form to ask for when images cannot reach you. LOOK before you call a visual change done — a material, an effect, a layout, anything whose whole point is what it looks like. Reading back the data you just wrote proves you wrote it, not that it did anything; the difference between "the component says 1.0" and "the sprite is gone" is the entire job.+- To read the RUNNING game, ask by name before you write a probe. find_entities says which entities there are and what each carries; inspect_entity gives ONE of them whole — every component with its live data, which is where physics, AI, animation and UI state all are, because they ARE components. list_resources gives the state that belongs to no entity, and get_systems what runs each frame. None of them is confirmed. play_probe is the escape hatch for what they do not answer, and it costs the user a prompt every time.- A game you have built is not tested until you have PLAYED it: toggle_play, then step to advance it (its loop is throttled to about a frame a second whenever the editor window is not the focused one, so waiting shows you a frozen picture of a healthy game), play_input to press the keys a player would, play_probe to read what the game now thinks, and screenshot to see what a player would see. Step-look-step is the loop; twenty probes without a screenshot is how a project ships game-over-on-arrival with every component reporting exactly the value it should.- Prefer one apply_scene_ops over many small calls when building something: it is one undo step for the user and one round trip for you, and it is the ONE write the user sees BEFORE it lands — they get a line-by-line preview and can strike parts of it out. A dozen set_field calls give them no such chance, so build with a batch and save the single writes for genuinely single changes.- Units are the editor's: 1 world unit = 1 design pixel. Y is up in the world, and UI is laid out top-down. The world's ORIGIN IS THE CENTRE OF THE VIEW, not a corner: a default camera on a W×H design resolution sees y from −H/2 to +H/2 (its \`orthoSize\` is H/2) and x at least −W/2 to +W/2, wider when the window is. So the bottom of the screen is y = −H/2 and the top is +H/2 — a HUD placed at y = H − 20, or a floor at y = 0, is written in SCREEN coordinates and lands off camera or halfway up. Nothing errors: the entity is there, the fields read back what you wrote, and the picture is empty, which is why the FIRST screenshot of anything you positioned by arithmetic is worth more than the next ten probes.diff --git a/desktop/electron/surfaceDriver.ts b/desktop/electron/surfaceDriver.tsindex a941ae589..74b909266 100644--- a/desktop/electron/surfaceDriver.ts+++ b/desktop/electron/surfaceDriver.ts@@ -209,6 +209,12 @@ function colorGrid(image: Electron.NativeImage, rect: GameRect | null, cols: num* prefix instead of the game. Destructuring here makes the obvious reading the true* one; `window.__estellaPlay` keeps working for code that spells it out.*/+/**+ * The realm's own read surface, by name — a closed set, because `play_query`+ * builds a call out of it. Anything not here is not reachable through it.+ */+const PLAY_QUERIES = new Set(['inspect', 'entities', 'resources', 'systems']);+const PROBE_SCOPE ='const p = window.__estellaPlay;'+ " if (!p) throw new Error('this realm publishes no probe surface — enter play first');"@@ -244,6 +250,18 @@ export function createSurfaceDriver(if (!root) throw new Error('no project open');return root;};+ /** The play realm's frame. It is an estella:// OOPIF, so a main-process eval+ * is the only thing that reaches it; `frame` picks one in a multiplayer+ * preview (0 = the host). */+ const playFrame = (input: Record<string, unknown>) => {+ const frames = requireWin().webContents.mainFrame.frames.filter((f) => f.url.startsWith('estella://'));+ const at = Number(input.frame ?? 0);+ const frame = frames[at];+ if (!frame) {+ throw new Error(`no play realm at index ${at} (${frames.length} running — enter play first)`);+ }+ return frame;+ };const exec = async (code: string): Promise<unknown> => {const win = requireWin();@@ -280,27 +298,28 @@ export function createSurfaceDriver(return colorGrid(image, rect, Number(input.cols ?? 64), Number(input.rows ?? 32));}case 'play_probe': {- // The play realm is an estella:// OOPIF — only a main-process frame eval- // reaches it (window.__estellaPlay is the probe the realm publishes).- const frames = requireWin().webContents.mainFrame.frames.filter((f) => f.url.startsWith('estella://'));- const at = Number(input.frame ?? 0);- const frame = frames[at];- if (!frame) {- throw new Error(`no play realm at index ${at} (${frames.length} running — enter play first)`);+ return unwrap(await playFrame(input).executeJavaScript(+ carryError(String(input.code ?? 'true'), PROBE_SCOPE),+ ));+ }+ // The NAMED reads. Same realm, but the expression is OURS — no arbitrary+ // code, nothing to confirm. `kind` is a closed set, so a caller reaches+ // only what the realm published.+ case 'play_query': {+ const kind = String(input.kind ?? '');+ if (!PLAY_QUERIES.has(kind)) {+ throw new Error(`no play query "${kind}" (it answers: ${[...PLAY_QUERIES].join(', ')})`);}- return unwrap(await frame.executeJavaScript(carryError(String(input.code ?? 'true'), PROBE_SCOPE)));+ const arg = JSON.stringify(input.arg ?? null);+ return unwrap(await playFrame(input).executeJavaScript(+ carryError(`window.__estellaPlay.${kind}(...(${arg} === null ? [] : [${arg}]))`, PROBE_SCOPE),+ ));}case 'play_input': {- // Same frame lookup as play_probe — the realm is the only thing that has- // an InputState — but the code is OURS, so a caller cannot mistype the- // facade and get silence. Everything routes through the realm's- // `__estellaPlay.input`, which is the platform binding's own callbacks.- const frames = requireWin().webContents.mainFrame.frames.filter((f) => f.url.startsWith('estella://'));- const at = Number(input.frame ?? 0);- const frame = frames[at];- if (!frame) {- throw new Error(`no play realm at index ${at} (${frames.length} running — enter play first)`);- }+ // Same realm as play_probe, and like play_query the code is OURS — a+ // caller cannot mistype the facade and get silence. Everything routes+ // through `__estellaPlay.input`, the platform binding's own callbacks.+ const frame = playFrame(input);const { kind } = input as { kind?: string };const x = Number(input.x ?? 0), y = Number(input.y ?? 0);const button = Number(input.button ?? 0);diff --git a/desktop/shared/toolCatalog.mjs b/desktop/shared/toolCatalog.mjsindex ed097ab24..a7ac52b94 100644--- a/desktop/shared/toolCatalog.mjs+++ b/desktop/shared/toolCatalog.mjs@@ -597,6 +597,45 @@ const ATOMS = [const from = Math.max(0, t.length - tail);return { total: t.length, from, events: t.slice(from) };})` },+ // — The RUNNING game, read by name. `play_probe` below is the escape hatch,+ // `irreversible` because it runs the model's code; these run OURS, so they+ // are `read` and looking at the game costs no confirmation. —+ { name: 'find_entities', effect: 'read',+ description: 'Which entities the RUNNING game has, and what each carries. `component` keeps only the ones with that component, `name` is a case-insensitive substring of the entity name; both optional, so with neither you get the world. '+ + 'Answers `{ total, entities: [{ entity, name, components }] }` — `total` counts every match and `entities` is what fitted under `limit` (default 100), so a capped list can never read as the whole of what is there. '+ + 'Start here: the ids it returns are what inspect_entity takes.',+ schema: obj({+ component: { type: 'string' }, name: { type: 'string' }, limit: { type: 'number' },+ frame: { type: 'number', description: 'which realm in a multiplayer preview (0 = host)' },+ }),+ op: 'play_query',+ opInput: (i) => ({+ kind: 'entities',+ arg: { component: i.component, name: i.name, limit: i.limit },+ frame: i.frame,+ }) },+ { name: 'inspect_entity', effect: 'read',+ description: 'ONE entity of the RUNNING game, whole: `{ entity, name, parent, children, components: { Transform: {...}, Health: {...}, ... } }` — every component on it with its live data, not a list of names you then fetch one at a time. '+ + 'This is the "what IS this thing" call. Physics, AI, animation and UI state are all components, so they are all in here: a RigidBody, a StateMachineAgent\'s current state, a SpriteAnimation\'s frame, a UINode\'s computed box. '+ + 'A single value too large to send whole (a tilemap\'s tiles) comes back as { truncated, bytes, keys } in ITS place, so nothing else in the reply is lost to it.',+ schema: obj({+ entity: { type: 'number' },+ frame: { type: 'number', description: 'which realm in a multiplayer preview (0 = host)' },+ }, ['entity']),+ op: 'play_query',+ opInput: (i) => ({ kind: 'inspect', arg: Number(i.entity), frame: i.frame }) },+ { name: 'list_resources', effect: 'read',+ description: 'Every RESOURCE the running game holds, by name, with its value — the state that belongs to no entity (a score, a phase, a life count, the loaded-asset table). '+ + 'All of them at once, so there is no name to guess first.',+ schema: obj({ frame: { type: 'number' } }),+ op: 'play_query',+ opInput: (i) => ({ kind: 'resources', frame: i.frame }) },+ { name: 'get_systems', effect: 'read',+ description: 'What the running game does each frame: the systems and phases that ran, with their cost in ms, worst first, plus the entity count. '+ + 'Timings are recorded only while stats are on; when they are not, the lists are `null` and a note says so — "nothing ran" and "nobody was counting" are opposite answers and must not share a shape.',+ schema: obj({ frame: { type: 'number' } }),+ op: 'play_query',+ opInput: (i) => ({ kind: 'systems', frame: i.frame }) },{ name: 'play_probe', effect: 'irreversible',description: "Evaluate JS inside the RUNNING play realm and return the result — the gameplay probe. One expression gives its value; several statements need an explicit `return`. "+ 'These are ALREADY IN SCOPE (no prefix, though `window.__estellaPlay` holds them too): '@@ -764,7 +803,10 @@ async function invokeTool(tool, driver, rawInput, allowWrites) {return { input, data: await tool.run(input, call) };}- if (tool.op) return { input, data: await driver.op(tool.op, input) };+ // `opInput` is the op-side twin of a method tool's `args`: the tool shapes+ // what the host op receives, rather than every op having to speak the tool's+ // own argument names. Absent = the input verbatim, which is what most want.+ if (tool.op) return { input, data: await driver.op(tool.op, tool.opInput ? tool.opInput(input) : input) };// A js template may DECLINE (return null) for inputs it has nothing special// to do with, leaving the tool's typed `method` door to handle them — which// is how a tool grows one alternate path without every call losing the door.diff --git a/desktop/src/engine/playQuery.ts b/desktop/src/engine/playQuery.tsnew file mode 100644index 000000000..f9974503c--- /dev/null+++ b/desktop/src/engine/playQuery.ts@@ -0,0 +1,163 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file playQuery.ts+ * @brief Reading the RUNNING game by name, in shapes an agent can act on+ * without writing code to get them.+ *+ * The realm always had a probe — arbitrary JS with `find`/`get`/`resource` in+ * scope — and it is the escape hatch, confirmed because the code is the model's.+ * What it is a poor door for is the ordinary questions, which every run asks and+ * every run had to re-derive: what IS this entity, what state does the game+ * hold, what runs each frame. Named, they cost no confirmation and no guessing.+ *+ * The engine holds exactly three kinds of state, and these follow them rather+ * than inventing a taxonomy: entities carrying components, resources belonging+ * to no entity, and the schedule. Physics, AI, animation and UI state are all+ * COMPONENTS, so they arrive with the entity rather than needing a query each.+ *+ * Pure over {@link Realm} so the shaping is testable without a running game;+ * playHost implements that interface from its `app`.+ */++/** What a query needs of a running game. The host binds it to `app`/`world`. */+export interface Realm {+ entities(): number[];+ /** Component names on one entity, structural and transient ones excluded. */+ componentsOf(entity: number): string[];+ /** One component's live data, or null when the entity does not have it. */+ read(entity: number, type: string): unknown;+ /** The structural three, which `componentsOf` leaves out. */+ nameOf(entity: number): string | null;+ parentOf(entity: number): number | null;+ childrenOf(entity: number): number[];+ /** Every resource, by the name its `defineResource` was given. */+ resources(): Array<[string, unknown]>;+ /** Per-system and per-phase cost, or null when nothing is recording. */+ timings(): { systems: ReadonlyMap<string, number> | null; phases: ReadonlyMap<string, number> | null };+ entityCount(): number;+}++/**+ * A value too large to send whole, replaced in ITS place. A reply cut by the+ * transport's budget is cut at a byte offset, leaving the caller half a JSON+ * document and no way to tell which field went missing.+ */+export const MAX_VALUE_JSON = 4000;++export function bounded(value: unknown): unknown {+ let json: string;+ try {+ json = JSON.stringify(value) ?? 'null';+ } catch {+ return { unserializable: true };+ }+ if (json.length <= MAX_VALUE_JSON) return value;+ return {+ truncated: true,+ bytes: json.length,+ keys: value && typeof value === 'object' ? Object.keys(value) : [],+ };+}++export interface EntityInspection {+ entity: number;+ name: string | null;+ parent: number | null;+ children: number[];+ components: Record<string, unknown>;+}++/**+ * One entity, WHOLE. `get` answers about a component you can already name,+ * which is the second question; this is the first.+ */+export function inspectEntity(realm: Realm, entity: number): EntityInspection {+ if (!realm.entities().includes(entity)) {+ throw new Error(`no entity ${entity} in this realm — find_entities lists the ones there are`);+ }+ const components: Record<string, unknown> = {};+ for (const type of realm.componentsOf(entity)) components[type] = bounded(realm.read(entity, type));+ return {+ entity,+ name: realm.nameOf(entity),+ parent: realm.parentOf(entity),+ children: realm.childrenOf(entity),+ components,+ };+}++export interface EntityFilter {+ component?: string;+ name?: string;+ limit?: number;+}++export interface EntityList {+ total: number;+ entities: Array<{ entity: number; name: string | null; components: string[] }>;+ truncatedAt?: number;+}++/** How many entities one answer carries. A world can hold thousands; a reply+ * that carried them all would spend the turn's context on a list. */+const DEFAULT_LIMIT = 100;+const MAX_LIMIT = 500;++/**+ * Which entities there are, and what each carries — so the answer says which to+ * inspect, not only how many. `total` counts every match and `entities` is what+ * fitted: a capped list read as the whole world is how a search concludes+ * something is not there.+ */+export function findEntities(realm: Realm, filter: EntityFilter = {}): EntityList {+ const limit = Math.max(1, Math.min(MAX_LIMIT, Math.floor(filter.limit ?? DEFAULT_LIMIT)));+ const needle = filter.name?.toLowerCase();+ const out: EntityList['entities'] = [];+ let total = 0;+ for (const entity of realm.entities()) {+ const components = realm.componentsOf(entity);+ if (filter.component && !components.includes(filter.component)) continue;+ const name = realm.nameOf(entity);+ if (needle && !(name ?? '').toLowerCase().includes(needle)) continue;+ total++;+ if (out.length < limit) out.push({ entity, name, components });+ }+ return { total, entities: out, ...(total > out.length ? { truncatedAt: limit } : {}) };+}++/** Every resource with its value — the state that belongs to no entity, all of+ * it, so there is no name to guess first. */+export function readResources(realm: Realm): { resources: Record<string, unknown> } {+ const resources: Record<string, unknown> = {};+ for (const [name, value] of realm.resources()) if (name) resources[name] = bounded(value);+ return { resources };+}++export interface SystemReport {+ entities: number;+ systems: Array<{ name: string; ms: number }> | null;+ phases: Array<{ name: string; ms: number }> | null;+ note?: string;+}++/**+ * What runs each frame and what it cost, worst first.+ *+ * Null rather than an empty list when nothing is recording: "nothing ran" and+ * "nobody was counting" are opposite answers, and an empty list reads as the+ * first one.+ */+export function readSystems(realm: Realm): SystemReport {+ const { systems, phases } = realm.timings();+ const rows = (m: ReadonlyMap<string, number> | null) =>+ (m === null ? null : [...m].map(([name, ms]) => ({ name, ms })).sort((a, b) => b.ms - a.ms));+ return {+ entities: realm.entityCount(),+ systems: rows(systems),+ phases: rows(phases),+ ...(systems === null+ ? { note: 'timings are not being recorded — this realm has stats off, so the lists are absent rather than empty' }+ : {}),+ };+}diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.tsindex ecdf14bc9..883a5fe48 100644--- a/desktop/src/playHost.ts+++ b/desktop/src/playHost.ts@@ -20,6 +20,10 @@ import type { ESEngineModule } from 'esengine/wasm';import { PLAY_PROTOCOL_VERSION } from './engine/playProtocol';import type { PlayOutbound, PlayInbound, LiveVisibility } from './engine/playProtocol';import { translateAssetHandles, projectRelative } from './engine/liveAssetRefs';+import {+ inspectEntity, findEntities, readResources, readSystems,+ type Realm, type EntityFilter,+} from '@/engine/playQuery';type LiveEntity = SceneData['entities'][number];@@ -67,6 +71,36 @@ function inspectableTypes(world: App['world'], entity: number): string[] {});}+/** {@link Realm} over the live app — the one place these reach the SDK. */+function realm(): Realm {+ const world = app!.world;+ const structural = <T>(entity: number, type: string): T | null => {+ const def = getComponent(type);+ return def ? (world.tryGet(entity as never, def) as T | null) : null;+ };+ return {+ entities: () => world.getAllEntities() as never as number[],+ componentsOf: (e) => inspectableTypes(world, e),+ read: (e, type) => {+ const def = getComponent(type);+ return def ? world.tryGet(e as never, def) ?? null : null;+ },+ nameOf: (e) => structural<{ value?: string }>(e, 'Name')?.value ?? null,+ parentOf: (e) => structural<{ entity?: number }>(e, 'Parent')?.entity ?? null,+ childrenOf: (e) => [...(structural<{ entities?: number[] }>(e, 'Children')?.entities ?? [])],+ resources: () => {+ const entries = [...(app as unknown as {+ resources_: { resources_: Map<symbol, unknown> };+ }).resources_.resources_];+ const nameOf = (k: symbol): string =>+ (/^Resource_\d+_(.+)$/.exec(k.description ?? '')?.[1] ?? k.description ?? '');+ return entries.map(([k, v]) => [nameOf(k), v] as [string, unknown]);+ },+ timings: () => ({ systems: app!.getSystemTimings(), phases: app!.getPhaseTimings() }),+ entityCount: () => app!.getEntityCount(),+ };+}+function liveSnapshot(world: App['world'], selectedId: number | null, withTree: boolean): { tree: SceneData | null; selected: LiveEntity | null } {const nameDef = getComponent('Name');const parentDef = getComponent('Parent');@@ -418,6 +452,15 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {},/** What `find` can be asked about: the component names this realm knows. */componentNames: () => componentNamesOf(app!),++ // — The NAMED reads (the `play_query` op). The shaping is in+ // engine/playQuery, over an interface `realm()` binds to `app`, so it is+ // testable without a running game. —+ inspect: (entity: number) => inspectEntity(realm(), entity),+ entities: (filter: EntityFilter = {}) => findEntities(realm(), filter),+ resources: () => readResources(realm()),+ systems: () => readSystems(realm()),+/*** A resource's live value by name — the other half of "what does the game* think is going on", for state that belongs to no entity (a score, a lifediff --git a/desktop/tests/editor-mcp-tools.test.ts b/desktop/tests/editor-mcp-tools.test.tsindex 917a70781..91c2f13e7 100644--- a/desktop/tests/editor-mcp-tools.test.ts+++ b/desktop/tests/editor-mcp-tools.test.ts@@ -483,3 +483,62 @@ describe('re-running an authoring step is not a new asset', () => {expect(driver.js.mock.calls[0][0]).toContain('refreshAssets()');});});++/**+ * Reading the RUNNING game by name. `play_probe` is the escape hatch and is+ * confirmed because it runs code the model wrote; these run code of ours, and+ * the whole point of that is that looking costs nothing.+ */+describe('the named reads over the running game', () => {+ const NAMED = ['find_entities', 'inspect_entity', 'list_resources', 'get_systems'];++ it('are read-tier, so observing the game is never confirmed', () => {+ for (const name of NAMED) {+ expect([name, toolNamed(name).effect]).toEqual([name, 'read']);+ expect([name, mutates(toolNamed(name))]).toEqual([name, false]);+ }+ });++ it('shape the op call themselves, so the host takes one closed vocabulary', async () => {+ const driver = vi.fn() as unknown as { op: ReturnType<typeof vi.fn> } & ((...a: unknown[]) => unknown);+ driver.op = vi.fn(async () => ({ entity: 7, components: {} }));++ await runTool(toolNamed('inspect_entity'), driver, { entity: 7 });+ expect(driver.op).toHaveBeenCalledWith('play_query', { kind: 'inspect', arg: 7, frame: undefined });++ await runTool(toolNamed('find_entities'), driver, { component: 'Health', limit: 5 });+ expect(driver.op).toHaveBeenLastCalledWith('play_query', {+ kind: 'entities',+ arg: { component: 'Health', name: undefined, limit: 5 },+ frame: undefined,+ });++ await runTool(toolNamed('list_resources'), driver, {});+ expect(driver.op).toHaveBeenLastCalledWith('play_query', { kind: 'resources', frame: undefined });+ });++ // An op tool without one keeps taking the input verbatim, which is what every+ // op that existed before this did.+ it('leaves an op tool that shapes nothing alone', async () => {+ const driver = vi.fn() as unknown as { op: ReturnType<typeof vi.fn> } & ((...a: unknown[]) => unknown);+ driver.op = vi.fn(async () => ({}));+ await runTool(toolNamed('check_scripts'), driver, { path: 'src/a.ts' });+ expect(driver.op).toHaveBeenCalledWith('check_scripts', { path: 'src/a.ts' });+ });++ it('answers structured data, not prose', async () => {+ const driver = vi.fn() as unknown as { op: ReturnType<typeof vi.fn> } & ((...a: unknown[]) => unknown);+ driver.op = vi.fn(async () => ({+ entity: 7,+ name: 'Skeleton',+ parent: null,+ children: [],+ components: { Transform: { x: 27, y: 81 }, Health: { current: 40 } },+ }));+ const res = await runTool(toolNamed('inspect_entity'), driver, { entity: 7 });+ expect(JSON.parse(res.content[0].text)).toMatchObject({+ name: 'Skeleton',+ components: { Transform: { x: 27, y: 81 }, Health: { current: 40 } },+ });+ });+});diff --git a/desktop/tests/play-query.test.ts b/desktop/tests/play-query.test.tsnew file mode 100644index 000000000..323bbee04--- /dev/null+++ b/desktop/tests/play-query.test.ts@@ -0,0 +1,203 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Reading the running game by name — the shapes an agent gets back.+ *+ * The claims here are about what an answer says, because that is what decides+ * whether the next call is the right one: a capped list read as the whole world+ * is how a search concludes something is not there, and an empty timing list+ * read as "nothing ran" is the opposite of "nobody was counting".+ */+import { describe, it, expect } from 'vitest';+import {+ inspectEntity, findEntities, readResources, readSystems, bounded, MAX_VALUE_JSON,+ type Realm,+} from '@/engine/playQuery';++interface Spec {+ name?: string | null;+ parent?: number | null;+ children?: number[];+ components?: Record<string, unknown>;+}++function fakeRealm(+ entities: Record<number, Spec>,+ over: Partial<Pick<Realm, 'resources' | 'timings' | 'entityCount'>> = {},+): Realm {+ const ids = Object.keys(entities).map(Number);+ const at = (e: number) => entities[e] ?? {};+ return {+ entities: () => ids,+ componentsOf: (e) => Object.keys(at(e).components ?? {}),+ read: (e, type) => at(e).components?.[type] ?? null,+ nameOf: (e) => at(e).name ?? null,+ parentOf: (e) => at(e).parent ?? null,+ childrenOf: (e) => at(e).children ?? [],+ resources: over.resources ?? (() => []),+ timings: over.timings ?? (() => ({ systems: new Map(), phases: new Map() })),+ entityCount: over.entityCount ?? (() => ids.length),+ };+}++describe('one entity, whole', () => {+ const realm = fakeRealm({+ 7: {+ name: 'Skeleton',+ parent: 3,+ children: [8],+ components: {+ Transform: { x: 27, y: 81 },+ Health: { current: 40, max: 100 },+ StateMachineAgent: { current: 'chase' },+ },+ },+ });++ // The shape the whole thing exists for: what IS this, in one call, rather+ // than a list of names and one fetch per name.+ it('answers with the name and every component, not a list to fetch from', () => {+ expect(inspectEntity(realm, 7)).toEqual({+ entity: 7,+ name: 'Skeleton',+ parent: 3,+ children: [8],+ components: {+ Transform: { x: 27, y: 81 },+ Health: { current: 40, max: 100 },+ StateMachineAgent: { current: 'chase' },+ },+ });+ });++ // AI, animation, physics and UI state are components, so asking for the+ // entity is asking for all of them — there is no per-domain query to know.+ it('carries the subsystem state, because that state IS components', () => {+ const components = inspectEntity(realm, 7).components;+ expect(components.StateMachineAgent).toEqual({ current: 'chase' });+ });++ it('says an entity is not there rather than answering about an empty one', () => {+ expect(() => inspectEntity(realm, 99)).toThrow(/no entity 99/);+ });+});++describe('which entities there are', () => {+ const realm = fakeRealm({+ 1: { name: 'Player', components: { Transform: {}, Health: {} } },+ 2: { name: 'Skeleton A', components: { Transform: {}, Health: {}, StateMachineAgent: {} } },+ 3: { name: 'Skeleton B', components: { Transform: {}, Health: {}, StateMachineAgent: {} } },+ 4: { name: 'Ground', components: { Transform: {} } },+ });++ it('answers the whole world when nothing is asked of it', () => {+ expect(findEntities(realm).total).toBe(4);+ });++ it('filters by component', () => {+ expect(findEntities(realm, { component: 'StateMachineAgent' }).entities.map((e) => e.entity))+ .toEqual([2, 3]);+ });++ it('filters by name, case-insensitively and by part', () => {+ expect(findEntities(realm, { name: 'skeleton' }).total).toBe(2);+ });++ it('takes both at once', () => {+ expect(findEntities(realm, { component: 'Health', name: 'player' }).entities).toHaveLength(1);+ });++ it('says what each one carries, so the next call is inspect and not a guess', () => {+ expect(findEntities(realm, { name: 'Player' }).entities[0].components).toEqual(['Transform', 'Health']);+ });++ // A capped list read as the whole world is how a search concludes something+ // is not there. The count is of every match; the list is what fitted.+ it('counts every match even when it can only carry some', () => {+ const out = findEntities(realm, { limit: 2 });+ expect(out.total).toBe(4);+ expect(out.entities).toHaveLength(2);+ expect(out.truncatedAt).toBe(2);+ });++ it('says nothing about truncation when nothing was truncated', () => {+ expect(findEntities(realm)).not.toHaveProperty('truncatedAt');+ });++ it('answers an empty world with a zero, not a throw', () => {+ expect(findEntities(fakeRealm({}))).toEqual({ total: 0, entities: [] });+ });+});++describe('the state that belongs to no entity', () => {+ it('answers with every resource at once, so no name has to be guessed', () => {+ const realm = fakeRealm({}, {+ resources: () => [['GameState', { lives: 3 }], ['Time', { frameCount: 90 }]],+ });+ expect(readResources(realm)).toEqual({+ resources: { GameState: { lives: 3 }, Time: { frameCount: 90 } },+ });+ });++ it('drops one whose name did not survive, rather than keying on an empty string', () => {+ const realm = fakeRealm({}, { resources: () => [['', { x: 1 }], ['Score', { n: 2 }]] });+ expect(Object.keys(readResources(realm).resources)).toEqual(['Score']);+ });+});++describe('what runs each frame', () => {+ it('lists systems and phases worst first', () => {+ const realm = fakeRealm({}, {+ timings: () => ({+ systems: new Map([['Render', 2], ['Physics', 9], ['AI', 4]]),+ phases: new Map([['Update', 13]]),+ }),+ });+ expect(readSystems(realm).systems?.map((r) => r.name)).toEqual(['Physics', 'AI', 'Render']);+ expect(readSystems(realm).phases).toEqual([{ name: 'Update', ms: 13 }]);+ });++ // "Nothing ran" and "nobody was counting" are opposite answers, and an empty+ // list reads as the first.+ it('answers null with a reason when nothing is recording', () => {+ const realm = fakeRealm({}, { timings: () => ({ systems: null, phases: null }) });+ const out = readSystems(realm);+ expect(out.systems).toBeNull();+ expect(out.note).toMatch(/not being recorded/);+ });++ it('says nothing extra when it IS recording', () => {+ const realm = fakeRealm({}, { timings: () => ({ systems: new Map(), phases: new Map() }) });+ expect(readSystems(realm)).not.toHaveProperty('note');+ });+});++describe('a value too large to send', () => {+ // Cut at a byte offset by the transport, a caller is left holding half a JSON+ // document with no way to tell which field went missing. Cut per value, and+ // the one that was cut is the one that says so.+ it('stands in for the big one and leaves its neighbours whole', () => {+ const realm = fakeRealm({+ 1: {+ name: 'Level',+ components: {+ Transform: { x: 1 },+ TilemapLayer: { tiles: Array.from({ length: MAX_VALUE_JSON }, (_, i) => i) },+ },+ },+ });+ const components = inspectEntity(realm, 1).components;+ expect(components.Transform).toEqual({ x: 1 });+ expect(components.TilemapLayer).toMatchObject({ truncated: true, keys: ['tiles'] });+ });++ it('leaves anything that fits exactly as it was', () => {+ expect(bounded({ x: 1 })).toEqual({ x: 1 });+ });++ it('says so rather than throwing on something that will not serialise', () => {+ const cyclic: Record<string, unknown> = {};+ cyclic.self = cyclic;+ expect(bounded(cyclic)).toEqual({ unserializable: true });+ });+});