Compare commits

...
13 Commits
Author SHA1 Message Date
williamandClaude Sonnet 5 23052b8afd feat(veille): implement l'Agent de veille autonome et le profil freelance
CI / quality (pull_request) Successful in 13m3s
- Nouveau module freelance-profile (GET/PATCH /profile, upsert implicite au premier acces)
- Nouveau module veille : cron quotidien (@nestjs/schedule), frequence quotidienne/hebdomadaire par profil (explicite ou inferee par mots-cles de domaines volatils)
- Garde-fous de generation de signal recalcules cote code : minimum 3 sources independantes, score de pertinence >= max(0.7, seuil du profil), exclusion blacklist, dedoublonnage 30 jours par (profil, competence, type)
- GET /veille/signals (priorite obsolete > refresh > emerging puis pertinence), POST /veille/signals/:id/action avec train (demarre une session + Agent 1 avec un message synthetique)/snooze (resurgence codee dans action_taken, pas de colonne dediee)/dismiss (marque le signal et le profil)
- Ajoute @nestjs/schedule en dependance (version 6.1.3, compatible CommonJS/Jest - la 12.x est ESM-only et casse Jest)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-02 10:32:18 +01:00
williamandClaude Sonnet 5 4d8236b8e5 feat(sessions): enchainer les Agents 5-7 dans l'orchestration de session
- confirmLevel() declenche desormais l'Agent 5 (Plan) et renvoie le curriculum pret pour CurriculumCard
- Nouveau confirmCurriculum() : confirme le curriculum (immuable), passe la session en "teaching", genere le module 1
- Nouveaux endpoints de sous-interaction module (exercice, indice, debogage, Feynman, completion) et de resultat d'evaluation finale
- routeIncomingMessage() route desormais "planning" (rappel canned), "teaching" (interpretation du message libre via currentAwaiting) et "evaluating" (Agent 7) sans jamais laisser le LLM decider du statut ou de l'UI
- Tests unitaires et de controleur mis a jour en consequence

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-02 10:22:32 +01:00
williamandClaude Sonnet 5 83c50575b1 feat(sessions): implement Agent 7 (Evaluation finale) du pipeline coach
- Evaluation en deux temps (entretien client simule puis cas de mission), demarree automatiquement a la fin du dernier module
- Scores "total"/"validated" toujours recalcules cote code a partir des bits individuels renvoyes par le LLM, jamais pris tels quels
- Passage automatique entretien -> mission dans le meme echange si l'entretien est valide (>=4/5), sans confirmation utilisateur separee
- Resultat final persiste via upsert (session_evaluation), session marquee "completed" seulement si les deux etapes sont validees

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-02 10:22:19 +01:00
williamandClaude Sonnet 5 d9618defe6 feat(sessions): implement Agent 6 (Redacteur) du pipeline coach
- Redige un module a la fois (hook, theorie, We Do, 6 exercices 2/2/2, debogage, synthese Feynman), avec validation cote code (mots minimum, structure, 5 indices par exercice) et relance unique
- Progression stockee dans session_module.content.progress ("currentAwaiting") : permet au pipeline voix/texte unique d'interpreter un message libre sans que le LLM ne decide de l'UI
- Exercice/indice/debogage/Feynman geres independamment, garde-fou de fin de module (>=4/6 + debogage + Feynman) recalcule integralement cote code
- DTOs REST dedies (vue publique sans reponses internes, indices reveles progressivement)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-02 10:22:10 +01:00
williamandClaude Sonnet 5 af87d169ac feat(sessions): implement Agent 5 (Plan) du pipeline coach
- Ajoute le prompt verbatim de l'Agent 5 (Backward Design) avec placeholders objectif/profil/corpus
- Valide cote code le nombre de modules (3-7) et le statut de verrouillage (seul le premier module est "unlocked"), avec relance unique en cas d'echec
- Persiste le curriculum dans session_curriculum, pret pour CurriculumCard

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-02 10:21:56 +01:00
williamandClaude Sonnet 5 755bc07d18 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>
2026-11-02 09:48:10 +01:00
williamandClaude Sonnet 5 5c00976e8f feat(sessions): implement Agents 2, 3, 4 (Cartographie, Niveau, Recherche)
Agent 2 (MappingAgent): single-call concept map over real web search
(OpenRouter ":online"), code-side validation (>=5 sources total, >=2 per
concept, mandatory "etre capable de" wording) with one retry before
failing - never trusts the LLM's self-reported compliance.

Agent 3 (LevelAgent): 3-5 situational questions built from the concept
map, same conversational shape as ObjectiveAgent (ephemeral in-memory
history). Produces a 3-dimension profile (mastered/gap/unknown) the user
can dispute per concept before confirming.

Agent 4 (ResearchAgent): one parallel ":online" call per concept,
calibrated by the level profile (mastered->advanced sources,
gap->intermediate, unknown->beginner). A failed subtopic never fails
the whole batch - it's recorded in the corpus and the rest proceeds.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-02 09:47:53 +01:00
williamandClaude Sonnet 5 b5cdc30207 feat(llm): add OpenRouter ":online" web-search option
Agents 2, 4 and the future veille service must not hallucinate sources
from the model's memory (docs/Max Refonte Coach Freelance.md). OpenRouter's
native ":online" model suffix performs real web search grounding with no
custom tool-calling plumbing needed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-02 09:29:52 +01:00
williamandClaude Sonnet 5 85da9fcad0 refactor(pipeline): the text bar is not a chat, Max always replies by voice
Two pieces of direct user feedback, addressed together since they touch
the same files:

1. ObjectiveValidationCard now lives in its own dedicated, movable
   window (objectiveWindow.ts / ObjectiveWindowRoot.tsx), independent
   of the text input window. Confirming an objective must never depend
   on opening that window, including when the whole exchange happens
   by voice. Both sendTextTurn and voice-turn open/feed this window
   through the same shared handleRouteMessageResult code path, so text
   and voice behave identically - no more special-casing one channel.

2. The "chat window" was never meant to be a chat: it's an alternate
   text entry point for the exact same voice pipeline. Removed the
   message history/ChatBubble display and the old
   sessions:route-message + voice-turn-synced plumbing that existed to
   sync a conversation transcript across windows. Replaced with a new
   text-turn IPC handler mirroring voice-turn (routeMessage ->
   handleRouteMessageResult -> synthesizeSpeech) minus the STT step;
   the reply is relayed to the avatar window via the existing
   proactive-speech channel and spoken aloud, never displayed. The
   input window shrinks accordingly (560px -> 100px tall) and no
   longer auto-opens when a session starts, since there is nothing to
   show there anymore - it only opens on explicit user request.

useProactiveSpeech now accepts an onStateChange callback so the avatar
status indicator correctly flips back to idle once a text-turn reply
finishes playing (it previously only ever got set to 'speaking', never
reset - a latent gap this reuse surfaced).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-01 10:52:09 +01:00
williamandClaude Sonnet 5 4b45c4a644 fix(voice): sync voice-originated pipeline turns to the chat window
A learn-intent conversation driven entirely by voice never reached
ObjectiveValidationCard: the chat window's Zustand store lives in its
own isolated renderer process and only ever updated from its own
direct sessions:route-message calls, never from voice-turn results
handled in the main process. A user doing everything by voice could
never see or confirm their objective.

