La version 3 est celle de main (identifiant de match) ; l'abandon prend la version 4, avec la migration des versions 1, 2 et 3 testée. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
421 lines
18 KiB
TypeScript
421 lines
18 KiB
TypeScript
// Tests de l'analyse d'un match entier (étape 1l) : l'identifiant de match
|
||
// (version 3 des événements) et sa migration, les tables du match dans
|
||
// l'analyse de partie, le rattachement des parties d'un match (avec et sans
|
||
// identifiant), le bilan du match sur un vrai match joué par le moteur (la
|
||
// remontée de 0–4 à 5–4), les phrases du maître et le prompt « Bilan de mon
|
||
// match ».
|
||
//
|
||
// Copyright (C) 2026 les auteurs d'Ustagammon.
|
||
// Licence : GPLv3 ou ultérieure (voir LICENSE).
|
||
|
||
import assert from "node:assert/strict";
|
||
import { readFileSync } from "node:fs";
|
||
import { test } from "node:test";
|
||
import {
|
||
missingAnalyses,
|
||
readyForMatchSummary,
|
||
readyForSummary,
|
||
} from "../src/domain/analysis/game-analysis.js";
|
||
import {
|
||
cubeKindsWithoutError,
|
||
formatMatchLoss,
|
||
groupMatches,
|
||
LINK_DELAY_MS,
|
||
type MatchGame,
|
||
matchOfGame,
|
||
summarizeMatch,
|
||
} from "../src/domain/analysis/match-analysis.js";
|
||
import {
|
||
decisiveSentence,
|
||
LINE_LIMIT,
|
||
matchCubeAgreements,
|
||
matchCubeSentence,
|
||
PHRASE_KEYS,
|
||
} from "../src/domain/analysis/phrases.js";
|
||
import type { Engine } from "../src/domain/game/engine.js";
|
||
import {
|
||
currentLine,
|
||
EVENT_VERSION,
|
||
type GameJournal,
|
||
migrateJournal,
|
||
} from "../src/domain/game/events.js";
|
||
import { Game } from "../src/domain/game/game.js";
|
||
import { firstGameOf, nextGameOf, withMatchId } from "../src/domain/game/match.js";
|
||
import { replay } from "../src/domain/game/state.js";
|
||
import { CUBE_ERROR_WORDS, matchPosition, matchPrompt } from "../src/domain/prompts/prompts.js";
|
||
import { PROMPT_FILES, parsePromptTemplate } from "../src/domain/prompts/templates.js";
|
||
import { createGameSession } from "../src/storage/game-session.js";
|
||
import { memoryStorage, openGameLibrary } from "../src/storage/open-library.js";
|
||
import { loadPhrases } from "./support/advice.js";
|
||
import { COMEBACK_MATCH_ID, playComebackMatch } from "./support/match.js";
|
||
import { loadNodeEngine } from "./support/node-engine.js";
|
||
|
||
const root = new URL("../../../", import.meta.url);
|
||
const phrases = loadPhrases();
|
||
const engine: Engine = await loadNodeEngine();
|
||
const comeback = await playComebackMatch(engine);
|
||
|
||
/** Un nombre de gnubg de bureau (tests/reference/analysis/). */
|
||
function reference(id: string): { at_score: number; equities: { equity: number; loss: number }[] } {
|
||
return JSON.parse(readFileSync(new URL(`tests/reference/analysis/${id}.json`, root), "utf8"));
|
||
}
|
||
|
||
// --------------------------------------------- Identifiant et migration
|
||
|
||
test("un journal de la version 2 passe à la version courante sans identifiant de match inventé", () => {
|
||
const v2 = JSON.parse(JSON.stringify(comeback[1]?.journal)) as {
|
||
events: { version: number; type: string; match?: { id?: string } }[];
|
||
};
|
||
for (const event of v2.events) {
|
||
event.version = 2;
|
||
if (event.type === "GameStarted") {
|
||
delete event.match?.id;
|
||
}
|
||
}
|
||
const migrated = migrateJournal(v2 as unknown as GameJournal);
|
||
assert.ok(migrated.events.every((event) => event.version === EVENT_VERSION));
|
||
assert.equal(EVENT_VERSION, 4);
|
||
const start = migrated.events[0];
|
||
assert.ok(start?.type === "GameStarted");
|
||
assert.deepEqual(start.match, {
|
||
length: 5,
|
||
score: { player: 0, computer: 2 },
|
||
crawford: false,
|
||
});
|
||
// Le reste de la partie est le même.
|
||
assert.deepEqual(
|
||
replay(currentLine(migrated)).matchAfter,
|
||
replay(currentLine(comeback[1]?.journal as GameJournal)).matchAfter,
|
||
);
|
||
// Le journal analysé reste analysé : l'analyse ne dépend pas du numéro.
|
||
assert.deepEqual(migrated.review, comeback[1]?.journal.review);
|
||
});
|
||
|
||
test("les tables du match d'une analyse enregistrée sont relues, ou oubliées si mal formées", () => {
|
||
const journal = comeback[3]?.journal as GameJournal;
|
||
const review = journal.review;
|
||
assert.ok(review?.matchChances !== undefined && review.matchLosses !== undefined);
|
||
// Bien formées : rien ne change.
|
||
assert.equal(migrateJournal(journal), journal);
|
||
// Une entrée hors du journal, une valeur qui n'est pas un nombre : oubliées.
|
||
const damaged = {
|
||
...journal,
|
||
review: {
|
||
...review,
|
||
matchChances: { ...review.matchChances, "99": 0.5, "1": "beaucoup" },
|
||
matchLosses: "rien",
|
||
},
|
||
} as unknown as GameJournal;
|
||
const read = migrateJournal(damaged);
|
||
const { "1": _, ...others } = review.matchChances;
|
||
assert.deepEqual(read.review?.matchChances, others);
|
||
assert.equal(read.review?.matchLosses, undefined);
|
||
// Une analyse d'avant l'étape 1l (sans ces tables) les fait calculer, sans
|
||
// retarder le bilan de la partie.
|
||
const { matchChances: _c, matchLosses: _l, ...before } = review;
|
||
const old = { ...journal, review: before };
|
||
assert.equal(migrateJournal(old), old);
|
||
const tasks = missingAnalyses(old);
|
||
assert.ok(tasks.some((t) => t.kind === "matchChance"));
|
||
assert.ok(tasks.some((t) => t.kind === "matchLoss"));
|
||
assert.ok(readyForSummary(old));
|
||
assert.ok(!readyForMatchSummary(old));
|
||
});
|
||
|
||
test("la première partie d'un match lui donne son identifiant ; les suivantes le gardent", async () => {
|
||
const match = firstGameOf(5);
|
||
assert.equal(match.id, undefined);
|
||
assert.equal(withMatchId(match, "m1").id, "m1");
|
||
assert.equal(withMatchId(firstGameOf(5, "m0"), "m1").id, "m0");
|
||
const next = nextGameOf(firstGameOf(5, "m0"), {
|
||
score: { player: 0, computer: 2 },
|
||
over: false,
|
||
crawford: false,
|
||
});
|
||
assert.equal(next?.id, "m0");
|
||
|
||
const { library } = await openGameLibrary({ localStorage: memoryStorage() });
|
||
const session = createGameSession(library, {
|
||
start: (newGame) => Game.start(engine, newGame),
|
||
resume: (journal) => Game.resume(engine, journal),
|
||
});
|
||
const first = session.newGame({ match: firstGameOf(5) });
|
||
const id = session.shownId;
|
||
assert.equal(first.state.match?.id, id);
|
||
// Une partie libre reste sans match.
|
||
assert.equal(session.newGame({}).state.match, null);
|
||
// La partie suivante d'un match garde son identifiant.
|
||
const second = session.newGame({
|
||
match: { ...firstGameOf(5, id ?? ""), score: { player: 1, computer: 0 } },
|
||
});
|
||
assert.equal(second.state.match?.id, id);
|
||
});
|
||
|
||
// ------------------------------------------- Les parties d'un match
|
||
|
||
test("les parties d'un match sont réunies par leur identifiant", () => {
|
||
const { matches, loose } = groupMatches([...comeback].reverse());
|
||
assert.equal(loose.length, 0);
|
||
assert.equal(matches.length, 1);
|
||
const match = matches[0];
|
||
assert.ok(match !== undefined);
|
||
assert.equal(match.id, COMEBACK_MATCH_ID);
|
||
assert.equal(match.inferred, false);
|
||
assert.deepEqual(
|
||
match.games.map((g) => g.id),
|
||
comeback.map((g) => g.id),
|
||
);
|
||
assert.deepEqual(match.score, { player: 5, computer: 4 });
|
||
assert.equal(match.over, true);
|
||
assert.equal(match.winner, "player");
|
||
assert.equal(match.waiting, false);
|
||
assert.deepEqual(matchOfGame(matches, "partie-3")?.number, 3);
|
||
assert.equal(matchOfGame(matches, "ailleurs"), null);
|
||
// Un match en cours : la dernière partie finie, la suivante à venir.
|
||
const ongoing = groupMatches(comeback.slice(0, 2)).matches[0];
|
||
assert.deepEqual(ongoing?.score, { player: 0, computer: 4 });
|
||
assert.equal(ongoing?.over, false);
|
||
assert.equal(ongoing?.waiting, true);
|
||
});
|
||
|
||
test("les matchs joués avant l'identifiant sont rattachés d'après les scores et les dates", async () => {
|
||
const legacy = await playComebackMatch(engine, { matchId: null, analyse: false });
|
||
const { matches, loose } = groupMatches(legacy);
|
||
assert.equal(loose.length, 0);
|
||
assert.equal(matches.length, 1);
|
||
assert.equal(matches[0]?.inferred, true);
|
||
assert.equal(matches[0]?.id, "partie-1");
|
||
assert.deepEqual(
|
||
matches[0]?.games.map((g) => g.id),
|
||
legacy.map((g) => g.id),
|
||
);
|
||
|
||
// Trop de temps entre deux parties : on ne devine pas.
|
||
const late = legacy.map(
|
||
(g, i): MatchGame =>
|
||
i < 2
|
||
? g
|
||
: {
|
||
...g,
|
||
startedAt: g.startedAt + LINK_DELAY_MS,
|
||
updatedAt: g.updatedAt + LINK_DELAY_MS,
|
||
},
|
||
);
|
||
const split = groupMatches(late);
|
||
assert.deepEqual(
|
||
split.matches.map((m) => m.games.length),
|
||
[2],
|
||
);
|
||
assert.deepEqual(
|
||
split.loose.map((g) => g.id),
|
||
["partie-3", "partie-4", "partie-5"],
|
||
);
|
||
|
||
// Deux parties pourraient suivre la même : la chaîne s'arrête là.
|
||
const twin = {
|
||
...(legacy[2] as MatchGame),
|
||
id: "jumelle",
|
||
startedAt: (legacy[2]?.startedAt ?? 0) + 1,
|
||
};
|
||
const ambiguous = groupMatches([...legacy, twin]);
|
||
assert.deepEqual(
|
||
ambiguous.matches.map((m) => m.games.map((g) => g.id)),
|
||
[["partie-1", "partie-2"]],
|
||
);
|
||
assert.equal(ambiguous.loose.length, 4);
|
||
});
|
||
|
||
// ------------------------------------------------------- Le bilan
|
||
|
||
test("le bilan du match : la remontée de 0–4 à 5–4", () => {
|
||
const match = groupMatches(comeback).matches[0];
|
||
assert.ok(match !== undefined);
|
||
const summary = summarizeMatch(match);
|
||
assert.equal(summary.ready, true);
|
||
assert.deepEqual(summary.comeback, { player: 0, computer: 4 });
|
||
assert.deepEqual(
|
||
summary.rows.map((r) => [r.scoreBefore, r.scoreAfter, r.crawford, r.result?.winner]),
|
||
[
|
||
[{ player: 0, computer: 0 }, { player: 0, computer: 2 }, false, "computer"],
|
||
[{ player: 0, computer: 2 }, { player: 0, computer: 4 }, false, "computer"],
|
||
[{ player: 0, computer: 4 }, { player: 2, computer: 4 }, true, "player"],
|
||
[{ player: 2, computer: 4 }, { player: 3, computer: 4 }, false, "player"],
|
||
[{ player: 3, computer: 4 }, { player: 5, computer: 4 }, false, "player"],
|
||
],
|
||
);
|
||
// Le double de la partie 4 : le moteur n'aurait pas doublé.
|
||
assert.equal(summary.cubeErrors.length, 1);
|
||
const error = summary.cubeErrors[0];
|
||
assert.equal(error?.kind, "wrongDouble");
|
||
assert.equal(error?.game, 4);
|
||
assert.equal(error?.turn, 1);
|
||
assert.deepEqual(error?.score, { player: 2, computer: 4 });
|
||
assert.ok(error?.loss !== null && (error?.loss ?? 0) < 0);
|
||
assert.deepEqual(cubeKindsWithoutError(summary), ["missedDouble", "wrongTake", "wrongPass"]);
|
||
assert.equal(summary.toReview?.advice.eventId, error?.advice.eventId);
|
||
assert.equal(summary.cube.decisions, 1);
|
||
assert.equal(summary.chequer.decisions, 0);
|
||
// Le moment décisif : le 5-5 de la dernière partie, qui gagne le match.
|
||
assert.equal(summary.decisive?.game, 5);
|
||
assert.deepEqual(summary.decisive?.roll, [5, 5]);
|
||
assert.equal(summary.decisive?.to, 1);
|
||
});
|
||
|
||
test("la courbe du match est continue d'une partie à l'autre, en chances de gagner le match", () => {
|
||
const match = groupMatches(comeback).matches[0];
|
||
assert.ok(match !== undefined);
|
||
const curve = summarizeMatch(match).curve;
|
||
assert.ok(curve.every((p) => p.chance !== null));
|
||
// Le début du match : 50 %, la table de gnubg à 0–0.
|
||
assert.equal(curve[0]?.turn, null);
|
||
assert.equal(curve[0]?.chance, reference("chances-5-0-0").at_score);
|
||
// Après la partie 1 (0–2), la table de gnubg de bureau à ce score.
|
||
assert.ok(Math.abs((curve[1]?.chance ?? 0) - reference("chances-5-0-2").at_score) < 1e-6);
|
||
// La fin d'une partie est le début de la suivante : les chances de
|
||
// GameEnded d'une partie sont celles de GameStarted de la suivante.
|
||
for (let i = 1; i < comeback.length; i++) {
|
||
const before = comeback[i - 1]?.journal as GameJournal;
|
||
const after = comeback[i]?.journal as GameJournal;
|
||
const end = currentLine(before).at(-1);
|
||
const start = currentLine(after)[0];
|
||
assert.ok(end?.type === "GameEnded" && start?.type === "GameStarted");
|
||
assert.equal(after.review?.matchChances?.[start.id], before.review?.matchChances?.[end.id]);
|
||
}
|
||
// La fin du match gagné : 100 %.
|
||
assert.equal(curve.at(-1)?.chance, 1);
|
||
assert.ok(curve.at(-1)?.ends);
|
||
});
|
||
|
||
test("la perte du double de la partie 4 vient du moteur, comme gnubg de bureau", async () => {
|
||
const match = groupMatches(comeback).matches[0];
|
||
assert.ok(match !== undefined);
|
||
const error = summarizeMatch(match).cubeErrors[0];
|
||
assert.ok(error !== undefined);
|
||
// Score 2–4 après Crawford, videau au centre à 1, le joueur au trait.
|
||
const cube = {
|
||
value: 1,
|
||
owner: "centered" as const,
|
||
match: { length: 5, score: { onRoll: 2, opponent: 4 }, crawford: false },
|
||
};
|
||
const converted = await engine.matchChances(cube, error.advice.equityLoss);
|
||
assert.equal(error.loss, converted.ofLoss);
|
||
// La même conversion, comparée à gnubg de bureau (2–4 videau 2 chez
|
||
// l'adversaire : équité −0,25 → perte −0,0625).
|
||
const ref = reference("chances-5-2-4-cube-2").equities[0];
|
||
const owned = await engine.matchChances(
|
||
{
|
||
value: 2,
|
||
owner: "opponent",
|
||
match: { length: 5, score: { onRoll: 2, opponent: 4 }, crawford: false },
|
||
},
|
||
ref?.equity ?? 0,
|
||
);
|
||
assert.ok(Math.abs(owned.ofLoss - (ref?.loss ?? 1)) < 1e-6);
|
||
});
|
||
|
||
// ----------------------------------------------- Phrases et prompt
|
||
|
||
test("les phrases du bilan du match", () => {
|
||
for (const key of PHRASE_KEYS.filter((k) => k.startsWith("match."))) {
|
||
assert.ok((phrases.get(key)?.length ?? 0) > 0, key);
|
||
}
|
||
assert.equal(
|
||
matchCubeSentence(phrases, 8, 2),
|
||
"8 décisions de videau ; pour 2 d'entre elles, j'aurais fait autrement.",
|
||
);
|
||
assert.equal(
|
||
matchCubeSentence(phrases, 3, 0),
|
||
"3 décisions de videau, toutes comme je les aurais prises.",
|
||
);
|
||
assert.equal(
|
||
matchCubeSentence(phrases, 1, 1),
|
||
"Une seule décision de videau, et j'aurais fait autrement.",
|
||
);
|
||
assert.equal(
|
||
matchCubeSentence(phrases, 1, 0),
|
||
"Une seule décision de videau, comme je l'aurais prise.",
|
||
);
|
||
assert.equal(
|
||
matchCubeSentence(phrases, 0, 0),
|
||
"Aucune décision de videau à relever sur ce match.",
|
||
);
|
||
assert.deepEqual(matchCubeAgreements(phrases, ["missedDouble", "wrongTake", "wrongPass"]), [
|
||
"Prises et refus : aucune différence avec mes choix.",
|
||
]);
|
||
const moment = {
|
||
game: 3,
|
||
gameId: "x",
|
||
turn: 6,
|
||
side: "player",
|
||
roll: [5, 5],
|
||
from: 0.24,
|
||
to: 0.46,
|
||
} as const;
|
||
assert.equal(
|
||
decisiveSentence(phrases, moment),
|
||
"Avec 5-5, vos chances de gagner le match passent de 24\u00a0% à 46\u00a0%. C'est le plus grand écart du match.",
|
||
);
|
||
assert.match(
|
||
decisiveSentence(phrases, { ...moment, side: "computer", roll: [6, 6] }),
|
||
/^Avec le 6-6 de l'ordinateur/,
|
||
);
|
||
assert.match(decisiveSentence(phrases, { ...moment, roll: null }), /^Sur ce double passé, /);
|
||
for (const text of [
|
||
decisiveSentence(phrases, { ...moment, side: "computer", roll: [6, 6] }),
|
||
matchCubeSentence(phrases, 12, 11),
|
||
]) {
|
||
assert.ok(text.length < LINE_LIMIT, text);
|
||
}
|
||
assert.equal(formatMatchLoss(-0.0119700283), "−1,2\u00a0%");
|
||
assert.equal(formatMatchLoss(0), "0,0\u00a0%");
|
||
});
|
||
|
||
test("le prompt « Bilan de mon match » cite le videau en chances de gagner le match", async () => {
|
||
const match = groupMatches(comeback).matches[0];
|
||
assert.ok(match !== undefined);
|
||
const summary = summarizeMatch(match);
|
||
const read = (kind: keyof typeof PROMPT_FILES) =>
|
||
parsePromptTemplate(
|
||
readFileSync(new URL(`docs/prompts/${PROMPT_FILES[kind]}`, root), "utf8"),
|
||
);
|
||
const templates = {
|
||
move: read("move"),
|
||
cube: read("cube"),
|
||
summary: read("summary"),
|
||
concept: read("concept"),
|
||
exercises: read("exercises"),
|
||
match: read("match"),
|
||
};
|
||
const position = await matchPosition(engine, summary);
|
||
const prompt = matchPrompt(templates, phrases, { summary, position });
|
||
assert.ok(!/[{}]/.test(prompt), prompt);
|
||
assert.match(prompt, /j'ai gagné le match 5 à 4 en cinq parties, après avoir été mené 0 à 4/);
|
||
assert.match(prompt, /- Partie 3 \(0–4, partie Crawford\) : je gagne un gammon, 2 points\./);
|
||
assert.match(prompt, /Une seule décision de videau, et j'aurais fait autrement\./);
|
||
assert.ok(prompt.includes(`(${CUBE_ERROR_WORDS.wrongDouble.toLowerCase()})`), prompt);
|
||
assert.match(prompt, /perte de 1,2\u00a0% de chances de gagner le match/);
|
||
// Jamais d'équité pour une perte en match.
|
||
assert.ok(!/écart [−+]?\d,\d{3}/.test(prompt), prompt);
|
||
assert.match(prompt, /partie 4, coup 1\) : la position avant ma décision/);
|
||
assert.equal(position.positionId, "wN1tAwADAAAAAA");
|
||
});
|
||
|
||
test("une décision de videau dont la perte s'écrirait 0,0 % n'est pas listée", () => {
|
||
const fourth = comeback[3] as MatchGame;
|
||
const review = fourth.journal.review;
|
||
assert.ok(review?.matchLosses !== undefined);
|
||
const tiny = Object.fromEntries(Object.keys(review.matchLosses).map((id) => [id, -0.0004]));
|
||
const games = comeback.map((g, i) =>
|
||
i === 3 ? { ...g, journal: { ...g.journal, review: { ...review, matchLosses: tiny } } } : g,
|
||
);
|
||
const match = groupMatches(games).matches[0];
|
||
assert.ok(match !== undefined);
|
||
const summary = summarizeMatch(match);
|
||
assert.equal(summary.cubeErrors.length, 0);
|
||
assert.equal(summary.cubeDecisions, 1);
|
||
assert.equal(
|
||
matchCubeSentence(phrases, summary.cubeDecisions, 0),
|
||
"Une seule décision de videau, comme je l'aurais prise.",
|
||
);
|
||
});
|