Motion

From Generous-Corp/pulp · View interactive version

Motion is an AI agent skill from the GitHub repository Generous-Corp/pulp. Debug or validate Pulp animations / transitions / scroll behavior using in-process motion fixtures and offline visual analysis. TRIGGER on phrases like "animation is wrong", "transition timing off", "fade too late", "card slides too far", "scroll jumps on restore", "scroll offset wrong on restore",

How to use this skill

Skill file

Motion

Pulp's agent-first motion observability — sample view geometry / scalar

values / scroll state over time, emit epsilon-bounded events with monotonic

timestamps and burst framing, and route them to log lines + inspector

events + JSONL fixtures. **You are reading this skill because an agent

needs to debug, validate, or reproduce a motion behavior.**

When to rope this skill in

Trigger this skill the moment a user (or your own reasoning) describes any

of these symptoms — don't reach for grep or git log, attach a trace:

If the user says any of those, this skill applies. Don't suggest reading

source; attach a trace and read the numbers.

Quick decision

Eight paths — pick by what you have, all eight terminate at the same

motion::Coordinator so fixtures, scrubber, cost, reduced-motion, and

provenance work identically across surfaces.

| You have | Path | Tool |

|---|---|---|

| C++ fixture code + a node id + a scalar / geometry of interest | A — In-process trace | motion::Coordinator / MotionInspector fixture APIs; an admitted exact T1 host may inject ControlMotionExecutor |

| A ScrollView whose offset / visible rect / content size you need to observe | A — Runtime trace (scroll) | Trace.scroll_geometry(name, scroll_view, props) — emits contentOffsetX/Y, visibleRect*, contentSize*, scrollableMax*, inset* |

| A captured frame sequence (no app instrumentation available) | B — Visual analysis | tools/motion/visual/analyze_sequence.py |

| A captured frame sequence whose frames paint a frame-identity stamp | B — Frame identity | tools/motion/visual/frame_stamp_decode.py (exact %, held, skipped, judder; -1 = unreadable) |

| A previously recorded .motion.jsonl fixture | C — Replay + assert | motion::replay_fixture + motion::assert_matches |

| An interaction that drives the suspect motion | D — Input record + replay | motion::make_input_recorder + motion::replay_inputs |

| A fixture available to C++ host/test code (design review / CI triage) | E — Timeline scrubber | Direct MotionScrubber fixture load; canonical T1 scrub/play/pause is capped at 4,096 emitted events |

| "Which animation is expensive and why?" | F — Cost attribution | CostAttributor + make_render_cost_probe; canonical T1 returns at most 64 redacted finite samples |

| SwiftUI / UIKit / AppKit / iOS / macOS / AUv3 host code path | G — Swift native | View.pulpMotionTrace { Trace.* } / PulpMotionGeometryProbe |

| Jetpack Compose or Android View code path | H — Android native | Modifier.pulpMotionGeometry { +Trace.* } / View.pulpMotionTrace |

| Imported design + intent doc (e.g. "fade in 350 ms ease-out") | Both A + C | Record a fixture from the import, assert timing / monotonicity |

Path A — In-process fixture trace

The runtime path is currently an in-process fixture API. The shipped `pulp

motion` command, Motion MCP wrappers, and legacy remote transport are

intentionally unavailable after Phase 3 authority deletion. Remote Motion work

uses dev.pulp.trace/control@1 only when the exact T1 host injects

ControlMotionExecutor; do not rebuild the old wire path in a custom fixture.

1. Confirm the complaint as a measurable property

Translate "looks off" into a metric and a target. Example mappings:

2. Start an owned in-process fixture

Use the test host's in-process fixture APIs. No environment flag or public CLI

turns a normal app or pulp-ui-preview launch into a remotely controlled Motion

host.

3. Attach a trace

The shipped pulp motion command and pulp_motion_* MCP wrappers were retired

with the raw inspector authority path. Use the in-process fixture APIs for

tests. Live remote operations require a canonical broker/control capability

