From bae5ace70cbd72a8ced15bf36323a08441514b8e Mon Sep 17 00:00:00 2001 From: william Date: Sat, 31 Oct 2026 20:16:03 +0100 Subject: [PATCH] feat(sessions): implement Agent 1 (Objectif) of the coach pipeline Add the sessions module (create/fetch session, Agent 1 conversation and confirmation endpoints, all JWT-protected) and a reusable OpenRouter client with DeepSeek/Qwen fallback + backoff on rate-limit/timeout. Agent 1 runs a Socratic dialogue to capture the 3 mandatory pillars (subject, professional goal, duration) and enforces two guardrail levels before any explicit user confirmation: level 1 is hard-coded length/format rules (objective-guardrails.ts), level 2 is an LLM coherence score across 3 dimensions (reject below 0.6). The objective is only persisted to session_objective, and the session only moves to objective_validated, once the user explicitly confirms via POST /sessions/:id/objective/confirm - never on the LLM's say-so alone. Co-Authored-By: Claude Sonnet 5 --- Max API/src/app.module.ts | 2 + Max API/src/auth/auth.module.ts | 1 + Max API/src/common/errors/api-error.ts | 12 + Max API/src/llm/llm.module.ts | 10 + Max API/src/llm/openrouter.service.spec.ts | 112 ++++++++ Max API/src/llm/openrouter.service.ts | 107 ++++++++ .../agents/objective-guardrails.spec.ts | 61 +++++ .../sessions/agents/objective-guardrails.ts | 88 +++++++ .../sessions/agents/objective.agent.spec.ts | 173 +++++++++++++ .../src/sessions/agents/objective.agent.ts | 239 ++++++++++++++++++ .../dto/objective-message-response.dto.ts | 24 ++ .../dto/send-objective-message.dto.ts | 12 + .../dto/session-objective-response.dto.ts | 10 + .../src/sessions/dto/session-response.dto.ts | 12 + .../src/sessions/sessions.controller.spec.ts | 69 +++++ Max API/src/sessions/sessions.controller.ts | 94 +++++++ Max API/src/sessions/sessions.module.ts | 15 ++ Max API/src/sessions/sessions.service.spec.ts | 128 ++++++++++ Max API/src/sessions/sessions.service.ts | 101 ++++++++ 19 files changed, 1270 insertions(+) create mode 100644 Max API/src/common/errors/api-error.ts create mode 100644 Max API/src/llm/llm.module.ts create mode 100644 Max API/src/llm/openrouter.service.spec.ts create mode 100644 Max API/src/llm/openrouter.service.ts create mode 100644 Max API/src/sessions/agents/objective-guardrails.spec.ts create mode 100644 Max API/src/sessions/agents/objective-guardrails.ts create mode 100644 Max API/src/sessions/agents/objective.agent.spec.ts create mode 100644 Max API/src/sessions/agents/objective.agent.ts create mode 100644 Max API/src/sessions/dto/objective-message-response.dto.ts create mode 100644 Max API/src/sessions/dto/send-objective-message.dto.ts create mode 100644 Max API/src/sessions/dto/session-objective-response.dto.ts create mode 100644 Max API/src/sessions/dto/session-response.dto.ts create mode 100644 Max API/src/sessions/sessions.controller.spec.ts create mode 100644 Max API/src/sessions/sessions.controller.ts create mode 100644 Max API/src/sessions/sessions.module.ts create mode 100644 Max API/src/sessions/sessions.service.spec.ts create mode 100644 Max API/src/sessions/sessions.service.ts diff --git a/Max API/src/app.module.ts b/Max API/src/app.module.ts index 52e196b..ba460de 100644 --- a/Max API/src/app.module.ts +++ b/Max API/src/app.module.ts @@ -5,6 +5,7 @@ import { AppController } from './app.controller'; import { AuthModule } from './auth/auth.module'; import { CryptoModule } from './common/crypto/crypto.module'; import { PrismaModule } from './prisma/prisma.module'; +import { SessionsModule } from './sessions/sessions.module'; import { UsersModule } from './users/users.module'; @Module({ @@ -15,6 +16,7 @@ import { UsersModule } from './users/users.module'; UsersModule, ApiKeysModule, AuthModule, + SessionsModule, ], controllers: [AppController], }) diff --git a/Max API/src/auth/auth.module.ts b/Max API/src/auth/auth.module.ts index e7a3ab4..376b9eb 100644 --- a/Max API/src/auth/auth.module.ts +++ b/Max API/src/auth/auth.module.ts @@ -24,5 +24,6 @@ const ACCESS_TOKEN_TTL = '1h'; ], controllers: [AuthController], providers: [AuthService, JwtAuthGuard], + exports: [JwtAuthGuard], }) export class AuthModule {} diff --git a/Max API/src/common/errors/api-error.ts b/Max API/src/common/errors/api-error.ts new file mode 100644 index 0000000..870b579 --- /dev/null +++ b/Max API/src/common/errors/api-error.ts @@ -0,0 +1,12 @@ +export type ApiErrorService = 'openrouter' | 'elevenlabs' | 'whisper'; + +export class ApiError extends Error { + constructor( + message: string, + public readonly service: ApiErrorService, + public readonly statusCode?: number, + ) { + super(message); + this.name = 'ApiError'; + } +} diff --git a/Max API/src/llm/llm.module.ts b/Max API/src/llm/llm.module.ts new file mode 100644 index 0000000..585849f --- /dev/null +++ b/Max API/src/llm/llm.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { ApiKeysModule } from '../api-keys/api-keys.module'; +import { OpenRouterService } from './openrouter.service'; + +@Module({ + imports: [ApiKeysModule], + providers: [OpenRouterService], + exports: [OpenRouterService], +}) +export class LlmModule {} diff --git a/Max API/src/llm/openrouter.service.spec.ts b/Max API/src/llm/openrouter.service.spec.ts new file mode 100644 index 0000000..c3da222 --- /dev/null +++ b/Max API/src/llm/openrouter.service.spec.ts @@ -0,0 +1,112 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { ApiKeysService } from '../api-keys/api-keys.service'; +import { ApiError } from '../common/errors/api-error'; +import { OpenRouterService } from './openrouter.service'; + +describe('OpenRouterService', () => { + let service: OpenRouterService; + const getDecryptedValue = jest.fn(() => Promise.resolve('sk-or-v1-test')); + + beforeEach(async () => { + jest.clearAllMocks(); + jest.useFakeTimers(); + const module: TestingModule = await Test.createTestingModule({ + providers: [ + OpenRouterService, + { provide: ApiKeysService, useValue: { getDecryptedValue } }, + ], + }).compile(); + + service = module.get(OpenRouterService); + jest.spyOn(global, 'fetch'); + }); + + afterEach(() => { + jest.useRealTimers(); + jest.restoreAllMocks(); + }); + + function mockFetchOnce(impl: () => Promise | Response): void { + (global.fetch as jest.Mock).mockImplementationOnce(impl); + } + + describe('chat()', () => { + it('should return assistant message when the API responds successfully', async () => { + mockFetchOnce( + () => + new Response( + JSON.stringify({ choices: [{ message: { content: 'Bonjour' } }] }), + { status: 200 }, + ), + ); + + const result = await service.chat(1, [ + { role: 'user', content: 'Salut' }, + ]); + + expect(result).toBe('Bonjour'); + expect(getDecryptedValue).toHaveBeenCalledWith(1, 'openrouter_api_key'); + }); + + it('should fall back to Qwen when the primary model errors', async () => { + mockFetchOnce(() => new Response('erreur serveur', { status: 500 })); + mockFetchOnce( + () => + new Response( + JSON.stringify({ + choices: [{ message: { content: 'Reponse secours' } }], + }), + { status: 200 }, + ), + ); + + const result = await service.chat(1, [ + { role: 'user', content: 'Salut' }, + ]); + + expect(result).toBe('Reponse secours'); + expect(global.fetch).toHaveBeenCalledTimes(2); + }); + + it('should retry with backoff on 429 before succeeding', async () => { + mockFetchOnce(() => new Response('rate limited', { status: 429 })); + mockFetchOnce( + () => + new Response( + JSON.stringify({ + choices: [{ message: { content: 'OK apres attente' } }], + }), + { status: 200 }, + ), + ); + + const promise = service.chat(1, [{ role: 'user', content: 'Salut' }]); + await jest.runAllTimersAsync(); + const result = await promise; + + expect(result).toBe('OK apres attente'); + }); + + it('should throw ApiError when every model is unreachable', async () => { + mockFetchOnce(() => Promise.reject(new Error('network down'))); + mockFetchOnce(() => Promise.reject(new Error('network down'))); + mockFetchOnce(() => Promise.reject(new Error('network down'))); + mockFetchOnce(() => Promise.reject(new Error('network down'))); + + await expect( + service.chat(1, [{ role: 'user', content: 'Salut' }]), + ).rejects.toThrow(ApiError); + }); + + it('should throw ApiError when the response is HTTP 200 without choices', async () => { + mockFetchOnce(() => new Response(JSON.stringify({}), { status: 200 })); + mockFetchOnce(() => new Response(JSON.stringify({}), { status: 200 })); + mockFetchOnce(() => new Response(JSON.stringify({}), { status: 200 })); + mockFetchOnce(() => new Response(JSON.stringify({}), { status: 200 })); + + await expect( + service.chat(1, [{ role: 'user', content: 'Salut' }]), + ).rejects.toThrow(/malformee/); + }); + }); +}); diff --git a/Max API/src/llm/openrouter.service.ts b/Max API/src/llm/openrouter.service.ts new file mode 100644 index 0000000..1fc081c --- /dev/null +++ b/Max API/src/llm/openrouter.service.ts @@ -0,0 +1,107 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { ApiKeysService } from '../api-keys/api-keys.service'; +import { ApiError } from '../common/errors/api-error'; + +export interface ChatMessage { + role: 'system' | 'user' | 'assistant'; + content: string; +} + +interface OpenRouterChoice { + message?: { content?: string }; +} + +interface OpenRouterResponseBody { + choices?: OpenRouterChoice[]; + error?: { message?: string }; +} + +const OPENROUTER_URL = 'https://openrouter.ai/api/v1/chat/completions'; +const PRIMARY_MODEL = 'deepseek/deepseek-chat'; +const FALLBACK_MODEL = 'qwen/qwen-2.5-72b-instruct'; +const OPENROUTER_KEY_SERVICE = 'openrouter_api_key'; +const MAX_ATTEMPTS = 4; +const RATE_LIMITED_STATUSES = new Set([429, 504]); + +function delay(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +/** + * Client OpenRouter avec bascule DeepSeek -> Qwen (voir CLAUDE.md section 2) : jusqu'a + * MAX_ATTEMPTS tentatives en alternant les deux modeles, avec backoff exponentiel sur + * rate-limit (429) et timeout (504). Le meme historique de messages est reutilise quel que + * soit le modele qui finit par repondre, pour que la bascule reste transparente. + */ +@Injectable() +export class OpenRouterService { + private readonly logger = new Logger(OpenRouterService.name); + + constructor(private readonly apiKeysService: ApiKeysService) {} + + async chat( + userId: number, + messages: ChatMessage[], + options: { jsonResponse?: boolean } = {}, + ): Promise { + const apiKey = await this.apiKeysService.getDecryptedValue( + userId, + OPENROUTER_KEY_SERVICE, + ); + + let lastError = 'raison inconnue'; + + for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) { + const model = attempt % 2 === 0 ? PRIMARY_MODEL : FALLBACK_MODEL; + let response: Response; + try { + response = await fetch(OPENROUTER_URL, { + method: 'POST', + headers: { + Authorization: `Bearer ${apiKey}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + model, + messages, + ...(options.jsonResponse + ? { response_format: { type: 'json_object' } } + : {}), + }), + }); + } catch (error) { + lastError = error instanceof Error ? error.message : String(error); + this.logger.warn(`${model} injoignable (${lastError})`); + continue; + } + + if (RATE_LIMITED_STATUSES.has(response.status)) { + lastError = `${response.status}: rate-limit ou timeout`; + this.logger.warn(`${model} ${lastError}, nouvelle tentative`); + await delay(2 ** attempt * 250); + continue; + } + + if (!response.ok) { + lastError = `${response.status}: ${await response.text()}`; + this.logger.warn(`${model} a renvoye une erreur (${lastError})`); + continue; + } + + const parsed = (await response.json()) as OpenRouterResponseBody; + const content = parsed.choices?.[0]?.message?.content; + if (!content) { + lastError = `reponse malformee (${parsed.error?.message ?? 'choices manquant'})`; + this.logger.warn(`${model}: ${lastError}`); + continue; + } + + return content; + } + + throw new ApiError( + `Aucun modele OpenRouter n'a pu repondre (${lastError})`, + 'openrouter', + ); + } +} diff --git a/Max API/src/sessions/agents/objective-guardrails.spec.ts b/Max API/src/sessions/agents/objective-guardrails.spec.ts new file mode 100644 index 0000000..bec4735 --- /dev/null +++ b/Max API/src/sessions/agents/objective-guardrails.spec.ts @@ -0,0 +1,61 @@ +import { + checkLevel1Guardrails, + parseDurationHours, +} from './objective-guardrails'; + +describe('parseDurationHours()', () => { + it('should parse hours, days, weeks and months into hours', () => { + expect(parseDurationHours('10 heures')).toBe(10); + expect(parseDurationHours('2 jours')).toBe(48); + expect(parseDurationHours('2 semaines')).toBe(336); + expect(parseDurationHours('1 mois')).toBe(720); + }); + + it('should accept a decimal amount', () => { + expect(parseDurationHours('1,5 jours')).toBe(36); + }); + + it('should return null for an unrecognized format', () => { + expect(parseDurationHours('bientot')).toBeNull(); + expect(parseDurationHours('')).toBeNull(); + }); +}); + +describe('checkLevel1Guardrails()', () => { + const validDraft = { + subject: 'Facturation freelance en micro-entreprise', + professionalGoal: + 'Pouvoir facturer mes clients sans erreur des le mois prochain', + duration: '2 semaines', + }; + + it('should return no failure for a valid draft', () => { + expect(checkLevel1Guardrails(validDraft)).toEqual([]); + }); + + it('should reject a subject that is too short or a single generic word', () => { + const failures = checkLevel1Guardrails({ ...validDraft, subject: 'Excel' }); + expect(failures.map((f) => f.field)).toContain('subject'); + }); + + it('should reject a professional goal that is too short', () => { + const failures = checkLevel1Guardrails({ + ...validDraft, + professionalGoal: 'Progresser', + }); + expect(failures.map((f) => f.field)).toContain('professionalGoal'); + }); + + it('should reject a duration outside 1h-12 weeks or unparseable', () => { + expect( + checkLevel1Guardrails({ ...validDraft, duration: 'un bon moment' }).map( + (f) => f.field, + ), + ).toContain('duration'); + expect( + checkLevel1Guardrails({ ...validDraft, duration: '24 mois' }).map( + (f) => f.field, + ), + ).toContain('duration'); + }); +}); diff --git a/Max API/src/sessions/agents/objective-guardrails.ts b/Max API/src/sessions/agents/objective-guardrails.ts new file mode 100644 index 0000000..4af14d0 --- /dev/null +++ b/Max API/src/sessions/agents/objective-guardrails.ts @@ -0,0 +1,88 @@ +export interface ObjectiveDraft { + subject: string; + professionalGoal: string; + duration: string; +} + +export interface GuardrailFailure { + field: 'subject' | 'professionalGoal' | 'duration'; + reason: string; +} + +const MIN_SUBJECT_LENGTH = 10; +const MIN_GOAL_LENGTH = 20; +const MIN_DURATION_HOURS = 1; +const MAX_DURATION_HOURS = 12 * 7 * 24; + +const DURATION_UNIT_HOURS = new Map([ + ['heure', 1], + ['heures', 1], + ['h', 1], + ['jour', 24], + ['jours', 24], + ['j', 24], + ['semaine', 7 * 24], + ['semaines', 7 * 24], + ['mois', 30 * 24], +]); + +/** + * Parse une duree en langage libre ("2 semaines", "10h", "1 mois") en heures. Retourne null si + * le format n'est pas reconnu, pour que l'appelant puisse redemander une reformulation plutot + * que de faire confiance a un texte non structure. + */ +export function parseDurationHours(duration: string): number | null { + const normalized = duration.trim().toLowerCase(); + const separatorIndex = normalized.search(/[a-zéû]/); + if (separatorIndex <= 0) return null; + + const amount = Number.parseFloat( + normalized.slice(0, separatorIndex).trim().replace(',', '.'), + ); + const unit = normalized.slice(separatorIndex).trim(); + const hoursPerUnit = DURATION_UNIT_HOURS.get(unit); + if (hoursPerUnit === undefined || Number.isNaN(amount)) return null; + return amount * hoursPerUnit; +} + +/** + * Garde-fous de niveau 1 (regles codees, voir CLAUDE.md section 2 / docs/Max Refonte Coach + * Freelance.md) : longueur/format uniquement, aucun appel LLM. Renvoie la liste des champs en + * echec, vide si l'objectif est recevable. + */ +export function checkLevel1Guardrails( + draft: ObjectiveDraft, +): GuardrailFailure[] { + const failures: GuardrailFailure[] = []; + + const subject = draft.subject.trim(); + if (subject.length < MIN_SUBJECT_LENGTH || !subject.includes(' ')) { + failures.push({ + field: 'subject', + reason: `Le sujet doit faire au moins ${MIN_SUBJECT_LENGTH} caracteres et ne pas etre un terme generique isole.`, + }); + } + + const professionalGoal = draft.professionalGoal.trim(); + if (professionalGoal.length < MIN_GOAL_LENGTH) { + failures.push({ + field: 'professionalGoal', + reason: `Le but professionnel doit faire au moins ${MIN_GOAL_LENGTH} caracteres.`, + }); + } + + const durationHours = parseDurationHours(draft.duration); + if ( + durationHours === null || + durationHours < MIN_DURATION_HOURS || + durationHours > MAX_DURATION_HOURS + ) { + failures.push({ + field: 'duration', + reason: + 'La duree doit etre comprise entre 1 heure et 12 semaines (ex: "2 semaines", "10 heures").', + }); + } + + return failures; +} diff --git a/Max API/src/sessions/agents/objective.agent.spec.ts b/Max API/src/sessions/agents/objective.agent.spec.ts new file mode 100644 index 0000000..d222ce0 --- /dev/null +++ b/Max API/src/sessions/agents/objective.agent.spec.ts @@ -0,0 +1,173 @@ +import { ConflictException } from '@nestjs/common'; +import { Test, TestingModule } from '@nestjs/testing'; +import { PrismaService } from '../../prisma/prisma.service'; +import { OpenRouterService } from '../../llm/openrouter.service'; +import { ObjectiveAgent } from './objective.agent'; + +describe('ObjectiveAgent', () => { + let agent: ObjectiveAgent; + const chat = jest.fn(); + const createSessionObjective = jest.fn< + Promise, + [{ data: Record }] + >(); + const prisma = { + sessionObjective: { create: createSessionObjective }, + session: { update: jest.fn() }, + }; + + const validDraft = { + subject: 'Facturation freelance en micro-entreprise', + professionalGoal: + 'Pouvoir facturer mes clients sans erreur des le mois prochain', + duration: '2 semaines', + }; + + beforeEach(async () => { + jest.clearAllMocks(); + const module: TestingModule = await Test.createTestingModule({ + providers: [ + ObjectiveAgent, + { provide: PrismaService, useValue: prisma }, + { provide: OpenRouterService, useValue: { chat } }, + ], + }).compile(); + + agent = module.get(ObjectiveAgent); + }); + + describe('converse()', () => { + it('should return the raw reply unready when the model answers with non-JSON text', async () => { + chat.mockResolvedValueOnce('Je ne comprends pas'); + + const result = await agent.converse(1, 7, 'bonjour'); + + expect(result).toEqual({ reply: 'Je ne comprends pas', ready: false }); + }); + + it('should keep asking when the model is not ready to confirm', async () => { + chat.mockResolvedValueOnce( + JSON.stringify({ + message: 'Quel est ton sujet ?', + readyToConfirm: false, + }), + ); + + const result = await agent.converse(1, 7, 'Je veux apprendre un truc'); + + expect(result).toEqual({ reply: 'Quel est ton sujet ?', ready: false }); + }); + + it('should reject a ready draft that fails level 1 guardrails without calling the coherence scorer', async () => { + chat.mockResolvedValueOnce( + JSON.stringify({ + message: 'Recap', + readyToConfirm: true, + subject: 'Excel', + professionalGoal: validDraft.professionalGoal, + duration: validDraft.duration, + }), + ); + + const result = await agent.converse(1, 7, 'Excel'); + + expect(result.ready).toBe(false); + expect(result.reply).toMatch(/sujet/); + expect(chat).toHaveBeenCalledTimes(1); + }); + + it('should reject a draft that fails the level 2 coherence score', async () => { + chat + .mockResolvedValueOnce( + JSON.stringify({ + message: 'Recap', + readyToConfirm: true, + ...validDraft, + }), + ) + .mockResolvedValueOnce( + JSON.stringify({ + clarity: 0.9, + specificity: 0.3, + feasibility: 0.9, + followUpQuestion: 'Peux-tu preciser le sujet ?', + }), + ); + + const result = await agent.converse(1, 7, 'message'); + + expect(result).toEqual({ + reply: 'Peux-tu preciser le sujet ?', + ready: false, + }); + }); + + it('should return ready with the draft when both guardrail levels pass', async () => { + chat + .mockResolvedValueOnce( + JSON.stringify({ + message: 'Voici le recap, confirmes-tu ?', + readyToConfirm: true, + ...validDraft, + }), + ) + .mockResolvedValueOnce( + JSON.stringify({ clarity: 0.9, specificity: 0.9, feasibility: 0.9 }), + ); + + const result = await agent.converse(1, 7, 'message'); + + expect(result).toEqual({ + reply: 'Voici le recap, confirmes-tu ?', + ready: true, + draft: validDraft, + }); + }); + }); + + describe('confirm()', () => { + it('should throw ConflictException when no draft is ready for this session', async () => { + await expect(agent.confirm(1, 7)).rejects.toThrow(ConflictException); + }); + + it('should persist the objective and move the session to objective_validated once ready', async () => { + chat + .mockResolvedValueOnce( + JSON.stringify({ + message: 'Recap', + readyToConfirm: true, + ...validDraft, + }), + ) + .mockResolvedValueOnce( + JSON.stringify({ clarity: 0.9, specificity: 0.9, feasibility: 0.9 }), + ); + await agent.converse(1, 7, 'message'); + + chat.mockResolvedValueOnce( + JSON.stringify({ clarity: 0.9, specificity: 0.9, feasibility: 0.9 }), + ); + prisma.sessionObjective.create.mockResolvedValueOnce({ + id: 1, + sessionId: 1, + ...validDraft, + validatedAt: new Date('2026-01-01'), + }); + + const result = await agent.confirm(1, 7); + + const createCallArgs = prisma.sessionObjective.create.mock.calls[0][0]; + expect(createCallArgs.data).toMatchObject({ + sessionId: 1, + ...validDraft, + }); + expect(prisma.session.update).toHaveBeenCalledWith({ + where: { id: 1 }, + data: { status: 'objective_validated' }, + }); + expect(result.id).toBe(1); + + await expect(agent.confirm(1, 7)).rejects.toThrow(ConflictException); + }); + }); +}); diff --git a/Max API/src/sessions/agents/objective.agent.ts b/Max API/src/sessions/agents/objective.agent.ts new file mode 100644 index 0000000..8df50ff --- /dev/null +++ b/Max API/src/sessions/agents/objective.agent.ts @@ -0,0 +1,239 @@ +import { ConflictException, Injectable, Logger } from '@nestjs/common'; +import { PrismaService } from '../../prisma/prisma.service'; +import { ChatMessage, OpenRouterService } from '../../llm/openrouter.service'; +import { + checkLevel1Guardrails, + GuardrailFailure, + ObjectiveDraft, +} from './objective-guardrails'; + +export interface ObjectiveTurnResult { + reply: string; + ready: boolean; + draft?: ObjectiveDraft; +} + +export interface ValidatedSessionObjective { + id: number; + sessionId: number; + subject: string; + professionalGoal: string; + duration: string; + validatedAt: Date | null; +} + +interface AgentJsonReply { + message: string; + subject?: string | null; + professionalGoal?: string | null; + duration?: string | null; + readyToConfirm?: boolean; +} + +interface CoherenceScore { + clarity: number; + specificity: number; + feasibility: number; + followUpQuestion?: string; +} + +const COHERENCE_THRESHOLD = 0.6; + +const SYSTEM_PROMPT = `Tu es Max, un coach de formation pour freelances. Ton seul objectif dans cet +echange est de reveler et faire formuler par l'utilisateur, par un dialogue socratique (des +questions, jamais un formulaire), un objectif de formation precis compose de 3 piliers +obligatoires : +1. subject : le sujet concret a apprendre (jamais un terme generique isole comme "Excel" ou + "marketing" : il doit designer une competence precise, utilisable dans une mission reelle). +2. professionalGoal : ce que l'utilisateur pourra faire professionnellement une fois la + formation terminee (une situation concrete de mission ou de client, pas juste "progresser"). +3. duration : le temps que l'utilisateur veut y consacrer, entre 1 heure et 12 semaines, dans un + format court ("10 heures", "2 semaines", "1 mois"). + +Pose une question a la fois, rebondis sur les reponses de l'utilisateur, et ne propose +"readyToConfirm": true que lorsque les 3 piliers sont clairement etablis ET que tu as deja +presente un recapitulatif dans "message" en demandant explicitement a l'utilisateur de confirmer. + +Reponds TOUJOURS avec un objet JSON strict, sans texte autour, de la forme : +{"message": "...", "subject": "..." | null, "professionalGoal": "..." | null, "duration": "..." | null, "readyToConfirm": true | false}`; + +const COHERENCE_SYSTEM_PROMPT = `Tu evalues la coherence d'un objectif de formation freelance +compose de 3 champs (subject, professionalGoal, duration). Note chaque dimension entre 0 et 1 : +- clarity : l'objectif est-il formule de maniere claire et non ambigue ? +- specificity : le sujet est-il assez precis (pas un terme generique) ? +- feasibility : le but professionnel est-il atteignable dans la duree indiquee ? + +Si une dimension est en dessous de 0.6, propose dans "followUpQuestion" une question precise a +poser a l'utilisateur pour ameliorer ce point. Reponds UNIQUEMENT avec un objet JSON strict : +{"clarity": 0.0, "specificity": 0.0, "feasibility": 0.0, "followUpQuestion": "..." | null}`; + +/** + * Agent 1 du pipeline (voir CLAUDE.md section 1 / docs/Max Refonte Coach Freelance.md) : + * dialogue socratique + garde-fous a deux niveaux (regles codees, puis score de coherence LLM) + * avant confirmation explicite de l'utilisateur. L'historique de conversation est ephemere + * (en memoire, par session) : rien n'est stocke en base avant la confirmation explicite. + */ +@Injectable() +export class ObjectiveAgent { + private readonly logger = new Logger(ObjectiveAgent.name); + private readonly conversations = new Map(); + private readonly readyDrafts = new Map(); + + constructor( + private readonly prisma: PrismaService, + private readonly llm: OpenRouterService, + ) {} + + async converse( + sessionId: number, + userId: number, + userMessage: string, + ): Promise { + const history = this.conversations.get(sessionId) ?? [ + { role: 'system', content: SYSTEM_PROMPT }, + ]; + history.push({ role: 'user', content: userMessage }); + + const raw = await this.llm.chat(userId, history, { jsonResponse: true }); + history.push({ role: 'assistant', content: raw }); + this.conversations.set(sessionId, history); + + const parsed = this.parseAgentReply(raw); + if (!parsed) { + return { reply: raw, ready: false }; + } + + if ( + !parsed.readyToConfirm || + !parsed.subject || + !parsed.professionalGoal || + !parsed.duration + ) { + return { reply: parsed.message, ready: false }; + } + + const draft: ObjectiveDraft = { + subject: parsed.subject, + professionalGoal: parsed.professionalGoal, + duration: parsed.duration, + }; + + const level1Failures = checkLevel1Guardrails(draft); + if (level1Failures.length > 0) { + const reply = this.describeLevel1Failures(level1Failures); + history.push({ role: 'assistant', content: reply }); + return { reply, ready: false }; + } + + const coherence = await this.scoreCoherence(userId, draft); + if (!this.passesCoherence(coherence)) { + const reply = + coherence.followUpQuestion ?? + 'Peux-tu preciser ton objectif pour le rendre plus concret ?'; + history.push({ role: 'assistant', content: reply }); + return { reply, ready: false }; + } + + this.readyDrafts.set(sessionId, draft); + return { reply: parsed.message, ready: true, draft }; + } + + async confirm( + sessionId: number, + userId: number, + ): Promise { + const draft = this.readyDrafts.get(sessionId); + if (!draft) { + throw new ConflictException( + "Aucun objectif pret a etre confirme pour cette session : continue le dialogue d'abord.", + ); + } + + const level1Failures = checkLevel1Guardrails(draft); + const coherence = + level1Failures.length === 0 + ? await this.scoreCoherence(userId, draft) + : null; + if ( + level1Failures.length > 0 || + !coherence || + !this.passesCoherence(coherence) + ) { + this.readyDrafts.delete(sessionId); + throw new ConflictException( + "L'objectif n'est plus valide, reprends le dialogue pour le reformuler.", + ); + } + + const objective = await this.prisma.sessionObjective.create({ + data: { + sessionId, + subject: draft.subject, + professionalGoal: draft.professionalGoal, + duration: draft.duration, + validatedAt: new Date(), + }, + }); + await this.prisma.session.update({ + where: { id: sessionId }, + data: { status: 'objective_validated' }, + }); + + this.conversations.delete(sessionId); + this.readyDrafts.delete(sessionId); + + return objective; + } + + private parseAgentReply(raw: string): AgentJsonReply | null { + try { + const parsed = JSON.parse(raw) as AgentJsonReply; + if (typeof parsed.message !== 'string') return null; + return parsed; + } catch { + this.logger.warn( + `Reponse de l'agent non-JSON, affichee telle quelle: ${raw}`, + ); + return null; + } + } + + private async scoreCoherence( + userId: number, + draft: ObjectiveDraft, + ): Promise { + const raw = await this.llm.chat( + userId, + [ + { role: 'system', content: COHERENCE_SYSTEM_PROMPT }, + { role: 'user', content: JSON.stringify(draft) }, + ], + { jsonResponse: true }, + ); + try { + return JSON.parse(raw) as CoherenceScore; + } catch { + this.logger.warn( + `Score de coherence non-JSON, objectif rejete par prudence: ${raw}`, + ); + return { + clarity: 0, + specificity: 0, + feasibility: 0, + followUpQuestion: 'Peux-tu reformuler ton objectif plus precisement ?', + }; + } + } + + private passesCoherence(score: CoherenceScore): boolean { + return ( + score.clarity >= COHERENCE_THRESHOLD && + score.specificity >= COHERENCE_THRESHOLD && + score.feasibility >= COHERENCE_THRESHOLD + ); + } + + private describeLevel1Failures(failures: GuardrailFailure[]): string { + return `Pas tout a fait : ${failures.map((f) => f.reason).join(' ')}`; + } +} diff --git a/Max API/src/sessions/dto/objective-message-response.dto.ts b/Max API/src/sessions/dto/objective-message-response.dto.ts new file mode 100644 index 0000000..32f345d --- /dev/null +++ b/Max API/src/sessions/dto/objective-message-response.dto.ts @@ -0,0 +1,24 @@ +import { ApiProperty } from '@nestjs/swagger'; + +export class ObjectiveDraftDto { + @ApiProperty() subject!: string; + @ApiProperty() professionalGoal!: string; + @ApiProperty() duration!: string; +} + +export class ObjectiveMessageResponseDto { + @ApiProperty({ + description: + "Prochaine question de Max, ou recapitulatif si l'objectif est pret.", + }) + reply!: string; + + @ApiProperty({ + description: + 'true si les 3 piliers sont valides (garde-fous niveau 1 et 2) et prets a etre confirmes via POST /sessions/:id/objective/confirm.', + }) + ready!: boolean; + + @ApiProperty({ type: ObjectiveDraftDto, required: false }) + draft?: ObjectiveDraftDto; +} diff --git a/Max API/src/sessions/dto/send-objective-message.dto.ts b/Max API/src/sessions/dto/send-objective-message.dto.ts new file mode 100644 index 0000000..d777651 --- /dev/null +++ b/Max API/src/sessions/dto/send-objective-message.dto.ts @@ -0,0 +1,12 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { IsString, MaxLength, MinLength } from 'class-validator'; + +export class SendObjectiveMessageDto { + @ApiProperty({ + example: 'Je voudrais apprendre a mieux facturer mes clients', + }) + @IsString() + @MinLength(1) + @MaxLength(2000) + message!: string; +} diff --git a/Max API/src/sessions/dto/session-objective-response.dto.ts b/Max API/src/sessions/dto/session-objective-response.dto.ts new file mode 100644 index 0000000..0741802 --- /dev/null +++ b/Max API/src/sessions/dto/session-objective-response.dto.ts @@ -0,0 +1,10 @@ +import { ApiProperty } from '@nestjs/swagger'; + +export class SessionObjectiveResponseDto { + @ApiProperty() id!: number; + @ApiProperty() sessionId!: number; + @ApiProperty() subject!: string; + @ApiProperty() professionalGoal!: string; + @ApiProperty() duration!: string; + @ApiProperty() validatedAt!: Date; +} diff --git a/Max API/src/sessions/dto/session-response.dto.ts b/Max API/src/sessions/dto/session-response.dto.ts new file mode 100644 index 0000000..695d42e --- /dev/null +++ b/Max API/src/sessions/dto/session-response.dto.ts @@ -0,0 +1,12 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { SessionStatus } from '@prisma/client'; +import { SessionObjectiveResponseDto } from './session-objective-response.dto'; + +export class SessionResponseDto { + @ApiProperty() id!: number; + @ApiProperty({ enum: SessionStatus }) status!: SessionStatus; + @ApiProperty() createdAt!: Date; + @ApiProperty() updatedAt!: Date; + @ApiProperty({ type: SessionObjectiveResponseDto, required: false }) + objective?: SessionObjectiveResponseDto; +} diff --git a/Max API/src/sessions/sessions.controller.spec.ts b/Max API/src/sessions/sessions.controller.spec.ts new file mode 100644 index 0000000..8eeb88a --- /dev/null +++ b/Max API/src/sessions/sessions.controller.spec.ts @@ -0,0 +1,69 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import type { AuthenticatedRequest } from '../auth/jwt-auth.guard'; +import { SessionsController } from './sessions.controller'; +import { SessionsService } from './sessions.service'; + +describe('SessionsController', () => { + let controller: SessionsController; + const sessionsService = { + create: jest.fn(), + findOne: jest.fn(), + sendObjectiveMessage: jest.fn(), + confirmObjective: jest.fn(), + }; + const request = { + user: { sub: 7, email: 'w@example.com' }, + } as AuthenticatedRequest; + + beforeEach(async () => { + jest.clearAllMocks(); + const module: TestingModule = await Test.createTestingModule({ + controllers: [SessionsController], + providers: [{ provide: SessionsService, useValue: sessionsService }], + }) + .overrideGuard(JwtAuthGuard) + .useValue({ canActivate: () => true }) + .compile(); + + controller = module.get(SessionsController); + }); + + it('should create a session for the authenticated user', async () => { + sessionsService.create.mockResolvedValueOnce({ + id: 1, + status: 'objective_discovery', + }); + const result = await controller.create(request); + expect(sessionsService.create).toHaveBeenCalledWith(7); + expect(result.id).toBe(1); + }); + + it('should fetch a session by id for the authenticated user', async () => { + sessionsService.findOne.mockResolvedValueOnce({ + id: 1, + status: 'objective_discovery', + }); + await controller.findOne(1, request); + expect(sessionsService.findOne).toHaveBeenCalledWith(1, 7); + }); + + it('should forward an objective message to the service', async () => { + sessionsService.sendObjectiveMessage.mockResolvedValueOnce({ + reply: 'ok', + ready: false, + }); + await controller.sendObjectiveMessage(1, { message: 'Bonjour' }, request); + expect(sessionsService.sendObjectiveMessage).toHaveBeenCalledWith( + 1, + 7, + 'Bonjour', + ); + }); + + it('should confirm the objective for the authenticated user', async () => { + sessionsService.confirmObjective.mockResolvedValueOnce({ id: 1 }); + await controller.confirmObjective(1, request); + expect(sessionsService.confirmObjective).toHaveBeenCalledWith(1, 7); + }); +}); diff --git a/Max API/src/sessions/sessions.controller.ts b/Max API/src/sessions/sessions.controller.ts new file mode 100644 index 0000000..9c3a2a8 --- /dev/null +++ b/Max API/src/sessions/sessions.controller.ts @@ -0,0 +1,94 @@ +import { + Body, + Controller, + Get, + HttpCode, + HttpStatus, + Param, + ParseIntPipe, + Post, + Req, + UseGuards, +} from '@nestjs/common'; +import { + ApiBearerAuth, + ApiOperation, + ApiResponse, + ApiTags, +} from '@nestjs/swagger'; +import type { AuthenticatedRequest } from '../auth/jwt-auth.guard'; +import { JwtAuthGuard } from '../auth/jwt-auth.guard'; +import { ObjectiveMessageResponseDto } from './dto/objective-message-response.dto'; +import { SendObjectiveMessageDto } from './dto/send-objective-message.dto'; +import { SessionObjectiveResponseDto } from './dto/session-objective-response.dto'; +import { SessionResponseDto } from './dto/session-response.dto'; +import { SessionsService } from './sessions.service'; + +@ApiTags('sessions') +@ApiBearerAuth() +@UseGuards(JwtAuthGuard) +@Controller('sessions') +export class SessionsController { + constructor(private readonly sessionsService: SessionsService) {} + + @Post() + @ApiOperation({ summary: 'Demarrer une nouvelle session de formation' }) + @ApiResponse({ status: HttpStatus.CREATED, type: SessionResponseDto }) + create(@Req() request: AuthenticatedRequest): Promise { + return this.sessionsService.create(request.user.sub); + } + + @Get(':id') + @ApiOperation({ summary: "Recuperer l'etat d'une session" }) + @ApiResponse({ status: HttpStatus.OK, type: SessionResponseDto }) + @ApiResponse({ status: HttpStatus.NOT_FOUND }) + findOne( + @Param('id', ParseIntPipe) id: number, + @Req() request: AuthenticatedRequest, + ): Promise { + return this.sessionsService.findOne(id, request.user.sub); + } + + @Post(':id/objective/message') + @ApiOperation({ + summary: + "Envoyer un message a l'Agent 1 (Objectif) et recevoir sa prochaine question", + }) + @ApiResponse({ + status: HttpStatus.CREATED, + type: ObjectiveMessageResponseDto, + }) + @ApiResponse({ + status: HttpStatus.CONFLICT, + description: 'Objectif deja valide pour cette session', + }) + sendObjectiveMessage( + @Param('id', ParseIntPipe) id: number, + @Body() dto: SendObjectiveMessageDto, + @Req() request: AuthenticatedRequest, + ): Promise { + return this.sessionsService.sendObjectiveMessage( + id, + request.user.sub, + dto.message, + ); + } + + @Post(':id/objective/confirm') + @HttpCode(HttpStatus.OK) + @ApiOperation({ + summary: + "Confirmer explicitement l'objectif propose par l'Agent 1 (immuable une fois valide)", + }) + @ApiResponse({ status: HttpStatus.OK, type: SessionObjectiveResponseDto }) + @ApiResponse({ + status: HttpStatus.CONFLICT, + description: 'Aucun objectif pret a confirmer', + }) + confirmObjective( + @Param('id', ParseIntPipe) id: number, + @Req() request: AuthenticatedRequest, + ): Promise { + return this.sessionsService.confirmObjective(id, request.user.sub); + } +} diff --git a/Max API/src/sessions/sessions.module.ts b/Max API/src/sessions/sessions.module.ts new file mode 100644 index 0000000..39bc069 --- /dev/null +++ b/Max API/src/sessions/sessions.module.ts @@ -0,0 +1,15 @@ +import { Module } from '@nestjs/common'; +import { AuthModule } from '../auth/auth.module'; +import { LlmModule } from '../llm/llm.module'; +import { PrismaModule } from '../prisma/prisma.module'; +import { ObjectiveAgent } from './agents/objective.agent'; +import { SessionsController } from './sessions.controller'; +import { SessionsService } from './sessions.service'; + +@Module({ + imports: [PrismaModule, LlmModule, AuthModule], + controllers: [SessionsController], + providers: [SessionsService, ObjectiveAgent], + exports: [SessionsService], +}) +export class SessionsModule {} diff --git a/Max API/src/sessions/sessions.service.spec.ts b/Max API/src/sessions/sessions.service.spec.ts new file mode 100644 index 0000000..ada6262 --- /dev/null +++ b/Max API/src/sessions/sessions.service.spec.ts @@ -0,0 +1,128 @@ +import { ConflictException, NotFoundException } from '@nestjs/common'; +import { Test, TestingModule } from '@nestjs/testing'; +import { PrismaService } from '../prisma/prisma.service'; +import { ObjectiveAgent } from './agents/objective.agent'; +import { SessionsService } from './sessions.service'; + +describe('SessionsService', () => { + let service: SessionsService; + const prisma = { + session: { create: jest.fn(), findUnique: jest.fn() }, + }; + const objectiveAgent = { converse: jest.fn(), confirm: jest.fn() }; + + beforeEach(async () => { + jest.clearAllMocks(); + const module: TestingModule = await Test.createTestingModule({ + providers: [ + SessionsService, + { provide: PrismaService, useValue: prisma }, + { provide: ObjectiveAgent, useValue: objectiveAgent }, + ], + }).compile(); + + service = module.get(SessionsService); + }); + + describe('create()', () => { + it('should create a session in objective_discovery status', async () => { + prisma.session.create.mockResolvedValueOnce({ + id: 1, + userId: 7, + status: 'objective_discovery', + createdAt: new Date('2026-01-01'), + updatedAt: new Date('2026-01-01'), + }); + + const result = await service.create(7); + + expect(prisma.session.create).toHaveBeenCalledWith({ + data: { userId: 7 }, + }); + expect(result.status).toBe('objective_discovery'); + expect(result.objective).toBeUndefined(); + }); + }); + + describe('findOne()', () => { + it('should throw NotFoundException when the session does not belong to the user', async () => { + prisma.session.findUnique.mockResolvedValueOnce({ + id: 1, + userId: 2, + objective: null, + }); + await expect(service.findOne(1, 99)).rejects.toThrow(NotFoundException); + }); + + it('should throw NotFoundException when the session does not exist', async () => { + prisma.session.findUnique.mockResolvedValueOnce(null); + await expect(service.findOne(1, 99)).rejects.toThrow(NotFoundException); + }); + }); + + describe('sendObjectiveMessage()', () => { + it('should delegate to the objective agent when the session is still in discovery', async () => { + prisma.session.findUnique.mockResolvedValueOnce({ + id: 1, + userId: 7, + status: 'objective_discovery', + objective: null, + }); + objectiveAgent.converse.mockResolvedValueOnce({ + reply: 'Quel est ton sujet ?', + ready: false, + }); + + const result = await service.sendObjectiveMessage( + 1, + 7, + 'Je veux apprendre', + ); + + expect(objectiveAgent.converse).toHaveBeenCalledWith( + 1, + 7, + 'Je veux apprendre', + ); + expect(result.ready).toBe(false); + }); + + it('should reject when the objective is already validated for this session', async () => { + prisma.session.findUnique.mockResolvedValueOnce({ + id: 1, + userId: 7, + status: 'objective_validated', + objective: { id: 1 }, + }); + + await expect( + service.sendObjectiveMessage(1, 7, 'Un message'), + ).rejects.toThrow(ConflictException); + expect(objectiveAgent.converse).not.toHaveBeenCalled(); + }); + }); + + describe('confirmObjective()', () => { + it('should map the confirmed objective to a response DTO', async () => { + prisma.session.findUnique.mockResolvedValueOnce({ + id: 1, + userId: 7, + status: 'objective_discovery', + objective: null, + }); + objectiveAgent.confirm.mockResolvedValueOnce({ + id: 5, + sessionId: 1, + subject: 'Facturation freelance', + professionalGoal: 'Facturer sans erreur', + duration: '2 semaines', + validatedAt: new Date('2026-01-02'), + }); + + const result = await service.confirmObjective(1, 7); + + expect(result.id).toBe(5); + expect(result.validatedAt).toEqual(new Date('2026-01-02')); + }); + }); +}); diff --git a/Max API/src/sessions/sessions.service.ts b/Max API/src/sessions/sessions.service.ts new file mode 100644 index 0000000..4705dd8 --- /dev/null +++ b/Max API/src/sessions/sessions.service.ts @@ -0,0 +1,101 @@ +import { + ConflictException, + Injectable, + NotFoundException, +} from '@nestjs/common'; +import { Session, SessionObjective } from '@prisma/client'; +import { PrismaService } from '../prisma/prisma.service'; +import { ObjectiveAgent, ObjectiveTurnResult } from './agents/objective.agent'; +import { SessionObjectiveResponseDto } from './dto/session-objective-response.dto'; +import { SessionResponseDto } from './dto/session-response.dto'; + +type SessionWithObjective = Session & { objective: SessionObjective | null }; + +@Injectable() +export class SessionsService { + constructor( + private readonly prisma: PrismaService, + private readonly objectiveAgent: ObjectiveAgent, + ) {} + + async create(userId: number): Promise { + const session = await this.prisma.session.create({ data: { userId } }); + return this.toResponse({ ...session, objective: null }); + } + + async findOne(id: number, userId: number): Promise { + const session = await this.findOwnedSession(id, userId); + return this.toResponse(session); + } + + async sendObjectiveMessage( + sessionId: number, + userId: number, + message: string, + ): Promise { + const session = await this.findOwnedSession(sessionId, userId); + this.assertObjectiveDiscoveryInProgress(session); + return this.objectiveAgent.converse(sessionId, userId, message); + } + + async confirmObjective( + sessionId: number, + userId: number, + ): Promise { + const session = await this.findOwnedSession(sessionId, userId); + this.assertObjectiveDiscoveryInProgress(session); + const objective = await this.objectiveAgent.confirm(sessionId, userId); + return { + id: objective.id, + sessionId: objective.sessionId, + subject: objective.subject, + professionalGoal: objective.professionalGoal, + duration: objective.duration, + validatedAt: objective.validatedAt ?? new Date(), + }; + } + + private async findOwnedSession( + id: number, + userId: number, + ): Promise { + const session = await this.prisma.session.findUnique({ + where: { id }, + include: { objective: true }, + }); + if (!session || session.userId !== userId) { + throw new NotFoundException(`Session ${id} introuvable`); + } + return session; + } + + private assertObjectiveDiscoveryInProgress( + session: SessionWithObjective, + ): void { + if (session.status !== 'objective_discovery') { + throw new ConflictException( + "L'objectif de cette session est deja valide ou cette session n'en est plus a cette etape.", + ); + } + } + + private toResponse(session: SessionWithObjective): SessionResponseDto { + return { + id: session.id, + status: session.status, + createdAt: session.createdAt, + updatedAt: session.updatedAt, + objective: session.objective + ? { + id: session.objective.id, + sessionId: session.objective.sessionId, + subject: session.objective.subject, + professionalGoal: session.objective.professionalGoal, + duration: session.objective.duration, + validatedAt: + session.objective.validatedAt ?? session.objective.createdAt, + } + : undefined, + }; + } +}