Files
game_voice_recorder/app/test/culprit.test.ts
EJClaw dc67f2105b 범인찾기 C2: 사이트 서버 Claude 호출 · 근거 확인 · 예산 장부
- POST /api/culprit/matches/:id/analyze: 등록된 앱 유저 이상(다시 분석은 관리자), 월 $100 · 하루 20회 · 중복 잠금
- Claude Opus 5.5 (생각 high, 구조화 출력, 출력 32k 상한, 거절 시 서버 측 fallback), 지시문 + 게임별 지식 묶음(자동 갱신 칸은 공식 데이터로 하루 한 번)
- 결과 확인: 10명 · 0.5 단위 점수 · 태그 · 팀마다 범인 1명(팀 최저점) · 없는 근거 번호 제거, 범인 근거가 안 맞으면 한 번 다시
- 비용 장부(culprit-ledger.json)는 토큰 · 비용만, 진행 단계는 실시간 알림(culprit.progress)
- 지시문 v1.1: 범인 = 가장 못함 + 가장 발목 + 결과의 원인 종합 판단, 자료 약어 설명 추가
- 배포: Dockerfile 에 prompt/ 복사, ANTHROPIC_API_KEY 넣는 스크립트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 14:27:59 +09:00

174 lines
10 KiB
TypeScript