with a frozen schema and receipt. ControlMotionExecutor is the canonical broker/control replacement

for exact T1 Motion outcomes.

4. Trigger the interaction

Drive the app — click, hover, type, fire whatever causes the suspected

animation. The motion server emits events as the values change.

5. Stop the trace

Stop through the same fixture-owned in-process API or canonical control

operation that started the trace. No shipped Motion CLI/MCP stop route exists.

6. Compare against intent

Did the trace match? Use the dedicated assertion helpers — do not conflate

continuity, monotonicity, settling time, and overshoot into a single number.

auto samples = motion::extract_scalar(events, "Card", "frame", "minY");
REQUIRE(motion::is_monotonic(samples));
REQUIRE(motion::settling_time_seconds(samples) < 0.7);
REQUIRE(motion::overshoot(samples) < 0.05);
REQUIRE(motion::final_value(samples) == Catch::Approx(120.0).margin(1.0));
// Local-step outlier check is a *separate* axis from monotonicity /
// timing — flags one-frame jumps (5x = "this one step is 5x larger
// than the median of its neighbors"). Use it alongside, not in place
// of, the helpers above.
REQUIRE(motion::local_step_outlier_ratio(samples) < 3.0);

Path B — Visual analysis

Use when no scalar is observable (transitions, GPU filters, mask compositing,

opacity-only effects you suspect aren't rendering).

1. Capture a frame sequence

Any source: a host window-capture loop, an ffmpeg extraction from a screen

recording, scripted PNG dumps. Land sequential frames in a directory:

captures/card-open/
  frame_0000.png
  frame_0001.png
  …

2. Run the pipeline

pip install -r tools/motion/visual/requirements.txt
python3 -m tools.motion.visual.analyze_sequence \
    --frames-dir ./captures/card-open/ \
    --output     ./reports/card-open/ \
    --keyframes 2

# Recommended flags for design / motion review:
python3 -m tools.motion.visual.analyze_sequence \
    --frames-dir ./captures/card-open/ \
    --output     ./reports/card-open/ \
    --grid                      # alphanumeric cell overlay (A1..H12) on
                                # frames/diffs/sprite so claims can cite a cell
    --trim                      # drop idle prefix + suffix from the analysis
                                # window (frames stay on disk)
    --affine                    # estimate translation/rotation/scale first→last
                                # (uses opencv if installed, else PIL-FFT
                                # translation only — see requirements-optional.txt)

Tunables: --grid-rows N (default 8, A..Z), --grid-cols N (default 12),

--grid-theme auto|light|dark (default auto — samples corner luminance),

--trim-threshold (default 0.01 mean-diff luminance fraction).

2b. Motion-gated capture from a host source

When you don't already have a frame directory, capture one with the

gated helper. It only starts saving frames once real motion appears,

so a short pre-roll doesn't pollute the analysis window.

# macOS window region (requires --bounds X,Y,W,H)
python3 tools/motion/visual/capture_sim_frames.py \
    --source macos --bounds 0,0,800,600 \
    --output-dir ./captures/card-open/ \
    --fps 30 --frame-count 60 \
    --gate-threshold 4.0 --gate-consecutive 1 \
    --idle-timeout 8

# Booted iOS Simulator
python3 tools/motion/visual/capture_sim_frames.py \
    --source simulator \
    --output-dir ./captures/card-open/ \
    --fps 30 --frame-count 60

The capture tool exits 3 (ctest SKIP) when neither screencapture

nor a booted simulator is available, so this composes cleanly with

CI lanes that lack the platform tooling.

3. Read the report

The pipeline writes analysis.json (machine-readable), summary.md

(agent-readable), diff/diff_NNNN_NNNN.png (pairwise heatmaps), and

keyframes.png (sprite). With --grid: grid/frame_NNNN.png,

diff_grid/diff_NNNN_NNNN.png, and keyframes_grid.png siblings.

With --affine: an analysis.json#affine_first_to_last block and a

## Net motion section in summary.md. With --trim:

summary.trimmed_leading_frames / summary.trimmed_trailing_frames.

The JSON carries schema_version — refuse unknown versions.

Claim-evidence contract. Every claim you make from this report

must cite: (1) pair index (NN→NN+1), (2) artifact type (frames/,

diff/, grid/, diff_grid/, keyframes.png, or

affine_first_to_last), and (3) a confidence score 0.0..1.0 from

pairs[].confidence / summary.mean_confidence. **Confidence < 0.7

means the analyzer is unsure** — escalate by re-running with

--max-diff-frames 0 (all pairs), a longer capture window, or fall

back to a runtime trace (Path A) if instrumentation is possible. The

summary.md preamble carries the same contract verbatim.

Path C — Fixtures (record / replay / assert)

A fixture is the on-disk form of a motion stream — a versioned JSONL file. Use

fixtures to:

Record

auto sink = motion::make_fixture_sink("test/motion/goldens/card-open.motion.jsonl");
int sid = Coordinator::instance().add_sink(std::move(sink));
// ... run the animation ...
Coordinator::instance().remove_sink(sid);  // closes the file

Replay

std::vector<motion::SampleEvent> replayed;
motion::replay_fixture("captures/card-open.motion.jsonl",
                       motion::make_buffer_sink(&replayed));

Assert

auto golden   = motion::load_fixture("test/motion/goldens/card-open.motion.jsonl");
auto captured = motion::load_fixture("/tmp/run.motion.jsonl");
auto diff     = motion::assert_matches(golden, captured);
REQUIRE(diff.matches());  // or inspect diff.differences on failure

`FixtureMatchOptions { component_epsilon, timing_epsilon_seconds,

require_same_event_count }` controls tolerances.

Path D — Input recording and replay

When the bug is "what the user did caused the wrong motion", record the

interaction alongside the motion stream so a fresh tree can replay the same

sequence deterministically.

// Recording — paired with whatever motion sinks you already have.
{
    auto recorder = motion::make_input_recorder("/tmp/card-open.motion.jsonl");
    root.simulate_hover({150, 150});
    clock.tick(1.0f / 60.0f);
    root.simulate_click({150, 150});
    // ... drive your animation ...
}   // RAII: destructor closes the sink + flips recording off.

// Replay against a fresh tree on a fresh FrameClock.
motion::replay_inputs("/tmp/card-open.motion.jsonl", fresh_root, fresh_clock);

make_input_recorder(path) installs a make_fixture_sink(path) AND flips

the process-wide input_recording_enabled() flag. View::simulate_* checks

that flag (a single relaxed atomic load, off by default) and emits a

SampleEvent::Kind::Input carrying the input_kind ("click" / "drag" /

"hover"), the recorded target's View::id(), and the root-space coords on

the existing components map. Click and drag also carry pointer_type,

pressure, modifiers, button, and pointer_id; hover remains

coordinate-only. Canonical order is `button, modifiers, pointer_id,

pointer_type, pressure, x, y for click and button, end_x, end_y, modifiers,

pointer_id, pointer_type, pressure, start_x, start_y, steps` for drag.

replay_inputs(path, root, clock):

subsequent inputs tick by the delta).

