feat(anatomy): R5.4 review files in Rust (CHANGELOG, REVIEW-REPORT, review overlays, app drawings) and the whole-draft --check

This commit is contained in:
bchanot committed 2026-10-23 11:21:49 +02:00
1 parent 43ce28a79b
commit fef21d67ef
17 files changed
+2103 -52

No files matched your search

+4
View File
@@ -122,3 +122,7 @@ required-features = ["curation"]
[[test]]
name = "curation_draft"
required-features = ["curation"]
[[test]]
name = "curation_review"
required-features = ["curation"]
+94 -32
View File
@@ -1,10 +1,12 @@
//! `import-equine` (R5.2, R5.3): the anatomical pipeline on the core. Reads the historical
//! `import-equine` (R5.2 to R5.4): the anatomical pipeline on the core. Reads the historical
//! equine files, the authored curation files and the frozen cleaned drawing of the repository,
//! and produces the two generated folders the TypeScript `pnpm import:equine` writes:
//! `legacy-import/` (complete) and `draft/` (its R5.3 files; the review drawings and the two
//! Markdown reports join at R5.4).
//! and produces the two generated folders the TypeScript `pnpm import:equine` writes, whole:
//! `legacy-import/` (6 files) and `draft/` (12 files).
//!
//! import-equine --check compare with the committed folders, write nothing
//! import-equine --check compare with the committed folders, write nothing: every file
//! byte for byte, except the application's drawings, which may
//! fall back on parsed trees under the declared R3 rule; a file
//! missing, not produced or different fails the check
//! import-equine --out <dir> write <dir>/legacy-import and <dir>/draft (<dir> absent or empty)
//!
//! The repository is found from this crate's manifest folder; a relative `--out` is typed from
@@ -19,6 +21,7 @@ use std::io::Write;
use std::path::{Component, Path, PathBuf};
use std::{env, fs, process};
use faunosteo_core::curation::draft::svg_compare::{TriggerNames, compare_drawing};
use faunosteo_core::curation::draft::{
DraftInput, build_equine_draft, parse_changeset, parse_references, parse_view_box,
render_draft_artifacts,
@@ -27,6 +30,7 @@ use faunosteo_core::curation::legacy::{
EquineLegacyInput, HEAD_VIEW_ID, ImportResult, SvgSource, import_equine_legacy,
render_artifacts,
};
use faunosteo_core::domain::sheet::AnatomicalSheetDocument;
const SEED: &str = concat!(
env!("CARGO_MANIFEST_DIR"),
@@ -37,16 +41,9 @@ const LEGACY_FOLDER: &str = "legacy-import";
const DRAFT_FOLDER: &str = "draft";
const CLEANED_ASSET: &str = "assets/horse.svg";
// shortcut: the draft files R5.4 will produce (review drawings, CHANGELOG, REVIEW-REPORT) are
// listed as pending by `--check` and not counted; R5.4 removes this list and compares them.
const PENDING_R5_4: [&str; 6] = [
"review/annotations-main.svg",
"review/annotations-head.svg",
"review/app-main.svg",
"review/app-head.svg",
"CHANGELOG.md",
"REVIEW-REPORT.md",
];
/// The files of the draft whose comparison may fall back on parsed trees under the declared
/// R3 trigger-name rule (`svg_compare`): the application's drawings of each view.
const APP_DRAWING_PREFIX: &str = "review/app-";
/// A file of a generated folder: its path relative to the folder and its bytes.
type FolderFile = (String, Vec<u8>);
@@ -55,6 +52,8 @@ type FolderFile = (String, Vec<u8>);
struct Folder {
name: &'static str,
files: Vec<FolderFile>,
/// The declared tree rule of the application's drawings (the draft only).
trigger_names: Option<TriggerNames>,
}
/// A bound no source or generated file approaches (the largest, the draft CHANGELOG, is about
@@ -122,6 +121,7 @@ fn legacy_folder(input: &EquineLegacyInput, result: &ImportResult) -> Result<Fol
Ok(Folder {
name: LEGACY_FOLDER,
files,
trigger_names: None,
})
}
@@ -143,11 +143,16 @@ fn draft_folder(result: &ImportResult) -> Result<Folder, String> {
changes: &changeset.changes,
})
.map_err(|error| error.to_string())?;
let mut files = texts(render_draft_artifacts(&draft).map_err(|error| error.to_string())?);
let rendered =
render_draft_artifacts(&draft, &result.anomalies).map_err(|error| error.to_string())?;
let typed: AnatomicalSheetDocument =
serde_json::from_value(draft.document.clone()).map_err(|error| error.to_string())?;
let mut files = texts(rendered);
files.push((CLEANED_ASSET.to_owned(), cleaned_svg));
Ok(Folder {
name: DRAFT_FOLDER,
files,
trigger_names: Some(TriggerNames::of(&typed)),
})
}
@@ -177,8 +182,41 @@ fn listed(dir: &Path, prefix: &str, out: &mut Vec<String>) -> Result<(), String>
Ok(())
}
/// The differences between a produced folder and the committed one; pending R5.4 files of the
/// draft are reported, not counted.
/// How one produced file compares with the committed one: byte identity, or, for the
/// application's drawings only, parsed trees under the declared R3 rule (printed as declared).
fn compare_file(
folder: &Folder,
name: &str,
produced: &[u8],
committed: &[u8],
) -> Result<(), String> {
if produced == committed {
return Ok(());
}
let rule = folder
.trigger_names
.as_ref()
.filter(|_| name.starts_with(APP_DRAWING_PREFIX));
let (Ok(produced), Ok(committed)) = (
std::str::from_utf8(produced),
std::str::from_utf8(committed),
) else {
return Err(format!("{}: differs: {name}", folder.name));
};
match compare_drawing(produced, committed, rule) {
Ok(_) => {
println!(
"{}: declared: {name} (trees equal under the R3 trigger-name rule)",
folder.name
);
Ok(())
}
Err(why) => Err(format!("{}: differs: {name} ({why})", folder.name)),
}
}
/// The differences between a produced folder and the committed one: every committed file must
/// be produced and every produced file committed and equal (`compare_file`).
fn check(folder: &Folder) -> Result<Vec<String>, String> {
let target = Path::new(SEED).join(folder.name);
// The generated folder itself must lie in the seed: a link there is never listed through.
@@ -190,8 +228,11 @@ fn check(folder: &Folder) -> Result<Vec<String>, String> {
let mut problems = Vec::new();
for (name, bytes) in &folder.files {
match read(&target.join(name)) {
Ok(committed) if committed == *bytes => {}
Ok(_) => problems.push(format!("{}: differs: {name}", folder.name)),
Ok(committed) => {
if let Err(problem) = compare_file(folder, name, bytes, &committed) {
problems.push(problem);
}
}
Err(_) => problems.push(format!("{}: missing: {name}", folder.name)),
}
}
@@ -201,10 +242,6 @@ fn check(folder: &Folder) -> Result<Vec<String>, String> {
if folder.files.iter().any(|(produced, _)| *produced == name) {
continue;
}
if folder.name == DRAFT_FOLDER && PENDING_R5_4.contains(&name.as_str()) {
println!("{}: pending R5.4 (not compared): {name}", folder.name);
continue;
}
problems.push(format!("{}: not produced: {name}", folder.name));
}
Ok(problems)
@@ -233,7 +270,7 @@ fn claim_destination(typed: &Path, seed: &Path) -> Result<PathBuf, String> {
}
None => return Err(refuse("not a destination folder")),
};
if inside(&parent, seed) || inside_by_identity(&parent, seed) {
if inside(&parent, seed) || inside_by_identity(&parent, seed)? {
return Err(refuse("inside the seed folder"));
}
let name = out
@@ -245,6 +282,10 @@ fn claim_destination(typed: &Path, seed: &Path) -> Result<PathBuf, String> {
Ok(metadata) if metadata.file_type().is_symlink() => return Err(refuse("a symbolic link")),
Ok(metadata) if !metadata.is_dir() => return Err(refuse("not a folder")),
Ok(_) => {
// An existing folder may itself be a second path to a folder of the seed.
if inside_by_identity(&root, seed)? {
return Err(refuse("inside the seed folder"));
}
let mut entries =
fs::read_dir(&root).map_err(|error| format!("{}: {error}", root.display()))?;
if entries.next().is_some() {
@@ -281,15 +322,18 @@ fn seed_identities(seed: &Path) -> Option<Vec<(u64, u64)>> {
/// Whether `folder` or one of its ancestors is the seed folder or a folder under it, by file
/// identity: a second path to any of them (a bind mount, a share mounted twice on the same
/// device) is caught too. A walk that fails counts as inside.
fn inside_by_identity(folder: &Path, seed: &Path) -> bool {
/// device) is caught too. A seed walk that fails is an error (the claim then refuses).
fn inside_by_identity(folder: &Path, seed: &Path) -> Result<bool, String> {
use std::os::unix::fs::MetadataExt;
let Some(identities) = seed_identities(seed) else {
return true;
};
folder.ancestors().any(|ancestor| {
let identities = seed_identities(seed).ok_or_else(|| {
format!(
"{}: the seed folder cannot be read, nothing written",
seed.display()
)
})?;
Ok(folder.ancestors().any(|ancestor| {
fs::metadata(ancestor).is_ok_and(|m| identities.contains(&(m.dev(), m.ino())))
})
}))
}
/// Where a relative destination is typed from: `INIT_CWD` when pnpm set it to an absolute
@@ -437,6 +481,24 @@ mod tests {
assert!(refused.contains("not empty"), "{refused}");
}
#[test]
fn a_difference_fails_the_check_unless_a_declared_rule_covers_it() {
let draft = Folder {
name: DRAFT_FOLDER,
files: Vec::new(),
trigger_names: None,
};
assert!(compare_file(&draft, "CHANGELOG.md", b"a\n", b"a\n").is_ok());
let differs = compare_file(&draft, "CHANGELOG.md", b"a\n", b"b\n")
.err()
.unwrap_or_default();
assert!(differs.contains("differs: CHANGELOG.md"), "{differs}");
// No rule for the folder: even an application drawing must be byte-identical.
let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>";
let other = b"<svg xmlns=\"http://www.w3.org/2000/svg\"><g/></svg>";
assert!(compare_file(&draft, "review/app-main.svg", svg, other).is_err());
}
#[test]
fn a_folder_under_the_seed_or_the_seed_itself_is_inside_it() {
let seed = Path::new("/repo/supabase/seed/anatomical-sheets/equine");
@@ -0,0 +1,37 @@
//! The drawing of one view exactly as the application renders it
//! (`packages/anatomy/src/curation/app-review.ts`): the cleaned asset framed on the view's box
//! plus the annotation layer generated from the document, by the R3 layer the editor canvas
//! uses. Written under `draft/review/app-<view>.svg` so the markers and the framing can be
//! compared outside the browser.
//!
//! Declared difference: the R3 owner decision (2026-10-15) gives a trigger without a name of
//! its own the opened view's name in each language; the TypeScript renderer wrote the French
//! name twice (`svg_compare::TriggerNames`).
use std::collections::HashSet;
use super::drawing::{CleanedDrawing, drawing_text};
use super::targets::fail;
use crate::anatomy::layer::{find_view, render_layer, view_box_of};
use crate::anatomy::svg::Node;
use crate::curation::PipelineError;
use crate::domain::sheet::AnatomicalSheetDocument;
pub fn render_app_review_drawing(
drawing: &CleanedDrawing,
document: &AnatomicalSheetDocument,
view_id: &str,
) -> Result<String, PipelineError> {
let view =
find_view(document, view_id).ok_or_else(|| fail(format!("unknown view \"{view_id}\"")))?;
let mut root = drawing.root.clone();
if let Some(view_box) = view_box_of(view) {
root.set_attr("viewBox", view_box);
}
root.remove_attr("width");
root.remove_attr("height");
let layer = render_layer(document, view_id, &HashSet::new())
.map_err(|_| fail(format!("unknown view \"{view_id}\"")))?;
root.children.push(Node::Element(layer));
Ok(drawing_text(&drawing.prolog, &root))
}
+187
View File
@@ -0,0 +1,187 @@
//! French CHANGELOG of the working revision (`packages/anatomy/src/curation/changelog.ts`):
//! volumes before / after, then one table per change level with every elementary edit. Pure
//! formatting of the records, deterministic (no dates). The text returned here is the raw
//! report; `markdown::format_markdown` aligns its tables as Prettier did.
use serde_json::Value;
use super::labels::{LEVELS, kind_label, level_label};
use super::migration_map::MigrationMapStats;
use super::records::ChangeRecord;
use super::schema::ChangeLevel;
use super::stats::{DocumentStats, stat_rows};
use super::targets::fail;
use crate::curation::PipelineError;
use crate::curation::markdown::{Cell, code, table};
use crate::json::to_js_compact;
/// The longest value text a table cell shows, in UTF-16 units (`text.length`).
const MAX_VALUE_LENGTH: usize = 120;
/// `isLabel`: a non-empty object whose keys are `fr` / `en` with string values.
fn is_label(value: &Value) -> bool {
value.as_object().is_some_and(|map| {
!map.is_empty()
&& map
.iter()
.all(|(key, value)| (key == "fr" || key == "en") && value.is_string())
})
}
/// `compactValue`: labels as text, other non-strings as JSON, cut to 120 UTF-16 units with an
/// ellipsis. A cut inside a surrogate pair leaves a lone surrogate, which the file write turned
/// into U+FFFD: `from_utf16_lossy` gives the same text.
pub fn compact_value(value: &Value) -> Result<String, PipelineError> {
let text = match value {
Value::String(text) => text.clone(),
Value::Object(map) if is_label(value) => map
.values()
.filter_map(Value::as_str)
.collect::<Vec<_>>()
.join(" / "),
other => to_js_compact(other).map_err(|error| fail(format!("value: {error}")))?,
};
let units: Vec<u16> = text.encode_utf16().collect();
if units.len() <= MAX_VALUE_LENGTH {
return Ok(text);
}
Ok(format!(
"{}…",
String::from_utf16_lossy(&units[..MAX_VALUE_LENGTH - 1])
))
}
/// `recordSubject`: the target, with its field when there is one.
pub fn record_subject(record: &ChangeRecord) -> String {
match &record.field {
None => record.target.clone(),
Some(field) => format!("{}.{field}", record.target),
}
}
fn record_row(record: &ChangeRecord) -> Result<Vec<Cell>, PipelineError> {
let change = &record.change;
let references: Vec<String> = change
.reference_ids
.iter()
.map(|id| code(Some(id)))
.collect();
let references = if references.is_empty() {
"-".to_owned()
} else {
references.join(", ")
};
let confirm = if change.level.needs_confirmation() {
"oui"
} else {
"non"
};
Ok(vec![
Cell::from(format!("{} {}", code(Some(&change.id)), change.title.fr)),
Cell::from(code(Some(&record_subject(record)))),
Cell::from(compact_value(&record.before)?),
Cell::from(compact_value(&record.after)?),
Cell::from(kind_label(change.kind)),
Cell::from(change.rationale.as_str()),
Cell::from(references),
Cell::from(confirm),
])
}
fn level_section(level: ChangeLevel, records: &[ChangeRecord]) -> Result<String, PipelineError> {
let rows = records
.iter()
.filter(|record| record.change.level == level)
.map(record_row)
.collect::<Result<Vec<_>, _>>()?;
let head = [
"Changement",
"Objet",
"Avant",
"Après",
"Nature",
"Justification",
"Références",
"Confirmation requise",
];
let body = if rows.is_empty() {
"Aucun changement de ce niveau.".to_owned()
} else {
table(&head, &rows)
};
Ok(format!("## {}\n\n{body}", level_label(level)))
}
fn comparison(before: &DocumentStats, after: &DocumentStats) -> String {
let after_rows = stat_rows(after);
let rows: Vec<Vec<Cell>> = stat_rows(before)
.into_iter()
.map(|(label, value)| {
let later = after_rows
.iter()
.find(|(other, _)| *other == label)
.map_or(0, |(_, value)| *value);
vec![Cell::from(label), Cell::from(value), Cell::from(later)]
})
.collect();
format!(
"## Comparaison quantitative\n\n{}",
table(&["Indicateur", "Avant", "Après"], &rows)
)
}
fn intro() -> String {
[
"# Journal des changements : révision de travail",
"",
"Généré par `pnpm import:equine` : import historique (`legacy-import/`) puis changements \
rédigés (`curation/changes.json`). Ne pas modifier à la main : relancer la commande.",
"",
"Niveaux : A = erreur démontrée, B = amélioration étayée, C = point incertain. Les \
niveaux B et C demandent une confirmation professionnelle.",
]
.join("\n")
}
/// Fate of the legacy finding nodes a Report v2 may cite (`report-migration-map.json`).
fn migration(stats: &MigrationMapStats) -> String {
let row = |label: &str, value: usize| vec![Cell::from(label), Cell::from(value.to_string())];
let rows = vec![
row("Nœuds du catalogue historique", stats.nodes),
row("Chemin identique", stats.identical),
row(
"Chemin renommé ou déplacé (suivi des renommages)",
stats.remapped,
),
row(
"Relogé sous une autre catégorie (correspondance unique)",
stats.rehomed,
),
row(
"Retiré : le bilan garde le constat avec ses libellés figés",
stats.removed,
),
];
format!(
"## Migration des bilans v2\n\n{}",
table(&["Nœuds", "Nombre"], &rows)
)
}
/// `renderChangelog`: the raw text, before the table alignment.
pub fn render_changelog(
records: &[ChangeRecord],
before: &DocumentStats,
after: &DocumentStats,
migration_stats: &MigrationMapStats,
) -> Result<String, PipelineError> {
let mut sections = vec![
intro(),
comparison(before, after),
migration(migration_stats),
];
for level in LEVELS {
sections.push(level_section(level, records)?);
}
Ok(format!("{}\n", sections.join("\n\n")))
}
+41
View File
@@ -0,0 +1,41 @@
//! The frozen cleaned drawing as the review files read it: the text of
//! `draft/assets/horse.svg` through the core's one SVG reader (refused if the reader removes
//! anything: the product's drawings come out untouched), and its prolog (the bytes before the
//! root element: the XML declaration and its line break), kept verbatim in front of every
//! drawing the pipeline writes, as xmldom's serialiser kept it.
use crate::anatomy::svg::serialize::serialize;
use crate::anatomy::svg::{Element, read_svg};
use crate::curation::PipelineError;
pub struct CleanedDrawing {
pub prolog: String,
pub root: Element,
}
fn refuse(why: impl std::fmt::Display) -> PipelineError {
PipelineError::Source(format!("horse.svg: {why}"))
}
/// Reads the cleaned drawing (UTF-8, refused otherwise, as `TextDecoder` fatal was).
pub fn read_cleaned_drawing(bytes: &[u8]) -> Result<CleanedDrawing, PipelineError> {
let text = std::str::from_utf8(bytes).map_err(|_| refuse("invalid UTF-8"))?;
let sanitized = read_svg(text).map_err(|error| refuse(error.reason()))?;
if !sanitized.removed.is_empty() {
return Err(refuse(format!(
"the reader removed {:?}",
sanitized.removed
)));
}
let document = roxmltree::Document::parse(text).map_err(refuse)?;
let start = document.root_element().range().start;
Ok(CleanedDrawing {
prolog: text[..start].to_owned(),
root: sanitized.root,
})
}
/// The file text of a drawing built on the cleaned root.
pub fn drawing_text(prolog: &str, root: &Element) -> String {
format!("{prolog}{}", serialize(root))
}
+45
View File
@@ -0,0 +1,45 @@
//! French labels shared by the CHANGELOG and the review report
//! (`packages/anatomy/src/curation/labels.ts`).
use super::schema::{ChangeKind, ChangeLevel, ChangePriority};
pub fn kind_label(kind: ChangeKind) -> &'static str {
match kind {
ChangeKind::Correction => "Correction",
ChangeKind::Terminology => "Terminologie",
ChangeKind::Translation => "Traduction",
ChangeKind::Restructure => "Réorganisation",
ChangeKind::Enrichment => "Ajout",
ChangeKind::Reference => "Référence",
ChangeKind::Geometry => "Géométrie",
ChangeKind::Removal => "Suppression",
ChangeKind::Technical => "Technique",
}
}
pub fn level_label(level: ChangeLevel) -> &'static str {
match level {
ChangeLevel::A => "Niveau A : erreurs démontrées",
ChangeLevel::B => "Niveau B : améliorations étayées (confirmation requise)",
ChangeLevel::C => "Niveau C : points incertains (question au professionnel)",
}
}
pub fn priority_label(priority: ChangePriority) -> &'static str {
match priority {
ChangePriority::High => "haute",
ChangePriority::Medium => "moyenne",
ChangePriority::Low => "basse",
}
}
pub const LEVELS: [ChangeLevel; 3] = [ChangeLevel::A, ChangeLevel::B, ChangeLevel::C];
/// The letter of a level, as the reports print it.
pub fn level_letter(level: ChangeLevel) -> &'static str {
match level {
ChangeLevel::A => "A",
ChangeLevel::B => "B",
ChangeLevel::C => "C",
}
}
+7
View File
@@ -4,17 +4,24 @@
//! R5.4). Parity with the TypeScript is proven by `tests/curation_draft.rs` against the
//! committed `draft/` folder, `oracles/r5/pipeline.json` and `oracles/r5/curation-synthetic.json`.
pub mod app_review;
pub mod apply;
pub mod changelog;
pub mod drawing;
pub mod fields;
pub mod labels;
pub mod migration_map;
pub mod ops;
pub mod overlay;
pub mod pipeline;
pub mod records;
pub mod rename;
pub mod review_report;
pub mod schema;
pub mod seed;
pub mod shape;
pub mod stats;
pub mod svg_compare;
pub mod targets;
pub use apply::{apply_changeset, curated_issues};
+3 -1
View File
@@ -398,9 +398,11 @@ fn apply_cite(
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
// `before.includes(id)`: only an equal string matches; hashed once per item.
let existing: HashSet<&str> = before.iter().filter_map(Value::as_str).collect();
let added: Vec<Value> = distinct(&op.reference_ids)
.into_iter()
.filter(|id| !before.contains(&Value::from(id.as_str())))
.filter(|id| !existing.contains(id.as_str()))
.map(|id| Value::from(id.clone()))
.collect();
if added.is_empty() {
+365
View File
@@ -0,0 +1,365 @@
//! Before / after drawing of one view for the professional review
//! (`packages/anatomy/src/curation/overlay.ts`): the cleaned anatomy, the curated annotations
//! as an SVG layer, and the baseline position of every moved or removed annotation beside it
//! (dashed). Pure data, deterministic, opens in any browser.
use serde_json::Value;
use super::drawing::{CleanedDrawing, drawing_text};
use super::records::{js_deep_equal, js_string};
use super::targets::fail;
use crate::anatomy::svg::number::{is_js_space, js_number_of};
use crate::anatomy::svg::{Element, Node};
use crate::curation::PipelineError;
use crate::curation::text::js_round;
use crate::json::js_number;
pub const REVIEW_OVERLAY_DIR: &str = "review";
const LAYER_ID: &str = "review-annotations";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Status {
Unchanged,
Moved,
Added,
Removed,
}
impl Status {
fn name(self) -> &'static str {
match self {
Self::Unchanged => "unchanged",
Self::Moved => "moved",
Self::Added => "added",
Self::Removed => "removed",
}
}
/// The marker style, attribute by attribute in the TypeScript order.
fn style(self) -> &'static [(&'static str, &'static str)] {
match self {
Self::Unchanged => &[
("stroke", "#1d4ed8"),
("fill", "#1d4ed8"),
("fill-opacity", "0.12"),
],
Self::Moved | Self::Added => &[
("stroke", "#15803d"),
("fill", "#15803d"),
("fill-opacity", "0.2"),
],
// fill-opacity rather than fill="none": some rasterizers drop unfilled shapes.
Self::Removed => &[
("stroke", "#b91c1c"),
("fill", "#b91c1c"),
("fill-opacity", "0.04"),
("stroke-dasharray", "8 6"),
],
}
}
fn stroke(self) -> &'static str {
self.style()[0].1
}
}
struct Marker<'a> {
id: String,
geometry: &'a Value,
status: Status,
}
fn annotations(doc: &Value) -> &[Value] {
doc.get("annotations")
.and_then(Value::as_array)
.map_or(&[], Vec::as_slice)
}
/// Annotations of the view that carry a geometry (`withGeometry`).
fn with_geometry<'a>(doc: &'a Value, view_id: &str) -> impl Iterator<Item = &'a Value> {
annotations(doc).iter().filter(move |a| {
a.get("view_id").and_then(Value::as_str) == Some(view_id)
&& a.get("geometry").is_some_and(|g| !g.is_null())
})
}
/// `new Map(entries)`: the first position of an id, its last value.
fn previous_geometries<'a>(before: &'a Value, view_id: &str) -> Vec<(String, &'a Value)> {
let mut map: Vec<(String, &Value)> = Vec::new();
for annotation in with_geometry(before, view_id) {
let id = js_string(annotation.get("id"));
let geometry = &annotation["geometry"];
match map.iter_mut().find(|(known, _)| *known == id) {
Some(entry) => entry.1 = geometry,
None => map.push((id, geometry)),
}
}
map
}
/// `overlayMarkers`: curated annotations with their status, then the baseline shapes they left.
fn overlay_markers<'a>(before: &'a Value, after: &'a Value, view_id: &str) -> Vec<Marker<'a>> {
let previous = previous_geometries(before, view_id);
let mut markers = Vec::new();
for annotation in with_geometry(after, view_id) {
let id = js_string(annotation.get("id"));
let geometry = &annotation["geometry"];
let old = previous
.iter()
.find(|(known, _)| *known == id)
.map(|(_, g)| *g);
let status = match old {
None => Status::Added,
Some(old) if js_deep_equal(old, geometry) => Status::Unchanged,
Some(_) => Status::Moved,
};
markers.push(Marker {
id: id.clone(),
geometry,
status,
});
if let (Status::Moved, Some(old)) = (status, old) {
markers.push(Marker {
id,
geometry: old,
status: Status::Removed,
});
}
}
let kept: Vec<String> = annotations(after)
.iter()
.map(|a| js_string(a.get("id")))
.collect();
for (id, geometry) in previous {
if !kept.contains(&id) {
markers.push(Marker {
id,
geometry,
status: Status::Removed,
});
}
}
markers
}
fn number(geometry: &Value, key: &str) -> f64 {
geometry
.get(key)
.and_then(Value::as_f64)
.unwrap_or(f64::NAN)
}
/// `String(number)`, NaN included.
fn text_of(value: f64) -> String {
if value.is_nan() {
"NaN".to_owned()
} else {
js_number(value)
}
}
fn points(geometry: &Value) -> Vec<(f64, f64)> {
let list = geometry.get("points").and_then(Value::as_array);
list.into_iter()
.flatten()
.map(|point| {
let at = |i: usize| point.get(i).and_then(Value::as_f64).unwrap_or(f64::NAN);
(at(0), at(1))
})
.collect()
}
fn shape_element(geometry: &Value) -> Result<Element, PipelineError> {
match geometry.get("type").and_then(Value::as_str) {
Some("circle") => Ok(Element::svg(
"circle",
vec![
("cx", text_of(number(geometry, "cx"))),
("cy", text_of(number(geometry, "cy"))),
("r", text_of(number(geometry, "r"))),
],
Vec::new(),
)),
Some("polygon") => {
let list: Vec<String> = points(geometry)
.into_iter()
.map(|(x, y)| format!("{},{}", text_of(x), text_of(y)))
.collect();
Ok(Element::svg(
"polygon",
vec![("points", list.join(" "))],
Vec::new(),
))
}
Some("path") => Ok(Element::svg(
"path",
vec![("d", js_string(geometry.get("d")))],
Vec::new(),
)),
_ => Err(fail("a geometry of an unknown type")),
}
}
fn label_anchor(geometry: &Value) -> Option<(f64, f64)> {
match geometry.get("type").and_then(Value::as_str) {
Some("circle") => Some((
number(geometry, "cx"),
number(geometry, "cy") - number(geometry, "r") - 4.0,
)),
Some("polygon") => {
let list = points(geometry);
let (sx, sy) = list
.iter()
.fold((0.0, 0.0), |(ax, ay), (x, y)| (ax + x, ay + y));
let n = list.len() as f64;
Some((sx / n, sy / n))
}
_ => None,
}
}
fn text_element(attrs: Vec<(&str, String)>, text: String) -> Element {
Element::svg("text", attrs, vec![Node::Text(text)])
}
fn marker_group(marker: &Marker<'_>, font_size: f64) -> Result<Element, PipelineError> {
let mut shape = shape_element(marker.geometry)?;
for (key, value) in marker.status.style() {
shape.set_attr(key, (*value).to_owned());
}
shape.set_attr("stroke-width", text_of(font_size / 8.0));
let title = Element::svg(
"title",
Vec::new(),
vec![Node::Text(format!(
"{} ({})",
marker.id,
marker.status.name()
))],
);
let mut children = vec![Node::Element(title), Node::Element(shape)];
if let Some((x, y)) = label_anchor(marker.geometry).filter(|_| marker.status != Status::Removed)
{
children.push(Node::Element(text_element(
vec![
("x", text_of(x)),
("y", text_of(y)),
("text-anchor", "middle".to_owned()),
("font-family", "sans-serif".to_owned()),
("font-size", text_of(font_size)),
("fill", marker.status.stroke().to_owned()),
],
marker.id.clone(),
)));
}
Ok(Element::svg(
"g",
vec![
("data-review-id", marker.id.clone()),
("data-review-status", marker.status.name().to_owned()),
],
children,
))
}
fn legend(layer: &mut Element, (x, y): (f64, f64), font_size: f64) {
let lines = [
(Status::Unchanged, "bleu : inchangé"),
(
Status::Moved,
"vert : déplacé ou ajouté (pointillé rouge = position précédente)",
),
(Status::Removed, "rouge pointillé : retiré"),
];
for (index, (status, label)) in lines.into_iter().enumerate() {
let line = (index + 1) as f64;
layer.children.push(Node::Element(text_element(
vec![
("x", text_of(x)),
("y", text_of(y + line * font_size * 1.3)),
("font-family", "sans-serif".to_owned()),
("font-size", text_of(font_size)),
("fill", status.stroke().to_owned()),
],
label.to_owned(),
)));
}
}
/// `raw.split(/[\s,]+/).map(Number)`, without the trim the TypeScript did not do: a run of
/// separators splits once, a leading or trailing run leaves an empty part (`Number("")` is 0).
fn split_numbers(raw: &str) -> Vec<f64> {
let mut parts = Vec::new();
let mut current = String::new();
let mut in_separator = false;
for c in raw.chars() {
if is_js_space(c) || c == ',' {
if !in_separator {
parts.push(std::mem::take(&mut current));
in_separator = true;
}
} else {
in_separator = false;
current.push(c);
}
}
parts.push(current);
parts.iter().map(|part| js_number_of(part)).collect()
}
/// `Math.max(Math.round(width / 90), 10)` with `Math.max`'s NaN.
fn font_size_of(width: f64) -> f64 {
let rounded = js_round(width / 90.0);
if rounded.is_nan() {
f64::NAN
} else {
rounded.max(10.0)
}
}
pub struct OverlayInput<'a> {
pub drawing: &'a CleanedDrawing,
pub before: &'a Value,
pub after: &'a Value,
pub view_id: &'a str,
}
/// The review drawing of one view, framed on that view's box (`renderReviewOverlay`).
pub fn render_review_overlay(input: &OverlayInput<'_>) -> Result<String, PipelineError> {
let view = input
.after
.get("views")
.and_then(Value::as_array)
.and_then(|views| {
views
.iter()
.find(|v| v.get("id").and_then(Value::as_str) == Some(input.view_id))
})
.ok_or_else(|| fail(format!("unknown view \"{}\"", input.view_id)))?;
let mut root = input.drawing.root.clone();
if let Some(view_box) = view.get("view_box").filter(|b| b.is_object()) {
let part = |key: &str| text_of(number(view_box, key));
let text = format!(
"{} {} {} {}",
part("min_x"),
part("min_y"),
part("width"),
part("height")
);
root.set_attr("viewBox", text);
}
root.remove_attr("width");
root.remove_attr("height");
let frame = split_numbers(root.attr("viewBox").unwrap_or("0 0 1000 1000"));
let at = |i: usize| frame.get(i).copied().unwrap_or(f64::NAN);
let font_size = font_size_of(at(2));
let mut layer = Element::svg("g", vec![("id", LAYER_ID.to_owned())], Vec::new());
for marker in overlay_markers(input.before, input.after, input.view_id) {
layer
.children
.push(Node::Element(marker_group(&marker, font_size)?));
}
legend(&mut layer, (at(0) + font_size, at(1)), font_size);
root.children.push(Node::Element(layer));
Ok(drawing_text(&input.drawing.prolog, &root))
}
+76 -9
View File
@@ -10,9 +10,14 @@
use serde_json::{Map, Value, json};
use super::app_review::render_app_review_drawing;
use super::apply::{apply_changeset, curated_issues};
use super::changelog::render_changelog;
use super::drawing::read_cleaned_drawing;
use super::migration_map::{MigrationMapInput, SheetRef, build_report_migration_map};
use super::overlay::{OverlayInput, REVIEW_OVERLAY_DIR, render_review_overlay};
use super::records::ChangeRecord;
use super::review_report::{ReviewReportInput, render_review_report};
use super::schema::{
ASSET_CHANGE_ID, Change, ChangeKind, ChangeLevel, ChangePriority, ChangeSummary, ChangeTitle,
Op, SetOp,
@@ -23,10 +28,11 @@ use super::targets::fail;
use crate::anatomy::svg::number::{js_number_of, js_split_list};
use crate::curation::PipelineError;
use crate::curation::ids::{asset_id_from_sha256, sha256_hex};
use crate::curation::legacy::types::{AssetRecord, ImportResult};
use crate::curation::legacy::types::{Anomaly, AssetRecord, ImportResult};
use crate::curation::legacy::{HEAD_VIEW_ID, MAIN_VIEW_ID};
use crate::curation::markdown::format_markdown;
use crate::curation::prettier_json::format_json;
use crate::domain::sheet::{Reference, SheetIssue, ViewBox};
use crate::domain::sheet::{AnatomicalSheetDocument, Reference, SheetIssue, ViewBox};
pub const DRAFT_SEED_SQL_FILE: &str = "equine_draft.sql";
pub const SHEET_REF_FILE: &str = "sheet-ref.json";
@@ -55,6 +61,8 @@ pub struct DraftResult {
/// Integrity warnings of the curated document (errors refuse).
pub issues: Vec<SheetIssue>,
pub sheet_id: String,
/// The frozen cleaned drawing, `draft/assets/horse.svg`, the review drawings' base.
pub cleaned_svg: Vec<u8>,
}
/// Manifest entry of the cleaned drawing; id derived from its sha256 (`cleanedAsset`).
@@ -151,6 +159,7 @@ pub fn build_equine_draft(input: &DraftInput<'_>) -> Result<DraftResult, Pipelin
changes: changes.iter().map(Change::summary).collect(),
assets: vec![asset],
sheet_id: input.import_result.sheet_id.clone(),
cleaned_svg: input.cleaned_svg.to_vec(),
})
}
@@ -179,12 +188,53 @@ pub fn draft_migration_map(
})
}
/// The R5.3 text artifacts of the draft folder, in the TypeScript order; the R5.4 files
/// (review drawings, CHANGELOG, REVIEW-REPORT) are not produced yet.
pub fn render_draft_artifacts(draft: &DraftResult) -> Result<Vec<(String, String)>, PipelineError> {
/// The views of the curated document, in document order.
fn view_ids(document: &Value) -> Vec<String> {
document
.get("views")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|view| view.get("id").and_then(Value::as_str).map(str::to_owned))
.collect()
}
/// One review overlay per view (`review/annotations-<view>.svg`), then the application's
/// drawing of each view (`review/app-<view>.svg`).
fn review_drawings(draft: &DraftResult) -> Result<Vec<(String, String)>, PipelineError> {
let drawing = read_cleaned_drawing(&draft.cleaned_svg)?;
let typed: AnatomicalSheetDocument = serde_json::from_value(draft.document.clone())
.map_err(|error| fail(format!("curated document: {error}")))?;
let views = view_ids(&draft.document);
let mut files = Vec::new();
for view_id in &views {
let overlay = render_review_overlay(&OverlayInput {
drawing: &drawing,
before: &draft.baseline,
after: &draft.document,
view_id,
})?;
files.push((
format!("{REVIEW_OVERLAY_DIR}/annotations-{view_id}.svg"),
overlay,
));
}
for view_id in &views {
let app = render_app_review_drawing(&drawing, &typed, view_id)?;
files.push((format!("{REVIEW_OVERLAY_DIR}/app-{view_id}.svg"), app));
}
Ok(files)
}
/// The text artifacts of the draft folder, keyed by file name, in the TypeScript order
/// (`renderDraftArtifacts`); the frozen `assets/horse.svg` is the caller's byte copy.
pub fn render_draft_artifacts(
draft: &DraftResult,
legacy_anomalies: &[Anomaly],
) -> Result<Vec<(String, String)>, PipelineError> {
let document_json = format_json(&draft.document)?;
let reference = sheet_ref(draft, &document_json);
let (map, _stats) = draft_migration_map(draft, &reference)?;
let (map, migration_stats) = draft_migration_map(draft, &reference)?;
let assets = serde_json::to_value(&draft.assets)
.map_err(|error| fail(format!("assets.json: {error}")))?;
let sheet_ref_json = json!({
@@ -194,17 +244,34 @@ pub fn render_draft_artifacts(draft: &DraftResult) -> Result<Vec<(String, String
"schema_version": draft.document.get("schema_version"),
"species_id": draft.document.get("species_id"),
});
let changelog = render_changelog(
&draft.records,
&draft.stats_before,
&draft.stats_after,
&migration_stats,
)?;
let review = render_review_report(&ReviewReportInput {
changes: &draft.changes,
records: &draft.records,
document: &draft.document,
stats_before: &draft.stats_before,
legacy_anomalies,
})?;
let seed = render_draft_seed_sql(&DraftSeedParams {
sheet_id: &draft.sheet_id,
assets: &draft.assets,
document_json: &document_json,
change_note: DRAFT_CHANGE_NOTE,
})?;
Ok(vec![
let mut files = vec![
("document.json".to_owned(), document_json),
("assets.json".to_owned(), format_json(&assets)?),
(SHEET_REF_FILE.to_owned(), format_json(&sheet_ref_json)?),
(MIGRATION_MAP_FILE.to_owned(), format_json(&map)?),
(DRAFT_SEED_SQL_FILE.to_owned(), seed),
])
];
files.extend(review_drawings(draft)?);
files.push(("CHANGELOG.md".to_owned(), format_markdown(&changelog)?));
files.push(("REVIEW-REPORT.md".to_owned(), format_markdown(&review)?));
files.push((DRAFT_SEED_SQL_FILE.to_owned(), seed));
Ok(files)
}
@@ -0,0 +1,379 @@
//! French review report for the osteopath, ten fixed sections
//! (`packages/anatomy/src/curation/review-report.ts`). It only formats data (changes,
//! records, stats, references): no medical content is written here, every statement comes
//! from the authored changeset. The text returned is the raw report, before the table
//! alignment.
use std::cmp::Ordering;
use std::collections::HashSet;
use serde_json::Value;
use super::changelog::{compact_value, record_subject};
use super::labels::{kind_label, level_letter, priority_label};
use super::records::{ChangeRecord, js_string};
use super::schema::{ChangeKind, ChangeLevel, ChangePriority, ChangeSummary};
use super::stats::{DocumentStats, stat_rows};
use super::targets::{Step, TargetKind, all_findings, at, top_collection_path, zone_findings};
use crate::curation::PipelineError;
use crate::curation::legacy::types::Anomaly;
use crate::curation::markdown::{Cell, code, table};
use crate::curation::text::utf16_cmp;
pub struct ReviewReportInput<'a> {
pub changes: &'a [ChangeSummary],
pub records: &'a [ChangeRecord],
pub document: &'a Value,
pub stats_before: &'a DocumentStats,
pub legacy_anomalies: &'a [Anomaly],
}
const NONE: &str = "Aucun élément dans cette révision.";
/// `[...new Set(items)]`: first occurrences, in order.
fn distinct(items: impl Iterator<Item = String>) -> Vec<String> {
let mut seen = HashSet::new();
items.filter(|item| seen.insert(item.clone())).collect()
}
fn codes(items: &[String]) -> String {
items
.iter()
.map(|item| code(Some(item)))
.collect::<Vec<_>>()
.join(", ")
}
fn subjects(input: &ReviewReportInput<'_>, change: &ChangeSummary) -> String {
let own = input
.records
.iter()
.filter(|record| record.change.id == change.id)
.map(record_subject);
codes(&distinct(own))
}
fn references(ids: &[String]) -> String {
if ids.is_empty() {
"aucune".to_owned()
} else {
codes(ids)
}
}
fn change_line(input: &ReviewReportInput<'_>, change: &ChangeSummary) -> String {
let confirm = if change.level.needs_confirmation() {
"oui"
} else {
"non"
};
let question = change
.question
.as_ref()
.map_or_else(String::new, |question| format!(" Question : {question}"));
format!(
"- {} {} (niveau {}, {}, confirmation requise : {confirm}). {} Objets : {}. \
Références : {}.{question}",
code(Some(&change.id)),
change.title.fr,
level_letter(change.level),
kind_label(change.kind),
change.rationale,
subjects(input, change),
references(&change.reference_ids),
)
}
fn change_list(input: &ReviewReportInput<'_>, keep: impl Fn(&ChangeSummary) -> bool) -> String {
let lines: Vec<String> = input
.changes
.iter()
.filter(|change| keep(change))
.map(|change| change_line(input, change))
.collect();
if lines.is_empty() {
NONE.to_owned()
} else {
lines.join("\n")
}
}
fn stat_table(head: &str, stats: &DocumentStats) -> String {
let rows: Vec<Vec<Cell>> = stat_rows(stats)
.into_iter()
.map(|(label, value)| vec![Cell::from(label), Cell::from(value)])
.collect();
table(&[head, "Valeur"], &rows)
}
fn initial_quality(input: &ReviewReportInput<'_>) -> String {
let to_validate = input
.legacy_anomalies
.iter()
.filter(|anomaly| anomaly.level == "a_valider")
.count();
[
format!(
"L'import historique signale {} anomalies, dont {to_validate} à valider (détail dans \
`legacy-import/IMPORT-REPORT.md`).",
input.legacy_anomalies.len()
),
String::new(),
stat_table("Indicateur (import historique)", input.stats_before),
]
.join("\n")
}
fn translations(input: &ReviewReportInput<'_>) -> String {
let changes: Vec<&ChangeSummary> = input
.changes
.iter()
.filter(|change| change.kind == ChangeKind::Translation)
.collect();
let ids: HashSet<&str> = changes.iter().map(|change| change.id.as_str()).collect();
let targets = distinct(
input
.records
.iter()
.filter(|record| ids.contains(record.change.id.as_str()))
.map(record_subject),
);
let head = format!(
"{} changement(s) de traduction, {} objet(s) traduit(s).",
changes.len(),
targets.len()
);
if targets.is_empty() {
return head;
}
let lines: Vec<String> = targets
.iter()
.map(|target| format!("- {}", code(Some(target))))
.collect();
format!("{head}\n\n{}", lines.join("\n"))
}
fn vet_flag_changes(input: &ReviewReportInput<'_>) -> Result<String, PipelineError> {
let mut lines = Vec::new();
for record in input
.records
.iter()
.filter(|record| record.field.as_deref() == Some("requires_vet_referral"))
{
lines.push(format!(
"- {} : {} → {} ({})",
code(Some(&record.target)),
compact_value(&record.before)?,
compact_value(&record.after)?,
code(Some(&record.change.id))
));
}
Ok(if lines.is_empty() {
"Aucun renvoi vétérinaire modifié dans cette révision.".to_owned()
} else {
lines.join("\n")
})
}
fn vet_flags_per_zone(document: &Value) -> Result<String, PipelineError> {
let zones_path = top_collection_path(TargetKind::Zone);
let count = document
.get("finding_zones")
.and_then(Value::as_array)
.map_or(0, Vec::len);
let mut rows = Vec::new();
for index in 0..count {
let mut zone_path = zones_path.clone();
zone_path.push(Step::Index(index));
let zone = at(document, &zone_path)?;
let flags = zone_findings(document, &zone_path)?
.iter()
.filter(|entry| {
at(document, &entry.path)
.is_ok_and(|item| item.get("requires_vet_referral") == Some(&Value::Bool(true)))
})
.count();
if flags > 0 {
rows.push(vec![
Cell::from(code(Some(&js_string(zone.get("id"))))),
Cell::from(flags),
]);
}
}
Ok(if rows.is_empty() {
"Aucun renvoi vétérinaire.".to_owned()
} else {
table(&["Zone", "Renvois vétérinaires"], &rows)
})
}
fn clinical_vigilance(input: &ReviewReportInput<'_>) -> Result<String, PipelineError> {
Ok([
"Renvois vétérinaires modifiés :".to_owned(),
String::new(),
vet_flag_changes(input)?,
String::new(),
"Renvois vétérinaires de la fiche, par zone :".to_owned(),
String::new(),
vet_flags_per_zone(input.document)?,
]
.join("\n"))
}
fn citation_count(document: &Value, id: &str) -> Result<usize, PipelineError> {
let wanted = Value::from(id);
let mut count = 0;
for entry in all_findings(document)? {
let cited = at(document, &entry.path)?
.get("reference_ids")
.and_then(Value::as_array)
.is_some_and(|ids| ids.contains(&wanted));
count += usize::from(cited);
}
Ok(count)
}
/// `Boolean(value)` of a reference field.
fn truthy_text(value: Option<&Value>) -> Option<String> {
match value {
None | Some(Value::Null | Value::Bool(false)) => None,
Some(Value::String(text)) if text.is_empty() => None,
other => Some(js_string(other)),
}
}
fn bibliography(document: &Value) -> Result<String, PipelineError> {
let references = document
.get("references")
.and_then(Value::as_array)
.map_or(&[][..], Vec::as_slice);
let mut lines = Vec::new();
for (index, reference) in references.iter().enumerate() {
let links: Vec<String> = [
truthy_text(reference.get("url")).map(|url| format!("URL : {url}")),
truthy_text(reference.get("doi")).map(|doi| format!("DOI : {doi}")),
]
.into_iter()
.flatten()
.collect();
let place = if links.is_empty() {
String::new()
} else {
format!(" ({})", links.join(", "))
};
let id = js_string(reference.get("id"));
lines.push(format!(
"{}. {} {}{place}, cité par {} nœud(s).",
index + 1,
code(Some(&id)),
js_string(reference.get("citation")),
citation_count(document, &id)?
));
}
Ok(if lines.is_empty() {
"Aucune référence déclarée.".to_owned()
} else {
lines.join("\n")
})
}
fn priority_rank(priority: ChangePriority) -> u8 {
match priority {
ChangePriority::High => 0,
ChangePriority::Medium => 1,
ChangePriority::Low => 2,
}
}
/// `byPriorityThenId`: priority order, then ids by UTF-16 code units (a stable sort).
fn by_priority_then_id(a: &&ChangeSummary, b: &&ChangeSummary) -> Ordering {
priority_rank(a.priority)
.cmp(&priority_rank(b.priority))
.then_with(|| utf16_cmp(&a.id, &b.id))
}
fn professional_decisions(input: &ReviewReportInput<'_>) -> String {
let mut questions: Vec<&ChangeSummary> = input
.changes
.iter()
.filter(|change| change.question.is_some())
.collect();
questions.sort_by(by_priority_then_id);
if questions.is_empty() {
return "Aucune question ouverte.".to_owned();
}
questions
.iter()
.enumerate()
.map(|(index, change)| {
format!(
"{}. {} (priorité {}) : {} Références : {}.",
index + 1,
code(Some(&change.id)),
priority_label(change.priority),
change.question.as_deref().unwrap_or_default(),
references(&change.reference_ids)
)
})
.collect::<Vec<_>>()
.join("\n")
}
fn intro() -> String {
[
"# Rapport de revue : révision de travail",
"",
"Généré par `pnpm import:equine` à partir des changements rédigés \
(`curation/changes.json`). Ne pas modifier à la main. Rien n’est publié : la révision \
reste un brouillon jusqu’à la décision du professionnel.",
]
.join("\n")
}
/// `renderReviewReport`: the raw text, before the table alignment.
pub fn render_review_report(input: &ReviewReportInput<'_>) -> Result<String, PipelineError> {
let is = |level: ChangeLevel| move |c: &ChangeSummary| c.level == level;
let sections: Vec<(&str, String)> = vec![
("1. Qualité des données initiales", initial_quality(input)),
(
"2. Principales erreurs anatomiques et ostéopathiques",
change_list(input, |c| {
c.level == ChangeLevel::A
&& matches!(c.kind, ChangeKind::Correction | ChangeKind::Removal)
}),
),
(
"3. Corrections effectuées",
change_list(input, is(ChangeLevel::A)),
),
(
"4. Ajouts",
change_list(input, |c| c.kind == ChangeKind::Enrichment),
),
(
"5. Réorganisations du catalogue",
change_list(input, |c| c.kind == ChangeKind::Restructure),
),
(
"6. Éléments incertains",
change_list(input, is(ChangeLevel::C)),
),
("7. Traductions", translations(input)),
(
"8. Points de vigilance clinique",
clinical_vigilance(input)?,
),
("9. Bibliographie", bibliography(input.document)?),
(
"10. Décisions réservées au professionnel",
professional_decisions(input),
),
];
let mut parts = vec![intro()];
parts.extend(
sections
.into_iter()
.map(|(title, body)| format!("## {title}\n\n{body}")),
);
Ok(format!("{}\n", parts.join("\n\n")))
}
+43
View File
@@ -172,3 +172,46 @@ pub fn document_stats(doc: &Value) -> Result<DocumentStats, PipelineError> {
.count(),
})
}
fn count_rows(label: &str, counts: &Counts) -> Vec<(String, usize)> {
counts
.iter()
.map(|(key, value)| {
let count = value
.as_u64()
.map_or(0, |n| usize::try_from(n).unwrap_or(usize::MAX));
(format!("{label} ({key})"), count)
})
.collect()
}
/// `statRows`: labelled rows, fixed order, French labels.
pub fn stat_rows(stats: &DocumentStats) -> Vec<(String, usize)> {
let row = |label: &str, value: usize| vec![(label.to_owned(), value)];
[
row("Vues", stats.views),
row("Dessins SVG distincts", stats.assets),
row("Annotations", stats.annotations),
count_rows("Annotations", &stats.annotations_by_kind),
count_rows("Annotations, revue", &stats.annotations_by_review_status),
row("Catégories d'annotation", stats.annotation_categories),
row("Zones de constats", stats.finding_zones),
row("Catégories de constats", stats.finding_categories),
row("Nœuds (catégories incluses)", stats.nodes),
row("Feuilles", stats.leaves),
row("Renvois vétérinaires", stats.vet_referrals),
count_rows("Nœuds, revue", &stats.nodes_by_review_status),
row("Descriptions", stats.descriptions),
row(
"Descriptions en français seulement",
stats.descriptions_fr_only,
),
row("Références bibliographiques", stats.references),
row("Nœuds cités", stats.cited_nodes),
row(
"Régions vertébrales avec plage documentée",
stats.regions_with_count_range,
),
]
.concat()
}
@@ -0,0 +1,123 @@
//! How a produced review drawing is compared with the committed xmldom file: byte for byte,
//! else as parsed trees after a declared rule. One rule exists: the R3 owner decision
//! (2026-10-15) that a trigger without a name of its own carries the opened view's name in
//! each language, where the TypeScript renderer wrote the French name twice. It is applied to
//! the committed tree (the frozen file stays as it is): on an element that opens a view, a
//! `data-anno-name-en` equal to the view's French name takes its English name, and a title
//! `FR / FR` under it reads `FR / EN`. Any other difference is reported.
use crate::anatomy::svg::tree::parse_svg;
use crate::anatomy::svg::{Element, Node};
use crate::domain::sheet::AnatomicalSheetDocument;
/// (view id, French name, English name) of every view of the produced document.
pub struct TriggerNames {
views: Vec<(String, String, String)>,
}
impl TriggerNames {
pub fn of(document: &AnatomicalSheetDocument) -> Self {
let views = document
.views
.iter()
.map(|view| {
(
view.id().to_owned(),
view.name().fr.clone(),
view.name().en.clone(),
)
})
.collect();
Self { views }
}
fn apply(&self, element: &mut Element) {
let opened = element.attr("data-anno-opens-view").map(str::to_owned);
let view = opened.and_then(|id| self.views.iter().find(|(v, _, _)| *v == id));
if let Some((_, fr, en)) = view {
if element.attr("data-anno-name-en") == Some(fr.as_str()) {
element.set_attr("data-anno-name-en", en.clone());
}
rename_titles(element, &format!("{fr} / {fr}"), &format!("{fr} / {en}"));
}
for child in &mut element.children {
if let Node::Element(child) = child {
self.apply(child);
}
}
}
}
fn rename_titles(element: &mut Element, from: &str, to: &str) {
for child in &mut element.children {
let Node::Element(child) = child else {
continue;
};
if child.local_name() == "title" {
for text in &mut child.children {
if let Node::Text(value) = text
&& value == from
{
*value = to.to_owned();
}
}
}
}
}
/// How two drawings were found equal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Match {
Bytes,
TreeAfterRule,
}
/// The first place two trees differ, as a path of element names.
fn first_difference(a: &Element, b: &Element, path: &str) -> Option<String> {
let here = format!("{path}/{}", a.qname);
if a.qname != b.qname || a.namespace != b.namespace {
return Some(format!("{here}: element {} vs {}", a.qname, b.qname));
}
if a.attrs != b.attrs {
return Some(format!("{here}: attributes differ"));
}
if a.children.len() != b.children.len() {
return Some(format!(
"{here}: {} vs {} children",
a.children.len(),
b.children.len()
));
}
a.children
.iter()
.zip(&b.children)
.enumerate()
.find_map(|(index, pair)| match pair {
(Node::Element(x), Node::Element(y)) => {
first_difference(x, y, &format!("{here}[{index}]"))
}
(Node::Text(x), Node::Text(y)) if x == y => None,
_ => Some(format!("{here}[{index}]: text or node kind differs")),
})
}
/// Compares a produced drawing with the committed one: bytes, else trees after `rule`.
pub fn compare_drawing(
produced: &str,
committed: &str,
rule: Option<&TriggerNames>,
) -> Result<Match, String> {
if produced == committed {
return Ok(Match::Bytes);
}
let Some(rule) = rule else {
return Err("bytes differ and no tree rule is declared".to_owned());
};
let produced = parse_svg(produced).map_err(|e| format!("produced: {}", e.reason()))?;
let mut committed = parse_svg(committed).map_err(|e| format!("committed: {}", e.reason()))?;
rule.apply(&mut committed);
match first_difference(&produced, &committed, "") {
None => Ok(Match::TreeAfterRule),
Some(difference) => Err(difference),
}
}
+31 -10
View File
@@ -37,6 +37,23 @@ const CURATION: &str = "supabase/seed/anatomical-sheets/equine/curation";
const DRAFT: &str = "supabase/seed/anatomical-sheets/equine/draft";
/// The files R5.3 produces; the review drawings and the Markdown reports are R5.4.
/// The text files of the draft, in the TypeScript order; the review files (drawings, the two
/// reports) are checked by `tests/curation_review.rs` (R5.4).
const DRAFT_FILES: [&str; 11] = [
"document.json",
"assets.json",
"sheet-ref.json",
"report-migration-map.json",
"review/annotations-main.svg",
"review/annotations-head.svg",
"review/app-main.svg",
"review/app-head.svg",
"CHANGELOG.md",
"REVIEW-REPORT.md",
"equine_draft.sql",
];
/// The files R5.3 produced, compared byte for byte here.
const R5_3_FILES: [&str; 5] = [
"document.json",
"assets.json",
@@ -105,10 +122,13 @@ fn value<T: serde::Serialize + ?Sized>(value: &T) -> Value {
#[test]
fn the_r5_3_files_of_the_committed_draft_folder_are_reproduced_byte_for_byte() {
let draft = equine_draft();
let files = render_draft_artifacts(&draft).unwrap();
let files = render_draft_artifacts(&draft, &[]).unwrap();
let names: Vec<&str> = files.iter().map(|(name, _)| name.as_str()).collect();
assert_eq!(names, R5_3_FILES);
for (name, text) in &files {
assert_eq!(names, DRAFT_FILES);
for (name, text) in files
.iter()
.filter(|(name, _)| R5_3_FILES.contains(&name.as_str()))
{
assert!(
*text == common::repo_file(&format!("{DRAFT}/{name}")),
"{name} differs"
@@ -122,7 +142,7 @@ fn the_r5_3_files_of_the_committed_draft_folder_are_reproduced_byte_for_byte() {
#[test]
fn the_document_fingerprint_is_the_historical_value() {
let files = render_draft_artifacts(&equine_draft()).unwrap();
let files = render_draft_artifacts(&equine_draft(), &[]).unwrap();
let document = &files[0].1;
let reference: Value = serde_json::from_str(&files[2].1).unwrap();
assert_eq!(
@@ -177,8 +197,8 @@ fn the_draft_section_of_the_frozen_run_is_reproduced() {
#[test]
fn two_runs_emit_the_same_bytes() {
let first = render_draft_artifacts(&equine_draft()).unwrap();
let second = render_draft_artifacts(&equine_draft()).unwrap();
let first = render_draft_artifacts(&equine_draft(), &[]).unwrap();
let second = render_draft_artifacts(&equine_draft(), &[]).unwrap();
assert_eq!(first, second);
}
@@ -202,7 +222,7 @@ fn node_is_leaf(
#[test]
fn the_612_legacy_leaves_migrate_through_the_produced_map_as_the_typescript_measured() {
let draft = equine_draft();
let files = render_draft_artifacts(&draft).unwrap();
let files = render_draft_artifacts(&draft, &[]).unwrap();
let map: ReportMigrationMap = serde_json::from_str(&files[3].1).unwrap();
let document: AnatomicalSheetDocument = serde_json::from_value(draft.document.clone()).unwrap();
let leaves = archive_support::legacy_leaves();
@@ -517,13 +537,14 @@ fn mobility(document: &Value) -> &Value {
&document["finding_zones"][0]["categories"][0]["children"][0]
}
/// An inherited `Object.prototype` member name (`constructor`, `toString`, `__proto__`…) in a
/// An inherited `Object.prototype` member name (`constructor`, `toString`, `valueOf`…) in a
/// field path is an ordinary key in the port: it is never resolved through a prototype, the
/// settable table still checks the first segment, and every object of the sheet contract is
/// strict, so the key cannot reach the document. The only accepted form is a key a later op
/// replaces: the document is then the one the later op alone gives; one record traces the
/// overwritten write. The TypeScript refused that form (structuredClone of the function read).
/// `__proto__` is refused at the op (`a_proto_segment_is_refused_at_the_op`).
/// overwritten write (or removed with its item). The TypeScript refused that form
/// (structuredClone of the function read). `__proto__` is not one of these names: it is
/// refused at the op (`a_proto_segment_is_refused_at_the_op`).
#[test]
fn an_inherited_member_name_is_a_plain_key_and_bypasses_nothing() {
let renamed = json!({ "fr": "Mobilité", "en": "Mobility" });
+360
View File
@@ -0,0 +1,360 @@
//! The Rust review files against the TypeScript (R5.4): CHANGELOG.md and REVIEW-REPORT.md of the
//! committed draft byte for byte, their raw texts against the ledger's pre-Prettier digests, the
//! four review drawings byte for byte or, for the application's main drawing, as trees under
//! the declared R3 rule; the synthetic cases of `oracles/r5/review-synthetic.json`; two runs
//! byte-equal; an undeclared difference refused.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use faunosteo_core::curation::PipelineError;
use faunosteo_core::curation::draft::app_review::render_app_review_drawing;
use faunosteo_core::curation::draft::changelog::render_changelog;
use faunosteo_core::curation::draft::drawing::read_cleaned_drawing;
use faunosteo_core::curation::draft::migration_map::{
MigrationMapInput, SheetRef, build_report_migration_map,
};
use faunosteo_core::curation::draft::overlay::{OverlayInput, render_review_overlay};
use faunosteo_core::curation::draft::review_report::{ReviewReportInput, render_review_report};
use faunosteo_core::curation::draft::stats::document_stats;
use faunosteo_core::curation::draft::svg_compare::{Match, TriggerNames, compare_drawing};
use faunosteo_core::curation::draft::{
DraftInput, DraftResult, apply_changeset, build_equine_draft, parse_changeset,
parse_references, parse_view_box, render_draft_artifacts,
};
use faunosteo_core::curation::ids::sha256_hex;
use faunosteo_core::curation::legacy::types::Anomaly;
use faunosteo_core::curation::legacy::{
EquineLegacyInput, HEAD_VIEW_ID, ImportResult, SvgSource, import_equine_legacy,
};
use faunosteo_core::curation::markdown::format_markdown;
use faunosteo_core::curation::prettier_json::format_json;
use faunosteo_core::domain::sheet::AnatomicalSheetDocument;
use faunosteo_core::json::to_js_compact;
use serde_json::{Map, Value};
const SOURCES: &str = "supabase/seed/anatomical-sheets/equine/legacy-sources";
const CURATION: &str = "supabase/seed/anatomical-sheets/equine/curation";
const DRAFT: &str = "supabase/seed/anatomical-sheets/equine/draft";
fn bytes(relative: &str) -> Vec<u8> {
std::fs::read(common::repo_path(relative)).unwrap()
}
fn equine() -> (ImportResult, DraftResult) {
let svg = |name: &str| SvgSource {
file_name: name.to_owned(),
bytes: bytes(&format!("{SOURCES}/{name}")),
};
let result = import_equine_legacy(&EquineLegacyInput {
main_svg: svg("Horse.svg"),
head_svg: svg("Horse_head.svg"),
catalog: bytes(&format!("{SOURCES}/pathologies.json")),
vertebrae: bytes(&format!("{SOURCES}/vertebrae.ts")),
})
.unwrap();
let references =
parse_references(&common::repo_file(&format!("{CURATION}/references.json"))).unwrap();
let changeset =
parse_changeset(&common::repo_file(&format!("{CURATION}/changes.json"))).unwrap();
let head = result.view_boxes.get(HEAD_VIEW_ID).and_then(Value::as_str);
let draft = build_equine_draft(&DraftInput {
import_result: &result,
cleaned_svg: &bytes(&format!("{DRAFT}/assets/horse.svg")),
head_view_box: parse_view_box(head).unwrap(),
references: &references,
changes: &changeset.changes,
})
.unwrap();
(result, draft)
}
fn oracle(name: &str) -> Value {
serde_json::from_str(&common::repo_file(&format!(
"crates/core/tests/oracles/r5/{name}"
)))
.unwrap()
}
fn typed(document: &Value) -> AnatomicalSheetDocument {
serde_json::from_value(document.clone()).unwrap()
}
const REVIEW_FILES: [&str; 6] = [
"review/annotations-main.svg",
"review/annotations-head.svg",
"review/app-main.svg",
"review/app-head.svg",
"CHANGELOG.md",
"REVIEW-REPORT.md",
];
#[test]
fn the_review_files_of_the_committed_draft_are_reproduced() {
let (result, draft) = equine();
let files = render_draft_artifacts(&draft, &result.anomalies).unwrap();
let rule = TriggerNames::of(&typed(&draft.document));
for name in REVIEW_FILES {
let produced = &files.iter().find(|(file, _)| file == name).unwrap().1;
let committed = common::repo_file(&format!("{DRAFT}/{name}"));
let outcome = compare_drawing(produced, &committed, Some(&rule));
let expected = if name == "review/app-main.svg" {
Match::TreeAfterRule
} else {
Match::Bytes
};
assert_eq!(outcome, Ok(expected), "{name}");
}
}
/// The one declared difference of the drawings, measured: `app-main.svg` differs from the
/// xmldom file in the trigger's English name and its title only, byte for byte elsewhere.
#[test]
fn app_main_differs_only_by_the_r3_trigger_names() {
let (result, draft) = equine();
let files = render_draft_artifacts(&draft, &result.anomalies).unwrap();
let produced = &files
.iter()
.find(|(file, _)| file == "review/app-main.svg")
.unwrap()
.1;
let committed = common::repo_file(&format!("{DRAFT}/review/app-main.svg"));
let fr = "Tête (vue latérale gauche)";
let en = "Head (left lateral view)";
let expected = committed
.replace(
&format!("data-anno-name-en=\"{fr}\""),
&format!("data-anno-name-en=\"{en}\""),
)
.replace(
&format!("<title>{fr} / {fr}</title>"),
&format!("<title>{fr} / {en}</title>"),
);
assert_ne!(expected, committed);
assert_eq!(*produced, expected);
}
#[test]
fn the_raw_reports_are_the_texts_prettier_received() {
let (result, draft) = equine();
let document_json = format_json(&draft.document).unwrap();
let reference = SheetRef {
sheet_id: draft.sheet_id.clone(),
version_id: None,
document_sha256: sha256_hex(document_json.as_bytes()),
};
let (_, stats) =
faunosteo_core::curation::draft::pipeline::draft_migration_map(&draft, &reference).unwrap();
let changelog = render_changelog(
&draft.records,
&draft.stats_before,
&draft.stats_after,
&stats,
)
.unwrap();
let review = render_review_report(&ReviewReportInput {
changes: &draft.changes,
records: &draft.records,
document: &draft.document,
stats_before: &draft.stats_before,
legacy_anomalies: &result.anomalies,
})
.unwrap();
let ledger = oracle("pipeline.json")["artifacts"]
.as_array()
.unwrap()
.clone();
for (file, raw) in [("CHANGELOG.md", changelog), ("REVIEW-REPORT.md", review)] {
let row = ledger
.iter()
.find(|row| row["folder"] == DRAFT && row["file"] == file)
.unwrap();
assert_eq!(
sha256_hex(raw.as_bytes()),
row["before_prettier_sha256"],
"{file} raw"
);
let formatted = format_markdown(&raw).unwrap();
assert_eq!(
sha256_hex(formatted.as_bytes()),
row["sha256"],
"{file} formatted"
);
}
}
#[test]
fn two_runs_emit_the_same_review_files() {
let (result, draft) = equine();
let first = render_draft_artifacts(&draft, &result.anomalies).unwrap();
let second = render_draft_artifacts(&draft, &result.anomalies).unwrap();
assert_eq!(first, second);
}
#[test]
fn an_undeclared_drawing_difference_is_refused() {
let committed = common::repo_file(&format!("{DRAFT}/review/annotations-main.svg"));
let changed = committed.replacen("#1d4ed8", "#1d4ed9", 1);
let (_, draft) = equine();
let rule = TriggerNames::of(&typed(&draft.document));
assert!(compare_drawing(&changed, &committed, None).is_err());
assert!(compare_drawing(&changed, &committed, Some(&rule)).is_err());
let app = common::repo_file(&format!("{DRAFT}/review/app-head.svg"));
let moved = app.replacen("cx=\"", "cx=\"1", 1);
assert!(compare_drawing(&moved, &app, Some(&rule)).is_err());
}
// ---------------------------------------------------------------------------------------------
// Synthetic cases written by the TypeScript (`oracles/r5/review-synthetic.json`).
/// Cases the port refuses where the TypeScript wrote a file (declared in RUST.md §11.12).
const DECLARED_REFUSALS: [&str; 1] = ["declared-emoji-in-a-cell"];
struct Rendered {
changelog_raw: String,
changelog: Result<String, PipelineError>,
review_raw: String,
review: Result<String, PipelineError>,
drawings: Map<String, Value>,
}
fn render_case(frozen: &Value, case: &Value) -> Rendered {
let baseline = &frozen["baseline"];
let references = parse_references(
&to_js_compact(&serde_json::json!({ "references": frozen["references"] })).unwrap(),
)
.unwrap();
let changeset = parse_changeset(&to_js_compact(&case["changes_file"]).unwrap()).unwrap();
let result = apply_changeset(baseline, &references, &changeset.changes).unwrap();
let before = document_stats(baseline).unwrap();
let after = document_stats(&result.document).unwrap();
let sheet = SheetRef {
sheet_id: "11111111-1111-5111-8111-111111111111".to_owned(),
version_id: None,
document_sha256: "0".repeat(64),
};
let (_, stats) = build_report_migration_map(&MigrationMapInput {
baseline,
final_document: &result.document,
legacy_id_map: frozen["legacy_id_map"].as_object().unwrap(),
records: &result.records,
sheet: &sheet,
main_view_id: "main",
})
.unwrap();
let anomalies: Vec<Anomaly> = frozen["anomalies"]
.as_array()
.unwrap()
.iter()
.map(|a| {
let text = |key: &str| a[key].as_str().unwrap().to_owned();
let level = if a["level"] == "a_valider" {
"a_valider"
} else {
"informatif"
};
Anomaly {
code: text("code"),
level,
subject: text("subject"),
message: text("message"),
}
})
.collect();
let changes: Vec<_> = changeset.changes.iter().map(|c| c.summary()).collect();
let changelog_raw = render_changelog(&result.records, &before, &after, &stats).unwrap();
let review_raw = render_review_report(&ReviewReportInput {
changes: &changes,
records: &result.records,
document: &result.document,
stats_before: &before,
legacy_anomalies: &anomalies,
})
.unwrap();
let drawing = read_cleaned_drawing(frozen["drawing"].as_str().unwrap().as_bytes()).unwrap();
let document = typed(&result.document);
let mut drawings = Map::new();
for view in &document.views {
let id = view.id();
let overlay = render_review_overlay(&OverlayInput {
drawing: &drawing,
before: baseline,
after: &result.document,
view_id: id,
})
.unwrap();
drawings.insert(format!("annotations-{id}"), Value::from(overlay));
}
for view in &document.views {
let app = render_app_review_drawing(&drawing, &document, view.id()).unwrap();
drawings.insert(format!("app-{}", view.id()), Value::from(app));
}
Rendered {
changelog: format_markdown(&changelog_raw),
review: format_markdown(&review_raw),
changelog_raw,
review_raw,
drawings,
}
}
#[test]
fn the_synthetic_review_cases_match_the_typescript_or_are_refused_as_declared() {
let frozen = oracle("review-synthetic.json");
let cases = frozen["cases"].as_array().unwrap();
assert_eq!(cases.len(), 4);
for case in cases {
let name = case["name"].as_str().unwrap();
let rendered = render_case(&frozen, case);
assert_eq!(
rendered.changelog_raw,
case["changelog_raw"].as_str().unwrap(),
"{name}"
);
assert_eq!(
rendered.review_raw,
case["review_raw"].as_str().unwrap(),
"{name}"
);
if DECLARED_REFUSALS.contains(&name) {
let refused = rendered.changelog.unwrap_err();
assert!(
matches!(refused, PipelineError::UnsupportedWidth(_)),
"{name}"
);
continue;
}
assert_eq!(
rendered.changelog.unwrap(),
case["changelog"].as_str().unwrap(),
"{name}"
);
assert_eq!(
rendered.review.unwrap(),
case["review"].as_str().unwrap(),
"{name}"
);
let views = typed(&case_document(&frozen, case)).views.len();
assert_eq!(rendered.drawings.len(), 2 * views, "{name}");
let rule = TriggerNames::of(&typed(&case_document(&frozen, case)));
for (key, produced) in &rendered.drawings {
let committed = case["drawings"][key].as_str().unwrap();
let outcome = compare_drawing(produced.as_str().unwrap(), committed, Some(&rule));
assert!(outcome.is_ok(), "{name} {key}: {outcome:?}");
if key.starts_with("annotations-") {
assert_eq!(outcome, Ok(Match::Bytes), "{name} {key}");
}
}
}
}
fn case_document(frozen: &Value, case: &Value) -> Value {
let references = parse_references(
&to_js_compact(&serde_json::json!({ "references": frozen["references"] })).unwrap(),
)
.unwrap();
let changeset = parse_changeset(&to_js_compact(&case["changes_file"]).unwrap()).unwrap();
apply_changeset(&frozen["baseline"], &references, &changeset.changes)
.unwrap()
.document
}
@@ -0,0 +1 @@
{"baseline":{"schema_version":2,"species_id":"equine","name":{"fr":"Mini","en":"Mini"},"description":{},"scope_disclaimer":{},"attribution":{"authors":[],"license":null,"notes":null},"vertebral_config":{"regions":[{"code":"C","name":{"fr":"Cervicales","en":"Cervical"},"count":7},{"code":"T","name":{"fr":"Thoraciques","en":"Thoracic"},"count":18}]},"references":[],"categories":[{"id":"joints","name":{"fr":"Articulations","en":"Joints"},"color":null},{"id":"bones","name":{"fr":"Os","en":"Bones"},"color":null}],"views":[{"id":"main","kind":"main","name":{"fr":"Vue","en":"View"},"svg_asset_id":"3f6c1b52-8a4e-4d17-9b0c-5e2a7d91c4f8","view_box":null},{"id":"head","kind":"detail","parent_view_id":"main","name":{"fr":"Tête","en":"Head"},"svg_asset_id":null,"view_box":{"min_x":0,"min_y":0,"width":10,"height":10}}],"annotations":[{"id":"hip","kind":"point","view_id":"main","category_id":"joints","laterality":"bilateral","geometry":{"type":"circle","cx":1,"cy":2,"r":3},"name":{"fr":"Hanche","en":"Hip"},"finding_zone_id":"hip","vertebral_region_code":null},{"id":"neck","kind":"zone","view_id":"main","category_id":"bones","laterality":"unpaired","geometry":null,"name":{"fr":"Cou","en":"Neck"},"finding_zone_id":"neck","vertebral_region_code":"C"},{"id":"head-trigger","kind":"detail_trigger","view_id":"main","category_id":"bones","laterality":"unpaired","geometry":null,"name":null,"opens_view_id":"head"}],"finding_zones":[{"id":"hip","name":{"fr":"Hanche","en":"Hip"},"categories":[{"id":"hip-dysfunctions","kind":"dysfunction","name":{"fr":"Dysfonctions","en":"Dysfunctions"},"children":[{"id":"mobility","name":{"fr":"mobility fr","en":"mobility en"},"children":[{"id":"flexion","name":{"fr":"flexion fr","en":"flexion en"}},{"id":"extension","name":{"fr":"extension fr","en":"extension en"}}]},{"id":"pain","name":{"fr":"pain fr","en":"pain en"}}]},{"id":"anamnesis","kind":"anamnesis","name":{"fr":"Anamnèse","en":"Anamnesis"},"children":[{"id":"trauma","name":{"fr":"trauma fr","en":"trauma en"}}]}]},{"id":"neck","name":{"fr":"Cou","en":"Neck"},"categories":[{"id":"neck-dysfunctions","kind":"dysfunction","name":{"fr":"Dysfonctions","en":"Dysfunctions"},"children":[{"id":"stiffness","name":{"fr":"stiffness fr","en":"stiffness en"}},{"id":"vet","name":{"fr":"vet fr","en":"vet en"},"requires_vet_referral":true}]}]}]},"references":[{"id":"atlas","type":"book","citation":"Atlas of anatomy","url":null,"doi":null},{"id":"paper","type":"journal","citation":"A paper","url":null,"doi":"10.1/x"}],"drawing":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 100 80\" width=\"100\" height=\"80\">\n <path d=\"M0 0 L10 10\" fill=\"#ccbbaa\"/>\n <g id=\"body\"><circle cx=\"5\" cy=\"5\" r=\"2\" fill=\"#998877\"/></g>\n</svg>\n","anomalies":[{"code":"a.one","level":"a_valider","subject":"s","message":"m"},{"code":"a.two","level":"informatif","subject":"s","message":"m"},{"code":"a.three","level":"a_valider","subject":"s","message":"m"}],"legacy_id_map":{"views":{"head":"head"},"annotations":{"legacy-hip":"hip","legacy-neck":"neck"},"categories":{},"finding_nodes":{},"assets":{}},"cases":[{"name":"every-section","changes_file":{"changes":[{"id":"CHG-001","level":"A","kind":"correction","title":{"fr":"Essai","en":"Test"},"rationale":"Essai","reference_ids":["atlas"],"ops":[{"op":"set","target":"finding:hip/hip-dysfunctions/mobility","field":"name","value":{"fr":"Mobilité | pipe","en":"Mobility\nline"}},{"op":"set","target":"finding:neck/neck-dysfunctions/stiffness","field":"requires_vet_referral","value":true},{"op":"set","target":"annotation:hip","field":"geometry","value":{"type":"circle","cx":30,"cy":20.5,"r":4}},{"op":"set","target":"annotation:neck","field":"geometry","value":{"type":"polygon","points":[[10,10],[20,10],[15,25]]}}]},{"id":"CHG-002","level":"B","kind":"translation","title":{"fr":"Essai","en":"Test"},"rationale":"Essai","reference_ids":[],"priority":"high","ops":[{"op":"set","target":"finding:hip/hip-dysfunctions/mobility/flexion","field":"description","value":{"fr":"mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot ","en":"mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot mot é"}},{"op":"cite","target":"zone:hip","reference_ids":["paper"],"scope":"subtree"}]},{"id":"CHG-010","level":"C","kind":"enrichment","title":{"fr":"Essai","en":"Test"},"rationale":"Essai","reference_ids":["paper"],"question":"Faut-il la garder ?","priority":"low","ops":[{"op":"add","target":"finding:hip/hip-dysfunctions/mobility","value":{"id":"rotation","name":{"fr":"Rotation « axiale »","en":"Axial rotation"}}}]},{"id":"CHG-0011","level":"C","kind":"restructure","title":{"fr":"Essai","en":"Test"},"rationale":"Essai","reference_ids":[],"question":"Retrait confirmé ?","priority":"high",Line truncated
@@ -0,0 +1,307 @@
/**
* R5.4 freeze (owner brief 2026-10-23 §4, "tester les cas nécessaires"): the TypeScript review
* files on synthetic changesets over the mini sheet and a small drawing, so the Rust port of
* the CHANGELOG, the review report, the review overlays and the application's drawings is held
* to the generic contract and not only to the equine data. Each case records the raw and the
* formatted Markdown and the four drawings. `MAKE_R5_ORACLES=1` writes
* crates/core/tests/oracles/r5/review-synthetic.json.
*/
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import {
applyChangeset,
buildReportMigrationMap,
ChangesetSchema,
documentStats,
renderAppReviewDrawing,
renderChangelog,
renderReviewOverlay,
renderReviewReport,
} from '../src'
import { changeSummary } from '../src/curation/schema'
import { formatMarkdown } from '../src/format'
import { MINI_REFERENCES, miniSheet } from './fixtures/mini-sheet'
const HERE = dirname(fileURLToPath(import.meta.url))
const OUT = resolve(HERE, '../../../crates/core/tests/oracles/r5')
const MAKE = process.env.MAKE_R5_ORACLES === '1'
type Json = Record<string, unknown>
const DRAWING = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 80" width="100" height="80">',
' <path d="M0 0 L10 10" fill="#ccbbaa"/>',
' <g id="body"><circle cx="5" cy="5" r="2" fill="#998877"/></g>',
'</svg>',
'',
].join('\n')
const LEGACY_ID_MAP = {
views: { head: 'head' },
annotations: { 'legacy-hip': 'hip', 'legacy-neck': 'neck' },
categories: {},
finding_nodes: {},
assets: {},
}
const SHEET = {
sheetId: '11111111-1111-5111-8111-111111111111',
versionId: null,
documentSha256: '0'.repeat(64),
}
const ANOMALIES = [
{ code: 'a.one', level: 'a_valider', subject: 's', message: 'm' },
{ code: 'a.two', level: 'informatif', subject: 's', message: 'm' },
{ code: 'a.three', level: 'a_valider', subject: 's', message: 'm' },
]
const MOBILITY = 'finding:hip/hip-dysfunctions/mobility'
function change(id: string, ops: unknown[], extra: Json = {}): Json {
return {
id,
level: 'A',
kind: 'technical',
title: { fr: 'Essai', en: 'Test' },
rationale: 'Essai',
reference_ids: [],
...extra,
ops,
}
}
interface Case {
name: string
changes_file: Json
}
const LONG = 'mot '.repeat(40)
const CASES: Case[] = [
{
name: 'every-section',
changes_file: {
changes: [
change(
'CHG-001',
[
{
op: 'set',
target: MOBILITY,
field: 'name',
value: { fr: 'Mobilité | pipe', en: 'Mobility\nline' },
},
{
op: 'set',
target: 'finding:neck/neck-dysfunctions/stiffness',
field: 'requires_vet_referral',
value: true,
},
{
op: 'set',
target: 'annotation:hip',
field: 'geometry',
value: { type: 'circle', cx: 30, cy: 20.5, r: 4 },
},
{
op: 'set',
target: 'annotation:neck',
field: 'geometry',
value: {
type: 'polygon',
points: [
[10, 10],
[20, 10],
[15, 25],
],
},
},
],
{ kind: 'correction', reference_ids: ['atlas'] },
),
change(
'CHG-002',
[
{
op: 'set',
target: `${MOBILITY}/flexion`,
field: 'description',
value: { fr: LONG, en: `${LONG}é` },
},
{
op: 'cite',
target: 'zone:hip',
reference_ids: ['paper'],
scope: 'subtree',
},
],
{ level: 'B', kind: 'translation', priority: 'high' },
),
change(
'CHG-010',
[
{
op: 'add',
target: MOBILITY,
value: {
id: 'rotation',
name: { fr: 'Rotation « axiale »', en: 'Axial rotation' },
},
},
],
{
level: 'C',
kind: 'enrichment',
question: 'Faut-il la garder ?',
priority: 'low',
reference_ids: ['paper'],
},
),
change(
'CHG-0011',
[{ op: 'remove', target: 'finding:hip/anamnesis/trauma' }],
{
level: 'C',
kind: 'restructure',
question: 'Retrait confirmé ?',
priority: 'high',
},
),
change('CHG-003', [{ op: 'remove', target: `${MOBILITY}/extension` }], {
kind: 'removal',
}),
],
},
},
{
name: 'detail-view-and-path',
changes_file: {
changes: [
change('CHG-001', [
{
op: 'add',
target: 'document',
field: 'annotations',
value: {
id: 'skull',
kind: 'point',
view_id: 'head',
category_id: 'bones',
laterality: 'unpaired',
geometry: { type: 'path', d: 'M1 1 L5 5' },
name: { fr: 'Crâne', en: 'Skull' },
finding_zone_id: 'neck',
vertebral_region_code: null,
},
},
{
op: 'set',
target: 'view:head',
field: 'view_box',
value: { min_x: 2.5, min_y: 1, width: 40, height: 30 },
},
]),
],
},
},
{
name: 'nothing-but-a-level-a',
changes_file: {
changes: [
change('CHG-001', [
{ op: 'set', target: 'document', field: 'name.en', value: 'Small' },
]),
],
},
},
{
// Prettier measures an emoji with its RGI table; the port refuses (declared, R5.2).
name: 'declared-emoji-in-a-cell',
changes_file: {
changes: [
change('CHG-001', [
{
op: 'set',
target: MOBILITY,
field: 'name.en',
value: 'Mobility 🐴',
},
]),
],
},
},
]
async function run(c: Case) {
const changeset = ChangesetSchema.parse(c.changes_file)
const baseline = miniSheet()
const result = applyChangeset(baseline, MINI_REFERENCES, changeset)
const before = documentStats(baseline)
const after = documentStats(result.document)
const migration = buildReportMigrationMap({
baseline: miniSheet() as never,
final: result.document as never,
legacyIdMap: LEGACY_ID_MAP,
records: result.records,
sheet: SHEET,
mainViewId: 'main',
})
const changelogRaw = renderChangelog(result, before, after, migration.stats)
const reviewRaw = renderReviewReport({
changes: changeset.changes.map(changeSummary),
records: result.records,
document: result.document,
statsBefore: before,
legacyAnomalies: ANOMALIES as never,
})
const drawings: Record<string, string> = {}
for (const view of result.document.views) {
drawings[`annotations-${view.id}`] = renderReviewOverlay({
cleanedSvg: DRAWING,
before: miniSheet(),
after: result.document,
viewId: view.id,
})
}
for (const view of result.document.views) {
drawings[`app-${view.id}`] = renderAppReviewDrawing({
cleanedSvg: DRAWING,
document: result.document,
viewId: view.id,
})
}
return {
...c,
changelog_raw: changelogRaw,
changelog: await formatMarkdown(changelogRaw),
review_raw: reviewRaw,
review: await formatMarkdown(reviewRaw),
drawings,
}
}
describe('R5.4 synthetic review oracle', () => {
it('review-synthetic.json', async () => {
const rows = []
for (const c of CASES) rows.push(await run(c))
const oracle = {
baseline: miniSheet(),
references: MINI_REFERENCES,
drawing: DRAWING,
anomalies: ANOMALIES,
legacy_id_map: LEGACY_ID_MAP,
cases: rows,
}
const text = `${JSON.stringify(oracle)}\n`
const file = resolve(OUT, 'review-synthetic.json')
if (MAKE) {
mkdirSync(OUT, { recursive: true })
writeFileSync(file, text)
}
expect(text).toBe(readFileSync(file, 'utf8'))
})
})