# Verify Motion

Check that a scene does what the brief asked for. The ball moves right, the title comes first, nothing leaves the frame. Then fix what fails and check again.

`validate` checks that a scene is well formed. `verify` checks that it does the right thing. An agent writes down what the brief expects as checks, such as "the ball moves right during the first second" or "the title appears before the subtitle". Then it runs `motion-sdk verify` and fixes whatever fails. Each failure names the node, the check, what was expected, what the scene actually does, when it happened and the edit that fixes it.

Verify runs natively on the evaluated timeline, with no GPU and no rendering. It uses the same evaluator as the renderer: transforms, opacity, color, the camera, prefabs and SVG parts. A short scene verifies in milliseconds, so an agent can run it after every edit.

Motion graphics research found the same thing. When failed checks went back to the model, it got far more animations right: from about 59% to 94% in one published study.

## The Loop

### Write the Checks From the Brief

Write one check for each thing the brief asks for. Write them before the scene, or alongside it.

```ts title="checks.ts"
import { checks, expect } from "@motion-sdk/scene"

export default checks([
  expect("ball").movesRight({ during: [0, 1] }),
  expect("ball").endsAt([5, 0]),
  expect("ball").staysStill({ during: [1, 2] }),
  expect("ball").staysInFrame(),
])
```

Every method returns a plain `Check` object. `JSON.stringify` the result to get `checks.json`:

```jsonc title="checks.json"
{
  "checks": [
    { "moves": { "node": "ball", "direction": "right", "during": [0, 1] } },
    { "position": { "node": "ball", "value": [5, 0] } },
    { "stays_still": { "node": "ball", "during": [1, 2] } },
    { "stays_in_frame": { "node": "ball" } }
  ]
}
```

### Verify

```bash title="Terminal"
motion-sdk verify scene.json checks.json --json
```

The exit code is `0` when every check passes and `1` otherwise. From Node, `verify()` in `@motion-sdk/scene/verify` runs the CLI and returns the typed report:

```ts title="loop.ts"
import { verify, formatFailures } from "@motion-sdk/scene/verify"

const report = await verify(scene, checksDoc)
if (!report.ok) agent.send(formatFailures(report))
```

### Fix and Verify Again

Apply each `hint`, then run verify again until `ok` is `true`. After that, render a frame and look at it, because checks cover motion, not taste.

## A Failure

Here the ball goes the wrong way: it travels from `x = 5` to `x = -5` instead of from `-5` to `5`.

```text title="motion-sdk verify wrong.json checks.json"
FAIL [0] moves ball (moved_wrong_way): `ball` should move right by at least 0.18 during [0, 1] s; it moved left by 10.00 (from [5.00, 0.00, 0.00] to [-5.00, 0.00, 0.00])
  hint: change `ball`'s `position` keys so it travels right by at least 0.18 (right is world +x here): its world x at 1 s must be at least 5.18
FAIL [1] position ball (wrong_position): `ball` should be at [5.00, 0.00] at 2 s (within 0.09); it is at [-5.00, 0.00], off by 10.00
  hint: move `ball` by [10.00, 0.00, 0.00] at 2 s: edit its `position` key at (or last before) that time, or `transform.position` if it has no track; positions here are world, so subtract any parent offset
2 of 4 checks passed
```

With `--json`, each failure is an object:

```jsonc title="motion-sdk verify wrong.json checks.json --json"
{
  "ok": false,
  "checks": 4,
  "passed": 2,
  "failures": [
    {
      "index": 0,
      "code": "moved_wrong_way",
      "check": "moves",
      "node": "ball",
      "window": [0.0, 1.0],
      "expected": { "direction": "right", "min_distance": 0.18 },
      "actual": { "distance": -10.0, "from": [5.0, 0.0, 0.0], "to": [-5.0, 0.0, 0.0] },
      "message": "`ball` should move right by at least 0.18 during [0, 1] s; it moved left by 10.00 (...)",
      "hint": "change `ball`'s `position` keys so it travels right by at least 0.18 (right is world +x here): its world x at 1 s must be at least 5.18"
    }
  ]
}
```