coords with hit_test land on the same descendant).

fixtures retain the historical defaults (mouse, pressure 0.5, no

modifiers, left button, pointer id 0). Missing or invalid metadata fields

independently keep those defaults without discarding valid sibling fields.

The motion stream that emerges — when paired with the same animation

primitives — matches the originally-recorded one within

FixtureMatchOptions::timing_epsilon_seconds. Use the ID-keyed

assert_matches for the comparison so reordered identical bursts don't

false-fail.

Path E — Timeline scrubber (in-process replay)

pulp::inspect::MotionScrubber loads a .motion.jsonl fixture in trusted

host/test code and

re-emits the prefix of events with frame <= playhead to caller sinks. The

scrubber is passive — no clock is pumped, no

animation runs live; play() is a jump-to-end that emits every event.

Real-time pacing and live overlay drawing are intentionally Phase 11+.

Protocol surface (routed by DomainHandler::handle_motion):

| Method | Params | Response |

|----------------------|---------------------|---------------------------------------------------------|

| Motion.loadFixture | { path } | Unavailable: remote sessions cannot authorize host filesystem reads |

| Motion.scrubTo | { frame } | { playhead_frame, emitted_count } + broadcast events |

| Motion.play | {} | { playing:true, emitted_count, playhead_frame } |

