manifoldxplan · web target 1 execution method: subagent-driven#1402026-11-06
0 of 0 done

Web target, plan 1: transpiler, snapshot and headless replay

This plan builds slices 1 and 2 of the spec: the Python-to-JavaScript transpiler, the state snapshot, a runtime that runs the transpiled app in Node without rendering, and the replay harness that proves the exported app equals the Python one frame by frame. It ends with the first consumer replaying in its own CI. Rendering with three.js and export --web's page (slice 3) and run --web (slice 4) get their own plans, written against the interfaces this one lands.

goalAn app's per-frame Python, transpiled, run on its snapshotted state in Node, gives the same trace as the Python app over a scripted input. architectureA new package manifoldx.web: a type model fed by annotations, the live objects after setup and inference; a transpiler that emits one ES module per app module from the roots; a snapshot of the reached objects; static JS (pyrt.js, manifoldx.js) shipped in the wheel; a replay harness on both sides. techPython 3.13, ast, numpy; plain ES modules; Node 20+ as a test dependency only (node --test, node --enable-source-maps). spec.knowledge/analysis/2026-11-06-web-target-design.html later plansplan 2: three.js rendering, HTML GUI, browser input, export --web's page, visual parity (spec slice 3). Plan 3: run --web (slice 4).

Global constraints

Review focus

File structure

fileresponsibility
src/manifoldx/web/__init__.pypublic names: transpile_app, snapshot, export_web, TranspileError, SnapshotError
src/manifoldx/web/types.pythe type model (Ty) and TypeEnv: annotations, live types, inference, call-site propagation
src/manifoldx/web/transpile.pyexpressions, statements, classes and closures to JS; source maps
src/manifoldx/web/reach.pyroots from an engine; reach through types; the root chain for errors
src/manifoldx/web/snapshot.pyreached objects to JSON; handles for manifoldx objects; functions and closures
src/manifoldx/web/export.pyrun the app's setup without a window, then write the output folder
src/manifoldx/web/replay.pyScriptInput, the Python replay, the Node replay, trace comparison
src/manifoldx/web/js/pyrt.jsPython semantics JS lacks (the spikes' runtime, grown)
src/manifoldx/web/js/manifoldx.jsthe engine surface reached code calls; state loading; the frame step
src/manifoldx/web/js/replay.mjsNode entry: load an export folder, replay a script, print the trace as JSON
src/manifoldx/engine.py, input.pyEngine.set_material, InputState.capture_pointer
src/manifoldx/gltf/engine_export.py, writer.pyentity and material ids in extras; extra materials
src/manifoldx/cli.pymanifoldx export --web
examples/web_walk.pythe public example the replay runs in CI
tests/web/one test file per task; tests/web/parity.py runs a snippet on both sides

Tasks

1Engine APIs: set_material and capture_pointersrc/manifoldx/engine.py · src/manifoldx/input.py · tests/test_web_engine_apis.py

interfaces

produces Engine.set_material(entity: int | EntityHandle, material) -> None · InputState.capture_pointer(on: bool) -> None · InputState.pointer_captured: bool
  1. Write the failing tests: after engine.set_material(h, m), engine.store._components["Material"][h.index, 0] == engine._material_registry.register(m); an int index works like a handle; a dead entity raises ValueError. capture_pointer(True) sets pointer_captured and calls the hook InputState._on_capture when one is set; with no window it only sets the flag.
  2. Run uv run pytest tests/test_web_engine_apis.py -v: fails with AttributeError.
  3. Implement both. On the desktop, the engine sets input._on_capture when it opens a glfw canvas, to a function that sets the cursor mode to disabled or normal on the canvas's window (and raw motion when supported). This moves the first consumer's workaround into manifoldx.
  4. Run the tests: pass. Run make test: no other test changes.
  5. Commit: feat(engine): set_material and capture_pointer as public API.
2glTF export: entity and material ids, extra materialssrc/manifoldx/gltf/engine_export.py · writer.py · tests/test_gltf_engine.py

interfaces

produces each node's extras gain "mx": {"entity": int, "material": int} (merged under the app's extras, which keep their keys) · the scene's extras gain "mx_materials": {str(id): gltf_material_index} for every material in engine._material_registry._materials, written even when no node uses it · build_glb(..., extra_materials=list[tuple[int, material]])
  1. Write the failing tests in tests/test_gltf_engine.py: a node's extras carry its entity index and material id; a material registered but used by no entity appears in mx_materials and in the glTF's materials; an app's extras {"pick": "b1"} survive next to "mx"; existing exports' other fields are unchanged.
  2. Run them: fail.
  3. Implement in nodes() and build_glb. Materials stay merged by object identity as today; mx_materials maps every registry id to the index the writer gave that object.
  4. Run uv run pytest tests/test_gltf_engine.py tests/test_gltf_writer.py tests/test_gltf_conformance.py -v: pass.
  5. Commit: feat(gltf): write entity and material ids, and unused materials.
