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
+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 () => {