| Motion.pause | {} | { playing:false, playhead_frame } |

Emitted events reuse MotionInspector's Motion.start / .sample / .end shape,

with an additional "replay":true marker so fixture consumers can distinguish

replayed bursts from live coordinator events.

After trusted host/test code loads the fixture, use the in-process

MotionScrubber API to scrub, play, or pause. The retired pulp motion command

must not be recreated as a remote filesystem or mutation fallback.

Direct C++ usage:

pulp::inspect::MotionScrubber scrub(/*server=*/nullptr);
std::vector<motion::SampleEvent> buf;
scrub.add_sink(motion::make_buffer_sink(&buf));
scrub.load_fixture("captures/card-open.motion.jsonl");
scrub.scrub_to(120);   // emits prefix with frame <= 120
scrub.scrub_to(0);     // emits only the frame-0 prefix (backwards scrub)
scrub.play();          // jump to max frame, emit everything

Gotchas:

play is called. Don't pre-clear UI overlays during the trusted load and

expect a refill — wait for the first scrub_to.

clear it before each scrub or compare counts modulo the prefix size.

timestamps, not wall clock. Don't drive a live clock from them.

Path F — Cost attribution

When the question is "which animation is expensive and why?", switch

the cost channel on. It's off by default and runs on a separate stream

from the fixture format — cost samples don't appear in *.motion.jsonl.

Enable + wire a probe (in-process)

#include <pulp/view/motion_cost.hpp>
#include <pulp/view/motion_cost_render.hpp>

auto& cost = pulp::view::motion::CostAttributor::instance();
cost.set_enabled(true);

// Optional but recommended: surface real render stats. Pointers may be
// null — defensive degradation returns 0 for the missing field.
cost.set_probe(pulp::view::motion::make_render_cost_probe(
    &render_pass_manager, &dirty_tracker));

// Sink: JSONL on disk for later analysis…
cost.add_sink(pulp::view::motion::make_cost_sink("/tmp/run.motion-cost.jsonl"));
// …or a buffer for in-test assertions:
std::vector<pulp::view::motion::CostSample> samples;
cost.add_sink(pulp::view::motion::make_cost_buffer_sink(&samples));

Each frame, the Coordinator's tick now emits one CostSample per active

sink with:

order, so a reader can answer "this 12ms pass came from

figma:LevelMeter/Panel (source_kind=design-import)" without

cross-referencing the event fixture.

Inspector domain

Motion.enableCost / Motion.disableCost toggle the channel; while

enabled, Motion.cost events broadcast per frame. Motion.snapshot

also reports cost_enabled and cost_samples_emitted.

Toggle cost attribution through the explicitly owned in-process host/test API;

the retired CLI and MCP mutation wrappers are not control surfaces.

Notes

its own version header ({"motion_cost_version":1}). Do not confuse

with the fixture schema — they're independent.

attributor still emits cost samples — the render-cost timeline is

useful by itself even without any motion trace activity.

implementations cheap.

Path G — Swift native (iOS / AUv3 / macOS)

When the suspect motion lives in a pure SwiftUI / UIKit / AppKit code

path — an iOS AUv3 editor, a Swift host app, anything wired through

apple/Sources/PulpSwift/ — use the Swift facade. Samples flow into

the same motion::Coordinator as the JS-bridge and design-import

paths, so fixtures, scrubber, cost attribution, reduced-motion gating,

and provenance envelopes all work identically.

