diff --git a/.fallowrc.jsonc b/.fallowrc.jsonc
index bb5010e282..c62d63c151 100644
--- a/.fallowrc.jsonc
+++ b/.fallowrc.jsonc
@@ -35,6 +35,7 @@
"packages/cli/src/commands/layout-audit.browser.js",
"packages/cli/src/commands/contrast-audit.browser.js",
"packages/cli/src/commands/motion-sample.browser.js",
+ "packages/cli/src/commands/motion-signature.browser.js",
// Worker entry points loaded dynamically by their *Pool.ts companions.
"packages/producer/src/services/pngDecodeBlitWorker.ts",
"packages/producer/src/services/shaderTransitionWorker.ts",
diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx
index aecb67293f..b816e22425 100644
--- a/docs/packages/cli.mdx
+++ b/docs/packages/cli.mdx
@@ -715,6 +715,12 @@ HTML. Without a sidecar, nothing changes.
| `staysInFrame(selector)` | Off-frame drift — once visible, the box never leaves the canvas (`motion_off_frame`) |
| `keepsMoving(withinSelector?)` | A frozen shot — no fully static window longer than `maxStaticSec`, default 2s (`motion_frozen`) |
+`keepsMoving` uses the same motion classifier as the frozen-sweep guard: box
+geometry, opacity, text and generated content, form-control state, painted CSS
+counters, clip-path, variable-font axes, and the pixels of visible
+canvas/video/img elements all count as motion — so a playing same-origin (or
+CORS-readable) background video keeps a scope live on its own. Elements under
+`data-layout-ignore` never count.
`duration`, `keepsMoving.withinSelector`, and `keepsMoving.maxStaticSec` are
optional. Findings use the same shape and envelope as layout findings and are
errors by default, so a failed assertion fails the run. A selector that matches
diff --git a/packages/cli/scripts/build-copy.mjs b/packages/cli/scripts/build-copy.mjs
index 55f198e91a..52f3136499 100644
--- a/packages/cli/scripts/build-copy.mjs
+++ b/packages/cli/scripts/build-copy.mjs
@@ -104,6 +104,11 @@ async function main() {
cpSync(contrastAuditScript, join(DIST, "commands", "contrast-audit.browser.js"));
}
+ const motionSignatureScript = join(CLI_ROOT, "src", "commands", "motion-signature.browser.js");
+ if (existsSync(motionSignatureScript)) {
+ cpSync(motionSignatureScript, join(DIST, "commands", "motion-signature.browser.js"));
+ }
+
const motionSampleScript = join(CLI_ROOT, "src", "commands", "motion-sample.browser.js");
if (existsSync(motionSampleScript)) {
cpSync(motionSampleScript, join(DIST, "commands", "motion-sample.browser.js"));
diff --git a/packages/cli/src/commands/layout-audit.browser.js b/packages/cli/src/commands/layout-audit.browser.js
index 057ddaf471..1ac087bc89 100644
--- a/packages/cli/src/commands/layout-audit.browser.js
+++ b/packages/cli/src/commands/layout-audit.browser.js
@@ -1629,163 +1629,10 @@
return contentOverlapIssues(root, time);
};
- // Frozen-sweep guard (#U10, checkPipeline.ts): a compact per-sample
- // fingerprint of every visible element's box, opacity, and rendered text
- // state, in DOM order. Node
- // calls this once per seeked grid point and compares the strings across the
- // whole run — if every sample produces the identical string, the seek never
- // actually moved anything and the whole audit run is unreliable. Deliberately
- // a single opaque string (not a structured array) since Node only ever needs
- // equality, not per-element diffing.
- // Pixel-only media motion (a 2D/WebGL canvas repainting or a playing video
- // without any element moving) is invisible to a DOM-state fingerprint
- // and false-positives sweep_static. Downsample each visible canvas/video to
- // 8x8 and fold its pixels into the fingerprint. Tainted, zero-sized, or
- // unreadable media hashes to a constant — no worse than DOM-state-only
- // detection and never a new false negative for DOM-motion compositions.
- // Media inside iframes is intentionally outside this fingerprint: it lives
- // in a separate document, and cross-origin frames are inaccessible under SOP.
- function mediaPixelHash(element) {
- try {
- const rect = element.getBoundingClientRect();
- const sourceWidth = element.videoWidth || element.width || rect.width;
- const sourceHeight = element.videoHeight || element.height || rect.height;
- if (!sourceWidth || !sourceHeight) return "x";
- const off = document.createElement("canvas");
- off.width = 8;
- off.height = 8;
- const ctx = off.getContext("2d");
- if (!ctx) return "x";
- ctx.drawImage(element, 0, 0, 8, 8);
- const data = ctx.getImageData(0, 0, 8, 8).data;
- let hash = 0;
- for (let i = 0; i < data.length; i++) hash = (hash * 31 + data[i]) >>> 0;
- return String(hash);
- } catch {
- return "x";
- }
- }
-
- function foldFingerprintField(hash, value) {
- hash ^= value.length;
- hash = Math.imul(hash, 16777619);
- for (let i = 0; i < value.length; i++) {
- hash ^= value.charCodeAt(i);
- hash = Math.imul(hash, 16777619);
- }
- return hash;
- }
-
- function cssFingerprintValue(value) {
- return value === "none" || value === "normal" ? "" : value || "";
- }
-
- function foldCounterState(hash, style) {
- hash = foldFingerprintField(hash, cssFingerprintValue(style.counterReset));
- hash = foldFingerprintField(hash, cssFingerprintValue(style.counterIncrement));
- return foldFingerprintField(hash, cssFingerprintValue(style.counterSet));
- }
-
- function counterStateHash(style) {
- const reset = cssFingerprintValue(style.counterReset);
- const increment = cssFingerprintValue(style.counterIncrement);
- const set = cssFingerprintValue(style.counterSet);
- if (!reset && !increment && !set) return "";
- let hash = 2166136261;
- hash = foldCounterState(hash, style);
- return (hash >>> 0).toString(36);
- }
-
- function foldLiveControlState(hash, element) {
- if (element.tagName === "INPUT") {
- hash = foldFingerprintField(hash, element.type || "");
- hash = foldFingerprintField(hash, element.value || "");
- hash = foldFingerprintField(hash, element.checked ? "1" : "0");
- return foldFingerprintField(hash, element.indeterminate ? "1" : "0");
- }
- if (element.tagName === "TEXTAREA") {
- return foldFingerprintField(hash, element.value || "");
- }
- if (element.tagName !== "SELECT") return foldFingerprintField(hash, "");
- hash = foldFingerprintField(hash, String(element.selectedIndex));
- hash = foldFingerprintField(hash, element.value || "");
- for (let i = 0; i < element.options.length; i++) {
- hash = foldFingerprintField(hash, element.options[i].selected ? "1" : "0");
- }
- return hash;
- }
-
- function textualStateHash(element, style) {
- // Chromium resolves attr() here, so pseudo computed content is the
- // platform-owned rendered value rather than a CSS expression to reparse.
- const before = getComputedStyle(element, "::before");
- const after = getComputedStyle(element, "::after");
- // Visible descendants are fingerprinted separately; direct nodes prevent
- // a hidden descendant's text mutation from masquerading as visible motion.
- let directText = "";
- for (const node of directTextNodes(element)) {
- directText += node.textContent || "";
- }
- let hash = 2166136261;
- hash = foldFingerprintField(hash, directText);
- hash = foldLiveControlState(hash, element);
- hash = foldFingerprintField(hash, cssFingerprintValue(before.content));
- hash = foldFingerprintField(hash, cssFingerprintValue(after.content));
- hash = foldCounterState(hash, style);
- hash = foldCounterState(hash, before);
- hash = foldCounterState(hash, after);
- return (hash >>> 0).toString(36);
- }
-
- window.__hyperframesLayoutGeometry = function collectLayoutGeometry() {
- const root =
- document.querySelector("[data-composition-id][data-width][data-height]") ||
- document.querySelector("[data-composition-id]") ||
- document.body;
- const allElements = [root, ...root.querySelectorAll("*")];
- const elements = allElements.filter((element) => isVisibleElement(element));
- const parts = elements.map((element) => {
- const rect = toRect(element.getBoundingClientRect());
- const opacity = round(opacityChain(element));
- // Variable-font axis animation (font-variation-settings) is a real,
- // visible motion channel that moves no geometry and no opacity, so a
- // box+opacity+text fingerprint reads it as a frozen timeline. Worse in a
- // DUPLEXED face (Recursive holds an identical advance width at every
- // weight by design), where not even the line width shifts — the whole
- // run then false-positives sweep_static. Fold the computed axis string
- // in; it is "normal" for every element that does not use it, so this
- // adds nothing to the fingerprint of an ordinary composition.
- const style = getComputedStyle(element);
- const axes = style.fontVariationSettings;
- const textState = textualStateHash(element, style);
- return `${rect.left},${rect.top},${rect.width},${rect.height},${opacity},${
- axes && axes !== "normal" ? axes : ""
- },${textState}`;
- });
- const visibleElements = new Set(elements);
- for (let ancestor = root.parentElement; ancestor; ancestor = ancestor.parentElement) {
- const state = counterStateHash(getComputedStyle(ancestor));
- if (state) parts.push(`c:${state}`);
- }
- // Counter declarations can live on zero-box owners while a visible
- // descendant's ::before/::after paints the resulting value.
- for (const element of allElements) {
- if (visibleElements.has(element)) continue;
- const state = counterStateHash(getComputedStyle(element));
- if (state) parts.push(`c:${state}`);
- }
- // img shares the same pixel-only-motion blind spot as canvas/video: an
- // equal-size, equal-position opaque src/visibility swap moves no
- // geometry and no opacity. mediaPixelHash already handles it generically
- // (drawImage accepts any CanvasImageSource; width/height fall back to
- // rect.width/height same as canvas/video), so only the element selector
- // needed widening.
- for (const media of root.querySelectorAll("canvas, video, img")) {
- if (!isVisibleElement(media)) continue;
- parts.push(`p:${mediaPixelHash(media)}`);
- }
- return parts.join("|");
- };
+ // The frozen-sweep fingerprint (window.__hyperframesLayoutGeometry, #U10 in
+ // checkPipeline.ts) lives in motion-signature.browser.js, the single owner
+ // of "what counts as motion" shared with motion-sample.browser.js's
+ // liveness signature.
// Rotation-pivot sampling (rotation_pivot_drift). Per sample, report every
// rotatable candidate's bbox center, size, and current rotation angle. Node
diff --git a/packages/cli/src/commands/layout-audit.browser.test.ts b/packages/cli/src/commands/layout-audit.browser.test.ts
index d8cb203845..ad76a0556d 100644
--- a/packages/cli/src/commands/layout-audit.browser.test.ts
+++ b/packages/cli/src/commands/layout-audit.browser.test.ts
@@ -31,400 +31,6 @@ describe("layout-audit.browser", () => {
clearGeometryCollector();
});
- it("changes the sweep fingerprint when visible video pixels advance", () => {
- document.body.innerHTML = `
-
-
-
- `;
- installGeometry({
- root: rect({ left: 0, top: 0, width: 640, height: 360 }),
- footage: rect({ left: 0, top: 0, width: 640, height: 360 }),
- });
-
- let pixelValue = 20;
- const getContextSpy = vi.spyOn(HTMLCanvasElement.prototype, "getContext") as unknown as {
- mockReturnValue(value: CanvasRenderingContext2D): void;
- };
- getContextSpy.mockReturnValue({
- drawImage() {},
- getImageData() {
- return { data: new Uint8ClampedArray(8 * 8 * 4).fill(pixelValue) };
- },
- } as unknown as CanvasRenderingContext2D);
-
- installAuditScript();
- const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string })
- .__hyperframesLayoutGeometry;
- const before = collect();
- pixelValue = 220;
- const after = collect();
-
- expect(after).not.toBe(before);
- });
-
- // PRINFRA-666: an equal-size, equal-position opaque src/visibility
- // swap (the authoring pattern for a paused-GSAP-cursor-driven "reveal
- // frame N of a still sequence" composition) moves no geometry and no
- // opacity, so it was invisible to the fingerprint and false-positived
- // sweep_static — mediaPixelHash already existed for exactly this pixel-only
- // motion class, it just wasn't applied to img.
- it("changes the sweep fingerprint when a same-size opaque img is swapped", () => {
- document.body.innerHTML = `
-
-
-
- `;
- installGeometry({
- root: rect({ left: 0, top: 0, width: 640, height: 360 }),
- frame: rect({ left: 0, top: 0, width: 640, height: 360 }),
- });
-
- let pixelValue = 20;
- const getContextSpy = vi.spyOn(HTMLCanvasElement.prototype, "getContext") as unknown as {
- mockReturnValue(value: CanvasRenderingContext2D): void;
- };
- getContextSpy.mockReturnValue({
- drawImage() {},
- getImageData() {
- return { data: new Uint8ClampedArray(8 * 8 * 4).fill(pixelValue) };
- },
- } as unknown as CanvasRenderingContext2D);
-
- installAuditScript();
- const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string })
- .__hyperframesLayoutGeometry;
- const before = collect();
- pixelValue = 220;
- const after = collect();
-
- expect(after).not.toBe(before);
- });
-
- // Opacity-reveal fixture (CLI feedback digest 2026-07-14): code-typing style
- // scenes reveal pre-laid-out characters via opacity only — no geometry ever
- // moves. The sweep fingerprint must treat that as motion, both while a glyph
- // fades (opacity value changes) and when it crosses the 0.2 visibility floor
- // (element enters the signature); otherwise `check` misfires `sweep_static`
- // and authors reach for geometry hacks (a slow host y-drift) to pass.
- it("changes the sweep fingerprint when text reveals via opacity alone", () => {
- document.body.innerHTML = `
-
-
c
-
- `;
-
- let charOpacity = "0";
- installGeometry(
- {
- root: rect({ left: 0, top: 0, width: 640, height: 360 }),
- code: rect({ left: 40, top: 40, width: 560, height: 48 }),
- char: rect({ left: 40, top: 40, width: 18, height: 48 }),
- },
- {
- char: {
- get opacity() {
- return charOpacity;
- },
- } as Partial,
- },
- );
-
- installAuditScript();
- const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string })
- .__hyperframesLayoutGeometry;
-
- const hidden = collect(); // below the 0.2 visibility floor — not in the signature
- charOpacity = "0.5";
- const fading = collect(); // mid-fade — present, opacity part of the signature
- charOpacity = "1";
- const revealed = collect(); // settled
-
- expect(fading).not.toBe(hidden);
- expect(revealed).not.toBe(fading);
- });
-
- // Variable-font axis animation (registry block `weight-wave`): a crest of
- // weight travels along a headline by rewriting each character's
- // font-variation-settings, and NOTHING else changes — no geometry, no
- // opacity, no canvas. A duplexed face makes it total: Recursive holds one
- // advance width at every weight by design, so not even the line width
- // shifts and all six sweep samples hashed identically until the axis string
- // joined the fingerprint. `check` then failed a working composition with
- // sweep_static, and the documented remedies (spread the reveal, keep an
- // element animating) cannot help — the motion is real, the fingerprint was
- // just blind to it.
- it("changes the sweep fingerprint when only font-variation-settings moves", () => {
- document.body.innerHTML = `
-
-
P
-
- `;
-
- let axes = '"wght" 400, "slnt" 0';
- installGeometry(
- {
- root: rect({ left: 0, top: 0, width: 640, height: 360 }),
- line: rect({ left: 40, top: 40, width: 560, height: 48 }),
- char: rect({ left: 40, top: 40, width: 18, height: 48 }),
- },
- {
- char: {
- get fontVariationSettings() {
- return axes;
- },
- } as Partial,
- },
- );
-
- installAuditScript();
- const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string })
- .__hyperframesLayoutGeometry;
-
- const rest = collect();
- axes = '"wght" 1000, "slnt" -12'; // the crest arrives over this character
- const crest = collect();
-
- expect(crest).not.toBe(rest);
- });
-
- // The other direction, and it guards the more dangerous failure: a
- // fingerprint that varies on its own would make sweep_static unfireable and
- // every green layout verdict meaningless. Identical scene, axes included,
- // must hash identically.
- it("keeps the sweep fingerprint identical when nothing moves, font axes included", () => {
- document.body.innerHTML = `
-
@@ -3324,23 +2930,13 @@ function rangeTextRect(selected: Node | null, rects: Record): D
function installGeometry(
rects: Record,
styleOverrides: Record> = {},
- pseudoStyleOverrides: Record<
- string,
- { before?: Partial; after?: Partial }
- > = {},
): void {
// Style-fixture branching mirrors the audit's per-property reads; splitting
// it would scatter one mock across helpers.
// fallow-ignore-next-line complexity
- vi.spyOn(window, "getComputedStyle").mockImplementation((element, pseudoElement) => {
+ vi.spyOn(window, "getComputedStyle").mockImplementation((element) => {
const el = element as Element;
const isBubble = el.id === "bubble";
- const pseudoOverride =
- pseudoElement === "::before"
- ? pseudoStyleOverrides[el.id]?.before
- : pseudoElement === "::after"
- ? pseudoStyleOverrides[el.id]?.after
- : undefined;
return {
display: "block",
visibility: "visible",
@@ -3364,7 +2960,6 @@ function installGeometry(
paddingLeft: isBubble ? "16px" : "0px",
fontSize: "36px",
...styleOverrides[el.id],
- ...pseudoOverride,
} as unknown as CSSStyleDeclaration;
});
diff --git a/packages/cli/src/commands/layout.ts b/packages/cli/src/commands/layout.ts
index 42bd3bb305..1159a33236 100644
--- a/packages/cli/src/commands/layout.ts
+++ b/packages/cli/src/commands/layout.ts
@@ -390,6 +390,7 @@ async function runMotionPass(
width: window.innerWidth,
height: window.innerHeight,
}));
+ await page.addScriptTag({ content: loadBrowserScript("motion-signature.browser.js") });
await page.addScriptTag({ content: loadBrowserScript("motion-sample.browser.js") });
const frames = await collectMotionFrames(page, times, selectors, livenessScopes);
return { issues: evaluateMotion(frames, spec.assertions, canvas), sampleCount: frames.length };
diff --git a/packages/cli/src/commands/motion-sample.browser.js b/packages/cli/src/commands/motion-sample.browser.js
index 9d3e520d5f..b136dad0f0 100644
--- a/packages/cli/src/commands/motion-sample.browser.js
+++ b/packages/cli/src/commands/motion-sample.browser.js
@@ -4,7 +4,13 @@
// scope it returns a bucketed signature of all visible elements, so the Node-side
// evaluator can detect frozen windows by comparing signatures across frames.
(function () {
- const IGNORE_TAGS = new Set(["SCRIPT", "STYLE", "TEMPLATE", "NOSCRIPT", "META", "LINK"]);
+ // Visibility, opacity, and the liveness signature all come from the shared
+ // motion classifier so this sampler and the frozen-sweep guard can never
+ // disagree on what counts as motion (see motion-signature.browser.js).
+ const shared = window.__hyperframesMotionSignature;
+ if (!shared) {
+ throw new Error("motion-signature.browser.js must be injected before motion-sample.browser.js");
+ }
function round(value) {
return Math.round(value * 100) / 100;
@@ -21,71 +27,15 @@
};
}
- function opacityChain(element) {
- let opacity = 1;
- for (let current = element; current; current = current.parentElement) {
- const parsed = Number.parseFloat(getComputedStyle(current).opacity || "1");
- if (Number.isFinite(parsed)) opacity *= parsed;
- }
- return opacity;
- }
-
- // Mirrors layout-audit.browser.js isVisibleElement.
- // fallow-ignore-next-line complexity
- function isVisibleElement(element) {
- if (IGNORE_TAGS.has(element.tagName)) return false;
- const style = getComputedStyle(element);
- if (
- style.display === "none" ||
- style.visibility === "hidden" ||
- style.visibility === "collapse"
- ) {
- return false;
- }
- if (opacityChain(element) < 0.2) return false;
- const rect = element.getBoundingClientRect();
- return rect.width > 0.5 && rect.height > 0.5;
- }
-
function sampleElement(element) {
const rect = element.getBoundingClientRect();
return {
rect: toRect(rect),
- opacity: round(opacityChain(element)),
- visible: isVisibleElement(element),
+ opacity: round(shared.opacityChain(element)),
+ visible: shared.isVisibleElement(element),
};
}
- function compositionRoot() {
- return document.querySelector("[data-composition-id]") || document.body;
- }
-
- // ponytail: bucket position to 2px and opacity to 0.08 so the RFC's "moves ≥2px /
- // opacity ≥0.08" thresholds fall out of bucketing. Boundary-straddling moves are
- // approximate — good enough for liveness; tighten only if false negatives show up.
- function elementSignature(element) {
- const rect = element.getBoundingClientRect();
- const bx = Math.round(rect.left / 2);
- const by = Math.round(rect.top / 2);
- const bw = Math.round(rect.width / 2);
- const bh = Math.round(rect.height / 2);
- const bo = Math.round(opacityChain(element) / 0.08);
- return bx + "," + by + "," + bw + "," + bh + "," + bo;
- }
-
- function livenessSignature(root) {
- if (!root) return "";
- const parts = [];
- // ponytail: O(DOM) × MOTION_MAX_SAMPLES (300) — fine for typical compositions;
- // narrow selector (e.g. "[id],[class]") if heavy-DOM compositions slow this down.
- const all = root.querySelectorAll("*");
- for (const element of all) {
- if (!isVisibleElement(element)) continue;
- parts.push(elementSignature(element));
- }
- return parts.join("|");
- }
-
function safeQuery(selector) {
try {
return document.querySelector(selector);
@@ -108,8 +58,12 @@
function sampleLiveness(scopes) {
const liveness = {};
for (const scope of scopes) {
- const root = scope === "*" ? compositionRoot() : safeQuery(scope);
- liveness[scope] = livenessSignature(root);
+ const root = scope === "*" ? shared.compositionRoot() : safeQuery(scope);
+ // ponytail: O(DOM) × MOTION_MAX_SAMPLES (300), with three computed-style
+ // reads (element + ::before/::after) plus an ancestor walk per box-generating
+ // element — fine for typical compositions; narrow the scope if heavy-DOM
+ // compositions slow down.
+ liveness[scope] = shared.compositionSignature(root, { quantize: true });
}
return liveness;
}
diff --git a/packages/cli/src/commands/motion-sample.browser.test.ts b/packages/cli/src/commands/motion-sample.browser.test.ts
index d8003cf646..0db96bbaaa 100644
--- a/packages/cli/src/commands/motion-sample.browser.test.ts
+++ b/packages/cli/src/commands/motion-sample.browser.test.ts
@@ -6,6 +6,7 @@ import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
+const signatureScript = readFileSync(join(__dirname, "motion-signature.browser.js"), "utf-8");
const script = readFileSync(join(__dirname, "motion-sample.browser.js"), "utf-8");
interface Geo {
@@ -13,6 +14,8 @@ interface Geo {
opacity?: string;
display?: string;
visibility?: string;
+ /** `::after` computed `content`; re-read on every call when a getter. */
+ afterContent?: string;
}
interface SampleResult {
@@ -24,8 +27,13 @@ interface SampleResult {
}
function installGeometry(byId: Record): void {
- vi.spyOn(window, "getComputedStyle").mockImplementation((element) => {
+ vi.spyOn(window, "getComputedStyle").mockImplementation((element, pseudoElement) => {
const geo = byId[(element as Element).id] ?? {};
+ if (pseudoElement) {
+ return {
+ content: pseudoElement === "::after" ? (geo.afterContent ?? "none") : "none",
+ } as unknown as CSSStyleDeclaration;
+ }
return {
display: geo.display ?? "block",
visibility: geo.visibility ?? "visible",
@@ -47,6 +55,9 @@ function installGeometry(byId: Record): void {
}
function installScript(): void {
+ // The sampler reads the shared motion classifier at install time.
+ // eslint-disable-next-line no-new-func
+ new Function(signatureScript)();
// eslint-disable-next-line no-new-func
new Function(script)();
}
@@ -62,6 +73,13 @@ describe("motion-sample.browser", () => {
vi.restoreAllMocks();
document.body.innerHTML = "";
delete (window as unknown as { __hyperframesMotionSample?: unknown }).__hyperframesMotionSample;
+ Reflect.deleteProperty(window, "__hyperframesMotionSignature");
+ Reflect.deleteProperty(window, "__hyperframesLayoutGeometry");
+ });
+
+ it("throws at install when the shared motion classifier is missing", () => {
+ // eslint-disable-next-line no-new-func
+ expect(() => new Function(script)()).toThrow(/motion-signature\.browser\.js/);
});
it("samples a present, visible selector and returns null for an absent one", () => {
@@ -79,6 +97,18 @@ describe("motion-sample.browser", () => {
expect(result.data["#missing"]).toBeNull();
});
+ it("reports an explicitly asserted data-layout-ignore element as visible", () => {
+ document.body.innerHTML = `
+
x
+ `;
+ installGeometry({ glow: { rect: { left: 100, top: 50, width: 300, height: 80 } } });
+ installScript();
+
+ // The layout-audit opt-out excludes the layer from liveness, not from an
+ // assertion that names it.
+ expect(sample({ selectors: ["#glow"] }).data["#glow"]?.visible).toBe(true);
+ });
+
it("reflects inherited ancestor opacity", () => {
document.body.innerHTML = `
Hi
@@ -114,6 +144,46 @@ describe("motion-sample.browser", () => {
expect(moved).not.toBe(before);
});
+ // Liveness and the frozen-sweep guard share one classifier: a fixed-width
+ // attr()-backed countdown that the sweep guard accepts as motion must not be
+ // reported frozen by keepsMoving.
+ it("changes the liveness signature when attr-backed generated content changes, in step with the sweep fingerprint", () => {
+ document.body.innerHTML = `
+
',
+ ),
+ );
+ // Blink leaves counter() unsubstituted in computed content, so the only
+ // signal is the owner's counter state.
+ expect(
+ await page.evaluate(
+ () => getComputedStyle(document.getElementById("countdown")!, "::after").content,
+ ),
+ ).toBe("counter(countdown)");
+ const before = await sample();
+ await mutate('document.getElementById("owner").style.counterReset = "countdown 9"');
+ const after = await sample();
+
+ expect(after.sweep).not.toBe(before.sweep);
+ expect(after.liveness).not.toBe(before.liveness);
+ });
+
+ it("sees a counter painted by a zero-box host's absolutely positioned pseudo-element", async () => {
+ await load(
+ composition(
+ "body { counter-reset: countdown 10; } #host { width: 0; height: 0; } #host::after { position: absolute; left: 100px; top: 100px; content: counter(countdown); }",
+ '',
+ ),
+ );
+ const before = await sample();
+ await mutate('document.body.style.counterReset = "countdown 9"');
+ const after = await sample();
+
+ expect(after.sweep).not.toBe(before.sweep);
+ });
+
+ it("sees a counter owned above the composition root change", async () => {
+ await load(
+ composition(
+ "body { counter-reset: countdown 10; } #countdown::after { content: counter(countdown); }",
+ '',
+ ),
+ );
+ const before = await sample();
+ await mutate('document.body.style.counterReset = "countdown 9"');
+ const after = await sample();
+
+ expect(after.sweep).not.toBe(before.sweep);
+ });
+
+ it("sees a pseudo-element's own counter-increment change", async () => {
+ await load(
+ composition(
+ "#countdown::after { counter-increment: countdown 10; content: counter(countdown); } #countdown.next::after { counter-increment: countdown 9; }",
+ '',
+ ),
+ );
+ const before = await sample();
+ await mutate('document.getElementById("countdown").classList.add("next")');
+ const after = await sample();
+
+ expect(after.sweep).not.toBe(before.sweep);
+ });
+
+ it("sees a clip-path wipe over a box that never moves", async () => {
+ await load(
+ composition(
+ "#panel { width: 200px; height: 100px; background: #f00; clip-path: inset(0 100% 0 0); }",
+ '',
+ ),
+ );
+ const before = await sample();
+ await mutate('document.getElementById("panel").style.clipPath = "inset(0 50% 0 0)"');
+ const after = await sample();
+
+ expect(after.sweep).not.toBe(before.sweep);
+ expect(after.liveness).not.toBe(before.liveness);
+ });
+
+ it("sees textarea value and checkbox indeterminate changes", async () => {
+ await load(
+ composition(
+ "",
+ '',
+ ),
+ );
+ const start = await sample();
+ await mutate('document.getElementById("note").value = "09"');
+ const afterText = await sample();
+ await mutate('document.getElementById("toggle").indeterminate = true');
+ const afterIndeterminate = await sample();
+
+ expect(afterText.sweep).not.toBe(start.sweep);
+ expect(afterIndeterminate.sweep).not.toBe(afterText.sweep);
+ });
+
+ it("sees the composition root's own text change", async () => {
+ await load(composition("", "10"));
+ const before = await sample();
+ await mutate('document.getElementById("root").firstChild.textContent = "09"');
+ const after = await sample();
+
+ expect(after.sweep).not.toBe(before.sweep);
+ expect(after.liveness).not.toBe(before.liveness);
+ });
+
+ it("ignores text mutations inside a display:none descendant", async () => {
+ await load(
+ composition(
+ "#hidden { display: none; }",
+ '1010',
+ ),
+ );
+ const before = await sample();
+ await mutate('document.getElementById("hidden").textContent = "09"');
+ const after = await sample();
+
+ expect(after).toEqual(before);
+ });
+
+ it("ignores motion on a data-layout-ignore layer", async () => {
+ await load(
+ composition(
+ "#glow { position: absolute; width: 100px; height: 100px; background: #0f0; }",
+ '10',
+ ),
+ );
+ const before = await sample();
+ await mutate('document.getElementById("glow").style.left = "200px"');
+ const after = await sample();
+
+ expect(after).toEqual(before);
+ });
+});
diff --git a/packages/cli/src/commands/motion-signature.browser.js b/packages/cli/src/commands/motion-signature.browser.js
new file mode 100644
index 0000000000..9392a1f528
--- /dev/null
+++ b/packages/cli/src/commands/motion-signature.browser.js
@@ -0,0 +1,361 @@
+// Shared "what counts as motion" classifier for the two seek-time samplers.
+// Injected via page.addScriptTag BEFORE layout-audit.browser.js and
+// motion-sample.browser.js (see checkBrowser.ts injectAuditScripts and
+// layout.ts); both consume it through window.__hyperframesMotionSignature.
+//
+// Two Node-side decisions compare per-sample signatures of the composition:
+// - the frozen-sweep guard (#U10, checkPipeline.ts detectSweepStatic) reads
+// window.__hyperframesLayoutGeometry once per layout-grid seek and fails
+// the run with sweep_static when every sample is byte-identical;
+// - keepsMoving liveness (motionAudit.ts) reads motion-sample's liveness
+// signature per motion sample and reports motion_frozen on long runs of
+// identical signatures.
+// They meet in one decision (a motion_frozen finding suppresses sweep_static),
+// so the set of channels that count as motion MUST be identical for both —
+// otherwise a composition one sampler accepts as live is rejected as frozen
+// by the other. This module is that single owner. The only sanctioned
+// difference is quantization: liveness buckets position to 2px and opacity to
+// 0.08 so the motion RFC's "moves ≥2px / opacity ≥0.08" thresholds fall out of
+// bucketing, while the sweep guard wants exact (0.01) rounding because it asks
+// whether the seek moved anything at all.
+//
+// Adding a channel (e.g. SVG stroke-dasharray/dashoffset): append one reader
+// `(element, ctx) => string` to ELEMENT_CHANNELS. `ctx` carries the element's
+// computed style, its ::before/::after styles, its inherited opacity, and the
+// quantize flag. A reader returns a string that is equal between two samples
+// iff that channel did not visibly change; return "" for elements the channel
+// does not apply to so ordinary compositions gain no payload.
+//
+// Signatures are a single opaque string per sample (not a structured array):
+// Node only ever needs equality, never per-element diffing. Textual channels
+// are hashed (FNV-1a, length-delimited fields) so raw composition text never
+// leaves the page and per-sample payloads stay compact.
+(function () {
+ const IGNORE_TAGS = new Set(["SCRIPT", "STYLE", "TEMPLATE", "NOSCRIPT", "META", "LINK"]);
+ const MEDIA_TAGS = new Set(["CANVAS", "VIDEO", "IMG"]);
+ const FNV_OFFSET_BASIS = 2166136261;
+ const FNV_PRIME = 16777619;
+ const LIVENESS_POSITION_BUCKET_PX = 2;
+ const LIVENESS_OPACITY_BUCKET = 0.08;
+ const IGNORE_SELECTOR = "[data-layout-ignore], [data-layout-check='ignore']";
+ // counter(name) / counters(name, sep) in generated content. A list-item box
+ // whose ::marker content is `normal` paints counter(list-item) implicitly.
+ const COUNTER_FUNCTION = /counters?\(\s*([^\s,)]+)/g;
+ const IMPLICIT_MARKER_CONTENT = "counter(list-item)";
+ const LIST_ITEM_DISPLAY = /\blist-item\b/;
+
+ function round(value) {
+ return Math.round(value * 100) / 100;
+ }
+
+ function opacityChain(element) {
+ let opacity = 1;
+ for (let current = element; current; current = current.parentElement) {
+ const parsed = Number.parseFloat(getComputedStyle(current).opacity || "1");
+ if (Number.isFinite(parsed)) opacity *= parsed;
+ }
+ return opacity;
+ }
+
+ function compositionRoot() {
+ return (
+ document.querySelector("[data-composition-id][data-width][data-height]") ||
+ document.querySelector("[data-composition-id]") ||
+ document.body
+ );
+ }
+
+ function isHiddenStyle(style) {
+ return (
+ style.display === "none" || style.visibility === "hidden" || style.visibility === "collapse"
+ );
+ }
+
+ // Same visibility floor as layout-audit.browser.js isVisibleElement's default.
+ // The author opt-out (data-layout-ignore / data-layout-check=ignore) is NOT
+ // applied here: motion-sample reports this bit for explicitly asserted
+ // selectors, and an assertion naming an element outranks a layout-audit
+ // opt-out. compositionSignature applies the opt-out itself (see there).
+ // clip-path is not probed either; it is a channel, so a clip-path wipe over a
+ // static box counts as motion directly.
+ // fallow-ignore-next-line complexity
+ function isVisibleElement(element, style, opacity) {
+ if (IGNORE_TAGS.has(element.tagName)) return false;
+ if (isHiddenStyle(style || getComputedStyle(element))) return false;
+ if ((opacity === undefined ? opacityChain(element) : opacity) < 0.2) return false;
+ const rect = element.getBoundingClientRect();
+ return rect.width > 0.5 && rect.height > 0.5;
+ }
+
+ function foldField(hash, value) {
+ hash ^= value.length;
+ hash = Math.imul(hash, FNV_PRIME);
+ for (let i = 0; i < value.length; i++) {
+ hash ^= value.charCodeAt(i);
+ hash = Math.imul(hash, FNV_PRIME);
+ }
+ return hash;
+ }
+
+ function hashFields(fields) {
+ let hash = FNV_OFFSET_BASIS;
+ for (const field of fields) hash = foldField(hash, field);
+ return (hash >>> 0).toString(36);
+ }
+
+ // `none` / `normal` are the computed initial values of content, counter-*,
+ // clip-path, and font-variation-settings; collapse them so unused channels
+ // stay "".
+ function cssValue(value) {
+ return value === "none" || value === "normal" ? "" : value || "";
+ }
+
+ // --- Per-element channels: (element, ctx) => string --------------------------
+
+ function boxChannel(element, ctx) {
+ const rect = element.getBoundingClientRect();
+ const box = [rect.left, rect.top, rect.width, rect.height];
+ if (ctx.quantize) {
+ return box.map((value) => Math.round(value / LIVENESS_POSITION_BUCKET_PX)).join(",");
+ }
+ return box.map(round).join(",");
+ }
+
+ function opacityChannel(element, ctx) {
+ return String(
+ ctx.quantize ? Math.round(ctx.opacity / LIVENESS_OPACITY_BUCKET) : round(ctx.opacity),
+ );
+ }
+
+ // Variable-font axis animation moves no geometry and no opacity; in a
+ // DUPLEXED face (Recursive holds one advance width at every weight) not even
+ // the line width shifts, so without this channel the whole run reads frozen.
+ function fontAxesChannel(element, ctx) {
+ const axes = cssValue(ctx.style.fontVariationSettings);
+ return axes ? hashFields([axes]) : "";
+ }
+
+ // A clip-path wipe (inset(0 100% 0 0) → inset(0)) reveals a box that never
+ // moves; the computed clip-path string is the only thing that changes.
+ function clipPathChannel(element, ctx) {
+ const clip = cssValue(ctx.style.clipPath);
+ return clip ? hashFields([clip]) : "";
+ }
+
+ // Direct text nodes only: descendants are signed separately, and a hidden
+ // descendant's text mutation must not masquerade as visible motion.
+ function textChannel(element) {
+ const text = Array.from(element.childNodes)
+ .filter((node) => node.nodeType === 3)
+ .map((node) => node.textContent)
+ .join("");
+ return text && hashFields([text]);
+ }
+
+ function flag(value) {
+ return value ? "1" : "0";
+ }
+
+ function inputState(element) {
+ return [
+ element.type || "",
+ element.value || "",
+ flag(element.checked),
+ flag(element.indeterminate),
+ ];
+ }
+
+ function selectState(element) {
+ const fields = [String(element.selectedIndex), element.value || ""];
+ for (const option of element.options) fields.push(flag(option.selected));
+ return fields;
+ }
+
+ const CONTROL_STATE = {
+ INPUT: inputState,
+ TEXTAREA: (element) => [element.value || ""],
+ SELECT: selectState,
+ };
+
+ // Form controls paint their value/checked state without changing the box.
+ function controlChannel(element) {
+ const read = CONTROL_STATE[element.tagName];
+ return read ? hashFields(read(element)) : "";
+ }
+
+ // Chromium substitutes attr() in computed pseudo content, so this is the
+ // platform-owned rendered string rather than a CSS expression to reparse.
+ // counter() is NOT substituted — that is what the counter channel is for.
+ function generatedContentChannel(element, ctx) {
+ const before = cssValue(ctx.pseudo.before.content);
+ const after = cssValue(ctx.pseudo.after.content);
+ return before || after ? hashFields([before, after]) : "";
+ }
+
+ // Pixel-only media motion (a 2D/WebGL canvas repainting, a playing video, or
+ // an equal-size opaque src swap) moves no geometry and no opacity, so
+ // it is invisible to every DOM-state channel. Downsample each visible media
+ // element to 8x8 and fold its pixels in. Tainted, zero-sized, or unreadable
+ // media hashes to a constant — no worse than DOM-state-only detection and
+ // never a new false negative for DOM-motion compositions. Media inside
+ // iframes is intentionally outside this signature: it lives in a separate
+ // document, and cross-origin frames are inaccessible under SOP.
+ // fallow-ignore-next-line complexity
+ function mediaPixelChannel(element) {
+ if (!MEDIA_TAGS.has(element.tagName)) return "";
+ try {
+ const rect = element.getBoundingClientRect();
+ const sourceWidth = element.videoWidth || element.width || rect.width;
+ const sourceHeight = element.videoHeight || element.height || rect.height;
+ if (!sourceWidth || !sourceHeight) return "x";
+ const off = document.createElement("canvas");
+ off.width = 8;
+ off.height = 8;
+ const ctx2d = off.getContext("2d");
+ if (!ctx2d) return "x";
+ ctx2d.drawImage(element, 0, 0, 8, 8);
+ const data = ctx2d.getImageData(0, 0, 8, 8).data;
+ let hash = 0;
+ for (let i = 0; i < data.length; i++) hash = (hash * 31 + data[i]) >>> 0;
+ return String(hash);
+ } catch {
+ return "x";
+ }
+ }
+
+ const ELEMENT_CHANNELS = [
+ boxChannel,
+ opacityChannel,
+ fontAxesChannel,
+ clipPathChannel,
+ textChannel,
+ controlChannel,
+ generatedContentChannel,
+ mediaPixelChannel,
+ ];
+
+ // --- Composition-level counter channel ------------------------------------
+ //
+ // Counter declarations often live on zero-box owners (or on ancestors of the
+ // composition root) while some pseudo-element paints the value, so counter
+ // state is a composition-level channel over every element that generates a
+ // box — not just the visible ones. Two guards keep a decoy counter from
+ // making a frozen composition read as live: a display:none subtree generates
+ // no boxes and therefore cannot feed any painted counter(), and only
+ // declarations that NAME a counter some generated content actually paints
+ // are folded in — a varying counter nobody renders is not motion. The gate
+ // is name-level, not scope-level: a same-named owner that cannot reach the
+ // consumer in the box tree still counts, which is accepted for a guard whose
+ // job is catching frozen timelines, not defeating deliberate authors.
+ // visibility:hidden and zero-box owners stay in as owners: they generate
+ // boxes, their counters propagate to visible descendants/siblings, and their
+ // own absolutely-positioned pseudo-elements can paint. /
are not surfaced in computed counter-* and stay invisible here.
+
+ // Generated content of one box owner that reaches the screen: the host is
+ // not under an author opt-out, has a paintable inherited opacity, and the
+ // pseudo box itself is not hidden. A list-item box also paints its ::marker
+ // (counter(list-item) when the marker content is `normal`).
+ function markerContent(element, style) {
+ if (isHiddenStyle(style) || !LIST_ITEM_DISPLAY.test(style.display)) return "";
+ return cssValue(getComputedStyle(element, "::marker").content) || IMPLICIT_MARKER_CONTENT;
+ }
+
+ function paintedContent(element, style, pseudo, opacity) {
+ if (opacity < 0.2 || element.closest(IGNORE_SELECTOR)) return [];
+ const boxes = [pseudo.before, pseudo.after].filter((box) => !isHiddenStyle(box));
+ return [...boxes.map((box) => cssValue(box.content)), markerContent(element, style)];
+ }
+
+ function consumedCounterNames(owners) {
+ const names = new Set();
+ for (const owner of owners) {
+ for (const content of owner.painted) {
+ for (const match of content.matchAll(COUNTER_FUNCTION)) names.add(match[1]);
+ }
+ }
+ return names;
+ }
+
+ // `counter-reset: a 10 b 3` → does any named counter get painted?
+ function namesConsumedCounter(declaration, consumed) {
+ return declaration.split(/\s+/).some((token) => consumed.has(token));
+ }
+
+ function counterState(style, consumed) {
+ const fields = [style.counterReset, style.counterIncrement, style.counterSet]
+ .map(cssValue)
+ .filter((declaration) => declaration && namesConsumedCounter(declaration, consumed));
+ return fields.length > 0 ? "c:" + hashFields(fields) : "";
+ }
+
+ function counterParts(root, owners) {
+ const consumed = consumedCounterNames(owners);
+ if (consumed.size === 0) return [];
+ const parts = [];
+ function push(style) {
+ const state = counterState(style, consumed);
+ if (state) parts.push(state);
+ }
+ for (let ancestor = root.parentElement; ancestor; ancestor = ancestor.parentElement) {
+ push(getComputedStyle(ancestor));
+ }
+ for (const owner of owners) {
+ push(owner.style);
+ push(owner.pseudo.before);
+ push(owner.pseudo.after);
+ }
+ return parts;
+ }
+
+ // One signature of everything under `root` (root included — a composition
+ // whose only textual motion is a direct text node of the root still moves)
+ // that a viewer could see change between two seeks. `options.quantize`
+ // selects liveness bucketing (see header). Elements under an author opt-out
+ // (data-layout-ignore / data-layout-check=ignore) — typically a decorative
+ // layer that may animate off the seeked timeline — are neither signed nor
+ // allowed to consume counters: they must not prove that the timeline
+ // advanced. They remain counter owners, since their boxes still propagate.
+ // fallow-ignore-next-line complexity
+ function compositionSignature(root, options) {
+ if (!root) return "";
+ const quantize = !!(options && options.quantize);
+ const parts = [];
+ const boxOwners = [];
+ const hiddenSubtree = new Set();
+ for (const element of [root, ...root.querySelectorAll("*")]) {
+ if (IGNORE_TAGS.has(element.tagName)) continue;
+ const style = getComputedStyle(element);
+ if (style.display === "none" || hiddenSubtree.has(element.parentElement)) {
+ hiddenSubtree.add(element);
+ continue;
+ }
+ const pseudo = {
+ before: getComputedStyle(element, "::before"),
+ after: getComputedStyle(element, "::after"),
+ };
+ const opacity = opacityChain(element);
+ boxOwners.push({ style, pseudo, painted: paintedContent(element, style, pseudo, opacity) });
+ if (element.closest(IGNORE_SELECTOR)) continue;
+ if (!isVisibleElement(element, style, opacity)) continue;
+ const ctx = { style, pseudo, opacity, quantize };
+ parts.push(ELEMENT_CHANNELS.map((channel) => channel(element, ctx)).join(","));
+ }
+ parts.push(...counterParts(root, boxOwners));
+ return parts.join("|");
+ }
+
+ window.__hyperframesMotionSignature = {
+ compositionRoot,
+ isVisibleElement,
+ opacityChain,
+ compositionSignature,
+ };
+
+ // Frozen-sweep guard entry point (checkBrowser.ts collectLayoutGeometry).
+ // The name predates the textual/media channels and is kept for driver
+ // compatibility.
+ window.__hyperframesLayoutGeometry = function collectLayoutGeometry() {
+ return compositionSignature(compositionRoot(), { quantize: false });
+ };
+})();
diff --git a/packages/cli/src/commands/motion-signature.browser.test.ts b/packages/cli/src/commands/motion-signature.browser.test.ts
new file mode 100644
index 0000000000..2bb57675b9
--- /dev/null
+++ b/packages/cli/src/commands/motion-signature.browser.test.ts
@@ -0,0 +1,808 @@
+// @vitest-environment happy-dom
+// fallow-ignore-file code-duplication
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const script = readFileSync(join(__dirname, "motion-signature.browser.js"), "utf-8");
+
+interface RectInput {
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+}
+
+type StyleOverride = Partial;
+
+interface Fixture {
+ /** Bounding rects keyed by element id (or lower-case tag name for id-less elements). */
+ rects: Record;
+ /** Computed-style overrides keyed like `rects`; getters are re-read on every call. */
+ styles?: Record;
+ /** `::before` / `::after` computed-style overrides keyed like `rects`. */
+ pseudo?: Record;
+}
+
+const BASE_STYLE: StyleOverride = {
+ display: "block",
+ visibility: "visible",
+ opacity: "1",
+ fontVariationSettings: "normal",
+ clipPath: "none",
+ counterReset: "none",
+ counterIncrement: "none",
+ counterSet: "none",
+};
+
+const BASE_PSEUDO_STYLE: StyleOverride = {
+ content: "none",
+ counterReset: "none",
+ counterIncrement: "none",
+ counterSet: "none",
+};
+
+function keyFor(element: Element): string {
+ return element.id || element.tagName.toLowerCase();
+}
+
+// A per-element fake `getComputedStyle`: each element reports ONLY its own
+// declared style, exactly like the real platform (a child of a display:none
+// parent still computes display:block). Any ancestor awareness — hidden
+// subtrees, counter owners above the root — must therefore come from the
+// classifier under test, which is what pins those branches.
+function installFixture({ rects, styles = {}, pseudo = {} }: Fixture): void {
+ vi.spyOn(window, "getComputedStyle").mockImplementation((element, pseudoElement) => {
+ const key = keyFor(element as Element);
+ if (pseudoElement === "::before" || pseudoElement === "::after") {
+ const override = pseudoElement === "::before" ? pseudo[key]?.before : pseudo[key]?.after;
+ return { ...BASE_PSEUDO_STYLE, ...override } as CSSStyleDeclaration;
+ }
+ return { ...BASE_STYLE, ...styles[key] } as CSSStyleDeclaration;
+ });
+ for (const element of Array.from(document.querySelectorAll("*"))) {
+ const input = rects[keyFor(element)] ?? { left: 0, top: 0, width: 0, height: 0 };
+ vi.spyOn(element, "getBoundingClientRect").mockReturnValue(rect(input));
+ }
+}
+
+function rect({ left, top, width, height }: RectInput): DOMRect {
+ return {
+ left,
+ top,
+ right: left + width,
+ bottom: top + height,
+ width,
+ height,
+ x: left,
+ y: top,
+ toJSON() {
+ return this;
+ },
+ } as DOMRect;
+}
+
+interface SignatureWindow {
+ __hyperframesLayoutGeometry: () => string;
+ __hyperframesMotionSignature: {
+ compositionRoot(): Element;
+ compositionSignature(root: Element | null, options?: { quantize?: boolean }): string;
+ };
+}
+
+function signatureWindow(): SignatureWindow {
+ return window as unknown as SignatureWindow;
+}
+
+function installScript(): () => string {
+ window.eval(script);
+ return signatureWindow().__hyperframesLayoutGeometry;
+}
+
+function mockMediaPixels(read: () => number): void {
+ const getContextSpy = vi.spyOn(HTMLCanvasElement.prototype, "getContext") as unknown as {
+ mockReturnValue(value: CanvasRenderingContext2D): void;
+ };
+ getContextSpy.mockReturnValue({
+ drawImage() {},
+ getImageData() {
+ return { data: new Uint8ClampedArray(8 * 8 * 4).fill(read()) };
+ },
+ } as unknown as CanvasRenderingContext2D);
+}
+
+const ROOT = { left: 0, top: 0, width: 640, height: 360 };
+const COUNTDOWN = { left: 280, top: 140, width: 80, height: 48 };
+const ZERO_BOX = { left: 0, top: 0, width: 0, height: 0 };
+const COUNTER_CONSUMER = { after: { content: "counter(countdown)" } };
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ document.body.innerHTML = "";
+ Reflect.deleteProperty(window, "__hyperframesLayoutGeometry");
+ Reflect.deleteProperty(window, "__hyperframesMotionSignature");
+});
+
+describe("motion-signature.browser media and geometry channels", () => {
+ it("changes the sweep fingerprint when visible video pixels advance", () => {
+ document.body.innerHTML = `
+
+
+
+ `;
+ installFixture({ rects: { root: ROOT, footage: ROOT } });
+ let pixelValue = 20;
+ mockMediaPixels(() => pixelValue);
+
+ const collect = installScript();
+ const before = collect();
+ pixelValue = 220;
+
+ expect(collect()).not.toBe(before);
+ });
+
+ // PRINFRA-666: an equal-size, equal-position opaque src/visibility
+ // swap (the authoring pattern for a paused-GSAP-cursor-driven "reveal
+ // frame N of a still sequence" composition) moves no geometry and no
+ // opacity, so it was invisible to the fingerprint and false-positived
+ // sweep_static — mediaPixelHash already existed for exactly this pixel-only
+ // motion class, it just wasn't applied to img.
+ it("changes the sweep fingerprint when a same-size opaque img is swapped", () => {
+ document.body.innerHTML = `
+
+
+
+ `;
+ installFixture({ rects: { root: ROOT, frame: ROOT } });
+ let pixelValue = 20;
+ mockMediaPixels(() => pixelValue);
+
+ const collect = installScript();
+ const before = collect();
+ pixelValue = 220;
+
+ expect(collect()).not.toBe(before);
+ });
+
+ // Opacity-reveal fixture (CLI feedback digest 2026-07-14): code-typing style
+ // scenes reveal pre-laid-out characters via opacity only — no geometry ever
+ // moves. The sweep fingerprint must treat that as motion, both while a glyph
+ // fades (opacity value changes) and when it crosses the 0.2 visibility floor
+ // (element enters the signature); otherwise `check` misfires `sweep_static`
+ // and authors reach for geometry hacks (a slow host y-drift) to pass.
+ it("changes the sweep fingerprint when text reveals via opacity alone", () => {
+ document.body.innerHTML = `
+
+
c
+
+ `;
+ let charOpacity = "0";
+ installFixture({
+ rects: {
+ root: ROOT,
+ code: { left: 40, top: 40, width: 560, height: 48 },
+ char: { left: 40, top: 40, width: 18, height: 48 },
+ },
+ styles: {
+ char: {
+ get opacity() {
+ return charOpacity;
+ },
+ } as StyleOverride,
+ },
+ });
+
+ const collect = installScript();
+ const hidden = collect(); // below the 0.2 visibility floor — not in the signature
+ charOpacity = "0.5";
+ const fading = collect(); // mid-fade — present, opacity part of the signature
+ charOpacity = "1";
+ const revealed = collect(); // settled
+
+ expect(fading).not.toBe(hidden);
+ expect(revealed).not.toBe(fading);
+ });
+
+ // Variable-font axis animation (registry block `weight-wave`): a crest of
+ // weight travels across a line of text. In a duplexed face nothing moves
+ // but the axis string — the fingerprint must still see it.
+ it("changes the sweep fingerprint when only font-variation-settings moves", () => {
+ document.body.innerHTML = `
+
+
P
+
+ `;
+ let axes = '"wght" 400, "slnt" 0';
+ installFixture({
+ rects: {
+ root: ROOT,
+ line: { left: 40, top: 40, width: 560, height: 48 },
+ char: { left: 40, top: 40, width: 18, height: 48 },
+ },
+ styles: {
+ char: {
+ get fontVariationSettings() {
+ return axes;
+ },
+ } as StyleOverride,
+ },
+ });
+
+ const collect = installScript();
+ const rest = collect();
+ axes = '"wght" 1000, "slnt" -12'; // the crest arrives over this character
+
+ expect(collect()).not.toBe(rest);
+ });
+
+ // The other direction, and it guards the more dangerous failure: a
+ // fingerprint that varies on its own would make sweep_static unfireable and
+ // every green layout verdict meaningless. Identical scene, axes included,
+ // must hash identically.
+ it("keeps the sweep fingerprint identical when nothing moves, font axes included", () => {
+ document.body.innerHTML = `
+
+ `;
+ let counterReset = "countdown 10";
+ installFixture({
+ rects: { root: ROOT, "counter-owner": ZERO_BOX, countdown: COUNTDOWN },
+ styles: {
+ "counter-owner": {
+ get counterReset() {
+ return counterReset;
+ },
+ } as StyleOverride,
+ },
+ });
+
+ const collect = installScript();
+ const before = collect();
+ counterReset = "countdown 9";
+
+ expect(collect()).toBe(before);
+ });
+});
diff --git a/packages/cli/src/utils/checkBrowser.ts b/packages/cli/src/utils/checkBrowser.ts
index f5c00ec52a..29a3e75c72 100644
--- a/packages/cli/src/utils/checkBrowser.ts
+++ b/packages/cli/src/utils/checkBrowser.ts
@@ -434,6 +434,8 @@ async function hasNoTimelineDeclaration(page: Page): Promise {
}
async function injectAuditScripts(page: Page, contrast: boolean): Promise {
+ // The shared motion classifier must land before both samplers that consume it.
+ await page.addScriptTag({ content: loadBrowserScript("motion-signature.browser.js") });
await page.addScriptTag({ content: loadBrowserScript("layout-audit.browser.js") });
await page.addScriptTag({ content: loadBrowserScript("motion-sample.browser.js") });
if (contrast) {
diff --git a/packages/cli/src/utils/checkPipeline.ts b/packages/cli/src/utils/checkPipeline.ts
index aecddd6dfc..9701b2b287 100644
--- a/packages/cli/src/utils/checkPipeline.ts
+++ b/packages/cli/src/utils/checkPipeline.ts
@@ -500,7 +500,7 @@ const ZERO_LAYOUT_RECT: LayoutRect = {
/**
* Frozen-sweep guard (#U10): if every layout-grid sample produced the exact
- * same visible-state fingerprint (see layout-audit.browser.js), the seek
+ * same visible-state fingerprint (see motion-signature.browser.js), the seek
* never actually advanced the composition's timeline — every other green
* verdict from this run is meaningless, not just a missed defect. Skips
* short (<3s) compositions, single-sample runs (nothing to compare), and
diff --git a/packages/cli/src/utils/checkTypes.ts b/packages/cli/src/utils/checkTypes.ts
index eff7ca812e..caf76893e5 100644
--- a/packages/cli/src/utils/checkTypes.ts
+++ b/packages/cli/src/utils/checkTypes.ts
@@ -196,7 +196,9 @@ export interface CheckAuditDriver {
collectOverlap(time: number): Promise;
/** Frozen-sweep guard (#U10): an opaque fingerprint of the current seeked
* visual state, for detecting a timeline that never advances under seek.
- * The method keeps its legacy name for driver compatibility. */
+ * Produced by motion-signature.browser.js — the same classifier that feeds
+ * motion-sample's liveness signature. The method keeps its legacy name for
+ * driver compatibility. */
collectLayoutGeometry(): Promise;
/** rotation_pivot_drift: every rotatable element's bbox center/size/angle at
* the current seeked state. Accumulated across the grid — see checkPipeline. */