| Field | Meaning |
| --- | --- |
| `index` | The check's position in `checks`. It's missing for document errors. |
| `code` | A stable code from the list below. |
| `check`, `node`, `other` | The check and the nodes it names. |
| `window` | The `[start, end]` seconds that were checked. |
| `at` | The first time the check failed. |
| `expected`, `actual` | Numbers in world units, seconds, degrees or fractions of the frame. |
| `message` | One sentence comparing expected with actual. |
| `hint` | A concrete edit that fixes the scene. |

The JSON Schemas are `schema/checks.schema.json` and `schema/verify-report.schema.json`. `@motion-sdk/scene` exports the same types as `Checks`, `Check` and `VerifyReport`.

## How It Measures

- **Time.** The timeline is sampled at `fps`, which defaults to 60 per second, plus the exact start and end of every window. `during` defaults to the whole timeline. `[t, t]` checks a single instant. The end of the timeline means its last pose, even when the timeline loops.
- **Position.** World position of the node's origin, in world units. `[x, y]` ignores z. Children include their parents' motion.
- **Direction.** Measured as seen from the camera. "Right" is the camera's right, and the hint names the world axis when it matches one. A move counts its net travel over the window. The default `min_distance` is 2% of the frame height at the node.
- **Screen checks.** `overlaps`, `does_not_overlap`, `relative` and `stays_in_frame` project the bounds of the node and everything under it through the scene camera, at the canvas aspect ratio. Bounds come from the geometry: boxes, spheres, shapes, SVG parts and strokes. Text size is estimated from its character count. Models and particles count as points. Hidden parts don't count.
- **Shown.** A node is shown when it and its parents are visible and its combined opacity is above 0.01. `stays_in_frame` skips samples where the node is hidden.
- **Rotation and scale.** Rotation is the node's own Euler angle relative to its parent, as a signed change, so 360 is one full turn. Scale is the mean of its three components.
- **Color.** The animated `color`, else the node's `color`, else its material's color. Each RGB channel must be within `tol`.

## Checks

Each check is an object with a single key. `node` accepts generated ids too, such as `lamps.3.bulb` or `painter#arm`.