The facade's C++ side is Vellum's motion bridge

(integrations/pulp-vellum/src/swift_motion_bridge.cpp, over

vellum::view::motion), not Pulp's core/view. The

swift-bridge-split-guard test fails if PulpBridge.cpp or the motion

shims reach back into pulp/view headers.

Quick attach (SwiftUI)

import PulpSwift
import SwiftUI

struct CardView: View {
    @State var opacity: Double = 1
    var body: some View {
        Rectangle()
            .opacity(opacity)
            .pulpMotionTrace("Card") {
                Trace.value("opacity", opacity)
                Trace.geometry("frame",
                    properties: [.minX, .minY, .width, .height])
                Trace.scrollGeometry("scroll")
            }
    }
}

The pulpMotionTrace(_:fps:_:) modifier:

source_id=<view name> provenance on onAppear.

global-space frame into pulp_motion_update_geometry.

registration, no probe, zero cost beyond a SwiftUI background view.

Direct publish (no SwiftUI)

PulpMotion.publishValue(view: "Card", metric: "opacity", value: 0.5)
PulpMotion.publishComponents(view: "Card", metric: "frame",
                             components: [("x", x), ("y", y)])

Both are guarded by the backend's isTracingEnabled() so they cost a

single branch when motion is off.

UIKit / AppKit / non-SwiftUI probe

final class CardUIView: UIView {
    private let probe = PulpMotionGeometryProbe(view: "Card")
    override func layoutSubviews() {
        super.layoutSubviews()
        probe.update(minX: frame.minX, minY: frame.minY,
                     width: frame.width, height: frame.height)
    }
    // deinit auto-detaches.
}

Host wiring (once at app launch)

PulpSwift is a pure-Swift package; the C bridge lives in

integrations/pulp-vellum/src/swift_motion_bridge.cpp (excluded from SwiftPM and

linked by the AUv3 / standalone host). At launch the host installs a

PulpMotionBackend that forwards into the C ABI:

var backend = PulpMotionBackend()
backend.isTracingEnabled  = { pulp_motion_tracing_enabled() }
backend.publishValue      = { v, m, val, eps, p in
    v.withCString { vc in m.withCString { mc in
        pulp_motion_publish_value(vc, mc, val, eps, Int32(p))
    }}
}
// …same shape for publishComponents, ambient provenance,
//   registerGeometryTrace, updateGeometry, detachTrace.
PulpMotionRuntime.installBackend(backend)

In unit tests, install a recording backend instead — `swift test

--package-path apple` runs the facade with no C++ host linked.

Enable PULP_ENABLE_PULP_VELLUM with a Vellum SDK that exports

Vellum::MirrorView_core and link the native host to pulp::vellum

(Pulp::vellum for an installed Pulp SDK). Use the Vellum Coordinator

and its bound FrameClock for Swift tracing. The

pulp-test-motion-swift-bridge target covers the native motion ABI

and invalid state-buffer guards.

Off-by-default contract

Every Swift entry point is a no-op when the process-wide Coordinator

has tracing disabled. The C bridge double-checks

(pulp_motion_tracing_enabled()) so even a misconfigured Swift caller

cannot spam events in production.

Files

vellum::view::motion. A mutex-protected registry keeps the

TraceHandle separate from the lambda-captured atomic rect so

Coordinator::reset() cannot self-deadlock.

Trace.* factories, MotionGeometryProperty,

@MotionTraceBuilder, PulpMotionBackend / PulpMotionRuntime.

pulpMotionTrace(_:) modifier + UIKit / AppKit

PulpMotionGeometryProbe.

XCTest coverage.

round-trip test for the C ABI shims and Coordinator integration.

Path H — Android native (Kotlin / Compose / View)

When the suspect motion lives in a Kotlin / Compose / Android View

code path — a Pulp Android app screen, a TalkBack overlay, a

SurfaceView driver — use the Kotlin facade. Samples flow into the

