From 2fe455f5d12a5e4a352cc8f32119c21491e34510 Mon Sep 17 00:00:00 2001 From: Denis Defolie Date: Sun, 11 Oct 2026 17:03:14 +0200 Subject: [PATCH] Add pure correction and pedagogy logic with full test coverage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit scripts/correction/: AnswerValidator (multiple choice, sentence correction via tap-the-faulty-word + retype) and DictationAnalyzer build the CorrectionResult structure from cahier des charges §6. Dictation analysis aligns words with WordAligner (Wagner-Fischer edit distance) before any character comparison, so an omitted or added word doesn't cascade into false errors on every following word. TextNormalizer handles non-breaking spaces, typographic apostrophes, and decomposed-vs-composed French accented characters via an explicit table (GDScript has no built-in NFC/NFD normalization). Error classification follows the data annotations only (rule_id present -> grammatical, absent -> unclassified), never a runtime linguistic guess. scripts/pedagogy/: DifficultyManager (per-skill difficulty from recent results), AttemptFlow (3-attempt graduated aid: hint, then explanation, then reveal, matching exercise-lifecycle.md's second gap), and ReviewScheduler (the five mastery states from §9, with session-counted spaced review intervals [1, 3, 6, 12] rather than wall-clock dates, since a family device's clock isn't trustworthy). All of it is pure: no scene tree, no clock or RNG read directly, every effectful input (session number, attempt outcome) is a parameter. 65 headless tests across both layers, including the word-omission-doesn't-cascade regression and the full decouverte -> acquise -> a_reviser -> acquise path. Co-Authored-By: Claude Sonnet 5 --- docs/specs/decisions.md | 9 +- scripts/correction/answer_validator.gd | 99 +++++++++ scripts/correction/answer_validator.gd.uid | 1 + scripts/correction/correction_result.gd | 35 +++ scripts/correction/correction_result.gd.uid | 1 + scripts/correction/dictation_analyzer.gd | 128 +++++++++++ scripts/correction/dictation_analyzer.gd.uid | 1 + scripts/correction/text_normalizer.gd | 67 ++++++ scripts/correction/text_normalizer.gd.uid | 1 + scripts/correction/word_aligner.gd | 55 +++++ scripts/correction/word_aligner.gd.uid | 1 + scripts/data/semantic_checks.gd | 15 +- scripts/pedagogy/attempt_flow.gd | 26 +++ scripts/pedagogy/attempt_flow.gd.uid | 1 + scripts/pedagogy/difficulty_manager.gd | 35 +++ scripts/pedagogy/difficulty_manager.gd.uid | 1 + scripts/pedagogy/review_scheduler.gd | 200 ++++++++++++++++++ scripts/pedagogy/review_scheduler.gd.uid | 1 + tests/correction/test_answer_validator.gd | 77 +++++++ tests/correction/test_answer_validator.gd.uid | 1 + tests/correction/test_dictation_analyzer.gd | 67 ++++++ .../correction/test_dictation_analyzer.gd.uid | 1 + tests/correction/test_text_normalizer.gd | 39 ++++ tests/correction/test_text_normalizer.gd.uid | 1 + tests/correction/test_word_aligner.gd | 45 ++++ tests/correction/test_word_aligner.gd.uid | 1 + tests/data/test_schema_validator.gd | 27 +-- tests/data/test_schema_validator.gd.uid | 1 + tests/data/test_semantic_checks.gd | 14 +- tests/data/test_semantic_checks.gd.uid | 1 + tests/pedagogy/test_attempt_flow.gd | 19 ++ tests/pedagogy/test_attempt_flow.gd.uid | 1 + tests/pedagogy/test_difficulty_manager.gd | 32 +++ tests/pedagogy/test_difficulty_manager.gd.uid | 1 + tests/pedagogy/test_review_scheduler.gd | 133 ++++++++++++ tests/pedagogy/test_review_scheduler.gd.uid | 1 + 36 files changed, 1111 insertions(+), 28 deletions(-) create mode 100644 scripts/correction/answer_validator.gd create mode 100644 scripts/correction/answer_validator.gd.uid create mode 100644 scripts/correction/correction_result.gd create mode 100644 scripts/correction/correction_result.gd.uid create mode 100644 scripts/correction/dictation_analyzer.gd create mode 100644 scripts/correction/dictation_analyzer.gd.uid create mode 100644 scripts/correction/text_normalizer.gd create mode 100644 scripts/correction/text_normalizer.gd.uid create mode 100644 scripts/correction/word_aligner.gd create mode 100644 scripts/correction/word_aligner.gd.uid create mode 100644 scripts/pedagogy/attempt_flow.gd create mode 100644 scripts/pedagogy/attempt_flow.gd.uid create mode 100644 scripts/pedagogy/difficulty_manager.gd create mode 100644 scripts/pedagogy/difficulty_manager.gd.uid create mode 100644 scripts/pedagogy/review_scheduler.gd create mode 100644 scripts/pedagogy/review_scheduler.gd.uid create mode 100644 tests/correction/test_answer_validator.gd create mode 100644 tests/correction/test_answer_validator.gd.uid create mode 100644 tests/correction/test_dictation_analyzer.gd create mode 100644 tests/correction/test_dictation_analyzer.gd.uid create mode 100644 tests/correction/test_text_normalizer.gd create mode 100644 tests/correction/test_text_normalizer.gd.uid create mode 100644 tests/correction/test_word_aligner.gd create mode 100644 tests/correction/test_word_aligner.gd.uid create mode 100644 tests/data/test_schema_validator.gd.uid create mode 100644 tests/data/test_semantic_checks.gd.uid create mode 100644 tests/pedagogy/test_attempt_flow.gd create mode 100644 tests/pedagogy/test_attempt_flow.gd.uid create mode 100644 tests/pedagogy/test_difficulty_manager.gd create mode 100644 tests/pedagogy/test_difficulty_manager.gd.uid create mode 100644 tests/pedagogy/test_review_scheduler.gd create mode 100644 tests/pedagogy/test_review_scheduler.gd.uid diff --git a/docs/specs/decisions.md b/docs/specs/decisions.md index f38919d..720d975 100644 --- a/docs/specs/decisions.md +++ b/docs/specs/decisions.md @@ -97,4 +97,11 @@ Ajouts à l'arborescence proposée : - Schéma de dictée : `words` (annotation mot par mot : `rule_id` et `expects_capital` facultatifs) est **obligatoire**, pas facultatif — sans lui, l'erreur reste non classée (cf. « Points durs » du prompt de lancement). Le nombre de mots dans `words` doit correspondre à `target_text` découpé sur les espaces. - Le schéma `save` reste provisoire pour le champ `skills` (`{"type": "object"}`, sans validation des clés dynamiques) : le validateur actuel ne sait pas exprimer un schéma pour des clés arbitraires. À affiner à l'étape « Profils et sauvegardes ». - GUT est pinné en v9.6.0, pas la dernière version (9.7.1 référence le singleton `AccessibilityServer`, absent de Godot 4.6.3 en mode headless). -- `tools/setup.sh` lance `godot --headless --path . --import` en fin d'installation : nécessaire pour que les scripts `class_name` globaux (`SchemaValidator`, `DataLoader`, `SemanticChecks`) soient résolus avant la première exécution de `make test` / `make validate-data`. +- `tools/setup.sh` lance `godot --headless --path . --import` en fin d'installation : nécessaire pour que les scripts `class_name` globaux (`SchemaValidator`, `DataLoader`, `SemanticChecks`) soient résolus avant la première exécution de `make test` / `make validate-data`. Même précaution après l'ajout de tout nouveau script `class_name` (ex. `AnswerValidator`, `DictationAnalyzer`, `ReviewScheduler` à l'étape « Logique pure ») : sans réimport, Godot échoue silencieusement avec « Nonexistent function ... in base 'GDScript' » au lieu de signaler l'erreur de compilation réelle. + +## 12. Étape « Logique pure » : précisions prises en cours d'implémentation + +- GDScript traite l'avertissement « inferred as Variant » (`var x := f()` quand `f()` retourne `Variant`) comme une erreur de compilation en mode script headless. Toujours typer explicitement (`var x: Variant = f()`) quand une fonction peut renvoyer `null`. +- `DictationAnalyzer` aligne les mots en comparant une version en minuscules (alignement insensible à la casse) : sinon une majuscule manquante en début de mot est vue comme une substitution par `WordAligner` et jamais testée comme erreur de capitalisation à part (point 6 des décisions). Les mots originaux (avec leur casse) restent utilisés pour construire les erreurs et pour la vérification de majuscule. +- `ReviewScheduler.record_attempt` est une fonction pure qui duplique l'état (`Dictionary.duplicate(true)`) plutôt que de le modifier en place ; `ProgressManager` (étape « Profils et sauvegardes ») sera responsable de stocker l'état retourné. +- Le planning de révision est entièrement piloté par le numéro de séance (`current_session`), jamais par une horloge : paliers `[1, 3, 6, 12]` séances après la dernière réussite à un palier donné, comme décidé au point 5. Une compétence « acquise » dont le délai est dépassé sans nouvelle tentative passe à « à réviser » via `ReviewScheduler.mark_overdue_as_review`, à appeler par `ProgressManager` en début de séance. diff --git a/scripts/correction/answer_validator.gd b/scripts/correction/answer_validator.gd new file mode 100644 index 0000000..1fe591d --- /dev/null +++ b/scripts/correction/answer_validator.gd @@ -0,0 +1,99 @@ +class_name AnswerValidator +extends RefCounted +## Valide une reponse de choix multiple ou de correction de phrase et produit +## la structure de correction du §6 (voir CorrectionResult). Code pur : aucune +## dependance a l'arbre de scenes, aucune horloge, aucun hasard. + + +static func validate_multiple_choice( + exercise: Dictionary, selected_answer: int +) -> CorrectionResult: + var correct_answer: int = exercise["correct_answer"] + if selected_answer == correct_answer: + return CorrectionResult.correct(exercise["explanation"]) + + var answers: Array = exercise["answers"] + var found := "" + if selected_answer >= 0 and selected_answer < answers.size(): + found = answers[selected_answer] + var expected: String = answers[correct_answer] + + var error := { + "position": 0, + "error_type": "grammatical", + "rule_id": exercise["rule_id"], + "found": found, + "expected": expected, + } + return CorrectionResult.incorrect( + [error], exercise["explanation"], exercise["hint"], [expected] + ) + + +## selected_indices : index des tokens que l'enfant a touches comme fautifs. +## corrections : correction saisie pour chaque token touche (cle = index du +## token, valeur = texte saisi). +static func validate_sentence_correction( + exercise: Dictionary, selected_indices: Array[int], corrections: Dictionary +) -> CorrectionResult: + var tokens: Array = exercise["tokens"] + var errors: Array[Dictionary] = [] + + for i in tokens.size(): + var token: Dictionary = tokens[i] + var is_faulty: bool = token.get("correct", true) == false + var was_selected: bool = selected_indices.has(i) + + if is_faulty and not was_selected: + errors.append(_missed_error(i, token, exercise)) + elif is_faulty and was_selected: + var submitted: String = corrections.get(i, "") + if submitted != token["expected"]: + errors.append(_wrong_correction_error(i, submitted, token, exercise)) + elif not is_faulty and was_selected: + errors.append(_false_positive_error(i, token, exercise)) + + if errors.is_empty(): + return CorrectionResult.correct(exercise["explanation"]) + + var remediation: Array[String] = [] + for token: Dictionary in tokens: + if token.get("correct", true) == false: + remediation.append(token["expected"]) + return CorrectionResult.incorrect( + errors, exercise["explanation"], exercise["hint"], remediation + ) + + +static func _missed_error(index: int, token: Dictionary, exercise: Dictionary) -> Dictionary: + return { + "position": index, + "error_type": "grammatical", + "rule_id": token.get("rule_id", exercise["rule_id"]), + "found": token["text"], + "expected": token["expected"], + } + + +static func _wrong_correction_error( + index: int, submitted: String, token: Dictionary, exercise: Dictionary +) -> Dictionary: + return { + "position": index, + "error_type": "grammatical", + "rule_id": token.get("rule_id", exercise["rule_id"]), + "found": submitted, + "expected": token["expected"], + } + + +static func _false_positive_error( + index: int, token: Dictionary, exercise: Dictionary +) -> Dictionary: + return { + "position": index, + "error_type": "unclassified", + "rule_id": exercise["rule_id"], + "found": token["text"], + "expected": token["text"], + } diff --git a/scripts/correction/answer_validator.gd.uid b/scripts/correction/answer_validator.gd.uid new file mode 100644 index 0000000..f1e48c0 --- /dev/null +++ b/scripts/correction/answer_validator.gd.uid @@ -0,0 +1 @@ +uid://cxrvun2qowvp8 diff --git a/scripts/correction/correction_result.gd b/scripts/correction/correction_result.gd new file mode 100644 index 0000000..aa9d6d2 --- /dev/null +++ b/scripts/correction/correction_result.gd @@ -0,0 +1,35 @@ +class_name CorrectionResult +extends RefCounted +## Structure de correction retournee par answer_validator et dictation_analyzer +## (cahier des charges §6, docs/specs/decisions.md point 4). Chaque entree de +## `errors` : {"position": int, "error_type": String ("lexical" | "grammatical" | +## "unclassified" | "capitalization"), "rule_id": String, "found": String, +## "expected": String}. + +var is_correct: bool +var errors: Array[Dictionary] +var explanation: String +var hint: String +var remediation: Array[String] + + +static func correct(explanation: String) -> CorrectionResult: + var result := CorrectionResult.new() + result.is_correct = true + result.errors = [] + result.explanation = explanation + result.hint = "" + result.remediation = [] + return result + + +static func incorrect( + errors: Array[Dictionary], explanation: String, hint: String, remediation: Array[String] +) -> CorrectionResult: + var result := CorrectionResult.new() + result.is_correct = false + result.errors = errors + result.explanation = explanation + result.hint = hint + result.remediation = remediation + return result diff --git a/scripts/correction/correction_result.gd.uid b/scripts/correction/correction_result.gd.uid new file mode 100644 index 0000000..44a22bf --- /dev/null +++ b/scripts/correction/correction_result.gd.uid @@ -0,0 +1 @@ +uid://38ngt760408y diff --git a/scripts/correction/dictation_analyzer.gd b/scripts/correction/dictation_analyzer.gd new file mode 100644 index 0000000..22ca511 --- /dev/null +++ b/scripts/correction/dictation_analyzer.gd @@ -0,0 +1,128 @@ +class_name DictationAnalyzer +extends RefCounted +## Analyse la production ecrite d'un enfant pour une dictee : alignement mot a +## mot (WordAligner) avant comparaison, normalisation (TextNormalizer), puis +## classification de chaque erreur via les annotations de la donnee cible +## (dictation["words"]). Sans annotation (pas de rule_id), l'erreur reste non +## classee (voir "Points durs" du prompt de lancement). Code pur, sans horloge +## ni hasard. L'explication complete (texte de la regle) est composee par la +## couche d'affichage a partir des rule_id retournes, pas ici. + + +static func analyze(dictation: Dictionary, submitted_text: String) -> CorrectionResult: + var normalized_submitted := TextNormalizer.normalize(submitted_text) + var normalized_target := TextNormalizer.normalize(dictation["target_text"]) + + if _matches_target_or_variant(dictation, normalized_submitted, normalized_target): + return CorrectionResult.correct(_build_explanation(0)) + + var target_words := TextNormalizer.split_words(normalized_target) + var submitted_words := TextNormalizer.split_words(normalized_submitted) + var words_meta: Array = dictation["words"] + + # L'alignement se fait insensible a la casse : une majuscule manquante est + # une erreur de capitalisation a part, pas un mot substitue (voir + # docs/specs/decisions.md point 6). + var target_words_for_align := _to_lower_all(target_words) + var submitted_words_for_align := _to_lower_all(submitted_words) + var ops := WordAligner.align(target_words_for_align, submitted_words_for_align) + var errors: Array[Dictionary] = [] + + for op: Dictionary in ops: + match op["op"]: + "match": + var capital_error: Variant = _check_capitalization( + words_meta, op["target_index"], submitted_words[op["submitted_index"]] + ) + if capital_error != null: + errors.append(capital_error) + "substitute": + ( + errors + . append( + _classify_error( + words_meta, + op["target_index"], + submitted_words[op["submitted_index"]], + ) + ) + ) + "delete": + errors.append(_classify_error(words_meta, op["target_index"], "")) + "insert": + ( + errors + . append( + { + "position": target_words.size(), + "error_type": "unclassified", + "rule_id": "", + "found": submitted_words[op["submitted_index"]], + "expected": "", + } + ) + ) + + if errors.is_empty(): + return CorrectionResult.correct(_build_explanation(0)) + + return CorrectionResult.incorrect( + errors, _build_explanation(errors.size()), "", [dictation["target_text"]] + ) + + +static func _matches_target_or_variant( + dictation: Dictionary, normalized_submitted: String, normalized_target: String +) -> bool: + if normalized_submitted == normalized_target: + return true + for variant: String in dictation.get("accepted_variants", []): + if normalized_submitted == TextNormalizer.normalize(variant): + return true + return false + + +static func _classify_error(words_meta: Array, target_index: int, found: String) -> Dictionary: + var meta: Dictionary = words_meta[target_index] if target_index < words_meta.size() else {} + var expected: String = meta.get("text", "") + var rule_id: String = meta.get("rule_id", "") + return { + "position": target_index, + "error_type": "grammatical" if not rule_id.is_empty() else "unclassified", + "rule_id": rule_id, + "found": found, + "expected": expected, + } + + +static func _check_capitalization( + words_meta: Array, target_index: int, submitted_word: String +) -> Variant: + if target_index >= words_meta.size() or submitted_word.is_empty(): + return null + var meta: Dictionary = words_meta[target_index] + if not meta.get("expects_capital", false): + return null + var first_letter := submitted_word.substr(0, 1) + if first_letter == first_letter.to_upper(): + return null + return { + "position": target_index, + "error_type": "capitalization", + "rule_id": meta.get("rule_id", ""), + "found": submitted_word, + "expected": meta.get("text", submitted_word), + } + + +static func _to_lower_all(words: Array[String]) -> Array[String]: + var result: Array[String] = [] + for word in words: + result.append(word.to_lower()) + return result + + +static func _build_explanation(error_count: int) -> String: + if error_count == 0: + return "Dictee correcte." + return "Dictee corrigee : %d erreur(s) a revoir." % error_count diff --git a/scripts/correction/dictation_analyzer.gd.uid b/scripts/correction/dictation_analyzer.gd.uid new file mode 100644 index 0000000..cc65cc3 --- /dev/null +++ b/scripts/correction/dictation_analyzer.gd.uid @@ -0,0 +1 @@ +uid://cj3x15p8r3rmj diff --git a/scripts/correction/text_normalizer.gd b/scripts/correction/text_normalizer.gd new file mode 100644 index 0000000..6a97487 --- /dev/null +++ b/scripts/correction/text_normalizer.gd @@ -0,0 +1,67 @@ +class_name TextNormalizer +extends RefCounted +## Normalisation de texte avant comparaison dans les dictees : espaces (dont +## insecables), apostrophes typographiques, et sequences Unicode decomposees +## des caracteres francais ramenees a leur forme composee. GDScript n'expose +## pas de normalisation NFC/NFD native : table explicite ici, comme prevu par +## les "Points durs" du prompt de lancement. + +const NBSP := " " +const NARROW_NBSP := " " +const TYPOGRAPHIC_APOSTROPHE := "’" + +## Sequences decomposees (lettre de base + marque combinante) -> caractere +## compose. Couvre les caracteres francais courants : accents, cedille, trema. +const DECOMPOSED_TO_COMPOSED := { + "é": "é", + "è": "è", + "ê": "ê", + "ë": "ë", + "É": "É", + "È": "È", + "Ê": "Ê", + "Ë": "Ë", + "à": "à", + "â": "â", + "À": "À", + "Â": "Â", + "ù": "ù", + "û": "û", + "ü": "ü", + "Ù": "Ù", + "Û": "Û", + "Ü": "Ü", + "î": "î", + "ï": "ï", + "Î": "Î", + "Ï": "Ï", + "ô": "ô", + "ö": "ö", + "Ô": "Ô", + "Ö": "Ö", + "ç": "ç", + "Ç": "Ç", +} + + +static func normalize(text: String) -> String: + var result := text + result = result.replace(NBSP, " ") + result = result.replace(NARROW_NBSP, " ") + result = result.replace(TYPOGRAPHIC_APOSTROPHE, "'") + for decomposed: String in DECOMPOSED_TO_COMPOSED: + result = result.replace(decomposed, DECOMPOSED_TO_COMPOSED[decomposed]) + while result.find(" ") != -1: + result = result.replace(" ", " ") + return result.strip_edges() + + +static func split_words(text: String) -> Array[String]: + var normalized := normalize(text) + var words: Array[String] = [] + if normalized.is_empty(): + return words + var parts: PackedStringArray = normalized.split(" ", false) + for part in parts: + words.append(part) + return words diff --git a/scripts/correction/text_normalizer.gd.uid b/scripts/correction/text_normalizer.gd.uid new file mode 100644 index 0000000..3ff6628 --- /dev/null +++ b/scripts/correction/text_normalizer.gd.uid @@ -0,0 +1 @@ +uid://07glvxpdv5ml diff --git a/scripts/correction/word_aligner.gd b/scripts/correction/word_aligner.gd new file mode 100644 index 0000000..f4625c5 --- /dev/null +++ b/scripts/correction/word_aligner.gd @@ -0,0 +1,55 @@ +class_name WordAligner +extends RefCounted +## Alignement mot a mot entre le texte cible et la production de l'enfant +## (distance d'edition, algorithme de Wagner-Fischer), avant toute comparaison +## caractere par caractere : sans cela, un mot omis ou ajoute decale tous les +## mots suivants et les transforme en erreurs (voir "Points durs" du prompt de +## lancement). + + +## Chaque operation : {"op": "match" | "substitute" | "delete" | "insert", +## "target_index": int (-1 si insert), "submitted_index": int (-1 si delete)}. +## "delete" = mot du texte cible absent de la production ; "insert" = mot +## ajoute par l'enfant, absent du texte cible. +static func align(target_words: Array[String], submitted_words: Array[String]) -> Array[Dictionary]: + var n := target_words.size() + var m := submitted_words.size() + + var cost: Array = [] + for i in n + 1: + var row: Array[int] = [] + for _j in m + 1: + row.append(0) + cost.append(row) + for i in n + 1: + cost[i][0] = i + for j in m + 1: + cost[0][j] = j + + for i in range(1, n + 1): + for j in range(1, m + 1): + if target_words[i - 1] == submitted_words[j - 1]: + cost[i][j] = cost[i - 1][j - 1] + else: + cost[i][j] = 1 + mini(mini(cost[i - 1][j], cost[i][j - 1]), cost[i - 1][j - 1]) + + var ops: Array[Dictionary] = [] + var i := n + var j := m + while i > 0 or j > 0: + if i > 0 and j > 0 and target_words[i - 1] == submitted_words[j - 1]: + ops.append({"op": "match", "target_index": i - 1, "submitted_index": j - 1}) + i -= 1 + j -= 1 + elif i > 0 and j > 0 and cost[i][j] == cost[i - 1][j - 1] + 1: + ops.append({"op": "substitute", "target_index": i - 1, "submitted_index": j - 1}) + i -= 1 + j -= 1 + elif i > 0 and cost[i][j] == cost[i - 1][j] + 1: + ops.append({"op": "delete", "target_index": i - 1, "submitted_index": -1}) + i -= 1 + else: + ops.append({"op": "insert", "target_index": -1, "submitted_index": j - 1}) + j -= 1 + ops.reverse() + return ops diff --git a/scripts/correction/word_aligner.gd.uid b/scripts/correction/word_aligner.gd.uid new file mode 100644 index 0000000..458c45b --- /dev/null +++ b/scripts/correction/word_aligner.gd.uid @@ -0,0 +1 @@ +uid://dmrmm4pljh4j1 diff --git a/scripts/data/semantic_checks.gd b/scripts/data/semantic_checks.gd index 277ff50..45aa136 100644 --- a/scripts/data/semantic_checks.gd +++ b/scripts/data/semantic_checks.gd @@ -12,8 +12,10 @@ static func check_multiple_choice(data: Dictionary, path: String) -> Array[Strin var correct_answer: int = data.get("correct_answer", -1) if correct_answer < 0 or correct_answer >= answers.size(): errors.append( - "%s : correct_answer (%d) hors des bornes de answers (%d element(s))" - % [path, correct_answer, answers.size()] + ( + "%s : correct_answer (%d) hors des bornes de answers (%d element(s))" + % [path, correct_answer, answers.size()] + ) ) return errors @@ -28,8 +30,7 @@ static func check_sentence_correction(data: Dictionary, path: String) -> Array[S has_error_token = true if not token.has("expected"): errors.append( - "%s.tokens[%d] : token fautif sans correction attendue ('expected')" - % [path, i] + "%s.tokens[%d] : token fautif sans correction attendue ('expected')" % [path, i] ) if not has_error_token: errors.append("%s : aucun token fautif, rien a corriger" % path) @@ -43,7 +44,9 @@ static func check_dictation(data: Dictionary, path: String) -> Array[String]: var expected_word_count := target_text.split(" ", false).size() if words.size() != expected_word_count: errors.append( - "%s : %d mot(s) annote(s) pour %d mot(s) dans target_text" - % [path, words.size(), expected_word_count] + ( + "%s : %d mot(s) annote(s) pour %d mot(s) dans target_text" + % [path, words.size(), expected_word_count] + ) ) return errors diff --git a/scripts/pedagogy/attempt_flow.gd b/scripts/pedagogy/attempt_flow.gd new file mode 100644 index 0000000..cdd5803 --- /dev/null +++ b/scripts/pedagogy/attempt_flow.gd @@ -0,0 +1,26 @@ +class_name AttemptFlow +extends RefCounted +## Aide graduee sur les tentatives successives d'un meme exercice, tant que la +## reponse est fausse (docs/specs/decisions.md point 7 ; exercise-lifecycle.md, +## ecart 2). Code pur. + +enum SupportLevel { HINT, EXPLANATION, REVEAL } + +const MAX_ATTEMPTS := 3 + + +## attempt_number : numero de la tentative fautive en cours (1 pour la +## premiere erreur sur cet exercice, 2 pour la deuxieme, etc.). +static func support_level_for_attempt(attempt_number: int) -> SupportLevel: + if attempt_number <= 1: + return SupportLevel.HINT + if attempt_number < MAX_ATTEMPTS: + return SupportLevel.EXPLANATION + return SupportLevel.REVEAL + + +## Vrai quand la tentative fautive courante doit mettre fin a l'exercice (la +## reponse corrigee est alors montree, sans sanction, et la competence est +## marquee pour une revision avec d'autres exemples). +static func should_end_exercise(attempt_number: int) -> bool: + return attempt_number >= MAX_ATTEMPTS diff --git a/scripts/pedagogy/attempt_flow.gd.uid b/scripts/pedagogy/attempt_flow.gd.uid new file mode 100644 index 0000000..114185c --- /dev/null +++ b/scripts/pedagogy/attempt_flow.gd.uid @@ -0,0 +1 @@ +uid://dmkh8crqa1shs diff --git a/scripts/pedagogy/difficulty_manager.gd b/scripts/pedagogy/difficulty_manager.gd new file mode 100644 index 0000000..8fb356a --- /dev/null +++ b/scripts/pedagogy/difficulty_manager.gd @@ -0,0 +1,35 @@ +class_name DifficultyManager +extends RefCounted +## Suggere le niveau de difficulte (1 a 3) du prochain exercice pour une +## competence, a partir de l'historique recent de reussites. Code pur : ne lit +## ni horloge ni hasard, ne modifie aucun etat (ProgressManager est responsable +## du stockage). + +const MIN_DIFFICULTY := 1 +const MAX_DIFFICULTY := 3 +const WINDOW := 3 + + +## recent_results : resultats des tentatives les plus recentes, la derniere en +## dernier. Monte d'un niveau apres WINDOW reussites consecutives ; descend +## d'un niveau apres WINDOW echecs consecutifs ; ne bouge pas sinon. Jamais en +## dehors de [MIN_DIFFICULTY, MAX_DIFFICULTY] : la difficulte evolue sans +## jamais bloquer durablement l'enfant (cahier des charges §2). +static func next_difficulty(current_difficulty: int, recent_results: Array[bool]) -> int: + if recent_results.size() < WINDOW: + return clampi(current_difficulty, MIN_DIFFICULTY, MAX_DIFFICULTY) + + var last_window: Array[bool] = recent_results.slice(recent_results.size() - WINDOW) + var all_success := true + var all_failure := true + for result in last_window: + if result: + all_failure = false + else: + all_success = false + + if all_success: + return clampi(current_difficulty + 1, MIN_DIFFICULTY, MAX_DIFFICULTY) + if all_failure: + return clampi(current_difficulty - 1, MIN_DIFFICULTY, MAX_DIFFICULTY) + return clampi(current_difficulty, MIN_DIFFICULTY, MAX_DIFFICULTY) diff --git a/scripts/pedagogy/difficulty_manager.gd.uid b/scripts/pedagogy/difficulty_manager.gd.uid new file mode 100644 index 0000000..5400f2d --- /dev/null +++ b/scripts/pedagogy/difficulty_manager.gd.uid @@ -0,0 +1 @@ +uid://dkdkwuxn8iw diff --git a/scripts/pedagogy/review_scheduler.gd b/scripts/pedagogy/review_scheduler.gd new file mode 100644 index 0000000..748f068 --- /dev/null +++ b/scripts/pedagogy/review_scheduler.gd @@ -0,0 +1,200 @@ +class_name ReviewScheduler +extends RefCounted +## Transitions de maitrise (cahier des charges §9) et planification des +## revisions. Code pur : l'horloge n'intervient jamais ; le numero de seance +## est injecte par l'appelant (ProgressManager), jamais lu directement (voir +## l'invariant d'architecture dans CLAUDE.md). Seuils et paliers detailles dans +## docs/specs/decisions.md, point 5. + +const RECENT_WINDOW_SMALL := 5 +const RECENT_WINDOW_LARGE := 8 +const MIN_SUCCESS_RATE_CONSOLIDATION := 0.6 +const MIN_SUCCESS_RATE_ACQUISE := 0.85 +const MIN_SUCCESSES_WITHOUT_HINT_CONSOLIDATION := 2 +const MIN_HINTLESS_RECENT_SUCCESSES_ACQUISE := 4 +const MIN_DISTINCT_SESSIONS_ACQUISE := 3 +const MIN_DISTINCT_FORMATS_ACQUISE := 2 +const REVIEW_INTERVALS_SESSIONS: Array[int] = [1, 3, 6, 12] + +const STATUS_DECOUVERTE := "decouverte" +const STATUS_EN_ACQUISITION := "en_acquisition" +const STATUS_EN_CONSOLIDATION := "en_consolidation" +const STATUS_ACQUISE := "acquise" +const STATUS_A_REVISER := "a_reviser" + + +static func initial_state() -> Dictionary: + return { + "status": STATUS_DECOUVERTE, + "recent_results": [] as Array[bool], + "recent_hint_used": [] as Array[bool], + "sessions_succeeded": [] as Array[int], + "formats_succeeded": [] as Array[String], + "last_session_practiced": -1, + "review_interval_index": -1, + "next_review_session": -1, + } + + +## attempt : {"success": bool, "hint_used": bool, "exercise_type": String}. +## Retourne un nouvel etat ; ne modifie jamais `state` en place. +static func record_attempt( + state: Dictionary, attempt: Dictionary, current_session: int +) -> Dictionary: + var previous_status: String = state["status"] + var new_state: Dictionary = state.duplicate(true) + var success: bool = attempt["success"] + var hint_used: bool = attempt["hint_used"] + var exercise_type: String = attempt["exercise_type"] + + _push_bounded(new_state["recent_results"], success, RECENT_WINDOW_LARGE) + _push_bounded(new_state["recent_hint_used"], hint_used, RECENT_WINDOW_LARGE) + new_state["last_session_practiced"] = current_session + + if success: + if not new_state["sessions_succeeded"].has(current_session): + new_state["sessions_succeeded"].append(current_session) + if not new_state["formats_succeeded"].has(exercise_type): + new_state["formats_succeeded"].append(exercise_type) + + var was_due: bool = is_due_for_review(state, current_session) + new_state["status"] = _next_status(new_state, success) + _update_review_schedule(new_state, previous_status, success, was_due, current_session) + + return new_state + + +static func is_due_for_review(state: Dictionary, current_session: int) -> bool: + var next_review: int = state.get("next_review_session", -1) + return next_review != -1 and current_session >= next_review + + +## A appeler au debut d'une seance pour chaque competence "acquise" avant toute +## nouvelle tentative : un delai de revision atteint sans pratique bascule la +## competence en "a_reviser" (cahier des charges §9, delai de revision). +static func mark_overdue_as_review(state: Dictionary, current_session: int) -> Dictionary: + if state["status"] == STATUS_ACQUISE and is_due_for_review(state, current_session): + var new_state: Dictionary = state.duplicate(true) + new_state["status"] = STATUS_A_REVISER + new_state["review_interval_index"] = -1 + new_state["next_review_session"] = -1 + return new_state + return state + + +static func _update_review_schedule( + new_state: Dictionary, + previous_status: String, + success: bool, + was_due: bool, + current_session: int, +) -> void: + var status: String = new_state["status"] + + if status == STATUS_A_REVISER: + new_state["review_interval_index"] = -1 + new_state["next_review_session"] = -1 + return + + if status != STATUS_ACQUISE: + return + + if previous_status != STATUS_ACQUISE: + # Premiere arrivee en "acquise" (depuis en_consolidation ou a_reviser). + new_state["review_interval_index"] = 0 + new_state["next_review_session"] = current_session + REVIEW_INTERVALS_SESSIONS[0] + return + + if success and was_due: + var next_index: int = mini( + int(new_state["review_interval_index"]) + 1, REVIEW_INTERVALS_SESSIONS.size() - 1 + ) + new_state["review_interval_index"] = next_index + new_state["next_review_session"] = current_session + REVIEW_INTERVALS_SESSIONS[next_index] + + +static func _next_status(state: Dictionary, last_success: bool) -> String: + var current_status: String = state["status"] + + if current_status == STATUS_ACQUISE or current_status == STATUS_A_REVISER: + return STATUS_ACQUISE if last_success else STATUS_A_REVISER + + if not last_success: + return current_status + + if current_status == STATUS_DECOUVERTE: + return STATUS_EN_ACQUISITION + + if current_status == STATUS_EN_ACQUISITION: + return STATUS_EN_CONSOLIDATION if _is_ready_for_consolidation(state) else current_status + + if current_status == STATUS_EN_CONSOLIDATION: + return STATUS_ACQUISE if _is_ready_for_acquise(state) else current_status + + return current_status + + +static func _is_ready_for_consolidation(state: Dictionary) -> bool: + var recent: Array = _last_n(state["recent_results"], RECENT_WINDOW_SMALL) + var hints: Array = _last_n(state["recent_hint_used"], RECENT_WINDOW_SMALL) + if recent.is_empty(): + return false + + var successes_without_hint := 0 + var success_count := 0 + for i in recent.size(): + if recent[i]: + success_count += 1 + if not hints[i]: + successes_without_hint += 1 + + var success_rate := float(success_count) / float(recent.size()) + return ( + successes_without_hint >= MIN_SUCCESSES_WITHOUT_HINT_CONSOLIDATION + and success_rate >= MIN_SUCCESS_RATE_CONSOLIDATION + ) + + +static func _is_ready_for_acquise(state: Dictionary) -> bool: + var recent: Array = _last_n(state["recent_results"], RECENT_WINDOW_LARGE) + var hints: Array = _last_n(state["recent_hint_used"], RECENT_WINDOW_LARGE) + if recent.size() < RECENT_WINDOW_LARGE: + return false + + var success_count := 0 + for result in recent: + if result: + success_count += 1 + var success_rate := float(success_count) / float(recent.size()) + if success_rate < MIN_SUCCESS_RATE_ACQUISE: + return false + + var hintless_recent_successes := 0 + var i := recent.size() - 1 + while i >= 0 and hintless_recent_successes < MIN_HINTLESS_RECENT_SUCCESSES_ACQUISE: + if recent[i]: + if hints[i]: + return false + hintless_recent_successes += 1 + i -= 1 + if hintless_recent_successes < MIN_HINTLESS_RECENT_SUCCESSES_ACQUISE: + return false + + if state["sessions_succeeded"].size() < MIN_DISTINCT_SESSIONS_ACQUISE: + return false + if state["formats_succeeded"].size() < MIN_DISTINCT_FORMATS_ACQUISE: + return false + + return true + + +static func _push_bounded(array: Array, value: Variant, max_size: int) -> void: + array.append(value) + while array.size() > max_size: + array.remove_at(0) + + +static func _last_n(array: Array, n: int) -> Array: + if array.size() <= n: + return array.duplicate() + return array.slice(array.size() - n) diff --git a/scripts/pedagogy/review_scheduler.gd.uid b/scripts/pedagogy/review_scheduler.gd.uid new file mode 100644 index 0000000..9994836 --- /dev/null +++ b/scripts/pedagogy/review_scheduler.gd.uid @@ -0,0 +1 @@ +uid://cvg4qps443hwe diff --git a/tests/correction/test_answer_validator.gd b/tests/correction/test_answer_validator.gd new file mode 100644 index 0000000..39f5452 --- /dev/null +++ b/tests/correction/test_answer_validator.gd @@ -0,0 +1,77 @@ +extends GutTest +## Tests de AnswerValidator (choix multiple et correction de phrase). + +var multiple_choice_exercise: Dictionary = { + "rule_id": "regle_test", + "answers": ["petit", "petits", "petite"], + "correct_answer": 1, + "hint": "indice", + "explanation": "explication", +} + +var sentence_correction_exercise: Dictionary = { + "rule_id": "regle_test", + "hint": "indice", + "explanation": "explication", + "tokens": + [ + {"text": "Les", "correct": true}, + { + "text": "petit", + "correct": false, + "expected": "petits", + "rule_id": "regle_accord_adjectif", + }, + {"text": "chiens", "correct": true}, + ], +} + + +func test_multiple_choice_correct_answer() -> void: + var result := AnswerValidator.validate_multiple_choice(multiple_choice_exercise, 1) + assert_true(result.is_correct) + assert_eq(result.errors, []) + + +func test_multiple_choice_wrong_answer_reports_found_and_expected() -> void: + var result := AnswerValidator.validate_multiple_choice(multiple_choice_exercise, 0) + assert_false(result.is_correct) + assert_eq(result.errors.size(), 1) + assert_eq(result.errors[0]["found"], "petit") + assert_eq(result.errors[0]["expected"], "petits") + assert_eq(result.errors[0]["rule_id"], "regle_test") + + +func test_sentence_correction_fully_correct() -> void: + var result := AnswerValidator.validate_sentence_correction( + sentence_correction_exercise, [1], {1: "petits"} + ) + assert_true(result.is_correct) + + +func test_sentence_correction_missed_faulty_token() -> void: + var result := AnswerValidator.validate_sentence_correction(sentence_correction_exercise, [], {}) + assert_false(result.is_correct) + assert_eq(result.errors.size(), 1) + assert_eq(result.errors[0]["rule_id"], "regle_accord_adjectif") + assert_eq(result.errors[0]["found"], "petit") + assert_eq(result.errors[0]["expected"], "petits") + + +func test_sentence_correction_wrong_correction_text() -> void: + var result := AnswerValidator.validate_sentence_correction( + sentence_correction_exercise, [1], {1: "petite"} + ) + assert_false(result.is_correct) + assert_eq(result.errors[0]["found"], "petite") + assert_eq(result.errors[0]["expected"], "petits") + + +func test_sentence_correction_false_positive_on_correct_token() -> void: + var result := AnswerValidator.validate_sentence_correction( + sentence_correction_exercise, [1, 2], {1: "petits", 2: "chien"} + ) + assert_false(result.is_correct) + assert_eq(result.errors.size(), 1) + assert_eq(result.errors[0]["error_type"], "unclassified") + assert_eq(result.errors[0]["position"], 2) diff --git a/tests/correction/test_answer_validator.gd.uid b/tests/correction/test_answer_validator.gd.uid new file mode 100644 index 0000000..b1660fb --- /dev/null +++ b/tests/correction/test_answer_validator.gd.uid @@ -0,0 +1 @@ +uid://ctn0svsnq535v diff --git a/tests/correction/test_dictation_analyzer.gd b/tests/correction/test_dictation_analyzer.gd new file mode 100644 index 0000000..e2d5ac5 --- /dev/null +++ b/tests/correction/test_dictation_analyzer.gd @@ -0,0 +1,67 @@ +extends GutTest +## Tests de DictationAnalyzer : alignement, classification lexicale/grammaticale +## via annotation, majuscule, variantes acceptees. + +var dictation: Dictionary = { + "target_text": "Les petits chats dorment.", + "words": + [ + {"text": "Les", "expects_capital": true}, + {"text": "petits", "rule_id": "regle_accord_adjectif"}, + {"text": "chats"}, + {"text": "dorment."}, + ], + "accepted_variants": [], +} + + +func test_exact_match_is_correct() -> void: + var result := DictationAnalyzer.analyze(dictation, "Les petits chats dorment.") + assert_true(result.is_correct) + assert_eq(result.errors, []) + + +func test_annotated_word_error_is_classified_as_grammatical() -> void: + var result := DictationAnalyzer.analyze(dictation, "Les petit chats dorment.") + assert_false(result.is_correct) + assert_eq(result.errors.size(), 1) + assert_eq(result.errors[0]["error_type"], "grammatical") + assert_eq(result.errors[0]["rule_id"], "regle_accord_adjectif") + assert_eq(result.errors[0]["found"], "petit") + assert_eq(result.errors[0]["expected"], "petits") + + +func test_unannotated_word_error_is_unclassified() -> void: + var result := DictationAnalyzer.analyze(dictation, "Les petits chat dorment.") + assert_false(result.is_correct) + assert_eq(result.errors.size(), 1) + assert_eq(result.errors[0]["error_type"], "unclassified") + assert_eq(result.errors[0]["rule_id"], "") + + +func test_missing_word_does_not_cascade_into_further_errors() -> void: + # Le mot "petits" est omis : sans alignement, cela provoquerait deux + # erreurs en cascade sur "chats" et "dorment.". + var result := DictationAnalyzer.analyze(dictation, "Les chats dorment.") + assert_false(result.is_correct) + assert_eq(result.errors.size(), 1) + assert_eq(result.errors[0]["rule_id"], "regle_accord_adjectif") + + +func test_missing_capital_is_reported_separately() -> void: + var result := DictationAnalyzer.analyze(dictation, "les petits chats dorment.") + assert_false(result.is_correct) + assert_eq(result.errors.size(), 1) + assert_eq(result.errors[0]["error_type"], "capitalization") + + +func test_accepted_variant_is_treated_as_correct() -> void: + var dictation_with_variant: Dictionary = dictation.duplicate(true) + dictation_with_variant["accepted_variants"] = ["Les petits chats dorment"] + var result := DictationAnalyzer.analyze(dictation_with_variant, "Les petits chats dorment") + assert_true(result.is_correct) + + +func test_normalizes_before_comparing() -> void: + var result := DictationAnalyzer.analyze(dictation, "Les petits chats dorment.") + assert_true(result.is_correct) diff --git a/tests/correction/test_dictation_analyzer.gd.uid b/tests/correction/test_dictation_analyzer.gd.uid new file mode 100644 index 0000000..0a0fc21 --- /dev/null +++ b/tests/correction/test_dictation_analyzer.gd.uid @@ -0,0 +1 @@ +uid://ta26vku8mxa diff --git a/tests/correction/test_text_normalizer.gd b/tests/correction/test_text_normalizer.gd new file mode 100644 index 0000000..18efe15 --- /dev/null +++ b/tests/correction/test_text_normalizer.gd @@ -0,0 +1,39 @@ +extends GutTest +## Tests de TextNormalizer : espaces, apostrophes, caracteres francais decomposes. + + +func test_normalizes_non_breaking_spaces() -> void: + var text := "Les petits chats" + assert_eq(TextNormalizer.normalize(text), "Les petits chats") + + +func test_normalizes_typographic_apostrophe() -> void: + assert_eq(TextNormalizer.normalize("l’école"), "l'école") + + +func test_collapses_multiple_spaces() -> void: + assert_eq(TextNormalizer.normalize("Les petits chats"), "Les petits chats") + + +func test_recomposes_decomposed_accented_characters() -> void: + # "e" + accent aigu combinant (U+0301) doit devenir "é" precompose. + var decomposed := "école" + assert_eq(TextNormalizer.normalize(decomposed), "école") + + +func test_recomposes_cedille() -> void: + var decomposed := "français" + assert_eq(TextNormalizer.normalize(decomposed), "français") + + +func test_strips_leading_and_trailing_whitespace() -> void: + assert_eq(TextNormalizer.normalize(" bonjour "), "bonjour") + + +func test_split_words_splits_on_single_spaces() -> void: + var words := TextNormalizer.split_words("Les petits chats dorment.") + assert_eq(words, ["Les", "petits", "chats", "dorment."]) + + +func test_split_words_on_empty_text_returns_empty_array() -> void: + assert_eq(TextNormalizer.split_words(" "), []) diff --git a/tests/correction/test_text_normalizer.gd.uid b/tests/correction/test_text_normalizer.gd.uid new file mode 100644 index 0000000..d51cc6c --- /dev/null +++ b/tests/correction/test_text_normalizer.gd.uid @@ -0,0 +1 @@ +uid://dqrgabx44in1k diff --git a/tests/correction/test_word_aligner.gd b/tests/correction/test_word_aligner.gd new file mode 100644 index 0000000..bd84d29 --- /dev/null +++ b/tests/correction/test_word_aligner.gd @@ -0,0 +1,45 @@ +extends GutTest +## Tests de WordAligner : l'alignement doit absorber les mots omis ou ajoutes +## sans decaler les comparaisons suivantes. + +var target: Array[String] = ["Les", "petits", "chats", "dorment."] + + +func test_identical_sequences_are_all_matches() -> void: + var ops := WordAligner.align(target, target.duplicate()) + for op in ops: + assert_eq(op["op"], "match") + assert_eq(ops.size(), 4) + + +func test_single_substitution_is_detected_at_the_right_position() -> void: + var submitted: Array[String] = ["Les", "petit", "chats", "dorment."] + var ops := WordAligner.align(target, submitted) + assert_eq(ops.size(), 4) + assert_eq(ops[1]["op"], "substitute") + assert_eq(ops[1]["target_index"], 1) + assert_eq(ops[0]["op"], "match") + assert_eq(ops[2]["op"], "match") + assert_eq(ops[3]["op"], "match") + + +func test_missing_word_is_a_delete_and_does_not_shift_later_matches() -> void: + # L'enfant a oublie "petits" : sans alignement, "chats" se comparerait a + # "petits" et "dorment." a "chats", generant deux fausses erreurs en cascade. + var submitted: Array[String] = ["Les", "chats", "dorment."] + var ops := WordAligner.align(target, submitted) + assert_eq(ops.size(), 4) + assert_eq(ops[0]["op"], "match") + assert_eq(ops[1]["op"], "delete") + assert_eq(ops[1]["target_index"], 1) + assert_eq(ops[2]["op"], "match") + assert_eq(ops[2]["target_index"], 2) + assert_eq(ops[3]["op"], "match") + assert_eq(ops[3]["target_index"], 3) + + +func test_extra_word_is_an_insert() -> void: + var submitted: Array[String] = ["Les", "petits", "petits", "chats", "dorment."] + var ops := WordAligner.align(target, submitted) + var insert_ops: Array = ops.filter(func(op: Dictionary) -> bool: return op["op"] == "insert") + assert_eq(insert_ops.size(), 1) diff --git a/tests/correction/test_word_aligner.gd.uid b/tests/correction/test_word_aligner.gd.uid new file mode 100644 index 0000000..dba8501 --- /dev/null +++ b/tests/correction/test_word_aligner.gd.uid @@ -0,0 +1 @@ +uid://de278l35ygq6i diff --git a/tests/data/test_schema_validator.gd b/tests/data/test_schema_validator.gd index 0ce1b12..aa1c0e0 100644 --- a/tests/data/test_schema_validator.gd +++ b/tests/data/test_schema_validator.gd @@ -6,64 +6,65 @@ var schema: Dictionary = { "type": "object", "required": ["id", "level"], "additionalProperties": false, - "properties": { - "id": { "type": "string", "pattern": "^[a-z][a-z0-9_]*$" }, - "level": { "type": "string", "enum": ["CE1", "CE2"] }, - "difficulty": { "type": "integer", "minimum": 1, "maximum": 3 }, - "tags": { "type": "array", "minItems": 1, "items": { "type": "string" } }, + "properties": + { + "id": {"type": "string", "pattern": "^[a-z][a-z0-9_]*$"}, + "level": {"type": "string", "enum": ["CE1", "CE2"]}, + "difficulty": {"type": "integer", "minimum": 1, "maximum": 3}, + "tags": {"type": "array", "minItems": 1, "items": {"type": "string"}}, }, } func test_valid_object_has_no_errors() -> void: - var data := { "id": "ex_01", "level": "CE1", "difficulty": 2, "tags": ["pluriel"] } + var data := {"id": "ex_01", "level": "CE1", "difficulty": 2, "tags": ["pluriel"]} assert_eq(SchemaValidator.validate(data, schema), []) func test_missing_required_property_is_reported() -> void: - var data := { "level": "CE1" } + var data := {"level": "CE1"} var errors := SchemaValidator.validate(data, schema) assert_eq(errors.size(), 1) assert_string_contains(errors[0], "id") func test_wrong_type_is_reported() -> void: - var data := { "id": "ex_01", "level": "CE1", "difficulty": "deux" } + var data := {"id": "ex_01", "level": "CE1", "difficulty": "deux"} var errors := SchemaValidator.validate(data, schema) assert_eq(errors.size(), 1) assert_string_contains(errors[0], "difficulty") func test_enum_violation_is_reported() -> void: - var data := { "id": "ex_01", "level": "CM1" } + var data := {"id": "ex_01", "level": "CM1"} var errors := SchemaValidator.validate(data, schema) assert_eq(errors.size(), 1) assert_string_contains(errors[0], "level") func test_pattern_violation_is_reported() -> void: - var data := { "id": "Ex-01", "level": "CE1" } + var data := {"id": "Ex-01", "level": "CE1"} var errors := SchemaValidator.validate(data, schema) assert_eq(errors.size(), 1) assert_string_contains(errors[0], "id") func test_unexpected_property_is_reported_when_additional_forbidden() -> void: - var data := { "id": "ex_01", "level": "CE1", "extra": true } + var data := {"id": "ex_01", "level": "CE1", "extra": true} var errors := SchemaValidator.validate(data, schema) assert_eq(errors.size(), 1) assert_string_contains(errors[0], "extra") func test_min_items_violation_is_reported() -> void: - var data := { "id": "ex_01", "level": "CE1", "tags": [] } + var data := {"id": "ex_01", "level": "CE1", "tags": []} var errors := SchemaValidator.validate(data, schema) assert_eq(errors.size(), 1) assert_string_contains(errors[0], "tags") func test_numeric_bounds_are_checked() -> void: - var data := { "id": "ex_01", "level": "CE1", "difficulty": 9 } + var data := {"id": "ex_01", "level": "CE1", "difficulty": 9} var errors := SchemaValidator.validate(data, schema) assert_eq(errors.size(), 1) assert_string_contains(errors[0], "difficulty") diff --git a/tests/data/test_schema_validator.gd.uid b/tests/data/test_schema_validator.gd.uid new file mode 100644 index 0000000..ddbe7d2 --- /dev/null +++ b/tests/data/test_schema_validator.gd.uid @@ -0,0 +1 @@ +uid://c3gl78mc1o27p diff --git a/tests/data/test_semantic_checks.gd b/tests/data/test_semantic_checks.gd index 54ce285..c287cca 100644 --- a/tests/data/test_semantic_checks.gd +++ b/tests/data/test_semantic_checks.gd @@ -3,24 +3,24 @@ extends GutTest func test_multiple_choice_rejects_out_of_bounds_correct_answer() -> void: - var data := { "answers": ["a", "b"], "correct_answer": 5 } + var data := {"answers": ["a", "b"], "correct_answer": 5} var errors := SemanticChecks.check_multiple_choice(data, "test") assert_eq(errors.size(), 1) func test_multiple_choice_accepts_valid_index() -> void: - var data := { "answers": ["a", "b"], "correct_answer": 1 } + var data := {"answers": ["a", "b"], "correct_answer": 1} assert_eq(SemanticChecks.check_multiple_choice(data, "test"), []) func test_sentence_correction_requires_at_least_one_error_token() -> void: - var data := { "tokens": [{ "text": "Les", "correct": true }] } + var data := {"tokens": [{"text": "Les", "correct": true}]} var errors := SemanticChecks.check_sentence_correction(data, "test") assert_eq(errors.size(), 1) func test_sentence_correction_requires_expected_on_error_tokens() -> void: - var data := { "tokens": [{ "text": "petit", "correct": false }] } + var data := {"tokens": [{"text": "petit", "correct": false}]} var errors := SemanticChecks.check_sentence_correction(data, "test") assert_eq(errors.size(), 1) assert_string_contains(errors[0], "expected") @@ -29,7 +29,7 @@ func test_sentence_correction_requires_expected_on_error_tokens() -> void: func test_dictation_word_count_must_match_target_text() -> void: var data := { "target_text": "Les petits chats dorment.", - "words": [{ "text": "Les" }, { "text": "petits" }], + "words": [{"text": "Les"}, {"text": "petits"}], } var errors := SemanticChecks.check_dictation(data, "test") assert_eq(errors.size(), 1) @@ -38,8 +38,6 @@ func test_dictation_word_count_must_match_target_text() -> void: func test_dictation_accepts_matching_word_count() -> void: var data := { "target_text": "Les petits chats dorment.", - "words": [ - { "text": "Les" }, { "text": "petits" }, { "text": "chats" }, { "text": "dorment." } - ], + "words": [{"text": "Les"}, {"text": "petits"}, {"text": "chats"}, {"text": "dorment."}], } assert_eq(SemanticChecks.check_dictation(data, "test"), []) diff --git a/tests/data/test_semantic_checks.gd.uid b/tests/data/test_semantic_checks.gd.uid new file mode 100644 index 0000000..81c8f1d --- /dev/null +++ b/tests/data/test_semantic_checks.gd.uid @@ -0,0 +1 @@ +uid://bxlm60qsghevm diff --git a/tests/pedagogy/test_attempt_flow.gd b/tests/pedagogy/test_attempt_flow.gd new file mode 100644 index 0000000..452face --- /dev/null +++ b/tests/pedagogy/test_attempt_flow.gd @@ -0,0 +1,19 @@ +extends GutTest +## Tests de AttemptFlow : aide graduee sur 3 tentatives, sortie sans blocage. + + +func test_first_error_gives_a_hint() -> void: + assert_eq(AttemptFlow.support_level_for_attempt(1), AttemptFlow.SupportLevel.HINT) + + +func test_second_error_gives_an_explanation() -> void: + assert_eq(AttemptFlow.support_level_for_attempt(2), AttemptFlow.SupportLevel.EXPLANATION) + + +func test_third_error_reveals_the_answer() -> void: + assert_eq(AttemptFlow.support_level_for_attempt(3), AttemptFlow.SupportLevel.REVEAL) + + +func test_exercise_ends_at_max_attempts() -> void: + assert_false(AttemptFlow.should_end_exercise(2)) + assert_true(AttemptFlow.should_end_exercise(3)) diff --git a/tests/pedagogy/test_attempt_flow.gd.uid b/tests/pedagogy/test_attempt_flow.gd.uid new file mode 100644 index 0000000..63286c8 --- /dev/null +++ b/tests/pedagogy/test_attempt_flow.gd.uid @@ -0,0 +1 @@ +uid://dkijvppw88nt8 diff --git a/tests/pedagogy/test_difficulty_manager.gd b/tests/pedagogy/test_difficulty_manager.gd new file mode 100644 index 0000000..66f8ebf --- /dev/null +++ b/tests/pedagogy/test_difficulty_manager.gd @@ -0,0 +1,32 @@ +extends GutTest +## Tests de DifficultyManager. + + +func test_three_consecutive_successes_raise_difficulty() -> void: + var recent: Array[bool] = [true, true, true] + assert_eq(DifficultyManager.next_difficulty(1, recent), 2) + + +func test_three_consecutive_failures_lower_difficulty() -> void: + var recent: Array[bool] = [false, false, false] + assert_eq(DifficultyManager.next_difficulty(2, recent), 1) + + +func test_mixed_results_keep_difficulty_stable() -> void: + var recent: Array[bool] = [true, false, true] + assert_eq(DifficultyManager.next_difficulty(2, recent), 2) + + +func test_difficulty_never_exceeds_maximum() -> void: + var recent: Array[bool] = [true, true, true] + assert_eq(DifficultyManager.next_difficulty(3, recent), 3) + + +func test_difficulty_never_goes_below_minimum() -> void: + var recent: Array[bool] = [false, false, false] + assert_eq(DifficultyManager.next_difficulty(1, recent), 1) + + +func test_not_enough_history_keeps_difficulty_unchanged() -> void: + var recent: Array[bool] = [true, true] + assert_eq(DifficultyManager.next_difficulty(2, recent), 2) diff --git a/tests/pedagogy/test_difficulty_manager.gd.uid b/tests/pedagogy/test_difficulty_manager.gd.uid new file mode 100644 index 0000000..b5927ad --- /dev/null +++ b/tests/pedagogy/test_difficulty_manager.gd.uid @@ -0,0 +1 @@ +uid://tglbwa62prwa diff --git a/tests/pedagogy/test_review_scheduler.gd b/tests/pedagogy/test_review_scheduler.gd new file mode 100644 index 0000000..0a6c5d2 --- /dev/null +++ b/tests/pedagogy/test_review_scheduler.gd @@ -0,0 +1,133 @@ +extends GutTest +## Tests de ReviewScheduler : transitions de maitrise (cahier des charges §9) +## et planification des revisions en seances (pas en dates calendaires). + + +func _attempt( + success: bool, hint_used: bool = false, exercise_type: String = "multiple_choice" +) -> Dictionary: + return {"success": success, "hint_used": hint_used, "exercise_type": exercise_type} + + +func test_initial_state_is_decouverte() -> void: + assert_eq(ReviewScheduler.initial_state()["status"], ReviewScheduler.STATUS_DECOUVERTE) + + +func test_first_success_moves_to_en_acquisition() -> void: + var state := ReviewScheduler.record_attempt(ReviewScheduler.initial_state(), _attempt(true), 1) + assert_eq(state["status"], ReviewScheduler.STATUS_EN_ACQUISITION) + + +func test_first_failure_stays_at_decouverte() -> void: + var state := ReviewScheduler.record_attempt(ReviewScheduler.initial_state(), _attempt(false), 1) + assert_eq(state["status"], ReviewScheduler.STATUS_DECOUVERTE) + + +func test_two_hintless_successes_reach_en_consolidation() -> void: + var state := ReviewScheduler.initial_state() + state = ReviewScheduler.record_attempt(state, _attempt(true), 1) + state = ReviewScheduler.record_attempt(state, _attempt(true), 1) + assert_eq(state["status"], ReviewScheduler.STATUS_EN_CONSOLIDATION) + + +func test_successes_with_hints_do_not_reach_en_consolidation() -> void: + var state := ReviewScheduler.initial_state() + state = ReviewScheduler.record_attempt(state, _attempt(true, true), 1) + state = ReviewScheduler.record_attempt(state, _attempt(true, true), 1) + assert_eq(state["status"], ReviewScheduler.STATUS_EN_ACQUISITION) + + +func test_full_path_to_acquise_requires_sessions_and_formats() -> void: + var state := ReviewScheduler.initial_state() + var sessions := [1, 1, 2, 2, 3, 3, 4, 4] + var types := ["multiple_choice", "sentence_correction"] + for i in 8: + state = ReviewScheduler.record_attempt( + state, _attempt(true, false, types[i % 2]), sessions[i] + ) + assert_eq(state["status"], ReviewScheduler.STATUS_ACQUISE) + assert_eq(state["review_interval_index"], 0) + assert_eq(state["next_review_session"], 4 + ReviewScheduler.REVIEW_INTERVALS_SESSIONS[0]) + + +func test_acquise_requires_at_least_three_distinct_sessions() -> void: + var state := ReviewScheduler.initial_state() + var types := ["multiple_choice", "sentence_correction"] + # 8 succes mais seulement 2 seances distinctes : ne doit pas atteindre "acquise". + for i in 8: + state = ReviewScheduler.record_attempt( + state, _attempt(true, false, types[i % 2]), 1 if i < 4 else 2 + ) + assert_ne(state["status"], ReviewScheduler.STATUS_ACQUISE) + + +func test_acquise_requires_at_least_two_distinct_formats() -> void: + var state := ReviewScheduler.initial_state() + var sessions := [1, 1, 2, 2, 3, 3, 4, 4] + for i in 8: + state = ReviewScheduler.record_attempt(state, _attempt(true), sessions[i]) + assert_ne(state["status"], ReviewScheduler.STATUS_ACQUISE) + + +func _make_acquise_state(interval_index: int, next_review_session: int) -> Dictionary: + var state := ReviewScheduler.initial_state() + state["status"] = ReviewScheduler.STATUS_ACQUISE + state["recent_results"] = [true, true, true, true, true, true, true, true] + state["recent_hint_used"] = [false, false, false, false, false, false, false, false] + state["sessions_succeeded"] = [1, 2, 3] + state["formats_succeeded"] = ["multiple_choice", "sentence_correction"] + state["review_interval_index"] = interval_index + state["next_review_session"] = next_review_session + return state + + +func test_failure_on_acquise_skill_moves_to_a_reviser() -> void: + var state := _make_acquise_state(0, 99) + state = ReviewScheduler.record_attempt(state, _attempt(false), 5) + assert_eq(state["status"], ReviewScheduler.STATUS_A_REVISER) + assert_eq(state["next_review_session"], -1) + + +func test_success_on_a_reviser_skill_returns_to_acquise_at_first_interval() -> void: + var state := _make_acquise_state(2, 99) + state["status"] = ReviewScheduler.STATUS_A_REVISER + state = ReviewScheduler.record_attempt(state, _attempt(true), 10) + assert_eq(state["status"], ReviewScheduler.STATUS_ACQUISE) + assert_eq(state["review_interval_index"], 0) + assert_eq(state["next_review_session"], 10 + ReviewScheduler.REVIEW_INTERVALS_SESSIONS[0]) + + +func test_successful_review_on_time_advances_to_next_interval() -> void: + var state := _make_acquise_state(0, 5) + assert_true(ReviewScheduler.is_due_for_review(state, 5)) + state = ReviewScheduler.record_attempt(state, _attempt(true), 5) + assert_eq(state["status"], ReviewScheduler.STATUS_ACQUISE) + assert_eq(state["review_interval_index"], 1) + assert_eq(state["next_review_session"], 5 + ReviewScheduler.REVIEW_INTERVALS_SESSIONS[1]) + + +func test_success_before_due_date_does_not_advance_interval() -> void: + var state := _make_acquise_state(0, 10) + assert_false(ReviewScheduler.is_due_for_review(state, 5)) + state = ReviewScheduler.record_attempt(state, _attempt(true), 5) + assert_eq(state["review_interval_index"], 0) + assert_eq(state["next_review_session"], 10) + + +func test_review_interval_never_exceeds_last_step() -> void: + var last_index := ReviewScheduler.REVIEW_INTERVALS_SESSIONS.size() - 1 + var state := _make_acquise_state(last_index, 5) + state = ReviewScheduler.record_attempt(state, _attempt(true), 5) + assert_eq(state["review_interval_index"], last_index) + + +func test_mark_overdue_as_review_transitions_without_new_attempt() -> void: + var state := _make_acquise_state(0, 5) + var updated := ReviewScheduler.mark_overdue_as_review(state, 6) + assert_eq(updated["status"], ReviewScheduler.STATUS_A_REVISER) + + +func test_mark_overdue_as_review_does_nothing_before_due_date() -> void: + var state := _make_acquise_state(0, 5) + var updated := ReviewScheduler.mark_overdue_as_review(state, 3) + assert_eq(updated["status"], ReviewScheduler.STATUS_ACQUISE) diff --git a/tests/pedagogy/test_review_scheduler.gd.uid b/tests/pedagogy/test_review_scheduler.gd.uid new file mode 100644 index 0000000..ae43023 --- /dev/null +++ b/tests/pedagogy/test_review_scheduler.gd.uid @@ -0,0 +1 @@ +uid://cryfvtynu2fue