| Check | TypeScript | Passes when |
| --- | --- | --- |
| `moves` | `movesRight()`, `movesLeft()`, `movesUp()`, `movesDown()`, `movesToward()`, `movesAway()`, `moves(dir)` | Net travel in that screen direction is at least `min_distance` |
| `stays_still` | `staysStill()` | The position drifts by no more than `tol` |
| `position` | `endsAt(p)`, `startsAt(p)`, `isAt(p, t)` | The world position at `at` is within `tol` of `value` |
| `rotates` | `rotates(deg, { axis })` | The rotation changes by `degrees` (within 2 degrees by default) |
| `scales` | `scales(factor)`, `scalesTo(s)` | The scale changes by `factor`, or ends at `to` |
| `visible` / `hidden` | `visibleDuring(w)`, `visibleAt(t)`, `hiddenDuring(w)`, `hiddenAt(t)` | The node is shown, or hidden, at every sample |
| `fades_in` / `fades_out` | `fadesIn()`, `fadesOut()` | Opacity goes from 0.1 or less to 0.9 or more, or the reverse |
| `appears_before` | `appearsBefore(other, { gap })` | The node is first shown before `other` |
| `before` | `before(other, { gap })` | The node finishes animating before `other` starts |
| `overlaps` | `overlaps(other, { throughout })` | The on-screen bounds touch at some sample, or at every sample |
| `does_not_overlap` | `doesNotOverlap(other)` | The on-screen bounds never touch |
| `relative` | `rightOf()`, `leftOf()`, `above()`, `below()`, `inFrontOf()`, `behind()` | The node's centre is on that side of `other`'s at every sample |
| `stays_in_frame` | `staysInFrame({ margin })` | The bounds stay inside the frame, less `margin` |
| `color` | `colorIs(c, { at })` | The color is within `tol` per channel |
| `planted` | `planted({ during })` | The node slides at most `tol_px` canvas pixels on screen (default 4), such as an ankle during a [plant](/docs/features/rigging#planted-feet) window |
| `reaches` | `reaches(target)` | An [IK](/docs/features/rigging#ik) end is within `tol_px` pixels of its goal at every sample (default 2) |
| `attached` | `attachedTo(to)` | The node keeps its offset from `to`, as if parented to it, within `tol_px` pixels (default 2) |
| `lifts` | `lifts({ during, min })` | Over one swing, the node's highest point on screen is at least `min` (a fraction of the frame height, default 0.02) above the higher of its start and end, such as an ankle through a [walk](/docs/guides/walk-cycle) swing |

`expectIn(scene)` gives you an `expect` limited to that scene's node ids, so a typo becomes a compile error.

## Custom Checks

When a brief says something the built-in checks can't, write the check as code. `custom(name, (trace) => ...)` goes in the same `checks([...])` list. `verify()` runs the built-in checks in the CLI. It then samples the timeline once with `motion-sdk verify --trace` and runs your functions against it in Node, so every failure lands in one report.

```ts title="checks.ts"
import { checks, custom, expect } from "@motion-sdk/scene";
import { formatFailures, verify } from "@motion-sdk/scene/verify";

const doc = checks([
  expect("arm").staysInFrame(),
  custom("arm swings faster than head", (trace) => {
    const arm = trace.node("arm").max("angularSpeed");
    const head = trace.node("head").max("angularSpeed");
    return arm.value > 2 * head.value || {
      message: `arm peaks at ${arm.value.toFixed(0)}°/s, head at ${head.value.toFixed(0)}°/s`,
      hint: "Widen the arm's rotation keyframes so it swings at least twice as fast as the head.",
      node: "arm",
      at: arm.t,
    };
  }),
]);

const report = await verify("scene.json", doc);
if (!report.ok) console.log(formatFailures(report));
```

```text title="Output"
[1] custom "arm swings faster than head" custom_check_failed: arm peaks at 33°/s, head at 66°/s
  fix: Widen the arm's rotation keyframes so it swings at least twice as fast as the head.
1 of 2 checks passed
```

A check passes when it returns `true` (or nothing). It fails when it returns `false` or a failure `{ message, hint, node?, other?, window?, at?, expected?, actual? }`. A failure becomes a `VerifyFailure` with `check: "custom"`, its `name` and the code `custom_check_failed`, so it reads the same as a built-in failure. When the function throws, for example because it names a node that isn't in the scene, you get a `custom_check_error` failure with the error message instead of a crash. Checks can be `async`.

### The Trace

`trace.node(id)` gives you one node over the timeline. Ids are the same as in the built-in checks, generated ids included.

| Method | Returns |
| --- | --- |
| `at(t)` | The nearest sample: `position`, `rotation` (degrees), `scale`, `opacity`, `shown`, `color` (hex) and `rgb`, `bounds` and `center` (frame fractions, y from the top, `null` when hidden), `frameHeight` |
| `points(during?)` | Every sample in a window |
| `velocity(t)`, `speed(t)` | World velocity and speed, in units per second |
| `angularSpeed(t, axis?)` | Rotation speed in degrees per second, about z by default |
| `series(key, during?)` | Values over time: `"x"`, `"y"`, `"z"`, `"rotation.z"`, `"scale.y"`, `"opacity"`, `"speed"`, `"angularSpeed"`, a function of the sample, or a whole `"position"`, `"rotation"` or `"scale"` |
| `max(key, during?)`, `min(key, during?)` | `{ t, value }` of the extreme |
| `peaks(key, opts?)`, `valleys(key, opts?)` | Times of local maxima or minima; `prominence` ignores smaller wiggles |
| `firstTime(pred)`, `lastTime(pred)` | The first or last time a predicate holds, or `undefined` |
| `every(pred, during?)`, `some(pred, during?)` | Whether a predicate holds at every sample, or at any |

`trace.times`, `trace.duration`, `trace.fps` and `trace.ids()` describe the sampling. `trace.during([a, b])` lists the sample times in a window. Sampling uses the checks document's `fps` (60 by default). The `nodes` option of `verify()` limits the trace to the nodes your checks read.

### More Examples

```ts title="checks.ts"
import { checks, custom } from "@motion-sdk/scene";

const words = [0.3, 0.9, 1.5]; // from the voice-over

export default checks([
  // "The ball bounces three times."
  custom("ball bounces 3 times", (trace) => {
    const ball = trace.node("ball");
    const hits = ball.valleys("y", { prominence: 0.5 }).filter((t) => ball.at(t).position[1] < -2);
    return hits.length === 3 || {
      message: `the ball touches the floor ${hits.length} times`,
      hint: "Add an up-and-down keyframe pair per bounce: three floor contacts in total.",
      node: "ball",
      expected: 3,
      actual: hits.length,
    };
  }),
  // "The mouth opens on each word."
  custom("mouth open at each word", (trace) => {
    const late = words.find((t) => trace.node("mouth").at(t).scale[1] < 0.6);
    return late === undefined || {
      message: `the mouth is closed on the word at ${late}s`,
      hint: "Put each open-mouth scale key on the word's time, not after it.",
      node: "mouth",
      at: late,
    };
  }),
]);
```

### The Raw Trace

`motion-sdk verify scene.json --trace` prints the same data as JSON, for checks in another language. Each node has per-sample arrays (`position`, `rotation`, `scale`, `opacity`, `color`, `bounds` and `frame_height`) that line up with `times`. `--nodes arm,head` keeps only those nodes, and `--fps` sets the sample rate. The schema is `schema/trace.schema.json`, and `@motion-sdk/scene` exports it as `TraceData`. `trace(scene)` from `@motion-sdk/scene/verify` returns it already wrapped as a `Trace`.

## Benchmark

`examples/verify/` holds 14 short briefs in the style of motion graphics benchmarks. Each has a correct scene, a scene with a typical agent mistake and the checks that tell them apart. The mistakes include a slide going the wrong way, a subtitle arriving too early, a clockwise turn instead of counter-clockwise, a logo growing out of frame, cars sharing a lane, a moon dipping behind its planet, motions that overlap in time and a caption that never fades. A test keeps the score at 14 of 14: every correct scene passes and every wrong scene fails with the listed codes. `examples/verify/custom/` adds 4 briefs that need custom checks: an arm that must swing faster than the head, a ball that must bounce three times, a mouth that must open on each word and a card that must ease into place. Each has a `checks.ts` and the committed traces of both scenes, and a test runs the checks on them. `examples/gen/gen_verify.py` regenerates them.

## Failure Codes

### `invalid_scene`

The scene has validation errors, so nothing was checked.

### `invalid_checks`

The checks document does not parse, or a check is malformed.

### `unknown_node`

A check names a node that is not in the scene (after expansion).

### `empty_window`

The window ends before it starts.

### `moved_too_little`

The node moved the right way, but not far enough.

### `moved_wrong_way`

The node moved the opposite way.

### `not_still`

The node moved during a window where it should stay still.

### `wrong_position`

The node is not at the expected position.

### `wrong_rotation`

The rotation changed by the wrong amount.

### `wrong_scale`

The scale changed by the wrong amount.

### `not_visible`

The node is hidden or transparent when it should be shown.

### `not_hidden`

The node is shown when it should be hidden.

### `never_appears`

The node is never shown.

### `appears_too_late`

The node appears at the same time as, or after, the other.

### `not_fading_in`

Opacity does not go from low to high over the window.

### `not_fading_out`

Opacity does not go from high to low over the window.

### `no_overlap`

The two nodes never touch on screen (or not throughout).

### `unexpected_overlap`

The two nodes touch on screen when they should not.

### `wrong_side`

The node is on the wrong side of the other.

### `out_of_frame`

Part of the node leaves the frame.

### `wrong_color`

The node has a different color.

### `no_motion`

One of the two nodes never animates, so there is no order to check.

### `motion_out_of_order`

The node's animation overlaps or follows the other's.

### `custom_check_failed`

A custom check returned `false` or a failure. The message and hint are the ones the check wrote.

### `custom_check_error`

A custom check threw, so its result is unknown. The message carries the error, such as a node id that isn't in the scene.

### `foot_slid`

A planted node slid on screen during its window. Drive the foot with `ik` toward a top-level goal and give the goal a `plant` window, or `walk()` the character.

### `ik_unreached`

An IK end didn't reach its goal: the goal is further than the chain's length, `soft` stops it short, or nothing drives the end. Move the goal's keys closer or lengthen the chain.

### `drifted`

The node moved away from the node it should stay with. Add `"constrain": [{"attach": {"to": "..."}}]` or parent it.

### `low_lift`

A swing foot didn't rise far enough on screen. Raise `lift` in `walk()` (or the goal's mid-swing keys). In a front view the step toward the camera moves the foot down the screen, so it needs more lift than a side view to read.
