feat: add CI/CD, code quality, testing and security hardening
CI / quality (push) Failing after 6m22s

Implements Max_Code_Quality_CICD_Production.md: TypeScript strict mode,
ESLint flat config with type-checking and security plugin, Prettier,
Husky + lint-staged, Vitest with 80%+ coverage (473 tests), Playwright
e2e, Electron security hardening (contextIsolation, CSP, IPC validation),
electron-builder + electron-updater, Dockerfile, Gitea Actions CI/release
workflows, and SonarQube docker-compose setup. Also fixes two real bugs
found while writing tests: unawaited clipboard promises and a mermaid
container ref timing issue in CoachDrawingView.

Fixes lint-staged on Windows/Node 24 by invoking eslint/prettier via
`node <bin>.js` instead of their .cmd shims, which Node's child_process
now refuses to spawn without shell:true.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
william
2026-10-29 09:05:21 +01:00
co-authored by Claude Sonnet 5
parent 1959ddb41a
commit e9690a49f9
230 changed files with 22781 additions and 448 deletions
+38
View File
@@ -0,0 +1,38 @@
import { parentPort } from 'node:worker_threads'
import { writeFileSync, readdirSync, statSync, unlinkSync } from 'fs'
import { join } from 'path'
interface WriteJob {
filePath: string
png: Buffer
}
interface PurgeJob {
purgeDir: string
cutoff: number
}
// Tourne dans un worker_thread dedie : ecrit les PNG encodes et purge les anciens fichiers sur
// disque. L'encodage PNG lui-meme (nativeImage.toPNG()) reste dans le thread principal car les API
// Electron ne sont pas utilisables depuis un worker_thread ; seules les operations fichier (Node
// pur, aucune dependance Electron) sont deportees ici pour ne jamais occuper le thread JS
// principal pendant la capture continue du mode Coach.
parentPort?.on('message', (job: WriteJob | PurgeJob) => {
try {
if ('purgeDir' in job) {
for (const file of readdirSync(job.purgeDir)) {
const filePath = join(job.purgeDir, file)
if (statSync(filePath).mtimeMs < job.cutoff) unlinkSync(filePath)
}
parentPort?.postMessage({ ok: true })
} else {
writeFileSync(job.filePath, job.png)
parentPort?.postMessage({ ok: true, filePath: job.filePath })
}
} catch (error) {
parentPort?.postMessage({
ok: false,
error: error instanceof Error ? error.message : String(error)
})
}
})
+883
View File
@@ -0,0 +1,883 @@
import { app } from 'electron'
import { DatabaseSync } from 'node:sqlite'
import { join } from 'path'
import type {
AssessmentKind,
ComplianceCheck,
ConceptStatus,
CourseComplianceReport,
ExerciseDifficulty,
ExerciseStyle,
ModuleAssessment,
ModuleDetail,
ModuleDiagram,
ModuleDiagramKind,
SubjectProgress,
SubjectStatus
} from '../../shared/coach'
export type { ConceptStatus } from '../../shared/coach'
// Sequence d'intervalles (jours) approximant la courbe d'oubli d'Ebbinghaus : calculee cote code,
// jamais laissee a l'IA (source d'erreurs si elle devait calculer des dates elle-meme).
const REVIEW_INTERVALS_DAYS = [1, 3, 7, 16, 35]
const DAY_MS = 24 * 60 * 60 * 1000
let db: DatabaseSync | null = null
function addColumnIfMissing(
database: DatabaseSync,
table: string,
column: string,
type: string
): void {
try {
database.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`)
} catch {
// Colonne deja presente (node:sqlite n'a pas d'equivalent "ADD COLUMN IF NOT EXISTS") : ok.
}
}
function getDb(): DatabaseSync {
if (db) return db
const dbPath = join(app.getPath('userData'), 'coach.sqlite')
db = new DatabaseSync(dbPath)
db.exec(`
CREATE TABLE IF NOT EXISTS subjects (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
level TEXT,
created_at TEXT NOT NULL,
last_session_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS concepts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
subject_id INTEGER NOT NULL REFERENCES subjects(id),
name TEXT NOT NULL,
status TEXT NOT NULL,
last_reviewed_at TEXT NOT NULL,
UNIQUE(subject_id, name)
);
CREATE TABLE IF NOT EXISTS assessments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
subject_id INTEGER NOT NULL REFERENCES subjects(id),
concept TEXT,
question TEXT NOT NULL,
question_type TEXT NOT NULL,
options_json TEXT,
answer TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS module_diagrams (
id INTEGER PRIMARY KEY AUTOINCREMENT,
subject_id INTEGER NOT NULL REFERENCES subjects(id),
concept TEXT NOT NULL,
kind TEXT NOT NULL,
title TEXT NOT NULL,
data TEXT NOT NULL,
created_at TEXT NOT NULL
);
`)
addColumnIfMissing(db, 'concepts', 'next_review_at', 'TEXT')
addColumnIfMissing(db, 'concepts', 'interval_index', 'INTEGER NOT NULL DEFAULT 0')
addColumnIfMissing(db, 'concepts', 'reminded', 'INTEGER NOT NULL DEFAULT 0')
addColumnIfMissing(db, 'concepts', 'order_index', 'INTEGER NOT NULL DEFAULT 0')
addColumnIfMissing(db, 'concepts', 'locked', 'INTEGER NOT NULL DEFAULT 0')
addColumnIfMissing(db, 'concepts', 'theory_summary', 'TEXT')
addColumnIfMissing(db, 'subjects', 'research_summary', 'TEXT')
addColumnIfMissing(db, 'subjects', 'status', "TEXT NOT NULL DEFAULT 'researching'")
addColumnIfMissing(db, 'assessments', 'kind', "TEXT NOT NULL DEFAULT 'module'")
addColumnIfMissing(db, 'assessments', 'dont_know', 'INTEGER NOT NULL DEFAULT 0')
addColumnIfMissing(db, 'subjects', 'objective', 'TEXT')
addColumnIfMissing(db, 'assessments', 'difficulty', 'TEXT')
addColumnIfMissing(db, 'assessments', 'exercise_style', 'TEXT')
addColumnIfMissing(db, 'assessments', 'targets_common_error', 'TEXT')
return db
}
function upsertSubject(name: string, level?: string): number {
const now = new Date().toISOString()
const database = getDb()
const existing = database.prepare('SELECT id FROM subjects WHERE name = ?').get(name) as
{ id: number } | undefined
if (existing) {
database
.prepare('UPDATE subjects SET last_session_at = ?, level = COALESCE(?, level) WHERE id = ?')
.run(now, level ?? null, existing.id)
return existing.id
}
const result = database
.prepare('INSERT INTO subjects (name, level, created_at, last_session_at) VALUES (?, ?, ?, ?)')
.run(name, level ?? null, now, now)
return Number(result.lastInsertRowid)
}
function getSubjectId(name: string): number | undefined {
const row = getDb().prepare('SELECT id FROM subjects WHERE name = ?').get(name) as
{ id: number } | undefined
return row?.id
}
export function setSubjectLevel(subjectName: string, level: string): void {
upsertSubject(subjectName, level)
}
export function getSubjectLevel(subjectName: string): string | null {
const subjectId = getSubjectId(subjectName)
if (!subjectId) return null
const row = getDb().prepare('SELECT level FROM subjects WHERE id = ?').get(subjectId) as
{ level: string | null } | undefined
return row?.level ?? null
}
export function setResearchSummary(subjectName: string, summary: string): void {
const subjectId = upsertSubject(subjectName)
getDb().prepare('UPDATE subjects SET research_summary = ? WHERE id = ?').run(summary, subjectId)
}
export function setSubjectStatus(subjectName: string, status: SubjectStatus): void {
const subjectId = upsertSubject(subjectName)
getDb().prepare('UPDATE subjects SET status = ? WHERE id = ?').run(status, subjectId)
}
export function getResearchSummary(subjectName: string): string | null {
const subjectId = getSubjectId(subjectName)
if (!subjectId) return null
const row = getDb()
.prepare('SELECT research_summary FROM subjects WHERE id = ?')
.get(subjectId) as { research_summary: string | null } | undefined
return row?.research_summary ?? null
}
export function setSubjectObjective(subjectName: string, objective: string): void {
const subjectId = upsertSubject(subjectName)
getDb().prepare('UPDATE subjects SET objective = ? WHERE id = ?').run(objective, subjectId)
}
export function getSubjectObjective(subjectName: string): string | null {
const subjectId = getSubjectId(subjectName)
if (!subjectId) return null
const row = getDb().prepare('SELECT objective FROM subjects WHERE id = ?').get(subjectId) as
{ objective: string | null } | undefined
return row?.objective ?? null
}
/** Au moins une evaluation ecrite existe pour ce sujet (et ce concept/type si precises). */
export function hasAssessment(
subjectName: string,
concept?: string,
kind?: AssessmentKind
): boolean {
const subjectId = getSubjectId(subjectName)
if (!subjectId) return false
const conditions = ['subject_id = ?']
const values: (string | number)[] = [subjectId]
if (concept) {
conditions.push('concept = ?')
values.push(concept)
}
if (kind) {
conditions.push('kind = ?')
values.push(kind)
}
const row = getDb()
.prepare(`SELECT 1 FROM assessments WHERE ${conditions.join(' AND ')} LIMIT 1`)
.get(...values)
return row !== undefined
}
export function saveAssessment(
subjectName: string,
concept: string | null,
question: string,
type: string,
options: string[] | null,
answer: string,
kind: AssessmentKind,
dontKnow: boolean,
difficulty: ExerciseDifficulty | null = null,
exerciseStyle: ExerciseStyle | null = null,
targetsCommonError: string | null = null
): void {
const subjectId = upsertSubject(subjectName)
getDb()
.prepare(
`INSERT INTO assessments (subject_id, concept, question, question_type, options_json, answer, kind, dont_know, difficulty, exercise_style, targets_common_error, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
)
.run(
subjectId,
concept,
question,
type,
options ? JSON.stringify(options) : null,
answer,
kind,
dontKnow ? 1 : 0,
difficulty,
exerciseStyle,
targetsCommonError,
new Date().toISOString()
)
}
/** Au moins 2 difficultes distinctes parmi les evaluations kind="module" de ce module. */
export function hasMultipleDifficulties(subjectName: string, moduleName: string): boolean {
const subjectId = getSubjectId(subjectName)
if (!subjectId) return false
const rows = getDb()
.prepare(
`SELECT DISTINCT difficulty FROM assessments
WHERE subject_id = ? AND concept = ? AND kind = 'module' AND difficulty IS NOT NULL`
)
.all(subjectId, moduleName) as { difficulty: string }[]
return rows.length >= 2
}
/**
* Part des evaluations kind="module" repondues "Je ne sais pas" pour ce module — proxy pour "a
* reussi", pas seulement "a tente" (RÈGLE 8.3 de docs/Max_Regles_Strictes_Module_Coach.md : un
* module valide uniquement si l'utilisateur a reussi, pas juste essaye). Renvoie 1 (bloquant) s'il
* n'y a aucune evaluation.
*/
export function moduleDontKnowRatio(subjectName: string, moduleName: string): number {
const subjectId = getSubjectId(subjectName)
if (!subjectId) return 1
const rows = getDb()
.prepare(
`SELECT dont_know FROM assessments WHERE subject_id = ? AND concept = ? AND kind = 'module'`
)
.all(subjectId, moduleName) as { dont_know: number }[]
if (rows.length === 0) return 1
return rows.filter((r) => r.dont_know === 1).length / rows.length
}
export function upsertConceptStatus(
subjectName: string,
conceptName: string,
status: ConceptStatus
): void {
const subjectId = upsertSubject(subjectName)
const now = new Date().toISOString()
const database = getDb()
const existing = database
.prepare('SELECT interval_index FROM concepts WHERE subject_id = ? AND name = ?')
.get(subjectId, conceptName) as { interval_index: number } | undefined
let intervalIndex = existing?.interval_index ?? 0
let nextReviewAt: string | null = null
const reminded = 0
if (status === 'acquired') {
const intervalDays =
REVIEW_INTERVALS_DAYS[Math.min(intervalIndex, REVIEW_INTERVALS_DAYS.length - 1)] ?? 0
nextReviewAt = new Date(Date.now() + intervalDays * DAY_MS).toISOString()
intervalIndex = Math.min(intervalIndex + 1, REVIEW_INTERVALS_DAYS.length - 1)
} else if (status === 'to_review') {
intervalIndex = 0
nextReviewAt = new Date(Date.now() + (REVIEW_INTERVALS_DAYS[0] ?? 0) * DAY_MS).toISOString()
}
database
.prepare(
`INSERT INTO concepts (subject_id, name, status, last_reviewed_at, next_review_at, interval_index, reminded)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(subject_id, name) DO UPDATE SET
status = excluded.status,
last_reviewed_at = excluded.last_reviewed_at,
next_review_at = excluded.next_review_at,
interval_index = excluded.interval_index,
reminded = excluded.reminded`
)
.run(subjectId, conceptName, status, now, nextReviewAt, intervalIndex, reminded)
}
/** Ecrit/remplace le contenu theorique complet d'un module existant. */
export function setModuleTheory(subjectName: string, moduleName: string, content: string): boolean {
const subjectId = getSubjectId(subjectName)
if (!subjectId) return false
const result = getDb()
.prepare('UPDATE concepts SET theory_summary = ? WHERE subject_id = ? AND name = ?')
.run(content, subjectId, moduleName)
return result.changes > 0
}
export function saveModuleDiagram(
subjectName: string,
moduleName: string,
kind: ModuleDiagramKind,
title: string,
data: unknown
): void {
const subjectId = upsertSubject(subjectName)
getDb()
.prepare(
'INSERT INTO module_diagrams (subject_id, concept, kind, title, data, created_at) VALUES (?, ?, ?, ?, ?, ?)'
)
.run(subjectId, moduleName, kind, title, JSON.stringify(data), new Date().toISOString())
}
export interface ModuleInput {
name: string
}
/**
* Cree ou REVISE (ajoute/supprime/modifie) les modules d'un plan de cours, dans l'ordre : seul le
* premier est deverrouille. Remplacement complet par rapport au dernier appel (un module absent de
* la nouvelle liste est supprime), sauf si sa progression reelle doit etre protegee (deja `acquired`
* ou deja evalue via une evaluation `kind="module"`) — evite de perdre une progression reelle lors
* d'une revision du plan suite a l'evaluation initiale. Ne prend plus de contenu directement (voir
* ModuleInput) : le contenu deja ecrit (`theory_summary`, uniquement via write_module_content) est
* TOUJOURS preserve ici (plus aucun moyen de le court-circuiter ou de l'effacer via ce point
* d'entree — constate en test reel : un `theorySummary` sommaire glisse ici contournait entierement
* la validation stricte de write_module_content).
*/
export function createModules(subjectName: string, modules: ModuleInput[]): void {
const subjectId = upsertSubject(subjectName)
const now = new Date().toISOString()
const database = getDb()
const newNames = new Set(modules.map((m) => m.name))
const existing = database
.prepare('SELECT name, status FROM concepts WHERE subject_id = ?')
.all(subjectId) as { name: string; status: ConceptStatus }[]
for (const row of existing) {
if (newNames.has(row.name)) continue
const hasModuleAssessment = database
.prepare(
"SELECT 1 FROM assessments WHERE subject_id = ? AND concept = ? AND kind = 'module' LIMIT 1"
)
.get(subjectId, row.name)
if (row.status === 'acquired' || hasModuleAssessment) continue
database
.prepare('DELETE FROM concepts WHERE subject_id = ? AND name = ?')
.run(subjectId, row.name)
database
.prepare('DELETE FROM module_diagrams WHERE subject_id = ? AND concept = ?')
.run(subjectId, row.name)
}
modules.forEach((module, index) => {
database
.prepare(
`INSERT INTO concepts (subject_id, name, status, last_reviewed_at, order_index, locked)
VALUES (?, ?, 'not_started', ?, ?, ?)
ON CONFLICT(subject_id, name) DO UPDATE SET
order_index = excluded.order_index,
locked = excluded.locked`
)
.run(subjectId, module.name, now, index, index === 0 ? 0 : 1)
})
}
/** Tous les modules d'un sujet ont un contenu ecrit (write_module_content deja appele pour chacun). */
/**
* Vrai uniquement si CHAQUE module a un contenu present ET structurellement conforme (6 sections,
* longueurs minimales, etc. — voir validateModuleContent). Un contenu juste "non vide" ne suffit
* pas : constate en test reel, un `theorySummary` sommaire glisse ailleurs (desormais impossible,
* voir createModules) suffisait a tort a satisfaire cette verification.
*/
export function allModulesHaveContent(subjectName: string): boolean {
return listModules(subjectName).length > 0 && modulesMissingContent(subjectName).length === 0
}
/** Noms des modules d'un sujet dont le contenu est absent OU non conforme (RÈGLE du document). */
export function modulesMissingContent(subjectName: string): string[] {
const subjectId = getSubjectId(subjectName)
if (!subjectId) return []
const rows = getDb()
.prepare(
'SELECT name, theory_summary FROM concepts WHERE subject_id = ? ORDER BY order_index ASC'
)
.all(subjectId) as { name: string; theory_summary: string | null }[]
if (rows.length === 0) return []
return rows
.filter((r) => !r.theory_summary || validateModuleContent(r.theory_summary).length > 0)
.map((r) => r.name)
}
export interface ModuleRow {
name: string
status: ConceptStatus
locked: boolean
orderIndex: number
}
export function listModules(subjectName: string): ModuleRow[] {
const subjectId = getSubjectId(subjectName)
if (!subjectId) return []
const rows = getDb()
.prepare(
'SELECT name, status, locked, order_index FROM concepts WHERE subject_id = ? ORDER BY order_index ASC'
)
.all(subjectId) as {
name: string
status: ConceptStatus
locked: number
order_index: number
}[]
return rows.map((r) => ({
name: r.name,
status: r.status,
locked: r.locked === 1,
orderIndex: r.order_index
}))
}
/** Deverrouille le module dont order_index suit celui donne, s'il existe. */
export function unlockNextModule(subjectName: string, afterOrderIndex: number): void {
const subjectId = getSubjectId(subjectName)
if (!subjectId) return
getDb()
.prepare(
'UPDATE concepts SET locked = 0 WHERE subject_id = ? AND order_index = ? AND locked = 1'
)
.run(subjectId, afterOrderIndex + 1)
}
export function getModuleOrderIndex(subjectName: string, moduleName: string): number | null {
const subjectId = getSubjectId(subjectName)
if (!subjectId) return null
const row = getDb()
.prepare('SELECT order_index FROM concepts WHERE subject_id = ? AND name = ?')
.get(subjectId, moduleName) as { order_index: number } | undefined
return row?.order_index ?? null
}
export function areAllModulesAcquired(subjectName: string): boolean {
const modules = listModules(subjectName)
return modules.length > 0 && modules.every((m) => m.status === 'acquired')
}
export function getModuleDetail(subjectName: string, moduleName: string): ModuleDetail | null {
const subjectId = getSubjectId(subjectName)
if (!subjectId) return null
const database = getDb()
const module = database
.prepare(
'SELECT status, locked, theory_summary FROM concepts WHERE subject_id = ? AND name = ?'
)
.get(subjectId, moduleName) as
{ status: ConceptStatus; locked: number; theory_summary: string | null } | undefined
if (!module) return null
const assessmentRows = database
.prepare(
'SELECT question, answer, dont_know, difficulty, exercise_style, targets_common_error, created_at FROM assessments WHERE subject_id = ? AND concept = ? ORDER BY id ASC'
)
.all(subjectId, moduleName) as {
question: string
answer: string
dont_know: number
difficulty: ExerciseDifficulty | null
exercise_style: ExerciseStyle | null
targets_common_error: string | null
created_at: string
}[]
const assessments: ModuleAssessment[] = assessmentRows.map((a) => ({
question: a.question,
answer: a.answer,
dontKnow: a.dont_know === 1,
difficulty: a.difficulty,
exerciseStyle: a.exercise_style,
targetsCommonError: a.targets_common_error,
createdAt: a.created_at
}))
const diagramRows = database
.prepare(
'SELECT kind, title, data, created_at FROM module_diagrams WHERE subject_id = ? AND concept = ? ORDER BY id ASC'
)
.all(subjectId, moduleName) as {
kind: ModuleDiagramKind
title: string
data: string
created_at: string
}[]
const diagrams: ModuleDiagram[] = diagramRows.map((d) => ({
kind: d.kind,
title: d.title,
data: JSON.parse(d.data) as unknown,
createdAt: d.created_at
}))
return {
name: moduleName,
status: module.status,
locked: module.locked === 1,
theorySummary: module.theory_summary,
assessments,
diagrams
}
}
export interface DueReview {
conceptId: number
subject: string
concept: string
}
export function getDueReviews(nowIso: string): DueReview[] {
const rows = getDb()
.prepare(
`SELECT concepts.id as conceptId, subjects.name as subject, concepts.name as concept
FROM concepts JOIN subjects ON subjects.id = concepts.subject_id
WHERE concepts.next_review_at IS NOT NULL
AND concepts.next_review_at <= ?
AND concepts.reminded = 0`
)
.all(nowIso) as unknown as DueReview[]
return rows
}
export function markReminded(conceptId: number): void {
getDb().prepare('UPDATE concepts SET reminded = 1 WHERE id = ?').run(conceptId)
}
function stripAccents(text: string): string {
return text.normalize('NFD').replace(/[̀-ͯ]/g, '')
}
function sectionIndex(content: string, label: string): number {
return stripAccents(content).toLowerCase().indexOf(stripAccents(label).toLowerCase())
}
function countWords(text: string): number {
return text.trim().split(/\s+/).filter(Boolean).length
}
// Structure imposee par docs/Max_Regles_Strictes_Module_Coach.md (RÈGLE 1) : 6 sections obligatoires
// dans cet ordre, remplace l'ancienne structure a 5 sections (Accroche/Contexte/Idee centrale/
// Analogie/Exemple) devenue trop sommaire suite au retour utilisateur fournissant ce document.
export const REQUIRED_CONTENT_SECTIONS = [
'Accroche',
'Developpement theorique',
'Phase guidee',
'Exercices progressifs',
'Exercice de debogage',
'Synthese'
]
// Longueurs minimales par section (RÈGLE 2/3/7 et annexe du document) — seules les sections dont la
// longueur se verifie simplement par un comptage de mots sont contraintes ici ; les sous-sections
// tres fines (idee centrale 80 mots, analogie 60 mots...) ne sont pas verifiees individuellement,
// seulement leur section parente, pour rester un garde-fou robuste plutot qu'une analyse fragile.
const SECTION_MIN_WORDS = new Map<string, number>([
['Accroche', 150],
['Developpement theorique', 300],
['Synthese', 100]
])
/** Sections obligatoires absentes d'un contenu de module, selon la structure pedagogique imposee. */
export function missingContentSections(content: string): string[] {
return REQUIRED_CONTENT_SECTIONS.filter((s) => sectionIndex(content, s) === -1)
}
/**
* Verifie un contenu de module par rapport a docs/Max_Regles_Strictes_Module_Coach.md : sections
* presentes ET dans l'ordre, longueurs minimales, phase guidee avec au moins 3 etapes numerotees,
* au moins 6 exercices numerotes couvrant les 3 niveaux de difficulte, exercice de debogage
* mentionnant une erreur a trouver. Heuristique par comptage/mots-cles (comme le reste du pipeline
* Coach), pas une comprehension du contenu : un garde-fou reel mais pas une preuve de qualite.
*/
export function validateModuleContent(content: string): string[] {
const violations: string[] = []
const missing = missingContentSections(content)
if (missing.length > 0) {
violations.push(`Sections manquantes : ${missing.join(', ')}`)
return violations
}
const positions = REQUIRED_CONTENT_SECTIONS.map((label) => ({
label,
index: sectionIndex(content, label)
})).sort((a, b) => a.index - b.index)
if (positions.map((p) => p.label).join('|') !== REQUIRED_CONTENT_SECTIONS.join('|')) {
violations.push(
`Les sections ne sont pas dans l'ordre impose : ${REQUIRED_CONTENT_SECTIONS.join(' -> ')}`
)
}
for (const [i, current] of positions.entries()) {
const { label, index } = current
const next = positions[i + 1]
const end = next ? next.index : content.length
const sectionText = content.slice(index, end)
const minWords = SECTION_MIN_WORDS.get(label)
if (minWords) {
const words = countWords(sectionText)
if (words < minWords) {
violations.push(`Section "${label}" trop courte : ${words} mots (minimum ${minWords})`)
}
}
// Match sur le texte sans accents : le modele ecrit naturellement "ÉTAPE" (accentue), qui ne
// correspond jamais a /etape/i (code point different, pas juste une variante de casse) —
// constate en test reel : un module correctement structure etait rejete a chaque tentative.
const normalizedSection = stripAccents(sectionText).toLowerCase()
if (label === 'Phase guidee') {
const steps = normalizedSection.match(/etape\s*\d/g) ?? []
if (steps.length < 3) {
violations.push(
`Section "Phase guidee" : au moins 3 etapes numerotees requises ("ETAPE 1", "ETAPE 2"...), ${steps.length} trouvee(s)`
)
}
}
if (label === 'Exercices progressifs') {
const exercises = normalizedSection.match(/exercice\s*\d/g) ?? []
if (exercises.length < 6) {
violations.push(
`Section "Exercices progressifs" : au moins 6 exercices numerotes requis ("EXERCICE 1"...), ${exercises.length} trouve(s)`
)
}
for (const level of ['facile', 'moyen', 'difficile']) {
if (!normalizedSection.includes(level)) {
violations.push(`Section "Exercices progressifs" : aucun exercice de niveau "${level}"`)
}
}
}
if (label === 'Exercice de debogage') {
if (!normalizedSection.includes('erreur')) {
violations.push(
`Section "Exercice de debogage" : aucune mention d'une erreur a trouver/corriger`
)
}
}
}
return violations
}
/**
* Empeche de rediger/mettre a jour le contenu d'un module si un module ANTERIEUR (order_index plus
* petit) n'est pas encore acquis — demande utilisateur explicite : "interdire a Max de passer a la
* redaction du module suivant si le precedent n'a pas passe la validation". Ne s'applique qu'une
* fois le niveau enregistre (getSubjectLevel) : avant, tous les modules sont legitimement rediges
* d'un coup en phase de preparation initiale, avant la moindre evaluation.
*/
export function canWriteModuleContent(
subjectName: string,
moduleName: string
): { ok: boolean; blockedBy: string | null } {
if (!getSubjectLevel(subjectName)) return { ok: true, blockedBy: null }
const modules = listModules(subjectName)
const target = modules.find((m) => m.name === moduleName)
if (!target) return { ok: true, blockedBy: null }
const earlierUnacquired = modules.find(
(m) => m.orderIndex < target.orderIndex && m.status !== 'acquired'
)
return { ok: !earlierUnacquired, blockedBy: earlierUnacquired?.name ?? null }
}
const MIN_MODULES = 3
const MAX_MODULES_COMPLIANCE = 7
/**
* Rapport de conformite au guide pedagogique "methode prof", calcule uniquement a partir des
* donnees deja stockees (aucune confiance envers le modele) : rend auditable par l'utilisateur ce
* qu'un garde-fou technique isole ne peut pas garantir (cohérence globale, structure du contenu).
*/
export function getCourseComplianceReport(subjectName: string): CourseComplianceReport | null {
const subjectId = getSubjectId(subjectName)
if (!subjectId) return null
const database = getDb()
const subjectRow = database
.prepare('SELECT objective, research_summary FROM subjects WHERE id = ?')
.get(subjectId) as { objective: string | null; research_summary: string | null } | undefined
let research: Record<string, unknown>
try {
research = subjectRow?.research_summary
? (JSON.parse(subjectRow.research_summary) as Record<string, unknown>)
: {}
} catch {
research = {}
}
const keyConcepts: unknown[] = Array.isArray(research.keyConcepts) ? research.keyConcepts : []
const commonErrors: string[] = Array.isArray(research.commonErrors)
? (research.commonErrors as string[])
: []
const sources = Array.isArray(research.sources) ? (research.sources as { level?: number }[]) : []
const modules = listModules(subjectName)
const checks: ComplianceCheck[] = []
checks.push({
key: 'sources',
label: 'Recherche sourcee (docs/Max_Recherche_Sources_Coach.md)',
ok: sources.length > 0 && sources.some((s) => typeof s.level === 'number' && s.level <= 3),
detail:
sources.length > 0
? `${sources.length} source(s), dont ${sources.filter((s) => (s.level ?? 4) <= 3).length} de niveau 1-3`
: 'Aucune source enregistree'
})
checks.push({
key: 'objective',
label: 'Objectif final mesurable defini',
ok: !!subjectRow?.objective,
detail: subjectRow?.objective ?? 'Aucun objectif enregistre'
})
checks.push({
key: 'prerequisites',
label: 'Prerequis identifies',
ok: !!research.prerequisites,
detail: typeof research.prerequisites === 'string' ? research.prerequisites : 'Non renseigne'
})
checks.push({
key: 'keyConcepts',
label: '5 a 10 concepts cles identifies',
ok: keyConcepts.length >= 5 && keyConcepts.length <= 10,
detail: `${keyConcepts.length} concept(s)`
})
checks.push({
key: 'commonErrors',
label: '3 erreurs typiques identifiees',
ok: commonErrors.length >= 3,
detail: `${commonErrors.length} erreur(s)`
})
checks.push({
key: 'feynman',
label: 'Auto-verification Feynman faite',
ok: !!research.feynmanExplanation,
detail: typeof research.feynmanExplanation === 'string' ? 'Presente' : 'Absente'
})
checks.push({
key: 'moduleCount',
label: '3 a 7 modules',
ok: modules.length >= MIN_MODULES && modules.length <= MAX_MODULES_COMPLIANCE,
detail: `${modules.length} module(s)`
})
for (const module of modules) {
const moduleRow = database
.prepare('SELECT theory_summary FROM concepts WHERE subject_id = ? AND name = ?')
.get(subjectId, module.name) as { theory_summary: string | null } | undefined
const content = moduleRow?.theory_summary ?? ''
const violations = validateModuleContent(content)
checks.push({
key: `module-structure-${module.name}`,
label: `Contenu conforme (6 sections, RÈGLES) : "${module.name}"`,
ok: violations.length === 0,
detail: violations.length === 0 ? 'Conforme' : violations.join(' | ')
})
if (module.status === 'acquired') {
checks.push({
key: `module-difficulty-${module.name}`,
label: `Progression de difficulte respectee : "${module.name}"`,
ok: hasMultipleDifficulties(subjectName, module.name),
detail: hasMultipleDifficulties(subjectName, module.name)
? 'Au moins 2 difficultes distinctes'
: 'Une seule difficulte utilisee (ou aucune)'
})
}
const debugRow = database
.prepare(
`SELECT 1 FROM assessments WHERE subject_id = ? AND concept = ? AND kind = 'module'
AND exercise_style = 'debogage' AND targets_common_error IS NOT NULL LIMIT 1`
)
.get(subjectId, module.name)
checks.push({
key: `module-debug-${module.name}`,
label: `Exercice de debogage lie a une erreur typique : "${module.name}"`,
ok: debugRow !== undefined,
detail: debugRow !== undefined ? 'Present' : 'Absent'
})
}
const finalRow = database
.prepare(
`SELECT difficulty FROM assessments WHERE subject_id = ? AND kind = 'final' ORDER BY id DESC LIMIT 1`
)
.get(subjectId) as { difficulty: string | null } | undefined
checks.push({
key: 'finalDifficulty',
label: 'Evaluation finale exigeante (difficulte "difficile")',
ok: finalRow?.difficulty === 'difficile',
detail: finalRow?.difficulty ?? 'Pas encore evaluee'
})
const acquiredModules = modules.filter((m) => m.status === 'acquired')
if (acquiredModules.length > 0) {
const reviewRows = database
.prepare(
'SELECT COUNT(*) as count FROM concepts WHERE subject_id = ? AND status = ? AND next_review_at IS NOT NULL'
)
.get(subjectId, 'acquired') as { count: number }
checks.push({
key: 'reviewsScheduled',
label: 'Revisions programmees pour les modules acquis',
ok: reviewRows.count === acquiredModules.length,
detail: `${reviewRows.count}/${acquiredModules.length} module(s) acquis avec revision programmee`
})
}
return { subject: subjectName, checks }
}
export function getProgress(subjectName?: string): SubjectProgress[] {
const database = getDb()
const subjects = (
subjectName
? database.prepare('SELECT * FROM subjects WHERE name = ?').all(subjectName)
: database.prepare('SELECT * FROM subjects ORDER BY last_session_at DESC').all()
) as {
id: number
name: string
level: string | null
status: SubjectStatus
objective: string | null
last_session_at: string
}[]
return subjects.map((subject) => {
const concepts = database
.prepare(
'SELECT name, status, last_reviewed_at, next_review_at, locked, order_index FROM concepts WHERE subject_id = ? ORDER BY order_index ASC'
)
.all(subject.id) as {
name: string
status: ConceptStatus
last_reviewed_at: string
next_review_at: string | null
locked: number
order_index: number
}[]
return {
subject: subject.name,
level: subject.level,
status: subject.status,
objective: subject.objective,
lastSessionAt: subject.last_session_at,
concepts: concepts.map((c) => ({
name: c.name,
status: c.status,
lastReviewedAt: c.last_reviewed_at,
nextReviewAt: c.next_review_at,
locked: c.locked === 1,
orderIndex: c.order_index
}))
}
})
}
+123
View File
@@ -0,0 +1,123 @@
import { sendToRenderer } from '../windowBridge'
import type { CourseBuildState, CourseBuildStepStatus } from '../../shared/courseBuild'
/**
* Suit et affiche a l'utilisateur l'avancement de la construction d'un plan de cours (recherche,
* plan, redaction des modules, evaluation initiale, niveau, revision), pour que Max n'ait plus a
* l'annoncer a l'oral a chaque etape (demande utilisateur explicite) : le stepper remplace la
* narration vocale par un affichage visuel, pilote par code a partir des outils reellement appeles
* (jamais par ce que le modele dit avoir fait).
*/
const STEP_DEFS: { key: string; label: string }[] = [
{ key: 'recherche', label: 'Recherche approfondie' },
{ key: 'plan', label: 'Objectif et plan de modules' },
{ key: 'redaction', label: 'Redaction des modules' },
{ key: 'evaluation_initiale', label: 'Evaluation initiale' },
{ key: 'niveau', label: 'Niveau enregistre' },
{ key: 'revision', label: 'Ajustement du plan' }
]
interface InternalState {
subject: string
statuses: Map<string, CourseBuildStepStatus>
totalModules: number
writtenModules: number
sourceCount: number
}
let state: InternalState | null = null
function emit(): void {
if (!state) return
const payload: CourseBuildState = {
subject: state.subject,
steps: STEP_DEFS.map((def) => {
const detail =
def.key === 'redaction' && state!.totalModules > 0
? `${state!.writtenModules}/${state!.totalModules}`
: def.key === 'recherche' && state!.sourceCount > 0
? `${state!.sourceCount} source(s)`
: undefined
return {
key: def.key,
label: def.label,
status: state!.statuses.get(def.key) ?? 'pending',
...(detail !== undefined ? { detail } : {})
}
})
}
sendToRenderer('course-build-step', payload)
}
/**
* Efface le stepper explicitement (ex: au moment ou open_module_for_user ouvre le premier module,
* signe que la construction est terminee et remise a l'utilisateur). AUCUN masquage automatique par
* minuterie : un tour de voix dans ce pipeline peut prendre plusieurs dizaines de secondes a
* plusieurs minutes entre deux appels d'outils (constate en test reel), et un masquage par inactivite
* effaçait l'etat ENTIER (y compris les coches deja validees) avant l'etape suivante — l'utilisateur
* voyait alors des coches "se decocher" (demande utilisateur explicite : elles doivent rester).
*/
export function clearCourseBuild(): void {
state = null
sendToRenderer('course-build-step', null)
}
function ensureState(subject: string): InternalState {
if (!state || state.subject !== subject) {
state = {
subject,
statuses: new Map(STEP_DEFS.map((d) => [d.key, 'pending'])),
totalModules: 0,
writtenModules: 0,
sourceCount: 0
}
}
return state
}
/** A appeler apres l'execution reussie de chaque outil du pipeline Coach, avec ses arguments bruts. */
export function recordCourseBuildTool(toolName: string, args: Record<string, unknown>): void {
const subject = typeof args.subject === 'string' ? args.subject.trim() : null
if (!subject) return
const s = ensureState(subject)
switch (toolName) {
case 'research_topic':
s.statuses.set('recherche', 'done')
s.statuses.set('plan', 'active')
s.sourceCount = Array.isArray(args.sources) ? args.sources.length : 0
break
case 'generate_course_plan':
if (s.statuses.get('niveau') === 'done') {
s.statuses.set('revision', 'done')
} else {
s.statuses.set('plan', 'done')
s.totalModules = Array.isArray(args.modules) ? args.modules.length : 0
s.writtenModules = 0
s.statuses.set('redaction', s.totalModules > 0 ? 'active' : 'pending')
}
break
case 'write_module_content':
s.writtenModules += 1
if (s.totalModules > 0 && s.writtenModules >= s.totalModules) {
s.statuses.set('redaction', 'done')
s.statuses.set('evaluation_initiale', 'active')
}
break
case 'ask_written_exercise':
if (args.kind === 'initial') {
s.statuses.set('evaluation_initiale', 'done')
s.statuses.set('niveau', 'active')
}
break
case 'record_subject_level':
s.statuses.set('niveau', 'done')
break
default:
return
}
emit()
}
+154
View File
@@ -0,0 +1,154 @@
import { BrowserWindow, ipcMain, type IpcMainEvent } from 'electron'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'
import type { DrawShape } from '../../shared/drawing'
import { SECURE_WEB_PREFERENCES, blockExternalNavigation } from '../utils/windowSecurity'
let win: BrowserWindow | null = null
let windowReady: Promise<void> | null = null
// Fenetre normale et independante de l'avatar, meme pattern singleton que progressWindow.ts.
function ensureWindow(): { window: BrowserWindow; ready: Promise<void> } {
if (win && !win.isDestroyed()) return { window: win, ready: windowReady ?? Promise.resolve() }
win = new BrowserWindow({
width: 700,
height: 560,
title: 'Max — tableau',
alwaysOnTop: true,
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
...SECURE_WEB_PREFERENCES
}
})
blockExternalNavigation(win)
// Meme raison que exerciseWindow.ts : visible au-dessus de tout (y compris plein ecran), mais en
// dessous de l'avatar ('screen-saver') qui reste donc toujours devant.
win.setAlwaysOnTop(true, 'floating')
win.maximize()
win.on('closed', () => {
win = null
windowReady = null
})
const window = win
windowReady = new Promise((resolve) => {
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
void window.loadURL(`${process.env['ELECTRON_RENDERER_URL']}#coach-drawing`)
} else {
void window.loadFile(join(__dirname, '../renderer/index.html'), { hash: 'coach-drawing' })
}
if (window.webContents.isLoading()) {
window.webContents.once('did-finish-load', () => resolve())
} else {
resolve()
}
})
return { window, ready: windowReady }
}
/** Ouvre (ou reutilise) la fenetre et initialise le canvas (titre, dimensions, vide). */
export async function openDrawingWindow(
title: string,
width: number,
height: number
): Promise<void> {
const { window, ready } = ensureWindow()
window.show()
window.moveTop()
window.focus()
await ready
window.webContents.send('init-drawing', { title, width, height })
}
/**
* Revele une forme dans la fenetre deja ouverte, avec un audio optionnel (narration pas-a-pas).
* Attend l'accuse de reception du renderer (forme dessinee + audio termine) avant de se resoudre,
* pour que draw_schema puisse enchainer les formes au rythme de la narration.
*/
export function revealShape(
shape: DrawShape,
audio: ArrayBuffer | null,
timeoutMs = 20000
): Promise<void> {
return new Promise((resolve) => {
if (!win || win.isDestroyed()) {
resolve()
return
}
const window = win
const requestId = Math.random().toString(36).slice(2)
let settled = false
const finish = (): void => {
if (settled) return
settled = true
clearTimeout(timeout)
ipcMain.removeListener('shape-reveal-done', handler)
resolve()
}
const timeout = setTimeout(finish, timeoutMs)
function handler(_event: IpcMainEvent, id: string): void {
if (id !== requestId) return
finish()
}
ipcMain.on('shape-reveal-done', handler)
window.once('closed', finish)
window.webContents.send('reveal-shape', { requestId, shape, audio })
})
}
/** Rend un diagramme Mermaid (cycle/hierarchie/flux) dans la fenetre, d'un coup (pas de reveal
* noeud-par-noeud : la fiabilite du layout prime sur l'effet progressif pour ce type precis). */
export async function renderMermaid(title: string, mermaidCode: string): Promise<void> {
const { window, ready } = ensureWindow()
window.show()
window.moveTop()
window.focus()
await ready
return new Promise((resolve, reject) => {
const requestId = Math.random().toString(36).slice(2)
function handler(_event: IpcMainEvent, id: string, ok: boolean, error?: string): void {
if (id !== requestId) return
ipcMain.removeListener('mermaid-render-done', handler)
if (ok) resolve()
else reject(new Error(error ?? 'Echec du rendu Mermaid'))
}
ipcMain.on('mermaid-render-done', handler)
window.webContents.send('render-mermaid', { requestId, title, mermaidCode })
})
}
/** Joue une legende audio seule (sans forme associee), pour la narration sequencee de Mermaid. */
export function playCaption(audio: ArrayBuffer, timeoutMs = 20000): Promise<void> {
return new Promise((resolve) => {
if (!win || win.isDestroyed()) {
resolve()
return
}
const window = win
const requestId = Math.random().toString(36).slice(2)
let settled = false
const finish = (): void => {
if (settled) return
settled = true
clearTimeout(timeout)
ipcMain.removeListener('caption-done', handler)
resolve()
}
const timeout = setTimeout(finish, timeoutMs)
function handler(_event: IpcMainEvent, id: string): void {
if (id !== requestId) return
finish()
}
ipcMain.on('caption-done', handler)
window.once('closed', finish)
window.webContents.send('play-caption', { requestId, audio })
})
}
+105
View File
@@ -0,0 +1,105 @@
import { BrowserWindow, ipcMain, type IpcMainEvent } from 'electron'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'
import type { ExerciseFormAnswer, ExerciseFormItem } from '../../shared/coach'
import { SECURE_WEB_PREFERENCES, blockExternalNavigation } from '../utils/windowSecurity'
let win: BrowserWindow | null = null
// Delai avant fermeture automatique de la fenetre une fois le formulaire soumis (demande
// utilisateur explicite : la fenetre ne doit pas rester ouverte indefiniment apres soumission).
const AUTO_CLOSE_DELAY_MS = 2000
// Fenetre normale et independante de l'avatar et de la courbe d'apprentissage, meme pattern
// singleton que progressWindow.ts.
function ensureWindow(): BrowserWindow {
if (win && !win.isDestroyed()) return win
win = new BrowserWindow({
width: 520,
height: 480,
title: 'Max — exercice',
alwaysOnTop: true,
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
...SECURE_WEB_PREFERENCES
}
})
blockExternalNavigation(win)
// Niveau en dessous de l'avatar ('screen-saver') mais au-dessus de tout le reste, y compris une
// appli en plein ecran : sans ca, la fenetre pouvait s'ouvrir derriere le premier plan actuel et
// l'utilisateur devait la retrouver via la barre des taches (constate en test reel).
win.setAlwaysOnTop(true, 'floating')
win.maximize()
win.on('closed', () => {
win = null
})
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
void win.loadURL(`${process.env['ELECTRON_RENDERER_URL']}#coach-exercise`)
} else {
void win.loadFile(join(__dirname, '../renderer/index.html'), { hash: 'coach-exercise' })
}
return win
}
export interface QuestionInput {
question: string
type: ExerciseFormItem['type']
options: string[] | null
}
/**
* Ouvre la fenetre d'exercice, pose TOUTES les questions en une seule fois (formulaire groupe, pas
* une par une : demande utilisateur explicite) et attend la soumission de l'utilisateur. Renvoie un
* tableau de reponses (meme ordre que `questions`), `null` par entree si la fenetre est fermee sans
* soumission ou si le delai est depasse. La fenetre se ferme automatiquement 2 secondes apres
* soumission.
*/
export function requestWrittenAnswers(
questions: QuestionInput[],
timeoutMs = 30 * 60 * 1000
): Promise<(string | null)[]> {
return new Promise((resolve) => {
const window = ensureWindow()
window.show()
window.moveTop()
window.focus()
const requestId = Math.random().toString(36).slice(2)
const items: ExerciseFormItem[] = questions.map((q, index) => ({
id: String(index),
question: q.question,
type: q.type,
options: q.options
}))
let settled = false
const finish = (answers: (string | null)[]): void => {
if (settled) return
settled = true
clearTimeout(timeout)
ipcMain.removeListener('written-form-result', handler)
resolve(answers)
}
const timeout = setTimeout(() => finish(items.map(() => null)), timeoutMs)
function handler(_event: IpcMainEvent, id: string, answers: ExerciseFormAnswer[]): void {
if (id !== requestId) return
const byId = new Map(answers.map((a) => [a.id, a.answer]))
finish(items.map((item) => byId.get(item.id) ?? null))
setTimeout(() => {
if (win && !win.isDestroyed()) win.close()
}, AUTO_CLOSE_DELAY_MS)
}
ipcMain.on('written-form-result', handler)
window.once('closed', () => finish(items.map(() => null)))
const send = (): void => window.webContents.send('ask-written-form', { requestId, items })
if (window.webContents.isLoading()) {
window.webContents.once('did-finish-load', send)
} else {
send()
}
})
}
+60
View File
@@ -0,0 +1,60 @@
import type { DrawShape } from '../../../shared/drawing'
import { num } from './utils'
const PALETTE = ['#2a5fb8', '#b83a3a', '#3a9b5c', '#c98a1e', '#7a4ab8', '#1e9ab0']
interface Slice {
label?: string | undefined
value: number
color?: string | undefined
caption?: string | undefined
}
/**
* Cercle divise en secteurs (camembert) : les angles sont calcules proportionnellement par le
* code a partir des valeurs fournies, jamais devines par le modele.
*/
export function buildCircleSector(params: Record<string, unknown>): DrawShape[] {
const cx = num(params.cx, 250, 0, 2000)
const cy = num(params.cy, 220, 0, 2000)
const radius = num(params.radius, 140, 30, 800)
const rawSlices = Array.isArray(params.slices) ? params.slices : []
const slices: Slice[] = rawSlices
.map((s): Slice | null => {
if (typeof s !== 'object' || s === null) return null
const slice = s as Record<string, unknown>
const value = num(slice.value, 0, 0, 1e9)
if (value <= 0) return null
return {
label: typeof slice.label === 'string' ? slice.label : undefined,
value,
color: typeof slice.color === 'string' ? slice.color : undefined,
caption: typeof slice.caption === 'string' ? slice.caption : undefined
}
})
.filter((s): s is Slice => s !== null)
if (slices.length === 0) return []
const total = slices.reduce((sum, s) => sum + s.value, 0)
let current = -90 // demarre en haut (12h), sens horaire
return slices.map((slice, i) => {
const sweep = (slice.value / total) * 360
const shape: DrawShape = {
type: 'arc',
x: cx,
y: cy,
radius,
startAngle: current,
endAngle: current + sweep,
closed: true,
color: slice.color ?? PALETTE[i % PALETTE.length],
label: slice.label,
caption: slice.caption
}
current += sweep
return shape
})
}
+61
View File
@@ -0,0 +1,61 @@
import type { DrawShape } from '../../../shared/drawing'
import { num, str } from './utils'
interface Point {
x: number
y: number
label?: string | undefined
caption?: string | undefined
}
/**
* Axes de coordonnees perpendiculaires (toujours a angle droit par construction) avec points a
* tracer optionnels, pour l'algebre/la geometrie analytique.
*/
export function buildCoordinateAxes(params: Record<string, unknown>): DrawShape[] {
const x = num(params.x, 80, 0, 2000)
const y = num(params.y, 60, 0, 2000)
const width = num(params.width, 320, 80, 1500)
const height = num(params.height, 260, 80, 1500)
const color = str(params.color, '#333333')
const originX = x
const originY = y + height
const shapes: DrawShape[] = [
{ type: 'arrow', x: originX, y: originY, x2: originX + width, y2: originY, color },
{ type: 'arrow', x: originX, y: originY, x2: originX, y2: y, color },
{
type: 'text',
x: originX + width - 10,
y: originY + 18,
content: str(params.xLabel, 'x'),
color
},
{ type: 'text', x: originX - 16, y: y - 6, content: str(params.yLabel, 'y'), color }
]
const rawPoints = Array.isArray(params.points) ? params.points : []
for (const p of rawPoints) {
if (typeof p !== 'object' || p === null) continue
const point = p as Record<string, unknown>
const px = originX + num(point.x, 0, -width, width)
const py = originY - num(point.y, 0, -height, height)
const pt: Point = {
x: px,
y: py,
label: typeof point.label === 'string' ? point.label : undefined,
caption: typeof point.caption === 'string' ? point.caption : undefined
}
shapes.push({
type: 'circle',
x: pt.x,
y: pt.y,
radius: 4,
color: '#b83a3a',
label: pt.label,
caption: pt.caption
})
}
return shapes
}
+16
View File
@@ -0,0 +1,16 @@
import type { DrawShape } from '../../../shared/drawing'
import { buildRightTriangle } from './rightTriangle'
import { buildTriangle } from './triangle'
import { buildRegularPolygon } from './regularPolygon'
import { buildCircleSector } from './circleSector'
import { buildVennDiagram } from './vennDiagram'
import { buildCoordinateAxes } from './coordinateAxes'
export const PRESET_GENERATORS = new Map<string, (params: Record<string, unknown>) => DrawShape[]>([
['right_triangle', buildRightTriangle],
['triangle', buildTriangle],
['regular_polygon', buildRegularPolygon],
['circle_sector', buildCircleSector],
['venn_diagram', buildVennDiagram],
['coordinate_axes', buildCoordinateAxes]
])
+35
View File
@@ -0,0 +1,35 @@
import type { DrawShape } from '../../../shared/drawing'
import { num, str } from './utils'
/**
* Polygone regulier a N cotes (carre, pentagone, hexagone...) inscrit dans un cercle : les sommets
* sont toujours parfaitement espaces par construction, jamais devines par le modele.
*/
export function buildRegularPolygon(params: Record<string, unknown>): DrawShape[] {
const sides = Math.round(num(params.sides, 6, 3, 12))
const cx = num(params.cx, 250, 0, 2000)
const cy = num(params.cy, 220, 0, 2000)
const radius = num(params.radius, 140, 30, 800)
const color = str(params.color, '#2a5fb8')
const labels = Array.isArray(params.labels) ? params.labels.map((l) => String(l)) : []
const captions = Array.isArray(params.captions) ? params.captions.map((c) => String(c)) : []
const vertices = Array.from({ length: sides }, (_, i) => {
const angle = -Math.PI / 2 + (i * 2 * Math.PI) / sides
return { x: cx + radius * Math.cos(angle), y: cy + radius * Math.sin(angle) }
})
return vertices.map((vertex, i) => {
const next = vertices[(i + 1) % sides] ?? vertex
return {
type: 'line',
x: vertex.x,
y: vertex.y,
x2: next.x,
y2: next.y,
color,
label: labels.at(i),
caption: captions.at(i)
}
})
}
+59
View File
@@ -0,0 +1,59 @@
import type { DrawShape } from '../../../shared/drawing'
import { num, str, strOrUndefined } from './utils'
/**
* Triangle rectangle toujours geometriquement valide : angle droit fixe en bas-a-gauche, angle
* theta en haut. Le modele ne fournit que des labels/captions, jamais de coordonnees.
*/
export function buildRightTriangle(params: Record<string, unknown>): DrawShape[] {
const x = num(params.x, 120, 0, 2000)
const y = num(params.y, 80, 0, 2000)
const size = num(params.size, 220, 50, 800)
const color = str(params.color, '#2a5fb8')
const hypotenuseColor = str(params.hypotenuseColor, '#b83a3a')
return [
{
type: 'line',
x,
y,
x2: x,
y2: y + size,
color,
label: str(params.adjacentLabel, 'Adjacent'),
caption: strOrUndefined(params.adjacentCaption)
},
{
type: 'line',
x,
y: y + size,
x2: x + size,
y2: y + size,
color,
label: str(params.oppositeLabel, 'Opposé'),
caption: strOrUndefined(params.oppositeCaption)
},
{
type: 'line',
x,
y,
x2: x + size,
y2: y + size,
color: hypotenuseColor,
label: str(params.hypotenuseLabel, 'Hypoténuse'),
caption: strOrUndefined(params.hypotenuseCaption)
},
{ type: 'rect', x, y: y + size - 14, width: 14, height: 14, color: '#555555' },
{
type: 'arc',
x,
y,
radius: 28,
startAngle: 45,
endAngle: 90,
color: '#555555',
label: str(params.angleLabel, 'θ'),
caption: strOrUndefined(params.angleCaption)
}
]
}
+63
View File
@@ -0,0 +1,63 @@
import type { DrawShape } from '../../../shared/drawing'
import { num, str, strOrUndefined } from './utils'
/**
* Triangle quelconque (equilateral, isocele, scalene, rectangle...) toujours valide : decrit par
* une base, une hauteur et un decalage horizontal du sommet — jamais par 3 sommets devines par le
* modele (source d'incoherences). apexOffset = base/2 donne un triangle isocele, 0 ou base un
* triangle rectangle, toute autre valeur un triangle scalene.
*/
export function buildTriangle(params: Record<string, unknown>): DrawShape[] {
const x = num(params.x, 120, 0, 2000)
const y = num(params.y, 80, 0, 2000)
const base = num(params.base, 220, 40, 1000)
const height = num(params.height, 180, 40, 1000)
const apexOffset = num(params.apexOffset, base / 2, -500, 1500)
const color = str(params.color, '#2a5fb8')
const bottomLeft = { x, y: y + height }
const bottomRight = { x: x + base, y: y + height }
const apex = { x: x + apexOffset, y }
const shapes: DrawShape[] = [
{
type: 'line',
x: bottomLeft.x,
y: bottomLeft.y,
x2: bottomRight.x,
y2: bottomRight.y,
color,
label: strOrUndefined(params.baseLabel),
caption: strOrUndefined(params.baseCaption)
},
{
type: 'line',
x: bottomLeft.x,
y: bottomLeft.y,
x2: apex.x,
y2: apex.y,
color,
label: strOrUndefined(params.leftSideLabel),
caption: strOrUndefined(params.leftSideCaption)
},
{
type: 'line',
x: apex.x,
y: apex.y,
x2: bottomRight.x,
y2: bottomRight.y,
color,
label: strOrUndefined(params.rightSideLabel),
caption: strOrUndefined(params.rightSideCaption)
},
{
type: 'text',
x: apex.x - 6,
y: apex.y - 8,
content: str(params.apexLabel, ''),
color: '#555555',
caption: strOrUndefined(params.apexCaption)
}
]
return shapes.filter((shape) => shape.type !== 'text' || shape.content)
}
+13
View File
@@ -0,0 +1,13 @@
export function num(value: unknown, fallback: number, min = -1e6, max = 1e6): number {
const n = Number(value)
if (!Number.isFinite(n)) return fallback
return Math.min(Math.max(n, min), max)
}
export function str(value: unknown, fallback = ''): string {
return typeof value === 'string' && value.trim() ? value.trim() : fallback
}
export function strOrUndefined(value: unknown): string | undefined {
return typeof value === 'string' && value.trim() ? value.trim() : undefined
}
+38
View File
@@ -0,0 +1,38 @@
import type { DrawShape } from '../../../shared/drawing'
import { num, str } from './utils'
const PALETTE = ['#2a5fb8', '#b83a3a', '#3a9b5c']
/**
* Diagramme de Venn a 2 ou 3 cercles, disposition standard (cote-a-cote ou triangulaire) calculee
* par le code : le chevauchement est toujours coherent, jamais devine par le modele.
*/
export function buildVennDiagram(params: Record<string, unknown>): DrawShape[] {
const cx = num(params.cx, 300, 0, 2000)
const cy = num(params.cy, 220, 0, 2000)
const radius = num(params.radius, 110, 30, 500)
const rawLabels = Array.isArray(params.labels) ? params.labels : []
const labels = rawLabels.slice(0, 3).map((l) => (typeof l === 'string' ? l : undefined))
const count = Math.max(2, Math.min(3, labels.length || 2))
const centers =
count === 2
? [
{ x: cx - radius * 0.5, y: cy },
{ x: cx + radius * 0.5, y: cy }
]
: [
{ x: cx, y: cy - radius * 0.5 },
{ x: cx - radius * 0.55, y: cy + radius * 0.35 },
{ x: cx + radius * 0.55, y: cy + radius * 0.35 }
]
return centers.map((center, i) => ({
type: 'circle',
x: center.x,
y: center.y,
radius,
color: str((params.colors as unknown[] | undefined)?.at(i), PALETTE.at(i % PALETTE.length)),
label: labels.at(i)
}))
}
+58
View File
@@ -0,0 +1,58 @@
import { BrowserWindow } from 'electron'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'
import { SECURE_WEB_PREFERENCES, blockExternalNavigation } from '../utils/windowSecurity'
let win: BrowserWindow | null = null
export interface ModuleTarget {
subject: string
module: string
}
function sendNavigateToModule(window: BrowserWindow, target: ModuleTarget): void {
const send = (): void => window.webContents.send('navigate-to-module', target)
if (window.webContents.isLoading()) {
window.webContents.once('did-finish-load', send)
} else {
send()
}
}
// Fenetre normale et independante de l'avatar (qui continue de s'afficher a cote, inchange) :
// meme principe singleton que src/main/browser/browserWindow.ts, mais charge le renderer compile
// de l'app avec un hash different plutot qu'une URL externe.
export function openCoachProgressWindow(navigateTo?: ModuleTarget): void {
if (win && !win.isDestroyed()) {
win.show()
win.moveTop()
win.focus()
if (navigateTo) sendNavigateToModule(win, navigateTo)
return
}
win = new BrowserWindow({
width: 480,
height: 640,
title: "Max — courbe d'apprentissage",
alwaysOnTop: true,
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
...SECURE_WEB_PREFERENCES
}
})
blockExternalNavigation(win)
win.setAlwaysOnTop(true, 'floating')
win.maximize()
win.on('closed', () => {
win = null
})
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
void win.loadURL(`${process.env['ELECTRON_RENDERER_URL']}#coach-progress`)
} else {
void win.loadFile(join(__dirname, '../renderer/index.html'), { hash: 'coach-progress' })
}
if (navigateTo) sendNavigateToModule(win, navigateTo)
}
+40
View File
@@ -0,0 +1,40 @@
import { Notification } from 'electron'
import { synthesizeSpeech } from '../ai/elevenlabs'
import { sendToRenderer } from '../windowBridge'
import { getDueReviews, markReminded } from './coachStore'
const TICK_MS = 5 * 60 * 1000
async function checkDueReviews(): Promise<void> {
const due = getDueReviews(new Date().toISOString())
if (due.length === 0) return
const summary = due.map((d) => `${d.concept} (${d.subject})`).join(', ')
new Notification({
title: 'Revision due',
body: `A reviser : ${summary}`
}).show()
try {
const message = `C'est le moment de reviser : ${summary}. Repasse en mode apprentissage pour qu'on y travaille ensemble.`
const speech = await synthesizeSpeech(message)
const buffer = speech.buffer.slice(
speech.byteOffset,
speech.byteOffset + speech.byteLength
) as ArrayBuffer
sendToRenderer('proactive-speech', buffer)
} catch (error) {
console.error('[coach] echec annonce vocale de revision', error)
}
for (const review of due) markReminded(review.conceptId)
}
// Tourne independamment du mode actif : une revision peut etre signalee meme hors mode Coach.
export function startReviewScheduler(): void {
setInterval(() => {
checkDueReviews().catch((error) =>
console.error('[coach] echec verification des revisions', error)
)
}, TICK_MS)
}
+70
View File
@@ -0,0 +1,70 @@
import { app, desktopCapturer, screen } from 'electron'
import { Worker } from 'node:worker_threads'
import { existsSync, mkdirSync, readdirSync } from 'fs'
import { join } from 'path'
const CAPTURE_INTERVAL_MS = 1000
const ROLLING_WINDOW_MS = 7 * 60 * 60 * 1000
let worker: Worker | null = null
let intervalHandle: ReturnType<typeof setInterval> | null = null
function captureDir(): string {
const dir = join(app.getPath('userData'), 'coach-captures')
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
return dir
}
function ensureWorker(): Worker {
if (worker) return worker
worker = new Worker(join(__dirname, 'captureWorker.js'))
worker.on('error', (error) => console.error('[coach] erreur worker de capture', error))
return worker
}
async function captureOnce(): Promise<void> {
const display = screen.getPrimaryDisplay()
const sources = await desktopCapturer.getSources({
types: ['screen'],
thumbnailSize: display.size
})
const source = sources[0]
if (!source) return
const png = source.thumbnail.toPNG()
const filePath = join(captureDir(), `capture-${Date.now()}.png`)
ensureWorker().postMessage({ filePath, png })
}
function purgeOldCaptures(): void {
const cutoff = Date.now() - ROLLING_WINDOW_MS
ensureWorker().postMessage({ purgeDir: captureDir(), cutoff })
}
let tickCount = 0
export function startVisionCapture(): void {
if (intervalHandle) return
intervalHandle = setInterval(() => {
tickCount += 1
captureOnce().catch((error) => console.error('[coach] echec capture ecran', error))
if (tickCount % 60 === 0) purgeOldCaptures()
}, CAPTURE_INTERVAL_MS)
}
export function stopVisionCapture(): void {
if (intervalHandle) {
clearInterval(intervalHandle)
intervalHandle = null
}
}
export function getRecentCaptures(count: number): string[] {
const dir = captureDir()
if (!existsSync(dir)) return []
return readdirSync(dir)
.filter((f: string) => f.endsWith('.png'))
.sort()
.slice(-count)
.map((f: string) => join(dir, f))
}