manifoldxplan · web target 5a execution: subagent-driven, one queue worker per task#1402026-11-07
0 of 0 done

Web target, plan 5a: the store, queries, spawn and destroy, batches

This plan builds the first of slice 5's three plans. The page gets manifoldx's entity store: the export writes it as ecs.bin, frame code reads and writes component arrays through queries with numpy expressions, spawns from a geometry library and destroys, moves single entities through their handles, and three.js draws one instanced mesh per geometry and material. On the desktop, a query starts returning only the entities that have its components. It ends with examples/web_crowd.py replaying with no mismatch in Node and in Chromium, and one draw call per batch.

goalExport examples/web_crowd.py with manifoldx export --web: Space spawns a ring of boxes, a query system drifts them, boxes that fall below y = -10 are destroyed, a click picks the box under the crosshair and paints it gold. The Python replay, the Node replay and the Chromium replay trace the same store frame by frame, and the page draws one call per (geometry, material) batch. architecturePython writes the store's arrays below the high-water mark into ecs.bin, its layouts into state.json, and under --web a glb that is a library of geometries and materials by id with no entity nodes. manifoldx.js holds a Store of typed arrays with the desktop's slot rules and command flush, and the Query, accessor, field view and entity handle objects the transpiled code calls. pyrt.js gains NdArray and $rt.nd, numpy's element-wise rules on typed arrays. types.py and transpile.py type and emit queries, fields, arrays, component constructors, spawn and destroy. scene.js keeps one InstancedMesh per batch, rebuilt when the store's version moves. techPython 3.13 and numpy 2; plain ES modules; Node 20+ for node --test and the replay; three.js 0.186.1 as vendored; Playwright with Chromium in the existing browser CI job on lavapipe. spec.knowledge/analysis/2026-11-07-web-target-slice5-design.html (approved; sections 05, 10 to 13, Q3 and Q8 of section 16) builds onplan 1, plan 2 and plan 3, all on main. This plan's branch is feat/web-target-5a; its PR targets main. Plans 5b (events and widgets) and 5c (skinned entities and the second consumer) follow it. code it changessrc/manifoldx/ecs.py, src/manifoldx/gltf/engine_export.py, src/manifoldx/gltf/writer.py, src/manifoldx/web/: snapshot.py, export.py, reach.py, types.py, transpile.py, replay.py, and in js/: pyrt.js, manifoldx.js, scene.js, browser.js, replay.mjs. New: examples/web_crowd.py, benchmarks/suites/web.py.

Done when

The spec's criterion for 5a, as tests

examples/web_crowd.py (boxes spawned by a key, drifting by a query system, destroyed when they fall, picked and highlighted) replays with no mismatch: compare(replay_python(...), replay_node(...)) is None in tests/web/test_web_crowd.py, and the Chromium trace of the same script compares None against Python in tests/web/browser/test_web_crowd_page.py. In that page, renderer.info.render.calls for a frame equals the number of non-empty batches. The breaking tests of task 11 each make compare fail. CI's test and browser jobs are green.

Global constraints

Review focus

File structure

fileresponsibility
src/manifoldx/ecs.pyEntityStore._members and the filtering query (task 1); _FieldView[:, j], a column view (task 7)
src/manifoldx/web/snapshot.pyecs_bytes(engine) -> (header, bytes); the {"__geometry": id} value form; origin in the engine dict; components on system roots
src/manifoldx/web/export.pyBuilt.ecs, ecs.bin in write_version, the glb in library mode
src/manifoldx/gltf/engine_export.py, writer.pyexport_engine(..., library=False); build_glb(..., geometries=None) and mx_geometries in the scene's extras
src/manifoldx/web/js/manifoldx.jsStore, traceStore, Query, Accessor, FieldView, EntityHandle, engine.spawn, engine.destroy, the flush in step
src/manifoldx/web/js/pyrt.jsNdArray and $rt.nd; $rt.component(name, values)
src/manifoldx/web/types.pythe kinds nd, query, accessor, field, component; GEOMETRY; the surface of handles, spawn, destroy, camera.up
src/manifoldx/web/transpile.pyarray expressions to $rt.nd.*; query field reads and queued writes; component constructors; spawn's n=
src/manifoldx/web/reach.pya system's query is allowed; Root.components; component classes are not app classes
src/manifoldx/web/replay.pystore_trace(store); the flush after the systems
src/manifoldx/web/js/scene.jsthe geometry library, one InstancedMesh per batch, materialOf from the store
src/manifoldx/web/js/browser.js, replay.mjsecs.bin loaded; __mx.renderer; per-frame timings for the bench
examples/web_crowd.pythe public example the done criterion replays
tests/test_ecs.pymembership and the column view on the desktop
tests/web/test_ecs_snapshot.py, test_store.py, test_ndarray.py, test_queries.py, test_spawn.py, test_handles.py, test_web_crowd.pyPython tests, most through Node (run_both, replay_node)
tests/web/apps/drift.py, spawner.py, handles.pysmall test apps for tasks 7 to 9
tests/web/js/scene.test.mjsthe batches, in Node
tests/web/browser/test_web_crowd_page.pyChromium: the replay, draw calls, materials read from the batch
benchmarks/suites/web.pythe web-crowd case

Tasks

1Desktop: a query returns only the entities with its components (changes behaviour)ecs.py · tests/test_ecs.py · CHANGELOG.md

