Add pure correction and pedagogy logic with full test coverage

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 <noreply@anthropic.com>
This commit is contained in:
Denis Defolie
2026-10-11 17:03:14 +02:00
parent d057c8ee77
commit 2fe455f5d1
36 changed files with 1111 additions and 28 deletions
+99
View File
@@ -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"],
}
@@ -0,0 +1 @@
uid://cxrvun2qowvp8
+35
View File
@@ -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
@@ -0,0 +1 @@
uid://38ngt760408y
+128
View File
@@ -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
@@ -0,0 +1 @@
uid://cj3x15p8r3rmj
+67
View File
@@ -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
@@ -0,0 +1 @@
uid://07glvxpdv5ml
+55
View File
@@ -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
+1
View File
@@ -0,0 +1 @@
uid://dmrmm4pljh4j1