A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(abi): ES_CONST, and two more hand-copied boundary constants
yhhfac3208f7852
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ac6020314..4c1432a70 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -49,6 +49,33 @@ published separately; it ships inside the editor.### Fixed+- **Two more hand-copied boundary constants, and a way to stop the next one.**+ The tile cell encoding (13-bit id, three flip bits, the chunk stride) and the+ particle colour LUT size were each written once in C++ and again in TypeScript,+ tied only by a test. Neither fails when it drifts: a wrong mask decodes a stored+ cell into a **different tile**, and a wrong LUT size over- or under-runs a+ fixed-size upload.++ `ES_CONST` marks a constant that crosses, beside `ES_COMPONENT` and `ES_ENUM`.+ EHT scans for it — found by scanning, not from a list, because a list of what to+ extract is the thing that goes stale — and emits+ `sdk/src/wasm/constants.generated.ts`, which the two TS files now re-export. The+ values join the ABI layout hash, so a binary and a bundle built from different+ ones refuse each other at `connect()`. `ABI_LAYOUT_HASH` changes: rebuild the+ engine.++ A marker the extractor cannot read is a **hard failure**, not a skip: a silently+ ungenerated constant is exactly the drift this exists to stop. Two headers+ claiming one TS name is refused for the same reason. And EHT's build cache now+ hashes every header it reads rather than the component directory alone —+ otherwise editing a constant is answered with "no changes detected" and the old+ value stays in the hash.++ What is still owed is written down: the hash pairs a **binary** with a+ **bundle**, and says nothing about a **saved map**. Widening the id mask still+ reads every older `.esscene` into the wrong cells; that half needs a format+ version of its own.+- **The entity split had two authors and no handshake.** A handle crosses theboundary as a bare `u32`, so a side that disagrees about where the index endsdoes not fail — it decodes to **another entity's** index and the frame is merelydiff --git a/build-tools/build.config.js b/build-tools/build.config.jsindex d9d36dafe..d2e9f883d 100644--- a/build-tools/build.config.js+++ b/build-tools/build.config.js@@ -214,6 +214,7 @@ export default {eht: {inputDir: 'src/esengine/ecs/components',entityHeader: 'src/esengine/core/Types.hpp',+ constRoots: ['src/esengine'],outputDir: 'src/esengine/bindings',tsOutputDir: 'sdk/src',script: 'tools/eht.py',diff --git a/build-tools/tasks/eht.js b/build-tools/tasks/eht.jsindex 8a8804dc0..9006db8d0 100644--- a/build-tools/tasks/eht.js+++ b/build-tools/tasks/eht.js@@ -16,7 +16,7 @@ export async function runEht(options = {}) {const inputDir = path.join(rootDir, config.eht.inputDir);const script = path.join(rootDir, config.eht.script);- const componentFiles = await getComponentFiles(inputDir);+ const componentFiles = await getHeaderFiles(inputDir);if (componentFiles.length === 0) {logger.warn('No component files found');@@ -35,11 +35,15 @@ export async function runEht(options = {}) {const cache = new HashCache(config.paths.cache);await cache.load();- // The entity split comes from core/Types.hpp, which is NOT under the- // component directory — leaving it out means editing the split and being- // told "no changes detected", with the old split still in the hash.- const entityHeader = path.join(rootDir, config.eht.entityHeader);- const allFiles = [script, entityHeader, ...generatorFiles, ...componentFiles];+ // EVERY header EHT reads, not just the component directory: the entity+ // split is in core/Types.hpp and an ES_CONST can be anywhere. One left out+ // is "no changes detected" with the old value still in the ABI hash.+ const boundaryHeaders = (await Promise.all(+ config.eht.constRoots.map((r) => getHeaderFiles(path.join(rootDir, r))),+ )).flat();+ const allFiles = [script, ...generatorFiles, ...new Set([+ ...componentFiles, ...boundaryHeaders, path.join(rootDir, config.eht.entityHeader),+ ])];const currentHash = await hashFiles(allFiles);if (!await cache.isChanged('eht', currentHash)) {@@ -62,7 +66,7 @@ export async function runEht(options = {}) {return { skipped: false };}-async function getComponentFiles(inputDir) {+async function getHeaderFiles(inputDir) {const files = [];try {const { readdir, stat } = await import('fs/promises');@@ -124,6 +128,7 @@ async function executeEht(rootDir, script) {// Passed rather than left to the generator's default: the path the cache// hashes and the path the generator reads must be one path.'--entity-header', path.join(rootDir, config.eht.entityHeader),+ '--const-root', ...config.eht.constRoots.map((r) => path.join(rootDir, r)),'--output', outputDir,'--ts-output', tsOutputDir,], {diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex e26ea0916..35de63b0e 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -5,7 +5,7 @@ Symbols: 113 public · 84 beta · 1514 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```-"077eebc0e561321f"+"9bc45f6f2153c7c6"```## ANCHOR_AXES — const @experimentaldiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 234eee152..af86839e4 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -5,7 +5,7 @@ Symbols: 113 public · 89 beta · 1533 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```-"077eebc0e561321f"+"9bc45f6f2153c7c6"```## ANCHOR_AXES — const @experimentaldiff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.tsindex d423da795..ba296656c 100644--- a/sdk/src/ecs/component.generated.ts+++ b/sdk/src/ecs/component.generated.ts@@ -15,7 +15,7 @@ import type { AlignContent, AlignItems, AlignSelf, BodyType, CanvasScaleMode, Cl* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to* run on mismatch, because mismatched offsets read the wrong heap bytes.*/-export const ABI_LAYOUT_HASH = '077eebc0e561321f';+export const ABI_LAYOUT_HASH = '9bc45f6f2153c7c6';/*** One asset-valued field of a component: which field, and what kind ofdiff --git a/sdk/src/particle/gradient.ts b/sdk/src/particle/gradient.tsindex 0d8d4b555..09f8a4b0d 100644--- a/sdk/src/particle/gradient.ts+++ b/sdk/src/particle/gradient.ts@@ -7,6 +7,8 @@* C++ particle sim samples by normalized particle age. Curve math lives* here (TS) only — the runtime just indexes the baked table.*/++import { GRADIENT_LUT_SIZE } from '../wasm/constants.generated';import type { Color } from '../types';export interface GradientStop {@@ -19,8 +21,12 @@ export interface Gradient {stops: GradientStop[];}-/** LUT resolution — MUST match the C++ `particle::kColorLutSize`. */-export const GRADIENT_LUT_SIZE = 32;+/**+ * LUT resolution, from the C++ `kColorLutSize` that owns it. The baked gradient+ * is uploaded as a flat `n * 4` float array, so a second answer here over- or+ * under-runs the C++ `ColorLut` rather than failing.+ */+export { GRADIENT_LUT_SIZE };function sampleGradient(sorted: GradientStop[], t: number): Color {const first = sorted[0];diff --git a/sdk/src/tilemap/chunkCodec.ts b/sdk/src/tilemap/chunkCodec.tsindex f412c2c03..2cf218e28 100644--- a/sdk/src/tilemap/chunkCodec.ts+++ b/sdk/src/tilemap/chunkCodec.ts@@ -9,8 +9,14 @@* (CHUNK_SIZE = 16; empty chunks are omitted by the exporter.)*/-/** Tiles per chunk side (mirrors C++ `tilemap::CHUNK_SIZE`). */-export const CHUNK_SIZE = 16;+import { CHUNK_SIZE } from '../wasm/constants.generated';++/**+ * Tiles per chunk side, from the C++ `CHUNK_SIZE` that owns it. Generated, so+ * this is not a second answer: a chunk decoded at the wrong side length reads a+ * saved map into the wrong cells rather than failing to load.+ */+export { CHUNK_SIZE };const CHUNK_TILES = CHUNK_SIZE * CHUNK_SIZE;const ESTM_MAGIC = 0x4d545345;diff --git a/sdk/src/tilemap/tileBits.ts b/sdk/src/tilemap/tileBits.tsindex 4740a2703..ac1fafb4a 100644--- a/sdk/src/tilemap/tileBits.ts+++ b/sdk/src/tilemap/tileBits.ts@@ -12,11 +12,17 @@* corner permutation — keep the base perms below byte-identical with the C++ side.*/-/** Mirrors C++ `tilemap::TILE_ID_MASK` — 13 bits, max id 8191. */-export const TILE_ID_MASK = 0x1fff;-export const TILE_FLIP_H = 0x2000;-export const TILE_FLIP_V = 0x4000;-export const TILE_FLIP_D = 0x8000;+import {+ TILE_ID_MASK, TILE_FLIP_H, TILE_FLIP_V, TILE_FLIP_D,+} from '../wasm/constants.generated';++/**+ * The cell encoding, from the C++ declarations that own it — 13 bits of id, max+ * 8191, and three flip bits. Generated, so this is not a second answer, and in+ * the ABI layout hash, so a binary and a bundle built from different values+ * refuse each other rather than decoding each other's cells.+ */+export { TILE_ID_MASK, TILE_FLIP_H, TILE_FLIP_V, TILE_FLIP_D };export const TILE_FLAGS_MASK = TILE_FLIP_H | TILE_FLIP_V | TILE_FLIP_D;/** The three orientation bits a cell can carry (Tiled H/V/anti-diagonal). */diff --git a/sdk/src/wasm/constants.generated.ts b/sdk/src/wasm/constants.generated.tsnew file mode 100644index 000000000..0807aeb48--- /dev/null+++ b/sdk/src/wasm/constants.generated.ts@@ -0,0 +1,30 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file constants.generated.ts+ * @brief Boundary constants marked `ES_CONST` in the C++ headers+ * @details Generated by EHT - DO NOT EDIT+ *+ * Hand-copied, these do not fail when they drift — a wrong mask decodes a+ * stored cell into a different tile. They are in the ABI layout hash, so a+ * WASM binary and an SDK bundle built from different values refuse each+ * other rather than disagreeing quietly.+ */++/** C++ `CHUNK_SIZE` in `D:/estella/src/esengine/tilemap/TilemapSystem.hpp`. */+export const CHUNK_SIZE = 16;++/** C++ `kColorLutSize` in `D:/estella/src/esengine/particle/ParticleSystem.hpp`. */+export const GRADIENT_LUT_SIZE = 32;++/** C++ `TILE_FLIP_D` in `D:/estella/src/esengine/tilemap/TilemapSystem.hpp`. */+export const TILE_FLIP_D = 0x8000;++/** C++ `TILE_FLIP_H` in `D:/estella/src/esengine/tilemap/TilemapSystem.hpp`. */+export const TILE_FLIP_H = 0x2000;++/** C++ `TILE_FLIP_V` in `D:/estella/src/esengine/tilemap/TilemapSystem.hpp`. */+export const TILE_FLIP_V = 0x4000;++/** C++ `TILE_ID_MASK` in `D:/estella/src/esengine/tilemap/TilemapSystem.hpp`. */+export const TILE_ID_MASK = 0x1fff;diff --git a/sdk/tests/cpp-contract.test.ts b/sdk/tests/cpp-contract.test.tsindex e4c8760f9..a4fd0ce32 100644--- a/sdk/tests/cpp-contract.test.ts+++ b/sdk/tests/cpp-contract.test.ts@@ -140,8 +140,8 @@ describe('C++ contract: animation tween enums (animation/TweenData.hpp)', () =>describe('C++ contract: particle color LUT (particle/ParticleSystem.hpp)', () => {it('GRADIENT_LUT_SIZE === kColorLutSize', () => {- // The baked gradient is uploaded as a flat kColorLutSize*4 float array; a- // mismatch would over/under-run the C++ ColorLut on setColorGradient.+ // GENERATED from this header now, so this is a second parser of it:+ // what it catches is a stale projection or an extraction bug.const cpp = parseConst(readCpp('particle/ParticleSystem.hpp'), 'kColorLutSize');expect(GRADIENT_LUT_SIZE).toBe(cpp);});diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cppindex 77948fc0f..a8fa8ce09 100644--- a/src/esengine/bindings/WebBindings.generated.cpp+++ b/src/esengine/bindings/WebBindings.generated.cpp@@ -3070,7 +3070,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif// ABI Hash -- runtime handshake against the SDK bundle// =============================================================================-static const char* kEsAbiLayoutHash = "077eebc0e561321f";+static const char* kEsAbiLayoutHash = "9bc45f6f2153c7c6";std::string esengineGetAbiLayoutHash() {return std::string(kEsAbiLayoutHash);diff --git a/src/esengine/core/Reflection.hpp b/src/esengine/core/Reflection.hppindex b89fd71ec..fe0811e91 100644--- a/src/esengine/core/Reflection.hpp+++ b/src/esengine/core/Reflection.hpp@@ -118,6 +118,16 @@*/#define ES_ENUM(...)+/**+ * @brief Mark a constant that CROSSES the boundary, so EHT emits its TS twin+ *+ * @details Hand-copied, such a constant does not fail when it drifts — a wrong+ * mask decodes a stored cell into a different tile. Marked, it has one+ * author and joins the ABI layout hash. `ts=<Name>` renames the+ * generated symbol; `hex` emits the value as hex, for a mask.+ */+#define ES_CONST(...)+/*** @brief Mark an enum value for explicit naming in bindings*diff --git a/src/esengine/particle/ParticleSystem.hpp b/src/esengine/particle/ParticleSystem.hppindex f1abc253d..c551eb30b 100644--- a/src/esengine/particle/ParticleSystem.hpp+++ b/src/esengine/particle/ParticleSystem.hpp@@ -16,6 +16,7 @@#include <functional>#include <random>#include <array>+#include "../core/Reflection.hpp"namespace esengine { class RandomSource; }@@ -23,6 +24,7 @@ namespace esengine::particle {// Resolution of the per-emitter over-life lookup tables (baked in TS from a// gradient/curve, sampled here per particle). 32 keeps them smooth and small.+ES_CONST(ts=GRADIENT_LUT_SIZE)inline constexpr int kColorLutSize = 32;using ColorLut = std::array<glm::vec4, kColorLutSize>;// Size-over-life: a scalar multiplier curve × the particle's start size.diff --git a/src/esengine/tilemap/TilemapSystem.hpp b/src/esengine/tilemap/TilemapSystem.hppindex 188b55dd1..afc87db1e 100644--- a/src/esengine/tilemap/TilemapSystem.hpp+++ b/src/esengine/tilemap/TilemapSystem.hpp@@ -9,16 +9,22 @@#include <string>#include <unordered_map>#include <vector>+#include "../core/Reflection.hpp"namespace esengine {namespace tilemap {static constexpr u16 EMPTY_TILE = 0;+ES_CONST()static constexpr u32 CHUNK_SIZE = 16;+ES_CONST(hex)static constexpr u16 TILE_ID_MASK = 0x1FFF;+ES_CONST(hex)static constexpr u16 TILE_FLIP_H = 0x2000;+ES_CONST(hex)static constexpr u16 TILE_FLIP_V = 0x4000;+ES_CONST(hex)static constexpr u16 TILE_FLIP_D = 0x8000;enum class GridType : u8 {diff --git a/tools/contract-inventory.mjs b/tools/contract-inventory.mjsindex 1bb7a87bb..b5a119059 100644--- a/tools/contract-inventory.mjs+++ b/tools/contract-inventory.mjs@@ -131,9 +131,15 @@ for (const fact of FACTS) {+ ' and no `owed` says why that is accepted.');}// The debt is paid the day the gate says so, not the day someone remembers.- if (fact.owed && fact.digest && /no digest covers it/.test(fact.owed)) {- findings.push(`${fact.id}: owes "no digest covers it" but now HAS one (${fact.digest.name}).`- + ' Delete the `owed` line — a gap that reads as open after it closed is worse than none.');+ // Keyed on a FIELD, not on how the sentence was worded: a rule that greps its+ // own prose is dodged by a rephrase, which is the failure it exists to stop.+ if (fact.owedUntil === 'digest' && fact.digest) {+ findings.push(`${fact.id}: its gap says it closes when a digest covers the fact, and`+ + ` one does now (${fact.digest.name}). Rewrite or delete \`owed\` — a gap that`+ + ' reads as open after it closed is worse than none.');+ }+ if (fact.owedUntil && !fact.owed) {+ findings.push(`${fact.id}: declares owedUntil with no \`owed\` saying what is missing.`);}report.push({ ...fact, status });}diff --git a/tools/eht/__main__.py b/tools/eht/__main__.pyindex 915531118..8aa996974 100644--- a/tools/eht/__main__.py+++ b/tools/eht/__main__.py@@ -7,6 +7,7 @@ from pathlib import Pathfrom .parser import CppParserfrom .abi import compute_abi_hashfrom .entity_layout import parse_entity_layout, generate_ts as generate_entity_ts+from .constants import parse_constants, canonical as const_canonical, generate_ts as generate_consts_tsfrom .generators import (EmbindGenerator, TypeScriptGenerator, MetadataGenerator,PtrLayoutGenerator, EditorAPIGenerator, NativeBindingsGenerator, AotComponentsGenerator,@@ -81,6 +82,9 @@ def main() -> int:parser.add_argument('--entity-header', type=Path,default=Path('src/esengine/core/Types.hpp'),help='Header declaring Entity::Layout = PackedId<index, gen>')+ parser.add_argument('--const-root', type=Path, nargs='+',+ default=[Path('src/esengine')],+ help='Roots scanned for ES_CONST boundary constants')parser.add_argument('--verbose', '-v', action='store_true')# Opt-in native (QuickJS) bindings. Off by default so the standard EHT run and# its committed *.generated.* files are unchanged; a native build passes this@@ -171,8 +175,13 @@ def main() -> int:# offset — a handle that decodes to another entity — so it is in the hash.entity = parse_entity_layout(args.entity_header)print(f"Entity layout: index={entity[0]} gen={entity[1]}")+ # Constants that cross say so at their declaration; a wrong one decodes a+ # stored cell into a different tile rather than failing.+ consts = parse_constants(args.const_root)+ print(f"Boundary constants: {len(consts)}")abi_hash = compute_abi_hash(- cpp_parser.components, cpp_parser.enums, ptr_gen.layouts, entity+ cpp_parser.components, cpp_parser.enums, ptr_gen.layouts, entity,+ const_canonical(consts))print(f"ABI layout hash: {abi_hash}")@@ -239,6 +248,9 @@ def main() -> int:# ── Entity split ──write_ts('wasm/entityLayout.generated.ts', generate_entity_ts(*entity))+ # ── Boundary constants ──+ write_ts('wasm/constants.generated.ts', generate_consts_ts(consts))+# ── Pointer Layouts & Accessors ──write_ts('wasm/ptrLayouts.generated.ts', ptr_gen.generate())write_ts('ecs/bridge/ptrAccessors.generated.ts', ptr_gen.generate_accessors())diff --git a/tools/eht/abi.py b/tools/eht/abi.pyindex fdead2de1..96db9c948 100644--- a/tools/eht/abi.py+++ b/tools/eht/abi.py@@ -7,7 +7,8 @@ SDK compares the two: a mismatch means the loaded WASM binary and the shipped SDwere generated from different schemas, so the pointer offsets the SDK uses wouldread the wrong bytes. Refusing to run is the only safe response.-The entity split is in here for the same reason the offsets are: a handle is a+The entity split and the `ES_CONST` values are in here for the same reason the+offsets are: a handle is abare u32, so two sides that disagree about where the index ends decode eachother's handles rather than refusing.@@ -24,13 +25,15 @@ from .data import Component, Enumdef _canonical(components: List[Component], enums: List[Enum],- layouts: List[Dict], entity: Tuple[int, int]) -> str:+ layouts: List[Dict], entity: Tuple[int, int],+ consts: List[str]) -> str:"""Build an order-independent canonical description of the boundary ABI.Components/enums/layouts are sorted by name so the hash is stable regardlessof filesystem glob order (which is not guaranteed across machines)."""parts: List[str] = [f'ENTITY index={entity[0]} gen={entity[1]}']+ parts.extend(sorted(consts))for enum in sorted(enums, key=lambda e: e.name):vals = ','.join(enum.values)@@ -50,7 +53,8 @@ def _canonical(components: List[Component], enums: List[Enum],def compute_abi_hash(components: List[Component], enums: List[Enum],- layouts: List[Dict], entity: Tuple[int, int]) -> str:+ layouts: List[Dict], entity: Tuple[int, int],+ consts: List[str]) -> str:"""Return a stable 16-hex-char digest of the boundary ABI."""- canonical = _canonical(components, enums, layouts, entity)+ canonical = _canonical(components, enums, layouts, entity, consts)return hashlib.sha1(canonical.encode('utf-8')).hexdigest()[:16]diff --git a/tools/eht/constants.py b/tools/eht/constants.pynew file mode 100644index 000000000..4dac1964d--- /dev/null+++ b/tools/eht/constants.py@@ -0,0 +1,127 @@+"""Constants marked `ES_CONST` — the boundary values that were hand-copied.++A mask the SDK also needs is otherwise written twice, and a wrong mask does not+fail: it decodes a stored cell into a different tile, or over-runs a fixed-size+upload. The C++ declaration is the author; the TS is generated from it and the+value joins the ABI layout hash, so a WASM binary and an SDK bundle built from+different values refuse each other at `connect()`.++Found by SCANNING rather than from a list: a constant that crosses says so at+its declaration, and a list of what to extract is the thing that goes stale.+"""++import re+from pathlib import Path+from typing import Dict, List, NamedTuple++from .parser import CppParser+++class Constant(NamedTuple):+ """One `ES_CONST` declaration, and where it came from."""+ cpp_name: str+ ts_name: str+ value: int+ hex: bool+ header: str+++#: `ES_CONST(attrs)` then a `constexpr` integer on the following line(s).+_DECL = re.compile(+ r'ES_CONST\(([^)]*)\)\s*'+ r'(?:static\s+|inline\s+)?constexpr\s+\w[\w:]*\s+(\w+)\s*=\s*'+ r'(0[xX][0-9a-fA-F]+|-?\d+)\s*;')++#: `ES_CONST` with something that is not a constexpr integer behind it.+_ORPHAN = re.compile(r'ES_CONST\([^)]*\)')+++def parse_constants(roots: List[Path]) -> List[Constant]:+ """Every `ES_CONST` under `roots`, sorted so the output is reproducible."""+ out: List[Constant] = []+ for root in roots:+ if not root.is_dir():+ raise SystemExit(f"[FAIL] ES_CONST scan: no such directory: {root}")+ for header in sorted(root.rglob('*.hpp')):+ raw = header.read_text(encoding='utf-8', errors='replace')+ if 'ES_CONST' not in raw:+ continue+ # Comments out first, or the macro's own @code example is read as a+ # declaration and Reflection.hpp starts exporting TILE_ID_MASK.+ text = CppParser._strip_comments(raw)+ found = list(_DECL.finditer(text))+ # A marker the pattern could not read is a constant that silently+ # would NOT be generated — the exact drift this exists to stop.+ if len(found) != len(_ORPHAN.findall(text)) - _macro_definitions(text):+ raise SystemExit(+ f"[FAIL] ES_CONST in {header} that is not followed by a "+ "`constexpr <int type> NAME = <integer>;`. Only integers cross.")+ for m in found:+ attrs = _attrs(m.group(1))+ out.append(Constant(+ cpp_name=m.group(2),+ ts_name=attrs.get('ts', m.group(2)),+ value=int(m.group(3), 0),+ hex='hex' in attrs,+ header=header.as_posix(),+ ))+ _refuse_duplicates(out)+ return sorted(out, key=lambda c: c.ts_name)+++def _macro_definitions(text: str) -> int:+ """`#define ES_CONST(...)` in Reflection.hpp is not a declaration."""+ return len(re.findall(r'#\s*define\s+ES_CONST', text))+++def _attrs(raw: str) -> Dict[str, str]:+ attrs: Dict[str, str] = {}+ for part in (p.strip() for p in raw.split(',')):+ if not part:+ continue+ key, _, value = part.partition('=')+ attrs[key.strip()] = value.strip()+ return attrs+++def _refuse_duplicates(consts: List[Constant]) -> None:+ """Two headers claiming one TS name would make the generated file depend on+ scan order — and one of the two would be silently dropped."""+ seen: Dict[str, Constant] = {}+ for c in consts:+ prior = seen.get(c.ts_name)+ if prior is not None:+ raise SystemExit(+ f"[FAIL] ES_CONST: '{c.ts_name}' declared in both {prior.header} "+ f"and {c.header}. A boundary constant has one author.")+ seen[c.ts_name] = c+++def canonical(consts: List[Constant]) -> List[str]:+ """What the ABI hash takes of them: name and value, in a stable order."""+ return [f'CONST {c.ts_name}={c.value}' for c in consts]+++def generate_ts(consts: List[Constant]) -> str:+ """The TS half. No imports: this is a leaf every realm can reach."""+ lines = [+ '// SPDX-License-Identifier: Apache-2.0',+ '// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team',+ '/**',+ ' * @file constants.generated.ts',+ ' * @brief Boundary constants marked `ES_CONST` in the C++ headers',+ ' * @details Generated by EHT - DO NOT EDIT',+ ' *',+ ' * Hand-copied, these do not fail when they drift — a wrong mask decodes a',+ ' * stored cell into a different tile. They are in the ABI layout hash, so a',+ ' * WASM binary and an SDK bundle built from different values refuse each',+ ' * other rather than disagreeing quietly.',+ ' */',+ '',+ ]+ for c in consts:+ value = f'0x{c.value:x}' if c.hex else str(c.value)+ lines.append(f'/** C++ `{c.cpp_name}` in `{c.header}`. */')+ lines.append(f'export const {c.ts_name} = {value};')+ lines.append('')+ return '\n'.join(lines)diff --git a/tools/lib/contractFacts.mjs b/tools/lib/contractFacts.mjsindex ad449495a..da19895d3 100644--- a/tools/lib/contractFacts.mjs+++ b/tools/lib/contractFacts.mjs@@ -25,6 +25,10 @@* generating one from the other: same-source generation proves both inherited* one implementation, an independent pair proves both satisfy the contract.*+ * `owed` states a gap in prose so it reads as work; `owedUntil: 'digest'` says+ * MACHINE-READABLY what would close it, so the gate reports the debt as paid+ * rather than leaving a sentence that has stopped being true.+ ** A verification's `how` is `compiler` (the build fails), `handshake` (the two* sides compare at run time and refuse), `test` (a suite parses the other side* and asserts), or `independent-source` (a list written from the spec, not@@ -169,37 +173,37 @@ export const FACTS = [digest: null,owed: 'hand-copied, outside the directory EHT parses. The pin is a test, not a'+ ' handshake: a drift ships if the suite is not run.',+ owedUntil: 'digest',},{id: 'particleColorLut',what: 'How many entries the particle colour lookup table has, which is its stride on both sides.',surface: 'runtime-wasm-abi',authors: [- { path: 'src/esengine/particle/ParticleSystem.hpp', probe: /LUT/, kind: 'semantic' },- { path: 'sdk/src/particle/gradient.ts', probe: /GRADIENT_LUT_SIZE/, kind: 'semantic' },+ { path: 'src/esengine/particle/ParticleSystem.hpp', probe: /ES_CONST\(ts=GRADIENT_LUT_SIZE\)/, kind: 'semantic' },],- projections: [],+ projections: ['sdk/src/wasm/constants.generated.ts'],verification: [{ path: 'sdk/tests/cpp-contract.test.ts', how: 'test', probe: /particle color LUT/ },],- digest: null,- owed: 'hand-copied; the pin is a test, not a handshake.',+ digest: { name: 'eht-abi-layout-hash', path: 'tools/eht/constants.py', probe: /CONST / },},{id: 'tilemapCellEncoding',what: 'Which bits of a tile word are the id and which are the three flip flags.',surface: 'project-asset-format',authors: [- { path: 'src/esengine/tilemap/TilemapSystem.hpp', probe: /FLIP/, kind: 'semantic' },- { path: 'sdk/src/tilemap/tileBits.ts', probe: /TILE_ID_MASK/, kind: 'semantic' },+ { path: 'src/esengine/tilemap/TilemapSystem.hpp', probe: /ES_CONST\(hex\)/, kind: 'semantic' },],- projections: [],+ projections: ['sdk/src/wasm/constants.generated.ts'],verification: [{ path: 'sdk/tests/cpp-contract.test.ts', how: 'test', probe: /tilemap cell encoding/ },],- digest: null,- owed: 'hand-copied; and it is a FILE format, so a drift mis-renders every saved map'- + ' rather than failing to load.',+ digest: { name: 'eht-abi-layout-hash', path: 'tools/eht/constants.py', probe: /CONST /},+ owed: 'the hash pairs a BINARY with a BUNDLE; it says nothing about a saved map.'+ + ' This is a file format, so widening the id mask still reads every older'+ + ' `.esscene` into the wrong cells — that half needs a format version of its'+ + ' own, not an ABI comparison.',},{id: 'uiBaseLayer',