Repository Public
1/**2 * Quality Report — deterministic checks run on every save, generation and publication attempt.3 * It verifies what a program can verify (structure, syntax, references, accessibility fields, declared data4 * nature). It is NOT a scientific review: a clean report means "nothing mechanical is wrong", and the report5 * says so. A human reads the sheet before it is published.6 */7import { allBlocks, type Block, type LeafBlock, type Sheet } from "@/schema";8import { checkLatex } from "@/renderer/latex";9import { validateSimulation } from "@/sim/registry";1011export type Severity = "error" | "warning" | "info";12export interface QualityItem { severity: Severity; code: string; blockId?: string; fr: string; en: string }13export interface QualityReport {14 errors: number; warnings: number; infos: number;15 items: QualityItem[];16 /** Publication is refused while this is false. */17 publishable: boolean;18 stats: { blocks: number; words: number; sources: number; sourcesChecked: number; claims: number; claimsUnverified: number };19 checkedAt: string;20}2122const VISUAL = new Set(["diagram", "chart", "matrix", "svg", "image"]);23const textFields = (b: Block | LeafBlock): string[] => {24 const out: (string | undefined)[] = [];25 const walk = (v: unknown, key?: string) => {26 if (typeof v === "string") { if (key !== "latex" && key !== "code" && key !== "id" && key !== "type") out.push(v); }27 else if (Array.isArray(v)) v.forEach((x) => walk(x, key));28 else if (v && typeof v === "object") for (const [k, x] of Object.entries(v)) { if (k === "tree" || k === "blocks") continue; walk(x, k); }29 };30 walk(b);31 return out.filter((s): s is string => !!s);32};3334export function qualityReport(doc: Sheet): QualityReport {35 const items: QualityItem[] = [];36 const add = (severity: Severity, code: string, fr: string, en: string, blockId?: string) => items.push({ severity, code, fr, en, blockId });37 const blocks = allBlocks(doc);38 const m = doc.metadata;3940 // 1. Title, introduction, objective.41 const h1 = doc.blocks.filter((b) => b.type === "heading" && b.level === 1);42 if (h1.length === 0) add("error", "no_title_block", "La fiche n’a pas de titre principal (niveau 1).", "The sheet has no main title (level 1).");43 if (h1.length > 1) add("warning", "many_h1", "Plusieurs titres de niveau 1 : un seul est attendu.", "Several level-1 titles: one is expected.", h1[1].id);44 if (!doc.blocks.slice(0, 4).some((b) => b.type === "paragraph")) add("warning", "no_intro", "Aucune introduction dans les premiers blocs.", "No introduction among the first blocks.");45 if (m.objectives.length === 0) add("warning", "no_objectives", "Aucun objectif pédagogique n’est déclaré.", "No learning objective is declared.");46 if (!m.summary.trim()) add("warning", "no_summary", "Résumé manquant (utilisé pour le partage et les moteurs de recherche).", "Summary missing (used for sharing and search engines).");47 if (m.topics.length === 0) add("warning", "no_topic", "Aucun thème : la fiche n’apparaîtra dans aucune catégorie.", "No topic: the sheet will not appear in any category.");48 if (m.example) add("info", "example", "Fiche marquée « exemple » : un bandeau l’indique aux lecteurs tant qu’elle n’a pas été révisée.", "Marked as an example: a banner tells readers until it has been reviewed.");4950 // Citations and inline maths in every text field.51 const sourceIds = new Set(doc.sources.map((s) => s.id));52 const cited = new Set<string>();53 for (const b of blocks) {54 for (const s of b.sourceIds ?? []) cited.add(s);55 for (const t of textFields(b)) {56 for (const c of t.matchAll(/\[\^([a-z0-9-]+)\]/g)) { cited.add(c[1]); if (!sourceIds.has(c[1])) add("error", "unknown_citation", `Citation [^${c[1]}] sans source correspondante.`, `Citation [^${c[1]}] has no matching source.`, b.id); }57 for (const f of t.matchAll(/\$([^$\n]+)\$/g)) { const r = checkLatex(f[1]); if (!r.ok) add("error", "inline_latex", `Formule en ligne invalide : ${f[1].slice(0, 60)} — ${r.error}`, `Invalid inline formula: ${f[1].slice(0, 60)} — ${r.error}`, b.id); }58 for (const l of t.matchAll(/\]\(([^)]+)\)/g)) if (!/^(https:\/\/|mailto:)/.test(l[1])) add("warning", "unsafe_link", `Lien ignoré (seuls https:// et mailto: sont rendus) : ${l[1].slice(0, 80)}`, `Link ignored (only https:// and mailto: are rendered): ${l[1].slice(0, 80)}`, b.id);59 }60 }6162 for (const b of blocks) {63 // 10. Text alternatives.64 if (VISUAL.has(b.type) && !b.alt?.trim()) add("error", "no_alt", `Texte alternatif manquant (${b.type}).`, `Missing text alternative (${b.type}).`, b.id);65 if (b.type === "simulation" && !b.alt?.trim()) add("warning", "no_alt", "Simulation sans description textuelle.", "Simulation without a text description.", b.id);6667 switch (b.type) {68 case "heading": if (b.text.length > 90) add("warning", "long_heading", "Titre long : risque de débordement sur mobile.", "Long heading: may overflow on phones.", b.id); break;69 case "equation": {70 // 4. Formulas: syntax, defined variables, flagged derivations.71 const r = checkLatex(b.latex);72 if (!r.ok) add("error", "latex", `Équation invalide : ${r.error}`, `Invalid equation: ${r.error}`, b.id);73 for (const v of b.variables ?? []) { const s = checkLatex(v.symbol); if (!s.ok) add("error", "latex_symbol", `Symbole invalide : ${v.symbol}`, `Invalid symbol: ${v.symbol}`, b.id); }74 if (!b.variables?.length) add("warning", "no_variables", "Équation sans définition des variables.", "Equation without variable definitions.", b.id);75 if (b.derivation === "unverified") add("warning", "unverified_derivation", "Dérivation non vérifiée : signalée au lecteur.", "Unverified derivation: flagged to the reader.", b.id);76 break;77 }78 case "diagram": {79 // 3. Arrows must mean something.80 if (b.edges.length > 0 && b.legend.length === 0 && !b.edges.some((e) => e.label)) add("warning", "arrows_unexplained", "Diagramme dont les flèches n’ont ni étiquette ni légende.", "Diagram whose arrows have neither labels nor a legend.", b.id);81 for (const n of b.nodes) if (n.label.length > 40) add("warning", "long_node_label", `Étiquette de nœud longue (« ${n.label.slice(0, 30)}… ») : lisibilité réduite sur mobile.`, `Long node label (“${n.label.slice(0, 30)}…”): harder to read on phones.`, b.id);82 if (b.nodes.length > 24) add("warning", "dense_diagram", "Diagramme dense (plus de 24 nœuds) : vérifier la lisibilité sur iPhone.", "Dense diagram (more than 24 nodes): check readability on a phone.", b.id);83 const linked = new Set(b.edges.flatMap((e) => [e.from, e.to]));84 if (b.edges.length > 0) for (const n of b.nodes) if (!linked.has(n.id)) add("info", "orphan_node", `Nœud isolé : ${n.label}`, `Unconnected node: ${n.label}`, b.id);85 break;86 }87 case "chart": {88 // 5. Charts: units, nature of the data, sources.89 if (b.dataKind === "empirical" && !(b.sourceIds?.length)) add("error", "empirical_without_source", "Graphique de données réelles sans source.", "Chart of real data without a source.", b.id);90 if (b.dataKind !== "empirical" && !b.caption) add("warning", "no_caption", "Graphique non empirique sans légende expliquant comment les valeurs ont été obtenues.", "Non-empirical chart without a caption explaining how the values were obtained.", b.id);91 if (!b.x.unit && !b.y.unit) add("info", "no_units", "Aucune unité sur les axes.", "No unit on either axis.", b.id);92 for (const s of b.series) {93 if (b.x.type === "number" && s.points.some((p) => typeof p.x !== "number")) add("error", "chart_x_type", `Série « ${s.name} » : abscisses non numériques sur un axe numérique.`, `Series “${s.name}”: non-numeric x values on a numeric axis.`, b.id);94 if ((b.x.scale === "log" && s.points.some((p) => typeof p.x === "number" && p.x <= 0)) || (b.y.scale === "log" && s.points.some((p) => p.y <= 0))) add("error", "chart_log", `Série « ${s.name} » : valeur non positive sur une échelle logarithmique.`, `Series “${s.name}”: non-positive value on a log scale.`, b.id);95 if (s.points.some((p) => (p.lo !== undefined && p.lo > p.y) || (p.hi !== undefined && p.hi < p.y))) add("error", "chart_interval", `Série « ${s.name} » : intervalle qui ne contient pas la valeur.`, `Series “${s.name}”: interval that does not contain the value.`, b.id);96 }97 break;98 }99 case "matrix": if (b.dataKind === "empirical" && !(b.sourceIds?.length)) add("error", "empirical_without_source", "Matrice de données réelles sans source.", "Matrix of real data without a source.", b.id); break;100 case "table": if (b.columns.length > 5) add("warning", "wide_table", "Tableau de plus de 5 colonnes : défilement horizontal sur mobile.", "Table with more than 5 columns: scrolls sideways on phones.", b.id); break;101 case "simulation": for (const e of validateSimulation(b)) add("error", "simulation", `Simulation : ${e}`, `Simulation: ${e}`, b.id); break;102 case "code": if (b.code.split("\n").some((l) => l.length > 100)) add("info", "long_code_line", "Ligne de code de plus de 100 caractères : défilement horizontal.", "Code line longer than 100 characters: scrolls sideways.", b.id); break;103 default: break;104 }105 }106107 // 6–8. Sources and claims.108 if (doc.sources.length === 0) add("warning", "no_sources", "Aucune source citée.", "No source is cited.");109 for (const s of doc.sources) {110 if (s.status === "unverified") add("warning", "source_unverified", `Source non vérifiée : ${s.title.slice(0, 80)}`, `Unverified source: ${s.title.slice(0, 80)}`);111 if (s.status === "unreachable") add("warning", "source_unreachable", `Source injoignable lors de la vérification : ${s.title.slice(0, 80)}`, `Source unreachable when checked: ${s.title.slice(0, 80)}`);112 if (!s.doi && !s.url && s.type !== "book" && s.type !== "upload") add("info", "source_no_locator", `Source sans DOI ni URL : ${s.title.slice(0, 80)}`, `Source without DOI or URL: ${s.title.slice(0, 80)}`);113 if (!cited.has(s.id)) add("info", "source_uncited", `Source jamais citée dans le texte : ${s.title.slice(0, 80)}`, `Source never cited in the text: ${s.title.slice(0, 80)}`);114 }115 if (doc.sources.length > 0 && !blocks.some((b) => b.type === "references")) add("warning", "no_references_block", "Des sources existent mais aucun bloc « Références » ne les affiche.", "Sources exist but no “References” block shows them.");116 for (const c of doc.claims) {117 if (c.status === "sourced" && c.sourceIds.length === 0) add("error", "claim_without_source", `Affirmation déclarée « sourcée » sans source : ${c.text.slice(0, 80)}`, `Claim declared “sourced” without a source: ${c.text.slice(0, 80)}`, c.blockId);118 if (c.status === "unverified") add("warning", "claim_unverified", `Affirmation non vérifiée : ${c.text.slice(0, 100)}`, `Unverified claim: ${c.text.slice(0, 100)}`, c.blockId);119 }120121 const order: Record<Severity, number> = { error: 0, warning: 1, info: 2 };122 items.sort((a, b) => order[a.severity] - order[b.severity]);123 const count = (s: Severity) => items.filter((i) => i.severity === s).length;124 const words = blocks.flatMap(textFields).join(" ").split(/\s+/).filter(Boolean).length;125 return {126 errors: count("error"), warnings: count("warning"), infos: count("info"), items,127 publishable: count("error") === 0,128 stats: { blocks: blocks.length, words, sources: doc.sources.length, sourcesChecked: doc.sources.filter((s) => s.status === "resolved" || s.status === "reviewed").length, claims: doc.claims.length, claimsUnverified: doc.claims.filter((c) => c.status === "unverified").length },129 checkedAt: new Date().toISOString(),130 };131}132