The main process now opens the chat window and broadcasts the voice
turn (reply/ready/draft) to it whenever intent is 'learn'; the chat
window's store applies it the same way it applies its own responses.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-01 10:25:48 +01:00
williamandClaude Sonnet 5 ef0015fc2b fix(agents): drop the subjective feasibility dimension from Agent 1's coherence check
Found via real user testing: a valid objective ("trigonometrie, en 2
semaines") was never shown in ObjectiveValidationCard because the
LLM-scored "feasibility" dimension judged the timeline too ambitious
and silently replaced the ready-to-confirm recap with a follow-up
question about the user's experience, even though duration already
passes the hard-coded 1h-12-weeks range check.

Duration plausibility is a coded rule, not a subjective LLM opinion:
keep only clarity and specificity in the coherence score.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-01 09:57:01 +01:00
williamandClaude Sonnet 5 a0f4d9df1e fix(agents): accept spelled-out small numbers in duration parsing
"1 semaine" reformulated by the LLM as "une semaine" was wrongly
rejected as an invalid duration (parseDurationHours only accepted a
leading digit), even though 168h is well within the 1h-12-weeks range.
Found via real user testing: "apprends-moi la trigonometrie en 1
semaine" was rejected with the generic out-of-range message.

Fix is two-layered: the prompt now explicitly tells the model to
always write duration as "<digit> <unit>", and the parser accepts
common French spelled-out numbers (un/une through douze) as a
defense-in-depth fallback since prompts are not a hard guarantee.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-01 09:46:24 +01:00
williamandClaude Sonnet 5 73bc2587b8 fix(voice): route voice turns through the same backend pipeline as chat
Voice interactions still called OpenRouter directly from the main
process with a leftover pre-redesign system prompt ("coach de
formation vocal"), bypassing Max API's intent router and the new
PERSONALITY_PROMPT entirely - causing Max to misrepresent himself in
spoken conversation. voice-turn now calls routeMessage() (the same
POST /sessions/messages entry point the chat window uses), so voice
and text share one personality and one pipeline.

The leaked-boilerplate/degenerate-text safety checks that used to live
alongside the old direct OpenRouter call move to a focused
speechSafety.ts module, still applied to the reply before it's spoken.
getAssistantReply() and its model-fallback plumbing are deleted - that
logic now lives server-side in Max API's OpenRouterService.

A learn-intent voice command (e.g. saying "apprends-moi React out
loud") now opens the pipeline stepper and syncs session status exactly
like typing it in chat, via a handleRouteMessageResult() helper shared
between voice-turn and sessions:route-message.

Known limitations (unchanged from the text-chat intent router, now
just consistent across both channels): casual chat-intent turns have
no cross-turn memory (no pre-session history storage server-side yet),
and a voice-started session's messages don't appear in the chat
window's own transcript if opened afterwards (per-window state only).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-01 09:33:24 +01:00
90 changed files with 7422 additions and 578 deletions
+46
View File
@@ -15,6 +15,7 @@
"@nestjs/core": "^11.0.1",
"@nestjs/jwt": "11.0.2",
"@nestjs/platform-express": "^11.0.1",
"@nestjs/schedule": "^6.1.3",
"@nestjs/swagger": "^11.4.7",
"@prisma/client": "6.19.3",
"bcrypt": "^6.0.0",
@@ -2388,6 +2389,19 @@
"@nestjs/core": "^11.0.0"
}
},
"node_modules/@nestjs/schedule": {
"version": "6.1.3",
"resolved": "https://registry.npmjs.org/@nestjs/schedule/-/schedule-6.1.3.tgz",
"integrity": "sha512-RflMFOpR16Dwd1jAUbeB4mfGTCh65fvEdL4mSjQPJChpkRGRjIXjb+6YQcK2faQrVT60c9DmLmoVR7/ONCtuYQ==",
"license": "MIT",
"dependencies": {
"cron": "4.4.0"
},
"peerDependencies": {
"@nestjs/common": "^10.0.0 || ^11.0.0",
"@nestjs/core": "^10.0.0 || ^11.0.0"
}
},
"node_modules/@nestjs/schematics": {
"version": "11.1.0",
"resolved": "https://registry.npmjs.org/@nestjs/schematics/-/schematics-11.1.0.tgz",
@@ -3321,6 +3335,12 @@
"@types/node": "*"
}
},
"node_modules/@types/luxon": {
"version": "3.7.6",
"resolved": "https://registry.npmjs.org/@types/luxon/-/luxon-3.7.6.tgz",
"integrity": "sha512-6KSjliQAXK8ZLgFQO4B7iE4Rpf/B3rItzCFuXezBY/XIAGxOdLd7vRNK9/StRPwiS/yJsVbB7HKpW46B8tcEuQ==",
"license": "MIT"
},
"node_modules/@types/methods": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz",
@@ -5359,6 +5379,23 @@
"dev": true,
"license": "MIT"
},
"node_modules/cron": {
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/cron/-/cron-4.4.0.tgz",
"integrity": "sha512-fkdfq+b+AHI4cKdhZlppHveI/mgz2qpiYxcm+t5E5TsxX7QrLS1VE0+7GENEk9z0EeGPcpSciGv6ez24duWhwQ==",
"license": "MIT",
"dependencies": {
"@types/luxon": "~3.7.0",
"luxon": "~3.7.0"
},
"engines": {
"node": ">=18.x"
},
"funding": {
"type": "ko-fi",
"url": "https://ko-fi.com/intcreator"
}
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -8035,6 +8072,15 @@
"yallist": "^3.0.2"
}
},
"node_modules/luxon": {
"version": "3.7.2",
"resolved": "https://registry.npmjs.org/luxon/-/luxon-3.7.2.tgz",
"integrity": "sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==",
"license": "MIT",
"engines": {
"node": ">=12"
}
},
"node_modules/magic-string": {
"version": "0.30.17",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.17.tgz",
+1
View File
@@ -37,6 +37,7 @@
"@nestjs/core": "^11.0.1",
"@nestjs/jwt": "11.0.2",
"@nestjs/platform-express": "^11.0.1",
"@nestjs/schedule": "^6.1.3",
"@nestjs/swagger": "^11.4.7",
"@prisma/client": "6.19.3",
"bcrypt": "^6.0.0",
+6
View File
@@ -1,22 +1,28 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { ScheduleModule } from '@nestjs/schedule';
import { ApiKeysModule } from './api-keys/api-keys.module';
import { AppController } from './app.controller';
import { AuthModule } from './auth/auth.module';
import { CryptoModule } from './common/crypto/crypto.module';
import { FreelanceProfileModule } from './freelance-profile/freelance-profile.module';
import { PrismaModule } from './prisma/prisma.module';
import { SessionsModule } from './sessions/sessions.module';
import { UsersModule } from './users/users.module';
import { VeilleModule } from './veille/veille.module';
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
ScheduleModule.forRoot(),
PrismaModule,
CryptoModule,
UsersModule,
ApiKeysModule,
AuthModule,
SessionsModule,
FreelanceProfileModule,
VeilleModule,
],
controllers: [AppController],
})
@@ -0,0 +1,72 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
export class FreelanceProfileResponseDto {
@ApiProperty()
id!: number;
@ApiPropertyOptional()
displayName!: string | null;
@ApiPropertyOptional()
positioning!: string | null;
@ApiProperty({ type: [String] })
domains!: string[];
@ApiProperty({ type: [String] })
stack!: string[];
@ApiProperty({ type: [String] })
targetMissionTypes!: string[];
@ApiProperty({ type: [String] })
targetSectors!: string[];
@ApiPropertyOptional()
seniorityLevel!: string | null;
@ApiPropertyOptional()
tjm!: number | null;
@ApiPropertyOptional()
experienceYears!: number | null;
@ApiProperty({ type: [String] })
certifications!: string[];
@ApiPropertyOptional()
workFormat!: string | null;
@ApiPropertyOptional()
geographicZone!: string | null;
@ApiProperty({ type: [String] })
competencesAcquired!: string[];
@ApiProperty({ type: [String] })
competencesInProgress!: string[];
@ApiProperty({ type: [String] })
competencesDismissed!: string[];
@ApiPropertyOptional()
lastTrainingAt!: Date | null;
@ApiPropertyOptional({ enum: ['daily', 'weekly'] })
veilleFrequency!: string | null;
@ApiProperty({ type: [String] })
veilleExtraTopics!: string[];
@ApiProperty({ type: [String] })
veilleBlacklist!: string[];
@ApiPropertyOptional()
veilleRelevanceThreshold!: number | null;
@ApiProperty()
veilleNotificationsEnabled!: boolean;
@ApiPropertyOptional()
lastVeilleAt!: Date | null;
}
@@ -0,0 +1,97 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import {
IsArray,
IsBoolean,
IsNumber,
IsOptional,
IsString,
} from 'class-validator';
/** Champs renseignes manuellement par le freelance - jamais les champs geres par le pipeline
* (competencesAcquired/InProgress/Dismissed, lastTrainingAt, lastVeilleAt). */
export class UpdateFreelanceProfileDto {
@ApiPropertyOptional()
@IsOptional()
@IsString()
displayName?: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
positioning?: string;
@ApiPropertyOptional({ type: [String] })
@IsOptional()
@IsArray()
domains?: string[];
@ApiPropertyOptional({ type: [String] })
@IsOptional()
@IsArray()
stack?: string[];
@ApiPropertyOptional({ type: [String] })
@IsOptional()
@IsArray()
targetMissionTypes?: string[];
@ApiPropertyOptional({ type: [String] })
@IsOptional()
@IsArray()
targetSectors?: string[];
@ApiPropertyOptional()
@IsOptional()
@IsString()
seniorityLevel?: string;
@ApiPropertyOptional()
@IsOptional()
@IsNumber()
tjm?: number;
@ApiPropertyOptional()
@IsOptional()
@IsNumber()
experienceYears?: number;
@ApiPropertyOptional({ type: [String] })
@IsOptional()
@IsArray()
certifications?: string[];
@ApiPropertyOptional()
@IsOptional()
@IsString()
workFormat?: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
geographicZone?: string;
@ApiPropertyOptional({ enum: ['daily', 'weekly'] })
@IsOptional()
@IsString()
veilleFrequency?: string;
@ApiPropertyOptional({ type: [String] })
@IsOptional()
@IsArray()
veilleExtraTopics?: string[];
@ApiPropertyOptional({ type: [String] })
@IsOptional()
@IsArray()
veilleBlacklist?: string[];
@ApiPropertyOptional()
@IsOptional()
@IsNumber()
veilleRelevanceThreshold?: number;
@ApiPropertyOptional()
@IsOptional()
@IsBoolean()
veilleNotificationsEnabled?: boolean;
}
@@ -0,0 +1,41 @@
import { Test, TestingModule } from '@nestjs/testing';
import type { AuthenticatedRequest } from '../auth/jwt-auth.guard';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { FreelanceProfileController } from './freelance-profile.controller';
import { FreelanceProfileService } from './freelance-profile.service';
describe('FreelanceProfileController', () => {
let controller: FreelanceProfileController;
const freelanceProfileService = { getOrCreate: jest.fn(), update: jest.fn() };
const request = {
user: { sub: 7, email: 'w@example.com' },
} as AuthenticatedRequest;
beforeEach(async () => {
jest.clearAllMocks();
const module: TestingModule = await Test.createTestingModule({
controllers: [FreelanceProfileController],
providers: [
{ provide: FreelanceProfileService, useValue: freelanceProfileService },
],
})
.overrideGuard(JwtAuthGuard)
.useValue({ canActivate: () => true })
.compile();
controller = module.get(FreelanceProfileController);
});
it('should fetch the profile of the authenticated user', async () => {
freelanceProfileService.getOrCreate.mockResolvedValueOnce({ id: 1 });
await controller.getProfile(request);
expect(freelanceProfileService.getOrCreate).toHaveBeenCalledWith(7);
});
it('should forward a profile update to the service', async () => {
freelanceProfileService.update.mockResolvedValueOnce({ id: 1 });
const dto = { displayName: 'William' };
await controller.updateProfile(dto, request);
expect(freelanceProfileService.update).toHaveBeenCalledWith(7, dto);
});
});
@@ -0,0 +1,43 @@
import { Body, Controller, Get, Patch, 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 { FreelanceProfileResponseDto } from './dto/freelance-profile-response.dto';
import { UpdateFreelanceProfileDto } from './dto/update-freelance-profile.dto';
import { FreelanceProfileService } from './freelance-profile.service';
@ApiTags('freelance-profile')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Controller('profile')
export class FreelanceProfileController {
constructor(
private readonly freelanceProfileService: FreelanceProfileService,
) {}
@Get()
@ApiOperation({
summary: "Recuperer le profil freelance de l'utilisateur authentifie",
})
@ApiResponse({ status: 200, type: FreelanceProfileResponseDto })
getProfile(
@Req() request: AuthenticatedRequest,
): Promise<FreelanceProfileResponseDto> {
return this.freelanceProfileService.getOrCreate(request.user.sub);
}
@Patch()
@ApiOperation({ summary: 'Mettre a jour le profil freelance' })
@ApiResponse({ status: 200, type: FreelanceProfileResponseDto })
updateProfile(
@Body() dto: UpdateFreelanceProfileDto,
@Req() request: AuthenticatedRequest,
): Promise<FreelanceProfileResponseDto> {
return this.freelanceProfileService.update(request.user.sub, dto);
}
}
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { FreelanceProfileController } from './freelance-profile.controller';
import { FreelanceProfileService } from './freelance-profile.service';
@Module({
controllers: [FreelanceProfileController],
providers: [FreelanceProfileService],
exports: [FreelanceProfileService],
})
export class FreelanceProfileModule {}
@@ -0,0 +1,82 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PrismaService } from '../prisma/prisma.service';
import { FreelanceProfileService } from './freelance-profile.service';
describe('FreelanceProfileService', () => {
let service: FreelanceProfileService;
const prisma = { freelanceProfile: { upsert: jest.fn() } };
const storedProfile = {
id: 1,
userId: 7,
displayName: null,
positioning: null,
domains: ['Facturation'],
stack: null,
targetMissionTypes: null,
targetSectors: null,
seniorityLevel: null,
tjm: null,
experienceYears: null,
certifications: null,
workFormat: null,
geographicZone: null,
competencesAcquired: null,
competencesInProgress: null,
competencesDismissed: null,
lastTrainingAt: null,
veilleFrequency: null,
veilleExtraTopics: null,
veilleBlacklist: null,
veilleRelevanceThreshold: null,
veilleNotificationsEnabled: true,
lastVeilleAt: null,
};
beforeEach(async () => {
jest.clearAllMocks();
const module: TestingModule = await Test.createTestingModule({
providers: [
FreelanceProfileService,
{ provide: PrismaService, useValue: prisma },
],
}).compile();
service = module.get(FreelanceProfileService);
});
describe('getOrCreate()', () => {
it('should upsert an empty profile and default every JSON array field to []', async () => {
prisma.freelanceProfile.upsert.mockResolvedValueOnce(storedProfile);
const result = await service.getOrCreate(7);
expect(prisma.freelanceProfile.upsert).toHaveBeenCalledWith({
where: { userId: 7 },
create: { userId: 7 },
update: {},
});
expect(result.domains).toEqual(['Facturation']);
expect(result.stack).toEqual([]);
expect(result.competencesAcquired).toEqual([]);
});
});
describe('update()', () => {
it('should upsert the provided fields', async () => {
prisma.freelanceProfile.upsert.mockResolvedValueOnce({
...storedProfile,
displayName: 'William',
});
const result = await service.update(7, { displayName: 'William' });
expect(prisma.freelanceProfile.upsert).toHaveBeenCalledWith({
where: { userId: 7 },
create: { userId: 7, displayName: 'William' },
update: { displayName: 'William' },
});
expect(result.displayName).toBe('William');
});
});
});
@@ -0,0 +1,66 @@
import { Injectable } from '@nestjs/common';
import { FreelanceProfile } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { FreelanceProfileResponseDto } from './dto/freelance-profile-response.dto';
import { UpdateFreelanceProfileDto } from './dto/update-freelance-profile.dto';
@Injectable()
export class FreelanceProfileService {
constructor(private readonly prisma: PrismaService) {}
/** Cree le profil au premier acces (aucun endpoint de creation dedie : un freelance a toujours
* un profil, vide par defaut, des sa premiere consultation). */
async getOrCreate(userId: number): Promise<FreelanceProfileResponseDto> {
const profile = await this.prisma.freelanceProfile.upsert({
where: { userId },
create: { userId },
update: {},
});
return this.toResponse(profile);
}
async update(
userId: number,
dto: UpdateFreelanceProfileDto,
): Promise<FreelanceProfileResponseDto> {
const profile = await this.prisma.freelanceProfile.upsert({
where: { userId },
create: { userId, ...dto },
update: { ...dto },
});
return this.toResponse(profile);
}
private toResponse(profile: FreelanceProfile): FreelanceProfileResponseDto {
return {
id: profile.id,
displayName: profile.displayName,
positioning: profile.positioning,
domains: (profile.domains as unknown as string[]) ?? [],
stack: (profile.stack as unknown as string[]) ?? [],
targetMissionTypes:
(profile.targetMissionTypes as unknown as string[]) ?? [],
targetSectors: (profile.targetSectors as unknown as string[]) ?? [],
seniorityLevel: profile.seniorityLevel,
tjm: profile.tjm,
experienceYears: profile.experienceYears,
certifications: (profile.certifications as unknown as string[]) ?? [],
workFormat: profile.workFormat,
geographicZone: profile.geographicZone,
competencesAcquired:
(profile.competencesAcquired as unknown as string[]) ?? [],
competencesInProgress:
(profile.competencesInProgress as unknown as string[]) ?? [],
competencesDismissed:
(profile.competencesDismissed as unknown as string[]) ?? [],
lastTrainingAt: profile.lastTrainingAt,
veilleFrequency: profile.veilleFrequency,
veilleExtraTopics:
(profile.veilleExtraTopics as unknown as string[]) ?? [],
veilleBlacklist: (profile.veilleBlacklist as unknown as string[]) ?? [],
veilleRelevanceThreshold: profile.veilleRelevanceThreshold,
veilleNotificationsEnabled: profile.veilleNotificationsEnabled,
lastVeilleAt: profile.lastVeilleAt,
};
}
}
@@ -30,6 +30,15 @@ describe('OpenRouterService', () => {
(global.fetch as jest.Mock).mockImplementationOnce(impl);
}
function getLastRequestedModel(): string {
const mock = global.fetch as jest.Mock<
Promise<Response> | Response,
[string, { body: string }]
>;
const [, init] = mock.mock.calls[mock.mock.calls.length - 1];
return (JSON.parse(init.body) as { model: string }).model;
}
describe('chat()', () => {
it('should return assistant message when the API responds successfully', async () => {
mockFetchOnce(
@@ -108,5 +117,35 @@ describe('OpenRouterService', () => {
service.chat(1, [{ role: 'user', content: 'Salut' }]),
).rejects.toThrow(/malformee/);
});
it('should append the ":online" suffix to the model when options.online is true', async () => {
mockFetchOnce(
() =>
new Response(
JSON.stringify({ choices: [{ message: { content: 'ok' } }] }),
{ status: 200 },
),
);
await service.chat(1, [{ role: 'user', content: 'Salut' }], {
online: true,
});
expect(getLastRequestedModel()).toBe('deepseek/deepseek-chat:online');
});
it('should NOT append the ":online" suffix when options.online is absent', async () => {
mockFetchOnce(
() =>
new Response(
JSON.stringify({ choices: [{ message: { content: 'ok' } }] }),
{ status: 200 },
),
);
await service.chat(1, [{ role: 'user', content: 'Salut' }]);
expect(getLastRequestedModel()).toBe('deepseek/deepseek-chat');
});
});
});
+7 -2
View File
@@ -42,7 +42,7 @@ export class OpenRouterService {
async chat(
userId: number,
messages: ChatMessage[],
options: { jsonResponse?: boolean } = {},
options: { jsonResponse?: boolean; online?: boolean } = {},
): Promise<string> {
const apiKey = await this.apiKeysService.getDecryptedValue(
userId,
@@ -52,7 +52,12 @@ export class OpenRouterService {
let lastError = 'raison inconnue';
for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
const model = attempt % 2 === 0 ? PRIMARY_MODEL : FALLBACK_MODEL;
const baseModel = attempt % 2 === 0 ? PRIMARY_MODEL : FALLBACK_MODEL;
// Le suffixe ":online" (fonctionnalite native OpenRouter) fait effectuer une vraie
// recherche web au modele avant de repondre : utilise par les agents de recherche
// (cartographie, recherche approfondie, veille) pour respecter l'interdiction de generer
// des sources depuis la seule memoire du modele (voir docs/Max Refonte Coach Freelance.md).
const model = options.online ? `${baseModel}:online` : baseModel;
let response: Response;
try {
response = await fetch(OPENROUTER_URL, {
@@ -0,0 +1,215 @@
import { ConflictException } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { PrismaService } from '../../prisma/prisma.service';
import { OpenRouterService } from '../../llm/openrouter.service';
import { ModuleAgent } from './module.agent';
import { EvaluationAgent } from './evaluation.agent';
describe('EvaluationAgent', () => {
let agent: EvaluationAgent;
const chat = jest.fn();
const upsertEvaluation = jest.fn<
Promise<unknown>,
[
{
create: {
interviewScore: number;
practicalScore: number;
validated: boolean;
};
},
]
>();
const prisma = {
sessionObjective: { findUniqueOrThrow: jest.fn() },
sessionEvaluation: { upsert: upsertEvaluation },
session: { update: jest.fn() },
};
const moduleAgent = { getAllExercisePrompts: jest.fn() };
beforeEach(async () => {
jest.clearAllMocks();
prisma.sessionObjective.findUniqueOrThrow.mockResolvedValue({
subject: 'Facturation freelance',
});
moduleAgent.getAllExercisePrompts.mockResolvedValue(['exercice deja vu']);
const module: TestingModule = await Test.createTestingModule({
providers: [
EvaluationAgent,
{ provide: PrismaService, useValue: prisma },
{ provide: OpenRouterService, useValue: { chat } },
{ provide: ModuleAgent, useValue: moduleAgent },
],
}).compile();
agent = module.get(EvaluationAgent);
});
describe('start()', () => {
it('should start the interview stage without a user message', async () => {
chat.mockResolvedValueOnce(
JSON.stringify({ message: 'Explique-moi ta demarche.', done: false }),
);
const result = await agent.start(1, 7);
expect(result).toEqual({
reply: 'Explique-moi ta demarche.',
done: false,
stage: 'interview',
});
});
});
describe('converse()', () => {
it('should throw ConflictException when no evaluation has started for this session', async () => {
await expect(agent.converse(1, 7, 'reponse')).rejects.toThrow(
ConflictException,
);
});
it('should keep asking while the interview is not done', async () => {
chat.mockResolvedValueOnce(
JSON.stringify({ message: 'Question 1', done: false }),
);
await agent.start(1, 7);
chat.mockResolvedValueOnce(
JSON.stringify({ message: 'Question 2', done: false }),
);
const result = await agent.converse(1, 7, 'reponse 1');
expect(result).toEqual({
reply: 'Question 2',
done: false,
stage: 'interview',
});
});
it('should recompute the interview score in code, persist as failed, and stop (no mission) when below 4/5', async () => {
chat.mockResolvedValueOnce(
JSON.stringify({ message: 'Q1', done: false }),
);
await agent.start(1, 7);
chat.mockResolvedValueOnce(
JSON.stringify({
message: 'Bilan',
done: true,
// Le LLM pretend 5/5 - le code doit recalculer et ignorer cette pretention.
scores: {
vocabulary: 1,
clarity: 0,
limits: 0,
value: 0,
consistency: 1,
},
total: 5,
validated: true,
}),
);
const result = await agent.converse(1, 7, 'reponse finale');
expect(result).toEqual({
reply: 'Bilan',
done: true,
stage: 'interview',
});
const upsertCall = upsertEvaluation.mock.calls[0][0];
expect(upsertCall.create.interviewScore).toBe(2);
expect(upsertCall.create.practicalScore).toBe(0);
expect(upsertCall.create.validated).toBe(false);
expect(prisma.session.update).not.toHaveBeenCalled();
// Nouvelle conversation requise apres un echec : l'etat ephemere est nettoye.
await expect(agent.converse(1, 7, 'suite')).rejects.toThrow(
ConflictException,
);
});
it('should auto-continue to the mission stage when the interview passes (4/5), without a separate confirmation', async () => {
chat.mockResolvedValueOnce(
JSON.stringify({ message: 'Q1', done: false }),
);
await agent.start(1, 7);
chat
.mockResolvedValueOnce(
JSON.stringify({
message: 'Bilan interview',
done: true,
scores: {
vocabulary: 1,
clarity: 1,
limits: 1,
value: 1,
consistency: 0,
},
}),
)
.mockResolvedValueOnce(
JSON.stringify({ message: 'Voici le cas de mission', done: false }),
);
const result = await agent.converse(1, 7, 'reponse finale interview');
expect(moduleAgent.getAllExercisePrompts).toHaveBeenCalledWith(1);
expect(result).toEqual({
reply: 'Voici le cas de mission',
done: false,
stage: 'mission',
});
expect(prisma.sessionEvaluation.upsert).not.toHaveBeenCalled();
});
it('should recompute the mission score, persist the final combined result, and complete the session on full success', async () => {
chat.mockResolvedValueOnce(
JSON.stringify({ message: 'Q1', done: false }),
);
await agent.start(1, 7);
chat
.mockResolvedValueOnce(
JSON.stringify({
message: 'Bilan interview',
done: true,
scores: {
vocabulary: 1,
clarity: 1,
limits: 1,
value: 1,
consistency: 1,
},
}),
)
.mockResolvedValueOnce(
JSON.stringify({ message: 'Cas de mission', done: false }),
);
await agent.converse(1, 7, 'reponse interview');
chat.mockResolvedValueOnce(
JSON.stringify({
message: 'Resultat mission',
done: true,
scores: { application: 1, reasoning: 1, edge_cases: 0, autonomy: 1 },
}),
);
const result = await agent.converse(1, 7, 'reponse mission');
expect(result).toEqual({
reply: 'Resultat mission',
done: true,
stage: 'mission',
});
const upsertCall = upsertEvaluation.mock.calls[0][0];
expect(upsertCall.create.interviewScore).toBe(5);
expect(upsertCall.create.practicalScore).toBe(3);
expect(upsertCall.create.validated).toBe(true);
expect(prisma.session.update).toHaveBeenCalledWith({
where: { id: 1 },
data: { status: 'completed' },
});
});
});
});
@@ -0,0 +1,319 @@
import { ConflictException, Injectable, Logger } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import { ChatMessage, OpenRouterService } from '../../llm/openrouter.service';
import { buildAgentPrompt } from '../prompts/base.prompt';
import { buildEvaluationPrompt } from '../prompts/evaluation.prompt';
import { ModuleAgent } from './module.agent';
export type EvaluationStage = 'interview' | 'mission';
export interface InterviewScores {
vocabulary: 0 | 1;
clarity: 0 | 1;
limits: 0 | 1;
value: 0 | 1;
consistency: 0 | 1;
}
export interface MissionScores {
application: 0 | 1;
reasoning: 0 | 1;
edge_cases: 0 | 1;
autonomy: 0 | 1;
}
export interface EvaluationTurnResult {
reply: string;
done: boolean;
stage: EvaluationStage;
}
export interface EvaluationFinalResult {
validated: boolean;
interviewScore: number;
practicalScore: number;
feedback: {
interview: {
scores: InterviewScores;
feedback: string;
remedialModules: number[];
};
mission?: { scores: MissionScores; feedback: string };
};
}
interface AgentJsonReply {
message?: unknown;
done?: unknown;
scores?: unknown;
}
interface EvaluationState {
history: ChatMessage[];
stage: EvaluationStage;
competence: string;
interviewResult?: {
scores: InterviewScores;
total: number;
validated: boolean;
feedback: string;
};
}
const INTERVIEW_THRESHOLD = 4;
const MISSION_THRESHOLD = 3;
/**
* Agent 7 du pipeline (docs/Max_System_Prompt.md + docs/Max Refonte Coach Freelance.md) :
* evaluation finale en deux temps (entretien client puis cas de mission), demarree
* automatiquement une fois le dernier module complete (voir module.agent.ts, completeModule()).
* Avec personnalite (buildAgentPrompt) : Max parle directement, joue le client puis presente le
* cas de mission. Les scores "total"/"validated" du LLM ne sont JAMAIS utilises tels quels -
* recalcules ici a partir de "scores", meme principe que les autres garde-fous du pipeline.
*/
@Injectable()
export class EvaluationAgent {
private readonly logger = new Logger(EvaluationAgent.name);
private readonly states = new Map<number, EvaluationState>();
constructor(
private readonly prisma: PrismaService,
private readonly llm: OpenRouterService,
private readonly moduleAgent: ModuleAgent,
) {}
/** Demarre l'etape "interview", sans message utilisateur (meme principe que LevelAgent.start :
* Max parle en premier des que l'etape commence). */
async start(
sessionId: number,
userId: number,
): Promise<EvaluationTurnResult> {
const objective = await this.prisma.sessionObjective.findUniqueOrThrow({
where: { sessionId },
});
const competence = objective.subject;
const systemPrompt = buildAgentPrompt(buildEvaluationPrompt(competence));
const history: ChatMessage[] = [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: '[DEBUT] stage: interview' },
];
const raw = await this.llm.chat(userId, history, { jsonResponse: true });
history.push({ role: 'assistant', content: raw });
this.states.set(sessionId, { history, stage: 'interview', competence });
const parsed = this.parseTurn(raw);
return { reply: parsed?.message ?? raw, done: false, stage: 'interview' };
}
async converse(
sessionId: number,
userId: number,
userMessage: string,
): Promise<EvaluationTurnResult> {
const state = this.states.get(sessionId);
if (!state) {
throw new ConflictException(
"L'evaluation finale n'a pas encore demarre pour cette session.",
);
}
state.history.push({ role: 'user', content: userMessage });
const raw = await this.llm.chat(userId, state.history, {
jsonResponse: true,
});
state.history.push({ role: 'assistant', content: raw });
const parsed = this.parseTurn(raw);
if (!parsed || !parsed.done || !parsed.scores) {
return { reply: parsed?.message ?? raw, done: false, stage: state.stage };
}
if (state.stage === 'interview') {
return this.handleInterviewDone(sessionId, userId, state, parsed);
}
return this.handleMissionDone(sessionId, userId, state, parsed);
}
private async handleInterviewDone(
sessionId: number,
userId: number,
state: EvaluationState,
parsed: { message: string; scores?: Record<string, unknown> },
): Promise<EvaluationTurnResult> {
const scores = this.coerceInterviewScores(parsed.scores ?? {});
const total =
scores.vocabulary +
scores.clarity +
scores.limits +
scores.value +
scores.consistency;
const validated = total >= INTERVIEW_THRESHOLD;
state.interviewResult = {
scores,
total,
validated,
feedback: parsed.message,
};
if (!validated) {
// Echec etape 1 : pas de passage a l'etape mission (docs/Max Refonte Coach Freelance.md,
// "condition de validation globale" - les deux etapes dans cet ordre). On persiste quand
// meme le resultat final (non valide) pour que le frontend puisse afficher les lacunes.
await this.persistFinal(sessionId, {
validated: false,
interviewScore: total,
practicalScore: 0,
feedback: {
interview: {
scores,
feedback: parsed.message,
remedialModules: [],
},
},
});
this.states.delete(sessionId);
return {
reply: parsed.message,
done: true,
stage: 'interview',
};
}
// Passage automatique a l'etape mission, sans confirmation separee (docs/Max_System_Prompt.md :
// "Tu ne melanges pas les deux etapes dans le meme echange" mais rien n'exige de validation
// utilisateur entre les deux, contrairement a l'objectif/au curriculum).
const exerciseHistory =
await this.moduleAgent.getAllExercisePrompts(sessionId);
state.stage = 'mission';
state.history.push({
role: 'user',
content: `[ETAPE SUIVANTE] stage: mission. Enonces deja utilises a ne jamais reprendre : ${JSON.stringify(exerciseHistory)}`,
});
const raw = await this.llm.chat(userId, state.history, {
jsonResponse: true,
});
state.history.push({ role: 'assistant', content: raw });
const missionParsed = this.parseTurn(raw);
return {
reply: missionParsed?.message ?? raw,
done: false,
stage: 'mission',
};
}
private async handleMissionDone(
sessionId: number,
_userId: number,
state: EvaluationState,
parsed: { message: string; scores?: Record<string, unknown> },
): Promise<EvaluationTurnResult> {
const scores = this.coerceMissionScores(parsed.scores ?? {});
const total =
scores.application +
scores.reasoning +
scores.edge_cases +
scores.autonomy;
const validated = total >= MISSION_THRESHOLD;
const interview = state.interviewResult;
if (!interview) {
throw new ConflictException(
"Resultat de l'entretien manquant pour finaliser l'evaluation.",
);
}
await this.persistFinal(sessionId, {
validated: interview.validated && validated,
interviewScore: interview.total,
practicalScore: total,
feedback: {
interview: {
scores: interview.scores,
feedback: interview.feedback,
remedialModules: [],
},
mission: { scores, feedback: parsed.message },
},
});
this.states.delete(sessionId);
if (interview.validated && validated) {
await this.prisma.session.update({
where: { id: sessionId },
data: { status: 'completed' },
});
}
return { reply: parsed.message, done: true, stage: 'mission' };
}
private async persistFinal(
sessionId: number,
result: EvaluationFinalResult,
): Promise<void> {
await this.prisma.sessionEvaluation.upsert({
where: { sessionId },
create: {
sessionId,
interviewScore: result.interviewScore,
practicalScore: result.practicalScore,
validated: result.validated,
feedback: result.feedback as unknown as Prisma.InputJsonValue,
completedAt: new Date(),
},
update: {
interviewScore: result.interviewScore,
practicalScore: result.practicalScore,
validated: result.validated,
feedback: result.feedback as unknown as Prisma.InputJsonValue,
completedAt: new Date(),
},
});
}
private toBit(value: unknown): 0 | 1 {
return Number(value) === 1 ? 1 : 0;
}
private coerceInterviewScores(raw: Record<string, unknown>): InterviewScores {
return {
vocabulary: this.toBit(raw.vocabulary),
clarity: this.toBit(raw.clarity),
limits: this.toBit(raw.limits),
value: this.toBit(raw.value),
consistency: this.toBit(raw.consistency),
};
}
private coerceMissionScores(raw: Record<string, unknown>): MissionScores {
return {
application: this.toBit(raw.application),
reasoning: this.toBit(raw.reasoning),
edge_cases: this.toBit(raw.edge_cases),
autonomy: this.toBit(raw.autonomy),
};
}
private parseTurn(raw: string): {
message: string;
done: boolean;
scores?: Record<string, unknown>;
} | null {
try {
const parsed = JSON.parse(raw) as AgentJsonReply;
if (typeof parsed.message !== 'string') return null;
return {
message: parsed.message,
done: parsed.done === true,
scores:
parsed.scores && typeof parsed.scores === 'object'
? (parsed.scores as Record<string, unknown>)
: undefined,
};
} catch {
this.logger.warn(
`Reponse de l'Agent 7 non-JSON, affichee telle quelle: ${raw}`,
);
return null;
}
}
}
@@ -0,0 +1,201 @@
import { ConflictException } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { PrismaService } from '../../prisma/prisma.service';
import { OpenRouterService } from '../../llm/openrouter.service';
import { LevelAgent } from './level.agent';
describe('LevelAgent', () => {
let agent: LevelAgent;
const chat = jest.fn<Promise<string>, [number, unknown[], unknown?]>();
const create = jest.fn<
Promise<unknown>,
[{ data: { questionsAsked: string[]; userAnswers: string[] } }]
>();
const findUnique = jest.fn();
const update = jest.fn<
Promise<unknown>,
[
{
data: {
masteredConcepts: string[];
gapConcepts: { concept: string }[];
};
},
]
>();
const prisma = {
sessionLevelAssessment: { create, findUnique, update },
};
const profileJson = JSON.stringify({
message: 'Voila, j-ai une idee claire de ton niveau.',
done: true,
mastered: ['Facturation'],
gaps: [{ concept: 'TVA', description: 'Confond taux normal et reduit' }],
unknown: ['TVA intracommunautaire'],
overall_level: 'intermediate',
});
beforeEach(async () => {
jest.clearAllMocks();
const module: TestingModule = await Test.createTestingModule({
providers: [
LevelAgent,
{ provide: PrismaService, useValue: prisma },
{ provide: OpenRouterService, useValue: { chat } },
],
}).compile();
agent = module.get(LevelAgent);
});
describe('start()', () => {
it('should ask the first situational question without any user message', async () => {
chat.mockResolvedValueOnce(
JSON.stringify({
message:
'Si un client te demande une facture avec TVA, que fais-tu ?',
done: false,
}),
);
const result = await agent.start(
1,
7,
'Facturation freelance',
'Facturation, TVA',
);
// Pas d'assertion sur le contenu exact du tableau "history" passe a chat() : jest garde une
// reference (pas une copie) des arguments, et ce meme tableau est mute juste apres (push de
// la reponse assistant) - comparer son contenu ici verifierait son etat final, pas celui au
// moment de l'appel.
expect(chat).toHaveBeenCalledTimes(1);
expect(chat.mock.calls[0][0]).toBe(7);
expect(chat.mock.calls[0][2]).toEqual({ jsonResponse: true });
expect(result).toEqual({
reply: 'Si un client te demande une facture avec TVA, que fais-tu ?',
done: false,
});
});
});
describe('converse()', () => {
it('should throw ConflictException when start() was never called for this session', async () => {
await expect(agent.converse(1, 7, 'une reponse')).rejects.toThrow(
ConflictException,
);
});
it('should keep asking until done, then produce the profile', async () => {
chat.mockResolvedValueOnce(
JSON.stringify({ message: 'Premiere question ?', done: false }),
);
await agent.start(1, 7, 'Facturation freelance', 'Facturation, TVA');
chat.mockResolvedValueOnce(profileJson);
const result = await agent.converse(1, 7, 'Ma reponse');
expect(result.done).toBe(true);
expect(result.profile).toEqual({
mastered: ['Facturation'],
gaps: [
{ concept: 'TVA', description: 'Confond taux normal et reduit' },
],
unknown: ['TVA intracommunautaire'],
overallLevel: 'intermediate',
});
});
});
describe('confirm()', () => {
it('should throw ConflictException when no profile is ready', async () => {
await expect(agent.confirm(1)).rejects.toThrow(ConflictException);
});
it('should persist the profile with the extracted questions/answers once ready', async () => {
chat.mockResolvedValueOnce(
JSON.stringify({ message: 'Premiere question ?', done: false }),
);
await agent.start(1, 7, 'Facturation freelance', 'Facturation, TVA');
chat.mockResolvedValueOnce(profileJson);
await agent.converse(1, 7, 'Ma reponse');
create.mockResolvedValueOnce({
id: 2,
sessionId: 1,
masteredConcepts: ['Facturation'],
gapConcepts: [
{ concept: 'TVA', description: 'Confond taux normal et reduit' },
],
unknownConcepts: ['TVA intracommunautaire'],
overallLevel: 'intermediate',
completedAt: new Date('2026-01-01'),
});
const result = await agent.confirm(1);
expect(create.mock.calls[0][0].data.questionsAsked).toEqual([
'Premiere question ?',
]);
expect(create.mock.calls[0][0].data.userAnswers).toEqual(['Ma reponse']);
expect(result.id).toBe(2);
await expect(agent.confirm(1)).rejects.toThrow(ConflictException);
});
});
describe('dispute()', () => {
it('should throw ConflictException when no level assessment exists yet', async () => {
findUnique.mockResolvedValueOnce(null);
await expect(
agent.dispute(1, 7, 'TVA', 'Ma reponse argumentee'),
).rejects.toThrow(ConflictException);
});
it('should move a concept into "mastered" when the dispute answer demonstrates mastery', async () => {
findUnique.mockResolvedValueOnce({
masteredConcepts: ['Facturation'],
gapConcepts: [
{ concept: 'TVA', description: 'Confond taux normal et reduit' },
],
unknownConcepts: [],
});
chat.mockResolvedValueOnce(
JSON.stringify({ bucket: 'mastered', description: null }),
);
update.mockResolvedValueOnce({
id: 1,
sessionId: 1,
masteredConcepts: ['Facturation', 'TVA'],
gapConcepts: [],
unknownConcepts: [],
});
await agent.dispute(
1,
7,
'TVA',
"J'applique le bon taux selon le pays du client.",
);
expect(update.mock.calls[0][0].data.masteredConcepts).toContain('TVA');
expect(update.mock.calls[0][0].data.gapConcepts).toEqual([]);
});
it('should default to "gap" when the dispute response is not valid JSON (prudence)', async () => {
findUnique.mockResolvedValueOnce({
masteredConcepts: [],
gapConcepts: [],
unknownConcepts: ['TVA'],
});
chat.mockResolvedValueOnce('reponse non-JSON');
update.mockResolvedValueOnce({ id: 1, sessionId: 1 });
await agent.dispute(1, 7, 'TVA', 'reponse');
expect(update.mock.calls[0][0].data.gapConcepts[0].concept).toBe('TVA');
});
});
});
+329
View File
@@ -0,0 +1,329 @@
import { ConflictException, Injectable, Logger } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import { ChatMessage, OpenRouterService } from '../../llm/openrouter.service';
import { buildAgentPrompt } from '../prompts/base.prompt';
import { LEVEL_JSON_CONTRACT, LEVEL_PROMPT } from '../prompts/level.prompt';
export type OverallLevel = 'beginner' | 'intermediate' | 'advanced';
export interface LevelGap {
concept: string;
description: string;
}
export interface LevelProfile {
mastered: string[];
gaps: LevelGap[];
unknown: string[];
overallLevel: OverallLevel;
}
export interface LevelTurnResult {
reply: string;
done: boolean;
profile?: LevelProfile;
}
export interface StoredLevelAssessment {
id: number;
sessionId: number;
masteredConcepts: unknown;
gapConcepts: unknown;
unknownConcepts: unknown;
overallLevel: string;
completedAt: Date | null;
}
interface AgentJsonReply {
message?: unknown;
done?: unknown;
mastered?: unknown;
gaps?: unknown;
unknown?: unknown;
overall_level?: unknown;
}
/**
* Agent 3 du pipeline (docs/Max_System_Prompt.md) : 3 a 5 questions situationnelles construites
* depuis la carte des concepts de l'Agent 2, jamais un QCM. Meme forme conversationnelle que
* ObjectiveAgent (historique ephemere en memoire, par session) : wrap avec buildAgentPrompt() car
* ces questions sont posees/lues par l'utilisateur comme venant de Max (contrairement a
* MappingAgent/ResearchAgent, qui produisent des donnees que personne n'entend).
*/
@Injectable()
export class LevelAgent {
private readonly logger = new Logger(LevelAgent.name);
private readonly conversations = new Map<number, ChatMessage[]>();
private readonly readyProfiles = new Map<number, LevelProfile>();
constructor(
private readonly prisma: PrismaService,
private readonly llm: OpenRouterService,
) {}
/**
* Premier tour, sans message utilisateur : demarre la conversation pour que Max pose
* immediatement sa premiere question des que l'Agent 2 a produit la carte (voir
* sessions.service.ts, confirmObjective()). C'est le seul moment ou Max parle pendant la
* construction, hors reponse directe a l'utilisateur (docs/Max Refonte Coach Freelance.md,
* "Garde-fous transversaux").
*/
async start(
sessionId: number,
userId: number,
objectiveSummary: string,
conceptMapSummary: string,
): Promise<LevelTurnResult> {
const systemPrompt = buildAgentPrompt(
`${LEVEL_PROMPT.replace('[OBJECTIF_INJECTÉ_PAR_LE_BACKEND]', objectiveSummary).replace('[CARTE_INJECTÉE_PAR_LE_BACKEND]', conceptMapSummary)}\n\n${LEVEL_JSON_CONTRACT}`,
);
const history: ChatMessage[] = [{ role: 'system', content: systemPrompt }];
const raw = await this.llm.chat(userId, history, { jsonResponse: true });
history.push({ role: 'assistant', content: raw });
this.conversations.set(sessionId, history);
return this.handleReply(sessionId, raw);
}
async converse(
sessionId: number,
userId: number,
userMessage: string,
): Promise<LevelTurnResult> {
const history = this.conversations.get(sessionId);
if (!history) {
throw new ConflictException(
"L'evaluation de niveau n'a pas encore demarre pour cette session.",
);
}
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);
return this.handleReply(sessionId, raw);
}
async confirm(sessionId: number): Promise<StoredLevelAssessment> {
const profile = this.readyProfiles.get(sessionId);
const history = this.conversations.get(sessionId);
if (!profile || !history) {
throw new ConflictException(
"Aucun profil de niveau pret a confirmer pour cette session : continue le dialogue d'abord.",
);
}
const { questionsAsked, userAnswers } = this.extractExchanges(history);
const record = await this.prisma.sessionLevelAssessment.create({
data: {
sessionId,
questionsAsked: questionsAsked,
userAnswers: userAnswers,
masteredConcepts: profile.mastered,
gapConcepts: profile.gaps as unknown as Prisma.InputJsonValue,
unknownConcepts: profile.unknown,
overallLevel: profile.overallLevel,
completedAt: new Date(),
},
});
this.conversations.delete(sessionId);
this.readyProfiles.delete(sessionId);
return record;
}
/**
* Contestation d'un concept (docs/Max Refonte Coach Freelance.md : "en cas de correction,
* l'agent relance une question ciblee sur le point conteste"). Simplification assumee : un seul
* aller-retour (concept + reponse fournis ensemble), pas une sous-conversation a part, pour
* rester compatible avec le pipeline vocal/texte unique (pas de sous-etat de routage dedie).
*/
async dispute(
sessionId: number,
userId: number,
concept: string,
answer: string,
): Promise<StoredLevelAssessment> {
const existing = await this.prisma.sessionLevelAssessment.findUnique({
where: { sessionId },
});
if (!existing) {
throw new ConflictException(
'Aucun profil de niveau a contester pour cette session.',
);
}
const raw = await this.llm.chat(
userId,
[
{
role: 'system',
content:
'Tu evalues si la reponse suivante demontre une maitrise reelle du concept indique. ' +
'Reponds UNIQUEMENT avec ce JSON strict : ' +
'{"bucket": "mastered" | "gap" | "unknown", "description": "..." | null}. ' +
'"description" est obligatoire si bucket="gap" (lacune precise observee), sinon null.',
},
{
role: 'user',
content: JSON.stringify({ concept, answer }),
},
],
{ jsonResponse: true },
);
const bucket = this.parseDisputeBucket(raw);
const mastered = new Set(existing.masteredConcepts as unknown as string[]);
const gaps = (existing.gapConcepts as unknown as LevelGap[]).filter(
(g) => g.concept !== concept,
);
const unknown = new Set(existing.unknownConcepts as unknown as string[]);
mastered.delete(concept);
unknown.delete(concept);
if (bucket.bucket === 'mastered') mastered.add(concept);
else if (bucket.bucket === 'gap') {
gaps.push({
concept,
description:
bucket.description ?? 'Lacune confirmee a la contestation.',
});
} else unknown.add(concept);
return this.prisma.sessionLevelAssessment.update({
where: { sessionId },
data: {
masteredConcepts: Array.from(mastered),
gapConcepts: gaps as unknown as Prisma.InputJsonValue,
unknownConcepts: Array.from(unknown),
},
});
}
private handleReply(sessionId: number, raw: string): LevelTurnResult {
const parsed = this.parseAgentReply(raw);
if (!parsed) return { reply: raw, done: false };
if (
!parsed.done ||
!parsed.mastered ||
!parsed.gaps ||
!parsed.unknown ||
!parsed.overallLevel
) {
return { reply: parsed.message, done: false };
}
const profile: LevelProfile = {
mastered: parsed.mastered,
gaps: parsed.gaps,
unknown: parsed.unknown,
overallLevel: parsed.overallLevel,
};
this.readyProfiles.set(sessionId, profile);
return { reply: parsed.message, done: true, profile };
}
private parseAgentReply(raw: string): {
message: string;
done: boolean;
mastered?: string[];
gaps?: LevelGap[];
unknown?: string[];
overallLevel?: OverallLevel;
} | null {
try {
const parsed = JSON.parse(raw) as AgentJsonReply;
if (typeof parsed.message !== 'string') return null;
const done = parsed.done === true;
if (!done) return { message: parsed.message, done: false };
if (
!Array.isArray(parsed.mastered) ||
!Array.isArray(parsed.gaps) ||
!Array.isArray(parsed.unknown) ||
!['beginner', 'intermediate', 'advanced'].includes(
String(parsed.overall_level),
)
) {
return { message: parsed.message, done: false };
}
return {
message: parsed.message,
done: true,
mastered: (parsed.mastered as unknown[]).map(String),
gaps: (parsed.gaps as { concept?: unknown; description?: unknown }[])
.filter(
(g) =>
typeof g.concept === 'string' &&
typeof g.description === 'string',
)
.map((g) => ({
concept: String(g.concept),
description: String(g.description),
})),
unknown: (parsed.unknown as unknown[]).map(String),
overallLevel: parsed.overall_level as OverallLevel,
};
} catch {
this.logger.warn(
`Reponse de l'Agent 3 non-JSON, affichee telle quelle: ${raw}`,
);
return null;
}
}
private parseDisputeBucket(raw: string): {
bucket: 'mastered' | 'gap' | 'unknown';
description: string | null;
} {
try {
const parsed = JSON.parse(raw) as {
bucket?: unknown;
description?: unknown;
};
if (!['mastered', 'gap', 'unknown'].includes(String(parsed.bucket))) {
return { bucket: 'gap', description: null };
}
return {
bucket: parsed.bucket as 'mastered' | 'gap' | 'unknown',
description:
typeof parsed.description === 'string' ? parsed.description : null,
};
} catch {
this.logger.warn(
`Reponse de contestation non-JSON, classee "gap" par prudence: ${raw}`,
);
return { bucket: 'gap', description: null };
}
}
private extractExchanges(history: ChatMessage[]): {
questionsAsked: string[];
userAnswers: string[];
} {
const questionsAsked: string[] = [];
const userAnswers: string[] = [];
for (const message of history) {
if (message.role === 'assistant') {
try {
const parsed = JSON.parse(message.content) as {
message?: unknown;
done?: unknown;
};
// La derniere reponse (done=true) est la phrase de transition du profil, pas une
// question posee a l'utilisateur - elle n'a donc pas de reponse correspondante.
if (typeof parsed.message === 'string' && parsed.done !== true) {
questionsAsked.push(parsed.message);
}
} catch {
// Reponse non-JSON ignoree pour l'historique des questions (deja geree en temps reel
// par handleReply, qui a renvoye le texte brut tel quel a l'utilisateur).
}
} else if (message.role === 'user') {
userAnswers.push(message.content);
}
}
return { questionsAsked, userAnswers };
}
}
@@ -0,0 +1,139 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PrismaService } from '../../prisma/prisma.service';
import { OpenRouterService } from '../../llm/openrouter.service';
import { MappingAgent } from './mapping.agent';
describe('MappingAgent', () => {
let agent: MappingAgent;
const chat = jest.fn();
const findUnique = jest.fn();
const create = jest.fn<Promise<unknown>, [{ data: { sessionId: number } }]>();
const prisma = { sessionConceptMap: { findUnique, create } };
const validConceptMapJson = JSON.stringify({
concepts: [
{
name: 'Facturation',
level: 'beginner',
prerequisites: [],
can_do: 'être capable de facturer un client avec la bonne TVA',
market_demand: 'high',
sources: [
{ title: 'URSSAF', source_tier: 1 },
{ title: 'Guide expert-comptable', source_tier: 3 },
],
},
{
name: 'TVA intracommunautaire',
level: 'intermediate',
prerequisites: ['Facturation'],
can_do: 'être capable de facturer un client europeen sans TVA',
market_demand: 'medium',
sources: [
{ title: 'Impots.gouv.fr', source_tier: 1 },
{ title: "Offre d'emploi comptable", source_tier: 4 },
{ title: 'LinkedIn Learning', source_tier: 3 },
],
},
],
sources_count: 5,
});
beforeEach(async () => {
jest.clearAllMocks();
const module: TestingModule = await Test.createTestingModule({
providers: [
MappingAgent,
{ provide: PrismaService, useValue: prisma },
{ provide: OpenRouterService, useValue: { chat } },
],
}).compile();
agent = module.get(MappingAgent);
});
describe('runForSession()', () => {
it('should do nothing if a concept map already exists for this session (idempotent)', async () => {
findUnique.mockResolvedValueOnce({ id: 1 });
await agent.runForSession(1, 7, 'Facturation freelance');
expect(chat).not.toHaveBeenCalled();
expect(create).not.toHaveBeenCalled();
});
it('should request real web search (":online") and persist a valid concept map', async () => {
findUnique.mockResolvedValueOnce(null);
chat.mockResolvedValueOnce(validConceptMapJson);
await agent.runForSession(1, 7, 'Facturation freelance');
expect(chat).toHaveBeenCalledWith(
7,
expect.anything(),
expect.objectContaining({ online: true }),
);
expect(create).toHaveBeenCalledTimes(1);
expect(create.mock.calls[0][0].data.sessionId).toBe(1);
});
it('should retry once then accept when the first attempt fails the measurable rules (e.g. too few sources)', async () => {
findUnique.mockResolvedValueOnce(null);
chat
.mockResolvedValueOnce(
JSON.stringify({
concepts: [
{
name: 'Facturation',
level: 'beginner',
prerequisites: [],
can_do: 'être capable de facturer',
sources: [{ title: 'Seule source', source_tier: 1 }],
},
],
sources_count: 1,
}),
)
.mockResolvedValueOnce(validConceptMapJson);
await agent.runForSession(1, 7, 'Facturation freelance');
expect(chat).toHaveBeenCalledTimes(2);
expect(create).toHaveBeenCalledTimes(1);
});
it('should throw when the concept map still fails after the retry', async () => {
findUnique.mockResolvedValueOnce(null);
chat.mockResolvedValue('reponse non-JSON');
await expect(
agent.runForSession(1, 7, 'Facturation freelance'),
).rejects.toThrow(/carte conforme/);
expect(create).not.toHaveBeenCalled();
});
it('should reject a concept using forbidden wording ("comprendre"/"savoir") even with enough sources', async () => {
findUnique.mockResolvedValueOnce(null);
const invalidWording = JSON.stringify({
concepts: [
{
name: 'Facturation',
level: 'beginner',
prerequisites: [],
can_do: 'comprendre la facturation',
sources: [
{ title: 'A', source_tier: 1 },
{ title: 'B', source_tier: 3 },
],
},
],
sources_count: 5,
});
chat.mockResolvedValue(invalidWording);
await expect(
agent.runForSession(1, 7, 'Facturation freelance'),
).rejects.toThrow(/carte conforme/);
});
});
});
@@ -0,0 +1,208 @@
import { Injectable, Logger } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import { OpenRouterService } from '../../llm/openrouter.service';
import {
MAPPING_JSON_CONTRACT,
MAPPING_PROMPT,
} from '../prompts/mapping.prompt';
export interface ConceptSource {
title: string;
sourceTier: 1 | 2 | 3 | 4;
}
export interface Concept {
name: string;
level: 'beginner' | 'intermediate' | 'advanced';
prerequisites: string[];
canDo: string;
marketDemand: 'low' | 'medium' | 'high';
sources: ConceptSource[];
}
export interface ConceptMapResult {
concepts: Concept[];
sourcesCount: number;
}
interface RawConceptSource {
title?: unknown;
source_tier?: unknown;
}
interface RawConcept {
name?: unknown;
level?: unknown;
prerequisites?: unknown;
can_do?: unknown;
market_demand?: unknown;
sources?: unknown;
}
interface RawConceptMap {
concepts?: unknown;
sources_count?: unknown;
}
const SYSTEM_PROMPT_TEMPLATE = `${MAPPING_PROMPT}\n\n${MAPPING_JSON_CONTRACT}`;
const MIN_SOURCES_COUNT = 5;
const MAX_VALIDATION_RETRIES = 1;
const CAN_DO_PATTERN = /etre capable de|être capable de/i;
const FORBIDDEN_WORDING_PATTERN = /\b(comprendre|savoir)\b/i;
/**
* Agent 2 du pipeline (docs/Max_System_Prompt.md + docs/Max Refonte Coach Freelance.md) :
* cartographie des concepts cles, un seul appel LLM avec recherche web reelle (OpenRouter
* ":online", voir openrouter.service.ts) - aucune conversation, aucun tour utilisateur. Pas de
* personnalite Max ici (voir buildAgentPrompt) : personne n'entend cet agent, c'est un producteur
* de donnees pur, meme choix que intent-router.prompt.ts.
*/
@Injectable()
export class MappingAgent {
private readonly logger = new Logger(MappingAgent.name);
constructor(
private readonly prisma: PrismaService,
private readonly llm: OpenRouterService,
) {}
async runForSession(
sessionId: number,
userId: number,
objectiveSummary: string,
): Promise<void> {
const existing = await this.prisma.sessionConceptMap.findUnique({
where: { sessionId },
});
if (existing) return;
const prompt = SYSTEM_PROMPT_TEMPLATE.replace(
'[OBJECTIF_INJECTÉ_PAR_LE_BACKEND]',
objectiveSummary,
);
let result = await this.requestAndValidate(userId, prompt);
for (
let attempt = 0;
!result && attempt < MAX_VALIDATION_RETRIES;
attempt++
) {
this.logger.warn(
`Carte des concepts non conforme aux regles mesurables, nouvelle tentative (${attempt + 1})`,
);
result = await this.requestAndValidate(userId, prompt);
}
if (!result) {
throw new Error(
"L'Agent 2 (Cartographie) n'a pas produit de carte conforme apres relance.",
);
}
const sourcesUsed = this.flattenSources(result.concepts);
await this.prisma.sessionConceptMap.create({
data: {
sessionId,
concepts: result.concepts as unknown as Prisma.InputJsonValue,
sourcesUsed: sourcesUsed as unknown as Prisma.InputJsonValue,
completedAt: new Date(),
},
});
}
private async requestAndValidate(
userId: number,
prompt: string,
): Promise<ConceptMapResult | null> {
const raw = await this.llm.chat(
userId,
[{ role: 'system', content: prompt }],
{
jsonResponse: true,
online: true,
},
);
const parsed = this.parse(raw);
if (!parsed) return null;
if (!this.passesMeasurableRules(parsed)) return null;
return parsed;
}
private parse(raw: string): ConceptMapResult | null {
try {
const data = JSON.parse(raw) as RawConceptMap;
if (!Array.isArray(data.concepts)) return null;
const concepts: Concept[] = [];
for (const raw_ of data.concepts as RawConcept[]) {
const concept = this.parseConcept(raw_);
if (!concept) return null;
concepts.push(concept);
}
if (concepts.length === 0) return null;
const sourcesCount =
Number(data.sources_count) || this.flattenSources(concepts).length;
return { concepts, sourcesCount };
} catch {
this.logger.warn(`Carte des concepts non-JSON, rejetee: ${raw}`);
return null;
}
}
private parseConcept(raw: RawConcept): Concept | null {
if (typeof raw.name !== 'string' || typeof raw.can_do !== 'string')
return null;
if (!['beginner', 'intermediate', 'advanced'].includes(String(raw.level))) {
return null;
}
if (!Array.isArray(raw.sources) || raw.sources.length === 0) return null;
const sources: ConceptSource[] = [];
for (const rawSource of raw.sources as RawConceptSource[]) {
if (typeof rawSource.title !== 'string') return null;
const tier = Number(rawSource.source_tier);
sources.push({
title: rawSource.title,
sourceTier: ([1, 2, 3, 4].includes(tier) ? tier : 3) as 1 | 2 | 3 | 4,
});
}
return {
name: raw.name,
level: raw.level as Concept['level'],
prerequisites: Array.isArray(raw.prerequisites)
? raw.prerequisites.map(String)
: [],
canDo: raw.can_do,
marketDemand: (['low', 'medium', 'high'].includes(
String(raw.market_demand),
)
? raw.market_demand
: 'medium') as Concept['marketDemand'],
sources,
};
}
/** Regles mesurables de docs/Max Refonte Coach Freelance.md : >=5 sources au total, "etre
* capable de" obligatoire (0 "comprendre"/"savoir" tolere), >=2 sources par concept cle. */
private passesMeasurableRules(result: ConceptMapResult): boolean {
if (result.sourcesCount < MIN_SOURCES_COUNT) return false;
for (const concept of result.concepts) {
if (!CAN_DO_PATTERN.test(concept.canDo)) return false;
if (FORBIDDEN_WORDING_PATTERN.test(concept.canDo)) return false;
if (concept.sources.length < 2) return false;
}
return true;
}
private flattenSources(concepts: Concept[]): ConceptSource[] {
const deduped = new Map<string, ConceptSource>();
for (const concept of concepts) {
for (const source of concept.sources) {
deduped.set(source.title, source);
}
}
return Array.from(deduped.values());
}
}
@@ -0,0 +1,440 @@
import { ConflictException } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { PrismaService } from '../../prisma/prisma.service';
import { OpenRouterService } from '../../llm/openrouter.service';
import { ModuleAgent, StoredModuleContent } from './module.agent';
function words(n: number, base = 'mot'): string {
return new Array(n).fill(base).join(' ');
}
function buildExercise(id: number, level: 'easy' | 'medium' | 'hard') {
return {
level,
context: `Contexte exercice ${id}`,
prompt: `Enonce exercice ${id}`,
hints: ['indice 1', 'indice 2', 'indice 3', 'indice 4', 'indice 5'],
correctAnswerInternal: `reponse-${id}`,
};
}
function buildValidAuthoredJson() {
return {
hook: words(160),
theory: {
coreIdea: words(70),
analogy: words(70),
formalDefinition: words(70),
workedExample: words(70),
counterExample: words(70),
},
weDo: {
problem: 'Un probleme guide',
guidingQuestions: ['Question 1 ?', 'Question 2 ?', 'Question 3 ?'],
},
exercises: [
buildExercise(1, 'easy'),
buildExercise(2, 'easy'),
buildExercise(3, 'medium'),
buildExercise(4, 'medium'),
buildExercise(5, 'hard'),
buildExercise(6, 'hard'),
],
debugExercise: {
codeOrReasoningWithBug: 'const x = 1 // bug',
language: 'typescript',
instruction: 'Trouve et corrige le bug.',
correctionInternal: 'const x = 2',
},
synthesis: {
recap: words(40),
metacognitionQuestions: [words(10), words(10), words(10)],
feynmanPrompt: words(40),
},
};
}
function buildStoredContent(): StoredModuleContent {
const authored = buildValidAuthoredJson();
return {
...authored,
exercises: authored.exercises.map((e, i) => ({
id: `ex-${i + 1}`,
...e,
})),
progress: {
currentAwaiting: { type: 'exercise', exerciseId: 'ex-1' },
exercises: {
'ex-1': { attempts: 0, passed: false, hintLevel: 0 },
'ex-2': { attempts: 0, passed: false, hintLevel: 0 },
'ex-3': { attempts: 0, passed: false, hintLevel: 0 },
'ex-4': { attempts: 0, passed: false, hintLevel: 0 },
'ex-5': { attempts: 0, passed: false, hintLevel: 0 },
'ex-6': { attempts: 0, passed: false, hintLevel: 0 },
},
debugPassed: false,
feynman: null,
},
} as unknown as StoredModuleContent;
}
describe('ModuleAgent', () => {
let agent: ModuleAgent;
const chat = jest.fn();
const createModule = jest.fn<
Promise<unknown>,
[{ data: { moduleIndex: number; status: string } }]
>();
const updateModule = jest.fn<
Promise<unknown>,
[{ where: { id: number }; data: { content: StoredModuleContent } }]
>();
const prisma = {
sessionModule: {
findUnique: jest.fn(),
findMany: jest.fn(),
create: createModule,
update: updateModule,
},
sessionCurriculum: { findUniqueOrThrow: jest.fn(), update: jest.fn() },
sessionObjective: { findUniqueOrThrow: jest.fn() },
sessionLevelAssessment: { findUniqueOrThrow: jest.fn() },
sessionResearch: { findUniqueOrThrow: jest.fn() },
session: { update: jest.fn() },
};
beforeEach(async () => {
jest.clearAllMocks();
prisma.sessionObjective.findUniqueOrThrow.mockResolvedValue({
subject: 'Facturation',
professionalGoal: 'Facturer sans erreur',
duration: '2 semaines',
});
prisma.sessionLevelAssessment.findUniqueOrThrow.mockResolvedValue({
overallLevel: 'beginner',
});
prisma.sessionResearch.findUniqueOrThrow.mockResolvedValue({
corpus: {
subtopics: [
{
subtopic: 'TVA',
summary: 'resume',
keyPoints: ['a'],
commonMistakes: ['b'],
},
],
},
});
prisma.sessionModule.findMany.mockResolvedValue([]);
const module: TestingModule = await Test.createTestingModule({
providers: [
ModuleAgent,
{ provide: PrismaService, useValue: prisma },
{ provide: OpenRouterService, useValue: { chat } },
],
}).compile();
agent = module.get(ModuleAgent);
});
describe('generateModule()', () => {
it('should return the existing public content when the module was already generated (idempotent)', async () => {
const content = buildStoredContent();
prisma.sessionModule.findUnique.mockResolvedValueOnce({
id: 1,
title: 'Module existant',
content,
});
const result = await agent.generateModule(1, 7, 1);
expect(result.title).toBe('Module existant');
expect(chat).not.toHaveBeenCalled();
expect(prisma.sessionModule.create).not.toHaveBeenCalled();
});
it('should generate and persist a valid module', async () => {
prisma.sessionModule.findUnique.mockResolvedValueOnce(null);
prisma.sessionCurriculum.findUniqueOrThrow.mockResolvedValueOnce({
modules: [{ index: 1, title: 'Module 1', concept: 'concept-1' }],
});
chat.mockResolvedValueOnce(JSON.stringify(buildValidAuthoredJson()));
const result = await agent.generateModule(1, 7, 1);
expect(result.title).toBe('Module 1');
expect(result.exercises).toHaveLength(6);
expect(result.exercises[0].revealedHints).toEqual([]);
const createCall = createModule.mock.calls[0][0];
expect(createCall.data.moduleIndex).toBe(1);
expect(createCall.data.status).toBe('generated');
});
it('should throw ConflictException when the requested module index is not in the curriculum', async () => {
prisma.sessionModule.findUnique.mockResolvedValueOnce(null);
prisma.sessionCurriculum.findUniqueOrThrow.mockResolvedValueOnce({
modules: [{ index: 1, title: 'Module 1', concept: 'concept-1' }],
});
await expect(agent.generateModule(1, 7, 2)).rejects.toThrow(
ConflictException,
);
});
it('should retry once then throw when the module content fails validation (too short)', async () => {
prisma.sessionModule.findUnique.mockResolvedValueOnce(null);
prisma.sessionCurriculum.findUniqueOrThrow.mockResolvedValueOnce({
modules: [{ index: 1, title: 'Module 1', concept: 'concept-1' }],
});
const tooShort = { ...buildValidAuthoredJson(), hook: 'trop court' };
chat.mockResolvedValueOnce(JSON.stringify(tooShort));
chat.mockResolvedValueOnce(JSON.stringify(tooShort));
await expect(agent.generateModule(1, 7, 1)).rejects.toThrow();
expect(chat).toHaveBeenCalledTimes(2);
expect(prisma.sessionModule.create).not.toHaveBeenCalled();
});
});
describe('submitExerciseAnswer()', () => {
it('should judge the answer, update progress, and recompute currentAwaiting', async () => {
const content = buildStoredContent();
prisma.sessionModule.findUnique.mockResolvedValueOnce({ id: 1, content });
chat.mockResolvedValueOnce(
JSON.stringify({ correct: true, feedback: 'Bonne reponse, car...' }),
);
const result = await agent.submitExerciseAnswer(
1,
7,
1,
'ex-1',
'ma reponse',
);
expect(result).toEqual({
correct: true,
feedback: 'Bonne reponse, car...',
});
const updateCall = updateModule.mock.calls[0][0];
expect(updateCall.data.content.progress.currentAwaiting).toEqual({
type: 'exercise',
exerciseId: 'ex-2',
});
});
it('should throw ConflictException for an unknown exercise id', async () => {
const content = buildStoredContent();
prisma.sessionModule.findUnique.mockResolvedValueOnce({ id: 1, content });
await expect(
agent.submitExerciseAnswer(1, 7, 1, 'ex-unknown', 'reponse'),
).rejects.toThrow(ConflictException);
});
it('should default to incorrect when the judge reply is not valid JSON', async () => {
const content = buildStoredContent();
prisma.sessionModule.findUnique.mockResolvedValueOnce({ id: 1, content });
chat.mockResolvedValueOnce('pas du json');
const result = await agent.submitExerciseAnswer(
1,
7,
1,
'ex-1',
'reponse',
);
expect(result.correct).toBe(false);
});
});
describe('requestHint()', () => {
it('should reveal hints one level at a time without calling the LLM', async () => {
const content = buildStoredContent();
prisma.sessionModule.findUnique.mockResolvedValueOnce({ id: 1, content });
const result = await agent.requestHint(1, 1, 'ex-1');
expect(chat).not.toHaveBeenCalled();
expect(result).toEqual({ level: 1, hint: 'indice 1' });
});
it('should return null once all 5 hints are exhausted', async () => {
const content = buildStoredContent();
content.progress.exercises['ex-1'].hintLevel = 5;
prisma.sessionModule.findUnique.mockResolvedValueOnce({ id: 1, content });
const result = await agent.requestHint(1, 1, 'ex-1');
expect(result).toEqual({ level: 5, hint: null });
expect(prisma.sessionModule.update).not.toHaveBeenCalled();
});
});
describe('submitDebugCorrection()', () => {
it('should judge the correction against the internal correction and update progress', async () => {
const content = buildStoredContent();
prisma.sessionModule.findUnique.mockResolvedValueOnce({ id: 1, content });
chat.mockResolvedValueOnce(
JSON.stringify({ correct: true, feedback: 'Correction exacte.' }),
);
const result = await agent.submitDebugCorrection(1, 7, 1, 'const x = 2');
expect(result.correct).toBe(true);
const updateCall = updateModule.mock.calls[0][0];
expect(updateCall.data.content.progress.debugPassed).toBe(true);
});
});
describe('submitFeynmanExplanation()', () => {
it('should parse the feedback and store validation status', async () => {
const content = buildStoredContent();
content.progress.debugPassed = true;
content.progress.exercises = Object.fromEntries(
Object.keys(content.progress.exercises).map((k) => [
k,
{ attempts: 1, passed: true, hintLevel: 0 },
]),
);
prisma.sessionModule.findUnique.mockResolvedValueOnce({ id: 1, content });
chat.mockResolvedValueOnce(
JSON.stringify({ strengths: ['clair'], gaps: [], validated: true }),
);
const result = await agent.submitFeynmanExplanation(
1,
7,
1,
'explication',
);
expect(result).toEqual({
strengths: ['clair'],
gaps: [],
validated: true,
});
const updateCall = updateModule.mock.calls[0][0];
expect(updateCall.data.content.progress.currentAwaiting).toBeNull();
expect(updateCall.data.content.progress.feynman).toEqual({
submitted: true,
validated: true,
});
});
});
describe('completeModule()', () => {
const startEvaluation = jest.fn();
it('should report missing requirements when nothing is done yet', async () => {
const content = buildStoredContent();
prisma.sessionModule.findUnique.mockResolvedValueOnce({ id: 1, content });
const result = await agent.completeModule(1, 7, 1, startEvaluation);
expect(result).toEqual({
completed: false,
missing: [
'0/4 exercices reussis (minimum requis: 4/6)',
"l'exercice de debogage n'est pas encore reussi",
"le test Feynman n'est pas encore valide",
],
});
expect(prisma.sessionModule.update).not.toHaveBeenCalled();
expect(startEvaluation).not.toHaveBeenCalled();
});
it('should unlock and generate the next module when all requirements are met and a next module exists', async () => {
const content = buildStoredContent();
content.progress.debugPassed = true;
content.progress.feynman = { submitted: true, validated: true };
content.progress.exercises = Object.fromEntries(
Object.keys(content.progress.exercises).map((k, i) => [
k,
{ attempts: 1, passed: i < 4, hintLevel: 0 },
]),
);
prisma.sessionModule.findUnique
.mockResolvedValueOnce({ id: 1, content })
.mockResolvedValueOnce(null);
prisma.sessionCurriculum.findUniqueOrThrow
.mockResolvedValueOnce({
modules: [
{ index: 1, title: 'Module 1', concept: 'c1', status: 'unlocked' },
{ index: 2, title: 'Module 2', concept: 'c2', status: 'locked' },
],
})
.mockResolvedValueOnce({
modules: [
{ index: 1, title: 'Module 1', concept: 'c1' },
{ index: 2, title: 'Module 2', concept: 'c2' },
],
});
chat.mockResolvedValueOnce(JSON.stringify(buildValidAuthoredJson()));
const result = await agent.completeModule(1, 7, 1, startEvaluation);
expect(result).toEqual({
completed: true,
nextModuleIndex: 2,
evaluationStarted: false,
});
expect(prisma.sessionCurriculum.update).toHaveBeenCalledWith({
where: { sessionId: 1 },
data: {
modules: [
{ index: 1, title: 'Module 1', concept: 'c1', status: 'unlocked' },
{ index: 2, title: 'Module 2', concept: 'c2', status: 'unlocked' },
],
},
});
expect(startEvaluation).not.toHaveBeenCalled();
});
it('should start the final evaluation when this was the last module', async () => {
const content = buildStoredContent();
content.progress.debugPassed = true;
content.progress.feynman = { submitted: true, validated: true };
content.progress.exercises = Object.fromEntries(
Object.keys(content.progress.exercises).map((k, i) => [
k,
{ attempts: 1, passed: i < 4, hintLevel: 0 },
]),
);
prisma.sessionModule.findUnique.mockResolvedValueOnce({ id: 1, content });
prisma.sessionCurriculum.findUniqueOrThrow.mockResolvedValueOnce({
modules: [
{ index: 1, title: 'Module 1', concept: 'c1', status: 'unlocked' },
],
});
const result = await agent.completeModule(1, 7, 1, startEvaluation);
expect(result).toEqual({
completed: true,
nextModuleIndex: null,
evaluationStarted: true,
});
expect(prisma.session.update).toHaveBeenCalledWith({
where: { id: 1 },
data: { status: 'evaluating' },
});
expect(startEvaluation).toHaveBeenCalledWith(1, 7);
});
});
describe('getAllExercisePrompts()', () => {
it('should collect every exercise prompt and debug instruction across all modules', async () => {
const content = buildStoredContent();
prisma.sessionModule.findMany.mockResolvedValueOnce([{ content }]);
const prompts = await agent.getAllExercisePrompts(1);
expect(prompts).toContain('Enonce exercice 1');
expect(prompts).toContain('Trouve et corrige le bug.');
expect(prompts).toHaveLength(7);
});
});
});
+791
View File
@@ -0,0 +1,791 @@
import { ConflictException, Injectable, Logger } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import { OpenRouterService } from '../../llm/openrouter.service';
import { buildModulePrompt } from '../prompts/module.prompt';
import { ResearchCorpus } from './research.agent';
export type ExerciseLevel = 'easy' | 'medium' | 'hard';
export interface AuthoredExercise {
id: string;
level: ExerciseLevel;
context: string;
prompt: string;
hints: string[];
correctAnswerInternal: string;
}
export interface AuthoredDebugExercise {
codeOrReasoningWithBug: string;
language: string;
instruction: string;
correctionInternal: string;
}
export interface AuthoredSynthesis {
recap: string;
metacognitionQuestions: string[];
feynmanPrompt: string;
}
export interface AuthoredTheory {
coreIdea: string;
analogy: string;
formalDefinition: string;
workedExample: string;
counterExample: string;
}
export interface AuthoredWeDo {
problem: string;
guidingQuestions: string[];
}
/**
* Suivi de progression d'un module, stocke a l'interieur de session_module.content (pas de
* colonne dediee) : "currentAwaiting" dit au pipeline voix/texte unique (routeIncomingMessage,
* sessions.service.ts) a quoi un message libre de l'utilisateur doit etre interprete comme une
* reponse, sans qu'il ait besoin de "dire une formule magique" - decision prise cote code, jamais
* par le LLM.
*/
export interface ModuleProgress {
currentAwaiting:
| { type: 'exercise'; exerciseId: string }
| { type: 'debug' }
| { type: 'feynman' }
| null;
exercises: Record<
string,
{ attempts: number; passed: boolean; hintLevel: number }
>;
debugPassed: boolean;
feynman: { submitted: boolean; validated: boolean } | null;
}
export interface StoredModuleContent {
hook: string;
theory: AuthoredTheory;
weDo: AuthoredWeDo;
exercises: AuthoredExercise[];
debugExercise: AuthoredDebugExercise;
synthesis: AuthoredSynthesis;
progress: ModuleProgress;
}
/** Vue publique d'un module : jamais les champs "*Internal" (reponses/corrections), jamais les
* indices au-dela du niveau deja debloque pour chaque exercice. */
export interface PublicModuleContent {
title: string;
hook: string;
theory: AuthoredTheory;
weDo: AuthoredWeDo;
exercises: {
id: string;
level: ExerciseLevel;
context: string;
prompt: string;
revealedHints: string[];
passed: boolean;
}[];
debugExercise: {
instruction: string;
codeOrReasoningWithBug: string;
language: string;
};
synthesis: AuthoredSynthesis;
progress: ModuleProgress;
}
export interface JudgeResult {
correct: boolean;
feedback: string;
}
export interface FeynmanFeedback {
strengths: string[];
gaps: string[];
validated: boolean;
}
export type CompleteModuleResult =
| {
completed: true;
nextModuleIndex: number | null;
evaluationStarted: boolean;
}
| { completed: false; missing: string[] };
interface RawModuleContent {
hook?: unknown;
theory?: {
coreIdea?: unknown;
analogy?: unknown;
formalDefinition?: unknown;
workedExample?: unknown;
counterExample?: unknown;
};
weDo?: { problem?: unknown; guidingQuestions?: unknown };
exercises?: unknown;
debugExercise?: {
codeOrReasoningWithBug?: unknown;
language?: unknown;
instruction?: unknown;
correctionInternal?: unknown;
};
synthesis?: {
recap?: unknown;
metacognitionQuestions?: unknown;
feynmanPrompt?: unknown;
};
}
const MIN_HOOK_WORDS = 150;
const MIN_THEORY_WORDS = 300;
const MIN_SYNTHESIS_WORDS = 100;
const REQUIRED_HINTS_PER_EXERCISE = 5;
const REQUIRED_EXERCISES_PASSED = 4;
const MAX_VALIDATION_RETRIES = 1;
function countWords(text: string): number {
return text
.trim()
.split(/\s+/)
.filter((w) => w.length > 0).length;
}
/**
* Agent 6 du pipeline (docs/Max_System_Prompt.md + docs/Max Refonte Coach Freelance.md) :
* redige un module a la fois (6 sections obligatoires), puis gere les sous-interactions
* (exercice, indice, debogage, Feynman) toutes routees depuis le meme pipeline voix/texte
* unique via "currentAwaiting" - jamais de LLM qui decide quoi afficher.
*/
@Injectable()
export class ModuleAgent {
private readonly logger = new Logger(ModuleAgent.name);
constructor(
private readonly prisma: PrismaService,
private readonly llm: OpenRouterService,
) {}
async generateModule(
sessionId: number,
userId: number,
moduleIndex: number,
): Promise<PublicModuleContent> {
const existing = await this.prisma.sessionModule.findUnique({
where: { sessionId_moduleIndex: { sessionId, moduleIndex } },
});
if (existing) {
return this.toPublicContent(
existing.title,
existing.content as unknown as StoredModuleContent,
);
}
const curriculum = await this.prisma.sessionCurriculum.findUniqueOrThrow({
where: { sessionId },
});
const modules = curriculum.modules as unknown as {
index: number;
title: string;
concept: string;
}[];
const target = modules.find((m) => m.index === moduleIndex);
if (!target) {
throw new ConflictException(
`Module ${moduleIndex} introuvable dans le curriculum de cette session.`,
);
}
const objective = await this.prisma.sessionObjective.findUniqueOrThrow({
where: { sessionId },
});
const level = await this.prisma.sessionLevelAssessment.findUniqueOrThrow({
where: { sessionId },
});
const research = await this.prisma.sessionResearch.findUniqueOrThrow({
where: { sessionId },
});
const previousModules = await this.prisma.sessionModule.findMany({
where: { sessionId, moduleIndex: { lt: moduleIndex } },
orderBy: { moduleIndex: 'asc' },
});
const prompt = buildModulePrompt({
index: moduleIndex,
title: target.title,
concept: target.concept,
objectiveSummary: `${objective.subject} pour ${objective.professionalGoal}, en ${objective.duration}`,
levelSummary: level.overallLevel,
corpusSummary: this.summarizeCorpus(
research.corpus as unknown as ResearchCorpus,
),
previousModulesSummary:
previousModules.map((m) => m.title).join(', ') || 'aucun',
});
let authored = await this.requestAndValidate(userId, prompt);
for (
let attempt = 0;
!authored && attempt < MAX_VALIDATION_RETRIES;
attempt++
) {
this.logger.warn(
`Module ${moduleIndex} non conforme (mots minimum / structure), nouvelle tentative (${attempt + 1})`,
);
authored = await this.requestAndValidate(userId, prompt);
}
if (!authored) {
throw new Error(
`L'Agent 6 (Redacteur) n'a pas produit de module ${moduleIndex} conforme apres relance.`,
);
}
const progress: ModuleProgress = {
currentAwaiting: {
type: 'exercise',
exerciseId: authored.exercises[0].id,
},
exercises: Object.fromEntries(
authored.exercises.map((e) => [
e.id,
{ attempts: 0, passed: false, hintLevel: 0 },
]),
),
debugPassed: false,
feynman: null,
};
const content: StoredModuleContent = { ...authored, progress };
await this.prisma.sessionModule.create({
data: {
sessionId,
moduleIndex,
title: target.title,
content: content as unknown as Prisma.InputJsonValue,
status: 'generated',
},
});
return this.toPublicContent(target.title, content);
}
async submitExerciseAnswer(
sessionId: number,
userId: number,
moduleIndex: number,
exerciseId: string,
answer: string,
): Promise<JudgeResult> {
const { record, content } = await this.loadModule(sessionId, moduleIndex);
const exercise = content.exercises.find((e) => e.id === exerciseId);
const progressEntry = Reflect.get(
content.progress.exercises,
exerciseId,
) as ModuleProgress['exercises'][string] | undefined;
if (!exercise || !progressEntry) {
throw new ConflictException(`Exercice ${exerciseId} introuvable.`);
}
const result = await this.judge(
userId,
`Exercice (niveau ${exercise.level}) : ${exercise.prompt}`,
exercise.correctAnswerInternal,
answer,
);
progressEntry.attempts += 1;
progressEntry.passed = progressEntry.passed || result.correct;
content.progress.currentAwaiting = this.nextAwaiting(content);
await this.saveContent(record.id, content);
return result;
}
/** Pur lookup dans les indices deja rediges par l'Agent 6 - aucun appel LLM necessaire. */
async requestHint(
sessionId: number,
moduleIndex: number,
exerciseId: string,
): Promise<{ level: number; hint: string | null }> {
const { record, content } = await this.loadModule(sessionId, moduleIndex);
const exercise = content.exercises.find((e) => e.id === exerciseId);
const progressEntry = Reflect.get(
content.progress.exercises,
exerciseId,
) as ModuleProgress['exercises'][string] | undefined;
if (!exercise || !progressEntry) {
throw new ConflictException(`Exercice ${exerciseId} introuvable.`);
}
if (progressEntry.hintLevel >= REQUIRED_HINTS_PER_EXERCISE) {
return { level: progressEntry.hintLevel, hint: null };
}
progressEntry.hintLevel += 1;
await this.saveContent(record.id, content);
return {
level: progressEntry.hintLevel,
hint: exercise.hints[progressEntry.hintLevel - 1] ?? null,
};
}
async submitDebugCorrection(
sessionId: number,
userId: number,
moduleIndex: number,
correction: string,
): Promise<JudgeResult> {
const { record, content } = await this.loadModule(sessionId, moduleIndex);
const result = await this.judge(
userId,
`Correction de l'erreur intentionnelle : ${content.debugExercise.instruction}`,
content.debugExercise.correctionInternal,
correction,
);
content.progress.debugPassed =
content.progress.debugPassed || result.correct;
content.progress.currentAwaiting = this.nextAwaiting(content);
await this.saveContent(record.id, content);
return result;
}
async submitFeynmanExplanation(
sessionId: number,
userId: number,
moduleIndex: number,
explanation: string,
): Promise<FeynmanFeedback> {
const { record, content } = await this.loadModule(sessionId, moduleIndex);
const raw = await this.llm.chat(
userId,
[
{
role: 'system',
content:
'Tu evalues une explication "test de Feynman" (expliquer un concept comme a quelqu\'un ' +
`qui n'y connait rien). Concept : ${content.theory.coreIdea}. ` +
'Reponds UNIQUEMENT avec ce JSON strict : ' +
'{"strengths": ["..."], "gaps": ["..."], "validated": true | false}. ' +
'"validated" est true seulement si l\'explication est correcte et ne presuppose aucun jargon non explique.',
},
{ role: 'user', content: explanation },
],
{ jsonResponse: true },
);
const feedback = this.parseFeynmanFeedback(raw);
content.progress.feynman = {
submitted: true,
validated: feedback.validated,
};
content.progress.currentAwaiting = this.nextAwaiting(content);
await this.saveContent(record.id, content);
return feedback;
}
/**
* Garde-fou de validation (docs/Max Refonte Coach Freelance.md) : >=4/6 exercices reussis ET
* debogage reussi ET Feynman complete (et valide). Calcule integralement cote code a partir de
* "progress" - jamais une decision du LLM. Si valide : deverrouille/genere le module suivant
* (meme principe d'enchainement synchrone que confirmObjective/confirmLevel), ou demarre
* l'Agent 7 si c'etait le dernier module.
*/
async completeModule(
sessionId: number,
userId: number,
moduleIndex: number,
startEvaluation: (sessionId: number, userId: number) => Promise<void>,
): Promise<CompleteModuleResult> {
const { record, content } = await this.loadModule(sessionId, moduleIndex);
const missing: string[] = [];
const passedCount = Object.values(content.progress.exercises).filter(
(e) => e.passed,
).length;
if (passedCount < REQUIRED_EXERCISES_PASSED) {
missing.push(
`${passedCount}/${REQUIRED_EXERCISES_PASSED} exercices reussis (minimum requis: ${REQUIRED_EXERCISES_PASSED}/6)`,
);
}
if (!content.progress.debugPassed) {
missing.push("l'exercice de debogage n'est pas encore reussi");
}
if (!content.progress.feynman?.validated) {
missing.push("le test Feynman n'est pas encore valide");
}
if (missing.length > 0) {
return { completed: false, missing };
}
await this.prisma.sessionModule.update({
where: { id: record.id },
data: { status: 'completed', completedAt: new Date() },
});
const curriculum = await this.prisma.sessionCurriculum.findUniqueOrThrow({
where: { sessionId },
});
const modules = curriculum.modules as unknown as {
index: number;
status: string;
}[];
const nextModule = modules.find((m) => m.index === moduleIndex + 1);
if (nextModule) {
const updatedModules = modules.map((m) =>
m.index === nextModule.index ? { ...m, status: 'unlocked' } : m,
);
await this.prisma.sessionCurriculum.update({
where: { sessionId },
data: { modules: updatedModules },
});
await this.generateModule(sessionId, userId, nextModule.index);
return {
completed: true,
nextModuleIndex: nextModule.index,
evaluationStarted: false,
};
}
await this.prisma.session.update({
where: { id: sessionId },
data: { status: 'evaluating' },
});
await startEvaluation(sessionId, userId);
return { completed: true, nextModuleIndex: null, evaluationStarted: true };
}
/** Expose, pour l'Agent 7, tous les enonces d'exercices deja utilises dans les modules - pour
* garantir que le cas de mission final n'en reprend aucun (docs/Max Refonte Coach
* Freelance.md, "jamais un exercice deja vu pendant les modules"). */
async getAllExercisePrompts(sessionId: number): Promise<string[]> {
const modules = await this.prisma.sessionModule.findMany({
where: { sessionId },
});
const prompts: string[] = [];
for (const m of modules) {
const content = m.content as unknown as StoredModuleContent;
prompts.push(...content.exercises.map((e) => e.prompt));
prompts.push(content.debugExercise.instruction);
}
return prompts;
}
private nextAwaiting(
content: StoredModuleContent,
): ModuleProgress['currentAwaiting'] {
const nextUnpassedExercise = content.exercises.find(
(e) =>
!(
Reflect.get(content.progress.exercises, e.id) as
ModuleProgress['exercises'][string] | undefined
)?.passed,
);
if (nextUnpassedExercise) {
return { type: 'exercise', exerciseId: nextUnpassedExercise.id };
}
if (!content.progress.debugPassed) return { type: 'debug' };
if (!content.progress.feynman?.validated) return { type: 'feynman' };
return null;
}
private async judge(
userId: number,
questionContext: string,
referenceAnswer: string,
userAnswer: string,
): Promise<JudgeResult> {
const raw = await this.llm.chat(
userId,
[
{
role: 'system',
content:
"Tu juges si la reponse de l'utilisateur est correcte par rapport a la reponse de " +
`reference. Contexte : ${questionContext}. Reponse de reference : ${referenceAnswer}. ` +
'Reponds UNIQUEMENT avec ce JSON strict : {"correct": true | false, "feedback": "..."}. ' +
'"feedback" precise TOUJOURS ce qui est juste ou faux et pourquoi - jamais seulement ' +
'"Bravo !" ou "Non."',
},
{ role: 'user', content: userAnswer },
],
{ jsonResponse: true },
);
return this.parseJudgeResult(raw);
}
private parseJudgeResult(raw: string): JudgeResult {
try {
const parsed = JSON.parse(raw) as {
correct?: unknown;
feedback?: unknown;
};
return {
correct: parsed.correct === true,
feedback:
typeof parsed.feedback === 'string'
? parsed.feedback
: 'Reponse non evaluable, reessaie avec plus de details.',
};
} catch {
this.logger.warn(
`Jugement d'exercice non-JSON, rejete par prudence: ${raw}`,
);
return {
correct: false,
feedback: 'Reponse non evaluable, reessaie avec plus de details.',
};
}
}
private parseFeynmanFeedback(raw: string): FeynmanFeedback {
try {
const parsed = JSON.parse(raw) as {
strengths?: unknown;
gaps?: unknown;
validated?: unknown;
};
return {
strengths: Array.isArray(parsed.strengths)
? parsed.strengths.map(String)
: [],
gaps: Array.isArray(parsed.gaps) ? parsed.gaps.map(String) : [],
validated: parsed.validated === true,
};
} catch {
this.logger.warn(
`Evaluation Feynman non-JSON, rejetee par prudence: ${raw}`,
);
return {
strengths: [],
gaps: ['Explication non evaluable.'],
validated: false,
};
}
}
private async requestAndValidate(
userId: number,
prompt: string,
): Promise<Omit<StoredModuleContent, 'progress'> | null> {
const raw = await this.llm.chat(
userId,
[{ role: 'system', content: prompt }],
{ jsonResponse: true },
);
return this.parseAndValidate(raw);
}
private parseAndValidate(
raw: string,
): Omit<StoredModuleContent, 'progress'> | null {
let data: RawModuleContent;
try {
data = JSON.parse(raw) as RawModuleContent;
} catch {
this.logger.warn(`Module non-JSON, rejete: ${raw}`);
return null;
}
if (
typeof data.hook !== 'string' ||
countWords(data.hook) < MIN_HOOK_WORDS
) {
return null;
}
const theory = data.theory;
if (
!theory ||
typeof theory.coreIdea !== 'string' ||
typeof theory.analogy !== 'string' ||
typeof theory.formalDefinition !== 'string' ||
typeof theory.workedExample !== 'string' ||
typeof theory.counterExample !== 'string'
) {
return null;
}
const theoryWordCount = [
theory.coreIdea,
theory.analogy,
theory.formalDefinition,
theory.workedExample,
theory.counterExample,
].reduce((sum, t) => sum + countWords(t), 0);
if (theoryWordCount < MIN_THEORY_WORDS) return null;
if (
!data.weDo ||
typeof data.weDo.problem !== 'string' ||
!Array.isArray(data.weDo.guidingQuestions) ||
data.weDo.guidingQuestions.length < 3
) {
return null;
}
const exercises = this.parseExercises(data.exercises);
if (!exercises) return null;
const debug = data.debugExercise;
if (
!debug ||
typeof debug.codeOrReasoningWithBug !== 'string' ||
typeof debug.language !== 'string' ||
typeof debug.instruction !== 'string' ||
typeof debug.correctionInternal !== 'string'
) {
return null;
}
const synthesis = data.synthesis;
if (
!synthesis ||
typeof synthesis.recap !== 'string' ||
!Array.isArray(synthesis.metacognitionQuestions) ||
synthesis.metacognitionQuestions.length < 3 ||
typeof synthesis.feynmanPrompt !== 'string'
) {
return null;
}
const metacognitionWordCount = (
synthesis.metacognitionQuestions as unknown[]
).reduce<number>((sum, q) => sum + countWords(String(q)), 0);
const synthesisWordCount =
countWords(synthesis.recap) +
metacognitionWordCount +
countWords(synthesis.feynmanPrompt);
if (synthesisWordCount < MIN_SYNTHESIS_WORDS) return null;
return {
hook: data.hook,
theory: theory as AuthoredTheory,
weDo: {
problem: data.weDo.problem,
guidingQuestions: data.weDo.guidingQuestions.map(String),
},
exercises,
debugExercise: {
codeOrReasoningWithBug: debug.codeOrReasoningWithBug,
language: debug.language,
instruction: debug.instruction,
correctionInternal: debug.correctionInternal,
},
synthesis: {
recap: synthesis.recap,
metacognitionQuestions: synthesis.metacognitionQuestions.map(String),
feynmanPrompt: synthesis.feynmanPrompt,
},
};
}
private parseExercises(raw: unknown): AuthoredExercise[] | null {
if (!Array.isArray(raw) || raw.length !== 6) return null;
const exercises: AuthoredExercise[] = [];
let easy = 0;
let medium = 0;
let hard = 0;
let index = 0;
for (const rawItem of raw) {
index += 1;
const item = rawItem as {
level?: unknown;
context?: unknown;
prompt?: unknown;
hints?: unknown;
correctAnswerInternal?: unknown;
};
if (
!['easy', 'medium', 'hard'].includes(String(item.level)) ||
typeof item.context !== 'string' ||
typeof item.prompt !== 'string' ||
typeof item.correctAnswerInternal !== 'string' ||
!Array.isArray(item.hints) ||
item.hints.length !== REQUIRED_HINTS_PER_EXERCISE
) {
return null;
}
if (item.level === 'easy') easy += 1;
else if (item.level === 'medium') medium += 1;
else hard += 1;
exercises.push({
id: `ex-${index}`,
level: item.level as ExerciseLevel,
context: item.context,
prompt: item.prompt,
hints: item.hints.map(String),
correctAnswerInternal: item.correctAnswerInternal,
});
}
if (easy !== 2 || medium !== 2 || hard !== 2) return null;
return exercises;
}
private summarizeCorpus(corpus: ResearchCorpus): string {
return corpus.subtopics
.map(
(s) =>
`${s.subtopic}: ${s.summary} | points cles: ${s.keyPoints.join('; ')} | erreurs frequentes: ${s.commonMistakes.join('; ')}`,
)
.join(' || ');
}
private async loadModule(
sessionId: number,
moduleIndex: number,
): Promise<{
record: { id: number };
content: StoredModuleContent;
}> {
const record = await this.prisma.sessionModule.findUnique({
where: { sessionId_moduleIndex: { sessionId, moduleIndex } },
});
if (!record) {
throw new ConflictException(
`Module ${moduleIndex} introuvable pour cette session.`,
);
}
return {
record,
content: record.content as unknown as StoredModuleContent,
};
}
private async saveContent(
recordId: number,
content: StoredModuleContent,
): Promise<void> {
await this.prisma.sessionModule.update({
where: { id: recordId },
data: { content: content as unknown as Prisma.InputJsonValue },
});
}
private toPublicContent(
title: string,
content: StoredModuleContent,
): PublicModuleContent {
return {
title,
hook: content.hook,
theory: content.theory,
weDo: content.weDo,
exercises: content.exercises.map((e) => {
const progress = Reflect.get(content.progress.exercises, e.id) as
ModuleProgress['exercises'][string] | undefined;
return {
id: e.id,
level: e.level,
context: e.context,
prompt: e.prompt,
revealedHints: e.hints.slice(0, progress?.hintLevel ?? 0),
passed: progress?.passed ?? false,
};
}),
debugExercise: {
instruction: content.debugExercise.instruction,
codeOrReasoningWithBug: content.debugExercise.codeOrReasoningWithBug,
language: content.debugExercise.language,
},
synthesis: content.synthesis,
progress: content.progress,
};
}
}
@@ -15,9 +15,16 @@ describe('parseDurationHours()', () => {
expect(parseDurationHours('1,5 jours')).toBe(36);
});
it('should accept a spelled-out small number as a fallback (LLM may ignore the digit rule)', () => {
expect(parseDurationHours('une semaine')).toBe(168);
expect(parseDurationHours('un mois')).toBe(720);
expect(parseDurationHours('deux jours')).toBe(48);
});
it('should return null for an unrecognized format', () => {
expect(parseDurationHours('bientot')).toBeNull();
expect(parseDurationHours('')).toBeNull();
expect(parseDurationHours('un bon moment')).toBeNull();
});
});
@@ -26,22 +26,61 @@ const DURATION_UNIT_HOURS = new Map<string, number>([
['mois', 30 * 24],
]);
// Le LLM ecrit parfois le nombre en toutes lettres ("une semaine") malgre la consigne du prompt
// de toujours utiliser un chiffre (constate en test reel : rejet a tort d'un "1 semaine" valide
// reformule ainsi par le modele) : accepte au moins les petits nombres les plus frequents en
// defense en profondeur, sans remplacer la consigne cote prompt qui reste la premiere ligne de
// defense.
const SPELLED_OUT_NUMBERS = new Map<string, number>([
['un', 1],
['une', 1],
['deux', 2],
['trois', 3],
['quatre', 4],
['cinq', 5],
['six', 6],
['sept', 7],
['huit', 8],
['neuf', 9],
['dix', 10],
['onze', 11],
['douze', 12],
]);
/**
* 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.
* Parse une duree en langage libre ("2 semaines", "10h", "1 mois", "une semaine") 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();
if (!normalized) return null;
const spaceIndex = normalized.indexOf(' ');
let amountText: string;
let unit: string;
if (spaceIndex === -1) {
// Pas d'espace : nombre et unite colles ("10h").
const separatorIndex = normalized.search(/[a-zéû]/);
if (separatorIndex <= 0) return null;
amountText = normalized.slice(0, separatorIndex);
unit = normalized.slice(separatorIndex);
} else {
// Un seul espace separe le nombre de l'unite ("1 semaine") : tout ce qui suit le premier
// espace fait partie de l'unite, pour rejeter proprement une phrase ("un bon moment") plutot
// que d'essayer de la faire correspondre a une unite connue.
amountText = normalized.slice(0, spaceIndex).trim();
unit = normalized.slice(spaceIndex + 1).trim();
}
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;
if (hoursPerUnit === undefined) return null;
const numericAmount = Number.parseFloat(amountText.replace(',', '.'));
const amount = Number.isNaN(numericAmount)
? SPELLED_OUT_NUMBERS.get(amountText)
: numericAmount;
if (amount === undefined || Number.isNaN(amount)) return null;
return amount * hoursPerUnit;
}
@@ -89,7 +89,6 @@ describe('ObjectiveAgent', () => {
JSON.stringify({
clarity: 0.9,
specificity: 0.3,
feasibility: 0.9,
followUpQuestion: 'Peux-tu preciser le sujet ?',
}),
);
@@ -112,7 +111,7 @@ describe('ObjectiveAgent', () => {
}),
)
.mockResolvedValueOnce(
JSON.stringify({ clarity: 0.9, specificity: 0.9, feasibility: 0.9 }),
JSON.stringify({ clarity: 0.9, specificity: 0.9 }),
);
const result = await agent.converse(1, 7, 'message');
@@ -140,12 +139,12 @@ describe('ObjectiveAgent', () => {
}),
)
.mockResolvedValueOnce(
JSON.stringify({ clarity: 0.9, specificity: 0.9, feasibility: 0.9 }),
JSON.stringify({ clarity: 0.9, specificity: 0.9 }),
);
await agent.converse(1, 7, 'message');
chat.mockResolvedValueOnce(
JSON.stringify({ clarity: 0.9, specificity: 0.9, feasibility: 0.9 }),
JSON.stringify({ clarity: 0.9, specificity: 0.9 }),
);
prisma.sessionObjective.create.mockResolvedValueOnce({
id: 1,
@@ -38,7 +38,6 @@ interface AgentJsonReply {
interface CoherenceScore {
clarity: number;
specificity: number;
feasibility: number;
followUpQuestion?: string;
}
@@ -48,15 +47,18 @@ const SYSTEM_PROMPT = buildAgentPrompt(
`${OBJECTIVE_PROMPT}\n\n${OBJECTIVE_JSON_CONTRACT}`,
);
// Note : une dimension "feasibility" (but atteignable dans la duree indiquee) a existe ici mais a
// ete retiree (constate en test reel : rejetait a tort "trigonometrie en 2 semaines" par jugement
// subjectif du LLM, alors que la duree respecte deja la regle stricte 1h-12 semaines de
// objective-guardrails.ts). La plausibilite de la duree est une regle codee, pas un jugement LLM.
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}`;
{"clarity": 0.0, "specificity": 0.0, "followUpQuestion": "..." | null}`;
/**
* Agent 1 du pipeline (voir CLAUDE.md section 1 / docs/Max Refonte Coach Freelance.md) :
@@ -210,7 +212,6 @@ export class ObjectiveAgent {
return {
clarity: 0,
specificity: 0,
feasibility: 0,
followUpQuestion: 'Peux-tu reformuler ton objectif plus precisement ?',
};
}
@@ -219,8 +220,7 @@ export class ObjectiveAgent {
private passesCoherence(score: CoherenceScore): boolean {
return (
score.clarity >= COHERENCE_THRESHOLD &&
score.specificity >= COHERENCE_THRESHOLD &&
score.feasibility >= COHERENCE_THRESHOLD
score.specificity >= COHERENCE_THRESHOLD
);
}
@@ -0,0 +1,140 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PrismaService } from '../../prisma/prisma.service';
import { OpenRouterService } from '../../llm/openrouter.service';
import { PlanAgent } from './plan.agent';
describe('PlanAgent', () => {
let agent: PlanAgent;
const chat = jest.fn();
const createCurriculum = jest.fn<
Promise<unknown>,
[{ data: { totalModules: number; totalDuration: string } }]
>();
const prisma = {
sessionCurriculum: { findUnique: jest.fn(), create: createCurriculum },
sessionObjective: { findUniqueOrThrow: jest.fn() },
sessionLevelAssessment: { findUniqueOrThrow: jest.fn() },
sessionResearch: { findUniqueOrThrow: jest.fn() },
};
const validCurriculum = {
modules: [
{
index: 1,
title: 'A',
concept: 'concept-a',
estimated_duration: '2h',
prerequisites: [],
status: 'unlocked',
},
{
index: 2,
title: 'B',
concept: 'concept-b',
estimated_duration: '3h',
prerequisites: ['A'],
status: 'locked',
},
{
index: 3,
title: 'C',
concept: 'concept-c',
estimated_duration: '2h',
prerequisites: ['B'],
status: 'locked',
},
],
total_duration: '1 semaine',
};
beforeEach(async () => {
jest.clearAllMocks();
prisma.sessionObjective.findUniqueOrThrow.mockResolvedValue({
subject: 'Facturation',
professionalGoal: 'Facturer sans erreur',
duration: '2 semaines',
});
prisma.sessionLevelAssessment.findUniqueOrThrow.mockResolvedValue({
masteredConcepts: ['Devis'],
gapConcepts: [],
unknownConcepts: ['TVA'],
overallLevel: 'beginner',
});
prisma.sessionResearch.findUniqueOrThrow.mockResolvedValue({
corpus: { subtopics: [{ subtopic: 'TVA', keyPoints: ['taux reduit'] }] },
});
const module: TestingModule = await Test.createTestingModule({
providers: [
PlanAgent,
{ provide: PrismaService, useValue: prisma },
{ provide: OpenRouterService, useValue: { chat } },
],
}).compile();
agent = module.get(PlanAgent);
});
describe('runForSession()', () => {
it('should do nothing when a curriculum already exists (idempotent)', async () => {
prisma.sessionCurriculum.findUnique.mockResolvedValueOnce({ id: 1 });
await agent.runForSession(1, 7);
expect(chat).not.toHaveBeenCalled();
expect(prisma.sessionCurriculum.create).not.toHaveBeenCalled();
});
it('should persist a valid curriculum (3-7 modules, only the first unlocked)', async () => {
prisma.sessionCurriculum.findUnique.mockResolvedValueOnce(null);
chat.mockResolvedValueOnce(JSON.stringify(validCurriculum));
await agent.runForSession(1, 7);
const createCall = createCurriculum.mock.calls[0][0];
expect(createCall.data.totalModules).toBe(3);
expect(createCall.data.totalDuration).toBe('1 semaine');
});
it('should retry once then throw when the module count is out of the 3-7 range', async () => {
prisma.sessionCurriculum.findUnique.mockResolvedValueOnce(null);
const tooFew = {
modules: [
{
index: 1,
title: 'A',
concept: 'a',
estimated_duration: '1h',
prerequisites: [],
status: 'unlocked',
},
],
total_duration: '1h',
};
chat.mockResolvedValueOnce(JSON.stringify(tooFew));
chat.mockResolvedValueOnce(JSON.stringify(tooFew));
await expect(agent.runForSession(1, 7)).rejects.toThrow();
expect(chat).toHaveBeenCalledTimes(2);
expect(prisma.sessionCurriculum.create).not.toHaveBeenCalled();
});
it('should reject a curriculum where a module other than the first is unlocked', async () => {
prisma.sessionCurriculum.findUnique.mockResolvedValueOnce(null);
const badLocking = {
modules: validCurriculum.modules.map((m) => ({
...m,
status: 'unlocked',
})),
total_duration: '1 semaine',
};
chat.mockResolvedValueOnce(JSON.stringify(badLocking));
chat.mockResolvedValueOnce(JSON.stringify(validCurriculum));
await agent.runForSession(1, 7);
expect(chat).toHaveBeenCalledTimes(2);
expect(prisma.sessionCurriculum.create).toHaveBeenCalled();
});
});
});
+214
View File
@@ -0,0 +1,214 @@
import { Injectable, Logger } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import { OpenRouterService } from '../../llm/openrouter.service';
import { PLAN_PROMPT } from '../prompts/plan.prompt';
import { LevelGap } from './level.agent';
import { ResearchCorpus } from './research.agent';
export type CurriculumModuleStatus = 'locked' | 'unlocked' | 'completed';
export interface CurriculumModule {
index: number;
title: string;
concept: string;
estimatedDuration: string;
prerequisites: string[];
status: CurriculumModuleStatus;
}
export interface CurriculumResult {
modules: CurriculumModule[];
totalDuration: string;
}
interface RawCurriculumModule {
index?: unknown;
title?: unknown;
concept?: unknown;
estimated_duration?: unknown;
prerequisites?: unknown;
status?: unknown;
}
interface RawCurriculum {
modules?: unknown;
total_duration?: unknown;
}
const MIN_MODULES = 3;
const MAX_MODULES = 7;
const MAX_VALIDATION_RETRIES = 1;
/**
* Agent 5 du pipeline (docs/Max_System_Prompt.md + docs/Max Refonte Coach Freelance.md) :
* Backward Design, un seul appel LLM (pas de ":online", raisonne sur l'objectif/le profil/le
* corpus deja stockes). Pas de personnalite Max (producteur de JSON pur, meme choix que
* MappingAgent/ResearchAgent). N'enchaine jamais automatiquement vers l'Agent 6 : le curriculum
* doit d'abord etre valide explicitement par l'utilisateur (CurriculumCard, voir
* sessions.service.ts confirmCurriculum()).
*/
@Injectable()
export class PlanAgent {
private readonly logger = new Logger(PlanAgent.name);
constructor(
private readonly prisma: PrismaService,
private readonly llm: OpenRouterService,
) {}
async runForSession(sessionId: number, userId: number): Promise<void> {
const existing = await this.prisma.sessionCurriculum.findUnique({
where: { sessionId },
});
if (existing) return;
const objective = await this.prisma.sessionObjective.findUniqueOrThrow({
where: { sessionId },
});
const level = await this.prisma.sessionLevelAssessment.findUniqueOrThrow({
where: { sessionId },
});
const research = await this.prisma.sessionResearch.findUniqueOrThrow({
where: { sessionId },
});
const objectiveSummary = `${objective.subject} pour ${objective.professionalGoal}, en ${objective.duration}`;
const profileSummary = this.summarizeProfile(
level.masteredConcepts as unknown as string[],
level.gapConcepts as unknown as LevelGap[],
level.unknownConcepts as unknown as string[],
level.overallLevel,
);
const corpusSummary = this.summarizeCorpus(
research.corpus as unknown as ResearchCorpus,
);
const prompt = PLAN_PROMPT.replace('[OBJECTIF_INJECTÉ]', objectiveSummary)
.replace('[PROFIL_INJECTÉ]', profileSummary)
.replace('[RÉSUMÉ_DU_CORPUS_INJECTÉ]', corpusSummary);
let result = await this.requestAndValidate(userId, prompt);
for (
let attempt = 0;
!result && attempt < MAX_VALIDATION_RETRIES;
attempt++
) {
this.logger.warn(
`Curriculum non conforme aux regles (3-7 modules, premier deverrouille), nouvelle tentative (${attempt + 1})`,
);
result = await this.requestAndValidate(userId, prompt);
}
if (!result) {
throw new Error(
"L'Agent 5 (Plan) n'a pas produit de curriculum conforme apres relance.",
);
}
await this.prisma.sessionCurriculum.create({
data: {
sessionId,
modules: result.modules as unknown as Prisma.InputJsonValue,
totalModules: result.modules.length,
totalDuration: result.totalDuration,
},
});
}
private async requestAndValidate(
userId: number,
prompt: string,
): Promise<CurriculumResult | null> {
const raw = await this.llm.chat(
userId,
[{ role: 'system', content: prompt }],
{ jsonResponse: true },
);
const parsed = this.parse(raw);
if (!parsed) return null;
if (!this.passesRules(parsed)) return null;
return parsed;
}
private parse(raw: string): CurriculumResult | null {
try {
const data = JSON.parse(raw) as RawCurriculum;
if (!Array.isArray(data.modules) || data.modules.length === 0) {
return null;
}
const modules: CurriculumModule[] = [];
for (const rawModule of data.modules as RawCurriculumModule[]) {
const module = this.parseModule(rawModule);
if (!module) return null;
modules.push(module);
}
if (typeof data.total_duration !== 'string') return null;
return { modules, totalDuration: data.total_duration };
} catch {
this.logger.warn(`Curriculum non-JSON, rejete: ${raw}`);
return null;
}
}
private parseModule(raw: RawCurriculumModule): CurriculumModule | null {
const index = Number(raw.index);
if (
!Number.isInteger(index) ||
typeof raw.title !== 'string' ||
typeof raw.concept !== 'string' ||
raw.concept.trim().length === 0 ||
typeof raw.estimated_duration !== 'string'
) {
return null;
}
if (!['locked', 'unlocked', 'completed'].includes(String(raw.status))) {
return null;
}
return {
index,
title: raw.title,
concept: raw.concept,
estimatedDuration: raw.estimated_duration,
prerequisites: Array.isArray(raw.prerequisites)
? raw.prerequisites.map(String)
: [],
status: raw.status as CurriculumModuleStatus,
};
}
/** Regles mesurables de docs/Max Refonte Coach Freelance.md : 3 a 7 modules, un seul deverrouille
* au depart (le premier). */
private passesRules(result: CurriculumResult): boolean {
if (
result.modules.length < MIN_MODULES ||
result.modules.length > MAX_MODULES
) {
return false;
}
const sorted = [...result.modules].sort((a, b) => a.index - b.index);
if (sorted[0]?.status !== 'unlocked') return false;
return sorted.slice(1).every((m) => m.status === 'locked');
}
private summarizeProfile(
mastered: string[],
gaps: LevelGap[],
unknown: string[],
overallLevel: string,
): string {
return [
`niveau global: ${overallLevel}`,
`maitrise: ${mastered.join(', ') || 'aucun'}`,
`lacunes: ${gaps.map((g) => `${g.concept} (${g.description})`).join('; ') || 'aucune'}`,
`inconnu: ${unknown.join(', ') || 'aucun'}`,
].join(' | ');
}
private summarizeCorpus(corpus: ResearchCorpus): string {
return corpus.subtopics
.map((s) => `${s.subtopic}: ${s.keyPoints.join('; ')}`)
.join(' || ');
}
}
@@ -0,0 +1,135 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PrismaService } from '../../prisma/prisma.service';
import { OpenRouterService } from '../../llm/openrouter.service';
import { ResearchAgent } from './research.agent';
describe('ResearchAgent', () => {
let agent: ResearchAgent;
const chat = jest.fn();
const findUniqueResearch = jest.fn();
const create = jest.fn<
Promise<unknown>,
[
{
data: {
sessionId: number;
sourcesCount: number;
corpus: { failedSubtopics: string[] };
};
},
]
>();
const findUniqueConceptMap = jest.fn();
const findUniqueLevel = jest.fn();
const prisma = {
sessionResearch: { findUnique: findUniqueResearch, create },
sessionConceptMap: { findUnique: findUniqueConceptMap },
sessionLevelAssessment: { findUnique: findUniqueLevel },
};
const conceptMap = {
concepts: [{ name: 'Facturation' }, { name: 'TVA' }],
};
const levelAssessment = {
masteredConcepts: ['Facturation'],
gapConcepts: [{ concept: 'TVA', description: 'confond les taux' }],
unknownConcepts: [],
};
function subtopicJson(subtopic: string): string {
return JSON.stringify({
subtopic,
summary: `Resume sur ${subtopic}`,
key_points: ['point 1'],
examples: ['exemple 1'],
common_mistakes: ['erreur 1'],
sources: [
{ title: 'Source A', url: 'https://a.example', level: 1 },
{ title: 'Source B', url: 'https://b.example', level: 4 },
],
});
}
beforeEach(async () => {
jest.clearAllMocks();
const module: TestingModule = await Test.createTestingModule({
providers: [
ResearchAgent,
{ provide: PrismaService, useValue: prisma },
{ provide: OpenRouterService, useValue: { chat } },
],
}).compile();
agent = module.get(ResearchAgent);
});
describe('runForSession()', () => {
it('should do nothing if research already exists for this session (idempotent)', async () => {
findUniqueResearch.mockResolvedValueOnce({ id: 1 });
await agent.runForSession(1, 7);
expect(chat).not.toHaveBeenCalled();
expect(create).not.toHaveBeenCalled();
});
it('should throw when the concept map or level assessment is missing', async () => {
findUniqueResearch.mockResolvedValueOnce(null);
findUniqueConceptMap.mockResolvedValueOnce(null);
findUniqueLevel.mockResolvedValueOnce(null);
await expect(agent.runForSession(1, 7)).rejects.toThrow(
/carte des concepts ou profil de niveau manquant/,
);
});
it('should research every concept in parallel with online search and persist the aggregated corpus', async () => {
findUniqueResearch.mockResolvedValueOnce(null);
findUniqueConceptMap.mockResolvedValueOnce(conceptMap);
findUniqueLevel.mockResolvedValueOnce(levelAssessment);
chat
.mockResolvedValueOnce(subtopicJson('Facturation'))
.mockResolvedValueOnce(subtopicJson('TVA'));
await agent.runForSession(1, 7);
expect(chat).toHaveBeenCalledTimes(2);
expect(chat).toHaveBeenCalledWith(
7,
expect.anything(),
expect.objectContaining({ online: true }),
);
expect(create).toHaveBeenCalledTimes(1);
expect(create.mock.calls[0][0].data.sessionId).toBe(1);
expect(create.mock.calls[0][0].data.sourcesCount).toBe(4);
});
it('should not fail the whole batch when one subtopic fails, and record it as failed', async () => {
findUniqueResearch.mockResolvedValueOnce(null);
findUniqueConceptMap.mockResolvedValueOnce(conceptMap);
findUniqueLevel.mockResolvedValueOnce(levelAssessment);
chat
.mockResolvedValueOnce(subtopicJson('Facturation'))
.mockRejectedValueOnce(new Error('OpenRouter indisponible'));
await agent.runForSession(1, 7);
expect(create).toHaveBeenCalledTimes(1);
expect(create.mock.calls[0][0].data.corpus.failedSubtopics).toEqual([
'TVA',
]);
});
it('should throw when every subtopic fails', async () => {
findUniqueResearch.mockResolvedValueOnce(null);
findUniqueConceptMap.mockResolvedValueOnce(conceptMap);
findUniqueLevel.mockResolvedValueOnce(levelAssessment);
chat.mockResolvedValue('reponse non-JSON');
await expect(agent.runForSession(1, 7)).rejects.toThrow(
/n'a reussi aucun sous-theme/,
);
expect(create).not.toHaveBeenCalled();
});
});
});
@@ -0,0 +1,209 @@
import { Injectable, Logger } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import { OpenRouterService } from '../../llm/openrouter.service';
import { buildResearchPrompt } from '../prompts/research.prompt';
import { Concept } from './mapping.agent';
import { LevelGap } from './level.agent';
export interface ResearchSource {
title: string;
url: string;
level: 1 | 2 | 3 | 4;
}
export interface SubtopicResearch {
subtopic: string;
summary: string;
keyPoints: string[];
examples: string[];
commonMistakes: string[];
sources: ResearchSource[];
}
export interface ResearchCorpus {
subtopics: SubtopicResearch[];
failedSubtopics: string[];
}
interface RawSubtopicResearch {
summary?: unknown;
key_points?: unknown;
examples?: unknown;
common_mistakes?: unknown;
sources?: unknown;
}
/**
* Agent 4 du pipeline (docs/Max_System_Prompt.md + docs/Max Refonte Coach Freelance.md) : un
* appel LLM en parallele par concept de la carte (Agent 2), recherche web reelle (":online"),
* calibre sur le profil de niveau (Agent 3). Comme MappingAgent, aucune personnalite Max ici :
* producteur de donnees pur, personne n'entend cet agent.
*/
@Injectable()
export class ResearchAgent {
private readonly logger = new Logger(ResearchAgent.name);
constructor(
private readonly prisma: PrismaService,
private readonly llm: OpenRouterService,
) {}
async runForSession(sessionId: number, userId: number): Promise<void> {
const existing = await this.prisma.sessionResearch.findUnique({
where: { sessionId },
});
if (existing) return;
const conceptMap = await this.prisma.sessionConceptMap.findUnique({
where: { sessionId },
});
const levelAssessment = await this.prisma.sessionLevelAssessment.findUnique(
{
where: { sessionId },
},
);
if (!conceptMap || !levelAssessment) {
throw new Error(
"Impossible de lancer l'Agent 4 : carte des concepts ou profil de niveau manquant pour cette session.",
);
}
const concepts = conceptMap.concepts as unknown as Concept[];
const mastered = new Set(
levelAssessment.masteredConcepts as unknown as string[],
);
const gaps = new Set(
(levelAssessment.gapConcepts as unknown as LevelGap[]).map(
(g) => g.concept,
),
);
// Chaque job attrape sa propre erreur et renvoie son nom de concept avec le resultat (ou null)
// plutot que de laisser Promise.allSettled rejeter : evite toute correlation par index entre
// deux tableaux separes pour retrouver quel concept a echoue.
const outcomes = await Promise.all(
concepts.map(async (concept) => {
try {
const research = await this.researchSubtopic(
userId,
concept.name,
this.calibrateLevel(concept.name, mastered, gaps),
);
return { name: concept.name, research };
} catch (error) {
this.logger.warn(
`Recherche du sous-theme "${concept.name}" echouee: ${String(error)}`,
);
return { name: concept.name, research: null };
}
}),
);
const subtopics: SubtopicResearch[] = [];
const failedSubtopics: string[] = [];
for (const outcome of outcomes) {
if (outcome.research) {
subtopics.push(outcome.research);
} else {
failedSubtopics.push(outcome.name);
}
}
if (subtopics.length === 0) {
throw new Error(
"L'Agent 4 (Recherche Approfondie) n'a reussi aucun sous-theme.",
);
}
const corpus: ResearchCorpus = { subtopics, failedSubtopics };
const sourcesCount = subtopics.reduce(
(sum, s) => sum + s.sources.length,
0,
);
await this.prisma.sessionResearch.create({
data: {
sessionId,
corpus: corpus as unknown as Prisma.InputJsonValue,
subtopicsCovered: subtopics.map((s) => s.subtopic),
sourcesCount,
completedAt: new Date(),
},
});
}
/** Calibrage par le niveau (docs/Max Refonte Coach Freelance.md) : mastered -> sources avancees
* pour aller au-dela, gap -> consolidation ciblee, unknown -> progression depuis les
* fondamentaux. */
private calibrateLevel(
name: string,
mastered: Set<string>,
gaps: Set<string>,
): 'beginner' | 'intermediate' | 'advanced' {
if (mastered.has(name)) return 'advanced';
if (gaps.has(name)) return 'intermediate';
return 'beginner';
}
private async researchSubtopic(
userId: number,
subtopic: string,
level: 'beginner' | 'intermediate' | 'advanced',
): Promise<SubtopicResearch | null> {
const raw = await this.llm.chat(
userId,
[{ role: 'system', content: buildResearchPrompt(subtopic, level) }],
{ jsonResponse: true, online: true },
);
return this.parse(raw, subtopic);
}
private parse(raw: string, subtopic: string): SubtopicResearch | null {
try {
const data = JSON.parse(raw) as RawSubtopicResearch;
if (typeof data.summary !== 'string') return null;
if (!Array.isArray(data.sources) || data.sources.length === 0)
return null;
const sources: ResearchSource[] = [];
for (const rawSource of data.sources as {
title?: unknown;
url?: unknown;
level?: unknown;
}[]) {
if (
typeof rawSource.title !== 'string' ||
typeof rawSource.url !== 'string'
) {
continue;
}
const level = Number(rawSource.level);
sources.push({
title: rawSource.title,
url: rawSource.url,
level: ([1, 2, 3, 4].includes(level) ? level : 3) as 1 | 2 | 3 | 4,
});
}
if (sources.length === 0) return null;
return {
subtopic,
summary: data.summary,
keyPoints: Array.isArray(data.key_points)
? data.key_points.map(String)
: [],
examples: Array.isArray(data.examples) ? data.examples.map(String) : [],
commonMistakes: Array.isArray(data.common_mistakes)
? data.common_mistakes.map(String)
: [],
sources,
};
} catch {
this.logger.warn(
`Recherche du sous-theme "${subtopic}" non-JSON, rejetee: ${raw}`,
);
return null;
}
}
}
@@ -0,0 +1,21 @@
import { ApiProperty } from '@nestjs/swagger';
export class CurriculumModuleDto {
@ApiProperty() index!: number;
@ApiProperty() title!: string;
@ApiProperty() concept!: string;
@ApiProperty() estimatedDuration!: string;
@ApiProperty({ type: [String] }) prerequisites!: string[];
@ApiProperty({ enum: ['locked', 'unlocked', 'completed'] })
status!: 'locked' | 'unlocked' | 'completed';
}
// Carte le DTO decrit par CurriculumCard (docs/Max_Composants_Frontend.md) : affiche avant que la
// redaction (Agent 6) ne commence, sur confirmation explicite ("Demarrer la formation" ->
// POST /sessions/:id/curriculum/confirm).
export class CurriculumResponseDto {
@ApiProperty({ type: [CurriculumModuleDto] }) modules!: CurriculumModuleDto[];
@ApiProperty() totalDuration!: string;
@ApiProperty({ required: false })
validatedAt?: Date;
}
@@ -0,0 +1,10 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsString, MaxLength, MinLength } from 'class-validator';
export class DebugCorrectionDto {
@ApiProperty({ example: 'La boucle doit commencer a 0, pas a 1.' })
@IsString()
@MinLength(1)
@MaxLength(4000)
correction!: string;
}
@@ -0,0 +1,14 @@
import { ApiProperty } from '@nestjs/swagger';
// Carte EvaluationResult de docs/Max_Composants_Frontend.md (EvaluationScoreCard). Les scores
// viennent directement de session_evaluation (interviewScore sur 5, practicalScore sur 4),
// recalcules cote code - jamais le "total"/"validated" auto-declare par le LLM.
export class EvaluationResultResponseDto {
@ApiProperty() validated!: boolean;
@ApiProperty() interviewScore!: number;
@ApiProperty({ type: [String] }) interviewFeedback!: string[];
@ApiProperty() practicalScore!: number;
@ApiProperty({ type: [String] }) practicalFeedback!: string[];
@ApiProperty({ type: [String] }) strengths!: string[];
@ApiProperty({ type: [String] }) remainingGaps!: string[];
}
@@ -0,0 +1,19 @@
import { ApiProperty } from '@nestjs/swagger';
// "stage" est le signal structure (code, jamais LLM) qui dit au frontend d'afficher
// InterviewSimCard ou MissionCaseCard (docs/Max_Composants_Frontend.md). "done" ne signale
// JAMAIS "cette etape est terminee" (la transition interview->mission reussie se fait de maniere
// transparente a l'interieur d'un seul appel, voir evaluation.agent.ts handleInterviewDone) : il
// signale que l'EVALUATION ENTIERE est terminee (echec a l'entretien, ou cas de mission juge) -
// a ce moment-la, va chercher le resultat complet via GET /sessions/:id/evaluation.
export class EvaluationTurnResponseDto {
@ApiProperty({ description: 'Question/propos de Max a dire a voix haute.' })
reply!: string;
@ApiProperty({
description:
"true si l'evaluation entiere est terminee (voir commentaire de classe) - jamais juste l'etape en cours.",
})
done!: boolean;
@ApiProperty({ enum: ['interview', 'mission'] })
stage!: 'interview' | 'mission';
}
@@ -0,0 +1,18 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsString, MaxLength, MinLength } from 'class-validator';
export class ExerciseAnswerDto {
@ApiProperty({ example: 'ex-1' })
@IsString()
@MinLength(1)
@MaxLength(50)
exerciseId!: string;
@ApiProperty({
example: 'Je ferais pivoter le vecteur avec une matrice de rotation.',
})
@IsString()
@MinLength(1)
@MaxLength(4000)
answer!: string;
}
@@ -0,0 +1,8 @@
import { ApiProperty } from '@nestjs/swagger';
// Carte FeynmanFeedback de docs/Max_Composants_Frontend.md (FeynmanCard).
export class FeynmanFeedbackResponseDto {
@ApiProperty({ type: [String] }) strengths!: string[];
@ApiProperty({ type: [String] }) gaps!: string[];
@ApiProperty() validated!: boolean;
}
@@ -0,0 +1,12 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsString, MaxLength, MinLength } from 'class-validator';
export class FeynmanSubmissionDto {
@ApiProperty({
example: "C'est comme faire tourner une photo autour d'un point fixe.",
})
@IsString()
@MinLength(1)
@MaxLength(4000)
explanation!: string;
}
@@ -0,0 +1,10 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsString, MaxLength, MinLength } from 'class-validator';
export class HintRequestDto {
@ApiProperty({ example: 'ex-1' })
@IsString()
@MinLength(1)
@MaxLength(50)
exerciseId!: string;
}
@@ -0,0 +1,11 @@
import { ApiProperty } from '@nestjs/swagger';
export class HintResponseDto {
@ApiProperty({ description: 'Niveau d-indice atteint (1 a 5).' })
level!: number;
@ApiProperty({
nullable: true,
description: 'null si les 5 niveaux ont deja ete demandes.',
})
hint!: string | null;
}
@@ -0,0 +1,8 @@
import { ApiProperty } from '@nestjs/swagger';
/** Reponse partagee par l'exercice, le debogage - feedback toujours substantiel (jamais "Bravo !"
* / "Non." seuls), jamais de reponse correcte revelee. */
export class JudgeResultResponseDto {
@ApiProperty() correct!: boolean;
@ApiProperty() feedback!: string;
}
@@ -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;
}
@@ -0,0 +1,20 @@
import { ApiProperty } from '@nestjs/swagger';
// "missing" est calcule integralement cote code (module.agent.ts, completeModule()) - jamais une
// decision du LLM - pour dire precisement au frontend quoi faire retravailler.
export class ModuleCompleteResponseDto {
@ApiProperty() completed!: boolean;
@ApiProperty({ type: [String], required: false }) missing?: string[];
@ApiProperty({
required: false,
description:
'Index du module suivant genere, si different de null et completed=true.',
})
nextModuleIndex?: number | null;
@ApiProperty({
required: false,
description:
"true si c'etait le dernier module : l'Agent 7 (evaluation) vient de demarrer.",
})
evaluationStarted?: boolean;
}
@@ -0,0 +1,64 @@
import { ApiProperty } from '@nestjs/swagger';
class ModuleTheoryDto {
@ApiProperty() coreIdea!: string;
@ApiProperty() analogy!: string;
@ApiProperty() formalDefinition!: string;
@ApiProperty() workedExample!: string;
@ApiProperty() counterExample!: string;
}
class ModuleWeDoDto {
@ApiProperty() problem!: string;
@ApiProperty({ type: [String] }) guidingQuestions!: string[];
}
export class PublicExerciseDto {
@ApiProperty() id!: string;
@ApiProperty({ enum: ['easy', 'medium', 'hard'] })
level!: 'easy' | 'medium' | 'hard';
@ApiProperty() context!: string;
@ApiProperty() prompt!: string;
@ApiProperty({
type: [String],
description: 'Indices deja debloques (0 a 5), jamais ceux au-dela.',
})
revealedHints!: string[];
@ApiProperty() passed!: boolean;
}
class PublicDebugExerciseDto {
@ApiProperty() instruction!: string;
@ApiProperty() codeOrReasoningWithBug!: string;
@ApiProperty() language!: string;
}
class ModuleSynthesisDto {
@ApiProperty() recap!: string;
@ApiProperty({ type: [String] }) metacognitionQuestions!: string[];
@ApiProperty() feynmanPrompt!: string;
}
class ModuleAwaitingDto {
@ApiProperty({ enum: ['exercise', 'debug', 'feynman'] })
type!: 'exercise' | 'debug' | 'feynman';
@ApiProperty({ required: false }) exerciseId?: string;
}
// "awaiting" est le signal structure (code, jamais LLM) qui dit au frontend - et au pipeline
// voix/texte unique (routeIncomingMessage) - ce qu'un prochain message libre de l'utilisateur doit
// etre interprete comme : une reponse a cet exercice, une correction de debogage, ou une
// explication Feynman. Jamais null tant que le module n'est pas termine.
export class ModuleStateResponseDto {
@ApiProperty() moduleIndex!: number;
@ApiProperty() title!: string;
@ApiProperty() hook!: string;
@ApiProperty({ type: ModuleTheoryDto }) theory!: ModuleTheoryDto;
@ApiProperty({ type: ModuleWeDoDto }) weDo!: ModuleWeDoDto;
@ApiProperty({ type: [PublicExerciseDto] }) exercises!: PublicExerciseDto[];
@ApiProperty({ type: PublicDebugExerciseDto })
debugExercise!: PublicDebugExerciseDto;
@ApiProperty({ type: ModuleSynthesisDto }) synthesis!: ModuleSynthesisDto;
@ApiProperty({ type: ModuleAwaitingDto, nullable: true })
awaiting!: ModuleAwaitingDto | null;
}
@@ -1,6 +1,12 @@
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,
// 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 +15,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 +27,44 @@ 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;
@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;
}
@@ -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;
}
@@ -0,0 +1,80 @@
// Prompt de role de l'Agent 7 (docs/Max_System_Prompt.md). [COMPÉTENCE_INJECTÉE] et l'etape
// (interview|mission) sont remplaces par le backend (evaluation.agent.ts). Avec personnalite
// (buildAgentPrompt) : Max parle directement ici, il joue le role du client puis presente le cas
// de mission.
export function buildEvaluationPrompt(competence: string): string {
return `## Ton rôle dans cet échange
Tu dois évaluer si l'utilisateur a réellement acquis cette compétence :
${competence}
L'évaluation se fait en deux temps. Le backend indique dans quel temps tu opères via le champ
"stage" du contrat JSON ci-dessous.
---
### Si stage = "interview" (entretien client simulé)
Tu joues le rôle d'un client potentiel qui évalue le freelance avant de lui confier une mission.
Tu poses 3 à 5 questions du type :
- "Explique-moi comment tu utiliserais [compétence] dans ce contexte."
- "Quels sont les risques ou limites de cette approche ?"
- "Pourquoi ce choix plutôt qu'une alternative ?"
Tu évalues chaque réponse sur ces 5 critères :
1. Vocabulaire professionnel correct
2. Clarté conceptuelle
3. Connaissance des limites
4. Valeur client formulée
5. Cohérence entre les réponses
Seuil de validation : 4/5.
---
### Si stage = "mission" (cas de mission réel)
Tu soumets un problème concret du même type que ce que le freelance
rencontrera en mission — différent de tous les exercices du cours (liste fournie dans le
contexte, ne jamais reutiliser un de ces enonces).
Le problème doit être de niveau difficile.
Tu évalues la réponse sur ces 4 critères :
1. Application correcte de la compétence
2. Qualité du raisonnement (pas seulement la réponse finale)
3. Gestion des cas limites
4. Autonomie (sans indice de ta part)
Seuil de validation : 3/4.
## Ce que tu ne fais pas
- Tu ne donnes pas la réponse si l'utilisateur échoue
- Tu ne mélanges pas les deux étapes dans le même échange
- Tu ne valides pas si le seuil n'est pas atteint
${EVALUATION_JSON_CONTRACT}`;
}
// Ajout technique non present dans docs/Max_System_Prompt.md : comme pour level.prompt.ts, le
// backend a besoin d'un contrat JSON constant a chaque tour pour distinguer "encore une
// question/pas de cas de mission encore soumis" de "score final pret". Les scores sont RECALCULES
// cote code (evaluation.agent.ts) a partir de "scores" - "total"/"validated" du LLM ne sont
// jamais utilises tels quels (meme principe que objective.agent.ts pour la coherence, et
// mapping.agent.ts pour les regles mesurables).
export const EVALUATION_JSON_CONTRACT = `Reponds TOUJOURS avec un objet JSON strict, sans texte
autour.
Tant que tu n'as pas pose/obtenu reponse a tes 3-5 questions (etape interview) ou pas encore
soumis le cas de mission ou pas encore recu la reponse au cas de mission (etape mission) :
{"message": "...", "done": false}
Une fois l'etape "interview" terminee (toutes les questions posees et reponses recues) :
{"message": "...", "done": true, "scores": {"vocabulary": 0 | 1, "clarity": 0 | 1, "limits": 0 | 1, "value": 0 | 1, "consistency": 0 | 1}, "feedback": "..."}
Une fois l'etape "mission" terminee (cas soumis, reponse de l'utilisateur recue et evaluee) :
{"message": "...", "done": true, "scores": {"application": 0 | 1, "reasoning": 0 | 1, "edge_cases": 0 | 1, "autonomy": 0 | 1}, "feedback": "..."}
"message" est la question/le cas de mission en cours, ou une courte phrase de transition une fois
"done": true (jamais le score brut). N'inclus jamais "total" ni "validated" : le backend les
recalcule lui-meme a partir de "scores".`;
@@ -0,0 +1,53 @@
// Prompt de role de l'Agent 3 (docs/Max_System_Prompt.md). [OBJECTIF_INJECTÉ_PAR_LE_BACKEND] et
// [CARTE_INJECTÉE_PAR_LE_BACKEND] sont remplaces par le backend (level.agent.ts) avant l'envoi.
export const LEVEL_PROMPT = `## Ton rôle dans cet échange
Tu dois évaluer le niveau réel de l'utilisateur sur ce domaine :
[OBJECTIF_INJECTÉ_PAR_LE_BACKEND]
La carte des compétences du domaine est :
[CARTE_INJECTÉE_PAR_LE_BACKEND]
## Ce que tu fais
Tu poses 3 à 5 questions situationnelles construites depuis la carte des compétences.
Chaque question cible un concept clé de la carte.
Les questions décrivent des situations professionnelles réelles — jamais de définitions,
jamais de QCM, jamais "à quel niveau tu te situes ?".
Exemple de bonne question : "Si un client te demande d'animer une rotation de 45°
sur un objet 3D, comment tu t'y prends ?"
Exemple de mauvaise question : "Est-ce que tu connais les matrices ?"
Une fois les réponses reçues, tu produis un profil de niveau en JSON :
{
"mastered": ["concept A", "concept B"],
"gaps": [
{ "concept": "concept C", "description": "lacune précise observée" }
],
"unknown": ["concept D", "concept E"],
"overall_level": "beginner|intermediate|advanced"
}
## Ce que tu ne fais pas
- Tu ne commences pas à corriger ou expliquer pendant l'évaluation
- Tu ne donnes pas le résultat avant d'avoir posé toutes les questions
- Tu ne poses pas plus de 5 questions`;
// Ajout technique non present dans docs/Max_System_Prompt.md : le document decrit un enchainement
// question->question->profil final en texte libre. Comme pour l'Agent 1, le backend a besoin d'un
// contrat JSON constant a chaque tour pour distinguer "encore une question" de "profil pret" (et,
// cote level.agent.ts, du cas special "relance ciblee apres contestation"). "message" reste la
// question ou le profil tels que decrits ci-dessus ; le reste du JSON est une couche de transport.
export const LEVEL_JSON_CONTRACT = `Reponds TOUJOURS avec un objet JSON strict, sans texte autour,
de la forme :
{"message": "...", "done": false}
tant que tu n'as pas pose et obtenu de reponse a tes 3-5 questions.
Une fois toutes les questions posees et les reponses recues, reponds avec :
{"message": "...", "done": true, "mastered": ["..."], "gaps": [{"concept": "...", "description": "..."}], "unknown": ["..."], "overall_level": "beginner" | "intermediate" | "advanced"}
"message" dans ce cas final est une courte phrase de transition annoncant que le profil est pret
(ex: "Voila, j'ai une idee claire de ton niveau."), jamais la liste brute des concepts.`;
@@ -0,0 +1,64 @@
// Prompt de role de l'Agent 2 (docs/Max_System_Prompt.md).
export const MAPPING_PROMPT = `## Ton rôle dans cet échange
Tu dois cartographier les concepts clés du domaine de l'objectif suivant :
[OBJECTIF_INJECTÉ_PAR_LE_BACKEND]
## Ce que tu fais
Tu effectues une recherche sur les concepts fondamentaux de ce domaine.
Pour chaque concept tu identifies :
- Son nom exact
- Son niveau de complexité (débutant / intermédiaire / avancé)
- Ses prérequis
- Ce que "maîtriser ce concept" permet de faire concrètement
- Les sources qui le confirment (minimum 2 sources par concept)
Minimum 5 sources consultées au total.
Tu ne génères pas depuis ta mémoire seule — tu cherches.
## Format de sortie obligatoire
Tu retournes un JSON structuré :
{
"concepts": [
{
"name": "...",
"level": "beginner|intermediate|advanced",
"prerequisites": ["..."],
"can_do": "être capable de...",
"sources": ["..."]
}
],
"sources_count": N
}
## Ce que tu ne fais pas
- Tu ne rédiges pas de cours
- Tu ne poses pas de questions à l'utilisateur
- Tu ne proposes pas de plan`;
// Ajout technique non present dans docs/Max_System_Prompt.md : docs/Max Refonte Coach
// Freelance.md precise que les regles de hierarchie des sources (RESEARCH_SOURCE_RULES)
// s'appliquent aussi a l'Agent 2, et que la carte doit porter un market_demand par concept pour
// alimenter le calibrage de l'Agent 4 ("concepts maitrises -> sources avancees", etc.) et la
// future veille. Le schema JSON ci-dessus est donc etendu ici avec market_demand et le niveau de
// hierarchie de chaque source, sans changer le role conversationnel decrit par le document.
export const MAPPING_JSON_CONTRACT = `Etends le JSON de sortie pour qu'il corresponde exactement a
ce schema (chaque champ est obligatoire) :
{
"concepts": [
{
"name": "...",
"level": "beginner" | "intermediate" | "advanced",
"prerequisites": ["..."],
"can_do": "être capable de...",
"market_demand": "low" | "medium" | "high",
"sources": [{ "title": "...", "source_tier": 1 | 2 | 3 | 4 }]
}
],
"sources_count": N
}
Reponds TOUJOURS avec cet objet JSON strict, sans texte avant ni apres.`;
@@ -0,0 +1,111 @@
// Prompt de role de l'Agent 6 (docs/Max_System_Prompt.md). Les placeholders [INDEX], [TITRE],
// [CONCEPT], [OBJECTIF_INJECTÉ], [NIVEAU_INJECTÉ], [CORPUS_INJECTÉ], [LISTE_MODULES_PRÉCÉDENTS]
// sont remplaces par le backend (module.agent.ts). Pas de personnalite Max (contenu long
// affiche et lu a l'ecran, jamais raconte par Max - docs/Max Refonte Coach Freelance.md,
// "Jamais de cours a l'oral") ni de ":online" (redige a partir du corpus deja recupere).
export function buildModulePrompt(params: {
index: number;
title: string;
concept: string;
objectiveSummary: string;
levelSummary: string;
corpusSummary: string;
previousModulesSummary: string;
}): string {
return `## Ton rôle dans cet échange
Tu dois rédiger le contenu du module suivant :
Module ${params.index} — ${params.title}
Concept ciblé : ${params.concept}
Objectif global de la formation : ${params.objectiveSummary}
Niveau de l'utilisateur : ${params.levelSummary}
Corpus de recherche disponible : ${params.corpusSummary}
Modules précédents déjà enseignés : ${params.previousModulesSummary}
## Structure obligatoire — 6 sections dans cet ordre
1. ACCROCHE (minimum 150 mots)
Situation réelle + contexte historique + 3 cas d'usage actuels + question d'amorce.
Ne pas commencer par une définition.
2. THÉORIE (minimum 300 mots)
Idée centrale en langage simple + analogie vérifiée + définition formelle
+ exemple résolu étape par étape + contre-exemple.
3. PHASE GUIDÉE — WE DO (minimum 3 étapes)
Problème similaire à l'exemple, guidé par questions.
Ne jamais donner la réponse — guider jusqu'à ce que l'utilisateur y arrive.
4. EXERCICES (minimum 6 exercices)
2 faciles + 2 moyens + 2 difficiles.
Chaque exercice ancré dans un contexte de mission freelance réelle.
5. EXERCICE DE DÉBOGAGE (1 obligatoire)
Code ou raisonnement contenant une erreur intentionnelle subtile à trouver.
6. SYNTHÈSE ET AUTO-ÉVALUATION (minimum 100 mots)
Récapitulatif + 3 questions de méta-cognition + test Feynman
("Explique ce concept comme si j'avais 12 ans").
## Règles absolues
- Vérifie deux fois chaque calcul ou formule avant de l'écrire
- Ne présuppose aucune connaissance non enseignée dans les modules précédents
- Ne donne jamais la réponse à un exercice directement
## Ce que tu ne fais pas
- Tu ne poses pas de questions à l'utilisateur
- Tu ne rédiges pas le module suivant
- Tu ne t'écarte pas des 6 sections
${MODULE_JSON_CONTRACT}`;
}
// Ajout technique non present dans docs/Max_System_Prompt.md : le document decrit 6 sections en
// prose. Pour etre affichable dans ModulePanel/ExerciseCard/DebugExerciseCard/FeynmanCard
// (docs/Max_Composants_Frontend.md) et validable cote code (nombre de mots, nombre d'exercices,
// echelle d'indices a 5 niveaux), le contenu doit arriver structure. "correctAnswerInternal"/
// "correctionInternal" ne sont jamais exposes au frontend (voir module.agent.ts, toPublicContent).
export const MODULE_JSON_CONTRACT = `Tu retournes un JSON structuré exactement sous cette forme :
{
"hook": "... (>= 150 mots, situation reelle + contexte historique + 3 cas d'usage + question d'amorce)",
"theory": {
"coreIdea": "...",
"analogy": "...",
"formalDefinition": "...",
"workedExample": "...",
"counterExample": "..."
},
"weDo": {
"problem": "...",
"guidingQuestions": ["...", "...", "..."]
},
"exercises": [
{
"level": "easy",
"context": "contexte de mission freelance reelle",
"prompt": "...",
"hints": ["indice niveau 1 (clarification)", "indice niveau 2 (rappel de concept)", "indice niveau 3 (pointage precis)", "indice niveau 4 (exemple analogue)", "indice niveau 5 (decomposition)"],
"correctAnswerInternal": "..."
}
],
"debugExercise": {
"codeOrReasoningWithBug": "...",
"language": "...",
"instruction": "...",
"correctionInternal": "..."
},
"synthesis": {
"recap": "...",
"metacognitionQuestions": ["...", "...", "..."],
"feynmanPrompt": "Explique ce concept comme si j'avais 12 ans"
}
}
Le tableau "exercises" contient EXACTEMENT 6 elements : 2 avec "level":"easy", 2 avec
"level":"medium", 2 avec "level":"hard", chacun avec EXACTEMENT 5 indices dans "hints" (du plus
leger au plus explicite). "correctAnswerInternal" et "correctionInternal" sont la reponse/correction
exacte, jamais montrees a l'utilisateur. Reponds UNIQUEMENT avec cet objet JSON strict, sans texte
avant ni apres.`;
@@ -41,4 +41,9 @@ export const OBJECTIVE_JSON_CONTRACT = `Reponds TOUJOURS avec un objet JSON stri
"message" contient la question en cours, ou la phrase de reformulation ("Ton objectif : ... C'est
bien ça ?") une fois les 3 piliers identifies. Ne mets "readyToConfirm": true que lorsque les 3
piliers (subject, professionalGoal, duration) sont clairement etablis ET que "message" contient
deja cette reformulation en attente de confirmation.`;
deja cette reformulation en attente de confirmation.
"duration" doit TOUJOURS etre ecrit avec un chiffre suivi d'une unite, jamais en toutes lettres :
par exemple "1 semaine" (jamais "une semaine"), "10 heures", "2 jours", "1 mois". Reformule toi-meme
la duree de l'utilisateur dans ce format avant de la mettre dans "duration", meme s'il l'a exprimee
autrement a l'oral ou a l'ecrit.`;
@@ -0,0 +1,53 @@
// Prompt de role de l'Agent 5 (docs/Max_System_Prompt.md). [OBJECTIF_INJECTÉ],
// [PROFIL_INJECTÉ] et [RÉSUMÉ_DU_CORPUS_INJECTÉ] sont remplaces par le backend
// (plan.agent.ts). Pas de personnalite Max ici (producteur de JSON pur, personne ne
// l'entend, meme choix que mapping.prompt.ts/research.prompt.ts) ni de ":online" (raisonne
// sur des donnees deja recuperees par les Agents 2/3/4, pas une recherche fraiche).
export const PLAN_PROMPT = `## Ton rôle dans cet échange
Tu dois construire le curriculum de formation pour cet objectif :
[OBJECTIF_INJECTÉ]
Profil de niveau de l'utilisateur :
[PROFIL_INJECTÉ]
Corpus de recherche disponible :
[RÉSUMÉ_DU_CORPUS_INJECTÉ]
## Ce que tu fais
Tu appliques la méthode Backward Design :
1. Tu pars de l'objectif final (ce que l'utilisateur doit savoir faire)
2. Tu identifies les modules nécessaires pour y arriver
3. Tu ordonnes les modules du plus simple au plus complexe
Règles de construction :
- 3 à 7 modules maximum
- Un module = un seul concept clé
- Les concepts déjà maîtrisés (profil "mastered") sont exclus ou condensés en révision rapide
- Les gaps sont prioritaires dans l'ordre des modules
Tu retournes un JSON :
{
"modules": [
{
"index": 1,
"title": "...",
"concept": "...",
"estimated_duration": "...",
"prerequisites": ["..."],
"status": "unlocked"
}
],
"total_duration": "..."
}
Seul le module d'index 1 a le statut "unlocked". Tous les autres ont "locked".
## Ce que tu ne fais pas
- Tu ne rédiges pas le contenu des modules
- Tu ne poses pas de questions à l'utilisateur
- Tu ne dépasses pas 7 modules
Reponds UNIQUEMENT avec cet objet JSON strict, sans texte avant ni apres.`;
@@ -0,0 +1,34 @@
// Regles de recherche partagees par les Agents 2 (Cartographie) et 4 (Recherche Approfondie) -
// docs/Max Refonte Coach Freelance.md, section "Systeme de recherche - regles et hierarchie des
// sources" : "Ces regles s'appliquent aux deux agents de recherche". Ce texte n'apparait pas tel
// quel dans docs/Max_System_Prompt.md (qui ne donne qu'une version courte pour l'Agent 4) : il est
// ajoute ici pour que l'Agent 2 applique la meme rigueur, comme l'exige le document de refonte.
export const RESEARCH_SOURCE_RULES = `## Hierarchie des sources a respecter (4 niveaux)
1. Referentiels officiels : certifications professionnelles, organismes de normalisation,
referentiels metiers (ex: AWS, Google, Microsoft, Adobe ; IEEE, ACM, W3C, ISO ; RNCP, ROME,
O*NET). Definissent ce qu'une competence veut dire officiellement.
2. Curricula universitaires : syllabus et plans de cours reconnus (ex: MIT OCW, Stanford Online,
Polytechnique). Structurent les prerequis et la progression logique.
3. Plateformes structurees : plans de cours de plateformes reconnues, documentation officielle
(ex: Coursera, edX, LinkedIn Learning - structure uniquement ; MDN, React Docs, AWS Docs).
4. Signal marche : offres d'emploi et missions freelance, rapports sectoriels (ex: 20 a 50 offres
analysees, Stack Overflow Survey, State of JS/CSS).
## Regles mesurables et verifiables
- Minimum 5 sources citees au total dans la sortie.
- Diversite obligatoire : au moins une source de niveau 1, une de niveau 3, une de niveau 4.
- Fraicheur : date de publication/mise a jour <= 2 ans pour un sujet tech, <= 5 ans pour un sujet
stable.
- Consensus inter-sources : chaque concept cle confirme par au moins 2 sources independantes.
- Formulation actionnable obligatoire : chaque competence formulee en "etre capable de...".
0 "comprendre" ou "savoir" tolere.
## Ce que tu dois faire concretement
- Classe chaque source avec son niveau de hierarchie (1, 2, 3 ou 4).
- Refuse de valider un concept sans au moins une source citee et une formulation
"etre capable de".
- Si un concept n'a pu etre confirme que par une seule source, signale-le explicitement plutot
que de le presenter avec la meme confiance qu'un concept a double confirmation.`;
@@ -0,0 +1,43 @@
import { RESEARCH_SOURCE_RULES } from './research-source-rules.prompt';
// Prompt de role de l'Agent 4 (docs/Max_System_Prompt.md). [SOUS_THÈME_INJECTÉ_PAR_LE_BACKEND] et
// [NIVEAU_INJECTÉ] sont remplaces par le backend (research.agent.ts), un appel par sous-theme
// (concept de la carte de l'Agent 2), execute en parallele.
export function buildResearchPrompt(subtopic: string, level: string): string {
return `## Ton rôle dans cet échange
Tu dois constituer un corpus de formation complet sur ce sous-thème :
${subtopic}
Le niveau de l'utilisateur est : ${level}
(beginner = partir des fondamentaux / intermediate = partir des bases
/ advanced = aller directement aux cas complexes)
## Ce que tu fais
Tu recherches des sources fiables sur ce sous-thème.
Minimum 3 sources par sous-thème, fraîches (moins de 2 ans pour la tech).
${RESEARCH_SOURCE_RULES}
Tu produis un JSON :
{
"subtopic": "...",
"summary": "...",
"key_points": ["..."],
"examples": ["..."],
"common_mistakes": ["..."],
"sources": [{ "title": "...", "url": "...", "level": 1|2|3|4 }]
}
## Ce que tu ne fais pas
- Tu ne génères pas depuis ta mémoire seule
- Tu ne rédiges pas de cours
- Tu ne poses pas de questions à l'utilisateur
Note : cet agent est appelé en parallèle sur plusieurs sous-thèmes simultanément.
Tu traites uniquement le sous-thème indiqué.
Reponds UNIQUEMENT avec cet objet JSON strict, sans texte avant ni apres.`;
}
@@ -11,7 +11,16 @@ describe('SessionsController', () => {
findOne: jest.fn(),
sendObjectiveMessage: jest.fn(),
confirmObjective: jest.fn(),
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' },
@@ -68,6 +77,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',
@@ -79,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);
});
});
+157
View File
@@ -18,6 +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';
@@ -112,4 +125,148 @@ 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), declencher l'Agent 4 (Recherche Approfondie) puis l'Agent 5 (Plan) - renvoie le curriculum pret pour CurriculumCard",
})
@ApiResponse({ status: HttpStatus.OK, type: CurriculumResponseDto })
@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<CurriculumResponseDto> {
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);
}
@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<ModuleStateResponseDto> {
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<JudgeResultResponseDto> {
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<HintResponseDto> {
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<JudgeResultResponseDto> {
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<FeynmanFeedbackResponseDto> {
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<ModuleCompleteResponseDto> {
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<EvaluationResultResponseDto> {
return this.sessionsService.getEvaluationResult(id, request.user.sub);
}
}
+17 -1
View File
@@ -2,15 +2,31 @@ 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';
@Module({
imports: [PrismaModule, LlmModule, AuthModule],
controllers: [SessionsController],
providers: [SessionsService, ObjectiveAgent, IntentRouterAgent],
providers: [
SessionsService,
ObjectiveAgent,
MappingAgent,
LevelAgent,
ResearchAgent,
PlanAgent,
ModuleAgent,
EvaluationAgent,
IntentRouterAgent,
],
exports: [SessionsService],
})
export class SessionsModule {}
+447 -3
View File
@@ -2,16 +2,59 @@ 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';
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() },
sessionCurriculum: {
findUnique: jest.fn(),
findUniqueOrThrow: jest.fn(),
update: jest.fn<
Promise<unknown>,
[{ 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() };
const levelAgent = {
start: jest.fn(),
converse: jest.fn(),
confirm: jest.fn(),
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() };
@@ -22,6 +65,12 @@ describe('SessionsService', () => {
SessionsService,
{ provide: PrismaService, useValue: prisma },
{ provide: ObjectiveAgent, useValue: objectiveAgent },
{ 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 },
],
@@ -109,7 +158,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 +173,133 @@ 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 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,
});
const result = 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' },
});
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 () => {
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,7 +335,31 @@ describe('SessionsService', () => {
expect(intentRouter.analyze).not.toHaveBeenCalled();
});
it('should reject when the active session is in a status with no agent built yet', async () => {
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 transitional status not reachable from a free message (crash-recovery edge case)', async () => {
prisma.session.findFirst.mockResolvedValueOnce({
id: 1,
userId: 7,
@@ -175,6 +370,97 @@ describe('SessionsService', () => {
service.routeIncomingMessage(7, 'un message'),
).rejects.toThrow(ConflictException);
expect(objectiveAgent.converse).not.toHaveBeenCalled();
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 () => {
@@ -232,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,
);
});
});
});
+474 -2
View File
@@ -3,25 +3,67 @@ 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 };
const IMPLEMENTED_STATUSES = new Set(['objective_discovery']);
// "researching" est gere entierement cote code par confirmLevel() (declenche l'Agent 4 puis
// 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()
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 planAgent: PlanAgent,
private readonly moduleAgent: ModuleAgent,
private readonly evaluationAgent: EvaluationAgent,
private readonly intentRouter: IntentRouterAgent,
private readonly llm: OpenRouterService,
) {}
@@ -46,6 +88,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 +104,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 +136,223 @@ export class SessionsService {
professionalGoal: objective.professionalGoal,
duration: objective.duration,
validatedAt: objective.validatedAt ?? new Date(),
nextPrompt: firstTurn.reply,
};
}
/**
* 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<CurriculumResponseDto> {
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' },
});
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<ModuleStateResponseDto> {
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<JudgeResultResponseDto> {
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<HintResponseDto> {
const moduleIndex = await this.assertTeachingInProgress(sessionId, userId);
return this.moduleAgent.requestHint(sessionId, moduleIndex, dto.exerciseId);
}
async submitDebugCorrection(
sessionId: number,
userId: number,
dto: DebugCorrectionDto,
): Promise<JudgeResultResponseDto> {
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<FeynmanFeedbackResponseDto> {
const moduleIndex = await this.assertTeachingInProgress(sessionId, userId);
return this.moduleAgent.submitFeynmanExplanation(
sessionId,
userId,
moduleIndex,
dto.explanation,
);
}
async completeModule(
sessionId: number,
userId: number,
): Promise<ModuleCompleteResponseDto> {
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<EvaluationResultResponseDto> {
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<void> {
await this.evaluationAgent.start(sessionId, userId);
}
private async assertTeachingInProgress(
sessionId: number,
userId: number,
): Promise<number> {
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(
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 +374,53 @@ 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,
};
}
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,
@@ -146,6 +483,141 @@ 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,
};
}
/**
* 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<RouteMessageResponseDto> {
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,
@@ -0,0 +1,12 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
/** "sessionId" n'est renseigne que pour l'action "train" - signal structure pour le frontend
* (voix uniquement, jamais de decision d'UI prise par un LLM) : sa seule presence suffit a savoir
* qu'une nouvelle session de formation vient d'etre demarree et doit etre ouverte. */
export class VeilleSignalActionResultDto {
@ApiProperty()
actionTaken!: string;
@ApiPropertyOptional()
sessionId?: number;
}
@@ -0,0 +1,8 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsIn } from 'class-validator';
export class VeilleSignalActionDto {
@ApiProperty({ enum: ['train', 'snooze', 'dismiss'] })
@IsIn(['train', 'snooze', 'dismiss'])
action!: 'train' | 'snooze' | 'dismiss';
}
@@ -0,0 +1,32 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
export class VeilleSignalSourceDto {
@ApiProperty()
title!: string;
@ApiProperty()
url!: string;
}
export class VeilleSignalResponseDto {
@ApiProperty()
id!: number;
@ApiProperty({ enum: ['emerging', 'refresh', 'obsolete'] })
type!: string;
@ApiProperty()
competence!: string;
@ApiProperty({ type: [VeilleSignalSourceDto] })
sources!: VeilleSignalSourceDto[];
@ApiProperty()
relevanceScore!: number;
@ApiPropertyOptional()
actionTaken!: string | null;
@ApiProperty()
createdAt!: Date;
}
@@ -0,0 +1,40 @@
import { Test, TestingModule } from '@nestjs/testing';
import type { AuthenticatedRequest } from '../auth/jwt-auth.guard';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { VeilleController } from './veille.controller';
import { VeilleService } from './veille.service';
describe('VeilleController', () => {
let controller: VeilleController;
const veilleService = { getActiveSignals: jest.fn(), applyAction: jest.fn() };
const request = {
user: { sub: 7, email: 'w@example.com' },
} as AuthenticatedRequest;
beforeEach(async () => {
jest.clearAllMocks();
const module: TestingModule = await Test.createTestingModule({
controllers: [VeilleController],
providers: [{ provide: VeilleService, useValue: veilleService }],
})
.overrideGuard(JwtAuthGuard)
.useValue({ canActivate: () => true })
.compile();
controller = module.get(VeilleController);
});
it('should list the active signals for the authenticated user', async () => {
veilleService.getActiveSignals.mockResolvedValueOnce([]);
await controller.getSignals(request);
expect(veilleService.getActiveSignals).toHaveBeenCalledWith(7);
});
it('should forward a signal action to the service', async () => {
veilleService.applyAction.mockResolvedValueOnce({
actionTaken: 'dismissed',
});
await controller.applyAction(1, { action: 'dismiss' }, request);
expect(veilleService.applyAction).toHaveBeenCalledWith(1, 7, 'dismiss');
});
});
+56
View File
@@ -0,0 +1,56 @@
import {
Body,
Controller,
Get,
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 { VeilleSignalActionDto } from './dto/veille-signal-action.dto';
import { VeilleSignalActionResultDto } from './dto/veille-signal-action-result.dto';
import { VeilleSignalResponseDto } from './dto/veille-signal-response.dto';
import { VeilleService } from './veille.service';
@ApiTags('veille')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Controller('veille')
export class VeilleController {
constructor(private readonly veilleService: VeilleService) {}
@Get('signals')
@ApiOperation({
summary:
'Lister les signaux de veille actifs (priorite obsolete > refresh > emerging, puis pertinence)',
})
@ApiResponse({ status: 200, type: [VeilleSignalResponseDto] })
getSignals(
@Req() request: AuthenticatedRequest,
): Promise<VeilleSignalResponseDto[]> {
return this.veilleService.getActiveSignals(request.user.sub);
}
@Post('signals/:id/action')
@ApiOperation({
summary:
"Agir sur un signal de veille : demarrer une formation (train), le repousser 14 jours (snooze) ou l'ecarter (dismiss)",
})
@ApiResponse({ status: 201, type: VeilleSignalActionResultDto })
applyAction(
@Param('id', ParseIntPipe) id: number,
@Body() dto: VeilleSignalActionDto,
@Req() request: AuthenticatedRequest,
): Promise<VeilleSignalActionResultDto> {
return this.veilleService.applyAction(id, request.user.sub, dto.action);
}
}
+11
View File
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { SessionsModule } from '../sessions/sessions.module';
import { VeilleController } from './veille.controller';
import { VeilleService } from './veille.service';
@Module({
imports: [SessionsModule],
controllers: [VeilleController],
providers: [VeilleService],
})
export class VeilleModule {}
+39
View File
@@ -0,0 +1,39 @@
/**
* Prompt de l'Agent de Veille (docs/Max Refonte Coach Freelance.md, "veille autonome") - pas de
* personnalite Max ici, personne n'entend cet agent (meme principe que ResearchAgent). Un appel
* par sujet surveille (domaine du profil ou sujet additionnel), recherche web reelle (":online").
*/
export function buildVeilleScanPrompt(topic: string): string {
return `## Ton role dans cet echange
Tu es un veilleur technologique pour un freelance specialise dans : ${topic}
## Ce que tu fais
Tu recherches, sur le web reel, des signaux recents et concrets pertinents pour ce freelance :
- "emerging" : une competence/outil/pratique emergente dans ce domaine qu'il ne maitrise pas encore
- "refresh" : une evolution significative d'une competence existante (nouvelle version majeure, nouvelle norme)
- "obsolete" : une pratique ou un outil du domaine en train de devenir obsolete
Minimum 3 sources independantes et fiables par signal (pas le meme site duplique), fraiches (moins de 6 mois sauf si clairement toujours d'actualite).
Tu produis un JSON (tableau, 0 a 5 signaux, uniquement si vraiment pertinent) :
{
"signals": [
{
"type": "emerging" | "refresh" | "obsolete",
"competence": "nom precis de la competence concernee",
"relevance_score": 0.0 a 1.0,
"sources": [{ "title": "...", "url": "..." }]
}
]
}
## Ce que tu ne fais pas
- Tu n'inventes pas de signal pour remplir le quota - un tableau vide est une reponse valide
- Tu ne generes pas depuis ta memoire seule, uniquement depuis une recherche web reelle
- Tu ne proposes jamais moins de 3 sources pour un signal que tu remontes
Reponds UNIQUEMENT avec cet objet JSON strict, sans texte avant ni apres.`;
}
+376
View File
@@ -0,0 +1,376 @@
import { ForbiddenException } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { PrismaService } from '../prisma/prisma.service';
import { OpenRouterService } from '../llm/openrouter.service';
import { SessionsService } from '../sessions/sessions.service';
import { VeilleService } from './veille.service';
function makeProfile(overrides: Record<string, unknown> = {}) {
return {
id: 1,
userId: 7,
domains: ['Facturation freelance'],
stack: [],
veilleExtraTopics: [],
veilleBlacklist: [],
veilleRelevanceThreshold: null,
veilleFrequency: null,
veilleNotificationsEnabled: true,
lastVeilleAt: null,
competencesDismissed: [],
...overrides,
};
}
function makeSignal(
type: string,
score: number,
overrides: Record<string, unknown> = {},
) {
return {
signals: [
{
type,
competence: 'TVA intracommunautaire',
relevance_score: score,
sources: [
{ title: 'Source 1', url: 'https://a.example' },
{ title: 'Source 2', url: 'https://b.example' },
{ title: 'Source 3', url: 'https://c.example' },
],
...overrides,
},
],
};
}
describe('VeilleService', () => {
let service: VeilleService;
const chat = jest.fn();
const updateProfile = jest.fn<
Promise<unknown>,
[{ where: { id: number }; data: Record<string, unknown> }]
>();
const createSignal = jest.fn<
Promise<unknown>,
[{ data: { freelanceProfileId: number } }]
>();
const updateSignal = jest.fn<
Promise<unknown>,
[{ where: { id: number }; data: { actionTaken: string } }]
>();
const prisma = {
freelanceProfile: {
findMany: jest.fn(),
findUnique: jest.fn(),
update: updateProfile,
},
veilleSignal: {
create: createSignal,
findFirst: jest.fn(),
findMany: jest.fn(),
findUnique: jest.fn(),
update: updateSignal,
},
};
const sessionsService = {
create: jest.fn(),
sendObjectiveMessage: jest.fn(),
};
beforeEach(async () => {
jest.clearAllMocks();
const module: TestingModule = await Test.createTestingModule({
providers: [
VeilleService,
{ provide: PrismaService, useValue: prisma },
{ provide: OpenRouterService, useValue: { chat } },
{ provide: SessionsService, useValue: sessionsService },
],
}).compile();
service = module.get(VeilleService);
});
describe('isDueToday()', () => {
it('should always be due for a profile with daily frequency', () => {
const profile = makeProfile({
veilleFrequency: 'daily',
lastVeilleAt: new Date(),
});
expect(service.isDueToday(profile as never)).toBe(true);
});
it('should be due when a weekly profile has never run', () => {
const profile = makeProfile({
veilleFrequency: 'weekly',
lastVeilleAt: null,
});
expect(service.isDueToday(profile as never)).toBe(true);
});
it('should not be due for a weekly profile that ran 2 days ago', () => {
const twoDaysAgo = new Date();
twoDaysAgo.setDate(twoDaysAgo.getDate() - 2);
const profile = makeProfile({
veilleFrequency: 'weekly',
lastVeilleAt: twoDaysAgo,
});
expect(service.isDueToday(profile as never)).toBe(false);
});
it('should infer a daily cadence for a volatile domain when no explicit frequency is set', () => {
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const profile = makeProfile({
veilleFrequency: null,
domains: ['Intelligence artificielle generative'],
lastVeilleAt: yesterday,
});
expect(service.isDueToday(profile as never)).toBe(true);
});
});
describe('runCycleForProfile()', () => {
it('should persist a signal with >=3 sources and relevance above threshold', async () => {
const profile = makeProfile();
chat.mockResolvedValueOnce(JSON.stringify(makeSignal('emerging', 0.9)));
prisma.veilleSignal.findFirst.mockResolvedValueOnce(null);
await service.runCycleForProfile(profile as never);
expect(createSignal.mock.calls[0][0].data.freelanceProfileId).toBe(1);
const updateCall = updateProfile.mock.calls[0][0];
expect(updateCall.where).toEqual({ id: 1 });
expect(updateCall.data.lastVeilleAt).toBeInstanceOf(Date);
});
it('should reject a signal with fewer than 3 sources', async () => {
const profile = makeProfile();
const payload = makeSignal('emerging', 0.9);
payload.signals[0].sources = payload.signals[0].sources.slice(0, 2);
chat.mockResolvedValueOnce(JSON.stringify(payload));
await service.runCycleForProfile(profile as never);
expect(prisma.veilleSignal.create).not.toHaveBeenCalled();
});
it('should reject a signal below the relevance threshold', async () => {
const profile = makeProfile();
chat.mockResolvedValueOnce(JSON.stringify(makeSignal('emerging', 0.5)));
await service.runCycleForProfile(profile as never);
expect(prisma.veilleSignal.create).not.toHaveBeenCalled();
});
it('should honor a profile relevance threshold stricter than the default', async () => {
const profile = makeProfile({ veilleRelevanceThreshold: 0.95 });
chat.mockResolvedValueOnce(JSON.stringify(makeSignal('emerging', 0.8)));
await service.runCycleForProfile(profile as never);
expect(prisma.veilleSignal.create).not.toHaveBeenCalled();
});
it('should reject a competence on the blacklist', async () => {
const profile = makeProfile({
veilleBlacklist: ['tva intracommunautaire'],
});
chat.mockResolvedValueOnce(JSON.stringify(makeSignal('emerging', 0.9)));
await service.runCycleForProfile(profile as never);
expect(prisma.veilleSignal.create).not.toHaveBeenCalled();
});
it('should not duplicate a signal already raised in the last 30 days', async () => {
const profile = makeProfile();
chat.mockResolvedValueOnce(JSON.stringify(makeSignal('emerging', 0.9)));
prisma.veilleSignal.findFirst.mockResolvedValueOnce({ id: 99 });
await service.runCycleForProfile(profile as never);
expect(prisma.veilleSignal.create).not.toHaveBeenCalled();
});
it('should do nothing but stamp lastVeilleAt when there is no topic to watch', async () => {
const profile = makeProfile({ domains: [], veilleExtraTopics: [] });
await service.runCycleForProfile(profile as never);
expect(chat).not.toHaveBeenCalled();
const updateCall = updateProfile.mock.calls[0][0];
expect(updateCall.where).toEqual({ id: 1 });
expect(updateCall.data.lastVeilleAt).toBeInstanceOf(Date);
});
});
describe('getActiveSignals()', () => {
it('should return an empty list when the user has no profile yet', async () => {
prisma.freelanceProfile.findUnique.mockResolvedValueOnce(null);
const result = await service.getActiveSignals(7);
expect(result).toEqual([]);
});
it('should order by type priority (obsolete > refresh > emerging) then relevance desc', async () => {
prisma.freelanceProfile.findUnique.mockResolvedValueOnce({ id: 1 });
prisma.veilleSignal.findMany.mockResolvedValueOnce([
{
id: 1,
type: 'emerging',
competence: 'A',
sources: [],
relevanceScore: 0.9,
actionTaken: null,
createdAt: new Date(),
},
{
id: 2,
type: 'obsolete',
competence: 'B',
sources: [],
relevanceScore: 0.8,
actionTaken: null,
createdAt: new Date(),
},
{
id: 3,
type: 'refresh',
competence: 'C',
sources: [],
relevanceScore: 0.95,
actionTaken: null,
createdAt: new Date(),
},
]);
const result = await service.getActiveSignals(7);
expect(result.map((s) => s.id)).toEqual([2, 3, 1]);
});
it('should exclude a dismissed signal', async () => {
prisma.freelanceProfile.findUnique.mockResolvedValueOnce({ id: 1 });
prisma.veilleSignal.findMany.mockResolvedValueOnce([
{
id: 1,
type: 'emerging',
competence: 'A',
sources: [],
relevanceScore: 0.9,
actionTaken: 'dismissed',
createdAt: new Date(),
},
]);
const result = await service.getActiveSignals(7);
expect(result).toEqual([]);
});
it('should exclude a snoozed signal whose resurface date has not passed', async () => {
const future = new Date();
future.setDate(future.getDate() + 10);
prisma.freelanceProfile.findUnique.mockResolvedValueOnce({ id: 1 });
prisma.veilleSignal.findMany.mockResolvedValueOnce([
{
id: 1,
type: 'emerging',
competence: 'A',
sources: [],
relevanceScore: 0.9,
actionTaken: `snoozed_until:${future.toISOString()}`,
createdAt: new Date(),
},
]);
const result = await service.getActiveSignals(7);
expect(result).toEqual([]);
});
it('should resurface a snoozed signal once its resurface date has passed', async () => {
const past = new Date();
past.setDate(past.getDate() - 1);
prisma.freelanceProfile.findUnique.mockResolvedValueOnce({ id: 1 });
prisma.veilleSignal.findMany.mockResolvedValueOnce([
{
id: 1,
type: 'emerging',
competence: 'A',
sources: [],
relevanceScore: 0.9,
actionTaken: `snoozed_until:${past.toISOString()}`,
createdAt: new Date(),
},
]);
const result = await service.getActiveSignals(7);
expect(result).toHaveLength(1);
});
});
describe('applyAction()', () => {
it('should throw ForbiddenException when the signal does not belong to the user', async () => {
prisma.veilleSignal.findUnique.mockResolvedValueOnce({
id: 1,
freelanceProfile: { userId: 99, id: 1, competencesDismissed: [] },
});
await expect(service.applyAction(1, 7, 'dismiss')).rejects.toThrow(
ForbiddenException,
);
});
it('should mark the signal dismissed and add the competence to the profile', async () => {
prisma.veilleSignal.findUnique.mockResolvedValueOnce({
id: 1,
competence: 'TVA',
freelanceProfile: { userId: 7, id: 1, competencesDismissed: [] },
});
const result = await service.applyAction(1, 7, 'dismiss');
expect(result).toEqual({ actionTaken: 'dismissed' });
expect(prisma.freelanceProfile.update).toHaveBeenCalledWith({
where: { id: 1 },
data: { competencesDismissed: ['TVA'] },
});
});
it('should snooze the signal with a resurface date 14 days out', async () => {
prisma.veilleSignal.findUnique.mockResolvedValueOnce({
id: 1,
competence: 'TVA',
freelanceProfile: { userId: 7, id: 1, competencesDismissed: [] },
});
const result = await service.applyAction(1, 7, 'snooze');
expect(result).toEqual({ actionTaken: 'snoozed' });
const updateCall = updateSignal.mock.calls[0][0];
expect(updateCall.data.actionTaken).toMatch(/^snoozed_until:/);
});
it('should start a new training session on train', async () => {
prisma.veilleSignal.findUnique.mockResolvedValueOnce({
id: 1,
competence: 'TVA intracommunautaire',
freelanceProfile: { userId: 7, id: 1, competencesDismissed: [] },
});
sessionsService.create.mockResolvedValueOnce({ id: 42 });
const result = await service.applyAction(1, 7, 'train');
expect(result).toEqual({ actionTaken: 'trained', sessionId: 42 });
expect(sessionsService.sendObjectiveMessage).toHaveBeenCalledWith(
42,
7,
'Je veux me former sur TVA intracommunautaire.',
);
});
});
});
+354
View File
@@ -0,0 +1,354 @@
import { ForbiddenException, Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { FreelanceProfile, Prisma, VeilleSignal } from '@prisma/client';
import { OpenRouterService } from '../llm/openrouter.service';
import { PrismaService } from '../prisma/prisma.service';
import { SessionsService } from '../sessions/sessions.service';
import { VeilleSignalActionResultDto } from './dto/veille-signal-action-result.dto';
import { VeilleSignalResponseDto } from './dto/veille-signal-response.dto';
import { buildVeilleScanPrompt } from './veille.prompt';
export interface VeilleSignalSource {
title: string;
url: string;
}
interface RawVeilleSignal {
type?: unknown;
competence?: unknown;
relevance_score?: unknown;
sources?: unknown;
}
const MIN_SOURCES = 3;
const DEFAULT_RELEVANCE_THRESHOLD = 0.7;
const DEDUP_WINDOW_DAYS = 30;
const SNOOZE_DAYS = 14;
const SNOOZE_PREFIX = 'snoozed_until:';
const WEEKLY_STALENESS_DAYS = 7;
const TYPE_PRIORITY: Record<string, number> = {
obsolete: 0,
refresh: 1,
emerging: 2,
};
/** Domaines qui evoluent vite : veille quotidienne plutot qu'hebdomadaire, sauf si le freelance a
* explicitement choisi une frequence (profile.veilleFrequency). Liste volontairement simple -
* un faux negatif se rattrape a la prochaine veille hebdomadaire, pas de consequence grave. */
const VOLATILE_DOMAIN_KEYWORDS = [
'ia',
'intelligence artificielle',
'ai',
'llm',
'genai',
'ia generative',
'web3',
'blockchain',
'no-code',
'low-code',
];
/**
* Agent de veille (docs/Max Refonte Coach Freelance.md, "veille autonome") : tourne en tache de
* fond (cron), jamais a la demande de l'utilisateur. Propose des signaux (competence emergente, a
* rafraichir, ou obsolete) que le freelance traite explicitement (train/snooze/dismiss) - ne
* modifie jamais le profil ou ne demarre jamais de session de son propre chef.
*/
@Injectable()
export class VeilleService {
private readonly logger = new Logger(VeilleService.name);
constructor(
private readonly prisma: PrismaService,
private readonly llm: OpenRouterService,
private readonly sessionsService: SessionsService,
) {}
/** Un seul cron quotidien : la distinction quotidien/hebdomadaire se fait par profil (voir
* isDueToday), pas par decorateur separe - plus simple a tester et a faire evoluer. */
@Cron(CronExpression.EVERY_DAY_AT_6AM)
async runDailyTick(): Promise<void> {
const profiles = await this.prisma.freelanceProfile.findMany({
where: { veilleNotificationsEnabled: true },
});
for (const profile of profiles) {
if (!this.isDueToday(profile)) continue;
try {
await this.runCycleForProfile(profile);
} catch (error) {
this.logger.warn(
`Veille du profil ${profile.id} echouee: ${String(error)}`,
);
}
}
}
isDueToday(profile: FreelanceProfile): boolean {
const frequency = profile.veilleFrequency ?? this.inferFrequency(profile);
if (frequency === 'daily') return true;
if (!profile.lastVeilleAt) return true;
const daysSinceLastRun =
(Date.now() - profile.lastVeilleAt.getTime()) / (1000 * 60 * 60 * 24);
return daysSinceLastRun >= WEEKLY_STALENESS_DAYS;
}
private inferFrequency(profile: FreelanceProfile): 'daily' | 'weekly' {
const domains = (profile.domains as unknown as string[]) ?? [];
const isVolatile = domains.some((domain) =>
VOLATILE_DOMAIN_KEYWORDS.some((keyword) =>
domain.toLowerCase().includes(keyword),
),
);
return isVolatile ? 'daily' : 'weekly';
}
async runCycleForProfile(profile: FreelanceProfile): Promise<void> {
const domains = (profile.domains as unknown as string[]) ?? [];
const extraTopics =
(profile.veilleExtraTopics as unknown as string[]) ?? [];
const topics = [...new Set([...domains, ...extraTopics])];
if (topics.length === 0) {
await this.prisma.freelanceProfile.update({
where: { id: profile.id },
data: { lastVeilleAt: new Date() },
});
return;
}
const blacklist = new Set(
((profile.veilleBlacklist as unknown as string[]) ?? []).map((c) =>
c.toLowerCase(),
),
);
const threshold = Math.max(
DEFAULT_RELEVANCE_THRESHOLD,
profile.veilleRelevanceThreshold ?? 0,
);
const outcomes = await Promise.all(
topics.map((topic) => this.scanTopic(profile.userId, topic)),
);
const candidates = outcomes.flat();
for (const candidate of candidates) {
if (candidate.sources.length < MIN_SOURCES) continue;
if (candidate.relevanceScore < threshold) continue;
if (blacklist.has(candidate.competence.toLowerCase())) continue;
if (
await this.isDuplicate(profile.id, candidate.competence, candidate.type)
) {
continue;
}
await this.prisma.veilleSignal.create({
data: {
freelanceProfileId: profile.id,
type: candidate.type,
competence: candidate.competence,
sources: candidate.sources as unknown as Prisma.InputJsonValue,
relevanceScore: candidate.relevanceScore,
},
});
}
await this.prisma.freelanceProfile.update({
where: { id: profile.id },
data: { lastVeilleAt: new Date() },
});
}
private async isDuplicate(
freelanceProfileId: number,
competence: string,
type: string,
): Promise<boolean> {
const since = new Date();
since.setDate(since.getDate() - DEDUP_WINDOW_DAYS);
const existing = await this.prisma.veilleSignal.findFirst({
where: {
freelanceProfileId,
competence,
type,
createdAt: { gte: since },
},
});
return existing !== null;
}
private async scanTopic(
userId: number,
topic: string,
): Promise<
{
type: string;
competence: string;
relevanceScore: number;
sources: VeilleSignalSource[];
}[]
> {
try {
const raw = await this.llm.chat(
userId,
[{ role: 'system', content: buildVeilleScanPrompt(topic) }],
{ jsonResponse: true, online: true },
);
return this.parseSignals(raw);
} catch (error) {
this.logger.warn(`Veille du sujet "${topic}" echouee: ${String(error)}`);
return [];
}
}
private parseSignals(raw: string): {
type: string;
competence: string;
relevanceScore: number;
sources: VeilleSignalSource[];
}[] {
try {
const data = JSON.parse(raw) as { signals?: unknown };
if (!Array.isArray(data.signals)) return [];
const results: {
type: string;
competence: string;
relevanceScore: number;
sources: VeilleSignalSource[];
}[] = [];
for (const rawSignal of data.signals as RawVeilleSignal[]) {
if (
!['emerging', 'refresh', 'obsolete'].includes(
String(rawSignal.type),
) ||
typeof rawSignal.competence !== 'string' ||
!Array.isArray(rawSignal.sources)
) {
continue;
}
const sources: VeilleSignalSource[] = [];
for (const rawSource of rawSignal.sources as {
title?: unknown;
url?: unknown;
}[]) {
if (
typeof rawSource.title === 'string' &&
typeof rawSource.url === 'string'
) {
sources.push({ title: rawSource.title, url: rawSource.url });
}
}
results.push({
type: rawSignal.type as string,
competence: rawSignal.competence,
relevanceScore: Number(rawSignal.relevance_score) || 0,
sources,
});
}
return results;
} catch {
this.logger.warn(`Reponse de veille non-JSON, rejetee: ${raw}`);
return [];
}
}
async getActiveSignals(userId: number): Promise<VeilleSignalResponseDto[]> {
const profile = await this.prisma.freelanceProfile.findUnique({
where: { userId },
});
if (!profile) return [];
const signals = await this.prisma.veilleSignal.findMany({
where: { freelanceProfileId: profile.id },
orderBy: { createdAt: 'desc' },
});
return signals
.filter((signal) => this.isActionable(signal))
.sort(
(a, b) =>
TYPE_PRIORITY[a.type] - TYPE_PRIORITY[b.type] ||
b.relevanceScore - a.relevanceScore,
)
.map((signal) => this.toResponse(signal));
}
/** Un signal sans action est actionnable. Un signal "snooze" le redevient automatiquement une
* fois sa date de resurgence passee (voir SNOOZE_PREFIX) - pas de colonne dediee en base. */
private isActionable(signal: VeilleSignal): boolean {
if (!signal.actionTaken) return true;
if (signal.actionTaken.startsWith(SNOOZE_PREFIX)) {
const resurfaceAt = new Date(
signal.actionTaken.slice(SNOOZE_PREFIX.length),
);
return resurfaceAt.getTime() <= Date.now();
}
return false;
}
async applyAction(
signalId: number,
userId: number,
action: 'train' | 'snooze' | 'dismiss',
): Promise<VeilleSignalActionResultDto> {
const signal = await this.prisma.veilleSignal.findUnique({
where: { id: signalId },
include: { freelanceProfile: true },
});
if (!signal || signal.freelanceProfile.userId !== userId) {
throw new ForbiddenException('Signal de veille introuvable.');
}
if (action === 'snooze') {
const resurfaceAt = new Date();
resurfaceAt.setDate(resurfaceAt.getDate() + SNOOZE_DAYS);
await this.prisma.veilleSignal.update({
where: { id: signalId },
data: { actionTaken: `${SNOOZE_PREFIX}${resurfaceAt.toISOString()}` },
});
return { actionTaken: 'snoozed' };
}
if (action === 'dismiss') {
await this.prisma.veilleSignal.update({
where: { id: signalId },
data: { actionTaken: 'dismissed' },
});
const dismissed = new Set(
(signal.freelanceProfile.competencesDismissed as unknown as string[]) ??
[],
);
dismissed.add(signal.competence);
await this.prisma.freelanceProfile.update({
where: { id: signal.freelanceProfile.id },
data: {
competencesDismissed: [...dismissed],
},
});
return { actionTaken: 'dismissed' };
}
await this.prisma.veilleSignal.update({
where: { id: signalId },
data: { actionTaken: 'trained' },
});
const session = await this.sessionsService.create(userId);
await this.sessionsService.sendObjectiveMessage(
session.id,
userId,
`Je veux me former sur ${signal.competence}.`,
);
return { actionTaken: 'trained', sessionId: session.id };
}
private toResponse(signal: VeilleSignal): VeilleSignalResponseDto {
return {
id: signal.id,
type: signal.type,
competence: signal.competence,
sources: signal.sources as unknown as VeilleSignalSource[],
relevanceScore: signal.relevanceScore,
actionTaken: signal.actionTaken,
createdAt: signal.createdAt,
};
}
}
-131
View File
@@ -1,131 +0,0 @@
import { logger } from '../utils/logger'
import { getConfigValue, requireLoggedIn } from '../auth/session'
const OPENROUTER_URL = 'https://openrouter.ai/api/v1/chat/completions'
// Si le modele principal est temporairement indisponible cote fournisseur (constate en test reel :
// 429 "rate-limited upstream" puis 504 "operation was aborted" sur deepseek/deepseek-chat), on
// bascule automatiquement sur un modele de secours de meme categorie, plutot que de faire echouer
// la reponse et d'afficher une erreur a l'utilisateur.
const FALLBACK_MODEL = process.env.OPENROUTER_FALLBACK_MODEL || 'qwen/qwen-2.5-72b-instruct'
interface ChatMessage {
role: 'system' | 'user' | 'assistant'
content: string
}
const BASE_SYSTEM_PROMPT = `Tu es Max, le coach de formation vocal d'un freelance. Tu discutes avec
lui de maniere naturelle et amicale, comme un collegue. Tes reponses sont lues a voix haute, donc
reste concis (2 a 4 phrases), parle en francais naturel, sans listes a puces ni mise en forme.
Regle absolue : ne decris jamais un processus ou un resultat que tu n'as pas reellement obtenu.
Si tu n'es pas sur de ta reponse, dis-le honnetement plutot que d'inventer une information.`
// Marqueurs pour detecter une fuite de "boilerplate" interne du modele (constate en test reel :
// "Use the results below to formulate an answer..." prononce a voix haute au lieu d'une vraie
// reponse de Max) : present si ca ressemble a de l'anglais generique sans aucun mot-outil francais.
const ENGLISH_LEAK_MARKERS =
/\b(the|unless|below|formulate|additional|information|needed|answer the|user question)\b/i
const FRENCH_MARKERS =
/\b(le|la|les|de|des|et|un|une|est|tu|je|pour|dans|avec|qui|que|ce|ton|ta)\b/i
function containsLeakedBoilerplate(text: string): boolean {
return ENGLISH_LEAK_MARKERS.test(text) && !FRENCH_MARKERS.test(text)
}
/**
* Le modele peut "decrocher" et renvoyer un texte corrompu (constate en test reel : " foia" +
* caracteres chinois/bengalis a la place d'une vraie phrase). Detecte via la part de caracteres
* non-latins/non-imprimables dans le texte.
*/
function isDegenerateText(text: string): boolean {
const trimmed = text.trim()
if (!trimmed) return false
let latinCount = 0
for (const char of trimmed) {
const code = char.codePointAt(0) ?? 0
if ((code >= 0x20 && code <= 0x7e) || (code >= 0xa0 && code <= 0x24f)) latinCount++
}
return latinCount / trimmed.length < 0.7 || (trimmed.length > 15 && latinCount < 8)
}
const FALLBACK_REPLY =
"Voila, j'ai bien avance avec toi sur ce sujet. Dis-moi si tu veux qu'on continue."
// Historique borne en memoire pour garder le contexte entre deux echanges vocaux.
const history: ChatMessage[] = []
const MAX_HISTORY_MESSAGES = 16
export async function getAssistantReply(userText: string): Promise<string> {
requireLoggedIn()
const apiKey = getConfigValue('OPENROUTER_API_KEY')
if (!apiKey) throw new Error('OPENROUTER_API_KEY manquante dans .env')
const primaryModel = getConfigValue('OPENROUTER_MODEL') || 'deepseek/deepseek-chat'
history.push({ role: 'user', content: userText })
const messages: ChatMessage[] = [{ role: 'system', content: BASE_SYSTEM_PROMPT }, ...history]
const callModel = (model: string): Promise<Response> =>
fetch(OPENROUTER_URL, {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ model, messages })
})
// La bascule de modele (panne HTTP ou reponse invalide) doit rester TRANSPARENTE pour
// l'utilisateur : meme `messages` (donc meme contexte de conversation) est reutilise quel que
// soit le modele qui repond, et on essaie l'AUTRE modele avant d'abandonner, plutot que de
// remonter une erreur visible des le premier echec (constate en test reel : une reponse 200 OK
// sans "choices" apres bascule faisait planter tout le tour au lieu d'etre rattrapee).
const modelsToTry = [primaryModel, FALLBACK_MODEL]
let data: ChatMessage | null = null
let lastError: string | null = null
for (const model of modelsToTry) {
let response: Response
try {
response = await callModel(model)
} catch (error) {
lastError = error instanceof Error ? error.message : String(error)
console.warn(`[chat] ${model} injoignable (${lastError}), tentative suivante si possible`)
continue
}
if (!response.ok) {
lastError = `${response.status}: ${await response.text()}`
console.warn(
`[chat] ${model} a renvoye une erreur (${lastError}), tentative suivante si possible`
)
continue
}
const parsed = (await response.json()) as { choices?: { message: ChatMessage }[] }
const choice = parsed.choices?.[0]
if (!choice) {
lastError = `reponse inattendue (${(parsed as { error?: { message?: string } })?.error?.message ?? 'forme inconnue'})`
console.warn(`[chat] ${model} : ${lastError}, tentative suivante si possible`)
continue
}
data = choice.message
break
}
if (!data) {
throw new Error(`Aucun modele disponible n'a pu repondre (${lastError ?? 'raison inconnue'})`)
}
let reply = data.content ?? ''
if (containsLeakedBoilerplate(reply) || isDegenerateText(reply)) {
console.warn(`[chat] reponse finale rejetee (fuite/degeneree), fallback utilise: ${reply}`)
reply = FALLBACK_REPLY
}
logger.debug(`[chat] reponse finale: ${reply}`)
history.push({ role: 'assistant', content: reply })
history.splice(0, Math.max(0, history.length - MAX_HISTORY_MESSAGES))
return reply
}
+42
View File
@@ -0,0 +1,42 @@
// Marqueurs pour detecter une fuite de "boilerplate" interne du modele (constate en test reel :
// "Use the results below to formulate an answer..." prononce a voix haute au lieu d'une vraie
// reponse de Max) : present si ca ressemble a de l'anglais generique sans aucun mot-outil francais.
const ENGLISH_LEAK_MARKERS =
/\b(the|unless|below|formulate|additional|information|needed|answer the|user question)\b/i
const FRENCH_MARKERS =
/\b(le|la|les|de|des|et|un|une|est|tu|je|pour|dans|avec|qui|que|ce|ton|ta)\b/i
export function containsLeakedBoilerplate(text: string): boolean {
return ENGLISH_LEAK_MARKERS.test(text) && !FRENCH_MARKERS.test(text)
}
/**
* Le modele peut "decrocher" et renvoyer un texte corrompu (constate en test reel : " foia" +
* caracteres chinois/bengalis a la place d'une vraie phrase). Detecte via la part de caracteres
* non-latins/non-imprimables dans le texte.
*/
export function isDegenerateText(text: string): boolean {
const trimmed = text.trim()
if (!trimmed) return false
let latinCount = 0
for (const char of trimmed) {
const code = char.codePointAt(0) ?? 0
if ((code >= 0x20 && code <= 0x7e) || (code >= 0xa0 && code <= 0x24f)) latinCount++
}
return latinCount / trimmed.length < 0.7 || (trimmed.length > 15 && latinCount < 8)
}
export const SPEECH_FALLBACK_REPLY =
"Voila, j'ai bien avance avec toi sur ce sujet. Dis-moi si tu veux qu'on continue."
/**
* A appliquer sur tout texte destine a etre prononce a voix haute (voir voice-turn dans
* src/main/index.ts) avant de l'envoyer a la synthese vocale : remplace une reponse
* fuyante/corrompue par une phrase de secours plutot que de la lire telle quelle a l'utilisateur.
*/
export function sanitizeForSpeech(text: string): string {
if (containsLeakedBoilerplate(text) || isDegenerateText(text)) {
return SPEECH_FALLBACK_REPLY
}
return text
}
+7 -5
View File
@@ -6,9 +6,11 @@ import { SECURE_WEB_PREFERENCES, blockExternalNavigation } from './utils/windowS
let win: BrowserWindow | null = null
let onClosedCallback: (() => void) | null = null
// Fenetre separee et deplacable (retour utilisateur direct : le chat et le stepper doivent etre
// des vraies fenetres Electron, pas des panneaux ancres dans la fenetre avatar), meme pattern
// singleton que src/main/auth/loginWindow.ts et stepperWindow.ts.
// Fenetre separee et deplacable (retour utilisateur direct : la barre de saisie texte et le
// stepper doivent etre des vraies fenetres Electron, pas des panneaux ancres dans la fenetre
// avatar), meme pattern singleton que src/main/auth/loginWindow.ts et stepperWindow.ts. Ce n'est
// PAS une fenetre de chat (retour utilisateur direct) : juste une barre de saisie alternative au
// micro, sans historique de conversation affiche - d'ou sa petite taille.
export function isChatWindowOpen(): boolean {
return win !== null && !win.isDestroyed()
}
@@ -22,8 +24,8 @@ export function openChatWindow(): void {
win = new BrowserWindow({
width: 380,
height: 560,
title: 'Max — conversation',
height: 100,
title: 'Max — écrire un message',
frame: false,
transparent: true,
backgroundColor: '#00000000',
+73 -26
View File
@@ -3,13 +3,14 @@ import { app, session, shell, BrowserWindow, ipcMain } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import { transcribeAudio, synthesizeSpeech } from './ai/elevenlabs'
import { getAssistantReply } from './ai/openrouter'
import { sanitizeForSpeech } from './ai/speechSafety'
import { setMainWindow } from './windowBridge'
import { stripWakeWord } from './wakeWord'
import { loginAndLoadKeys } from './auth/authClient'
import { openLoginWindow, closeLoginWindow } from './auth/loginWindow'
import { clearSession, getCurrentUserEmail, isLoggedIn, requireLoggedIn } from './auth/session'
import { closeChatWindow, isChatWindowOpen, onChatWindowClosed, openChatWindow } from './chatWindow'
import { closeObjectiveWindow, openObjectiveWindow } from './objectiveWindow'
import { closeStepperWindow, openStepperWindow } from './stepperWindow'
import {
confirmObjective,
@@ -18,9 +19,10 @@ import {
routeMessage,
sendObjectiveMessage
} from './api/sessionsClient'
import type { VoiceTurnResult } from '../shared/voice'
import type { TextTurnResult, VoiceTurnResult } from '../shared/voice'
import type { AuthStatus, LoginResult } from '../shared/auth'
import type {
ObjectiveDraft,
ObjectiveMessageResponse,
RouteMessageResponse,
SessionObjectiveResponse,
@@ -153,6 +155,7 @@ app
clearSession()
closeChatWindow()
closeStepperWindow()
closeObjectiveWindow()
event.sender.send('toggle-listening', false)
})
@@ -167,7 +170,10 @@ app
// fenetre de chat est fermee autrement que par ce menu (ex: Alt+F4).
onChatWindowClosed(() => mainWindow?.webContents.send('chat-window-closed'))
ipcMain.on('session-ended', () => closeStepperWindow())
ipcMain.on('session-ended', () => {
closeStepperWindow()
closeObjectiveWindow()
})
// Relais inter-fenetres : la fenetre du stepper vit dans son propre process renderer isole
// (voir src/main/stepperWindow.ts) et n'a donc pas acces a l'etat de la fenetre de chat qui
@@ -179,10 +185,39 @@ app
}
}
// Relais inter-fenetres vers la fenetre dediee a la validation de l'objectif (voir
// src/main/objectiveWindow.ts) : separee du chat texte sur demande directe de l'utilisateur
// (la confirmation ne doit jamais dependre d'ouvrir la conversation, y compris quand tout
// l'echange se fait au vocal). Ouverte et alimentee ici, dans le code partage par le texte et
// la voix (handleRouteMessageResult), pour garantir que les deux canaux se comportent pareil.
function broadcastObjectiveReady(sessionId: number, draft: ObjectiveDraft): void {
openObjectiveWindow()
for (const window of BrowserWindow.getAllWindows()) {
window.webContents.send('objective-ready', sessionId, draft)
}
}
// Partage entre la barre de saisie texte (text-turn) et la voix (voice-turn) : "learn" est le
// seul cas ou une session existe reellement (nouvelle ou poursuivie), cote serveur, quel que
// soit le canal d'entree (routeur d'intention, voir docs/Max_System_Prompt.md).
// openStepperWindow()/openObjectiveWindow() sont idempotentes (singleton).
async function handleRouteMessageResult(result: RouteMessageResponse): Promise<void> {
if (result.type === 'learn' && result.sessionId !== undefined) {
openStepperWindow()
const session = await getSession(result.sessionId)
broadcastSessionStatus(session.status)
if (result.ready && result.draft) {
broadcastObjectiveReady(result.sessionId, result.draft)
}
}
}
ipcMain.handle(
'voice-turn',
async (_event, inputAudio: ArrayBuffer, mimeType: string): Promise<VoiceTurnResult> => {
try {
requireLoggedIn()
const start = performance.now()
const transcript = await transcribeAudio(Buffer.from(inputAudio), mimeType)
const afterStt = performance.now()
@@ -194,8 +229,13 @@ app
return { ok: 'ignored', transcript }
}
const reply = await getAssistantReply(command)
// Meme point d'entree que la barre de saisie texte (POST /sessions/messages, routeur
// d'intention inclus) : une seule personnalite, un seul pipeline, quel que soit le canal
// d'entree.
const routed = await routeMessage(command)
const afterChat = performance.now()
const reply = sanitizeForSpeech(routed.reply)
await handleRouteMessageResult(routed)
const speech = await synthesizeSpeech(reply)
const afterTts = performance.now()
@@ -215,6 +255,35 @@ app
}
)
// Entree alternative au micro, PAS un chat (retour utilisateur direct) : le texte tape suit
// exactement le meme pipeline qu'une phrase prononcee (meme routeMessage,
// handleRouteMessageResult, personnalite, routeur d'intention) et Max repond TOUJOURS a voix
// haute via la file d'attente partagee (proactive-speech, jouee dans la fenetre avatar) -
// jamais de reponse affichee a l'ecrit, aucun historique de conversation.
ipcMain.handle('text-turn', async (_event, message: unknown): Promise<TextTurnResult> => {
try {
requireLoggedIn()
if (typeof message !== 'string' || message.trim().length === 0) {
throw new Error('message vide')
}
if (message.length > 2000) throw new Error('message trop long')
const routed = await routeMessage(message)
const reply = sanitizeForSpeech(routed.reply)
await handleRouteMessageResult(routed)
const speech = await synthesizeSpeech(reply)
const audio = speech.buffer.slice(
speech.byteOffset,
speech.byteOffset + speech.byteLength
) as ArrayBuffer
mainWindow?.webContents.send('proactive-speech', audio)
return { ok: true }
} catch (error) {
console.error('[text-turn]', error)
return { ok: false, error: error instanceof Error ? error.message : String(error) }
}
})
ipcMain.handle(
'auth-login',
async (_event, email: string, password: string): Promise<LoginResult> => {
@@ -267,28 +336,6 @@ app
}
)
ipcMain.handle(
'sessions:route-message',
async (_event, message: unknown): Promise<RouteMessageResponse> => {
requireLoggedIn()
if (typeof message !== 'string' || message.trim().length === 0) {
throw new Error('message vide')
}
if (message.length > 2000) throw new Error('message trop long')
const result = await routeMessage(message)
// "learn" est le seul cas ou une session existe reellement (nouvelle ou poursuivie) :
// c'est le seul moment ou le stepper doit apparaitre (routeur d'intention, voir
// docs/Max_System_Prompt.md). openStepperWindow() est idempotent (singleton).
if (result.type === 'learn' && result.sessionId !== undefined) {
openStepperWindow()
const session = await getSession(result.sessionId)
broadcastSessionStatus(session.status)
}
return result
}
)
ipcMain.handle(
'sessions:confirm-objective',
async (_event, id: unknown): Promise<SessionObjectiveResponse> => {
+54
View File
@@ -0,0 +1,54 @@
import { BrowserWindow } from 'electron'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'
import { SECURE_WEB_PREFERENCES, blockExternalNavigation } from './utils/windowSecurity'
let win: BrowserWindow | null = null
// Fenetre separee et dediee, independante du chat texte (retour utilisateur direct : la
// confirmation de l'objectif ne doit jamais dependre d'ouvrir la fenetre de conversation, y
// compris quand tout l'echange se fait au vocal) : affiche uniquement ObjectiveValidationCard.
// Meme pattern singleton que chatWindow.ts/stepperWindow.ts.
export function isObjectiveWindowOpen(): boolean {
return win !== null && !win.isDestroyed()
}
export function openObjectiveWindow(): void {
if (isObjectiveWindowOpen()) {
win?.show()
win?.focus()
return
}
win = new BrowserWindow({
width: 360,
height: 320,
title: 'Max — ton objectif',
frame: false,
transparent: true,
backgroundColor: '#00000000',
hasShadow: false,
alwaysOnTop: true,
resizable: false,
skipTaskbar: true,
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
...SECURE_WEB_PREFERENCES
}
})
blockExternalNavigation(win)
win.setAlwaysOnTop(true, 'floating')
win.on('closed', () => {
win = null
})
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
void win.loadURL(`${process.env['ELECTRON_RENDERER_URL']}#objective`)
} else {
void win.loadFile(join(__dirname, '../renderer/index.html'), { hash: 'objective' })
}
}
export function closeObjectiveWindow(): void {
if (isObjectiveWindowOpen()) win?.close()
}
+4 -3
View File
@@ -1,9 +1,9 @@
import { ElectronAPI } from '@electron-toolkit/preload'
import type { VoiceTurnResult } from '../shared/voice'
import type { TextTurnResult, VoiceTurnResult } from '../shared/voice'
import type { AuthStatus, LoginResult } from '../shared/auth'
import type {
ObjectiveDraft,
ObjectiveMessageResponse,
RouteMessageResponse,
SessionObjectiveResponse,
SessionResponse,
SessionStatus
@@ -14,7 +14,6 @@ export interface SessionsApi {
get: (id: number) => Promise<SessionResponse>
sendObjectiveMessage: (id: number, message: string) => Promise<ObjectiveMessageResponse>
confirmObjective: (id: number) => Promise<SessionObjectiveResponse>
routeMessage: (message: string) => Promise<RouteMessageResponse>
}
export interface ForgeAvatarApi {
@@ -22,6 +21,7 @@ export interface ForgeAvatarApi {
getWindowBounds: () => Promise<{ x: number; y: number; width: number; height: number }>
setWindowPosition: (x: number, y: number, width: number, height: number) => void
sendVoiceTurn: (audio: ArrayBuffer, mimeType: string) => Promise<VoiceTurnResult>
sendTextTurn: (message: string) => Promise<TextTurnResult>
openLoginWindow: () => void
logout: () => void
quitApp: () => void
@@ -31,6 +31,7 @@ export interface ForgeAvatarApi {
onProactiveSpeech: (callback: (audio: ArrayBuffer) => void) => () => void
onChatWindowClosed: (callback: () => void) => () => void
onSessionStatusChanged: (callback: (status: SessionStatus) => void) => () => void
onObjectiveReady: (callback: (sessionId: number, draft: ObjectiveDraft) => void) => () => void
onUpdateAvailable: (callback: () => void) => () => void
onUpdateReady: (callback: () => void) => () => void
login: (email: string, password: string) => Promise<LoginResult>
+16 -5
View File
@@ -1,10 +1,10 @@
import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
import type { VoiceTurnResult } from '../shared/voice'
import type { TextTurnResult, VoiceTurnResult } from '../shared/voice'
import type { AuthStatus, LoginResult } from '../shared/auth'
import type {
ObjectiveDraft,
ObjectiveMessageResponse,
RouteMessageResponse,
SessionObjectiveResponse,
SessionResponse,
SessionStatus
@@ -21,6 +21,8 @@ const api = {
},
sendVoiceTurn: (audio: ArrayBuffer, mimeType: string): Promise<VoiceTurnResult> =>
ipcRenderer.invoke('voice-turn', audio, mimeType),
sendTextTurn: (message: string): Promise<TextTurnResult> =>
ipcRenderer.invoke('text-turn', message),
openLoginWindow: (): void => {
ipcRenderer.send('open-login-window')
},
@@ -58,6 +60,17 @@ const api = {
ipcRenderer.on('session-status-changed', handler)
return () => ipcRenderer.removeListener('session-status-changed', handler)
},
onObjectiveReady: (
callback: (sessionId: number, draft: ObjectiveDraft) => void
): (() => void) => {
const handler = (
_event: Electron.IpcRendererEvent,
sessionId: number,
draft: ObjectiveDraft
): void => callback(sessionId, draft)
ipcRenderer.on('objective-ready', handler)
return () => ipcRenderer.removeListener('objective-ready', handler)
},
onUpdateAvailable: (callback: () => void): (() => void) => {
const handler = (): void => callback()
ipcRenderer.on('update:available', handler)
@@ -77,9 +90,7 @@ const api = {
sendObjectiveMessage: (id: number, message: string): Promise<ObjectiveMessageResponse> =>
ipcRenderer.invoke('sessions:send-objective-message', id, message),
confirmObjective: (id: number): Promise<SessionObjectiveResponse> =>
ipcRenderer.invoke('sessions:confirm-objective', id),
routeMessage: (message: string): Promise<RouteMessageResponse> =>
ipcRenderer.invoke('sessions:route-message', message)
ipcRenderer.invoke('sessions:confirm-objective', id)
}
}
+8 -18
View File
@@ -22,7 +22,6 @@ function App(): React.JSX.Element {
const [voiceState, setVoiceState] = useState<VoiceState>('idle')
const [voiceError, setVoiceError] = useState<string | null>(null)
const [updateStatus, setUpdateStatus] = useState<'available' | 'ready' | null>(null)
const sessionId = useSessionStore((state) => state.sessionId)
const restartSession = useSessionStore((state) => state.restart)
useEffect(() => window.api.onUpdateAvailable(() => setUpdateStatus('available')), [])
useEffect(() => window.api.onUpdateReady(() => setUpdateStatus('ready')), [])
@@ -37,7 +36,7 @@ function App(): React.JSX.Element {
if (state === 'recording' || state === 'processing') setVoiceError(null)
}, [])
useVoiceAssistant(avatar, listening, handleVoiceStateChange, handleVoiceError)
useProactiveSpeech(avatar)
useProactiveSpeech(avatar, setVoiceState)
useEffect(() => {
listeningRef.current = listening
@@ -66,26 +65,17 @@ function App(): React.JSX.Element {
// pour revalider loggedIn aupres du main process plutot que de le deduire de l'etat d'ecoute
// (l'utilisateur peut couper l'ecoute manuellement sans se deconnecter).
useEffect(() => window.api.onToggleListening(refreshAuthStatus), [refreshAuthStatus])
useEffect(() => window.api.onProactiveSpeech(() => setVoiceState('speaking')), [])
// Le stepper n'apparait que lorsqu'une session existe reellement (l'utilisateur a mentionne
// vouloir apprendre quelque chose, pas juste parce qu'il est connecte) : il vit desormais dans sa
// propre fenetre, ouverte directement par le main process des que sessions:create reussit (voir
// src/main/index.ts) - rien a faire ici.
// propre fenetre, ouverte directement par le main process des que le routeur d'intention detecte
// "learn" (voir src/main/index.ts) - rien a faire ici. Meme chose pour la fenetre de validation
// de l'objectif. La barre de saisie texte, elle, n'est qu'une entree alternative au micro (pas un
// chat, voir ChatPanel.tsx) : elle ne s'ouvre jamais automatiquement, uniquement sur demande
// explicite de l'utilisateur via le menu contextuel.
// Garde-fou : en usage normal, c'est l'ouverture du chat via le menu contextuel qui permet
// d'envoyer le premier message qui cree la session, donc la fenetre de chat est deja ouverte a ce
// moment-la. Ce filet de securite l'ouvre quand meme si une session demarre sans qu'elle le soit.
const previousSessionId = useRef<number | null>(null)
useEffect(() => {
if (previousSessionId.current === null && sessionId !== null && !chatOpen) {
window.api.toggleChatWindow()
setChatOpen(true)
}
previousSessionId.current = sessionId
}, [sessionId, chatOpen])
// Resynchronise la coche du menu si la fenetre de chat est fermee autrement que par ce menu.
// Resynchronise la coche du menu si la fenetre de saisie texte est fermee autrement que par ce
// menu (ex: Alt+F4).
useEffect(() => window.api.onChatWindowClosed(() => setChatOpen(false)), [])
const onContextMenu = useCallback((event: React.MouseEvent) => {
@@ -1,68 +1,25 @@
import { useEffect, useRef } from 'react'
import { useSessionStore } from '../stores/useSessionStore'
import ChatBubble from './ChatBubble'
import InputBar from './InputBar'
import ObjectiveValidationCard from './ObjectiveValidationCard'
/**
* Panneau de conversation (docs/Max_Composants_Frontend.md section 4) : historique de messages +
* carte de validation de l'objectif + barre de saisie. Rendu dans sa propre fenetre Electron
* separee et deplacable (voir src/main/chatWindow.ts et la route #chat dans main.tsx), distincte
* de la fenetre de l'avatar et de celle du PipelineStepper - voir le retour utilisateur qui
* demandait que chat et stepper soient des fenetres separees, deplacables independamment.
* N'affiche jamais un statut calcule localement.
* Ce n'est PAS un chat (retour utilisateur direct) : juste une barre de saisie alternative au
* micro, rendue dans sa propre fenetre Electron separee et deplacable (voir src/main/chatWindow.ts
* et la route #chat dans main.tsx). Le texte tape suit exactement le meme pipeline qu'une phrase
* prononcee a voix haute (meme routeur d'intention, meme Agent 1, voir "text-turn" dans
* src/main/index.ts) et Max repond TOUJOURS a voix haute via la file d'attente audio partagee -
* jamais de reponse affichee a l'ecrit, donc aucun historique de conversation ici.
*/
export default function ChatPanel(): React.JSX.Element {
const {
messages,
objectiveDraft,
objectiveReady,
objectiveConfirmed,
loading,
error,
sendMessage,
confirmObjective,
restart
} = useSessionStore()
const chatRef = useRef<HTMLDivElement | null>(null)
useEffect(() => {
const chat = chatRef.current
if (chat && typeof chat.scrollTo === 'function') {
chat.scrollTo({ top: chat.scrollHeight })
}
}, [messages])
const showObjectiveCard = objectiveReady && objectiveDraft !== null && !objectiveConfirmed
const { loading, error, sendTextTurn } = useSessionStore()
return (
<div className="chat-panel">
<div className="chat-panel__messages" ref={chatRef}>
{messages.map((message) => (
<ChatBubble
key={message.id}
role={message.role}
content={message.content}
timestamp={message.timestamp}
/>
))}
</div>
{error && <p className="chat-panel__error">{error}</p>}
{showObjectiveCard && objectiveDraft ? (
<ObjectiveValidationCard
objective={objectiveDraft}
onConfirm={confirmObjective}
onRestart={restart}
/>
) : (
<InputBar
placeholder="Explique a Max ce que tu veux apprendre..."
placeholder="Ecris ce que tu veux dire a Max..."
disabled={loading}
onSend={(text) => void sendMessage(text)}
onSend={(text) => void sendTextTurn(text)}
/>
)}
</div>
)
}
@@ -0,0 +1,29 @@
import { useEffect } from 'react'
import { useSessionStore } from '../stores/useSessionStore'
import ObjectiveValidationCard from './ObjectiveValidationCard'
/**
* Point d'entree de la fenetre dediee a la validation de l'objectif (voir
* src/main/objectiveWindow.ts et la route #objective dans main.tsx). Separee de la fenetre de
* chat : la confirmation de l'objectif ne doit jamais dependre d'ouvrir la conversation texte,
* y compris quand tout l'echange se fait au vocal (retour utilisateur direct). Cette fenetre vit
* dans son propre process renderer isole : son etat (sessionId, brouillon) lui est relaye par le
* main process des que l'Agent 1 produit un objectif pret a confirmer, quel que soit le canal
* d'entree (texte ou vocal, voir "objective-ready" dans src/main/index.ts).
*/
export default function ObjectiveWindowRoot(): React.JSX.Element | null {
const { objectiveDraft, objectiveReady, confirmObjective, restart } = useSessionStore()
const applyObjectiveReady = useSessionStore((state) => state.applyObjectiveReady)
useEffect(() => window.api.onObjectiveReady(applyObjectiveReady), [applyObjectiveReady])
if (!objectiveReady || objectiveDraft === null) return null
return (
<ObjectiveValidationCard
objective={objectiveDraft}
onConfirm={confirmObjective}
onRestart={restart}
/>
)
}
+6 -3
View File
@@ -12,15 +12,18 @@ import { createRoot } from 'react-dom/client'
import App from './App'
import ChatPanel from './components/ChatPanel'
import LoginView from './components/LoginView'
import ObjectiveWindowRoot from './components/ObjectiveWindowRoot'
import StepperView from './components/StepperView'
// Fenetres secondaires (login, chat, stepper - chacune ouverte/fermee par le main process) :
// chargent ce meme bundle avec un hash different pour afficher une autre vue que l'avatar. La
// fenetre avatar, chargee sans hash, continue de monter <App /> comme avant, sans aucun changement.
// Fenetres secondaires (login, chat, stepper, objectif - chacune ouverte/fermee par le main
// process) : chargent ce meme bundle avec un hash different pour afficher une autre vue que
// l'avatar. La fenetre avatar, chargee sans hash, continue de monter <App /> comme avant, sans
// aucun changement.
function renderForHash(): React.JSX.Element {
if (location.hash === '#login') return <LoginView />
if (location.hash === '#chat') return <ChatPanel />
if (location.hash === '#stepper') return <StepperView />
if (location.hash === '#objective') return <ObjectiveWindowRoot />
return <App />
}
@@ -1,75 +1,46 @@
import { create } from 'zustand'
import type { ObjectiveDraft, SessionStatus } from '../../../shared/session'
export interface ChatMessage {
id: string
role: 'max' | 'user'
content: string
timestamp: Date
}
interface SessionState {
sessionId: number | null
status: SessionStatus | null
messages: ChatMessage[]
objectiveDraft: ObjectiveDraft | null
objectiveReady: boolean
objectiveConfirmed: boolean
loading: boolean
error: string | null
sendMessage: (text: string) => Promise<void>
sendTextTurn: (text: string) => Promise<void>
confirmObjective: (objective: ObjectiveDraft) => Promise<void>
restart: () => void
setStatus: (status: SessionStatus) => void
}
function pushMessage(
messages: ChatMessage[],
role: ChatMessage['role'],
content: string
): ChatMessage[] {
return [...messages, { id: crypto.randomUUID(), role, content, timestamp: new Date() }]
applyObjectiveReady: (sessionId: number, draft: ObjectiveDraft) => void
}
/**
* Seule source de verite pour l'etat du pipeline cote renderer. Le statut de session n'est JAMAIS
* calcule ici : il vient toujours de ce que l'API a reellement renvoye (voir
* docs/Max_Composants_Frontend.md, regle de PipelineStepper).
* docs/Max_Composants_Frontend.md, regle de PipelineStepper). La barre de saisie texte n'est PAS
* un chat (retour utilisateur direct) : elle ne garde aucun historique de conversation, Max
* repond toujours a voix haute (voir ChatPanel.tsx et "text-turn" dans src/main/index.ts). La
* carte de validation de l'objectif vit dans sa propre fenetre dediee, alimentee par
* applyObjectiveReady quel que soit le canal d'entree (texte ou vocal).
*/
export const useSessionStore = create<SessionState>((set, get) => ({
sessionId: null,
status: null,
messages: [],
objectiveDraft: null,
objectiveReady: false,
objectiveConfirmed: false,
loading: false,
error: null,
sendMessage: async (text: string): Promise<void> => {
set((state) => ({
messages: pushMessage(state.messages, 'user', text),
loading: true,
error: null
}))
sendTextTurn: async (text: string): Promise<void> => {
set({ loading: true, error: null })
try {
// Point d'entree unique (docs/Max_System_Prompt.md, routeur d'intention) : ne cree une
// session que si le backend detecte reellement une intention d'apprendre. Un message de
// simple conversation ("salut ça va ?") ne demarre jamais de formation.
const result = await window.api.sessions.routeMessage(text)
if (result.type === 'learn' && result.sessionId !== undefined) {
const session = await window.api.sessions.get(result.sessionId)
set({ sessionId: result.sessionId, status: session.status })
const result = await window.api.sendTextTurn(text)
if (!result.ok) {
set({ loading: false, error: result.error })
return
}
set((state) => ({
messages: pushMessage(state.messages, 'max', result.reply),
objectiveReady: result.ready ?? false,
objectiveDraft: result.draft ?? state.objectiveDraft,
loading: false
}))
set({ loading: false })
} catch (error) {
set({
loading: false,
@@ -91,7 +62,6 @@ export const useSessionStore = create<SessionState>((set, get) => ({
const session = await window.api.sessions.get(sessionId)
set({
status: session.status,
objectiveConfirmed: true,
loading: false
})
} catch (error) {
@@ -107,21 +77,28 @@ export const useSessionStore = create<SessionState>((set, get) => ({
set({
sessionId: null,
status: null,
messages: [],
objectiveDraft: null,
objectiveReady: false,
objectiveConfirmed: false,
loading: false,
error: null
})
},
// Utilise uniquement par la fenetre du stepper (src/renderer/src/components/StepperView.tsx),
// qui vit dans un process renderer isole et n'a donc pas sa propre copie a jour de l'etat :
// le main process relaie le statut recu par la fenetre de chat via l'IPC
// "session-status-changed" (voir src/main/index.ts). La fenetre de chat, elle, continue de
// deriver son statut directement des reponses de ses propres appels API.
// Utilise par la fenetre du stepper (StepperView.tsx) : elle vit dans un process renderer isole
// et n'a donc pas sa propre copie a jour de l'etat. Le main process relaie le statut des qu'il
// change reellement cote serveur, quel que soit le canal d'entree (voir
// "session-status-changed" dans src/main/index.ts).
setStatus: (status: SessionStatus): void => {
set({ status })
},
// Utilise uniquement par la fenetre dediee a la validation de l'objectif
// (ObjectiveWindowRoot.tsx), separee de la barre de saisie texte sur demande directe de
// l'utilisateur : la confirmation ne doit jamais dependre d'ouvrir cette barre, y compris quand
// tout l'echange se fait au vocal. Alimentee par le main process des que l'Agent 1 produit un
// objectif pret a confirmer, quel que soit le canal d'entree (texte ou vocal, voir
// "objective-ready" dans src/main/index.ts, declenche depuis le meme handleRouteMessageResult).
applyObjectiveReady: (sessionId: number, draft: ObjectiveDraft): void => {
set({ sessionId, objectiveDraft: draft, objectiveReady: true })
}
}))
+6 -18
View File
@@ -356,12 +356,12 @@
pointer-events: none;
}
/* ── Fenetre de chat (fenetre Electron separee et deplacable, voir src/main/chatWindow.ts) ──
Remplit entierement sa propre fenetre transparente : le cadre arrondi/l'ombre donnent
l'apparence d'une carte flottante malgre la fenetre rectangulaire sous-jacente. La fenetre
entiere est une zone de glisser-deplacer (-webkit-app-region: drag), sauf les zones
interactives (messages, saisie, carte de validation) qui doivent rester cliquables/
selectionnables. */
/* ── Barre de saisie texte (fenetre Electron separee et deplacable, voir src/main/chatWindow.ts) ──
Ce n'est PAS un chat (retour utilisateur direct) : juste une entree alternative au micro, sans
historique de conversation affiche. Remplit entierement sa propre fenetre transparente : le
cadre arrondi/l'ombre donnent l'apparence d'une carte flottante malgre la fenetre rectangulaire
sous-jacente. La fenetre entiere est une zone de glisser-deplacer (-webkit-app-region: drag),
sauf la zone de saisie qui doit rester cliquable/selectionnable. */
.chat-panel {
width: 100%;
@@ -378,18 +378,6 @@
-webkit-app-region: drag;
}
.chat-panel__messages {
flex: 1;
min-height: 60px;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: var(--space-2);
scrollbar-width: thin;
scrollbar-color: var(--surface-2) transparent;
-webkit-app-region: no-drag;
}
.chat-panel__error {
margin: 0;
font-size: var(--text-sm);
@@ -2,16 +2,20 @@ import { useEffect, type RefObject } from 'react'
import type { AvatarHandle } from '../components/AvatarViewer'
import { bindSpeechAvatar, enqueueSpeech } from './speechQueue'
// Joue une reponse de l'IA declenchee sans question de l'utilisateur (ex: rappel programme,
// commentaire immediat pendant qu'un outil s'execute), independamment de l'etat d'activation de
// l'ecoute vocale. Passe par la file d'attente partagee (speechQueue.ts) pour ne jamais chevaucher
// la reponse finale d'un tour de voix (constate en test reel : deux chemins audio independants se
// chevauchaient avant cette unification).
export function useProactiveSpeech(avatarRef: RefObject<AvatarHandle | null>): void {
// Joue une reponse de l'IA declenchee sans micro actif (ex: reponse a un message tape dans la
// barre de saisie texte - voir "text-turn" dans src/main/index.ts - ou un rappel programme),
// independamment de l'etat d'activation de l'ecoute vocale. Passe par la file d'attente partagee
// (speechQueue.ts) pour ne jamais chevaucher la reponse finale d'un tour de voix (constate en test
// reel : deux chemins audio independants se chevauchaient avant cette unification).
export function useProactiveSpeech(
avatarRef: RefObject<AvatarHandle | null>,
onStateChange?: (state: 'speaking' | 'idle') => void
): void {
useEffect(() => {
bindSpeechAvatar(avatarRef)
return window.api.onProactiveSpeech((audio) => {
void enqueueSpeech(audio)
onStateChange?.('speaking')
void enqueueSpeech(audio).then(() => onStateChange?.('idle'))
})
}, [avatarRef])
}, [avatarRef, onStateChange])
}
+6
View File
@@ -2,3 +2,9 @@ export type VoiceTurnResult =
| { ok: true; transcript: string; reply: string; audio: ArrayBuffer }
| { ok: 'ignored'; transcript: string }
| { ok: false; error: string }
// Reponse d'un message tape dans la barre de saisie texte (voir "text-turn" dans
// src/main/index.ts) : ce n'est pas un chat (retour utilisateur direct) - Max repond TOUJOURS a
// voix haute via la file d'attente audio partagee (proactive-speech), jamais par du texte affiche.
// Le resultat ne contient donc ni reponse ni audio, seulement si l'envoi a reussi.
export type TextTurnResult = { ok: true } | { ok: false; error: string }
@@ -234,13 +234,13 @@ describe('<App />', () => {
expect(screen.queryByLabelText('Message')).not.toBeInTheDocument()
})
it('should open the chat window automatically if a session starts without it (safety net)', async () => {
it('should NOT open the text input window automatically when a session starts (not a chat - only explicit user request opens it)', async () => {
getAuthStatus.mockResolvedValue({ loggedIn: true, email: 'william@example.com' })
render(<App />)
await waitFor(() => expect(getAuthStatus).toHaveBeenCalled())
act(() => useSessionStore.setState({ sessionId: 1, status: 'objective_discovery' }))
expect(toggleChatWindow).toHaveBeenCalledOnce()
expect(toggleChatWindow).not.toHaveBeenCalled()
})
})
@@ -1,66 +1,47 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { render, screen, fireEvent } from '@testing-library/react'
import ChatPanel from '../../../src/renderer/src/components/ChatPanel'
import { useSessionStore } from '../../../src/renderer/src/stores/useSessionStore'
const get = vi.fn()
const routeMessage = vi.fn()
const confirmObjective = vi.fn()
const sendTextTurn = vi.fn()
const notifySessionEnded = vi.fn()
beforeEach(() => {
vi.clearAllMocks()
;(window as unknown as { api: Record<string, unknown> }).api = {
sessions: { get, routeMessage, confirmObjective },
sendTextTurn,
notifySessionEnded
}
useSessionStore.getState().restart()
})
/**
* Ce n'est PAS un chat (retour utilisateur direct) : juste une barre de saisie alternative au
* micro. Le texte tape suit le meme pipeline qu'une phrase prononcee et Max repond toujours a
* voix haute - aucune bulle, aucun historique de conversation affiche ici.
*/
describe('<ChatPanel />', () => {
it('should show an input bar and no pipeline steps before any session exists', () => {
it('should show only the message input, no conversation history', () => {
render(<ChatPanel />)
expect(screen.getByLabelText('Message')).toBeInTheDocument()
expect(screen.queryByText('Objectif')).not.toBeInTheDocument()
expect(screen.queryByText('Ton objectif de formation')).not.toBeInTheDocument()
})
it('should send the first message, creating a session, and render the conversation', async () => {
routeMessage.mockResolvedValueOnce({
type: 'learn',
sessionId: 1,
reply: 'Quel est ton sujet ?',
ready: false
})
get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' })
it('should submit the typed text via text-turn and clear the field', async () => {
sendTextTurn.mockResolvedValueOnce({ ok: true })
render(<ChatPanel />)
fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'Je veux apprendre' } })
fireEvent.change(screen.getByLabelText('Message'), {
target: { value: 'Je veux apprendre la facturation' }
})
fireEvent.click(screen.getByRole('button', { name: 'Envoyer le message' }))
expect(await screen.findByText('Je veux apprendre')).toBeInTheDocument()
expect(await screen.findByText('Quel est ton sujet ?')).toBeInTheDocument()
expect(sendTextTurn).toHaveBeenCalledWith('Je veux apprendre la facturation')
expect(await screen.findByDisplayValue('')).toBeInTheDocument()
})
it('should show the ObjectiveValidationCard instead of the input bar once the agent is ready', async () => {
routeMessage.mockResolvedValueOnce({
type: 'learn',
sessionId: 1,
reply: 'Voici le recap',
ready: true,
draft: { subject: 's', professionalGoal: 'g', duration: '1 semaine' }
})
get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' })
render(<ChatPanel />)
fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'message' } })
fireEvent.click(screen.getByRole('button', { name: 'Envoyer le message' }))
await waitFor(() => expect(screen.getByText('Ton objectif de formation')).toBeInTheDocument())
expect(screen.queryByLabelText('Message')).not.toBeInTheDocument()
})
it('should show the store error message when a call fails', async () => {
routeMessage.mockRejectedValueOnce(new Error('Max API injoignable'))
it('should show the store error message when the backend reports a failure', async () => {
sendTextTurn.mockResolvedValueOnce({ ok: false, error: 'Max API injoignable' })
render(<ChatPanel />)
fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'message' } })
@@ -0,0 +1,73 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'
import ObjectiveWindowRoot from '../../../src/renderer/src/components/ObjectiveWindowRoot'
import { useSessionStore } from '../../../src/renderer/src/stores/useSessionStore'
const confirmObjective = vi.fn()
const notifySessionEnded = vi.fn()
let objectiveReadyCallback: ((sessionId: number, draft: unknown) => void) | undefined
const onObjectiveReady = vi.fn((callback: (sessionId: number, draft: unknown) => void) => {
objectiveReadyCallback = callback
return () => {}
})
beforeEach(() => {
vi.clearAllMocks()
objectiveReadyCallback = undefined
;(window as unknown as { api: Record<string, unknown> }).api = {
sessions: { confirmObjective, get: vi.fn() },
notifySessionEnded,
onObjectiveReady
}
useSessionStore.getState().restart()
})
/**
* Fenetre independante du chat texte (retour utilisateur direct : la confirmation de l'objectif
* ne doit jamais dependre d'ouvrir la conversation, y compris quand tout l'echange se fait au
* vocal). Son etat vient exclusivement du relais "objective-ready" du main process.
*/
describe('<ObjectiveWindowRoot />', () => {
it('should render nothing before the main process relays a ready objective', () => {
const { container } = render(<ObjectiveWindowRoot />)
expect(container).toBeEmptyDOMElement()
})
it('should show the card once the main process relays a ready objective (text or voice, same path)', () => {
render(<ObjectiveWindowRoot />)
act(() =>
objectiveReadyCallback?.(1, {
subject: 'Facturation freelance',
professionalGoal: 'Facturer sans erreur',
duration: '2 semaines'
})
)
expect(screen.getByText('Ton objectif de formation')).toBeInTheDocument()
expect(screen.getByText('Facturation freelance')).toBeInTheDocument()
})
it('should confirm the objective via the store, independently of any chat window', async () => {
confirmObjective.mockResolvedValueOnce({})
;(window as unknown as { api: { sessions: Record<string, unknown> } }).api.sessions.get = vi
.fn()
.mockResolvedValueOnce({ id: 1, status: 'objective_validated' })
render(<ObjectiveWindowRoot />)
act(() =>
objectiveReadyCallback?.(1, {
subject: 'Facturation freelance',
professionalGoal: 'Facturer sans erreur',
duration: '2 semaines'
})
)
fireEvent.click(
screen.getByRole('button', { name: "C'est exactement ca, confirmer l'objectif" })
)
await waitFor(() => expect(confirmObjective).toHaveBeenCalledWith(1))
expect(await screen.findByText(/Objectif enregistre/)).toBeInTheDocument()
})
})
@@ -2,116 +2,76 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
import { useSessionStore } from '../../../../src/renderer/src/stores/useSessionStore'
const get = vi.fn()
const routeMessage = vi.fn()
const sendTextTurn = vi.fn()
const confirmObjective = vi.fn()
const notifySessionEnded = vi.fn()
beforeEach(() => {
vi.clearAllMocks()
;(window as unknown as { api: Record<string, unknown> }).api = {
sessions: { get, routeMessage, confirmObjective },
sessions: { get, confirmObjective },
sendTextTurn,
notifySessionEnded
}
useSessionStore.getState().restart()
})
/**
* La barre de saisie texte n'est PAS un chat (retour utilisateur direct) : elle ne garde aucun
* historique de conversation, et Max repond toujours a voix haute (voir text-turn dans
* src/main/index.ts). Le store ne fait donc que suivre le succes/l'echec de l'envoi, rien de plus.
*/
describe('useSessionStore', () => {
it('should not create a session when the backend classifies the message as chat', async () => {
routeMessage.mockResolvedValueOnce({ type: 'chat', reply: 'Salut, comment puis-je aider ?' })
it('should send a typed message via text-turn and clear the loading state on success', async () => {
sendTextTurn.mockResolvedValueOnce({ ok: true })
await useSessionStore.getState().sendMessage('Salut ça va ?')
await useSessionStore.getState().sendTextTurn('Je veux apprendre la facturation')
expect(routeMessage).toHaveBeenCalledWith('Salut ça va ?')
expect(get).not.toHaveBeenCalled()
expect(sendTextTurn).toHaveBeenCalledWith('Je veux apprendre la facturation')
const state = useSessionStore.getState()
expect(state.sessionId).toBeNull()
expect(state.messages.map((m) => m.role)).toEqual(['user', 'max'])
expect(state.loading).toBe(false)
expect(state.error).toBeNull()
})
it('should set the session id and fetch the fresh status when the backend starts a training session', async () => {
routeMessage.mockResolvedValueOnce({
type: 'learn',
sessionId: 1,
reply: 'Quel est ton sujet ?',
ready: false
})
get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' })
it('should set an error when the backend reports a failure', async () => {
sendTextTurn.mockResolvedValueOnce({ ok: false, error: 'Max API injoignable' })
await useSessionStore.getState().sendMessage('Je veux apprendre la facturation')
expect(get).toHaveBeenCalledWith(1)
const state = useSessionStore.getState()
expect(state.sessionId).toBe(1)
expect(state.status).toBe('objective_discovery')
expect(state.messages.map((m) => m.role)).toEqual(['user', 'max'])
})
it('should reuse the same session id on subsequent messages of an ongoing training', async () => {
routeMessage.mockResolvedValueOnce({
type: 'learn',
sessionId: 1,
reply: 'Quel est ton sujet ?',
ready: false
})
get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' })
await useSessionStore.getState().sendMessage('premier message')
routeMessage.mockResolvedValueOnce({
type: 'learn',
sessionId: 1,
reply: 'Et ton but professionnel ?',
ready: false
})
get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' })
await useSessionStore.getState().sendMessage('second message')
expect(routeMessage).toHaveBeenCalledTimes(2)
expect(useSessionStore.getState().sessionId).toBe(1)
})
it('should store the draft and ready flag once the agent is ready to confirm', async () => {
const draft = {
subject: 'Facturation freelance',
professionalGoal: 'Facturer sans erreur',
duration: '2 semaines'
}
routeMessage.mockResolvedValueOnce({
type: 'learn',
sessionId: 1,
reply: 'Voici le recap',
ready: true,
draft
})
get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' })
await useSessionStore.getState().sendMessage('message')
const state = useSessionStore.getState()
expect(state.objectiveReady).toBe(true)
expect(state.objectiveDraft).toEqual(draft)
})
it('should set an error and stop loading when sending a message fails', async () => {
routeMessage.mockRejectedValueOnce(new Error('Max API injoignable'))
await useSessionStore.getState().sendMessage('message')
await useSessionStore.getState().sendTextTurn('message')
const state = useSessionStore.getState()
expect(state.error).toBe('Max API injoignable')
expect(state.loading).toBe(false)
})
it('should confirm the objective and refresh the session status', async () => {
routeMessage.mockResolvedValueOnce({
type: 'learn',
sessionId: 1,
reply: 'Recap',
ready: true,
draft: { subject: 's', professionalGoal: 'g', duration: '1 semaine' }
it('should set an error and stop loading when sending a message throws', async () => {
sendTextTurn.mockRejectedValueOnce(new Error('Max API injoignable'))
await useSessionStore.getState().sendTextTurn('message')
const state = useSessionStore.getState()
expect(state.error).toBe('Max API injoignable')
expect(state.loading).toBe(false)
})
get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' })
await useSessionStore.getState().sendMessage('message')
it('should apply an objective-ready broadcast from the main process (used by the dedicated objective window)', () => {
const draft = {
subject: 'Facturation freelance',
professionalGoal: 'Facturer sans erreur',
duration: '2 semaines'
}
useSessionStore.getState().applyObjectiveReady(1, draft)
const state = useSessionStore.getState()
expect(state.sessionId).toBe(1)
expect(state.objectiveReady).toBe(true)
expect(state.objectiveDraft).toEqual(draft)
})
it('should confirm the objective and refresh the session status', async () => {
useSessionStore
.getState()
.applyObjectiveReady(1, { subject: 's', professionalGoal: 'g', duration: '1 semaine' })
confirmObjective.mockResolvedValueOnce({})
get.mockResolvedValueOnce({ id: 1, status: 'objective_validated' })
@@ -122,7 +82,6 @@ describe('useSessionStore', () => {
expect(confirmObjective).toHaveBeenCalledWith(1)
const state = useSessionStore.getState()
expect(state.objectiveConfirmed).toBe(true)
expect(state.status).toBe('objective_validated')
})
@@ -135,15 +94,10 @@ describe('useSessionStore', () => {
expect(useSessionStore.getState().error).toBe('Aucune session en cours')
})
it('should reset all state on restart and notify the main process', async () => {
routeMessage.mockResolvedValueOnce({
type: 'learn',
sessionId: 1,
reply: 'ok',
ready: false
})
get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' })
await useSessionStore.getState().sendMessage('message')
it('should reset all state on restart and notify the main process', () => {
useSessionStore
.getState()
.applyObjectiveReady(1, { subject: 's', professionalGoal: 'g', duration: '1 semaine' })
notifySessionEnded.mockClear()
useSessionStore.getState().restart()
@@ -151,7 +105,8 @@ describe('useSessionStore', () => {
expect(notifySessionEnded).toHaveBeenCalledOnce()
const state = useSessionStore.getState()
expect(state.sessionId).toBeNull()
expect(state.messages).toEqual([])
expect(state.objectiveReady).toBe(false)
expect(state.objectiveDraft).toBeNull()
})
it('should set the status directly (used by the stepper window to sync with the main process)', () => {
@@ -31,4 +31,16 @@ describe('useProactiveSpeech()', () => {
onProactiveSpeechCallback?.(audio)
expect(enqueueSpeech).toHaveBeenCalledWith(audio)
})
it('should report speaking then idle around playback (used by the avatar status indicator for text-turn replies)', async () => {
const onStateChange = vi.fn()
renderHook(() => useProactiveSpeech({ current: null }, onStateChange))
onProactiveSpeechCallback?.(new ArrayBuffer(4))
expect(onStateChange).toHaveBeenCalledWith('speaking')
await Promise.resolve()
await Promise.resolve()
expect(onStateChange).toHaveBeenCalledWith('idle')
})
})
@@ -0,0 +1,78 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { EventEmitter } from 'node:events'
vi.mock('@electron-toolkit/utils', () => ({ is: { dev: false } }))
class FakeWebContents extends EventEmitter {}
class FakeBrowserWindow extends EventEmitter {
webContents = new FakeWebContents()
show = vi.fn()
focus = vi.fn()
setAlwaysOnTop = vi.fn()
loadURL = vi.fn()
loadFile = vi.fn()
close = vi.fn()
destroyed = false
isDestroyed(): boolean {
return this.destroyed
}
}
let lastWindow: FakeBrowserWindow | null = null
function createBrowserWindow(): FakeBrowserWindow {
const window = new FakeBrowserWindow()
lastWindow = window
return window
}
vi.mock('electron', () => ({
BrowserWindow: vi.fn(createBrowserWindow)
}))
const { openObjectiveWindow, closeObjectiveWindow, isObjectiveWindowOpen } =
await import('../../src/main/objectiveWindow')
describe('objectiveWindow', () => {
beforeEach(() => {
lastWindow?.emit('closed')
vi.clearAllMocks()
lastWindow = null
})
describe('openObjectiveWindow()', () => {
it('should create and load a window on the #objective hash', () => {
openObjectiveWindow()
expect(lastWindow?.loadFile).toHaveBeenCalledWith(
expect.stringContaining('index.html'),
expect.objectContaining({ hash: 'objective' })
)
expect(isObjectiveWindowOpen()).toBe(true)
})
it('should reuse the existing window and bring it to front on a second call', () => {
openObjectiveWindow()
const firstWindow = lastWindow
openObjectiveWindow()
expect(lastWindow).toBe(firstWindow)
expect(firstWindow?.show).toHaveBeenCalled()
expect(firstWindow?.focus).toHaveBeenCalled()
})
})
describe('closeObjectiveWindow()', () => {
it('should close the window when one is open', () => {
openObjectiveWindow()
closeObjectiveWindow()
expect(lastWindow?.close).toHaveBeenCalled()
})
it('should do nothing when no window is open', () => {
expect(() => closeObjectiveWindow()).not.toThrow()
expect(isObjectiveWindowOpen()).toBe(false)
})
})
})
-90
View File
@@ -1,90 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { setCurrentUserEmail, clearSession } from '../../src/main/auth/session'
vi.mock('@electron-toolkit/utils', () => ({ is: { dev: false } }))
const { getAssistantReply } = await import('../../src/main/ai/openrouter')
function okResponse(body: unknown): Response {
return { ok: true, json: () => Promise.resolve(body) } as Response
}
function textMessage(content: string): unknown {
return { choices: [{ message: { role: 'assistant', content } }] }
}
describe('getAssistantReply()', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.stubGlobal('fetch', vi.fn())
process.env.OPENROUTER_API_KEY = 'test-key'
setCurrentUserEmail('test@example.com')
})
afterEach(() => {
clearSession()
})
it('should throw when the API key is missing', async () => {
delete process.env.OPENROUTER_API_KEY
await expect(getAssistantReply('Bonjour')).rejects.toThrow(/OPENROUTER_API_KEY/)
})
it('should return the assistant text reply when the API responds successfully', async () => {
vi.mocked(fetch).mockResolvedValue(okResponse(textMessage('Bonjour, comment puis-je aider ?')))
const reply = await getAssistantReply('Salut Max')
expect(reply).toBe('Bonjour, comment puis-je aider ?')
})
it('should transparently fall back to the secondary model when the primary one errors out', async () => {
vi.mocked(fetch)
.mockResolvedValueOnce({
ok: false,
status: 503,
text: () => Promise.resolve('unavailable')
} as Response)
.mockResolvedValueOnce(okResponse(textMessage('Reponse du modele de secours.')))
const reply = await getAssistantReply('question')
expect(reply).toBe('Reponse du modele de secours.')
})
it('should treat a 200 response with no choices as a failure and try the other model', async () => {
vi.mocked(fetch)
.mockResolvedValueOnce(okResponse({}))
.mockResolvedValueOnce(okResponse(textMessage('Ca marche quand meme.')))
const reply = await getAssistantReply('question')
expect(reply).toBe('Ca marche quand meme.')
})
it('should throw a clear error when both models fail', async () => {
vi.mocked(fetch).mockResolvedValue({
ok: false,
status: 500,
text: () => Promise.resolve('panne totale')
} as Response)
await expect(getAssistantReply('question')).rejects.toThrow(/Aucun modele disponible/)
})
it('should replace a leaked English boilerplate reply with the safe fallback message', async () => {
vi.mocked(fetch).mockResolvedValue(
okResponse(
textMessage(
'Use the results below to formulate an answer to the user question with additional information needed'
)
)
)
const reply = await getAssistantReply('question')
expect(reply).toMatch(/bien avance avec toi/)
})
it('should replace a degenerate (non-Latin) reply with the safe fallback message', async () => {
vi.mocked(fetch).mockResolvedValue(
okResponse(textMessage('的问题是什么呢我不知道该怎么办才好呢'))
)
const reply = await getAssistantReply('question')
expect(reply).toMatch(/bien avance avec toi/)
})
})
@@ -0,0 +1,55 @@
import { describe, it, expect } from 'vitest'
import {
containsLeakedBoilerplate,
isDegenerateText,
sanitizeForSpeech,
SPEECH_FALLBACK_REPLY
} from '../../src/main/ai/speechSafety'
describe('containsLeakedBoilerplate()', () => {
it('should detect leaked English model boilerplate with no French words', () => {
expect(
containsLeakedBoilerplate(
'Use the results below to formulate an answer to the user question with additional information needed'
)
).toBe(true)
})
it('should not flag a normal French reply', () => {
expect(containsLeakedBoilerplate('Bonjour, comment puis-je aider ?')).toBe(false)
})
})
describe('isDegenerateText()', () => {
it('should detect a non-Latin corrupted reply', () => {
expect(isDegenerateText('的问题是什么呢我不知道该怎么办才好呢')).toBe(true)
})
it('should not flag a normal French reply', () => {
expect(isDegenerateText('Bonjour, comment puis-je aider ?')).toBe(false)
})
it('should not flag an empty string', () => {
expect(isDegenerateText('')).toBe(false)
})
})
describe('sanitizeForSpeech()', () => {
it('should replace a leaked English boilerplate reply with the safe fallback message', () => {
expect(
sanitizeForSpeech(
'Use the results below to formulate an answer to the user question with additional information needed'
)
).toBe(SPEECH_FALLBACK_REPLY)
})
it('should replace a degenerate (non-Latin) reply with the safe fallback message', () => {
expect(sanitizeForSpeech('的问题是什么呢我不知道该怎么办才好呢')).toBe(SPEECH_FALLBACK_REPLY)
})
it('should return the original text when it is a normal French reply', () => {
expect(sanitizeForSpeech('Bonjour, comment puis-je aider ?')).toBe(
'Bonjour, comment puis-je aider ?'
)
})
})