same motion::Coordinator as the Swift, JS-bridge, and design-import

paths, so fixtures, scrubber, cost attribution, reduced-motion

gating, and provenance envelopes all work identically. The Android

bridge is the platform sibling of Path G and follows the same shape

(C ABI + closure-bag backend seam + probe wrapper).

Quick attach (Jetpack Compose)

import androidx.compose.ui.Modifier
import com.pulp.motion.PulpMotion
import com.pulp.motion.Trace
import com.pulp.motion.pulpMotionGeometry

Box(
    Modifier
        .size(120.dp)
        .pulpMotionGeometry("Card") {
            +Trace.value("opacity", opacity.toDouble())
            +Trace.geometry("frame",
                properties = listOf(
                    MotionGeometryProperty.minX,
                    MotionGeometryProperty.minY,
                    MotionGeometryProperty.width,
                    MotionGeometryProperty.height,
                ))
        }
) { ... }

The Modifier.pulpMotionGeometry(name, fps) modifier:

provenance (set on the C bridge).

pulp_motion_update_geometry.

Compose-side cost beyond a single branch in composed { }.

Quick attach (View hierarchy)

For non-Compose UIs (XML layouts, SurfaceView, custom Views):

class CardView(context: Context) : View(context) {
    private val probe = pulpMotionTrace("Card") {
        +Trace.geometry("frame")
    }
}

View.pulpMotionTrace(name, fps) { ... } returns a

PulpMotionGeometryProbe? — null when tracing is disabled, an

AutoCloseable handle otherwise. The probe installs a

ViewTreeObserver.OnPreDrawListener (NOT OnGlobalLayoutListener —

PreDraw catches intra-frame scroll/translation GlobalLayout misses)

and pushes window-space rects via getLocationInWindow(). Auto-

detaches when the host View is removed from the window.

Direct publish (no View / no Compose)

PulpMotion.publishValue(view = "Card", metric = "opacity", value = 0.5)
PulpMotion.publishComponents(
    view = "Card",
    metric = "frame",
    components = rect.toMotionComponents(),
)

Both short-circuit on PulpMotion.isTracingEnabled so they cost a

single branch when motion is off.

Ambient provenance (scoped)

PulpMotion.withProvenance(kind = "android", id = "CardView") {
    PulpMotion.publishValue(view = "Card", metric = "opacity", value = 1.0)
}

withProvenance is single-threaded by design — the process-wide

ambient slot is not coroutine-safe. Do not call from suspending code

that may switch dispatchers inside the block. The Swift bridge ships

the same constraint; this is a deliberate limit, not a TODO.

Host wiring (once at app launch)

PulpApplication.onCreate, after System.loadLibrary("pulp"):

if (nativeLoaded) {
    com.pulp.motion.PulpMotion.installNativeBackend()
}

installNativeBackend() wires every PulpMotionBackend closure to

the matching external fun on the internal PulpMotionNative

object. The C bridge double-checks

motion::Coordinator::tracing_enabled() so a misconfigured backend

cannot spam events in production.

Testability (JVM unit tests, no NDK)

The closure-bag backend lets gradle test exercise the facade

without ever loading libpulp.so:

val recorder = RecorderBackend()
PulpMotionRuntime.installBackend(recorder.asBackend())
PulpMotion.publishValue("Card", "opacity", 0.5)
assertEquals(1, recorder.publishedValues.size)

See android/app/src/test/kotlin/com/pulp/motion/PulpMotionTest.kt

for the full pattern.

Off-by-default contract

Every Kotlin entry point is a no-op when the process-wide Coordinator

has tracing disabled. The C bridge re-checks

pulp_motion_tracing_enabled() so even a misconfigured caller

cannot spam events in production. The View probe extension returns

null immediately when tracing is off — no listener installed, no

allocation.

Files

ABI declarations the JNI shims forward into (also pulled by the

Catch2 host test).

C ABI + Java_com_pulp_motion_PulpMotionNative_* JNI shims.

