Files
ForgeBase/Max API/src/sessions/agents/objective.agent.spec.ts
T
williamandClaude Sonnet 5 bae5ace70c 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 <noreply@anthropic.com>
2026-10-31 20:16:03 +01:00

174 lines
5.2 KiB
TypeScript

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<unknown>,
[{ data: Record<string, unknown> }]
>();
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);
});
});
});