diff --git a/Max API/src/sessions/agents/module.agent.spec.ts b/Max API/src/sessions/agents/module.agent.spec.ts new file mode 100644 index 0000000..716e4e9 --- /dev/null +++ b/Max API/src/sessions/agents/module.agent.spec.ts @@ -0,0 +1,440 @@ +import { ConflictException } from '@nestjs/common'; +import { Test, TestingModule } from '@nestjs/testing'; +import { PrismaService } from '../../prisma/prisma.service'; +import { OpenRouterService } from '../../llm/openrouter.service'; +import { ModuleAgent, StoredModuleContent } from './module.agent'; + +function words(n: number, base = 'mot'): string { + return new Array(n).fill(base).join(' '); +} + +function buildExercise(id: number, level: 'easy' | 'medium' | 'hard') { + return { + level, + context: `Contexte exercice ${id}`, + prompt: `Enonce exercice ${id}`, + hints: ['indice 1', 'indice 2', 'indice 3', 'indice 4', 'indice 5'], + correctAnswerInternal: `reponse-${id}`, + }; +} + +function buildValidAuthoredJson() { + return { + hook: words(160), + theory: { + coreIdea: words(70), + analogy: words(70), + formalDefinition: words(70), + workedExample: words(70), + counterExample: words(70), + }, + weDo: { + problem: 'Un probleme guide', + guidingQuestions: ['Question 1 ?', 'Question 2 ?', 'Question 3 ?'], + }, + exercises: [ + buildExercise(1, 'easy'), + buildExercise(2, 'easy'), + buildExercise(3, 'medium'), + buildExercise(4, 'medium'), + buildExercise(5, 'hard'), + buildExercise(6, 'hard'), + ], + debugExercise: { + codeOrReasoningWithBug: 'const x = 1 // bug', + language: 'typescript', + instruction: 'Trouve et corrige le bug.', + correctionInternal: 'const x = 2', + }, + synthesis: { + recap: words(40), + metacognitionQuestions: [words(10), words(10), words(10)], + feynmanPrompt: words(40), + }, + }; +} + +function buildStoredContent(): StoredModuleContent { + const authored = buildValidAuthoredJson(); + return { + ...authored, + exercises: authored.exercises.map((e, i) => ({ + id: `ex-${i + 1}`, + ...e, + })), + progress: { + currentAwaiting: { type: 'exercise', exerciseId: 'ex-1' }, + exercises: { + 'ex-1': { attempts: 0, passed: false, hintLevel: 0 }, + 'ex-2': { attempts: 0, passed: false, hintLevel: 0 }, + 'ex-3': { attempts: 0, passed: false, hintLevel: 0 }, + 'ex-4': { attempts: 0, passed: false, hintLevel: 0 }, + 'ex-5': { attempts: 0, passed: false, hintLevel: 0 }, + 'ex-6': { attempts: 0, passed: false, hintLevel: 0 }, + }, + debugPassed: false, + feynman: null, + }, + } as unknown as StoredModuleContent; +} + +describe('ModuleAgent', () => { + let agent: ModuleAgent; + const chat = jest.fn(); + const createModule = jest.fn< + Promise, + [{ data: { moduleIndex: number; status: string } }] + >(); + const updateModule = jest.fn< + Promise, + [{ where: { id: number }; data: { content: StoredModuleContent } }] + >(); + const prisma = { + sessionModule: { + findUnique: jest.fn(), + findMany: jest.fn(), + create: createModule, + update: updateModule, + }, + sessionCurriculum: { findUniqueOrThrow: jest.fn(), update: jest.fn() }, + sessionObjective: { findUniqueOrThrow: jest.fn() }, + sessionLevelAssessment: { findUniqueOrThrow: jest.fn() }, + sessionResearch: { findUniqueOrThrow: jest.fn() }, + session: { update: jest.fn() }, + }; + + beforeEach(async () => { + jest.clearAllMocks(); + prisma.sessionObjective.findUniqueOrThrow.mockResolvedValue({ + subject: 'Facturation', + professionalGoal: 'Facturer sans erreur', + duration: '2 semaines', + }); + prisma.sessionLevelAssessment.findUniqueOrThrow.mockResolvedValue({ + overallLevel: 'beginner', + }); + prisma.sessionResearch.findUniqueOrThrow.mockResolvedValue({ + corpus: { + subtopics: [ + { + subtopic: 'TVA', + summary: 'resume', + keyPoints: ['a'], + commonMistakes: ['b'], + }, + ], + }, + }); + prisma.sessionModule.findMany.mockResolvedValue([]); + + const module: TestingModule = await Test.createTestingModule({ + providers: [ + ModuleAgent, + { provide: PrismaService, useValue: prisma }, + { provide: OpenRouterService, useValue: { chat } }, + ], + }).compile(); + + agent = module.get(ModuleAgent); + }); + + describe('generateModule()', () => { + it('should return the existing public content when the module was already generated (idempotent)', async () => { + const content = buildStoredContent(); + prisma.sessionModule.findUnique.mockResolvedValueOnce({ + id: 1, + title: 'Module existant', + content, + }); + + const result = await agent.generateModule(1, 7, 1); + + expect(result.title).toBe('Module existant'); + expect(chat).not.toHaveBeenCalled(); + expect(prisma.sessionModule.create).not.toHaveBeenCalled(); + }); + + it('should generate and persist a valid module', async () => { + prisma.sessionModule.findUnique.mockResolvedValueOnce(null); + prisma.sessionCurriculum.findUniqueOrThrow.mockResolvedValueOnce({ + modules: [{ index: 1, title: 'Module 1', concept: 'concept-1' }], + }); + chat.mockResolvedValueOnce(JSON.stringify(buildValidAuthoredJson())); + + const result = await agent.generateModule(1, 7, 1); + + expect(result.title).toBe('Module 1'); + expect(result.exercises).toHaveLength(6); + expect(result.exercises[0].revealedHints).toEqual([]); + const createCall = createModule.mock.calls[0][0]; + expect(createCall.data.moduleIndex).toBe(1); + expect(createCall.data.status).toBe('generated'); + }); + + it('should throw ConflictException when the requested module index is not in the curriculum', async () => { + prisma.sessionModule.findUnique.mockResolvedValueOnce(null); + prisma.sessionCurriculum.findUniqueOrThrow.mockResolvedValueOnce({ + modules: [{ index: 1, title: 'Module 1', concept: 'concept-1' }], + }); + + await expect(agent.generateModule(1, 7, 2)).rejects.toThrow( + ConflictException, + ); + }); + + it('should retry once then throw when the module content fails validation (too short)', async () => { + prisma.sessionModule.findUnique.mockResolvedValueOnce(null); + prisma.sessionCurriculum.findUniqueOrThrow.mockResolvedValueOnce({ + modules: [{ index: 1, title: 'Module 1', concept: 'concept-1' }], + }); + const tooShort = { ...buildValidAuthoredJson(), hook: 'trop court' }; + chat.mockResolvedValueOnce(JSON.stringify(tooShort)); + chat.mockResolvedValueOnce(JSON.stringify(tooShort)); + + await expect(agent.generateModule(1, 7, 1)).rejects.toThrow(); + expect(chat).toHaveBeenCalledTimes(2); + expect(prisma.sessionModule.create).not.toHaveBeenCalled(); + }); + }); + + describe('submitExerciseAnswer()', () => { + it('should judge the answer, update progress, and recompute currentAwaiting', async () => { + const content = buildStoredContent(); + prisma.sessionModule.findUnique.mockResolvedValueOnce({ id: 1, content }); + chat.mockResolvedValueOnce( + JSON.stringify({ correct: true, feedback: 'Bonne reponse, car...' }), + ); + + const result = await agent.submitExerciseAnswer( + 1, + 7, + 1, + 'ex-1', + 'ma reponse', + ); + + expect(result).toEqual({ + correct: true, + feedback: 'Bonne reponse, car...', + }); + const updateCall = updateModule.mock.calls[0][0]; + expect(updateCall.data.content.progress.currentAwaiting).toEqual({ + type: 'exercise', + exerciseId: 'ex-2', + }); + }); + + it('should throw ConflictException for an unknown exercise id', async () => { + const content = buildStoredContent(); + prisma.sessionModule.findUnique.mockResolvedValueOnce({ id: 1, content }); + + await expect( + agent.submitExerciseAnswer(1, 7, 1, 'ex-unknown', 'reponse'), + ).rejects.toThrow(ConflictException); + }); + + it('should default to incorrect when the judge reply is not valid JSON', async () => { + const content = buildStoredContent(); + prisma.sessionModule.findUnique.mockResolvedValueOnce({ id: 1, content }); + chat.mockResolvedValueOnce('pas du json'); + + const result = await agent.submitExerciseAnswer( + 1, + 7, + 1, + 'ex-1', + 'reponse', + ); + + expect(result.correct).toBe(false); + }); + }); + + describe('requestHint()', () => { + it('should reveal hints one level at a time without calling the LLM', async () => { + const content = buildStoredContent(); + prisma.sessionModule.findUnique.mockResolvedValueOnce({ id: 1, content }); + + const result = await agent.requestHint(1, 1, 'ex-1'); + + expect(chat).not.toHaveBeenCalled(); + expect(result).toEqual({ level: 1, hint: 'indice 1' }); + }); + + it('should return null once all 5 hints are exhausted', async () => { + const content = buildStoredContent(); + content.progress.exercises['ex-1'].hintLevel = 5; + prisma.sessionModule.findUnique.mockResolvedValueOnce({ id: 1, content }); + + const result = await agent.requestHint(1, 1, 'ex-1'); + + expect(result).toEqual({ level: 5, hint: null }); + expect(prisma.sessionModule.update).not.toHaveBeenCalled(); + }); + }); + + describe('submitDebugCorrection()', () => { + it('should judge the correction against the internal correction and update progress', async () => { + const content = buildStoredContent(); + prisma.sessionModule.findUnique.mockResolvedValueOnce({ id: 1, content }); + chat.mockResolvedValueOnce( + JSON.stringify({ correct: true, feedback: 'Correction exacte.' }), + ); + + const result = await agent.submitDebugCorrection(1, 7, 1, 'const x = 2'); + + expect(result.correct).toBe(true); + const updateCall = updateModule.mock.calls[0][0]; + expect(updateCall.data.content.progress.debugPassed).toBe(true); + }); + }); + + describe('submitFeynmanExplanation()', () => { + it('should parse the feedback and store validation status', async () => { + const content = buildStoredContent(); + content.progress.debugPassed = true; + content.progress.exercises = Object.fromEntries( + Object.keys(content.progress.exercises).map((k) => [ + k, + { attempts: 1, passed: true, hintLevel: 0 }, + ]), + ); + prisma.sessionModule.findUnique.mockResolvedValueOnce({ id: 1, content }); + chat.mockResolvedValueOnce( + JSON.stringify({ strengths: ['clair'], gaps: [], validated: true }), + ); + + const result = await agent.submitFeynmanExplanation( + 1, + 7, + 1, + 'explication', + ); + + expect(result).toEqual({ + strengths: ['clair'], + gaps: [], + validated: true, + }); + const updateCall = updateModule.mock.calls[0][0]; + expect(updateCall.data.content.progress.currentAwaiting).toBeNull(); + expect(updateCall.data.content.progress.feynman).toEqual({ + submitted: true, + validated: true, + }); + }); + }); + + describe('completeModule()', () => { + const startEvaluation = jest.fn(); + + it('should report missing requirements when nothing is done yet', async () => { + const content = buildStoredContent(); + prisma.sessionModule.findUnique.mockResolvedValueOnce({ id: 1, content }); + + const result = await agent.completeModule(1, 7, 1, startEvaluation); + + expect(result).toEqual({ + completed: false, + missing: [ + '0/4 exercices reussis (minimum requis: 4/6)', + "l'exercice de debogage n'est pas encore reussi", + "le test Feynman n'est pas encore valide", + ], + }); + expect(prisma.sessionModule.update).not.toHaveBeenCalled(); + expect(startEvaluation).not.toHaveBeenCalled(); + }); + + it('should unlock and generate the next module when all requirements are met and a next module exists', async () => { + const content = buildStoredContent(); + content.progress.debugPassed = true; + content.progress.feynman = { submitted: true, validated: true }; + content.progress.exercises = Object.fromEntries( + Object.keys(content.progress.exercises).map((k, i) => [ + k, + { attempts: 1, passed: i < 4, hintLevel: 0 }, + ]), + ); + prisma.sessionModule.findUnique + .mockResolvedValueOnce({ id: 1, content }) + .mockResolvedValueOnce(null); + prisma.sessionCurriculum.findUniqueOrThrow + .mockResolvedValueOnce({ + modules: [ + { index: 1, title: 'Module 1', concept: 'c1', status: 'unlocked' }, + { index: 2, title: 'Module 2', concept: 'c2', status: 'locked' }, + ], + }) + .mockResolvedValueOnce({ + modules: [ + { index: 1, title: 'Module 1', concept: 'c1' }, + { index: 2, title: 'Module 2', concept: 'c2' }, + ], + }); + chat.mockResolvedValueOnce(JSON.stringify(buildValidAuthoredJson())); + + const result = await agent.completeModule(1, 7, 1, startEvaluation); + + expect(result).toEqual({ + completed: true, + nextModuleIndex: 2, + evaluationStarted: false, + }); + expect(prisma.sessionCurriculum.update).toHaveBeenCalledWith({ + where: { sessionId: 1 }, + data: { + modules: [ + { index: 1, title: 'Module 1', concept: 'c1', status: 'unlocked' }, + { index: 2, title: 'Module 2', concept: 'c2', status: 'unlocked' }, + ], + }, + }); + expect(startEvaluation).not.toHaveBeenCalled(); + }); + + it('should start the final evaluation when this was the last module', async () => { + const content = buildStoredContent(); + content.progress.debugPassed = true; + content.progress.feynman = { submitted: true, validated: true }; + content.progress.exercises = Object.fromEntries( + Object.keys(content.progress.exercises).map((k, i) => [ + k, + { attempts: 1, passed: i < 4, hintLevel: 0 }, + ]), + ); + prisma.sessionModule.findUnique.mockResolvedValueOnce({ id: 1, content }); + prisma.sessionCurriculum.findUniqueOrThrow.mockResolvedValueOnce({ + modules: [ + { index: 1, title: 'Module 1', concept: 'c1', status: 'unlocked' }, + ], + }); + + const result = await agent.completeModule(1, 7, 1, startEvaluation); + + expect(result).toEqual({ + completed: true, + nextModuleIndex: null, + evaluationStarted: true, + }); + expect(prisma.session.update).toHaveBeenCalledWith({ + where: { id: 1 }, + data: { status: 'evaluating' }, + }); + expect(startEvaluation).toHaveBeenCalledWith(1, 7); + }); + }); + + describe('getAllExercisePrompts()', () => { + it('should collect every exercise prompt and debug instruction across all modules', async () => { + const content = buildStoredContent(); + prisma.sessionModule.findMany.mockResolvedValueOnce([{ content }]); + + const prompts = await agent.getAllExercisePrompts(1); + + expect(prompts).toContain('Enonce exercice 1'); + expect(prompts).toContain('Trouve et corrige le bug.'); + expect(prompts).toHaveLength(7); + }); + }); +}); diff --git a/Max API/src/sessions/agents/module.agent.ts b/Max API/src/sessions/agents/module.agent.ts new file mode 100644 index 0000000..9bd263f --- /dev/null +++ b/Max API/src/sessions/agents/module.agent.ts @@ -0,0 +1,791 @@ +import { ConflictException, Injectable, Logger } from '@nestjs/common'; +import { Prisma } from '@prisma/client'; +import { PrismaService } from '../../prisma/prisma.service'; +import { OpenRouterService } from '../../llm/openrouter.service'; +import { buildModulePrompt } from '../prompts/module.prompt'; +import { ResearchCorpus } from './research.agent'; + +export type ExerciseLevel = 'easy' | 'medium' | 'hard'; + +export interface AuthoredExercise { + id: string; + level: ExerciseLevel; + context: string; + prompt: string; + hints: string[]; + correctAnswerInternal: string; +} + +export interface AuthoredDebugExercise { + codeOrReasoningWithBug: string; + language: string; + instruction: string; + correctionInternal: string; +} + +export interface AuthoredSynthesis { + recap: string; + metacognitionQuestions: string[]; + feynmanPrompt: string; +} + +export interface AuthoredTheory { + coreIdea: string; + analogy: string; + formalDefinition: string; + workedExample: string; + counterExample: string; +} + +export interface AuthoredWeDo { + problem: string; + guidingQuestions: string[]; +} + +/** + * Suivi de progression d'un module, stocke a l'interieur de session_module.content (pas de + * colonne dediee) : "currentAwaiting" dit au pipeline voix/texte unique (routeIncomingMessage, + * sessions.service.ts) a quoi un message libre de l'utilisateur doit etre interprete comme une + * reponse, sans qu'il ait besoin de "dire une formule magique" - decision prise cote code, jamais + * par le LLM. + */ +export interface ModuleProgress { + currentAwaiting: + | { type: 'exercise'; exerciseId: string } + | { type: 'debug' } + | { type: 'feynman' } + | null; + exercises: Record< + string, + { attempts: number; passed: boolean; hintLevel: number } + >; + debugPassed: boolean; + feynman: { submitted: boolean; validated: boolean } | null; +} + +export interface StoredModuleContent { + hook: string; + theory: AuthoredTheory; + weDo: AuthoredWeDo; + exercises: AuthoredExercise[]; + debugExercise: AuthoredDebugExercise; + synthesis: AuthoredSynthesis; + progress: ModuleProgress; +} + +/** Vue publique d'un module : jamais les champs "*Internal" (reponses/corrections), jamais les + * indices au-dela du niveau deja debloque pour chaque exercice. */ +export interface PublicModuleContent { + title: string; + hook: string; + theory: AuthoredTheory; + weDo: AuthoredWeDo; + exercises: { + id: string; + level: ExerciseLevel; + context: string; + prompt: string; + revealedHints: string[]; + passed: boolean; + }[]; + debugExercise: { + instruction: string; + codeOrReasoningWithBug: string; + language: string; + }; + synthesis: AuthoredSynthesis; + progress: ModuleProgress; +} + +export interface JudgeResult { + correct: boolean; + feedback: string; +} + +export interface FeynmanFeedback { + strengths: string[]; + gaps: string[]; + validated: boolean; +} + +export type CompleteModuleResult = + | { + completed: true; + nextModuleIndex: number | null; + evaluationStarted: boolean; + } + | { completed: false; missing: string[] }; + +interface RawModuleContent { + hook?: unknown; + theory?: { + coreIdea?: unknown; + analogy?: unknown; + formalDefinition?: unknown; + workedExample?: unknown; + counterExample?: unknown; + }; + weDo?: { problem?: unknown; guidingQuestions?: unknown }; + exercises?: unknown; + debugExercise?: { + codeOrReasoningWithBug?: unknown; + language?: unknown; + instruction?: unknown; + correctionInternal?: unknown; + }; + synthesis?: { + recap?: unknown; + metacognitionQuestions?: unknown; + feynmanPrompt?: unknown; + }; +} + +const MIN_HOOK_WORDS = 150; +const MIN_THEORY_WORDS = 300; +const MIN_SYNTHESIS_WORDS = 100; +const REQUIRED_HINTS_PER_EXERCISE = 5; +const REQUIRED_EXERCISES_PASSED = 4; +const MAX_VALIDATION_RETRIES = 1; + +function countWords(text: string): number { + return text + .trim() + .split(/\s+/) + .filter((w) => w.length > 0).length; +} + +/** + * Agent 6 du pipeline (docs/Max_System_Prompt.md + docs/Max Refonte Coach Freelance.md) : + * redige un module a la fois (6 sections obligatoires), puis gere les sous-interactions + * (exercice, indice, debogage, Feynman) toutes routees depuis le meme pipeline voix/texte + * unique via "currentAwaiting" - jamais de LLM qui decide quoi afficher. + */ +@Injectable() +export class ModuleAgent { + private readonly logger = new Logger(ModuleAgent.name); + + constructor( + private readonly prisma: PrismaService, + private readonly llm: OpenRouterService, + ) {} + + async generateModule( + sessionId: number, + userId: number, + moduleIndex: number, + ): Promise { + const existing = await this.prisma.sessionModule.findUnique({ + where: { sessionId_moduleIndex: { sessionId, moduleIndex } }, + }); + if (existing) { + return this.toPublicContent( + existing.title, + existing.content as unknown as StoredModuleContent, + ); + } + + const curriculum = await this.prisma.sessionCurriculum.findUniqueOrThrow({ + where: { sessionId }, + }); + const modules = curriculum.modules as unknown as { + index: number; + title: string; + concept: string; + }[]; + const target = modules.find((m) => m.index === moduleIndex); + if (!target) { + throw new ConflictException( + `Module ${moduleIndex} introuvable dans le curriculum de cette session.`, + ); + } + + const objective = await this.prisma.sessionObjective.findUniqueOrThrow({ + where: { sessionId }, + }); + const level = await this.prisma.sessionLevelAssessment.findUniqueOrThrow({ + where: { sessionId }, + }); + const research = await this.prisma.sessionResearch.findUniqueOrThrow({ + where: { sessionId }, + }); + const previousModules = await this.prisma.sessionModule.findMany({ + where: { sessionId, moduleIndex: { lt: moduleIndex } }, + orderBy: { moduleIndex: 'asc' }, + }); + + const prompt = buildModulePrompt({ + index: moduleIndex, + title: target.title, + concept: target.concept, + objectiveSummary: `${objective.subject} pour ${objective.professionalGoal}, en ${objective.duration}`, + levelSummary: level.overallLevel, + corpusSummary: this.summarizeCorpus( + research.corpus as unknown as ResearchCorpus, + ), + previousModulesSummary: + previousModules.map((m) => m.title).join(', ') || 'aucun', + }); + + let authored = await this.requestAndValidate(userId, prompt); + for ( + let attempt = 0; + !authored && attempt < MAX_VALIDATION_RETRIES; + attempt++ + ) { + this.logger.warn( + `Module ${moduleIndex} non conforme (mots minimum / structure), nouvelle tentative (${attempt + 1})`, + ); + authored = await this.requestAndValidate(userId, prompt); + } + if (!authored) { + throw new Error( + `L'Agent 6 (Redacteur) n'a pas produit de module ${moduleIndex} conforme apres relance.`, + ); + } + + const progress: ModuleProgress = { + currentAwaiting: { + type: 'exercise', + exerciseId: authored.exercises[0].id, + }, + exercises: Object.fromEntries( + authored.exercises.map((e) => [ + e.id, + { attempts: 0, passed: false, hintLevel: 0 }, + ]), + ), + debugPassed: false, + feynman: null, + }; + const content: StoredModuleContent = { ...authored, progress }; + + await this.prisma.sessionModule.create({ + data: { + sessionId, + moduleIndex, + title: target.title, + content: content as unknown as Prisma.InputJsonValue, + status: 'generated', + }, + }); + + return this.toPublicContent(target.title, content); + } + + async submitExerciseAnswer( + sessionId: number, + userId: number, + moduleIndex: number, + exerciseId: string, + answer: string, + ): Promise { + const { record, content } = await this.loadModule(sessionId, moduleIndex); + const exercise = content.exercises.find((e) => e.id === exerciseId); + const progressEntry = Reflect.get( + content.progress.exercises, + exerciseId, + ) as ModuleProgress['exercises'][string] | undefined; + if (!exercise || !progressEntry) { + throw new ConflictException(`Exercice ${exerciseId} introuvable.`); + } + + const result = await this.judge( + userId, + `Exercice (niveau ${exercise.level}) : ${exercise.prompt}`, + exercise.correctAnswerInternal, + answer, + ); + + progressEntry.attempts += 1; + progressEntry.passed = progressEntry.passed || result.correct; + content.progress.currentAwaiting = this.nextAwaiting(content); + await this.saveContent(record.id, content); + return result; + } + + /** Pur lookup dans les indices deja rediges par l'Agent 6 - aucun appel LLM necessaire. */ + async requestHint( + sessionId: number, + moduleIndex: number, + exerciseId: string, + ): Promise<{ level: number; hint: string | null }> { + const { record, content } = await this.loadModule(sessionId, moduleIndex); + const exercise = content.exercises.find((e) => e.id === exerciseId); + const progressEntry = Reflect.get( + content.progress.exercises, + exerciseId, + ) as ModuleProgress['exercises'][string] | undefined; + if (!exercise || !progressEntry) { + throw new ConflictException(`Exercice ${exerciseId} introuvable.`); + } + if (progressEntry.hintLevel >= REQUIRED_HINTS_PER_EXERCISE) { + return { level: progressEntry.hintLevel, hint: null }; + } + progressEntry.hintLevel += 1; + await this.saveContent(record.id, content); + return { + level: progressEntry.hintLevel, + hint: exercise.hints[progressEntry.hintLevel - 1] ?? null, + }; + } + + async submitDebugCorrection( + sessionId: number, + userId: number, + moduleIndex: number, + correction: string, + ): Promise { + const { record, content } = await this.loadModule(sessionId, moduleIndex); + const result = await this.judge( + userId, + `Correction de l'erreur intentionnelle : ${content.debugExercise.instruction}`, + content.debugExercise.correctionInternal, + correction, + ); + content.progress.debugPassed = + content.progress.debugPassed || result.correct; + content.progress.currentAwaiting = this.nextAwaiting(content); + await this.saveContent(record.id, content); + return result; + } + + async submitFeynmanExplanation( + sessionId: number, + userId: number, + moduleIndex: number, + explanation: string, + ): Promise { + const { record, content } = await this.loadModule(sessionId, moduleIndex); + const raw = await this.llm.chat( + userId, + [ + { + role: 'system', + content: + 'Tu evalues une explication "test de Feynman" (expliquer un concept comme a quelqu\'un ' + + `qui n'y connait rien). Concept : ${content.theory.coreIdea}. ` + + 'Reponds UNIQUEMENT avec ce JSON strict : ' + + '{"strengths": ["..."], "gaps": ["..."], "validated": true | false}. ' + + '"validated" est true seulement si l\'explication est correcte et ne presuppose aucun jargon non explique.', + }, + { role: 'user', content: explanation }, + ], + { jsonResponse: true }, + ); + const feedback = this.parseFeynmanFeedback(raw); + content.progress.feynman = { + submitted: true, + validated: feedback.validated, + }; + content.progress.currentAwaiting = this.nextAwaiting(content); + await this.saveContent(record.id, content); + return feedback; + } + + /** + * Garde-fou de validation (docs/Max Refonte Coach Freelance.md) : >=4/6 exercices reussis ET + * debogage reussi ET Feynman complete (et valide). Calcule integralement cote code a partir de + * "progress" - jamais une decision du LLM. Si valide : deverrouille/genere le module suivant + * (meme principe d'enchainement synchrone que confirmObjective/confirmLevel), ou demarre + * l'Agent 7 si c'etait le dernier module. + */ + async completeModule( + sessionId: number, + userId: number, + moduleIndex: number, + startEvaluation: (sessionId: number, userId: number) => Promise, + ): Promise { + const { record, content } = await this.loadModule(sessionId, moduleIndex); + const missing: string[] = []; + const passedCount = Object.values(content.progress.exercises).filter( + (e) => e.passed, + ).length; + if (passedCount < REQUIRED_EXERCISES_PASSED) { + missing.push( + `${passedCount}/${REQUIRED_EXERCISES_PASSED} exercices reussis (minimum requis: ${REQUIRED_EXERCISES_PASSED}/6)`, + ); + } + if (!content.progress.debugPassed) { + missing.push("l'exercice de debogage n'est pas encore reussi"); + } + if (!content.progress.feynman?.validated) { + missing.push("le test Feynman n'est pas encore valide"); + } + if (missing.length > 0) { + return { completed: false, missing }; + } + + await this.prisma.sessionModule.update({ + where: { id: record.id }, + data: { status: 'completed', completedAt: new Date() }, + }); + + const curriculum = await this.prisma.sessionCurriculum.findUniqueOrThrow({ + where: { sessionId }, + }); + const modules = curriculum.modules as unknown as { + index: number; + status: string; + }[]; + const nextModule = modules.find((m) => m.index === moduleIndex + 1); + + if (nextModule) { + const updatedModules = modules.map((m) => + m.index === nextModule.index ? { ...m, status: 'unlocked' } : m, + ); + await this.prisma.sessionCurriculum.update({ + where: { sessionId }, + data: { modules: updatedModules }, + }); + await this.generateModule(sessionId, userId, nextModule.index); + return { + completed: true, + nextModuleIndex: nextModule.index, + evaluationStarted: false, + }; + } + + await this.prisma.session.update({ + where: { id: sessionId }, + data: { status: 'evaluating' }, + }); + await startEvaluation(sessionId, userId); + return { completed: true, nextModuleIndex: null, evaluationStarted: true }; + } + + /** Expose, pour l'Agent 7, tous les enonces d'exercices deja utilises dans les modules - pour + * garantir que le cas de mission final n'en reprend aucun (docs/Max Refonte Coach + * Freelance.md, "jamais un exercice deja vu pendant les modules"). */ + async getAllExercisePrompts(sessionId: number): Promise { + const modules = await this.prisma.sessionModule.findMany({ + where: { sessionId }, + }); + const prompts: string[] = []; + for (const m of modules) { + const content = m.content as unknown as StoredModuleContent; + prompts.push(...content.exercises.map((e) => e.prompt)); + prompts.push(content.debugExercise.instruction); + } + return prompts; + } + + private nextAwaiting( + content: StoredModuleContent, + ): ModuleProgress['currentAwaiting'] { + const nextUnpassedExercise = content.exercises.find( + (e) => + !( + Reflect.get(content.progress.exercises, e.id) as + ModuleProgress['exercises'][string] | undefined + )?.passed, + ); + if (nextUnpassedExercise) { + return { type: 'exercise', exerciseId: nextUnpassedExercise.id }; + } + if (!content.progress.debugPassed) return { type: 'debug' }; + if (!content.progress.feynman?.validated) return { type: 'feynman' }; + return null; + } + + private async judge( + userId: number, + questionContext: string, + referenceAnswer: string, + userAnswer: string, + ): Promise { + const raw = await this.llm.chat( + userId, + [ + { + role: 'system', + content: + "Tu juges si la reponse de l'utilisateur est correcte par rapport a la reponse de " + + `reference. Contexte : ${questionContext}. Reponse de reference : ${referenceAnswer}. ` + + 'Reponds UNIQUEMENT avec ce JSON strict : {"correct": true | false, "feedback": "..."}. ' + + '"feedback" precise TOUJOURS ce qui est juste ou faux et pourquoi - jamais seulement ' + + '"Bravo !" ou "Non."', + }, + { role: 'user', content: userAnswer }, + ], + { jsonResponse: true }, + ); + return this.parseJudgeResult(raw); + } + + private parseJudgeResult(raw: string): JudgeResult { + try { + const parsed = JSON.parse(raw) as { + correct?: unknown; + feedback?: unknown; + }; + return { + correct: parsed.correct === true, + feedback: + typeof parsed.feedback === 'string' + ? parsed.feedback + : 'Reponse non evaluable, reessaie avec plus de details.', + }; + } catch { + this.logger.warn( + `Jugement d'exercice non-JSON, rejete par prudence: ${raw}`, + ); + return { + correct: false, + feedback: 'Reponse non evaluable, reessaie avec plus de details.', + }; + } + } + + private parseFeynmanFeedback(raw: string): FeynmanFeedback { + try { + const parsed = JSON.parse(raw) as { + strengths?: unknown; + gaps?: unknown; + validated?: unknown; + }; + return { + strengths: Array.isArray(parsed.strengths) + ? parsed.strengths.map(String) + : [], + gaps: Array.isArray(parsed.gaps) ? parsed.gaps.map(String) : [], + validated: parsed.validated === true, + }; + } catch { + this.logger.warn( + `Evaluation Feynman non-JSON, rejetee par prudence: ${raw}`, + ); + return { + strengths: [], + gaps: ['Explication non evaluable.'], + validated: false, + }; + } + } + + private async requestAndValidate( + userId: number, + prompt: string, + ): Promise | null> { + const raw = await this.llm.chat( + userId, + [{ role: 'system', content: prompt }], + { jsonResponse: true }, + ); + return this.parseAndValidate(raw); + } + + private parseAndValidate( + raw: string, + ): Omit | null { + let data: RawModuleContent; + try { + data = JSON.parse(raw) as RawModuleContent; + } catch { + this.logger.warn(`Module non-JSON, rejete: ${raw}`); + return null; + } + + if ( + typeof data.hook !== 'string' || + countWords(data.hook) < MIN_HOOK_WORDS + ) { + return null; + } + const theory = data.theory; + if ( + !theory || + typeof theory.coreIdea !== 'string' || + typeof theory.analogy !== 'string' || + typeof theory.formalDefinition !== 'string' || + typeof theory.workedExample !== 'string' || + typeof theory.counterExample !== 'string' + ) { + return null; + } + const theoryWordCount = [ + theory.coreIdea, + theory.analogy, + theory.formalDefinition, + theory.workedExample, + theory.counterExample, + ].reduce((sum, t) => sum + countWords(t), 0); + if (theoryWordCount < MIN_THEORY_WORDS) return null; + + if ( + !data.weDo || + typeof data.weDo.problem !== 'string' || + !Array.isArray(data.weDo.guidingQuestions) || + data.weDo.guidingQuestions.length < 3 + ) { + return null; + } + + const exercises = this.parseExercises(data.exercises); + if (!exercises) return null; + + const debug = data.debugExercise; + if ( + !debug || + typeof debug.codeOrReasoningWithBug !== 'string' || + typeof debug.language !== 'string' || + typeof debug.instruction !== 'string' || + typeof debug.correctionInternal !== 'string' + ) { + return null; + } + + const synthesis = data.synthesis; + if ( + !synthesis || + typeof synthesis.recap !== 'string' || + !Array.isArray(synthesis.metacognitionQuestions) || + synthesis.metacognitionQuestions.length < 3 || + typeof synthesis.feynmanPrompt !== 'string' + ) { + return null; + } + const metacognitionWordCount = ( + synthesis.metacognitionQuestions as unknown[] + ).reduce((sum, q) => sum + countWords(String(q)), 0); + const synthesisWordCount = + countWords(synthesis.recap) + + metacognitionWordCount + + countWords(synthesis.feynmanPrompt); + if (synthesisWordCount < MIN_SYNTHESIS_WORDS) return null; + + return { + hook: data.hook, + theory: theory as AuthoredTheory, + weDo: { + problem: data.weDo.problem, + guidingQuestions: data.weDo.guidingQuestions.map(String), + }, + exercises, + debugExercise: { + codeOrReasoningWithBug: debug.codeOrReasoningWithBug, + language: debug.language, + instruction: debug.instruction, + correctionInternal: debug.correctionInternal, + }, + synthesis: { + recap: synthesis.recap, + metacognitionQuestions: synthesis.metacognitionQuestions.map(String), + feynmanPrompt: synthesis.feynmanPrompt, + }, + }; + } + + private parseExercises(raw: unknown): AuthoredExercise[] | null { + if (!Array.isArray(raw) || raw.length !== 6) return null; + const exercises: AuthoredExercise[] = []; + let easy = 0; + let medium = 0; + let hard = 0; + let index = 0; + for (const rawItem of raw) { + index += 1; + const item = rawItem as { + level?: unknown; + context?: unknown; + prompt?: unknown; + hints?: unknown; + correctAnswerInternal?: unknown; + }; + if ( + !['easy', 'medium', 'hard'].includes(String(item.level)) || + typeof item.context !== 'string' || + typeof item.prompt !== 'string' || + typeof item.correctAnswerInternal !== 'string' || + !Array.isArray(item.hints) || + item.hints.length !== REQUIRED_HINTS_PER_EXERCISE + ) { + return null; + } + if (item.level === 'easy') easy += 1; + else if (item.level === 'medium') medium += 1; + else hard += 1; + + exercises.push({ + id: `ex-${index}`, + level: item.level as ExerciseLevel, + context: item.context, + prompt: item.prompt, + hints: item.hints.map(String), + correctAnswerInternal: item.correctAnswerInternal, + }); + } + if (easy !== 2 || medium !== 2 || hard !== 2) return null; + return exercises; + } + + private summarizeCorpus(corpus: ResearchCorpus): string { + return corpus.subtopics + .map( + (s) => + `${s.subtopic}: ${s.summary} | points cles: ${s.keyPoints.join('; ')} | erreurs frequentes: ${s.commonMistakes.join('; ')}`, + ) + .join(' || '); + } + + private async loadModule( + sessionId: number, + moduleIndex: number, + ): Promise<{ + record: { id: number }; + content: StoredModuleContent; + }> { + const record = await this.prisma.sessionModule.findUnique({ + where: { sessionId_moduleIndex: { sessionId, moduleIndex } }, + }); + if (!record) { + throw new ConflictException( + `Module ${moduleIndex} introuvable pour cette session.`, + ); + } + return { + record, + content: record.content as unknown as StoredModuleContent, + }; + } + + private async saveContent( + recordId: number, + content: StoredModuleContent, + ): Promise { + await this.prisma.sessionModule.update({ + where: { id: recordId }, + data: { content: content as unknown as Prisma.InputJsonValue }, + }); + } + + private toPublicContent( + title: string, + content: StoredModuleContent, + ): PublicModuleContent { + return { + title, + hook: content.hook, + theory: content.theory, + weDo: content.weDo, + exercises: content.exercises.map((e) => { + const progress = Reflect.get(content.progress.exercises, e.id) as + ModuleProgress['exercises'][string] | undefined; + return { + id: e.id, + level: e.level, + context: e.context, + prompt: e.prompt, + revealedHints: e.hints.slice(0, progress?.hintLevel ?? 0), + passed: progress?.passed ?? false, + }; + }), + debugExercise: { + instruction: content.debugExercise.instruction, + codeOrReasoningWithBug: content.debugExercise.codeOrReasoningWithBug, + language: content.debugExercise.language, + }, + synthesis: content.synthesis, + progress: content.progress, + }; + } +} diff --git a/Max API/src/sessions/dto/debug-correction.dto.ts b/Max API/src/sessions/dto/debug-correction.dto.ts new file mode 100644 index 0000000..fc84a5b --- /dev/null +++ b/Max API/src/sessions/dto/debug-correction.dto.ts @@ -0,0 +1,10 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { IsString, MaxLength, MinLength } from 'class-validator'; + +export class DebugCorrectionDto { + @ApiProperty({ example: 'La boucle doit commencer a 0, pas a 1.' }) + @IsString() + @MinLength(1) + @MaxLength(4000) + correction!: string; +} diff --git a/Max API/src/sessions/dto/exercise-answer.dto.ts b/Max API/src/sessions/dto/exercise-answer.dto.ts new file mode 100644 index 0000000..e0758be --- /dev/null +++ b/Max API/src/sessions/dto/exercise-answer.dto.ts @@ -0,0 +1,18 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { IsString, MaxLength, MinLength } from 'class-validator'; + +export class ExerciseAnswerDto { + @ApiProperty({ example: 'ex-1' }) + @IsString() + @MinLength(1) + @MaxLength(50) + exerciseId!: string; + + @ApiProperty({ + example: 'Je ferais pivoter le vecteur avec une matrice de rotation.', + }) + @IsString() + @MinLength(1) + @MaxLength(4000) + answer!: string; +} diff --git a/Max API/src/sessions/dto/feynman-feedback-response.dto.ts b/Max API/src/sessions/dto/feynman-feedback-response.dto.ts new file mode 100644 index 0000000..f67f2c5 --- /dev/null +++ b/Max API/src/sessions/dto/feynman-feedback-response.dto.ts @@ -0,0 +1,8 @@ +import { ApiProperty } from '@nestjs/swagger'; + +// Carte FeynmanFeedback de docs/Max_Composants_Frontend.md (FeynmanCard). +export class FeynmanFeedbackResponseDto { + @ApiProperty({ type: [String] }) strengths!: string[]; + @ApiProperty({ type: [String] }) gaps!: string[]; + @ApiProperty() validated!: boolean; +} diff --git a/Max API/src/sessions/dto/feynman-submission.dto.ts b/Max API/src/sessions/dto/feynman-submission.dto.ts new file mode 100644 index 0000000..ea3a86e --- /dev/null +++ b/Max API/src/sessions/dto/feynman-submission.dto.ts @@ -0,0 +1,12 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { IsString, MaxLength, MinLength } from 'class-validator'; + +export class FeynmanSubmissionDto { + @ApiProperty({ + example: "C'est comme faire tourner une photo autour d'un point fixe.", + }) + @IsString() + @MinLength(1) + @MaxLength(4000) + explanation!: string; +} diff --git a/Max API/src/sessions/dto/hint-request.dto.ts b/Max API/src/sessions/dto/hint-request.dto.ts new file mode 100644 index 0000000..829225b --- /dev/null +++ b/Max API/src/sessions/dto/hint-request.dto.ts @@ -0,0 +1,10 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { IsString, MaxLength, MinLength } from 'class-validator'; + +export class HintRequestDto { + @ApiProperty({ example: 'ex-1' }) + @IsString() + @MinLength(1) + @MaxLength(50) + exerciseId!: string; +} diff --git a/Max API/src/sessions/dto/hint-response.dto.ts b/Max API/src/sessions/dto/hint-response.dto.ts new file mode 100644 index 0000000..b2b3d4e --- /dev/null +++ b/Max API/src/sessions/dto/hint-response.dto.ts @@ -0,0 +1,11 @@ +import { ApiProperty } from '@nestjs/swagger'; + +export class HintResponseDto { + @ApiProperty({ description: 'Niveau d-indice atteint (1 a 5).' }) + level!: number; + @ApiProperty({ + nullable: true, + description: 'null si les 5 niveaux ont deja ete demandes.', + }) + hint!: string | null; +} diff --git a/Max API/src/sessions/dto/judge-result-response.dto.ts b/Max API/src/sessions/dto/judge-result-response.dto.ts new file mode 100644 index 0000000..b7faaf1 --- /dev/null +++ b/Max API/src/sessions/dto/judge-result-response.dto.ts @@ -0,0 +1,8 @@ +import { ApiProperty } from '@nestjs/swagger'; + +/** Reponse partagee par l'exercice, le debogage - feedback toujours substantiel (jamais "Bravo !" + * / "Non." seuls), jamais de reponse correcte revelee. */ +export class JudgeResultResponseDto { + @ApiProperty() correct!: boolean; + @ApiProperty() feedback!: string; +} diff --git a/Max API/src/sessions/dto/module-complete-response.dto.ts b/Max API/src/sessions/dto/module-complete-response.dto.ts new file mode 100644 index 0000000..7dc9662 --- /dev/null +++ b/Max API/src/sessions/dto/module-complete-response.dto.ts @@ -0,0 +1,20 @@ +import { ApiProperty } from '@nestjs/swagger'; + +// "missing" est calcule integralement cote code (module.agent.ts, completeModule()) - jamais une +// decision du LLM - pour dire precisement au frontend quoi faire retravailler. +export class ModuleCompleteResponseDto { + @ApiProperty() completed!: boolean; + @ApiProperty({ type: [String], required: false }) missing?: string[]; + @ApiProperty({ + required: false, + description: + 'Index du module suivant genere, si different de null et completed=true.', + }) + nextModuleIndex?: number | null; + @ApiProperty({ + required: false, + description: + "true si c'etait le dernier module : l'Agent 7 (evaluation) vient de demarrer.", + }) + evaluationStarted?: boolean; +} diff --git a/Max API/src/sessions/dto/module-content-response.dto.ts b/Max API/src/sessions/dto/module-content-response.dto.ts new file mode 100644 index 0000000..ac63fc4 --- /dev/null +++ b/Max API/src/sessions/dto/module-content-response.dto.ts @@ -0,0 +1,64 @@ +import { ApiProperty } from '@nestjs/swagger'; + +class ModuleTheoryDto { + @ApiProperty() coreIdea!: string; + @ApiProperty() analogy!: string; + @ApiProperty() formalDefinition!: string; + @ApiProperty() workedExample!: string; + @ApiProperty() counterExample!: string; +} + +class ModuleWeDoDto { + @ApiProperty() problem!: string; + @ApiProperty({ type: [String] }) guidingQuestions!: string[]; +} + +export class PublicExerciseDto { + @ApiProperty() id!: string; + @ApiProperty({ enum: ['easy', 'medium', 'hard'] }) + level!: 'easy' | 'medium' | 'hard'; + @ApiProperty() context!: string; + @ApiProperty() prompt!: string; + @ApiProperty({ + type: [String], + description: 'Indices deja debloques (0 a 5), jamais ceux au-dela.', + }) + revealedHints!: string[]; + @ApiProperty() passed!: boolean; +} + +class PublicDebugExerciseDto { + @ApiProperty() instruction!: string; + @ApiProperty() codeOrReasoningWithBug!: string; + @ApiProperty() language!: string; +} + +class ModuleSynthesisDto { + @ApiProperty() recap!: string; + @ApiProperty({ type: [String] }) metacognitionQuestions!: string[]; + @ApiProperty() feynmanPrompt!: string; +} + +class ModuleAwaitingDto { + @ApiProperty({ enum: ['exercise', 'debug', 'feynman'] }) + type!: 'exercise' | 'debug' | 'feynman'; + @ApiProperty({ required: false }) exerciseId?: string; +} + +// "awaiting" est le signal structure (code, jamais LLM) qui dit au frontend - et au pipeline +// voix/texte unique (routeIncomingMessage) - ce qu'un prochain message libre de l'utilisateur doit +// etre interprete comme : une reponse a cet exercice, une correction de debogage, ou une +// explication Feynman. Jamais null tant que le module n'est pas termine. +export class ModuleStateResponseDto { + @ApiProperty() moduleIndex!: number; + @ApiProperty() title!: string; + @ApiProperty() hook!: string; + @ApiProperty({ type: ModuleTheoryDto }) theory!: ModuleTheoryDto; + @ApiProperty({ type: ModuleWeDoDto }) weDo!: ModuleWeDoDto; + @ApiProperty({ type: [PublicExerciseDto] }) exercises!: PublicExerciseDto[]; + @ApiProperty({ type: PublicDebugExerciseDto }) + debugExercise!: PublicDebugExerciseDto; + @ApiProperty({ type: ModuleSynthesisDto }) synthesis!: ModuleSynthesisDto; + @ApiProperty({ type: ModuleAwaitingDto, nullable: true }) + awaiting!: ModuleAwaitingDto | null; +} diff --git a/Max API/src/sessions/prompts/module.prompt.ts b/Max API/src/sessions/prompts/module.prompt.ts new file mode 100644 index 0000000..074f70d --- /dev/null +++ b/Max API/src/sessions/prompts/module.prompt.ts @@ -0,0 +1,111 @@ +// Prompt de role de l'Agent 6 (docs/Max_System_Prompt.md). Les placeholders [INDEX], [TITRE], +// [CONCEPT], [OBJECTIF_INJECTÉ], [NIVEAU_INJECTÉ], [CORPUS_INJECTÉ], [LISTE_MODULES_PRÉCÉDENTS] +// sont remplaces par le backend (module.agent.ts). Pas de personnalite Max (contenu long +// affiche et lu a l'ecran, jamais raconte par Max - docs/Max Refonte Coach Freelance.md, +// "Jamais de cours a l'oral") ni de ":online" (redige a partir du corpus deja recupere). +export function buildModulePrompt(params: { + index: number; + title: string; + concept: string; + objectiveSummary: string; + levelSummary: string; + corpusSummary: string; + previousModulesSummary: string; +}): string { + return `## Ton rôle dans cet échange + +Tu dois rédiger le contenu du module suivant : +Module ${params.index} — ${params.title} +Concept ciblé : ${params.concept} + +Objectif global de la formation : ${params.objectiveSummary} +Niveau de l'utilisateur : ${params.levelSummary} +Corpus de recherche disponible : ${params.corpusSummary} +Modules précédents déjà enseignés : ${params.previousModulesSummary} + +## Structure obligatoire — 6 sections dans cet ordre + +1. ACCROCHE (minimum 150 mots) + Situation réelle + contexte historique + 3 cas d'usage actuels + question d'amorce. + Ne pas commencer par une définition. + +2. THÉORIE (minimum 300 mots) + Idée centrale en langage simple + analogie vérifiée + définition formelle + + exemple résolu étape par étape + contre-exemple. + +3. PHASE GUIDÉE — WE DO (minimum 3 étapes) + Problème similaire à l'exemple, guidé par questions. + Ne jamais donner la réponse — guider jusqu'à ce que l'utilisateur y arrive. + +4. EXERCICES (minimum 6 exercices) + 2 faciles + 2 moyens + 2 difficiles. + Chaque exercice ancré dans un contexte de mission freelance réelle. + +5. EXERCICE DE DÉBOGAGE (1 obligatoire) + Code ou raisonnement contenant une erreur intentionnelle subtile à trouver. + +6. SYNTHÈSE ET AUTO-ÉVALUATION (minimum 100 mots) + Récapitulatif + 3 questions de méta-cognition + test Feynman + ("Explique ce concept comme si j'avais 12 ans"). + +## Règles absolues + +- Vérifie deux fois chaque calcul ou formule avant de l'écrire +- Ne présuppose aucune connaissance non enseignée dans les modules précédents +- Ne donne jamais la réponse à un exercice directement + +## Ce que tu ne fais pas + +- Tu ne poses pas de questions à l'utilisateur +- Tu ne rédiges pas le module suivant +- Tu ne t'écarte pas des 6 sections + +${MODULE_JSON_CONTRACT}`; +} + +// Ajout technique non present dans docs/Max_System_Prompt.md : le document decrit 6 sections en +// prose. Pour etre affichable dans ModulePanel/ExerciseCard/DebugExerciseCard/FeynmanCard +// (docs/Max_Composants_Frontend.md) et validable cote code (nombre de mots, nombre d'exercices, +// echelle d'indices a 5 niveaux), le contenu doit arriver structure. "correctAnswerInternal"/ +// "correctionInternal" ne sont jamais exposes au frontend (voir module.agent.ts, toPublicContent). +export const MODULE_JSON_CONTRACT = `Tu retournes un JSON structuré exactement sous cette forme : +{ + "hook": "... (>= 150 mots, situation reelle + contexte historique + 3 cas d'usage + question d'amorce)", + "theory": { + "coreIdea": "...", + "analogy": "...", + "formalDefinition": "...", + "workedExample": "...", + "counterExample": "..." + }, + "weDo": { + "problem": "...", + "guidingQuestions": ["...", "...", "..."] + }, + "exercises": [ + { + "level": "easy", + "context": "contexte de mission freelance reelle", + "prompt": "...", + "hints": ["indice niveau 1 (clarification)", "indice niveau 2 (rappel de concept)", "indice niveau 3 (pointage precis)", "indice niveau 4 (exemple analogue)", "indice niveau 5 (decomposition)"], + "correctAnswerInternal": "..." + } + ], + "debugExercise": { + "codeOrReasoningWithBug": "...", + "language": "...", + "instruction": "...", + "correctionInternal": "..." + }, + "synthesis": { + "recap": "...", + "metacognitionQuestions": ["...", "...", "..."], + "feynmanPrompt": "Explique ce concept comme si j'avais 12 ans" + } +} + +Le tableau "exercises" contient EXACTEMENT 6 elements : 2 avec "level":"easy", 2 avec +"level":"medium", 2 avec "level":"hard", chacun avec EXACTEMENT 5 indices dans "hints" (du plus +leger au plus explicite). "correctAnswerInternal" et "correctionInternal" sont la reponse/correction +exacte, jamais montrees a l'utilisateur. Reponds UNIQUEMENT avec cet objet JSON strict, sans texte +avant ni apres.`;