feat(sessions): wire Agents 2-4 into the pipeline orchestration

confirmObjective() now chains Agent 2 (mapping) then starts Agent 3
(level) synchronously after Agent 1 confirms - by the time the HTTP
response returns, session.status is already "level_assessment" and
the response carries Agent 3's first question in a new "nextPrompt"
field, to be spoken aloud (never displayed as text).

New endpoints: POST /sessions/:id/level/confirm (runs Agent 4, advances
to "planning") and POST /sessions/:id/level/dispute. routeIncomingMessage
dispatches "level_assessment" sessions to LevelAgent.converse(), same
single entry point used for text and voice.

RouteMessageResponseDto gains levelDone/levelProfile fields: every
response field is a structured, typed signal the frontend's main
process can branch on to decide whether to open a result window - never
an instruction embedded in the LLM's reply text.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
william
2026-11-02 09:48:10 +01:00
co-authored by Claude Sonnet 5
parent 5c00976e8f
commit 755bc07d18
10 changed files with 459 additions and 7 deletions
@@ -0,0 +1,19 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsString, MaxLength, MinLength } from 'class-validator';
export class LevelDisputeDto {
@ApiProperty({ example: 'Shaders de vertex' })
@IsString()
@MinLength(1)
@MaxLength(200)
concept!: string;
@ApiProperty({
example:
"J'ecrirais un shader qui modifie gl_Position selon une matrice de rotation.",
})
@IsString()
@MinLength(1)
@MaxLength(2000)
answer!: string;
}
@@ -0,0 +1,13 @@
import { ApiProperty } from '@nestjs/swagger';
import { LevelGapDto } from './level-turn-response.dto';
export class LevelProfileResponseDto {
@ApiProperty() id!: number;
@ApiProperty() sessionId!: number;
@ApiProperty({ type: [String] }) mastered!: string[];
@ApiProperty({ type: [LevelGapDto] }) gaps!: LevelGapDto[];
@ApiProperty({ type: [String] }) unknown!: string[];
@ApiProperty({ enum: ['beginner', 'intermediate', 'advanced'] })
overallLevel!: 'beginner' | 'intermediate' | 'advanced';
@ApiProperty({ required: false }) completedAt?: Date;
}
@@ -0,0 +1,30 @@
import { ApiProperty } from '@nestjs/swagger';
export class LevelGapDto {
@ApiProperty() concept!: string;
@ApiProperty() description!: string;
}
export class LevelProfileDto {
@ApiProperty({ type: [String] }) mastered!: string[];
@ApiProperty({ type: [LevelGapDto] }) gaps!: LevelGapDto[];
@ApiProperty({ type: [String] }) unknown!: string[];
@ApiProperty({ enum: ['beginner', 'intermediate', 'advanced'] })
overallLevel!: 'beginner' | 'intermediate' | 'advanced';
}
export class LevelTurnResponseDto {
@ApiProperty({
description: 'Question de Max, ou transition une fois le profil pret.',
})
reply!: string;
@ApiProperty({
description:
'true une fois les 3-5 questions posees et le profil pret a etre confirme via POST /sessions/:id/level/confirm.',
})
done!: boolean;
@ApiProperty({ type: LevelProfileDto, required: false })
profile?: LevelProfileDto;
}
@@ -1,6 +1,11 @@
import { ApiProperty } from '@nestjs/swagger';
import { ObjectiveDraftDto } from './objective-message-response.dto';
import { LevelProfileDto } from './level-turn-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,
// LevelResultCard, etc.) - jamais une instruction au LLM. Un seul champ booleen/objet par agent
// evite d'avoir a parser le texte de "reply" pour savoir quoi afficher.
export class RouteMessageResponseDto {
@ApiProperty({
enum: ['chat', 'learn'],
@@ -9,7 +14,10 @@ export class RouteMessageResponseDto {
})
type!: 'chat' | 'learn';
@ApiProperty({ description: 'Reponse de Max a afficher dans le chat.' })
@ApiProperty({
description:
'Reponse de Max a dire a voix haute (jamais affichee en bulle de texte).',
})
reply!: string;
@ApiProperty({
@@ -18,9 +26,23 @@ export class RouteMessageResponseDto {
})
sessionId?: number;
@ApiProperty({ required: false })
@ApiProperty({
required: false,
description:
'Agent 1 (Objectif) : true quand "draft" est pret pour ObjectiveValidationCard.',
})
ready?: boolean;
@ApiProperty({ type: ObjectiveDraftDto, required: false })
draft?: ObjectiveDraftDto;
@ApiProperty({
required: false,
description:
'Agent 3 (Niveau) : true quand "levelProfile" est pret pour LevelResultCard.',
})
levelDone?: boolean;
@ApiProperty({ type: LevelProfileDto, required: false })
levelProfile?: LevelProfileDto;
}
@@ -7,4 +7,17 @@ export class SessionObjectiveResponseDto {
@ApiProperty() professionalGoal!: string;
@ApiProperty() duration!: string;
@ApiProperty() validatedAt!: Date;
// Une fois l'objectif confirme, le backend enchaine automatiquement l'Agent 2 (Cartographie)
// puis demarre l'Agent 3 (Niveau) dans le meme appel (voir sessions.service.ts,
// confirmObjective()) : "Max ne parle pas pendant les phases de traitement" sauf pour annoncer
// le debut de l'evaluation de niveau (docs/Max Refonte Coach Freelance.md). Ce champ porte cette
// toute premiere question, a dire a voix haute des que la confirmation reussit - jamais affichee
// en texte.
@ApiProperty({
required: false,
description:
'Premiere question de Max pour l-evaluation de niveau (Agent 3), a dire a voix haute juste apres la confirmation. Absent quand ce DTO ne sert qu-a lire l-etat existant (GET /sessions/:id).',
})
nextPrompt?: string;
}
@@ -11,6 +11,8 @@ describe('SessionsController', () => {
findOne: jest.fn(),
sendObjectiveMessage: jest.fn(),
confirmObjective: jest.fn(),
confirmLevel: jest.fn(),
disputeLevel: jest.fn(),
routeIncomingMessage: jest.fn(),
};
const request = {
@@ -68,6 +70,25 @@ describe('SessionsController', () => {
expect(sessionsService.confirmObjective).toHaveBeenCalledWith(1, 7);
});
it('should confirm the level profile for the authenticated user', async () => {
sessionsService.confirmLevel.mockResolvedValueOnce(undefined);
await controller.confirmLevel(1, request);
expect(sessionsService.confirmLevel).toHaveBeenCalledWith(1, 7);
});
it('should forward a level dispute to the service', async () => {
sessionsService.disputeLevel.mockResolvedValueOnce({ id: 2 });
await controller.disputeLevel(
1,
{ concept: 'TVA', answer: 'Ma reponse' },
request,
);
expect(sessionsService.disputeLevel).toHaveBeenCalledWith(1, 7, {
concept: 'TVA',
answer: 'Ma reponse',
});
});
it('should route an incoming message for the authenticated user', async () => {
sessionsService.routeIncomingMessage.mockResolvedValueOnce({
type: 'chat',
@@ -18,6 +18,8 @@ import {
} from '@nestjs/swagger';
import type { AuthenticatedRequest } from '../auth/jwt-auth.guard';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { LevelDisputeDto } from './dto/level-dispute.dto';
import { LevelProfileResponseDto } from './dto/level-profile-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';
@@ -112,4 +114,40 @@ export class SessionsController {
): Promise<SessionObjectiveResponseDto> {
return this.sessionsService.confirmObjective(id, request.user.sub);
}
@Post(':id/level/confirm')
@HttpCode(HttpStatus.OK)
@ApiOperation({
summary:
"Confirmer le profil de niveau (Agent 3) et declencher l'Agent 4 (Recherche Approfondie)",
})
@ApiResponse({ status: HttpStatus.OK })
@ApiResponse({
status: HttpStatus.CONFLICT,
description: "Cette session n'est plus a l'etape d'evaluation de niveau",
})
confirmLevel(
@Param('id', ParseIntPipe) id: number,
@Req() request: AuthenticatedRequest,
): Promise<void> {
return this.sessionsService.confirmLevel(id, request.user.sub);
}
@Post(':id/level/dispute')
@ApiOperation({
summary:
'Contester un concept du profil de niveau (Agent 3) avec une reponse argumentee, met a jour le profil stocke',
})
@ApiResponse({ status: HttpStatus.CREATED, type: LevelProfileResponseDto })
@ApiResponse({
status: HttpStatus.CONFLICT,
description: "Cette session n'est plus a l'etape d'evaluation de niveau",
})
disputeLevel(
@Param('id', ParseIntPipe) id: number,
@Body() dto: LevelDisputeDto,
@Req() request: AuthenticatedRequest,
): Promise<LevelProfileResponseDto> {
return this.sessionsService.disputeLevel(id, request.user.sub, dto);
}
}
+11 -1
View File
@@ -3,14 +3,24 @@ import { AuthModule } from '../auth/auth.module';
import { LlmModule } from '../llm/llm.module';
import { PrismaModule } from '../prisma/prisma.module';
import { IntentRouterAgent } from './agents/intent-router.agent';
import { LevelAgent } from './agents/level.agent';
import { MappingAgent } from './agents/mapping.agent';
import { ObjectiveAgent } from './agents/objective.agent';
import { ResearchAgent } from './agents/research.agent';
import { SessionsController } from './sessions.controller';
import { SessionsService } from './sessions.service';
@Module({
imports: [PrismaModule, LlmModule, AuthModule],
controllers: [SessionsController],
providers: [SessionsService, ObjectiveAgent, IntentRouterAgent],
providers: [
SessionsService,
ObjectiveAgent,
MappingAgent,
LevelAgent,
ResearchAgent,
IntentRouterAgent,
],
exports: [SessionsService],
})
export class SessionsModule {}
+161 -3
View File
@@ -3,15 +3,32 @@ import { Test, TestingModule } from '@nestjs/testing';
import { OpenRouterService } from '../llm/openrouter.service';
import { PrismaService } from '../prisma/prisma.service';
import { IntentRouterAgent } from './agents/intent-router.agent';
import { LevelAgent } from './agents/level.agent';
import { MappingAgent } from './agents/mapping.agent';
import { ObjectiveAgent } from './agents/objective.agent';
import { ResearchAgent } from './agents/research.agent';
import { SessionsService } from './sessions.service';
describe('SessionsService', () => {
let service: SessionsService;
const prisma = {
session: { create: jest.fn(), findUnique: jest.fn(), findFirst: jest.fn() },
session: {
create: jest.fn(),
findUnique: jest.fn(),
findFirst: jest.fn(),
update: jest.fn(),
},
sessionConceptMap: { findUniqueOrThrow: jest.fn() },
};
const objectiveAgent = { converse: jest.fn(), confirm: jest.fn() };
const mappingAgent = { runForSession: jest.fn() };
const levelAgent = {
start: jest.fn(),
converse: jest.fn(),
confirm: jest.fn(),
dispute: jest.fn(),
};
const researchAgent = { runForSession: jest.fn() };
const intentRouter = { analyze: jest.fn() };
const llm = { chat: jest.fn() };
@@ -22,6 +39,9 @@ describe('SessionsService', () => {
SessionsService,
{ provide: PrismaService, useValue: prisma },
{ provide: ObjectiveAgent, useValue: objectiveAgent },
{ provide: MappingAgent, useValue: mappingAgent },
{ provide: LevelAgent, useValue: levelAgent },
{ provide: ResearchAgent, useValue: researchAgent },
{ provide: IntentRouterAgent, useValue: intentRouter },
{ provide: OpenRouterService, useValue: llm },
],
@@ -109,7 +129,7 @@ describe('SessionsService', () => {
});
describe('confirmObjective()', () => {
it('should map the confirmed objective to a response DTO', async () => {
it('should confirm the objective, then chain Agent 2 (mapping) and start Agent 3 (level), ending with status level_assessment', async () => {
prisma.session.findUnique.mockResolvedValueOnce({
id: 1,
userId: 7,
@@ -124,11 +144,124 @@ describe('SessionsService', () => {
duration: '2 semaines',
validatedAt: new Date('2026-01-02'),
});
prisma.sessionConceptMap.findUniqueOrThrow.mockResolvedValueOnce({
concepts: [{ name: 'Facturation' }, { name: 'TVA' }],
});
levelAgent.start.mockResolvedValueOnce({
reply:
'Si un client te demande une facture avec TVA, comment fais-tu ?',
done: false,
});
const result = await service.confirmObjective(1, 7);
expect(objectiveAgent.confirm).toHaveBeenCalledWith(1, 7);
expect(mappingAgent.runForSession).toHaveBeenCalledWith(
1,
7,
'Facturation freelance pour Facturer sans erreur, en 2 semaines',
);
expect(levelAgent.start).toHaveBeenCalledWith(
1,
7,
'Facturation freelance pour Facturer sans erreur, en 2 semaines',
'Facturation, TVA',
);
expect(prisma.session.update).toHaveBeenCalledWith({
where: { id: 1 },
data: { status: 'mapping' },
});
expect(prisma.session.update).toHaveBeenCalledWith({
where: { id: 1 },
data: { status: 'level_assessment' },
});
expect(result.id).toBe(5);
expect(result.validatedAt).toEqual(new Date('2026-01-02'));
expect(result.nextPrompt).toBe(
'Si un client te demande une facture avec TVA, comment fais-tu ?',
);
});
});
describe('confirmLevel()', () => {
it('should confirm the level profile, run Agent 4, and advance status to planning', async () => {
prisma.session.findUnique.mockResolvedValueOnce({
id: 1,
userId: 7,
status: 'level_assessment',
objective: null,
});
await service.confirmLevel(1, 7);
expect(levelAgent.confirm).toHaveBeenCalledWith(1);
expect(researchAgent.runForSession).toHaveBeenCalledWith(1, 7);
expect(prisma.session.update).toHaveBeenCalledWith({
where: { id: 1 },
data: { status: 'planning' },
});
});
it('should reject when the session is not at the level_assessment stage', async () => {
prisma.session.findUnique.mockResolvedValueOnce({
id: 1,
userId: 7,
status: 'objective_discovery',
objective: null,
});
await expect(service.confirmLevel(1, 7)).rejects.toThrow(
ConflictException,
);
expect(levelAgent.confirm).not.toHaveBeenCalled();
});
});
describe('disputeLevel()', () => {
it('should forward the dispute to the level agent and map the updated profile', async () => {
prisma.session.findUnique.mockResolvedValueOnce({
id: 1,
userId: 7,
status: 'level_assessment',
objective: null,
});
levelAgent.dispute.mockResolvedValueOnce({
id: 2,
sessionId: 1,
masteredConcepts: ['TVA'],
gapConcepts: [],
unknownConcepts: [],
overallLevel: 'intermediate',
completedAt: new Date('2026-01-03'),
});
const result = await service.disputeLevel(1, 7, {
concept: 'TVA',
answer: "J'applique le taux reduit pour ce type de prestation.",
});
expect(levelAgent.dispute).toHaveBeenCalledWith(
1,
7,
'TVA',
"J'applique le taux reduit pour ce type de prestation.",
);
expect(result.mastered).toEqual(['TVA']);
expect(result.overallLevel).toBe('intermediate');
});
it('should reject when the session is not at the level_assessment stage', async () => {
prisma.session.findUnique.mockResolvedValueOnce({
id: 1,
userId: 7,
status: 'planning',
objective: null,
});
await expect(
service.disputeLevel(1, 7, { concept: 'TVA', answer: 'reponse' }),
).rejects.toThrow(ConflictException);
expect(levelAgent.dispute).not.toHaveBeenCalled();
});
});
@@ -164,17 +297,42 @@ describe('SessionsService', () => {
expect(intentRouter.analyze).not.toHaveBeenCalled();
});
it('should route to the level agent when an active level_assessment session exists', async () => {
prisma.session.findFirst.mockResolvedValueOnce({
id: 1,
userId: 7,
status: 'level_assessment',
});
levelAgent.converse.mockResolvedValueOnce({
reply: 'Et pour une facture en devise etrangere ?',
done: false,
});
const result = await service.routeIncomingMessage(7, 'Je dirais ...');
expect(levelAgent.converse).toHaveBeenCalledWith(1, 7, 'Je dirais ...');
expect(objectiveAgent.converse).not.toHaveBeenCalled();
expect(result).toEqual({
type: 'learn',
sessionId: 1,
reply: 'Et pour une facture en devise etrangere ?',
levelDone: false,
levelProfile: undefined,
});
});
it('should reject when the active session is in a status with no agent built yet', async () => {
prisma.session.findFirst.mockResolvedValueOnce({
id: 1,
userId: 7,
status: 'mapping',
status: 'planning',
});
await expect(
service.routeIncomingMessage(7, 'un message'),
).rejects.toThrow(ConflictException);
expect(objectiveAgent.converse).not.toHaveBeenCalled();
expect(levelAgent.converse).not.toHaveBeenCalled();
});
it('should reply conversationally without creating a session when intent is chat', async () => {
+129 -1
View File
@@ -7,7 +7,12 @@ import { Session, SessionObjective } from '@prisma/client';
import { OpenRouterService } from '../llm/openrouter.service';
import { PrismaService } from '../prisma/prisma.service';
import { IntentRouterAgent } from './agents/intent-router.agent';
import { LevelAgent, StoredLevelAssessment } from './agents/level.agent';
import { MappingAgent } from './agents/mapping.agent';
import { ObjectiveAgent, ObjectiveTurnResult } from './agents/objective.agent';
import { ResearchAgent } from './agents/research.agent';
import { LevelDisputeDto } from './dto/level-dispute.dto';
import { LevelProfileResponseDto } from './dto/level-profile-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';
@@ -15,13 +20,22 @@ import { SessionResponseDto } from './dto/session-response.dto';
type SessionWithObjective = Session & { objective: SessionObjective | null };
const IMPLEMENTED_STATUSES = new Set(['objective_discovery']);
// "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).
const IMPLEMENTED_STATUSES = new Set([
'objective_discovery',
'level_assessment',
]);
@Injectable()
export class SessionsService {
constructor(
private readonly prisma: PrismaService,
private readonly objectiveAgent: ObjectiveAgent,
private readonly mappingAgent: MappingAgent,
private readonly levelAgent: LevelAgent,
private readonly researchAgent: ResearchAgent,
private readonly intentRouter: IntentRouterAgent,
private readonly llm: OpenRouterService,
) {}
@@ -46,6 +60,15 @@ export class SessionsService {
return this.objectiveAgent.converse(sessionId, userId, message);
}
/**
* Confirme l'objectif (Agent 1) puis enchaine automatiquement, dans le meme appel : Agent 2
* (Cartographie, aucun tour utilisateur), puis demarre Agent 3 (Niveau) pour obtenir sa
* premiere question. Par le moment ou cette methode repond, session.status vaut deja
* "level_assessment" (voir SessionStatus, docs/Max_System_Prompt.md table des declencheurs).
* Si l'Agent 2 ou l'Agent 3 echoue, l'exception remonte telle quelle : l'objectif reste
* confirme (status="objective_validated") et reappeler cet endpoint relance la chaine de
* maniere idempotente (mappingAgent.runForSession() ne refait rien si la carte existe deja).
*/
async confirmObjective(
sessionId: number,
userId: number,
@@ -53,6 +76,31 @@ export class SessionsService {
const session = await this.findOwnedSession(sessionId, userId);
this.assertObjectiveDiscoveryInProgress(session);
const objective = await this.objectiveAgent.confirm(sessionId, userId);
const objectiveSummary = `${objective.subject} pour ${objective.professionalGoal}, en ${objective.duration}`;
await this.prisma.session.update({
where: { id: sessionId },
data: { status: 'mapping' },
});
await this.mappingAgent.runForSession(sessionId, userId, objectiveSummary);
await this.prisma.session.update({
where: { id: sessionId },
data: { status: 'level_assessment' },
});
const conceptMap = await this.prisma.sessionConceptMap.findUniqueOrThrow({
where: { sessionId },
});
const conceptMapSummary = this.summarizeConceptMap(
conceptMap.concepts as unknown as { name: string }[],
);
const firstTurn = await this.levelAgent.start(
sessionId,
userId,
objectiveSummary,
conceptMapSummary,
);
return {
id: objective.id,
sessionId: objective.sessionId,
@@ -60,9 +108,51 @@ export class SessionsService {
professionalGoal: objective.professionalGoal,
duration: objective.duration,
validatedAt: objective.validatedAt ?? new Date(),
nextPrompt: firstTurn.reply,
};
}
/**
* 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).
*/
async confirmLevel(sessionId: number, userId: number): Promise<void> {
const session = await this.findOwnedSession(sessionId, userId);
if (session.status !== 'level_assessment') {
throw new ConflictException(
"Cette session n'est plus a l'etape d'evaluation de niveau.",
);
}
await this.levelAgent.confirm(sessionId);
await this.researchAgent.runForSession(sessionId, userId);
await this.prisma.session.update({
where: { id: sessionId },
data: { status: 'planning' },
});
}
async disputeLevel(
sessionId: number,
userId: number,
dto: LevelDisputeDto,
): Promise<LevelProfileResponseDto> {
const session = await this.findOwnedSession(sessionId, userId);
if (session.status !== 'level_assessment') {
throw new ConflictException(
"Cette session n'est plus a l'etape d'evaluation de niveau.",
);
}
const updated = await this.levelAgent.dispute(
sessionId,
userId,
dto.concept,
dto.answer,
);
return this.toLevelProfileResponse(updated);
}
/**
* Porte d'entree unique du chat (docs/Max_System_Prompt.md) : route vers l'agent de la session
* active si elle existe, sinon classifie le message (routeur d'intention) pour decider de
@@ -84,6 +174,22 @@ export class SessionsService {
"Cette etape du pipeline n'est pas encore implementee.",
);
}
if (activeSession.status === 'level_assessment') {
const turn = await this.levelAgent.converse(
activeSession.id,
userId,
message,
);
return {
type: 'learn',
sessionId: activeSession.id,
reply: turn.reply,
levelDone: turn.done,
levelProfile: turn.profile,
};
}
const result = await this.sendObjectiveMessage(
activeSession.id,
userId,
@@ -146,6 +252,28 @@ export class SessionsService {
}
}
private summarizeConceptMap(concepts: { name: string }[]): string {
return concepts.map((c) => c.name).join(', ');
}
private toLevelProfileResponse(
record: StoredLevelAssessment,
): LevelProfileResponseDto {
return {
id: record.id,
sessionId: record.sessionId,
mastered: record.masteredConcepts as string[],
gaps: record.gapConcepts as {
concept: string;
description: string;
}[],
unknown: record.unknownConcepts as string[],
overallLevel: record.overallLevel as
'beginner' | 'intermediate' | 'advanced',
completedAt: record.completedAt ?? undefined,
};
}
private toResponse(session: SessionWithObjective): SessionResponseDto {
return {
id: session.id,