Compare commits
50
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
23052b8afd | ||
|
|
4d8236b8e5 | ||
|
|
83c50575b1 | ||
|
|
d9618defe6 | ||
|
|
af87d169ac | ||
|
|
755bc07d18 | ||
|
|
5c00976e8f | ||
|
|
b5cdc30207 | ||
|
|
85da9fcad0 | ||
|
|
4b45c4a644 | ||
|
|
ef0015fc2b | ||
|
|
a0f4d9df1e | ||
|
|
73bc2587b8 | ||
|
|
78d6547037 | ||
|
|
7179743d4e | ||
|
|
ce25d3f290 | ||
|
|
dc368a32f0 | ||
|
|
c1440f83c0 | ||
|
|
4da3254d0a | ||
|
|
6e8a9d2f0d | ||
|
|
b072960012 | ||
|
|
cb9b4177e4 | ||
|
|
242aa1d708 | ||
|
|
717729242f | ||
|
|
919b82ef37 | ||
|
|
309db80add | ||
|
|
ed32c21f24 | ||
|
|
050aad9469 | ||
|
|
00619add9f | ||
|
|
ef4cd41ad4 | ||
|
|
d46a1ca69f | ||
|
|
253c65b00a | ||
|
|
0d85a8a85e | ||
|
|
8c761c81a9 | ||
|
|
d0c730fa6f | ||
|
|
acdd8a08d3 | ||
|
|
6cb38a2f36 | ||
|
|
0cc277049e | ||
|
|
cf92418bad | ||
|
|
c99b01a902 | ||
|
|
a55323a3fa | ||
|
|
7c480e1ce4 | ||
|
|
bae5ace70c | ||
|
|
b321dff3bd | ||
|
|
b8aec9ed6b | ||
|
|
83043b5819 | ||
|
|
2363dc8164 | ||
|
|
9aa5abc121 | ||
|
|
885e24d037 | ||
|
|
605f9070a8 |
@@ -0,0 +1,5 @@
|
|||||||
|
# Variables lues par docker-compose.yml a la racine du depot (service "postgres").
|
||||||
|
# Copier ce fichier en ".env" (jamais commite) et renseigner de vraies valeurs.
|
||||||
|
POSTGRES_USER=max_api
|
||||||
|
POSTGRES_PASSWORD=
|
||||||
|
POSTGRES_DB=max_api
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
out
|
||||||
|
coverage
|
||||||
|
.DS_Store
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
@@ -6,33 +6,87 @@
|
|||||||
|
|
||||||
## 1. Contexte du projet
|
## 1. Contexte du projet
|
||||||
|
|
||||||
Max est une application de bureau (Windows, Mac, Linux) et mobile (Android) construite avec :
|
Max est une application de bureau (Windows, Mac, Linux) construite avec Electron + React TypeScript. Max est **exclusivement un coach de formation pour freelances**. Il n'y a plus de mode Assistant ni de sélection de mode — Max démarre directement en mode Coach.
|
||||||
|
|
||||||
- **Electron 28+** — shell desktop
|
### Stack technique
|
||||||
- **React 18 + TypeScript 5** — interface utilisateur
|
|
||||||
- **Vite** — bundler
|
|
||||||
- **Three.js + GLTFLoader** — rendu 3D de l'avatar
|
|
||||||
- **Zustand** — state management
|
|
||||||
- **SQLite (better-sqlite3)** — stockage local
|
|
||||||
- **OpenRouter + DeepSeek** — LLM via function calling
|
|
||||||
- **ElevenLabs** — TTS + STT
|
|
||||||
- **WebSocket + desktopCapturer** — captures d'écran (mode Coach)
|
|
||||||
|
|
||||||
L'app propose deux modes payants :
|
| Couche | Technologie |
|
||||||
|
| --- | --- |
|
||||||
|
| Desktop shell | Electron 28+ |
|
||||||
|
| UI | React 18 + TypeScript 5 + Vite |
|
||||||
|
| Avatar 3D | Three.js + GLTFLoader + AnimationMixer |
|
||||||
|
| State management | Zustand |
|
||||||
|
| LLM | OpenRouter + DeepSeek (principal) + Qwen (secours) |
|
||||||
|
| TTS + STT | ElevenLabs (proxy backend) |
|
||||||
|
| Vision écran | desktopCapturer (Electron) |
|
||||||
|
| Backend | NestJS 11 + Prisma 6 + PostgreSQL 16 (dossier `Max API/`) |
|
||||||
|
| Base de données session | PostgreSQL via Prisma (côté backend) |
|
||||||
|
|
||||||
- **Mode Coach** — tuteur socratique avec vision écran, protocole pédagogique strict
|
### Ce que Max fait
|
||||||
- **Mode Assistant** — gestion emails, veille, transcription, planification
|
|
||||||
|
Max forme les freelances sur des compétences précises via un pipeline de 7 agents séquentiels. Chaque agent est un appel API séparé avec un system prompt ultra-spécialisé. Le résultat de chaque agent est stocké en base de données et passé au suivant.
|
||||||
|
|
||||||
|
### Pipeline des 7 agents
|
||||||
|
|
||||||
|
| # | Agent | Rôle |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 1 | Objectif | Dialogue socratique — révèle et valide l'objectif du freelance (3 piliers : sujet, but professionnel, durée) |
|
||||||
|
| 2 | Recherche Cartographie | Recherche légère — carte des concepts clés du domaine pour construire l'évaluation de niveau |
|
||||||
|
| 3 | Niveau | Évaluation du niveau réel via questions situationnelles (jamais un QCM) |
|
||||||
|
| 4 | Recherche Approfondie | Corpus complet de sources fiables, parallélisé par sous-thème, calibré sur le niveau détecté |
|
||||||
|
| 5 | Plan | Curriculum en N modules via Backward Design — objectif final d'abord, modules ensuite |
|
||||||
|
| 6 | Rédacteur | Rédige un module à la fois — 6 sections obligatoires, méthode I Do/We Do/You Do |
|
||||||
|
| 7 | Évaluation finale | Simulation professionnelle en deux temps : entretien client simulé + cas de mission réel |
|
||||||
|
|
||||||
|
### State machine de session
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
type SessionStatus =
|
||||||
|
| 'objective_discovery' // Agent 1 — dialogue en cours
|
||||||
|
| 'objective_validated' // Agent 1 — objectif confirmé par l'utilisateur
|
||||||
|
| 'mapping' // Agent 2 — cartographie des concepts
|
||||||
|
| 'level_assessment' // Agent 3 — évaluation du niveau
|
||||||
|
| 'researching' // Agent 4 — recherche approfondie (parallèle)
|
||||||
|
| 'planning' // Agent 5 — construction du curriculum
|
||||||
|
| 'teaching' // Agent 6 — module en cours (currentModuleIndex)
|
||||||
|
| 'evaluating' // Agent 7 — évaluation finale
|
||||||
|
| 'completed' // Compétence validée
|
||||||
|
```
|
||||||
|
|
||||||
|
Aucun agent ne démarre si l'agent précédent n'a pas produit et stocké son output en base. La state machine est gérée côté code — jamais côté LLM.
|
||||||
|
|
||||||
|
### Schéma de base de données — une table par agent
|
||||||
|
|
||||||
|
| Table | Agent | Champs principaux |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `session` | Mère | `session_id`, `user_id`, `status`, `created_at`, `updated_at` |
|
||||||
|
| `session_objective` | Agent 1 | `subject`, `professional_goal`, `duration`, `trigger`, `validated_at` |
|
||||||
|
| `session_concept_map` | Agent 2 | `concepts` (JSON), `sources_used`, `completed_at` |
|
||||||
|
| `session_level_assessment` | Agent 3 | `questions_asked`, `user_answers`, `mastered_concepts`, `gap_concepts`, `unknown_concepts`, `overall_level`, `completed_at` |
|
||||||
|
| `session_research` | Agent 4 | `corpus` (JSON), `subtopics_covered`, `sources_count`, `completed_at` |
|
||||||
|
| `session_curriculum` | Agent 5 | `modules` (JSON), `total_modules`, `total_duration`, `validated_at` |
|
||||||
|
| `session_module` | Agent 6 | `module_index`, `title`, `content` (JSON), `status`, `completed_at` |
|
||||||
|
| `session_evaluation` | Agent 7 | `interview_score`, `practical_score`, `validated`, `feedback` (JSON), `completed_at` |
|
||||||
|
| `freelance_profile` | Profil / Veille | `domains`, `stack`, `seniority_level`, `competences_acquired`, `veille_*` |
|
||||||
|
| `veille_signal` | Agent Veille | `type`, `competence`, `sources`, `relevance_score`, `action_taken` |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. Architecture obligatoire
|
## 2. Architecture obligatoire
|
||||||
|
|
||||||
|
### Monorepo
|
||||||
|
|
||||||
```
|
```
|
||||||
|
/ ← Racine du dépôt Gitea
|
||||||
|
Max Avatar/ ← Application Electron (toutes les commandes npm run depuis ici)
|
||||||
src/
|
src/
|
||||||
main/ ← Electron main process (Node.js uniquement)
|
main/ ← Electron main process (Node.js uniquement)
|
||||||
index.ts
|
index.ts
|
||||||
ipc/ ← Handlers IPC — un fichier par domaine
|
ipc/ ← Handlers IPC — un fichier par domaine
|
||||||
services/ ← Logique métier — un fichier par service
|
services/ ← Logique métier — un fichier par service
|
||||||
|
agent.service.ts ← Orchestrateur du pipeline 7 agents
|
||||||
|
openrouter.service.ts
|
||||||
|
elevenlabs.service.ts
|
||||||
utils/
|
utils/
|
||||||
renderer/ ← React TypeScript (UI uniquement)
|
renderer/ ← React TypeScript (UI uniquement)
|
||||||
App.tsx
|
App.tsx
|
||||||
@@ -42,19 +96,61 @@ src/
|
|||||||
types/
|
types/
|
||||||
utils/
|
utils/
|
||||||
shared/ ← Types et constantes partagés main + renderer
|
shared/ ← Types et constantes partagés main + renderer
|
||||||
types.ts
|
types.ts ← SessionStatus, LearningObjective, AgentOutput...
|
||||||
constants.ts
|
constants.ts
|
||||||
preload/
|
preload/
|
||||||
index.ts
|
index.ts
|
||||||
|
Max API/ ← Backend NestJS + Prisma + PostgreSQL
|
||||||
|
src/
|
||||||
|
common/
|
||||||
|
crypto/ ← EncryptionService (AES-256-GCM pour les clés API)
|
||||||
|
users/
|
||||||
|
api-keys/ ← Gestion des clés OpenRouter par utilisateur (Provisioning API)
|
||||||
|
sessions/ ← Pipeline agents, state machine, tables de session
|
||||||
|
veille/ ← Agent de veille autonome
|
||||||
|
prisma/
|
||||||
|
schema.prisma ← Source de vérité du schéma BDD
|
||||||
|
CLAUDE.md ← Ce fichier
|
||||||
|
docs/ ← Documentation technique
|
||||||
```
|
```
|
||||||
|
|
||||||
### Règle d'architecture absolue
|
### Règles d'architecture absolues
|
||||||
|
|
||||||
- **Main process** : Node.js, accès filesystem, APIs externes, SQLite. Zéro UI.
|
- **Main process** : Node.js, accès filesystem, appels backend Max API. Zéro UI.
|
||||||
- **Renderer** : React, Three.js, UI. Zéro Node.js direct.
|
- **Renderer** : React, Three.js, UI. Zéro Node.js direct.
|
||||||
- **Communication** : EXCLUSIVEMENT via IPC (contextBridge). Jamais d'import Node.js dans le renderer.
|
- **Communication Electron** : EXCLUSIVEMENT via IPC (contextBridge). Jamais d'import Node.js dans le renderer.
|
||||||
|
- **Appels LLM** : JAMAIS depuis le renderer. Toujours via IPC → main → Max API backend.
|
||||||
|
- **Clés API** : JAMAIS dans le renderer, JAMAIS dans le main process. Elles vivent uniquement dans Max API, chiffrées AES-256-GCM.
|
||||||
- **Shared** : uniquement des types TypeScript et des constantes. Zéro logique.
|
- **Shared** : uniquement des types TypeScript et des constantes. Zéro logique.
|
||||||
|
|
||||||
|
### Gestion des clés API par utilisateur
|
||||||
|
|
||||||
|
Les clés OpenRouter sont créées programmatiquement via la Provisioning API d'OpenRouter (une clé par utilisateur, limitée en crédits). ElevenLabs n'a pas de système équivalent — Max API agit en proxy avec la clé maître. Voir `Max API/src/api-keys/`.
|
||||||
|
|
||||||
|
### Comportements LLM à anticiper dans le code
|
||||||
|
|
||||||
|
Le code doit gérer ces comportements sans planter :
|
||||||
|
|
||||||
|
- **Réponse malformée** : HTTP 200 sans `choices` → vérifier l'existence de `choices` avant tout accès
|
||||||
|
- **Ignore une instruction** : l'agent annonce une action sans l'exécuter → relance automatique ≤ 4 fois
|
||||||
|
- **Bascule secours** : après 4 échecs, basculer sur Qwen avec le même contexte de conversation
|
||||||
|
- **Texte dégénéré** : caractères non-latins → détection regex + relance
|
||||||
|
- **Rate limit (429) / timeout (504)** : retry avec backoff exponentiel
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// ✅ Pattern obligatoire pour tout appel LLM
|
||||||
|
const response = await callWithFallback({
|
||||||
|
primary: 'deepseek/deepseek-chat',
|
||||||
|
fallback: 'qwen/qwen-2.5-72b-instruct',
|
||||||
|
maxRetries: 4,
|
||||||
|
messages,
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response?.choices?.[0]?.message) {
|
||||||
|
throw new ApiError('Réponse malformée', 'openrouter')
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. TypeScript — Règles strictes
|
## 3. TypeScript — Règles strictes
|
||||||
@@ -341,7 +437,7 @@ import type { Message } from '../../shared/types'
|
|||||||
## 8. Ce que l'IA NE doit PAS faire
|
## 8. Ce que l'IA NE doit PAS faire
|
||||||
|
|
||||||
| Action interdite | Alternative correcte |
|
| Action interdite | Alternative correcte |
|
||||||
| ------------------------------------------------ | ----------------------------------------------------------- |
|
| --- | --- |
|
||||||
| Ajouter une dépendance npm sans justification | Signaler le besoin, expliquer pourquoi, attendre validation |
|
| Ajouter une dépendance npm sans justification | Signaler le besoin, expliquer pourquoi, attendre validation |
|
||||||
| Modifier la structure des dossiers sans raison | Justifier la modification avant de la faire |
|
| Modifier la structure des dossiers sans raison | Justifier la modification avant de la faire |
|
||||||
| Utiliser `console.log` en production | Utiliser le logger du projet |
|
| Utiliser `console.log` en production | Utiliser le logger du projet |
|
||||||
@@ -352,6 +448,9 @@ import type { Message } from '../../shared/types'
|
|||||||
| Écrire du code sans gestion d'erreur | Toujours gérer les cas d'erreur explicitement |
|
| Écrire du code sans gestion d'erreur | Toujours gérer les cas d'erreur explicitement |
|
||||||
| Faire un commit fourre-tout | Un commit = une chose, message Conventional Commits |
|
| Faire un commit fourre-tout | Un commit = une chose, message Conventional Commits |
|
||||||
| Exposer des secrets dans les logs | Masquer les clés API dans les logs |
|
| Exposer des secrets dans les logs | Masquer les clés API dans les logs |
|
||||||
|
| Appeler OpenRouter ou ElevenLabs depuis le renderer | Passer par IPC → main → Max API uniquement |
|
||||||
|
| Stocker une clé API dans le main process Electron | Les clés vivent uniquement dans Max API chiffrées |
|
||||||
|
| Avancer dans le pipeline sans vérifier le statut en base | Lire `session.status` avant chaque action agent |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -359,9 +458,10 @@ import type { Message } from '../../shared/types'
|
|||||||
|
|
||||||
### Avant de commencer une fonctionnalité
|
### Avant de commencer une fonctionnalité
|
||||||
|
|
||||||
1. Vérifier que la branche est à jour (`git pull origin develop`)
|
1. Vérifier que la branche est à jour (`git pull origin main`)
|
||||||
2. Créer une branche `feature/nom-de-la-fonctionnalite` depuis `develop`
|
2. Créer une branche `feature/nom-de-la-fonctionnalite` depuis `main`
|
||||||
3. Comprendre les types existants dans `src/shared/types.ts` avant d'en créer de nouveaux
|
3. Comprendre les types existants dans `src/shared/types.ts` avant d'en créer de nouveaux
|
||||||
|
4. Si la fonctionnalité touche le pipeline agent, lire `session.status` pour connaître l'état courant
|
||||||
|
|
||||||
### Pendant le développement
|
### Pendant le développement
|
||||||
|
|
||||||
@@ -380,16 +480,17 @@ npm run test # tous les tests passent
|
|||||||
|
|
||||||
Husky lance ces vérifications automatiquement — un commit échoue si l'une d'elles échoue.
|
Husky lance ces vérifications automatiquement — un commit échoue si l'une d'elles échoue.
|
||||||
|
|
||||||
verifie que le code ne contient pas d'érreur sur le sonarqube de dev (http://localhost:9000) avec le token suivant : squ_bc83f67e11ee5a4fd3c86ad19281e0c159062846
|
Vérifier que le code ne contient pas d'erreur sur le SonarQube de dev (http://localhost:9000) avec le token : squ_bc83f67e11ee5a4fd3c86ad19281e0c159062846
|
||||||
|
|
||||||
### Format du message de commit
|
### Format du message de commit
|
||||||
|
|
||||||
```
|
```
|
||||||
feat(coach): ajouter la phase guidée We Do avec protocole interactif
|
feat(agent-objectif): implémenter la validation des 3 piliers avec garde-fous
|
||||||
|
|
||||||
- Implémenter l'escalier d'indices en 5 niveaux
|
- Valider sujet (min 10 chars, non générique), but professionnel (min 20 chars), durée (1h-12 semaines)
|
||||||
- Ajouter la validation de réponse avant passage à l'étape suivante
|
- Ajouter validation IA avec score de cohérence sur 3 dimensions
|
||||||
- Tests unitaires pour les 5 niveaux d'indices
|
- Stocker l'objectif validé en base avant de passer à l'Agent 2
|
||||||
|
- Tests unitaires pour les cas de rejet et de validation
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -442,8 +543,8 @@ function animate() {
|
|||||||
## 12. Références rapides
|
## 12. Références rapides
|
||||||
|
|
||||||
| Besoin | Commande |
|
| Besoin | Commande |
|
||||||
| --------------------- | ----------------------- |
|
| --- | --- |
|
||||||
| Lancer en dev | `npm run dev` |
|
| Lancer en dev (depuis Max Avatar/) | `npm run dev` |
|
||||||
| Vérifier les types | `npm run typecheck` |
|
| Vérifier les types | `npm run typecheck` |
|
||||||
| Corriger le lint | `npm run lint:fix` |
|
| Corriger le lint | `npm run lint:fix` |
|
||||||
| Lancer les tests | `npm run test` |
|
| Lancer les tests | `npm run test` |
|
||||||
@@ -453,3 +554,6 @@ function animate() {
|
|||||||
| Build Mac | `npm run build:mac` |
|
| Build Mac | `npm run build:mac` |
|
||||||
| Build Linux | `npm run build:linux` |
|
| Build Linux | `npm run build:linux` |
|
||||||
| Audit sécurité | `npm audit` |
|
| Audit sécurité | `npm audit` |
|
||||||
|
| Lancer le backend (depuis Max API/) | `npm run start:dev` |
|
||||||
|
| Migration BDD | `npx prisma migrate dev` |
|
||||||
|
| Seed BDD | `npm run prisma:seed` |
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Copier ce fichier en ".env" (jamais commite) et renseigner de vraies valeurs.
|
||||||
|
|
||||||
|
PORT=3000
|
||||||
|
|
||||||
|
# Doit correspondre a POSTGRES_USER/POSTGRES_PASSWORD/POSTGRES_DB du ".env" a la racine du depot
|
||||||
|
# (lu par docker-compose.yml pour le service "postgres").
|
||||||
|
DATABASE_URL="postgresql://max_api:changeme@localhost:5432/max_api?schema=public"
|
||||||
|
|
||||||
|
# Cle maitresse de chiffrement des cles API stockees (AES-256-GCM) : exactement 32 octets en
|
||||||
|
# hexadecimal (64 caracteres). Generer avec : node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
|
||||||
|
# Ne JAMAIS reutiliser la meme cle entre environnements, ne jamais la commiter.
|
||||||
|
ENCRYPTION_KEY=
|
||||||
|
|
||||||
|
# Secret de signature des jetons JWT (route POST /auth/login). Generer avec la meme commande que
|
||||||
|
# ENCRYPTION_KEY ci-dessus (longueur non contrainte, mais au moins 32 octets recommande).
|
||||||
|
JWT_SECRET=
|
||||||
|
|
||||||
|
# --- Valeurs utilisees uniquement par prisma/seed.ts pour provisionner le premier utilisateur ---
|
||||||
|
SEED_USER_FIRST_NAME=
|
||||||
|
SEED_USER_LAST_NAME=
|
||||||
|
SEED_USER_EMAIL=
|
||||||
|
SEED_USER_PASSWORD=
|
||||||
|
SEED_ELEVENLABS_API_KEY=
|
||||||
|
SEED_ELEVENLABS_VOICE_ID=
|
||||||
|
SEED_OPENROUTER_API_KEY=
|
||||||
|
SEED_OPENROUTER_MODEL=
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
coverage
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
*.log*
|
||||||
|
.DS_Store
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"singleQuote": true,
|
||||||
|
"trailingComma": "all"
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
<p align="center">
|
||||||
|
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||||
|
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||||
|
|
||||||
|
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||||
|
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||||
|
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||||
|
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||||
|
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||||
|
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
|
||||||
|
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||||
|
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
|
||||||
|
</p>
|
||||||
|
<!--[](https://opencollective.com/nest#backer)
|
||||||
|
[](https://opencollective.com/nest#sponsor)-->
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||||
|
|
||||||
|
## Project setup
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
## Compile and run the project
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# development
|
||||||
|
$ npm run start
|
||||||
|
|
||||||
|
# watch mode
|
||||||
|
$ npm run start:dev
|
||||||
|
|
||||||
|
# production mode
|
||||||
|
$ npm run start:prod
|
||||||
|
```
|
||||||
|
|
||||||
|
## Run tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# unit tests
|
||||||
|
$ npm run test
|
||||||
|
|
||||||
|
# e2e tests
|
||||||
|
$ npm run test:e2e
|
||||||
|
|
||||||
|
# test coverage
|
||||||
|
$ npm run test:cov
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
|
||||||
|
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
|
||||||
|
|
||||||
|
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ npm install -g @nestjs/mau
|
||||||
|
$ mau deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
|
||||||
|
|
||||||
|
## Resources
|
||||||
|
|
||||||
|
Check out a few resources that may come in handy when working with NestJS:
|
||||||
|
|
||||||
|
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
|
||||||
|
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
|
||||||
|
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
|
||||||
|
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
|
||||||
|
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
|
||||||
|
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
|
||||||
|
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
|
||||||
|
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
|
||||||
|
|
||||||
|
## Support
|
||||||
|
|
||||||
|
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
|
||||||
|
|
||||||
|
## Stay in touch
|
||||||
|
|
||||||
|
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
|
||||||
|
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||||
|
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
// @ts-check
|
||||||
|
import eslint from '@eslint/js';
|
||||||
|
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
|
||||||
|
import eslintPluginSecurity from 'eslint-plugin-security';
|
||||||
|
import globals from 'globals';
|
||||||
|
import tseslint from 'typescript-eslint';
|
||||||
|
|
||||||
|
export default tseslint.config(
|
||||||
|
{
|
||||||
|
ignores: ['eslint.config.mjs'],
|
||||||
|
},
|
||||||
|
eslint.configs.recommended,
|
||||||
|
...tseslint.configs.recommendedTypeChecked,
|
||||||
|
eslintPluginSecurity.configs.recommended,
|
||||||
|
eslintPluginPrettierRecommended,
|
||||||
|
{
|
||||||
|
languageOptions: {
|
||||||
|
globals: {
|
||||||
|
...globals.node,
|
||||||
|
...globals.jest,
|
||||||
|
},
|
||||||
|
sourceType: 'commonjs',
|
||||||
|
parserOptions: {
|
||||||
|
projectService: true,
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
rules: {
|
||||||
|
// CLAUDE.md interdit tout `any`, explicite ou implicite, et toute promesse non geree :
|
||||||
|
// contrairement au defaut de @nestjs/schematics, ces deux regles restent des erreurs ici.
|
||||||
|
'@typescript-eslint/no-explicit-any': 'error',
|
||||||
|
'@typescript-eslint/no-floating-promises': 'error',
|
||||||
|
'@typescript-eslint/no-unsafe-argument': 'warn',
|
||||||
|
'no-console': ['warn', { allow: ['warn', 'error'] }],
|
||||||
|
'security/detect-object-injection': 'error',
|
||||||
|
'prettier/prettier': ['error', { endOfLine: 'auto' }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/nest-cli",
|
||||||
|
"collection": "@nestjs/schematics",
|
||||||
|
"sourceRoot": "src",
|
||||||
|
"compilerOptions": {
|
||||||
|
"deleteOutDir": true
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+11166
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,108 @@
|
|||||||
|
{
|
||||||
|
"name": "max-api",
|
||||||
|
"version": "0.0.1",
|
||||||
|
"description": "Backend Max : detient les cles API externes (OpenRouter, ElevenLabs) cote serveur et gere les comptes utilisateurs.",
|
||||||
|
"author": "Vandal William",
|
||||||
|
"private": true,
|
||||||
|
"license": "UNLICENSED",
|
||||||
|
"overrides": {
|
||||||
|
"multer": "2.5.0"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"build": "nest build",
|
||||||
|
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
|
"dev": "nest start --watch",
|
||||||
|
"start": "nest start",
|
||||||
|
"start:dev": "nest start --watch",
|
||||||
|
"start:debug": "nest start --debug --watch",
|
||||||
|
"start:prod": "node dist/main",
|
||||||
|
"typecheck": "tsc --noEmit",
|
||||||
|
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\"",
|
||||||
|
"lint:fix": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||||
|
"test": "jest",
|
||||||
|
"test:watch": "jest --watch",
|
||||||
|
"test:coverage": "jest --coverage",
|
||||||
|
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||||
|
"test:e2e": "jest --config ./test/jest-e2e.json",
|
||||||
|
"prisma:generate": "prisma generate",
|
||||||
|
"prisma:migrate": "prisma migrate dev",
|
||||||
|
"prisma:deploy": "prisma migrate deploy",
|
||||||
|
"prisma:studio": "prisma studio",
|
||||||
|
"prisma:seed": "ts-node prisma/seed.ts",
|
||||||
|
"postinstall": "prisma generate"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@nestjs/common": "^11.0.1",
|
||||||
|
"@nestjs/config": "4.0.4",
|
||||||
|
"@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",
|
||||||
|
"class-transformer": "^0.5.1",
|
||||||
|
"class-validator": "^0.15.1",
|
||||||
|
"dotenv": "^18.0.9",
|
||||||
|
"reflect-metadata": "^0.2.2",
|
||||||
|
"rxjs": "^7.8.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/eslintrc": "^3.2.0",
|
||||||
|
"@eslint/js": "^9.18.0",
|
||||||
|
"@nestjs/cli": "^11.0.0",
|
||||||
|
"@nestjs/schematics": "^11.0.0",
|
||||||
|
"@nestjs/testing": "^11.0.1",
|
||||||
|
"@types/bcrypt": "^6.0.0",
|
||||||
|
"@types/express": "^5.0.0",
|
||||||
|
"@types/jest": "^30.0.0",
|
||||||
|
"@types/node": "^22.10.7",
|
||||||
|
"@types/supertest": "^6.0.2",
|
||||||
|
"eslint": "^9.18.0",
|
||||||
|
"eslint-config-prettier": "^10.0.1",
|
||||||
|
"eslint-plugin-prettier": "^5.2.2",
|
||||||
|
"eslint-plugin-security": "^4.2.1",
|
||||||
|
"globals": "^16.0.0",
|
||||||
|
"jest": "^30.0.0",
|
||||||
|
"prettier": "^3.4.2",
|
||||||
|
"prisma": "6.19.3",
|
||||||
|
"source-map-support": "^0.5.21",
|
||||||
|
"supertest": "^7.0.0",
|
||||||
|
"ts-jest": "^29.2.5",
|
||||||
|
"ts-loader": "^9.5.2",
|
||||||
|
"ts-node": "^10.9.2",
|
||||||
|
"tsconfig-paths": "^4.2.0",
|
||||||
|
"typescript": "^5.7.3",
|
||||||
|
"typescript-eslint": "^8.20.0"
|
||||||
|
},
|
||||||
|
"prisma": {
|
||||||
|
"seed": "ts-node prisma/seed.ts"
|
||||||
|
},
|
||||||
|
"jest": {
|
||||||
|
"moduleFileExtensions": [
|
||||||
|
"js",
|
||||||
|
"json",
|
||||||
|
"ts"
|
||||||
|
],
|
||||||
|
"rootDir": "src",
|
||||||
|
"testRegex": ".*\\.spec\\.ts$",
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
|
},
|
||||||
|
"collectCoverageFrom": [
|
||||||
|
"**/*.(t|j)s",
|
||||||
|
"!**/*.module.ts",
|
||||||
|
"!main.ts"
|
||||||
|
],
|
||||||
|
"coverageDirectory": "../coverage",
|
||||||
|
"testEnvironment": "node",
|
||||||
|
"coverageThreshold": {
|
||||||
|
"global": {
|
||||||
|
"statements": 80,
|
||||||
|
"branches": 75,
|
||||||
|
"functions": 80,
|
||||||
|
"lines": 80
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "user" (
|
||||||
|
"id" SERIAL NOT NULL,
|
||||||
|
"first_name" TEXT NOT NULL,
|
||||||
|
"last_name" TEXT NOT NULL,
|
||||||
|
"email" TEXT NOT NULL,
|
||||||
|
"password" TEXT NOT NULL,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "user_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "api_key" (
|
||||||
|
"id" SERIAL NOT NULL,
|
||||||
|
"user_id" INTEGER NOT NULL,
|
||||||
|
"service_name" TEXT NOT NULL,
|
||||||
|
"key" TEXT NOT NULL,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "api_key_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "user_email_key" ON "user"("email");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "api_key_user_id_service_name_key" ON "api_key"("user_id", "service_name");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "api_key" ADD CONSTRAINT "api_key_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "session_status" AS ENUM ('objective_discovery', 'objective_validated', 'mapping', 'level_assessment', 'researching', 'planning', 'teaching', 'evaluating', 'completed');
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "session" (
|
||||||
|
"id" SERIAL NOT NULL,
|
||||||
|
"user_id" INTEGER NOT NULL,
|
||||||
|
"status" "session_status" NOT NULL DEFAULT 'objective_discovery',
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "session_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "session_objective" (
|
||||||
|
"id" SERIAL NOT NULL,
|
||||||
|
"session_id" INTEGER NOT NULL,
|
||||||
|
"subject" TEXT NOT NULL,
|
||||||
|
"professional_goal" TEXT NOT NULL,
|
||||||
|
"duration" TEXT NOT NULL,
|
||||||
|
"trigger" TEXT,
|
||||||
|
"validated_at" TIMESTAMP(3),
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "session_objective_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "session_concept_map" (
|
||||||
|
"id" SERIAL NOT NULL,
|
||||||
|
"session_id" INTEGER NOT NULL,
|
||||||
|
"concepts" JSONB NOT NULL,
|
||||||
|
"sources_used" JSONB NOT NULL,
|
||||||
|
"completed_at" TIMESTAMP(3),
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "session_concept_map_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "session_level_assessment" (
|
||||||
|
"id" SERIAL NOT NULL,
|
||||||
|
"session_id" INTEGER NOT NULL,
|
||||||
|
"questions_asked" JSONB NOT NULL,
|
||||||
|
"user_answers" JSONB NOT NULL,
|
||||||
|
"mastered_concepts" JSONB NOT NULL,
|
||||||
|
"gap_concepts" JSONB NOT NULL,
|
||||||
|
"unknown_concepts" JSONB NOT NULL,
|
||||||
|
"overall_level" TEXT NOT NULL,
|
||||||
|
"completed_at" TIMESTAMP(3),
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "session_level_assessment_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "session_research" (
|
||||||
|
"id" SERIAL NOT NULL,
|
||||||
|
"session_id" INTEGER NOT NULL,
|
||||||
|
"corpus" JSONB NOT NULL,
|
||||||
|
"subtopics_covered" JSONB NOT NULL,
|
||||||
|
"sources_count" INTEGER NOT NULL,
|
||||||
|
"completed_at" TIMESTAMP(3),
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "session_research_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "session_curriculum" (
|
||||||
|
"id" SERIAL NOT NULL,
|
||||||
|
"session_id" INTEGER NOT NULL,
|
||||||
|
"modules" JSONB NOT NULL,
|
||||||
|
"total_modules" INTEGER NOT NULL,
|
||||||
|
"total_duration" TEXT NOT NULL,
|
||||||
|
"validated_at" TIMESTAMP(3),
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "session_curriculum_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "session_module" (
|
||||||
|
"id" SERIAL NOT NULL,
|
||||||
|
"session_id" INTEGER NOT NULL,
|
||||||
|
"module_index" INTEGER NOT NULL,
|
||||||
|
"title" TEXT NOT NULL,
|
||||||
|
"content" JSONB NOT NULL,
|
||||||
|
"status" TEXT NOT NULL DEFAULT 'locked',
|
||||||
|
"completed_at" TIMESTAMP(3),
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "session_module_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "session_evaluation" (
|
||||||
|
"id" SERIAL NOT NULL,
|
||||||
|
"session_id" INTEGER NOT NULL,
|
||||||
|
"interview_score" DOUBLE PRECISION,
|
||||||
|
"practical_score" DOUBLE PRECISION,
|
||||||
|
"validated" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"feedback" JSONB,
|
||||||
|
"completed_at" TIMESTAMP(3),
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "session_evaluation_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "freelance_profile" (
|
||||||
|
"id" SERIAL NOT NULL,
|
||||||
|
"user_id" INTEGER NOT NULL,
|
||||||
|
"display_name" TEXT,
|
||||||
|
"positioning" TEXT,
|
||||||
|
"domains" JSONB,
|
||||||
|
"stack" JSONB,
|
||||||
|
"target_mission_types" JSONB,
|
||||||
|
"target_sectors" JSONB,
|
||||||
|
"seniority_level" TEXT,
|
||||||
|
"tjm" DOUBLE PRECISION,
|
||||||
|
"experience_years" INTEGER,
|
||||||
|
"certifications" JSONB,
|
||||||
|
"work_format" TEXT,
|
||||||
|
"geographic_zone" TEXT,
|
||||||
|
"competences_acquired" JSONB,
|
||||||
|
"competences_in_progress" JSONB,
|
||||||
|
"competences_dismissed" JSONB,
|
||||||
|
"last_training_at" TIMESTAMP(3),
|
||||||
|
"veille_frequency" TEXT,
|
||||||
|
"veille_extra_topics" JSONB,
|
||||||
|
"veille_blacklist" JSONB,
|
||||||
|
"veille_relevance_threshold" DOUBLE PRECISION,
|
||||||
|
"veille_notifications_enabled" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"last_veille_at" TIMESTAMP(3),
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "freelance_profile_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "veille_signal" (
|
||||||
|
"id" SERIAL NOT NULL,
|
||||||
|
"freelance_profile_id" INTEGER NOT NULL,
|
||||||
|
"type" TEXT NOT NULL,
|
||||||
|
"competence" TEXT NOT NULL,
|
||||||
|
"sources" JSONB NOT NULL,
|
||||||
|
"relevance_score" DOUBLE PRECISION NOT NULL,
|
||||||
|
"action_taken" TEXT,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "veille_signal_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "session_objective_session_id_key" ON "session_objective"("session_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "session_concept_map_session_id_key" ON "session_concept_map"("session_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "session_level_assessment_session_id_key" ON "session_level_assessment"("session_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "session_research_session_id_key" ON "session_research"("session_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "session_curriculum_session_id_key" ON "session_curriculum"("session_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "session_module_session_id_module_index_key" ON "session_module"("session_id", "module_index");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "session_evaluation_session_id_key" ON "session_evaluation"("session_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "freelance_profile_user_id_key" ON "freelance_profile"("user_id");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "session" ADD CONSTRAINT "session_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "session_objective" ADD CONSTRAINT "session_objective_session_id_fkey" FOREIGN KEY ("session_id") REFERENCES "session"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "session_concept_map" ADD CONSTRAINT "session_concept_map_session_id_fkey" FOREIGN KEY ("session_id") REFERENCES "session"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "session_level_assessment" ADD CONSTRAINT "session_level_assessment_session_id_fkey" FOREIGN KEY ("session_id") REFERENCES "session"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "session_research" ADD CONSTRAINT "session_research_session_id_fkey" FOREIGN KEY ("session_id") REFERENCES "session"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "session_curriculum" ADD CONSTRAINT "session_curriculum_session_id_fkey" FOREIGN KEY ("session_id") REFERENCES "session"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "session_module" ADD CONSTRAINT "session_module_session_id_fkey" FOREIGN KEY ("session_id") REFERENCES "session"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "session_evaluation" ADD CONSTRAINT "session_evaluation_session_id_fkey" FOREIGN KEY ("session_id") REFERENCES "session"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "freelance_profile" ADD CONSTRAINT "freelance_profile_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "veille_signal" ADD CONSTRAINT "veille_signal_freelance_profile_id_fkey" FOREIGN KEY ("freelance_profile_id") REFERENCES "freelance_profile"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Please do not edit this file manually
|
||||||
|
# It should be added in your version-control system (e.g., Git)
|
||||||
|
provider = "postgresql"
|
||||||
@@ -0,0 +1,243 @@
|
|||||||
|
generator client {
|
||||||
|
provider = "prisma-client-js"
|
||||||
|
}
|
||||||
|
|
||||||
|
datasource db {
|
||||||
|
provider = "postgresql"
|
||||||
|
url = env("DATABASE_URL")
|
||||||
|
}
|
||||||
|
|
||||||
|
model User {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
firstName String @map("first_name")
|
||||||
|
lastName String @map("last_name")
|
||||||
|
email String @unique
|
||||||
|
password String
|
||||||
|
apiKeys ApiKey[]
|
||||||
|
sessions Session[]
|
||||||
|
freelanceProfile FreelanceProfile?
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
@@map("user")
|
||||||
|
}
|
||||||
|
|
||||||
|
// La colonne "key" contient la valeur chiffree (AES-256-GCM, voir EncryptionService), jamais la
|
||||||
|
// cle en clair : seul le serveur, qui detient ENCRYPTION_KEY, peut la dechiffrer.
|
||||||
|
model ApiKey {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
userId Int @map("user_id")
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
serviceName String @map("service_name")
|
||||||
|
key String
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
@@unique([userId, serviceName])
|
||||||
|
@@map("api_key")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pipeline de formation freelance — 7 agents sequentiels, voir CLAUDE.md section 1.
|
||||||
|
// Aucun agent ne demarre si l'agent precedent n'a pas produit et stocke son output ici :
|
||||||
|
// la state machine est geree cote code (Max API), jamais cote LLM.
|
||||||
|
enum SessionStatus {
|
||||||
|
objective_discovery
|
||||||
|
objective_validated
|
||||||
|
mapping
|
||||||
|
level_assessment
|
||||||
|
researching
|
||||||
|
planning
|
||||||
|
teaching
|
||||||
|
evaluating
|
||||||
|
completed
|
||||||
|
|
||||||
|
@@map("session_status")
|
||||||
|
}
|
||||||
|
|
||||||
|
model Session {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
userId Int @map("user_id")
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
status SessionStatus @default(objective_discovery)
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
objective SessionObjective?
|
||||||
|
conceptMap SessionConceptMap?
|
||||||
|
level SessionLevelAssessment?
|
||||||
|
research SessionResearch?
|
||||||
|
curriculum SessionCurriculum?
|
||||||
|
modules SessionModule[]
|
||||||
|
evaluation SessionEvaluation?
|
||||||
|
|
||||||
|
@@map("session")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Agent 1 - Objectif : dialogue socratique revelant et validant les 3 piliers (sujet, but
|
||||||
|
// professionnel, duree). Immuable une fois validated_at renseigne.
|
||||||
|
model SessionObjective {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
sessionId Int @unique @map("session_id")
|
||||||
|
session Session @relation(fields: [sessionId], references: [id], onDelete: Cascade)
|
||||||
|
subject String
|
||||||
|
professionalGoal String @map("professional_goal")
|
||||||
|
duration String
|
||||||
|
trigger String?
|
||||||
|
validatedAt DateTime? @map("validated_at")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
@@map("session_objective")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Agent 2 - Recherche Cartographie : carte des concepts cles du domaine, sert a construire
|
||||||
|
// l'evaluation de niveau (Agent 3).
|
||||||
|
model SessionConceptMap {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
sessionId Int @unique @map("session_id")
|
||||||
|
session Session @relation(fields: [sessionId], references: [id], onDelete: Cascade)
|
||||||
|
concepts Json
|
||||||
|
sourcesUsed Json @map("sources_used")
|
||||||
|
completedAt DateTime? @map("completed_at")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
@@map("session_concept_map")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Agent 3 - Niveau : evaluation du niveau reel via questions situationnelles (jamais un QCM).
|
||||||
|
model SessionLevelAssessment {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
sessionId Int @unique @map("session_id")
|
||||||
|
session Session @relation(fields: [sessionId], references: [id], onDelete: Cascade)
|
||||||
|
questionsAsked Json @map("questions_asked")
|
||||||
|
userAnswers Json @map("user_answers")
|
||||||
|
masteredConcepts Json @map("mastered_concepts")
|
||||||
|
gapConcepts Json @map("gap_concepts")
|
||||||
|
unknownConcepts Json @map("unknown_concepts")
|
||||||
|
overallLevel String @map("overall_level")
|
||||||
|
completedAt DateTime? @map("completed_at")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
@@map("session_level_assessment")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Agent 4 - Recherche Approfondie : corpus de sources fiables, parallelise par sous-theme,
|
||||||
|
// calibre sur le niveau detecte par l'Agent 3.
|
||||||
|
model SessionResearch {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
sessionId Int @unique @map("session_id")
|
||||||
|
session Session @relation(fields: [sessionId], references: [id], onDelete: Cascade)
|
||||||
|
corpus Json
|
||||||
|
subtopicsCovered Json @map("subtopics_covered")
|
||||||
|
sourcesCount Int @map("sources_count")
|
||||||
|
completedAt DateTime? @map("completed_at")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
@@map("session_research")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Agent 5 - Plan : curriculum en N modules via Backward Design (objectif final d'abord).
|
||||||
|
model SessionCurriculum {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
sessionId Int @unique @map("session_id")
|
||||||
|
session Session @relation(fields: [sessionId], references: [id], onDelete: Cascade)
|
||||||
|
modules Json
|
||||||
|
totalModules Int @map("total_modules")
|
||||||
|
totalDuration String @map("total_duration")
|
||||||
|
validatedAt DateTime? @map("validated_at")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
@@map("session_curriculum")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Agent 6 - Redacteur : un module a la fois, 6 sections obligatoires (methode I Do/We Do/You Do).
|
||||||
|
model SessionModule {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
sessionId Int @map("session_id")
|
||||||
|
session Session @relation(fields: [sessionId], references: [id], onDelete: Cascade)
|
||||||
|
moduleIndex Int @map("module_index")
|
||||||
|
title String
|
||||||
|
content Json
|
||||||
|
status String @default("locked")
|
||||||
|
completedAt DateTime? @map("completed_at")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
@@unique([sessionId, moduleIndex])
|
||||||
|
@@map("session_module")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Agent 7 - Evaluation finale : entretien client simule (conceptuel) + cas de mission reel
|
||||||
|
// (pratique). Competence maitrisee seulement si tous les modules sont valides ET les deux
|
||||||
|
// volets sont reussis.
|
||||||
|
model SessionEvaluation {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
sessionId Int @unique @map("session_id")
|
||||||
|
session Session @relation(fields: [sessionId], references: [id], onDelete: Cascade)
|
||||||
|
interviewScore Float? @map("interview_score")
|
||||||
|
practicalScore Float? @map("practical_score")
|
||||||
|
validated Boolean @default(false)
|
||||||
|
feedback Json?
|
||||||
|
completedAt DateTime? @map("completed_at")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
@@map("session_evaluation")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Profil freelance : renseigne manuellement (positionnement, stack, TJM...) et alimente
|
||||||
|
// automatiquement par le pipeline (competences acquises) et l'Agent de Veille.
|
||||||
|
model FreelanceProfile {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
userId Int @unique @map("user_id")
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
displayName String? @map("display_name")
|
||||||
|
positioning String?
|
||||||
|
domains Json?
|
||||||
|
stack Json?
|
||||||
|
targetMissionTypes Json? @map("target_mission_types")
|
||||||
|
targetSectors Json? @map("target_sectors")
|
||||||
|
seniorityLevel String? @map("seniority_level")
|
||||||
|
tjm Float?
|
||||||
|
experienceYears Int? @map("experience_years")
|
||||||
|
certifications Json?
|
||||||
|
workFormat String? @map("work_format")
|
||||||
|
geographicZone String? @map("geographic_zone")
|
||||||
|
competencesAcquired Json? @map("competences_acquired")
|
||||||
|
competencesInProgress Json? @map("competences_in_progress")
|
||||||
|
competencesDismissed Json? @map("competences_dismissed")
|
||||||
|
lastTrainingAt DateTime? @map("last_training_at")
|
||||||
|
veilleFrequency String? @map("veille_frequency")
|
||||||
|
veilleExtraTopics Json? @map("veille_extra_topics")
|
||||||
|
veilleBlacklist Json? @map("veille_blacklist")
|
||||||
|
veilleRelevanceThreshold Float? @map("veille_relevance_threshold")
|
||||||
|
veilleNotificationsEnabled Boolean @default(true) @map("veille_notifications_enabled")
|
||||||
|
lastVeilleAt DateTime? @map("last_veille_at")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
veilleSignals VeilleSignal[]
|
||||||
|
|
||||||
|
@@map("freelance_profile")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Agent de Veille : signaux de marche cross-valides (>=3 sources independantes) avant
|
||||||
|
// notification, score de pertinence calibre sur le freelance_profile.
|
||||||
|
model VeilleSignal {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
freelanceProfileId Int @map("freelance_profile_id")
|
||||||
|
freelanceProfile FreelanceProfile @relation(fields: [freelanceProfileId], references: [id], onDelete: Cascade)
|
||||||
|
type String
|
||||||
|
competence String
|
||||||
|
sources Json
|
||||||
|
relevanceScore Float @map("relevance_score")
|
||||||
|
actionTaken String? @map("action_taken")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
@@map("veille_signal")
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
/**
|
||||||
|
* Script de provisionnement du premier utilisateur (dev uniquement). Toutes les valeurs sensibles
|
||||||
|
* viennent de process.env (voir .env.example) : rien n'est jamais ecrit en dur ici.
|
||||||
|
* Lancer avec : npm run prisma:seed
|
||||||
|
*/
|
||||||
|
import 'dotenv/config';
|
||||||
|
import { createCipheriv, randomBytes } from 'node:crypto';
|
||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
import * as bcrypt from 'bcrypt';
|
||||||
|
|
||||||
|
const BCRYPT_SALT_ROUNDS = 12;
|
||||||
|
const ALGORITHM = 'aes-256-gcm';
|
||||||
|
const IV_LENGTH_BYTES = 12;
|
||||||
|
|
||||||
|
function requireEnv(key: string): string {
|
||||||
|
const value = process.env[key];
|
||||||
|
if (!value) throw new Error(`Variable d'environnement manquante : ${key}`);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Duplique volontairement EncryptionService.encrypt() : ce script tourne hors du contexte Nest
|
||||||
|
// (pas d'injection de dependances disponible), et cette seule fonction ne justifie pas de
|
||||||
|
// demarrer toute l'application pour un script de provisionnement ponctuel.
|
||||||
|
function encrypt(plaintext: string, masterKey: Buffer): string {
|
||||||
|
const iv = randomBytes(IV_LENGTH_BYTES);
|
||||||
|
const cipher = createCipheriv(ALGORITHM, masterKey, iv);
|
||||||
|
const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
|
||||||
|
const authTag = cipher.getAuthTag();
|
||||||
|
return [iv, authTag, ciphertext].map((buffer) => buffer.toString('hex')).join(':');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main(): Promise<void> {
|
||||||
|
const encryptionKeyHex = requireEnv('ENCRYPTION_KEY');
|
||||||
|
const masterKey = Buffer.from(encryptionKeyHex, 'hex');
|
||||||
|
if (masterKey.length !== 32) {
|
||||||
|
throw new Error('ENCRYPTION_KEY doit faire exactement 32 octets (64 caracteres hexadecimaux)');
|
||||||
|
}
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
try {
|
||||||
|
const hashedPassword = await bcrypt.hash(requireEnv('SEED_USER_PASSWORD'), BCRYPT_SALT_ROUNDS);
|
||||||
|
|
||||||
|
const user = await prisma.user.upsert({
|
||||||
|
where: { email: requireEnv('SEED_USER_EMAIL') },
|
||||||
|
update: {},
|
||||||
|
create: {
|
||||||
|
firstName: requireEnv('SEED_USER_FIRST_NAME'),
|
||||||
|
lastName: requireEnv('SEED_USER_LAST_NAME'),
|
||||||
|
email: requireEnv('SEED_USER_EMAIL'),
|
||||||
|
password: hashedPassword,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const apiKeys: { serviceName: string; value: string }[] = [
|
||||||
|
{ serviceName: 'elevenlabs_api_key', value: requireEnv('SEED_ELEVENLABS_API_KEY') },
|
||||||
|
{ serviceName: 'elevenlabs_voice_id', value: requireEnv('SEED_ELEVENLABS_VOICE_ID') },
|
||||||
|
{ serviceName: 'openrouter_api_key', value: requireEnv('SEED_OPENROUTER_API_KEY') },
|
||||||
|
{ serviceName: 'openrouter_model', value: requireEnv('SEED_OPENROUTER_MODEL') },
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const { serviceName, value } of apiKeys) {
|
||||||
|
await prisma.apiKey.upsert({
|
||||||
|
where: { userId_serviceName: { userId: user.id, serviceName } },
|
||||||
|
update: { key: encrypt(value, masterKey) },
|
||||||
|
create: { userId: user.id, serviceName, key: encrypt(value, masterKey) },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// eslint-disable-next-line no-console -- script CLI ponctuel, pas du code applicatif en continu
|
||||||
|
console.log(`Utilisateur "${user.email}" provisionne avec ${apiKeys.length} cle(s) API.`);
|
||||||
|
} finally {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((error: unknown) => {
|
||||||
|
console.error('[seed] echec du provisionnement :', error);
|
||||||
|
process.exitCode = 1;
|
||||||
|
});
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { ApiKeysController } from './api-keys.controller';
|
||||||
|
import { ApiKeysService } from './api-keys.service';
|
||||||
|
|
||||||
|
describe('ApiKeysController', () => {
|
||||||
|
let controller: ApiKeysController;
|
||||||
|
let service: Record<keyof ApiKeysService, jest.Mock>;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
service = {
|
||||||
|
create: jest.fn(),
|
||||||
|
findAll: jest.fn(),
|
||||||
|
findOne: jest.fn(),
|
||||||
|
update: jest.fn(),
|
||||||
|
remove: jest.fn(),
|
||||||
|
getDecryptedValue: jest.fn(),
|
||||||
|
getAllDecrypted: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
controllers: [ApiKeysController],
|
||||||
|
providers: [{ provide: ApiKeysService, useValue: service }],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
controller = module.get<ApiKeysController>(ApiKeysController);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delegate create() to the service', async () => {
|
||||||
|
const dto = {
|
||||||
|
userId: 1,
|
||||||
|
serviceName: 'openrouter_api_key',
|
||||||
|
key: 'sk-or-v1-x',
|
||||||
|
};
|
||||||
|
service.create.mockResolvedValue({ id: 1 });
|
||||||
|
|
||||||
|
const result = await controller.create(dto);
|
||||||
|
|
||||||
|
expect(service.create).toHaveBeenCalledWith(dto);
|
||||||
|
expect(result).toEqual({ id: 1 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delegate findAll() without a filter', async () => {
|
||||||
|
service.findAll.mockResolvedValue([{ id: 1 }]);
|
||||||
|
|
||||||
|
const result = await controller.findAll(undefined);
|
||||||
|
|
||||||
|
expect(service.findAll).toHaveBeenCalledWith(undefined);
|
||||||
|
expect(result).toEqual([{ id: 1 }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delegate findAll() with a userId filter', async () => {
|
||||||
|
service.findAll.mockResolvedValue([{ id: 1, userId: 1 }]);
|
||||||
|
|
||||||
|
await controller.findAll(1);
|
||||||
|
|
||||||
|
expect(service.findAll).toHaveBeenCalledWith(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delegate findOne() to the service', async () => {
|
||||||
|
service.findOne.mockResolvedValue({ id: 1 });
|
||||||
|
|
||||||
|
const result = await controller.findOne(1);
|
||||||
|
|
||||||
|
expect(service.findOne).toHaveBeenCalledWith(1);
|
||||||
|
expect(result).toEqual({ id: 1 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delegate update() to the service', async () => {
|
||||||
|
service.update.mockResolvedValue({ id: 1, serviceName: 'nouveau_nom' });
|
||||||
|
|
||||||
|
const result = await controller.update(1, { serviceName: 'nouveau_nom' });
|
||||||
|
|
||||||
|
expect(service.update).toHaveBeenCalledWith(1, {
|
||||||
|
serviceName: 'nouveau_nom',
|
||||||
|
});
|
||||||
|
expect(result).toEqual({ id: 1, serviceName: 'nouveau_nom' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delegate remove() to the service', async () => {
|
||||||
|
service.remove.mockResolvedValue(undefined);
|
||||||
|
|
||||||
|
await controller.remove(1);
|
||||||
|
|
||||||
|
expect(service.remove).toHaveBeenCalledWith(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Delete,
|
||||||
|
Get,
|
||||||
|
HttpCode,
|
||||||
|
HttpStatus,
|
||||||
|
Param,
|
||||||
|
ParseIntPipe,
|
||||||
|
Patch,
|
||||||
|
Post,
|
||||||
|
Query,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { ApiOperation, ApiQuery, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { ApiKeyResponseDto } from './dto/api-key-response.dto';
|
||||||
|
import { CreateApiKeyDto } from './dto/create-api-key.dto';
|
||||||
|
import { UpdateApiKeyDto } from './dto/update-api-key.dto';
|
||||||
|
import { ApiKeysService } from './api-keys.service';
|
||||||
|
|
||||||
|
@ApiTags('api-keys')
|
||||||
|
@Controller('api-keys')
|
||||||
|
export class ApiKeysController {
|
||||||
|
constructor(private readonly apiKeysService: ApiKeysService) {}
|
||||||
|
|
||||||
|
@Post()
|
||||||
|
@ApiOperation({
|
||||||
|
summary:
|
||||||
|
'Enregistrer une cle API pour un utilisateur (chiffree avant stockage)',
|
||||||
|
})
|
||||||
|
@ApiResponse({ status: HttpStatus.CREATED, type: ApiKeyResponseDto })
|
||||||
|
@ApiResponse({
|
||||||
|
status: HttpStatus.CONFLICT,
|
||||||
|
description: 'Cle deja presente pour ce service',
|
||||||
|
})
|
||||||
|
create(@Body() dto: CreateApiKeyDto): Promise<ApiKeyResponseDto> {
|
||||||
|
return this.apiKeysService.create(dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
@ApiOperation({
|
||||||
|
summary:
|
||||||
|
'Lister les cles API (sans leur valeur), filtrable par utilisateur',
|
||||||
|
})
|
||||||
|
@ApiQuery({ name: 'userId', required: false, type: Number })
|
||||||
|
@ApiResponse({ status: HttpStatus.OK, type: [ApiKeyResponseDto] })
|
||||||
|
findAll(
|
||||||
|
@Query('userId', new ParseIntPipe({ optional: true })) userId?: number,
|
||||||
|
): Promise<ApiKeyResponseDto[]> {
|
||||||
|
return this.apiKeysService.findAll(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':id')
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Recuperer une cle API (sans sa valeur) par son id',
|
||||||
|
})
|
||||||
|
@ApiResponse({ status: HttpStatus.OK, type: ApiKeyResponseDto })
|
||||||
|
@ApiResponse({ status: HttpStatus.NOT_FOUND, description: 'Cle introuvable' })
|
||||||
|
findOne(@Param('id', ParseIntPipe) id: number): Promise<ApiKeyResponseDto> {
|
||||||
|
return this.apiKeysService.findOne(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch(':id')
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Mettre a jour une cle API (nom de service et/ou valeur)',
|
||||||
|
})
|
||||||
|
@ApiResponse({ status: HttpStatus.OK, type: ApiKeyResponseDto })
|
||||||
|
@ApiResponse({ status: HttpStatus.NOT_FOUND, description: 'Cle introuvable' })
|
||||||
|
update(
|
||||||
|
@Param('id', ParseIntPipe) id: number,
|
||||||
|
@Body() dto: UpdateApiKeyDto,
|
||||||
|
): Promise<ApiKeyResponseDto> {
|
||||||
|
return this.apiKeysService.update(id, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete(':id')
|
||||||
|
@HttpCode(HttpStatus.NO_CONTENT)
|
||||||
|
@ApiOperation({ summary: 'Supprimer une cle API' })
|
||||||
|
@ApiResponse({ status: HttpStatus.NO_CONTENT })
|
||||||
|
@ApiResponse({ status: HttpStatus.NOT_FOUND, description: 'Cle introuvable' })
|
||||||
|
remove(@Param('id', ParseIntPipe) id: number): Promise<void> {
|
||||||
|
return this.apiKeysService.remove(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { ApiKeysController } from './api-keys.controller';
|
||||||
|
import { ApiKeysService } from './api-keys.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
controllers: [ApiKeysController],
|
||||||
|
providers: [ApiKeysService],
|
||||||
|
exports: [ApiKeysService],
|
||||||
|
})
|
||||||
|
export class ApiKeysModule {}
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
import { ConflictException, NotFoundException } from '@nestjs/common';
|
||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { Prisma } from '@prisma/client';
|
||||||
|
import { EncryptionService } from '../common/crypto/encryption.service';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import { ApiKeysService } from './api-keys.service';
|
||||||
|
|
||||||
|
function prismaKnownError(code: string): Prisma.PrismaClientKnownRequestError {
|
||||||
|
return new Prisma.PrismaClientKnownRequestError('mock', {
|
||||||
|
code,
|
||||||
|
clientVersion: 'test',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('ApiKeysService', () => {
|
||||||
|
let service: ApiKeysService;
|
||||||
|
let prisma: {
|
||||||
|
apiKey: {
|
||||||
|
create: jest.Mock;
|
||||||
|
findMany: jest.Mock;
|
||||||
|
findUnique: jest.Mock;
|
||||||
|
update: jest.Mock;
|
||||||
|
delete: jest.Mock;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
let encryption: { encrypt: jest.Mock; decrypt: jest.Mock };
|
||||||
|
|
||||||
|
const dbApiKey = {
|
||||||
|
id: 1,
|
||||||
|
userId: 1,
|
||||||
|
serviceName: 'openrouter_api_key',
|
||||||
|
key: 'encrypted-payload',
|
||||||
|
createdAt: new Date('2026-01-01'),
|
||||||
|
updatedAt: new Date('2026-01-01'),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
prisma = {
|
||||||
|
apiKey: {
|
||||||
|
create: jest.fn(),
|
||||||
|
findMany: jest.fn(),
|
||||||
|
findUnique: jest.fn(),
|
||||||
|
update: jest.fn(),
|
||||||
|
delete: jest.fn(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
encryption = {
|
||||||
|
encrypt: jest.fn().mockReturnValue('encrypted-payload'),
|
||||||
|
decrypt: jest.fn().mockReturnValue('sk-or-v1-plaintext'),
|
||||||
|
};
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
ApiKeysService,
|
||||||
|
{ provide: PrismaService, useValue: prisma },
|
||||||
|
{ provide: EncryptionService, useValue: encryption },
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
service = module.get<ApiKeysService>(ApiKeysService);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('create()', () => {
|
||||||
|
it('should encrypt the key before storing it and never return it', async () => {
|
||||||
|
prisma.apiKey.create.mockResolvedValue(dbApiKey);
|
||||||
|
|
||||||
|
const result = await service.create({
|
||||||
|
userId: 1,
|
||||||
|
serviceName: 'openrouter_api_key',
|
||||||
|
key: 'sk-or-v1-plaintext',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(encryption.encrypt).toHaveBeenCalledWith('sk-or-v1-plaintext');
|
||||||
|
expect(result).not.toHaveProperty('key');
|
||||||
|
expect(result.serviceName).toBe('openrouter_api_key');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw ConflictException when the service already has a key for this user', async () => {
|
||||||
|
prisma.apiKey.create.mockRejectedValue(prismaKnownError('P2002'));
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.create({
|
||||||
|
userId: 1,
|
||||||
|
serviceName: 'openrouter_api_key',
|
||||||
|
key: 'x',
|
||||||
|
}),
|
||||||
|
).rejects.toThrow(ConflictException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should rethrow unexpected errors', async () => {
|
||||||
|
prisma.apiKey.create.mockRejectedValue(new Error('boom'));
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.create({
|
||||||
|
userId: 1,
|
||||||
|
serviceName: 'openrouter_api_key',
|
||||||
|
key: 'x',
|
||||||
|
}),
|
||||||
|
).rejects.toThrow('boom');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('findAll()', () => {
|
||||||
|
it('should list all keys without filtering when no userId is given', async () => {
|
||||||
|
prisma.apiKey.findMany.mockResolvedValue([dbApiKey]);
|
||||||
|
|
||||||
|
const result = await service.findAll();
|
||||||
|
|
||||||
|
expect(prisma.apiKey.findMany).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ where: undefined }),
|
||||||
|
);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0]).not.toHaveProperty('key');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should filter by userId when given', async () => {
|
||||||
|
prisma.apiKey.findMany.mockResolvedValue([dbApiKey]);
|
||||||
|
|
||||||
|
await service.findAll(1);
|
||||||
|
|
||||||
|
expect(prisma.apiKey.findMany).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ where: { userId: 1 } }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('findOne()', () => {
|
||||||
|
it('should return the key metadata when found', async () => {
|
||||||
|
prisma.apiKey.findUnique.mockResolvedValue(dbApiKey);
|
||||||
|
|
||||||
|
const result = await service.findOne(1);
|
||||||
|
|
||||||
|
expect(result.id).toBe(1);
|
||||||
|
expect(result).not.toHaveProperty('key');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw NotFoundException when missing', async () => {
|
||||||
|
prisma.apiKey.findUnique.mockResolvedValue(null);
|
||||||
|
|
||||||
|
await expect(service.findOne(999)).rejects.toThrow(NotFoundException);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('update()', () => {
|
||||||
|
it('should re-encrypt the key when a new value is provided', async () => {
|
||||||
|
prisma.apiKey.update.mockResolvedValue(dbApiKey);
|
||||||
|
|
||||||
|
await service.update(1, { key: 'nouvelle-valeur' });
|
||||||
|
|
||||||
|
expect(encryption.encrypt).toHaveBeenCalledWith('nouvelle-valeur');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not touch the key field when no new value is provided', async () => {
|
||||||
|
prisma.apiKey.update.mockResolvedValue(dbApiKey);
|
||||||
|
|
||||||
|
await service.update(1, { serviceName: 'nouveau_nom' });
|
||||||
|
|
||||||
|
const updateArgs = (
|
||||||
|
prisma.apiKey.update.mock.calls[0] as [Prisma.ApiKeyUpdateArgs]
|
||||||
|
)[0];
|
||||||
|
expect(updateArgs.data.key).toBeUndefined();
|
||||||
|
expect(encryption.encrypt).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw NotFoundException when the key does not exist', async () => {
|
||||||
|
prisma.apiKey.update.mockRejectedValue(prismaKnownError('P2025'));
|
||||||
|
|
||||||
|
await expect(service.update(999, { serviceName: 'x' })).rejects.toThrow(
|
||||||
|
NotFoundException,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw ConflictException on duplicate (userId, serviceName)', async () => {
|
||||||
|
prisma.apiKey.update.mockRejectedValue(prismaKnownError('P2002'));
|
||||||
|
|
||||||
|
await expect(service.update(1, { serviceName: 'dup' })).rejects.toThrow(
|
||||||
|
ConflictException,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should rethrow unexpected errors', async () => {
|
||||||
|
prisma.apiKey.update.mockRejectedValue(new Error('boom'));
|
||||||
|
|
||||||
|
await expect(service.update(1, { serviceName: 'x' })).rejects.toThrow(
|
||||||
|
'boom',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('remove()', () => {
|
||||||
|
it('should delete the key', async () => {
|
||||||
|
prisma.apiKey.delete.mockResolvedValue(dbApiKey);
|
||||||
|
|
||||||
|
await expect(service.remove(1)).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw NotFoundException when the key does not exist', async () => {
|
||||||
|
prisma.apiKey.delete.mockRejectedValue(prismaKnownError('P2025'));
|
||||||
|
|
||||||
|
await expect(service.remove(999)).rejects.toThrow(NotFoundException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should rethrow unexpected errors', async () => {
|
||||||
|
prisma.apiKey.delete.mockRejectedValue(new Error('boom'));
|
||||||
|
|
||||||
|
await expect(service.remove(1)).rejects.toThrow('boom');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getDecryptedValue()', () => {
|
||||||
|
it('should return the decrypted plaintext value for internal use', async () => {
|
||||||
|
prisma.apiKey.findUnique.mockResolvedValue(dbApiKey);
|
||||||
|
|
||||||
|
const value = await service.getDecryptedValue(1, 'openrouter_api_key');
|
||||||
|
|
||||||
|
expect(prisma.apiKey.findUnique).toHaveBeenCalledWith({
|
||||||
|
where: {
|
||||||
|
userId_serviceName: { userId: 1, serviceName: 'openrouter_api_key' },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(encryption.decrypt).toHaveBeenCalledWith('encrypted-payload');
|
||||||
|
expect(value).toBe('sk-or-v1-plaintext');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw NotFoundException when no key exists for this service', async () => {
|
||||||
|
prisma.apiKey.findUnique.mockResolvedValue(null);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.getDecryptedValue(1, 'unknown_service'),
|
||||||
|
).rejects.toThrow(NotFoundException);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getAllDecrypted()', () => {
|
||||||
|
it('should return a map of serviceName to decrypted value for every key of the user', async () => {
|
||||||
|
prisma.apiKey.findMany.mockResolvedValue([
|
||||||
|
dbApiKey,
|
||||||
|
{
|
||||||
|
...dbApiKey,
|
||||||
|
id: 2,
|
||||||
|
serviceName: 'elevenlabs_api_key',
|
||||||
|
key: 'other-encrypted',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
encryption.decrypt.mockImplementation((payload: string) =>
|
||||||
|
payload === 'other-encrypted'
|
||||||
|
? 'sk-el-plaintext'
|
||||||
|
: 'sk-or-v1-plaintext',
|
||||||
|
);
|
||||||
|
|
||||||
|
const result = await service.getAllDecrypted(1);
|
||||||
|
|
||||||
|
expect(prisma.apiKey.findMany).toHaveBeenCalledWith({
|
||||||
|
where: { userId: 1 },
|
||||||
|
});
|
||||||
|
expect(result).toEqual({
|
||||||
|
openrouter_api_key: 'sk-or-v1-plaintext',
|
||||||
|
elevenlabs_api_key: 'sk-el-plaintext',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return an empty object when the user has no keys', async () => {
|
||||||
|
prisma.apiKey.findMany.mockResolvedValue([]);
|
||||||
|
|
||||||
|
await expect(service.getAllDecrypted(1)).resolves.toEqual({});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import {
|
||||||
|
ConflictException,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { ApiKey, Prisma } from '@prisma/client';
|
||||||
|
import { EncryptionService } from '../common/crypto/encryption.service';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import { ApiKeyResponseDto } from './dto/api-key-response.dto';
|
||||||
|
import { CreateApiKeyDto } from './dto/create-api-key.dto';
|
||||||
|
import { UpdateApiKeyDto } from './dto/update-api-key.dto';
|
||||||
|
|
||||||
|
const UNIQUE_CONSTRAINT_VIOLATION = 'P2002';
|
||||||
|
const RECORD_NOT_FOUND = 'P2025';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ApiKeysService {
|
||||||
|
constructor(
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly encryption: EncryptionService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async create(dto: CreateApiKeyDto): Promise<ApiKeyResponseDto> {
|
||||||
|
try {
|
||||||
|
const apiKey = await this.prisma.apiKey.create({
|
||||||
|
data: {
|
||||||
|
userId: dto.userId,
|
||||||
|
serviceName: dto.serviceName,
|
||||||
|
key: this.encryption.encrypt(dto.key),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return this.toResponse(apiKey);
|
||||||
|
} catch (error) {
|
||||||
|
if (
|
||||||
|
error instanceof Prisma.PrismaClientKnownRequestError &&
|
||||||
|
error.code === UNIQUE_CONSTRAINT_VIOLATION
|
||||||
|
) {
|
||||||
|
throw new ConflictException(
|
||||||
|
`L'utilisateur ${dto.userId} a deja une cle enregistree pour "${dto.serviceName}"`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async findAll(userId?: number): Promise<ApiKeyResponseDto[]> {
|
||||||
|
const apiKeys = await this.prisma.apiKey.findMany({
|
||||||
|
where: userId === undefined ? undefined : { userId },
|
||||||
|
orderBy: { id: 'asc' },
|
||||||
|
});
|
||||||
|
return apiKeys.map((apiKey) => this.toResponse(apiKey));
|
||||||
|
}
|
||||||
|
|
||||||
|
async findOne(id: number): Promise<ApiKeyResponseDto> {
|
||||||
|
const apiKey = await this.prisma.apiKey.findUnique({ where: { id } });
|
||||||
|
if (!apiKey) throw new NotFoundException(`Cle API ${id} introuvable`);
|
||||||
|
return this.toResponse(apiKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(id: number, dto: UpdateApiKeyDto): Promise<ApiKeyResponseDto> {
|
||||||
|
const data: Prisma.ApiKeyUpdateInput = { serviceName: dto.serviceName };
|
||||||
|
if (dto.key) {
|
||||||
|
data.key = this.encryption.encrypt(dto.key);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const apiKey = await this.prisma.apiKey.update({ where: { id }, data });
|
||||||
|
return this.toResponse(apiKey);
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof Prisma.PrismaClientKnownRequestError) {
|
||||||
|
if (error.code === RECORD_NOT_FOUND)
|
||||||
|
throw new NotFoundException(`Cle API ${id} introuvable`);
|
||||||
|
if (error.code === UNIQUE_CONSTRAINT_VIOLATION) {
|
||||||
|
throw new ConflictException(
|
||||||
|
`Une cle existe deja pour ce service chez cet utilisateur`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async remove(id: number): Promise<void> {
|
||||||
|
try {
|
||||||
|
await this.prisma.apiKey.delete({ where: { id } });
|
||||||
|
} catch (error) {
|
||||||
|
if (
|
||||||
|
error instanceof Prisma.PrismaClientKnownRequestError &&
|
||||||
|
error.code === RECORD_NOT_FOUND
|
||||||
|
) {
|
||||||
|
throw new NotFoundException(`Cle API ${id} introuvable`);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Usage interne uniquement (ex: futur service de proxy vers OpenRouter/ElevenLabs) : jamais
|
||||||
|
* expose directement via un controleur HTTP. Renvoie la valeur en clair.
|
||||||
|
*/
|
||||||
|
async getDecryptedValue(
|
||||||
|
userId: number,
|
||||||
|
serviceName: string,
|
||||||
|
): Promise<string> {
|
||||||
|
const apiKey = await this.prisma.apiKey.findUnique({
|
||||||
|
where: { userId_serviceName: { userId, serviceName } },
|
||||||
|
});
|
||||||
|
if (!apiKey) {
|
||||||
|
throw new NotFoundException(
|
||||||
|
`Aucune cle "${serviceName}" pour l'utilisateur ${userId}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return this.encryption.decrypt(apiKey.key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Usage interne uniquement (AuthService, apres connexion reussie) : dechiffre toutes les cles
|
||||||
|
* d'un utilisateur en une fois, sous forme `{ serviceName: valeur en clair }`. Jamais expose par
|
||||||
|
* une route generique /api-keys — uniquement via la route /auth/me/keys, protegee par JWT, qui
|
||||||
|
* ne peut renvoyer que les cles de l'utilisateur authentifie lui-meme.
|
||||||
|
*/
|
||||||
|
async getAllDecrypted(userId: number): Promise<Record<string, string>> {
|
||||||
|
const apiKeys = await this.prisma.apiKey.findMany({ where: { userId } });
|
||||||
|
const result: Record<string, string> = {};
|
||||||
|
for (const apiKey of apiKeys) {
|
||||||
|
result[apiKey.serviceName] = this.encryption.decrypt(apiKey.key);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ne jamais inclure la valeur de la cle (meme chiffree) dans une reponse HTTP. */
|
||||||
|
private toResponse(apiKey: ApiKey): ApiKeyResponseDto {
|
||||||
|
return {
|
||||||
|
id: apiKey.id,
|
||||||
|
userId: apiKey.userId,
|
||||||
|
serviceName: apiKey.serviceName,
|
||||||
|
createdAt: apiKey.createdAt,
|
||||||
|
updatedAt: apiKey.updatedAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ne contient jamais la valeur de la cle (ni chiffree ni dechiffree) : une fois creee, la cle
|
||||||
|
* n'est plus jamais renvoyee par l'API. Seul le backend lui-meme, via
|
||||||
|
* ApiKeysService.getDecryptedValue(), peut la lire pour appeler le service externe correspondant.
|
||||||
|
*/
|
||||||
|
export class ApiKeyResponseDto {
|
||||||
|
@ApiProperty({ example: 1 })
|
||||||
|
id!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 1 })
|
||||||
|
userId!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'openrouter_api_key' })
|
||||||
|
serviceName!: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
createdAt!: Date;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
updatedAt!: Date;
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsInt, IsString, Min, MinLength } from 'class-validator';
|
||||||
|
|
||||||
|
export class CreateApiKeyDto {
|
||||||
|
@ApiProperty({ example: 1 })
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
userId!: number;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
example: 'openrouter_api_key',
|
||||||
|
description:
|
||||||
|
'Identifiant du service cible (openrouter_api_key, elevenlabs_api_key, ...).',
|
||||||
|
})
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
serviceName!: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
example: 'sk-or-v1-...',
|
||||||
|
description:
|
||||||
|
"Valeur en clair, chiffree (AES-256-GCM) avant stockage. Jamais renvoyee telle quelle par l'API.",
|
||||||
|
})
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
key!: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { OmitType, PartialType } from '@nestjs/swagger';
|
||||||
|
import { CreateApiKeyDto } from './create-api-key.dto';
|
||||||
|
|
||||||
|
// Changer le userId d'une cle n'a pas de sens via une mise a jour partielle : supprimer et
|
||||||
|
// recreer la cle sous le bon utilisateur plutot.
|
||||||
|
export class UpdateApiKeyDto extends PartialType(
|
||||||
|
OmitType(CreateApiKeyDto, ['userId'] as const),
|
||||||
|
) {}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { AppController } from './app.controller';
|
||||||
|
|
||||||
|
describe('AppController', () => {
|
||||||
|
let appController: AppController;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const app: TestingModule = await Test.createTestingModule({
|
||||||
|
controllers: [AppController],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
appController = app.get<AppController>(AppController);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getHealth()', () => {
|
||||||
|
it('should return ok status', () => {
|
||||||
|
expect(appController.getHealth()).toEqual({ status: 'ok' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { Controller, Get } from '@nestjs/common';
|
||||||
|
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
@ApiTags('health')
|
||||||
|
@Controller()
|
||||||
|
export class AppController {
|
||||||
|
@Get('health')
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Verifie que l'API et sa base de donnees repondent",
|
||||||
|
})
|
||||||
|
getHealth(): { status: 'ok' } {
|
||||||
|
return { status: 'ok' };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
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],
|
||||||
|
})
|
||||||
|
export class AppModule {}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { AuthController } from './auth.controller';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
import { JwtAuthGuard } from './jwt-auth.guard';
|
||||||
|
import type { AuthenticatedRequest } from './jwt-auth.guard';
|
||||||
|
|
||||||
|
describe('AuthController', () => {
|
||||||
|
let controller: AuthController;
|
||||||
|
let service: Record<keyof AuthService, jest.Mock>;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
service = {
|
||||||
|
login: jest.fn(),
|
||||||
|
getDecryptedKeysForUser: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
controllers: [AuthController],
|
||||||
|
providers: [{ provide: AuthService, useValue: service }],
|
||||||
|
})
|
||||||
|
.overrideGuard(JwtAuthGuard)
|
||||||
|
.useValue({ canActivate: () => true })
|
||||||
|
.compile();
|
||||||
|
|
||||||
|
controller = module.get<AuthController>(AuthController);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delegate login() to the service', async () => {
|
||||||
|
const dto = { email: 'william@example.com', password: 'x' };
|
||||||
|
service.login.mockResolvedValue({ accessToken: 'jwt', user: { id: 1 } });
|
||||||
|
|
||||||
|
const result = await controller.login(dto);
|
||||||
|
|
||||||
|
expect(service.login).toHaveBeenCalledWith(dto);
|
||||||
|
expect(result).toEqual({ accessToken: 'jwt', user: { id: 1 } });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delegate getMyKeys() to the service using the authenticated user id', async () => {
|
||||||
|
service.getDecryptedKeysForUser.mockResolvedValue({
|
||||||
|
openrouter_api_key: 'sk-or-v1-x',
|
||||||
|
});
|
||||||
|
const request = {
|
||||||
|
user: { sub: 1, email: 'william@example.com' },
|
||||||
|
} as AuthenticatedRequest;
|
||||||
|
|
||||||
|
const result = await controller.getMyKeys(request);
|
||||||
|
|
||||||
|
expect(service.getDecryptedKeysForUser).toHaveBeenCalledWith(1);
|
||||||
|
expect(result).toEqual({ openrouter_api_key: 'sk-or-v1-x' });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
HttpStatus,
|
||||||
|
Post,
|
||||||
|
Req,
|
||||||
|
UseGuards,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiOperation,
|
||||||
|
ApiResponse,
|
||||||
|
ApiTags,
|
||||||
|
} from '@nestjs/swagger';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
import { LoginDto } from './dto/login.dto';
|
||||||
|
import { LoginResponseDto } from './dto/login-response.dto';
|
||||||
|
import { JwtAuthGuard } from './jwt-auth.guard';
|
||||||
|
import type { AuthenticatedRequest } from './jwt-auth.guard';
|
||||||
|
|
||||||
|
@ApiTags('auth')
|
||||||
|
@Controller('auth')
|
||||||
|
export class AuthController {
|
||||||
|
constructor(private readonly authService: AuthService) {}
|
||||||
|
|
||||||
|
@Post('login')
|
||||||
|
@ApiOperation({ summary: 'Authentifier un utilisateur et obtenir un jeton' })
|
||||||
|
@ApiResponse({ status: HttpStatus.OK, type: LoginResponseDto })
|
||||||
|
@ApiResponse({
|
||||||
|
status: HttpStatus.UNAUTHORIZED,
|
||||||
|
description: 'Email ou mot de passe incorrect',
|
||||||
|
})
|
||||||
|
login(@Body() dto: LoginDto): Promise<LoginResponseDto> {
|
||||||
|
return this.authService.login(dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('me/keys')
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@ApiOperation({
|
||||||
|
summary:
|
||||||
|
"Recuperer les cles API dechiffrees de l'utilisateur authentifie (service -> valeur en clair)",
|
||||||
|
})
|
||||||
|
@ApiResponse({ status: HttpStatus.OK })
|
||||||
|
@ApiResponse({ status: HttpStatus.UNAUTHORIZED })
|
||||||
|
getMyKeys(
|
||||||
|
@Req() request: AuthenticatedRequest,
|
||||||
|
): Promise<Record<string, string>> {
|
||||||
|
return this.authService.getDecryptedKeysForUser(request.user.sub);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
|
import { JwtModule } from '@nestjs/jwt';
|
||||||
|
import { ApiKeysModule } from '../api-keys/api-keys.module';
|
||||||
|
import { UsersModule } from '../users/users.module';
|
||||||
|
import { AuthController } from './auth.controller';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
import { JwtAuthGuard } from './jwt-auth.guard';
|
||||||
|
|
||||||
|
const ACCESS_TOKEN_TTL = '1h';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
UsersModule,
|
||||||
|
ApiKeysModule,
|
||||||
|
JwtModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
inject: [ConfigService],
|
||||||
|
useFactory: (config: ConfigService) => ({
|
||||||
|
secret: config.getOrThrow<string>('JWT_SECRET'),
|
||||||
|
signOptions: { expiresIn: ACCESS_TOKEN_TTL },
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
controllers: [AuthController],
|
||||||
|
providers: [AuthService, JwtAuthGuard],
|
||||||
|
// JwtModule doit aussi etre exporte : JwtAuthGuard est instancie dans le contexte d'injection du
|
||||||
|
// module CONSOMMATEUR (ex: SessionsModule) quand il est utilise via @UseGuards() hors d'AuthModule,
|
||||||
|
// et a donc besoin d'y resoudre JwtService lui-meme (sinon UnknownDependenciesException).
|
||||||
|
exports: [JwtAuthGuard, JwtModule],
|
||||||
|
})
|
||||||
|
export class AuthModule {}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import { UnauthorizedException } from '@nestjs/common';
|
||||||
|
import { JwtService } from '@nestjs/jwt';
|
||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import * as bcrypt from 'bcrypt';
|
||||||
|
import { ApiKeysService } from '../api-keys/api-keys.service';
|
||||||
|
import { UsersService } from '../users/users.service';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
|
||||||
|
describe('AuthService', () => {
|
||||||
|
let service: AuthService;
|
||||||
|
let usersService: { findByEmailForAuth: jest.Mock };
|
||||||
|
let apiKeysService: { getAllDecrypted: jest.Mock };
|
||||||
|
let jwtService: { signAsync: jest.Mock };
|
||||||
|
|
||||||
|
const dbUser = {
|
||||||
|
id: 1,
|
||||||
|
firstName: 'William',
|
||||||
|
lastName: 'Vandal',
|
||||||
|
email: 'william@example.com',
|
||||||
|
password: '',
|
||||||
|
createdAt: new Date('2026-01-01'),
|
||||||
|
updatedAt: new Date('2026-01-01'),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
dbUser.password = await bcrypt.hash('le-bon-mot-de-passe', 12);
|
||||||
|
|
||||||
|
usersService = { findByEmailForAuth: jest.fn() };
|
||||||
|
apiKeysService = { getAllDecrypted: jest.fn() };
|
||||||
|
jwtService = { signAsync: jest.fn().mockResolvedValue('signed-jwt') };
|
||||||
|
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
AuthService,
|
||||||
|
{ provide: UsersService, useValue: usersService },
|
||||||
|
{ provide: ApiKeysService, useValue: apiKeysService },
|
||||||
|
{ provide: JwtService, useValue: jwtService },
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get<AuthService>(AuthService);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('login()', () => {
|
||||||
|
it('should return an access token and the user when the password matches', async () => {
|
||||||
|
usersService.findByEmailForAuth.mockResolvedValue(dbUser);
|
||||||
|
|
||||||
|
const result = await service.login({
|
||||||
|
email: 'william@example.com',
|
||||||
|
password: 'le-bon-mot-de-passe',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.accessToken).toBe('signed-jwt');
|
||||||
|
expect(result.user).not.toHaveProperty('password');
|
||||||
|
expect(jwtService.signAsync).toHaveBeenCalledWith({
|
||||||
|
sub: 1,
|
||||||
|
email: 'william@example.com',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw UnauthorizedException when the email is unknown', async () => {
|
||||||
|
usersService.findByEmailForAuth.mockResolvedValue(null);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.login({ email: 'inconnu@example.com', password: 'x' }),
|
||||||
|
).rejects.toThrow(UnauthorizedException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw UnauthorizedException when the password is wrong', async () => {
|
||||||
|
usersService.findByEmailForAuth.mockResolvedValue(dbUser);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.login({
|
||||||
|
email: 'william@example.com',
|
||||||
|
password: 'mauvais-mot-de-passe',
|
||||||
|
}),
|
||||||
|
).rejects.toThrow(UnauthorizedException);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getDecryptedKeysForUser()', () => {
|
||||||
|
it('should delegate to ApiKeysService.getAllDecrypted', async () => {
|
||||||
|
apiKeysService.getAllDecrypted.mockResolvedValue({
|
||||||
|
openrouter_api_key: 'sk-or-v1-x',
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await service.getDecryptedKeysForUser(1);
|
||||||
|
|
||||||
|
expect(apiKeysService.getAllDecrypted).toHaveBeenCalledWith(1);
|
||||||
|
expect(result).toEqual({ openrouter_api_key: 'sk-or-v1-x' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||||
|
import { JwtService } from '@nestjs/jwt';
|
||||||
|
import * as bcrypt from 'bcrypt';
|
||||||
|
import { ApiKeysService } from '../api-keys/api-keys.service';
|
||||||
|
import { UsersService } from '../users/users.service';
|
||||||
|
import { LoginDto } from './dto/login.dto';
|
||||||
|
import { LoginResponseDto } from './dto/login-response.dto';
|
||||||
|
import { JwtPayload } from './jwt-payload.interface';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AuthService {
|
||||||
|
constructor(
|
||||||
|
private readonly usersService: UsersService,
|
||||||
|
private readonly apiKeysService: ApiKeysService,
|
||||||
|
private readonly jwtService: JwtService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async login(dto: LoginDto): Promise<LoginResponseDto> {
|
||||||
|
const user = await this.usersService.findByEmailForAuth(dto.email);
|
||||||
|
// Message volontairement generique (ni "email inconnu" ni "mot de passe incorrect") : ne pas
|
||||||
|
// confirmer a un attaquant qu'un email donne correspond a un compte existant.
|
||||||
|
const invalidCredentials = (): never => {
|
||||||
|
throw new UnauthorizedException('Email ou mot de passe incorrect');
|
||||||
|
};
|
||||||
|
if (!user) return invalidCredentials();
|
||||||
|
|
||||||
|
const passwordMatches = await bcrypt.compare(dto.password, user.password);
|
||||||
|
if (!passwordMatches) return invalidCredentials();
|
||||||
|
|
||||||
|
const payload: JwtPayload = { sub: user.id, email: user.email };
|
||||||
|
const accessToken = await this.jwtService.signAsync(payload);
|
||||||
|
|
||||||
|
return {
|
||||||
|
accessToken,
|
||||||
|
user: {
|
||||||
|
id: user.id,
|
||||||
|
firstName: user.firstName,
|
||||||
|
lastName: user.lastName,
|
||||||
|
email: user.email,
|
||||||
|
createdAt: user.createdAt,
|
||||||
|
updatedAt: user.updatedAt,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cles de l'utilisateur authentifie uniquement (userId extrait du JWT verifie, jamais du body). */
|
||||||
|
getDecryptedKeysForUser(userId: number): Promise<Record<string, string>> {
|
||||||
|
return this.apiKeysService.getAllDecrypted(userId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { UserResponseDto } from '../../users/dto/user-response.dto';
|
||||||
|
|
||||||
|
export class LoginResponseDto {
|
||||||
|
@ApiProperty({
|
||||||
|
description:
|
||||||
|
'Jeton JWT, a transmettre dans "Authorization: Bearer <token>".',
|
||||||
|
})
|
||||||
|
accessToken!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ type: UserResponseDto })
|
||||||
|
user!: UserResponseDto;
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsEmail, IsString, MinLength } from 'class-validator';
|
||||||
|
|
||||||
|
export class LoginDto {
|
||||||
|
@ApiProperty({ example: 'william@example.com' })
|
||||||
|
@IsEmail()
|
||||||
|
email!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'un-mot-de-passe-robuste' })
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
password!: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import { ExecutionContext, UnauthorizedException } from '@nestjs/common';
|
||||||
|
import { JwtService } from '@nestjs/jwt';
|
||||||
|
import { AuthenticatedRequest, JwtAuthGuard } from './jwt-auth.guard';
|
||||||
|
|
||||||
|
function createContext(authorization?: string): ExecutionContext {
|
||||||
|
const request = { headers: { authorization } } as AuthenticatedRequest;
|
||||||
|
return {
|
||||||
|
switchToHttp: () => ({ getRequest: () => request }),
|
||||||
|
} as unknown as ExecutionContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('JwtAuthGuard', () => {
|
||||||
|
let guard: JwtAuthGuard;
|
||||||
|
let jwtService: { verifyAsync: jest.Mock };
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jwtService = { verifyAsync: jest.fn() };
|
||||||
|
guard = new JwtAuthGuard(jwtService as unknown as JwtService);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should allow the request and attach the payload when the token is valid', async () => {
|
||||||
|
jwtService.verifyAsync.mockResolvedValue({
|
||||||
|
sub: 1,
|
||||||
|
email: 'william@example.com',
|
||||||
|
});
|
||||||
|
const context = createContext('Bearer valid-token');
|
||||||
|
|
||||||
|
await expect(guard.canActivate(context)).resolves.toBe(true);
|
||||||
|
expect(jwtService.verifyAsync).toHaveBeenCalledWith('valid-token');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw UnauthorizedException when no Authorization header is present', async () => {
|
||||||
|
const context = createContext(undefined);
|
||||||
|
|
||||||
|
await expect(guard.canActivate(context)).rejects.toThrow(
|
||||||
|
UnauthorizedException,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw UnauthorizedException when the header does not start with "Bearer "', async () => {
|
||||||
|
const context = createContext('Basic abc');
|
||||||
|
|
||||||
|
await expect(guard.canActivate(context)).rejects.toThrow(
|
||||||
|
UnauthorizedException,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw UnauthorizedException when the token is invalid or expired', async () => {
|
||||||
|
jwtService.verifyAsync.mockRejectedValue(new Error('expired'));
|
||||||
|
const context = createContext('Bearer expired-token');
|
||||||
|
|
||||||
|
await expect(guard.canActivate(context)).rejects.toThrow(
|
||||||
|
UnauthorizedException,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import {
|
||||||
|
CanActivate,
|
||||||
|
ExecutionContext,
|
||||||
|
Injectable,
|
||||||
|
UnauthorizedException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { JwtService } from '@nestjs/jwt';
|
||||||
|
import type { Request } from 'express';
|
||||||
|
import type { JwtPayload } from './jwt-payload.interface';
|
||||||
|
|
||||||
|
export interface AuthenticatedRequest extends Request {
|
||||||
|
user: JwtPayload;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class JwtAuthGuard implements CanActivate {
|
||||||
|
constructor(private readonly jwtService: JwtService) {}
|
||||||
|
|
||||||
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||||
|
const request = context.switchToHttp().getRequest<AuthenticatedRequest>();
|
||||||
|
const authHeader = request.headers.authorization;
|
||||||
|
const token = authHeader?.startsWith('Bearer ')
|
||||||
|
? authHeader.slice('Bearer '.length)
|
||||||
|
: undefined;
|
||||||
|
if (!token) throw new UnauthorizedException('Jeton manquant');
|
||||||
|
|
||||||
|
try {
|
||||||
|
request.user = await this.jwtService.verifyAsync<JwtPayload>(token);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
throw new UnauthorizedException('Jeton invalide ou expire');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
export interface JwtPayload {
|
||||||
|
sub: number;
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { Global, Module } from '@nestjs/common';
|
||||||
|
import { EncryptionService } from './encryption.service';
|
||||||
|
|
||||||
|
@Global()
|
||||||
|
@Module({
|
||||||
|
providers: [EncryptionService],
|
||||||
|
exports: [EncryptionService],
|
||||||
|
})
|
||||||
|
export class CryptoModule {}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { EncryptionService } from './encryption.service';
|
||||||
|
|
||||||
|
const VALID_KEY_HEX = 'a'.repeat(64); // 32 octets
|
||||||
|
|
||||||
|
describe('EncryptionService', () => {
|
||||||
|
let service: EncryptionService;
|
||||||
|
let getOrThrow: jest.Mock;
|
||||||
|
|
||||||
|
async function createService(keyHex: string): Promise<EncryptionService> {
|
||||||
|
getOrThrow = jest.fn().mockReturnValue(keyHex);
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
EncryptionService,
|
||||||
|
{ provide: ConfigService, useValue: { getOrThrow } },
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
return module.get<EncryptionService>(EncryptionService);
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
service = await createService(VALID_KEY_HEX);
|
||||||
|
service.onModuleInit();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('encrypt() / decrypt()', () => {
|
||||||
|
it('should decrypt back to the original plaintext', () => {
|
||||||
|
const encrypted = service.encrypt('sk-or-v1-secret');
|
||||||
|
expect(service.decrypt(encrypted)).toBe('sk-or-v1-secret');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should produce a different ciphertext each time (random iv)', () => {
|
||||||
|
const first = service.encrypt('same-value');
|
||||||
|
const second = service.encrypt('same-value');
|
||||||
|
expect(first).not.toBe(second);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw when the payload format is invalid', () => {
|
||||||
|
expect(() => service.decrypt('not-a-valid-payload')).toThrow(
|
||||||
|
'Format de valeur chiffree invalide',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw when the auth tag has been tampered with', () => {
|
||||||
|
const encrypted = service.encrypt('sk-or-v1-secret');
|
||||||
|
const [iv, authTag, ciphertext] = encrypted.split(':');
|
||||||
|
const tampered = `${iv}:${'0'.repeat(authTag.length)}:${ciphertext}`;
|
||||||
|
expect(() => service.decrypt(tampered)).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('onModuleInit()', () => {
|
||||||
|
it('should throw when ENCRYPTION_KEY is not exactly 32 bytes', async () => {
|
||||||
|
const shortKeyService = await createService('abcd');
|
||||||
|
expect(() => shortKeyService.onModuleInit()).toThrow(/32 octets/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
|
||||||
|
import { Injectable, OnModuleInit } from '@nestjs/common';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
|
||||||
|
const ALGORITHM = 'aes-256-gcm';
|
||||||
|
const KEY_LENGTH_BYTES = 32;
|
||||||
|
const IV_LENGTH_BYTES = 12;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Chiffrement symetrique reversible (AES-256-GCM) pour les cles API stockees en base : elles
|
||||||
|
* doivent pouvoir etre dechiffrees pour appeler les services externes, contrairement a un mot de
|
||||||
|
* passe utilisateur qui lui est hache (sens unique, voir UsersService).
|
||||||
|
*/
|
||||||
|
@Injectable()
|
||||||
|
export class EncryptionService implements OnModuleInit {
|
||||||
|
private masterKey!: Buffer;
|
||||||
|
|
||||||
|
constructor(private readonly config: ConfigService) {}
|
||||||
|
|
||||||
|
onModuleInit(): void {
|
||||||
|
const hex = this.config.getOrThrow<string>('ENCRYPTION_KEY');
|
||||||
|
const key = Buffer.from(hex, 'hex');
|
||||||
|
if (key.length !== KEY_LENGTH_BYTES) {
|
||||||
|
throw new Error(
|
||||||
|
`ENCRYPTION_KEY doit faire exactement ${KEY_LENGTH_BYTES} octets (${KEY_LENGTH_BYTES * 2} caracteres hexadecimaux)`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
this.masterKey = key;
|
||||||
|
}
|
||||||
|
|
||||||
|
encrypt(plaintext: string): string {
|
||||||
|
const iv = randomBytes(IV_LENGTH_BYTES);
|
||||||
|
const cipher = createCipheriv(ALGORITHM, this.masterKey, iv);
|
||||||
|
const ciphertext = Buffer.concat([
|
||||||
|
cipher.update(plaintext, 'utf8'),
|
||||||
|
cipher.final(),
|
||||||
|
]);
|
||||||
|
const authTag = cipher.getAuthTag();
|
||||||
|
return [iv, authTag, ciphertext]
|
||||||
|
.map((buffer) => buffer.toString('hex'))
|
||||||
|
.join(':');
|
||||||
|
}
|
||||||
|
|
||||||
|
decrypt(payload: string): string {
|
||||||
|
const [ivHex, authTagHex, ciphertextHex] = payload.split(':');
|
||||||
|
if (!ivHex || !authTagHex || !ciphertextHex) {
|
||||||
|
throw new Error('Format de valeur chiffree invalide');
|
||||||
|
}
|
||||||
|
const decipher = createDecipheriv(
|
||||||
|
ALGORITHM,
|
||||||
|
this.masterKey,
|
||||||
|
Buffer.from(ivHex, 'hex'),
|
||||||
|
);
|
||||||
|
decipher.setAuthTag(Buffer.from(authTagHex, 'hex'));
|
||||||
|
return Buffer.concat([
|
||||||
|
decipher.update(Buffer.from(ciphertextHex, 'hex')),
|
||||||
|
decipher.final(),
|
||||||
|
]).toString('utf8');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
export type ApiErrorService = 'openrouter' | 'elevenlabs' | 'whisper';
|
||||||
|
|
||||||
|
export class ApiError extends Error {
|
||||||
|
constructor(
|
||||||
|
message: string,
|
||||||
|
public readonly service: ApiErrorService,
|
||||||
|
public readonly statusCode?: number,
|
||||||
|
) {
|
||||||
|
super(message);
|
||||||
|
this.name = 'ApiError';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { ApiKeysModule } from '../api-keys/api-keys.module';
|
||||||
|
import { OpenRouterService } from './openrouter.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [ApiKeysModule],
|
||||||
|
providers: [OpenRouterService],
|
||||||
|
exports: [OpenRouterService],
|
||||||
|
})
|
||||||
|
export class LlmModule {}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { ApiKeysService } from '../api-keys/api-keys.service';
|
||||||
|
import { ApiError } from '../common/errors/api-error';
|
||||||
|
import { OpenRouterService } from './openrouter.service';
|
||||||
|
|
||||||
|
describe('OpenRouterService', () => {
|
||||||
|
let service: OpenRouterService;
|
||||||
|
const getDecryptedValue = jest.fn(() => Promise.resolve('sk-or-v1-test'));
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
jest.useFakeTimers();
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
OpenRouterService,
|
||||||
|
{ provide: ApiKeysService, useValue: { getDecryptedValue } },
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get(OpenRouterService);
|
||||||
|
jest.spyOn(global, 'fetch');
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
jest.useRealTimers();
|
||||||
|
jest.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
function mockFetchOnce(impl: () => Promise<Response> | Response): void {
|
||||||
|
(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(
|
||||||
|
() =>
|
||||||
|
new Response(
|
||||||
|
JSON.stringify({ choices: [{ message: { content: 'Bonjour' } }] }),
|
||||||
|
{ status: 200 },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const result = await service.chat(1, [
|
||||||
|
{ role: 'user', content: 'Salut' },
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(result).toBe('Bonjour');
|
||||||
|
expect(getDecryptedValue).toHaveBeenCalledWith(1, 'openrouter_api_key');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should fall back to Qwen when the primary model errors', async () => {
|
||||||
|
mockFetchOnce(() => new Response('erreur serveur', { status: 500 }));
|
||||||
|
mockFetchOnce(
|
||||||
|
() =>
|
||||||
|
new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
choices: [{ message: { content: 'Reponse secours' } }],
|
||||||
|
}),
|
||||||
|
{ status: 200 },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const result = await service.chat(1, [
|
||||||
|
{ role: 'user', content: 'Salut' },
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(result).toBe('Reponse secours');
|
||||||
|
expect(global.fetch).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should retry with backoff on 429 before succeeding', async () => {
|
||||||
|
mockFetchOnce(() => new Response('rate limited', { status: 429 }));
|
||||||
|
mockFetchOnce(
|
||||||
|
() =>
|
||||||
|
new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
choices: [{ message: { content: 'OK apres attente' } }],
|
||||||
|
}),
|
||||||
|
{ status: 200 },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const promise = service.chat(1, [{ role: 'user', content: 'Salut' }]);
|
||||||
|
await jest.runAllTimersAsync();
|
||||||
|
const result = await promise;
|
||||||
|
|
||||||
|
expect(result).toBe('OK apres attente');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw ApiError when every model is unreachable', async () => {
|
||||||
|
mockFetchOnce(() => Promise.reject(new Error('network down')));
|
||||||
|
mockFetchOnce(() => Promise.reject(new Error('network down')));
|
||||||
|
mockFetchOnce(() => Promise.reject(new Error('network down')));
|
||||||
|
mockFetchOnce(() => Promise.reject(new Error('network down')));
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.chat(1, [{ role: 'user', content: 'Salut' }]),
|
||||||
|
).rejects.toThrow(ApiError);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw ApiError when the response is HTTP 200 without choices', async () => {
|
||||||
|
mockFetchOnce(() => new Response(JSON.stringify({}), { status: 200 }));
|
||||||
|
mockFetchOnce(() => new Response(JSON.stringify({}), { status: 200 }));
|
||||||
|
mockFetchOnce(() => new Response(JSON.stringify({}), { status: 200 }));
|
||||||
|
mockFetchOnce(() => new Response(JSON.stringify({}), { status: 200 }));
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.chat(1, [{ role: 'user', content: 'Salut' }]),
|
||||||
|
).rejects.toThrow(/malformee/);
|
||||||
|
});
|
||||||
|
|
||||||
|
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');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { ApiKeysService } from '../api-keys/api-keys.service';
|
||||||
|
import { ApiError } from '../common/errors/api-error';
|
||||||
|
|
||||||
|
export interface ChatMessage {
|
||||||
|
role: 'system' | 'user' | 'assistant';
|
||||||
|
content: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface OpenRouterChoice {
|
||||||
|
message?: { content?: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
interface OpenRouterResponseBody {
|
||||||
|
choices?: OpenRouterChoice[];
|
||||||
|
error?: { message?: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
const OPENROUTER_URL = 'https://openrouter.ai/api/v1/chat/completions';
|
||||||
|
const PRIMARY_MODEL = 'deepseek/deepseek-chat';
|
||||||
|
const FALLBACK_MODEL = 'qwen/qwen-2.5-72b-instruct';
|
||||||
|
const OPENROUTER_KEY_SERVICE = 'openrouter_api_key';
|
||||||
|
const MAX_ATTEMPTS = 4;
|
||||||
|
const RATE_LIMITED_STATUSES = new Set([429, 504]);
|
||||||
|
|
||||||
|
function delay(ms: number): Promise<void> {
|
||||||
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Client OpenRouter avec bascule DeepSeek -> Qwen (voir CLAUDE.md section 2) : jusqu'a
|
||||||
|
* MAX_ATTEMPTS tentatives en alternant les deux modeles, avec backoff exponentiel sur
|
||||||
|
* rate-limit (429) et timeout (504). Le meme historique de messages est reutilise quel que
|
||||||
|
* soit le modele qui finit par repondre, pour que la bascule reste transparente.
|
||||||
|
*/
|
||||||
|
@Injectable()
|
||||||
|
export class OpenRouterService {
|
||||||
|
private readonly logger = new Logger(OpenRouterService.name);
|
||||||
|
|
||||||
|
constructor(private readonly apiKeysService: ApiKeysService) {}
|
||||||
|
|
||||||
|
async chat(
|
||||||
|
userId: number,
|
||||||
|
messages: ChatMessage[],
|
||||||
|
options: { jsonResponse?: boolean; online?: boolean } = {},
|
||||||
|
): Promise<string> {
|
||||||
|
const apiKey = await this.apiKeysService.getDecryptedValue(
|
||||||
|
userId,
|
||||||
|
OPENROUTER_KEY_SERVICE,
|
||||||
|
);
|
||||||
|
|
||||||
|
let lastError = 'raison inconnue';
|
||||||
|
|
||||||
|
for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
|
||||||
|
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, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${apiKey}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
model,
|
||||||
|
messages,
|
||||||
|
...(options.jsonResponse
|
||||||
|
? { response_format: { type: 'json_object' } }
|
||||||
|
: {}),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
lastError = error instanceof Error ? error.message : String(error);
|
||||||
|
this.logger.warn(`${model} injoignable (${lastError})`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (RATE_LIMITED_STATUSES.has(response.status)) {
|
||||||
|
lastError = `${response.status}: rate-limit ou timeout`;
|
||||||
|
this.logger.warn(`${model} ${lastError}, nouvelle tentative`);
|
||||||
|
await delay(2 ** attempt * 250);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
lastError = `${response.status}: ${await response.text()}`;
|
||||||
|
this.logger.warn(`${model} a renvoye une erreur (${lastError})`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = (await response.json()) as OpenRouterResponseBody;
|
||||||
|
const content = parsed.choices?.[0]?.message?.content;
|
||||||
|
if (!content) {
|
||||||
|
lastError = `reponse malformee (${parsed.error?.message ?? 'choices manquant'})`;
|
||||||
|
this.logger.warn(`${model}: ${lastError}`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new ApiError(
|
||||||
|
`Aucun modele OpenRouter n'a pu repondre (${lastError})`,
|
||||||
|
'openrouter',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { ValidationPipe } from '@nestjs/common';
|
||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||||
|
import { AppModule } from './app.module';
|
||||||
|
|
||||||
|
async function bootstrap(): Promise<void> {
|
||||||
|
const app = await NestFactory.create(AppModule);
|
||||||
|
|
||||||
|
app.useGlobalPipes(
|
||||||
|
new ValidationPipe({
|
||||||
|
whitelist: true,
|
||||||
|
forbidNonWhitelisted: true,
|
||||||
|
transform: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const swaggerConfig = new DocumentBuilder()
|
||||||
|
.setTitle('Max API')
|
||||||
|
.setDescription(
|
||||||
|
'Backend Max : comptes utilisateurs et cles API externes (OpenRouter, ElevenLabs) chiffrees cote serveur.',
|
||||||
|
)
|
||||||
|
.setVersion('1.0')
|
||||||
|
.build();
|
||||||
|
const swaggerDocument = SwaggerModule.createDocument(app, swaggerConfig);
|
||||||
|
SwaggerModule.setup('api/docs', app, swaggerDocument);
|
||||||
|
|
||||||
|
await app.listen(process.env.PORT ?? 3000);
|
||||||
|
}
|
||||||
|
|
||||||
|
void bootstrap();
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { Global, Module } from '@nestjs/common';
|
||||||
|
import { PrismaService } from './prisma.service';
|
||||||
|
|
||||||
|
@Global()
|
||||||
|
@Module({
|
||||||
|
providers: [PrismaService],
|
||||||
|
exports: [PrismaService],
|
||||||
|
})
|
||||||
|
export class PrismaModule {}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { PrismaService } from './prisma.service';
|
||||||
|
|
||||||
|
describe('PrismaService', () => {
|
||||||
|
let service: PrismaService;
|
||||||
|
|
||||||
|
let connectSpy: jest.SpyInstance;
|
||||||
|
let disconnectSpy: jest.SpyInstance;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
service = new PrismaService();
|
||||||
|
connectSpy = jest.spyOn(service, '$connect').mockResolvedValue(undefined);
|
||||||
|
disconnectSpy = jest
|
||||||
|
.spyOn(service, '$disconnect')
|
||||||
|
.mockResolvedValue(undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should connect to the database on module init', async () => {
|
||||||
|
await service.onModuleInit();
|
||||||
|
expect(connectSpy).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should disconnect from the database on module destroy', async () => {
|
||||||
|
await service.onModuleDestroy();
|
||||||
|
expect(disconnectSpy).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class PrismaService
|
||||||
|
extends PrismaClient
|
||||||
|
implements OnModuleInit, OnModuleDestroy
|
||||||
|
{
|
||||||
|
async onModuleInit(): Promise<void> {
|
||||||
|
await this.$connect();
|
||||||
|
}
|
||||||
|
|
||||||
|
async onModuleDestroy(): Promise<void> {
|
||||||
|
await this.$disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,66 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { OpenRouterService } from '../../llm/openrouter.service';
|
||||||
|
import { IntentRouterAgent } from './intent-router.agent';
|
||||||
|
|
||||||
|
describe('IntentRouterAgent', () => {
|
||||||
|
let agent: IntentRouterAgent;
|
||||||
|
const chat = jest.fn();
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
IntentRouterAgent,
|
||||||
|
{ provide: OpenRouterService, useValue: { chat } },
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
agent = module.get(IntentRouterAgent);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('analyze()', () => {
|
||||||
|
it('should return learn with the extracted subject when the model detects a learning intent', async () => {
|
||||||
|
chat.mockResolvedValueOnce(
|
||||||
|
JSON.stringify({ intent: 'learn', subject: 'React' }),
|
||||||
|
);
|
||||||
|
|
||||||
|
const result = await agent.analyze(7, 'Apprends-moi React');
|
||||||
|
|
||||||
|
expect(result).toEqual({ intent: 'learn', subject: 'React' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return chat with a null subject when the model detects a chat intent', async () => {
|
||||||
|
chat.mockResolvedValueOnce(
|
||||||
|
JSON.stringify({ intent: 'chat', subject: null }),
|
||||||
|
);
|
||||||
|
|
||||||
|
const result = await agent.analyze(7, 'Salut Max ça roule ?');
|
||||||
|
|
||||||
|
expect(result).toEqual({ intent: 'chat', subject: null });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should default to chat when the model response is not valid JSON', async () => {
|
||||||
|
chat.mockResolvedValueOnce('je ne sais pas');
|
||||||
|
|
||||||
|
const result = await agent.analyze(7, 'message ambigu');
|
||||||
|
|
||||||
|
expect(result).toEqual({ intent: 'chat', subject: null });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should default to chat when "intent" is neither "learn" nor "chat"', async () => {
|
||||||
|
chat.mockResolvedValueOnce(JSON.stringify({ intent: 'autre chose' }));
|
||||||
|
|
||||||
|
const result = await agent.analyze(7, 'message');
|
||||||
|
|
||||||
|
expect(result).toEqual({ intent: 'chat', subject: null });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should default to a null subject when "learn" is detected but subject is not a string', async () => {
|
||||||
|
chat.mockResolvedValueOnce(JSON.stringify({ intent: 'learn' }));
|
||||||
|
|
||||||
|
const result = await agent.analyze(7, 'message');
|
||||||
|
|
||||||
|
expect(result).toEqual({ intent: 'learn', subject: null });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { OpenRouterService } from '../../llm/openrouter.service';
|
||||||
|
import { buildIntentRouterPrompt } from '../prompts/intent-router.prompt';
|
||||||
|
|
||||||
|
export interface IntentRouterResult {
|
||||||
|
intent: 'learn' | 'chat';
|
||||||
|
subject: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IntentRouterJsonReply {
|
||||||
|
intent?: unknown;
|
||||||
|
subject?: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Porte d'entree du pipeline (docs/Max_System_Prompt.md) : classifie un message quand aucune
|
||||||
|
* session active n'existe. "En cas de doute -> chat" est applique a la fois par le prompt et par
|
||||||
|
* ce code : toute reponse non reconnue ou non-JSON est traitee comme "chat", jamais "learn" par
|
||||||
|
* defaut, pour ne jamais creer de session par erreur.
|
||||||
|
*/
|
||||||
|
@Injectable()
|
||||||
|
export class IntentRouterAgent {
|
||||||
|
private readonly logger = new Logger(IntentRouterAgent.name);
|
||||||
|
|
||||||
|
constructor(private readonly llm: OpenRouterService) {}
|
||||||
|
|
||||||
|
async analyze(userId: number, message: string): Promise<IntentRouterResult> {
|
||||||
|
const raw = await this.llm.chat(
|
||||||
|
userId,
|
||||||
|
[{ role: 'system', content: buildIntentRouterPrompt(message) }],
|
||||||
|
{ jsonResponse: true },
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(raw) as IntentRouterJsonReply;
|
||||||
|
if (parsed.intent === 'learn') {
|
||||||
|
return {
|
||||||
|
intent: 'learn',
|
||||||
|
subject: typeof parsed.subject === 'string' ? parsed.subject : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { intent: 'chat', subject: null };
|
||||||
|
} catch {
|
||||||
|
this.logger.warn(
|
||||||
|
`Reponse du routeur d'intention non-JSON, traitee comme "chat" par prudence: ${raw}`,
|
||||||
|
);
|
||||||
|
return { intent: 'chat', subject: 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');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import {
|
||||||
|
checkLevel1Guardrails,
|
||||||
|
parseDurationHours,
|
||||||
|
} from './objective-guardrails';
|
||||||
|
|
||||||
|
describe('parseDurationHours()', () => {
|
||||||
|
it('should parse hours, days, weeks and months into hours', () => {
|
||||||
|
expect(parseDurationHours('10 heures')).toBe(10);
|
||||||
|
expect(parseDurationHours('2 jours')).toBe(48);
|
||||||
|
expect(parseDurationHours('2 semaines')).toBe(336);
|
||||||
|
expect(parseDurationHours('1 mois')).toBe(720);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should accept a decimal amount', () => {
|
||||||
|
expect(parseDurationHours('1,5 jours')).toBe(36);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should 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();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('checkLevel1Guardrails()', () => {
|
||||||
|
const validDraft = {
|
||||||
|
subject: 'Facturation freelance en micro-entreprise',
|
||||||
|
professionalGoal:
|
||||||
|
'Pouvoir facturer mes clients sans erreur des le mois prochain',
|
||||||
|
duration: '2 semaines',
|
||||||
|
};
|
||||||
|
|
||||||
|
it('should return no failure for a valid draft', () => {
|
||||||
|
expect(checkLevel1Guardrails(validDraft)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject a subject that is too short or a single generic word', () => {
|
||||||
|
const failures = checkLevel1Guardrails({ ...validDraft, subject: 'Excel' });
|
||||||
|
expect(failures.map((f) => f.field)).toContain('subject');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject a professional goal that is too short', () => {
|
||||||
|
const failures = checkLevel1Guardrails({
|
||||||
|
...validDraft,
|
||||||
|
professionalGoal: 'Progresser',
|
||||||
|
});
|
||||||
|
expect(failures.map((f) => f.field)).toContain('professionalGoal');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject a duration outside 1h-12 weeks or unparseable', () => {
|
||||||
|
expect(
|
||||||
|
checkLevel1Guardrails({ ...validDraft, duration: 'un bon moment' }).map(
|
||||||
|
(f) => f.field,
|
||||||
|
),
|
||||||
|
).toContain('duration');
|
||||||
|
expect(
|
||||||
|
checkLevel1Guardrails({ ...validDraft, duration: '24 mois' }).map(
|
||||||
|
(f) => f.field,
|
||||||
|
),
|
||||||
|
).toContain('duration');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
export interface ObjectiveDraft {
|
||||||
|
subject: string;
|
||||||
|
professionalGoal: string;
|
||||||
|
duration: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GuardrailFailure {
|
||||||
|
field: 'subject' | 'professionalGoal' | 'duration';
|
||||||
|
reason: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MIN_SUBJECT_LENGTH = 10;
|
||||||
|
const MIN_GOAL_LENGTH = 20;
|
||||||
|
const MIN_DURATION_HOURS = 1;
|
||||||
|
const MAX_DURATION_HOURS = 12 * 7 * 24;
|
||||||
|
|
||||||
|
const DURATION_UNIT_HOURS = new Map<string, number>([
|
||||||
|
['heure', 1],
|
||||||
|
['heures', 1],
|
||||||
|
['h', 1],
|
||||||
|
['jour', 24],
|
||||||
|
['jours', 24],
|
||||||
|
['j', 24],
|
||||||
|
['semaine', 7 * 24],
|
||||||
|
['semaines', 7 * 24],
|
||||||
|
['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", "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 hoursPerUnit = DURATION_UNIT_HOURS.get(unit);
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Garde-fous de niveau 1 (regles codees, voir CLAUDE.md section 2 / docs/Max Refonte Coach
|
||||||
|
* Freelance.md) : longueur/format uniquement, aucun appel LLM. Renvoie la liste des champs en
|
||||||
|
* echec, vide si l'objectif est recevable.
|
||||||
|
*/
|
||||||
|
export function checkLevel1Guardrails(
|
||||||
|
draft: ObjectiveDraft,
|
||||||
|
): GuardrailFailure[] {
|
||||||
|
const failures: GuardrailFailure[] = [];
|
||||||
|
|
||||||
|
const subject = draft.subject.trim();
|
||||||
|
if (subject.length < MIN_SUBJECT_LENGTH || !subject.includes(' ')) {
|
||||||
|
failures.push({
|
||||||
|
field: 'subject',
|
||||||
|
reason: `Le sujet doit faire au moins ${MIN_SUBJECT_LENGTH} caracteres et ne pas etre un terme generique isole.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const professionalGoal = draft.professionalGoal.trim();
|
||||||
|
if (professionalGoal.length < MIN_GOAL_LENGTH) {
|
||||||
|
failures.push({
|
||||||
|
field: 'professionalGoal',
|
||||||
|
reason: `Le but professionnel doit faire au moins ${MIN_GOAL_LENGTH} caracteres.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const durationHours = parseDurationHours(draft.duration);
|
||||||
|
if (
|
||||||
|
durationHours === null ||
|
||||||
|
durationHours < MIN_DURATION_HOURS ||
|
||||||
|
durationHours > MAX_DURATION_HOURS
|
||||||
|
) {
|
||||||
|
failures.push({
|
||||||
|
field: 'duration',
|
||||||
|
reason:
|
||||||
|
'La duree doit etre comprise entre 1 heure et 12 semaines (ex: "2 semaines", "10 heures").',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return failures;
|
||||||
|
}
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
import { ConflictException } from '@nestjs/common';
|
||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { PrismaService } from '../../prisma/prisma.service';
|
||||||
|
import { OpenRouterService } from '../../llm/openrouter.service';
|
||||||
|
import { ObjectiveAgent } from './objective.agent';
|
||||||
|
|
||||||
|
describe('ObjectiveAgent', () => {
|
||||||
|
let agent: ObjectiveAgent;
|
||||||
|
const chat = jest.fn();
|
||||||
|
const createSessionObjective = jest.fn<
|
||||||
|
Promise<unknown>,
|
||||||
|
[{ data: Record<string, unknown> }]
|
||||||
|
>();
|
||||||
|
const prisma = {
|
||||||
|
sessionObjective: { create: createSessionObjective },
|
||||||
|
session: { update: jest.fn() },
|
||||||
|
};
|
||||||
|
|
||||||
|
const validDraft = {
|
||||||
|
subject: 'Facturation freelance en micro-entreprise',
|
||||||
|
professionalGoal:
|
||||||
|
'Pouvoir facturer mes clients sans erreur des le mois prochain',
|
||||||
|
duration: '2 semaines',
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
ObjectiveAgent,
|
||||||
|
{ provide: PrismaService, useValue: prisma },
|
||||||
|
{ provide: OpenRouterService, useValue: { chat } },
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
agent = module.get(ObjectiveAgent);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('converse()', () => {
|
||||||
|
it('should return the raw reply unready when the model answers with non-JSON text', async () => {
|
||||||
|
chat.mockResolvedValueOnce('Je ne comprends pas');
|
||||||
|
|
||||||
|
const result = await agent.converse(1, 7, 'bonjour');
|
||||||
|
|
||||||
|
expect(result).toEqual({ reply: 'Je ne comprends pas', ready: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should keep asking when the model is not ready to confirm', async () => {
|
||||||
|
chat.mockResolvedValueOnce(
|
||||||
|
JSON.stringify({
|
||||||
|
message: 'Quel est ton sujet ?',
|
||||||
|
readyToConfirm: false,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const result = await agent.converse(1, 7, 'Je veux apprendre un truc');
|
||||||
|
|
||||||
|
expect(result).toEqual({ reply: 'Quel est ton sujet ?', ready: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject a ready draft that fails level 1 guardrails without calling the coherence scorer', async () => {
|
||||||
|
chat.mockResolvedValueOnce(
|
||||||
|
JSON.stringify({
|
||||||
|
message: 'Recap',
|
||||||
|
readyToConfirm: true,
|
||||||
|
subject: 'Excel',
|
||||||
|
professionalGoal: validDraft.professionalGoal,
|
||||||
|
duration: validDraft.duration,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const result = await agent.converse(1, 7, 'Excel');
|
||||||
|
|
||||||
|
expect(result.ready).toBe(false);
|
||||||
|
expect(result.reply).toMatch(/sujet/);
|
||||||
|
expect(chat).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should reject a draft that fails the level 2 coherence score', async () => {
|
||||||
|
chat
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
JSON.stringify({
|
||||||
|
message: 'Recap',
|
||||||
|
readyToConfirm: true,
|
||||||
|
...validDraft,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
JSON.stringify({
|
||||||
|
clarity: 0.9,
|
||||||
|
specificity: 0.3,
|
||||||
|
followUpQuestion: 'Peux-tu preciser le sujet ?',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const result = await agent.converse(1, 7, 'message');
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
reply: 'Peux-tu preciser le sujet ?',
|
||||||
|
ready: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return ready with the draft when both guardrail levels pass', async () => {
|
||||||
|
chat
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
JSON.stringify({
|
||||||
|
message: 'Voici le recap, confirmes-tu ?',
|
||||||
|
readyToConfirm: true,
|
||||||
|
...validDraft,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
JSON.stringify({ clarity: 0.9, specificity: 0.9 }),
|
||||||
|
);
|
||||||
|
|
||||||
|
const result = await agent.converse(1, 7, 'message');
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
reply: 'Voici le recap, confirmes-tu ?',
|
||||||
|
ready: true,
|
||||||
|
draft: validDraft,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('confirm()', () => {
|
||||||
|
it('should throw ConflictException when no draft is ready for this session', async () => {
|
||||||
|
await expect(agent.confirm(1, 7)).rejects.toThrow(ConflictException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should persist the objective and move the session to objective_validated once ready', async () => {
|
||||||
|
chat
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
JSON.stringify({
|
||||||
|
message: 'Recap',
|
||||||
|
readyToConfirm: true,
|
||||||
|
...validDraft,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
JSON.stringify({ clarity: 0.9, specificity: 0.9 }),
|
||||||
|
);
|
||||||
|
await agent.converse(1, 7, 'message');
|
||||||
|
|
||||||
|
chat.mockResolvedValueOnce(
|
||||||
|
JSON.stringify({ clarity: 0.9, specificity: 0.9 }),
|
||||||
|
);
|
||||||
|
prisma.sessionObjective.create.mockResolvedValueOnce({
|
||||||
|
id: 1,
|
||||||
|
sessionId: 1,
|
||||||
|
...validDraft,
|
||||||
|
validatedAt: new Date('2026-01-01'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await agent.confirm(1, 7);
|
||||||
|
|
||||||
|
const createCallArgs = prisma.sessionObjective.create.mock.calls[0][0];
|
||||||
|
expect(createCallArgs.data).toMatchObject({
|
||||||
|
sessionId: 1,
|
||||||
|
...validDraft,
|
||||||
|
});
|
||||||
|
expect(prisma.session.update).toHaveBeenCalledWith({
|
||||||
|
where: { id: 1 },
|
||||||
|
data: { status: 'objective_validated' },
|
||||||
|
});
|
||||||
|
expect(result.id).toBe(1);
|
||||||
|
|
||||||
|
await expect(agent.confirm(1, 7)).rejects.toThrow(ConflictException);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,230 @@
|
|||||||
|
import { ConflictException, Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { PrismaService } from '../../prisma/prisma.service';
|
||||||
|
import { ChatMessage, OpenRouterService } from '../../llm/openrouter.service';
|
||||||
|
import { buildAgentPrompt } from '../prompts/base.prompt';
|
||||||
|
import {
|
||||||
|
OBJECTIVE_JSON_CONTRACT,
|
||||||
|
OBJECTIVE_PROMPT,
|
||||||
|
} from '../prompts/objective.prompt';
|
||||||
|
import {
|
||||||
|
checkLevel1Guardrails,
|
||||||
|
GuardrailFailure,
|
||||||
|
ObjectiveDraft,
|
||||||
|
} from './objective-guardrails';
|
||||||
|
|
||||||
|
export interface ObjectiveTurnResult {
|
||||||
|
reply: string;
|
||||||
|
ready: boolean;
|
||||||
|
draft?: ObjectiveDraft;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ValidatedSessionObjective {
|
||||||
|
id: number;
|
||||||
|
sessionId: number;
|
||||||
|
subject: string;
|
||||||
|
professionalGoal: string;
|
||||||
|
duration: string;
|
||||||
|
validatedAt: Date | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AgentJsonReply {
|
||||||
|
message: string;
|
||||||
|
subject?: string | null;
|
||||||
|
professionalGoal?: string | null;
|
||||||
|
duration?: string | null;
|
||||||
|
readyToConfirm?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CoherenceScore {
|
||||||
|
clarity: number;
|
||||||
|
specificity: number;
|
||||||
|
followUpQuestion?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const COHERENCE_THRESHOLD = 0.6;
|
||||||
|
|
||||||
|
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) ?
|
||||||
|
|
||||||
|
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, "followUpQuestion": "..." | null}`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Agent 1 du pipeline (voir CLAUDE.md section 1 / docs/Max Refonte Coach Freelance.md) :
|
||||||
|
* dialogue socratique + garde-fous a deux niveaux (regles codees, puis score de coherence LLM)
|
||||||
|
* avant confirmation explicite de l'utilisateur. L'historique de conversation est ephemere
|
||||||
|
* (en memoire, par session) : rien n'est stocke en base avant la confirmation explicite.
|
||||||
|
*/
|
||||||
|
@Injectable()
|
||||||
|
export class ObjectiveAgent {
|
||||||
|
private readonly logger = new Logger(ObjectiveAgent.name);
|
||||||
|
private readonly conversations = new Map<number, ChatMessage[]>();
|
||||||
|
private readonly readyDrafts = new Map<number, ObjectiveDraft>();
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly llm: OpenRouterService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async converse(
|
||||||
|
sessionId: number,
|
||||||
|
userId: number,
|
||||||
|
userMessage: string,
|
||||||
|
): Promise<ObjectiveTurnResult> {
|
||||||
|
const history = this.conversations.get(sessionId) ?? [
|
||||||
|
{ role: 'system', content: SYSTEM_PROMPT },
|
||||||
|
];
|
||||||
|
history.push({ role: 'user', content: userMessage });
|
||||||
|
|
||||||
|
const raw = await this.llm.chat(userId, history, { jsonResponse: true });
|
||||||
|
history.push({ role: 'assistant', content: raw });
|
||||||
|
this.conversations.set(sessionId, history);
|
||||||
|
|
||||||
|
const parsed = this.parseAgentReply(raw);
|
||||||
|
if (!parsed) {
|
||||||
|
return { reply: raw, ready: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
!parsed.readyToConfirm ||
|
||||||
|
!parsed.subject ||
|
||||||
|
!parsed.professionalGoal ||
|
||||||
|
!parsed.duration
|
||||||
|
) {
|
||||||
|
return { reply: parsed.message, ready: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
const draft: ObjectiveDraft = {
|
||||||
|
subject: parsed.subject,
|
||||||
|
professionalGoal: parsed.professionalGoal,
|
||||||
|
duration: parsed.duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
const level1Failures = checkLevel1Guardrails(draft);
|
||||||
|
if (level1Failures.length > 0) {
|
||||||
|
const reply = this.describeLevel1Failures(level1Failures);
|
||||||
|
history.push({ role: 'assistant', content: reply });
|
||||||
|
return { reply, ready: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
const coherence = await this.scoreCoherence(userId, draft);
|
||||||
|
if (!this.passesCoherence(coherence)) {
|
||||||
|
const reply =
|
||||||
|
coherence.followUpQuestion ??
|
||||||
|
'Peux-tu preciser ton objectif pour le rendre plus concret ?';
|
||||||
|
history.push({ role: 'assistant', content: reply });
|
||||||
|
return { reply, ready: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
this.readyDrafts.set(sessionId, draft);
|
||||||
|
return { reply: parsed.message, ready: true, draft };
|
||||||
|
}
|
||||||
|
|
||||||
|
async confirm(
|
||||||
|
sessionId: number,
|
||||||
|
userId: number,
|
||||||
|
): Promise<ValidatedSessionObjective> {
|
||||||
|
const draft = this.readyDrafts.get(sessionId);
|
||||||
|
if (!draft) {
|
||||||
|
throw new ConflictException(
|
||||||
|
"Aucun objectif pret a etre confirme pour cette session : continue le dialogue d'abord.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const level1Failures = checkLevel1Guardrails(draft);
|
||||||
|
const coherence =
|
||||||
|
level1Failures.length === 0
|
||||||
|
? await this.scoreCoherence(userId, draft)
|
||||||
|
: null;
|
||||||
|
if (
|
||||||
|
level1Failures.length > 0 ||
|
||||||
|
!coherence ||
|
||||||
|
!this.passesCoherence(coherence)
|
||||||
|
) {
|
||||||
|
this.readyDrafts.delete(sessionId);
|
||||||
|
throw new ConflictException(
|
||||||
|
"L'objectif n'est plus valide, reprends le dialogue pour le reformuler.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const objective = await this.prisma.sessionObjective.create({
|
||||||
|
data: {
|
||||||
|
sessionId,
|
||||||
|
subject: draft.subject,
|
||||||
|
professionalGoal: draft.professionalGoal,
|
||||||
|
duration: draft.duration,
|
||||||
|
validatedAt: new Date(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await this.prisma.session.update({
|
||||||
|
where: { id: sessionId },
|
||||||
|
data: { status: 'objective_validated' },
|
||||||
|
});
|
||||||
|
|
||||||
|
this.conversations.delete(sessionId);
|
||||||
|
this.readyDrafts.delete(sessionId);
|
||||||
|
|
||||||
|
return objective;
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseAgentReply(raw: string): AgentJsonReply | null {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(raw) as AgentJsonReply;
|
||||||
|
if (typeof parsed.message !== 'string') return null;
|
||||||
|
return parsed;
|
||||||
|
} catch {
|
||||||
|
this.logger.warn(
|
||||||
|
`Reponse de l'agent non-JSON, affichee telle quelle: ${raw}`,
|
||||||
|
);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async scoreCoherence(
|
||||||
|
userId: number,
|
||||||
|
draft: ObjectiveDraft,
|
||||||
|
): Promise<CoherenceScore> {
|
||||||
|
const raw = await this.llm.chat(
|
||||||
|
userId,
|
||||||
|
[
|
||||||
|
{ role: 'system', content: COHERENCE_SYSTEM_PROMPT },
|
||||||
|
{ role: 'user', content: JSON.stringify(draft) },
|
||||||
|
],
|
||||||
|
{ jsonResponse: true },
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
return JSON.parse(raw) as CoherenceScore;
|
||||||
|
} catch {
|
||||||
|
this.logger.warn(
|
||||||
|
`Score de coherence non-JSON, objectif rejete par prudence: ${raw}`,
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
clarity: 0,
|
||||||
|
specificity: 0,
|
||||||
|
followUpQuestion: 'Peux-tu reformuler ton objectif plus precisement ?',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private passesCoherence(score: CoherenceScore): boolean {
|
||||||
|
return (
|
||||||
|
score.clarity >= COHERENCE_THRESHOLD &&
|
||||||
|
score.specificity >= COHERENCE_THRESHOLD
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private describeLevel1Failures(failures: GuardrailFailure[]): string {
|
||||||
|
return `Pas tout a fait : ${failures.map((f) => f.reason).join(' ')}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
export class ObjectiveDraftDto {
|
||||||
|
@ApiProperty() subject!: string;
|
||||||
|
@ApiProperty() professionalGoal!: string;
|
||||||
|
@ApiProperty() duration!: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ObjectiveMessageResponseDto {
|
||||||
|
@ApiProperty({
|
||||||
|
description:
|
||||||
|
"Prochaine question de Max, ou recapitulatif si l'objectif est pret.",
|
||||||
|
})
|
||||||
|
reply!: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
description:
|
||||||
|
'true si les 3 piliers sont valides (garde-fous niveau 1 et 2) et prets a etre confirmes via POST /sessions/:id/objective/confirm.',
|
||||||
|
})
|
||||||
|
ready!: boolean;
|
||||||
|
|
||||||
|
@ApiProperty({ type: ObjectiveDraftDto, required: false })
|
||||||
|
draft?: ObjectiveDraftDto;
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
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'],
|
||||||
|
description:
|
||||||
|
'"chat" : reponse conversationnelle, aucune session creee. "learn" : une session de formation est active (nouvelle ou existante).',
|
||||||
|
})
|
||||||
|
type!: 'chat' | 'learn';
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
description:
|
||||||
|
'Reponse de Max a dire a voix haute (jamais affichee en bulle de texte).',
|
||||||
|
})
|
||||||
|
reply!: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
required: false,
|
||||||
|
description: 'Present uniquement si type="learn".',
|
||||||
|
})
|
||||||
|
sessionId?: number;
|
||||||
|
|
||||||
|
@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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsString, MaxLength, MinLength } from 'class-validator';
|
||||||
|
|
||||||
|
export class SendObjectiveMessageDto {
|
||||||
|
@ApiProperty({
|
||||||
|
example: 'Je voudrais apprendre a mieux facturer mes clients',
|
||||||
|
})
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
@MaxLength(2000)
|
||||||
|
message!: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
export class SessionObjectiveResponseDto {
|
||||||
|
@ApiProperty() id!: number;
|
||||||
|
@ApiProperty() sessionId!: number;
|
||||||
|
@ApiProperty() subject!: string;
|
||||||
|
@ApiProperty() professionalGoal!: string;
|
||||||
|
@ApiProperty() duration!: string;
|
||||||
|
@ApiProperty() validatedAt!: Date;
|
||||||
|
|
||||||
|
// 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,12 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { SessionStatus } from '@prisma/client';
|
||||||
|
import { SessionObjectiveResponseDto } from './session-objective-response.dto';
|
||||||
|
|
||||||
|
export class SessionResponseDto {
|
||||||
|
@ApiProperty() id!: number;
|
||||||
|
@ApiProperty({ enum: SessionStatus }) status!: SessionStatus;
|
||||||
|
@ApiProperty() createdAt!: Date;
|
||||||
|
@ApiProperty() updatedAt!: Date;
|
||||||
|
@ApiProperty({ type: SessionObjectiveResponseDto, required: false })
|
||||||
|
objective?: SessionObjectiveResponseDto;
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
// Prompt de personnalite permanent (docs/Max_System_Prompt.md) : injecte en tete de TOUS les
|
||||||
|
// agents du pipeline via buildAgentPrompt(). Chaque futur agent (mapping, level, research, plan,
|
||||||
|
// module, evaluation) aura son propre <nom>.prompt.ts suivant exactement ce meme pattern des
|
||||||
|
// qu'il sera construit (voir objective.prompt.ts pour l'exemple actuel).
|
||||||
|
export const PERSONALITY_PROMPT = `Tu es Max, un coach de formation personnel destiné aux freelances.
|
||||||
|
Tu aides les freelances à acquérir des compétences précises
|
||||||
|
et à les valoriser professionnellement.
|
||||||
|
|
||||||
|
## Ton identité
|
||||||
|
|
||||||
|
Tu es Max. Pas un assistant, pas un chatbot, pas un pote. Un coach professionnel.
|
||||||
|
Tu es direct, structuré, bienveillant — jamais familier.
|
||||||
|
|
||||||
|
## Règles de communication — non négociables
|
||||||
|
|
||||||
|
LANGUE : Tu t'exprimes exclusivement en français sauf si l'utilisateur
|
||||||
|
écrit dans une autre langue.
|
||||||
|
|
||||||
|
TU/VOUS : Tu utilises "tu" — proche mais professionnel.
|
||||||
|
|
||||||
|
TON : Chaleureux et direct. Comme un bon prof qui respecte son élève.
|
||||||
|
|
||||||
|
CE QUE TU NE DIS JAMAIS :
|
||||||
|
- Aucune apostrophe familière : "pote", "gros", "mec", "frère",
|
||||||
|
"chef", "boss", "buddy", "bro"
|
||||||
|
- Aucune blague sauf si l'utilisateur en demande explicitement une
|
||||||
|
- Aucun "super !", "génial !", "excellent !" répété
|
||||||
|
- Aucune question rhétorique vide ("Tu vois ce que je veux dire ?")
|
||||||
|
- Aucune formule de politesse creuse en fin de message
|
||||||
|
("N'hésite pas à me dire si...", "Je suis là pour toi")
|
||||||
|
|
||||||
|
LONGUEUR : Tes réponses sont concises. Tu vas à l'essentiel.
|
||||||
|
|
||||||
|
ERREURS : Si tu fais une erreur, tu la corriges sans t'excuser excessivement.
|
||||||
|
|
||||||
|
## Règle fondamentale
|
||||||
|
|
||||||
|
Tu ne commences jamais à enseigner un sujet directement.
|
||||||
|
Le processus de formation a des étapes définies.
|
||||||
|
Tu fais uniquement ce que ton rôle dans cet échange te demande de faire.`;
|
||||||
|
|
||||||
|
export function buildAgentPrompt(agentPrompt: string): string {
|
||||||
|
return `${PERSONALITY_PROMPT}\n\n${agentPrompt}`;
|
||||||
|
}
|
||||||
@@ -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,39 @@
|
|||||||
|
// Routeur d'intention (docs/Max_System_Prompt.md) : appele avant tout agent, uniquement quand
|
||||||
|
// aucune session active n'existe pour l'utilisateur. Classifieur interne, pas Max qui parle — donc
|
||||||
|
// jamais enveloppe par buildAgentPrompt()/PERSONALITY_PROMPT.
|
||||||
|
//
|
||||||
|
// Simplification connue : le document reference un [HISTORIQUE_INJECTÉ] (historique recent de la
|
||||||
|
// conversation) pour desambiguiser un message court. Il n'existe pas encore de stockage de
|
||||||
|
// l'historique de conversation hors-session cote backend (la conversation de l'Agent 1 n'est
|
||||||
|
// conservee qu'une fois une session creee) : la classification se fait donc uniquement sur le
|
||||||
|
// dernier message de l'utilisateur. A ameliorer si des faux negatifs/positifs apparaissent en
|
||||||
|
// usage reel.
|
||||||
|
export function buildIntentRouterPrompt(message: string): string {
|
||||||
|
return `Tu analyses le message suivant et tu determines si l'utilisateur
|
||||||
|
exprime une intention d'apprendre ou d'acquerir une competence.
|
||||||
|
|
||||||
|
Message : ${message}
|
||||||
|
|
||||||
|
Reponds UNIQUEMENT avec ce JSON, sans texte avant ni apres :
|
||||||
|
{
|
||||||
|
"intent": "learn" | "chat",
|
||||||
|
"subject": "..." | null
|
||||||
|
}
|
||||||
|
|
||||||
|
"intent": "learn" si le message exprime clairement le souhait :
|
||||||
|
- d'apprendre quelque chose
|
||||||
|
- de maitriser une competence
|
||||||
|
- de se former sur un sujet
|
||||||
|
- de comprendre un concept dans un but professionnel
|
||||||
|
- d'acquerir une nouvelle technologie ou pratique
|
||||||
|
|
||||||
|
"intent": "chat" dans tous les autres cas :
|
||||||
|
- question generale
|
||||||
|
- conversation informelle
|
||||||
|
- demande d'aide ponctuelle non liee a une formation
|
||||||
|
- message ambigu
|
||||||
|
|
||||||
|
En cas de doute -> "chat". Ne jamais creer une session par erreur.
|
||||||
|
|
||||||
|
"subject" : si "learn", extraire le sujet mentionne. Sinon null.`;
|
||||||
|
}
|
||||||
@@ -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.`;
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
// Prompt de role de l'Agent 1 (docs/Max_System_Prompt.md).
|
||||||
|
export const OBJECTIVE_PROMPT = `## Ton rôle dans cet échange
|
||||||
|
|
||||||
|
Tu dois révéler et valider l'objectif de formation de l'utilisateur.
|
||||||
|
Un objectif valide contient exactement 3 piliers :
|
||||||
|
1. Le sujet — quoi exactement apprendre
|
||||||
|
2. Le but professionnel — pour en faire quoi, dans quel contexte métier
|
||||||
|
3. La durée — en combien de temps
|
||||||
|
|
||||||
|
## Ce que tu fais
|
||||||
|
|
||||||
|
Tu poses des questions courtes et ciblées pour obtenir ces 3 piliers.
|
||||||
|
Maximum 3 questions dans un seul message.
|
||||||
|
Tu n'inventes pas l'objectif. Tu ne supposes pas. Tu demandes.
|
||||||
|
|
||||||
|
Une fois les 3 piliers identifiés, tu les reformules sous cette forme :
|
||||||
|
"Ton objectif : [sujet] pour [but professionnel], en [durée]. C'est bien ça ?"
|
||||||
|
|
||||||
|
Tu attends la confirmation explicite de l'utilisateur.
|
||||||
|
Si l'utilisateur corrige, tu reformules à nouveau.
|
||||||
|
|
||||||
|
## Ce que tu ne fais pas
|
||||||
|
|
||||||
|
- Tu ne commences pas à expliquer le sujet
|
||||||
|
- Tu ne proposes pas de plan de cours
|
||||||
|
- Tu ne recherches pas de sources
|
||||||
|
- Tu ne poses pas plus de 3 questions à la fois`;
|
||||||
|
|
||||||
|
// Ajout technique non present dans docs/Max_System_Prompt.md : le document decrit un agent qui
|
||||||
|
// reformule l'objectif en texte libre et attend une confirmation humaine (signal "bouton" pour
|
||||||
|
// objective_validated, voir la table des declencheurs de session.status). En pratique,
|
||||||
|
// ObjectiveValidationCard a besoin des 3 piliers separes (subject/professionalGoal/duration) pour
|
||||||
|
// les afficher en 3 champs editables, et objective.agent.ts a besoin d'un signal structure
|
||||||
|
// (readyToConfirm) pour declencher ses propres garde-fous (objective-guardrails.ts + score de
|
||||||
|
// coherence) avant meme d'afficher cette carte. Le contrat JSON ci-dessous est donc une couche de
|
||||||
|
// transport technique : "message" reste exactement la phrase de reformulation decrite ci-dessus,
|
||||||
|
// le reste du JSON ne change rien au comportement conversationnel specifie par le document.
|
||||||
|
export const OBJECTIVE_JSON_CONTRACT = `Reponds TOUJOURS avec un objet JSON strict, sans texte autour, de la forme :
|
||||||
|
{"message": "...", "subject": "..." | null, "professionalGoal": "..." | null, "duration": "..." | null, "readyToConfirm": true | false}
|
||||||
|
|
||||||
|
"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.
|
||||||
|
|
||||||
|
"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.`;
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user