3The parity harness and the core subsetsrc/manifoldx/web/{__init__,types,transpile}.py · js/pyrt.js · tests/web/{conftest,parity,test_core}.py

interfaces

produces transpile_app(sources: dict[str, str], roots: list[str] | None = None, live: LiveTypes | None = None) -> dict[str, JsModule] · JsModule(name: str, code: str, source_map: str | None) · TranspileError(path: str, line: int, what: str, root: str | None) with str "path:line: what is outside the subset (reached from root)" · parity.run_both(src: str) -> tuple[object, object] (runs main() in Python and in Node, JSON values) · Ty, TypeEnv in types.py
  1. Write tests/web/parity.py: run_both(src) writes src as mod.py, imports it and calls main(); transpiles it with roots=None (whole module), copies pyrt.js beside it, runs node --input-type=module -e that imports main and prints JSON.stringify(main(), replacer), where the replacer turns typed arrays and Sets into arrays. tests/web/conftest.py skips the folder when Node is missing.
  2. Write the failing tests, one per row, each a main() whose Python and JS results must be equal: Each test also checks that the generated JS has no eval and no with.
  3. Run uv run pytest tests/web/test_core.py -v: fail (module missing).
  4. Implement types.py (Ty with kinds num, int, bool, str, none, list, tuple, dict, set, vec, obj, fn, union, unknown; vec carries dtype "f64" or "f32") and transpile.py starting from the spike's design: locals declared once with let at the top of each function, comprehensions as IIFEs, % through mod, tests through truthy unless both sides are known booleans, and/or on non-booleans through or_/and_ with thunks. A list.append is push; a list's pop is pop.
  5. Run the tests: pass. Commit: feat(web): transpiler core and the parity harness.
verify

uv run pytest tests/web/test_core.py -v: 9 passed; with Node off the PATH, 9 skipped with "node not found".

4numpy vectors, float32 and mathsrc/manifoldx/web/{types,transpile}.py · js/pyrt.js · tests/web/test_numpy.py

interfaces

consumes task 3 · produces pyrt.js exports vadd, vsub, vmul, vdiv, vneg, vnorm, arange, radians, degrees; f32 variants keep Float32Array
  1. Write the failing parity tests: inplace_alias pins numpy's in-place +=: b sees the change.
  2. Run: fail.
  3. Implement: a value is a vector when its type says so (from np.array, np.zeros, an np.ndarray annotation, a live array, or arithmetic on one); arithmetic on vectors goes through the v* helpers; += on a vector writes in place (viadd(a, b) mutating a); np.array(x, np.float32) is Float32Array.from(x); float32 norm is Math.fround(Math.sqrt(...)) over frounded products summed in order. radians multiplies by Math.PI / 180 computed once.
  4. Run: pass. Commit: feat(web): numpy vectors and float32 in the transpiler.
5Classes, closures, collections and textsrc/manifoldx/web/transpile.py · js/pyrt.js · tests/web/test_classes.py · tests/web/test_text.py

interfaces

consumes tasks 3, 4 · produces classes emit with a constructor only for dataclasses or when __init__ is reached; a method's first parameter emits as this; __call__ instances are callable (pyrt callable_(obj)); pyrt exports truthy, contains, dget, next_, lrep, str_, fmt, wrap, cplen
  1. Write the failing parity tests: a dataclass with field(default_factory=...), a @property, a class with __call__ called as a function, a closure that captures a loop variable through a default (lambda i=i: i), keyword arguments to a function in another module (two-module variant of run_both), hasattr and isinstance over a value that may be either of two app classes, dicts with string keys and .get, list + and * n, next(x for x in xs if ...).
  2. Write the failing text tests (Review focus): len("Matemática"), len("a😀b"), f"{x:.1f}" for x in (0.05, 2.25, 12.75, 3.0), str(3.0) and str(3) through f-strings with no spec, textwrap.wrap of a 60-character Spanish name with accents and of a hyphenated word at widths 10 and 28. JS must equal Python exactly; len and wrap count code points (cplen).
  3. Run: fail.
  4. Implement. fmt rounds half to even on exact ties (decide the tie with the exact decimal expansion of the double, as Python does); str_ prints a float with a fractional part of zero as "3.0", which needs the type: the transpiler passes "float" or "int" to str_ when it knows it and fails on an unknown numeric type in a format with no spec. wrap ports textwrap.TextWrapper._split's hyphen rule and _wrap_chunks with the defaults.
  5. Run: pass. Commit: feat(web): classes, closures, collections and text.
6Types from live objects and call sitessrc/manifoldx/web/types.py · tests/web/test_types.py

interfaces

consumes task 3's Ty, TypeEnv · produces LiveTypes.observe(obj) records each app class's field types from values (a union across instances) · TypeEnv.solve(reached_functions) -> None fills parameter and return types
  1. Write the failing tests: an unannotated def f(scene, pid): return scene.by_id(pid) called from a root as f(self.scene, self.selected) types scene as the live class of self.scene and pid as str | None; a field holding a Building on one instance and a Landmark on another types as their union; a + whose operand type stays unknown raises TranspileError whose message contains annotate and the expression's text; an annotation wins over a live type.
  2. Run: fail.
  3. Implement the solve as a fixed point: start with annotations and live field types; each pass types locals forward through each reached function, joins argument types at call sites into the callee's parameters, and joins return types into callers; stop when no type changes, at most 20 passes, then report the first operator whose operand is still unknown. Operators that need a type: +, *, +=, == and != on non-scalars, f-string fields with no spec, % with a string left side.
  4. Run: pass. Commit: feat(web): types from live objects and call sites.
7Roots and reachsrc/manifoldx/web/reach.py · tests/web/test_reach.py

interfaces

