Skip to content

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.

test(residency): what exists in a packaged streamed world, and what leaves with it

esengineab98f0cbf0fe
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index c87e4cc3c..76f73681d 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -623,6 +623,13 @@ jobs:
- name: Drive the third-person character in its package
run: node tools/verify-third-person.mjs
+ # Which places EXIST in that package, and what leaves with them. A camera
+ # cannot answer this: a cell that is not drawn and a cell that is not there
+ # look the same, and a body an unload forgot is invisible until someone
+ # walks into it.
+ - name: Drive a streamed world in its package
+ run: node tools/verify-world-residency.mjs
+
# The same game packaged twice from one tree, compiled and interpreted, and
# the two frames held against each other — the only check that sees what a
# compiled system does to a PIXEL.
diff --git a/examples/world-streaming-3d/assets/scenes/main.esscene b/examples/world-streaming-3d/assets/scenes/main.esscene
index dfe886550..7353a02ed 100644
--- a/examples/world-streaming-3d/assets/scenes/main.esscene
+++ b/examples/world-streaming-3d/assets/scenes/main.esscene
@@ -593,7 +593,7 @@
"position": {
"x": 1500,
"y": 40,
- "z": 300
+ "z": 100
},
"scale": {
"x": 2,
diff --git a/examples/world-streaming-3d/src/main.ts b/examples/world-streaming-3d/src/main.ts
index ffc97901e..6065f831a 100644
--- a/examples/world-streaming-3d/src/main.ts
+++ b/examples/world-streaming-3d/src/main.ts
@@ -54,8 +54,13 @@ let remembered = 0;
const staleBlowSystem = defineSystem(
[Res(Input), GetWorld(), EventWriter(Damage)],
(input: InputState, world: World, damage: EventWriterInstance<DamagePayload>) => {
- const enemy = world.findEntityByName('Enemy');
- if (enemy !== null) remembered = enemy;
+ // Remembered ONCE. Refreshing it every frame is how a test for a stale
+ // handle quietly becomes a test for a live one: after the cell comes back
+ // the name resolves again, to a different entity.
+ if (remembered === 0) {
+ const enemy = world.findEntityByName('Enemy');
+ if (enemy !== null) remembered = enemy;
+ }
if (!input.isKeyPressed('KeyJ') || remembered === 0) return;
const player = world.findEntityByName('Player') ?? 0;
const canary = world.findEntityByName('Canary');
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 613b81467..206bf62e3 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -10103,6 +10103,7 @@ desiredCells: string[]
loadCount: number
loadingCells: string[]
persistentEntities: number
+persistentHandles: number[]
residentCells: string[]
sourceCount: number
streamed: boolean
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index fc6cf8551..6d180509d 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -10296,6 +10296,7 @@ desiredCells: string[]
loadCount: number
loadingCells: string[]
persistentEntities: number
+persistentHandles: number[]
residentCells: string[]
sourceCount: number
streamed: boolean
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index fa76f9a18..fa392e98f 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -10098,6 +10098,7 @@ desiredCells: string[]
loadCount: number
loadingCells: string[]
persistentEntities: number
+persistentHandles: number[]
residentCells: string[]
sourceCount: number
streamed: boolean
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 295c8b01b..abe8bf734 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -10350,6 +10350,7 @@ desiredCells: string[]
loadCount: number
loadingCells: string[]
persistentEntities: number
+persistentHandles: number[]
residentCells: string[]
sourceCount: number
streamed: boolean
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 6f2781216..84b85633a 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -10126,6 +10126,7 @@ desiredCells: string[]
loadCount: number
loadingCells: string[]
persistentEntities: number
+persistentHandles: number[]
residentCells: string[]
sourceCount: number
streamed: boolean
diff --git a/sdk/src/residency/report.ts b/sdk/src/residency/report.ts
index 9e72d3354..65cae31d6 100644
--- a/sdk/src/residency/report.ts
+++ b/sdk/src/residency/report.ts
@@ -46,6 +46,8 @@ export interface WorldResidencyReport {
cellHandles: Record<string, number[]>;
/** Live entities the persistent world owns; residency never touches these. */
persistentEntities: number;
+ /** Their handles. Unchanged for the life of the world — that is the claim. */
+ persistentHandles: number[];
}
const EMPTY: WorldResidencyReport = {
@@ -53,7 +55,8 @@ const EMPTY: WorldResidencyReport = {
desiredCells: [], residentCells: [], loadingCells: [], unloadingCells: [],
loadCount: 0, unloadCount: 0,
cellEntityCounts: {}, cellRenderCounts: {}, assetRefsByCell: {},
- authoredCellEntityCounts: {}, cellStableIds: {}, cellHandles: {}, persistentEntities: 0,
+ authoredCellEntityCounts: {}, cellStableIds: {}, cellHandles: {},
+ persistentEntities: 0, persistentHandles: [],
};
/**
@@ -98,6 +101,7 @@ export function worldResidencyReport(app: App): WorldResidencyReport {
assetRefsByCell[cell.name] = scenes.assetScopeFor(cell.name)?.size ?? 0;
}
+ const persistent = [...(scenes.getScene(manifest.scene)?.entities ?? [])].sort((a, b) => a - b);
return {
streamed: true,
cellCount: status.cellCount,
@@ -110,6 +114,7 @@ export function worldResidencyReport(app: App): WorldResidencyReport {
unloadCount: status.unloadCount,
cellEntityCounts, cellRenderCounts, assetRefsByCell, authoredCellEntityCounts,
cellStableIds, cellHandles,
- persistentEntities: scenes.getScene(manifest.scene)?.entities.size ?? 0,
+ persistentEntities: persistent.length,
+ persistentHandles: persistent,
};
}
diff --git a/tools/check-residency-authority.mjs b/tools/check-residency-authority.mjs
new file mode 100644
index 000000000..d1ce5697b
--- /dev/null
+++ b/tools/check-residency-authority.mjs
@@ -0,0 +1,105 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file check-residency-authority.mjs — existence has one author.
+ *
+ * Residency decides what is in the world. The moment a second thing can decide
+ * it — a renderer that loads a place to draw it, a report that reconciles while
+ * reading, gameplay calling loadCell — the answer to "why does this entity
+ * exist" stops having one owner, and every lifetime bug after that is a bug
+ * about who asked. None of that is stopped by the language, so it is checked.
+ *
+ * node tools/check-residency-authority.mjs
+ */
+import { readFileSync, readdirSync, existsSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const RESIDENCY = path.join(ROOT, 'sdk', 'src', 'residency');
+const read = (rel) => readFileSync(path.join(ROOT, rel), 'utf8');
+
+/**
+ * Who may name the residency resource, and why. A file not here that reaches for
+ * it is a second author, which is the whole thing this file exists to refuse.
+ */
+const MAY_NAME_THE_STREAMER = {
+ 'sdk/src/core-content.ts': 'the public surface exports it',
+ 'sdk/src/runtime/runtimeLoader.ts': 'adopts the cooked manifest once the persistent scene is up',
+};
+
+const problems = [];
+const say = (file, what) => problems.push(`${file}: ${what}`);
+
+// 1. The decision is pure. A module that can reach a loader is a module that can
+// load, and then "which cells should exist" and "bring one in" are one thing.
+const cells = read('sdk/src/residency/cells.ts');
+const imports = [...cells.matchAll(/^\s*import\b[^;]*;/gm)].map((m) => m[0]);
+if (imports.length > 0) {
+ say('sdk/src/residency/cells.ts',
+ `the residency decision imports ${imports.length} module(s) — it answers from geometry alone`);
+}
+
+const streamer = read('sdk/src/residency/WorldStreamer.ts');
+
+// 2. Unloading is a real destroy. A flag looks the same from a camera and is the
+// difference between a place being gone and a place being invisible.
+for (const flag of ['sleep(', 'wake(', 'Disabled', 'setEntityVisible', '.visible =']) {
+ if (streamer.includes(flag)) {
+ say('sdk/src/residency/WorldStreamer.ts',
+ `unloading reaches for "${flag}" — a cell leaves by being destroyed, not hidden`);
+ }
+}
+
+// 3. …and takes what the cell brought. Scene persistence answers a different
+// question, and honouring it here leaves exactly what residency removes.
+if (!/keepPersistent:\s*false/.test(streamer)) {
+ say('sdk/src/residency/WorldStreamer.ts',
+ 'a cell is unloaded without keepPersistent: false, so something it brought can survive it');
+}
+
+// 4. One author. Everything else may READ the report.
+for (const dir of ['sdk/src', 'pipeline/src']) {
+ for (const file of walk(path.join(ROOT, dir))) {
+ const rel = path.relative(ROOT, file).split(path.sep).join('/');
+ if (rel.startsWith('sdk/src/residency/')) continue;
+ const text = readFileSync(file, 'utf8');
+ if (!/\bWorldStreaming\b(?!Source)/.test(text)) continue;
+ if (!(rel in MAY_NAME_THE_STREAMER)) {
+ say(rel, 'names the residency resource — declare why in MAY_NAME_THE_STREAMER or read the report instead');
+ }
+ }
+}
+
+// 5. One place installs it, so there is one schedule slot residency runs in.
+const installs = [...walk(path.join(ROOT, 'sdk', 'src'))].filter((file) =>
+ /addSystemToSchedule\([^)]*worldResidencySystem/.test(readFileSync(file, 'utf8')));
+if (installs.length !== 1) {
+ say('sdk/src', `${installs.length} place(s) schedule the residency system — exactly one may`);
+}
+
+// 6. Reading residency cannot change it. A report that reconciled would make
+// what exists depend on who looked.
+const report = read('sdk/src/residency/report.ts');
+for (const mutator of ['.update(', '.loadManifest(', '.clear(']) {
+ if (report.includes(mutator)) {
+ say('sdk/src/residency/report.ts', `the report calls "${mutator}" — reading must not reconcile`);
+ }
+}
+
+function* walk(dir) {
+ if (!existsSync(dir)) return;
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue;
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) yield* walk(full);
+ else if (/\.ts$/.test(entry.name)) yield full;
+ }
+}
+
+if (problems.length > 0) {
+ for (const problem of problems) console.error(` ${problem}`);
+ console.error(`check-residency-authority: ${problems.length} finding(s).`);
+ process.exit(1);
+}
+console.log('check-residency-authority: one author decides what exists, and unloading destroys.');
diff --git a/tools/gates.mjs b/tools/gates.mjs
index 2129f196e..014f4065b 100644
--- a/tools/gates.mjs
+++ b/tools/gates.mjs
@@ -78,6 +78,7 @@ export const GATES = [
// has no snapshot to enforce, so what is enforced there is the ANSWER: that it
// is experimental, said the same way in every place someone reads it.
{ id: 'plugin-api-contract', run: 'node tools/check-plugin-api-contract.mjs' },
+ { id: 'residency-authority', run: 'node tools/check-residency-authority.mjs' },
// Everything below reads what this emits: the declaration snapshot, the
// editor's own type-check and the examples all resolve `esengine` from dist.
{ id: 'sdk-build', run: 'pnpm --filter ./sdk build' },
diff --git a/tools/goldenProjects.mjs b/tools/goldenProjects.mjs
index dac9ed5bd..4491822a4 100644
--- a/tools/goldenProjects.mjs
+++ b/tools/goldenProjects.mjs
@@ -53,7 +53,7 @@ export const CAPABILITIES = [
'ui-layout', 'text', 'localization',
'spine', 'material', 'asset-lifecycle',
'model-import', 'model-animation', 'model-skinning',
- 'physics-3d', 'mesh-shadow', 'environment', 'level-of-detail',
+ 'physics-3d', 'mesh-shadow', 'environment', 'level-of-detail', 'world-streaming',
'tilemap', 'tile-collision',
'touch', 'safe-area', 'pause-resume',
'texture-atlas',
@@ -98,6 +98,9 @@ export const EVIDENCE = {
'physics-3d': /\b(RigidBody3D|CharacterController3D|BoxCollider3D|MeshCollider3D)\b/,
'mesh-shadow': /\bmeshShadows\b/,
'level-of-detail': /\bLODGroup\b/,
+ // The declarations, not the streamer: a project EXERCISES residency by saying
+ // its world is cut and by carrying something that asks for places.
+ 'world-streaming': /\b(StreamedWorld|WorldStreamingSource)\b/,
environment: /\.esenv\b/,
'asset-lifecycle': /\b(Assets|loadGroup|releaseGroup|preload)\b/,
tilemap: /\bTilemap(Layer)?\b/,
@@ -240,6 +243,15 @@ export const GOLDEN = [
// something moved, not that the world allowed it.
interact: { keys: ['KeyW'], frames: 60 },
},
+ {
+ id: 'world-streaming-3d',
+ certifies: ['world-streaming'],
+ targets: ['web'],
+ tier: 'pr',
+ // Walking is what makes a place exist here, so the frame after 60 frames of
+ // it differs by more than a character moving — a cell came in.
+ interact: { keys: ['KeyD'], frames: 60 },
+ },
{
id: 'ui-controls',
certifies: ['ui-layout', 'text'],
diff --git a/tools/launchers/residency-run.mjs b/tools/launchers/residency-run.mjs
index 99cd3dd9c..0f64cd3da 100644
--- a/tools/launchers/residency-run.mjs
+++ b/tools/launchers/residency-run.mjs
@@ -149,6 +149,26 @@ async function main() {
}
const where = async () => (await exec(`window.__estellaCooked.probe(${JSON.stringify(['Player'])})`)).at.Player;
+
+ /**
+ * Let residency finish what the last gesture asked for.
+ *
+ * A cell arrives over the network, so the frames a driver asks for are not the
+ * thing it is waiting on: reading straight after a step reports a place that is
+ * still `loading`, which is neither "here" nor "not asked for".
+ */
+ const settle = async (tries = 150) => {
+ for (let i = 0; i < tries; i++) {
+ const s = await exec('window.__estellaCooked.streaming()');
+ if (!s.streamed) return true;
+ if (s.loadingCells.length === 0 && s.unloadingCells.length === 0) return true;
+ await exec(holdScript([], 2));
+ await new Promise((r) => setTimeout(r, 20));
+ }
+ console.log(' ! residency never settled');
+ return false;
+ };
+
const read = async () => ({
streaming: await exec('window.__estellaCooked.streaming()'),
at: (await exec(`window.__estellaCooked.probe(${JSON.stringify(NAMES)})`)).at,
@@ -191,6 +211,7 @@ async function main() {
for (const step of steps) {
if (step.do === 'read') {
+ await settle();
console.log(`reading ${step.as}: ${JSON.stringify(await read())}`);
continue;
}
diff --git a/tools/verify-world-residency.mjs b/tools/verify-world-residency.mjs
new file mode 100644
index 000000000..2a43cf55d
--- /dev/null
+++ b/tools/verify-world-residency.mjs
@@ -0,0 +1,255 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file verify-world-residency.mjs — a place exists because someone is near it.
+ *
+ * The unit criteria hold the decision: the union over sources, the hysteresis
+ * band, what the cook cuts and what it refuses. What they cannot say is whether
+ * a cell LEAVING the world takes everything it brought — the renderer's
+ * instances, the physics body, the navigating agent, the asset receipts — and
+ * that is the whole feature. So this drives the real package: real cooked cells,
+ * real Jolt, real navigation, real input.
+ *
+ * Four launches, because a claim about what boot produced cannot be made after
+ * something walked, and a wall that blocks cannot be un-walked into.
+ *
+ * The scene is `world-streaming-3d`, and it is a FIXTURE: its cell size, radii
+ * and coordinates answer to these claims and nothing else.
+ */
+import { spawnSync } from 'node:child_process';
+import { rmSync, mkdirSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { runElectron } from './lib/electronRun.mjs';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const WORK = path.join(ROOT, '.golden', 'world-residency');
+const PROJECT = path.join(ROOT, 'examples', 'world-streaming-3d');
+const LAUNCHER = path.join(ROOT, 'tools', 'launchers', 'residency-run.mjs');
+
+const A = 'main.cell_0_0';
+const B = 'main.cell_1_0';
+const C = 'main.cell_2_0';
+const D = 'main.cell_0_5';
+
+function packageGame() {
+ rmSync(WORK, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
+ mkdirSync(WORK, { recursive: true });
+ const out = path.join(WORK, 'web');
+ const r = spawnSync(process.execPath, [
+ path.join(ROOT, 'pipeline', 'bin', 'estella.mjs'), 'export', PROJECT,
+ '--platform', 'web', '--out', out,
+ ], { encoding: 'utf8', cwd: ROOT });
+ if (r.status !== 0) {
+ console.error('✗ world-residency: the package did not build');
+ for (const l of `${r.stderr ?? ''}${r.stdout ?? ''}`.split('\n').slice(-8)) {
+ if (l.trim()) console.error(` ${l}`);
+ }
+ process.exit(1);
+ }
+ return out;
+}
+
+/** Run one script against the package and return every labelled reading. */
+function drive(dir, name, steps) {
+ const script = path.join(WORK, `${name}.json`);
+ writeFileSync(script, JSON.stringify(steps, null, 2));
+ const r = runElectron([
+ LAUNCHER, '--dir', dir, '--script', script, '--w', '640', '--h', '360',
+ ], { encoding: 'utf8', cwd: ROOT });
+ const readings = {};
+ for (const line of (r.stdout || '').split('\n')) {
+ const at = line.indexOf('reading ');
+ if (at < 0) continue;
+ const label = line.slice(at + 8, line.indexOf(':', at));
+ try {
+ readings[label] = JSON.parse(line.slice(line.indexOf('{', at)));
+ } catch { /* a truncated line is a missing reading, reported below */ }
+ }
+ if (Object.keys(readings).length === 0) {
+ console.error(`✗ ${name}: no readings — ${(r.stdout || r.stderr || '').trim().slice(-300)}`);
+ process.exit(1);
+ }
+ return readings;
+}
+
+const results = [];
+function claim(ok, text, detail) {
+ results.push({ ok, text, detail });
+ console.log(`${ok ? '✓' : '✗'} ${text}${detail ? ` — ${detail}` : ''}`);
+}
+
+const resident = (r, cell) => r.streaming.residentCells.includes(cell);
+const entities = (r, cell) => r.streaming.cellEntityCounts[cell];
+const authored = (r, cell) => r.streaming.authoredCellEntityCounts[cell];
+/** An entity handle's slot, so a criterion can say whether one was REUSED. */
+const slot = (handle) => handle & 0xFFFFF;
+
+function main() {
+ const dir = packageGame();
+
+ // ---- 1. What boot produced, before anything walked -------------------
+ const start = drive(dir, 'residency', [
+ { do: 'step', frames: 30 },
+ { do: 'read', as: 'initial' },
+ { do: 'tap', key: 'KeyL', frames: 30 },
+ { do: 'read', as: 'scoutOn' },
+ { do: 'tap', key: 'KeyL', frames: 30 },
+ { do: 'read', as: 'scoutOff' },
+ { do: 'tap', key: 'KeyM', frames: 420 },
+ { do: 'read', as: 'bobbed' },
+ ]);
+
+ const initial = start.initial;
+ claim(initial.streaming.streamed && initial.streaming.cellCount === 4,
+ 'the package ships a cut world', `${initial.streaming.cellCount} cells`);
+ claim(resident(initial, A) && !resident(initial, C) && !resident(initial, D),
+ 'only the place the player stands in is resident',
+ `resident ${JSON.stringify(initial.streaming.residentCells)}`);
+ // Not drawn and not there are different things, and only one of them is this.
+ claim(entities(initial, C) === undefined && initial.at.Arch === undefined
+ && (initial.streaming.cellRenderCounts[C] ?? 0) === 0,
+ 'a cell nobody needs has no entities, no renderers and nothing to probe');
+
+ // ---- 6. Two sources are unioned --------------------------------------
+ const scoutOn = start.scoutOn;
+ claim(scoutOn.streaming.sourceCount === 2 && resident(scoutOn, A) && resident(scoutOn, C),
+ 'a second source brings its own place in without taking the first away',
+ `${scoutOn.streaming.sourceCount} sources, resident ${JSON.stringify(scoutOn.streaming.residentCells)}`);
+ claim(scoutOn.at.Arch !== undefined && scoutOn.at.ArchTop !== undefined,
+ 'and that place arrived whole');
+ const scoutOff = start.scoutOff;
+ claim(!resident(scoutOff, C) && resident(scoutOff, A),
+ 'switching it off gives up only what no source still needs',
+ `resident ${JSON.stringify(scoutOff.streaming.residentCells)}`);
+
+ // ---- 5. A boundary is a band, not a treadmill ------------------------
+ const bobbed = start.bobbed;
+ const loads = bobbed.streaming.loadCount - scoutOff.streaming.loadCount;
+ const unloads = bobbed.streaming.unloadCount - scoutOff.streaming.unloadCount;
+ claim(resident(bobbed, D) && loads === 1 && unloads === 0,
+ 'a source breathing across a boundary loads the place once and keeps it',
+ `${loads} load(s), ${unloads} unload(s) over 420 frames`);
+
+ // ---- 2/3/4/7/8. The journey ------------------------------------------
+ const trip = drive(dir, 'journey', [
+ { do: 'step', frames: 30 },
+ { do: 'read', as: 'atA' },
+ { do: 'walkTo', x: 900, z: 300, budget: 900 },
+ { do: 'read', as: 'atB' },
+ { do: 'walkTo', x: 1750, z: 300, budget: 1200 },
+ { do: 'read', as: 'atC' },
+ { do: 'walkTo', x: 900, z: 300, budget: 1200 },
+ { do: 'read', as: 'backAtB' },
+ ]);
+
+ const atB = trip.atB;
+ claim(resident(atB, B) && entities(atB, B) === authored(atB, B) && atB.at.Enemy !== undefined,
+ 'walking into a place instantiates everything the cook put in it',
+ `${entities(atB, B)}/${authored(atB, B)} entities`);
+ claim(atB.streaming.physicsCharacters >= 2 && atB.streaming.navAgents === 1
+ && atB.streaming.hunters === 1,
+ 'and its enemy arrives as a physical, navigating, deciding thing',
+ `${atB.streaming.physicsCharacters} characters, ${atB.streaming.navAgents} agent(s)`);
+ claim(atB.ai.found && (atB.ai.visible || atB.ai.hasTarget),
+ 'which then notices the player it was not told about',
+ `visible=${atB.ai.visible} hasTarget=${atB.ai.hasTarget}`);
+
+ const atC = trip.atC;
+ claim(!resident(atC, B) && entities(atC, B) === undefined && atC.at.Enemy === undefined
+ && atC.at.Wall === undefined,
+ 'leaving takes the place with it — every entity, not the picture of them',
+ `resident ${JSON.stringify(atC.streaming.residentCells)}`);
+ claim(atC.streaming.navAgents === 0 && atC.streaming.hunters === 0
+ && atC.streaming.stalePhysics === 0,
+ 'no agent, no hunter and no physics row outlives the cell that brought it',
+ `${atC.streaming.stalePhysics} stale physics row(s)`);
+ claim((atC.streaming.assetRefsByCell[B] ?? 0) === 0,
+ 'and the cell owes nothing for the assets it acquired');
+
+ // ---- 8. A subtree is the residency atom ------------------------------
+ claim(atC.at.Arch !== undefined && atC.at.ArchTop !== undefined
+ && Math.abs(atC.at.ArchTop.x - 1900) < 1,
+ 'a child standing in another cell comes in with its root, not with its own place',
+ `ArchTop at x=${atC.at.ArchTop?.x?.toFixed(0)}`);
+ claim(trip.atA.at.ArchTop === undefined && atB.at.ArchTop === undefined,
+ 'and is gone whenever its root is');
+
+ // ---- 4. Coming back produces ONE of everything -----------------------
+ const back = trip.backAtB;
+ claim(resident(back, B) && entities(back, B) === authored(back, B)
+ && back.streaming.hunters === 1 && back.streaming.navAgents === 1,
+ 'coming back builds the place once, not twice',
+ `${entities(back, B)}/${authored(back, B)} entities, ${back.streaming.hunters} hunter(s)`);
+ const sameRows = JSON.stringify(back.streaming.cellStableIds[B])
+ === JSON.stringify(atB.streaming.cellStableIds[B]);
+ const newHandles = JSON.stringify(back.streaming.cellHandles[B])
+ !== JSON.stringify(atB.streaming.cellHandles[B]);
+ claim(sameRows && newHandles,
+ 'with the same authored rows and different runtime handles',
+ `rows ${JSON.stringify(back.streaming.cellStableIds[B])}`);
+
+ // ---- 7. The persistent world is not rebuilt --------------------------
+ const persistent = JSON.stringify(trip.atA.streaming.persistentHandles);
+ claim([atB, atC, back].every((r) => JSON.stringify(r.streaming.persistentHandles) === persistent),
+ 'nothing the world is made of was rebuilt along the way',
+ `${trip.atA.streaming.persistentEntities} persistent entities`);
+
+ // ---- 9. A wall that unloaded is not still there ----------------------
+ const ghost = drive(dir, 'ghost', [
+ { do: 'step', frames: 30 },
+ { do: 'walkTo', x: 900, z: 300, budget: 900 },
+ { do: 'read', as: 'approach' },
+ { do: 'walkTo', x: 900, z: 760, budget: 400 },
+ { do: 'read', as: 'blocked' },
+ { do: 'tap', key: 'KeyK', frames: 60 },
+ { do: 'read', as: 'sourceOff' },
+ { do: 'walkTo', x: 900, z: 760, budget: 400 },
+ { do: 'read', as: 'through' },
+ ]);
+ claim(ghost.approach.at.Wall !== undefined && ghost.blocked.at.Player.z < 440,
+ 'a wall the cell brought stops the player',
+ `stopped at z=${ghost.blocked.at.Player.z.toFixed(0)}`);
+ claim(ghost.sourceOff.streaming.sourceCount === 0
+ && ghost.sourceOff.streaming.residentCells.length === 0
+ && ghost.sourceOff.at.Wall === undefined
+ && ghost.sourceOff.streaming.stalePhysics === 0,
+ 'with nobody asking, every place leaves and leaves no body behind');
+ claim(ghost.through.at.Player.z > 520,
+ 'and the player walks through where the wall was',
+ `reached z=${ghost.through.at.Player.z.toFixed(0)}`);
+
+ // ---- 10. A blow aimed at what is gone -------------------------------
+ const stale = drive(dir, 'stale', [
+ { do: 'step', frames: 30 },
+ { do: 'walkTo', x: 900, z: 300, budget: 900 },
+ { do: 'read', as: 'met' },
+ { do: 'walkTo', x: 1750, z: 300, budget: 1200 },
+ { do: 'read', as: 'gone' },
+ { do: 'walkTo', x: 900, z: 300, budget: 1200 },
+ { do: 'read', as: 'back' },
+ { do: 'tap', key: 'KeyJ', frames: 30 },
+ { do: 'read', as: 'blown' },
+ ]);
+ const before = stale.met.streaming.cellHandles[B] ?? [];
+ const after = stale.back.streaming.cellHandles[B] ?? [];
+ const reused = before.some((h) => after.some((n) => slot(n) === slot(h) && n !== h));
+ claim(stale.gone.at.Enemy === undefined && after.length === before.length,
+ 'the enemy a blow was aimed at really did stop existing');
+ claim(stale.blown.combat.targets.Canary.health < 100,
+ 'the gesture reached the damage bus',
+ `canary at ${stale.blown.combat.targets.Canary.health}`);
+ claim(stale.blown.combat.targets.Enemy.health === stale.blown.combat.targets.Enemy.max,
+ 'and the blow held for the entity that left landed on nobody',
+ `enemy at ${stale.blown.combat.targets.Enemy.health}, slot reused: ${reused}`);
+ // Without a reused slot the claim above is true for a duller reason, so say so.
+ if (!reused) {
+ console.log(' note: no handle slot was recycled in this run — the claim is weaker than it reads');
+ }
+
+ const failed = results.filter((r) => !r.ok).length;
+ console.log(`\nworld-residency: ${results.length - failed}/${results.length}`);
+ process.exit(failed === 0 ? 0 : 1);
+}
+
+main();