This task changes the desktop's behaviour, as the maintainer settled in Q3: today EntityStore.get_component_view returns every alive entity whatever the query (src/manifoldx/ecs.py:123-127). An app whose query names a component some entities lack writes those entities' rows today and skips them after this task, and its len(q) changes. It goes first so every later task builds on the fixed rule.

interfaces

consumes EntityStore as it is · produces EntityStore._members: dict[str, np.ndarray], a bool array of max_entities per registered component, allocated by register_component; spawn(n, **component_data) sets the bit of every given component and of Transform when registered, and clears every other component's bit at the slots it fills; get_component_view(names) returns the alive entities whose bit is set for every name, ascending; a name that is not registered matches nothing; names == [] keeps returning every alive entity
  1. Write the failing tests in tests/test_ecs.py. They describe the new rule; today the first fails with 5 entities instead of 3, which is the old behaviour written down first:
  2. Run uv run pytest tests/test_ecs.py -q: the five new tests fail (the second, third and fourth on a missing _members or on lengths).
  3. Implement in src/manifoldx/ecs.py. register_component adds self._members[name] = np.zeros(self.max_entities, bool). spawn, after it picks indices: for every registered name, self._members[name][indices] = name in component_data or name == "Transform". get_component_view: start from self._alive.copy(), and for each name AND its member array, or return an empty view when the name is not registered; the indices are np.flatnonzero(mask) (int64, ascending, as np.where gave). Update the docstring of get_component_view to say what it now does.
  4. Run uv run pytest tests/test_ecs.py tests/test_systems.py tests/test_commands.py tests/test_command_queueing.py tests/test_engine.py -q: all pass. A test of these that relied on the old rule is a finding: report it in the commit body and fix the test only when the test, not the rule, is wrong.
  5. Find which examples and demos relied on the old rule. Save this script outside the repo (the system temp dir) and run it from the worktree, once on main and once on this branch, with nice; it fires each app's startup on a headless device (lavapipe is enough) and prints, per system, how many entities its query sees: Diff the two outputs. Every line whose count changed is an app that relied on the old rule: check that its system still does what it should (most name only Transform, which every entity has). Fix an app only if it breaks, in this task, and list the diff in the commit body.
  6. Add to CHANGELOG.md under [Unreleased], ### Changed: A system's query returns only the alive entities that have every component it names, as its docstring said; before, it returned every alive entity. An app whose query names a component some entities lack no longer writes their rows, and len(query) counts only the matching entities (#140).
  7. Commit: fix(ecs): a query returns only the entities that have its components (#140).
verify

uv run pytest tests/test_ecs.py tests/test_systems.py tests/test_commands.py tests/test_command_queueing.py tests/test_engine.py -q: all pass, the five new tests included. The audit's diff is in the commit body. Revert the get_component_view change once: test_a_query_returns_only_entities_with_all_its_components fails.

2The store crosses: ecs.bin, layouts, geometry values, the originweb/snapshot.py · web/export.py · web/types.py · tests/web/test_ecs_snapshot.py

interfaces

consumes EntityStore._members (task 1), _Writer.value (src/manifoldx/web/snapshot.py:156), build_export and write_version (src/manifoldx/web/export.py:66, :178) · produces ecs_bytes(engine) -> tuple[dict, bytes] in snapshot.py; state.json gains "ecs": {"max_entities", "high_water", "free": [int], "alive": [offset, nbytes], "components": [{"name", "dtype": "f4"|"u4", "cols", "fields": {field: [col, size]}, "rows": [offset, nbytes], "members": [offset, nbytes]}]}; Built.ecs: bytes, written as ecs.bin by write_version beside state.json; the engine dict gains "origin": [x, z]; the value form {"__geometry": id}; GEOMETRY = obj("manifoldx.Geometry") in types.py, which LiveTypes.of gives a geometry
  1. Write the failing tests in tests/web/test_ecs_snapshot.py, on an app written into tmp_path that spawns a ground (Mesh, Material, Transform), three boxes with a Velocity(Component) of v: Vector3, destroys one at setup with engine.store.destroy, and holds a geometry no entity uses in a module global CRATE that a system reads:
  2. Run uv run pytest tests/web/test_ecs_snapshot.py -q: fails (no ecs key, no ecs.bin).
  3. Implement ecs_bytes. Layout of ecs.bin: the alive mask as uint8 for slots [0, high_water), then per registered component, in the store's registration order, its rows [0, high_water) row-major little-endian in its dtype, then its member bits as uint8; every block starts on a multiple of 4 (zero padding). fields: Transform's from its columns with both spellings, Mesh geometry_id, Material material_id, a Component subclass's _layout (src/manifoldx/components.py:94-100), an @engine.component class's _component_start_idx (src/manifoldx/ecs.py:603-609); a dtype other than float32 or uint32 raises SnapshotError(f"the component {name}", f"dtype {dtype}; ecs.bin carries float32 and uint32 and it") so the message reads as the test says. snapshot() puts the header under "ecs" and build_export keeps the bytes in Built.ecs.
  4. In _Writer.value, before the dict branch: a value whose id is in engine._geometry_registry._object_to_id, a dict with a 2-d "positions" array, or an object with to_geometry becomes {"__geometry": engine._geometry_registry.register(v)}, so the library glb (task 3) writes it. In LiveTypes.of, the same values type as GEOMETRY. The engine dict gains "origin": [float(x), float(z)] from engine._origin.
  5. In manifoldx.js's load, a {"__geometry": id} value resolves through resolve("geometry", id), which returns one frozen {geometry_id: id} per id.
  6. Run uv run pytest tests/web/test_ecs_snapshot.py tests/web/test_snapshot.py tests/web/test_build_export.py -q: all pass.
  7. Commit: feat(web): the entity store crosses to the page as ecs.bin.
verify

uv run pytest tests/web/test_ecs_snapshot.py tests/web/test_snapshot.py tests/web/test_build_export.py -q: all pass, the four new tests included.

3Under --web the glb is a library of geometries and materialsgltf/engine_export.py · gltf/writer.py · web/export.py · tests/test_gltf_library.py

interfaces

consumes export_engine (src/manifoldx/gltf/engine_export.py:110), build_glb and _Writer (src/manifoldx/gltf/writer.py:25), the geometries task 2 registers · produces export_engine(engine, path, *, ..., library=False); build_glb(nodes, *, ..., geometries=None), geometries being [(id, geometry)] written once each as a glTF mesh with one primitive, no material and no node, mapped in the scene's extras as "mx_geometries": {str(id): mesh index}; every glTF material carries "extras": {"mx": {"vertex_colors": bool}}; build_export calls export_engine(..., library=True)
  1. Write the failing tests in tests/test_gltf_library.py, reading the glb with tests/gltf_helpers.py's load and accessor, on a headless engine with a ground and two boxes sharing a cube, a sphere geometry registered but drawn by no entity, two phong materials and one StandardMaterial with vertex_colors=True on a geometry with colours:
  2. Run uv run pytest tests/test_gltf_library.py -q: fails on the unknown library argument.
  3. Implement. _Writer.library(id, geometry) writes the accessors with COLOR_0 whenever the geometry has colors (_Writer.geometry with colors=True), adds a mesh, and records the id; _material sets out["extras"] = {"mx": {"vertex_colors": bool(getattr(mat, "vertex_colors", False)) and getattr(mat, "albedo_map", None) is None}}, the rule node() uses today (writer.py:148-149). export_engine(..., library=True) passes no nodes and geometries= every (id, geo) of engine._geometry_registry._geometries except the named built-ins (reg._name_to_id: the sprite quad and axis lines are not meshes), still writes lights, environment, scene extras and every material, and keeps code_report. An entity drawn without a mesh (point cloud, label, volume) is still reported as dropped, as nodes() reports it today; move that check into a helper both paths call. build_export passes library=True.
  4. Run uv run pytest tests/test_gltf_library.py tests/test_gltf_engine.py tests/test_gltf_scene.py tests/test_gltf_writer.py -q: all pass.
  5. Commit: feat(gltf): a library mode that writes geometries and materials by id.
verify

uv run pytest tests/test_gltf_library.py tests/test_gltf_engine.py tests/test_gltf_scene.py tests/test_gltf_writer.py -q: all pass; git diff main -- tests/test_gltf_engine.py tests/test_gltf_scene.py tests/test_gltf_writer.py is empty. The page does not read the library until task 10, so tests/web/browser is not run here.

4The page's Store, its flush, and the store in the tracejs/manifoldx.js · js/replay.mjs · js/browser.js · web/replay.py · tests/web/test_store.py

interfaces

consumes the "ecs" header and ecs.bin (task 2) · produces JS class Store: static load(header, buffer: ArrayBuffer) -> Store; maxEntities, highWater, capacity, alive: Uint8Array, free: number[], version: number (bumped by spawn, destroy and any write to Mesh or Material), dirty: [lo, hi] | null (the slots whose Transform rows changed since takeDirty()); layout(name) -> {dtype, cols, fields} | undefined; column(name) -> Float32Array | Uint32Array; member(name) -> Uint8Array; spawn(n, rows: Map<string, TypedArray>) -> Int32Array (each array n × cols); destroy(indices), immediate; query(names) -> Int32Array; write(name, index, col, values), immediate; queueUpdate(name, indices, colStart, colEnd, data: Float32Array); queueDestroy(indices); flush(); takeDirty() · traceStore(store) -> {alive, free, high_water, rows} · loadApp(state, modules, {ecs, ...}) sets engine.store; step(app, dt) ends with engine.store.flush() · Python replay.store_trace(store) -> dict, the same form; replay_python flushes engine.commands after the systems and both traces gain "store"
  1. Write the failing tests in tests/web/test_store.py. A helper run_store_ops(ops, max_entities) runs a list of operations in Node against Store (an empty store with Transform and Velocity layouts, built with Store.load from a header of high_water 0) and returns the state after each; the same ops run on an EntityStore: Every index is below max_entities, as on the desktop. In Node an index at or past the page's current capacity is a dead slot and is skipped, as the desktop skips a dead one.
  2. Run uv run pytest tests/web/test_store.py -q: fails, Store is not exported.
  3. Implement Store in manifoldx.js. spawn: k = min(n, free.length), reused are the last k of free reversed, then the lowest dead slots not among them, growing the arrays first when the fresh slots reach capacity (double, at most maxEntities, copying rows and member bits); when fewer than n dead slots exist within maxEntities, throw RuntimeError's message above as an Error (the runtime's Python-exception mapping, as raises.py's test shows). Member bits: set for each name in rows and for Transform, cleared for the others. destroy: sort and dedupe, keep alive ones, clear alive, push to free ascending. query: the alive slots below highWater whose bit is set for every name, ascending; an unknown name gives an empty Int32Array. flush applies the queue in order, an update writing data into columns [colStart, colEnd) of each index's row (cast by the column's typed array), then clears it. Digest past 1,000 alive entities: the alive rows of a component, row-major, viewed as uint32 words w[i]; d = Σ w[i]·(i+1) mod 2^32 (JS: (d + Math.imul(w, i + 1)) >>> 0; numpy: uint64 products masked to 32 bits, summed, mod 2^32).
  4. Wire it: loadApp builds engine.store = Store.load(state.ecs, options.ecs); replay.mjs's load reads ecs.bin with readFileSync and passes its buffer; browser.js's loadVersion fetches ${base}ecs.bin as an ArrayBuffer; traceEntry adds store: traceStore(engine.store); step calls engine.store.flush() after the systems. In replay.py, replay_python calls engine.commands.execute(engine.store); engine.commands.clear() after run_all, as _draw_frame does (src/manifoldx/engine.py:1252-1253), and adds "store": store_trace(engine.store). Update the replay docstring's trace form.
  5. Run uv run pytest tests/web/test_store.py tests/web/test_replay.py tests/web/test_frames.py -q: all pass; web_walk's replay now compares the store too.
  6. Break it once: make spawn take the free list from its start; test_the_page_picks_slots_as_the_desktop fails. Restore it.
  7. Commit: feat(web): the page's entity store, its flush, and the store in the trace.
verify

uv run pytest tests/web/test_store.py tests/web/test_replay.py tests/web/test_frames.py -q: all pass. node out/replay.mjs on a fresh export --web examples/web_walk.py out/ still prints its roots and state.

5Arrays I: NdArray, constructors, element-wise operators, numpy 2's dtypesweb/types.py · web/transpile.py · js/pyrt.js · tests/web/test_ndarray.py

interfaces

consumes Ty, arith_dtype, TypeEnv.binop and lib_call (src/manifoldx/web/types.py:43, :190, :1012, :837), _Module.e_BinOp, e_UnaryOp, compare, lib_call (src/manifoldx/web/transpile.py:891, :960, :983, :1188) · produces Ty gains rank: int | None = None; nd(dtype, rank) -> Ty, kind "nd", dtype among "f32" "f64" "bool" "i32"; nd_dtype(op, a, b) -> str | None, numpy 2's promotion · pyrt: class NdArray {data, shape, dtype}, C-contiguous; $rt.nd.asnd(x) (a Float32Array or Float64Array, the existing vec, as rank 1); $rt.nd.add sub mul div pow neg abs lt le gt ge eq ne and or not; $rt.nd.zeros ones full (shape, dtype), $rt.nd.arange(start, stop, step, dtype); $rt.nd.tolist(a); NdArray.prototype.toJSON for the trace
  1. Write the failing parity tests in tests/web/test_ndarray.py, as tests/web/test_numpy.py does, each a main() returning plain values through .tolist(), compared bit for bit:
  2. Run uv run pytest tests/web/test_ndarray.py -q: fails at transpiling.
  3. Types: np.zeros, np.ones and np.full with a tuple shape type as nd(dtype, len(shape)), with an int shape stay vec when the dtype is a float (today's form) and are nd(dtype, 1) for bool and int32; np.arange with a dtype argument is nd. TypeEnv.binop: an nd on either side with an nd, a vec or a number gives nd(nd_dtype(...), max rank); comparisons give nd("bool", rank); & | ~ only on bool. nd_dtype follows numpy 2: f32 with f32 or a Python number is f32; f64 anywhere is f64; i32 with a Python int is i32, with a Python float, with f32 or with / is f64; bool in arithmetic fails the export.
  4. Transpile: every operator on an nd becomes $rt.nd.<op>(a, b); abs(a) becomes $rt.nd.abs(a); a.tolist() becomes $rt.nd.tolist(a). ** with a constant exponent of 2, 0.5 or -1 becomes mul(a, a), $rt.nd.sqrt or div(1, a) in the result's dtype; any other exponent fails with the message above.
  5. Runtime: each operation allocates the result's typed array (Float32Array for f32, so every element rounds), broadcasting a scalar, a trailing row and equal shapes, else throwing the message above. Python int scalars against i32 wrap to int32 as numpy does (| 0).
  6. Run the same command: all pass. Then run uv run pytest tests/web/test_numpy.py -q: the existing vec cases still pass.
  7. Commit: feat(web): numpy arrays of any rank in frame code, element-wise.
verify

uv run pytest tests/web/test_ndarray.py tests/web/test_numpy.py tests/web/test_types.py -q: all pass, the breaking test included.

6Arrays II: functions, reductions, stacking, indexing copiesweb/types.py · web/transpile.py · js/pyrt.js · tests/web/test_ndarray.py

interfaces

consumes task 5's nd and $rt.nd · produces $rt.nd.sin cos sqrt exp floor clip minimum maximum; $rt.nd.where(cond) (a tuple of index arrays, as numpy) and $rt.nd.where(cond, x, y); $rt.nd.norm(a, axis); $rt.nd.sum mean min max(a, axis) with axis null, 0 or 1; $rt.nd.argmin argmax(a); $rt.nd.stack(list, axis), $rt.nd.column_stack(list); $rt.nd.getitem(a, key) for an int, [:, j], a bool mask or an index array, each a copy; len(a), a.shape, float(a[i]), int(...)
  1. Add the failing parity cases to tests/web/test_ndarray.py: each function on float64 and float32 arrays of shape (k, 3) with k in 1, 7, 9 and 300 (below, inside and past numpy's pairwise blocks of 8 and 128); np.linalg.norm(a, axis=1); np.sum, np.mean, np.min, np.max with axis=None, 0 and 1; np.where(m) and np.where(m, a, np.inf); np.clip(a, -1.0, 1.0); np.stack([x, y, z], axis=1) and np.column_stack; np.argmin with a tie (numpy takes the first) and with a NaN (numpy takes the NaN's index); a[2], a[:, 1], a[a[:, 1] > 0.5], a[np.array([2, 0])]. Plus:
  2. Run uv run pytest tests/web/test_ndarray.py -q: the new cases fail.
  3. Implement. Reductions follow numpy's order so float32 sums round alike: axis=1 on a (k, c) array sums each row left to right; axis=0 adds row after row; axis=None uses numpy's pairwise sum over the flat array (numpy/_core/src/umath/loops_utils.h.src, pairwise_sum): fewer than 8 elements left to right, up to 128 with eight accumulators combined as ((r0+r1)+(r2+r3))+((r4+r5)+(r6+r7)) and the rest added left to right, above 128 split at n / 2 rounded down to a multiple of 8 and recurse; every addition rounds to the dtype. mean is that sum divided by the count. norm(a, axis=1) is sqrt(sum(a * a, axis=1)) with those roundings. min and max propagate NaN. sin cos exp on f32 compute in float64 and round; on f64 they are Math.sin, as today's scalar math is. The where choose form follows task 5's dtype rules (a Python np.inf keeps f32). Indexing returns new arrays; a[i] of a rank-1 array is a number (a num with the array's dtype). A Subscript store on an nd fails with the message above. The .sum(), .min(), .max(), .mean() method forms fail naming the np. function.
  4. Run the same command: all pass. Write the transcendental count into this plan's departures section.
  5. Commit: feat(web): numpy functions, reductions and indexing in frame code.
verify

uv run pytest tests/web/test_ndarray.py tests/web/test_numpy.py -q: all pass; change the pairwise block size from 8 to 4 once and the k = 9 float32 sum differs.

7Queries in systems: accessors, field views, queued writesecs.py · web/reach.py · web/types.py · web/transpile.py · web/snapshot.py · js/manifoldx.js · tests/web/test_queries.py · tests/web/apps/drift.py

interfaces

consumes Store (task 4), nd (tasks 5, 6), System.component_names (src/manifoldx/systems.py:16), Reach._query (src/manifoldx/web/reach.py:367) · produces desktop: _FieldView.__getitem__((slice(None), j)), a one-column field view, so q[Transform].pos[:, 1] < -10.0 gives entity indices · Root.components: tuple[str, ...] from the live system; state.json roots gain "components" · types: query(components), accessor(component), field(component, name, start, size); the first parameter of a system root types as its query · JS: class Query (get(name) -> Accessor, length, iteration over indices), class Accessor (field(name) -> FieldView), class FieldView (data -> NdArray f32 (k, size), col(j), add sub mul div radd rsub rtruediv returning f32 NdArray, lt le gt ge returning the entity indices as an i32 NdArray, set(v), iadd isub imul, which queue); step passes new Query(store, r.components, engine) to each system
  1. Desktop first. Write test_a_column_of_a_field_compares_to_entity_indices in tests/test_ecs.py: three entities at y = 0, -20 and 5, the second not first in the store; inside a system, q[Transform].pos[:, 1] < -10.0 equals np.array([that index]), and q[Transform].pos[:, 1].data is (3, 1). Run it: fails with TypeError: '_FieldView' object is not subscriptable. Implement __getitem__ for a key (slice(None), j) with an int j in range, returning _FieldView(store, indices, component, col_start + j, col_start + j + 1, field_name, commands); any other key raises TypeError("a field view takes [:, j], one column"). Run it: passes.
  2. Write tests/web/apps/drift.py: a Velocity(Component) with v: Vector3; setup spawns a ground without Velocity and 12 boxes with velocities from np.linspace; system drift(q: Query[Transform, Velocity], dt) does q[Velocity].v += GRAVITY * dt (GRAVITY a float32 (3,) global), q[Transform].pos += q[Velocity].v * dt and q[Transform].rot += SPIN (a float32 quaternion global); a second system watch(q: Query[Transform, Velocity], dt) stores float(np.sum(q[Transform].pos.data, axis=None)) and len(q) in engine.state, reading what drift queued (the old rows); a third, low(q: Query[Transform], dt), stores len(q[Transform].pos[:, 1] < 0.0). Then the failing tests in tests/web/test_queries.py:
  3. Run uv run pytest tests/web/test_queries.py tests/test_ecs.py -q: the web tests fail on the reach error component queries are not supported in the browser yet.
  4. Reach and types. Remove Reach._query's error; find_roots fills Root.components from System.component_names, and snapshot writes it on each root. In TypeEnv, the first parameter of a system root types as query(components) (the live registration, so Query[...], mx.Query[...] or no annotation all work); q[X] where X names Transform, Mesh, Material or a Component subclass types as accessor(name); an attribute of an accessor types as field(...) from the layouts task 2 writes (the same table, built from the live classes); field.data is nd("f32", 2); arithmetic with a field follows _FieldView: the other side is cast to float32 first and the result is nd("f32", 2) (src/manifoldx/ecs.py:269-307); < <= > >= give nd("i32", 1), the entity indices; field[:, j] is a one-column field; len(q) is an int and for i in q binds ints. A field in np.* or with unary minus fails naming .data.
  5. Transpile. q[Transform] becomes q.get("Transform"); .pos on an accessor .field("pos"); x.pos = v on an accessor .field("pos").set(v); x.pos += v .field("pos").iadd(v), likewise -= and *=; /= becomes .set(f.rtruediv...) as Python falls back to __truediv__ then the setter; rot += composes with _quat_multiply(other, current) (src/manifoldx/ecs.py:332-354) in float32, each product and sum rounded, then normalised with a zero norm kept as 1. The runtime classes follow the interfaces; set and the in-place forms call store.queueUpdate with the field's columns.
  6. Run uv run pytest tests/web/test_queries.py tests/test_ecs.py tests/web/test_replay.py -q: all pass.
  7. Commit the desktop change and the web change separately: feat(ecs): a field view takes [:, j], one column, then feat(web): component queries in systems, with queued writes.
verify

uv run pytest tests/web/test_queries.py tests/test_ecs.py tests/web/test_replay.py tests/web/test_reach.py -q: all pass, the breaking test included.

8Entity handles in frame code; set_material through the store; #153, #154web/types.py · web/transpile.py · js/manifoldx.js · tests/web/test_handles.py · tests/web/apps/handles.py

interfaces

consumes Store.write and queueDestroy (task 4), the engine dict's origin (task 2), EntityHandle and _TransformProxy (src/manifoldx/engine.py:25-160) · produces JS class EntityHandle (index, transform, set_material(m), destroy(free_geometry = true)), class TransformProxy (pos: a new Float64Array(3), row plus [ox, 0, oz]; setting it stores v - offset rounded to float32; rot, scale: new Float32Arrays; setting them writes at once); resolve("entity", i) returns one EntityHandle per index; engine.set_material(entity, material) writes the Material column at once, bumps store.version, keeps the ["material", i, id] log entry, and throws set_material: entity ${i} is not alive as the desktop raises · types: RUNTIME_SURFACE for manifoldx.engine.EntityHandle and manifoldx.engine._TransformProxy; WRITABLE gains the proxy's pos rot scale and the camera's up (#153); a write to a field of a material fails with the set_material hint (#154)
  1. Write tests/web/apps/handles.py: 8 crates spawned at setup, their handles in a list of app objects (Crate with entity, phase); a system moves each crate in a circle with c.entity.transform.pos = (x, y, z) from floats, spins it with c.entity.transform.rot = Transform.rotation(y=angle), scales it from scale's read value, paints the crate under a timer with c.entity.set_material(RED), and at frame 50 destroys crate 3 with crates[3].entity.destroy(); engine.camera.up is written each frame. A second copy of the app calls engine.set_origin(5000.0, -3000.0) (src/manifoldx/engine.py:705) at setup before the spawns. Then the failing tests in tests/web/test_handles.py:
  2. Run uv run pytest tests/web/test_handles.py -q: fails at the export (transform on an EntityHandle types as unknown).
  3. Implement the surface and the runtime classes. EntityHandle.destroy queues the index for the flush and frees nothing (the library keeps the geometry, spec section 05). transform.pos[1] = y changes only the returned copy, as on the desktop: no special case. The material hint is a branch in the write check of Reach._attribute for receivers of a manifoldx.resources material class.
  4. Run uv run pytest tests/web/test_handles.py tests/web/test_replay.py tests/web/test_state_access.py -q: all pass.
  5. Commit: feat(web): entity handles in frame code, set_material through the store (#153, #154).
verify

uv run pytest tests/web/test_handles.py tests/web/test_replay.py tests/web/test_state_access.py -q: all pass.

9Spawn and destroy in frame code, from the geometry libraryweb/types.py · web/reach.py · web/transpile.py · js/pyrt.js · js/manifoldx.js · tests/web/test_spawn.py · tests/web/apps/spawner.py

interfaces

consumes Store.spawn and queueDestroy (task 4), GEOMETRY and {"__geometry": id} (task 2), EntityHandle (task 8), Engine.spawn and Engine.destroy (src/manifoldx/engine.py:1030, :1123) · produces pyrt $rt.component(name, values: Map), a plain record {component, values}; types: Ty("component", name=...) for a call of Transform, Mesh, Material or a Component subclass, TypeEnv.components: dict[str, str] (qualname to store name) for the app's Component subclasses, which are not app classes and are never transpiled; RUNTIME_SURFACE Engine.spawn returning the handle (or None) and Engine.destroy; RUNTIME_KEYWORDS = {"manifoldx.Engine.spawn": ("n",)}, passed as a final {n: k} · JS engine.spawn(...components, opts), engine.destroy(x)
  1. Write tests/web/apps/spawner.py: CUBE and BALL geometries as module globals, no entity drawing BALL at setup; on just_pressed("Space") a system spawns 20 boxes with engine.spawn(Mesh(CUBE), Material(BLUE), Transform(pos=ring, scale=(0.4, 0.4, 0.4)), Life(t=2.0), n=20) where ring is (20, 3) float64 from np.cos and np.sin of np.arange; on "b" one ball with engine.spawn(Mesh(BALL), Material(RED), Transform(pos=(0.0, 2.0, 0.0))), keeping its handle in engine.state's app object; a system age(q: Query[Life], dt) does q[Life].t -= dt and engine.destroy(q[Life].t <= 0.0); on "x" the ball's handle is destroyed; n=0 is spawned once and its result (None) stored. Then the failing tests in tests/web/test_spawn.py:
  2. Run uv run pytest tests/web/test_spawn.py -q: fails at the export.
  3. Types and reach. In TypeEnv._class, a class whose live object subclasses manifoldx.components.Component is recorded in components and not as a ClassInfo; a call of it types as Ty("component", name=cls.__name__); so do the setup-imported Transform, Mesh and Material (resolved through library_class to manifoldx.components.*). Mesh(x) needs x typed GEOMETRY; Material(m) a material handle.
  4. Transpile. A component call becomes $rt.component("Transform", new Map([["pos", ...]])): keywords by name, positional arguments mapped to pos rot scale for Transform, geometry for Mesh, material for Material; a Component subclass takes keywords only, as its __init__. A call to a runtime-surface function listed in RUNTIME_KEYWORDS passes its keywords as a final object literal.
  5. Runtime. engine.spawn mirrors Engine.spawn and each get_data: Transform's defaults (scale 1, w 1), its pos, rot, scale broadcast to n rows, cast to float32, the origin subtracted in float64 from a given pos (engine.py:1066-1072); Mesh and Material rows of the geometry and material id; a Component's fields by Component.get_data's rules (components.py:123-158), fields missing from the call taking the class default the layout carries (add "defaults" to the component's header entry in task 2's form). It calls store.spawn at once and returns resolve("entity", first), or null for n 0. engine.destroy(x): null does nothing, a bool NdArray gives its true positions, an i32 NdArray, array or Int32Array its values; non-empty, it queues.
  6. Run uv run pytest tests/web/test_spawn.py tests/web/test_queries.py tests/web/test_handles.py -q: all pass.
  7. Commit: feat(web): spawn and destroy in frame code, from the geometry library.
verify

uv run pytest tests/web/test_spawn.py tests/web/test_queries.py tests/web/test_handles.py tests/web/test_ecs_snapshot.py -q: all pass.

10The page draws instanced batches from the storejs/scene.js · js/browser.js · tests/web/js/scene.test.mjs

interfaces

consumes the library glb (task 3), Store with version and takeDirty() (task 4), buildScene (src/manifoldx/web/js/scene.js:124) · produces buildScene(THREE, gltf, renderer) reads extras.mx_geometries into geometries: Map<id, BufferGeometry>; the MxScene gains batches: Map<"gid:mid", InstancedMesh> and sync(engine) also syncs batches from engine.store; materialOf(entity) reads the store's Material column; entities, setMaterial and resetMaterials are removed, and browser.js drops the setMaterial hook and the resetMaterials() call (browser.js:140, :241); __mx.renderer is the renderer
  1. Rewrite the scene tests that read entities or call setMaterial and resetMaterials (tests/web/js/scene.test.mjs:56, :67, :249), and add, on the web_walk export (six boxes, a ground, one cube geometry, eight materials):
  2. Run uv run pytest tests/web/test_node_suites.py -q: the scene suite fails.
  3. Implement in scene.js. At load, each mx_geometries entry's glTF mesh gives its BufferGeometry (gltf.parser.getDependency("mesh", index)). sync: when store.version differs from the last seen, one pass over the alive slots with a Mesh bit and a geometry id other than 0 rebuilds each batch's member list, keyed `${gid}:${mid}`; a batch is created on first use with the drawn material (materials.get(mid), or a white basic material for id 0, as the desktop draws a mesh without a Material), cloned with vertexColors on when the material's userData.mx.vertex_colors is true and the geometry has colour; capacity doubles; count is the member count and visible is count > 0; all members' matrices are written. Otherwise only members in store.takeDirty()'s range are rewritten. A batch whose matrices changed sets instanceMatrix.needsUpdate and recomputes its bounding sphere. With extras.shadows every batch casts and receives, and the shadow fit (fitShadow) runs after the first batch sync, so auto_fit sees the batches.
  4. Run uv run pytest tests/web/test_node_suites.py -q: all pass.
  5. Commit: feat(web): the page draws one instanced mesh per geometry and material.
verify

uv run pytest tests/web/test_node_suites.py -q: all pass. Chromium, draw calls and the visual check run in task 12.

11examples/web_crowd.py, its Node replay and the breaking testsexamples/web_crowd.py · tests/web/test_web_crowd.py · examples/README.md

interfaces

consumes tasks 1 to 10 · produces examples/web_crowd.py, public, and tests/web/test_web_crowd.py with script(seed, n) -> list[Frame], PATHS, and the fixtures crowd_export and crowd_python_trace the browser test reuses
  1. Write examples/web_crowd.py, in the style of examples/web_walk.py (a module docstring with the controls and both commands, constants at the top, plain functions):
    • A ground (Mesh, Material, Transform, no Velocity) and a fixed camera looking at the origin from (0, 12, 22); a Velocity(Component) with v: Vector3; CUBE a module global; three box materials and GOLD.
    • spawn_wave(q: Query[Transform], dt): on just_pressed("Space"), 24 boxes on a ring of radius 4 + wave at height 6 with outward velocities, material wave % 3, all from np.arange, np.cos, np.sin and np.column_stack on float64, in one engine.spawn(..., n=24); engine.state["waves"] counts them.
    • drift(q: Query[Transform, Velocity], dt): gravity into v, pos += v * dt, a spin into rot, and engine.destroy(q[Transform].pos[:, 1] < -10.0).
    • pick(q: Query[Transform, Velocity], dt), after drift, so it reads the rows before the flush: on a left click, the ray from engine.camera through engine.input.mouse_pos (camera.fov, engine.w, engine.h), the boxes' distances to it with np.linalg.norm(..., axis=1), np.where to put np.inf on misses, np.argmin; the hit box turns GOLD with engine.set_material, the previous one gets its material back; engine.state["picked"] holds the entity index or None.
    • A panel with ValueDisplays: boxes alive (len of a query read in a system and kept in engine.state), waves, picked.
  2. Write the failing tests in tests/web/test_web_crowd.py. The script, seeded, of 600 frames: Space at frames 5, 6 and 200 (two waves in a row, one after the first fell), left clicks at pixel positions over a box on frames 40, 41 (the same box twice) and 120, a click on the sky at 150, a resize to 640×400 at frame 300, Space at 301:
  3. Run uv run pytest tests/web/test_web_crowd.py -q; fix what the replay finds in the task that owns it (and note it in that task's departure lines), until all pass.
  4. Add the example to examples/README.md's list beside web_walk.py.
  5. Commit: feat(examples): web_crowd, the ECS in the page end to end.
verify

uv run pytest tests/web/test_web_crowd.py -q: all pass, four breaking cases included. uv run python examples/web_crowd.py opens a window where Space, falling and clicking work, checked by its --render --duration 2 MP4 or manifoldx look under manifoldx run on a host with a GPU or lavapipe.

12Chromium: web_crowd's replay, one draw call per batch, materials from the batchtests/web/browser/test_web_crowd_page.py · tests/web/browser/conftest.py · js/browser.js

interfaces

consumes the fixtures of tests/web/browser/conftest.py (served, open_page, _export), test_page.py's tick and drive patterns, task 11's script and Python trace, __mx.renderer (task 10) · produces crowd_export in the browser conftest; Chromium checks the replay cannot see
  1. Write tests/web/browser/test_web_crowd_page.py:
  2. Run uv run pytest tests/web/browser/test_web_crowd_page.py tests/web/browser/test_page.py tests/web/browser/test_visual.py -v on a host with Chromium and lavapipe. Each failure is a defect of an earlier task or of the page: fix it there, and note in the departures section what the browser forced.
  3. Break one once: drop the store.version check so membership never rebuilds after load; test_an_entitys_material_is_read_from_its_batch fails. Restore it.
  4. Commit: test(web): web_crowd in Chromium, draw calls and batch materials.
verify

uv run pytest tests/web/browser/test_web_crowd_page.py tests/web/browser/test_page.py tests/web/browser/test_visual.py tests/web/browser/test_run_web.py -v: all pass with no skips on a host with Chromium; otherwise push and read the browser job, which fails on any skip.

13The web-crowd bench case and the docsbenchmarks/suites/web.py · js/browser.js · know-how/web-export.md · know-how/benchmarking.md · CHANGELOG.md · AGENTS.md

interfaces

consumes the @case registry (benchmarks/harness.py), everything above · produces @case("web", "web-crowd", sizes=[1_000, 10_000], smoke=100) returning {"ms": page work per frame, "calls": draw calls}; __mx.frameMs, {work, render} of the last tick in milliseconds (work from the frame's start to the batch sync's end, render the renderer.render call)
  1. In browser.js's runFrame, time the frame with performance.now() into mx.frameMs.
  2. Write benchmarks/suites/web.py: the case writes an app into a temp dir that spawns n boxes at setup in one batch with a Velocity, and a query system moving all of them every frame; exports it, serves it, opens headless Chromium with Playwright, runs 60 manual ticks, and returns the median work and the last tick's draw calls. Without Playwright or Chromium it raises, which the harness reports as the case's error (benchmarks/__main__.py:46). It reports and does not gate (spec section 11).
  3. Run uv run python -m benchmarks web --case web-crowd --sizes 1000 once; with Chromium it prints a row with calls 2 (the batch and nothing else; the app has no ground).
  4. Docs. know-how/web-export.md: ecs.bin in the folder listing; a section "Entities in the page" (queries filter by component, the field view's desktop semantics including [:, j], what queues and what is immediate, spawn from geometries the export saw, handles, the array subset and its errors, batches and draw calls); the trace's store. know-how/benchmarking.md: the web suite. CHANGELOG.md under [Unreleased], ### Added: the store in the page, queries, arrays, spawn and destroy, handles, instanced batches, library glTF mode, _FieldView[:, j], examples/web_crowd.py. AGENTS.md's web target line: plan 5a and its path.
  5. Commit: docs(web): entities in the page, the web-crowd bench.
verify

uv run pytest tests/test_benchmarks.py -q, which runs every case at its smoke size: passes, the new case reporting an error rather than failing where Chromium is missing. The know-how's commands run as written.

Where this plan departs from the spec

Self-review