Internal mutex-protected registry keeps the TraceHandle

separate from the lambda-captured atomic rect so

Coordinator::reset() cannot self-deadlock — same fix shape as

the Swift bridge.

internal object with external fun JNI declarations.

closure-bag backend + PulpMotionRuntime.installBackend(...).

public facade (publishValue, publishComponents,

setAmbientProvenance, withProvenance, register / update /

detach, installNativeBackend()).

factories, MotionGeometryProperty, @MotionTraceBuilder

motionTrace { } block, RectF/Rect.toMotionComponents().

View.pulpMotionTrace(...) extension + PulpMotionGeometryProbe

(AutoCloseable).

Modifier.pulpMotionGeometry(...) modifier + pulpMotionPublish(...)

composable.

JVM facade unit tests (JUnit4 only, no Mockito, no native lib).

the C ABI + the Coordinator::reset() deadlock regression.

Agent contract

Apply these on every motion debugging run:

  1. State the complaint as a measurable target before instrumenting.
  2. Use runtime trace by default. Drop to visual analysis only when no scalar

is observable.

  1. Pick the metric, space, and source explicitly. Defaults are reasonable,

but the intent should be obvious from your request.

  1. Keep continuity, monotonicity, settling time, and overshoot as separate

assertions. Do not write a single "smoothness" check that conflates them.

  1. Cite evidence with frame indices, sample timestamps, and metric values when

reporting. "Looks wrong" without evidence is not a finding.

  1. Land a golden fixture when fixing a bug — the next regression should fail

in CI, not after a user reports it.

Env knobs (standalone `pulp-ui-preview`)

| Variable | Effect |

|---|---|

| PULP_MOTION_LOG=1 | Install the default log sink + enable tracing |

| PULP_MOTION_FIREHOSE=1 | Broadcast every publish_* call to all sinks |

There is no environment variable that starts an inspector server. Runtime

inspection requires an explicitly wired custom fixture and authenticated

discovery.

Files this skill covers

Provenance

Every trace can carry a Provenance envelope that flows through the fixture

to agents reading a golden weeks later:

auto handle = motion::Coordinator::instance()
    .trace("Card", { 60 })
    .with_provenance({ "tween", "Card.opacity", __FILE__, __LINE__ })
    .value("opacity", [&]{ return opacity; })
    .attach();

The envelope shows up on the trace's TraceStarted event and in the JSONL

fixture. When you read a fixture and the burst looks wrong, the provenance

tells you which file / Figma node / animator the trace was attached to —

without grepping.

Adapter shortcuts (each animation surface stamps itself)

Direct with_provenance(...) is the bedrock; Phase 9 added per-surface

shortcuts so common cases don't require hand-building an envelope:

t.publish(view, metric) each tick. The macro

PULP_MOTION_TWEEN("knob-hover", from, to, duration) auto-fills

source_file / source_line from std::source_location::current().

Runner::publish(view, metric, value) stamps source_kind="animator-set",

source_id="knob-glow".

