commit 318644f4b0f2417d35aacb1e926aaf8033d0d4e8 Author: claude-math Date: Sat Nov 7 19:12:25 2026 +0100 Plugin claude-math : exercices et vérification de calculs Plugin Claude Code regroupant : - le skill `math-exercises` (génération et correction de séries d'exercices progressifs, suivi de progression et des notions à revoir) ; - la commande `/exos`, qui force Opus via son frontmatter `model:` ; - un hook `UserPromptSubmit` qui vérifie automatiquement les affirmations mathématiques tapées dans un message (chaînes d'égalités et de congruences, divisibilité, primalité, pgcd/ppcm/φ) et rend un verdict ligne par ligne. Le dépôt sert à la fois de plugin et de marketplace à entrée unique, pour pouvoir être installé directement depuis son URL. Co-Authored-By: Claude Opus 5 (1M context) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json new file mode 100644 index 0000000..3df508e --- /dev/null +++ b/.claude-plugin/marketplace.json @@ -0,0 +1,14 @@ +{ + "name": "claude-math", + "description": "Marketplace à plugin unique : claude-math.", + "owner": { + "name": "claude-math" + }, + "plugins": [ + { + "name": "claude-math", + "source": "./", + "description": "Exercices et correction de maths pour la cryptographie, avec vérification automatique des calculs." + } + ] +} diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json new file mode 100644 index 0000000..462ea27 --- /dev/null +++ b/.claude-plugin/plugin.json @@ -0,0 +1,6 @@ +{ + "name": "claude-math", + "description": "Exercices calibrés et correction pour un cours de mathématiques pour la cryptographie : génération de séries progressives, notation du cours, suivi de progression, et vérification automatique des calculs arithmétiques/modulaires tapés dans les messages.", + "version": "1.0.0", + "keywords": ["maths", "cryptographie", "arithmétique", "exercices"] +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..b5ed61e --- /dev/null +++ b/README.md @@ -0,0 +1,90 @@ +# claude-math + +Plugin Claude Code pour un cours de **mathématiques pour la cryptographie** : +génération d'exercices calibrés, correction, suivi de progression, et +vérification automatique des calculs tapés dans les messages. + +| Composant | Chemin | Rôle | +|---|---|---| +| Skill | `skills/math-exercises/SKILL.md` | Génère des séries de 4 exercices progressifs sur le prochain sujet non maîtrisé, corrige les réponses, et tient à jour `PROGRESS.md` / `REVISIONS.md`. | +| Commande | `commands/exos.md` | `/exos` — lance le skill en forçant Opus via son frontmatter `model:`. | +| Hook | `hooks/verify-calculations.sh` | `UserPromptSubmit` : vérifie automatiquement toute affirmation mathématique tapée dans un message et renvoie un verdict ✅/❌ ligne par ligne. | + +## Installation + +> **Prérequis : Nix.** Le hook de vérification lance Python + sympy via +> `nix-shell -p python3 python3Packages.sympy`. Sans Nix sur la machine, le +> skill et la commande fonctionnent normalement mais le hook échoue +> silencieusement — aucun calcul n'est vérifié (il ne bloque jamais l'envoi +> d'un message). Voir [Se passer de Nix](#se-passer-de-nix) pour l'adapter. + +```bash +/plugin marketplace add +/plugin install claude-math@claude-math +``` + +Le dépôt est à la fois le plugin (`.claude-plugin/plugin.json`) et une +marketplace à entrée unique (`.claude-plugin/marketplace.json`), donc les deux +commandes suffisent. + +## Ce que le skill attend du projet où il tourne + +Le plugin ne transporte **pas** les données du cours. Dans le dossier de +travail, il s'attend à trouver : + +- `CLAUDE.md` — le plan du cours (TD1/TD2/TD3 et leurs sous-sections) ; c'est + la source de la liste des sujets ; +- `NOTATIONS_REFERENCE.md` — les notations telles qu'elles apparaissent en + cours ; +- `PROGRESS.md` — suivi par sujet (créé par le skill s'il manque) ; +- `REVISIONS.md` — notions non réussies du premier coup, pour re-test espacé + (créé par le skill s'il manque) ; +- les PDF des TD et de leurs corrections, pour calibrer notation et difficulté. + +## Le hook de vérification + +À chaque message, le hook extrait les énoncés vérifiables et les contrôle : + +- chaînes d'égalités et de congruences — `8^6 mod 15 = 64*8^4 = … = 4` ; +- divisibilité — `7 | 28` ; +- primalité — `13 est premier` ; +- `pgcd` / `ppcm` / `φ(n)` ; +- équations à une inconnue — `2x + 3 = 7`. + +**Règle de portée du modulus :** un `mod N` écrit sur *n'importe quel* maillon +d'une chaîne porte sur **tous** les maillons. C'est la convention du cours : +le modulus est énoncé une fois et reste implicite ensuite. Si deux moduli +différents apparaissent dans la même chaîne, le hook se tait plutôt que +d'accuser à tort. + +Notations acceptées : exposants Unicode (`4²²`), `≡`, `(mod 15)`, `φ`, `×`, +`·`, `pgcd`/`ppcm`, et le LaTeX courant (`$…$`, `\equiv`, `\pmod{15}`, +`8^{6}`). Les maths noyées dans de la prose française sont extraites et +vérifiées ligne par ligne. + +### Se passer de Nix + +Remplacer dans `hooks/verify-calculations.sh` la ligne : + +```bash +nix-shell -p python3 python3Packages.sympy --run python3 << 'PYTHON_EOF' 2>/dev/null +``` + +par un interpréteur disposant de sympy, par exemple : + +```bash +python3 << 'PYTHON_EOF' 2>/dev/null +``` + +## Développement + +Le hook est un script bash qui encapsule un programme Python en heredoc. Pour +le tester sans passer par Claude Code, lui envoyer sur stdin le JSON de +l'évènement : + +```bash +printf '{"prompt": "8^6 mod 15 = 64 * 8^4 = 4"}' | bash hooks/verify-calculations.sh +``` + +Il répond sur stdout un JSON `{"systemMessage": …}` contenant les verdicts, et +les écrit en direct sur `/dev/tty` quand un terminal est disponible. diff --git a/commands/exos.md b/commands/exos.md new file mode 100644 index 0000000..085f713 --- /dev/null +++ b/commands/exos.md @@ -0,0 +1,11 @@ +--- +description: Exercices de maths pour la cryptographie — lance le skill math-exercises sur Opus +model: opus +--- + +Invoke the `math-exercises` skill now (via the Skill tool) and follow it end to +end — it is listed as `claude-math:math-exercises` when provided by this +plugin. Arguments, if any: $ARGUMENTS + +This command exists so the exercise loop always runs on Opus — the `model:` +frontmatter above forces it regardless of the session's current model. diff --git a/hooks/hooks.json b/hooks/hooks.json new file mode 100644 index 0000000..ff79857 --- /dev/null +++ b/hooks/hooks.json @@ -0,0 +1,19 @@ +{ + "description": "Vérifie, à chaque message envoyé, toute affirmation mathématique vérifiable qu'il contient (égalités et congruences, divisibilité, primalité, pgcd/ppcm/φ) et renvoie un verdict ligne par ligne.", + "hooks": { + "UserPromptSubmit": [ + { + "matcher": "", + "hooks": [ + { + "type": "command", + "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/verify-calculations.sh\"", + "timeout": 30, + "statusMessage": "Verifying calculations...", + "async": false + } + ] + } + ] + } +} diff --git a/hooks/verify-calculations.sh b/hooks/verify-calculations.sh new file mode 100755 index 0000000..d3a54d5 --- /dev/null +++ b/hooks/verify-calculations.sh @@ -0,0 +1,377 @@ +#!/bin/bash + +# Per-line verification hook for mathematical statements in the user's prompt. +# +# Streams a verdict for every verifiable line as it is checked (to /dev/tty, so +# it appears live rather than all at once when the hook returns), then emits a +# compact JSON summary on stdout so Claude sees the same results in context. +# +# Input: UserPromptSubmit hook JSON on stdin — the text lives in `.prompt`. +# Reading stdin as raw text (the previous behaviour) leaked the whole JSON +# envelope into the verdict output, so the payload is parsed properly here. + +INPUT=$(cat) + +[ ${#INPUT} -lt 3 ] && exit 0 + +export VERIFY_RAW="$INPUT" + +nix-shell -p python3 python3Packages.sympy --run python3 << 'PYTHON_EOF' 2>/dev/null +import sys +import os +import re +import math +import json +import time + +from sympy import isprime, totient, Symbol, Eq, solve, simplify +from sympy.parsing.sympy_parser import ( + parse_expr, standard_transformations, implicit_multiplication_application) + +TRANSFORMS = standard_transformations + (implicit_multiplication_application,) + +raw = os.environ.get('VERIFY_RAW', '') + +# The hook hands us the event JSON; fall back to raw text if that ever changes. +try: + payload = json.loads(raw) + prompt = payload.get('prompt', '') if isinstance(payload, dict) else raw +except Exception: + prompt = raw + +if not prompt.strip(): + sys.exit(0) + +# Live channel: the controlling terminal. Absent in headless/background runs, +# where the JSON summary below becomes the only output. +try: + live = open('/dev/tty', 'w') +except Exception: + live = None + +summary = [] +header_done = False + + +def emit(text): + """Print one line immediately, so checks appear as they happen.""" + if live: + live.write(text + "\n") + live.flush() + time.sleep(0.05) + + +def emit_header(): + global header_done + if not header_done: + emit("verifying lines...") + summary.append("verifying lines...") + header_done = True + + +# ---------------------------------------------------------------------- +# Normalisation: course notation -> something evaluable +# ---------------------------------------------------------------------- +SUPERSCRIPT = {'⁰': '0', '¹': '1', '²': '2', '³': '3', + '⁴': '4', '⁵': '5', '⁶': '6', '⁷': '7', + '⁸': '8', '⁹': '9'} + + +def desuperscript(s): + """4²² -> 4^22, so superscript powers verify like ASCII ones.""" + out, i = [], 0 + while i < len(s): + if s[i] in SUPERSCRIPT: + run = '' + while i < len(s) and s[i] in SUPERSCRIPT: + run += SUPERSCRIPT[s[i]] + i += 1 + out.append('^' + run) + else: + out.append(s[i]) + i += 1 + return ''.join(out) + + +def normalize(s): + s = desuperscript(s) + # LaTeX the user actually types + s = s.replace('\\varphi', 'phi').replace('\\phi', 'phi') + s = s.replace('\\equiv', '≡').replace('\\times', '*').replace('\\cdot', '*') + s = s.replace('\\pmod', 'mod').replace('\\mod', 'mod').replace('\\bmod', 'mod') + s = s.replace('$', '') + s = re.sub(r'\\[a-zA-Z]+', ' ', s) + # `\pmod{15}`, `8^{6}`: once the command names are gone, braces are just + # parentheses. + s = s.replace('{', '(').replace('}', ')') + # `≡ 4 (mod 15)` / `≡ 4 mod(15)` -> `≡ 4 mod 15`. The course writes the + # modulus in parentheses, and the chain scoping below needs it bare. + s = re.sub(r'\(\s*mod\s*([0-9]+)\s*\)', r'mod \1', s) + s = re.sub(r'\bmod\s*\(\s*([0-9]+)\s*\)', r'mod \1', s) + # unicode maths -> ASCII + s = s.replace('φ', 'phi').replace('ϕ', 'phi') + s = s.replace('×', '*').replace('·', '*').replace('⋅', '*') + s = s.replace('÷', '/') + s = s.replace('−', '-').replace('–', '-') + s = re.sub(r'\bpgcd\b|\bPGCD\b', 'gcd', s) + s = re.sub(r'\bppcm\b|\bPPCM\b', 'lcm', s) + s = re.sub(r'\bPhi\b', 'phi', s) + return s.strip() + + +ALLOWED = re.compile(r'^[0-9\s+\-*/%().,^]*$') + + +def _phi(n): + return int(totient(int(n))) + + +def _lcm(a, b): + return abs(a * b) // math.gcd(int(a), int(b)) if a and b else 0 + + +ENV = {'phi': _phi, 'gcd': math.gcd, 'lcm': _lcm} + + +def eval_expr(s): + """Evaluate a purely numeric expression (with phi/gcd/lcm) to an int.""" + s = s.replace('^', '**') + s = re.sub(r'\bmod\b', '%', s) # inner mods bind like *, as in Python + for m in re.finditer(r'\*\*\s*(\d+)', s): + if int(m.group(1)) > 10000: # keep the hook from hanging + raise ValueError('exponent too large') + bare = re.sub(r'\b(phi|gcd|lcm)\b', '', s) + if not ALLOWED.match(bare): + raise ValueError('unsupported characters') + val = eval(s, {'__builtins__': {}}, dict(ENV)) + if isinstance(val, float): + if abs(val - round(val)) > 1e-9: + raise ValueError('non-integer') + val = round(val) + return int(val) + + +MOD_TAIL = re.compile(r'^(.*)\bmod\s*([0-9]+)\s*$') + + +def split_mod(s): + """`expr mod N` -> ('expr', N); no trailing modulus -> ('expr', None).""" + m = MOD_TAIL.match(s.strip()) + if m: + return m.group(1).strip(), int(m.group(2)) + return s.strip(), None + + +def eval_term(s): + """Evaluate one side of a (chain of) equalities; a trailing `mod N` + applies to everything before it, matching the course convention.""" + s = s.strip() + if not s: + raise ValueError('empty') + expr, mod = split_mod(s) + val = eval_expr(expr) + return val % mod if mod is not None else val + + +# Values already pinned to a variable, so a later contradictory claim is caught. +known_vars = {} + + +# `mod`/`phi`/`gcd`/`lcm` read as operators; any other letters end a math run, +# which is how a claim gets separated from the prose around it. +MATH_RUN = re.compile(r'(?:[0-9]|\bmod\b|\bphi\b|\bgcd\b|\blcm\b|[+\-*/^()≡=,%]|\s)+') + + +def extract_segments(line): + """Pull the mathematical runs out of a line that also carries prose, so + `Euler's theorem gives 8^6 mod 15 = ... = 4 mod 15.` still gets checked + instead of being skipped because the sentence as a whole won't parse.""" + segments = [] + for m in MATH_RUN.finditer(line): + seg = m.group(0).strip(' ,;:.') + if not seg or not re.search(r'≡|=', seg): + continue + if len([p for p in re.split(r'≡|=', seg) if p.strip()]) >= 2: + segments.append(seg) + return segments + + +def verify_claim(line): + """-> (status, detail) for one already-normalised claim.""" + if not line or len(line) < 3: + return ('skip', None) + + # --- primality: "13 is prime", "15 n'est pas premier" --------------- + m = re.search(r'\b([0-9]+)\s+(?:is|est)\s+(not\s+|n\'est\s+pas\s+|pas\s+)?' + r'(?:a\s+|un\s+|une\s+)?(?:prime|premier)', line, re.I) + if not m: + m2 = re.search(r'\b([0-9]+)\s+n\'est\s+pas\s+premier', line, re.I) + if m2: + n = int(m2.group(1)) + actual = bool(isprime(n)) + return ('ok' if not actual else 'wrong', + f"{n} est premier" if actual else None) + if m: + n = int(m.group(1)) + claims_not = bool(m.group(2)) + actual = bool(isprime(n)) + ok = (actual != claims_not) + detail = None if ok else (f"{n} est premier" if actual + else f"{n} = composé") + return ('ok' if ok else 'wrong', detail) + + # --- divisibility: "7 | 28", "7 | (45 - 17)" ------------------------ + if '|' in line and line.count('|') == 1 and '||' not in line: + left, right = line.split('|') + try: + d, n = eval_term(left), eval_term(right) + except Exception: + pass + else: + if d == 0: + return ('wrong', 'division par 0') + ok = (n % d == 0) + return ('ok' if ok else 'wrong', + None if ok else f"reste {n % d}") + + # --- chain of equalities / congruences ------------------------------ + # A `mod N` written on ANY link scopes the WHOLE chain. The course states + # the modulus once and leaves it implicit everywhere else, so + # 8^6 mod 15 = 64*8^4 = 4*8*8^3 = 2*8*8^2 = 1*8^2 = 4 + # is read entirely modulo 15: every link gets reduced by 15, not just the + # one that happens to spell the modulus out. Scoping only the trailing + # `mod N` reported correct chains as wrong whenever the modulus was + # written on the first link instead of the last. + parts, mods = [], [] + for p in re.split(r'≡|=', line): + p = p.strip() + if not p: + continue + expr, n = split_mod(p) + parts.append(expr if expr else p) + if n is not None: + mods.append(n) + + distinct = sorted(set(mods)) + # Two different moduli in one chain is not a statement we can read with + # confidence; stay silent rather than accuse wrongly. + if len(distinct) > 1: + return ('skip', None) + mod = distinct[0] if distinct else None + body = ' = '.join(parts) + + if len(parts) >= 2: + try: + vals = [eval_expr(p) for p in parts] + except Exception: + vals = None + if vals is not None: + red = [v % mod for v in vals] if mod is not None else vals + ok = all(r == red[0] for r in red) + if ok: + return ('ok', None) + shown = ', '.join(str(r) for r in red) + return ('wrong', f"{shown} mod {mod}" if mod is not None else shown) + + # --- symbolic fallback: one unknown, e.g. "2x + 3 = 7" ---------- + # Skipped when the chain carries a modulus: solving `x ≡ 2 mod 5` as + # the equation x = 2 would drop the modulus and report a verification + # that never happened. + if mod is not None: + return ('skip', None) + # Prose sentences must not reach sympy: `parse_expr` with implicit + # multiplication turns every letter into a symbol, which is both + # meaningless and slow enough to blow the hook's timeout. + if re.search(r'[a-zA-Z]{2,}', re.sub(r'\b(mod|phi|gcd|lcm)\b', '', body)): + return ('skip', None) + if len(parts) == 2 and re.search(r'(? list of (shown_text, status, detail) for one source line. + + A line is first tried whole; only if that yields nothing do we fall back + to the maths embedded in prose, which may hold several claims at once + (`phi(15) = 8; 8^6 mod 15 = ... = 4 mod 15.`).""" + line = normalize(raw_line) + if not line: + return [] + + status, detail = verify_claim(line) + if status != 'skip': + return [(raw_line.strip(), status, detail)] + + results = [] + for seg in extract_segments(line): + s, d = verify_claim(seg) + if s != 'skip': + results.append((seg.strip(), s, d)) + return results + + +# ---------------------------------------------------------------------- +# Walk the prompt line by line, printing each verdict as it is decided. +# ---------------------------------------------------------------------- +lines = prompt.split('\n') +last_idx = -2 + +for i, raw_line in enumerate(lines): + try: + verdicts = verify_line(raw_line) + except Exception: + verdicts = [] + if not verdicts: + continue + + emit_header() + + # First line of a new block: blank line, then the line above it for context + # (typically the exercise label or the statement being worked on). + if i - 1 != last_idx: + emit("") + summary.append("") + if i > 0 and lines[i - 1].strip(): + ctx = lines[i - 1].strip() + emit(ctx) + summary.append(ctx) + + for shown, status, detail in verdicts: + verdict = f"{shown} = Ok ✅" if status == 'ok' else f"{shown} = Wrong ❌" + if detail: + verdict += f" ({detail})" + emit(verdict) + summary.append(verdict) + last_idx = i + +if live: + try: + live.close() + except Exception: + pass + +# Give Claude the same verdicts in context (and cover the no-tty case). +if any(s.strip() for s in summary): + print(json.dumps({"systemMessage": "\n".join(summary).strip()})) +PYTHON_EOF diff --git a/skills/math-exercises/SKILL.md b/skills/math-exercises/SKILL.md new file mode 100644 index 0000000..7164fae --- /dev/null +++ b/skills/math-exercises/SKILL.md @@ -0,0 +1,267 @@ +--- +name: math-exercises +description: > + Generate a set of 4 increasingly-difficult practice exercises on the next + not-yet-mastered topic of the crypto-maths course (the + outline in CLAUDE.md), styled after the TD PDFs in this directory, then + grade the user's answers, track per-topic completion in PROGRESS.md and + track not-first-try notions in REVISIONS.md for spaced re-testing. + Trigger whenever the user asks for math exercises or practice problems in + this course — "give me an exercise", "exercices", "des exos", "donne-moi un + exercice", "je veux m'entraîner", "quiz me", "practice", "next topic", + "continue les exercices", or any follow-up where the user submits answers + to exercises this skill generated earlier. Always use this skill instead of + improvising ad-hoc problems — it keeps difficulty calibrated to mental + arithmetic, keeps notation consistent with the course, and keeps PROGRESS.md + and REVISIONS.md in sync. +--- + +# Math exercises for the crypto-maths course + +## 0. Run on Opus — check before anything else + +This loop (writing calibrated exercises, grading proofs, diagnosing +conceptual vs. arithmetic mistakes) is tuned for Opus. **Before reading any +PDF or picking a topic**, check which model this session is running: + +- **Already Opus** → continue straight to step 1, say nothing about it. +- **Not Opus** → stop immediately. Do not read PDFs, pick a topic, or write + exercises. Tell the user, in one line, to run `/model opus` and then ask + again — or to use `/exos`, the command shipped by this plugin, which forces + Opus via its `model: opus` frontmatter (`commands/exos.md`). Only proceed on a + weaker model if the user explicitly says to go ahead anyway. + +A skill cannot switch the session model on its own — there is no tool for it, +and SKILL.md frontmatter has no `model:` field. `/exos` is the enforcement +mechanism; this step is the fallback when the skill is triggered by plain +language ("donne-moi un exercice") instead of the command. + +This skill runs a full loop: pick a topic → write a series → grade what the +user submits → remediate mistakes → record what wasn't passed first try → +mark the topic done. Course outline: `CLAUDE.md`. Notation reference: +`NOTATIONS_REFERENCE.md`. Progress tracker: `PROGRESS.md`. Weak-notion +tracker: `REVISIONS.md`. Source PDFs (course + exercise sheets + +corrections): `TD1-arithmetique.pdf`, `TD1-arithmetique-correctionEx.pdf`, +`TD2-groupes.pdf`, `TD2-groupes_feuilleexercice.pdf`, `TD3-anneaux.pdf`, +`TD3-anneaux-correction.1-5.pdf`. + +### What "passed on the first try" means + +An exercise counts as **first-try** only if the user's *first* submission for +it is fully correct, with no help beyond the original statement. All of these +count as **not** first-try, and get recorded in `REVISIONS.md`: + +- a wrong first answer, even if a later retry is correct; +- asking for a hint, a nudge, or "help" before producing a correct answer; +- an answer correct in substance but resting on an invalid step the user had + to be walked back from. + +Pure transcription typos (writing `n − 2` for `n + 2` while reasoning +correctly throughout) do **not** count as failures — note them and move on. + +## 1. Pick the topic — or enter remediation mode + +Read `PROGRESS.md` and `REVISIONS.md` first. If either doesn't exist, create +it: `PROGRESS.md` by listing every sub-section heading under TD1/TD2/TD3 in +`CLAUDE.md`, in order, as unchecked boxes (the topic list lives in CLAUDE.md, +PROGRESS.md only tracks status); `REVISIONS.md` with the two headings +`## À revoir` and `## Résolus` and nothing under them. + +Then count the unresolved entries under `## À revoir` in `REVISIONS.md`: + +- **More than 4 unresolved → REMEDIATION MODE.** Do *not* advance to a new + topic and do *not* touch `PROGRESS.md` this round. Instead build a series + of exactly 4 exercises, one targeting each of the **4 oldest** unresolved + entries (oldest first, so nothing starves). Say so plainly up front, e.g. + *"5 notions en attente de révision — on ne passe pas au sujet suivant, + cette série est une remise à niveau."* Skip to step 2, calibrating against + whichever TD each entry belongs to. +- **4 or fewer unresolved → normal mode.** Pick the topic as follows: + - Default topic = the **first unchecked box** in `PROGRESS.md`, in file + order (TD1 top to bottom, then TD2, then TD3). + - If the user names a specific topic/TD explicitly, use that instead. If + it's already checked off, generate the exercises anyway as a review round + but don't touch its checkbox (only the auto-picked "next" topic gets + marked done by this flow). + - Tell the user which topic you picked and why (e.g. "Next up: *Division + euclidienne et algorithme d'Euclide* (TD1)") before giving the exercises. + +## 2. Calibrate against the PDFs + +Read the course PDF(s) for the relevant TD (and the correction PDF if one +exists for it) to calibrate notation, phrasing and difficulty range — use the +`Read` tool's `pages` param if a PDF is long. **Do not copy an existing +exercise's numbers or statement.** Write new exercises in the same spirit. +Cross-check any notation you use against `NOTATIONS_REFERENCE.md` so it +matches what the student already sees in lecture (e.g. `pgcd`, `φ(n)`, +`Z×ₙ`, `≡ mod N`). + +## 3. Write the series + +### 3a. The 4 main exercises, increasing difficulty + +Label each with a difficulty tag and keep them on the chosen topic: + +1. **Facile** — direct, one-step application of a single definition/theorem. +2. **Moyen** — combines two small steps (e.g. compute something, then apply + a theorem to it). +3. **Difficile** — requires a short justification/proof, or a less obvious + case (e.g. picking the right theorem among several). +4. **Expert / synthèse** — the trickiest angle on this topic: an edge case, a + short proof, or a light combination with a topic already marked done in + `PROGRESS.md` (skip the combination if nothing is done yet). + +In **remediation mode** the four exercises instead target the four oldest +unresolved notions, still ordered easiest-to-hardest, each labelled with the +notion it re-tests: *"Exercice 2 — révision : lemme de linéarité de la +divisibilité"*. + +### 3b. Bonus revision exercises + +In **normal mode**, after the 4 main exercises, append up to **2 bonus +exercises** drawn from the unresolved entries in `REVISIONS.md`, oldest +first. Label them `Bonus A` / `Bonus B` and name the notion each re-tests. + +- Target the **notion**, not the literal exercise — re-asking the identical + question tests recall, not understanding. Change the numbers, the framing, + or the direction of the implication. +- Bonus exercises are **never** required to mark a topic done (see step 5), + and a failed bonus never blocks topic completion — it just keeps its entry + unresolved. +- If `REVISIONS.md` has no unresolved entries, there are no bonus exercises; + don't invent any. + +### 3c. Keep arithmetic mental-math friendly, always + +- No number a human must compute with should exceed 2 digits (≤ 99). +- Prefer small factors (2, 3, 5, 7, 11, 13) so divisions/multiplications land + cleanly; don't manufacture ugly remainders unless the exercise is + specifically about remainders (and then keep the remainder itself small). +- For modular exponentiation, keep the modulus ≤ 50 and the exponent small + enough to do by hand in ≤ 3–4 squaring steps. +- If a topic is purely structural/proof-based with no numbers, "difficulty" + still escalates as described above — the mental-math constraint just + doesn't apply to that exercise. + +Work out the full solution for each exercise yourself and keep it private — +don't reveal it until grading (or until the user asks you to give up on one). + +Present the whole series at once, clearly numbered and tagged, then stop and +wait for the user's attempt(s). Don't dump solutions preemptively. + +## 4. Grade what the user submits + +The user may answer one exercise at a time or all at once — handle either. +For each submitted answer: + +- **Correct:** confirm briefly, note in one line *why* it's correct (ties + back to the theorem/definition used), move on. +- **Incorrect:** diagnose which of the two applies before replying: + - **Conceptual mistake** (wrong theorem, wrong definition, invalid step): + explain the correct reasoning using the vocabulary from `CLAUDE.md` / + `NOTATIONS_REFERENCE.md`, give a short worked mini-example, and point to + exactly where to look — TD number, filename, and the sub-section name, + e.g. *"revoir TD2-groupes.pdf, partie 'Ordres et structures cycliques' + (théorème de Lagrange)"*. Let them retry the same exercise rather than + handing over the answer outright. If they stall across two or three + scaffolded attempts, stop withholding: show the full proof, annotate the + misconception, then re-test the technique on a fresh small exercise. + - **Calculation slip** (right method, arithmetic error): point out exactly + where the number went wrong, then give ONE relevant mental-math check + from the table below, and mention they can type the intermediate + calculation as a bare statement (e.g. `gcd(84, 18) = 6`, `15 mod 7 = 1`, + `3^4 mod 5 = 1`) — **this plugin already auto-verifies such statements on + every message** via its `UserPromptSubmit` hook + (`hooks/verify-calculations.sh`) and will flag a ✗ + instantly if it's wrong. Point this out the first time it's relevant in a + session; no need to repeat every time after that. + +### 4a. Record every exercise not passed first try + +As soon as an exercise fails the first-try bar defined above, **append an +entry to `## À revoir` in `REVISIONS.md`** — do it at grading time, not at +the end of the series, so nothing is lost if the session is interrupted. +One line per entry: + +``` +- [ ] **** — () · échoué le · +``` + +Record the **notion**, not the exercise number — "exercice 3b" is meaningless +three weeks later, "preuve pgcd(a,b) = pgcd(b,r) par double inclusion" is +not. If an entry for that notion already exists, don't duplicate it: append +`· re-échoué le ` to the existing line instead. + +Entries stay unresolved until the user clears them per step 5. A correct +*retry* never clears an entry — only a first-try pass on a later bonus or +remediation exercise does. + +### Notation conventions agreed with the user + +- **A `mod N` written on ANY link scopes the whole chain.** In `a ≡ b ≡ c mod + N` — and equally in `a mod N = b = c`, where the modulus is stated once up + front — every term is taken mod N. Do not read the modulus as binding only + to the link it happens to be written on. Grade chains accordingly; the + plugin's `hooks/verify-calculations.sh` applies the same rule. +- A chain of `≡` asserts that **every** term is congruent to every other, so + line-wide scoping makes the claim stronger, not weaker. A chain whose terms + reduce to different residues is false however the modulus scopes. +- Flag `=` used where `≡` belongs (`38 × 27 = 3 × 2 mod 5`), but treat it as a + notation note, not a conceptual error. + +### Mental-math verification techniques (pick the one matching the slip) + +| Operation | Quick manual check | +|---|---| +| Multiplication `a×b` | Casting out nines: digit-sum(a) mod 9 × digit-sum(b) mod 9 ≡ digit-sum(product) mod 9 | +| Division euclidienne `a = bq + r` | Re-expand `bq + r` and confirm it equals `a`, and `0 ≤ r < b` | +| `pgcd(a, b)` | Confirm the claimed gcd divides both `a` and `b` exactly | +| Bézout `ua + vb = pgcd(a,b)` | Plug `u, v` back in and recompute `ua + vb` directly | +| Modular exponentiation `a^k mod n` | Redo it by repeated squaring, reducing mod n after every squaring step | +| `φ(n)` | Recompute via `φ(n) = n·∏(1 − 1/p)` over its prime factors and cross-check it matches `p−1` for each prime factor | +| Any arithmetic/modular/gcd/divisibility/primality claim | Just state it plainly in your message — the repo's hook checks it automatically | + +### Divisibility proofs — lead with this frame + +This user's recurring trap. When grading any proof involving `|`, state it +up front rather than waiting for them to flounder: + +- To **use** `d | x`: substitute `x = kd`. +- To **prove** `d | y`: exhibit `y = (integer) × d`. +- **Never divide** — forming a fraction like `(a−r)/b` is always the wrong + move; reading `x/q = y` as `q | y` is a false step. +- `d` is an **arbitrary** common divisor, never the gcd itself. +- Proving every common divisor divides `k` gives an **upper bound** on the + pgcd, not its value — check attainment separately. + +## 5. Close out + +### 5a. Clear resolved revision entries + +When the user passes a **bonus** (normal mode) or **remediation** (remediation +mode) exercise **on the first try**, its notion is cleared: move that line +from `## À revoir` to `## Résolus` in `REVISIONS.md`, flipping it to +`- [x] … · résolu le `. If they need a retry or a hint, the entry +stays put and will come back in a later series. + +### 5b. Mark the topic done + +In **normal mode only**, once exercises 1–3 for the **auto-picked** topic are +answered correctly (after however many retries), check its box in +`PROGRESS.md`: `- [x] (fait le )`. Then tell the +user what's next in `PROGRESS.md` order and ask whether to start it now or +stop here. + +- Exercise 4 (expert/synthèse) is optional for marking completion: the user + may skip it, and the topic is still marked done as soon as exercises 1–3 + are all valid — don't withhold the checkbox waiting on exercise 4. If the + user does attempt exercise 4, it must also be correct before marking done. +- Bonus exercises are likewise never required for completion. +- A review round on an already-done topic never touches `PROGRESS.md`. +- **Remediation mode never marks a topic done** — it only clears + `REVISIONS.md` entries. Once the unresolved count drops to 4 or fewer, the + next series returns to normal mode and advances to the next topic. + +Whenever a series ends, state the current counts in one line — topics done +out of total, and unresolved revision entries — so the user knows where the +next series will go.