import { test } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import type { CulpritInput, CulpritMatchInfo, CulpritMatchItem } from '@gvr/shared';
import { SettingsStore, DEFAULT_TTS_TEXT } from '../src/core/settings.ts';
import { makeDemoLol } from './fixtures/demo-matches.ts';
import { culpritApi, MIN, seedValorant, setup } from './fixtures/culprit-seed.ts';
test('범인찾기: 발로란트 추가 지표 저장 (피해량 · 첫킬 · 설치 · 역할 · 라운드별 장비)', () => {
const ctx = setup();
const { id } = seedValorant(ctx);
const det = JSON.parse(ctx.store.getMatch(id)!.detail!);
const jett = det.players.find((p: any) => p.puuid === 'p-sh');
assert.equal(jett.stats.role, '타격대');
assert.ok(jett.stats.damage > 0, '피해량');
assert.equal(typeof jett.stats.firstKills, 'number');
assert.ok(det.players.reduce((n: number, p: any) => n + p.stats.firstKills, 0) > 0, '첫킬 합 > 0');
const plants = det.players.reduce((n: number, p: any) => n + p.stats.plants, 0);
assert.ok(plants > 0, '설치 기록');
const r = det.roundsDetail[1];
assert.equal(typeof r.allyAttack, 'boolean');
assert.ok(r.players['p-sh'] !== undefined, '라운드별 선수 지표');
assert.ok(Object.values<any>(r.economy).every((e) => typeof e.loadout === 'number'), '라운드 장비 값');
// 전반(1~12)과 후반(13~)은 공수가 바뀐다
assert.notEqual(det.roundsDetail[0].allyAttack, det.roundsDetail[12].allyAttack);
});
test('범인찾기: 분석 가능 판정과 AI 자료', () => {
const ctx = setup();
const { id } = seedValorant(ctx);
const m = ctx.store.getMatch(id)!;
assert.deepEqual(ctx.culprit.eligibility(m), { state: 'ready', reasons: [] });
const input = ctx.culprit.buildInput(m);
const lines = input.text.split('\n');
assert.match(lines[0], /^# 경기 발로란트 .* 13:9 \(우리 팀 승리\) · 22라운드/);
// 우리 팀이 P1~P5, 승한은 음성O, 디스코드 계정이 없는 상대는 음성X
const p1 = lines.find((l) => l.startsWith('P1 '))!;
assert.match(p1, /^P1 승한 우리 제트\(타격대\) \d+\/\d+\/\d+ ACS\d+ ADR\d+ 첫킬\d+\/첫데스\d+ HS\d+% 설치\d+\/해체\d+ .*음성O$/);
assert.match(lines.find((l) => l.startsWith('P6 '))!, /상대 .*음성X$/);
assert.equal(input.players.find((p) => p.id === 'P2')!.voice, true, '민수는 대화가 있다');
assert.equal(input.players.find((p) => p.id === 'P3')!.voice, false);
// 게임 계정이 없는 화자는 디스코드 이름으로
assert.ok(lines.some((l) => l.includes('도윤(게임 계정 모름)')));
// 근거 번호: 대화 · 이벤트 · 라운드 · 스탯
const u1 = lines.find((l) => l.startsWith('[u1] '))!;
assert.match(u1, /^\[u1\] R3 0:05 P1: 현우야 같이 가 기다려 둘 있어$/);
assert.equal(input.refs.u1.kind, 'utterance');
assert.ok(lines.some((l) => /^\[e\d+\] R\d+ \d+:\d+ 킬 P\d+ → P\d+/.test(l)), '킬 줄');
assert.ok(lines.some((l) => /^\[r1\] R1 우리 (공격|수비) 라운드 끝 · (승리|패배)\(.+\) \d+:\d+ · 평균 장비 우리 [\d,]+ \/ 상대 [\d,]+ · 선수 장비\/피해: P1 /.test(l)), '라운드 줄');
assert.deepEqual(input.refs['s:P4'], { kind: 'stat', pid: 'P4' });
assert.equal(input.stats.utterances, 4);
assert.equal(input.stats.basic, false);
// 줄은 시간 순서
const u2Index = lines.findIndex((l) => l.startsWith('[u2] '));
assert.ok(lines.findIndex((l) => l.startsWith('[r2] ')) < lines.findIndex((l) => l.startsWith('[u1] ')));
assert.ok(u2Index > lines.findIndex((l) => l.startsWith('[u1] ')));
});
test('범인찾기: 녹음이 늦게 시작 · 음성 변환 중 · 녹음 제외', () => {
const late = setup();
const a = seedValorant(late, { sessionStartOffsetMs: 17 * MIN });
const e = late.culprit.eligibility(late.store.getMatch(a.id)!);
assert.equal(e.state, 'blocked');
assert.deepEqual(e.reasons, ['녹음이 경기 시작 12분 뒤에 시작됐습니다']);
const pend = setup();
const b = seedValorant(pend, { pending: true });
assert.deepEqual(pend.culprit.eligibility(pend.store.getMatch(b.id)!), { state: 'pending', reasons: ['음성 변환 중 (1문장 남음)'] });
// 녹음 제외한 사람의 대화는 보내지 않는다
const ex = setup();
const c = seedValorant(ex);
ex.store.setExcluded('u2', true);
const input = ex.culprit.buildInput(ex.store.getMatch(c.id)!);
assert.ok(!input.text.includes('내가 뚫을게'));
assert.equal(input.players.find((p) => p.id === 'P2')!.voice, false);
// 경기 결과를 못 받은 경기
const nd = setup();
nd.store.upsertMatch({ id: 'val-x', game: 'valorant', started_at: Date.now() - 50 * MIN, ended_at: Date.now() - 10 * MIN, status: 'complete', detail: JSON.stringify({ live: true }) });
nd.store.startSession('s', 'g', 'c', null, Date.now() - 60 * MIN);
assert.deepEqual(nd.culprit.eligibility(nd.store.getMatch('val-x')!), { state: 'blocked', reasons: ['경기 결과를 받지 못했습니다'] });
});
test('범인찾기: 롤 포지션 · 시야 · 10/15분 지표와 골드 차', () => {
const ctx = setup();
const LS = Date.now() - 80 * MIN;
const lol = makeDemoLol();
ctx.store.setMeta('riot_self_puuid', 'l-sh');
ctx.store.startSession('s', 'g', 'c', null, LS - MIN);
ctx.store.endSession('s', LS + lol.durationMs + MIN);
ctx.games.matchStarted({ id: 'lol-1', game: 'lol', startedAt: LS, map: 'Map11', mode: 'CLASSIC', queue: '420', detail: { live: true } });
ctx.games.matchEnded('lol-1', LS + lol.durationMs);
(ctx.games.adapters[1] as any).applyHistory('lol-1', lol.game, lol.timeline, LS);
const m = ctx.store.getMatch('lol-1')!;
const det = JSON.parse(m.detail!);
assert.deepEqual(
det.players.map((p: any) => p.stats.role),
['미드', '정글', '탑', '원딜', '서폿', '미드', '정글', '탑', '원딜', '서폿'],
);
assert.deepEqual(det.players[1].stats.at10, { cs: 60, gold: det.players[1].stats.at10.gold, xp: 4220 });
assert.equal(ctx.culprit.eligibility(m).state, 'ready');
const input = ctx.culprit.buildInput(m);
assert.match(input.text, /\nP5 Duck 우리 [^ ]+\(서폿\) \d+\/\d+\/\d+ CS\d+ 골드\d+ 딜17500 받은\d+ 시야62 와드48\/4\/9 10분\d+·\d+ 15분\d+·\d+ 음성X\n/);
assert.match(input.text, /\n# 골드 차\(우리-상대\): 5분 [+-][\d,]+ · 10분/);
assert.match(input.text, /\n\[e\d+\] \d+:\d+ 킬 P\d+ → P\d+/);
assert.match(input.text, /\n\[e\d+\] \d+:\d+ 내셔 남작 처치 우리 팀 · P2\n/);
});
test('범인찾기 API: 목록 · 상세 · 내부 전용 경로', async () => {
const ctx = setup();
const { id } = seedValorant(ctx);
const api = await culpritApi(ctx);
const list = (await api.inject({ url: '/api/culprit/matches' })).json() as CulpritMatchItem[];
assert.equal(list.length, 1);
assert.equal(list[0].eligibility.state, 'ready');
// 브라우저(사이트 중계)는 내부 경로를 쓸 수 없다
assert.equal((await api.inject({ url: `/api/culprit/internal/${id}/input` })).statusCode, 403);
assert.equal((await api.inject({ method: 'PUT', url: `/api/culprit/internal/${id}/result`, payload: {} })).statusCode, 403);
const r = await api.inject({ url: `/api/culprit/internal/${id}/input`, headers: { 'x-gvr-internal': '1' } });
assert.equal(r.statusCode, 200);
const input = r.json().input as CulpritInput;
assert.ok(input.text.length > 1000);
const result = {
summary: '요약',
confidence: 'high',
confidence_note: '',
teams: [
{ team: 'ally', culprit: 'P2', reason: '이유', evidence: [{ ref: 'u2', note: '"아 그냥 간다"', target: input.refs.u2 }] },
{ team: 'enemy', culprit: 'P8', reason: '이유', evidence: [] },
],
players: input.players.map((p) => ({ id: p.id, score: p.id === 'P2' || p.id === 'P8' ? 3 : 7, tag: p.id === 'P2' || p.id === 'P8' ? '범인' : '무난', comment: '평', evidence: [] })),
};
const put = await api.inject({
method: 'PUT',
url: `/api/culprit/internal/${id}/result`,
headers: { 'x-gvr-internal': '1' },
payload: { result, players: input.players, model: 'claude-opus-5-5', createdBy: { id: 'u1', name: '승한' }, meta: { costUsd: 0.41 } },
});
assert.equal(put.statusCode, 200);
const info = (await api.inject({ url: `/api/culprit/matches/${id}` })).json() as CulpritMatchInfo;
assert.equal(info.eligibility.state, 'done');
assert.equal(info.analysis!.result.teams[0].culprit, 'P2');
assert.equal(info.analysis!.meta.costUsd, 0.41);
assert.equal(info.history.length, 1);
assert.equal(info.sources.utterances, 4);
const list2 = (await api.inject({ url: '/api/culprit/matches' })).json() as CulpritMatchItem[];
assert.deepEqual(
list2[0].culprits.map((c) => [c.team, c.name]),
[
['ally', '민수'],
['enemy', 'Kiwi'],
],
);
// 다시 분석하면 이전 결과는 기록으로 남는다
await api.inject({ method: 'PUT', url: `/api/culprit/internal/${id}/result`, headers: { 'x-gvr-internal': '1' }, payload: { result, players: input.players, model: 'm2', createdBy: { id: 'u1', name: '승한' }, meta: {} } });
const info2 = (await api.inject({ url: `/api/culprit/matches/${id}` })).json() as CulpritMatchInfo;
assert.equal(info2.history.length, 2);
assert.equal(info2.analysis!.model, 'm2');
assert.equal(info2.history.filter((h) => h.current).length, 1);
await api.close();
});
test('녹음 안내 문구: 예전 기본 문구는 AI 분석 안내가 들어간 새 기본 문구로, 직접 고친 문구는 그대로', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gvr-tts-'));
fs.writeFileSync(path.join(dir, 'settings.json'), JSON.stringify({ discord: { ttsText: '겜녹이가 이 음성채널을 녹음합니다. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.' } }));
assert.equal(new SettingsStore(dir).get().discord.ttsText, DEFAULT_TTS_TEXT);
assert.match(DEFAULT_TTS_TEXT, /AI 경기 분석에 쓰일 수 있어요/);
fs.writeFileSync(path.join(dir, 'settings.json'), JSON.stringify({ discord: { ttsText: '녹음 중입니다' } }));
assert.equal(new SettingsStore(dir).get().discord.ttsText, '녹음 중입니다');
});