"/styles/card.css", line) carries source_file / source_line` through;

CssAnimation::publish(view, metric) stamps

source_kind="css-transition", source_id=<property name>.

set_active_script_id(...)) records the script id; __flushFrames__

sets the ambient envelope per callback so a motion.publishValue from

inside an rAF body emits source_kind="rAF",

source_id="my-script.js:<callback_id>".

motion.setProvenance(kind, id, file?, line?) are exposed on the

globalThis.motion object the bridge installs. motion.clearProvenance()

empties the slot. Explicit PublishOptions::provenance always wins over

the ambient slot.

line at the top of every bundle, tagged with vendor + root-node id

(figma:Card/Hover, stitch:Panel, claude:HeaderLayout, …). Drop the

generated JS into a bridge and any animation it drives inherits the

envelope automatically.

Reduced-motion policy

pulp::view::MotionPreferences (sibling of AppearanceTracker) reads the

OS reduced-motion accessibility setting on first use and exposes it as a

MotionPolicy (Full / Reduced / Off) plus a clamped duration_scale

(0.0–2.0, default 1.0). Animation primitives honor the policy on start:

| Policy | Tween / ValueAnimation | CssAnimation | AnimatorSet |

|---|---|---|---|

| Full | Animate as configured | Animate as configured | Animate as configured |

| Reduced | Scale duration × duration_scale | Same | Same (via each Tween) |

| Off | Jump to target on tick 0 | Complete on first tick() | Each Tween starts finished |

Tests get a per-process override that wins over the OS value:

auto& prefs = pulp::view::MotionPreferences::instance();
prefs.set_override(pulp::view::MotionPolicy::Reduced);
prefs.set_duration_scale(0.5);
// …drive the animation…
prefs.reset_for_tests();   // clears override, re-reads OS

Fixtures recorded under a non-Full policy capture it on the v2 header:

{"motion_fixture_version":2,"policy":"reduced","duration_scale":0.5}

load_fixture_header(path) returns the policy + scale; the header-aware

assert_matches(g_hdr, g_events, c_hdr, c_events, opts) overload flags a

"policy-mismatch" diff item if the goldens were recorded under one policy

and the capture under another — no more silent comparisons of a Reduced

golden against a Full capture. policy / duration_scale are additive on

the header; v2 fixtures without them still load (defaulting to

policy="full", duration_scale=1.0).

Note: MotionPreferences is a sibling of AppearanceTracker, not a

subclass. Use the OS reader on the platform that matters (macOS: NSWorkspace

accessibilityDisplayShouldReduceMotion; Windows: SPI_GETCLIENTAREAANIMATION)

or set an override for deterministic tests.

Gotchas

not bundled in plugin/app artifacts. The CTest entry exits 3 (Skipped) when

they are missing — that's expected on bare CI runners.

python3 on your PATH. On a Homebrew Mac it can resolve to a framework

Python with no wheels, so every Pillow-backed visual test (including the

frame-stamp --cpp-frames cross-check) reports Skipped while the same

script passes from a shell. Read _Python3_EXECUTABLE in CMakeCache.txt

before trusting a skip, and visual-python-deps-present fails loudly on it.

capture keeps the stamp on its declared layout: a scaled, cropped or

colour-managed capture decodes every frame to -1. All--1 means the

instrument is blind, not that nothing presented. A frozen scene, by

contrast, decodes fine and reports held on every capture after the first;

that is the defect the stamp exists to catch, since similarity scores pass it.

fixtures are rejected outright (no v1 producer ships in the framework). Bumping

the schema is a deliberate break — write a migration tool, don't silently

accept old goldens.

after attach. Tests that count events should either filter it out or pass

through data_event_count(buffer).

origin and screen-origin offsets land when the host surfaces them. Use

ViewGlobal for portable code.

painting children. The presentation walker matches this quirk: a child of a

ScrollView with scale set on the ScrollView itself reports as if the scale

were not there. This is correct relative to what is painted.

schema is a deliberate break — write a migration tool, do not silently

accept old goldens.

publishes inherit it. Pass PublishOptions only when you want to configure

the threshold for that key.

animate_to() / first tick() for CssAnimation). Changing

MotionPreferences::set_override() partway through a running animation

does NOT retroactively re-scale it — the next animation that starts will

pick up the new policy.

emits one final-value Sample and exits. That's the contract — Off is not

"no observability", it's "single snap" — assertions like is_monotonic

and final_value still work.

clear overrides between cases. Forgetting it leaks state into the next

test (and surprises CI when run with --shuffle).

routinely a stack or member object that goes out of scope long before the

process does. The coordinator therefore holds a weak liveness token

alongside the clock pointer and resolves through it, so a clock whose scope

ends leaves the coordinator unbound rather than holding a pointer it will

later dereference. If you add another long-lived observer of a caller-owned

clock, observe it the same way — a raw pointer parked in a singleton is a

use-after-free waiting for the second test in the binary.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.