Import Design
Import benchmark rebuild control
The opt-in baked-native-rebuild lane in tools/import-design/design_import_benchmark.cpp
is a diagnostic full-rematerialization control. It is useful for measuring the
cost of rebuilding the same DesignIR, but it does not implement or prove a
structural retained planner. Keep the normal baked-native direct-setter lane
as the production baseline, and do not claim Chromium/Skia parity or planner
performance from the control alone. Structural claims require the authenticated
same-trace native receipts and identity/lifecycle evidence defined by the
planning trace matrix.
The rebuild control must replay the complete fixture state, including secondary
meter state such as the peak value; matching only a primary value changes the
rendered workload and invalidates retained-versus-rebuild comparisons.
The benchmark's host probes also compile into the Android APK, where
__linux__ is defined but bionic declares getloadavg only from API 29
(minSdk is 26). Guard a Linux-only libc call with
defined(__linux__) && !defined(__ANDROID__); android-build is skipped
on most PRs, so the break first shows on main.
To measure importer output rather than the built-in panel, pass
--ir=<design.ir.json> (baked-native and baked-native-rebuild only; live
and baked-cpp refuse it because neither can be built from a DesignIR) with
--frames=N. Fixed frames are what make the counters comparable run to run;
wall-clock pacing changes the frame count and every counter with it. Anchored
text nodes become keyed slots: the retained lane writes through the Label each
anchor resolved to at build, the rebuild lane rematerializes a copy of the IR.
The receipt binds the IR's sha256 and adds per-phase views constructed and
destroyed, slot identity changes and slot text mismatches, plus a terminal
teardown readback; a run that leaves live views exits 3. On the held-out
corpus the retained lane builds no views, rebinds no slots and records no
unmarked mutations, while the rebuild control rebinds every slot every frame
and records thousands of unmarked mutations. If the control ever reports zero
identity changes, the counter is blind, not the plan retained. --plant-leak
holds one subtree past the fixture's destruction to prove the readback fails.
--warmup-frames excludes warmup frames from every statistic, the cumulative
counters (paint_calls, paint_commands_total, layout_passes, bridge and
invalidation counts) included: they start at the first sampled frame.
Web-compat ui.js is flex-only: a DesignIR grid becomes wrapped rows
CodeGenMode::web_compat emits document.createElement + el.style, and the
web-compat runtime treats display:grid as a no-op (setGrid stores tracks but
never switches a view to LayoutMode::grid; only the bridge lane's createGrid
does). So generate_node lowers a row-flow grid with more than one column
track to flexDirection:'row' + flexWrap:'wrap', which reproduces the rows
for fixed-width cells. Single-column and column-flow grids keep the stacked
column. Every node with an authored height also gets flexShrink:'0', which in
a row parent pins its width too: a grid lowered as an unwrapped row overflows
rather than shrinking. Assert grid fixes on live bounds after
WidgetBridge::load_script, not on emitted text, and note that
emit_js_container (bridge lane) is a different emitter from the web-compat
generate_node. Forge's Designer link uses web_compat.
A DOM node's own layout row: one rule per language
Chromium's DOMSnapshot emits several layout rows for one DOM node: a
::before/::after box is followed by a zero-size generated-content row, a
list marker by its paint record, and a split inline by one row per line box.
The node's own box is the first row with positive area (a node whose rows are
all empty keeps its first). In C++ that rule is
CapturedStyleIndex::own_layout_row, which every per-node lookup and the
document-canvas proof read; in the differential lab it is
principal_layout_rows, read through snapshot.DomSnapshot. Never build a
{node: row} map from layout.nodeIndex directly: the last row wins and a
split inline's continuation or a pseudo's empty row silently stands in for
the node. test/fixtures/browser-capture-layout-rows pins both readers to the
same rows.
The lab's rescore subcommand replays a finished corpus's stored artifacts
through compare_one with no browser or importer build. Compare two
rescore.json files with cmp to prove a scoring refactor changed nothing.
Import a design from an external tool (Figma, Stitch, v0, Pencil, React Native, Claude Design, or the experimental JSX runtime lane) into this Pulp project.
Preconverted vector artwork is validation-only
The import-design CLI accepts a preconverted SVG only when its sidecar binds
the exact SVG SHA-256, source/provenance metadata, canvas dimensions, control
selectors, and bounds. Illustrator .ai, PDF, and other unconverted artwork
inputs fail closed with a diagnostic directing callers to a preconverted SVG;
this path does not implement Illustrator/PDF conversion or grant rights to
third-party artwork. Keep the sidecar and SVG together and retain both in the
import receipt.
Materialized browser source emission
For a browser capture that publishes materialized-document.json, use
pulp import-design --emit materialized-runtime --source-out <dir>. The CLI
stages src/MaterializedDocument.tsx, token and binding sidecars, the
normalized runtime document, and build.toml in the existing browser
transaction. Use --ids positional for legacy captures. --ids stable is
intentionally fail-closed: every binding must carry the complete
(component, local_path, content_hash) source tuple, and ambiguous historical
matches in ids.map.json are rejected. Verify deterministic output with
node --test tools/import-design/jsx-runtime/materialized_source_emitter.test.mjs
and keep the browser capture's Chromium validation receipt alongside the
emitted source tree.
No installed browser inside an agent sandbox
An installed macOS browser app (/Applications/Google Chrome.app and the
other .app candidates) registers with the window server even with
--headless=new. An agent sandbox (CODEX_SANDBOX set) denies that, so the
browser aborts at launch and macOS files a crash report for the user's own
Chrome. Browser discovery therefore drops .app candidates when
CODEX_SANDBOX is set, and the Chrome oracles skip (exit 77) rather than
launch one. In a sandbox, install a Pulp-managed browser or pass a headless
shell explicitly; never point PULP_CHROME at the installed app.
The capture browser runs at the capture's device scale
capture.mjs emulates its DPR with Emulation.setDeviceMetricsOverride, and
also launches Chrome with --force-device-scale-factor=<dpr> so the browser's
own scale agrees. Chrome composites backdrop-filter at the browser's scale:
with headless left at 1 under an emulated 2, a frosted box came back with
unblurred streaks of what was behind it (16,786 px on fixture
22-backdrop-opacity), and the lab charged that to the native render. Do not
drop the launch flag or emulate a scale the browser was not launched at.
At a real device scale Chromium reports DOMSnapshot layout bounds, text-box
bounds and content size in device pixels, so the capture divides those back
to CSS pixels (snapshotToCssPixels); without that the native lowering drew
every panel at twice its size. The snapshot's offset, client and scroll
rects and DOM.getBoxModel were already CSS pixels.
Testing a capture change against a built importer: pulp-import-design
runs the capture runtime staged beside its own binary
(<build>/tools/import-design/browser_capture-v1/capture.mjs) ahead of
PULP_BROWSER_CAPTURE_SCRIPT, so pointing that variable at an edited
capture.mjs silently runs the staged copy instead. Rebuild to restage it, or
copy the importer next to a runtime holding the edit, and check that the
captures actually differ before reading any score.
Browser capture provenance is an import boundary
The native importer validates capture.json before lowering the browser tree
or emitting a materialized runtime. Treat the capture envelope as a binding to
one exact input and capture environment: it must carry the staged editor.html
SHA-256, Chromium CDP identity, initial/resolved/document viewport dimensions,
matching device scale factor and reference viewport, plus, when the capture
recorded one, a contained materialized-document sidecar whose SHA-256,
schema/version, HTML field, and asset count agree with the envelope. Only
--emit materialized-runtime and --materialized-canvas-composition capture
that sidecar (browser_import_captures_materialized_document). Every other
import passes --omit-materialized-document, and the envelope then carries no
materialized fields, with no exception: Blob-URL @font-face faces are read
in the page into font-faces.json, so they do not need the sidecar. A stale,
hand-edited, mismatched, or
path-escaping envelope fails closed with the
browser-capture-provenance-invalid diagnostic. Keep the envelope and sidecar
from the same capture directory; do not copy one from an older browser run or
rewrite its source hash to bypass validation. The focused native coverage is
pulp-test-browser-capture-backend [*provenance*], and a real import must pass
the browser capture receipt before any native or materialized parity claim.
Importer differential calibration remains diagnostic until the receipt binds the
PNG digest and physical dimensions, viewport DPR, and interaction plan, then
records three agreeing source, importer, observer, font, capture, PNG, layout,
and native render receipt digests. Short campaigns remain unverified, and the
raw visual threshold is not relaxed by calibration or renderer disagreement.
Where a browser import spends its time
Every browser-lane import prints Browser lane timing: and writes
import-timings.json beside capture.json. Its stages are contiguous laps, so
they sum to the lane's wall time; the capture script's own phases
(provenance.timings, keyed by the progress tracker's phase names) nest under
browser-capture, and process-overhead names the subprocess time outside
them. capture_steps totals each CDP method and named unit; steps overlap and
nest, so read them as attribution, not as a sum. On Spectr the dominant cost is
the byte-stable screenshot horizon inside same-frame-capture (76
Page.captureScreenshot calls, about 60% of the import, split between the
accepted frame and the canvas-free chrome plate), followed by
browser-discovery, which launches a separate Chromium for the CDP capability
probe on every import. The chrome plate ships in the IR asset manifest, so
skipping it is not output-neutral even for lanes that never draw it.
Two identical imports never produce byte-identical DesignIR: imported_at,
settle_rounds (how many settle polls a loaded host needed) and the
content-addressed names of any asset that contains a live canvas all move.
Strip exactly those before calling a change output-neutral, and keep a
canvas-free asset's content hash (the chrome plate) as the pixel-level
control: it is stable across runs, so a change that moves it changed pixels.
HTML staging scans references from their literal starts
stage_html_project follows a project's dependencies with the three patterns in
html_project_stager.cpp (html_reference_pattern() and its two siblings).
Each ReferencePattern lists the literals its alternatives begin with, and
for_each_reference_match runs the regex only at offsets where one begins.
std::sregex_iterator over the same text yields the same matches, but it runs
libc++'s backtracking engine at every byte: on the 1.8 MB Spectr export that
was about 2 s per import. A new alternative must add its leading literal to
starts, or the scan never tries it; the differential case in
test_html_project_stager.cpp compares both scans over generated text and
fails when a literal is missing.
Captured line metrics travel as one `LineMetrics`
The capture's measured ascent/descent ride the line-box basis as
std::optional<LineMetrics> (pulp/view/text_line_metrics.hpp), and every
producer and consumer gates on LineMetrics::valid(): the sidecar parse, the
IR JSON parse, Label::set_cached_line_metrics and the bridge. The basis's
JSON (lineBoxes / lineBoxBasis) is read and written in
design_ir_json_text.cpp, with the shared field readers and member writers in
design_ir_json_primitives.hpp; add a basis field there, not in
design_ir_json.cpp, which is a frozen hotspot.
A captured page's own fonts ride the IR as `fontFamilyAssets`
font_faces.mjs reads every @font-face rule in the page's readable style
sheets, resolves each url() source against its own sheet, and keeps a face
only when Chromium loaded and decoded it. The capture's own network responses
say which staged or remote source answered, a data: or Blob source counts
when its family loaded, and the rule's FontFace status says whether
Chromium's font sanitizer accepted the file. A kept face's bytes must also
start with a TrueType (0x00010000/true), OTTO or wOF2 signature.
Anything else, WOFF 1.0 included (not every platform font manager decodes
it), is dropped, named in font-faces.json dropped and in the import's
warnings, and never handed to the platform font manager. register_font_file
sends WOFF2 files through register_font_woff2, so they decode the same way
on every platform. CoreText decodes WOFF2 itself, but a FreeType build without
Brotli does not. font_faces.mjs writes the bytes and descriptors to font-faces.json, and
attach_page_font_faces (tools/import-design/browser_capture_fonts.cpp)
writes each font once into the capture directory, adds it to the asset
manifest, and adds one font_family_assets entry per rule in page order, with
weight/weightMax, fontStyle and unicodeRange. A bundle's Blob font
(Claude standalone exports) keeps the pulp-materialized-asset-<sha256> id
its materialized runtime names it by; a file or data: font is
pulp-page-font-<sha256>. A Blob font is page input like any other: it is
typed and checked by its own bytes, never by the Blob's declared type, and a
Blob URL the page revoked before the capture read it is dropped by name. The
caps (256 distinct faces after verbatim repeats are folded, 64 MiB of
distinct bytes) leave room above real bundles, and Spectr declares 59. Descriptors of an inline <style> rule are read as
authored, because CSSOM re-serializes them (U+0000-00FF reads back as
U+0-FF) and DesignIR keeps them verbatim. Fonts never come from the
materialized document, so a capture that skips it still carries them. Without
them, native text is shaped with whatever same-named face the host has. For
JetBrains Mono that is the bundled static Regular, so 600 is synthesized and a
captured basis naming the variable instance (JetBrainsMono-Regular_wght2580000)
is rejected. A remote https font is read only with --allow-browser-network,
and a used face whose staged file is absent fails as capture-font-missing,
naming the authored path. Fixture: test/fixtures/browser-capture-font-face-url.
build_native_view_tree registers them before materializing
(core/view/src/design_import_native_fonts.cpp). Each unicode-range segment of a
family goes under a private alias, <family> [<12 hex>], named from its
content. Every font-family stack naming the family is rewritten to list the
aliases, last-defined first, in place of the family. So when you debug an
imported Label's face, expect effective_font_family() to show aliases, not
the CSS family. A face that can't be read or fails its manifest hash is
skipped with font-asset-unavailable, and that family keeps resolving to host
faces.
Generated JS registers a face that the export pass localized beside the script
(assets/<sha256>.ttf) with registerEmbeddedFont(family, 'assets/<sha256>.ttf', ...).
That is the name a UI_SCRIPT build embeds the file under. The call needs no
capability, so a shipped panel registers its fonts under an empty grant. It
never takes the manifest asset_id: no embedded file is named pulp-page-font-....
Only a face reachable solely by an absolute path still emits the
Filesystem-gated registerFont, and any registerFont in the script makes
infer_capabilities_from_js request Filesystem. So a headless tool that runs
generated JS (--validate's render, pulp-design-ir-observe,
pulp-design-import-bench) must seal the files beside the script into its
bridge with read_sealed_font_files (tools/import-design/sealed_font_files.hpp).
Putting registerFont back into the script instead would make the panel ask
for Filesystem. sealed_font_asset_name() is the single rule for that name.
A path-backed or hot-reloading ScriptedUiSession does the same host-side: it
seals the font files beside its script (symlinks that leave the directory are
skipped). Both bridge font calls check the sealed bytes' size and signature
(view::register_font_container) and never fall back to a path. A WOFF2 the
decoder rejects is refused, never handed to the platform font manager. A panel
may not rebind a family that host code or another panel's storage identity
registered first; registerEmbeddedFont returns false and logs why. Font
registration is process-global, so a test that probes it must use a family
name no other case registers.
Imported text looks heavier than Chromium: check font smoothing first
Pulp's default glyph raster on macOS is Chromium's `-webkit-font-smoothing:
auto pixel for pixel. kSlight` hinting turns CoreText smoothing on, and the
default SkSurfaceProps preblend applies. A design that sets antialiased,
which Tailwind's antialiased class and most design systems put on
html, body, therefore paints about 1.3x the glyph ink of its Chromium
capture. That looks like a rasterizer difference, but it is not one.
The two smoothing modes need different surface props:
antialiasedis reproduced exactly by hintingkNoneplus
SkSurfaceProps(0, kUnknown_SkPixelGeometry, 0, 1).
autoneeds today's defaults.
SkFont edging does not change the ink on a raster surface whose pixel
geometry is unknown.
Separate weight from placement with
tools/import-validation/text_raster_decomposition.py crops (ink ratio,
centroid, integer shift, transfer curve per text node) before you touch
baselines. It measures ink on either side of the box's background, so dark
text on a light panel reads as reliably as light on dark. Numbers it reported
for dark-on-light labels before it did were the glyphs' light fringe, not the
glyphs. On macOS the skia screenshot backend lives in
core/view/platform/mac/screenshot_mac.mm. core/view/src/screenshot_skia.cpp
is the non-Apple path, so a surface change made only there never reaches a
macOS render.
The import now carries the property. The capture records
-webkit-font-smoothing, the lowering stamps font_smoothing=antialiased on
those text nodes, and the materialized Label paints them unhinted
(Canvas::set_font_smoothing). The surface preblend is the host's job:
design_ir_text_raster_policy(ir) returns chromium when any captured text is
antialiased, and the observer creates its surfaces with it. A host or emitter
that renders imported text on a legacy surface still paints it heavy.
DesignIR JSON floats are shortest round-trip, not six digits
write_float_member (design_ir_json_primitives.hpp) writes each float with
std::to_chars, the shortest text that reads back as the same float. A plain
out << value uses the stream's six significant digits, which silently cut
Chromium's 1/64 px layout to 0.1 px from 1000 px up (a 1006.703125 px panel
became 1006.7 and the differential lab refused it as a different frame). Never
add a float member that bypasses the shared writer.
Rotated nodes: compare bounding boxes, not layout boxes
A Chromium DOMSnapshot bound is the box after its own and its ancestors' CSS
transforms; the native layout snapshot is the untransformed View box. Native
lowering turns a lone rotate(<n>deg) into View::set_rotation about the
box centre, so the differential lab maps each native box through the composed
rotations (importer_differential/native_transform.py) before measuring
geometry. A diagonal ADSR segment otherwise reads as a 90 px geometry failure.
Theme-painted form controls lower onto the Chromium-refresh skins
A captured <input type=range|checkbox|radio> whose native_theme verdict is
native has no CSS paint to lower. The capture records the HTML state the
theme paints from as ua_* attributes (browser_capture_controls.cpp), and
design_import_form_controls.cpp builds a RangeSlider / Checkbox in
UaSkin::chromium_refresh from it, in the native lane and the baked C++ lane
alike (ua_form_control_state() is the shared parse). The ui.js lane emits the
same widget and state from that parse (design_js_capture_lowering.cpp:
createRangeSlider/createCheckbox, createButtonSurface with its label as
children, setUaSkin, setCheckboxKind, the range, value and checked state), and every lane records the snapped paint rect
(setCapturedPaintRect in ui.js); Vellum's emitter conformance gate checks all of it. Only those controls get
the skin: an author or unresolved verdict, another import lane's checkbox,
AutoUi and every hand-built widget keep UaSkin::platform. Chromium paints a
theme part in its CSS-px-snapped box, so the skins paint in
View::self_paint_bounds() (the captured browser_box_paint_* rect), never the
fractional layout box; that is the 1 device px the Spectr slider was off by.
indeterminate and a disabled inherited from a <fieldset> are not in the
DOMSnapshot, so they are not recorded.
A native-verdict <button> records ua_control=button, ua_color_scheme and
ua_disabled, loses the UA stylesheet's grey background and 2px outset border,
and becomes a ButtonSurface (Chromium's push-button paint) in place of the
frame, with its text and icons kept as children. An `<input
type=button|submit|reset>` is the same theme part: it lowers the same way, its
value (or the UA's Submit / Reset default) the #control-value label child.
An author-styled button or button input keeps its captured paint and stays a
frame.
The differential lab knows which themed controls the lowering reskins
(THEME_SKINNED_TAGS / THEME_SKINNED_INPUT_TYPES in
tools/import-validation/importer_differential/form_controls.py, kept equal to
what record_ua_control_state records by a test). Those report
ua-theme-skinned, whose residual counts against the importer; every other
themed control (a select's arrow, text fields, meter, progress, the picker
types) stays the ua-default-form-chrome support boundary. Add a control to
both when you give it a native skin.
Emitter conformance: one IR, four lowerings, one gate
The native materializer, the ui.js emitter (design_codegen.cpp), the baked C++
exporter and the SwiftUI exporter each walk the IR on their own, so a lowering
added to one does not reach the others. Vellum owns this gate as the
vellum.design-emitter-conformance ctest (authoring/design_pipeline). It
builds its spectr, kelvin, form-controls, keyed-list and fidelity-scene fixtures through all four and compares, per anchor, the
anchored-view tree, widget kind, theme-control state, captured paint rect and
snapped self_paint_bounds(), and bindings, against the native lane. The baked
C++ is generated at build time by the Vellum gate, never
committed. A divergence must match an entry in allowlist.json, each linked to
an issue; an entry that matches nothing fails the gate, so delete it with the
fix. PULP_CONFORMANCE_REPORT=<path> writes every divergence as JSON. When you
lower something new in one emitter, run the gate before you claim the others
agree.
To see what a ui.js import looks like against Chromium, pass --emitter js to
the differential lab: the observer renders the candidate IR through its ui.js
program instead of the native materializer.
Page fonts: match on the declared range
prepare_native_ir_with_fonts registers each shipped face under a
content-named alias, and generated JS registers it with registerFont. Both
also hand each rule's declared font-weight range to
canvas::declare_font_face_weight_range: natively on the alias, from that
family's own rules (two families may bind one file with different ranges), and
in JS on the family. Chromium matches and synthesizes against the declared
range, not the file: one Regular file declared 400 700 draws 700
unemboldened, and declared 400 it draws 700 faux-bold.
registerFont declarations are owned by a unique per-bridge scope, separate
from the persisted storage identity: reload clears the retiring bridge's ranges
before registering the replacement realm, and bridge teardown removes only that
bridge's declarations. Lookup still unions declarations from all live owners of
a family; sharing a bare family across live editors with conflicting ranges is
therefore deliberately ambiguous and should use distinct family names.
paragraph_fakes_missing_font_styles decides SkParagraph's fake-styles switch
(CSS font matching over the declared ranges; bold only when the request is 600+
and the matched range ends below 600; italic keeps the default, which shares the
switch). It looks up each stack entry by its parsed name, because imported
stacks are quoted. Every paragraph Pulp builds must ask it, the painter and the
TextShaper measurement paths alike: SkParagraph's own shaping cache does not
key on the switch, so a measurement paragraph left at the default caches
emboldened runs that the painter then reuses, whatever its own switch says. A
canvas-only test does not reproduce that reuse; render a native tree.
A declared family also never yields to another family over weight in
match_registered_typeface: the resolver otherwise measured a 700 run in a
system face while the paragraph painted the page face, and the text wrapped.
Packaged SDK runtime contract
Illustrator/PDF vector-source boundary
PDF-compatible Illustrator artwork is a first-class source for the import CLI:
pulp import-design --from illustrator --file panel.ai --output panel.svg (the
ai and pdf aliases are equivalent). The command invokes the installed
tools/import-design/illustrator_to_svg.py helper through Pulp's argv-safe
child-process boundary. Poppler is an explicit runtime prerequisite; missing or
invalid converters fail closed. Every successful conversion writes a
pulp.illustrator-svg-provenance.v1 receipt containing source/output hashes,
the selected page, and converter identity. Existing SVG input continues through
the validated preconverted-SVG lane; the converter does not imply artwork
license or redistribute third-party design assets.
Release archives take the helper from the build directory, not from install():
tools/import-design/CMakeLists.txt stages it as
<build>/tools/import-design/illustrator_to_svg.py, and
tools/ci/release_package_cli.sh hard-fails when a release at or above the
product matrix's illustrator_import_floor lacks it. A new file listed under
import-design/ in release_product_matrix.json needs the same staging.
Every path the helper writes (the SVG and the receipt, explicit or default) goes
through _writable_destination, which refuses a symlink on the path as given.
Check before resolve(), never after: a resolved path is never a symlink, so a
check placed after it cannot fire, which is how a symlinked --provenance was
once written through to its target. Stage writes through mkstemp, never a
fixed .<name>.tmp, which a pre-planted symlink can redirect.
Compare destinations by file identity, and a destination that does not exist
yet by its name decomposed (NFD), case-folded and decomposed again: APFS treats
ART.PDF and art.pdf, and the NFC and NFD spellings of café.svg, as one
file, while resolve() keeps the caller's spelling.
The installed pulp-import-design SDK runtime includes the browser-capture
manifest plus the materialized JSX siblings
materialized_binding_contract.mjs, materialized_source_emitter.mjs, and
materialized_ids_map.mjs. Keep all three installed under bin/jsx-runtime;
the release provenance handoff hashes the complete tree and rejects a missing
sibling or an undeclared extra. Validate the archive with
python3 tools/scripts/test_release_artifact_contents.py before publishing.
A new module capture.mjs imports must be named in FOUR lists, not one:
browser_capture/runtime_manifest.txt (the source of truth CMake installs
from), tools/cli/upgrade_install.hpp (browser_capture_runtime_files),
experimental/pulp-rs/src/install_import_design.rs
(BROWSER_CAPTURE_RUNTIME_FILES), and tools/scripts/release_product_matrix.json
(common_cli_members). A source build passes with only the first; the miss
surfaces as the upgrade-manifest tests (C++ and Rust) or, worse, as an
upgraded SDK whose capture cannot resolve its own module graph.
TOOLS THIS SKILL ALREADY SHIPS — reach for these before hand-rolling (read this first)
Every one of these is documented further down this file. That was not enough:
an agent verifying an import hand-rolled PIL crop scripts instead, because the
guidance sat ~1,000 lines deep and a sibling skill told it to use PIL. If you
are about to write a script that opens two PNGs and diffs them, stop — it
exists:
| Need | Tool |
|---|---|
| "It looks off" → which node, and by how many px | pulp-import-design … --validate --dump-layout L.json then python3 tools/import-design/layout_parity.py L.json |
| "It looks wrong but nothing failed" → was a property DROPPED? | node tools/import-design/material_audit.mjs --fig d.fig --frame F — run this FIRST on any fidelity complaint |
| Labeled N-panel comparison montage | python3 tools/import-design/montage.py --out cmp.png ... |
| Per-widget fidelity audit + JSON report | python3 tools/import-design/fidelity_diff.py --render r.png --scene scene.pulp.json --assets-dir DIR --frame-reference src.png |
| Side-by-side + heatmap + top offending regions | python3 tools/scripts/figma_import_diff.py — use after EVERY codegen change |
| Render an import at the design's own canvas size | tools/scripts/render-figma-import.sh |
| "It matches the reference and still looks wrong" → is the PALETTE itself bad? | python3 tools/import-validation/check_palette_health.py --pack DIR --theme dark\|light (also --tokens/--artifact) |
| Masked per-region diff vs a reference | python3 tools/import-validation/diff_against_reference_regions.py |
| Re-import regression vs a golden | python3 tools/import-validation/golden_regression.py |
| Measure native HTML importer convergence against Chromium | python3 tools/import-validation/importer_differential_lab.py |
| Rasterize Figma vector frames | python3 tools/import-design/figma_rasterize_vector_frames.py |
| Before importing agent-authored HTML/JSX: contracts + realtime performance | python3 tools/import-design/check_contracts.py panel.html [app.jsx ...] [--system DIR] [--macros M.json] |
| Is the app's vendored runtime.js older than this SDK's @pulp/react? | python3 tools/import-validation/check_vendored_runtime.py <runtime.js\|app-dir> (CMake: pulp_check_vendored_react_runtime(<bundle>)) |
The full, machine-checked list is docs/status/tools.yaml (with inputs,
outputs, and availability for each), and its digest is generated into CLAUDE.md
so it is always in context. The table above is the fast path for this skill's
own work; the registry is the source of truth, and a coverage sweep in
tools/scripts/tools_registry_check.py fails CI if a tool lands here without
an entry — so nothing can go quiet the way fidelity_diff.py did.
A region score near 1.0 does not mean the region's controls are drawn.
diff_against_reference_regions.py scored Spectr's bottom toolbar 0.990 with
its range slider missing, because the bar's background dominates both the
histogram and the mean-pixel term. Whole-panel ink coverage could not see it
either (0.978). Read largest_uncovered_px: a missing element shows as one
uncovered patch at its own size (967 px at the default 1320x860 frame, 16 px
with the slider pasted back, 0 between two Chromium captures). Patch limits
are max_uncovered_fraction of the whole frame, so they hold at any --size;
the JSON also prints the limit in pixels of the current frame. Animated regions, like Spectr's
spectrum canvas, disagree on patches of thousands of pixels between two
captures, so gate those on coverage_floor only.
**Run check_contracts.py on every agent-authored panel before importing
it — its realtime gate is the one check here that sees frame cost.** A React
state setter inside onPointerMove / onMouseMove / onWheel (either phase),
a requestAnimationFrame loop or a repeating timer commits the whole captured
document on every event; one materialized editor measured ~42 ms per
pointermove against ~0.2 ms for the same element's mousemove. Screenshots,
pixel scores and the browser capture are all blind to it. The gate also flags a
setter called with a fresh object/array in a sync effect (every run commits) and
one handler registered for both capture and bubble phases, each with
file:line and the fix. It is static: it follows local functions a few calls
deep but not props, context or imports, and a clean run is not a frame-rate
proof — the view-bridge skill's "Realtime scripted editors" checklist and the
trace-analysis skill are. Without --system / --macros it still runs the
realtime gate and says which contract gates it SKIPPED.
A vendored runtime does not update itself. Materialized and JSX imports
compile @pulp/react into a bundle the app checks in; a later SDK fix (the scoped
captured-metadata re-apply, ~44 ms per commit) never reaches it until the
transform is re-run. Bundles now carry a /* @pulp/react runtime revision N */
banner from packages/pulp-react/runtime-fingerprint.json;
check_vendored_runtime.py (or pulp_check_vendored_react_runtime() at
configure time, warn-only unless STRICT) names each missing fix and the
refresh command, and judges banner-less bundles by each fix's signature. Bump
the manifest's revision and add a fix entry when a runtime change is worth a
refresh. Revision 2 added the per-pass path memo, per-pass typography dedup,
unread data-* attributes and reconciled captured paint as paint-only
commits. A signature must be an identifier the SDK runtime actually emits
(runtime_fingerprint.test.mjs checks each one against the generated entry
and the @pulp/react source) and one a hand-patched vendored copy is unlikely
to share.
Canonicalize repeated inline JSX once per document. Claude and agent HTML
exports can repeat the same text/babel or text/jsx program in several
<script> blocks. materialized_runtime_canonicalization.mjs memoizes the
deterministic esbuild result for that one document pass, while still emitting
each script and preserving jsx_scripts_compiled as the script count. Keep
the cache scoped to the call so one untrusted document cannot retain another
document's source or grow across imports.
Canonicalization must fail closed on duplicate asset IDs. Asset IDs join
HTML references to captured payloads. If malformed input repeats an ID, do not
let a trusted vendor payload remove an authored payload that shares the key;
preserve all colliding assets and report the collision in
runtime_canonicalization.duplicate_asset_ids_preserved. Capture-produced
documents have unique IDs, so this guard is transparent on the normal path.
Keep a planted collision regression alongside the canonicalization tests.
Pixel comparison cannot see a bad palette. Every visual gate above scores
agreement with the source, so a colour defect the source ALREADY had — an accent
that swallows its own ramp, a caption tier under its contrast bar — reproduces
faithfully and passes. check_palette_health.py judges the token values
themselves instead: accent-ramp structure, named-hue survival, and each text
tier against the QUIETEST surface it can land on, not just the app background.
Reach for it on any "looks off / illegible / wrong colour" report that a
pixel diff calls clean. Its bars are declared-value upper bounds — anything
composited under the type only takes real contrast lower.
It also judges whether the four status roles survive red-green colour
blindness, which no contrast check can see: contrast is a luminance measure,
so --success and --danger can each clear their bar against the surface
and still be one colour to the ~8% of men with a deficiency. That lane
REPORTS rather than blocks unless you pass --strict-cvd, for two reasons
worth knowing before you promote it: the bar sits in a narrow gap between
palettes designed to survive CVD (Okabe-Ito's worst pair is 11.6) and the
traffic-light pairs products ship (Material red-700/green-800 is 9.1), and
the tool also judges imported third-party designs, where a red/green status
hue is the designer's choice and not a Pulp defect. It models a dichromat
(severity 1.0), which is conservative for the anomalous-trichromat majority,
and it measures TOKEN PAIRS — necessary, not sufficient, since a UI that
disambiguates by icon or position can be fine while its tokens collide.
Check geometry BEFORE you look at pixels. A .fig carries Figma's
already-SOLVED rect for every node — auto-layout children included — so where
each node belongs is a known number, not something to infer from a screenshot.
--dump-layout writes Pulp's laid-out rects plus the design's own (as a
<stem>.geometry.json sibling), and layout_parity.py joins them by node id:
pulp-import-design --from fig --file d.fig --frame 'Main' --output ui.js \
--validate --screenshot-backend skia --dump-layout /tmp/layout.json
python3 tools/import-design/layout_parity.py /tmp/layout.json # exit 1 = findings
--validate writes its render PNG beside --output (e.g. ui.js →
<name>-<source>-render.png in the same directory), not into the CWD — so it no
longer litters whatever directory you ran it from. Pass --output into a temp
dir to keep artifacts together.
This is pixel-free — no thresholds, no anti-aliasing noise — and it answers the
question a screenshot cannot: which node, off by how much, and under which
parent. Deltas are parent-relative and clustered by parent, so a shifted panel
is ONE finding rather than one per descendant, and a group of children sharing
one offset is reported as an alignment/padding drop on the parent by name.
Unmatched ids are listed as dropped/extra — a completeness check no pixel
heuristic can match. Reach for this FIRST when a layout looks wrong; the
montage/heatmap tools tell you that something moved, this tells you what.
--gate-px 16 blocks only on displacement above 16px and reports the rest as
advisory drift — a correct import of the reference design tops out at 12px,
while a dropped auto-layout contract produces ten findings above 16px. The
import-layout-parity-gate ctest runs the whole pipeline on
test/fixtures/imports/fig/synthetic.fig and is strict (exact parity).
HTML/JSX imports have the same check, with Chromium as the design side.
The browser capture already holds Chromium's box for every laid-out node
(dom-snapshot.json, keyed by backendNodeId), and the IR stamps that id on
each node it lowers, so no adapter script is needed:
pulp-import-design --file p.html --emit ir-json --output p.pulp.json --native-panel-lowering
pulp-design-ir-observe --input p.pulp.json --render r.png --layout obs.json --width W --height H
python3 tools/import-design/layout_parity.py --capture p.pulp-browser-capture --observer-layout obs.json
--json also writes a boxes list: every matched node's Chromium box, native box
and delta, so a node that was checked and fine is distinguishable from one never
compared. A 4px move of a small element leaves the pixel similarity score near
1.0 and still fails here with the node id.
Three things that are not obvious. Parents come from the DOM, not the IR: a
native panel is lowered FLAT under browser:root, so IR parents would cluster
the whole page into one finding. The DOM parent is the nearest ancestor the
import LOWERED, walking past wrappers it skipped (the importer drops empty,
non-painting boxes); stopping at the direct DOM parent leaves such a node
parentless and reports a moved container's children as misplaced too. The
capture must be the IR's OWN capture:
backend ids are small sequential integers, and a second capture of the same
page joined all 105 of Spectr's ids cleanly — a wrong pairing looks right — so
the tool compares the IR's recorded capture-image hashes and exits 2 on a
mismatch. And a "share offset … alignment/padding dropped" cluster compares
dx/dy only: on Spectr it named three SVG paths whose real fault was their SIZE
(primitives boxed at the SVG viewport), so read each child's dw/dh before
trusting the diagnosis.
It validates BOXES, not the ink inside them. A label whose glyphs are shoved
to one side of a correctly-placed box, an icon drawn at the wrong scale inside
right-sized bounds, a colour, a gradient — all invisible to it, by construction.
This is not hypothetical: an icon-placement change that moved glyphs within
their correct boxes made fg-icon findings disappear and layout_parity went
greener while the render got worse. **Never read a clean layout_parity as "the
render is right."** It means the boxes are right.
EXTRA means "the render invented a node" — and only that. The synthetic
<key>/mask-scope clip wrappers the mask lowering adds (scene.mjs) have no
design counterpart by construction, so they are tallied separately
(synthetic_extra in the JSON, an "ignored N synthetic mask-scope node(s)"
line in the text) instead of polluting EXTRA with ~16 fixed false positives per
FX file. The whitelist is a narrow suffix match (/mask-scope, `" (mask
scope)"`), never a substring grep — a real node containing the marker mid-id
still counts as EXTRA.
The other half is TWO tools, not one, because they fail differently.
material_audit.mjs counts what the .fig DECLARES against what the import
emits, so it answers "was this dropped?" — deterministically, with no reference
image. thumb_parity.py compares block means against Figma's own raster, so it
answers "is the colour roughly right?" — and it is blind to anything that
preserves a region's mean. Reach for the audit first: a property that never
survived cannot be diagnosed by looking at pixels, and it is the cheaper
question. Neither proves the render is CORRECT; a human looking at a montage is
still the final say. (The audit's checks iterate declared occurrences, so a
node declaring the same property twice — knob bases carry doubled DROP_SHADOWs
in the reference files — would print the same finding line twice;
dedupFindings collapses byte-identical findings at the report boundary while
the count tables keep tallying occurrences.)
The one thing this design's fg-icon bug proves about all of them: **every checker
here went green while the icons were visibly broken.** layout_parity said the
boxes were right — and they were, because the box had collapsed to width 0 and
the glyph inside it was absolutely positioned, so the finding it did report
(dx=+6.5 dw=-12) read as a placement problem rather than the sizing one it was.
Read a tool's number as the answer to the question it asks, never as "the import
is fine."
Free offline ground truth: every .fig is a ZIP containing thumbnail.png
(Figma's own raster of the design) and a meta.json whose render_coordinates
thumbnail_sizegive an EXACT canvas→thumbnail transform — no image
alignment, no MCP, no REST, no rate limit. Note the thumbnail is ~0.4× (400 px
wide for a 1004 px design), so it adjudicates layout, colour, and presence —
NOT glyph-level detail. Do not draw fine conclusions from a 5× upscale of it.
Packaged asset recovery stays hash-gated. A .pulp.zip may contain the
right bytes under its own assets/ directory while an older producer left an
export-machine path in asset_manifest.local_path. Runtime resolution may
recover the same leaf from <document-dir>/assets/ only when the manifest
declares a SHA-256 and the candidate's bytes match it exactly. A same-name file
with different bytes remains unresolved and must keep the fail-closed
native-materialize-unresolved-asset diagnostic.
--validate renders at the design's own canvas size by default. Do not
pass --render-size unless you specifically want a different size; a mismatched
render and reference makes every similarity score meaningless.
LOCAL-FIRST — never start with the REST script when Figma desktop is open (read this first)
The headless REST exporter (figma_rest_export.py, used in the steps below) is
the CI / true-headless fallback. On a dense real file it **WILL be
rate-limited** (HTTP 429): Figma's /images render endpoint is a strict Tier-1
budget keyed to the file's plan, so a big frame can 429 for many minutes.
But the Figma MCP is ALSO quota-limited — do not treat it as free. On a
View/Collab seat the MCP is 6 tool calls per MONTH (any plan); Dev/Full seats
get 200–600/day + a per-minute cap. Every read tool counts (get_metadata,
get_screenshot, get_design_context); write tools (whoami,
generate_figma_design) are exempt. This is a hard MONTHLY quota — **backoff
cannot clear it**. So be maximally frugal. Order of preference, smartest first:
- Reuse a CACHED artifact. Prior sessions cache Figma PNGs/scenes under the
session scratchpad. find … -iname '<file>*' BEFORE spending a call — a cached
source screenshot suffices for source-vs-implementation checks with zero calls.
- Export a scene for import → the Pulp Figma desktop plugin
(tools/figma-plugin) exports the figma-plugin-export-v1 envelope (SVG +
node tree) directly from the open file — no MCP tool call, no REST budget.
This is the truly-unlimited local path; once you hold the envelope, all
importer/render work is offline forever. Prefer this to spend ZERO quota.
The plugin also exposes an explicit, offline Forge bridge:
Copy for Forge wraps that same scene plus content-addressed assets in the
versioned pulp-figma-clipboard-v1 text envelope; Import pasted Forge UI
accepts the reciprocal canonical DesignIR envelope and rebuilds editable
hierarchy, layout, stable source identity, and audio-widget bindings. This is
intentionally a plugin-mediated copy/paste protocol, not a claim of native
Figma Cmd+C clipboard compatibility.
- Inspect / verify a design → the Figma desktop MCP, but BUDGET the
6/month. When you must call, use ONE get_design_context (reference code +
screenshot + metadata together) instead of separate get_metadata +
get_screenshot, and never re-fetch what you cached.
- Only in true headless / CI (no desktop, no MCP) →
figma_rest_export.py.
Its figma_get honors 429 Retry-After with backoff; if it 429s it prints a
loud one-time advisory pointing back here — **switch to (0)/(1), don't wait out
6×300s of backoff. Pass --cache-dir DIR** to memoize the two REST-heavy
payloads (the /nodes geometry JSON + the frame SVG) per (file_key, node_id):
the first run populates the cache, every re-run reads it with ZERO REST calls
and needs no token — so iterating on the importer against a real Triaz frame
costs one fetch, not one per test. --refresh-cache busts it. This is the
transparent form of the manual --node-json / --frame-svg inputs.
Everything below documents lane (3)'s mechanics because it's the scriptable one,
but the ordering above governs which lane to start in. figma_rest_export.py
mirrors the desktop plugin field-for-field, so a scene from lane (2) or (3) is
interchangeable downstream.
There is no lane (4): pulp import-design --url cannot import from Figma.
Do not reach for --from figma --url 'https://figma.com/design/…' — the CLI
help and docs advertised it for a long time, but it never worked. --url is a
bare unauthenticated curl -fsSL (fetch_url_to_file) and the CLI has no
credential flag at all, so figma.com returns 403 for a private file and the
web app's HTML shell for a public one; the shell then dies deep inside
choc::json::parse with an error that looks like a parser bug rather than an
auth problem. The CLI now rejects figma.com design//file//proto/ URLs up
front (tools/import-design/figma_url.hpp) and names the lanes above. Note the
two --url flags are different: figma_rest_export.py --url is real — it
parses file-key + node-id out of the link and fetches with a token. The only
authenticated Figma REST client in the repo is that script; nothing in the C++
CLI can talk to Figma.
Figma → Pulp, faithful (1:1) — THE WORKING LANE (read first)
When the goal is a visually faithful (1:1) import of a component that lives in
the Figma file (e.g. the Ink & Signal library, file key q9iDYZzg86YrOQKr6I3bY0),
use the figma-plugin faithful-vector lane. This is the lane that actually
reproduces the design; the others below do NOT and waste hours:
- ❌ Do NOT hand-write a C++
paint()to mimic the design. It is never 1:1
(SVG icons, gradients, shadows, pills) and is pure slop. The framework exists
to render the design, not to re-draw it by hand.
- For runnable HTML, including Claude project exports,
.dc.htmlcomponents,
standalone bundles, and ordinary HTML, use `pulp import-design --file
<path>`. The CLI auto-detects the shape and evaluates it with isolated
Chromium; do not choose a parser by filename or add --execute-bundle.
--from claude remains accepted but is no longer needed for HTML.
The result is a pixel-exact static default frame. Semantic evidence is
diagnostic; live browser interactions require a runtime bridge. Captured CSS
variables describe only the active light / no-preference computed mode, and
only values visible on documentElement or body are promoted as global
tokens; component-scoped values remain capture evidence.
Browser selection is automatic and deterministic: explicit --browser,
then PULP_DESIGN_BROWSER, then PULP_DESIGN_BROWSER_MODE /
import_design.browser, then an explicitly installed managed Chrome for
Testing, then system Chrome/Chromium. Imports never download a browser.
If system discovery is insufficient, run
pulp tool install chrome-for-testing; use
pulp tool doctor chrome-for-testing --run for diagnostics.
Chrome's solved appearance reaches the IR through dom-snapshot.json.
DOMSnapshot.captureSnapshot is asked for the COMPUTED_STYLES list in
browser_capture/semantics.mjs, and the values land in
documents[0].layout.styles — rows of string-table indices, one row per
layout node, each row positional against the requested property list.
browser_capture_styles.cpp owns the join and the CSS→IRStyle mapping.
Facts worth knowing before touching any of it:
- **The rows are addressed by layout node; the semantic report is addressed by
backend_node_id.** The join is three hops: backend id → node index
(nodes.backendNodeId) → layout index (layout.nodeIndex) → style row.
- The list is sized for drawing a whole panel, not for describing a control.
A property the capture does not collect is one no consumer can ever draw — the
box arrives with that appearance defaulted, which renders as a plausible wrong
picture rather than an error. Collecting one costs a string per node;
re-capturing a corpus to add one later costs every design. So when in doubt,
collect it. Two properties earn specific mention: without background-size
the standard CSS grid idiom (a hard-stop gradient, tiled) lowers to a single
1 px line instead of eight columns, and reading only border-top-style makes
a dashed left border vanish — hence all four border-*-style are collected.
- A node can own more than one layout entry. A box that also lays out an
inline text box contributes two entries with the same nodeIndex; a
::before with generated content is the everyday case. Take the first
entry — the node's own box — so the choice is defined rather than
last-write-wins.
textBoxesare fragments, not guaranteed visual lines. Chromium can
report whitespace-separated inline runs such as "01 " and "RATE" as
separate entries with the same top coordinate. Coalesce same-baseline
fragments before deciding whether text wrapped. One coalesced line remains a
cache-capable paragraph with one captured box; do not lower it to permanent
white-space: nowrap, because a stale width/face/text basis must reflow.
Two or more distinct line tops use the same cache path with multiple boxes.
A same-baseline offset gap may be normalized only when its
omitted source range is entirely CSS-collapsible whitespace; otherwise drop
the captured-line decision and reflow normally rather than inventing a new
line. Validated captured boxes must reach both direct native materialization
and generated-JS setCapturedLineBoxes; merely enabling multiline lets the
two routes choose different breaks. Treating the raw entry count as the line
count makes an ordinary single-line label wrap in the Skia result.
- Element index N in the page is not element index N in the snapshot. The
page walk is document.querySelectorAll('*'); the snapshot also emits
pseudo-element boxes (::before / ::after) and shadow-tree content as
nodeType === 1. Counting those re-points every control after the first
::before at the node before its own — which still resolves and still looks
like data. snapshotElementNodes() in semantics.mjs is the one place that
correspondence is computed; every per-candidate snapshot value
(backend_node_id, paint_order) goes through it, and a candidate whose tag
disagrees with the node it landed on raises capture-node-alignment-mismatch
rather than shipping a neighbour's data.
- Paint order is consumed, never re-derived.
includePaintOrder: truemakes
Chromium answer "what paints on top of what" directly, and each candidate
carries that integer as paint_order. Do not sort by z-index instead:
opacity, transforms, filters and will-change all create stacking contexts,
so a z-index sort agrees on simple pages and diverges silently on exactly
the layered panels this exists for. A laid-out document that arrives without
paintOrders raises capture-paint-order-missing — a tree of nulls would
read as "this page has no layering".
- A control's own node usually carries only its label's styling. The
gradient, radius, and shadow stack that make it look like a knob sit on an
inner face element. Resolve through the candidate's paint_bounds — match it
against layout.bounds within the candidate's subtree — or you get the
caption's font where you expected the knob's fill.
computedStyleNamesin the snapshot is the property order. It is written
alongside the data precisely so no consumer hardcodes a parallel copy of
COMPUTED_STYLES; a drifted copy does not fail loudly, it maps a background
into a border. A snapshot without that key is skipped rather than decoded
against a guess.
- **Gotcha — the capture's path-redaction pass used to eat the CSS alpha
separator.** sanitizeSnapshot (security.mjs) rewrites bare local paths to
<local-path>, and a lone / surrounded by spaces matched. Chrome serializes
translucent modern colours as oklab(L a b / 0.34) — and `color-mix(in oklab,
… )` resolves to exactly that — so every translucent colour and every
box-shadow layer arrived unparseable, silently, with no error and no log. The
regex now requires at least one character after the slash. If you touch those
redaction regexes, re-run the capture on a panel built from color-mix() and
grep the snapshot for <local-path>: zero hits is the pass condition.
- Do not carry
transformonto a control node. It is placed by its
paint_bounds, which is already the transformed rectangle; re-applying the
matrix transforms it twice, off its own artwork.
- A declared knob pointer has two geometry contracts.
indicator_bounds
remains its page-space painted footprint for sprite crop/erasure, while its
nested intrinsic box plus six-number transform preserve the pointer's own
width and orientation for lowering. Never derive rotated pointer thickness
from the axis-aligned footprint: a 4x38 needle at 38 degrees sweeps roughly
26.5x32.4 and becomes a slab. Keep unrotated, scaled-viewBox, fractional HTML,
CSS zoom, and non-scaling-stroke cases when changing this capture contract;
unsupported projective or motion-path transforms must decline oriented
geometry rather than publish a partial matrix.
- Do not carry a border colour without a border width. Computed style
reports border-*-color on every element whether or not one is drawn, so an
ungated mapping paints borders the design never had.
**Whole-tree lowering (native_panel_lowering, opt-in) draws the panel from
its nodes instead of photographing it.** browser_capture_tree.cpp lowers every
painted node in the snapshot into a tree under the IR root. Two invariants that
are routinely confused, and the confusion is expensive:
- "Yoga must not re-solve" is the invariant. It is satisfied by every node
being position: absolute with Chrome's own solved width/height/offsets.
Yoga takes an absolutely positioned child out of flow, so nesting adds offset
arithmetic and no flex resolution — a Yoga-vs-Blink divergence stays
impossible however deep the tree goes.
- **"The tree must be flat" is NOT that invariant, and flattening costs the
editing surface.** A design gets edited section by section, which means an
agent has to be able to name a section and get its contents with it. Flat, two
div.face nodes are indistinguishable and there is no group to grab. So DOM
parentage, ids and class-derived names are preserved, and a child's box is
stored RELATIVE to its parent — which is what makes "move a container and its
children follow" true by construction rather than by special case. Composing
the offsets back down a chain returns Chrome's absolute box exactly; Blink's
1/64 px values survive binary32 unrounded, so the tests assert them with no
tolerance.
Ordering follows Chrome's paint model, which is itself hierarchical: siblings
are emitted in paint_order and carry it as z-index, so order lives inside
its stacking context rather than in one global sequence. Two consequences worth
knowing before you touch that file:
- A node that paints BEFORE its own DOM parent is hoisted, and flagged. A
nested painter always draws a parent's box before anything inside it, so a
negative-z-index child (or a descendant that escaped to an outer stacking
context) cannot be expressed in place. It is regrafted onto the nearest
ancestor that works and carries paint_order_hoisted + hoisted_from; the
root counts them in native_nodes_hoisted. Never reorder one silently. On a
real panel this is a handful of backdrop divs, not a rarity.
- **Re-expressing one flat order as a hierarchy can reorder interleaved
subtrees — native_nodes_overlapping_reorders is the honest measure of
whether it mattered.** Reordering disjoint boxes is invisible to the painter's
algorithm; reordering overlapping ones is a real regression. Only the
overlapping half is counted, and the count is recorded only when non-zero.
native_tree_root_children/native_tree_depthare the shape. A depth
of 1 means the lowering reflattened and every per-node count still looks
right, so check the shape, not only the census.
- A captured
<canvas>does NOT by itself flatten the panel. Canvas panels
lower hierarchically first (hoisting already covers a canvas that paints
before its parent) and switch to the flat paint-order list only when that
hierarchy reports overlapping_reorders > 0; the count that forced it is
recorded as native_tree_flattened_overlapping_reorders. Always flattening
on a canvas cost static canvas panels their sections for no fidelity gain.
- **The flat list still nests at compositing groups, and must not multiply
alpha instead.** An opacity < 1, mix-blend-mode, filter,
backdrop-filter or mask root keeps its descendants as children so the
View composites them as one layer; hung off the root they paint at full
strength beside an empty translucent box (Spectr's dimmed captions and
disabled ▸A/▸B came out 2.3-3.6x too bright). Pushing the group's alpha
into each descendant is only right where they do not overlap: a chip over
its button's fill comes out f/4 levels lighter (50 for a 200 fill).
native_tree_isolating_groups_nested counts kept groups;
native_tree_isolating_groups_refused counts groups left flat, each with
isolating_group_refused (interleaved-paint-order,
descendant-ink-outside-group because the View's layer is bounded by the
root's box, descendant-escapes-group-clip, transform). A refused group
is still wrong on screen; the reason says what to fix.
- A canvas snapshot is a VIEWPORT PLANE, not an element raster. Capture
composites the canvas bitmap into its content box on a transparent,
capture-sized PNG. Native lowering keeps the canvas as a box (its border and
background paint normally) holding the plane as an image child at the page
origin, clipped to the content box and anchored <canvas anchor>/layer[0].
Drawing the plane into the canvas box with fill shrinks the whole page
into the canvas. Only an asset whose pixel size matches the capture is
treated as a plane.
- Every lowered node, SVG shapes included, carries
backend_node_id. A
vector node's box is its root <svg>'s box (the viewBox frame), never the
shape's ink box, so anything comparing geometry by identity must compare a
shape against Chromium's <svg> box (the differential lab labels these rows
reference_frame: svg-viewport).
- A node can own several DOMSnapshot layout rows. A pseudo-element's own
box is followed by a zero-size row for its generated content at the page
origin; a reader that keeps the last row per node sees every ::before as
empty. Use the first positive-area row.
- Clips snap with the box paint. A clipper's box paints on
floor(edge + 0.5) CSS edges, and so does Chromium's overflow clip; lowering
snaps the stored clip the same way (only when a device scale is known), or a
rounded track's clipped fill lands one device row off at half-pixel offsets.
- **Clipping travels with the node, NOT with its place in the tree — never put
overflow back on a lowered node.** A tree that carries overflow clips by
DOM parentage, because a renderer applies it to whatever the node's children
turn out to be. CSS clips along the containing-block chain, and the two
disagree in both directions: an absolutely positioned node whose containing
block sits above an overflow: hidden ancestor escapes that clip in Chrome
(nested under it, where the boxes do not intersect, the node disappears
entirely), and a hoisted node regrafted past the ancestor that clipped it
paints outside the box that contained it. No re-parenting fixes both. So
lowering resolves each node's real clip chain — overflow along the
containing-block chain, taken against each clipper's PADDING box — intersects
it to one rectangle, and stores it on the node in the node's own space
(IRStyle::clip_rect, clipRect in the IR JSON). overflow is dropped from
every lowered node; the rectangle is the only authority.
- It is applied to the node's own ink, never inherited. The engine slot is
View::set_ancestor_clip_rect, and paint_content releases it before the
children, each of which carries its own. That asymmetry is load-bearing: a
child can legitimately need a WIDER clip than its parent (it escapes a
clipper the parent is inside), and an inherited clip is an intersection and
cannot widen. Merging it into overflow re-creates the original defect.
- **
native_nodes_clip_over_applied/native_nodes_clip_lostare now the
audit, and both should be absent.** They are computed off the emitted tree —
each node's stored rectangle composed with whatever its emitted ancestors
clip — against the CSS chain resolved independently, so a rectangle written
in the wrong space, dropped, or re-inherited from a parent's overflow
shows up as a number. A non-zero value is ink the panel draws wrongly.
- The panel frame's crop is not a disagreement. The root's own
overflow
is on both sides of the audit: a node the frame cuts is out of frame, not
mis-clipped, and counting it would fire on <html> for every cropped
capture.
- Known limits of one rectangle. A
clip-pathancestor clips to a shape
the rectangle cannot carry, so those nodes are counted in
native_nodes_clip_lost and carry clip_inexpressible="clip-path" — they
draw too much, not too little. A clipper's border-radius is likewise not
carried, so a rounded clipper under-clips at its corners; the audit compares
axis-aligned rectangles and cannot see that, deliberately — counting every
rounded card would bury the defects it exists to find. A rotated node
carries no stored clip either — a page-space rectangle has no meaning in
its turned frame, so the audit books it as clip_lost with
clip_inexpressible="rotate". A rotated element whose rotation could not
be recovered is element_capture_fallback and its whole subtree pools
into it.
- JS and Swift codegen do not lower it yet (allowlisted in
test_design_import_parity.cpp); the JS lane needs a setClipRect bridge
verb first. Both degrade by not clipping — too much ink, never a lost node.
- Anchors are DOM paths, not capture positions.
stable_anchor_idis
capture:tag#id-or-.class[ordinal]/…, with ordinals counted over ALL
same-signature siblings in the document rather than over the painted ones, so
hiding a sibling does not move the anchor. Keying on a layout index instead
identifies a node within one capture — the one job an anchor does not have,
since the tweaks layer replays edits ACROSS captures. A hoisted node keeps its
DOM anchor: hoisting is a rendering accommodation, not a claim about
structure.
- A
data-pulp-keysibling key replaces the ordinal. An element whose
data-pulp-key no sibling shares gets the segment tag[key=<key>], so a
reorder carries the anchor (and any stored edit) with the node; an ordinal
stays with the slot and would hand Drive's edit to whatever row moved into
first place. Ordinals are then counted over the siblings WITHOUT a usable key,
so reordering keyed rows never renumbers an unkeyed neighbour. A key declared
twice under one parent identifies neither sibling: both keep positional
anchors, and the collision is reported on the IR root
(native_keyed_duplicate_keys) and as an import warning, never silently.
The raw values ride along as pulp_key / pulp_id node attributes;
data-pulp-id is the page-wide source id the materialized lane maps, and it
does NOT change the anchor.
- **Anchors change for documents that already declare
data-pulp-key, and
there is no ordinal-to-key alias.** Every keyed node, and every node under
one, gets a new anchor. A stored edit (pulp-tweaks.json) on the old
ordinal path finds no node and surfaces as an orphaned-tweak drift; re-store
it against the new path once. An alias is deliberately not offered: an
ordinal named a SLOT at the time the edit was stored, and nothing records
which keyed node held that slot then, so the alias would guess, which is the
misapplied edit keys exist to prevent. The one case that does not orphan: in
a parent that mixes keyed and unkeyed same-signature siblings, the unkeyed
ones renumber over the unkeyed set only, so an old li[0] edit that belonged
to a keyed row now resolves onto the first UNKEYED row. Every such parent is
reported on the IR root (native_keyed_mixed_siblings, as
<parent anchor> <signature>) and as an import warning; re-check stored edits
under each one by hand. A duplicated key makes its siblings positional, so a
duplicate beside a usable key is reported in both lists. The update planner treats pulp_key and
pulp_id as immutable contract attributes (they start with pulp), so the
same anchor whose data-pulp-id changed is rebuilt, not retained.
- When improving the offline/native HTML importer, use the development-only
Importer Differential Lab rather than changing the authoritative browser
route. It runs Chromium and --offline separately, renders the candidate
DesignIR through Pulp/Skia, and compares structure, geometry, typography,
and pixels without modifying canonical output:
`python3 tools/import-validation/importer_differential_lab.py
analyze-corpus --importer <pulp-import-design> --observer
<pulp-design-ir-observe> --manifest
test/fixtures/import-differential/manifest.json --output <dir>`.
Production native promotion is disabled; threshold_eligible is advisory
evidence only. See docs/tools/importer-differential-lab.md.
Page-space gotcha: a browser-backed native import is panel-local, while
Chromium's screenshot and DOM snapshot are page-space. The lab passes the
signed authored-frame origin to pulp-design-ir-observe --origin, which
wraps the importer's panel root, untouched, in an observer-only page node and
positions it there. The captured browser_box_paint_*_px rects move with it
(the painter validates them against a view's absolute position, so leaving
them behind makes it reject every snapped rect and fractional edges
reappear). captured_raster_origin_*_px does NOT move: the sprite pass crops
it from the full-page screenshot, so it is page-space already. The page node,
never the panel root, carries --page-background, which the lab resolves
from the verified DOM snapshot by CSS canvas propagation (html, else body;
both transparent takes the UA canvas colour the capture recorded as
documentCanvas, and is unresolved without that report) and supplies only
for a panel with page around it. The UA canvas is the Canvas system colour
of the ROOT's used color-scheme (rgb(18, 18, 18) dark in Chrome 151), set
by root CSS or a color-scheme meta tag; a body's color-scheme never reaches
it, and the root's computed color-scheme reads normal under a dark meta,
so the capture asks Chromium with a probe rather than mapping the property. A whole-page panel owns its canvas: the importer stamps it on
the root, and filling underneath would hide a dropped stamp. Page-space
comparisons must not translate the browser nodes as well; that registers the
panel twice. The registered geometry gate instead moves BOTH sides back into
the panel frame (Chromium's boxes by register_browser_nodes_to_native_frame,
the native layout by native_nodes_in_panel_space with the receipt's
placement origin), and frame_placement_check and
verify_native_authored_frame read native rects relative to that origin.
Counter gotcha: the observer's render receipt carries its own work
counters (pulp-design-ir-observer-counters-v2; v1 receipts lack the
per-phase resource fields and are judged without them), phased as build,
first_frame and readback, plus views constructed/destroyed and a
terminal live_views_after_teardown read after the tree is destroyed. The
lab gates eligibility on a zero teardown residue and zero unmarked paint
mutations in readback only: materialization and the first layout set
paint state on views that have never been drawn (~80 "unmarked" mutations on
an 8-view card), which stales nothing. Gating those would block every
fixture for a non-defect; ungating readback would let a read-back that
mutates the painted tree pass. v2 also gates readback on zero
image_decodes, gpu_uploads and image_cache_builds, and leaves
paragraph_builds ungated there because measuring text shapes it. Raw DOM-snapshot hashes differ per capture
only by the CDP frame ID, so compare *_snapshot_semantic_sha256 across
runs, not the raw binding. platform_fonts_sha256 likewise fixes each text
run's backend_node_id, which Chromium numbers per run; a raw hash of
platform-fonts.json failed determinism on node order alone.
Normalize gotcha: normalize_design_ir (design_ir_normalize.cpp) runs
on every node parse_ir_node reads, and its rules are design-tool
heuristics that move geometry. A browser capture's design.ir.json goes
through the same parse when the observer loads it, so a rule that is right
for Figma can move a node Chromium already placed. The shadow sibling snap
lifted a knob label under a dial's 0 8px 16px shadow by the gap minus the
shadow's y offset (2 px at a 10px gap, 4 px at 12px). parse_design_ir_json
now passes IRParseOptions::measured_geometry when the IR's source adapter
is browser-capture, and a geometry rule that only makes up for how a
design tool draws must check it. Fixture 20-flex-gap-knob covers the snap.
Separator promotion, rounded-corner inheritance and name-based audio-widget
detection skip a capture too: a scaled hairline is really 0.3px wide, a
child's radius is its own, and a div.dial the capture did not bind is not
a knob (it became a live Knob with hit regions). Connector spanning needs a
row-direction node, which the capture never writes. Fixture
21-design-tool-heuristics covers them.
Paint-order gotcha: Chrome's paint order numbers a node by when its OWN
box paints, and an inkless wrapper still holds a number. Ordering siblings by
that number drew Spectr's full-panel body::before over every descendant of
the inkless div#root and flattened the whole panel. Siblings are ordered by
where their ink lands instead (an inkless node that takes no input and does
not clip, composite or transform moves to its subtree's first ink). The
reorder audit counts a pair only when both nodes paint or either takes input:
in a counted pair the SECOND node is drawn on top. Prove a change here by
rendering the same snapshot nested and flat (lower_painted_tree with
flatten_to_paint_order) and comparing bytes.
Transform gotcha: the capture places a node by its post-transform paint
box and copies every other length from computed style, which is
pre-transform. transform itself is not written to the IR (only a recovered
lone rotation is). So anything drawn inside the box has to be brought into
the box's scale by hand: type through inherited_type_scale (uniform only),
and border widths, radii and shadows through inherited_paint_scale and
apply_paint_scale (per axis for borders and hard shadow offsets, uniform
only for radii and blur). A chain one factor per axis cannot express is
refused and counted (native_nodes_paint_scale_refused), never approximated.
A new length-bearing style field needs the same treatment, or it will draw at
its untransformed size inside a scaled box.
Gate gotcha: a stable Chromium/native PNG hash is only determinism
evidence. The differential matcher must join captured elements by their
capture anchor (stable_anchor_id, which capture_anchors derives from the
browser snapshot the way the importer does) and fail closed on a mismatch.
Never join the two lanes by backendNodeId: they are two Chromium sessions,
and Spectr's div#root came back 31 in one and 30 in the other;
otherwise a same-text fallback can hide a wrong DOM identity. Native
synthetic roots, html/body wrappers, and explicit text children are
representation nodes and must be reported separately from browser element
precision/recall. Keep the visual threshold intact: text antialiasing can
dominate the pixel diff even when structure and geometry are exact.
Capture-moment gotcha: the lab's two lanes are two Chromium captures,
and the native IR is lowered from the candidate lane's. On an animated panel
the browser lane's screenshot is a different frame: Spectr's two captures
disagree on 42,764 spectrum pixels before any native render is involved. The
visual lens therefore scores against candidate/browser.png when the lanes'
DOM snapshots share a semantic digest, and reports the gap between the two
captures as visual.reference.capture_moment_residual. Do not read a visual
score against the browser lane's screenshot as fidelity on an animated panel.
The authored-fixture validator also records the native Skia PNG itself, its
hash and size, and the browser/native comparator result. This closes the
earlier measurement mistake of hashing generated JavaScript as if it were a
render receipt. A real PNG and repeated identical hashes prove capture
authenticity and determinism; they still do not prove Chromium/Skia pixel
parity, font/rasterizer provenance, lifecycle safety, or importer capability.
The v4 receipt also records that Chromium capture and native import processes
exited cleanly before their artifacts were read, plus the browser health and
runtime-exception counts. This is a process-level teardown control; it does
not claim that a native editor mount, keyed reorder, or stale-generation
update is safe. Those controls remain separate acceptance work.
The v4 receipt also records the generated artifact's lowering mode. The
current fresh panel is faithful_capture, meaning the native render is an
image-backed diagnostic path; it must not be described as proof that the
importer lowered the panel into native elements.
pulp-design-ir-observereplays input headlessly: ordered--click x,y,
--drag x1,y1:x2,y2 and --key <name> (tab/shift+tab traverse focus
as the window hosts do; other keys go to the focused view) run after layout
and BEFORE the render, so the PNG shows the post-interaction state. Steps
require --interaction-log <json>; the log records per step the hit
target's anchor and child-index path, handled, focus, and tree-ordered
control state. Two gotchas: a bare click never moves a knob (drag does),
and anchors are not unique — the figma-plugin scene fixture gives three
siblings one stable_anchor_id — so compare by path, not by anchor.
pulp-design-ir-observe --backend gpurenders through Skia Graphite on a
Dawn device (the default stays skia, the CPU raster, byte-identical to
before), and --render-receipt <json> records the backend actually used,
the adapter, frame outcome, readback, device loss, Skia milestone and Dawn
revision. A GPU request that cannot render fails; it never comes back as a
CPU render. Gotchas: an unscaled image blit renders byte-identically on
Graphite and CPU raster, so pixels alone cannot catch a silent fallback on
such a design (check the receipt and which GPU driver loaded); Pulp's macOS
GPU binaries also load libwgpu_native.dylib, a second WebGPU C API next to
Skia's static Dawn; and a SECOND Dawn copy in the process (e.g. via
DYLD_INSERT_LIBRARIES) is not benign — the observer then hits WebGPU
validation errors and a Tint internal compiler error. --gpu-fault seeds
failures for parity-lane calibration only.
Keep provider-version reads and device-loss injection inside the private
render implementation. Including Dawn/WebGPU headers in the importer bypasses
that boundary; putting the observer declaration under core/render/include
also exports a development diagnostic into the installed SDK. The source
boundary regression checks both mistakes, alongside the GPU receipt tests.
pulp-ui-frames-observerecords an imported panel (--design-ir) or a
scripted UI (--script) frame by frame under a fixed host clock: a
pulp-ui-frame-schedule-v1 file supplies the host timestamps, the
StateStore parameters, and timed hover/click/drag/key/context-press,
set_param, resize and editor attach_view/detach_view events
(test/fixtures/ui-frames/). It follows the host frame contract exactly,
including the SECOND continuity check after advance_host_frame: keeping
only begin_host_frame's answer stalls an input-started animation (a knob's
hover glow froze at 0.37 for nine frames). Gotchas it makes visible: a
view-first scripted document's first mounted frame paints bindWidgetToParam
controls at 0, one frame before the binding service catches up. Script
timers and performance.now() read the schedule's host clock by default
(WidgetBridge::set_time_source, --timer-clock schedule); pass
--timer-clock wall to see what a real host does, where a timer fires when
wall time passes its deadline however few frames that took. Date.now() is
always the engine's wall clock, so never derive timing from it in a fixture.
The lane that works (Figma is the source of truth):
# 1) Export the Figma NODE to a scene (faithful vectors + geometry + assets).
# Token resolves from --token, $FIGMA_TOKEN, then ~/.config/pulp/figma-token.
# ALWAYS pass --cache-dir: it memoizes the /nodes JSON + frame SVG, so a
# fix-loop iteration costs ZERO REST calls on a cache hit. Figma MCP allows
# only ~6 calls/MONTH on a View seat — re-fetching every iteration burns the
# quota for nothing.
python3 tools/import-design/figma_rest_export.py \
--file-key q9iDYZzg86YrOQKr6I3bY0 --node 187:2 \
--cache-dir .pulp-figma-cache \
--out scene.pulp.json # → "N nodes, faithful-vector SVG, interactive elements"
# 2) Import the scene (the source-of-truth lane: audio-widget + library matching,
# faithful-vector render) and validate against the Figma render.
build-gpu/tools/import-design/pulp-import-design \
--from figma-plugin --file scene.pulp.json --output ui.js \
--validate --screenshot-backend skia \
--reference <figma-node-render.png> --diff diff.png --render-size 1356x781
Offline `.fig` lane (`--from fig`) — no account, no network
When you have a local Figma save file (File → Save local copy…, a .fig),
--from fig decodes it offline — no Figma account, PAT, MCP, or network. It
produces the same figma-plugin envelope as figma_rest_export.py, then runs
the standard figma-plugin lane, so everything above (audio-widget/library
matching, faithful-vector render, --validate) applies unchanged. Requires
Node ≥ 22 on PATH (native zstd); the decoder is tools/import-design/fig_decode.mjs.
A .fig can carry hundreds of frames across many pages, so **outline first,
then pick a frame** — importing the whole file is never right:
# 1) Inventory the file (read-only): pages → frames with guid, size, node count.
pulp import-design --from fig --file design.fig --outline # or --outline --json
# 2) Import ONE frame, by name or guid (from the outline). --page scopes the lookup.
pulp import-design --from fig --file design.fig --frame '102:1624' --output ui.js
Frame selection accepts a guid (102:1624, unambiguous) or an exact
case-insensitive name.
Mirrored layers: m02/m12 is the transform ORIGIN, not the box corner.
A .fig transform with m00 = -1 (horizontal flip — Figma's ⇋ on an icon)
stores the box's RIGHT edge in m02; the visual box spans [m02 - w, m02].
Three consequences, all learned from the Triaz "Reverse/Env" chips
(mirrorAwareOrigin in scene.mjs owns the rule):
- Sidecar truth:
geometry.jsonmust report the visual min-corner, or
layout_parity cries "misplaced by exactly one width" (dx = -10.4 = the
icon's own width) at a node the flex pass placed perfectly.
- Container flips are dropped: an emitted frame carries no
scaleX(-1), so
a vector under a net-mirrored ancestor chain must have the ancestor mirror
baked into its own normalized path (geometryToPath's mirror arg) — the
icon frame's flip cancels its child Union's own baked flip in Figma, and
without the re-bake the "reverse" arrow renders pointing forwards.
- Scope: TRUE mirrors only (exactly one negative axis). BOTH axes negative
is a 180° rotation whose raw-m02 placement is pinned by the slider-fill
lesson (see the orthogonal-rotation test in fig.test.mjs) — do not
"fix" it to min-corner.
A flowing vector's flex slot is its NODE box, not its ink. Figma's
auto-layout never sees a stroke, but the emitted ink box includes it (CENTER/
OUTSIDE bands, round caps overhang). The decoder reconciles the two with
negative margins on the child's layout (widget keeps the exact ink; Yoga
gets the node box back) — gated to overhangs ≤ strokeWeight + 1, because
through instance expansion the ink is solved at INSTANCE scale while
node.size can still be the master's, and that gap is a scale delta, not a
stroke. The JS codegen lowers layout.margin_* via setFlex — it silently
dropped them before, so if margins ever stop landing, check
emit_js_layout_constraints in design_codegen.cpp first.
Known residual (parity, not render): resized-instance auto-layout re-solve.
A 32×32 INSTANCE of a 40×40 auto-layout SYMBOL re-solves child layout at
32×32 in both Figma and our Yoga pass, but the geometry sidecar composes the
MASTER's 40×40-solved child transforms, so parity reports a phantom offset on
such children (designers-pick "HiHat 01"/"Cymbal 01", dx,dy ≈ -4). Truth-side
fix would need the decoder to re-solve (or read derivedSymbolData layout for
swapped subtrees); the render itself matches Figma's re-layout behavior.
The .fig lane cannot capture multi-state designs. Alternate frames are
lowered ONLY by the faithful_svg path, and the .fig decoder emits a
widget-recognition tree — no render_mode, no svg_asset_id (grep
tools/import-design/fig/*.mjs: zero hits). Repeated --frame here is refused
with exit 2. The lane's merge plumbing is written and tested and will start
working the day the decoder learns faithful export; until then, do NOT wire a
multi-state surface onto it.
Multi-state capture is --file repeated, on a faithful lane. Export one
envelope per state with a lane that emits faithful frames — the REST
faithful-vector export (figma_rest_export.py --faithful-vector) or the Figma
plugin — then merge them at import:
python3 tools/import-design/figma_rest_export.py \
--file-key <KEY> --node 187:15 --out typing.pulp.json --faithful-vector
python3 tools/import-design/figma_rest_export.py \
--file-key <KEY> --node 187:349 --out piano.pulp.json --faithful-vector
pulp import-design --from figma-plugin \
--file typing.pulp.json --file piano.pulp.json \
--emit cpp --mode baked --output kbd.cpp
The first --file is frame 0, the second frame 1, … — that index is what a
design's swap <n> layer targets, so **reordering the flags re-points every
swap**. The merge (envelope_merge.cpp, shared with the fig lane) folds each
later envelope's root into the first's alternate_frames; the C++ codegen and
the native materializer each emit one add_frame per entry, in order. A single
--file skips the merge entirely and behaves exactly as it always has — keep
it that way when touching this lane.
Captured states nobody can render are exit 2, not a diagnostic.
find_unrenderable_alternate_frames reports every node carrying
alternate_frames that is not a renderable faithful node; the CLI refuses the
import. Without it, the states are dropped and the import "succeeds" with one
frame — the user asks for N states and silently gets one. That silent no-op is
what this surface shipped as before the guard existed; keep the guard.
Swap elements come from the plugin lane only. faithful-vector.ts reads a
layer named swap <n> into a swap element; the REST exporter does not detect
swaps. A REST-captured multi-state component holds all its frames but is driven
by set_active_frame(i) from consumer code.
**A swap whose target frame was never captured is reported, never silently
dead.** apply_swap_target_verification flags an unset (-1), negative,
out-of-range, or self-targeting swap with a conflict signal, so it rides the
SAME channel as any other unresolved control: --import-report <json> shows it and
--fail-on-unresolved exits 2. Do NOT add a parallel diagnostic channel for
frame problems — route through the import report. This fires on single-frame
imports too (a design whose swap was always dead now says so).
**Gotcha — an alternate frame is a SIBLING axis to children, not a
descendant.** Any pass that walks the IR and must see every control has to
descend alternate_frames as well (collect_import_report and
apply_placement_verification both do). A walk that only follows children
silently ignores every control on frame 1+. Each alternate is also its own
render region: verify its overlays against ITS width/height, not frame 0's — a
mode toggle routinely swaps to a differently sized frame.
Gotcha — never skip an alternate frame whose SVG fails to resolve. Frame
indices are positional, so dropping frame k renumbers every later frame and
silently re-points the swaps that target them. Both generators add the frame
blank (overlays intact) and diagnose it instead. The decoder is purely structural — geometry, style, text,
and bundled raster assets; widget recognition stays the importer's job (a
node's name flows through untouched for the resolver to classify). Fidelity
losses are reported as named warnings in the emitted envelope's diagnostics
(vector-simplified, gradient-approximated, asset-missing) rather than
silently dropped. External-library instances and cross-file variables that a
local file can't resolve surface the same way — treat them as data, not failures,
and fill in the critical ones by hand.
**Gotcha — a hand-written envelope fixture using data: URI SVG assets loses
its faithful node under --mode baked.** The baked lanes run
refresh_design_ir_asset_manifest, which resolves assets against the filesystem
and drops inline data: entries ("0 assets"); the faithful node then can't
resolve its SVG and falls back to plain widgets, so render_mode,
svg_asset_id, and interactive_elements all vanish from the output and the
import report goes empty. This looks exactly like a codegen bug and is not one.
Write real .svg files and reference them by relative local_path (what a real
.fig decode emits). Note also that --emit cpp requires --mode baked, and
looks_like_figma_plugin_export keys off figma-plugin-v1 /
"adapter": "figma-plugin" — a fixture missing those but containing "version"
"root"is parsed as a serialized DesignIR instead of an envelope.
**Gotcha — the .fig fixture-determinism test compares decoded content, not raw
bytes.** fig.test.mjs's "generator output is deterministic" test regenerates
synthetic.fig and compares it to the committed fixture. It must compare the
decompressed schema + message + rasters (unpackFig(...)), never the raw file
bytes: the inner fig-kiwi chunks are DEFLATE-compressed, and zlib's exact output
varies by Node/zlib version, so a raw byte-compare tests zlib rather than the
generator and goes red on any CI host whose zlib differs from the one that
committed the fixture (this is exactly what reddened a VM runner while the same
commit stayed green on bare-metal). If you touch make_synthetic_fig.mjs,
regenerate the fixture from the canonical toolchain, but keep the comparison at
the decoded layer.
**Component/instance semantics are preserved end-to-end via one normalized
figma-block contract.** All three Figma producers emit the same field names in
a node's figma block — component_key, main_component_name,
main_component_id, component_set_name, remote_library (emitted only when
true), variant_properties ({axis: value}), and component_properties
({name: {type, value}}, type ∈ TEXT/BOOLEAN/NUMBER/VARIANT/INSTANCE_SWAP…) —
and design_ir_json.cpp::parse_ir_node preserves all of them into namespaced
node attributes: figmaComponentKey, figmaMainComponentName,
figmaMainComponentId, figmaComponentSetName, figmaRemoteLibrary,
figmaVariant.<axis>, figmaComponentProperty.<name> +
figmaComponentPropertyType.<name>. The consumer strips Figma's "#<id>"
property-name uniquifier (colliding stripped names fall back to the raw key)
and stringifies values (bool → "true"/"false", round numbers without
.0). Per lane: the plugin captures instance componentProperties /
variantProperties directly; REST derives variant_properties from
VARIANT-typed componentProperties entries (REST has no separate variant map)
and reads remote / set name from the /nodes components maps; the .fig
decoder resolves a state-group member's variantPropSpecs through the set's
componentPropDefs (member-name "a=b, c=d" parse as fallback) and modern
componentPropAssignments ({defID, value}; value.textValue is a TextData
struct — the string is .characters; INSTANCE_SWAP guidValue resolves to
the swapped-in component's name when in-file). A kiwi COMPONENT_SET is a FRAME
with isStateGroup: true — the set, not the member SYMBOL, owns the VARIANT
defs. Nothing is fabricated: legacy files (no assignments) emit identity only.
SLOT nodes carry no component identity in the Plugin API (SlotNode is a
frame defined by a component property reference), so only their name flows.
**Mixed text runs are emitted by all three Figma lanes, on ONE offset unit:
UTF-8 bytes.** A text node with per-range styling (a bold word, a colored
span) carries an ordered runs array of style DELTAS against the dominant
style — `{start, end, fontSize?, fontWeight?, fontFamily?, fontStyle?, color?,
letterSpacing?, textDecoration?}` (camelCase; the exact shape
design_ir_json.cpp::parse_ir_text_runs reads). start/end are `[start,
end) **UTF-8 byte offsets into content`** in every lane — Figma indexes text
in UTF-16 code units (plugin getStyledTextSegments, REST
characterStyleOverrides, .fig TextData.characterStyleIDs all do), so
each producer converts through a per-code-point map (plugin
extract-pure.ts::utf16ToUtf8ByteOffsets, REST's u16_to_byte, .fig
extractFigTextRuns). A code-unit passthrough corrupts every run after the
first non-ASCII character — the tests pin an é/emoji fixture in each lane.
Homogeneous text emits NO runs array (the flat dominant style is the whole
story; the consumer prefers that path). Lane quirks: the plugin backfills the
dominant style from segment 0 when node-level reads return figma.mixed (a
symbol — typeof guards silently skip it otherwise); the .fig format has no
numeric fontWeight, so run weights derive from the override fontName.style
NAME ("Bold" → 700, "SemiBold" → 600, …); .fig styleOverrideTable rows are
NodeChange structs keyed by styleID. Codegen coverage (compat
text-per-range-styles): web-compat nested <span>s, JS-native
setTextRuns → AttributedString with captured-line reuse or responsive
multiline reflow, SwiftUI concatenated Text segments, and the direct native
materializer. Baked C++ alone still flattens — honest partial.
**textAlignVertical is design authority; the tall-slot heuristic is only a
fallback.** All three producers emit style.vertical_align
(top/middle/bottom; kiwi omits the .fig TOP default so it only appears when
set). Codegen honors it verbatim in both JS arms, and the native materializer
and baked C++ lane share the same rule (imported_vertical_align() in
design_ir_helpers.hpp), including an explicit top, which SUPPRESSES the
old slot-taller-than-font centering guess (that heuristic now fires only when
the source never says). A browser capture records middle for a control's
#control-value text; before the native lane read it, a button input's label
painted top-aligned, 1.41 CSS px below Chromium's. Expect imports to MOVE
text vs pre-emission renders where designs author TOP in a reserved slot —
that movement is fidelity, not a regression (layout dumps stay byte-identical;
vertical align is paint, not geometry). Auto-resize / truncation / max-lines /
whole-node hyperlink are preserved as namespaced attributes
(figma:text_auto_resize, figma:text_truncation, figma:max_lines,
figma:hyperlink), not lowered; paragraph/list/OpenType metadata is not
captured (compat text-extended-metadata).
**Gotcha - old-style instance swap lives in overriddenSymbolID, not
componentPropAssignments.** A file that predates component properties swaps a
nested instance's component with a symbolOverrides entry carrying
overriddenSymbolID — there are no componentPropAssignments /
componentPropertyReferences anywhere, so searching for the modern swap
machinery concludes "no swap" while every channel's icon IS swapped.
expandInstance (scene.mjs) honors the field: applyOverrideEntry's generic
copy lands it on the clone, and the expansion re-points at that master when it
resolves in-file (falling back to the authored symbolData.symbolID plus an
external-component diagnostic when it doesn't). Deeper override paths keep
resolving after the swap because the swap target's children carry the matching
overrideKeys. Symptom when broken: N siblings render identical component
content under N correct per-instance text overrides (sixteen mixer channels,
one kick-drum icon).
**Gotcha - Figma "Clip content" is frameMaskDisabled (inverted), and groups
never clip.** The .fig decoder emits style.overflow = 'clip' for a
FRAME/SYMBOL/INSTANCE with frameMaskDisabled: false unless the node is a
GROUP (resizeToFit: true — groups store the flag but ignore it). The REST
lane's equivalent is clipsContent → overflow. The native JS codegen lowers a
non-default style.overflow to setOverflow(id, 'clip') (bridge maps clip →
View::Overflow::hidden); visible is the View default and is deliberately
not emitted. This matters for expanded instances: a master whose decoration
overhangs its symbol bounds renders clipped in Figma, so an unclipped import
paints the overhang over whatever sits below the instance (a channel strip's
noise card ran 19px past its 235px symbol and buried the transport's step row).
**Gotcha - a mask: true child paints NOWHERE; materializing it as content
occludes everything painted after it.** Figma's mask layer clips the siblings
painted ABOVE it in the same parent and never renders its own fill. ALL THREE
Figma lanes now reconstruct this sibling-mask structure with one wrapper
contract: the masked siblings move into a synthetic
<mask name> (mask scope) wrapper (spans the parent, audio_widget: 'none',
node_id <maskId>/mask-scope) whose style.clip_path = path("<d>") carries
the mask outline in PARENT space. Per lane: the .fig decoder
(scene.mjs::walkChildren + maskClipOutline/boxMaskOutline;
geometryToClipPath in paths.mjs skips the 0,0-viewBox normalization
geometryToPath does because a CSS clip-path is consumed in the clipped
view's border-box space), the plugin (extract.ts::beginMaskScope over the
pure helpers in extract-pure.ts — maskClipOutline transforms
fillGeometry into parent space via inv(parent.absoluteTransform) ∘
node.absoluteTransform, group-proof; box-model masks get a synthesized
outline), and REST (figma_rest_export.py::_begin_mask_scope, same helpers
in Python; axis-aligned masks translate by absoluteBoundingBox deltas, robust
to REST's GROUP-parent coordinate quirks). The chain downstream already
existed end-to-end (parse_ir_style('clipPath') → codegen setClipPath →
SkPath::FromSVGString clip). Siblings BELOW the mask stay outside the
wrapper (Figma's scope); a second mask opens a nested wrapper so stacked
masks intersect. Fidelity is diagnosed, never silent: an outline clip is
exact for VECTOR (outline) masks and opaque-solid alpha masks; LUMINANCE
masks keep the best-effort outline clip plus a mask-luminance-approximated
warning, soft/partial alpha masks (image/gradient fill, partial opacity) get
complex-mask-flattened (plugin/REST; the .fig lane keeps its original
mask-approximated code), and unresolvable outlines / masks inside
auto-layout parents degrade with mask-approximated — but the mask itself is
never painted, in any branch of any lane. Arcs in vector mask geometry don't
survive a general affine, so an A command falls back to the box outline
(approximate clip beats no clip). Symptom when broken: a "gray" element whose
accent color is right there in the data — the selected mixer channel's red
tab read gray because the master's opaque Bg PAnel mask (invisible in
Figma) painted over it, and every channel body sat one gray lighter than the
design.
**Gotcha - a Figma slider stores a value-driven fill position that can detach
from the thumb.** A slider component (track + progress fill + round thumb) keeps
the fill's x/width per-instance; Figma's LIVE component render recomputes the
fill against the thumb at draw time, but the stored .fig (and REST/plugin
exports of it) only carry the frozen geometry - so an instance can persist a fill
that floats in a gap away from the thumb, and a faithful render draws a broken
detached bar. reconnect_slider_fill (core/view/src/design_import.cpp, run in
the native codegen arm BEFORE synthesize_primitive_paths bakes the width into
path_data) detects the triplet STRUCTURALLY - short wide container,
near-full-width thin track, shorter thin fill whose color differs from the track,
round thumb whose height fills the bar; never by layer name - and bridges the
fill to the thumb ONLY when they are horizontally disjoint. Do not "fix" a
detached fill by inventing a slider value or by matching on names: the structural
gap-bridge is the whole intervention, and a fill already touching its thumb (plus
track+thumb-only faders and every non-slider row) is left exactly as stored.
Covered by the [slider] cases in test_design_import_codegen.cpp.
**Gotcha - a "universal" IR fix is only universal across the emit paths that
carry it.** normalize_border_shorthand splits style.border into
border_color/border_width for every lane, but the border only PAINTS if the
node's emit path calls setBorder. design_codegen.cpp has TWO native-frame emit
paths: emit_js_container (recognized containers) and emit_js_generic_frame
(the fall-through for a childless node whose kind is neither
container/widget/vector/image/text — a v0/claude/stitch button/canvas/input
div). emit_js_generic_frame emitted background/gradient/corner-radius but NOT
setBorder, so a bordered generic-frame node silently lost its stroke on EVERY
lane even though the shorthand was split correctly. When you add a style emit to
one frame path, add it to BOTH — and verify a real lane, not a grep: import
test/fixtures/v0-dev/audio-control-panel.tsx and count declared-vs-emitted
(setBorder/setBackgroundGradient/setCornerRadius) in the output JS. A
grep-level "the field reaches the IR" check misses a drop that lives one layer
down in codegen.
**Gotcha - the v0 TSX parser does not resolve style={constObject}
references.** extract_jsx_style_body (design_import_v0_tsx.cpp) resolves only
inline style={{...}} object literals. A hand-authored/v0 pattern that hoists
the style into const panelStyle = {...} and passes style={panelStyle} is
dropped whole — on audio-control-panel.tsx the root panel loses its
background, padding, border, and radius. Resolving it means extracting
const …Style = {…} decls and threading a registry through
apply_v0_jsx_attribute; treat it as a focused parser change with its own tests,
not a one-liner.
**Gotcha - the HTML regex fallback (parse_stitch_html, shared by the claude
lane via parse_claude_html) must skip non-visible elements.** Its
<([a-z][a-z0-9]*)[^>]*>([^<]*)</\1> regex matches ANY tag, so a <script> body
(a Stitch tailwind.config = {...} block, a Claude bundler placeholder) or a
<style> sheet became a visible text LABEL — raw JS/CSS painted into the
imported UI. The fix filters a kNonVisibleTags set
(script/style/noscript/template/head/title/meta/link/base). When you touch this
fallback, verify with a real fixture: import
test/fixtures/imports/stitch/2025.04/code.html and confirm the element count
drops (the <script> label is gone) while the visible <div> text survives.
Note this is the LOSSY fallback — a JSON-IR or runtime-DOM claude/stitch input
never reaches it; it fires only on raw non-JSON HTML.
**Gotcha - .fig layer rotation was dropped, so a rotated needle rendered as an
axis-aligned stub.** scene.mjs's styleFor took only the translation column
(m02/m12) of a node's affine transform and threw away the rotation
(m00/m01/m10/m11). A knob's value needle — a thin ROUNDED_RECTANGLE rotated to
the value angle — then imported as a vertical bar floating off-centre instead of
a radial pointer (reported on TRIAZ "Rnd Pan"). The fix extracts
atan2(m10, m00), emits transform: rotate(<deg>deg), and **compensates
left/top for the renderer's centre transform-origin** (Figma rotates about the
layer origin; the view rotates about centre) — so NO setTransformOrigin is
emitted and CSS-lane rotate() (which is also centre-pivot) stays correct. The
native codegen lowers transform: rotate() to setRotation in the shared
emit_js_visual_overrides. TWO scope guards, both load-bearing:
- Non-orthogonal only. Apply the transform ONLY when the angle is not a
multiple of 90deg (mod90 > 0.5 && mod90 < 89.5). A multiple of 90deg keeps a
rect axis-aligned, and for a solid fill a 180deg spin is a visual no-op — the
centre-pivot compensation then only shifts the box off its row. That exact
case floated a slider's 180deg-rotated progress fill ABOVE its track (a
regression from the first cut of this fix). Orthogonal rotations fall through
to plain m02/m12 placement.
- Box-model only. A
VECTOR_LIKEnode bakes its rotation intopath_data,
so re-applying it double-rotates the glyph (guard !VECTOR_LIKE.has(node.type);
verify a rotated icon like the "Reverse" ↩ button is byte-identical
before/after).
Covered by [rotation] in test_design_import_codegen.cpp + a decoder test in
fig/fig.test.mjs (45deg needle rotates; VECTOR and 180deg fill do not).
All three lanes now lower rotation (audit "Rotation / transform" row). The
plugin (extract.ts walk + extract-pure.ts::decodeRelativeTransform) and
REST (figma_rest_export.py::_decode_rotation) producers decode
relativeTransform and emit the same transform: rotate(<deg>deg) spelling,
with the .fig guards mirrored field-for-field (non-orthogonal tolerance
0.5 < mod90 < 89.5; vector-like exclusion — extended in plugin/REST to EVERY
node-export capture, i.e. widget-instance and pure-vector-illustration PNGs,
because exportAsync/the REST images render bakes the rotation into the
pixels; an image FILL asset is raw bytes, not a node render, so image-filled
boxes still rotate). Placement differs from .fig by design: plugin/REST
position by absoluteBoundingBox deltas, and the rotated AABB's center IS the
node's center, so they emit the UNTRANSFORMED size (node.width/height,
REST size — both ride with the export) centered in the AABB and let the
center-pivot rotate() land it (the origin-pivot compensation formula is only
the plugin's node.x/y fallback path). Two additions the .fig lane does not
have:
- Skew / non-unit scale / mirror-plus-rotation is NOT representable as a
single center rotate() — the producers raise a
transform-skew-approximated warning (unsupported_property), keep the
node axis-aligned at its AABB (the pre-fix behavior), and never fake an
angle. A pure orthogonal flip stays silent (axis-aligned box already
occupies the right pixels — matches all shipped lanes).
figma:transform_matrix— the full 2x3 affine
("m00,m01,m02,m10,m11,m12", row-major, trimmed like the geometry attrs)
is preserved as a namespaced provenance attribute on every rotated or
diagnosed node, so a future matrix-capable renderer needs no re-export.
Same documented-provenance-sink contract as the figma:arc_data /
figma:stroke_* attrs; nothing consumes it today. The .fig lane does
not emit it (its rotation logic is frozen; envelope stays byte-identical).
Tests: transform.test.ts (plugin decode), rotation cases in
test_figma_rest_export.py (placement math, skew diagnostic, vector-leaf and
flowing-child exclusions), and plugin/REST end-to-end [rotation] cases in
test_design_import_codegen.cpp.
Gotcha - a "label" token names the caption, not the control.
detect_audio_widget (design_import.cpp) whole-token-matches "knob"/"fader"/…
to promote a node to a built-in widget. A node named sound / knob label
tokenizes to {sound, knob, label} and matched "knob", so the caption FRAME
promoted to a knob and painted a stock knob disc over its text (a "Classic"
filter-mode caption imported as a dark knob). The recognizer now returns none
whenever the name carries a label token — the caption is text; the real
control (sound / knob / small unipolar, no label) keeps its recognition.
This is the same "the layer name IS the art, not a control" rule as the
knob-art-layer suppression, one level up. Verified: createKnob count on a real
.fig dropped from 6 (all captions) to 0 while every art-layer knob still
rendered. Covered in detect_audio_widget tests.
Gotcha - a stroke-band vector must not ALSO carry a CSS border. Figma stores
a stroke as an already-expanded fillable band (strokeGeometry); geometryToPath
resolves it and scene.mjs paints it as a FILL in the stroke color (re-stroking
it would outline the outline). But the generic stroke→border lowering
(strokePaints + strokeWeight → style.border) then fired on that same node,
so codegen filled the band AND stroked it — two parallel lines where the design
has one (a triad-pad triangle and every stroked ring rendered doubled/too-thick;
the button rings even read as dark filled discs). The fix tracks
vectorStrokeExpressed (band painted OR stroke channels lowered) and skips the
border for those nodes. Covered by a materialize-level test in
fig/paths.test.mjs. One general fix cleared the triangle weight AND the
transport △○□ button rings at once.
Stroke survival — the four lanes a Figma stroke renders through (the
stroke-survival fix; fig/scene.mjs lowerStrokeChannels + fig/paths.mjs):
- Stroke-only vector, CENTER align — the baked
strokeGeometryband is
exact (caps/joins/dashes realized in the outline); painted as a FILL in the
stroke color. Unchanged, still the faithful path.
- Fill + stroke on one vector — the stroke rides the SAME path as real
stroke channels (stroke/strokeGradient/strokeWidth →
setSvgStroke/setSvgStrokeGradient/setSvgStrokeWidth): SvgPathWidget
fills then strokes one path, and for CENTER align the fill outline IS the
stroke centerline, so this is exact. No CSS border (would double the edge).
Fractional widths survive (the border lane rounded to whole px).
- INSIDE/OUTSIDE-aligned stroke bands are baked UNCLIPPED — Figma's blob
holds the boundary outlined at ±weight (verified: a weight-2 INSIDE
Polygon 5 carries a 4px band; render-time clipping against the fill
region is what trims it, and we don't clip). Filling that band verbatim
painted the XY-pad triangle fat and bright — a #373737 grey where Figma renders #2b2b2b. The
decoder now prefers the FILL outline + a centered stroke channel — right
width and color, half a weight off in position — and raises
stroke-align-approximated.
- Gradient strokes —
GRADIENT_LINEARlowers to thestrokeGradient
channel end-to-end (SvgPathWidget::set_stroke_gradient →
Canvas::set_stroke_gradient_linear; solid composite kept beside it as the
parse-failure fallback). Works on vectors AND on ellipse primitives whose
path is synthesized later — design_ir_json.cpp captures the stroke
channels UNCONDITIONALLY (not path_data-gated) precisely so
synthesize_primitive_paths can grow the path afterwards.
Vector-network fallback. Symbol children can carry EMPTY
fillGeometry/strokeGeometry on the master AND every instance's derived
data (the FX knobs' Oval rim), leaving only vectorData.vectorNetworkBlob.
paths.mjs decodes that network (layout self-validated by exact byte
consumption: 12-byte header + 12B vertices + 28B segments; tangents are
vertex-relative control offsets) into the shape's CENTERLINE and marks the
result centerline: true — the caller STROKES it via the channels above,
never fills. Refused (→ existing plain-box diagnostic) when regions are
present, any vertex joins 3+ segments, or the byte count is off. Never used
for BOOLEAN_OPERATION (operand children are the faithful fallback).
Diagnostics carry the instance-path node id. pushDiag records
node.__key || guidKey(node.guid) — recording only the master guid attached
every symbol-expanded diagnostic to the MASTER while the envelope/materials
sidecar name the clone, so material_audit's per-node join scored honest
out-loud degradations as SILENT drops (diagnosed column read 0).
Design contract (`pulp design compile`) — the token/widget allowlist
Before generating or hand-writing a UI, compile the design contract: the
closed set of tokens and components the UI is allowed to bind to. It is compiled
from the buildable sources of truth — a Theme (the token allowlist) and the
pulp::design::catalog() component set (each widget's native class plus the exact
theme tokens it paints through) — so it never drifts from the code.
# Built-in Ink & Signal system (default). Writes design-manifest.json +
# design-binding-prompt.md into --out-dir (default: cwd).
pulp design compile --out-dir build/design
# A project's own tokens instead of the built-in system:
pulp design compile --design-md DESIGN.md --out-dir build/design
pulp design compile --theme my-theme.json --dark --stdout --json
Two artifacts, one source of truth:
design-manifest.json— deterministic (all lists sorted): every token
(name, kind, value) and every component contract (native class, category,
reskin_tokens allowlist). This is the machine-readable allowlist an adherence
check validates generated JS against.
design-binding-prompt.md— an LLM-ready Markdown fragment listing the
allowed tokens and components with an explicit "do not invent token names"
directive. Embed it in an importer/codegen prompt so the model binds only to
real tokens and widgets. A value or widget outside the contract is a fidelity
break, not a silent drift.
The module is core/view/src/design_manifest.cpp
(pulp::design::compile_design_manifest / manifest_to_json /
emit_binding_prompt), gated behind PULP_ENABLE_DESIGN_IMPORT alongside the
rest of the authoring cluster.
Fidelity ledger (`--fidelity-report`) — a diffable record of import warnings
The import-time fidelity self-check (design_fidelity.hpp: skew, dropped-vector,
widget-size, …) always warns on stderr, and --strict-fidelity turns the hard
findings into exit 4. Those warnings are transient — they scroll past and are
lost. Pass --fidelity-report <file> to also persist the run's findings as a
named, machine-readable ledger so an import's fidelity is a durable artifact
you can diff across revisions or gate in CI:
pulp import-design --from fig --file synth.fig --frame 0:2 \
--output ui.js --fidelity-report build/fidelity.json
The ledger (core/view/src/design_fidelity_ledger.cpp,
pulp::view::fidelity_ledger_json) carries:
- a
summary—total,warnings(the hard findings that gate
--strict-fidelity), informational, and a by_kind count map;
- the
findings— each withkind,severity(warningfor a hard
finding, info for an advisory one), node_id, node_name, detail;
- the
taxonomy— every fidelity kind the checks can emit, each with a
stable slug, default severity, and one-line summary, so a consumer can render
a kind it does not itself know about.
It is emitted regardless of --strict-fidelity: warnings are data, not
failures. The taxonomy in fidelity_taxonomy() must stay in step with the kinds
design_fidelity.hpp emits — add a kind to one, add it to the other.
Adherence lint (`pulp design lint-adherence`) — the mechanical backstop
The binding prompt tells the model what's allowed; the adherence lint proves the
generated JS actually stayed inside the contract. It flags three high-signal
drifts and is the CI-gateable counterpart to the prompt:
# Lint an imported/generated UI against the built-in system (or a manifest):
pulp design lint-adherence ui.js
pulp design lint-adherence ui.js --manifest build/design/design-manifest.json
pulp design lint-adherence ui.js --design-md DESIGN.md --strict
- raw-color (error): a hex literal (
#rrggbb/#rgb/#rrggbbaa) where a
bound theme should be referenced via var(--token). When the value is one the
system defines, the finding names the token to bind instead.
- unknown-token (error): a
var(--name)reference whose token is not in the
manifest — a hallucinated or renamed token that silently falls back at runtime
(resolve_color returns the default). This is the exact failure the binding
prompt exists to prevent, caught mechanically.
- raw-dimension (info): an
<n>pxliteral whose value matches a dimension
token — prefer the token.
Exit 0 when clean, 1 on any error-severity finding (--strict fails on info too).
The scan is purely lexical (core/view/src/design_adherence.cpp,
pulp::design::lint_adherence): line/block comments are ignored, string literals
are scanned, and token→var(--x) mapping mirrors export_css_variables
(.→-). Pair it with compile — the prompt and the lint share one manifest.
Project design ledger (`pulp design record`) — resumability + review status
Import/design sessions span days and multiple agents; "which of these five ui.js
revisions did the human approve" is a signal that otherwise lives only in chat.
The design ledger (.pulp-design-meta.json) makes it a durable, CLI-owned
record: each emitted artifact as a named, versioned asset with its source
provenance, viewport, bound design system(s), and a review status.
# Record an emitted artifact (auto-assigns v1, v2, … per name):
pulp design record --name main-panel --asset ui.js \
--source fig --viewport 340x280 --system ink-signal
# Approve a revision (an approved version must never be silently regenerated):
pulp design record --name main-panel --version v2 --asset ui.js --status approved
# Read on resume; drop a stale entry; reconcile hand-deleted files:
pulp design record --list # or --list --json
pulp design record --remove main-panel@v1
pulp design record --reconcile # drop entries whose file is gone
Discipline: only the CLI writes the ledger; skills/agents READ it. On resume,
read it (--list --json) to recover the bound design system (⇒ load its binding
prompt from compile without re-asking) and to see which revisions are
approved vs needs-review vs changes-requested. Never hand-edit the file and
never regenerate an approved asset without an explicit request. The ledger
operations are pure (core/view/src/design_ledger.cpp,
pulp::design::parse_ledger / ledger_to_json / upsert_asset / remove_asset
/ reconcile); all file IO lives in the pulp design record CLI.
THE #1 LESSON — --validate does NOT render the faithful SVG. This is what
cost hours. The scene's root carries render_mode=faithful_svg + the embedded
SVG, and the C++ runtime honors it (design_import_native_common.cpp →
make_faithful_svg_frame → DesignFrameView/SkSVGDOM, line ~1734). But
pulp import-design --validate renders the emitted native-widget JS
(build_native_view_tree/codegen materialization), NOT the faithful SVG — so it
mis-lays composite vectors (e.g. piano black keys grouped/dropped) and reports
~18/255 even though the faithful render is pixel-perfect. **Do not trust
--validate's number as the faithful fidelity.** The CLI now DETECTS a
faithful_svg scene and prints a caveat before the similarity number ("…renders
the native-materialized widget tree, NOT the 1:1 faithful SVG… native-materialize
fidelity… will UNDERSTATE the true faithful render. Verify with pulp-svg-probe"),
so the trap is self-documenting — but the note is a signpost, not a fix: still run
pulp-svg-probe for the real 1:1 number.
Validate the FAITHFUL render with pulp-svg-probe (renders an SVG via
DesignFrameView/SkSVGDOM, the real 1:1 path):
# extract the data:image/svg+xml base64 from scene.pulp.json → faithful.svg, then:
build-gpu/tools/import-design/pulp-svg-probe faithful.svg out.png 1356 781
python3 tools/figma-import/verify_region.py source.png out.png 80 9.0 # → ~1.08/255 = 1:1
This is how Musical Typing was proven 1:1 (1.08/255 vs the design). Pulp's
SkSVGDOM does render Figma's effects-heavy SVG (67 filters, 61 masks)
faithfully — the export and the SkSVGDOM render are both fine; only the
native-materialize/codegen path is lossy.
Bitmap assets inside the faithful SVG (<image> + base64 data URI). Figma
exports raster fills as <image href="data:image/png;base64,…">. Two Skia traps
made every one of those render blank (a hole where the art should be), and
both are now fixed in core/canvas/src/svg_dom_cache.cpp — know them, because a
blank image in a faithful render looks like an export bug and is not:
- SkSVGDOM needs a resource provider.
SkSVGImage::LoadImagereturns early
on a null provider, and SkSVGDOM::Builder defaults it to null. SvgDomCache
installs skresources::DataURIResourceProviderProxy (+ registers the PNG /
JPEG / WebP / GIF codecs — Skia's codec registry starts EMPTY, so
SkCodec::MakeFromData fails until something calls SkCodecs::Register).
Gated on PULP_HAS_SKRESOURCES, a try-link probe in
core/canvas/CMakeLists.txt: the pinned native slices compile skresources
into libsvg.a (there is no libskresources.a at all), other slices ship a
standalone archive, and the wasm slice ships neither — only a try-link gets
all three right.
- Skia only parses
xlink:href, never SVG-2href. The literal attribute
name its parser matches is xlink:href; Figma emits the bare href with no
xlink namespace, so Skia drops the attribute and the IRI is empty *no matter
how good the resource provider is*. SvgDomCache rewrites the attribute name
(tag-scoped, never inside a value or text) before parsing.
If an <image> still comes out blank, check the configure line
Pulp: SVG <image> data-URI decoding enabled (skresources links) — the opposite
message means the active Skia bundle can't link skresources and <image> is
genuinely unavailable in that build.
One-command path (USE THIS): tools/import-design/make_catalog_component.py.
It runs the whole lane — exports the Figma node, embeds the faithful SVG (chunked
base64), and emits the DesignFrameView subclass + the catalog/CMake/showcase
paste-ins. Example:
python3 tools/import-design/make_catalog_component.py \
--name "Channel Strip" --class ChannelStripView --node 182:2 \
--category containers --usage "Pro channel strip…"
Then paste the printed lines into core/view/CMakeLists.txt, the
design_system.{hpp,cpp} catalog, the showcase, and add a test
(test_faithful_specimens.cpp pattern). Validate with pulp-svg-probe +
verify_region.py. This is how Musical Typing, Channel Strip, and 7 specimen
components were built — never hand-paint.
No-metadata source? Use the annotated-capture lane (pulp-annotated-capture-import).
make_catalog_component.py needs Figma as the source of truth — typed nodes,
node ids, component names. A bare SVG capture (a vectorized screenshot, a
hand-authored asset, or a JUCE UI run through an extractor) has none of that: it
is just paths and rects. The annotated-capture lane
(tools/import-design/annotated_capture.{hpp,cpp} + the
pulp-annotated-capture-import CLI) is the no-metadata analog: feed it the bare
SVG plus a sidecar manifest that supplies the missing semantics per element,
and it emits the SAME artifacts (populated DesignFrameElement table +
DesignFrameView subclass + <snake>_svg.cpp + CMake paste-ins).
build/tools/import-design/pulp-annotated-capture-import \
--svg capture.svg --manifest ui_manifest.json --class ReverbPanelView
The sidecar schema is intentionally aligned with **pulp-import-juce's
ui_manifest.json** so a JUCE UI extractor (component-type → kind, bounds →
geometry, parameterID → param_key) can emit a manifest this lane consumes
directly. Each element declares `{selector, kind, param_key, geometry, needle,
options, …} (full field list in annotated_capture.hpp`). When any element
carries a param_key, the generated ctor calls
route_changes_to_host_params(true) so the view runs unchanged embedded in
JUCE / iPlug2 / native. Gotcha baked into a regression test: emitted float
literals must be valid C++ (120.f, never the invalid 120f).
Strict validation (validate_annotated_capture) bounds each kind by its own
geometry: a knob by cx/cy ± hit_radius inside the canvas, an xy_pad by
its box (which must sit inside the canvas) with the cx/cy puck center inside
that box, edges inclusive. An xy_pad has no hit_radius; applying the knob
rule to it rejects every pad, because the absent radius parses as 0.
Under the hood: a 1:1 catalog component = subclass DesignFrameView with the embedded SVG.
See core/view/{include/pulp/view,src}/musical_typing_keyboard* +
design_system.cpp catalog entry: the class is
MusicalTypingKeyboard : public DesignFrameView, constructed from the
base64-embedded Figma SVG (musical_typing_keyboard_svg.cpp). Reskin/extend by
re-exporting the node and re-embedding — never re-draw by hand. The **C++
codegen** (generate_pulp_cpp) now lowers a faithful_svg node to a
DesignFrameView — it embeds the node's SVG as chunked base64 (resolved via the
shared resolve_svg_document, the same bytes the runtime materializer uses) and
reconstructs the typed interactive_elements overlays, so the generated C++ is
1:1, not just the runtime materializer. If the SVG asset can't be resolved at
codegen time it falls back to the native widget emit (so the output always
compiles). Remaining follow-ups: the JS emit path still lowers to native
widgets (a faithful frame needs a JS-bridge primitive that doesn't exist yet),
and --validate still renders the native-materialized output rather than the
faithful SVG.
Interactive-overlay kinds the IR carries end-to-end. The faithful_svg
interactive_elements IR (InteractiveElementKind in design_ir.hpp) supports
`knob, fader, toggle, dropdown, text_field, tab_group, stepper, swap, action,
xy_pad, value_label — each maps 1:1 in to_frame_elements()`
(design_import_native_common.cpp) to the DesignFrameElement::Kind the runtime
already backs, and the schema (figma-plugin-export-v1.json
interactive_element.kind) accepts exactly that set. The schema segments
required per-kind: knob needs cx/cy/hit_radius; every other kind needs the
box x/y/w/h. Field map: fader translates svg_patch_d along the track;
toggle is a click-to-flip rect (a toggle WITH svg_patch_d is a switch; with
flash it is a press-flash command button); swap carries target_frame;
action carries the command id action; xy_pad adds default_value_y
(Y axis; X reuses default_value); value_label carries text +
value_left_align. When you add a kind, touch the whole chain in one commit —
schema → gen-types (types.generated.ts) → producer (faithful-vector.ts,
incl. detectOverlayControls if it should auto-detect) → IR enum →
design_ir_json.cpp parse/serialize → to_frame_elements() → the
design_cpp_codegen.cpp token switch + field emit — or it silently degrades.
detectOverlayControls auto-emits swap/action/xy_pad/value_label from explicit
whole-word node names (run AFTER the tuned dropdown/stepper/tab_group/text_field
detectors so those always win); the richer node-tree signals (prototype reactions
for swap, value patterns for value_label) land with P2's unified resolver. An
unknown kind string no longer silent-knobs: interactive_kind_from_id
reports it unrecognized and the parser emits a log_warn (the full ordered
resolution ladder + import report is the P7 work).
Binding an interactive element to a host parameter (param_key). A
faithful_svg interactive element carries an optional param_key (e.g.
"filter.cutoff") that flows schema → interactive_element.param_key → IR
IRInteractiveElement::param_key → to_frame_elements() →
DesignFrameElement::param_key. This is the binding channel for
geometry-detected controls — the Triaz case, where a knob is a custom design
component (not a recognized Pulp-Library widget), so the recognized-widget path
that lowers its binding through IRNode never fires. When ANY element in a frame
carries a non-empty param_key, make_faithful_svg_frame auto-enables
route_changes_to_host_params(true), so a user gesture drives the
framework-agnostic HostParamSurface (JUCE APVTS / iPlug2 / StateStore) directly
via element_for_param_key / sync_from_host_params. It is inert until a
producer emits a key: an all-unbound frame keeps routing OFF and behaves exactly
as before (the public on_element_changed / on_gesture_* callbacks fire
regardless of routing, so an existing consumer never changes).
Producer emission (both lanes). faithful-vector.ts (labelAndBindKnobs) and
figma_rest_export.py (_label_elements) resolve each geometry knob against the
frame's Figma node tree by position and stamp three things from the matched node:
a human label, provenance source_node_id, and — when the layer name carries an
opt-in param:/bind:/meter: sigil — a param_key. paramKeyFromLayerName /
_param_key_from_layer_name mirror the C++ figma_binding_from_layer_name
EXACTLY (leading-ws tolerant, case-insensitive sigil, trimmed value, ≥1 alnum), so
a sigil-named knob binds identically to a recognized widget. The **sigil is
load-bearing**: a bare/DESCRIPTIVE name (the real Triaz case — "Cutoff", "Res")
is NEVER auto-bound (verified: all Triaz panel captions classify as label with
zero false bindings in both lanes) — it gets a label + source_node_id so the
annotated-manifest lane can bind it by node id. Match tie-breaks: a sigil node
beats a plain-named one; within a rank, nearest center then smallest area; the
root frame is excluded so a panel name ("sound / main panel") never mis-binds a
centered knob. Tests: [layer-name-binding]/knob cases in
faithful-vector.test.ts + ParamKeyBindingTest in test_figma_rest_export.py.
**Annotated-manifest binding (--param-binding-manifest) — the descriptive-name
lane.** Real designs (Triaz) name knobs descriptively ("Cutoff"), not with a
sigil, so the producer stamps source_node_id but no param_key. Supply a JSON
object mapping that Figma node id to a host-param key —
{"10:42": "filter.cutoff"} — via `pulp import-design … --param-binding-manifest
bindings.json. apply_param_binding_manifest` (design_import.cpp) walks the parsed
IR and sets param_key on each interactive element whose source_node_id is in
the manifest AND whose key is still empty — so **an explicit layer-name sigil
always wins**; the manifest never overwrites one. Applied once in the C++ import
CLI after IR parse (before the import report), so all downstream lanes
(materialize / codegen / DesignIR) see the binding. Get the node ids from the
importer's provenance or the Figma MCP get_metadata. Tests: [param-binding]
cases in test_design_import_ir.cpp (library) + test_import_design_tool.cpp
(CLI wiring + error paths).
Custom controls (P7 Tier-3) — the name→View factory registry. A genuinely
novel control resolves to kind=custom, which carries a factory_id (+ opaque
custom_props, typically JSON Pulp doesn't parse). The runtime
register_design_control_factory(id, factory) (design_frame_view.hpp) maps an
id to a std::function<unique_ptr<View>(const DesignControlContext&)>;
DesignFrameView::build_overlays looks the factory up for a Kind::custom
element and builds the overlay. UI-thread-only (registration at host startup,
lookup at overlay build) — the registry has no locking by contract. If no factory
is registered the element renders INERT (the baked SVG still shows) and
make_faithful_svg_frame emits a native-materialize-custom-factory-unregistered
diagnostic — a custom control never blanks or silent-knobs. Schema requires
factory_id for kind=custom. This is the piece a shared control PACKAGE (P8)
registers into. Beyond the usual atomic chain, the two exhaustive
DesignFrameElement::Kind switches in design_frame_view.cpp
(element_value/set_element_value) need the custom case, and the inspector's
frame_element_kind_name switch in inspect/src/inspector_window.cpp.
Import report (P7). Implementations of the import-report and
placement-verification passes live in core/view/src/design_ir_analysis.cpp
(extracted from design_ir_json.cpp, which is the IR JSON serialization
contract — keep the analysis passes there, not in the serializer).
collect_import_report(ir.root) (design_import.hpp)
walks the IR's interactive elements and surfaces each control's resolution
provenance — `{source_node_id, kind, resolution_rung, confidence_score,
conflict_signals, verification_pass} — plus summary counts (conflicted` /
low_confidence / unresolved) and ok(). pulp import-design prints the
human summary (import_report_to_text) to STDERR for EVERY output mode (codegen
- DesignIR-v1), writes the machine-readable JSON (
import_report_to_json) when
--import-report <path> is given, and --fail-on-unresolved makes a conflicted
or inert control a nonzero (2) exit — the CI gate. So a low-confidence or
conflicted control is SEEN at import time, never discovered later in the DAW.
apply_placement_verification(ir.root, frame_w, frame_h) runs first (the
structural half of the render-golden gate): it flags an overlay with no
renderable extent (zero hit-radius AND zero-area box) or one entirely outside the
frame region — setting verification_pass=false + a conflict so the report/gate
catch it. Frame size 0 = "unknown" (skips the bounds half, keeps the
degenerate-extent check). The full PIXEL-level golden diff is the render-path
follow-up.
**Multi-frame / post-processed components need a DEDICATED re-embed lane —
make_catalog_component.py is single-frame and applies no neutralization.** The
Musical Typing Keyboard is TWO frames (typing 187:15 / piano 187:349) AND its
exported SVG is post-processed: the design bakes a "selected keys shown" demo
chord as lit #16DAC2 key gradients, which must be NEUTRALIZED to the resting
key color (the live momentary overlay owns all pressed-state lighting) or the
[regression] no baked-lit demo chord test trips. So it has its own
tools/import-design/reembed_mtk.py: fetch both nodes via /images?format=svg,
neutralize, emit the chunked-base64 cpp. Neutralization is content-based, not
positional — a lit gradient is a <linearGradient> with both stops #16DAC2 +
a 0.26→1.0 opacity ramp; classify white (gradient y-extent ≥ 65 → #EBEEF1)
vs black (< 65 → #3A3F47/#16191E) so it survives Figma edits. --validate
asserts the decoded SVGs still match the committed file. **Gotcha — strip the
opacity:** the lit gradient's top stop is 0.26 opacity (the design's press
fade). Neutralization must REMOVE that stop-opacity="0.26", not just swap the
hex — a resting key is SOLID #EBEEF1, so a was-lit key that keeps the 0.26
renders translucent over the dark bed and reads GRAY beside its solid neighbours
(the "gray E4" report). Gotcha — reflow: removing a toolbar element (e.g. the
top-right OCTAVE/VEL cluster) lets Figma's flex REFLOW siblings — the overview
strip widened (right edge 151→677) and the > arrow moved (~550→689). Any
hardcoded element/overlay coords in musical_typing_keyboard.cpp (strip bounds,
arrow rects) must be re-derived from the regenerated SVG after such an edit.
Lesser gotchas:
--validate's "Similarity %" also breaks on size mismatch (it renders at
--render-size, often 2× the reference) — always diff at matched dimensions
with verify_region.py (per-tile).
--render-sizemust match the node aspect or content letterboxes → inflated diff.- Skia backend is mandatory for image/asset compositing (
--screenshot-backend skia).
This pairs with the upstream Figma-import toolkit (tools/figma-import/, which
captures the design HTML→Figma 1:1): Figma is the single source — design HTML
→ Figma (figma-import) → Pulp (this lane). Keep both ends improving from each
import's lessons.
CRITICAL: pulp-design-tool requires the GPU host (PULP_HAS_SKIA)
Before debugging any runtime-import resize / sizing / layout issue in pulp-design-tool or /tmp/<App>.app, verify the binary is using MacGpuWindowHost, not the CPU MacWindowHost. The design viewport pin, aspect-lock, and uniform paint-scale all live in MacGpuWindowHost (gated by #ifdef PULP_HAS_SKIA in core/view/platform/mac/window_host_mac.mm). When Skia isn't linked, WindowHost::create() returns MacWindowHost, where set_design_viewport() and set_fixed_aspect_ratio() are base-class no-ops — the example still builds and runs, but resize behaves as if every fix you've shipped is missing.
One-shot verification:
# In the worktree
nm build/examples/design-tool/pulp-design-tool 2>/dev/null | grep -q MacGpuWindowHost \
&& echo "OK: GPU host present" || echo "FAIL: CPU-only build"
# In a packaged .app
strings /tmp/MyApp.app/Contents/MacOS/MyApp-Bin | grep -F "[gpu-host]" \
&& echo "OK: GPU host present" || echo "FAIL: CPU-only build"
Recovery when Skia is missing (e.g. fresh worktree with external/skia-build/ containing only headers):
- Reuse the primary checkout's populated cache:
```bash
rm -rf external/skia-build
ln -s /Users/<you>/Code/pulp/external/skia-build external/skia-build
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release # should print "Skia: found at ..."
```
- Or run
tools/build-skia.shto rebuild Skia binaries from scratch (~30 min). - Or pass
-DSKIA_DIR=/abs/path/to/external/skia-builder/build/<plat>-gpu.
Defenses already shipped (don't bypass without reading the comments):
examples/design-tool/CMakeLists.txtissuesFATAL_ERRORat configure ifPULP_HAS_SKIAis FALSE — design-tool is intentionally a GPU-only example.examples/design-tool/main.cppchecks#ifndef PULP_HAS_SKIAat startup and exits with EX_CONFIG (78) + a loud stderr message.tools/cmake/PulpDependencies.cmakealready prints a screaming WARNING banner whenPULP_ENABLE_GPU=ONbut Skia isn't found; the release lane (PULP_REQUIRE_GPU_FOR_SDK=ONinrelease-cli.yml) escalates to FATAL_ERROR.
If your runtime-import test produces a window where content doesn't scale, the dark fill is visible past the design surface, or aspect-lock doesn't engage during drag, the FIRST thing to check is nm | grep MacGpuWindowHost. Don't tune set_design_viewport / windowWillResize: / setContentAspectRatio: until you've confirmed the GPU host is actually linked.
Detect which design source the user wants by checking:
- If a Figma MCP server is available (com.figma.mcp), offer to read the current file/selection
- If Stitch MCP is available (mcpstitch*), offer to list projects and get screens
- If Pencil MCP is available (mcppencil*), offer to read the current editor state
- If the user mentions Claude Design or hands over exported HTML, pass the
file directly with no --from flag. The CLI fingerprints Claude bundle
shapes versus generic HTML, assigns honest source provenance, and routes
both through the same Chromium evaluator. Anthropic has no public design
import API; manual file export remains the supported handoff.
- If the user provides a file path or URL, use that directly
- If none of the above, ask the user for a source and file
Workflow
Imported designs: declare dimensions in CMake, never hand-roll `view_size()`
Pulp's SDK auto-sizes plugin editors from a single pair of CMake args, so
every imported-design plugin opens at the right size in AU / AUv3 / VST3 /
CLAP / Standalone with no per-format override. **Always use the CMake path
— don't hand-roll Processor::view_size() for imported designs.**
pulp_add_plugin(MyPlugin
FORMATS AU AUv3 VST3 CLAP Standalone
...
DESIGN_WIDTH 900 # preferred editor width in logical pixels
DESIGN_HEIGHT 520 # preferred editor height in logical pixels
# Optional explicit bounds; omit for auto-derivation:
# min = preferred * 2/3
# max = preferred * 2
# aspect_ratio = width / height
# DESIGN_MIN_WIDTH 700
# DESIGN_MIN_HEIGHT 400
# DESIGN_MAX_WIDTH 1920
# DESIGN_MAX_HEIGHT 1080
SOURCES my_plugin.hpp my_plugin.cpp
)
Mechanism:
pulp_add_plugininjectsPULP_PLUGIN_DESIGN_W/H/MIN_W/...as
target_compile_definitions on ${target}_Core (PUBLIC, so every
linked format adapter sees them).
format::Processor::view_size()'s default checks for the macros and
calls view_size_from_design(w, h, ...) to derive the full ViewSize.
- The derived
min > 0is what enables CLAP'sgui_can_resize
(core/format/include/pulp/format/clap_entry.hpp:391) and prevents
the corner-drag-crops-instead-of-resizes regression that landed on the
m149 branch and bit us in Reaper.
Symptoms when this is missing (any of these = you forgot the CMake args):
- CLAP / VST3 corner-drag crops instead of resizes. Default
min = 0
fails gui_can_resize, host treats the editor as non-resizable.
- Plugin opens at a random portrait size after re-launch. With no
design-side dimensions and no saved window rect, hosts fall back to
the format's default content area (often portrait ~360×480).
How to choose the numbers:
- Open the imported JSX bundle in
pulp-screenshot --script <bundle.js>
and try --width / --height values until the layout looks right with
no letterboxing or content clipping. Those become DESIGN_WIDTH/HEIGHT.
- Trust the auto-derivation for min/max unless you have a specific reason
to clamp tighter (e.g., a widget that breaks below 700×400).
- The derived
aspect_ratio = width/heightmakes the host snap the
corner-drag to the design AR (Phase 3 design viewport letterboxes the
rest).
Stage B of #2784 — pulp import-design auto-emitting a .size.json
sidecar that pulp_add_plugin reads, so the dimensions are declared
once at import time — is the immediate follow-up. Until then,
DESIGN_WIDTH / DESIGN_HEIGHT is the codified path; the C++
view_size_from_design() helper is unit-tested in
test/test_processor_defaults.cpp.
Do not write a view_size() override for an imported-design plugin
unless you have a runtime-computed dimension (rare; usually a custom
non-script UI). Hand-rolling reintroduces the per-plugin maintenance
burden the SDK args were designed to eliminate.
DesignIR v1 asset manifest lane
When a user asks for canonical IR or an import pipeline handoff, prefer
pulp import-design --emit ir-json. The output is a versioned DesignIR v1
envelope with a deterministic assetManifest sidecar. Local images, SVGs,
font URLs, CSS url(...) values, and data URIs are recorded by default.
HTTP(S) assets are resolve-only unless the user explicitly passes
--allow-network-fetch; fetched assets use --asset-cache, honor
--asset-timeout-ms, and can be pinned with repeated
--asset-hash <uri=sha256> flags.
For --url imports, relative asset references resolve against the original
source URL, not the temporary downloaded file. The manifest keeps the authored
value in original_uri, stores the resolved fetch target in source_url, and
nodes keep their raw URI attributes plus a stable companion such as
srcAssetId or backgroundImageAssetId.
DesignIR v1.5 also carries document-level provenance (capture_method,
settle_rounds, fallback_reason, source_adapter, source_version,
imported_at) and structured top-level diagnostics. Parse APIs return the
shared normalized form, including interactive-frame promotion from the Pulp
view library.
The shared native-resolution layer lives in
core/view/src/design_import_native_common.{hpp,cpp}. It consumes normalized
DesignIR plus IRAssetManifest and returns a deterministic
ResolvedNativeNode tree for later baked-native/baked-cpp materializers.
Mapping precedence is audio_widget first, then IRNode.type, then HTML
subtype attributes such as input[type=range], with unsupported nodes and
properties degrading to diagnostics instead of throwing. When resolving frozen
DesignIR JSON, keep the embedded assetManifest fallback intact; do not
iterate IRNode.attributes directly when diagnostic order matters because it
is unordered. Use sorted attribute keys for stable output.
The baked-native materializer is the direct View-tree lane:
`build_native_view_tree(const DesignIR&, const IRAssetManifest&,
const NativeMaterializeOptions&)` is public in
<pulp/view/design_import.hpp>. It calls the shared native resolver, returns a
detached std::unique_ptr<View> subtree, and catches API-boundary failures into
diagnostics instead of throwing. Keep image assets routed through
IRAssetManifest::resolve(asset_id); never interpolate raw filesystem paths
from IR attributes.
**A manifest local_path is a HINT, not an address — resolve it, don't trust
it.** Runtime lanes must go through resolved_asset_uri() /
resolve_asset_file() (core/view/src/design_ir_helpers.hpp), never
"file://" + *asset.local_path. A writer can persist a bare
<content_hash>.<ext> filename, which then resolves against the DesignIR
document's own directory while the bytes actually sit in a shared
design-assets/ folder BESIDE that directory (Forge's project store does
exactly this). Because the same node also carries an absolute asset_path, the
web-compat lane reads the node and renders correctly while the native lane
reads the manifest and drops the image — the two lanes disagree, and the native
one is silently wrong. Diagnosing that from a screenshot costs hours.
The resolver tries: the recorded local_path, then a file:// original_uri,
then <content_hash><ext> under the document directory, a design-assets/
inside it, and a design-assets/ beside it. Recovery-by-hash logs a warning,
and an asset that resolves to nothing returns "" plus a logged line — the
materializer then emits native-materialize-unresolved-asset and a placeholder
instead of an ImageView pointed at nothing.
Two consequences when writing code or tests here:
- Pass a search root.
NativeMaterializeOptions::asset_base_directorymust be
the directory the DesignIR was loaded from (pulp-design-ir-observe and the
standalone import example do this). Without it, relative paths fall back to
process CWD and hash recovery has nowhere to look.
- A test that asserts on a resolved image must write real bytes where the
manifest points. A synthetic path (/resolved/cache/logo.png) now
materializes the placeholder, so dynamic_cast<ImageView*> returns null.
asset_uri() in the same header is deliberately NOT existence-checked: it is
the codegen lowering, naming where bytes are supposed to be for a generated
program that runs elsewhere. Do not "fix" it to check the filesystem.
Generated JS must resolve an image's stable asset identity through that
manifest helper when asset_path is absent. Persisted faithful captures remove
their importer scratch path and retain self-contained data: bytes, so an
asset_ref without setImageSource(...) is a blank saved-project regression.
The widget bridge must then preserve that value as an image source URI; routing
it through the legacy filesystem-path setter prepends file:// and paints the
base64 payload as placeholder text instead of decoding the captured pixels.
Self-contained JS export (relative asset paths). The emitted ui.js
never references decode-time locations: after resolve_sprite_skins stamps
absolute paths, localize_ir_assets (sprite_skins.cpp) copies every
referenced image/font into assets/ NEXT TO the --output file and rewrites
attributes["asset_path"] / font.resolved_path to output-relative
assets/<file> before codegen. This is load-bearing for the .fig lane,
whose scratch dir ($TMPDIR/pulp-fig-*) is deleted when the run exits — an
export that kept absolute paths would silently lose all images on any later
render. Renderers resolve the relative form via
WidgetBridge::set_script_base_dir(<script dir>) (set by --validate,
pulp-screenshot, and pulp-design-tool; unset base = historical
CWD resolution). It resolves setImageSource / setKnobSpriteStrip /
registerFont / loadFont only, and unlike set_asset_roots() it never
restricts loadAsset. Skipped for --dry-run (must not write files) and
baked emits (cpp codegen takes no asset paths). make_scratch_dir also
sweeps stale (>24h) pulp-<tag>-* siblings — runs killed mid-decode leak
their scratch dirs, and hundreds had accumulated before the sweep existed.
When testing emitted JS, note the unquoted // Source: header comment still
names the decode-time input; assert on QUOTED paths ('assets/...') when
pinning "no absolute references".
**Fonts are NOT localized, and a hosted editor now refuses the absolute
path.** localize_ir_assets rewrites image/sprite paths to assets/<file>
but leaves font.resolved_path absolute (it points into the design pack or
base_dir), so emitted registerFont('Family', '/abs/.../face.ttf') names a
file outside the script directory. WidgetBridge refuses an absolute path
that is not inside the script directory or a reviewed asset root unless the
host calls set_allow_unreviewed_file_paths(true); --validate,
pulp-screenshot and pulp-design-tool opt in (developer tools rendering
the developer's own import), but ScriptedUiSession (every DAW-hosted
editor) does not, so such a font silently falls back to the system face in a
plugin. Until fonts are localized like images, copy the face beside ui.js
and reference it as assets/<face>.ttf.
Windows path-separator gotcha (asset/font paths baked into generated JS):
when the CLI's asset pass (resolve_sprite_skins in sprite_skins.cpp) resolves an asset_ref/font asset_id to a path
that is stamped into attributes["asset_path"] / font.resolved_path (and from
there into setImageSource(...) / registerFont(...) in the generated JS),
convert it with fs::path::generic_string(), NOT .string(). On Windows
.string() emits native backslashes, which (a) bakes non-portable separators
into the generated UI and (b) breaks tests that assert on assets/...
substrings. generic_string() always emits /, and Windows file APIs accept
forward slashes. On POSIX the two are identical, so the change is a no-op there. The materialization call site itself should not run JS, but
do not market this as "no JS engine" globally because live React/parity lanes
still use the JS runtime. Baked/native consumers can link pulp::view-core;
live import, ScriptEngine, WidgetBridge, and scripted UI consumers should
link pulp::view-script or the full compatibility target, pulp::view.
The baked-cpp exporter emits native C++ source from the same resolved tree via
`generate_pulp_cpp(const DesignIR&, const IRAssetManifest&,
const CppExportOptions&). CLI usage is pulp import-design --mode baked --emit
cpp --output imported_ui.cpp; the tool writes the sibling .hpp` by default.
Generated code should contain direct widget construction, stable anchor IDs,
token/asset constants, bake_asset_manifest(), and TODO comments for unresolved
audio parameter or meter bindings. Knob current value and reset default are
distinct: emitted set_value(...) may come from the normalized value
attribute, while set_default_value(...) must come from normalized
audio_default. Preserve duplicate token names even when their values alias,
and emit non-hex semantic color tokens as strings rather than trying to parse
them as colors.
W3C Design Tokens (DTCG) export — `--emit-w3c-tokens`
pulp import-design ... --emit-w3c-tokens <path> (- = stdout) additionally
writes the imported IRTokens as a DTCG document via
pulp::view::to_w3c_tokens_json() (core/view/src/design_tokens_w3c.cpp).
Purely additive — the envelope tokens.json / --format pipeline is
untouched. Shape: top-level colors/dimensions/strings groups (empty
groups omitted), / in token names nests into DTCG groups
(brand/primary → colors.brand.primary), dimensions use the object form
{"value": N, "unit": "px"}, and IRTokens::source_identity provenance
lands under $extensions["dev.pulp.source"] (id/collection/mode/adapter,
empty subfields omitted).
String-token policy (there is no standard DTCG "string" type, and the
emitter never invents one):
- Font families promote to
$type: "fontFamily". Conservative name
heuristic, case-insensitive, segments split on both / and .: any
segment equal to font/fontFamily/font-family/typeface, or a final
segment of family/font. A comma-separated value ("Inter, sans-serif")
emits the DTCG array form ["Inter", "sans-serif"] (entries trimmed);
otherwise the plain string. These live in the strings group with the
same nesting + provenance as other tokens.
- Everything else is PARKED, never dropped. Ambiguous strings (easing
names, content text, component-style values) collect losslessly under the
document-root $extensions["dev.pulp.nonStandardTokens"] as
`{"<full name>": {"value": "<text>", "id", "collection", "mode",
"adapter"}} (provenance subfields from source_identity`, empties
omitted). Root $extensions is valid DTCG, so the real token groups
contain only standard-typed tokens.
pulp::view::validate_dtcg(json) (same header) is the in-repo,
dependency-free DTCG conformance check: it returns human-readable
violations (empty ⇒ conformant), covering resolvable + standard $type
per token (including group $type inheritance), $value shapes for
color/dimension/fontFamily, the reserved-$-key allowlist
($value/$type/$description/$extensions/$deprecated), and
$extensions being an object with namespaced (dotted) keys. The emitter
test asserts every emitted document validates clean AND that known-bad
documents are reported. Do not confuse this emitter with w3c_tokens.cpp
(export_w3c_tokens(Theme)) — that is the always-compiled runtime Theme
pair with flat dot-groups and string dimension values; the DTCG emitter is
the authoring-side surface. Note the fig lane currently extracts no
variables into IRTokens, so a bare .fig import emits {} — the
figma-plugin envelope and designmd lanes are the ones that carry tokens.
figma-plugin `binding` → canonical `pulp*` binding contract
The figma-plugin extractor (tools/figma-plugin/) exports a recognized Pulp
Library control as an audio widget (audio_widget) plus a single free-form
attributes["binding"] string (e.g. "filter.cutoff_hz"). The whole native
binding pipeline — the materializer (design_import_native_common.cpp,
NativeBindingMetadata::parse) and the binding-manifest codegen
(design_cpp_codegen.cpp) — only consumes the pulp*-prefixed contract, so a
raw binding string is invisible to them on its own.
parse_ir_node (design_ir_json.cpp, normalize_figma_plugin_binding)
normalizes that string into the canonical pulp* contract at the IR-ingest
boundary, so there is exactly ONE downstream binding consumer. Rules to keep in
mind when touching this:
- Recognized-widget gate. Synthesis only fires when
audio_widget != none.
A generic/visual frame that happens to carry a binding attribute gets NO
synthesized binding — it stays a generic node. Don't loosen this gate.
- Opt-in LAYER-NAME binding (
figma_binding_from_layer_name). A recognized
widget can declare its binding WITHOUT the explicit binding component
property, via a sigil-prefixed layer name — param:, bind:, or meter:
followed by "<module>.<param>" (e.g. a knob layer named
param:filter.cutoff_hz). normalize_figma_plugin_binding resolves the binding
from the binding attribute FIRST, then falls back to the layer-name sigil;
the rest of the lowering (module/param split, param-vs-meter routing by
audio_widget, pulp* synthesis) is identical either way. The **sigil is
load-bearing**: a bare/ordinary layer name is NEVER treated as a binding (no
false positives from names like "Big Cutoff Knob") — only a control the designer
explicitly tagged binds by name. An explicit binding attribute always wins
over the name. Case-insensitive on the sigil. This is the recognized-widget
path; binding a geometry-detected faithful-vector overlay (a knob the importer
found by geometry, not a Pulp Library component) by layer name is a separate
param_key-on-IRInteractiveElement path — keep the sigil convention identical
across both when you wire it. Pin any change with a
[layer-name-binding] case in test_design_import_sources.cpp.
- **Name→kind resolution matches whole WORD TOKENS, not substrings — in ALL
THREE lanes.** The C++ detect_audio_widget, the TS
audioWidgetKindFromName (extract-pure.ts), and the Python
widget_kind_from_name (figma_rest_export.py) all tokenize the layer name on
non-alnum + camelCase (acronym-aware, so VUMeter→{vu,meter}) + letter↔digit,
then match whole tokens (simple plural tolerated: Knobs→knob). The TS/Python
lanes were substring-based until the P2 resolver unification; all three now
share the boundary rule (mirrored, not one function — each has its own
vocabulary/return enum). This is deliberate: the old find()/includes()/in
substring match promoted Dialog/Radial→knob and Parameter/Diameter→meter
(gap survey). Don't revert any lane to substring matching; add new keywords as
tokens + a false-positive regression case (test_design_import.cpp,
audio-widget-name.test.ts, test_figma_rest_export.py). Lockstep is on the
VOCABULARY too, not just the boundary rule: the meter/waveform/spectrum aliases
(level, oscilloscope, analyzer/analyser) must exist in all three lanes —
the Python lane silently lagged on these until an adversarial-review follow-up,
so when you add a token to one lane, add it to the other two and pin it in each
lane's test in the SAME change. The faithful-vector
overlay lane's kindFromName (resolve-control.ts, P7) shares the same
whole-word convention for its own (InteractiveElementKind) vocabulary.
Component content is designer art — the `audio_widget: "none"` opt-out
Name-token recognition must NEVER fire inside a component's own content: a
layer literally named "knob base" / "knob ring" IS the designer's knob art, and
promoting it paints Pulp's built-in silver knob over the design. The contract
(same across lanes):
- The explicit opt-out: an envelope node with
audio_widget: "none"is a
real statement, not an absence — parse_ir_audio_widget
(design_ir_json.cpp) treats a literal "none" as explicit and skips
detect_node_audio_widget for that node. Only "none" opts out; unknown
strings still fall through to detection. The recognition resolver still runs
afterwards (it is keyed on component identity, not names), so a matched
library component becomes a real widget regardless.
- The
.figlane (tools/import-design/fig/scene.mjs) expands INSTANCE
nodes into their master SYMBOL subtree (override guidPaths resolve by guid OR
overrideKey; multi-segment paths forward into nested instances), stamps the
instance + every expanded node "none", and emits
figma.component_key / main_component_name from the master.
- The REST lane (
figma_rest_export.py::walk) stamps"none"on (1) any
INSTANCE / COMPONENT and its whole subtree — identity comes from the /nodes
components + componentSets maps, preferring the SET key (that is what the
resolver tables are keyed by); (2) any DETACHED copy — a widget-named frame
that directly owns raw shapes (_owns_shape_art) — one drawn widget whose
parts are art; and (3) any widget-named CONTAINER it declined to promote —
the pin matters because asset capture can collapse child containers into leaf
images, and the C++ heuristic re-run on that DEGRADED envelope would
re-promote the parent without it. Name promotion survives only for EMPTY /
text-only placeholder frames, where there is no art to destroy.
- Known asymmetry (follow-up): the TS plugin lane (
extract.ts) and the
C++-side detect on .fig DETACHED copies do not stamp the opt-out yet, so a
detached knob's shape leaves can still be name-promoted there. Fix belongs in
the shared detect gate or per-lane stamping — mirror the REST rules.
- Pinned by:
test_figma_rest_export.py(instance/detached/pin cases),
fig.test.mjs (expansion + opt-out contract), and the
explicit audio_widget 'none' suppresses name-based widget detection case in
test_design_import_sources.cpp (with a promoted control sibling).
`AudioWidgetType` is the vocabulary BOTH consumers key off
A lowered control reaches a running plugin down two independent paths, and both
of them dispatch on AudioWidgetType — not on the node type, not on a class
name:
- native:
kind_from_audio()incore/view/src/design_import_native_common.cpp
→ NativeWidgetKind → make_widget() → the bind_* callback
- script:
audio_widget_web_tag()/audio_widget_type_name()in
core/view/src/design_codegen.cpp → the bridge factory + the binding emission
So a new bindable affordance is an AudioWidgetType member. Expressing one as a
node type instead binds on the native path and renders inert in the emitted
script — the control materializes, hit-tests and animates, and the parameter
never moves. Adding the member makes every non-defaulted switch a compile error,
which is how the sites that need it announce themselves.
The producer end is one line in lower_semantic_controls
(tools/import-design/browser_capture_ir.cpp): its else continue drops any
capture kind it does not name, and a dropped control is still DRAWN by the
painted-tree lowering. That is why an unsupported affordance looks like a
working one — the shape a player reaches for is on screen, wired to nothing.
browser_capture/semantics.mjs already classifies far more than the lowering
admits (pulp-switch/pulp-check → toggle, pulp-stepper → stepper,
pulp-combo/pulp-select → select, pulp-radio, pulp-tab, pulp-numbox);
recognition has never been the ceiling.
Three traps when adding one, each of which compiles and runs:
- The event name is per widget.
KnobandFaderdispatchchangewith a
position; Toggle dispatches toggle with 1/0; Checkbox dispatches
change with 1/0. Wiring the wrong one registers a listener that never fires.
The table is core/view/src/widget_bridge/widget_callbacks.cpp.
- Boolean state is read from an attribute, not the numeric default.
imported_widget_semantics takes a toggle's opening state from checked /
value via attr_bool, so a lowering that writes only audio_default opens
every switch OFF — including the ones the design drew lit.
- A control over a designed body owns none of its own pixels. Knob and
fader call apply_designed_body_skin; anything else must suppress its stock
body itself when body_is_painted_beneath(node) is true, or it paints an
opaque widget over the art the import exists to reveal.
generate_pulp_js() has TWO arms and they are not interchangeable. The
native-bridge arm (CodeGenMode::bridge_native_js, the DEFAULT, and what
pulp import-design --emit js produces without --web-compat) emits through
emit_js_*; the web-compat arm emits through generate_node(). For a long
time only the second one bound anything: the native arm created the widget,
sized it, and printed the control's binding name in its grey sub-stack, so a
knob imported through the documented default rendered, turned under the mouse,
and moved no parameter — with the parameter's own name captioned underneath it.
Both arms now call one emit_js_param_binding(). The two address a widget
differently (el._id versus a string-literal id), which is what made the
emission get duplicated and then maintained on one side only, so the helper
takes the id EXPRESSION. Add a binder there, not in an arm.
A widget reached through the web-compat DOM has a SECOND wiring path inside the
bridge, and it is easy to miss: createX wires its callbacks inline, while a
lowercase tag routed through __domAppend goes to make_widget_for_tag() and
gets its callbacks from wire_callbacks(). A new widget kind needs FOUR tables
in step — the factory (factory_api.cpp), the tag map (web-compat-element.js
__widgetTagFactory__), make_widget_for_tag() (widget_bridge.cpp), and
wire_callbacks() (widget_callbacks.cpp) — plus a row in
widget_bridge_api_manifest.tsv. Miss the last wiring one and the factory path
works while the tag path builds a real, clickable control whose changes reach
nothing; the emitted script is identical either way.
The bindable vocabulary, and what is still NOT in it. Keep this list honest —
the authoring brief is written against it, and a brief that promises more than
this produces controls that render, drag, and move nothing:
| Component | Binds | Notes |
|---|---|---|
| pulp-knob | ✅ | continuous |
| pulp-fader | ✅ | continuous, drawn as a throw |
| pulp-switch / pulp-check | ✅ | on/off; data-pulp-value sets the opening state |
| pulp-select (segmented) | ✅ | data-pulp-choices="A|B|C", pipe separated |
| pulp-stepper | ✅ | a count; data-pulp-min / -max / -step are REQUIRED |
| pulp-meter | display | shows a macro; drives nothing. Binds by its pulpMeterValueKey in every lane: ui.js through bindMeter(id, key), native and baked C++ through bind_level_display with value_key set and an empty source and channel, which the host context binds by that key |
| pulp-combo, pulp-tab, pulp-radio, pulp-numbox | ❌ | recognised by the capture, dropped by the lowering — drawn faithfully, wired to nothing |
Everything outside that table is DECORATION, and decoration is most of a good
panel: a step grid, a transport readout, a patch list, LED pips, a routing
diagram. Draw it — just never put data-pulp-param or data-pulp-meter on it.
A SELECTOR is one control with a shared track, never N adjacent toggles: a row
of independent switches can show two lit at once, and even when it does not it
reads as several controls that happen to touch. The value a segment writes is a
function of the segment COUNT, so both directions go through
selector_segment_value() / selector_segment_index() (design_ir.hpp) rather
than a restated formula — and a STEPPER does the same through
stepper_normalized_value() / stepper_plain_value(), because it reports the
PLAIN number it shows while the parameter behind it is normalized. Its declared
range must reach the widget (setMin/setMax), or it keeps its own -24..24
default and a voice count reads as an octave offset. Note the asymmetry that
caught a regression: setValue/getValue on a Stepper have always meant the
PLAIN number, and changing them to normalized breaks callers — only the
parameter PUSH (apply_param_binding) converts — and the script emitter bakes those numbers at %.9g,
because a truncated literal still selects the right segment and is no longer
the value a native host would have written for it.
Pinned by test_design_import_toggle_binding.cpp, which proves the same thing
on both paths the only way that distinguishes a wired control from a convincing
one: click it and assert the STORE moved.
KEY-based recognition + the recognition-resolver merge module
NAME-token recognition (above) is a fallback. The AUTHORITATIVE recognition
signal is the Figma component identity — a component_set_key. This is a
SEPARATE mechanism from the 3-lane name-token vocabulary; do not conflate them.
- The merge module is the single source of truth.
core/view/.../recognition_resolver.{hpp,cpp}
(RecognitionResolver) is the ONE place that combines recognition SOURCES
into a merged component_set_key → kind (and → factory_id) table. Sources,
in precedence order (later wins on key collision):
1. built-in Pulp Figma Library (recognition_resolver_with_builtin_library(),
a Pulp-owned pack in recognition_audio_pack.{hpp,cpp} linked as
pulp-design-import-audio-pack, NOT part of the generic resolver;
mirrored in code from tools/figma-plugin/library-manifest.json and pinned
against the JSON by a drift-guard test),
2. the user's --recognition-manifest (flat library-manifest shape),
3. installed-package design_controls fragments (custom controls) —
gathered by discover_package_design_controls() (walks up for the project's
packages.lock.json, then reads the registry at tools/packages/registry.json
— the canonical CLI layout from find_registry_path, NOT a lockfile sibling;
a wrong path silently merges zero packages — builds ONE RecognitionSource
per installed package that declares any design_controls, named by package id)
and added via add_source(...) ONCE, in the same resolver-build block, NOT
by threading a third lookup through the importer lanes. **Do not scatter the
merge.** Any new recognition source becomes one more add_source call.
A package fragment carries factory_id (no built-in kind), so a match
routes to the custom-control materialize path below. With no custom-control
package installed this contributes zero sources, so behavior is unchanged.
--recognition-manifest <path>lets a designer map their OWN component-set
keys / name prefixes to Pulp kinds. Shape (mirrors library-manifest.json):
{ "widgets": { "<name>": { "kind"?, "component_set_key", "name_prefix"?, "factory_id"? } } }.
kind defaults to the widget's map key. factory_id (no kind) is the
custom-control path: a match resolves to a registered native overlay instead
of a built-in widget (same shape installed-package design_controls use).
Harvest keys from the Figma MCP search_design_system.
- Which lane is wired (authoritative): the C++ CLI figma-plugin lane. The
plugin envelope carries each instance's figma.component_key /
main_component_name EVEN when the in-Figma TS plugin did not recognize it
(a third-party component) — parse_ir_node stamps these into
attributes.figmaComponentKey / figmaMainComponentName. After parse, the
CLI (pulp_import_design.cpp, figma / figma-plugin sources only) builds the
resolver (built-in + optional user manifest) and calls
apply_recognition_resolver(ir.root, ...), which stamps audio_widget on any
instance that matched but was not already recognized. This is the lane that
turns a pixel-faithful-but-0-controls third-party design (the live Ink &
Signal "NumberBox" case) into a wired one.
- **The TS plugin (
extract.ts→widgetKindByLibraryKey) bakes recognition
at CAPTURE time** for the built-in library only; it is NOT yet wired to a
user manifest (it runs in the Figma sandbox; feeding it a manifest needs
plumbing through the plugin UI). **The Python REST lane no longer bakes
widget kinds for components at all** — it emits each instance's
figma.component_key / main_component_name (from the /nodes components +
componentSets maps, SET key preferred) and lets the C++ resolver do all
key-based recognition, so --recognition-manifest works for URL imports.
Follow-up: accept the user manifest in the TS lane too.
- Never-silent-knob (P7) holds. A component instance present in the design
but matched by NO source is NEVER guessed into a kind — apply_recognition_resolver
collects it into UnmatchedComponent[], which the CLI surfaces as an
unmapped-component import diagnostic. Additive guarantee: no manifest + no
resolvable third-party key ⇒ behavior unchanged; an already-stamped
audio_widget is never overridden.
- Custom-control materialize half (the package lane's runtime side). A
custom-factory match has no built-in audio_widget to stamp — instead the
resolver records the recognitionFactoryId node attribute. The CLI then runs
materialize_recognized_custom_controls(ir.root) (same module), which converts
every such node into a kind=custom IRInteractiveElement carrying that
factory_id + the node's geometry. The native materializer
(make_faithful_svg_frame → to_frame_elements) builds the overlay via the
factory the package registered with register_design_control_factory. An
unregistered factory renders inert (the baked SVG still shows) AND emits the
native-materialize-custom-factory-unregistered diagnostic — never a silent
knob. The conversion is idempotent and additive (a node with no
recognitionFactoryId is untouched).
- Merge ordering is deterministic and pinned. Package sources are gathered
in lockfile order; the resolver merges later sources OVER earlier ones, so on
a component_set_key (or name_prefix) collision the LAST-added package wins.
Tests pin this so a re-order is a visible change, not a silent one.
- Module/param split. Split on the FIRST
.:"filter.cutoff_hz"→
pulpBindingModule="filter", pulpBindingParam="cutoff_hz",
pulpParamKey="filter.cutoff_hz". No dot → empty module, whole string is the
param. param_key (non-empty) is what drives both the manifest entry and the
codegen bind_knob/bind_fader helper gate.
- Meters differ.
knob/fader/waveformmap to a writable param
(pulpParamKey); meter/spectrum map to pulpMeterSource +
pulpMeterChannel (no pulpParamKey), since a meter reads a metering input.
pulpRouteIdis required for the codegen helper to emit a live bind call;
it's synthesized deterministically as "figma-plugin:<binding>".
- No-overwrite / no-regression. Synthesis routes through
NativeBindingMetadata::serialize() (skip-empty, no-overwrite) and bails if
any canonical binding attr is already present, so a JSX/Claude node that
already carries pulp* is untouched. The raw attributes["binding"] is
always preserved — never delete the source evidence.
- This is a generalizable importer rule, not a per-fixture patch: it reads
the figma-plugin data and produces the contract for ANY recognized widget.
Skinned fader/meter width derivation
Recognized faders/meters must render their track/fill/bar at the captured art's
NARROW inset width, not the full node box. The sampler in
core/view/src/widget_skin_derive.cpp recovers horizontal extents from the
captured PNG pixels (row_art_bounds scans opaque pixels OUTWARD from the centre
column cx, so disjoint label glyphs on the same row never widen the result):
- Meter:
derive_meter_skinreportsbar_width_px= median opaque row width
inside the bar's OWN vertical region [top, bottom) (found via find_art_region
on cx). That excludes the label text below the bar.
- Fader:
derive_fader_skinreportsthumb_width_px(widest opaque row = the
silver slab) and track_width_px (median of the NARROW rows ≤ ~40% of the
widest = the thin track/fill column).
Gotchas learned wiring this:
- The widest row in the whole asset is usually the label text, not the thumb.
find_art_region/cx scoping is what keeps the thumb measurement honest — do
not measure the widest row over the entire image.
sprite_skins.cppdivides art px by `asset_scale = img.width /
node_box_width_px` (figma-plugin exports at 2×, but DERIVE it, don't hardcode
2). It stamps shape_width = thumb/bar width (→ widget width) and
skin_track_width (fader only). The column min_width keeps the box width so
the narrow widget centres.
- Render path: meter codegen reads
shape_width→ widget width (already wired);
fader needs BOTH — shape_width → widget/thumb width AND setFaderTrackWidth
→ Fader::set_skin_track_width, which makes Fader::paint draw the track at
exactly that thin centred width instead of 0.18 * box.
- Verify by reference-diff, never by eyeball. Measure visible-art width as a
% of the node box in BOTH the captured asset and the rendered PNG; target
within ~15%. For the smoke export the derived values were fader-track 5px
(5.2% box), fader-thumb 28px (29% box), meter-bar 18px (26% box), all matching
the reference within 3%.
- Everything is derived from sampled pixels / node data — NO per-instance or
hardcoded pixel constants (repo rule: every visual importer fix must be a
generalizable rule reading the design data).
A designed control: installing a painter is not the same as it being consulted
apply_designed_body_skin (core/view/src/design_import_native_common.cpp) is
what makes a control whose design already painted its own body stop drawing a
stock body over it. It installs a WidgetPainter via
apply_designed_control_skin, and the widget's paint is supposed to give that
delegate first refusal.
**Only the widget kinds whose paint actually calls effective_painter() honour
it.** Knob::paint does. Fader::paint did not, and WidgetPainter::paint_linear
had no caller anywhere in the repo — so installing the skin on a fader compiled,
ran, returned true, and moved zero pixels. Meter still has no painter hook at
all (WidgetPainter has paint_rotary / paint_linear / paint_button_background
and nothing for a level), so a designed meter still paints its stock body.
Checks worth doing before believing a designed-control skin works:
- Grep the hook for a call site, not just an override. An overridden virtual
with no caller is indistinguishable from a working one at compile time.
- Assert both halves in the test:
widget->painter() != nullptrproves the
install, and a counting painter reaching the hook proves the consult. Use
painter() and not effective_painter() for the install assertion, because
the latter walks up to an ancestor and will pass on a widget that was never
skinned itself.
- A designed FADER's Chrome-relative pixel diff is not a success metric.
The design authors a bare track and the widget supplies the fill/thumb, so the
oracle has nothing to match there. Judge a fader by what the widget stopped
overpainting, not by the number. A designed KNOB is the opposite (next point):
its value layer is authored-gated, so its Chrome diff IS the metric.
**A designed knob's value layer is authored-gated — no authored ring/pointer,
no pixels.** The skin used to synthesize the full arc gauge (accent value arc +
grey track + derived tick) on every designed knob. On a captured panel whose
knobs are plain gradient dials (data-pulp-paint, no data-pulp-indicator)
that painted arcs the reference never shows, riding OUTSIDE the authored dial —
the single largest bucket (~42%) of a real strict-fidelity failure. Now
apply_designed_body_skin sets DesignedControlSkin::draw_ring only when the
design declared a ring (design_ring_radius > 0) and draw_indicator only for
an authored pointer (knob_ind_r_out > 0) or that declared ring; with neither,
paint_rotary still returns true (the stock body stays suppressed) but emits
nothing, so the authored body beneath is the whole appearance. A design that
wants a moving part must author data-pulp-indicator — Pulp never substitutes
its own knob art. (paint_mod_ring_knob grew matching draw_track_and_fill /
draw_indicator flags, default true, so stock knobs are untouched.)
The control's box IS the design's body box. It comes from the author's
[data-pulp-paint] rect (browser_capture/semantics.mjs, paintBox), which in
practice is the dial element itself. paint_mod_ring_knob then takes
min(w, h) * radius_scale on local_bounds(), so **every radius_scale <= 0.5
paints on the body by construction** — a fixed 0.46 put the value arc at 92% of
the body radius, straight across a brushed cap the design had just drawn. No
constant can satisfy "the design owns the body", because the constant is a
fraction of the body; apply_designed_body_skin therefore derives the scale from
the body EDGE (0.5 + (ring_width/2 + 1) / min(w,h)) and treats a
design_ring_radius attribute as an override rather than the mechanism.
Two consequences when changing that radius:
- A scale above 0.5 paints OUTSIDE the widget's own box. That is legal here —
View clips only on overflow: hidden/scroll — and the hit rect is
unchanged, so the drag target stays on the dial. It does mean neighbouring
controls can converge: measure the gap between the two ARCS, not between their
boxes, because both arcs move outward together.
- Measure the arc radius in a band tight around the expected value. A wider band
silently averages in the design's own concentric decoration (kelvin's copper
hairline at r≈89 and tick ring at r≈98) and reports a radius a pixel high.
Meters, waveforms and spectra go through the view-core display seam
Native materialization and the generated C++ never name Meter,
WaveformView or SpectrumView: a meter/waveform/spectrum node is made
with make_data_display("pulp.level" | "pulp.series" | "pulp.bins") and
configured through LevelDisplay/SeriesDisplay/BinDisplay; binding goes
through bind_imported_level_display/bind_imported_series_display, in both
the materializer and the generated binding helpers. Those call the
provider-neutral virtual and then the deprecated bind_meter/
bind_waveform_display through the binder pulp::view-audio registers, so
emit the helper, never a bare ctx.bind_level_display, or old-only contexts
go silently unbound. setMeterColors fills through one
set_level_fill(optional background, stops) call: a gradient must never
restate the background. With no provider registered the materializer
returns a placeholder plus a data-display-unavailable diagnostic and the
binding reports native-binding-not-applied. Generated code keeps that
property: the non-faithful path emits a View fallback for a null factory
result, and the faithful_svg path must not (its variable is a
unique_ptr<DesignFrameView>). The guard is [data-display] in
test_design_import_native_materializer.cpp, which compiles generated displays
in both modes against view-core headers only and scans emitted output for
provider-only names.
Native codegen fidelity gaps
The render uses generate_native_node in core/view/src/design_codegen.cpp
(createCol/createRow/createLabel/createKnob/setFlex…), NOT the generate_node
DOM path. Several styles only existed on the DOM path; the native path needs its
own emission. Fixes landed here, each grounded in the export data:
- Nested padding. The figma-plugin export sends container padding as a nested
object layout.padding = {top,right,bottom,left}. parse_ir_layout in
design_ir_json.cpp only understood a uniform float / camelCase per-side keys,
so the nested form was dropped (→ 0, content hugged the edge). The parser now
accepts all three forms; the native container path already emitted per-side
setFlex(id,'padding_*',…), so once parsed it renders.
- Text wrap. A text node's
style.widthwas emitted only asmin_width, so a
long subtitle ran off the panel. Emit a hard setFlex(id,'width',w) +
setMultiLine(id,true) ONLY when the design box is taller than one line
(height > font_size*1.6) — that's the design's own signal that the string is a
wrapping paragraph. A one-line title (height ≈ one line) is deliberately NOT
bounded: forcing its hug-width as a wrap box makes it wrap when Pulp's font
metrics run a hair wider than Figma's.
- Knob value taper. The native silver knob maps a 0..1 value LINEARLY to its
[-135°,+135°] sweep, so the imported value must already encode the param taper.
The knob path emitted the RAW audio_default (e.g. 880), which set_value
clamps to 1.0 (and a linear normalise put 880 Hz at ~0.04 — indicator pointing
the wrong way). Now: for a frequency-unit knob (units == hz/khz) use a LOG
normalise so 880 Hz in [20,20000] lands ~0.55 (indicator ~straight up, matching
the design); other units fall back to linear (value-min)/(max-min). The fader
already normalised; the knob was the outlier.
- font_weight/font_family were ALREADY emitted on the native text path — no
fix needed; a regression test now pins them.
- Fader empty-track outline. The captured empty track has a faint lighter
edge. derive_fader_skin first tries to RECOVER it (brightest low-sat pixel on
a dark track row vs the row-centre fill). Gotcha: the importer's in-tree
minimal PNG decoder (decode_png_rgba in sprite_skins.cpp) FLATTENS the
sub-pixel anti-aliased rim — it reads the whole thin track column as uniform
fill, so the edge is unrecoverable from those pixels even though PIL sees it.
Fallback: SYNTHESISE the rim by lightening the sampled dark track colour
(lum < 90 → +30 per channel); a light/flat track stays borderless. Emitted
via setFaderTrackBorder(id,'#rrggbb') → Fader::set_skin_track_border_color,
which strokes the track rect in Fader::paint. Still derived from the captured
track colour — no hardcode.
- Knob bevel depth (the silver knob reads more heavily 3D than the flatter
captured disc) is a WidgetRenderStyle::silver cosmetic gap, NOT data-driven —
left as a follow-up rather than guessing gradient constants that would affect
every imported knob.
The Phase 5/7/9 benchmark harness lives at pulp-design-import-bench and is driven
by tools/scripts/design_import_benchmark.py. Run it under no-launch env
(`PULP_DISABLE_PLUGIN_EDITOR=1 PULP_HEADLESS=1 PULP_TEST_MODE=1
PULP_INSPECTOR_NO_LAUNCH=1). It compares live, baked-native`, and
baked-cpp lanes, emits startup/idle/interactive metrics, and computes the
Phase 9 gate from linked text+data section size using size/llvm-size; after
the target split it tracks live-runtime objects under pulp-view-script. Do
not use Debug object-file byte counts as the gate input. A valid report must
record the explicit binary-size delta and whether JS evaluation churn is
actually the dominant bottleneck for the measured fixture. Keep the legacy
top-level comparison entry pointed at baked-native, and add per-lane
results under comparisons for both baked lanes.
Benchmark receipt (pulp-design-import-benchmark-v2) gotchas:
- Layout belongs to the frame, not to
step().run_phaselaps
update, layout, record and submit on one clock and checks the laps
cover the frame (stages.consistent). A fixture that calls
layout_children() inside step() bills a layout to update and runs two
per frame. Before v2 every baked lane and the live script's step did exactly
that, so v1 receipts are not comparable per stage or per layout_passes.
- **The default
recordingcanvas cannot see decodes, uploads or text
shaping** — RecordingCanvas records commands and does none of that work.
Resource claims need --canvas=skia-raster (or skia-graphite where a Dawn
adapter exists); --require-steady-state exits 4 on a blind gate rather
than passing it. Paragraph builds are gated by TEXT, not by count: a step
legitimately shapes the runs it wrote (the IR fixtures write fresh
slot i frame N strings every frame), so the gate reads
paragraph_builds.unwritten, the builds of any text the fixture's
text_written_by_step(frame) did not list. A count budget ("at most N
builds") is blind to a culled slot: the slot shapes nothing, and a static
label re-shaping every frame fits inside N. A new fixture that writes text
must list it, or the gate fails it.
--paragraph-cache=off is the uncached text path and the gate's planted
negative; compare cached vs uncached with --baseline-arg /
--candidate-arg on the same lane.
--irresolves manifest assets against the DesignIR's directory. An
importer writes local_path relative to the DesignIR, and the IR-bound lanes
used to materialize without asset_base_directory, so they resolved those
paths against the process's working directory. Started anywhere but beside
the IR, the bench drew no images and its decode and image-cache counts read
zero: the steady-state gate was blind to images on imported panels. With
the real asset base the materializer's containment applies too: a manifest
path that climbs out of the IR's directory (../x.png) or names an absolute
file elsewhere is refused and drawn as a placeholder, even though the old
working-directory lookup used to load it. Keep a benchmarked IR's assets
beside it, as the importer writes them.
- **
--lane=live --ir(optionally--bundle) is the production JS path over
importer output.** The runtime's __pulpRuntimeSettle__ called from
engine.evaluate only records a budget; WidgetBridge::load_script drains
it. A per-frame step therefore calls service_frame_callbacks() itself,
the host's frame tick, instead of settling from JavaScript.
- Most fleet hosts confound most runs. A receipt is
confoundedwhen
getloadavg exceeds cores/4 or the thermal state is not nominal; the gate
hosts usually sit above that. design_import_benchmark.py --compare then
reports confounded, never win — measure on a quiet host, do not argue
the threshold down.
Node-type dispatch — exhaustive, never silent (all three producers)
All three Figma producers dispatch node types EXHAUSTIVELY against the pinned
@figma/plugin-typings SceneNode union (version in
tools/figma-plugin/package.json); the old shape was a default: "frame"
fallthrough that made every unsupported node — FigJam stickies, Slides rows,
SLICE export regions — look like a successfully imported empty frame. The
three dispatch sites, kept in lockstep (one decision table, three spellings):
- plugin:
tools/figma-plugin/src/extract-pure.ts::dispatchNodeType
(mapNodeType remains as an emit-type accessor only)
- REST:
tools/import-design/figma_rest_export.py::dispatch_node_type .fig:tools/import-design/fig/scene.mjs—envelopeType+
the walk-top skip checks + KNOWN_NODE_TYPES/SKIPPED_NODE_TYPES
The decision table, per family:
| Family | Dispatch | Diagnostic |
|---|---|---|
| TEXT_PATH | emit text, characters preserved | text-path-flattened (on-path layout flattened) |
| TRANSFORM_GROUP (.fig kiwi spelling: TRANSFORM) | emit frame, explicit | none — it renders fine |
| SLOT | emit frame (placeholder) | slot-placeholder (bare import has no slot content) |
| SLICE | skip — an export region paints nothing; a frame here invented a box | slice-skipped |
| Editor/FigJam (STICKY, CONNECTOR, SHAPE_WITH_TEXT, CODE_BLOCK, STAMP, WIDGET, EMBED, LINK_UNFURL, MEDIA, HIGHLIGHT, WASHI_TAPE, TABLE, REST TABLE_CELL) + Slides (SLIDE, SLIDE_ROW, SLIDE_GRID, INTERACTIVE_SLIDE_ELEMENT) | skip | unsupported-node |
| Unknown/new type | emit frame (never crash) | unknown-node-type — the fallback is stated, not silent |
Gotchas:
- Diagnostic taxonomy: plugin/REST envelopes carry `kind:
"unsupported_node" (added to ExtractedDiagnostic`, the envelope schema,
and C++ ImportDiagnosticKind; diagnostic_kind_from_code classifies the
four dispatch codes for kind-less producers). The .fig lane uses its own
pushDiag channel — every new code MUST be registered in
DIAGNOSTIC_SEVERITY (scene.mjs) or it silently downgrades to dropped
info; the dispatch codes are all warning deliberately, including
slice-skipped, because both .fig consumers drop info.
- The
.figkiwi vocabulary is NOT the Plugin API's: components are
SYMBOL, rectangles ROUNDED_RECTANGLE, polygons REGULAR_POLYGON, and
the transform group is TRANSFORM. Both spellings are accepted where they
differ. Dump a file's actual enum via readSchema(...).definitions →
NodeType before assuming a spelling.
- Skips run before budgets/geometry: plugin skips before the
maxNodes
count; .fig skips before instance expansion and the geometry ledger, so a
skipped node also disappears from --dump-layout (expect node-count deltas
vs pre-dispatch dumps ONLY for skipped families).
- No new IR node types: dispatch lands on existing envelope types
(frame/text/ellipse/vector); design_ir_json.cpp needed only the
new diagnostic kind, no node-type change.
Vector shape primitives → synthesized SVG path
vector/path/svg_path nodes carrying an authored path_data (d) already
lower to a native SvgPathWidget (createSvgPath+setSvgPath).
The shape PRIMITIVES — rect/rectangle/svg_rect, line/svg_line,
ellipse/circle, polygon, star — usually arrive with NO d, so they used
to drop to an empty frame (caught by the dropped-vector invariant).
synthesize_primitive_paths (in core/view/src/design_import.cpp, declared in
design_import.hpp) now derives a d from geometry and stamps it onto the node
so codegen lowers it like any other path. Key facts / gotchas:
- Runs as a codegen pre-pass, on a copy.
generate_pulp_jscopies the IR
root in the native arm, runs synthesize_primitive_paths, then emits AND runs
the dropped-vector fidelity walk over that copy — so both see the synthesized
path_data. The caller's IR and the web-compat arm are untouched. (Putting it
in the parse pipeline instead would miss the [object-coverage] drift guard,
which calls generate_pulp_js directly on hand-built nodes.)
- Drop-case ONLY — zero behavior change for renderable nodes. It fires only
when a primitive has no path_data, no children, no visible fill
(background_color/gradient/image), no asset_path, and is not an audio widget.
A filled rect still renders via the generic-frame branch; a rect with children
keeps them. Don't widen this to filled/childful nodes — converting them to a
terminal SvgPath would drop their children / box-shadow / border.
svg_fillis forced to"none".SvgPathWidget's default fill is OPAQUE
BLACK (has_fill_=true, {0,0,0,1}). A synthesized shape with no IR fill must
emit setSvgFill(id,'none') (→ clear_fill()) or it paints a phantom black
box. A border becomes svg_stroke/svg_stroke_width.
- Geometry only — source-agnostic. Paths are derived from
width/height,
per-corner border-radius (rounded rect via SVG arcs; the SvgPathWidget
parser supports H/V/A), and optional pointCount (polygon default 3,
star default 5) / innerRadius ratio (star default 0.5) ATTRIBUTES — never a
layer name. A line may have one zero extent (a horizontal/vertical rule).
MSVC gotcha: the polygon/star angle math must NOT use M_PI — MSVC does
not define it without _USE_MATH_DEFINES, which broke the Windows CLI build
(and the whole release pipeline) once. Use the local kSynthPi constant.
- Release-runner toolchain gotcha (C++20 P0960): the GitHub-hosted macOS
release runner's Apple clang is OLDER than the self-hosted PR-lane clang and
does NOT implement parenthesized aggregate initialization (Type p(arg) for
a ctor-less aggregate), even at -std=c++20. So JsonParser p(snap.html_text)
in import_detect.cpp compiled on PR CI but failed the release build ("no
matching constructor"), silently breaking every GitHub Release from ~v0.371 to
v0.391 (the tag-triggered sign-and-release.yml / release-cli.yml Build step
died; tags kept getting created so the breakage was invisible until the
release-cadence watchdog flagged the tags-without-Releases). **Always brace
aggregate init** (Type p{arg}) in CLI/import code — it's valid on every
toolchain. (PR CI cannot catch this class; it only surfaces on the older
release runner.)
polylineis intentionally NOT synthesized — it is an open run of explicit
points that geometry alone can't reconstruct; it stays codegen: missing
(carry path_data or rasterize at export).
is_vector_kindis the shared classifier. Exposed from
design_fidelity.hpp; codegen's is_path_kind and the dropped-vector
invariant both call it so they never disagree about what is a path node.
- Source of truth:
compat.json imports/object-coverage(these 9 types are now
codegen: handled) + the [object-coverage] drift guard + the
[view][import][codegen][vector] tests.
Vector fill rule (winding) — holes in multi-subpath icons
A multi-subpath vector's WINDING RULE decides which regions are holes, and
dropping it is perfectly silent: the icon fills as a solid slab, no parse
error anywhere. The designers-pick "Sub" speaker cabinet (a box with a hollow
woofer ring) was the sweep's worst dE2000 (~25) for exactly this reason.
The rule now flows end to end; facts to keep intact:
.figgeometry entries carry their ownwindingRuleEACH. A node's
fillGeometry is a LIST of per-region entries `{windingRule, commandsBlob,
styleID} — and one node can MIX rules ("Sub" is [NONZERO dot, ODD ring,
ODD box-with-hole]). paths.mjs` concatenates the blobs into one path, so
one rule must be chosen: evenodd wins when any entry declares it. Figma
direction-corrects the contours of its NONZERO regions (holes wind opposite
their outer — verified on real subtract bool-ops), and direction-corrected
nesting fills identically under either rule; an ODD region's SAME-direction
holes fill solid under nonzero. So evenodd is correct for both kinds. Do
NOT "fix" this to first-entry-wins — that re-fills the Sub woofer.
- Figma does NOT promise direction-corrected contours under ODD. Never
assume nonzero is safe because "baked geometry reverses holes" — that holds
only for the NONZERO-declared entries.
- The wire: decoder emits
fillRule: 'evenodd'on the envelope node
(omitted for nonzero — widget default) → design_ir_json.cpp reads
fillRule/fill_rule/fill-rule into attributes["svg_fill_rule"]
(only evenodd/nonzero accepted) → JS codegen emits
setSvgFillRule(id,'evenodd'); baked C++ codegen emits
->set_fill_rule(FillRule::evenodd) (path case only — SvgRect/SvgLine have
no fill rule, and emit_svg_paint is shared, so the emission lives at the
svg_path call site); native materializer's apply_svg_paint(SvgPathWidget&)
reads svg_fill_rule + raw fill-rule/fillRule.
- Diagnostic:
vector-fill-rule-approximated(registered 'warning' —
'info' is dropped by both consumers) fires for mixed rules on one node and
for a MULTI-subpath vector with no declared rule (nonzero fallback may fill
its holes solid). Single-contour shapes stay silent — both rules fill them
identically.
- Raster-testing gotcha: the Skia screenshot backend composites onto an
OPAQUE background and renders at its own pixel ratio (2x on Retina), so a
"hole is transparent" assertion always reads opaque, and design-space pixel
coords are wrong by the scale factor. Prove holes by DIFFERENCE between the
two rules' renders of the same path (see the donut test in
test_widget_bridge_svg.cpp).
Decoder-tail gaps: gradient-on-outline, null boolean-ops, per-corner radii
Three small .fig-decoder gaps that each look downstream but are all in
scene.mjs. The renderer/bridge/codegen already supported every one of
them — only the decoder wasn't populating the channel. Facts to keep:
- **A gradient-filled TEXT lowered to a glyph outline must set
fillGradient, not just flatten.** TEXT never takes the box branch (a text
fill is the glyph color, not a background), so when a label outlines
(missing/icon font) its linear gradient used to collapse to the first solid
— the sequencer's rainbow "GENERATE PATTERN" pill imported flat gray. The
glyph-outline branch now mirrors the VECTOR branch: firstGradient(node.fillPaints)
→ gradientPaintToCss → out.fillGradient, with the flattened solid kept
as out.fill (the widget's parse-failure fallback). Only LINEAR lowers;
a radial returns null and the generic gradient-approximated diagnostic
below still fires. Same wire as the fill-gradient path:
design_ir_json reads fillGradient→svg_fill_gradient (path-gated) →
codegen setSvgFillGradient.
- **A
BOOLEAN_OPERATIONwith null geometry AND no size paints nothing —
skip it, don't emit a 0×0 slab.** The sequencer's two Union nodes
(1:162/1:163) carry a 0-byte geometry blob and size:{x:null,y:null};
the box fallback emitted them as 0-sized frames still carrying their
#ffffff26 fill, which layout_parity flagged as EXTRA. The guard in
walk() fires ONLY when geometryToPath resolves nothing AND width/height
are both non-positive, so a boolean op whose geometry does resolve (or
that has real extent) keeps its paths. Diagnostic boolean-empty-skipped
(registered 'warning', like slice-skipped — the skip is correct
rendering, but 'info' is dropped by both consumers).
- Omitted corner radii are SQUARE (0), not "inherit the others." kiwi
drops zero fields, so a bottom-rounded panel arrives as
{bottomLeft:2, bottomRight:2} with the top corners absent. cornerRadius()
used to .filter() the absent corners out, which made the two present
corners look uniform and rounded ALL FOUR. It now NORMALIZES the four raw
fields (absent → 0) BEFORE collapsing, so it returns a single value only
when all four truly agree; otherwise perCornerRadii() carries the
asymmetric case to border_{top,bottom}_{left,right}_radius, which codegen
already lowers to setCornerRadius(id, "TopLeft", r). MixerPanelFL keeps
[0,0,2,2]; Rectangle 1047 keeps [3,0,0,3].
Figma resize constraints → flex/position
Figma layout constraints (a node's resize behavior relative to its parent)
parse into IRLayout.h_constraint / v_constraint (normalized tokens
left|right|center|scale|stretch and top|bottom|center|scale|stretch) and
lower to flex at codegen. Facts / gotchas:
- Parse (
design_ir_json.cpp,parse_ir_node): reads `constraints:
{horizontal, vertical} at node level, also under a figma{}` block, also
inside layout{} — first non-empty wins. Figma's `MIN/MAX/CENTER/STRETCH/
SCALE normalize to the token set (normalize_h_constraint` /
normalize_v_constraint); unrecognized → unset. Source-agnostic.
- Codegen map (
design_codegen.cpp,emit_layout_constraints, folded into
emit_position_if_absolute so it fires at every create site, depth>0 only):
center → margin_left/right (or top/bottom) 'auto'; right/bottom →
leading margin_*: 'auto' (push to trailing edge); scale → flex_grow:1;
stretch (pin both edges) → align_self:'stretch'; left/top → flex
default (emit nothing). The bridge setFlex accepts 'auto' only for
margin_* (not padding).
- Best-effort, hence
codegen: partial: axis-exactscale/stretch
depends on the parent's main axis, which the child doesn't carry. Stays inside
Flexbox primitives — do NOT add block/table/float to make it axis-perfect
(CLAUDE.md "Layout Model — Flex + Grid only").
- Native arm only so far; web-compat (
generate_node) constraint emission is a
follow-up. compat.json features.constraints tracks this (parsed handled,
codegen partial); features rows are documented-only (not probed by the
[object-coverage] drift guard). Tests: [view][import][constraints].
- Producers (all three Figma lanes emit the shared node-level shape,
passing their OWN raw spelling through untranslated — the parser owns
normalization, so never add a translation table in a producer):
.fig(fig/scene.mjs): raw kiwihorizontalConstraint/
verticalConstraint (MIN/MAX/CENTER/STRETCH/SCALE), possibly one axis
only.
- plugin (
figma-plugin/src/extract-pure.ts::extractConstraints→
serialize.ts): Plugin-API node.constraints (same spelling); guarded
with a property check — GROUP/SLICE have no constraints member. The
export schema enum rejects REST spellings by design (drift guard).
- REST (
figma_rest_export.py::walk): RESTconstraints
(LEFT/RIGHT/CENTER/LEFT_RIGHT/SCALE, TOP/BOTTOM/CENTER/TOP_BOTTOM/SCALE).
- Auto-layout gate: all three producers emit constraints only for a node
positioned in its parent's coordinate space — the same gate as absolute
positioning (parent not auto-layout, OR the child opted out via
stackPositioning/layoutPositioning ABSOLUTE). A FLOWING auto-layout
child is sized by the stack; its stale constraints would fight the flex pass
with margins/grow the design never asked for. Constraints are a no-op at
design size (verified pixel-identical on a 1299-node real file) — they only
change resize behavior.
Auto Layout completion (child grow/align, wrap extras, GRID, aspect, min/max)
The audit's "Auto Layout" row (checklist #3). All three producers now emit the
complete auto-layout contract; the layout keys use the CONSUMER's camelCase
spelling (flexGrow, alignSelf, alignContent, rowGap, columnGap,
aspectRatio, gridTemplateColumns/Rows, gridColumn/Row — the exact members
parse_ir_layout reads), values in CSS spellings (flex-start,
space-between) because the flex bridge and parse_flex_align accept kebab,
NOT snake. Never emit a key the consumer doesn't read — that dead-key trap is
this subsystem's signature bug (see the width_mode comment in
design_ir_json.cpp).
- Child grow/align — gated exactly like constraints, but inverted: emitted
only for a FLOWING child of a FLEX auto-layout parent (Figma leaves the
fields stale everywhere else, and an ABSOLUTE-positioned child's grow/align
would fight its coordinate placement). Source spellings: .fig kiwi
stackChildPrimaryGrow/stackChildAlignSelf, plugin+REST
layoutGrow/layoutAlign (INHERIT emits nothing — omitting align-self IS
inherit). An ABSOLUTE stack child now also gets position:absolute +
left/top in the plugin/REST lanes (it previously got neither flex nor
coordinates and collapsed onto the stack origin).
- Wrap extras —
counterAxisSpacing(kiwistackCounterSpacing) is the
gap BETWEEN wrapped tracks: a row's tracks stack vertically → rowGap, a
column's → columnGap. counterAxisAlignContent (stackCounterAlignContent)
SPACE_BETWEEN → alignContent: "space-between"; AUTO emits nothing.
Both are wrap-only — never emit them on a single-line stack.
- Figma GRID auto-layout (
layoutMode/stackMode == "GRID"; pinned
plugin typings 1.127.0 expose the full surface, no runtime cast needed) —
lowers to the existing IR grid contract. Plugin/REST: uniform tracks →
repeat(N, 1fr) from gridRowCount/gridColumnCount, gaps from
gridRowGap/gridColumnGap, children from 0-based
gridRowAnchorIndex/gridColumnAnchorIndex (+grid*Span) → CSS 1-based
lines. .fig kiwi: gridRows/gridColumns are GUID-keyed track lists whose
fractional-index position string sorts byte-wise into track order;
gridColumnsSizing/gridRowsSizing map track GUID → {minSizing,maxSizing}
(FLEX→fr, FIXED→px, else auto); children carry
gridRowAnchor/gridColumnAnchor GUIDs. Grid children FLOW: treat GRID
like flex in the absolute-position, constraints, and mask gates (a grid
child gets neither coordinates nor constraints). GRID mode ignores
stackSpacing — it is flex residue; the grid gaps own spacing.
- aspectRatio —
targetAspectRatio(kiwi OptionalVector{x,y}, REST
number-or-vector) emits ONLY when some axis is flexible (grow, stretch, or a
non-FIXED sizing mode). On a fully fixed node Yoga would re-derive the cross
axis from the ratio and fight Figma's solved size over rounding.
- min/max sizing — style-level
min_width/max_width/min_height/
max_height (snake; parse_ir_style resolves both spellings, native
materializer lowers to FlexStyle clamps, JS-web lane emits style.minWidth).
Per-axis guard > 0 — the .fig OptionalVector rides unset axes as 0 and a
zero max collapses the node. Figma honored these while solving, so they only
bind on host resize.
- Consumer completions that shipped with this slice: the JS codegen
(design_codegen.cpp) now lowers explicit flex_grow values, align_self,
aspect_ratio, row_gap/column_gap, flex_wrap, and align_content
(the constraint fallbacks check grow_done/stretch_done so an explicit
value is never doubled); the native materializer + cpp codegen read grid
templates from layout.grid_template_* when the v0/TSX contract attributes
are absent (previously a Figma GRID switched to grid mode with an EMPTY
column list and dropped every child), and both gained per-child
gridColumn/gridRow line parsing.
- Known 0.5px caveat: Pulp's grid engine stretches every child to its cell
(layout_grid() has no per-child alignment yet), while Figma keeps a
fixed-size child at its own size inside a larger track. On the reference
file this shows as grid cells 33→33.5px tall (track height) with y-placement
EXACT (the old absolute path was 0.5 off from rounding). Within the parity
gate; fix belongs to the grid engine, not the producers.
- Real-file parity:
layout_parity.pyreports byte-identical findings before/
after on the 1299-node reference frame; the only solved-rect deltas are the
16 grid cells above (≤0.5px). Tests: [view][import][autolayout],
fig.test.mjs auto-layout completion block, figma-plugin/test/layout.test.ts,
REST AutoLayoutTest.
Strokes beyond the first uniform solid (per-side, dashed, provenance, multi-paint)
The audit's "Strokes" row (checklist #8). All three producers now lower the
full box-stroke model; the earlier shorthand/stroke-band/per-corner fixes are
untouched (the vectorStrokeBand gate in fig/scene.mjs still suppresses the
CSS border on baked stroke-band vectors — do not regress it).
- Per-side box strokes (Figma
individualStrokeWeights): emitted as the
discrete border_{top,right,bottom,left}_width fields — ALL FOUR, because
an explicit 0 is a positive "no edge here" — plus the single Figma stroke
color repeated as border_{side}_color on each painted side; the uniform
border/border_width shorthand is omitted in that case. Producer
spellings (verified against each wire, never guess):
.figkiwi:borderStrokeWeightsIndependent(bool) +
border{Top,Right,Bottom,Left}Weight (absent side = 0). The fields are in
SYMBOL_INHERITED_KEYS so instances inherit them from masters.
- plugin:
strokeTopWeight/strokeRightWeight/strokeBottomWeight/
strokeLeftWeight (IndividualStrokesMixin; strokeWeight reads
figma.mixed exactly when they differ — four EQUAL side weights stay on
the uniform path). Logic in extract-pure.ts::extractStrokeStyle (pure,
testable); extract.ts merges style + attributes + diagnostics.
- REST: the
individualStrokeWeightsobject{top, right, bottom, left}
(figma_rest_export.py::extract_stroke_style).
Consumers: parse_ir_style reads all eight fields (both spellings), Yoga
takes per-edge insets, the native materializer applies per-side View
setters, and the JS codegen lowers painted sides to setBorderSide (0-width
sides emit nothing; the uniform setBorder never fires beside them) —
design_codegen.cpp::emit_js_box_border, shared by the container and
generic-frame fall-through branches.
- Dash pattern: a non-empty
dashPattern(.fig kiwi + plugin) /
strokeDashes (REST) maps to border_style: "dashed" — a box border
cannot express an arbitrary dash array, so this is the honest CSS
approximation (View's dashed stroke is a fixed 3w/3w SkDashPathEffect) and
the EXACT array is preserved as the figma:dash_pattern attribute.
Codegen emits setBorderStyle(id, 'dashed') beside the border (solid stays
silent); the native materializer maps border_style onto
View::BorderStyle (dashed/dotted/none/hidden — others degrade to solid).
- Preserved stroke provenance (namespaced
figma:*attributes, emitted
only on nodes with a visible stroke and only for NON-DEFAULT values):
figma:stroke_align (CENTER/OUTSIDE only — INSIDE is how a CSS box border
already paints), figma:stroke_cap (≠ NONE), figma:stroke_join (≠ MITER),
figma:stroke_miter_limit (≠ 4; REST's strokeMiterAngle in degrees is
normalized to the limit: 1/sin(angle/2), 28.96° = 4.0). No renderer
consumes these yet — Figma's own SVG/strokeGeometry export bakes caps/joins/
dashes into geometry, so they are provenance for a future path renderer and
for fidelity tooling. Do NOT emit them as lowered styles.
- Multi-paint / complex strokes are never silent: >1 visible stroke paint
→ multi-paint-stroke diagnostic (flattened to the FIRST SOLID); a
non-solid top paint, no solid paint at all (border dropped), or a .fig
variable-width brush stroke (dynamicStrokeSettings/scatterStrokeSettings/
stretchStrokeSettings) → complex-stroke-flattened. Both codes are
registered in DIAGNOSTIC_SEVERITY (fig lane), emitted with kind
capture_partial (plugin/REST), and mapped in the C++
diagnostic_kind_from_code fallback. Note the behavior CHANGE from the old
first-visible-solid gate: a gradient stroke sitting ON TOP of a solid now
flattens to that solid (with a diagnostic) instead of silently dropping the
border.
- Real-file sanity (designers-pick frame 1:486, 1299 nodes): 0 per-side /
0 dashed nodes (the file's one dashPattern frame sits outside 1:486),
36 figma:stroke_align + 1 cap + 1 join attrs, 20 complex-stroke-flattened
on gradient-stroked ovals the old code dropped silently; envelope otherwise
byte-identical, --dump-layout byte-identical (strokes in this frame are
paint-only — per-side widths WOULD move Yoga insets on files that use them).
Tests: [view][import]...[strokes], fig.test.mjs strokes block,
figma-plugin/test/strokes.test.ts (+ serialize schema round-trip), REST
StrokesTest.
Primitive geometry metadata (arc/donut, star/polygon, smoothing, boolean op)
Audit "Geometry" row. All three producers preserve the primitive-shape fields a
future path renderer needs to rebuild the shape without a re-export from Figma,
as namespaced figma:* attributes on the node (the same
provenance-not-lowered contract as the stroke attrs — nothing consumes them
yet; the PNG/faithful-SVG capture preserves the pixels, these preserve the
semantics; tracked in compat/imports.json):
| Attribute | Source field (plugin / REST / .fig kiwi) | Emitted when |
|---|---|---|
| figma:arc_data = "start,end,inner" | ELLIPSE.arcData (radians, same spelling all lanes) | sweep is not a plain full circle, or innerRadius > 0 (donut). .fig stamps a DEFAULT full-circle arcData on every ellipse — emitting unconditionally would grow an attr per node |
| figma:star_point_count | STAR.pointCount / — / count | always on STAR (required to rebuild it) |
| figma:star_inner_radius | STAR.innerRadius (0..1) / — / starInnerScale | always on STAR |
| figma:polygon_point_count | POLYGON.pointCount / — / REGULAR_POLYGON.count | always on POLYGON |
| figma:corner_smoothing | cornerSmoothing (0..1 squircle factor) | > 0 only (per-corner radii already ride in style) |
| figma:boolean_operation | booleanOperation, lowercased | always on BOOLEAN_OPERATION. Kiwi's XOR is the Plugin API's EXCLUDE — normalize it (fig/scene.mjs primitiveProvenanceAttrs) so all lanes share one vocabulary |
- REST cannot see star/polygon fields. The REST wire schema exposes
arcData, cornerSmoothing, and booleanOperation, but NOT
pointCount/innerRadius (verified against the REST file-node-types /
file-property-types docs) — so the star/polygon attrs are plugin/.fig-lane
only. Do not fabricate them in figma_rest_export.py.
- Numbers are formatted to at most 4 decimals with trailing zeros trimmed
(fmtGeomNum / _fmt_geom_num) so kiwi float32 vs Plugin-API double never
produce different attr strings; the full-circle test uses a 1e-4 epsilon
because kiwi's float32 2π ≠ Math.PI * 2.
- Capture policy stays PNG for vector-like leaves.
ImageView's decoder
is PNG/JPEG; SVG rendering exists only at frame level via the faithful-vector
lane (render_mode: faithful_svg → DesignFrameView), which is already
default-on. Switching leaf asset_ref capture to SVG would hand ImageView
bytes it cannot decode — leaf-level SVG is deferred until an SVG-capable
image path exists.
- Real-file sanity (designers-pick frame 1:486, 1299 nodes): 140
figma:boolean_operation (instance expansion multiplies the 41 raw scene
nodes), 1 figma:polygon_point_count, 0 arc/star/smoothing (every ellipse
in the frame is a plain full circle); envelope otherwise byte-identical and
--dump-layout byte-identical — the attrs are metadata-only and can never
move layout.
Tests: [view][import][figma-plugin][geometry] (C++ attr round-trip),
fig.test.mjs "primitive geometry" test,
figma-plugin/test/primitive-geometry.test.ts, REST
test_primitive_geometry_*.
Dev metadata + export settings (description, dev status, annotations, export presets)
Audit "Dev metadata" (Medium) + "Export settings" (Low) rows — the last
coverage slice, and PROVENANCE-ONLY BY DESIGN: these attrs are for dev
tooling, diagnostics, and round-trip provenance. NO renderer, codegen path, or
importer heuristic reads them, and export settings NEVER override Pulp's
deterministic PNG/SVG capture policy (they are asset hints, not a capture
contract). Emitters: plugin extract-pure.ts::extractDevMetadataAttrs, REST
figma_rest_export.py::extract_dev_metadata_attributes, .fig
scene.mjs::devMetadataAttrs; all ride the free-form attributes passthrough
(design_ir_json.cpp ~1232 — no allowlist, every attributes.* key lands
verbatim in IRNode::attributes). Tracked in compat/imports.json
(dev-metadata + export-settings rows).
| Attribute | Source field (plugin / REST / .fig kiwi) | Emitted when |
|---|---|---|
| figma:description | PublishableMixin.description (COMPONENT / COMPONENT_SET) / the /nodes response components+componentSets maps keyed by node id (NOT on the document node) / kiwi description, falling back to symbolDescription | trimmed value is non-empty |
| figma:dev_status | devStatus.type lowercased (ready_for_dev / completed) / same / absent — the kiwi schema has no per-node devStatus (sectionStatus is the unrelated section build-status; do not map it) | devStatus is set (it is null by default) |
| figma:annotations | annotations → compact JSON [{label, properties, category_id}]; label falls back to labelMarkdown (.fig: labelV2) | array non-empty AND at least one entry has something to state |
| figma:export_settings | exportSettings → compact JSON [{format, suffix, constraint, contents_only}] | array non-empty (an export preset existing at all is author intent; within an entry, defaults stay silent) |
- Value normalization is cross-lane, like
XOR → exclude: kiwi
imageType: JPEG → the Plugin API's jpg; kiwi constraint types
CONTENT_SCALE/CONTENT_WIDTH/CONTENT_HEIGHT → scale:N/width:N/height:N
(the SCALE:1 default stays silent, value via fmtGeomNum); kiwi
SCREAMING_SNAKE annotation property types → Plugin-API camelCase
(FILL → fills, STACK_SPACING → itemSpacing, `STROKE_WIDTH →
strokeWeight, STACK_MODE → layoutMode, COMPONENT → mainComponent`, …
— table + mechanical snake→camel in scene.mjs::annotationPropertyName).
- Lane asymmetries (verified, don't "fix"): REST does not expose
contentsOnly, so contents_only never appears in the REST lane. The kiwi
Annotation.categoryId is a file-local GUID ref (not the Plugin API's
stable category-id string), so the .fig lane never emits category_id.
contents_only is emitted only when explicitly false (Figma's default is
true).
- Deliberately NOT preserved: plugin data / shared plugin data (arbitrary
third-party payloads are envelope noise) and reactions/prototype metadata
(out of the importer's scope).
- Real-file sanity (designers-pick frame 1:486, 1299 nodes): 16
figma:export_settings (all the default preset every real .fig stamps,
honestly reduced to [{"format":"png"}]), 0 descriptions / annotations /
dev-status in that file (whole-file probe: 92 export-settings nodes, 0 of
the rest); --dump-layout byte-identical before/after — the attrs are
metadata-only and can never move layout or codegen output.
Tests: [view][import][figma-plugin][dev-metadata] (C++ attr round-trip),
fig.test.mjs "dev metadata + export settings" test,
figma-plugin/test/dev-metadata.test.ts, REST test_dev_metadata_* +
test_component_description_*.
Figma variables → tokens + per-property bindings
Two halves, both preserved end to end (audit item 5):
- Token definitions — the envelope-level
tokensblock
({colors, dimensions, strings}) → parse_ir_tokens → IRTokens. The
Figma-plugin v1 adapter additionally normalizes the forward-compatible
top-level token_source_identity extension into the same token table. The
plugin records each emitted token's original Figma variable id, collection,
mode, and figma-plugin adapter under the existing
category-qualified IRTokens::source_identity key
(colors.<canonical-name>, etc.). Keep the node binding's value as the bare
canonical name: category is known from the token map, while source identity
is independently queryable and survives W3C token export.
Canonical names are "collection/variable" lowercased, whitespace stripped,
/ → .; a multi-mode collection emits the default mode under the bare
name and every other mode suffixed .<mode-slug> (e.g. theme.bg +
theme.bg.dark); aliases resolve per mode; BOOLEAN → "true"/"false"
strings. The plugin's tokens.ts and REST's variables_to_tokens() share
these rules; the .fig lane keys tokens by the VARIABLE node's raw name.
- Per-property bindings — which token drives which node property. Every
producer emits figma.bound_variables: {property: tokenName} in the node's
figma block; parse_ir_node preserves each entry as a
figmaBoundVariable.<property> attribute (opaque passthrough, namespaced,
additive — the reader preserves, it does not interpret). Property keys use
the Plugin-API camelCase dialect in ALL three lanes (fills, strokes,
cornerRadius, itemSpacing, …); array-valued properties bind index 0 to
the bare key and later entries to <property>.<i>; nested alias maps bind
<property>.<key>.
Producers:
- plugin (
extract.tsreadsnode.boundVariables,
extract-pure.ts::extractBoundVariableBindings resolves via the token
pass's variableIdToName): an id the token pass didn't capture
(remote-library / deleted variable) is DROPPED with a
variable-binding-unresolved warning (once per variable) — the plugin has
the full local table, so an unresolvable id is genuinely dangling.
- REST (
figma_rest_export.py):boundVariablesrides in the /nodes
payload on every plan tier, but the /v1/files/:key/variables/local
endpoint (token definitions + names) is Enterprise-plan-gated — expect
HTTP 403 on most files (variables-endpoint-unavailable info diagnostic,
empty token maps). Without the name map, bindings emit the RAW variable id
(VariableID:…) plus one variable-binding-unresolved warning per id —
a stable join key, never a fabricated name. Successful fetches are cached
(<file_key>__variables.json, file-scoped).
.fig(fig/scene.mjs): scalar bindings come from the kiwi
node.variableConsumptionMap.entries[] (variableField enum →
Plugin-API camelCase via FIG_VARIABLE_FIELD_PROPERTY + mechanical
SNAKE→camel fallback; old-schema entries carrying only the numeric
nodeField are skipped), paint-level color bindings from
paint.colorVar on fillPaints/strokePaints (first visible bound paint
per side → fills/strokes). Guids resolve against the file's own
VARIABLE nodes — the same names collectVariableTokens keys the tokens
maps by; a guid outside that table (remote-library variable) is dropped
with a variable-binding-unresolved warning, once per variable.
Consumption status (compat features.variables-tokens, codegen partial):
token definitions feed the importer's existing token/theming plumbing;
bindings are preserved as queryable figmaBoundVariable.* attributes for
downstream theming/token-swap tooling, but codegen does NOT yet emit themeable
token references into the generated UI — swapping a token value does not
re-theme an already-generated import. Tests: [view][import][variables]
(C++), bound-variables.test.ts (plugin), test_figma_rest_export.py
variable tests (REST), the variable bindings case in fig.test.mjs (.fig).
Grid containers → native grid bridge (NOT Yoga grid)
Pulp's engine has its own grid layout (LayoutMode::grid + layout_grid()
in view.cpp, driven by the createGrid/setGrid bridge + GridStyle) — the
vendored Yoga (v3.2.1) has no grid API (no YGDisplayGrid; grid only exists
on Yoga's unreleased main). So "wire grid" for design-import is not a Yoga
task — it's emitting createGrid/setGrid instead of createCol/createRow.
Facts / gotchas:
- Parse (
design_ir_json.cpp,parse_ir_layout):display:grid,
gridTemplateColumns/Rows, gridAutoFlow, and per-item gridColumn/Row
(camelCase + snake_case) → IRLayout.grid_template_columns/_rows/
_auto_flow/grid_column/grid_row (raw CSS strings).
- Codegen (
design_codegen.cpp): `is_grid = is_container && (display=="grid"
|| a track template present). Emits createGrid + setGrid(id,
'template_columns'|'template_rows'|'auto_flow', …) + setGrid(id,'gap',…)`
(NOT setFlex gap), and suppresses flex justify_content/align_items
(guarded with !is_grid — they're meaningless for grid; do NOT wrap the child
recursion loop, it's interwoven with the flex nudge heuristics and must run for
grid too). Per-item placement (emit_grid_item_placement, folded into
emit_position_if_absolute): grid_column/grid_row "N / M" → `setGrid(id,
'column_start'/'column_end'/'row_start'/'row_end', N)`.
- Span:
"<start> / span <n>"resolves tocolumn/row_end = start + n.
Still deferred (auto-placed): span-WITHOUT-a-start-line, named lines, and
minmax() track sizing — setGrid column/row_start/end take ints only.
Stays within Flex+Grid (CLAUDE.md layout-model contract).
- Native arm only;
compat.json features.grid-containertracks it (parsed
handled, codegen partial). Tests: [view][import][grid].
Ordered paint stacks, paint opacity, image scale modes (audit item 7)
Figma renders fills bottom→top (array index 0 at the BOTTOM). The IR has
exactly three background slots — one solid color, one gradient, one image —
painted in that order, so a stack is representable exactly when it reads
[solid…, gradient?, image?] bottom→top. All three producers (plugin
extract-pure.ts::lowerFillPaints, REST `figma_rest_export.py::
lower_fill_paints, .fig scene.mjs` styleFor box branch) share this slot
scan, kept in field-for-field lockstep:
- Leading solids composite source-over (exact under NORMAL blend) into
background_color — a [#4b4d51, white@0.55] thumb is #aeafb1, not the
dark base. A fully opaque solid trims the stack below it (also exact).
- Paint-level opacity (distinct from layer opacity) folds into the emitted
color alpha: solids via paintToColor/paint_to_color/compositeSolids,
gradients by scaling every stop's alpha. An IMAGE paint's opacity folds into
the layer opacity only on a childless node (identical compositing);
with children it raises image-opacity-dropped instead of fading them.
- Image scale modes: on image-shaped nodes (plugin/.fig lanes, where an
image fill becomes an image node) scaleMode/imageScaleMode lowers to
object_fit — FILL→cover, FIT→contain — which ImageView::paint
actually honors (real rendered fix: a FILL photo no longer imports
stretched). CROP (spelled STRETCH in .fig blobs) approximates as
cover + image-scale-approximated; TILE has no painter → stretch default
- the same diagnostic. On frame-shaped nodes (REST lane keeps
background_image) it lowers to background_size/background_repeat
(View storage slots via setBackgroundSize/setBackgroundRepeat; raster
background paint honoring is still the deferred style_extras slot).
- No silent drops: paints beyond the slots raise
multi-paint-flattened;
VIDEO/PATTERN/unknown families raise unsupported-paint-type (and never
shadow a lowerable solid below them); non-NORMAL paint blendMode raises
paint-blend-unsupported (paint still lowers, composited normal). New
.fig codes MUST be registered in DIAGNOSTIC_SEVERITY or both consumers
drop them as invisible info.
- IR:
IRStyle.object_fit/background_sizeare parsed (objectFit/
backgroundSize, camel or snake) + emitted by JS/C++ codegens + the native
importer; the plugin envelope schema carries object_fit/background_size
(regenerate types.generated.ts via npm run gen-types after schema
edits). Tests: [view][import][paints], `tools/figma-plugin/test/
paints.test.ts, test/test_figma_rest_export.py::PaintStackTest`, and the
.fig Paint Lab fixture frame (regenerate synthetic.fig via
make_synthetic_fig.mjs — a staleness gate compares decoded content).
Layer blend modes: the shared supported-blend table + group isolation
A layer that COMPOSITES differently is not cosmetic (the motivating file lays
a light noise texture over its panels at MULTIPLY; ignoring it painted every
panel ~25/255 too bright, silently). One supported-blend table now spans all
three producers AND the consumer, kept in lockstep:
- The table (15 CSS-equivalent Figma modes): DARKEN, MULTIPLY, COLOR_BURN,
LIGHTEN, SCREEN, COLOR_DODGE, OVERLAY, SOFT_LIGHT, HARD_LIGHT, DIFFERENCE,
EXCLUSION, HUE, SATURATION, COLOR, LUMINOSITY — lowered by spelling
transform (UPPER_SNAKE → lowercase-hyphen) into style.mix_blend_mode.
Lives in .fig scene.mjs::FIGMA_BLEND_CSS, plugin
extract-pure.ts::FIGMA_BLEND_CSS (+ lowerLayerBlendMode), REST
figma_rest_export.py::_FIGMA_BLEND_CSS (+ blend_mode_to_css), consumer
design_ir_json.cpp::is_supported_blend_keyword.
- Unmappable modes (LINEAR_BURN, LINEAR_DODGE, future families) lower to
NOTHING and raise blend-unsupported in every producer — never
approximate: LINEAR_BURN's natural CSS spelling plus-darker maps to the
ADDITIVE kPlus in Skia/Chromium, which would LIGHTEN a layer the designer
asked to darken. The raw Figma mode still rides in figma.blend_mode for
provenance; the consumer promotes it into style.mix_blend_mode only when
supported (unmappable raws stay out silently — the producer already
diagnosed them, so the consumer must not double-diagnose).
- Consumer chokepoint:
validate_blend_modes(called on every adapter
parse path) clears any style.mixBlendMode outside the table WITH a
blend-unsupported diagnostic — an unknown keyword is invalid CSS on the
web path and a SILENT normal-fallback in setMixBlendMode on the native
path, so it must never reach codegen. plus-lighter/plus-darker stay
accepted for CSS-authored sources (the bridge maps both to kPlus).
- Group compositing: container
PASS_THROUGH(Figma's default) IS the
default web/native behavior — dropped silently and correctly. An EXPLICIT
NORMAL on a container is Figma's "isolate" (CSS isolation: isolate);
the flat lowering has no isolation layer, so when the subtree actually
blends, every lane raises group-isolation-approximated (gated on a
blending descendant — inert isolation is a no-op). A container with its own
non-default blend needs nothing: CSS mix-blend-mode itself forms an
isolated group, matching Figma. Faithful SVG capture remains the honest
path for exact isolate-group compositing.
- Layer vs paint channels stay separate: layer opacity → `IRStyle.
opacity, layer blend → mix_blend_mode`; paint opacity folds into paint
color alpha and paint blend raises paint-blend-unsupported (see the
paint-stack section above). No field double-applies.
- Plugin envelope schema carries
style.mix_blend_mode(regenerate
types.generated.ts after schema edits). Tests: [blend] in
test_design_import_ir.cpp + test_design_import_fidelity.cpp,
tools/figma-plugin/test/blend.test.ts,
test_figma_rest_export.py::LayerBlendTest, and the .fig blend +
isolate-group tests in fig.test.mjs.
Radial / conic background gradients
Linear gradients were end-to-end; radial/conic used to round-trip the CSS string
but the renderer flattened them to the first stop color. The canvas + Skia +
CoreGraphics backends ALREADY implement radial/two-circle/conic — the gaps were
only the CSS parser, the View paint dispatch, and the Figma exporter:
- Bridge parser (
widget_bridge.cpp,setBackgroundGradient): now parses
radial-gradient([circle][at X% Y%], stops…) and `conic-gradient([from
<angle>][at X% Y%], stops…) in addition to linear (shared parse_stops`
lambda). Center defaults to 50% 50%; conic from is offset by −90° because
CSS measures from the top while the canvas sweep starts at +x.
- View (
view.hpp/view.cpp):set_background_gradient_radial/_conic
store kind (bg_gradient_type_ 2/3) + center/radius/angle; View::paint
dispatches to canvas.set_fill_gradient_radial/_conic. radius_frac
defaults to ~farthest-corner (0.7071 × max(w,h)). CSS radial extent keywords
(closest-side/closest-corner/farthest-side/farthest-corner) map to an
approximate radius_frac in the bridge parser — exact per-keyword geometry
(needs w/h+center) and explicit px radii stay deferred (codegen partial).
- Figma export (
figma_rest_export.py):GRADIENT_RADIAL/GRADIENT_DIAMOND
→ radial-gradient(...), GRADIENT_ANGULAR → conic-gradient(...) (diamond
approximated by radial). Falls back to flat only when there are no stops.
- Design-import codegen is unchanged — it already emits the gradient string
verbatim to setBackgroundGradient; radial/conic now render instead of
flattening.
- Tests:
[view][widget-bridge][gradient](parser→kind), `[view][gradient]
[render]` (radial/conic differ from a flat fill — proves not the fallback),
[view][import][codegen][gradient], and the figma exporter python tests.
compat.json features.radial-angular-diamond-gradient: parsed handled,
codegen partial.
Background gradients: the JS lane and the native/baked-C++ lane are SEPARATE
The section above is the JS / scripted-UI lane (setBackgroundGradient,
emitted by generate_pulp_js). There is a second, independent lane — the
native materializer + baked C++ codegen — and until 2026-06 it dropped
background_gradient entirely (linear included), even though IRStyle
carried it and View could paint it. Fixing one lane does NOT fix the other;
they share no code unless you make them.
- Shared parser (
core/view/src/css_gradient.cpp,
apply_css_background_gradient): the CSS linear/radial/conic parser was
lifted out of widget_bridge.cpp into this free function. All three lanes now
route through it — the JS bridge (setBackgroundGradient delegates), the
native materializer, and baked C++ codegen — so gradients resolve identically.
- Native materializer (
design_import_native_common.cpp,
apply_visual_style): now calls apply_css_background_gradient(view, …) right
after set_background_color. The gradient paints over the solid base color.
- Baked C++ codegen (
design_cpp_codegen.cpp,emit_visual_style): emits a
verbatim pulp::view::apply_css_background_gradient(*var, "linear-gradient(…)")
runtime call plus #include <pulp/view/css_gradient.hpp> in the generated
source prologue.
- Why it mattered: this was the dominant ELYSIUM dark/light parity gap. The
light "hero" panel (Rectangle 5, a `linear-gradient(to bottom,#e4edf6,
#b7c8db)`) and the cube/prism/tuning illustration fills are all CSS gradients.
With them dropped, the panel rendered dark #1c1d1d and the position_cylinder
GPU-ROI similarity was 0.055; after wiring it jumped to 0.979 (range_prism
0.029→0.78, grains_knob_cap 0.15→0.79). Verify with
pulp-test-mac-platform-harness (PULP_DESIGN_GPU_DUMP_DIR=… dumps ROIs).
- Gotcha — stale CLI binary: after touching
emit_visual_style, rebuild
pulp-import-design before re-emitting --emit cpp; the tool links
pulp-view-core statically and a stale binary silently emits the old output
(no gradient call), which reads as a codegen bug that isn't there.
- Tests:
[view][import][native-materializer][gradient](materializer applies
it), [gradient] cpp-emit section in the always-built pulp-test-import-design-tool
(so the codegen path is covered even when the planning-gated cpp-codegen target
is skipped), plus the gated pulp-test-design-import-cpp-codegen.
Gradient colour-interpolation (`in oklab`) and the default Chrome hides
css_gradient.cpp honours in <space> [<hue> hue] anywhere in a gradient's
prefix (Chrome's computed style writes to right in oklab, circle in hsl and
from 90deg in oklch). Two things are easy to get wrong:
- The clause is not always there to read. CSS Color 4 makes Oklab the
default as soon as one stop is a non-legacy colour, and Chrome's computed style
DROPS in oklab from such a gradient because it is the default. Captured
designs are full of oklab(...) stops (Chrome serializes every modern colour
and every color-mix() that way), so a parser that only reads the clause
paints them in sRGB with nothing in the CSS to say why. default_interpolation
keys on the stop text for this reason.
- The oracle's green backdrop cannot see a refusal on its own. `in oklch
longer hue` from red to blue is green at its midpoint, which the geometry
scan's unpainted() reads as backdrop. chrome_gradient_oracle.py --colors
paints each case over two backdrops and reports a refusal only when the
renders differ; reuse that trick for any colour oracle.
Per-range text styles → nested `<span>`s
A text node used to take the FIRST-CHAR dominant style only (one run); mixed
text (a bold word, a colored span, a different size mid-string) lost its
per-range styling. Now:
- IR:
IRNode.text_runs— an ordered list of `IRTextRun{start,end +
optional font_size/font_weight/font_family/font_style/color/letter_spacing/
text_decoration}. [start,end) are offsets into text_content`. The dominant
style stays the node default; runs override.
- Parse (
design_ir_json.cpp): reads aruns/textRunsarray (start/end +
the per-run fields, plus italic:true → font_style:"italic"). Source-
agnostic.
- Figma export (
figma_rest_export.py,extract_text_runs): groups
consecutive characterStyleOverrides ids into ranges and resolves each
through styleOverrideTable (fontWeight, fontName.style→italic,
letterSpacing.value, textDecoration, fills→color). Emitted as the node's
runs.
- Codegen — web (primary):
emit_web_text_runsemits the covered ranges as
styled <span style=…> children and the gaps as plain createTextNode (so
gaps inherit the dominant style). Single-run text keeps the plain
.textContent path (no regression).
- Codegen — native: the JS-native arm emits
setTextRuns(id, [...]); the
bridge builds a canvas::AttributedString over the Label's dominant style.
The direct native materializer constructs the same runs without JS. The
common shaped-fragment painter preserves family/size/weight/italic-or-
oblique/tracking/color/decoration across captured lines and responsive
multiline reflow, including transforms, clamp, and ellipsis. Captured line
boxes are reused only when the dominant and every run face can be validated;
otherwise the label reflows. compat.json features.text-per-range-styles
stays codegen partial only because baked C++ still flattens. Offsets are
UTF-8 byte offsets, the same as the web arm.
- Offsets are UTF-8 BYTE offsets into
text_content. The Figma exporter
builds a UTF-16-code-unit → UTF-8-byte map (characterStyleOverrides is
UTF-16-indexed: a BMP char is 1 unit, an astral char / emoji is a surrogate
pair = 2 units) so a run after an emoji lands on the right byte — a plain
code-point slice was off by a byte-position per astral char. emit_web_text_runs
slices by byte and snaps boundaries forward to the next codepoint start
(continuation bytes are 10xxxxxx) so a stray mid-codepoint offset never emits
invalid UTF-8. Tests: [view][import][text] (incl. a multibyte case) + the
figma exporter python tests (incl. an emoji/surrogate-pair case).
Multi-frame components & swap-link toggles (mode frames)
A component with more than one state frame (e.g. a keyboard's typing vs piano
mode, switched by an in-design toggle) maps to DesignFrameView's multi-frame
support, NOT a crop or a parallel view:
- Export each state sub-frame standalone (`figma_rest_export.py --node
<sub-frame-id>`). When the design stacks the states in one spec frame to show
them at once, the sub-frames are the individual states — import each as its
own faithful SVG. MusicalTypingKeyboard (nodes 187:15 typing / 187:349
piano) is the reference: DesignFrameView(svg0, …) + add_frame(svg1, …).
set_active_frame(i)swaps the rendered SVG AND the intrinsic size (the host
re-lays-out), releasing any held momentary key first.
- The in-design toggle button is a
DesignFrameElement::Kind::swapelement with
target_frame set — a click calls set_active_frame. This is the importer's
swap link (see planning/2026-06-17-figma-interaction-linking-vocabulary.md
for the swap / resize / modal / popover / navigate verb set).
- Hit-rects are per-frame, in the sub-frame's own coords. Pull them from the
Figma node's absoluteBoundingBox minus the frame origin; the standalone SVG
export adds a uniform shadow margin (6px for these frames). Do NOT transcribe
combined-frame coordinates — the standalone export re-origins everything.
Design-import IR round-trip + review-hardening gotchas
Lessons from the di-1..di-5 closeout review — keep these invariants:
- Serialize every new IR field.
serialize_design_ir→
write_ir_layout_json / write_ir_node_json must emit any field
parse_ir_layout / parse_ir_node reads, or a frozen .pulp / `--emit
ir-json round-trip silently drops it. Constraints (constraints:{horizontal,
vertical}), grid (gridTemplate*/gridAutoFlow/gridColumn/gridRow`), and
text runs are all written now; mirror this for future IR additions and add a
[serialization] round-trip test.
- A document-loaded asset stays inside its document. With an
asset_base_directory, resolve_asset_file honours a manifest local_path
or file:// original_uri only when the path stays inside that directory
— judged by text first (.. folded, backslashes as separators, absolute,
drive-letter and UNC roots refused, no lookup) and then by the resolved path
(symlinks). A declared SHA-256 alone does not admit an escaping path,
because the document controls that hash; the one outside root is Pulp's own
asset cache (design_import_asset_cache_directory()), where an absolute path
loads only if its resolved file is in the cache and matches the hash. A refusal logs `asset '…' refused — … resolves
outside the document directory` and reads as unresolved. It is decided
before any lookup on purpose: refusing only files that exist would tell a
crafted manifest which outside files are present. collect_design_ir_assets
records an external local file by absolute path, so a document that keeps
that path will not load the asset. Every pulp import-design lane that
writes a document (js, ir-json, cpp, browser import) runs
localize_ir_assets, which copies it to assets/<sha256><ext> first; a
library caller that serializes DesignIR itself must do the same.
import-design-external-asset-localized pins the CLI behaviour end to end.
- Pencil stroke lives in an attribute. Shape stroke can arrive as
attributes["stroke_color"] (+ stroke_width/stroke-width), NOT
style.border_color. synthesize_primitive_paths consumes both, else a
stroked Pencil rect/ellipse synthesizes to an invisible fill:none path.
- Grid needs a column track. The native grid engine drops all children when
its column list is empty, so a display:grid node with no
gridTemplateColumns gets a default '1fr' column at codegen (don't emit a
bare createGrid with no template).
- Web-compat run children don't inherit. Pulp's web-compat
<span>Labels
don't inherit typography from the parent, so emit_web_text_runs copies the
node's dominant style onto each run child before applying the run override.
A STRETCH constraint now also emits min_width/min_height: '100%' so it
fills its axis even when the node has an explicit cross-axis size (Yoga clamps
up to the min) — no longer a no-op. (Text-run UTF-16→byte offset conversion is
also handled now — see the per-range text section.)
- Never hand DesignIR bytes to
choc::json::parsedirectly. The pinned
CHOC fork checks for end of input only after a backslash, so a document cut
inside a string literal makes it read past the buffer (the observer died with
SIGBUS), and its ParseError aborts any caller that does not catch it.
parse_design_ir_json bounds-checks the bytes first (terminated strings and
\u escapes, balanced nesting within kMaxDesignIrJsonDepth, no embedded
NUL) and throws DesignIrParseError; a CLI that loads a DesignIR catches it
and exits 1 with the reason. Malformed fixtures for this path live in the
parity harness corpus (tools/parity/corpus/fixtures/malformed/ in Vellum).
Malformed imports fail closed or warn — never pass silently
The rejection corpus (Vellum tools/parity/corpus/fixtures/malformed/) holds
each of these to a code. Keep the codes and the wording the lane's regexes
match:
- A DesignIR envelope newer than this build warns; it is not refused.
The reader deliberately keeps and round-trips any version (tests pin
this), so the check lives in the native resolver:
document-version-unsupported with the text `unsupported DesignIR version
N. Do not move it into parse_design_ir_json`: refusing there breaks the
preserve contract, and it was ruled out.
- Two ZIP members that land on one file refuse the import.
zip_entry_policy.hpp keys members by the lexically normalized,
case-folded path. Scene.pulp.json and ./assets//a.png collide with
scene.pulp.json and assets/a.png on a case-insensitive volume.
- **The native resolver warns on
node-type-unknownand
identity-duplicate.** Each warning is a diagnostic plus a
[pulp:warn] design-import: line. "Unknown" means kind_from_type does not
recognize the type and it is not a vector kind. The warning fires even when
the node's audio role or name still resolves it. Duplicates are found by a
document-order walk of stable_anchor_id (find_duplicate_anchors).
- Repeated derived anchors are disambiguated; repeated explicit ones refuse.
Every binder, tweak and lock addresses a node by its anchor, and the baked
C++ binder binds only on exactly one match, so a repeat silently loses its
binding. A content hash does not include the parent, so identical subtrees
under different parents (two cards, each an unlabelled slider) hash alike.
assign_anchors therefore runs a collision pass: the first node in document
order keeps the anchor, as does every node whose anchor was already unique,
and each later derived anchor (content hash, or the adapter fallback for a
node with no source id) is rehashed with its parent's anchor, then further
ancestors', until it is held by nothing else in the tree. The CLI runs the
same pass (resolve_anchor_collisions) for IRs that arrive already anchored,
then exits 2 only when two nodes carry the same explicit identity (a source
id or an authored anchor), naming each. The materializer keeps warning so an
already-built IR still renders. The adapter fallback also needs the
per-signature sibling index content_hash uses (counted over id-less
siblings only), or every id-less sibling of one shape gets one anchor.
- A successful decode does not prove an image is intact. Skia's PNG
decoder fills the rows of a truncated file with transparent pixels and
returns kSuccess, and the node paints blank. canvas::probe_image_file
therefore also walks the PNG chunks (whole chunks, correct CRCs, an IEND).
asset-undecodable comes from that probe. A PNG with a bad CRC now warns
even when it displays. Test fixtures need real CRCs: the 67-byte
tiny_png_bytes() in test_import_design_tool.cpp has a wrong IDAT length,
so it fails the probe.
- Web fonts that fail in Chromium are named. The capture health probe
lists document.fonts faces whose status is error as
provenance.health.failed_fonts. The lowering turns each one into a
font-undecodable warning. The capture stays healthy, because text still
paints in a fallback face.
Faithful-vector lane (Plan B): `faithful_svg` render mode → `DesignFrameView`
A parallel, newer rendering strategy to the per-widget sprite/native lanes
above: instead of recognizing each widget and rebuilding it, render the
node's own SVG export pixel-faithfully and overlay native interaction.
This is the lane that makes an imported frame look identical to the source
(gradients, multi-layer drop shadows, masks) while staying interactive.
This lane is the DEFAULT across every producer (REST exporter, plugin UI,
headless runner). A plain import yields the faithful frame WITH live overlays
(knobs, search field, dropdowns, steppers, tab groups). The legacy flat,
static node-tree export is opt-OUT: --no-faithful-vector (REST / headless)
or extractScene(nodes, {faithfulVector:false}) (plugin API). Forgetting an
opt-IN flag was the old failure mode — a fresh import came through static /
non-interactive — so the default is flipped. When no frame SVG is obtainable
(e.g. --node-json with no token and no --frame-svg) the lane degrades
gracefully to the flat export with a warning.
Pieces, source-of-truth → runtime:
- Rendering —
Canvas::draw_svg(SkiaCanvas, SkiaSkSVGDOM,libsvg.a)
renders an SVG document pixel-faithfully. Knob animation = wrap the needle
<path> in <g transform="rotate(a cx cy)"> and re-render; the rest of the
chrome stays pixel-exact. DesignFrameView (core/view) renders the SVG,
auto-crops to the panel (largest in-frame <rect>, frac 0.15–0.97 of the
frame), and overlays interaction from a TYPED element list — it does NOT
guess widgets from SVG structure.
- IR — a node opts in with
render_mode = NodeRenderMode::faithful_svg,
points svg_asset_id at an IRAssetManifest entry (mime image/svg+xml),
and carries interactive_elements[] (IRInteractiveElement: cx, cy,
hit_radius, svg_patch_d, default_value, source_node_id, label). These are
source-side semantics filled by the importer, NOT inferred from the SVG.
InteractiveElementKind is deliberately separate from AudioWidgetType.
source_node_idnow survives to the live element.to_frame_elements()
copies it onto DesignFrameElement, exposed at runtime via
DesignFrameView::element_source_node_id(i). So a live overlay can be mapped
back to its design node — the dev inspector's Wiring tab (Cmd-I) uses this
to flag controls that came from Figma but aren't wired up, and to fetch the
matching frame. Previously only stable_anchor_id ("figma:<id>") survived.
- Element labels (§2.1 auto-labeling) —
labelis the human-readable
parameter NAME a host shows (embed ABI v5 PulpEmbedParamInfo.name), taken
from the control's source Figma layer name when meaningful. The REST lane's
_node_label() is deliberately conservative — it returns "" (→ consumer
falls back to the binding key, no regression) for auto-generated names
(Ellipse 12, Frame 41, bare numbers) AND structural/kind words
(Dropdown, Search, Knob, Value, …), because a WRONG name is worse than
the synthetic key. _label_elements() assigns it: overlays resolve via their
source_node_id; geometry knobs (no node link) match the named node whose
frame-local center lands within the knob's hit radius (same coordinate
convention as _name_override_knobs). unit/range are a follow-up — only the
name flows today. Plugin-lane (TS) parity is the remaining lockstep item.
- Regex hardening (watch out): the import codegen scans the source for JS
keyboard shortcuts (extract_keyboard_shortcuts, design_import_shortcuts.cpp).
Because the faithful-vector envelope embeds a ~1 MB base64 SVG data URI, any
unbounded leading-identifier regex over that source catastrophically
backtracks (the \b(\w{1,64}) bound fixes it). When adding new source-scanning
regexes to the importer, bound/anchor the quantifiers — a 1 MB embedded asset
is the realistic input, not a few KB of JSX.
- Producer (REST lane) —
figma_rest_export.py(faithful-vector default-on;
--no-faithful-vector for the legacy flat export) fetches
the frame's own SVG (/images?format=svg, or --frame-svg FILE offline),
embeds it as a data:image/svg+xml;base64 asset (so the importer always
resolves it — no dependency on local_path stamping), sets the root's
render_mode/svg_asset_id, and attaches interactive_elements from
parse_frame_knobs(svg). That detector is the geometry auto-detect ported
from the vector-knob PoC: a knob DOME is a gradient <circle> (fill="url(",
r≥8); its NEEDLE is a thin light-stroked (white or #ABABAB — dark
ticks are #506274) short vertical <path d="Mx1 y1Lx2 y2"> just above the
dome; pair each needle to its nearest dome and emit the EXACT d as
svg_patch_d so the runtime can rotate that one path. --knob-name SUBSTR
(repeatable) is the name override: it supplements geometry with any
node whose name contains the substring (frame-local center from its abs
bbox), but those carry NO svg_patch_d (hit + value, no visual rotation),
the honest fallback for a knob geometry missed.
- Rate limits (REST lane) — every Figma GET in
figma_rest_export.pyroutes
through figma_get(), which honors the 429 Retry-After header (capped
exponential backoff when absent), retries transient 5xx + read-phase
timeouts/resets, and on a terminal 429 raises with the diagnostic headers
(rate-limit type / plan tier / upgrade link) instead of a traceback. **Watch
out: /images?format=svg (frame SVG) and the PNG captures are Figma Tier-1**
endpoints whose budget depends on the plan of the file being requested — a
Starter-plan file can throttle a Full-seat token hard. Don't fire ad-hoc
validation curls against /images next to an export; if you already have the
SVG/nodes JSON, feed them back via --frame-svg / --node-json to spend zero
budget on re-runs.
- Producer (plugin lane) — the Figma plugin mirrors the REST lane in
lockstep, faithful-vector default-on: extractScene(nodes) (defaults
faithfulVector:true; pass false to opt out) or headless
run-headless.mjs <node> (default; --no-faithful-vector opts out, and
injects the FAITHFUL_VECTOR global) captures each frame's SVG via
captureExportedNode(node,"SVG"), decodes the bytes with decodeSvgBytes
(the sandbox has NO TextDecoder), and runs the SAME knob detector
(src/faithful-vector.ts, kept identical to the Python parse_frame_knobs).
serialize.ts emits the three keys; the envelope schema
(figma-plugin-export-v1.json) documents them. Keep faithful-vector.ts
and figma_rest_export.py's detector in sync — both are ES-conservative
regex passes over the SVG text.
- Materializer —
materialize_node(design_import_native_common.cpp)
branches on faithful_svg first and builds a DesignFrameView via
make_faithful_svg_frame: resolve_svg_document() resolves the SVG text
from the asset — data:image/svg+xml (base64 AND percent-encoded) or an
on-disk file (local_path / file:// original_uri), read host-side at
materialize time. An unresolved/missing SVG emits a
native-materialize-faithful-svg-unresolved diagnostic and returns null so
the node FALLS BACK to normal materialization — a bad asset degrades, never
blanks the frame.
Interactive overlays beyond knobs (Plan B "full A")
Knobs are SVG-patch (rotate the needle path in the SVG — pixel-perfect).
The other controls are native-overlay: DesignFrameView is a composite
View that hosts an opaque child widget over the element's rect (build_overlays
in the ctor, positioned in layout_children() via the SAME panel_transform
the SVG is painted with, so they track scaling/letterbox; View::hit_test
routes events to them, knob hit-test is the parent fallback). IRInteractiveElement
DesignFrameElementcarrykind {knob,text_field,dropdown,tab_group,stepper}+
a rect (x,y,w,h) + options/selected_index/placeholder.
text_field→TextEditor(tap-focus + caret + accent focus ring). To keep
the baked leading icon (e.g. a search magnifier) visible, the producer INSETS
the overlay rect to start at the placeholder text's x (past the icon) and emits
the field's own box color (bg_color, from the box's SOLID fill). The overlay
paints that exact color, so the inset edge — and any corner curves — blend
seamlessly with the still-baked box+icon (same-color reveal). Empty bg_color
→ a default dark field. This is general (any leading-icon field), detected from
source structure, not a per-design constant.
dropdown→ComboBox(set_items fromoptions; opens a popup on click).
A real dropdown is detected only when the "dropdown"-named FRAME has a
DOWN-chevron child (Material expand_more) AND its shown text isn't the
unconfigured placeholder "Dropdown". Options carry ONLY the real shown value:
a static design defines no alternatives, and ELYSIUM's selectors are plain
frames (not component instances), so there are no variants to enumerate —
fabricating placeholders would be misleading. A design that defines component
variants would source the full list from its property definitions.
stepper→DesignStepper(a< >header value cycled in place: paints the
current option centered with </> chevrons; left half steps to previous,
right half to next, clamped — nothing painted behind the text so the header
chrome shows through). This is the SAME "Dropdown"-named FRAME family as the
dropdown, discriminated by its chevron child: a < > PAIR (Frame 41 in
ELYSIUM, or an explicit left+right chevron pair) and NOT a down-chevron, with
shown text != "Dropdown". (Previously these were dropped as faithful-static;
they are now live steppers.) Options carry only the real shown value, like
dropdowns — ELYSIUM's < > headers are actually a decorative pair of
expand_more icons inside Frame 41 with no defined alternatives, so there is
nothing to step to until a variant-carrying design or the developer supplies
the list.
tab_group→DesignTabGroup(a compact segmented control drawn opaque over
the tab strip; click a slot to move the selection highlight). Detected
structurally (detect_tab_group): a row of ≥3 similar-width container children
with short text labels; the child carrying a visible SOLID fill is the selected
tab. --select-tab=N is the design-import-standalone demo flag for capturing it.
momentary→ press/release primitive for keys / pads / drum triggers /
sustain / transport. on_gesture_begin(i) = note-on, on_gesture_end(i) =
note-off; set_element_value(i, 1/0) lights it via a NATIVE accent overlay
(the SVG is never recolored, so a re-export still skins it). Carries note
(typing keys = relative semitone 0..17, piano = absolute MIDI; consumers map
by note, never positional index — a re-export may reorder) and view_group
(per-view scope, e.g. typing=0 / piano=1; set_active_view_group releases any
held key so notes never stick across a mode switch). MusicalTypingKeyboard
is the reference consumer; its keys are code-defined (a rect table extracted
from the Figma frame), NOT discovered from SVG geometry — the faithful baked
SVG (dark) provides the pixels, the element list provides behavior. Gotchas:
(1) smallest-area hit tiebreak — among momentary rects containing the
point the smallest wins, so a narrow black key beats the white key it overlaps
(order-independent, survives re-export reordering). (2) **highlight must carve
out notches** — a lit white (larger) key's overlay rect would otherwise bleed
teal over the black keys notching its top, swallowing them; paint() subtracts
any smaller same-view momentary rect that GENUINELY notches the key's top
(x-overlap, starts at/above the top, AND reaches down into the key), painting
the highlight as bands that leave the black-key channels dark. The reach-into
test is load-bearing when one frame shows two keyboards in the same view group
(typing row above a piano keyboard): their keys overlap in x but not in y, so
without it a typing black key was mistaken for a notch on a piano key and drew
a tall bar across the inter-keyboard gap. The notch bottom is clamped to the
key. (3) match the design's own pressed paint, don't invent a flat color —
the lit fill replicates the figma's pressed-key gradient (in the MTK export,
paint36: accent teal 26%→100% opacity, key top→bottom), set per key over its
own height via set_fill_gradient_linear. A flat fill reads as a uniform slab
and the key letter vanishes; the gradient's lighter top lets the letter show.
Footgun that caused exactly this: canvas::Color channels are float 0–1
(Color::rgba8 takes 0–255 and converts) — assigning c.a = 120 clamps to
fully opaque, NOT 47%. Build alpha variants with Color::rgba(r, g, b, 0.26f).
All in DesignFrameView (core/view/src/design_frame_view.cpp).
Re-importing a design revision (round-trip)
Designers WILL revise a frame and expect the change to flow back into Pulp.
The round-trip is figma frame → figma_rest_export.py → embed, and the
canonical source of the faithful frame is the figma node, NOT a design-system
export folder. Hard-won steps (from re-importing the MTK after an even-spacing fix):
- Find the source node. It's in the embed's provenance header (e.g.
musical_typing_keyboard_svg.cpp: "Figma file <key> node <id>"). A
design-system HTML/CSS export folder (tokens, components, *.html) does NOT
contain the detailed frame SVG — only a schematic. Don't try to source the
faithful SVG from it.
- If the node still returns the OLD design, the revision lives elsewhere. A
byte-identical re-export means the figma node wasn't the thing edited (the
designer changed a different node, or only the HTML/CSS kit). Either get the
updated node's URL, or update the figma node yourself from the canonical spec
(see step 3), then export.
- Map CSS intent → figma layout. A folder's
flexeven-spacing
(.mtk-keys { display:flex; padding:6px; gap:0 }, keys flex:1) is NOT a
one-value figma fix. Figma auto-layout beds with FIXED-width, MIN-aligned
children + ABSOLUTE overlays need: symmetric padding and the flow children
set to fill (resize to content/n) and the absolute overlays
repositioned onto the new boundaries (use_figma). Verify with a figma
get_screenshot of the bed before exporting.
- Export + regenerate the embed. `figma_rest_export.py --file-key … --node …
--out scene.pulp.json --faithful-vector`. The frame SVG lands in the scene's
asset_manifest as frame-svg-<node> → an assets/<hash>.svg file (NOT an
inline JSON field). Base64-chunk it (≤8000 chars/literal) into the embed cpp,
matching the existing kParts[]+join format.
- Re-extract interactive rects. Geometry shifts on any spacing change. Re-run
the hit-rect extraction (path bounding boxes from the new SVG) and update the
element tables; positional index is NOT stable across a re-export.
- Neutralize baked pressed/selected states. A revision may bake a demo
"pressed" key (a teal gradient like paint36). For the interactive widget,
rewrite that gradient's stops to the resting fill (#EBEEF1→white) so the
live overlay owns every highlight — otherwise the widget shows a stuck-lit key.
- Verify headless both ways. Resting render: even spacing, no stuck keys. Lit
render: overlay lands exactly on the new key positions with the design's
pressed gradient.
The pulp-design-import-standalone example has demo flags to capture overlay states
headlessly: --focus-search (focus ring) and --open-dropdown=SUBSTR (opens
the matching ComboBox's popup). Use --raster=out.png (Skia) not --screenshot
when the session's live GPU-present path is wedged — raster is the same paint,
GPU-safe, and DOES render the open ComboBox popup (it paints its list inline).
- Detection is SOURCE-METADATA, not SVG geometry (Codex): the producer
walk has node names + absoluteBoundingBox. detect_overlay_controls
(figma_rest_export.py) finds a node named ~search (skipping the
ic:round-search icon; ELYSIUM names the placeholder TEXT "Search" with the
field as its parent group). The plugin lane must mirror this when wired.
- OCCLUSION GUARD — skip controls painted over by a later opaque node. A
design can carry a leftover/under-layer control that is fully covered by a
panel drawn on top (e.g. a stray "Radio Button" 1/2/3/4 buried under the
envelope graph). The baked SVG hides it, but a naive detector resurfaces it as
a live overlay floating ON TOP. Guard: in detection, drop any candidate whose
bbox is fully contained by a node painted AFTER its entire subtree (document
preorder = paint order) that has an opaque fill. Key invariants that took a
round to get right: (1) key the paint-index/subtree maps on OBJECT IDENTITY,
not the figma id string (absent/dup ids collide); (2) compare against the
candidate's subtree_end, NOT its own index — else the control's OWN
background <rect> (a descendant that fills it) looks like an occluder and
drops the control (this nuked the search field on the first cut); (3) "opaque"
must accept GRADIENT fills, not just SOLID — ELYSIUM's occluding panel is a
radial gradient. REST: _opaque_cover checks SOLID a>=.99 or GRADIENT with
all stops a>=.99 + node opacity. TS (faithful-vector.ts): proxies opacity
via style.background_color presence (the extractor sets it for SOLID and the
flat fallback of GRADIENT) + the node opacity field; Map<OverlayNode> keys
give object identity for free. KEEP both lanes' guards in sync.
- COORDINATE GOTCHA (cost me real time): the Figma node tree is frame-local
(root at abs origin, 1000×600 for ELYSIUM) but the SVG export adds the
drop-shadow margin (1146×746, panel at (73,50)). Node coords are NOT SVG
coords. Map every node-derived overlay rect:
svg = (node_abs - root_abs) + panel_origin, where panel_origin is
parse_panel_bounds(svg) (mirrors DesignFrameView::detect_panel). Knobs are
immune (parsed straight from the SVG); only node-tree-derived overlays need it.
Gotchas:
draw_svgrebuilds theSkSVGDOMevery call (a parsed-DOM cache is a
planned optimization) — fine at interactive rates, but don't call it in a
hot per-frame loop without profiling.
- The ASan/UBSan macOS runners link a PARTIAL Skia where
draw_svg(and
url()-mask compositing) is a no-op — render-comparison tests must SKIP when
similarity >= 0.999 rather than fail (mirror test_image_view_fill's
url()-mask guard and test_design_frame_view).
- Pure IR/round-trip + materializer tests (no actual SVG compositing) are
safe on every lane, so put coverage there; reserve the SKIP-guarded
render-diff assertions for the lanes that can composite.
Interactive (turnable) sprite knobs — `--knob-style sprite`
--knob-style sprite no longer DEMOTES a recognized knob to a static image.
A captured-art knob now stays a native Knob that actually TURNS:
- Importer hoist (
resolve_sprite_skinsinsprite_skins.cpp, in the
!use_silver_knobs block): the disposition is keyed on how many asset-backed image children
(captured layers) the knob has:
- exactly one (the ELYSIUM shape — a captured disc + a separate stroked
pointer the native notch replaces): HOIST the disc's asset_ref +
renderBounds onto the knob node and erase the child. The asset-resolution
pass then stamps asset_path + art_core_* on the knob (opaque-core
recovery is gated on render_bounds, which is why the bounds must be
hoisted too). The knob stays interactive.
- more than one (body + highlight + logo + …): DEMOTE to a plain
container (audio_widget = none) — the single-frame sprite skin can hold
only one layer and the leaf knob codegen would silently drop the rest, so
every layer renders as an image instead (faithful but not turnable; a
composited rotational strip is the Approach A follow-up). This preserves
the pre-interactive-sprite behavior and avoids silent layer loss.
- zero: leave the knob recognized; it falls through to the default knob.
Knobs whose art lives on the node itself (the kitchen-sink "knob" image-node
shape) already carried asset_ref and were never demoted — they just gained
the overlay below.
- Codegen (
design_codegen.cppknob branch): emits
setKnobSpriteStrip(id, body, 1, 'vertical') and, when the core was
recovered, setKnobSpriteCore(id, x, y, w, h) (core rect in the frame's own
pixel space). Silver mode is unchanged and still wins (@silver/global).
- Engine (
Knob::paint,widgets.cpp): a single-frame strip is a static
disc, so the engine overlays the native rotating indicator notch (factored
into draw_knob_indicator_notch, shared with the silver path) and, when a
sprite-core is set, CORE-FITS the frame so the disc fills the knob box (the
soft shadow bleed extends beyond) instead of drawing at the PNG's natural
2× size (which oversized it and overlapped neighbours). Multi-frame strips
encode rotation in the frames themselves and get NO overlay.
Gotchas:
- The REST export lane (
figma_rest_export.py) emits recognized knobs as
leaf audio_widget nodes WITHOUT capturing their internal vectors as a PNG
sprite (by design — see the REST-port capture rules). So a REST-exported
knob has render_bounds but no asset_ref: in sprite mode there is nothing
to skin, and it falls through to the default/standard knob. To get a
captured-art sprite knob you need the figma-plugin "Export to Pulp"
envelope (e.g. the ELYSIUM .pulp.zip), which captures the disc PNG.
- The knob's
asset_pathis a RUNTIME path, not build scratch. When the
disc carries a baked-in indicator (knob_ind_r_out), `enrich_imported_image_
asset_metadata re-encodes a *cleaned* disc and repoints asset_path` at it —
and that path is serialized into DesignIR JSON and baked verbatim into
codegen (setKnobSpriteStrip('<abs path>')), then loaded when the SHIPPED
plugin's editor opens. So it must outlive the import process: write derived
assets to default_asset_cache_directory() (PULP_IMPORT_ASSET_CACHE, then
a per-user cache dir), NEVER fs::temp_directory_path(). A temp-hosted
cleaned disc survives local testing and then silently unskins the knob after
a temp sweep or reboot, with zero diagnostics — the failure surfaces on a
customer's machine, far from the import. Key derived filenames by sha256
of the content (pulp::runtime::sha256_hex), like asset_id_for() and
IRAssetRef::content_hash; std::hash is implementation-defined and
unstable across runs and compilers. Note --asset-cache currently steers
only the manifest lane; the cleaned-disc write follows the env var / default.
- Validate turning headlessly: render the imported knob at value 0.0 / 0.5 /
1.0 with pulp-screenshot and confirm the white notch sweeps
lower-left → up → lower-right. The engine unit tests
(pulp-test-widgets [sprite]) pin the notch presence + sweep + core-fit;
the CLI tests (pulp-test-cli-import-design [sprite]) pin the hoist
end-to-end with a synthetic envelope + synthetic PNG (no proprietary
export).
The LIBRARY/materializer path has its own hoist (`hoist_captured_art_knobs`)
The sprite hoist above lives in the CLI (resolve_sprite_skins in
sprite_skins.cpp, gated on --knob-style sprite). The library/runtime path — build_native_view_tree,
used by the GPU harness, standalone/plugin editors, and any embedder — does NOT
go through the CLI, so without its own pass it synthesized a default Knob and
discarded the captured disc (a generic blue value-arc instead of the design's
skeuomorphic disc — this was the ELYSIUM grains_knob_cap residual).
hoist_captured_art_knobs(DesignIR&) (declared in design_import.hpp, defined
in design_import.cpp beside the sibling importer passes enrich_* /
synthesize_primitive_paths) is the library-side promotion. Contract:
- Run it BEFORE
enrich_imported_image_asset_metadataso the hoisted
asset_ref receives its absolute asset_path + opaque-core metadata. Order is
parse → absolutize → hoist_captured_art_knobs → enrich → build_native_view_tree.
- Layer disposition by captured-image area (not just count, unlike the CLU's
count-only rule): the largest asset-image child is the body disc; a secondary
layer counts as SUBSTANTIAL only if its area ≥ 40% of the body (the CLI rule
is count-only). ELYSIUM's Vector 7 pointer is a 0-width stroke hairline
(area 0) → not substantial →
the knob HOISTS the disc and stays interactive. Two comparable layers (body +
highlight) → demote to a static container.
- Capture the design's OWN pointer, don't synthesize one. The disc body PNG
(ELYSIUM Group 130) is a CLEAN face with the min/center/max REFERENCE ticks
baked in; the moving pointer is a SEPARATE node (Vector 7, a ~4×16 hairline).
Before erasing the hairline, the hoist stamps its geometry onto the knob as
fractions of the disc half-extent: knob_ind_r_in / knob_ind_r_out (the
radii the line runs between, derived from the hairline's endpoints vs the disc
center), knob_ind_w (stroke width frac, from border_width), knob_ind_color.
The materializer forwards these via
Knob::set_captured_indicator, and Knob::paint draws THAT pointer — pivoted
at the disc CORE center on the same [-135°,+135°] arc — instead of the generic
draw_knob_indicator_notch. Two bugs this fixes: (1) double line (the synthetic
notch + the disc's baked center tick); (2) misalignment (the synthetic notch
pivoted at the layout-BOX center with a guessed radius drifted off the baked
ticks). Pivot at the disc center + the design's own line ⇒ it rides the ticks by
construction. The synthetic notch is still the fallback for knobs with no
captured indicator metadata.
- The pointer scan must handle the DEMOTED hairline, not just asset images
(root-cause fix, 2026-06). Vector 7 is a thin stroke vector, so the
stroke→fill demotion pass (see "Hairline strokes") rewrites it from
type:image into a 1px-wide frame whose stroke color sits on
background_color, with NO asset_ref. The original hoist scanned only
asset-backed image children for the pointer, so it silently missed the demoted
Vector 7 entirely: knob_ind_* was never stamped (knob fell back to the
synthetic notch) AND the stray 1px frame rendered as a stuck second line.
Captured-pointer was effectively dead on ELYSIUM despite the metadata plumbing
existing. The fix: the pointer scan walks every non-body, non-text child and
picks the thinnest one (min(w,h) ≤ 2.5px), so it catches both the raw 0-width
hairline AND the 1px demoted frame. It tags that node __knob_pointer, reads
color from border_color → else background_color (demoted) → else color,
and the erase predicate removes __knob_pointer nodes too. Test:
[knob][sprite] "recognizes a stroke-demoted pointer frame".
Browser capture: the author DECLARES the indicator (`data-pulp-indicator`)
The renderer half above is source-agnostic — any knob carrying knob_ind_* gets
the design's own pointer swept by value — but the Figma producer cannot be
reused for a browser capture, and for a structural reason:
- A capture is one flat picture of the whole panel. A lowered knob has no
asset_path at all, and apply_captured_art_knob_skin returns immediately on
an empty one. So the knob paints no disc, and the design's indicator — which
is in the backdrop bitmap — never moves.
- The indicator is CSS, not a layer: a conic-gradient arc, a positioned dot.
There is no thinnest-child hairline to find, so the Figma scan finds nothing.
So the browser lane declares it, exactly as it already declares the paint box:
<div class="pulp-knob" data-pulp-param="cutoff" data-pulp-value="0.55">
<div class="dial" data-pulp-paint>
<div class="dot" data-pulp-indicator></div>
</div>
</div>
semantics.mjsreports the marked element's page rectangle (same frame as
bounds / paint_bounds) plus its browser-resolved colour: background-color
→ inside SVG, stroke then fill → border → text. A pointer no single
computed colour describes states its own: data-pulp-indicator="#b8f8c0". An
unpainted pointer reports "", which the consumer reads as "no attribute" and
draws its derived tick instead. **The SVG step is not appendable to the end of
that list** — see "A marked indicator's colour comes from PAINT" below.
lower_semantic_controlsconverts that rectangle to the SAMEknob_ind_*
fractions the Figma hoist stamps, by projecting the box's half-extents onto
the radial axis and its perpendicular. A plain width/height read is wrong
for a dot at 7 o'clock, whose diagonal — not its width — spans the radius.
apply_browser_capture_control_sprites(browser_knob_sprites.cpp, run from
import_browser_html right after lowering) crops the control out of the panel
capture. A knob gets a per-knob PNG stamped through asset_path /
png_natural_* / sprite_strip_frame_count=1. A fader gets a cleaned body
crop plus the declared indicator as its own sprite; Fader::paint moves that
authored sprite with the value instead of drawing the stock white slab.
A fader may retain captured track/ticks/border only when its control element
explicitly carries data-pulp-static-track; a single default screenshot can
never prove that a uniform track will stay uniform at another value, nor can
spatial variation distinguish a wide static tick from a value fill. The
declaration is therefore the positive semantic evidence: emit it only when
the track, ticks and border are invariant at every value AND no tick, marker,
label or gradient discontinuity is hidden beneath the thumb at the captured
value. data-pulp-indicator must bound the entire moving visual footprint,
including antialiasing, shadows and transforms. When the visible thumb's DOM
box is smaller than that footprint, mark a transparent wrapper around it;
pixels outside the declared rectangle remain static by contract. A single
capture cannot reconstruct occluded authored pixels. Omit data-pulp-static-track
for that case and for every low-contrast, alpha-only, edge-origin or bipolar
fill; the importer then retains the live native track/fill path. The
indicator erasure uses exactly the declared moving footprint. Undeclared
faders stay live. Apart from that declared footprint, a declared static
body's crop is byte-identical to the capture.
- The fader's isolated moving crop also supplies a durable
fader_ind_color. Colour selection is paint-aware: it ranks exact source
colours by local support instead of taking the first opaque or centre pixel,
so a hollow/ring thumb keeps its authored outline rather than an
antialiased/background blend. This attribute survives even when
fader_indicator_asset_path is later pruned for self-contained persistence.
knob_ind_color has the same durable, per-control role for knobs.
- The baked pointer is erased by rotational median: a dial face is
rotationally symmetric about its centre except for the pointer, so each erased
pixel takes the median of the same radius under 8 rotations (samples landing
back inside the pointer are dropped). This is the browser-lane counterpart of
clean_baked_knob_indicator; without it the live pointer draws beside a stuck
one.
Gotchas:
- An undeclared control gets nothing. No sprite, no indicator, no attribute
churn. Inferring one would put a live pointer on a design that has none, and
nothing in a flat picture says which pixels move.
- A declared indicator that cannot be honoured fails the import (exit 3).
A dropped pointer still renders a perfect static panel and passes every pixel
gate — that is exactly the failure that must not be silent.
- DPR 2 is load-bearing.
validate_reference_geometryrequires it, and
Knob::paint's no-core sprite branch divides the PNG's natural size by a
hardcoded kExportScale = 2.0f. The crop is paint_box × dpr, so the two
agree only at 2. Changing either without the other silently resizes the disc.
- A/B similarity can move. The live pointer is drawn on the
[-135°,+135°] arc at the control's data-pulp-value; a design that sweeps
differently lands its dot elsewhere, so the score shifts by roughly two dots'
worth of pixels. That is the honest cost of a live indicator, not a
regression.
- A rotated hairline is not covered. A bounding rectangle describes a dot or
an axis-aligned bar exactly; a CSS-rotated hairline's box is much wider than
the hairline, so its declared width comes out too large. Declare a dot, or the
pointer's own un-rotated box.
- Tests:
[browser-capture][knob][indicator]and
[browser-capture][fader][indicator][movement] in
test_browser_knob_sprites.cpp
— the load-bearing one is [movement], which renders the pointer at five
values and asserts the drawn geometry MOVED. A one-frame similarity score
cannot tell a live indicator from a frozen one.
- Indicator colour precedence is provenance, not merely a palette lookup.
A valid per-control knob_ind_color / fader_ind_color is authored evidence
and wins. design_indicator is only the panel-wide fallback and MUST NOT mark
the control as individually authored. With neither attribute present, the
stock widget theme remains in authority (knob.thumb for a captured knob
pointer and control.thumb for a fader thumb). Never gate
these durable attributes on a sprite path: project
packing may intentionally remove importer-time paths while preserving the
control contract.
Every consumer must receive the same authored indicator contract.
knob_ind_* and fader_ind_color must stay in lockstep across the native
materializer and BOTH generated-JS arms (bridge_native_js and web_compat).
The generated knob call is
setKnobCapturedIndicator(id, rIn, rOut, width, color, phase, authored) and the
generated fader skin passes the selected thumb colour plus its authored flag to
setFaderSkin; neither emission
may sit inside a sprite/captured-art-path branch. Generated-output regressions
must exercise absent sprite paths and conflicting per-control versus
design_indicator colours in both modes. The bridge registers these setters in
the widget_assets group (so reload_autocaps gates them as Filesystem, like
their siblings). Two traps:
- Fallback provenance stays live at paint time.
authored=falsestores
design_indicator only as the fallback passed to the widget's normal theme
token (knob.thumb or control.thumb); it must not snapshot the current
theme during the bridge call. A later host theme change still wins.
authored=true belongs to per-control evidence: knob_ind_color,
fader_ind_color, and the older per-control skin_thumb_color sampled from
that control's captured PNG. The newer isolated fader_ind_color is applied
last when both fader forms exist. Authored colors remain fixed over the
theme. A later authored=false fader call must clear any stale authored
thumb override so the live theme can regain authority; a later
authored=true call takes authority back. A sprite-less knob must
also draw the recovered pointer geometry; merely retaining metadata that only
the sprite branch reads is not portable-project support.
- Keep colour parsing shared. The bridge setters use the same
parse_css_color family as the materializer and accept #rgb, #rrggbb,
#rrggbbaa and supported CSS functional forms. Do not reintroduce a local
hex-only parser in either lane; browser-computed and Figma-demoted pointer
colours otherwise diverge between scripted and materialized panels.
- Emit nothing when there is no recovered pointer. The call installs a
captured indicator unconditionally, and a zero-length one suppresses the
synthetic notch — leaving an imported knob with no visible indicator at all.
- Import-time disc clean (
clean_baked_knob_indicator→
clear_baked_knob_antenna, design_import_png.cpp), NOT a render-time cover. Many
captured discs (ELYSIUM's included) BAKE an indicator into the disc PNG — here
it's a thin vertical ANTENNA standing straight up ABOVE the disc at 12 o'clock.
Since we draw our own rotating pointer, the baked one is a stuck second line. So
when a knob carries knob_ind_*, enrich_imported_image_asset_metadata decodes
the disc PNG and removes the antenna, re-encodes via a minimal PNG
encoder (encode_rgba_png_for_import, filter-0 scanlines + runtime
zlib_compress + IHDR/IDAT/IEND with hand-rolled CRC32), writes
$TMPDIR/pulp-import-assets/knobclean_<hash>.png, and repoints asset_path.
The removal MUST be non-destructive to the disc — two earlier attempts cut a
visible notch/gap into the ring's top:
- Copy-from-beside + alpha-punch (v1): copying a face strip horizontally
across the CURVED ring mismatched the rim, and p[3]=0 punched holes in the
ring. Wrong: never alpha-punch the disc, never copy across curvature.
- Clear a fixed column at the bbox center (v2): the antenna is NOT at the
opaque-bbox center — the bottom min/max ticks skew the bbox, so on the big
knob the center column had no antenna and nothing was removed.
The correct algorithm (clear_baked_knob_antenna, a pure RGBA8 function so it's
unit-testable): scan the disc bbox from the TOP down; each row, measure the
ACTUAL opaque span. A NARROW span (≤ ~18% of the disc width) is the antenna →
clear exactly that span (wherever it sits). The FIRST WIDE span is the disc body
→ STOP. So the ring, face, and bottom ticks are never touched. Result: a single
moving pointer at every value, antenna gone, no notch, min/max ticks intact.
Test: [knob][antenna] in pulp-test-design-import-native-common (antenna
cleared, disc body byte-for-byte intact; no-op when there's no antenna).
Requires no edit to the Figma source.
- Materializer skin (
make_widgetknob branch): when the knob node carries
an enrich-stamped asset_path (+ png_natural_*), it builds a single-frame
SpriteStrip + set_sprite_core from art_core_*, then applies the captured
indicator above. The knob is design-faithful AND turnable — Phase-D drag still
passes (pulp-test-mac-platform-harness knob_drag_probe).
- Gotcha: the harness pins
count_ir_nodes(ir.root)on the parsed scene —
assert structural counts BEFORE calling the hoist, since it removes the
captured layers.
- Tests:
[knob][sprite]inpulp-test-design-import-native-materializer
(hoist promote + demote + indicator-geometry capture + materializer forwarding,
pure, no I/O) + the GPU harness (end-to-end skin + interactivity).
Shaded and double CSS borders, and themed form controls
border-style: outset | inset | groove | ridge | doubleare painted by View
in per-side bands (border_shades / border_bands / border_band_color in
pulp/view/border_style.hpp, pure and public). Every lowering parses the
keyword through the one border_style_from_css() table there; dropping a
keyword paints a flat solid frame. The shading rule was fitted
to Chrome 151 renders and checked on 189 colours — re-measure with a probe
page before changing it, never from a fixture. Pure black is not special in
the code: any colour no brighter than rgb(32,32,32) by relative luminance is
lightened once before shading, which is why black shades to 168/84.
- A user-agent
<button>computes2px outset rgb(0, 0, 0). Chromium paints
that border with CSS only when the author styled the box (background, border,
or radius); otherwise its native theme paints the control and the computed
border is not what is drawn. Whether the theme painted is recorded per control
in the DOM snapshot's formControlTheme (from matched-rule origins) — read it
instead of re-deriving it from computed appearance, which stays auto in
both cases.
Rasterized-vector image: suppress its baked stroke as a CSS border
A Figma vector exported as a PNG (the FILTER & EQ curve Vector 3, every grid
Line, dividers) carries its stroke as border_color + border_width in the
IR — but the stroke is already in the raster. apply_visual_style draws a
CSS border from those fields, which paints a spurious box outline around the
image (the visible bug was a bright purple rectangle around the EQ curve). The
materializer passes skip_border=true for image_view nodes so the border is
not redrawn. If you add a code path that materializes images, keep that guard.
Test: [image][fidelity] in pulp-test-design-import-native-materializer.
Widget recognition by Figma layer NAME (dropdowns, search field)
Some interactive widgets are recognized by the designer's layer name, not the
node type — designers label these containers explicitly, so the name is a
source-honest signal (no content guessing). kind_from_name in
design_import_native_common.cpp runs in resolve_node AFTER audio-widget
detection and BEFORE kind_from_type:
- A
framenamedDropdown→combo_box(aComboBox) ONLY when
looks_like_real_dropdown: it carries a real selected value AND a SINGLE
square-ish down-chevron (aspect ≤ 1.8). The name alone over-matches — ELYSIUM
reuses "Dropdown" for two non-dropdowns that must stay plain frames:
- a prev/next preset cycler whose icon is a WIDE
< >pair (e.g. the 42×16
"Frame 41" on the ENVELOPE/FILTER/FX-RACK headers) — leave static (faithful)
until a real cycler interaction exists;
- an unconfigured design-system template whose value is the literal word
"Dropdown" (the stray "VST Style" placeholder). materialize_node renders it
as a hidden, zero-size, inert view (is_unconfigured_dropdown_template) so it
can't surface between panels — excluding it from combo_box alone left it
rendering as a static "Dropdown" frame.
combo_box is a leaf in materialize_node (text + chevron children are NOT
re-materialized — the ComboBox paints its own display) and owns its hits.
- A search field is a
frameCONTAINER (is_search_container: it wraps a text
child named Search/SearchBox) → text_editor sized to the WHOLE box (not
the inner text cell, so the field spans the box and the placeholder isn't
truncated). The inner text becomes the placeholder; the editor inherits its
font size and a content_inset_left so the caret clears the leading magnifier.
In materialize_node a promoted text_editor keeps only IMAGE children (the
icon) and drops the placeholder text + bg-pill chrome.
Web-compat parity caveat: this recognition is NATIVE-only — the web-compat
codegen does not detect these names. The screenshot-parity fixtures contain no
Dropdown/Search nodes, so the invariant holds today; if you add one to a
parity fixture, mirror the detection in the codegen (same lesson as the text
vertical-centering split). Tests: [combo-box], [text-editor] in
pulp-test-design-import-native-materializer.
`kind_from_type` Ink & Signal vocabulary (type-string aliases)
kind_from_type (the type-string fallback, after kind_from_name) also
recognizes the design-system / common-web component names so imported designs
map onto native widgets instead of falling through to native-unsupported-node:
toggle/switch→toggle_button; combobox/combo_box/dropdown/select→
combo_box (note: before this, combo_box had a kind but no type string
resolved to it — only the layer-NAME path above could reach it); pan/panner→
fader (1-D linear control); badge/chip/tag/pill→label;
panel/sidebar/side_panel/toolbar/channel_strip/card→view. Faithful
dedicated NativeWidgetKinds for the remaining gap widgets (Stepper, Toast,
InlineBanner, Dialog, Popover, EmptyState, Tab, ProgressBar) need new codegen
emitters across the C++/Swift backends — a follow-up, not these aliases. Test:
[design-system] in pulp-test-design-import-native-common. The pulp::design
catalog (pulp/design/design_system.hpp) is the authoritative component→native
mapping these aliases mirror.
Native widget fidelity is inherited — keep token keys correct
An imported design materializes these native widgets, so it inherits whatever
the native defaults look like. The native widgets were converged to the
Ink & Signal Figma source (Knob body+arc+dot, square Checkbox, teal Toggle,
filled TextButton::Style::primary, slab Fader thumb, segmented Stepper, area
Spectrum, bar Waveform, etc.), so a faithful import needs no per-instance skin
for the common case — getting the native default right is what makes the import
look right.
The recurring failure mode here is a wrong token key: a widget that calls
resolve_color("typo_or_old.key", <hardcoded fallback>) where the key isn't a
real theme token compiles, paints the hardcoded fallback, and silently ignores
the imported token set (the reskin never reaches it). This shipped the coral
ProgressBar/Tab and several grey CallOutBox/ListBox/key-mapping bugs.
Canonical keys are the t.colors["…"] names in theme_presets.cpp (dotted:
progress.fill, tab.active, text.primary, control.border, meter.green,
…) — never underscore/bare forms. Enforced by tools/scripts/token_key_check.py
(token-key-correctness ctest) and, on Pillow lanes, the
component-visual-regression per-primitive gate. See
docs/guides/design-tokens.md →
"Use the real token key". GPU vs raster fill caveat: an area/shader fill
(Canvas::draw_waveform) shows nothing on the CPU raster path — draw fills with
raster primitives if they must render off-GPU (see the skia-gpu-build skill).
Value-driven silhouette fill (illustration shapes — item 3)
A captured illustration PNG (ELYSIUM's prism / cylinder / pentagon / cube) can
be "filled" to a bound value via ImageView::set_fill_value(0..1) +
set_fill_color. ImageView::paint overlays the color from the bottom up to
value of the height, masked to the image's OWN alpha through the canvas
save_layer_with_mask url() path — so the fill clips to the shape silhouette.
**Per-shape gradient — each shape fills with ITS OWN colors, not one generic
color.** ELYSIUM's shapes are uniquely colored (DEPTH purple, POSITION magenta,
OFFSET green, SHIMMER amber). A single set_fill_color made all of them fill the
same purple — visually wrong. So the importer SAMPLES each shape's own vertical
gradient from its art and stamps shape_fill_gradient (sample_shape_fill_gradient
in design_import_png.cpp: average the opaque pixels in N bands bottom→top, emit
#rrggbb stops). ImageView::set_fill_gradient(stops) then paints that gradient
revealed to fill_value instead of the flat color, so the shape fills with its
real colors — "mapped to the original", only adjustable. **This is independent of
render_bounds** (the shapes carry none; only knobs/EQ-curve do), so sampling runs
for any non-knob colorful image. A near-grey image (logo/icon) is BELOW the
saturation gate (max_sat < 0.18) and gets no gradient — the capability won't
latch onto things that shouldn't fill.
Opt-in is preserved. The importer stamping shape_fill_gradient, and the
materializer forwarding it to set_fill_gradient, are BOTH inert until a fill
value is driven (fill_value stays −1 ⇒ emit_silhouette_fill early-returns).
So a plainly-imported design renders unchanged; only a deliberate post-import
step that drives set_fill_value turns a shape into a fillable control. That
post-import wiring is the opt-in. Example phrasings a user can ask for after an
import: "for the shapes, use their own gradients as the fill color", *"wire the
DEPTH knob to fill the cylinder", "make the prism fill adjustable with its own
gradient"*. What you should NOT do: auto-drive fills on every image (a logo with a
gradient would start filling) or hardcode per-shape colors in the importer — the
gradient must be SAMPLED from each shape so it stays faithful to any design.
The alpha-mask primitive: SkiaCanvas::save_layer_with_mask Phase 1 only
shipped gradient masks; url(<file>) image masks were future work. They are now
implemented (skia_canvas_mask.cpp parse_url_image_mask — decode the file to
an SkImage, build a kDecal shader scaled to the mask box; kDstIn keeps painted
content only where the image alpha is non-zero). Works on Skia raster AND
Graphite/GPU.
Binding which knob drives which shape is NOT in the figma source (no Figma
binding), so the import does not auto-wire it. The design-import-standalone example
demonstrates the opt-in by pairing each upper illustration with its column knob
(apply_shape_knob_fills, by laid-out x) and driving set_fill_value from the
knob each frame; the per-shape gradient flows through automatically because the
materializer already set it. Verify headlessly on the Skia raster backend,
not a GPU window: render_to_png(view, ..., ScreenshotBackend::skia) exercises
the url() mask without Dawn/Metal. PULP_KNOB_VALUE=<0..1> on the example sets
every knob, so a raster at 0.25 vs 0.9 shows the fill level rise with each shape's
own color (a quick visual check that the gradient is value-driven, not base art).
Tests: [view][image][fill] in pulp-test-image-view-fill (flat fill scales with
value; a 2-stop gradient fill differs from the flat fill; <2 stops clears it).
[native-materializer][fill] asserts the materializer forwards shape_fill_gradient
to set_fill_gradient WITHOUT driving the fill (opt-in intact). The mac harness
(pulp-test-mac-platform-harness) pins end-to-end sampling: ≥4 ELYSIUM shapes get
a sampled gradient while the grey chrome does not.
Imported text vertical centering — fix BOTH render paths together
The figma-plugin IR drops textAlignVertical, so a single-line label in a slot
taller than its text rides the TOP of its box (visible bug: ELYSIUM "SEARCH" sits
high; the 1·2·3·4 tab digits look off). The rule: center when
height > font_size * 1.15. **It must be applied to BOTH render paths or the
parity gate fails** — pulp-test-design-import-screenshot-parity pins
build_native_view_tree (baked/native) == web-compat generate_pulp_js (live).
The two paths are SEPARATE codegens:
- Native (
apply_label_style,design_import_native_common.cpp):
label.set_vertical_align(center).
- Web-compat is the HTML/DOM emitter (the
.style.*block in
design_codegen.cpp — document.createElement('span') + .style.verticalAlign),
NOT the createLabel/setVerticalAlign branch (that serves bridge-native-js).
It emits span.style.verticalAlign = 'middle'; the web-compat shim
(web-compat-style-decl-typography.js) maps verticalAlign →
setVerticalAlign → Label::set_vertical_align.
Both converge on one Label mechanism ⇒ identical pixels ⇒ parity holds. A
NATIVE-ONLY change diverged the control-strip fixture to 0.95 (< 0.97) because
the web-compat span otherwise top-aligns. Tests: [text] in the native
materializer suite + the parity suite (both fixtures green).
Hairline strokes (EQ grid) → demoted to 1px frames; parse the rgba() fill
The FILTER & EQ background grid is 8 hairline Line nodes. By the time they
reach materialize_node an upstream pass has already demoted them from
stroke-only images to 1px frames (one axis floored to 1, marked
__stroke_demoted=1) whose background_color is the stroke color — typically
rgba(171, 171, 171, 0.1). They still painted nothing because
apply_visual_style resolved background_color with parse_hex_color, which
does NOT handle rgb()/rgba(), so the fill was dropped and the grid vanished.
Fix: apply_visual_style now falls back to the shared parse_css_color
(exported from css_gradient.hpp) for rgb()/rgba()/transparent. So the bug was
NOT a 0-area-paint drop (that red herring cost time — flooring the flex dim did
nothing because the node is already a 1px frame, not an image); it was an
unparsed rgba fill. Test: [color] in the native materializer suite.
`IRStyle::box_shadow` is parsed layers, not a string
IRStyle::box_shadow is a std::vector<IRBoxShadow>, not an
optional<string>. CSS box-shadow is a comma-separated layer list; the old
single-string field silently dropped every layer past the first. Don't assign a
raw CSS string to it or compare it to one — use the helpers in design_ir.hpp:
parse_css_box_shadow(css)→ orderedIRBoxShadow{offset_x,offset_y,blur,spread,color,inset,raw}layers. Splits on top-level commas only (commas insidergba()/hsl()stay intact); each layer keeps its trimmedrawtext for lossless round-trip.box_shadow_to_css(layers)→ CSS string (prefers each layer'sraw).
Every IR ingest site (design_ir_json parse, claude_bundle, v0_tsx) parses
into the vector; every emit site (design_ir_json write, design_codegen web +
native, native_common) serializes back via box_shadow_to_css. Native
setBoxShadow reads box_shadow.front()'s parsed fields directly — no
re-tokenizing the raw string. Gotcha: the bridge takes one drop shadow, so
multi-layer stacks render only their first layer natively even though the IR now
preserves them all.
An initial-value style must install nothing natively
IRStyle keeps string properties as authored, so clip-path: none,
filter: none and friends arrive at apply_visual_style as non-empty
optionals. A property whose handler passes "anything unparsed" straight
through is the trap: the native materializer stored clip-path: none as SVG
path data, and every paint recorded clip_path_svg "none". Skia's path parser
rejects it, so the raster was unchanged and no pixel scorer saw it; a backend
that treats an unparseable path as an empty clip would erase the node. The JS
lane had always cleared on none, so the lanes disagreed silently.
test/test_design_import_inert_styles.cpp builds one scene through the IR JSON
reader with and without each inert declaration and requires an identical
drawlist, an identical drawlist from the next sibling on (headed by its open
save depth, so a leaked save is named as a leak) and an identical Skia raster.
When you add a style property to the materializer, add its inert value AND a
live value to that table: the live value is what proves the property reaches
the paint path at all, since a dropped property passes the inert check.
background-image has no live value there because the native materializer
does not paint it.
Figma effects: blurs lower for real; new families are diagnosed
All three Figma producers lower the ordered effect stack, honoring
per-effect visible: false (skipped, no diagnostic — it's the designer's own
off switch):
DROP_SHADOW/INNER_SHADOW→ orderedbox_shadowlayers (above).LAYER_BLUR→style.filter = "blur(Npx)". **The.figkiwi schema spells
it FOREGROUND_BLUR** — scene.mjs accepts both spellings; don't add a
LAYER_BLUR-only dispatch to the offline lane. Consumed end to end:
web-compat .style.filter → style-decl bridge setFilter; bridge-native
setFilter → View::FilterOp chain → save_layer_with_filters.
BACKGROUND_BLUR→style.backdrop_filter = "blur(Npx)"→ codegen web
.style.backdropFilter / native setBackdropFilter(id, blur_px) →
View::set_backdrop_blur. The native bridge setter is numeric, so
bridge-native codegen parses the radius out of the CSS value (mirrors the
web-compat style bridge).
- Multiple blurs of one kind keep array order as a space-joined function
sequence (blur(2px) blur(6px)) — setFilter sums the amounts.
- A
PROGRESSIVEblur keeps its end radius as a uniform blur plus a
progressive-blur-approximated (capture_partial) diagnostic (plugin/REST).
- Everything else (
NOISE,TEXTURE/GRAIN,GLASS, anything newer) raises
effect-unsupported in every lane — never a silent drop. The .fig lane's
code registry (DIAGNOSTIC_SEVERITY in scene.mjs) enforces
registered ⇔ emitted in both directions; register any new code there.
Shared lowering lives in extract-pure.ts::lowerEffects (plugin),
figma_rest_export.py::extract_style (REST), and
scene.mjs::effectsToBoxShadow/effectsToFilters (.fig);
material_audit.mjs::effectSurvived reads blurs through the survived arm
(style.filter / style.backdrop_filter), so regressing the lowering trips
the audit unless the diagnostic comes back. Still-partial: the C++ native
resolver lane (design_import_native_common.cpp) diagnoses filter /
backdropFilter as unsupported (it doesn't call the View setters), and
cpp/swiftui codegen don't emit them.
Backdrop under opacity: Chrome composites a backdrop-filter at the
element's opacity. It draws the filtered backdrop at that opacity, then the
element over it at that opacity, so an opacity: 0 box with
backdrop-filter shows nothing at all, and a hidden frosted toast must not
blur what is under it. View::push_effect_layers skips the backdrop layer
at opacity 0 and ends the chain in opacity() below 1. An ancestor's
opacity layer is the backdrop root, as in Chrome. Chrome's numbers come from
tools/import-validation/chrome_backdrop_opacity_oracle.py over fixture
22-backdrop-opacity, and pulp-test-css-backdrop-opacity holds Skia to them.
Backdrop edges are mirrored: at a frosted box's edge, Chrome blurs the
backdrop as if the box's own content were mirrored past its edges. It neither
repeats the edge column outward nor reads the page beside the box. The Skia
backdrop paths feed the blur SkImageFilters::Crop(bounds, kMirror) and
crop only the output; passing the rect as the blur's own crop rect clamps the
input instead, and a bright line just inside the edge smears up to 30 levels
too bright. The fixture's sixth box starts on a 4px amber band, and the
oracle prints Chrome's profile across that edge (row 210) for the
backdrop-filter mirrors the box at its edges test.
Step 1: Identify source and input
Ask the user or detect from context:
- CLI source: figma, figma-plugin, stitch, v0, pencil, claude, designmd, or jsx.
The runtime/source-contract lane also covers rn.
- Input: file path, URL, or an exported/generated artifact. MCP tools are
acquisition helpers; do not pass raw provider MCP JSON to the CLI unless that
source contract explicitly documents the shape. Claude is manual-file only;
designmd is static-file only.
Step 2: Read the design data
--from figma-plugin, NOT --from figma, for any .pulp.json/.pulp.zip envelope.
There are two distinct Figma sources: --from figma → parse_figma_json (the old Figma REST/file format) and --from figma-plugin → parse_figma_plugin_json (the plugin/headless export envelope, format_version 2026.05-figma-plugin-v1). Feeding a plugin envelope to --from figma historically produced a silent empty import — parse_figma_json found none of its structure and emitted only createCol('root') (1 elements: 1 containers, 0 widgets, 0 labels). The CLI now auto-detects the envelope and routes to the plugin parser with a note: on stderr (see looks_like_figma_plugin_export + test_import_source_routing.cpp), but always pass --from figma-plugin explicitly. Tell-tale of the old mistake: a ~13-line ui.js with only the root, or 0 widgets, 0 labels on a design that clearly has widgets.
Figma plugin export — .pulp.zip is the default ship shape:
The "Export to Pulp" button in tools/figma-plugin emits a .pulp.zip containing scene.pulp.json + assets/*.png whenever the design has images. The CLI auto-unpacks ZIPs transparently (look for Unpacked … on stdout); point --file directly at either form:
pulp import-design --from figma-plugin --file design.pulp.zip --output ui.js # canonical
pulp import-design --from figma-plugin --file scene.pulp.json --output ui.js # also fine
Headless alternative — tools/import-design/figma_rest_export.py (no plugin click).
For iterative dev you don't have to open Figma desktop and click Export every time. This script pulls a frame via the Figma REST API and emits the same figma-plugin-export-v1 envelope (it's a faithful PORT of pulp-figma-plugin/src/extract.ts — keep the two in sync). It captures vector/illustration nodes as PNG asset_refs via the REST /images endpoint, exactly like the plugin's exportAsync.
# one-time: figma.com -> Settings -> Security -> Personal access tokens ->
# Generate, check ONLY file_content:read, save to ~/.config/pulp/figma-token (chmod 600)
python3 tools/import-design/figma_rest_export.py \
--url 'https://figma.com/design/<KEY>/...?node-id=3-42' --out scene.pulp.json
pulp import-design --from figma-plugin --file scene.pulp.json --output ui.js
Token resolves from --token, then $FIGMA_TOKEN, then ~/.config/pulp/figma-token; lifecycle (added/expiry) tracked in ~/.config/pulp/figma.json. PATs expire (≤90 days) — regenerate same-scope; Figma OAuth2 is the permanent path (future). The plugin lane remains source-of-truth (audio-widget recognition, Pulp Library matching); the REST port covers generic frames/text/vectors/assets, which is what non-library designs (e.g. ELYSIUM) use. Asset PNGs only composite when the render uses the SKIA backend. Two independent gates: (1) a GPU/Skia-enabled build (PULP_HAS_SKIA), and (2) the Skia screenshot backend — render_to_png's macOS default is CoreGraphics, whose canvas lacks draw_image_from_file, so ImageView draws each image's filename as placeholder text (empty boxes + scattered *.png) even in a Skia build. pulp import-design --validate now defaults to --screenshot-backend skia so a fresh import render is faithful; only pass coregraphics deliberately. If a validate render shows missing images + filename text, it's the backend, not the import — re-render with Skia. See the screenshot skill.
Bundled (non-system) fonts — font_family_assets → registerFont (#43b). When the envelope carries font_family_assets (#43a: [{family, style, weight, asset_id}]) with the .ttf/.otf shipped in assets/, the importer registers each so a non-system family actually loads instead of setFontFamily silently falling back to a same-named system font. Pipeline: parse_figma_plugin_json → DesignIR.font_family_assets; the CLI resolves each asset_id → absolute path (same pass as image asset_path); generate_pulp_js emits registerFont('<family>','<path>') in the JS header before any setFontFamily; the registerFont bridge calls AssetManager::register_font_family → canvas::register_font_file (Skia typeface; no-op stub off-GPU). Gotcha: if the design's font is also system-installed (e.g. Inter on macOS), a render can't distinguish bundled-load from system-fallback — verify with a non-system family. Covered by [issue-43b] in test_design_import.cpp.
Two render-path traps behind registerFont (found chasing the ELYSIUM font gap). Emitting registerFont is necessary but historically NOT sufficient — two silent failures made registered fonts not render:
- SkParagraph never saw registered fonts.
register_fontpopulated only the Canvas2DfillText/FontResolverpath. But everyLabelrasterizes through SkParagraph (make_paragraphinskia_canvas_text.cpp), whoseFontCollection(TextFontContext::font_collection()) only registered the emoji typeface — user fonts fell back to a system face for ALL label text. The fix bridges the registry into the paragraph collection viaregistered_typefaces_snapshot()(inbundled_fonts.cpp), iterated intext_font_context.cpp::font_collection(). Diagnostic: if a registered font renders in rawctx.fillTextcanvas calls but NOT in Labels/section headers, the paragraph bridge is the suspect. - Variable fonts ignored
font-weight. A variable.ttf(Funnel Display:wght300–800 def 300; Clash Grotesk: 200–700 def 700) registers as ONE typeface at its default instance. SkParagraph and the static matcher pick the closest static weight, so e.g. afont-weight:700section header rendered at the 300 default for every weight. Fix:face_wght_axis()detects thewghtaxis;match_registered_typefacetreats a same-slant variable face as eligible past the 200-unit static tolerance; the resolver derives a syntheticwghtvariation from the request (clamped); andfont_collection()pre-bakes onemakeCloneper CSS weight (100–900) under the family alias so the provider's closest-match picks the right instance. Diagnostic: if regular-weight text picks up the font but bold/heavy text stays on the fallback, it's the variable-weight path. Covered by[variable-weight]intest_canvas_fonts.cpp.
The fonts the design uses may not be in the envelope at all. The Figma API does NOT expose font binaries (only family NAMES via _record_font). A REST/plugin export of a design using restricted foundry fonts (Clash Grotesk, Funnel Display) yields font_family_assets with NO asset_id → no registerFont → system fallback. Options: (a) the plugin's drag-drop font escape hatch (user-fonts.ts) lets the user supply the .ttf; (b) obtain the font under permissive terms and stamp it into the bundle (Funnel Display is OFL on Google Fonts; Clash Grotesk is free-for-commercial from Fontshare) — add the file to assets/<sha256>.ttf, a font/ttf manifest entry, and the matching asset_id on each font_family_assets entry. Embed note: the portable-bundle path-resolver preamble (pulp-view-embed) must wrap registerFont (alongside setImageSource/setKnobSpriteStrip) or relative font paths won't resolve against the bundle dir.
REST-port capture rules that mirror the plugin's extract.ts — keep them in sync when the P2/P3 shared extractor lands:
- Audio-widget recognition by name (
widget_kind_from_name): knob/fader/meter/dial/slider/xy-pad/waveform/spectrum nodes are emitted as leafaudio_widgetnodes so the importer renders them NATIVELY (silver knob etc., at the node's own size) — NOT captured as raw image sprites from their internal component-instance vectors (compoundI…;…ids), which renders misplaced fragments. This is what makes non-library designs (ELYSIUM) get real knobs. REGULAR_POLYGONis a vector leaf type. Figma REST reports polygons asREGULAR_POLYGON(the plugin SceneNode API saysPOLYGON). Omitting it makes polygon-based illustrations (ELYSIUM's Pentagon/RANGE shape) fail the pure-vector-illustration test → recurse into partial captures instead of rasterizing whole. Include both spellings.font_family_assetscapture (_record_font): walk TEXT nodes, collect{family, style, weight, italic?}deduped, emit at the envelope root. REST can't fetch an uploaded font's.ttfbinary, soasset_idis omitted and the consumer keeps the family NAME (system fallback) rather than registering a bundled file. Capturing the metadata keeps the REST envelope shape-conformant with the plugin.- sha256
content_hashfor captured PNGs: name + content-address each asset bysha256(bytes)(matches the plugin'sAssetCache), not a node-id placeholder — dedupes identical captures and lets the importer verify bytes.
Detection uses ZIP magic (PK\x03\x04), not the file extension — .zip renames still get unpacked. The temp dir is auto-cleaned at process exit. Older CLI builds read input via std::ifstream text mode and silently truncated at the first NUL byte in the ZIP header; the symptom was parser threw an unknown exception on any .pulp.zip. If you see that error, the CLI predates the auto-unpack support — rebuild from current main.
The extractor refuses hostile archives at parse time: entries whose filename is so long it would truncate inside the stack buffer, entries containing .. substrings, entries that resolve to an absolute path (fs::path::is_absolute()), entries with Windows drive-relative or UNC prefixes (C:foo, C:\\foo, \\\\server\\share\\…), entries beginning with / or \\, archives with more than 10000 entries, and archives whose total or per-file uncompressed size exceeds 256 MB / 64 MB respectively. Each rejection logs a labelled Error: refusing unsafe zip entry (<reason>): <name> (or oversized filename, total uncompressed size > …) on stderr and bails with a non-zero exit. If a legitimate plugin export ever trips one of these caps, the right move is to lift the cap deliberately in extract_pulp_zip_if_present rather than disable the guard.
Measuring import fidelity — tools/import-design/fidelity_diff.py:
Don't eyeball whether an imported+rendered design matches the Figma source — measure it. The fidelity diff harness (stdlib + PIL only) takes the rendered PNG, the scene.pulp.json, the captured asset_ref PNGs, and an optional whole-frame reference, and emits a per-widget pass/fail report against a configurable tolerance (default 15%).
python3 tools/import-design/fidelity_diff.py \
--render <render.png> --scene scene.pulp.json --assets-dir assets/ \
[--frame-reference frame.png] [--out-dir cmp/] [--json report.json] \
[--tolerance 0.15]
Heuristics live in a registry (HEURISTICS) so new ones are cheap to add; each is a small, unit-tested function. Current set: art_bounds (scale-invariant signature-blob aspect + info full_aspect for the housing+fill+thumb extent), declared_geometry (render aspect vs scene style box, reference-normalized so a fader's thin track doesn't false-fail), colors (knob/fader palette nearest-match + meter green→red gradient stops, sampled over matched crops), completeness (every scene text + widget must render; flags MISSING nodes and text that overflows its declared width or is clipped at the panel edge — the no-wrap bug), padding (panel edge → first child gap vs layout.padding; flags content hugging the wall), widget_detail (fader track/housing stroke presence, knob indicator angle vs reference, meter housing + warm→cool gradient ramp), text_style (per-line glyph height = size proxy, stroke density = weight proxy, vs font_size/font_weight), frame_overlay (content-aware whole-frame alignment + similarity + side-by-side + diff heatmap), side_by_side (per-widget comparison PNGs). Exit 0 = within tolerance, 1 = regression.
Trustworthiness gate: feed the original --frame-reference back in as --render — it must score 0 fails. That ground-truth pass is what makes the fails on a real import trustworthy. A faithful importer should converge to that baseline.
Gotchas baked into the tool: (1) the render and the captured asset PNGs are at different canvas scales, so absolute pixels are info-only — pass/fail is on aspect ratio. (2) Widget detection has two layers: the per-kind signature mask (the colored blob — fill-only for fader/meter) for a stable aspect anchor, and detect_full_widget which flood-fills from that anchor through connected foreground (absorbing the dark housing slot + thumb) so the compared crop matches the full reference widget — never compare a fill-only render blob against a housing+fill reference. The full-widget flood-fill is clipped to the declared box so it can't bleed into a neighbour. (3) Whole-frame alignment needs the real panel, not the canvas: detect_panel finds the rounded panel as a dark blob on a light page margin OR (flush dark render) as the border-ring + content box; interior_background samples the modal interior (rounded corners leak the page color, so the corner sampler is wrong for a panel crop). (4) Text detection is bg-relative glyph brightness on the panel crop (not absolute luma over the whole image, which lights up a light page margin); the row-cluster snap takes a prefer_y so a tall search window locks onto the predicted line, not the neighbouring one. (5) indicator_angle is coarse (±~15°) and detects either a dark or light notch; track_stroke is presence-only, not thickness. (6) Large renders are down-scaled to MAX_SCAN_DIM before the pure-Python pixel scans — without this a 1520² render takes minutes. (7) The render PNG is written to the CLI's CWD as <name>-figma plugin export-render.png; --render-size WxH is honored even though the meta JSON keeps the declared canvas. (8) A run where NOTHING measured is SKIPPED, exit 3 — never "OK". Fig-lane scenes hit this shape today (every node is audio_widget: "none", no type == "text" nodes, no root padding), so on that lane the tool has no verdict; do not list it as a passing lens there. summary.ok is false and summary.measured is 0 in the JSON. Regression coverage: test/test_import_fidelity_diff.py (CTest import-fidelity-diff, skips 77 without PIL) with tiny checked-in fixtures under test/fixtures/import-fidelity/, plus synthetic per-heuristic unit tests (panel detection, full-widget vs blob, text overflow/missing, padding hug, indicator angle).
Figma (MCP available):
- Use
com.figma.mcpto read the current file or selection - Extract frames, auto-layout, fills, strokes, effects, text, components
Figma Make runtime-import parser (Phase 6.6.3):
- The runtime-import lane accepts constrained, sanitized Figma Make React exports through
parse_figma_make_react()andsource: 'figma'. It normalizes the TSX file into the same bundle payload shape used by Claude and v0 runtime import. - Accepted input is a single
.tsx/.jsxReact component with explicit Figma provenance, no"use client"directive, React hook imports fromreactonly, and inlinestyle={{ ... }}objects. - Raw Figma Make defaults are intentionally rejected until a preprocessing step exists: unresolved
figma:asset/*imports, versioned import paths like<package>@<semver>, TailwindclassNameutilities, Radix primitives, Code Connect glue files, Next.js wrappers, custom JSX components, non-range inputs, and network/storage/worker APIs. - Representative fixtures live under
planning/fixtures/figma/; the primary one islevel-meter-panel.tsx. Runtools/import-validation/figma-roundtrip.sh --parser-onlyfor the parser/dispatch gate,tools/import-validation/figma-roundtrip.shfor parser-emitted screenshot diff, andtools/import-validation/figma-roundtrip.sh --coveragebefore pushing parser PRs.
Governed validation builds: every tools/import-validation/*-roundtrip.sh build step must invoke tools/ci/governed-build.sh cmake --build; do not add a raw cmake --build, -j, or --parallel flag. The governor owns the host lease and CMAKE_BUILD_PARALLEL_LEVEL, including the external Spectr checkout; keep the existing fixture, target, and artifact behavior unchanged.
Stitch (MCP available):
- Use
mcp__stitch__list_screensto show available screens - Use
mcp__stitch__get_screento read the selected screen - Extract component tree, inline styles, design system tokens
Pencil (MCP available):
- Use
mcp__pencil__get_editor_stateto check current file - Use
mcp__pencil__batch_getto read the node tree - Use
mcp__pencil__get_variablesfor design tokens - Use
mcp__pencil__get_style_guidefor style references
v0 (URL or TSX file):
- If URL provided, fetch the v0 generation
- If TSX file, read directly
- Extract JSX tree, Tailwind classes, shadcn/ui components
DESIGN.md (Google design.md, Apache-2.0):
- DESIGN.md is a design system spec (YAML frontmatter + Markdown body), not a screen export. There is no screen tree to render; output is
tokens.jsononly. - Run
pulp import-design --from designmd --file path/to/DESIGN.md --tokens tokens.json. Noui.jsis written — the dispatch arm skips the codegen step. No bridge scaffold either. - Detection is strict (all-of fingerprint, 95% min-confidence): filename
DESIGN.md+---frontmatter fence +name:key + at least one ofcolors/typography/rounded/spacing/components. Generic Jekyll/Hugo blog posts will not match. - Diagnostics: structured
[severity] code at path (line:col): messageon stderr. Exit codes — 0 OK, 1 usage/write, 2 detect-only no match, 3 parse error (malformed YAML, duplicate##section heading), 4 unsupported. - Format spec pin: tag
0.4.0(paws-and-pathsremains byte-identical, so the fixture is still a valid upstream control). Coverage includes all 0.3 behavior plus 0.4'somittedfrontmatter (bare section names or{section, reason?}objects), unknown typography sub-property warnings, flattened dot/nested token collision errors, and bounded malformed input (20 token levels; 64-character dimension recognition). Pulp preserves CSS color strings rather than evaluating them, so upstream'sgrad/color-mix()evaluator fixes do not require a parallel parser change. Pulp's existing--format css-variablesis the equivalent of upstream's newcss-vars; upstream--prefixis not part of Pulp's import contract. - Markdown body sections are ALWAYS scanned — with or without frontmatter.
parse_designmdreadsname: valuelist items and| name | value |table rows under## Colors(color tokens),## Spacing(spacing-*dims),## Border Radius/## Rounded(rounded-*dims), and## Shadows/## Elevation(shadow-*strings). Frontmatter wins on conflict (compared by normalized name, since frontmatter keys are dot-joined and case-preserving while body keys are lowercased and dash-joined); the body only fills gaps. This used to run only when a doc had no---frontmatter, which meant adding frontmatter to a prose-authored DESIGN.md silently dropped every body token — total and invisible for## Shadows, whose frontmatter key did not exist.shadows:is now a real frontmatter group. Table header/separator rows are skipped by requiring the value cell to be a real color/dimension/shadow. A### Light Mode/### Dark Modesubsection under## Colorsroutes to the bare name (light/default) or a<name>.darksuffix (dark) — the same multi-mode convention the Figma plugin uses (tools/figma-plugin/src/tokens.ts), so dark themes survive into the flat token maps. Emits abody-tokensinfo diagnostic when it recovers any. - See
docs/reference/imports/designmd.mdfor the full reference (supported subset, reference-resolution rules, attribution).
v0.dev runtime-import parser (Phase 6.6.2):
- The runtime-import lane accepts constrained v0 React exports through
parse_v0_dev_react()andsource: 'v0'. It normalizes the artifact into the same bundle payload shape used by Claude runtime import. - Accepted inputs: a bare single-file
.tsx/.jsxReact component, or a v0 code-project envelope containing[V0_FILE]tsx:file="..."blocks. Prefer the explicitsource: 'v0'route; standalone TSX has no reliable v0-only marker. - C-1 deliberately rejects default v0 surfaces that are outside the supported matrix: Tailwind
classNameoutput, shadcn/Radix components, Next.js wrappers/imports, custom JSX components, non-range inputs, and network/storage/worker APIs. Use inline Reactstyleobjects plus the supported DOM/CSS/API subset. - Representative fixtures live under
planning/fixtures/v0-dev/; the primary one isaudio-control-panel.tsx(audio control panel + canvas meter). Runtools/import-validation/v0-roundtrip.sh --parser-onlyfor the parser/dispatch gate.
Google Stitch runtime-import parser (Phase 6.6.4):
- The runtime-import lane accepts constrained Stitch React exports through
parse_stitch_react()andsource: 'stitch'. Stitch has no reliable standalone file marker, so do not auto-detect arbitrary TSX as Stitch. - Accepted input is a single-component React TSX module from Stitch's vanilla/inline-style export path. The default Tailwind export is out of scope until the shared Tailwind-to-inline-style preprocessor exists.
- C-3 deliberately rejects Tailwind
className, external CSS imports, Next.js wrappers or"use client", Radix/shadcn components, React Native imports, Stitch MCP JSON node trees, custom JSX components, non-range inputs, and network/storage/worker APIs. - Representative fixtures live under
planning/fixtures/stitch/; the primary one istransport-bar.tsx(transport controls + range sliders + canvas VU meter). Runtools/import-validation/stitch-roundtrip.sh --parser-onlyfor the parser/dispatch gate.
JSX-instrument runtime-import (experiment slice, 2026-05-17, planning/2026-05-17-jsx-instrument-import.md):
- Unlike v0/figma/stitch, the
jsxsource is NOT a synthetic shape-counter — it executes the user's real React tree.parse_jsx_react(bundle_js, component_name)wraps a pre-compiled IIFE bundle (esbuild output of React plus either ReactDOM or the @pulp/react native bridge + user JSX + nav/document sandbox shims) as a syntheticClaudeBundle, then the existingparse_claude_html_with_runtimeharness materializes it into aDesignIRvia DOM walking or the nativeWidgetBridgesnapshot fallback. Per Codex/RepoPrompt review: custom inline-defined components (knobs, faders, etc.) materialize as their underlying SVG primitives — DO NOT widget-promote them to native<Knob>/<Fader>, which would lose visual parity with the source JSX. - The JSX→JS compile happens in Node, not in the C++ runtime. Run
tools/import-design/jsx-runtime/jsx-transform.mjs --in <file>.jsx --out <out>.jsto produce the IIFE bundle. The script ships its ownnode_modules(React 18.3.1 + ReactDOM 18.3.1 + react-reconciler 0.29.2 + scheduler 0.23.2 + esbuild 0.24.0 +@babel/parser7.29.7 +css-tree3.2.1) attools/import-design/jsx-runtime/node_modules/. First-runnpm installis required. - For native-import validation, run
tools/import-design/jsx-runtime/jsx-contract-audit.mjs --in <file>.jsx --json <audit.json> --fail-on-weak-proofbefore relying on visual screenshots. Shape should come from the source contract, not from visual inference: the audit extracts JSX structure, props, style semantics, SVG/vector geometry,.map()rows, and handler closures so the importer can normalize those into Pulp-native attributes. Keep the live runtime fallback whenever the source contract is too dynamic. - Current Chainer/native bundles route
react-domthroughpulp-react-dom-shim.mjsand@pulp/react. The live lane writes that bundle verbatim. The baked lane first tries the DOM walker; when the bundle renders native views instead of DOM nodes, it freezes theWidgetBridgetree into DesignIR withcapture_method = runtime_native_snapshotandsnapshotSource = native-view, then can emit baked C++ from that IR. - Supported input today: single-file
.jsxor.tsx, default-exported React function component, hooks fromreactonly, inlinestyle={{...}}objects, SVG primitives (svg/path/circle/line),<input>/<button>form elements (text-input editing is degraded — plain text inputs fall back to a non-editable View per Codex review),setInterval/requestAnimationFrame/getBoundingClientRect. The TypeScript path strips TSX through the Node/esbuild transform before the C++ runtime parser sees the bundle. - Out of scope until follow-up PRs: window-level
mousemove/mouseupglobal fan-out (the canonical 2-week gotcha; static render works, interactive drag does not), viewport resize signaling (window.innerWidth/innerHeighthard-coded), screenshot-similarity acceptance gate (timers/random would need freezing for determinism), Babel-standalone embedding (replaces the Node shell-out). - End-to-end harness:
tools/import-validation/jsx-roundtrip.shruns the transform + builds + runs the smoke test (pulp-test-design-import-jsx-runtime— asserts >9 IR nodes + Chainer-shaped text materializes) + optionally renders apulp-screenshotPNG. Primary fixtures:planning/fixtures/jsx/chainer-instrument.jsx(762-line Chainer instrument with 9 inline custom components, SVG, drag, setInterval) andplanning/fixtures/jsx/typed-control.tsxfor TSX stripping. - The bundle's banner-installed shim is critical: ES module imports get hoisted to the top of esbuild's IIFE body, so the navigator/document/HTML*Element ctor shims MUST be emitted as an esbuild
banner(which is literally prepended outside the IIFE) — not inline in the entry source. Without that, React-DOM's DevTools UA sniff (navigator.userAgent.indexOf("Chrome")) crashes during module init. Mirrors the pre-payload shim block inrun_claude_bundle_payload_pipeline(design_import.cpp:1494).
React Native runtime-import parser (Phase 6.6.5):
- The runtime-import lane accepts constrained single-file RN component exports through
parse_react_native_export()andsource: 'rn'. The importfrom 'react-native'is unambiguous, so runtime dispatch may auto-detect RN when the source label is omitted. - Accepted input is a single TSX component with React imports from
react, RN imports fromreact-native, RN element vocabulary (View,Text,Pressable/Touchable*,ScrollView,TextInput), andStyleSheet.create({...})styles. Numeric RN style values are treated as CSS pixels. - C-4 deliberately rejects native/device APIs and wrappers outside the matrix:
Animated, Reanimated, Linking, Alert, AsyncStorage, Dimensions/Platform branching, Modal, virtualized lists, navigation, Expo modules,NativeModules,requireNativeComponent, image sources, DOM tags, and array-form styles. - RN defaults
flexDirectionto column; the parser-emitted bundle preserves that by injecting column flex semantics into the normalized DOM surface. Representative fixtures live underplanning/fixtures/rn/; the primary one isgain-stage.tsx. Runtools/import-validation/rn-roundtrip.sh --parser-onlyfor the parser/dispatch gate,tools/import-validation/rn-roundtrip.shfor parser-emitted screenshot diff, andtools/import-validation/rn-roundtrip.sh --coveragebefore pushing parser PRs.
Pencil runtime-import parser (Phase 6.6.6):
- The runtime-import lane accepts constrained Pencil/OpenPencil React exports through
parse_pencil_react()andsource: 'pencil'. Pencil has no reliable standalone file marker, so do not auto-detect arbitrary TSX as Pencil. - Accepted input is the sanitized post-preprocessor form of Pencil's Tailwind JSX export: a single React component with Tailwind classes expanded to inline
styleobjects and--pencil-*tokens resolved to literals. The MCP JSON node-tree path stays with the offline Pencil adapter and is not a runtime-import source parser. - C-5 deliberately rejects Tailwind
className, unresolved--pencil-*token references, MCP JSON envelopes,.pen/.figbinary references, external CSS imports, Next.js wrappers or"use client", Radix/shadcn components, React Native imports, custom JSX components, non-range inputs, and network/storage/worker APIs. - Representative fixtures live under
planning/fixtures/pencil/; the primary one isgain-stage-card.tsx(gain slider + canvas level meter + bypass). Runtools/import-validation/pencil-roundtrip.sh --parser-onlyfor the parser/dispatch gate,tools/import-validation/pencil-roundtrip.shfor parser-emitted screenshot diff, andtools/import-validation/pencil-roundtrip.sh --coveragebefore pushing parser PRs.
Claude Design (manual HTML export):
- Anthropic Labs has no MCP / public API. The user runs Claude Design, exports the canvas as Standalone HTML (or "Send to Local Coding Agent"), and hands you the resulting file.
- Run
pulp import-design --file <path>. No--from,--execute-bundle, or
export-shape incantation is needed. Pulp distinguishes project bundles,
design components, standalone bundles, and generic HTML for diagnostics, but
all runnable HTML uses the same authoritative Chromium evaluator.
- When the runnable page's first occupying body child is the authored panel,
agents may call pulp import-design --file <path> --fit-authored-frame
directly. import-design has no MCP command surface; the CLI is the supported
agent route. The opt-in derives a bounded viewport, reloads the same Chromium
target exactly once, and accepts only a contained authored-frame fixed point.
It is mutually exclusive with an explicit --render-size,
--browser-interactions, and --offline; non-browser inputs and non-import
command modes are rejected. If the root is absent, changes after reload, or is
not contained, the importer refuses safely with
capture-authored-frame-unavailable,
capture-authored-viewport-nonconvergent, or
capture-authored-frame-not-contained; rerun without the flag to use the
existing viewport workflow rather than accepting ambiguous pixels.
- Chromium captures the settled visual at DPR 2, CSS custom-property tokens,
semantic candidates, and provenance. The portable DesignIR uses the captured
visual as a faithful_capture backing and Pulp immediately renders it through
Skia for browser-vs-DesignIR A/B validation. That proof is a required adoption
gate even without --validate; the flag additionally publishes convenient
render/diff copies beside the primary output. Authored controls and knob art
remain pixels; never replace them with Pulp's silver/vector fallback.
- For dynamic or materialized canvas fixtures, add
--materialized-canvas-composition --require-canvas-ink when a blank frame
would invalidate the result. The opt-in gate inspects the decoded,
hash-verified sparse canvas plane rather than trusting changed_pixels
metadata. It requires at least 256 opaque canvas pixels and a viewport
relative floor of 0.1%, so transparent captures or isolated specks cannot
produce a false 100% A/B score. Opaque pixels are counted regardless of RGB
brightness, so a legitimately dark canvas still satisfies the coverage
contract. Keep the flag off for intentionally blank static panels. A passing
pixel score without this gate does not prove that an animated canvas actually
painted its graph.
- External browser requests are denied by default. If the export depends on a
CDN runtime and the health gate reports capture-source-unresolved, review
the listed URLs and retry with --allow-browser-network. The opt-in permits
only public HTTPS origins declared by the source; private/local destinations,
WebSockets, and undeclared redirects remain blocked, and successful response
content is hashed into capture provenance. Local relative assets are served
from the input folder without this opt-in.
- If authored async initialization has a real completion boundary, the page
may expose globalThis.__pulpCaptureReady as a Promise or function returning
one. Capture awaits it and fails on rejection. Do not add arbitrary sleeps.
- If the requested screen is not the landing state, pass
--browser-interactions <plan.json>. The
pulp-browser-interactions-v1 plan accepts only bounded click,
context-click, type, wait-for, and wait-ms actions. context-click
uses a real secondary-button gesture. End navigation sequences with
wait-for on a visible selector; strings in hidden/inert DOM or bundled
script source do not prove which screen rendered. Capture records action
results and typed-text length without retaining the text or a per-action
text hash in the interaction report. Typed text remains live rendered state
and may appear in screenshot, DOM/semantic, or token evidence, so never put
passwords, credentials, private drafts, or other secrets in a plan. Popup
pages are rejected. For a distinct post-action asynchronous completion
boundary, expose globalThis.__pulpInteractionReady; capture awaits it after
the plan without calling the initial __pulpCaptureReady contract twice.
Never add an arbitrary JavaScript action.
- If Chrome/Chromium is missing, install it from the URL printed by the CLI or
pass --browser <path>. --offline explicitly selects the legacy partial
static/QuickJS fallback. Chrome and Node are import-time tools only; generated
plugins do not embed or require either one.
- Never read pixels with virtual time paused. `Emulation.setVirtualTimePolicy
{policy:"pause"}` suppresses the compositor's BeginFrame source, and Chromium's
screenshot path waits for a fresh presented frame. From Chrome 151 the first
Page.captureScreenshot after a pause still resolves — captureBeyondViewport
resizes the capture surface and forces one commit — and every call after it
hangs forever. That is why settle.mjs pauses virtual time for the DOM,
semantics, token, and health reads and then calls resumeDynamicTime before
the screenshot loop. Determinism does not rest on the pause: tracked
timers/intervals/rAFs are cancelled, the schedulers are stubbed, CSS animation
and transition are disabled, and captureStableScreenshot requires a
byte-identical trailing run as the observable proof of stillness.
- Web Animations and video are frozen before the frame is read. The
motion stylesheet and scheduler stubs cannot reach element.animate() or a
playing <video>; both run on the document clock. freezeMotion
(settle.mjs) runs before every page-settle sample (waitForStable's
beforeSample), because a Web Animation that moves a box would otherwise
keep the layout from ever settling, even one a late timer or font load
starts mid-settle, and once more after every settle and before the
materialized document and the screenshot horizon. Each pass
settles only what an earlier one did not, or what the page restarted, and
counts each animation and video once: a finite Web Animation is finish()ed (its
resting frame), an infinite or unresolved one is paused at currentTime 0
and then committed and cancelled (commitStyles() writes the time-zero
values inline, cancel() drops the animation). A browser at its real device
scale kept presenting a merely paused composited animation mid-cycle while
the page read time zero, and nothing is left to hold once it is cancelled.
The page's own reference becomes idle, and restarting it is settled again.
A button, input, textarea, select or progress target is only
paused: the form-control theme check counts inline styling as author
styling, so committing would flip a theme-painted control to author-styled.
Under the real-scale launch it can still show the mid-cycle frame. So is a
target whose inline style declares an animated property !important:
committing would rewrite that declaration at normal priority.
A video is paused and rewound to its first frame unless it still shows
its poster. CSS animations and transitions stay on the stylesheet path, and
scroll- or view-driven animations are left to the fixed scroll position. An
animated GIF, APNG or WebP runs on the decoder's clock, so it is left alone
and listed in provenance.motion.volatile_sources (classified from its own
bytes by animatedImageKind, in the last pass only), next to the per-kind
counts. A page that
throws inside the freeze fails with capture-motion-freeze-failed.
- Browser discovery has a version FLOOR and no ceiling.
kMinimumChromiumMajor = 109 (browser_capture_backend.hpp) is the only
version comparison in the probe — nothing rejects a browser for being too
new, so a discovery failure on a current Chrome is never a version-range
problem. Selection order is --browser → PULP_DESIGN_BROWSER → managed
(~/.pulp/tools/chrome-for-testing: the release's chrome-headless-shell
via headless-shell.json, then the browser via current.json) → system
paths, and the default auto mode prefers the pinned browser over a system
one. The shell is accepted only when its record names the release and
platform current.json names, and only from <platform>-headless-shell/.
- Prefer the headless shell on a shared desktop. The full Chrome for
Testing binary connects to the window server even with --headless=new;
on m5s it intermittently hung (--dump-dom of a 127.0.0.1 page never
returned) while chrome-headless-shell of the same release answered in a
second, sandboxed or not. The `bootstrap_look_up
...MachPortRendezvousServer.1: Permission denied (1100)` line it prints is a
helper outliving its parent at teardown; it appears in passing runs too and
is not the cause. The CDP product of the shell is HeadlessChrome, which the
probe and the capture both report, so the identity check stays consistent.
launchBrowser() passes --headless=new only to the full browser
(headlessModeArguments()).
pulp config set import_design.browser {auto,managed,system} picks the mode;
managed-browser-unavailable fires only when managed is selected
explicitly and nothing is installed.
- A capability-probe failure names its own reason in the headline.
browser-capability-unavailable covers both a probe that ran out of time
("timed out after <N> ms") and a browser that lacks a capability (the
probe's stderr). The reason leads the first line because callers keep only
the start of the message: Forge's HTML import cuts it at 600 characters, which
once hid the reason inside the Checked list. The probe deadline is
probe_timeout_ms (15 s); production callers apply
probe_timeout_from_environment(), so PULP_DESIGN_BROWSER_PROBE_TIMEOUT_MS
raises it on a loaded CI host without touching the capture budget.
- The Node capture tests share the C++ order only in part.
browser_capture/capture_integration_support.mjs carries its own
installedBrowser() resolver, the only browser resolution in the repository
written in JavaScript. Its order is PULP_DESIGN_BROWSER, then (under GitHub
Actions) nothing, so a lane that did not provision the pinned build skips the
real-browser cases instead of launching the runner image's Chrome; then the
legacy PULP_BROWSER, then the managed install (managedHeadlessShell()
then managedBrowser(), the same record containment rules as
managed_headless_shell and managed_current_browser), then
hardcoded system paths. It does not read import_design.browser modes. On a
developer host, run pulp tool install chrome-for-testing once: until then
every local run of these suites, and every host-side pulp import-design,
launches the mutable system Chrome (on m3 that was 32 launches in a day, each
leaving a code-sign clone under /var/folders/.../X). The macOS gate
provisions differently: it downloads a checksum-pinned Chrome for Testing and
publishes PULP_DESIGN_BROWSER to $GITHUB_ENV for the
pulp-browser-capture-node-integration ctest. When you add a browser-driven
.mjs test, call installedBrowser() rather than growing a second candidate
list, and remember that on a host with no browser the cost of getting this
wrong is a silent skip rather than a failure.
- **Real-browser cases live in
*.integration.test.mjsfiles, and they run
concurrently.** The ctest pulp-browser-capture-node-integration is
RUN_SERIAL with the browser RESOURCE_LOCK and the suite's highest COST,
so ctest starts it first, alone, while every slot is free, instead of at the
end of the gate's test step. Do not trade that isolation for a partial slot
reservation: run two Chromes beside other tests (PROCESSORS 4) and browser
launches timed out or were killed before the guardian took custody
(browser child exited (SIGTERM)) in 4 of 20 merge groups on 6- and 12-vCPU
VMs, against none in 77 runs alone. The scheduling class lives in
tools/scripts/ctest_scheduling_policy.py (SERIAL_FIRST_TESTS); any other
test that launches a real Chrome must take the same browser lock. It runs
every *.integration.test.mjs file through
browser_capture/run_integration.mjs, which calls node --test with a file
concurrency of one Chrome per two cores and per 2 GiB of a declared memory
lease, capped by the file count: 1 on m1's 3-vCPU VM, 3 on m5's 6-vCPU VM,
6 on the Studio's 12-vCPU VM. Node runs the cases within one file in
sequence, so the files are the unit of parallelism: each case mostly waits on
a cold Chrome launch, so files overlap well inside the serial slot on a large
VM. On m1 a fixed width of 3 made every capture time out
(stalled=Page.captureScreenshot) and failed every merge group that landed
there, while m3 and m5 passed. The width is read when the suite runs
(TARTCI_GUEST_CORES / TARTCI_GUEST_MEM_MB, else
os.availableParallelism()), never at configure time. The six files are
split by theme (capture, paint, interactions, interaction guards, geometry,
frame fitting) and balanced near a minute each serially; the slowest file
bounds the wide run, so add a new case to a short file of the same theme
rather than to the longest. A new integration file is picked up by the glob
and excluded from the unit aggregate automatically.
- The per-case cost is the capture's own fidelity work, not test overhead.
A trivial page takes ~7.5 s: captureStableScreenshot always observes its
full 32-frame horizon (an early A,A plateau must not hide a later B,B
presentation) at ~50 ms per frame of headless software-compositing pacing,
once per pixel artifact that differs from the accepted frame, plus settle,
launch and shutdown. Shutdown used to be a fixed ~1.5 s: the custody anchor
ignores SIGTERM by design, so the group never empties on its own and the
guardian waited out its whole grace window before SIGKILL even after
Chromium's processes had exited, about 200 ms in. The grace now ends once the
group's leader is its only member (processGroupHasMembersBesidesLeader,
/bin/ps); a helper that ignores SIGTERM still gets the full window, and an
unreadable or capped listing waits as before. It used to take ~12 s because every bounded teardown
wait was Promise.race([p, delay(ms)]): the losing timer stayed armed and
held the capture process open for the rest of a 6 s bound after cleanup had
finished. Bound a wait with waitAtMost (browser_process.mjs), which clears
its timer, never with a bare delay race; browser_process.test.mjs times an
owner's exit after teardown to catch a regression. A plate that hides paint
(indicators, canvases) needs its own horizon only when something was hidden:
captureStableFrameWithHiddenPaint (settle.mjs) reuses the accepted bytes
when the page reports zero hidden elements. Before it, a canvas-free panel
re-proved an identical frame for its chrome plate, so every capture paid two
horizons (64 frames); on a loaded gate VM those frames stretch to several
hundred ms each, and the repeat alone ran the capture past its deadline in the
same-frame-capture phase. A new hidden-paint plate goes through that helper.
- Only a horizon's decisive frames carry the caller's encoding. The verdict
and the shipped bytes depend on the last STABLE_RUN_FRAMES (3) of
SCREENSHOT_HORIZON_FRAMES (32) frames alone, so the 29 before them are
taken as quality-1 JPEG with the caller's clip, captureBeyondViewport and
fromSurface untouched; they still wait for a fresh presentation each. Keep
the stable run equal to the decisive frame count, or a presentation frame
could extend the run that decides. A capture whose motion receipt lists an
animated image (volatile_sources) takes every frame in the caller's
encoding (horizonPresentationEncoding), because that image runs on the
decoder's wall clock and a faster horizon would move when the decisive
frames land; provenance.motion.horizon_presentation_format records which.
- Integration deadlines come from
capture_integration_support.mjs. Every
capture in the *.integration.test.mjs files runs under
CAPTURE_DEADLINE_MS (30 s), and each case's node:test timeout is
captureCaseTimeout(captures), which leaves room for Node start-up and
teardown beyond the capture deadlines. Do not hand-write --timeout-ms or a
case timeout in a new case: the old per-case literals (15 s capture inside a
20 s case) failed merge groups on the pinned Chrome for Testing with
browser-capture-timeout ... stalled=Page.captureScreenshot whenever the
gate VM's host was busy, and a case timeout at or below its capture deadline
surfaced as a bare test timed out after 20000ms that names no phase. The
guardian's custody wait is the same lesson in the product: a fixed budget
(1.5 s, then 5 s) was missed by a loaded VM and tore down a healthy launch
(guardian did not establish custody: browser child exited (SIGTERM) or
...: DevTools listening on ... -- the SIGTERM is the teardown, not the
cause). The wait fails at once if the guardian exits, so it now shares the
launch's own deadline (guardianCustodyTimeoutMs, never below
GUARDIAN_CUSTODY_MIN_TIMEOUT_MS). Do not reintroduce a fixed short timer
there.
--disable-frame-rate-limit --disable-gpu-vsync cut frames to ~5 ms but only
~15% of suite time, raised CPU ~60%, and would shrink the horizon's wall-clock
span for every real import, so it is not used.
- "Could not read the version" is not "wrong version". Reading
--version
has been observed to fail once and then succeed moments later on the same
browser, and it used to surface as "too old or incompatible" — a message that
sends you hunting for a version range that does not exist. The probe now
retries the read once, classifies a persistent failure as
browser-version-unreadable (distinct from browser-incompatible), and
records the exit code, attempt number, and elapsed time so a recurrence
explains itself. CPU load is NOT the cause: --version measures ~70-80 ms
idle and under saturation against a 15 s budget.
- A capture that hangs is a single unresolved CDP call, not a slow loop.
Every settle loop is bounded to seconds, so a multi-minute stall can only be
one awaited call. Diagnose by timestamping cdp.call start/resolve to stderr
and diffing the last line printed between two Chrome versions on one machine —
do not theorize from the code. The capture runtime now reports the phase, the
last completed browser call, and the calls still in flight when its deadline
expires, and writes the resolved browser build to stderr as a
[browser-capture] line before any page work, so a failed capture already
names both the Chrome and the stalled call.
- Prove a capture deadline reaped the BROWSER, not just the profile.
Removing the profile directory is the easy half, and it is the half a cleanup
test naturally asserts. The launched Chromium is a detached process group,
so it survives the runtime's process.exit and is re-parented to init, where
nothing will ever reap it — a green "profile removed" assertion sits happily
on top of a permanent leak. Cleanup that fires mid-launch is the sharp case:
the ownership marker lives inside the profile, so removing the profile
guarantees custody is never recorded, and any teardown gated on recorded
custody degrades to a silent no-op exactly when it is needed. Two rules
follow. A launch abandoned before custody exists must still be terminated
through the live child handle: while the handle is unreaped POSIX will not
reuse that pid, and since a group's id is its leader's pid, no other group can
come to bear the number either — which is what makes kill(-pid) safe there,
with no await permitted between the exitCode check and the signal. And the
test must assert the process is gone, not the directory: sample ps with
a positive control in the same sample, because BSD pgrep -fc prints 0 both
when nothing matched and when the pattern was wrong, and the second one reads
exactly like a pass.
- The launch-identity check needs a deadline, not a single probe.
startBrowserGuardian refuses to guard a pid until /bin/ps shows it owning
this capture's --user-data-dir, which is right: a numeric pid is not an
identity. But a just-spawned pid does not identify as the browser yet. Two
windows produce a false violation. Between fork and exec the pid still
carries the launcher's own argv, which owns no profile. And the ps helper
kills its own read at 3s and returns an empty string, which on a saturated
runner is reported as a mismatch rather than as an unread. Both render the
same message, browser launch identity did not match its owned profile,
wrapped in advice to install a browser that is already installed — and both
eject a PR from the merge queue with a red required macos. Probe to a
deadline (resolveOwnedBrowserIdentity) instead: keep failing closed, abort
at once when the child has exited, and say which of the two happened. A test
for this must make the pre-exec argv genuinely not own the profile —
sh -c '... --user-data-dir=X ...' carries the string in its own argv, so
identityOwnsProfile matches before any exec and the race is never exercised.
- The semantic report is evidence, not permission to promote visual controls.
Only explicit source contracts such as data-pulp-role may become native
interaction overlays in a later stage.
Inline <script> evaluation in --execute-bundle: The harness evaluates inline <script type="text/javascript"> (and untyped <script>) blocks AFTER the src-loaded payloads, then compiles + evaluates inline <script type="text/babel"> (and text/jsx) blocks via the bundle's own Babel-standalone (looked up as globalThis.Babel.transform). After both, the harness dispatches a readystatechange → DOMContentLoaded → readystatechange(complete) → window.load sequence and pumps four message-loop / frame-callback cycles for async settling. This is what makes a real Spectr-style Claude bundle (where the actual React app lives in inline text/babel blocks, not src-loaded payloads) materialize beyond the 9-element shell. Per-script soft-fail matches the existing src-loaded payload pattern. Inline application/json (and other */json) blocks are intentionally skipped — they're config blobs, not executable code.
Inline-bundle implementation gotchas:
core/view/js/web-compat.js'sdocumentis a plain object literal (not anElement), so it ships withoutaddEventListener/dispatchEvent. The Step 3 dispatcher constructs events defensively — usesnew Event(t)when available, falls back to{type, target, bubbles:false, preventDefault, stop*}literal otherwise — but bundles that calldocument.addEventListener('DOMContentLoaded', ...)only fire if the bundle (or some library it loads) installsaddEventListener/dispatchEventondocument/windowfirst. Real React-DOM does not do this — it attaches to therootelement it controls — so the DCL dispatch is a best-effort safety net, not a guarantee. See testDOMContentLoaded dispatch runs the queued handler when document supports itintest/test_design_import_inline_babel.cppfor the exact shim shape that satisfies the contract.- The harness's
error_outis the fallback reason (or empty on success). Don't piggyback diagnostic warnings on it from inside the harness; on success the harness clears the slot. If you need to surface a warning that survives a successful run, push it through a different channel (e.g. add awarningsvector toClaudeRuntimeOptions). - Empty
<span>(and other text-mapped tags:p,label,h1-h6,a,strong,em,small,code) get filtered out by the text-empty pruning injson_to_ir_node. If a fixture or test relies on observing an empty<span>with attributes round-tripping through the IR, use a<div>instead — divs map toframeand survive the prune. - Babel-standalone's loaded test: probe
typeof globalThis.Babel.transform === 'function'rather thantypeof Babel. Some bundles installBabelas a sentinel object before the real implementation arrives, which would false-positive on the looser check.
@pulp/react bundle dedup: when emitting React+@pulp/react consumer bundles (Spectr et al.), the consumer's bundler MUST be able to dedup React across the @pulp/react boundary. This means @pulp/react's published dist/index.mjs must externalize react, react-reconciler, react-reconciler/constants.js, and scheduler — otherwise esbuild emits TWO independent React module instances (one for user code, one for the reconciler) and ReactCurrentDispatcher.current desyncs at first commit, manifesting as "cannot read property 'useState' of null" inside the user's App(). The fix is a 1-line addition to packages/pulp-react/package.json's build script: --external:react --external:react-reconciler --external:react-reconciler/constants.js --external:scheduler. This must hold for any future package emitted from pulp import-design that pulls in @pulp/react.
Spectr's <svg><path> doesn't auto-route to <SvgPath>: Pulp v0.69.2+ ships an <SvgPath> JSX intrinsic that maps to the C++ SvgPathWidget shipped in v0.61.0 (#965/#991). However, plugin bundles emitted from Claude-Design exports (and similar) ship raw <svg><path/></svg> markup, not <SvgPath>. There's no automatic shim — the dom-adapter (or a future pulp import-design post-process) must rewrite <svg> → <SvgPath> for inline-icon use cases. Track plugin-side adoption when bumping SDK pin past v0.69.2. <!-- docs-noise-lint: skip — retained version provenance for SvgPath rollout -->
SDK-version drift can close audit symptoms automatically: segmented-control vertical stacking is closed by display:flex defaulting to flex-direction:row; FilterBank canvas is auto-resolved in current SDKs; App-root layout-bottom-strip is closed by the same flex-direction default; click-bubble dispatch is also handled in current SDKs. When auditing a freshly-imported plugin against an older SDK reference, run the WebView↔Native side-by-side at idle FIRST — many "broken" rows resolve via SDK upgrade alone with zero plugin-side work. Pattern documented in spectr/planning/audit-2026-05-03-webview-vs-native-v0.69.1.md.
JS string-literal escaping for emitted user text: when core/view/src/design_import.cpp emits user-supplied text into single-quoted JS literals (createLabel('...'), var.textContent = '...'), the text MUST go through js_single_quote_escape() — newlines, single quotes, and backslashes leak through otherwise and pulp-screenshot crashes with "unexpected end of string" at JS eval time. The helper sits next to the existing v0_html_attr_escape() and covers the six emission sites that take arbitrary text: four createLabel(text) calls in the audio-widget column path, the generic text-node createLabel(text_content), and the web-compat var.textContent = '...' line. Pinned by [issue-81] in test/test_design_import.cpp, which asserts both the absence of unescaped patterns AND the parity of unescaped single-quote counts on every emitted createLabel line. If you add a new emission site that takes user-supplied text, route it through js_single_quote_escape() AND extend the test.
File-based fallback:
- Read the file and parse based on --from source type
Source-Contracts Registry
Pulp keeps a permissive, machine-checkable source-contract registry at
tools/import-validation/source-contracts.json. It records each provider's
upstream anchors, runtime/static parser symbols, fixture paths, roundtrip
script, test tags, MCP lane, and minimum runtime surface references. This file
does not replace compat.json: compat.json still owns detection fingerprints,
parser-version, format-version, and compat-schema-version.
Run the warn-only checker after changing import parsers, source fixtures, or
roundtrip scripts:
python3 tools/import-validation/check-source-contracts.py
python3 tools/import-validation/check-source-contracts.py --format markdown
python3 -m pytest tools/import-validation/test_source_contracts.py -v
Each entry's verification_note records what a recheck actually ran: the
tests that passed, which roundtrip scripts, upstream URL rechecks and reference
screenshots were not run, and the date. Move last_verified only together with
a note that names its evidence; an entry you cannot evidence stays stale.
The checker takes --today YYYY-MM-DD. Any test that runs it as a subprocess against
a hard-coded last_verified must pass a fixed --today; otherwise the case flips from
"due" to "overdue" on the real clock and fails every PR (it did on 2026-11-13).
When cleaning Catch2 tags in source-contract test files, update the matching
validation.test_tags entry in source-contracts.json in the same change.
Scheduled provider recheck dates are advisory: an overdue
stale-source-contract finding is reported as informational and does not make
the strict registry check fail. Keep strict failures for an unverified or
malformed contract and for schema, parser, path, referential, or roundtrip
drift. A recheck due within --warn-days (default 7) is reported ahead of
time as source-contract-recheck-due, and under GitHub Actions both cadence
findings are also printed as ::warning annotations, so an upcoming or
overdue recheck shows on every pull request without failing any check on a
date alone. The warning is the prompt to do the recheck (re-run the parser and
runtime-import tests for that source, then record the result); never rewrite
last_verified dates to silence cadence reminders; verify the behavior with
the focused source-contract self-tests.
Prefer broad stable tags such as [view][import][designmd] when the registry row
represents a full validation surface; do not narrow it to one subarea tag if the
roundtrip/contract expects parser, lint, diff, export, and recovery coverage.
The checker also enforces coverage symmetry between
parse_design_source() labels and the registry. When adding a source label
such as jsx, add a matching row to source-contracts.json and reference
its roundtrip script there; otherwise pre-push will fail strict
source-contract validation.
parser.runtime_file — runtime parsers extracted out of design_import.cpp.
Each contract's parser block has a single file plus runtime/static
symbol names. After the P6-A3 refactor the runtime parsers
(parse_*_react, parse_claude_html_with_runtime, parse_react_native_export)
moved into core/view/src/claude_bundle.cpp while the static parsers stayed
in design_import.cpp. A single parser.file can no longer locate both, so
contracts whose runtime parser lives elsewhere set the optional
parser.runtime_file. The Phase 7 follow-up split claude_bundle.cpp again:
the per-design-tool source-detection families and their five public
parse_*_react entry points (parse_v0_dev_react, parse_figma_make_react,
parse_stitch_react, parse_react_native_export, parse_pencil_react) now
live in core/view/src/claude_bundle_sources.cpp; only parse_jsx_react and
parse_claude_html_with_runtime stayed in claude_bundle.cpp. So a contract's
runtime_file is now claude_bundle_sources.cpp for those five and
claude_bundle.cpp for the JSX/Claude-HTML pair. The checker
resolves parser.runtime and the explicit-runtime-parser dispatch symbol
against runtime_file (falling back to parser.file); parser.static always
resolves against parser.file. **If a future refactor moves a parser symbol
to a new file, update parser.file / parser.runtime_file in the same PR** —
otherwise the Source-contract registry check step fails for every PR.
Provider MCP lanes are input-acquisition lanes only unless the source contract
explicitly says otherwise. Current runtime parsers reject raw Figma/Stitch/Pencil
MCP JSON and accept only their constrained exported artifacts.
Where the runtime-import-dispatch tests live (2026-05-17 P5-1 split):
the WidgetBridge::install_runtime_import_handlers tests for Figma /
Stitch / v0 / Pencil / RN were moved out of test/test_widget_bridge.cpp
into a sibling test/test_widget_bridge_runtime_import.cpp so the 14k-line
god-test file can shrink toward per-surface modules. Both files are
listed in source-contracts.json's per-source test_files arrays, and
both targets (pulp-test-widget-bridge and
pulp-test-widget-bridge-runtime-import) are registered in
test_targets. When adding a new runtime-import dispatch test, place
it in the runtime-import sibling — keeping the parent file shrinking.
Two distinct "source-contract" subjects — don't conflate them
There are two unrelated things called "source-contract" under
tools/import-validation/:
- Source-PROVIDER registry (
source-contracts.json, the section above)
— Claude/Figma/Stitch/v0/Pencil trust metadata: parser symbols, fixtures,
roundtrip scripts. Per provider.
- Per-NODE source-contract evidence — the route/value/event/state/style
evidence about a single imported design's nodes. Two emitters historically
inferred this independently and could disagree: the C++ importer
(source_contract_overlay.node_route_rows on a route manifest) and the JS
audit (jsx-contract-audit.mjs → inputs.sourceAuditSummary). The
consumers are tools/scripts/frontend_ir_routes.py
(route_rows/row_node_id/route_counts/primitive_counts) and
tools/scripts/frontend_ir_sources.py (count_map/source_spans).
For (2), importer and audit output share one serialized shape that can be
validated against a single definition in tests:
- Schema:
tools/import-validation/schemas/source-contract-v0.schema.json
(pulp-source-contract-v0, draft-2020-12). Lives in the public repo (not
planning/schemas/) so Python, JS, and C++ can all reach one definition.
It pins the node_route_row field set and the audit materiality counts
block; both deliberately keep additionalProperties permissive so existing
C++/JS emission is unchanged.
- Golden fixtures + conformance test:
tools/import-validation/fixtures/source-contract-v0/ and
tools/import-validation/test_source_contract_schema.py. The test runs an
importer overlay and an audit summary through the real frontend-IR
consumers and asserts they agree on the shared golden-expectations.json
counts (the "two inference models can't disagree" proof). stdlib only — no
jsonschema dependency; a small validator interprets the keyword subset in
the frontend_ir_validation.py style.
The legacy inline sourceAuditSummary compat field stays in place; it is the
audit-side input the schema validates, not something to remove in this slice.
Step 3: Translate to Pulp code
Use the appropriate mapping document as your translation reference:
planning/figma-to-pulp-mapping.mdfor Figma designsplanning/stitch-to-pulp-mapping.mdfor Stitch screensplanning/v0-to-pulp-mapping.mdfor v0 generationsplanning/pencil-to-pulp-mapping.mdfor Pencil designs
Generate Pulp web-compat JavaScript:
- Layout:
document.createElement('div')+el.style.flexDirection, etc. - Typography:
el.style.fontSize,el.style.fontWeight, etc. - Colors:
el.style.backgroundColor,el.style.color, etc. - Audio widgets detected by name: knob/dial →
createKnob(), fader/slider →createFader(), meter/level/vu →createMeter(), xypad →createXYPad(), waveform →createWaveformView(), spectrum/analyzer →createSpectrumView() - Design tokens:
theme.colors["name"] = value,theme.dimensions["name"] = value
Step 4: Write output files
- Write the generated JS to
ui.js(or user-specified output path) - Extract design tokens to
tokens.jsonin W3C Design Tokens format - Report: number of elements, number of tokens, any warnings
Step 5: Offer refinement
After generating, offer to:
- Adjust specific elements ("make the knob smaller")
- Add audio widgets ("add a meter next to the gain knob")
- Change theme tokens ("use darker background colors")
- Preview the UI if a preview tool is available
For interactive review of the current checkout, prefer:
pulp design
If the design tool lives in a nonstandard worktree/build setup, use:
pulp design --build-dir /path/to/build --script /path/to/design-tool.js
When run outside a Pulp checkout, automatic binding currently only works when the pulp binary
itself lives inside a Pulp build tree. In generic PATH-installed or split repo/SDK layouts, pass
--build-dir and --script explicitly.
Mapping Quick Reference
Figma → Pulp
| Figma | Pulp |
|-------|------|
| Frame (auto-layout) | div with flex |
| Text | span |
| Rectangle | div with background |
| Component | JS function |
| Fill (solid) | backgroundColor |
| Fill (gradient) | background: linear-gradient(...) |
| Stroke | border |
| Drop shadow | boxShadow |
| Corner radius | borderRadius |
Stitch → Pulp
| Stitch | Pulp |
|--------|------|
| Container | div with flex |
| Text | span |
| Button | button |
| Input | input |
| Card | Panel |
| Design system colors | theme.colors |
v0 → Pulp
| v0 (Tailwind) | Pulp |
|----------------|------|
| flex flex-col | flexDirection: 'column' |
| gap-4 | gap: '16px' |
| bg-slate-900 | backgroundColor: '#0f172a' |
| rounded-lg | borderRadius: '8px' |
| <Button> | createButton() |
| <Slider> | createFader() |
DESIGN.md → Pulp
| DESIGN.md frontmatter | Pulp IR |
|------------------------|---------|
| colors.<name>: "#hex" | IRTokens.colors[name] = "#hex" |
| typography.<level>.<field>: ... | IRTokens.strings["typography.<level>.<field>"] = ... |
| rounded.<size>: <Nx> | IRTokens.dimensions["rounded-<size>"] = N |
| spacing.<size>: <Nx> | IRTokens.dimensions["spacing-<size>"] = N |
| components.<name>.<prop>: <ref-or-value> | IRTokens.strings["components.<name>.<prop>"] = ... (refs resolved in-place) |
| {colors.primary} | resolved to the primitive hex value at parse time |
| {typography.<level>} inside components | preserved verbatim (composite ref) |
| {colors} (group ref, outside components) | broken-ref warning |
| Markdown body ## Section | retained in DesignMdParseResult.sections for Phase 2 lint |
| Unknown ## Section (e.g. ## Iconography) | preserved without error |
| Duplicate ## Section | error-severity diagnostic → exit 3 |
Pencil → Pulp
| Pencil | Pulp |
|--------|------|
| Frame (auto-layout) | div with flex |
| Text | span |
| Rectangle | div with background |
| Variables (COLOR) | theme.colors |
| Variables (FLOAT) | theme.dimensions |
Stable-Anchor Identity (Phase 0a — inspector round-trip prerequisite)
Every tree-producing parser now stamps IRNode::stable_anchor_id,
source_node_id (when the source has a native ID), provenance
(adapter + version + source_uri), and confidence (PASS / DIVERGE /
NOT_IMPL). These fields key the tweaks layer (pulp-tweaks.json) so
inspector direct-manipulation edits survive re-import.
If you add a new parser, you MUST:
- After the IR tree is built, stamp
ir.root.provenancewith the
adapter name (e.g. "figma", "stitch-html", "pencil"), the
adapter version, and the source URI.
- Stamp
ir.root.confidence:
IRConfidence::passfor a clean loweringIRConfidence::divergefor lossy / regex / best-effort pathsIRConfidence::not_implif the adapter can't lower the source yet
- Call
assign_anchors(ir.root, strategy, adapter_name)with the
strategy that matches your source kind:
- adapter strategy when the source has native stable IDs
(Figma layer UUIDs, Pencil node IDs, Mitosis content-hash IDs).
Requires adapter_name (becomes the "<name>:" prefix) AND
source_node_id populated on each node.
- content-hash strategy when there are no native IDs
(Stitch HTML, v0 TSX, Claude Design HTML, raw JSX, generic HTML).
The hash is FNV-1a 32-bit base-36 over (tag, role, normalized
text, depth, sigIndex).
- path strategy for RN-style file exports / hand-edited code
where source position is the most stable identity.
- The strategy default lives in
default_anchor_strategy()in
core/view/include/pulp/view/anchor_strategy.hpp — mirrors the TS
DEFAULT_ANCHOR_STRATEGY map in packages/pulp-import-ir/src/anchors.ts.
Why this matters: Phase 1+ of the inspector roadmap writes user
inspector edits to a sidecar pulp-tweaks.json keyed by
stable_anchor_id. Without populated anchors the tweaks layer has
nothing to match against on re-import — defeating the "edit anywhere,
never lose work" principle. A parser that skips assign_anchors will
silently produce a tree where inspector edits get orphaned on the
next re-import.
Codegen contract: generate_pulp_js (both web-compat and
bridge_native_js modes) emits // @pulp-anchor <id> trail comments next to each
element when opts.include_comments == true. The runtime inspector
parses these to map generated elements back to their tweak-layer
identity. If you write a custom codegen path, preserve this pattern
so the inspector can still trace identity.
Phase 0b — setAnchor() bridge wiring: the web-compat codegen
path also emits a functional setAnchor(<var>._id, '<anchor>') call
after each createElement, AND the call is emitted unconditionally —
NOT gated on opts.include_comments. Rationale: the
// @pulp-anchor trail is cosmetic (for grep / debugging), but
setAnchor() is functional — the inspector cannot find a widget's
anchor without it, so dropping it in minified codegen would silently
break inspector tweaks in production. If you write a custom codegen
path, emit both: the comment (gated) for debuggability and the
setAnchor call (unconditional) for the runtime. The bridge side
(WidgetBridge::setAnchor) is a silent no-op on unknown widget IDs,
matching the rest of the bridge's tolerance for unmounted ids.
Codex P1 follow-up (#2303): The first argument to setAnchor <!-- docs-noise-lint: skip — retained: pins guidance to the PR that introduced the _id contract -->
MUST be the element's internal _id (the auto-generated __el_N__
that document.createElement assigns in core/view/js/web-compat.js),
NOT the generated JS variable name. The bridge keys widget() lookup
on _id; passing the var name silently no-ops and breaks the entire
anchor wiring chain for web-compat imports. Pre-fix codegen emitted
setAnchor('var', ...) (broken); post-fix emits setAnchor(var._id, ...)
(correct). If you write a new codegen variant or a non-web-compat
shim, ensure whatever id you pass matches the bridge's widget()
lookup key — not the JS-local variable name.
bridge_native_js codegen does NOT yet emit setAnchor (small
follow-up; the native-bridge JS codegen has many early-return branches
that need each to be wired). bridge_native_js is the default codegen
mode for imports; pass --web-compat only when the DOM-compatible JS
lane is required.
Phase 5.1 — setSource() source-jump wiring: alongside setAnchor,
the @pulp/react reconciler now forwards React's dev-mode __source
prop ({fileName, lineNumber, columnNumber}) through a `setSource(id,
file, line, col) bridge call (materializeUnder` →
bindSourceLocation in packages/pulp-react/src/host-config.ts). This
lands a View::SourceLocation on the live widget so the inspector's
J hotkey / Inspector.jumpToSource protocol method can open the
authoring JSX file:line in the user's editor. Gotchas:
__sourceis Babel-classic / automatic-dev-runtime only. esbuild's
jsx: 'transform' mode (current jsx-transform.mjs setting) does
not inline __source props — only Babel's
@babel/plugin-transform-react-jsx-development or esbuild's
jsx: 'automatic' + jsxDev: true do. So today bindSourceLocation
is a silent no-op for transform-mode bundles; it activates the moment
the JSX runtime emits __source. Migrating jsx-transform.mjs to the
automatic dev runtime is the remaining Phase 5.1 follow-up — do it as
a deliberate, separately-validated change because it shifts
jsxFactory semantics across every existing import fixture.
- Source maps gate behind
PULP_JSX_SOURCEMAP=1.jsx-transform.mjs
emits an inline source map only when that env var is set — off by
default to keep production bundles lean (~10-30% size add). It is
independent of the __source prop path.
setSourceno-ops on an empty file path and unknown widget id —
same tolerance as setAnchor. A custom codegen / shim that wants
source-jump must pass the same bridge-keyed _id as setAnchor.
Phase 1 — Tweaks persistence (`pulp-tweaks.json`)
TweakStore (inspect/include/pulp/inspect/tweak_store.hpp) now reads
and writes a sidecar pulp-tweaks.json so inspector edits survive
process restart.
- File location — resolved by
TweakStore::default_tweaks_path():
1. $PULP_TWEAKS_FILE env var if set (verbatim — useful for tests
and headless CI runs).
2. Otherwise walks up from cwd looking for a directory containing
package.json; if found uses <project_root>/pulp-tweaks.json.
3. Otherwise <cwd>/pulp-tweaks.json.
- Schema — `{ "$schema": "pulp-tweaks://v1", "version": 1,
"tweaks": { anchor: { dottedPath: value } }, "bypassed": { anchor:
true | string[] }, "sources"?: { anchor: { dottedPath: source } } }`.
Mirrors packages/pulp-import-ir/src/tweaks.ts TweaksFile with
the sibling bypassed overlay and sources sidecar Phase 1 adds.
Files written by @pulp/import-ir (no integer version) load as
v1 for back-compat; an explicit unknown version is a hard error
so we never silently drop fields we don't understand.
- Atomic write —
save_to_disk()writes<path>.tmpand renames
over the target; no partial flush ever lands at the canonical path.
- Auto-save — opt-in via
TweakStore::set_auto_save(true)or
Inspector.setAutoSave { enabled, path? } over the protocol. OFF
by default so unit tests don't touch disk by accident.
- Protocol surface —
Inspector.loadTweaks { path? },
Inspector.saveTweaks { path? }, `Inspector.setAutoSave { enabled,
path? }. All three default path to default_tweaks_path()`.
When wiring a new inspector client (web UI, CLI, MCP tool), prefer the
protocol methods over reaching into the C++ store directly — the
defaults + error reporting are the same and you get the resolved path
echoed back in the response for logging.
Phase 4a — Lock-to-source, Path A (generated-TSX/JS rewrite)
pulp/view/lock_to_source.hpp (impl core/view/src/lock_to_source.cpp)
is the engine that **promotes a tweak back into the generated import
artifact** so the edit is permanent and survives a fresh re-import.
Path A only — the artifact pulp import-design lowers a design into.
Path B (live React-bundle AST patch, #1308) and Path C (DESIGN.md <!-- docs-noise-lint: skip — retained: pins Path B/C scope to their tracking issue -->
token export) are separate phases and are NOT in this engine.
- How the element is found — every web-compat element block carries
the // @pulp-anchor <id> trail comment (emitted by generate_pulp_js
when include_comments is on). lock_tweak_into_source() locates the
block by that comment, then rewrites or inserts the matching
<var>.style.<prop> assignment. The block ends at the next
// @pulp-anchor comment or the first blank line (codegen emits
exactly one blank line between elements).
- Property-path mapping —
lock_property_to_style_name()collapses
the dotted tweak paths (paint.*, style.*, layout.*, transform.*,
or a bare name) onto the camelCase el.style.<name> surface. Hyphen/snake
fragments camelCase. The allow-list is exactly the set of properties
generate_node() emits — an unknown / mistyped path reports
unsupported_property instead of writing a bogus assignment.
- WYSIWYG T4 — reorder + proportional-resize round-trip. Two inspector
direct-manipulation gestures persist tweaks under non-paint/style/layout
paths and need explicit handling here:
layout.order— the reflow-aware drag-to-reorder rewritesflex().order;
it maps to the order style property (added to the kKnown allow-list).
transform.scale— the proportional Shift-resize persists a bare scale
factor under the transform namespace. The namespace collapses onto the
single transform style line, and format_lock_value() wraps the bare
factor into the CSS function form (1.5 → transform = 'scale(1.5)'). A
value already containing ( passes through so we never double-wrap.
When you add a NEW transform sub-component (rotate/translate) or a new flex
reorder property, extend both the kKnown allow-list AND format_lock_value()
if the tweak value needs a CSS-function wrapper.
- Status semantics —
rewritten/insertedmutate the text;
already_current is the idempotent re-lock no-op; anchor_not_found
and unsupported_property are graceful failures that leave the
source byte-identical so the caller keeps the tweak in the sidecar.
@generatedboundary guard —is_generated_source()is the
cheap check for the roadmap's "only lock into files marked
@generated" rule. It accepts both the Pulp codegen banner
(// Generated by Pulp import-design …) and a conventional
// @generated marker. The CLI / inspector layer owns the
read-confirm-write loop; the engine is pure text-in / text-out.
- Round-trip contract — locking a tweak into the generated text
produces exactly the text generate_pulp_js would emit had the IR
carried the tweaked value all along. test_lock_to_source.cpp
pins that byte-for-byte.
If you add a codegen property to design_codegen.cpp's generate_node,
add it to the kKnown allow-list in lock_property_to_style_name() too
— otherwise that property can never be locked to source.
- WYSIWYG T5 — structural reparent (
reparent_in_source). A reflow-aware
drop ("drop element A inside container B") is a TREE edit, not a style tweak.
In the generated artifact every element block ends with
<parentVar>.appendChild(<var>);. `reparent_in_source(source, {child_anchor,
new_parent_anchor})` locates the child block by anchor, finds its
<oldParent>.appendChild(<childVar>); line, resolves the new parent block's
const <var> = name, and rewrites the receiver to that var. Status semantics
mirror lock_tweak_into_source (rewritten / already_current /
anchor_not_found). The shared block helpers find_anchor_block() +
block_var_name() back both engines.
- Now physically relocates the block (gap closed).
reparent_in_source
moves the element's FULL source subtree — the block PLUS every DFS-contiguous
descendant block — to sit physically under the new parent, then re-indents it
one 2-space step in. The receiver rewrite alone is enough for the live DOM
(createElement + appendChild are order-independent), but a generated artifact
must also read correctly and round-trip a fresh re-import, so the block moves
too. Subtree boundary gotcha: find_subtree_range() detects the end of a
subtree purely from // @pulp-anchor comments + indentation — codegen is
depth-first, so a subtree is the run of lines until the next anchor at
indent <= base (a sibling/ancestor) or a non-anchor line indented < base
(the enclosing tail, e.g. document.body.appendChild(root)). Do NOT reuse
find_anchor_block() for relocation — it stops at the first blank line, which
is just ONE element block, not the whole subtree.
- Unsafe-reparent guard — REFUSE, don't rewrite (WYSIWYG sweep P2 fix). If
the new parent's anchor lies INSIDE the child's subtree (dropping a node under
its own descendant) or the subtree span can't be resolved, the engine now
rewrites NOTHING and returns anchor_not_found with result.source LEFT
BYTE-IDENTICAL to the input (plus a `"refused reparent ... cyclic/invalid
source"` message). Gotcha — this is a behavior change: the prior code
skipped only the physical block move but STILL rewrote the appendChild
receiver, which emitted <descendant>.appendChild(<ancestor>); — cyclic,
invalid source the re-import engine chokes on. Receiver-rewrite-without-move is
NOT a safe fallback for the cyclic case; the only safe outcome is to mutate
nothing. The live gesture's is_self_or_ancestor already prevents this, but
the source engine must defend independently. Test asserts r.source == gen.
- Live gesture → source wiring (gap closed).
InspectorOverlayexposes
`set_reparent_source_sink(std::function<void(ReparentSourceEdit{child_anchor,
new_parent_anchor})>). At the commit_reflow_drop` undo-entry site, a genuine
cross-parent reparent of an anchored view emits through the sink: the do_fn
locks under the NEW parent, the undo_fn re-emits with the ORIGINAL parent so
the host re-derives the inverse rewrite. Gotcha: EditHistory::perform()
runs do_fn immediately (it calls redo()), so the sink fires once on the
initial commit — don't ALSO call the sink inline before perform() or you
double-rewrite. The overlay is filesystem-free by design; the HOST owns the
source text + read/confirm/write loop. examples/ui-preview wires the sink to
its --script file behind the is_generated_source() @generated-boundary
guard, so a hand-authored script is never rewritten. Coverage:
pulp-test-lock-to-source [wysiwyg][t5] (engine: relocation + idempotency +
guard) and pulp-test-inspector [wysiwyg][t5] (gesture round-trip: live →
source → undo reverts both → redo → idempotent; plus the live-only no-sink
path).
- Insertion SLOT (WYSIWYG sweep P1 fix).
ReparentToSourceEdit/
ReparentSourceEdit carry a third field insert_after_anchor[_id]: the
anchor of the sibling the moved block should physically FOLLOW under the new
parent, or "" = first child. Gotcha: without it the relocation always
dropped the block as the parent's FIRST child, silently discarding the drop
position the user dragged to. The overlay computes the preceding visible
sibling in flex-order (preceding_sibling_anchor) for BOTH the new-parent
(do_fn) and old-parent (undo_fn) sides. Empty / unresolved slot → first-child
fallback (prior behavior preserved). insert_after_anchor must resolve in the
POST-erase buffer (after the moved subtree is removed), so the engine re-finds
it then.
- Same-parent reorder IS persisted (WYSIWYG sweep P1 fix). A same-parent
reflow reorder rewrites flex().order live; commit_reflow_drop now ALSO
emits a layout.order tweak (keyed by each view's OWN anchor) for the dragged
child AND every sibling whose order was normalized. Gotcha: an old comment
claimed the reorder was "persisted elsewhere" — it wasn't, so the new order
vanished on a fresh re-import. layout.order was already in the lock
allow-list (T4), so it round-trips as el.style.order. Un-anchored children
are skipped (nothing to lock). The cross-parent source sink only fires for a
genuine PARENT change; a pure reorder relies on the layout.order tweak path.
Coverage: pulp-test-lock-to-source [issue-wysiwyg-reflow-slot] (slot
after-sibling / first-child / unresolved-fallback) and
pulp-test-inspector [issue-wysiwyg-reflow-slot] (reorder tweak round-trip;
cross-parent slot carried to the sink).
Phase 4b — Lock-to-source, Path B (hand-authored JSX/TSX patch)
pulp/view/jsx_lock.hpp (impl core/view/src/jsx_lock.cpp) is the
Path B sibling of Path A; the roadmap tracks Path B under issue #1308. <!-- docs-noise-lint: skip — retained: pins Path B scope to its tracking issue -->
Where Path A rewrites the generated web-compat artifact, Path B
patches the user's own hand-authored JSX/TSX — the source behind a
live React bundle (--from jsx, --execute-bundle). There is no
generated file to rewrite, so the engine edits the authored source
directly.
- How the element is found — an element-instrumentation pass injects
a data-pulp-anchor="<stable_anchor_id>" attribute onto each authored
element (the JS-side instrumentation is a separate deliverable; the
engine only consumes the marker). jsx_lock_tweak_into_source()
scans for the matching attribute, walks left to the opening < and
right to the tag-closing > (respecting strings and {…} braces so a
> inside {a > b} does not end the tag early).
- Surgical patch, not an AST re-emit — mirrors 4a/4c. The engine
rewrites exactly one literal span: a property inside an inline
style={{…}} object, or a bare attribute (width={80},
color="#888"). Every other byte — comments, imports, formatting,
sibling props — is preserved byte-for-byte. It is deliberately NOT a
general JSX printer (Codex capped Path B from ballooning into a
multi-quarter parser).
too_dynamicis the safety valve — anything that is not a plain
rewritable literal fails as too_dynamic with a specific reason, and
the source is returned unchanged so the caller keeps the tweak in the
sidecar: a style={{ ...base }} spread, a computed key, a non-literal
value (padding={gap * 2}, color={theme.fg}), style={someVar}, or
a prop the author simply never wrote (Phase 4b patches existing
props only — it never inserts, which would risk a malformed tag).
- Other statuses —
patchedmutates;already_currentis the
idempotent no-op; anchor_not_found and anchor_ambiguous (the same
data-pulp-anchor on two elements — refuse to guess) and
unsupported_property are graceful failures that leave the source
byte-identical.
- Value rendering — a quoted prop keeps its quote style (contents
rewritten, single-quotes escaped for a JS string body); a bare numeric
prop stays bare when the new value is numeric, but is promoted to a
quoted string when the new value carries a unit (width={80} →
width={'120px'}).
jsx_lock_property_to_key()shares the samekKnownallow-list as
Path A's lock_property_to_style_name() — keep the two in sync so a
tweak can target the same set of properties on either path.
The engine is pure text-in / text-out — no filesystem I/O — so the
overlay / CLI layer owns the read-confirm-write loop and the
authored-vs-generated routing (is_authored_jsx_source() is the cheap
guard: a file carrying the codegen banner is Path A's, not Path B's).
test_jsx_lock.cpp pins the patch, the formatting-preservation
contract, and every failure path.
Phase 4c — token lock-to-source (`DESIGN.md` rewrite)
token_lock.hpp / token_lock.cpp (core/view/) lock a token-typed
inspector tweak back into the project's DESIGN.md so a re-import picks
up the corrected token instead of re-introducing the stale one. This is
the token-level sibling of Phase 4a (generated-TSX rewrite) and 4b
(JSX/TSX AST patch).
- Token vs element classification — `classify_token_tweak(anchor,
property_path) returns a TokenTarget` when the tweak addresses a
DESIGN.md token, std::nullopt for element-only tweaks (paint.*,
layout.*, text.* — those lock via 4a/4b). Two signals, in
priority order: a dotted property path whose head is a canonical
token group (colors / spacing / rounded / typography), or a
designtoken:<group>.<name> anchor. Typography paths must be
three-segment (typography.<level>.<field>). components.* is
deliberately not lockable — a component entry is a reference
bundle, not a primitive value.
- Surgical text rewrite, not
export_designmd— the lock parses
the YAML frontmatter only to locate the token (yaml-cpp Mark()
gives the value line), then edits exactly that one value span in the
original file text. Prose sections, YAML comments, key order,
indentation, and the value's original quote style are all preserved.
export_designmd(Theme, ...) re-emits the whole file and would lose
every one of those — never use it for a single-token lock. (It also
still throws, gated on #1307.)
- Conservatism —
lock_token_in_designmdfails (and returns the
input byte-identical) on: no frontmatter, missing group/token/field,
a nested color palette (not a scalar), or a source line that does not
match the expected key: <value> shape. A failed lock never mutates
DESIGN.md. The locator keys off the group, so a leaf name that
appears in two groups (e.g. md under both spacing and rounded)
still resolves unambiguously.
- Overlay wiring deferred — the inspector overlay "lock token"
affordance is intentionally not wired here (inspector_overlay.cpp
has in-flight PRs). The engine is pure data-in/data-out so the
overlay/protocol layer can adopt it without a rebuild.
Spec + design: