fix(anatomy): V1-2.2 refuse markers too small on the phone preview

Owner decision 2026-11-01: the scale bypass (viewBox blown up, drawing
scaled back) is closed by the visible size, 4 CSS px on the editor at
320 x 568 (equine junctions 4.97 px), verdict marker_too_small. A frame
is usable only where browsers draw it faithfully: edges within 2^20,
span from 1 unit, aspect 100, offset 256 spans; measured in 3 engines.
This commit is contained in:
bchanot committed 2026-11-01 01:28:48 +01:00
1 parent 9c606aa567
commit 96b99784b5
17 files changed
+944 -37

No files matched your search

@@ -0,0 +1,21 @@
# V1-2.2 decisions (2026-11-01): throwaway proof tools
Not part of any suite. Run from a worktree of the branch, Playwright engines from the user cache.
- `iso_probe_generator.rs.txt`: copy to `crates/core/tests/zz_probe_iso.rs`, run
`ISO_OUT=<empty dir> cargo test -p faunosteo-core --test zz_probe_iso -- --nocapture`, delete it.
Writes the equine main view (canvas and PDF forms) with a full-frame opaque magenta rectangle,
last child of the drawing, carrying each candidate style; plus the positive control (the
rectangle after the layer).
- `iso.mjs <worktree> <dir> chromium,firefox,webkit`: magenta pixel count and point hits per file.
- `measure.mjs <worktree>`: needs Vite on 127.0.0.1:5197 (`VITE_SUPABASE_URL= VITE_SUPABASE_ANON_KEY=
node_modules/.bin/vite --host 127.0.0.1 --port 5197 --strictPort` in apps/app); the editor's SVG box,
scale and visible disc sizes at 320, 360, 375, 390 and 1280 px, main view and head detail.
- `frame_probe_generator.rs.txt`: copy to `crates/core/tests/zz_frame_probe.rs`, run
`FRAME_OUT=<empty dir> cargo test -p faunosteo-core --test zz_frame_probe`, delete it. Writes one JSON per
limit case: the composed canvas, the preview box, the core's f64 expectation of each disc and hitbox, the
core's verdict on the frame (refused frames are written with their raw `viewBox`).
- `frame-probe.mjs <worktree> <dir> chromium,firefox,webkit`: the browser's layout of each hitbox against the
core (relative size gap, centre gap in px).
- `span-pixels.mjs <worktree> chromium,firefox,webkit`: painted pixels of one disc for spans 1 000 to 2^-20
(area and centroid gaps): where each engine stops drawing faithfully.
@@ -0,0 +1,32 @@
// Rust vs browser on the frame limits (owner brief 2026-11-01): each case is a composed canvas
// (`frame_probe_generator.rs.txt`) with the core's f64 expectation of every visible disc (size and
// centre in CSS px on the smallest preview box). The browser draws it in a box of that size, CSS as
// AnatomyCanvas (svg max-width/max-height 100 %, centred); answers the largest size and centre gaps.
import { createRequire } from 'node:module'
import { readFileSync, readdirSync } from 'node:fs'
const require = createRequire(process.argv[2] + '/apps/app/package.json')
const pw = require('@playwright/test')
const DIR = process.argv[3]
const cases = readdirSync(DIR).filter((f) => f.endsWith('.json')).sort().map((f) => JSON.parse(readFileSync(`${DIR}/${f}`, 'utf8')))
for (const engine of process.argv[4].split(',')) {
const browser = await pw[engine].launch()
const page = await browser.newPage({ viewport: { width: 600, height: 600 } })
console.log(`== ${engine} ${browser.version()}`)
for (const c of cases) {
const [bw, bh] = c.box
await page.setContent(`<html><body style="margin:0"><div id="b" style="width:${bw}px;height:${bh}px">${c.svg.replace(/^<svg /, '<svg style="max-width:100%;max-height:100%;display:block;margin:0 auto" ')}</div></body></html>`)
const got = await page.evaluate((markers) => {
const svg = document.querySelector('#b svg'); const s = svg.getBoundingClientRect()
// The hitbox (stroke none): Firefox counts a stroke in an element's client rect, the others do not.
const boxes = [...svg.querySelectorAll('circle[pointer-events="visibleFill"]')]
return markers.map((m) => { const t = boxes.find((e) => e.getAttribute('data-anno-id') === m.id); if (!t) return null
const r = t.getBoundingClientRect(); return { size: r.width, cx: r.x + r.width / 2 - s.x, cy: r.y + r.height / 2 - s.y } })
}, c.markers)
let size = 0, centre = 0
c.markers.forEach((m, i) => { const g = got[i]; if (!g) { size = Infinity; return }
size = Math.max(size, Math.abs(g.size - m.hitbox) / m.hitbox); centre = Math.max(centre, Math.hypot(g.cx - m.cx, g.cy - m.cy)) })
const disc = Math.min(...c.markers.map((m) => m.size))
console.log(c.name.padEnd(30), c.core.padEnd(12), JSON.stringify({ core_disc_px: +disc.toPrecision(4), hitbox_size_gap_rel: +size.toPrecision(2), max_centre_gap_px: +centre.toPrecision(2) }))
}
await browser.close()
}
@@ -0,0 +1,88 @@
// THROWAWAY (not committed as a test): copy to crates/core/tests/zz_frame_probe.rs, run
// `FRAME_OUT=<empty dir> cargo test -p faunosteo-core --test zz_frame_probe -- --nocapture`, delete it.
// Each case: the composed canvas, the preview box, the core's f64 expectation of every visible disc
// (size and centre in CSS px relative to the svg box), and the core's verdict on the frame.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use common::sheet_readers::{OPEN, document};
use faunosteo_core::anatomy::compose::compose_canvas;
use faunosteo_core::anatomy::frame::{DETAIL_PREVIEW_PX, MAIN_PREVIEW_PX, frame_faults, view_frame, FrameFault, Placement};
use faunosteo_core::anatomy::layer::twin_radius;
use faunosteo_core::anatomy::svg::{Element, read_svg, serialize::serialize};
use faunosteo_core::domain::sheet::{AnatomicalSheetDocument, Annotation, Geometry};
use serde::Deserialize;
use serde_json::{Value, json};
fn doc_of(text: &str) -> AnatomicalSheetDocument {
AnatomicalSheetDocument::deserialize(serde_json::from_str::<Value>(text).unwrap()).unwrap()
}
fn write(name: &str, doc: &AnatomicalSheetDocument, view: &str, root: &Element, raw: Option<[f64; 4]>) {
let out = std::env::var("FRAME_OUT").unwrap();
let v = doc.views.iter().find(|v| v.id() == view).unwrap();
let frame = raw.unwrap_or_else(|| { let f = view_frame(v, root).unwrap(); [f.min_x, f.min_y, f.width, f.height] });
let (bw, bh) = if v.is_main() { MAIN_PREVIEW_PX } else { DETAIL_PREVIEW_PX };
let scale = (bw / frame[2]).min(bh / frame[3]);
let faults = frame_faults(doc, |_| Some(root));
let core = if faults.iter().any(|f| matches!(f, FrameFault::NoFrame { .. })) { "no_frame" }
else if faults.iter().any(|f| matches!(f, FrameFault::Annotation { placement: Placement::TooSmall, .. })) { "too_small" }
else if faults.is_empty() { "accepted" } else { "out_of_frame" };
let mut svg = serialize(&compose_canvas(doc, view, root).unwrap());
if let Some(r) = raw {
let vb = svg[..svg.find('>').unwrap()].to_owned();
let start = vb.find("viewBox=\"").unwrap() + 9;
let end = start + vb[start..].find('"').unwrap();
svg.replace_range(start..end, &format!("{} {} {} {}", r[0], r[1], r[2], r[3]));
}
let markers: Vec<Value> = doc.annotations.iter().filter(|a| a.view_id() == view).filter_map(|a| match a {
Annotation::Observable(o) => match o.geometry.as_ref()? { Geometry::Circle(c) => Some(json!({
"id": o.id, "size": 2.0 * twin_radius(c.r) * scale, "hitbox": 2.0 * c.r * scale,
"cx": (c.cx - frame[0]) * scale, "cy": (c.cy - frame[1]) * scale })), _ => None },
_ => None }).collect();
std::fs::write(format!("{out}/{name}.json"), json!({ "name": name, "box": [bw, bh], "core": core, "svg": svg, "markers": markers }).to_string()).unwrap();
}
fn shared(view_box: &str, cx: f64, cy: f64, r: f64) -> (AnatomicalSheetDocument, Element) {
let mut doc: Value = serde_json::from_str(&document()).unwrap();
doc["annotations"][0]["geometry"] = json!({ "type": "circle", "cx": cx, "cy": cy, "r": r });
let text = OPEN.replace("0 0 10 10", view_box) + "<path d=\"M0 0h1\"/></svg>";
(doc_of(&doc.to_string()), read_svg(&text).unwrap().root)
}
fn scaled_horse(factor: f64) -> Element {
let horse = common::repo_file("supabase/seed/anatomical-sheets/equine/draft/assets/horse.svg");
let text = horse.replacen("viewBox=\"0 0 2073.4 1629.4\">", &format!("viewBox=\"0 0 {} {}\"><g transform=\"scale({factor})\">", 2073.4 * factor, 1629.4 * factor), 1).replacen("</svg>", "</g></svg>", 1);
read_svg(&text).unwrap().root
}
#[test]
fn write_cases() {
let equine = doc_of(&common::repo_file("supabase/seed/anatomical-sheets/equine/draft/document.json"));
for (name, factor) in [("a-equine-main", 1.0), ("b-equine-x1.24", 1.24), ("c-equine-x1.25", 1.25), ("c2-equine-x100", 100.0)] {
write(name, &equine, "main", &scaled_horse(factor), None);
}
write("d-equine-head-detail-box", &equine, "head", &scaled_horse(1.0), None);
let m = 1_048_576.0 - 8192.0;
let (d, r) = shared(&format!("{m} 0 8192 8192"), m + 4096.37, 4100.63, 200.0);
write("e-edge-magnitude-2^20", &d, "main", &r, None);
let (d, r) = shared("2550 0 10 10", 2555.37, 5.63, 1.0);
write("f-offset-ratio-256", &d, "main", &r, None);
let (d, r) = shared("1000000 0 10 10", 1_000_005.37, 5.63, 1.0);
write("g-offset-ratio-1e5-refused", &d, "main", &r, Some([1e6, 0.0, 10.0, 10.0]));
let (d, r) = shared("10000000 0 10 10", 10_000_005.37, 5.63, 1.0);
write("h-offset-ratio-1e6-refused", &d, "main", &r, Some([1e7, 0.0, 10.0, 10.0]));
let s = 1.0 / 1_048_576.0;
let (d, r) = shared(&format!("0 0 {s} {s}"), s * 0.537, s * 0.463, s / 4.0);
write("i-span-2^-20", &d, "main", &r, None);
let (d, r) = shared("0 0 1e-30 1e-30", 0.537e-30, 0.463e-30, 0.25e-30);
write("j-span-1e-30-refused", &d, "main", &r, Some([0.0, 0.0, 1e-30, 1e-30]));
// Span series, the point's hitbox a quarter of the span (its disc stays 4 units across).
for (label, span) in [("1", 1.0), ("2^-3", 0.125), ("2^-5", 0.03125), ("2^-7", 0.0078125), ("2^-10", 1.0 / 1024.0), ("2^-14", 1.0 / 16384.0)] {
let (d, r) = shared(&format!("0 0 {span} {span}"), span * 0.537, span * 0.463, span / 4.0);
write(&format!("m-span-{label}"), &d, "main", &r, None);
}
let (d, r) = shared("0 0 1000 1000", 500.37, 499.63, 20.0);
write("k-threshold-4.58px", &d, "main", &r, None);
let (d, r) = shared("0 0 1000 1000", 500.37, 499.63, 18.0);
write("l-threshold-3.43px", &d, "main", &r, None);
}
@@ -0,0 +1,32 @@
// Sibling-CSS isolation probe: a full-frame opaque magenta rect, last child of the drawing, carries each candidate style.
// Metric: pure-magenta pixel count (equal to control-none = no marker covered) and, in the canvas, the hit at each point centre.
import { createRequire } from 'node:module'
import { readFileSync, readdirSync } from 'node:fs'
const require = createRequire(process.argv[2] + '/apps/app/package.json')
const pw = require('@playwright/test')
const DIR = process.argv[3]
const doc = JSON.parse(readFileSync(process.argv[2] + '/supabase/seed/anatomical-sheets/equine/draft/document.json', 'utf8'))
const points = doc.annotations.filter((a) => a.view_id === 'main' && a.geometry.type === 'circle').map((a) => [a.id, a.geometry.cx, a.geometry.cy])
const names = [...new Set(readdirSync(DIR).map((f) => f.split('.')[0]))].sort()
const W = 1000, H = Math.round(1000 * 1629.4 / 2073.4)
const LIB = `window.mag = (d) => { let n = 0; for (let i = 0; i < d.length; i += 4) if (d[i] === 255 && d[i+1] === 0 && d[i+2] === 255) n++; return n }
window.pdf = async (svg) => { const root = new DOMParser().parseFromString(svg, 'image/svg+xml').documentElement; root.setAttribute('width', '${W}'); root.setAttribute('height', '${H}');
const url = URL.createObjectURL(new Blob([new XMLSerializer().serializeToString(root)], { type: 'image/svg+xml' })); const img = new Image(); img.width = ${W}; img.height = ${H}; img.src = url; await img.decode();
const c = document.createElement('canvas'); c.width = ${W}; c.height = ${H}; const x = c.getContext('2d'); x.fillStyle = '#fff'; x.fillRect(0, 0, ${W}, ${H}); x.drawImage(img, 0, 0, ${W}, ${H}); return window.mag(x.getImageData(0, 0, ${W}, ${H}).data) }
window.png = async (b64) => { const img = new Image(); img.src = 'data:image/png;base64,' + b64; await img.decode(); const c = document.createElement('canvas'); c.width = img.width; c.height = img.height; const x = c.getContext('2d'); x.drawImage(img, 0, 0); return window.mag(x.getImageData(0, 0, c.width, c.height).data) }`
for (const engine of process.argv[4].split(',')) {
const browser = await pw[engine].launch()
const work = await browser.newPage(); await work.setContent('<html><body></body></html>'); await work.addScriptTag({ content: LIB })
const shot = await browser.newPage({ viewport: { width: 1100, height: 900 } })
console.log(`== ${engine} ${browser.version()}`)
for (const name of names) {
const pdf = await work.evaluate((s) => window.pdf(s), readFileSync(`${DIR}/${name}.pdf.svg`, 'utf8'))
const svg = readFileSync(`${DIR}/${name}.canvas.svg`, 'utf8').replace(/^<svg /, `<svg width="${W}" height="${H}" `)
await shot.setContent(`<html><body style="margin:0;background:#fff"><div id="h" style="width:${W}px;height:${H}px">${svg}</div></body></html>`)
const canvas = await work.evaluate((b) => window.png(b), (await shot.locator('#h').screenshot()).toString('base64'))
const s = W / 2073.4
const hits = await shot.evaluate(([pts, s]) => pts.filter(([id, cx, cy]) => document.elementFromPoint(cx * s, cy * s)?.closest('[data-anno-id]')?.getAttribute('data-anno-id') === id).length, [points, s])
console.log(name.padEnd(16), JSON.stringify({ pdf_magenta: pdf, canvas_magenta: canvas, point_hits: `${hits}/${points.length}` }))
}
await browser.close()
}
@@ -0,0 +1,71 @@
// THROWAWAY (not committed): composed views for the sibling-CSS browser probe.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use std::collections::HashSet;
use faunosteo_core::anatomy::compose::{compose_canvas, compose_highlight};
use faunosteo_core::anatomy::svg::{read_svg, serialize::serialize};
use faunosteo_core::domain::sheet::AnatomicalSheetDocument;
use serde::Deserialize;
const RECT: &str = r##"<rect x="0" y="0" width="2073.4" height="1629.4" fill="#ff00ff" STYLE/>"##;
const CANDIDATES: [(&str, &str); 22] = [
("control-none", ""),
("z-index", "position:relative;z-index:2147483647"),
("transform-3d", "transform:translateZ(1000px);will-change:transform"),
("mix-blend", "mix-blend-mode:normal;isolation:isolate"),
("view-transition", "view-transition-name:hijack"),
("outline-small", "OUTLINE"),
("contain", "contain:strict;content-visibility:visible"),
("filter-css", "filter:drop-shadow(0 0 40px #ff00ff)"),
("backdrop", "backdrop-filter:blur(40px)"),
("position-fixed", "position:fixed;inset:0;z-index:9999"),
("paint-order", "paint-order:markers stroke fill"),
("stroke-huge", "stroke:#ff00ff;stroke-width:100000"),
("pointer", "pointer-events:all;cursor:pointer"),
("opacity", "opacity:1"),
("clip-css", "clip-path:inset(-9999px)"),
("mask-css", "mask-image:linear-gradient(#000,#000)"),
("display", "display:block"),
("visibility", "visibility:visible"),
("transform-scale", "transform:scale(10);transform-origin:50% 50%"),
("translate", "translate:0 0 9999px"),
("order", "order:-1;float:right"),
("anchor", "anchor-name:--x;position-anchor:--x"),
];
#[test]
fn write_probe() {
let out = std::env::var("ISO_OUT").unwrap();
let horse = common::repo_file("supabase/seed/anatomical-sheets/equine/draft/assets/horse.svg");
let text = common::repo_file("supabase/seed/anatomical-sheets/equine/draft/document.json");
let doc = AnatomicalSheetDocument::deserialize(serde_json::from_str::<serde_json::Value>(&text).unwrap()).unwrap();
let ids: HashSet<&str> = doc.annotations.iter().filter(|a| a.view_id() == "main").map(|a| a.id()).collect();
for (name, style) in CANDIDATES {
let rect = if style == "OUTLINE" {
r##"<rect x="10" y="10" width="5" height="5" fill="#ff00ff" style="outline:4000px solid #ff00ff;outline-offset:0"/>"##.to_owned()
} else if style.is_empty() {
RECT.replace(" STYLE", "")
} else {
RECT.replace("STYLE", &format!("style=\"{style}\""))
};
let pos = horse.rfind("</svg>").unwrap();
let drawing = format!("{}{}{}", &horse[..pos], rect, &horse[pos..]);
let read = read_svg(&drawing).unwrap();
// A style with a function call (`filter:`, `clip-path:`, `transform:scale(`…) is removed by the reader.
eprintln!("{name}: removed {:?}", read.removed);
let canvas = compose_canvas(&doc, "main", &read.root).unwrap();
let pdf = compose_highlight(&doc, "main", read.root.clone(), &ids, false).unwrap();
std::fs::write(format!("{out}/{name}.canvas.svg"), serialize(&canvas)).unwrap();
std::fs::write(format!("{out}/{name}.pdf.svg"), serialize(&pdf)).unwrap();
}
let canvas = compose_canvas(&doc, "main", &read_svg(&horse).unwrap().root).unwrap();
let mut s = serialize(&canvas);
let pos = s.rfind("</svg>").unwrap();
s.insert_str(pos, &RECT.replace(" STYLE", ""));
std::fs::write(format!("{out}/control-above.canvas.svg"), &s).unwrap();
let pdf = compose_highlight(&doc, "main", read_svg(&horse).unwrap().root, &ids, false).unwrap();
let mut s = serialize(&pdf);
let pos = s.rfind("</svg>").unwrap();
s.insert_str(pos, &RECT.replace(" STYLE", ""));
std::fs::write(format!("{out}/control-above.pdf.svg"), &s).unwrap();
}
@@ -0,0 +1,33 @@
import { createRequire } from 'node:module'
const require = createRequire(process.argv[2] + '/apps/app/package.json')
const pw = require('@playwright/test')
const sizes = [[320,568],[360,640],[375,667],[390,844],[1280,800]]
const browser = await pw.chromium.launch()
for (const [w,h] of sizes) {
const ctx = await browser.newContext({ viewport: { width: w, height: h }, locale: 'fr-FR', hasTouch: w < 500, isMobile: w < 500 })
const page = await ctx.newPage()
await page.goto('http://127.0.0.1:5197/new')
await page.getByLabel('Nom complet').first().fill('P F')
await page.getByLabel("Nom de l'animal").first().fill('A F')
await page.getByLabel('Nom du propriétaire').first().fill('O F')
await page.getByRole('button',{name:'Démarrer le bilan'}).click()
await page.waitForURL(/editor/)
const dlg = page.getByRole('dialog'); if (await dlg.count()) { await page.keyboard.press('Escape') }
await page.locator('[data-anno-id="hock"]').first().waitFor({ state: 'attached' })
const m = await page.evaluate(() => {
const svg = document.querySelector('.svg-canvas svg'); const r = svg.getBoundingClientRect()
const vb = svg.viewBox.baseVal
const twins = [...svg.querySelectorAll('circle[pointer-events="none"]')].map(c => c.getBoundingClientRect().width)
return { svgW: r.width, svgH: r.height, vbW: vb.width, vbH: vb.height, scale: Math.min(r.width / vb.width, r.height / vb.height), twinMin: Math.min(...twins), twinMax: Math.max(...twins) }
})
// detail modal
await page.locator('[data-anno-id="head-trigger"]').first().dispatchEvent('click')
let d = null
try { await page.locator('dialog [data-anno-id="atm"]').first().waitFor({ state: 'attached', timeout: 5000 })
d = await page.evaluate(() => { const svg = document.querySelector('dialog .svg-canvas svg'); const r = svg.getBoundingClientRect(); const vb = svg.viewBox.baseVal
const twins = [...svg.querySelectorAll('circle[pointer-events="none"]')].map(c => c.getBoundingClientRect().width)
return { svgW: r.width, svgH: r.height, vbW: vb.width, vbH: vb.height, scale: Math.min(r.width / vb.width, r.height / vb.height), twinMin: Math.min(...twins) } }) } catch (e) { d = String(e).slice(0,100) }
console.log(w, h, JSON.stringify(m), 'detail', JSON.stringify(d))
await ctx.close()
}
await browser.close()
@@ -0,0 +1,25 @@
// Painted pixels of one disc (r = span / 4, centre 0.537, 0.463 of the frame) in a 286 x 286 box,
// for frame spans from 1 000 down to 2^-20: area and centroid against the f64 expectation.
import { createRequire } from 'node:module'
const require = createRequire(process.argv[2] + '/apps/app/package.json')
const pw = require('@playwright/test')
const spans = [[1000, '1000'], [10, '10'], [1, '1'], [0.125, '2^-3'], [0.03125, '2^-5'], [1 / 128, '2^-7'], [1 / 1024, '2^-10'], [1 / 16384, '2^-14'], [1 / 1048576, '2^-20']]
const want = { area: Math.PI * 71.5 * 71.5, cx: 0.537 * 286, cy: 0.463 * 286 }
for (const engine of process.argv[3].split(',')) {
const browser = await pw[engine].launch()
const page = await browser.newPage({ viewport: { width: 400, height: 400 } })
console.log(`== ${engine} ${browser.version()} (expected area ${want.area.toFixed(0)} px, centroid ${want.cx.toFixed(2)}, ${want.cy.toFixed(2)})`)
for (const [s, label] of spans) {
await page.setContent(`<html><body style="margin:0;background:#fff"><div id="b" style="width:286px;height:286px"><svg viewBox="0 0 ${s} ${s}" style="max-width:100%;max-height:100%;display:block"><circle cx="${0.537 * s}" cy="${0.463 * s}" r="${s / 4}" fill="#ff00ff"/></svg></div></body></html>`)
const png = (await page.locator('#b').screenshot()).toString('base64')
const m = await page.evaluate(async (b64) => {
const img = new Image(); img.src = 'data:image/png;base64,' + b64; await img.decode()
const c = document.createElement('canvas'); c.width = img.width; c.height = img.height; const x = c.getContext('2d'); x.drawImage(img, 0, 0)
const d = x.getImageData(0, 0, c.width, c.height).data; let a = 0, sx = 0, sy = 0
for (let i = 0; i < d.length; i += 4) { const w = (255 - d[i + 1]) / 255; if (d[i] > 200 && d[i + 2] > 200 && w > 0) { const p = i / 4; a += w; sx += w * (p % c.width); sy += w * Math.floor(p / c.width) } }
return { area: a, cx: sx / a + 0.5, cy: sy / a + 0.5 }
}, png)
console.log(label.padEnd(6), JSON.stringify({ area_gap_rel: +((m.area - want.area) / want.area).toPrecision(2), centroid_gap_px: +Math.hypot(m.cx - want.cx, m.cy - want.cy).toPrecision(2) }))
}
await browser.close()
}
@@ -0,0 +1,57 @@
# V1-2.2 owner decisions (brief « décisions et poursuite des corrections », 2026-11-01), mutation
# run: J = junctions « the visible wins » (canvas passes), S = visible size on the phone preview,
# N = frame range rules (f32), plus the frame and isolation mutants of 2026-10-30 whose anchors
# moved (F5, I2, I6, I7). Each mutant is applied to its source file, its cargo suite runs, the
# file is restored. Run from the repo root; the 2026-10-30 script runs the other mutants as is.
import subprocess
F='crates/core/src/anatomy/frame.rs'
L='crates/core/src/anatomy/layer.rs'
C='crates/core/src/anatomy/compose.rs'
R='crates/core/src/domain/sheet/report.rs'
V='crates/core/src/domain/sheet/verdict.rs'
VIS='sheet_marker_visibility'
muts=[
('J1 canvas draws the PDF layer (document order)',C,' let layer = render_canvas_layer(document, view_id, &HashSet::new())?;',' let layer = render_composed_layer(document, view_id, &HashSet::new())?;','svg_marker_isolation'),
('J2 canvas twins never capture',L,' Form::Canvas => "visiblePainted",',' Form::Canvas => "none",','svg_marker_isolation'),
('J3 shapes before hitboxes',L,' passes[pass as usize].push(Node::Element(element));',' passes[[1, 0, 2][pass as usize]].push(Node::Element(element));','svg_marker_isolation'),
('J4 PDF view in canvas passes',L,' layer(document, view_id, states, Form::Highlight)',' layer(document, view_id, states, Form::Canvas)','anatomy_compose'),
('J5 canvas passes, frozen canvas compared',L,' let children = if form == Form::Canvas {',' let children = if false {','anatomy_canvas_op'),
('S1 size never checked',F,' if shown >= MIN_VISIBLE_PX {',' if true || shown >= MIN_VISIBLE_PX {',VIS),
('S2 point measured on its hitbox',F,' Geometry::Circle(c) if annotation.trigger().is_none() => 2.0 * twin_radius(c.r),',' Geometry::Circle(c) if annotation.trigger().is_none() => 2.0 * c.r,',VIS),
('S3 every view on the main box',F,' let (w, h) = if main_view {',' let (w, h) = if true || main_view {',VIS),
('S4 width-only scale',F,' (w / self.width).min(h / self.height)',' w / self.width',VIS),
('S5 shapes measured on their larger side',F,' _ => (bounds.max_x - bounds.min_x).min(bounds.max_y - bounds.min_y),',' _ => (bounds.max_x - bounds.min_x).max(bounds.max_y - bounds.min_y),',VIS),
('S6 too small reported as out of frame',R,' Placement::TooSmall => (TOO_SMALL, "shows too small on the phone preview"),',' Placement::TooSmall => (OUT_OF_FRAME, "shows too small on the phone preview"),',VIS),
('S7 verdict ignores too small',V,' if found(&[TOO_SMALL]) {\n out.push(codes::MARKER_TOO_SMALL);\n }\n','',VIS),
('S8 too small counted as a rules failure',V,' NO_FRAME,\n TOO_SMALL,\n ]',' NO_FRAME,\n ]',VIS),
('S9 threshold 3 px',F,'pub const MIN_VISIBLE_PX: f64 = 4.0;','pub const MIN_VISIBLE_PX: f64 = 3.0;',VIS),
('S10 threshold 5 px',F,'pub const MIN_VISIBLE_PX: f64 = 4.0;','pub const MIN_VISIBLE_PX: f64 = 5.0;',VIS),
('N1 magnitude unchecked',F,' && reach <= MAX_FRAME_MAGNITUDE\n','',VIS),
('N2 span floor unchecked',F,' && short >= MIN_FRAME_SPAN\n',' && short > 0.0\n',VIS),
('N3 aspect unchecked',F,' && long <= short * MAX_FRAME_ASPECT\n','',VIS),
('N4 offset ratio unchecked',F,' && reach <= short * MAX_FRAME_OFFSET_RATIO;',' ;',VIS),
('N5 reach on the near edges only',F,' let reach = [min_x, min_y, min_x + width, min_y + height]',' let reach = [min_x, min_y]',VIS),
('N6 reach without abs',F,' .fold(0.0_f64, |m, v| m.max(v.abs()));',' .fold(0.0_f64, |m, v| m.max(*v));',VIS),
('N7 non-finite accepted',F,' let usable = finite\n',' let usable = true\n','--lib'),
# Equivalent: the aspect rule (long <= short * 100) refuses a zero or negative span already.
('F5 zero width accepted (moved, equivalent)',F,' && short >= MIN_FRAME_SPAN\n',' && short >= -1.0\n','sheet_frame'),
('F8 unreadable path accepted (moved)',F,' None => (Placement::Unreadable, None),',' None => (Placement::InFrame, None),','sheet_frame'),
('F16 frame faults as rules failure (moved)',V,' let rule = |code: &str| {\n ![\n super::report::GEOMETRY_MISSING,\n OUT_OF_FRAME,\n NO_FRAME,\n TOO_SMALL,\n ]\n .contains(&code)\n };',' let rule = |code: &str| code != super::report::GEOMETRY_MISSING;','sheet_frame'),
('F17 slack follows the offset (rerun, test tightened)',F,' let slack = EDGE_TOLERANCE * self.width.max(self.height);',' let slack = EDGE_TOLERANCE * (self.width.max(self.height) + self.min_x.abs());','sheet_frame'),
('I2 layer inside the drawing group (canvas, moved)',C,' let layer = render_canvas_layer(document, view_id, &HashSet::new())?;\n root.children.push(Node::Element(checked(layer)?));',' let layer = render_canvas_layer(document, view_id, &HashSet::new())?;\n if let Some(Node::Element(group)) = root.children.first_mut() {\n group.children.push(Node::Element(checked(layer)?));\n }','svg_marker_isolation'),
('I6 PDF view draws the R3 layer (moved)',L,' layer(document, view_id, states, Form::Highlight)',' layer(document, view_id, states, Form::Review)','anatomy_compose'),
('I7 R3 layer gets the declared hitbox (moved)',L,' layer(document, view_id, states, Form::Review)',' layer(document, view_id, states, Form::Highlight)','anatomy_layer'),
('C1 census: a root attribute reaches the layer',C,' let mut root = Element {\n qname: "svg".to_owned(),\n namespace: asset.namespace,\n attrs: namespaces,',' let mut root = Element {\n qname: "svg".to_owned(),\n namespace: asset.namespace,\n attrs: namespaces.into_iter().chain(std::iter::once(super::svg::tree::Attribute { qname: "stroke-width".to_owned(), namespace: None, value: "9".to_owned() })).collect(),','svg_marker_isolation'),
]
for name,path,old,new,suite in muts:
src=open(path).read()
if src.count(old)!=1:
print(name,'ANCHOR NOT FOUND x',src.count(old), flush=True); continue
open(path,'w').write(src.replace(old,new))
try:
target = suite if suite.startswith('--') else f'--test {suite}'
r=subprocess.run(['bash','-c',f'. scripts/rust-env.sh && cargo test -q -p faunosteo-core {target} 2>&1 | tail -3'],capture_output=True,text=True)
out=r.stdout
print(f"{name} ({suite}): {'KILLED' if 'FAILED' in out else ('COMPILE-ERR' if 'could not compile' in out or 'error[' in out else 'SURVIVED')}", flush=True)
finally:
open(path,'w').write(src)
+115 -11
View File
@@ -8,8 +8,16 @@
//! visible in the canvas and in the PDF raster, whatever their aspect. Transforms inside the
//! drawing move the drawing only; the reader removes the root's own `transform`. So an
//! annotation is in frame when every point of its shape is inside the frame, edges included.
//!
//! Owner brief 2026-11-01 (the scale bypass): a frame moved far or blown up, its drawing scaled
//! back, kept the horse and shrank every marker to a speck while staying in frame. Two rules
//! close it. The frame is usable only inside the range browsers draw faithfully: they hold
//! coordinates and the view transform in `f32` (24-bit mantissa), so a coordinate's error is
//! about `|v| × 2⁻²⁴` and, measured against the frame, grows with the ratio of the frame's
//! farthest edge to its span. And each annotation must show at least `MIN_VISIBLE_PX` on the
//! smallest preview the product supports, measured on the shape the layer paints.
use super::layer::find_view;
use super::layer::{find_view, twin_radius};
use super::path::{Bounds, number_list, path_bounds};
use super::svg::Element;
use crate::domain::sheet::{AnatomicalSheetDocument, Annotation, Geometry, SheetView};
@@ -28,11 +36,44 @@ pub struct Frame {
/// below a device pixel.
const EDGE_TOLERANCE: f64 = 1e-9;
/// The largest magnitude of a frame edge: `2²⁰`, where an `f32` still holds a sixteenth of a
/// unit (the equine drawing spans 2 073.4).
pub const MAX_FRAME_MAGNITUDE: f64 = 1_048_576.0;
/// The smallest span: one unit. Measured 2026-11-01 (a disc a quarter of the frame, 286 px box,
/// painted pixels): WebKit 27.2 paints nothing from a span of `2⁻⁷`, Chromium 156 drifts at
/// `2⁻¹⁴` and paints nothing at `2⁻²⁰`, all three exact at `2⁻⁵`; one unit keeps a factor 32.
/// Below it the layer's fixed sizes (the disc floor of 4 units, strokes of 1.5 and 2) exceed
/// the frame anyway.
pub const MIN_FRAME_SPAN: f64 = 1.0;
/// The largest ratio of the frame's farthest edge to its smaller span: `2⁸`. A coordinate's
/// `f32` error is then at most `2⁻¹⁶` of the span, 0.15 px on a frame shown 10 000 px wide
/// (equine main view 1.27, head view 1.47).
pub const MAX_FRAME_OFFSET_RATIO: f64 = 256.0;
/// The largest ratio of the longer span to the shorter: beyond it the frame shows as a line on
/// the phone preview (2.9 px tall at 286 px wide; equine 1.27 and 1.32).
pub const MAX_FRAME_ASPECT: f64 = 100.0;
/// The smallest preview the markers must show on (owner decision 2026-11-01): the editor at
/// 320 × 568 CSS px, measured in Chromium. The main view's canvas box is 286 px wide and grows
/// to 310 px tall; a detail view sits in the dialog's 4:3 box, 254 × 191.
pub const MAIN_PREVIEW_PX: (f64, f64) = (286.0, 310.0);
pub const DETAIL_PREVIEW_PX: (f64, f64) = (254.0, 191.0);
/// The smallest visible size of an annotation on that preview (owner decision 2026-11-01): a
/// point's visible disc, a filled shape's smaller side. The equine junctions show 4.97 px.
pub const MIN_VISIBLE_PX: f64 = 4.0;
impl Frame {
fn from_numbers(min_x: f64, min_y: f64, width: f64, height: f64) -> Option<Self> {
let usable = [min_x, min_y, width, height].iter().all(|n| n.is_finite())
&& width > 0.0
&& height > 0.0;
let finite = [min_x, min_y, width, height].iter().all(|n| n.is_finite());
let (short, long) = (width.min(height), width.max(height));
let reach = [min_x, min_y, min_x + width, min_y + height]
.iter()
.fold(0.0_f64, |m, v| m.max(v.abs()));
let usable = finite
&& short >= MIN_FRAME_SPAN
&& reach <= MAX_FRAME_MAGNITUDE
&& long <= short * MAX_FRAME_ASPECT
&& reach <= short * MAX_FRAME_OFFSET_RATIO;
usable.then_some(Self {
min_x,
min_y,
@@ -52,6 +93,16 @@ impl Frame {
)
}
/// CSS pixels per frame unit on the smallest preview (`xMidYMid meet`).
pub fn preview_scale(&self, main_view: bool) -> f64 {
let (w, h) = if main_view {
MAIN_PREVIEW_PX
} else {
DETAIL_PREVIEW_PX
};
(w / self.width).min(h / self.height)
}
fn holds(&self, bounds: &Bounds) -> bool {
let slack = EDGE_TOLERANCE * self.width.max(self.height);
bounds.min_x >= self.min_x - slack
@@ -85,6 +136,19 @@ pub enum Placement {
OutOfFrame,
/// Path data a browser would not read whole.
Unreadable,
/// In frame, but smaller than `MIN_VISIBLE_PX` on the smallest preview.
TooSmall,
}
/// The size an annotation shows, in frame units: what the layer paints. A point's (or a circle
/// zone's) visible disc is its twin's diameter (`layer::twin_radius`, the hitbox is
/// transparent); a trigger's circle, its diameter; a polygon or a path, the smaller side of
/// its bounds (curves and arcs on their shape). `bounds` are the shape's, finite.
fn visible_size(annotation: &Annotation, geometry: &Geometry, bounds: &Bounds) -> f64 {
match geometry {
Geometry::Circle(c) if annotation.trigger().is_none() => 2.0 * twin_radius(c.r),
_ => (bounds.max_x - bounds.min_x).min(bounds.max_y - bounds.min_y),
}
}
pub fn geometry_bounds(geometry: &Geometry) -> Option<Bounds> {
@@ -110,15 +174,39 @@ pub fn geometry_bounds(geometry: &Geometry) -> Option<Bounds> {
/// A bound that is not a finite number (`f64::min` and `max` would drop a NaN) is unreadable,
/// never in frame.
pub fn placement(geometry: &Geometry, frame: &Frame) -> Placement {
placement_with_bounds(geometry, frame).0
}
fn placement_with_bounds(geometry: &Geometry, frame: &Frame) -> (Placement, Option<Bounds>) {
let finite = |b: &Bounds| {
[b.min_x, b.min_y, b.max_x, b.max_y]
.iter()
.all(|n| n.is_finite())
};
match geometry_bounds(geometry).filter(finite) {
None => Placement::Unreadable,
Some(bounds) if frame.holds(&bounds) => Placement::InFrame,
Some(_) => Placement::OutOfFrame,
None => (Placement::Unreadable, None),
Some(bounds) if frame.holds(&bounds) => (Placement::InFrame, Some(bounds)),
Some(bounds) => (Placement::OutOfFrame, Some(bounds)),
}
}
/// The placement of `annotation` on its view's frame, its visible size on the smallest preview
/// included.
pub fn annotation_placement(annotation: &Annotation, frame: &Frame, main_view: bool) -> Placement {
let Some(geometry) = geometry_of(annotation) else {
return Placement::InFrame;
};
match placement_with_bounds(geometry, frame) {
(Placement::InFrame, Some(bounds)) => {
let shown =
visible_size(annotation, geometry, &bounds) * frame.preview_scale(main_view);
if shown >= MIN_VISIBLE_PX {
Placement::InFrame
} else {
Placement::TooSmall
}
}
(placement, _) => placement,
}
}
@@ -154,23 +242,23 @@ pub fn frame_faults<'a>(
faults.push(FrameFault::NoFrame { view_index });
continue;
};
faults.extend(annotation_faults(document, view.id(), &frame));
faults.extend(annotation_faults(document, view, &frame));
}
faults
}
fn annotation_faults(
document: &AnatomicalSheetDocument,
view_id: &str,
view: &SheetView,
frame: &Frame,
) -> Vec<FrameFault> {
document
.annotations
.iter()
.enumerate()
.filter(|(_, a)| a.view_id() == view_id)
.filter(|(_, a)| a.view_id() == view.id())
.filter_map(|(annotation_index, annotation)| {
let placement = placement(geometry_of(annotation)?, frame);
let placement = annotation_placement(annotation, frame, view.is_main());
(placement != Placement::InFrame).then_some(FrameFault::Annotation {
annotation_index,
placement,
@@ -185,3 +273,19 @@ fn geometry_of(annotation: &Annotation) -> Option<&Geometry> {
Annotation::DetailTrigger(a) => a.geometry.as_ref(),
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Neither JSON nor the `viewBox` grammar carries a NaN, and the range rules refuse an
/// infinity; a NaN given directly is refused too (`f64::max` would drop it from the reach).
#[test]
fn a_non_finite_number_never_makes_a_frame() {
assert!(Frame::from_numbers(0.0, 0.0, 10.0, 10.0).is_some());
assert!(Frame::from_numbers(f64::NAN, 0.0, 10.0, 10.0).is_none());
assert!(Frame::from_numbers(0.0, f64::NAN, 10.0, 10.0).is_none());
assert!(Frame::from_numbers(f64::INFINITY, 0.0, 10.0, 10.0).is_none());
assert!(Frame::from_numbers(0.0, 0.0, f64::INFINITY, 10.0).is_none());
}
}
+6 -1
View File
@@ -237,7 +237,7 @@ impl Context<'_> {
let mut visible: Attrs = vec![
("cx", js_number(cx)),
("cy", js_number(cy)),
("r", js_number(2.0_f64.max(r - 12.0))),
("r", js_number(twin_radius(r))),
("fill", color.to_owned()),
("fill-opacity", self.twin_opacity.to_owned()),
("stroke", "#000".to_owned()),
@@ -256,6 +256,11 @@ impl Context<'_> {
}
}
/// The radius of a point's visible twin, drawn on its hitbox of radius `r`.
pub fn twin_radius(r: f64) -> f64 {
2.0_f64.max(r - 12.0)
}
/// A trigger without a name of its own takes the opened view's name in each language
/// (owner decision 2026-10-15; until R3 both attributes carried the French name). A language
/// left empty falls back to the other one.
+13 -7
View File
@@ -22,8 +22,12 @@ pub const GEOMETRY_MISSING: &str = "annotation.geometry.missing";
/// An annotation not entirely inside the frame of its view, or whose path data a browser would
/// not read whole (V1-2.2 owner brief 2026-10-30, `anatomy::frame`).
pub const OUT_OF_FRAME: &str = "annotation.geometry.out_of_frame";
/// A view drawn on a drawing with neither a `view_box` nor a usable drawing `viewBox`.
/// A view drawn on a drawing with neither a usable `view_box` nor a usable drawing `viewBox`
/// (`anatomy::frame`: finite, within the `f32` range rules, not a line).
pub const NO_FRAME: &str = "view.frame.unknown";
/// An annotation in frame that shows below `anatomy::frame::MIN_VISIBLE_PX` on the smallest
/// preview (owner brief 2026-11-01, the scale bypass).
pub const TOO_SMALL: &str = "annotation.geometry.too_small";
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
@@ -107,7 +111,7 @@ fn frame_issue(document: &AnatomicalSheetDocument, fault: &FrameFault) -> SheetI
NO_FRAME,
format!("views[{view_index}]"),
format!(
"View \"{}\" has neither a view_box nor a usable drawing viewBox",
"View \"{}\" has neither a usable view_box nor a usable drawing viewBox",
document.views[view_index].id()
),
),
@@ -116,13 +120,15 @@ fn frame_issue(document: &AnatomicalSheetDocument, fault: &FrameFault) -> SheetI
placement,
} => {
let annotation = &document.annotations[annotation_index];
let what = if placement == Placement::Unreadable {
"has path data that cannot be read whole"
} else {
"is not entirely inside the frame"
let (code, what) = match placement {
Placement::Unreadable => (OUT_OF_FRAME, "has path data that cannot be read whole"),
Placement::TooSmall => (TOO_SMALL, "shows too small on the phone preview"),
Placement::InFrame | Placement::OutOfFrame => {
(OUT_OF_FRAME, "is not entirely inside the frame")
}
};
(
OUT_OF_FRAME,
code,
format!("annotations[{annotation_index}].geometry"),
format!(
"Annotation \"{}\" {what} of view \"{}\"",
+31 -11
View File
@@ -21,7 +21,8 @@ use ts_rs::TS;
use super::caps::CapsReport;
use super::fingerprint::{FingerprintError, document_fingerprint};
use super::report::{
NO_FRAME, OUT_OF_FRAME, SheetReport, frame_issues, referenced_asset_ids, sheet_report,
NO_FRAME, OUT_OF_FRAME, SheetReport, TOO_SMALL, frame_issues, referenced_asset_ids,
sheet_report,
};
use super::review::{Completeness, ElementChange, ReviewGroup, change_list};
use super::schema::AnatomicalSheetDocument;
@@ -54,6 +55,9 @@ pub mod codes {
/// An annotation outside the frame of its view, or a view without a frame (V1-2.2):
/// measured on the views whose drawing reads clean.
pub const OUT_OF_FRAME: &str = "verification.validation.out_of_frame";
/// An annotation in frame that shows below 4 CSS px on the smallest preview (owner brief
/// 2026-11-01): measured on the same views.
pub const MARKER_TOO_SMALL: &str = "verification.validation.marker_too_small";
pub const FINGERPRINT: &str = "verification.integrity.fingerprint";
}
@@ -275,8 +279,15 @@ fn rule_failures(report: &SheetReport) -> Vec<&'static str> {
.filter(|i| i.severity == SheetIssueSeverity::Error)
};
let mut out = Vec::new();
let rule =
|code: &str| ![super::report::GEOMETRY_MISSING, OUT_OF_FRAME, NO_FRAME].contains(&code);
let rule = |code: &str| {
![
super::report::GEOMETRY_MISSING,
OUT_OF_FRAME,
NO_FRAME,
TOO_SMALL,
]
.contains(&code)
};
if errors().any(|i| rule(&i.code)) {
out.push(codes::RULES);
}
@@ -289,14 +300,23 @@ fn rule_failures(report: &SheetReport) -> Vec<&'static str> {
out
}
/// The frame code when a frame issue was found (after the drawing faults: a view is measured
/// only on a drawing that reads clean).
fn frame_failures(report: &SheetReport) -> Option<&'static str> {
report
.issues
.iter()
.any(|i| i.code == OUT_OF_FRAME || i.code == NO_FRAME)
.then_some(codes::OUT_OF_FRAME)
/// The frame codes of the frame issues found, in code order (after the drawing faults: a view
/// is measured only on a drawing that reads clean).
fn frame_failures(report: &SheetReport) -> Vec<&'static str> {
let found = |codes: &[&str]| {
report
.issues
.iter()
.any(|i| codes.contains(&i.code.as_str()))
};
let mut out = Vec::new();
if found(&[OUT_OF_FRAME, NO_FRAME]) {
out.push(codes::OUT_OF_FRAME);
}
if found(&[TOO_SMALL]) {
out.push(codes::MARKER_TOO_SMALL);
}
out
}
struct CheckedDrawing {
+14 -5
View File
@@ -409,16 +409,25 @@ fn both_composers_frame_the_view_on_the_measured_frame() {
}
/// The edge slack follows the frame's span, never its offset: a frame far from the origin
/// keeps the same strictness (security review of the three-MEDIUM brief).
/// keeps the same strictness (security review of the three-MEDIUM brief). Since the owner
/// brief of 2026-11-01 a frame that far (`1e15`) is unusable (`f32` range rules); at the
/// largest offset still accepted (256 spans) the edge is as strict.
#[test]
fn a_frame_far_from_the_origin_is_as_strict() {
let far = |cx: f64| {
let far = |min_x: f64, cx: f64| {
with_view_box(
&with_geometry("main", circle(cx, 5.0, 1.0)),
0,
json!({ "min_x": 1e15, "min_y": 0, "width": 1000, "height": 10 }),
json!({ "min_x": min_x, "min_y": 0, "width": 10, "height": 10 }),
)
};
assert!(accepted(&far(1e15 + 500.0)));
assert!(!accepted(&far(1e15 + 5000.0)));
assert!(accepted(&far(2550.0, 2559.0)), "edge reached");
assert!(
!accepted(&far(2550.0, 2559.0 + 1e-6)),
"a millionth past the edge"
);
assert!(
!accepted(&far(1e15, 1e15 + 5.0)),
"a frame at 1e15 is not usable"
);
}
@@ -0,0 +1,362 @@
//! V1-2.2 owner brief « décisions et poursuite des corrections » (2026-11-01), the scale
//! bypass: the horse with its `viewBox` blown up and its content scaled back is the same horse,
//! every marker in frame and shrunk to a speck, accepted. Two rules of `anatomy::frame` close
//! it, one definition for the verdict and the preview: every annotation shows at least 4 CSS px
//! on the smallest preview (the editor at 320 × 568: the main view's 286 × 310 box, a detail
//! view's 254 × 191; the visible disc for a point, the smaller side for a shape), and a frame is
//! usable only within the `f32` range rules (magnitude, span, aspect, offset against the span).
//! The document is never rewritten.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use common::sheet_readers::{DETAIL_ASSET, MAIN_ASSET, OPEN, document, drawing};
use faunosteo_core::anatomy::frame::{
MAX_FRAME_ASPECT, MAX_FRAME_MAGNITUDE, MAX_FRAME_OFFSET_RATIO, MIN_FRAME_SPAN, MIN_VISIBLE_PX,
};
use faunosteo_core::anatomy::svg::clean::clean_svg;
use faunosteo_core::domain::sheet::preview::{PreviewInput, PreviewSheet, PreviewStatus};
use faunosteo_core::domain::sheet::verdict::{
VerdictBinding, VerdictDrawing, VerdictInput, compute_verdict, sha256_hex,
};
use serde_json::{Value, json};
const SEED: &str = "supabase/seed/anatomical-sheets/equine/draft";
const HORSE_ID: &str = "7f767f74-3b36-51a7-8465-52dd7e2ead4a";
const TOO_SMALL: &str = "annotation.geometry.too_small";
const NO_FRAME: &str = "view.frame.unknown";
const OUT_OF_FRAME: &str = "annotation.geometry.out_of_frame";
/// The verdict's closed codes, as the SQL stores them.
const SMALL_FAILURE: &str = "verification.validation.marker_too_small";
const FRAME_FAILURE: &str = "verification.validation.out_of_frame";
/// The frame and size issues `(code, path)`, the verdict and the preview agreeing, and the
/// verdict's failures.
fn judged(
document: &str,
drawings: &[(&'static str, &str)],
) -> (Vec<(String, String)>, Vec<String>) {
let rows = drawings
.iter()
.map(|(asset_id, text)| VerdictDrawing {
asset_id,
sha256: Box::leak(sha256_hex(text.as_bytes()).into_boxed_str()),
byte_size: text.len() as u64,
bytes: Some(Box::leak(text.as_bytes().to_vec().into_boxed_slice())),
})
.collect();
let verdict = compute_verdict(&VerdictInput {
binding: VerdictBinding {
sheet_id: "s".to_owned(),
version_id: "v".to_owned(),
revision: 1,
review_id: "r".to_owned(),
},
document,
base_document: None,
drawings: rows,
});
let input = PreviewInput {
status: PreviewStatus::Draft,
document: document.to_owned(),
fingerprint: None,
};
let given = drawings
.iter()
.map(|(id, text)| drawing(id, text))
.collect();
let state = PreviewSheet::load(input, given).unwrap().state().unwrap();
let issues = |all: &[faunosteo_core::domain::sheet::SheetIssue]| -> Vec<(String, String)> {
all.iter()
.filter(|i| [TOO_SMALL, NO_FRAME, OUT_OF_FRAME].contains(&i.code.as_str()))
.map(|i| (i.code.clone(), i.path.clone()))
.collect()
};
let found = issues(&verdict.issues);
assert_eq!(
found,
issues(&state.report.issues),
"verdict and preview agree"
);
(found, verdict.failures)
}
/// The shared sheet with the given geometry on its first annotation, and drawings with the
/// given `viewBox` values.
fn shared(
view: &str,
geometry: Value,
main_box: &str,
detail_box: &str,
) -> (Vec<(String, String)>, Vec<String>) {
let mut doc: Value = serde_json::from_str(&document()).unwrap();
doc["annotations"][0]["geometry"] = geometry;
doc["annotations"][0]["view_id"] = json!(view);
let main = OPEN.replace("0 0 10 10", main_box) + "<path d=\"M0 0h1\"/></svg>";
let detail = OPEN.replace("0 0 10 10", detail_box) + "<path d=\"M0 0h1\"/></svg>";
judged(
&doc.to_string(),
&[(MAIN_ASSET, &main), (DETAIL_ASSET, &detail)],
)
}
fn on_main(geometry: Value, view_box: &str) -> (Vec<(String, String)>, Vec<String>) {
shared("main", geometry, view_box, "0 0 10 10")
}
fn circle(cx: f64, cy: f64, r: f64) -> Value {
json!({ "type": "circle", "cx": cx, "cy": cy, "r": r })
}
fn path(d: &str) -> Value {
json!({ "type": "path", "d": d })
}
fn codes(found: &(Vec<(String, String)>, Vec<String>)) -> Vec<String> {
found.0.iter().map(|(code, _)| code.clone()).collect()
}
/// The horse with its `viewBox` multiplied by `factor` and its content scaled back.
fn scaled_horse(factor: f64) -> String {
let horse = common::repo_file(&format!("{SEED}/assets/horse.svg"));
let frame = "viewBox=\"0 0 2073.4 1629.4\">";
assert_eq!(horse.matches(frame).count(), 1);
let text = horse
.replacen(
frame,
&format!(
"viewBox=\"0 0 {} {}\"><g transform=\"scale({factor})\">",
2073.4 * factor,
1629.4 * factor
),
1,
)
.replacen("</svg>", "</g></svg>", 1);
clean_svg(text.as_bytes()).stored.unwrap()
}
fn equine() -> String {
common::repo_file(&format!("{SEED}/document.json"))
}
#[test]
fn the_equine_draft_shows_every_marker_on_the_phone_preview() {
let horse = common::repo_file(&format!("{SEED}/assets/horse.svg"));
let (issues, failures) = judged(&equine(), &[(HORSE_ID, &horse)]);
assert!(issues.is_empty(), "{issues:?}");
assert!(failures.is_empty(), "{failures:?}");
// The smallest: the junctions (r 30, disc r 18) at 286 / 2073.4 px per unit.
let junction = 36.0 * 286.0 / 2073.4;
assert!((4.96..4.97).contains(&junction) && junction >= MIN_VISIBLE_PX);
}
/// The bypass: scaled ×100, every one of the 19 main-view markers is refused as too small (the
/// head view has its own `view_box`); scaled ×1 000 the frame passes `2²⁰` and is not usable.
/// The document text never changes.
#[test]
fn the_blown_up_horse_is_refused() {
let text = equine();
let (issues, failures) = judged(&text, &[(HORSE_ID, &scaled_horse(100.0))]);
assert_eq!(issues.len(), 19, "{issues:?}");
assert!(
issues.iter().all(|(code, _)| code == TOO_SMALL),
"{issues:?}"
);
assert_eq!(failures, [SMALL_FAILURE]);
let doc: Value = serde_json::from_str(&text).unwrap();
for (_, path) in &issues {
let index: usize = path
.strip_prefix("annotations[")
.and_then(|p| p.strip_suffix("].geometry"))
.unwrap()
.parse()
.unwrap();
assert_eq!(doc["annotations"][index]["view_id"], "main");
}
let (issues, failures) = judged(&text, &[(HORSE_ID, &scaled_horse(1000.0))]);
assert_eq!(issues, [(NO_FRAME.to_owned(), "views[0]".to_owned())]);
assert_eq!(failures, [FRAME_FAILURE]);
assert_eq!(text, equine(), "the document is never rewritten");
}
/// The threshold on the real sheet: the junctions fall below 4 px once the horse is scaled by
/// more than 4.966 / 4 ≈ 1.2414; the other points (disc r 22) hold until ≈ 1.517.
#[test]
fn the_equine_threshold_falls_on_the_junctions_first() {
let text = equine();
let small = |factor: f64| -> Vec<String> {
let (issues, _) = judged(&text, &[(HORSE_ID, &scaled_horse(factor))]);
let doc: Value = serde_json::from_str(&text).unwrap();
issues
.iter()
.map(|(_, path)| {
let index: usize = path[12..path.len() - 10].parse().unwrap();
doc["annotations"][index]["id"].as_str().unwrap().to_owned()
})
.collect()
};
assert!(small(1.24).is_empty());
let mut junctions = small(1.25);
junctions.sort();
assert_eq!(junctions, ["c7-t1", "l6-s1", "t18-l1"]);
assert_eq!(small(1.51).len(), 3);
assert_eq!(small(1.52).len(), 13, "every point, the zones still shown");
}
/// A point shows its visible disc, `2 × max(2, r − 12)`, never its transparent hitbox; at
/// 28.6 px per unit (a 10-unit frame on the main box) the disc floor of 4 units shows 114 px.
#[test]
fn a_point_is_measured_on_its_visible_disc() {
// A 1 000-unit frame: 0.286 px per unit. Hitbox r 20 (11.4 px across), disc r 8: 4.58 px.
assert!(codes(&on_main(circle(500.0, 500.0, 20.0), "0 0 1000 1000")).is_empty());
// Disc r 6 (r 18): 3.43 px, while the hitbox would show 10.3 px.
assert_eq!(
codes(&on_main(circle(500.0, 500.0, 18.0), "0 0 1000 1000")),
[TOO_SMALL]
);
// Under r 14 the disc stays r 2: a frame of 10 units shows it 114 px.
assert!(codes(&on_main(circle(5.0, 5.0, 1.0), "0 0 10 10")).is_empty());
}
/// A detail view is measured on the dialog's box (254 × 191), the main view on its own
/// (286 × 310): the same disc on the same 200-unit frame shows 3.82 px in a detail view,
/// 5.72 px on the main view.
#[test]
fn a_detail_view_is_measured_on_the_dialog_box() {
let disc = circle(100.0, 100.0, 1.0);
assert!(codes(&shared("main", disc.clone(), "0 0 200 200", "0 0 200 200")).is_empty());
assert_eq!(
codes(&shared("detail", disc, "0 0 200 200", "0 0 200 200")),
[TOO_SMALL]
);
}
/// Shapes show their smaller side, measured on the curve (never the control points) and the
/// arc: on a 10-unit frame (28.6 px per unit), 4 px is 0.14 unit.
#[test]
fn shapes_are_measured_on_their_curves_and_arcs() {
let main = |d: &str| codes(&on_main(path(d), "0 0 10 10"));
// A cubic whose control points rise 0.18 (5.1 px) while the curve rises 0.135 (3.9 px).
assert_eq!(main("M1 1 C1 1.18 3 1.18 3 1 Z"), [TOO_SMALL]);
assert!(
main("M1 1 C1 1.2 3 1.2 3 1 Z").is_empty(),
"rises 0.15: 4.3 px"
);
// A half ellipse of radius 0.06 (1.7 px), then 0.2 (5.7 px).
assert_eq!(main("M1 1 A1 0.06 0 0 1 3 1 Z"), [TOO_SMALL]);
assert!(main("M1 1 A1 0.2 0 0 1 3 1 Z").is_empty());
// A flat polygon has no smaller side. Declared limit: a thin shape drawn on a diagonal is
// measured on its bounds (the rule is a scale floor, never a shape review).
let line = json!({ "type": "polygon", "points": [[1, 1], [5, 1], [9, 1]] });
assert_eq!(codes(&on_main(line, "0 0 10 10")), [TOO_SMALL]);
}
/// The frame range rules, each at its limit and one step past it; past it the frame is not
/// usable (`view.frame.unknown`, the frame failure).
#[test]
fn the_frame_range_rules_hold_at_their_limits() {
let at =
|view_box: &str, cx: f64, cy: f64, r: f64| codes(&on_main(circle(cx, cy, r), view_box));
// Magnitude: the far edge at 2²⁰ (span 2¹³: the offset ratio, 128, holds on both sides).
let span = 8192.0;
let near = MAX_FRAME_MAGNITUDE - span;
let edge = format!("{near} 0 {span} {span}");
assert!(at(&edge, near + 4096.0, 4096.0, 200.0).is_empty(), "{edge}");
let past = format!("{} 0 {span} {span}", near + 1.0);
assert_eq!(at(&past, near + 4096.0, 4096.0, 200.0), [NO_FRAME]);
// Span: one unit is usable, just below it is not (browsers stop painting a frame of
// `2⁻⁷`, see `MIN_FRAME_SPAN`).
assert!(
at(
&format!("0 0 {MIN_FRAME_SPAN} {MIN_FRAME_SPAN}"),
0.5,
0.5,
0.25
)
.is_empty()
);
assert_eq!(at("0 0 0.999 0.999", 0.5, 0.5, 0.25), [NO_FRAME]);
assert_eq!(
at("0 0 0.0078125 0.0078125", 0.004, 0.004, 0.002),
[NO_FRAME]
);
// Aspect, on the main view while the annotation sits on the detail view (a frame of aspect
// 100 is at most 2.86 px tall on the phone, so nothing in it shows 4 px): 100, then 101.
let band = |w: f64| {
codes(&shared(
"detail",
circle(5.0, 5.0, 1.0),
&format!("0 0 {w} 10"),
"0 0 10 10",
))
};
assert!(band(10.0 * MAX_FRAME_ASPECT).is_empty());
assert_eq!(band(10.0 * MAX_FRAME_ASPECT + 10.0), [NO_FRAME]);
// Offset: the far edge at 256 spans, then past it.
let ratio = MAX_FRAME_OFFSET_RATIO;
assert!(
at(
&format!("{} 0 10 10", ratio * 10.0 - 10.0),
ratio * 10.0 - 5.0,
5.0,
1.0
)
.is_empty()
);
assert_eq!(
at(
&format!("{} 0 10 10", ratio * 10.0 - 9.0),
ratio * 10.0 - 4.0,
5.0,
1.0
),
[NO_FRAME]
);
// Negative offsets count the same.
assert_eq!(
at(
&format!("{} 0 10 10", -ratio * 10.0 - 1.0),
-ratio * 10.0 + 4.0,
5.0,
1.0
),
[NO_FRAME]
);
}
/// A view's own `view_box` follows the same rules as a drawing's `viewBox`.
#[test]
fn a_view_box_follows_the_same_rules() {
let mut doc: Value = serde_json::from_str(&document()).unwrap();
doc["views"][0]["view_box"] = json!({ "min_x": 1e7, "min_y": 0, "width": 10, "height": 10 });
doc["annotations"][0]["geometry"] = circle(1e7 + 5.0, 5.0, 1.0);
let main = OPEN.to_owned() + "<path d=\"M0 0h1\"/></svg>";
let (issues, failures) = judged(
&doc.to_string(),
&[(MAIN_ASSET, &main), (DETAIL_ASSET, &main)],
);
assert_eq!(issues, [(NO_FRAME.to_owned(), "views[0]".to_owned())]);
// The shared sheet fails `verification.validation.rules` on its own; the frame code joins it.
assert!(failures.iter().any(|f| f == FRAME_FAILURE), "{failures:?}");
}
/// The drawing's own transforms move the drawing only (the markers are drawn by the engine, in
/// the frame's user space): a drawing scaled down to nothing keeps its markers' size, and the
/// rule measures them alone.
#[test]
fn transforms_inside_the_drawing_never_change_the_measure() {
let mut doc: Value = serde_json::from_str(&document()).unwrap();
doc["annotations"][0]["geometry"] = circle(5.0, 5.0, 1.0);
let tiny =
OPEN.to_owned() + "<g transform=\"scale(0.000001)\"><path d=\"M0 0h10v10z\"/></g></svg>";
let main = OPEN.to_owned() + "<path d=\"M0 0h1\"/></svg>";
let (issues, failures) = judged(
&doc.to_string(),
&[(MAIN_ASSET, &tiny), (DETAIL_ASSET, &main)],
);
let measured = |f: &String| f == FRAME_FAILURE || f == SMALL_FAILURE;
assert!(
issues.is_empty() && !failures.iter().any(measured),
"{issues:?} {failures:?}"
);
}
+8 -1
View File
@@ -89,7 +89,14 @@ whole frame, which a `slice` would crop where the box is not the frame's); its
other attributes are kept (after sanitising). The verdict and the preview
refuse an annotation not entirely inside this same frame
(`verification.validation.out_of_frame`), so a drawing whose `viewBox` moved
away from the annotations is refused, never drawn without its markers.
away from the annotations is refused, never drawn without its markers. Since
the owner brief of 2026-11-01 a frame is usable only within the range browsers
draw faithfully (edges within 2²⁰, spans from 1 unit, aspect at most
100, farthest edge at most 256 smaller spans; otherwise no usable frame), and
every annotation must show at least 4 CSS px on the smallest preview, the
editor at 320 × 568 (`verification.validation.marker_too_small`): a frame
blown up with its drawing scaled back keeps the drawing and shrinks every
marker, refused.
The editor canvas is inlined in the page, where `#id` resolves against the
whole document. Since V1-2.2 (owner decision 2026-10-29) the core writes
+34
View File
@@ -4294,3 +4294,37 @@ which tints the part it covers at 30 %.
The five `fixme` of the previous checkpoint were one test, « a click on a vertebral junction records the junction », in
each of the five projects of the time: it now runs unmarked in the six. Module: 574 234 B gzip -9 (lot B 573 134).
**The scale bypass, closed by the visible size** (owner decision 2026-11-01: the projected visibility of the markers,
not a cap on the `viewBox`; threshold 4 CSS px on the smallest supported preview, the 6 px starting point refusing the
validated equine). The security review's reproduction: the horse's `viewBox` × 1 000 with the content scaled back draws
the same horse, every marker in frame and below a pixel, accepted. One definition in `anatomy::frame`, measured by the
verdict and the preview after the frame (`frame_faults`), the composers framing on the same `view_frame`:
| Rule | Value and why | Where |
|---|---|---|
| Smallest preview | the editor at 320 × 568 CSS px (the narrowest width the V1-2 contract §8.4 tests), measured in Chromium on 2026-11-01: the main view's canvas box 286 px wide, growing to 310 px tall (a tall frame reaches 310.4); a detail view in the dialog's 4:3 box, 254.9 × 191.1. `MAIN_PREVIEW_PX` 286 × 310, `DETAIL_PREVIEW_PX` 254 × 191, scale `min(w / width, h / height)` (`xMidYMid meet`) | `frame::Frame::preview_scale` |
| Visible size | what the layer paints, never the click surface: a point's (or a circle zone's) visible disc `2 × max(2, r − 12)` (`layer::twin_radius`, the one formula the layer draws with), a trigger circle's diameter, a polygon's or a path's smaller side, curves and arcs on their shape (`path_bounds`) | `frame::visible_size` |
| Threshold | `MIN_VISIBLE_PX` 4. Measured equine at 320 × 568: junctions 4.97 px (`c7-t1`, `l6-s1`, `t18-l1`, r 30), the other main points 6.07, the head points 15.1, the smallest zone side 13.1 (sacral). 6 px would refuse the junctions at 320, 360 (5.66) and 375 px (5.92) | |
| Refusal | issue `annotation.geometry.too_small` (path `annotations[i].geometry`), verdict `verification.validation.marker_too_small` after `out_of_frame`; the document never rewritten | `report.rs`, `verdict.rs`, `preview.rs` (through `frame_issues`) |
| Frame range (`f32`) | a frame is usable only if finite and: every edge within `2²⁰` (`f32` keeps a sixteenth of a unit there), each span at least 1 unit (painted pixels, below: WebKit 27.2 paints nothing from `2⁻⁷`, Chromium 156 drifts at `2⁻¹⁴`; below one unit the layer's fixed sizes exceed the frame), aspect at most 100 (beyond, the frame is 2.9 px tall on the phone box), farthest edge at most 256 smaller spans (a coordinate's `f32` error, about `|v| × 2⁻²⁴`, stays below `2⁻¹⁶` of the span: 0.15 px on a frame shown 10 000 px wide). Equine: edges 2 073.4, ratio 1.27 (main) and 1.47 (head). Otherwise no usable frame (`view.frame.unknown`, `out_of_frame`); the canvas falls back to `0 0 100 100`, the PDF view to no `viewBox` | `frame::Frame::from_numbers` |
The values and transforms the rule bounds: the markers' only transform is the frame's mapping onto the box (they sit
in the engine's root, §12.12), bounded by the frame range; their coordinates are inside the frame, so within it. The
drawing's own transforms move the drawing alone and change no measure (`transforms_inside_the_drawing_never_change_the_measure`);
a drawing scaled to nothing is the preview's and the reviewers' to see, as any drawing content.
Rust and the browsers on the limits (tools `.claude/audits/2026-11-01-v1-2-2-decisions-tools/`: `frame-probe.mjs` on
the cases of `frame_probe_generator.rs.txt`, `span-pixels.mjs`; Chromium 156, Firefox 157, WebKit 27.2). Each case is the
core's composed canvas in the preview box with the AnatomyCanvas CSS; the core's f64 expectation of each hitbox (stroke
none: Firefox counts a stroke in an element's client rect, the others do not) against the browser's layout:
| Case | Core | Chromium / WebKit: size gap, centre gap | Firefox |
|---|---|---|---|
| equine main, × 1.24, × 1.25, × 100, head on the detail box | accepted, accepted (junction disc 4.005 px), `too_small` (3.973), `too_small` (0.050), accepted (15.08) | ≤ 8.2e-5 relative, ≤ 0.014 px | ≤ 0.4 % relative (client rects in 1/60 px app units: 24 % of the 0.067 px hitbox at × 100), ≤ 0.012 px |
| thresholds on a 1 000-unit frame, discs 4.576 and 3.432 px | accepted, `too_small` | ≤ 1e-6 relative, ≤ 4.2e-7 px | ≤ 0.2 %, 0.0035 px |
| far edge at `2²⁰` (span 8 192); far edge at 256 spans (span 10) | accepted, accepted | 0, ≤ 0.0034 px | ≤ 0.84 %, ≤ 0.2 px |
| far edge at 10⁵ and 10⁶ spans (refused, drawn raw) | `no_frame` | centre gap 0.14 px, then 11 px: the `f32` error the ratio rule keeps out | 0.44 px, 9.6 px |
| span 1 unit to `2⁻²⁰`, disc a quarter of the frame, painted pixels | accepted from 1 unit (`no_frame` below) | Chromium exact to `2⁻¹⁰`, 0.46 px at `2⁻¹⁴`, nothing painted at `2⁻²⁰`; WebKit exact to `2⁻⁵`, nothing painted from `2⁻⁷` | exact at every span (its client rects drift from 286 px per unit: 3.3 % at a span of 1, rendering unaffected) |
Declared limit: a thin shape drawn on a diagonal is measured on its bounds, so it can pass while showing a line; the
rule is a scale floor against the bypass, never a review of shapes (the zones keep their declared 2-unit stroke).
+2 -1
View File
@@ -1046,7 +1046,8 @@ Four stages, each a superset of the previous:
| Caps of §1, all of them | yes | | | `verification.validation.caps` |
| Every annotation has a geometry | yes | | | `verification.validation.no_geometry` |
| Every reachable drawing present, size and sha256 equal to its row, read without removal, in the stored form of §9.2 | yes | | | `verification.integrity.*` |
| Every annotation entirely inside the frame of its view, edges included: the view's `view_box`, else the `viewBox` of the drawing it draws, read as a browser reads it (four numbers, positive width and height); curves and arcs measured on their shape; path data a browser would not read whole refused; a view drawn on a clean drawing without either has no frame. Measured on the views whose drawing reads clean; the document is never rewritten (owner brief 2026-10-30, RUST.md §12.11) | yes | | | `verification.validation.out_of_frame` (issues `annotation.geometry.out_of_frame`, `view.frame.unknown`) |
| Every annotation entirely inside the frame of its view, edges included: the view's `view_box`, else the `viewBox` of the drawing it draws, read as a browser reads it (four numbers, positive width and height) and usable within the range rules browsers draw faithfully (owner brief 2026-11-01: edges within 2²⁰, spans from 1 unit, aspect at most 100, farthest edge at most 256 smaller spans); curves and arcs measured on their shape; path data a browser would not read whole refused; a view drawn on a clean drawing without either has no frame. Measured on the views whose drawing reads clean; the document is never rewritten (owner brief 2026-10-30, RUST.md §12.11) | yes | | | `verification.validation.out_of_frame` (issues `annotation.geometry.out_of_frame`, `view.frame.unknown`) |
| Every annotation in frame shows at least 4 CSS px on the smallest preview, the editor at 320 × 568 (main view box 286 × 310, detail view box 254 × 191, `xMidYMid meet`): a point's visible disc (`2 × max(2, r − 12)`), a trigger circle's diameter, a polygon's or a path's smaller side (curves and arcs on their shape). Same views, same frame; the document is never rewritten (owner brief 2026-11-01, RUST.md §12.13) | yes | | | `verification.validation.marker_too_small` (issue `annotation.geometry.too_small`) |
| Fingerprint computed | yes | | | `verification.integrity.fingerprint` |
| Verdict passed, on the current revision | | yes | yes | `verdict.missing`, `verdict.failed`, `verdict.stale` |
| No `to_confirm` element (D2) | | yes | yes | `publish.to_confirm.open` |