diff --git a/Max API/src/sessions/dto/route-message-response.dto.ts b/Max API/src/sessions/dto/route-message-response.dto.ts index 5f50c26..88cfe0f 100644 --- a/Max API/src/sessions/dto/route-message-response.dto.ts +++ b/Max API/src/sessions/dto/route-message-response.dto.ts @@ -1,6 +1,7 @@ import { ApiProperty } from '@nestjs/swagger'; import { ObjectiveDraftDto } from './objective-message-response.dto'; import { LevelProfileDto } from './level-turn-response.dto'; +import { ModuleCompleteResponseDto } from './module-complete-response.dto'; // Chaque champ optionnel ci-dessous est un signal structure et non ambigu que le frontend (Max // Avatar) utilise pour decider, en code, d'ouvrir ou non une fenetre dediee (ObjectiveValidationCard, @@ -45,4 +46,25 @@ export class RouteMessageResponseDto { @ApiProperty({ type: LevelProfileDto, required: false }) levelProfile?: LevelProfileDto; + + @ApiProperty({ + required: false, + description: + "Agent 6 (teaching) : present quand le message a ete interprete comme une reponse d'exercice/debogage/Feynman. Si nextModuleIndex ou evaluationStarted est renseigne, le frontend doit rafraichir le module affiche (nouveau module genere) ou ouvrir la suite de l'evaluation finale.", + }) + moduleComplete?: ModuleCompleteResponseDto; + + @ApiProperty({ + enum: ['interview', 'mission'], + required: false, + description: 'Agent 7 (evaluating) : etape en cours.', + }) + evaluationStage?: 'interview' | 'mission'; + + @ApiProperty({ + required: false, + description: + "Agent 7 (evaluating) : true quand l'evaluation ENTIERE est terminee (voir EvaluationTurnResponseDto) - va chercher le resultat complet via GET /sessions/:id/evaluation pour EvaluationScoreCard.", + }) + evaluationDone?: boolean; } diff --git a/Max API/src/sessions/sessions.controller.spec.ts b/Max API/src/sessions/sessions.controller.spec.ts index 85a0141..cc8a18e 100644 --- a/Max API/src/sessions/sessions.controller.spec.ts +++ b/Max API/src/sessions/sessions.controller.spec.ts @@ -14,6 +14,13 @@ describe('SessionsController', () => { confirmLevel: jest.fn(), disputeLevel: jest.fn(), routeIncomingMessage: jest.fn(), + confirmCurriculum: jest.fn(), + submitExerciseAnswer: jest.fn(), + requestHint: jest.fn(), + submitDebugCorrection: jest.fn(), + submitFeynmanExplanation: jest.fn(), + completeModule: jest.fn(), + getEvaluationResult: jest.fn(), }; const request = { user: { sub: 7, email: 'w@example.com' }, @@ -100,4 +107,89 @@ describe('SessionsController', () => { 'Salut', ); }); + + it('should confirm the curriculum and return the first module state', async () => { + sessionsService.confirmCurriculum.mockResolvedValueOnce({ + moduleIndex: 1, + title: 'Module 1', + }); + await controller.confirmCurriculum(1, request); + expect(sessionsService.confirmCurriculum).toHaveBeenCalledWith(1, 7); + }); + + it('should forward an exercise answer to the service', async () => { + sessionsService.submitExerciseAnswer.mockResolvedValueOnce({ + correct: true, + feedback: 'Bravo', + }); + const dto = { exerciseId: 'ex-1', answer: 'ma reponse' }; + await controller.submitExerciseAnswer(1, dto, request); + expect(sessionsService.submitExerciseAnswer).toHaveBeenCalledWith( + 1, + 7, + dto, + ); + }); + + it('should forward a hint request to the service', async () => { + sessionsService.requestHint.mockResolvedValueOnce({ + level: 1, + hint: 'indice', + }); + const dto = { exerciseId: 'ex-1' }; + await controller.requestHint(1, dto, request); + expect(sessionsService.requestHint).toHaveBeenCalledWith(1, 7, dto); + }); + + it('should forward a debug correction to the service', async () => { + sessionsService.submitDebugCorrection.mockResolvedValueOnce({ + correct: true, + feedback: 'Correct', + }); + const dto = { correction: 'const x = 2' }; + await controller.submitDebugCorrection(1, dto, request); + expect(sessionsService.submitDebugCorrection).toHaveBeenCalledWith( + 1, + 7, + dto, + ); + }); + + it('should forward a Feynman explanation to the service', async () => { + sessionsService.submitFeynmanExplanation.mockResolvedValueOnce({ + strengths: [], + gaps: [], + validated: true, + }); + const dto = { explanation: 'mon explication' }; + await controller.submitFeynmanExplanation(1, dto, request); + expect(sessionsService.submitFeynmanExplanation).toHaveBeenCalledWith( + 1, + 7, + dto, + ); + }); + + it('should ask the service to check module completion', async () => { + sessionsService.completeModule.mockResolvedValueOnce({ + completed: false, + missing: ['...'], + }); + await controller.completeModule(1, request); + expect(sessionsService.completeModule).toHaveBeenCalledWith(1, 7); + }); + + it('should fetch the final evaluation result for the authenticated user', async () => { + sessionsService.getEvaluationResult.mockResolvedValueOnce({ + validated: true, + interviewScore: 5, + interviewFeedback: [], + practicalScore: 3, + practicalFeedback: [], + strengths: [], + remainingGaps: [], + }); + await controller.getEvaluationResult(1, request); + expect(sessionsService.getEvaluationResult).toHaveBeenCalledWith(1, 7); + }); }); diff --git a/Max API/src/sessions/sessions.controller.ts b/Max API/src/sessions/sessions.controller.ts index 3f9409c..b33d223 100644 --- a/Max API/src/sessions/sessions.controller.ts +++ b/Max API/src/sessions/sessions.controller.ts @@ -18,8 +18,19 @@ import { } from '@nestjs/swagger'; import type { AuthenticatedRequest } from '../auth/jwt-auth.guard'; import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { CurriculumResponseDto } from './dto/curriculum-response.dto'; +import { DebugCorrectionDto } from './dto/debug-correction.dto'; +import { EvaluationResultResponseDto } from './dto/evaluation-result-response.dto'; +import { ExerciseAnswerDto } from './dto/exercise-answer.dto'; +import { FeynmanFeedbackResponseDto } from './dto/feynman-feedback-response.dto'; +import { FeynmanSubmissionDto } from './dto/feynman-submission.dto'; +import { HintRequestDto } from './dto/hint-request.dto'; +import { HintResponseDto } from './dto/hint-response.dto'; +import { JudgeResultResponseDto } from './dto/judge-result-response.dto'; import { LevelDisputeDto } from './dto/level-dispute.dto'; import { LevelProfileResponseDto } from './dto/level-profile-response.dto'; +import { ModuleCompleteResponseDto } from './dto/module-complete-response.dto'; +import { ModuleStateResponseDto } from './dto/module-content-response.dto'; import { ObjectiveMessageResponseDto } from './dto/objective-message-response.dto'; import { RouteMessageResponseDto } from './dto/route-message-response.dto'; import { SendObjectiveMessageDto } from './dto/send-objective-message.dto'; @@ -119,9 +130,9 @@ export class SessionsController { @HttpCode(HttpStatus.OK) @ApiOperation({ summary: - "Confirmer le profil de niveau (Agent 3) et declencher l'Agent 4 (Recherche Approfondie)", + "Confirmer le profil de niveau (Agent 3), declencher l'Agent 4 (Recherche Approfondie) puis l'Agent 5 (Plan) - renvoie le curriculum pret pour CurriculumCard", }) - @ApiResponse({ status: HttpStatus.OK }) + @ApiResponse({ status: HttpStatus.OK, type: CurriculumResponseDto }) @ApiResponse({ status: HttpStatus.CONFLICT, description: "Cette session n'est plus a l'etape d'evaluation de niveau", @@ -129,7 +140,7 @@ export class SessionsController { confirmLevel( @Param('id', ParseIntPipe) id: number, @Req() request: AuthenticatedRequest, - ): Promise { + ): Promise { return this.sessionsService.confirmLevel(id, request.user.sub); } @@ -150,4 +161,112 @@ export class SessionsController { ): Promise { return this.sessionsService.disputeLevel(id, request.user.sub, dto); } + + @Post(':id/curriculum/confirm') + @HttpCode(HttpStatus.OK) + @ApiOperation({ + summary: + 'Confirmer le curriculum (CurriculumCard, "Demarrer la formation") - immuable, genere immediatement le module 1', + }) + @ApiResponse({ status: HttpStatus.OK, type: ModuleStateResponseDto }) + @ApiResponse({ + status: HttpStatus.CONFLICT, + description: "Pas a l'etape de planification, ou curriculum deja confirme", + }) + confirmCurriculum( + @Param('id', ParseIntPipe) id: number, + @Req() request: AuthenticatedRequest, + ): Promise { + return this.sessionsService.confirmCurriculum(id, request.user.sub); + } + + @Post(':id/module/exercise') + @ApiOperation({ + summary: + 'Repondre a un exercice du module en cours (equivalent REST de ce que routeIncomingMessage fait deja a partir de la voix/du texte)', + }) + @ApiResponse({ status: HttpStatus.CREATED, type: JudgeResultResponseDto }) + submitExerciseAnswer( + @Param('id', ParseIntPipe) id: number, + @Body() dto: ExerciseAnswerDto, + @Req() request: AuthenticatedRequest, + ): Promise { + return this.sessionsService.submitExerciseAnswer(id, request.user.sub, dto); + } + + @Post(':id/module/hint') + @ApiOperation({ + summary: "Demander l'indice suivant (1 a 5) pour un exercice", + }) + @ApiResponse({ status: HttpStatus.CREATED, type: HintResponseDto }) + requestHint( + @Param('id', ParseIntPipe) id: number, + @Body() dto: HintRequestDto, + @Req() request: AuthenticatedRequest, + ): Promise { + return this.sessionsService.requestHint(id, request.user.sub, dto); + } + + @Post(':id/module/debug') + @ApiOperation({ + summary: "Soumettre la correction de l'exercice de debogage", + }) + @ApiResponse({ status: HttpStatus.CREATED, type: JudgeResultResponseDto }) + submitDebugCorrection( + @Param('id', ParseIntPipe) id: number, + @Body() dto: DebugCorrectionDto, + @Req() request: AuthenticatedRequest, + ): Promise { + return this.sessionsService.submitDebugCorrection( + id, + request.user.sub, + dto, + ); + } + + @Post(':id/module/feynman') + @ApiOperation({ + summary: + 'Soumettre une explication pour le test Feynman du module en cours', + }) + @ApiResponse({ status: HttpStatus.CREATED, type: FeynmanFeedbackResponseDto }) + submitFeynmanExplanation( + @Param('id', ParseIntPipe) id: number, + @Body() dto: FeynmanSubmissionDto, + @Req() request: AuthenticatedRequest, + ): Promise { + return this.sessionsService.submitFeynmanExplanation( + id, + request.user.sub, + dto, + ); + } + + @Post(':id/module/complete') + @HttpCode(HttpStatus.OK) + @ApiOperation({ + summary: + 'Verifier et valider la fin du module en cours (>=4/6 exercices + debogage + Feynman) - calcule cote code, jamais par le LLM', + }) + @ApiResponse({ status: HttpStatus.OK, type: ModuleCompleteResponseDto }) + completeModule( + @Param('id', ParseIntPipe) id: number, + @Req() request: AuthenticatedRequest, + ): Promise { + return this.sessionsService.completeModule(id, request.user.sub); + } + + @Get(':id/evaluation') + @ApiOperation({ + summary: + "Recuperer le resultat complet de l'evaluation finale (Agent 7), pour EvaluationScoreCard", + }) + @ApiResponse({ status: HttpStatus.OK, type: EvaluationResultResponseDto }) + @ApiResponse({ status: HttpStatus.NOT_FOUND }) + getEvaluationResult( + @Param('id', ParseIntPipe) id: number, + @Req() request: AuthenticatedRequest, + ): Promise { + return this.sessionsService.getEvaluationResult(id, request.user.sub); + } } diff --git a/Max API/src/sessions/sessions.module.ts b/Max API/src/sessions/sessions.module.ts index 70e90a1..255e433 100644 --- a/Max API/src/sessions/sessions.module.ts +++ b/Max API/src/sessions/sessions.module.ts @@ -2,10 +2,13 @@ import { Module } from '@nestjs/common'; import { AuthModule } from '../auth/auth.module'; import { LlmModule } from '../llm/llm.module'; import { PrismaModule } from '../prisma/prisma.module'; +import { EvaluationAgent } from './agents/evaluation.agent'; import { IntentRouterAgent } from './agents/intent-router.agent'; import { LevelAgent } from './agents/level.agent'; import { MappingAgent } from './agents/mapping.agent'; +import { ModuleAgent } from './agents/module.agent'; import { ObjectiveAgent } from './agents/objective.agent'; +import { PlanAgent } from './agents/plan.agent'; import { ResearchAgent } from './agents/research.agent'; import { SessionsController } from './sessions.controller'; import { SessionsService } from './sessions.service'; @@ -19,6 +22,9 @@ import { SessionsService } from './sessions.service'; MappingAgent, LevelAgent, ResearchAgent, + PlanAgent, + ModuleAgent, + EvaluationAgent, IntentRouterAgent, ], exports: [SessionsService], diff --git a/Max API/src/sessions/sessions.service.spec.ts b/Max API/src/sessions/sessions.service.spec.ts index 5c330de..66d1a01 100644 --- a/Max API/src/sessions/sessions.service.spec.ts +++ b/Max API/src/sessions/sessions.service.spec.ts @@ -2,10 +2,13 @@ import { ConflictException, NotFoundException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { OpenRouterService } from '../llm/openrouter.service'; import { PrismaService } from '../prisma/prisma.service'; +import { EvaluationAgent } from './agents/evaluation.agent'; import { IntentRouterAgent } from './agents/intent-router.agent'; import { LevelAgent } from './agents/level.agent'; import { MappingAgent } from './agents/mapping.agent'; +import { ModuleAgent } from './agents/module.agent'; import { ObjectiveAgent } from './agents/objective.agent'; +import { PlanAgent } from './agents/plan.agent'; import { ResearchAgent } from './agents/research.agent'; import { SessionsService } from './sessions.service'; @@ -19,6 +22,19 @@ describe('SessionsService', () => { update: jest.fn(), }, sessionConceptMap: { findUniqueOrThrow: jest.fn() }, + sessionCurriculum: { + findUnique: jest.fn(), + findUniqueOrThrow: jest.fn(), + update: jest.fn< + Promise, + [{ where: { sessionId: number }; data: { validatedAt: Date } }] + >(), + }, + sessionModule: { + findFirst: jest.fn(), + findUniqueOrThrow: jest.fn(), + }, + sessionEvaluation: { findUnique: jest.fn() }, }; const objectiveAgent = { converse: jest.fn(), confirm: jest.fn() }; const mappingAgent = { runForSession: jest.fn() }; @@ -29,6 +45,16 @@ describe('SessionsService', () => { dispute: jest.fn(), }; const researchAgent = { runForSession: jest.fn() }; + const planAgent = { runForSession: jest.fn() }; + const moduleAgent = { + generateModule: jest.fn(), + submitExerciseAnswer: jest.fn(), + requestHint: jest.fn(), + submitDebugCorrection: jest.fn(), + submitFeynmanExplanation: jest.fn(), + completeModule: jest.fn(), + }; + const evaluationAgent = { start: jest.fn(), converse: jest.fn() }; const intentRouter = { analyze: jest.fn() }; const llm = { chat: jest.fn() }; @@ -42,6 +68,9 @@ describe('SessionsService', () => { { provide: MappingAgent, useValue: mappingAgent }, { provide: LevelAgent, useValue: levelAgent }, { provide: ResearchAgent, useValue: researchAgent }, + { provide: PlanAgent, useValue: planAgent }, + { provide: ModuleAgent, useValue: moduleAgent }, + { provide: EvaluationAgent, useValue: evaluationAgent }, { provide: IntentRouterAgent, useValue: intentRouter }, { provide: OpenRouterService, useValue: llm }, ], @@ -184,15 +213,20 @@ describe('SessionsService', () => { }); describe('confirmLevel()', () => { - it('should confirm the level profile, run Agent 4, and advance status to planning', async () => { + it('should confirm the level profile, run Agent 4 then Agent 5, and return the ready curriculum', async () => { prisma.session.findUnique.mockResolvedValueOnce({ id: 1, userId: 7, status: 'level_assessment', objective: null, }); + prisma.sessionCurriculum.findUniqueOrThrow.mockResolvedValueOnce({ + modules: [{ index: 1, title: 'Facturation', status: 'unlocked' }], + totalDuration: '2 semaines', + validatedAt: null, + }); - await service.confirmLevel(1, 7); + const result = await service.confirmLevel(1, 7); expect(levelAgent.confirm).toHaveBeenCalledWith(1); expect(researchAgent.runForSession).toHaveBeenCalledWith(1, 7); @@ -200,6 +234,10 @@ describe('SessionsService', () => { where: { id: 1 }, data: { status: 'planning' }, }); + expect(planAgent.runForSession).toHaveBeenCalledWith(1, 7); + expect(result.modules).toHaveLength(1); + expect(result.totalDuration).toBe('2 semaines'); + expect(result.validatedAt).toBeUndefined(); }); it('should reject when the session is not at the level_assessment stage', async () => { @@ -321,11 +359,11 @@ describe('SessionsService', () => { }); }); - it('should reject when the active session is in a status with no agent built yet', async () => { + it('should reject when the active session is in a transitional status not reachable from a free message (crash-recovery edge case)', async () => { prisma.session.findFirst.mockResolvedValueOnce({ id: 1, userId: 7, - status: 'planning', + status: 'mapping', }); await expect( @@ -335,6 +373,96 @@ describe('SessionsService', () => { expect(levelAgent.converse).not.toHaveBeenCalled(); }); + it('should return a canned reminder when the active session is at the planning stage (no LLM call)', async () => { + prisma.session.findFirst.mockResolvedValueOnce({ + id: 1, + userId: 7, + status: 'planning', + }); + + const result = await service.routeIncomingMessage(7, 'un message'); + + expect(result.type).toBe('learn'); + expect(result.reply).toMatch(/plan de formation/i); + expect(llm.chat).not.toHaveBeenCalled(); + }); + + it('should route to the module agent when the active session is teaching (exercise answer)', async () => { + prisma.session.findFirst.mockResolvedValueOnce({ + id: 1, + userId: 7, + status: 'teaching', + }); + prisma.session.findUnique.mockResolvedValueOnce({ + id: 1, + userId: 7, + status: 'teaching', + objective: null, + }); + prisma.sessionModule.findFirst.mockResolvedValueOnce({ + moduleIndex: 1, + status: 'generated', + }); + prisma.sessionModule.findUniqueOrThrow.mockResolvedValueOnce({ + content: { + exercises: [{ id: 'ex-1' }], + progress: { + currentAwaiting: { type: 'exercise', exerciseId: 'ex-1' }, + exercises: { 'ex-1': { attempts: 0, passed: false, hintLevel: 0 } }, + debugPassed: false, + feynman: null, + }, + }, + }); + moduleAgent.submitExerciseAnswer.mockResolvedValueOnce({ + correct: true, + feedback: 'Bien joue, le raisonnement est correct.', + }); + moduleAgent.completeModule.mockResolvedValueOnce({ + completed: false, + missing: ['3/4 exercices reussis'], + }); + + const result = await service.routeIncomingMessage( + 7, + 'Je ferais pivoter le vecteur.', + ); + + expect(moduleAgent.submitExerciseAnswer).toHaveBeenCalledWith( + 1, + 7, + 1, + 'ex-1', + 'Je ferais pivoter le vecteur.', + ); + expect(result.reply).toContain('Bien joue'); + expect(result.moduleComplete?.completed).toBe(false); + }); + + it('should route to the evaluation agent when the active session is evaluating', async () => { + prisma.session.findFirst.mockResolvedValueOnce({ + id: 1, + userId: 7, + status: 'evaluating', + }); + evaluationAgent.converse.mockResolvedValueOnce({ + reply: 'Quels sont les risques de cette approche ?', + done: false, + stage: 'interview', + }); + + const result = await service.routeIncomingMessage(7, 'Ma reponse'); + + expect(evaluationAgent.converse).toHaveBeenCalledWith(1, 7, 'Ma reponse'); + expect(result).toEqual({ + type: 'learn', + sessionId: 1, + reply: 'Quels sont les risques de cette approche ?', + evaluationStage: 'interview', + evaluationDone: false, + }); + }); + it('should reply conversationally without creating a session when intent is chat', async () => { prisma.session.findFirst.mockResolvedValueOnce(null); intentRouter.analyze.mockResolvedValueOnce({ @@ -390,4 +518,162 @@ describe('SessionsService', () => { }); }); }); + + describe('confirmCurriculum()', () => { + it('should validate the curriculum, advance to teaching, and generate module 1', async () => { + prisma.session.findUnique.mockResolvedValueOnce({ + id: 1, + userId: 7, + status: 'planning', + objective: null, + }); + prisma.sessionCurriculum.findUnique.mockResolvedValueOnce({ + validatedAt: null, + }); + moduleAgent.generateModule.mockResolvedValueOnce({ + title: 'Les bases de la facturation', + hook: 'hook', + theory: {}, + weDo: {}, + exercises: [], + debugExercise: {}, + synthesis: {}, + progress: { currentAwaiting: { type: 'exercise', exerciseId: 'ex-1' } }, + }); + + const result = await service.confirmCurriculum(1, 7); + + const curriculumUpdateCall = + prisma.sessionCurriculum.update.mock.calls[0][0]; + expect(curriculumUpdateCall.where).toEqual({ sessionId: 1 }); + expect(curriculumUpdateCall.data.validatedAt).toBeInstanceOf(Date); + expect(prisma.session.update).toHaveBeenCalledWith({ + where: { id: 1 }, + data: { status: 'teaching' }, + }); + expect(moduleAgent.generateModule).toHaveBeenCalledWith(1, 7, 1); + expect(result.moduleIndex).toBe(1); + expect(result.title).toBe('Les bases de la facturation'); + }); + + it('should reject when the curriculum is already confirmed', async () => { + prisma.session.findUnique.mockResolvedValueOnce({ + id: 1, + userId: 7, + status: 'planning', + objective: null, + }); + prisma.sessionCurriculum.findUnique.mockResolvedValueOnce({ + validatedAt: new Date('2026-01-01'), + }); + + await expect(service.confirmCurriculum(1, 7)).rejects.toThrow( + ConflictException, + ); + expect(moduleAgent.generateModule).not.toHaveBeenCalled(); + }); + }); + + describe('module sub-actions', () => { + beforeEach(() => { + prisma.session.findUnique.mockResolvedValueOnce({ + id: 1, + userId: 7, + status: 'teaching', + objective: null, + }); + prisma.sessionModule.findFirst.mockResolvedValueOnce({ + moduleIndex: 2, + status: 'generated', + }); + }); + + it('submitExerciseAnswer() should delegate to the module agent for the current module', async () => { + moduleAgent.submitExerciseAnswer.mockResolvedValueOnce({ + correct: true, + feedback: 'Correct.', + }); + + const result = await service.submitExerciseAnswer(1, 7, { + exerciseId: 'ex-1', + answer: 'reponse', + }); + + expect(moduleAgent.submitExerciseAnswer).toHaveBeenCalledWith( + 1, + 7, + 2, + 'ex-1', + 'reponse', + ); + expect(result.correct).toBe(true); + }); + + it('requestHint() should delegate to the module agent for the current module', async () => { + moduleAgent.requestHint.mockResolvedValueOnce({ + level: 1, + hint: 'Pense a la matrice.', + }); + + const result = await service.requestHint(1, 7, { exerciseId: 'ex-1' }); + + expect(moduleAgent.requestHint).toHaveBeenCalledWith(1, 2, 'ex-1'); + expect(result.hint).toBe('Pense a la matrice.'); + }); + + it('completeModule() should reject when the session is not teaching', async () => { + prisma.session.findUnique.mockReset(); + prisma.session.findUnique.mockResolvedValueOnce({ + id: 1, + userId: 7, + status: 'evaluating', + objective: null, + }); + + await expect(service.completeModule(1, 7)).rejects.toThrow( + ConflictException, + ); + }); + }); + + describe('getEvaluationResult()', () => { + it('should map the stored evaluation into EvaluationResultResponseDto', async () => { + prisma.session.findUnique.mockResolvedValueOnce({ + id: 1, + userId: 7, + status: 'completed', + objective: null, + }); + prisma.sessionEvaluation.findUnique.mockResolvedValueOnce({ + interviewScore: 5, + practicalScore: 3, + validated: true, + feedback: { + interview: { feedback: 'Tres bonne maitrise.', remedialModules: [] }, + mission: { feedback: 'Raisonnement solide.' }, + }, + completedAt: new Date('2026-01-10'), + }); + + const result = await service.getEvaluationResult(1, 7); + + expect(result.validated).toBe(true); + expect(result.interviewScore).toBe(5); + expect(result.practicalFeedback).toEqual(['Raisonnement solide.']); + }); + + it('should throw NotFoundException when no evaluation has completed yet', async () => { + prisma.session.findUnique.mockResolvedValueOnce({ + id: 1, + userId: 7, + status: 'evaluating', + objective: null, + }); + prisma.sessionEvaluation.findUnique.mockResolvedValueOnce(null); + + await expect(service.getEvaluationResult(1, 7)).rejects.toThrow( + NotFoundException, + ); + }); + }); }); diff --git a/Max API/src/sessions/sessions.service.ts b/Max API/src/sessions/sessions.service.ts index aad9acb..1696bd3 100644 --- a/Max API/src/sessions/sessions.service.ts +++ b/Max API/src/sessions/sessions.service.ts @@ -3,29 +3,54 @@ import { Injectable, NotFoundException, } from '@nestjs/common'; -import { Session, SessionObjective } from '@prisma/client'; +import { Session, SessionCurriculum, SessionObjective } from '@prisma/client'; import { OpenRouterService } from '../llm/openrouter.service'; import { PrismaService } from '../prisma/prisma.service'; +import { EvaluationAgent } from './agents/evaluation.agent'; import { IntentRouterAgent } from './agents/intent-router.agent'; import { LevelAgent, StoredLevelAssessment } from './agents/level.agent'; import { MappingAgent } from './agents/mapping.agent'; +import { ModuleAgent } from './agents/module.agent'; import { ObjectiveAgent, ObjectiveTurnResult } from './agents/objective.agent'; +import { PlanAgent } from './agents/plan.agent'; import { ResearchAgent } from './agents/research.agent'; +import { CurriculumResponseDto } from './dto/curriculum-response.dto'; +import { DebugCorrectionDto } from './dto/debug-correction.dto'; +import { EvaluationResultResponseDto } from './dto/evaluation-result-response.dto'; +import { ExerciseAnswerDto } from './dto/exercise-answer.dto'; +import { FeynmanFeedbackResponseDto } from './dto/feynman-feedback-response.dto'; +import { FeynmanSubmissionDto } from './dto/feynman-submission.dto'; +import { HintRequestDto } from './dto/hint-request.dto'; +import { HintResponseDto } from './dto/hint-response.dto'; +import { JudgeResultResponseDto } from './dto/judge-result-response.dto'; import { LevelDisputeDto } from './dto/level-dispute.dto'; import { LevelProfileResponseDto } from './dto/level-profile-response.dto'; +import { ModuleCompleteResponseDto } from './dto/module-complete-response.dto'; +import { ModuleStateResponseDto } from './dto/module-content-response.dto'; import { RouteMessageResponseDto } from './dto/route-message-response.dto'; import { buildAgentPrompt, PERSONALITY_PROMPT } from './prompts/base.prompt'; import { SessionObjectiveResponseDto } from './dto/session-objective-response.dto'; import { SessionResponseDto } from './dto/session-response.dto'; +import { + PublicModuleContent, + StoredModuleContent, +} from './agents/module.agent'; type SessionWithObjective = Session & { objective: SessionObjective | null }; // "researching" est gere entierement cote code par confirmLevel() (declenche l'Agent 4 puis -// avance directement a "planning") - il ne passe jamais par routeIncomingMessage(), donc il n'a -// pas besoin de figurer ici. "planning" et au-dela restent a implementer (prochain agent). +// l'Agent 5 et avance directement a "planning") - il ne passe jamais par routeIncomingMessage(), +// donc il n'a pas besoin de figurer ici. "planning" (en attente de confirmation du curriculum) et +// "evaluating" (Agent 7, conversationnel) sont geres ici. "teaching" n'est PAS un dispatch +// conversationnel libre (voir routeTeachingMessage()) : un message libre y est interprete via +// "currentAwaiting" plutot que classifie par un agent, donc il figure aussi dans ce Set mais est +// traite a part dans routeIncomingMessage(). const IMPLEMENTED_STATUSES = new Set([ 'objective_discovery', 'level_assessment', + 'planning', + 'teaching', + 'evaluating', ]); @Injectable() @@ -36,6 +61,9 @@ export class SessionsService { private readonly mappingAgent: MappingAgent, private readonly levelAgent: LevelAgent, private readonly researchAgent: ResearchAgent, + private readonly planAgent: PlanAgent, + private readonly moduleAgent: ModuleAgent, + private readonly evaluationAgent: EvaluationAgent, private readonly intentRouter: IntentRouterAgent, private readonly llm: OpenRouterService, ) {} @@ -113,12 +141,18 @@ export class SessionsService { } /** - * Agent 4 (Recherche Approfondie), une fois le profil de niveau confirme par l'utilisateur - * (pas de contestation, ou contestation resolue) - voir docs/Max Refonte Coach Freelance.md, - * "Avant de passer a l'Agent 4, Max presente un resume du profil de niveau a l'utilisateur". - * Avance directement a "planning" (l'Agent 5, prochain a etre implemente, prendra le relai). + * Agent 4 (Recherche Approfondie) puis Agent 5 (Plan), une fois le profil de niveau confirme + * par l'utilisateur (pas de contestation, ou contestation resolue) - voir docs/Max Refonte + * Coach Freelance.md, "Avant de passer a l'Agent 4, Max presente un resume du profil de niveau + * a l'utilisateur". Enchaine jusqu'au curriculum inclus (aucun tour utilisateur requis entre + * les deux, "Max ne parle pas pendant les phases de traitement") : par le moment ou cette + * methode repond, session.status vaut "planning" ET le curriculum est deja stocke, pret pour + * CurriculumCard - seule la confirmation finale ("Demarrer la formation") attend l'utilisateur. */ - async confirmLevel(sessionId: number, userId: number): Promise { + async confirmLevel( + sessionId: number, + userId: number, + ): Promise { const session = await this.findOwnedSession(sessionId, userId); if (session.status !== 'level_assessment') { throw new ConflictException( @@ -131,6 +165,172 @@ export class SessionsService { where: { id: sessionId }, data: { status: 'planning' }, }); + await this.planAgent.runForSession(sessionId, userId); + + const curriculum = await this.prisma.sessionCurriculum.findUniqueOrThrow({ + where: { sessionId }, + }); + return this.toCurriculumResponse(curriculum); + } + + /** + * Confirmation explicite du curriculum (CurriculumCard, "Demarrer la formation") - immuable + * une fois validatedAt renseigne, meme principe que l'objectif (Agent 1). Enchaine + * immediatement la generation du module 1 (Agent 6) : lire ce module EST le prochain moment + * utilisateur reel, donc on s'arrete la plutot que d'attendre un message. + */ + async confirmCurriculum( + sessionId: number, + userId: number, + ): Promise { + const session = await this.findOwnedSession(sessionId, userId); + if (session.status !== 'planning') { + throw new ConflictException( + "Cette session n'est plus a l'etape de planification.", + ); + } + const curriculum = await this.prisma.sessionCurriculum.findUnique({ + where: { sessionId }, + }); + if (!curriculum) { + throw new ConflictException( + 'Aucun curriculum pret a confirmer pour cette session.', + ); + } + if (curriculum.validatedAt) { + throw new ConflictException('Ce curriculum est deja confirme.'); + } + + await this.prisma.sessionCurriculum.update({ + where: { sessionId }, + data: { validatedAt: new Date() }, + }); + await this.prisma.session.update({ + where: { id: sessionId }, + data: { status: 'teaching' }, + }); + const content = await this.moduleAgent.generateModule(sessionId, userId, 1); + return this.toModuleStateResponse(1, content); + } + + async submitExerciseAnswer( + sessionId: number, + userId: number, + dto: ExerciseAnswerDto, + ): Promise { + const moduleIndex = await this.assertTeachingInProgress(sessionId, userId); + return this.moduleAgent.submitExerciseAnswer( + sessionId, + userId, + moduleIndex, + dto.exerciseId, + dto.answer, + ); + } + + async requestHint( + sessionId: number, + userId: number, + dto: HintRequestDto, + ): Promise { + const moduleIndex = await this.assertTeachingInProgress(sessionId, userId); + return this.moduleAgent.requestHint(sessionId, moduleIndex, dto.exerciseId); + } + + async submitDebugCorrection( + sessionId: number, + userId: number, + dto: DebugCorrectionDto, + ): Promise { + const moduleIndex = await this.assertTeachingInProgress(sessionId, userId); + return this.moduleAgent.submitDebugCorrection( + sessionId, + userId, + moduleIndex, + dto.correction, + ); + } + + async submitFeynmanExplanation( + sessionId: number, + userId: number, + dto: FeynmanSubmissionDto, + ): Promise { + const moduleIndex = await this.assertTeachingInProgress(sessionId, userId); + return this.moduleAgent.submitFeynmanExplanation( + sessionId, + userId, + moduleIndex, + dto.explanation, + ); + } + + async completeModule( + sessionId: number, + userId: number, + ): Promise { + const moduleIndex = await this.assertTeachingInProgress(sessionId, userId); + return this.moduleAgent.completeModule( + sessionId, + userId, + moduleIndex, + (sid, uid) => this.startEvaluation(sid, uid), + ); + } + + async getEvaluationResult( + sessionId: number, + userId: number, + ): Promise { + await this.findOwnedSession(sessionId, userId); + const record = await this.prisma.sessionEvaluation.findUnique({ + where: { sessionId }, + }); + if (!record || !record.completedAt) { + throw new NotFoundException( + 'Aucun resultat d-evaluation disponible pour cette session.', + ); + } + const feedback = record.feedback as unknown as { + interview: { feedback: string; remedialModules: number[] }; + mission?: { feedback: string }; + }; + return { + validated: record.validated, + interviewScore: record.interviewScore ?? 0, + interviewFeedback: [feedback.interview.feedback], + practicalScore: record.practicalScore ?? 0, + practicalFeedback: feedback.mission ? [feedback.mission.feedback] : [], + strengths: [], + remainingGaps: feedback.interview.remedialModules.map(String), + }; + } + + private async startEvaluation( + sessionId: number, + userId: number, + ): Promise { + await this.evaluationAgent.start(sessionId, userId); + } + + private async assertTeachingInProgress( + sessionId: number, + userId: number, + ): Promise { + const session = await this.findOwnedSession(sessionId, userId); + if (session.status !== 'teaching') { + throw new ConflictException( + "Cette session n'est pas a l'etape de redaction/exercices.", + ); + } + const current = await this.prisma.sessionModule.findFirst({ + where: { sessionId, status: { not: 'completed' } }, + orderBy: { moduleIndex: 'desc' }, + }); + if (!current) { + throw new ConflictException('Aucun module en cours pour cette session.'); + } + return current.moduleIndex; } async disputeLevel( @@ -190,6 +390,37 @@ export class SessionsService { }; } + if (activeSession.status === 'planning') { + // Reponse figee cote code (pas d'appel LLM) : le curriculum est deja pret des la fin de + // confirmLevel(), il ne manque que la confirmation explicite (CurriculumCard, "Demarrer + // la formation"). Evite un 409 deroutant si l'utilisateur dit quelque chose en attendant. + return { + type: 'learn', + sessionId: activeSession.id, + reply: + 'Ton plan de formation est pret. Confirme-le pour commencer la redaction du premier module.', + }; + } + + if (activeSession.status === 'teaching') { + return this.routeTeachingMessage(activeSession.id, userId, message); + } + + if (activeSession.status === 'evaluating') { + const turn = await this.evaluationAgent.converse( + activeSession.id, + userId, + message, + ); + return { + type: 'learn', + sessionId: activeSession.id, + reply: turn.reply, + evaluationStage: turn.stage, + evaluationDone: turn.done, + }; + } + const result = await this.sendObjectiveMessage( activeSession.id, userId, @@ -274,6 +505,119 @@ export class SessionsService { }; } + /** + * Route un message libre (voix ou texte) vers la sous-action attendue par le module en cours, + * a partir de "currentAwaiting" (jamais une classification par le LLM) : repond a l'exercice + * attendu, a la correction de debogage, ou a l'explication Feynman. Une demande d'indice est + * detectee par un motif simple ("indice"/"aide"/"hint"), uniquement quand un exercice est + * attendu (le debogage/Feynman n'ont pas d'echelle d'indices). Apres toute sous-action, + * verifie immediatement si le module est complet pour enchainer (module suivant ou Agent 7) + * sans attendre une action separee de l'utilisateur. + */ + private async routeTeachingMessage( + sessionId: number, + userId: number, + message: string, + ): Promise { + const moduleIndex = await this.assertTeachingInProgress(sessionId, userId); + const record = await this.prisma.sessionModule.findUniqueOrThrow({ + where: { sessionId_moduleIndex: { sessionId, moduleIndex } }, + }); + const content = record.content as unknown as StoredModuleContent; + const awaiting = content.progress.currentAwaiting; + + let reply: string; + if (!awaiting) { + reply = 'Ce module est deja termine.'; + } else if ( + awaiting.type === 'exercise' && + /\b(indice|aide|hint)\b/i.test(message) + ) { + const hint = await this.moduleAgent.requestHint( + sessionId, + moduleIndex, + awaiting.exerciseId, + ); + reply = + hint.hint ?? + 'Tu as deja utilise les 5 indices disponibles pour cet exercice.'; + } else if (awaiting.type === 'exercise') { + const judged = await this.moduleAgent.submitExerciseAnswer( + sessionId, + userId, + moduleIndex, + awaiting.exerciseId, + message, + ); + reply = judged.feedback; + } else if (awaiting.type === 'debug') { + const judged = await this.moduleAgent.submitDebugCorrection( + sessionId, + userId, + moduleIndex, + message, + ); + reply = judged.feedback; + } else { + const feynman = await this.moduleAgent.submitFeynmanExplanation( + sessionId, + userId, + moduleIndex, + message, + ); + reply = feynman.validated + ? `Explication validee. ${feynman.strengths.join(' ')}` + : `Pas tout a fait. ${feynman.gaps.join(' ')}`; + } + + const completion = await this.moduleAgent.completeModule( + sessionId, + userId, + moduleIndex, + (sid, uid) => this.startEvaluation(sid, uid), + ); + if (completion.completed && completion.nextModuleIndex) { + reply += ` Module suivant debloque : module ${completion.nextModuleIndex}.`; + } else if (completion.completed && completion.evaluationStarted) { + reply += ' Tous les modules sont termines. Place a l-evaluation finale.'; + } + + return { + type: 'learn', + sessionId, + reply, + moduleComplete: completion, + }; + } + + private toCurriculumResponse( + curriculum: SessionCurriculum, + ): CurriculumResponseDto { + return { + modules: + curriculum.modules as unknown as CurriculumResponseDto['modules'], + totalDuration: curriculum.totalDuration, + validatedAt: curriculum.validatedAt ?? undefined, + }; + } + + private toModuleStateResponse( + moduleIndex: number, + content: PublicModuleContent, + ): ModuleStateResponseDto { + return { + moduleIndex, + title: content.title, + hook: content.hook, + theory: content.theory, + weDo: content.weDo, + exercises: content.exercises, + debugExercise: content.debugExercise, + synthesis: content.synthesis, + awaiting: content.progress.currentAwaiting, + }; + } + private toResponse(session: SessionWithObjective): SessionResponseDto { return { id: session.id,