Mentor d'écriture (M1-M3) : coach dans les champs, relecture d'éditeur, méthode guidée « Donjon en 5 salles »
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 13m48s
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 13m16s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 3m3s
Build & Push Images / build (core) (push) Successful in 4m50s
Build & Push Images / build (web) (push) Successful in 3m26s
Build & Push Images / build-switcher (push) Successful in 26s
Build & Push Images / build (brain) (push) Canceled after 1m5s
Qualité & Sécurité / MegaLinter (PMD · Ruff · Bandit · gitleaks · hadolint) (push) Successful in 13m48s
Qualité & Sécurité / Web (ESLint · angular-eslint + sonarjs) (push) Successful in 13m16s
Qualité & Sécurité / Trivy (CVE dépendances Maven / pip / npm) (push) Failing after 3m3s
Build & Push Images / build (core) (push) Successful in 4m50s
Build & Push Images / build (web) (push) Successful in 3m26s
Build & Push Images / build-switcher (push) Successful in 26s
Build & Push Images / build (brain) (push) Canceled after 1m5s
- M1 coach : bouton ampoule sur 17 champs narratifs (scène, chapitre, arc),
panneau de conseils (à quoi ça sert, questions, exemple, piège classique).
Contenu statique i18n fr/en, sans IA ; ampoule aussi dans l'en-tête des
sections repliables (input coachTopic d'expandable-section).
- M2 relecture d'éditeur : WritingReviewService + GET
/api/campaigns/{id}/writing-review, 10 règles déterministes WRITE-001 à 010
(couloir, faux choix, révélation à chemin unique, rythme monotone, enjeux
absents, narration trop longue ou qui décide à la place des PJ, combat sans
but, fin unique, scènes non typées). Le back renvoie ruleId + params, les
textes fr/en sont dans l'i18n. Panneau sur le hub, encart dans les éditeurs,
liens « Voir » avec ?focus= (nouveaux focus : narration, choices, stakes).
- M3 méthode guidée : POST /api/campaigns/{id}/guided-skeleton (arc existant
ou nouveau, chapitre, scènes typées, chaînage optionnel, transactionnel)
+ assistant pas à pas générique /campaigns/:id/guided/:method, première
méthode « Donjon en 5 salles ». Entrées sur le hub de campagne.
- Garde-fous vitest : complétude des textes fr/en du coach, de la relecture
(règles lues dans le Java) et des méthodes guidées.
Vérifié : core clean verify (1182 tests), web build + 299 tests vitest, lint
sans erreur, parcours testés dans l'appli (back Postgres de dev).
À redéployer : core (2 endpoints, aucune migration) + web.
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Squelette d'aventure produit par une méthode guidée (Mentor d'écriture, phase M3 —
|
||||
* voir docs/conception-mentor-ecriture.md) : un chapitre et ses scènes, rédigés par le MJ
|
||||
* question par question. Générique : chaque méthode (Donjon en 5 salles, puis M5) construit
|
||||
* ce même squelette côté front ; le Core se contente de le persister d'un bloc.
|
||||
*
|
||||
* <p>Placement : soit {@code arcId} (arc LINÉAIRE existant de la campagne, le chapitre
|
||||
* est ajouté à la suite), soit {@code newArcName} (nouvel arc linéaire créé à la suite).
|
||||
* Exactement l'un des deux.</p>
|
||||
*
|
||||
* @param arcId arc existant où ajouter le chapitre, ou {@code null}
|
||||
* @param newArcName nom du nouvel arc à créer, ou {@code null}
|
||||
* @param chapter le chapitre (nom obligatoire)
|
||||
* @param scenes les scènes, dans l'ordre (au moins une avec un nom)
|
||||
* @param linkSequentially relier chaque scène à la suivante par une sortie
|
||||
* @param linkLabel libellé de ces sorties (rédigé dans la langue du MJ par le front)
|
||||
*/
|
||||
public record GuidedSkeleton(
|
||||
String arcId,
|
||||
String newArcName,
|
||||
ChapterSpec chapter,
|
||||
List<SceneSpec> scenes,
|
||||
boolean linkSequentially,
|
||||
String linkLabel
|
||||
) {
|
||||
|
||||
public record ChapterSpec(String name, String description, String playerObjectives, String narrativeStakes) {
|
||||
}
|
||||
|
||||
public record SceneSpec(
|
||||
String name, String description, SceneType type, String location,
|
||||
String choicesConsequences, String gmSecretNotes, String enemies) {
|
||||
}
|
||||
|
||||
/** Ce qui a été créé, pour que le front ouvre directement le chapitre. */
|
||||
public record Result(String arcId, String chapterId, List<String> sceneIds) {
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||
import com.loremind.domain.campaigncontext.structure.LinkType;
|
||||
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Persiste d'un bloc le squelette d'une méthode guidée (Mentor d'écriture, phase M3) :
|
||||
* arc (existant ou nouveau) → chapitre → scènes typées, éventuellement reliées en chaîne.
|
||||
*
|
||||
* <p>Ne fait qu'ajouter : rien d'existant n'est modifié, à part l'ordre naturel (le nouvel
|
||||
* arc et le nouveau chapitre se placent à la suite). Transactionnel : tout ou rien.</p>
|
||||
*/
|
||||
@Service
|
||||
public class GuidedSkeletonService {
|
||||
|
||||
private final ArcRepository arcRepository;
|
||||
private final ChapterRepository chapterRepository;
|
||||
private final SceneRepository sceneRepository;
|
||||
private final ArcService arcService;
|
||||
private final ChapterService chapterService;
|
||||
private final SceneService sceneService;
|
||||
|
||||
public GuidedSkeletonService(ArcRepository arcRepository,
|
||||
ChapterRepository chapterRepository,
|
||||
SceneRepository sceneRepository,
|
||||
ArcService arcService,
|
||||
ChapterService chapterService,
|
||||
SceneService sceneService) {
|
||||
this.arcRepository = arcRepository;
|
||||
this.chapterRepository = chapterRepository;
|
||||
this.sceneRepository = sceneRepository;
|
||||
this.arcService = arcService;
|
||||
this.chapterService = chapterService;
|
||||
this.sceneService = sceneService;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws IllegalArgumentException squelette invalide (placement ambigu, chapitre ou scènes sans nom,
|
||||
* arc d'une autre campagne ou non linéaire)
|
||||
*/
|
||||
@Transactional
|
||||
public GuidedSkeleton.Result create(String campaignId, GuidedSkeleton skeleton) {
|
||||
validate(skeleton);
|
||||
List<GuidedSkeleton.SceneSpec> specs = skeleton.scenes().stream()
|
||||
.filter(s -> s != null && !isBlank(s.name()))
|
||||
.toList();
|
||||
|
||||
String arcId = resolveArc(campaignId, skeleton);
|
||||
Chapter chapter = createChapter(arcId, skeleton.chapter());
|
||||
|
||||
List<Scene> scenes = new ArrayList<>();
|
||||
int order = 0;
|
||||
for (GuidedSkeleton.SceneSpec spec : specs) {
|
||||
scenes.add(sceneService.createScene(Scene.builder()
|
||||
.name(spec.name().trim())
|
||||
.description(blankToNull(spec.description()))
|
||||
.type(Objects.requireNonNullElse(spec.type(), SceneType.GENERIC))
|
||||
.location(blankToNull(spec.location()))
|
||||
.choicesConsequences(blankToNull(spec.choicesConsequences()))
|
||||
.gmSecretNotes(blankToNull(spec.gmSecretNotes()))
|
||||
.enemies(blankToNull(spec.enemies()))
|
||||
.chapterId(chapter.getId())
|
||||
.order(order++)
|
||||
.build()));
|
||||
}
|
||||
|
||||
if (skeleton.linkSequentially()) {
|
||||
linkInChain(scenes, isBlank(skeleton.linkLabel()) ? "→" : skeleton.linkLabel().trim());
|
||||
}
|
||||
|
||||
return new GuidedSkeleton.Result(arcId, chapter.getId(), scenes.stream().map(Scene::getId).toList());
|
||||
}
|
||||
|
||||
private static void validate(GuidedSkeleton skeleton) {
|
||||
if (skeleton == null) {
|
||||
throw new IllegalArgumentException("Squelette manquant.");
|
||||
}
|
||||
boolean hasArc = !isBlank(skeleton.arcId());
|
||||
boolean hasNewArc = !isBlank(skeleton.newArcName());
|
||||
if (hasArc == hasNewArc) {
|
||||
throw new IllegalArgumentException("Indiquer soit un arc existant, soit le nom d'un nouvel arc.");
|
||||
}
|
||||
if (skeleton.chapter() == null || isBlank(skeleton.chapter().name())) {
|
||||
throw new IllegalArgumentException("Le chapitre doit avoir un nom.");
|
||||
}
|
||||
if (skeleton.scenes() == null || skeleton.scenes().stream().noneMatch(s -> s != null && !isBlank(s.name()))) {
|
||||
throw new IllegalArgumentException("Il faut au moins une scène nommée.");
|
||||
}
|
||||
}
|
||||
|
||||
/** Arc existant (vérifié : même campagne, linéaire) ou nouvel arc linéaire placé à la suite. */
|
||||
private String resolveArc(String campaignId, GuidedSkeleton skeleton) {
|
||||
List<Arc> arcs = arcRepository.findByCampaignId(campaignId);
|
||||
if (!isBlank(skeleton.arcId())) {
|
||||
Arc arc = arcs.stream().filter(a -> skeleton.arcId().equals(a.getId())).findFirst()
|
||||
.orElseThrow(() -> new IllegalArgumentException("Arc introuvable dans cette campagne."));
|
||||
if (arc.getType() != ArcType.LINEAR) {
|
||||
throw new IllegalArgumentException("Une méthode guidée s'ajoute à un arc linéaire.");
|
||||
}
|
||||
return arc.getId();
|
||||
}
|
||||
// L'arc SYSTEM (« Quêtes libres », ordre 9999) reste en dernier : on ne le compte pas.
|
||||
int nextOrder = arcs.stream().filter(a -> a.getType() != ArcType.SYSTEM)
|
||||
.mapToInt(Arc::getOrder).max().orElse(-1) + 1;
|
||||
return arcService.createArc(Arc.builder()
|
||||
.name(skeleton.newArcName().trim())
|
||||
.campaignId(campaignId)
|
||||
.type(ArcType.LINEAR)
|
||||
.order(nextOrder)
|
||||
.build()).getId();
|
||||
}
|
||||
|
||||
private Chapter createChapter(String arcId, GuidedSkeleton.ChapterSpec spec) {
|
||||
int nextOrder = chapterRepository.findByArcId(arcId).stream()
|
||||
.mapToInt(Chapter::getOrder).max().orElse(-1) + 1;
|
||||
return chapterService.createChapter(Chapter.builder()
|
||||
.name(spec.name().trim())
|
||||
.description(blankToNull(spec.description()))
|
||||
.playerObjectives(blankToNull(spec.playerObjectives()))
|
||||
.narrativeStakes(blankToNull(spec.narrativeStakes()))
|
||||
.arcId(arcId)
|
||||
.order(nextOrder)
|
||||
.build());
|
||||
}
|
||||
|
||||
/** Chaque scène reçoit une sortie vers la suivante (la dernière n'en a pas). */
|
||||
private void linkInChain(List<Scene> scenes, String label) {
|
||||
for (int i = 0; i < scenes.size() - 1; i++) {
|
||||
Scene scene = scenes.get(i);
|
||||
scene.setBranches(new ArrayList<>(List.of(
|
||||
new SceneBranch(label, scenes.get(i + 1).getId(), null, LinkType.EXIT))));
|
||||
sceneRepository.save(scene);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isBlank(String s) {
|
||||
return s == null || s.isBlank();
|
||||
}
|
||||
|
||||
private static String blankToNull(String s) {
|
||||
return isBlank(s) ? null : s.trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
|
||||
import com.loremind.domain.campaigncontext.writingreview.WritingRemarkCategory;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Une remarque de relecture d'éditeur (Mentor d'écriture, phase M2) : un conseil
|
||||
* d'auteur sur la QUALITÉ de l'écriture, pas sur la complétude (ça, c'est le readiness).
|
||||
*
|
||||
* <p>Contrairement à {@link ReadinessGap}, le back ne rédige pas le texte : il
|
||||
* renvoie la règle et ses paramètres, et le front compose observation / pourquoi /
|
||||
* question depuis l'i18n ({@code writingReview.rules.<ruleId>}), en fr comme en en.</p>
|
||||
*
|
||||
* @param entityType type de l'entité concernée (réutilise celui du readiness pour les liens profonds)
|
||||
* @param entityId id de l'entité concernée
|
||||
* @param entityName libellé lisible de l'entité
|
||||
* @param ruleId identifiant stable de la règle (ex. {@code WRITE-002-FAKE-CHOICE})
|
||||
* @param category famille de la remarque (regroupement à l'affichage)
|
||||
* @param params valeurs à injecter dans le texte i18n (ex. {@code count}, {@code phrase})
|
||||
* @param arcId arc parent (navigation), ou {@code null}
|
||||
* @param chapterId chapitre parent (navigation), ou {@code null}
|
||||
*/
|
||||
public record WritingRemark(
|
||||
ReadinessEntityType entityType,
|
||||
String entityId,
|
||||
String entityName,
|
||||
String ruleId,
|
||||
WritingRemarkCategory category,
|
||||
Map<String, String> params,
|
||||
String arcId,
|
||||
String chapterId
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Relecture d'éditeur d'une campagne (Mentor d'écriture, phase M2).
|
||||
*
|
||||
* @param campaignId campagne relue
|
||||
* @param remarks remarques dans l'ordre de l'arbre (campagne, puis arc par arc)
|
||||
*/
|
||||
public record WritingReviewReport(String campaignId, List<WritingRemark> remarks) {
|
||||
}
|
||||
+333
@@ -0,0 +1,333 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import com.loremind.domain.campaigncontext.quest.Quest;
|
||||
import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
|
||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
import com.loremind.domain.campaigncontext.writingreview.WritingRemarkCategory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Relecture d'éditeur (Mentor d'écriture, phase M2 — voir docs/conception-mentor-ecriture.md) :
|
||||
* conseils d'auteur sur la QUALITÉ de l'écriture (vrais choix, rythme, enjeux, narration),
|
||||
* là où le readiness ({@link CampaignReadinessService}) ne juge que la complétude.
|
||||
*
|
||||
* <p><b>Déterministe, sans IA, sans persistance</b> ; même chargement en une passe que le
|
||||
* readiness (arcs → chapitres → scènes). Purement indicatif : une remarque est un conseil,
|
||||
* jamais un blocage. Le texte est composé côté front à partir de {@code ruleId} + {@code params}.</p>
|
||||
*
|
||||
* <p>L'arc SYSTEM (« Quêtes libres ») est de la plomberie invisible : ses chapitres-conteneurs
|
||||
* ne reçoivent pas de remarque de niveau chapitre, mais leurs scènes sont relues comme les autres.</p>
|
||||
*/
|
||||
@Service
|
||||
public class WritingReviewService {
|
||||
|
||||
/** WRITE-001 : à partir de combien de scènes un chapitre sans aucun choix devient un couloir. */
|
||||
static final int CORRIDOR_MIN_SCENES = 3;
|
||||
/** WRITE-003 : nombre minimal de chemins menant à une révélation (en deçà : un seul chemin). */
|
||||
static final int REVELATION_MIN_INCOMING = 2;
|
||||
/** WRITE-004 : longueur d'une suite de scènes du même genre jugée monotone. */
|
||||
static final int MONOTONOUS_RUN = 3;
|
||||
/** WRITE-006 : au-delà, la narration dépasse ~1 min de lecture à voix haute (~900 car./min). */
|
||||
static final int LONG_NARRATION_CHARS = 1200;
|
||||
/** WRITE-010 : nombre minimal de scènes pour juger la part de scènes non typées. */
|
||||
static final int UNTYPED_MIN_SCENES = 5;
|
||||
/** WRITE-010 : part de scènes « génériques » au-delà de laquelle on conseille de typer. */
|
||||
static final double UNTYPED_RATIO = 0.7;
|
||||
|
||||
/** Genre « combat » pour WRITE-004 (les autres genres = nom du {@link SceneType}). */
|
||||
static final String KIND_COMBAT = "COMBAT";
|
||||
|
||||
/**
|
||||
* WRITE-007 : la narration décide à la place des personnages (action ou émotion imposée).
|
||||
* Volontairement restreint aux tournures sans ambiguïté, pour éviter les faux positifs.
|
||||
*/
|
||||
private static final Pattern NARRATION_DECIDES = Pattern.compile(
|
||||
"\\b(vous (?:décidez|choisissez|ressentez|avez (?:très |si )?peur"
|
||||
+ "|êtes (?:terrifié|effrayé|terrorisé|paniqué|soulagé|ému)e?s?"
|
||||
+ "|entrez|vous précipitez|dégainez|attaquez|fuyez)"
|
||||
+ "|you (?:decide|choose|feel (?:afraid|scared|uneasy|relieved|guilty)"
|
||||
+ "|are (?:afraid|scared|terrified|relieved|panicking)"
|
||||
+ "|enter|rush|draw your|attack|flee))\\b",
|
||||
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.UNICODE_CHARACTER_CLASS);
|
||||
|
||||
private final CampaignRepository campaignRepository;
|
||||
private final ArcRepository arcRepository;
|
||||
private final ChapterRepository chapterRepository;
|
||||
private final SceneRepository sceneRepository;
|
||||
private final QuestRepository questRepository;
|
||||
|
||||
public WritingReviewService(CampaignRepository campaignRepository,
|
||||
ArcRepository arcRepository,
|
||||
ChapterRepository chapterRepository,
|
||||
SceneRepository sceneRepository,
|
||||
QuestRepository questRepository) {
|
||||
this.campaignRepository = campaignRepository;
|
||||
this.arcRepository = arcRepository;
|
||||
this.chapterRepository = chapterRepository;
|
||||
this.sceneRepository = sceneRepository;
|
||||
this.questRepository = questRepository;
|
||||
}
|
||||
|
||||
/** Relit toute la campagne et renvoie les remarques dans l'ordre de l'arbre. */
|
||||
public WritingReviewReport review(String campaignId) {
|
||||
List<WritingRemark> campaignRemarks = new ArrayList<>();
|
||||
List<WritingRemark> treeRemarks = new ArrayList<>();
|
||||
|
||||
Set<String> arcsWithQuests = questRepository.findByCampaignId(campaignId).stream()
|
||||
.map(Quest::getArcId).filter(id -> !isBlank(id)).collect(Collectors.toSet());
|
||||
|
||||
List<Arc> arcs = new ArrayList<>(arcRepository.findByCampaignId(campaignId));
|
||||
arcs.sort(Comparator.comparingInt(Arc::getOrder));
|
||||
|
||||
int totalScenes = 0;
|
||||
int genericScenes = 0;
|
||||
for (Arc arc : arcs) {
|
||||
List<Chapter> chapters = new ArrayList<>(chapterRepository.findByArcId(arc.getId()));
|
||||
chapters.sort(Comparator.comparingInt(Chapter::getOrder));
|
||||
boolean visibleArc = arc.getType() != ArcType.SYSTEM;
|
||||
|
||||
// WRITE-005 (arc) : seulement sur un arc qui a déjà du contenu.
|
||||
if (visibleArc && isBlank(arc.getStakes())
|
||||
&& (!chapters.isEmpty() || arcsWithQuests.contains(arc.getId()))) {
|
||||
treeRemarks.add(arcRemark(arc, "WRITE-005-NO-STAKES", WritingRemarkCategory.STAKES, Map.of()));
|
||||
}
|
||||
|
||||
List<Scene> lastChapterScenes = List.of();
|
||||
for (Chapter chapter : chapters) {
|
||||
List<Scene> scenes = new ArrayList<>(sceneRepository.findByChapterId(chapter.getId()));
|
||||
scenes.sort(Comparator.comparingInt(Scene::getOrder));
|
||||
totalScenes += scenes.size();
|
||||
genericScenes += (int) scenes.stream().filter(s -> typeOf(s) == SceneType.GENERIC).count();
|
||||
|
||||
if (visibleArc) {
|
||||
reviewChapter(arc, chapter, scenes, treeRemarks);
|
||||
}
|
||||
for (Scene scene : scenes) {
|
||||
reviewScene(arc, chapter, scene, scenes, treeRemarks);
|
||||
}
|
||||
if (!scenes.isEmpty()) {
|
||||
lastChapterScenes = scenes;
|
||||
}
|
||||
}
|
||||
|
||||
if (arc.getType() == ArcType.LINEAR && !lastChapterScenes.isEmpty()) {
|
||||
checkSingleEnding(arc, lastChapterScenes, treeRemarks);
|
||||
}
|
||||
}
|
||||
|
||||
// WRITE-010 — trop de scènes non typées pour juger le rythme.
|
||||
if (totalScenes >= UNTYPED_MIN_SCENES && (double) genericScenes / totalScenes > UNTYPED_RATIO) {
|
||||
String campaignName = campaignRepository.findById(campaignId).map(Campaign::getName).orElse(null);
|
||||
int pct = (int) Math.round(100.0 * genericScenes / totalScenes);
|
||||
campaignRemarks.add(new WritingRemark(ReadinessEntityType.CAMPAIGN, campaignId, campaignName,
|
||||
"WRITE-010-UNTYPED-SCENES", WritingRemarkCategory.PACING,
|
||||
Map.of("percent", String.valueOf(pct), "count", String.valueOf(genericScenes)),
|
||||
null, null));
|
||||
}
|
||||
|
||||
List<WritingRemark> remarks = new ArrayList<>(campaignRemarks);
|
||||
remarks.addAll(treeRemarks);
|
||||
return new WritingReviewReport(campaignId, remarks);
|
||||
}
|
||||
|
||||
// --- Niveau chapitre ---------------------------------------------------------------
|
||||
|
||||
private void reviewChapter(Arc arc, Chapter chapter, List<Scene> scenes, List<WritingRemark> out) {
|
||||
if (scenes.isEmpty()) return; // Chapitre vide : c'est l'affaire du readiness (CHAP-001).
|
||||
|
||||
// WRITE-001 — couloir : plusieurs scènes, aucune sortie ni aucun choix décrit.
|
||||
boolean anyBranch = scenes.stream().anyMatch(WritingReviewService::hasBranches);
|
||||
boolean anyChoice = scenes.stream().anyMatch(s -> !isBlank(s.getChoicesConsequences()));
|
||||
if (scenes.size() >= CORRIDOR_MIN_SCENES && !anyBranch && !anyChoice) {
|
||||
out.add(chapterRemark(arc, chapter, "WRITE-001-CORRIDOR", WritingRemarkCategory.AGENCY,
|
||||
Map.of("count", String.valueOf(scenes.size()))));
|
||||
}
|
||||
|
||||
// WRITE-004 — rythme monotone : N scènes d'affilée du même genre.
|
||||
MonotonousRun run = findMonotonousRun(scenes);
|
||||
if (run != null) {
|
||||
out.add(chapterRemark(arc, chapter, "WRITE-004-MONOTONOUS-PACING", WritingRemarkCategory.PACING,
|
||||
Map.of("count", String.valueOf(run.length()), "kind", run.kind())));
|
||||
}
|
||||
|
||||
// WRITE-005 (chapitre) — aucun enjeu narratif écrit.
|
||||
if (isBlank(chapter.getNarrativeStakes())) {
|
||||
out.add(chapterRemark(arc, chapter, "WRITE-005-NO-STAKES", WritingRemarkCategory.STAKES, Map.of()));
|
||||
}
|
||||
}
|
||||
|
||||
private record MonotonousRun(String kind, int length) {}
|
||||
|
||||
/** Première suite d'au moins {@link #MONOTONOUS_RUN} scènes consécutives du même genre, sinon null. */
|
||||
private static MonotonousRun findMonotonousRun(List<Scene> scenes) {
|
||||
String currentKind = null;
|
||||
int length = 0;
|
||||
MonotonousRun found = null;
|
||||
for (Scene scene : scenes) {
|
||||
String kind = pacingKind(scene);
|
||||
if (kind != null && kind.equals(currentKind)) {
|
||||
length++;
|
||||
} else {
|
||||
if (found != null) return found;
|
||||
currentKind = kind;
|
||||
length = kind == null ? 0 : 1;
|
||||
}
|
||||
if (length >= MONOTONOUS_RUN) {
|
||||
found = new MonotonousRun(currentKind, length);
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** Genre d'une scène pour le rythme : COMBAT, sinon son type s'il est renseigné, sinon null. */
|
||||
private static String pacingKind(Scene scene) {
|
||||
if (isCombat(scene)) return KIND_COMBAT;
|
||||
SceneType type = typeOf(scene);
|
||||
return type == SceneType.GENERIC ? null : type.name();
|
||||
}
|
||||
|
||||
// --- Niveau scène -------------------------------------------------------------------
|
||||
|
||||
private void reviewScene(Arc arc, Chapter chapter, Scene scene, List<Scene> chapterScenes,
|
||||
List<WritingRemark> out) {
|
||||
checkFakeChoice(arc, chapter, scene, chapterScenes, out);
|
||||
checkSingleClue(arc, chapter, scene, chapterScenes, out);
|
||||
checkNarration(arc, chapter, scene, out);
|
||||
checkCombatPurpose(arc, chapter, scene, out);
|
||||
}
|
||||
|
||||
/** WRITE-002 — faux carrefour : plusieurs sorties qui mènent toutes au même endroit. */
|
||||
private void checkFakeChoice(Arc arc, Chapter chapter, Scene scene, List<Scene> chapterScenes,
|
||||
List<WritingRemark> out) {
|
||||
List<SceneBranch> branches = scene.getBranches();
|
||||
if (branches == null || branches.size() < 2) return;
|
||||
Set<String> targets = branches.stream().map(SceneBranch::targetSceneId).collect(Collectors.toSet());
|
||||
if (targets.size() != 1) return;
|
||||
String target = targets.iterator().next();
|
||||
if (isBlank(target)) return; // Branche cassée : c'est l'affaire du readiness (SCENE-010).
|
||||
String targetName = chapterScenes.stream()
|
||||
.filter(s -> target.equals(s.getId())).map(Scene::getName)
|
||||
.filter(n -> !isBlank(n)).findFirst().orElse("?");
|
||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-002-FAKE-CHOICE", WritingRemarkCategory.AGENCY,
|
||||
Map.of("count", String.valueOf(branches.size()), "target", targetName)));
|
||||
}
|
||||
|
||||
/**
|
||||
* WRITE-003 — révélation à chemin unique (règle des 3 indices). Seulement dans un
|
||||
* chapitre qui utilise des liens : sans aucun lien, c'est WRITE-001 qui parle.
|
||||
*/
|
||||
private void checkSingleClue(Arc arc, Chapter chapter, Scene scene, List<Scene> chapterScenes,
|
||||
List<WritingRemark> out) {
|
||||
if (typeOf(scene) != SceneType.REVELATION || isBlank(scene.getId())) return;
|
||||
if (chapterScenes.stream().noneMatch(WritingReviewService::hasBranches)) return;
|
||||
long incoming = chapterScenes.stream()
|
||||
.filter(s -> !scene.getId().equals(s.getId()) && s.getBranches() != null)
|
||||
.flatMap(s -> s.getBranches().stream().map(SceneBranch::targetSceneId).distinct())
|
||||
.filter(scene.getId()::equals)
|
||||
.count();
|
||||
if (incoming < REVELATION_MIN_INCOMING) {
|
||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-003-SINGLE-CLUE", WritingRemarkCategory.AGENCY,
|
||||
Map.of("incoming", String.valueOf(incoming))));
|
||||
}
|
||||
}
|
||||
|
||||
/** WRITE-006 — narration trop longue ; WRITE-007 — narration qui décide à la place des PJ. */
|
||||
private void checkNarration(Arc arc, Chapter chapter, Scene scene, List<WritingRemark> out) {
|
||||
String narration = scene.getPlayerNarration();
|
||||
if (isBlank(narration)) return;
|
||||
int length = narration.strip().length();
|
||||
if (length > LONG_NARRATION_CHARS) {
|
||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-006-LONG-NARRATION", WritingRemarkCategory.NARRATION,
|
||||
Map.of("chars", String.valueOf(length))));
|
||||
}
|
||||
Matcher m = NARRATION_DECIDES.matcher(narration);
|
||||
if (m.find()) {
|
||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-007-NARRATION-DECIDES", WritingRemarkCategory.NARRATION,
|
||||
Map.of("phrase", m.group(1))));
|
||||
}
|
||||
}
|
||||
|
||||
/** WRITE-008 — combat sans but : ni choix décrits, ni notes sur les motivations des ennemis. */
|
||||
private void checkCombatPurpose(Arc arc, Chapter chapter, Scene scene, List<WritingRemark> out) {
|
||||
if (isCombat(scene) && isBlank(scene.getChoicesConsequences()) && isBlank(scene.getGmSecretNotes())) {
|
||||
out.add(sceneRemark(arc, chapter, scene, "WRITE-008-COMBAT-NO-PURPOSE", WritingRemarkCategory.STAKES,
|
||||
Map.of()));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Niveau arc -----------------------------------------------------------------------
|
||||
|
||||
/** WRITE-009 — fin unique : la dernière scène de l'arc ne prévoit ni sortie ni alternative. */
|
||||
private void checkSingleEnding(Arc arc, List<Scene> lastChapterScenes, List<WritingRemark> out) {
|
||||
Scene finale = lastChapterScenes.get(lastChapterScenes.size() - 1);
|
||||
if (!hasBranches(finale) && isBlank(finale.getChoicesConsequences())) {
|
||||
out.add(new WritingRemark(ReadinessEntityType.SCENE, finale.getId(), labelOr(finale.getName(), "Scène"),
|
||||
"WRITE-009-SINGLE-ENDING", WritingRemarkCategory.AGENCY,
|
||||
Map.of("arc", labelOr(arc.getName(), "Arc")), arc.getId(), finale.getChapterId()));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Helpers ----------------------------------------------------------------------------
|
||||
|
||||
private static boolean isCombat(Scene scene) {
|
||||
return typeOf(scene) == SceneType.ENCOUNTER
|
||||
|| !isBlank(scene.getCombatDifficulty())
|
||||
|| !isBlank(scene.getEnemies())
|
||||
|| (scene.getEnemyIds() != null && scene.getEnemyIds().stream().anyMatch(id -> !isBlank(id)));
|
||||
}
|
||||
|
||||
private static boolean hasBranches(Scene scene) {
|
||||
return scene.getBranches() != null && !scene.getBranches().isEmpty();
|
||||
}
|
||||
|
||||
private static SceneType typeOf(Scene scene) {
|
||||
return Objects.requireNonNullElse(scene.getType(), SceneType.GENERIC);
|
||||
}
|
||||
|
||||
private static WritingRemark sceneRemark(Arc arc, Chapter chapter, Scene scene, String ruleId,
|
||||
WritingRemarkCategory category, Map<String, String> params) {
|
||||
return new WritingRemark(ReadinessEntityType.SCENE, scene.getId(), labelOr(scene.getName(), "Scène"),
|
||||
ruleId, category, params, arc.getId(), chapter.getId());
|
||||
}
|
||||
|
||||
private static WritingRemark chapterRemark(Arc arc, Chapter chapter, String ruleId,
|
||||
WritingRemarkCategory category, Map<String, String> params) {
|
||||
return new WritingRemark(ReadinessEntityType.CHAPTER, chapter.getId(), labelOr(chapter.getName(), "Chapitre"),
|
||||
ruleId, category, params, arc.getId(), chapter.getId());
|
||||
}
|
||||
|
||||
private static WritingRemark arcRemark(Arc arc, String ruleId, WritingRemarkCategory category,
|
||||
Map<String, String> params) {
|
||||
return new WritingRemark(ReadinessEntityType.ARC, arc.getId(), labelOr(arc.getName(), "Arc"),
|
||||
ruleId, category, params, arc.getId(), null);
|
||||
}
|
||||
|
||||
private static boolean isBlank(String s) {
|
||||
return s == null || s.isBlank();
|
||||
}
|
||||
|
||||
private static String labelOr(String value, String fallback) {
|
||||
return isBlank(value) ? fallback : value;
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.loremind.domain.campaigncontext.writingreview;
|
||||
|
||||
/**
|
||||
* Famille d'une remarque de relecture (Mentor d'écriture, phase M2). Sert à
|
||||
* regrouper les conseils côté front ; n'implique aucune gravité : une remarque de
|
||||
* relecture est un conseil d'auteur, jamais un blocage.
|
||||
*/
|
||||
public enum WritingRemarkCategory {
|
||||
/** Pouvoir des joueurs : vrais choix, chemins multiples, issues alternatives. */
|
||||
AGENCY,
|
||||
/** Rythme : variété des scènes, lisibilité de la structure. */
|
||||
PACING,
|
||||
/** Enjeux : ce que les joueurs risquent, pourquoi l'adversité agit. */
|
||||
STAKES,
|
||||
/** Narration : textes lus aux joueurs. */
|
||||
NARRATION
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.campaigncontext.GuidedSkeleton;
|
||||
import com.loremind.application.campaigncontext.GuidedSkeletonService;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* REST Controller des méthodes guidées (Mentor d'écriture, phase M3) : persiste le
|
||||
* squelette (arc → chapitre → scènes) construit question par question par le MJ.
|
||||
*
|
||||
* <p>201 + ids créés ; 400 si le squelette est invalide ({@code GlobalExceptionHandler}) ;
|
||||
* 404 si la campagne est inconnue.</p>
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/campaigns/{campaignId}/guided-skeleton")
|
||||
public class GuidedSkeletonController {
|
||||
|
||||
private final GuidedSkeletonService guidedSkeletonService;
|
||||
private final CampaignRepository campaignRepository;
|
||||
|
||||
public GuidedSkeletonController(GuidedSkeletonService guidedSkeletonService,
|
||||
CampaignRepository campaignRepository) {
|
||||
this.guidedSkeletonService = guidedSkeletonService;
|
||||
this.campaignRepository = campaignRepository;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<GuidedSkeleton.Result> create(@PathVariable String campaignId,
|
||||
@RequestBody GuidedSkeleton skeleton) {
|
||||
if (!campaignRepository.existsById(campaignId)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
// Squelette invalide : IllegalArgumentException → 400 via GlobalExceptionHandler.
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(guidedSkeletonService.create(campaignId, skeleton));
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.loremind.infrastructure.web.controller;
|
||||
|
||||
import com.loremind.application.campaigncontext.WritingReviewReport;
|
||||
import com.loremind.application.campaigncontext.WritingReviewService;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* REST Controller de la relecture d'éditeur (Mentor d'écriture, phase M2) : conseils
|
||||
* d'auteur sur la qualité de l'écriture d'une campagne.
|
||||
*
|
||||
* <p>Read-model pur, toujours 200 quand la campagne existe (les remarques conseillent,
|
||||
* elles ne bloquent rien). 404 si la campagne est inconnue.</p>
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/campaigns/{campaignId}/writing-review")
|
||||
public class WritingReviewController {
|
||||
|
||||
private final WritingReviewService writingReviewService;
|
||||
private final CampaignRepository campaignRepository;
|
||||
|
||||
public WritingReviewController(WritingReviewService writingReviewService,
|
||||
CampaignRepository campaignRepository) {
|
||||
this.writingReviewService = writingReviewService;
|
||||
this.campaignRepository = campaignRepository;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<WritingReviewReport> getWritingReview(@PathVariable String campaignId) {
|
||||
if (!campaignRepository.existsById(campaignId)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
return ResponseEntity.ok(writingReviewService.review(campaignId));
|
||||
}
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Test unitaire pour {@link GuidedSkeletonService} (Mentor d'écriture, phase M3) :
|
||||
* placement (nouvel arc / arc existant), champs reportés, chaînage des scènes, validations.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class GuidedSkeletonServiceTest {
|
||||
|
||||
private static final String CAMP = "camp";
|
||||
|
||||
@Mock private ArcRepository arcRepository;
|
||||
@Mock private ChapterRepository chapterRepository;
|
||||
@Mock private SceneRepository sceneRepository;
|
||||
@Mock private ArcService arcService;
|
||||
@Mock private ChapterService chapterService;
|
||||
@Mock private SceneService sceneService;
|
||||
|
||||
@InjectMocks private GuidedSkeletonService service;
|
||||
|
||||
private final List<Scene> createdScenes = new ArrayList<>();
|
||||
|
||||
@BeforeEach
|
||||
void stubCreations() {
|
||||
AtomicInteger ids = new AtomicInteger();
|
||||
when(arcService.createArc(any(Arc.class))).thenAnswer(inv -> {
|
||||
Arc a = inv.getArgument(0);
|
||||
a.setId("new-arc");
|
||||
return a;
|
||||
});
|
||||
when(chapterService.createChapter(any(Chapter.class))).thenAnswer(inv -> {
|
||||
Chapter c = inv.getArgument(0);
|
||||
c.setId("new-chap");
|
||||
return c;
|
||||
});
|
||||
when(sceneService.createScene(any(Scene.class))).thenAnswer(inv -> {
|
||||
Scene s = inv.getArgument(0);
|
||||
s.setId("scene-" + ids.incrementAndGet());
|
||||
createdScenes.add(s);
|
||||
return s;
|
||||
});
|
||||
}
|
||||
|
||||
private static GuidedSkeleton.SceneSpec room(String name, SceneType type) {
|
||||
return new GuidedSkeleton.SceneSpec(name, "Ce qui s'y passe", type, "La crypte",
|
||||
"Combattre ou négocier", "Le gardien protège son frère", null);
|
||||
}
|
||||
|
||||
private static GuidedSkeleton skeleton(String arcId, String newArcName, boolean link) {
|
||||
return new GuidedSkeleton(arcId, newArcName,
|
||||
new GuidedSkeleton.ChapterSpec("La crypte oubliée", "Une accroche", "Retrouver le reliquaire", "Le village sera maudit"),
|
||||
List.of(room("Salle 1", SceneType.ENCOUNTER), room("Salle 2", SceneType.LOCATION), room("Salle 3", SceneType.REVELATION)),
|
||||
link, "Vers la salle suivante");
|
||||
}
|
||||
|
||||
@Test
|
||||
void newArc_isLinear_andPlacedAfterVisibleArcs_beforeSystemArc() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(
|
||||
Arc.builder().id("a1").type(ArcType.LINEAR).order(0).build(),
|
||||
Arc.builder().id("a2").type(ArcType.HUB).order(1).build(),
|
||||
Arc.builder().id("sys").type(ArcType.SYSTEM).order(9999).build()));
|
||||
|
||||
GuidedSkeleton.Result result = service.create(CAMP, skeleton(null, "Les terres brûlées", false));
|
||||
|
||||
ArgumentCaptor<Arc> arc = ArgumentCaptor.forClass(Arc.class);
|
||||
verify(arcService).createArc(arc.capture());
|
||||
assertEquals(ArcType.LINEAR, arc.getValue().getType());
|
||||
assertEquals(2, arc.getValue().getOrder());
|
||||
assertEquals(CAMP, arc.getValue().getCampaignId());
|
||||
assertEquals("new-arc", result.arcId());
|
||||
assertEquals("new-chap", result.chapterId());
|
||||
assertEquals(List.of("scene-1", "scene-2", "scene-3"), result.sceneIds());
|
||||
}
|
||||
|
||||
@Test
|
||||
void existingArc_chapterAppendedAfterExistingChapters_withItsFields() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(
|
||||
Arc.builder().id("a1").type(ArcType.LINEAR).order(0).build()));
|
||||
when(chapterRepository.findByArcId("a1")).thenReturn(List.of(
|
||||
Chapter.builder().id("c1").arcId("a1").order(0).build(),
|
||||
Chapter.builder().id("c2").arcId("a1").order(3).build()));
|
||||
|
||||
service.create(CAMP, skeleton("a1", null, false));
|
||||
|
||||
verify(arcService, never()).createArc(any(Arc.class));
|
||||
ArgumentCaptor<Chapter> chapter = ArgumentCaptor.forClass(Chapter.class);
|
||||
verify(chapterService).createChapter(chapter.capture());
|
||||
assertEquals("a1", chapter.getValue().getArcId());
|
||||
assertEquals(4, chapter.getValue().getOrder());
|
||||
assertEquals("Retrouver le reliquaire", chapter.getValue().getPlayerObjectives());
|
||||
assertEquals("Le village sera maudit", chapter.getValue().getNarrativeStakes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void scenes_keepOrderTypeAndFields() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of());
|
||||
|
||||
service.create(CAMP, skeleton(null, "Arc", false));
|
||||
|
||||
assertEquals(3, createdScenes.size());
|
||||
Scene first = createdScenes.get(0);
|
||||
assertEquals(0, first.getOrder());
|
||||
assertEquals("new-chap", first.getChapterId());
|
||||
assertEquals(SceneType.ENCOUNTER, first.getType());
|
||||
assertEquals("La crypte", first.getLocation());
|
||||
assertEquals("Combattre ou négocier", first.getChoicesConsequences());
|
||||
assertEquals("Le gardien protège son frère", first.getGmSecretNotes());
|
||||
assertEquals(SceneType.REVELATION, createdScenes.get(2).getType());
|
||||
assertEquals(2, createdScenes.get(2).getOrder());
|
||||
}
|
||||
|
||||
@Test
|
||||
void linkSequentially_chainsEachSceneToTheNext_lastHasNoExit() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of());
|
||||
|
||||
service.create(CAMP, skeleton(null, "Arc", true));
|
||||
|
||||
verify(sceneRepository, times(2)).save(any(Scene.class));
|
||||
assertEquals("scene-2", createdScenes.get(0).getBranches().get(0).targetSceneId());
|
||||
assertEquals("Vers la salle suivante", createdScenes.get(0).getBranches().get(0).label());
|
||||
assertEquals("scene-3", createdScenes.get(1).getBranches().get(0).targetSceneId());
|
||||
assertTrue(createdScenes.get(2).getBranches() == null || createdScenes.get(2).getBranches().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unnamedScenes_areSkipped_andBlankFieldsStoredAsNull() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of());
|
||||
GuidedSkeleton s = new GuidedSkeleton(null, "Arc",
|
||||
new GuidedSkeleton.ChapterSpec("Chap", " ", null, null),
|
||||
List.of(new GuidedSkeleton.SceneSpec("Salle", " ", null, "", null, null, null),
|
||||
new GuidedSkeleton.SceneSpec(" ", "ignorée", SceneType.EVENT, null, null, null, null)),
|
||||
false, null);
|
||||
|
||||
service.create(CAMP, s);
|
||||
|
||||
assertEquals(1, createdScenes.size());
|
||||
assertNull(createdScenes.get(0).getDescription());
|
||||
assertNull(createdScenes.get(0).getLocation());
|
||||
assertEquals(SceneType.GENERIC, createdScenes.get(0).getType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejects_ambiguousPlacement() {
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, skeleton("a1", "Arc", false)));
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, skeleton(null, " ", false)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejects_arcOfAnotherCampaign_orNonLinearArc() {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(
|
||||
Arc.builder().id("hub").type(ArcType.HUB).order(0).build()));
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, skeleton("ailleurs", null, false)));
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, skeleton("hub", null, false)));
|
||||
verify(chapterService, never()).createChapter(any(Chapter.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejects_missingChapterName_orNoNamedScene() {
|
||||
GuidedSkeleton noChapterName = new GuidedSkeleton(null, "Arc",
|
||||
new GuidedSkeleton.ChapterSpec(" ", null, null, null), List.of(room("S", null)), false, null);
|
||||
GuidedSkeleton noScene = new GuidedSkeleton(null, "Arc",
|
||||
new GuidedSkeleton.ChapterSpec("Chap", null, null, null),
|
||||
List.of(new GuidedSkeleton.SceneSpec("", null, null, null, null, null, null)), false, null);
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, noChapterName));
|
||||
assertThrows(IllegalArgumentException.class, () -> service.create(CAMP, noScene));
|
||||
}
|
||||
}
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
package com.loremind.application.campaigncontext;
|
||||
|
||||
import com.loremind.domain.campaigncontext.Campaign;
|
||||
import com.loremind.domain.campaigncontext.ports.ArcRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.CampaignRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.ChapterRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.QuestRepository;
|
||||
import com.loremind.domain.campaigncontext.ports.SceneRepository;
|
||||
import com.loremind.domain.campaigncontext.quest.Quest;
|
||||
import com.loremind.domain.campaigncontext.readiness.ReadinessEntityType;
|
||||
import com.loremind.domain.campaigncontext.structure.Arc;
|
||||
import com.loremind.domain.campaigncontext.structure.ArcType;
|
||||
import com.loremind.domain.campaigncontext.structure.Chapter;
|
||||
import com.loremind.domain.campaigncontext.structure.Scene;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneBranch;
|
||||
import com.loremind.domain.campaigncontext.structure.SceneType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Test unitaire pour {@link WritingReviewService} (Mentor d'écriture, phase M2).
|
||||
* Chaque règle WRITE-xxx a son cas positif ET un cas qui ne doit PAS la déclencher
|
||||
* (le mentor doit rester sobre : un faux positif décourage le débutant).
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class WritingReviewServiceTest {
|
||||
|
||||
private static final String CAMP = "camp";
|
||||
|
||||
@Mock private CampaignRepository campaignRepository;
|
||||
@Mock private ArcRepository arcRepository;
|
||||
@Mock private ChapterRepository chapterRepository;
|
||||
@Mock private SceneRepository sceneRepository;
|
||||
@Mock private QuestRepository questRepository;
|
||||
|
||||
@InjectMocks private WritingReviewService service;
|
||||
|
||||
// --- helpers ---
|
||||
|
||||
private static Arc arc(String id, ArcType type) {
|
||||
return Arc.builder().id(id).name(id).campaignId(CAMP).type(type).order(0).stakes("Le village brûle").build();
|
||||
}
|
||||
|
||||
private static Chapter chapter(String id, String arcId) {
|
||||
return Chapter.builder().id(id).name(id).arcId(arcId).order(0).narrativeStakes("Un allié en danger").build();
|
||||
}
|
||||
|
||||
/** Scène « propre » : typée, avec un choix décrit (ne déclenche aucune règle seule). */
|
||||
private static Scene.SceneBuilder scene(String id, int order) {
|
||||
return Scene.builder().id(id).name(id).chapterId("chap").order(order)
|
||||
.type(SceneType.NPC).choicesConsequences("Convaincre ou menacer");
|
||||
}
|
||||
|
||||
private void tree(Arc arc, Chapter chapter, List<Scene> scenes) {
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(arc));
|
||||
when(chapterRepository.findByArcId(arc.getId())).thenReturn(List.of(chapter));
|
||||
when(sceneRepository.findByChapterId(chapter.getId())).thenReturn(scenes);
|
||||
}
|
||||
|
||||
private void tree(List<Scene> scenes) {
|
||||
tree(arc("arc", ArcType.HUB), chapter("chap", "arc"), scenes);
|
||||
}
|
||||
|
||||
private Set<String> ruleIds() {
|
||||
return service.review(CAMP).remarks().stream().map(WritingRemark::ruleId).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private WritingRemark remark(String ruleId) {
|
||||
return service.review(CAMP).remarks().stream().filter(r -> r.ruleId().equals(ruleId))
|
||||
.findFirst().orElseThrow(() -> new AssertionError("Règle absente : " + ruleId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyCampaign_hasNoRemark() {
|
||||
assertTrue(service.review(CAMP).remarks().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void wellWrittenChapter_hasNoRemark() {
|
||||
tree(List.of(scene("s1", 0).build(), scene("s2", 1).type(SceneType.LOCATION).build()));
|
||||
assertTrue(service.review(CAMP).remarks().isEmpty());
|
||||
}
|
||||
|
||||
// --- WRITE-001 : couloir ---
|
||||
|
||||
@Test
|
||||
void corridor_threeScenesWithoutChoiceNorBranch() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).choicesConsequences(null).build(),
|
||||
scene("s2", 1).choicesConsequences(null).type(SceneType.LOCATION).build(),
|
||||
scene("s3", 2).choicesConsequences(null).build()));
|
||||
|
||||
WritingRemark r = remark("WRITE-001-CORRIDOR");
|
||||
assertEquals(ReadinessEntityType.CHAPTER, r.entityType());
|
||||
assertEquals("3", r.params().get("count"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void corridor_notRaised_whenOneSceneOffersAChoice() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).choicesConsequences(null).build(),
|
||||
scene("s2", 1).type(SceneType.LOCATION).build(),
|
||||
scene("s3", 2).choicesConsequences(null).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-001-CORRIDOR"));
|
||||
}
|
||||
|
||||
// --- WRITE-002 : faux carrefour ---
|
||||
|
||||
@Test
|
||||
void fakeChoice_allBranchesLeadToSameScene() {
|
||||
Scene target = scene("s2", 1).name("La crypte").type(SceneType.LOCATION).build();
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(SceneBranch.of("A", "s2"), SceneBranch.of("B", "s2"))).build(),
|
||||
target));
|
||||
|
||||
WritingRemark r = remark("WRITE-002-FAKE-CHOICE");
|
||||
assertEquals("s1", r.entityId());
|
||||
assertEquals("La crypte", r.params().get("target"));
|
||||
assertEquals("2", r.params().get("count"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fakeChoice_notRaised_whenBranchesDiverge() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(SceneBranch.of("A", "s2"), SceneBranch.of("B", "s3"))).build(),
|
||||
scene("s2", 1).type(SceneType.LOCATION).build(),
|
||||
scene("s3", 2).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-002-FAKE-CHOICE"));
|
||||
}
|
||||
|
||||
// --- WRITE-003 : révélation à chemin unique ---
|
||||
|
||||
@Test
|
||||
void singleClue_revelationReachableByOnePath() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(SceneBranch.of("A", "rev"))).build(),
|
||||
scene("rev", 1).type(SceneType.REVELATION).build()));
|
||||
|
||||
assertEquals("1", remark("WRITE-003-SINGLE-CLUE").params().get("incoming"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleClue_notRaised_withTwoPaths_orInChapterWithoutLinks() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).branches(List.of(SceneBranch.of("A", "rev"))).build(),
|
||||
scene("s2", 1).type(SceneType.LOCATION).branches(List.of(SceneBranch.of("B", "rev"))).build(),
|
||||
scene("rev", 2).type(SceneType.REVELATION).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-003-SINGLE-CLUE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleClue_notRaised_inChapterWithoutAnyLink() {
|
||||
tree(List.of(scene("s1", 0).build(), scene("rev", 1).type(SceneType.REVELATION).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-003-SINGLE-CLUE"));
|
||||
}
|
||||
|
||||
// --- WRITE-004 : rythme monotone ---
|
||||
|
||||
@Test
|
||||
void monotonousPacing_threeFightsInARow() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).type(SceneType.ENCOUNTER).build(),
|
||||
scene("s2", 1).enemies("Deux gobelins").build(),
|
||||
scene("s3", 2).combatDifficulty("Difficile").build(),
|
||||
scene("s4", 3).type(SceneType.LOCATION).build()));
|
||||
|
||||
WritingRemark r = remark("WRITE-004-MONOTONOUS-PACING");
|
||||
assertEquals("COMBAT", r.params().get("kind"));
|
||||
assertEquals("3", r.params().get("count"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void monotonousPacing_notRaised_whenVaried_orUntyped() {
|
||||
tree(List.of(
|
||||
scene("s1", 0).type(SceneType.ENCOUNTER).build(),
|
||||
scene("s2", 1).type(SceneType.NPC).build(),
|
||||
scene("s3", 2).type(SceneType.ENCOUNTER).build(),
|
||||
scene("s4", 3).type(SceneType.GENERIC).build(),
|
||||
scene("s5", 4).type(SceneType.GENERIC).build(),
|
||||
scene("s6", 5).type(SceneType.GENERIC).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-004-MONOTONOUS-PACING"));
|
||||
}
|
||||
|
||||
// --- WRITE-005 : sans enjeu ---
|
||||
|
||||
@Test
|
||||
void noStakes_onChapterAndArc() {
|
||||
Arc a = Arc.builder().id("arc").name("Arc").campaignId(CAMP).type(ArcType.LINEAR).order(0).build();
|
||||
Chapter c = Chapter.builder().id("chap").name("Chap").arcId("arc").order(0).build();
|
||||
tree(a, c, List.of(scene("s1", 0).branches(List.of(SceneBranch.of("A", "s1"))).build()));
|
||||
|
||||
List<WritingRemark> remarks = service.review(CAMP).remarks().stream()
|
||||
.filter(r -> r.ruleId().equals("WRITE-005-NO-STAKES")).toList();
|
||||
assertEquals(Set.of(ReadinessEntityType.ARC, ReadinessEntityType.CHAPTER),
|
||||
remarks.stream().map(WritingRemark::entityType).collect(Collectors.toSet()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void noStakes_notRaised_onEmptyArc_norOnSystemArc() {
|
||||
Arc empty = Arc.builder().id("empty").name("Vide").campaignId(CAMP).type(ArcType.LINEAR).order(0).build();
|
||||
Arc system = Arc.builder().id("sys").name("Quêtes libres").campaignId(CAMP).type(ArcType.SYSTEM).order(9999).build();
|
||||
Chapter container = Chapter.builder().id("box").name("Q").arcId("sys").order(0).build();
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(empty, system));
|
||||
when(chapterRepository.findByArcId("empty")).thenReturn(List.of());
|
||||
when(chapterRepository.findByArcId("sys")).thenReturn(List.of(container));
|
||||
when(sceneRepository.findByChapterId("box")).thenReturn(List.of(scene("s1", 0).build()));
|
||||
|
||||
assertFalse(ruleIds().contains("WRITE-005-NO-STAKES"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void noStakes_raisedOnHubArcCarriedByQuests() {
|
||||
Arc hub = Arc.builder().id("hub").name("Hub").campaignId(CAMP).type(ArcType.HUB).order(0).build();
|
||||
when(arcRepository.findByCampaignId(CAMP)).thenReturn(List.of(hub));
|
||||
when(questRepository.findByCampaignId(CAMP))
|
||||
.thenReturn(List.of(Quest.builder().id("q").campaignId(CAMP).arcId("hub").build()));
|
||||
|
||||
assertEquals(ReadinessEntityType.ARC, remark("WRITE-005-NO-STAKES").entityType());
|
||||
}
|
||||
|
||||
// --- WRITE-006 / WRITE-007 : narration ---
|
||||
|
||||
@Test
|
||||
void longNarration_overThreshold() {
|
||||
String text = "a".repeat(WritingReviewService.LONG_NARRATION_CHARS + 1);
|
||||
tree(List.of(scene("s1", 0).playerNarration(text).build()));
|
||||
|
||||
assertEquals(String.valueOf(text.length()), remark("WRITE-006-LONG-NARRATION").params().get("chars"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void narrationDecides_capturesThePhrase_inFrenchAndEnglish() {
|
||||
tree(List.of(scene("s1", 0).playerNarration("La porte grince. Vous avez peur et reculez.").build()));
|
||||
assertEquals("Vous avez peur", remark("WRITE-007-NARRATION-DECIDES").params().get("phrase"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void narrationDecides_english() {
|
||||
tree(List.of(scene("s1", 0).playerNarration("The door creaks open. You enter the hall.").build()));
|
||||
assertEquals("You enter", remark("WRITE-007-NARRATION-DECIDES").params().get("phrase"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void narration_notRaised_whenDescriptiveAndShort() {
|
||||
tree(List.of(scene("s1", 0)
|
||||
.playerNarration("La porte grince. Une odeur de cire flotte dans l'air. Que faites-vous ?").build()));
|
||||
Set<String> ids = ruleIds();
|
||||
assertFalse(ids.contains("WRITE-006-LONG-NARRATION"));
|
||||
assertFalse(ids.contains("WRITE-007-NARRATION-DECIDES"));
|
||||
}
|
||||
|
||||
// --- WRITE-008 : combat sans but ---
|
||||
|
||||
@Test
|
||||
void combatWithoutPurpose() {
|
||||
tree(List.of(scene("s1", 0).type(SceneType.ENCOUNTER).choicesConsequences(null).build()));
|
||||
assertEquals("s1", remark("WRITE-008-COMBAT-NO-PURPOSE").entityId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void combatWithoutPurpose_notRaised_whenGmNotesExplainMotives() {
|
||||
tree(List.of(scene("s1", 0).type(SceneType.ENCOUNTER).choicesConsequences(null)
|
||||
.gmSecretNotes("Ils veulent couler la barque").build()));
|
||||
assertFalse(ruleIds().contains("WRITE-008-COMBAT-NO-PURPOSE"));
|
||||
}
|
||||
|
||||
// --- WRITE-009 : fin unique ---
|
||||
|
||||
@Test
|
||||
void singleEnding_onLastSceneOfLinearArc() {
|
||||
tree(arc("arc", ArcType.LINEAR), chapter("chap", "arc"), List.of(
|
||||
scene("s1", 0).build(),
|
||||
scene("final", 1).type(SceneType.LOCATION).choicesConsequences(null).build()));
|
||||
|
||||
WritingRemark r = remark("WRITE-009-SINGLE-ENDING");
|
||||
assertEquals("final", r.entityId());
|
||||
assertEquals("arc", r.params().get("arc"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleEnding_notRaised_onHubArc_orWhenFinaleHasChoices() {
|
||||
tree(arc("arc", ArcType.HUB), chapter("chap", "arc"),
|
||||
List.of(scene("final", 0).choicesConsequences(null).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-009-SINGLE-ENDING"));
|
||||
}
|
||||
|
||||
// --- WRITE-010 : scènes non typées ---
|
||||
|
||||
@Test
|
||||
void untypedScenes_whenMostScenesAreGeneric() {
|
||||
List<Scene> scenes = new ArrayList<>(IntStream.range(0, 5)
|
||||
.mapToObj(i -> scene("s" + i, i).type(SceneType.GENERIC).build()).toList());
|
||||
tree(scenes);
|
||||
when(campaignRepository.findById(CAMP))
|
||||
.thenReturn(Optional.of(Campaign.builder().id(CAMP).name("Ma campagne").build()));
|
||||
|
||||
WritingRemark r = remark("WRITE-010-UNTYPED-SCENES");
|
||||
assertEquals(ReadinessEntityType.CAMPAIGN, r.entityType());
|
||||
assertEquals("100", r.params().get("percent"));
|
||||
// Remarque de campagne en tête de liste.
|
||||
assertEquals("WRITE-010-UNTYPED-SCENES", service.review(CAMP).remarks().get(0).ruleId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void untypedScenes_notRaised_belowMinimumSceneCount() {
|
||||
tree(List.of(scene("s1", 0).type(SceneType.GENERIC).build()));
|
||||
assertFalse(ruleIds().contains("WRITE-010-UNTYPED-SCENES"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user