consumes tasks 3, 6 · produces Root(kind: "system" | "handler" | "getter", label: str, func) · find_roots(engine) -> list[Root] · Reach(roots, env).functions: set[FunctionKey], .fields: dict[class_qualname, set[str]], .chain(key) -> list[str]
  1. Write the failing tests: find_roots returns each engine.systems._systems[i].func, each handler in engine._event_bus._handlers except "startup" and except manifoldx's own (the rule code_report uses), and each ValueDisplay._getter found by walking engine.gui._panels and their children. Reach follows a method only on the classes its receiver's type allows (two classes with a parts field: only the reached one's field is in .fields). Review focus: a root that calls Path("x").exists() raises TranspileError naming pathlib.Path, the line and the root's label. A system whose first parameter (its query) is used raises "component queries are not supported in the browser yet".
  2. Run: fail.
  3. Implement; a bound method root's owner and a closure's cells become snapshot roots (task 8).
  4. Run: pass. Commit: feat(web): roots and reach through types.
8The snapshot and its loadersrc/manifoldx/web/snapshot.py · js/manifoldx.js · tests/web/test_snapshot.py

interfaces

consumes task 7's Reach · produces snapshot(roots, reach, engine) -> dict {"table": [...], "roots": [...]} · entries: {"__type": "module.Class", "fields": {...}} · {"__ref": n} · {"__f32": [...]} · {"__set": [...]} · {"__engine": "Engine"} · {"__material": id} · {"__entity": index} · {"__widget": n} · {"__bound": ref, "name": str} · {"__closure": "module:line:col", "cells": {...}, "defaults": [...]} · SnapshotError(path_from_root: str, what: str) · manifoldx.js loadState(json, modules, resolve) -> roots
  1. Write the failing tests, each snapshotting in Python, loading in Node through loadState, and comparing a JSON view: shared objects stay one object (a.ground === b.terrain); only reached fields are written; float32 arrays load as Float32Array; a material reached in state but never spawned is registered, so its id is in the registry and task 2's export writes it; a dict with keys "constructor", "__proto__" and "toString" round trips and in/.get/indexing find each (Review focus); a dict with an int key raises SnapshotError whose path reads like Viewer.names; a lambda in a ValueDisplay with a default argument loads as a function that returns the same value as in Python.
  2. Run: fail.
  3. Implement. Objects load with Object.create(cls.prototype), never the constructor; a class with __call__ loads through callable_; dicts load as objects with a null prototype so prototype names are plain keys; the transpiler emits each reached closure as an exported factory __closure_<line>_<col>(cells, defaults).
  4. Run: pass. Commit: feat(web): state snapshot and loader.
9The headless runtime surfacesrc/manifoldx/web/js/manifoldx.js · tests/web/js/runtime.test.mjs · tests/web/test_node_suites.py

interfaces

consumes task 8 · produces createEngine({w, h, camera: {position, target, near, far}, materials, log}) -> engine with .input (ScriptInput: setFrame(frame), pressed_keys, just_pressed, mouse_delta, is_mouse_pressed, just_mouse_pressed, viewport_size, capture_pointer, pointer_captured), .camera (position, target as Float32Array; get_forward()), .gui.pointer_over_gui, .set_material(entity, material), .state, .w, .h · step(app, dt) runs the systems in order with (null, dt) · guiValues(app) -> list[str]
  1. Write the failing Node tests (node --test): camera.get_forward() equals numpy's float32 result for five fixed position/target pairs (values recorded by a Python test into a JSON fixture); setFrame drives every input getter; set_material and capture_pointer append ["material", entity, material_id] and ["capture", on] to log; step calls systems in registration order. tests/web/test_node_suites.py runs node --test tests/web/js/ from pytest so make test covers it.
  2. Run: fail.
  3. Implement.
  4. Run: pass. Commit: feat(web): headless runtime surface.
10Source mapssrc/manifoldx/web/transpile.py · tests/web/test_sourcemap.py

interfaces

consumes task 3 · produces JsModule.source_map: a source map v3 JSON with one segment per emitted statement, pointing at the Python line; each module ends with //# sourceMappingURL=<name>.js.map
  1. Write the failing test: a module whose reached function raises (xs[5] on a short list is undefined in JS, so use a call on None: self.missing.method()) is run with node --enable-source-maps; the stack trace names mod.py and the Python line of that call.
  2. Run: fail.
  3. Implement the mappings (base64 VLQ, line granularity: each emitted line maps to the Python line of the statement that produced it).
  4. Run: pass. Commit: feat(web): source maps to the Python lines.
11export --web (headless output)src/manifoldx/web/export.py · src/manifoldx/cli.py · tests/web/test_export_web.py

interfaces

consumes tasks 2–10 · produces export_web(module: str | None, script: str | None, out: Path, app_args: list[str]) -> int · the folder: app/<module>.js(+.map), pyrt.js, manifoldx.js, replay.mjs, state.json, scene.glb, report.json · manifoldx export --web [-m module | app.py] OUTDIR
  1. Write the failing tests: the CLI writes every file above for a small app; report.json lists each root, each transpiled function, and each function left as setup; a transpile error exits 1, prints file.py:line, and writes nothing; Review focus: an app with no systems and no GUI exports and its folder loads in Node; an app whose startup handler is async def exports with the handler's effect visible in state.json, or, if the engine's dispatch cannot await outside the loop, fails with "async startup handlers are not supported by export --web yet: <handler>".
  2. Run: fail.
  3. Implement. Capture the engine the way cli.export does (patch Engine.run, runpy); fire startup with engine._fire_startup() without creating a device (a handler that needs one, such as load_texture, creates it itself); order: roots, live types, reach, snapshot (which registers reached materials), transpile, then engine.export_gltf(out / "scene.glb"). Factor the shared capture out of cli.export into manifoldx.web.export.capture_engine(module, script, app_args) -> Engine and use it in both. Ship src/manifoldx/web/js/*.js as package data.
  4. Run: pass. Then uv build and unzip -l dist/*.whl | grep web/js: the three JS files are in the wheel.
  5. Commit: feat(cli): export --web writes the transpiled app and its state.
12The replay harness and the public examplesrc/manifoldx/web/replay.py · js/replay.mjs · examples/web_walk.py · tests/web/fixtures/web_walk_script.json · tests/web/test_replay.py

interfaces

consumes task 11 · produces Frame: {"keys": [str], "just": [str], "d": [float, float], "buttons": [int], "clicks": [int], "vp": [int, int]} · ScriptInput (Python, same API as InputState's public getters plus capture_pointer) · replay_python(module, script, frames, paths: list[str]) -> list[dict] · replay_node(out_dir, frames, paths) -> list[dict] · compare(a, b) -> Mismatch | None with .frame, .key, .left, .right · each trace frame: {"camera": {"position", "target"}, "gui": [str], "log": [...], "state": engine.state, "paths": {path: value}}
  1. Write examples/web_walk.py: a flat ground, six boxes with names, a first-person rig class in the app (walk with WASD, look with the mouse when the pointer is captured, Tab toggles a fly mode), a click that picks the box under the crosshair with a ray test written in the app and marks it with engine.set_material, a GUI panel with a ValueDisplay per line naming the picked box. No textures. It is the shape of the first consumer in 150 lines. Write tests/web/fixtures/web_walk_script.json: 600 frames from a seeded generator kept in the test file (the generator writes the fixture when --regen is passed), with clicks, Tab, Escape, right-drag and a resize.
  2. Write the failing test: compare(replay_python(...), replay_node(...)) is None for the example with paths=["rig.pos", "rig.yaw", "rig.mode", "selected"]; the trace has at least 3 distinct non-null selected values and at least one material entry, so the script exercises picking.
  3. Write the three breaking tests: patching the generated JS so the pick returns null, so the camera is a plain array, and dropping the boxes from the snapshot; each must make compare return a Mismatch.
  4. Run: fail. Implement. Run make test: pass.
  5. Commit: feat(web): replay harness and the web_walk example.
verify

uv run pytest tests/web/test_replay.py -v: 4 passed, and the parity test prints the frame count and the number of distinct selections.

13Docs and the PRknow-how/web-export.md · CHANGELOG.md · AGENTS.md (sub-projects line)
  1. Write know-how/web-export.md with a when: line: what reaches the browser, the subset and its errors, annotating when the export asks, the replay harness and how to write a script.
  2. Add a CHANGELOG.md entry under [Unreleased] and one line under "Sub-projects in flight" in AGENTS.md pointing at the spec and this plan.
  3. Run make test and make lint: pass. Push the branch, open the PR referencing #93 and #131, and work it until CI is green.
14The first consumer replays in its own CIthe consumer's repository: app code, a replay test, its CI workflow

Runs in the first consumer's repository after the manifoldx PR merges; its own issue, branch and PR. The consumer's agent docs name it.

  1. Pin manifoldx to the merge commit. Replace the three workarounds with engine.set_material, engine.input.capture_pointer and engine.input.viewport_size; its desktop tests and --shot still pass.
  2. Add a replay test: manifoldx export --web of the app into a temp folder, its own 900-frame script, paths=["rig.pos", "rig.yaw", "rig.pitch", "rig.mode", "selected", "captured"], compare is None.
  3. CI: install mesa-vulkan-drivers so the startup's textures get a software device, then run the replay test. If the adapter request still fails on the runner, record that under "where this plan departs" and run the replay in make check only.
  4. Its existing hand-written web viewer stays until plan 2 replaces it.

Where this plan departs from the spec