Files
game_voice_recorder/site/server/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

290 lines
16 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 WebSocket from 'ws';
import type { CulpritBudget, CulpritInput, CulpritMatchInfo } from '@gvr/shared';
import { buildServer } from '../src/app.ts';
import type { Config } from '../src/config.ts';
import { checkResult, costOf, normRef, type ModelCall } from '../src/culprit.ts';
import { buildSystemPrompt, KnowledgeAuto, outputSchema, replaceAutoSection } from '../src/culprit-prompt.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-culprit-srv-'));
/** AI 답 만들기: 우리 팀 범인 P4, 상대 팀 범인 P7 */
function answer(input: CulpritInput, opts: { badRefs?: boolean; culpritScore?: number } = {}) {
const firstKill = Object.keys(input.refs).find((k) => k.startsWith('e'))!;
return {
summary: '접전 끝에 이긴 경기.',
confidence: 'high',
confidence_note: '',
teams: [
{
team: 'ally',
culprit: 'P4',
reason: '혼자 들어가 첫 데스.',
evidence: opts.badRefs ? [{ ref: 'u999', note: '없는 문장' }] : [{ ref: `[${firstKill}]`, note: '첫 데스' }, { ref: 's:p4', note: '스탯' }, { ref: 'u404', note: '없는 근거' }],
},
{ team: 'enemy', culprit: 'P7', reason: 'ACS 최저.', evidence: [{ ref: 's:P7', note: 'ACS 133' }] },
],
players: input.players.map((p) => ({
id: p.id,
score: p.id === 'P4' ? (opts.culpritScore ?? 3.5) : p.id === 'P7' ? 3 : 7.26,
tag: p.id === 'P4' || p.id === 'P7' ? '범인' : p.id === 'P1' ? '범인' : '무난',
comment: '한 줄 평',
evidence: [],
})),
};
}
async function harness(opts: { calls: ((input: CulpritInput) => Awaited<ReturnType<ModelCall>>)[]; culprit?: Partial<NonNullable<Config['culprit']>> }) {
// 앱 코어 (실제 범인찾기 코드 + 시연 경기)
const seed = await import('../../../app/test/fixtures/culprit-seed.ts');
const core = seed.setup();
const { id: matchId } = seed.seedValorant(core);
const local = await seed.culpritApi(core);
const cfg: Config = {
port: 0,
host: '127.0.0.1',
publicUrl: 'http://127.0.0.1',
clientId: 'cid',
clientSecret: 'secret',
botToken: 'bot',
allowedGuilds: ['111'],
owners: ['super1'],
superAdmins: ['super1'],
sessionSecret: 'x'.repeat(32),
dataDir: tmp(),
webDir: '/nonexistent',
version: 'test',
discordApi: 'http://127.0.0.1:1',
assetUpstream: {},
culprit: { apiKey: 'test-key', model: 'claude-opus-5-5', effort: 'high', monthLimitUsd: 100, dailyLimit: 20, tone: 'medium', ...opts.culprit },
};
const seen: { system: string; user: string; schema: any; effort: string; maxTokens: number }[] = [];
let n = 0;
const call: ModelCall = async (req) => {
seen.push(req);
const input = (await local.inject({ url: `/api/culprit/internal/${matchId}/input`, headers: { 'x-gvr-internal': '1' } })).json().input as CulpritInput;
const f = opts.calls[Math.min(n++, opts.calls.length - 1)];
return f(input);
};
// 자동 갱신 칸: 네트워크 없이 고정 값
const knowledge = new KnowledgeAuto(async () => {
throw new Error('offline');
});
const { app, store, hub } = await buildServer(cfg, { culpritCall: call, culpritKnowledge: knowledge });
await app.listen({ host: '127.0.0.1', port: 0 });
const base = `http://127.0.0.1:${(app.server.address() as any).port}`;
const login = (id: string) => {
const s = store.createSession({ id, name: id, avatar: null });
return `gvr_sid=${encodeURIComponent(app.signCookie(s.token))}`;
};
store.upsertAppUser({ id: 'user1', name: '유저', avatar: null, role: 'user', addedBy: 'super1' });
// 게임 PC 연결 (실제 RelayClient)
const code = store.createCode('t');
const reg = store.redeem(code.code, 'GAME-PC')!;
const { RelayClient } = await import('../../../app/src/core/relay/client.ts');
const { Bus } = await import('../../../app/src/core/util/events.ts');
const rc = new RelayClient(local as any, new Bus(), () => ({ serverUrl: base, deviceId: reg.deviceId, deviceKey: reg.deviceKey, name: 'GAME-PC', version: 't', guildId: '111' }));
rc.start();
await waitFor(() => hub.status().online);
const events: any[] = [];
const ws = new WebSocket(base.replace('http', 'ws') + '/ws', { headers: { cookie: login('member1') } });
ws.on('message', (d) => events.push(JSON.parse(String(d))));
await new Promise((r) => ws.on('open', r));
const post = (cookie: string, body: any = {}) =>
fetch(`${base}/api/culprit/matches/${matchId}/analyze`, { method: 'POST', headers: { cookie, 'content-type': 'application/json' }, body: JSON.stringify(body) });
const close = async () => {
ws.close();
rc.stop();
await app.close();
await local.close();
};
return { base, cfg, matchId, core, local, app, login, post, events, seen, close, stages: () => events.filter((e) => e.type === 'culprit.progress').map((e) => e.data.stage) };
}
async function waitFor(fn: () => boolean, ms = 8000) {
const t = Date.now();
while (!fn()) {
if (Date.now() - t > ms) throw new Error('timeout');
await new Promise((r) => setTimeout(r, 30));
}
}
const ok = (input: CulpritInput, o?: Parameters<typeof answer>[1]) => ({
text: JSON.stringify(answer(input, o)),
stopReason: 'end_turn',
usages: [{ model: 'claude-opus-5-5', input: 26000, output: 14000, cacheRead: 0, cacheWrite: 0 }],
fallback: false,
});
test('범인찾기 서버: 권한 · 분석 · 근거 확인 · 결과 저장 · 비용 장부 · 중복 방지', async () => {
const h = await harness({ calls: [(i) => ok(i)] });
try {
const guest = h.login('member1');
const user = h.login('user1');
const admin = h.login('super1');
const b0 = (await (await fetch(h.base + '/api/culprit/budget', { headers: { cookie: guest } })).json()) as CulpritBudget;
assert.deepEqual([b0.enabled, b0.canAnalyze, b0.canReanalyze, b0.monthSpentUsd, b0.dailyLimit, b0.model], [true, false, false, 0, 20, 'claude-opus-5-5']);
// (가) 등록된 앱 유저 이상만
assert.equal((await h.post(guest)).status, 403);
// 브라우저는 내부 경로를 못 쓴다
assert.equal((await fetch(`${h.base}/api/culprit/internal/${h.matchId}/input`, { headers: { cookie: admin } })).status, 404);
assert.equal((await fetch(`${h.base}/api/culprit/internal/${h.matchId}/result`, { method: 'PUT', headers: { cookie: admin, 'content-type': 'application/json' }, body: '{}' })).status, 404);
// 다른 사이트에서 온 요청은 거절
assert.equal((await fetch(`${h.base}/api/culprit/matches/${h.matchId}/analyze`, { method: 'POST', headers: { cookie: user, origin: 'https://evil.example' } })).status, 403);
const r = await h.post(user);
assert.equal(r.status, 202);
// 동시에 누르면 한 번만
const dup = await h.post(user);
assert.ok(dup.status === 409, `중복 ${dup.status}`);
await waitFor(() => h.stages().includes('done') || h.stages().includes('failed'));
assert.deepEqual(h.stages(), ['thinking', 'verify', 'done']);
// 보낸 프롬프트: 지시문 + 발로란트 지식 묶음(파일 스냅샷) + 말투 중간맛, 경기 자료는 <match> 안
const sent = h.seen[0];
assert.match(sent.system, /^너는 겜녹이의 경기 분석가다/);
assert.match(sent.system, /말투: medium\(중간맛\)/);
assert.match(sent.system, /<knowledge game="valorant">[\s\S]*## 자동 갱신 \(2026-10-15 스냅샷\)/);
assert.ok(!sent.system.includes('<!--'), 'HTML 주석은 빼고 보낸다');
assert.match(sent.user, /^<match>\n# 경기 발로란트 /);
assert.equal(sent.effort, 'high');
assert.equal(sent.maxTokens, 32000);
assert.equal(sent.schema.type, 'object');
// 결과: 없는 근거는 빠지고, 근거 번호는 그 순간으로 연결, 범인 태그는 팀마다 한 명
const info = (await (await fetch(`${h.base}/api/culprit/matches/${h.matchId}`, { headers: { cookie: guest } })).json()) as CulpritMatchInfo;
assert.equal(info.eligibility.state, 'done');
const a = info.analysis!;
assert.deepEqual(a.result.teams.map((t) => t.culprit), ['P4', 'P7']);
assert.deepEqual(a.result.teams[0].evidence.map((e) => e.ref), [a.result.teams[0].evidence[0].ref, 's:P4']);
assert.equal(a.result.teams[0].evidence[0].target!.kind, 'event');
assert.equal(a.result.players.find((p) => p.id === 'P1')!.tag, '아쉬움');
assert.equal(a.result.players.filter((p) => p.tag === '범인').length, 2);
assert.equal(a.result.players.find((p) => p.id === 'P2')!.score, 7.5, '0.5 단위로');
assert.equal(a.createdBy.id, 'user1');
assert.equal(a.meta.costUsd, 0.384);
assert.equal(a.meta.tone, 'medium');
const b1 = (await (await fetch(h.base + '/api/culprit/budget', { headers: { cookie: user } })).json()) as CulpritBudget;
assert.deepEqual([b1.monthSpentUsd, b1.todayCount, b1.estimateUsd, b1.canReanalyze], [0.384, 1, 0.38, false]);
// 한 경기 한 번: 다시 누르면 409, 다시 분석은 관리자만
assert.equal((await h.post(user)).status, 409);
assert.equal((await h.post(user, { reanalyze: true })).status, 403);
assert.equal((await h.post(admin, { reanalyze: true })).status, 202);
await waitFor(() => h.stages().filter((s) => s === 'done').length === 2);
const info2 = (await (await fetch(`${h.base}/api/culprit/matches/${h.matchId}`, { headers: { cookie: guest } })).json()) as CulpritMatchInfo;
assert.equal(info2.history.length, 2);
assert.equal(info2.analysis!.createdBy.id, 'super1');
// 서버에는 비용 장부만 (대화 내용 없음)
const ledger = fs.readFileSync(path.join(h.cfg.dataDir, 'culprit-ledger.json'), 'utf8');
assert.equal(JSON.parse(ledger).length, 2);
assert.ok(!ledger.includes('기다려') && !ledger.includes('현우'), '장부에 대화 · 이름 없음');
} finally {
await h.close();
}
});
test('범인찾기 서버: 근거가 하나도 안 맞으면 한 번 다시, 거절 · 하루 횟수 · 예산', async () => {
// 1) 첫 답의 범인 근거가 모두 없는 번호 → 다시 분석 (하루 횟수는 1번만 센다)
const h = await harness({ calls: [(i) => ok(i, { badRefs: true }), (i) => ok(i)] });
try {
assert.equal((await h.post(h.login('user1'))).status, 202);
await waitFor(() => h.stages().includes('done') || h.stages().includes('failed'));
assert.equal(h.seen.length, 2);
const b = (await (await fetch(h.base + '/api/culprit/budget', { headers: { cookie: h.login('user1') } })).json()) as CulpritBudget;
assert.equal(b.todayCount, 1);
assert.equal(b.monthSpentUsd, 0.768);
} finally {
await h.close();
}
// 2) 거절(refusal): 실패 알림, 비용은 장부에 남고 잠금은 풀린다
const r = await harness({ calls: [() => ({ text: null, stopReason: 'refusal', usages: [{ model: 'claude-opus-5-5', input: 26000, output: 10, cacheRead: 0, cacheWrite: 0 }], fallback: true })] });
try {
assert.equal((await r.post(r.login('user1'))).status, 202);
await waitFor(() => r.stages().includes('failed'));
assert.equal(r.events.find((e) => e.data?.stage === 'failed').data.message, 'AI 가 이 경기 분석을 거절했습니다');
const info = (await (await fetch(`${r.base}/api/culprit/matches/${r.matchId}`, { headers: { cookie: r.login('user1') } })).json()) as CulpritMatchInfo;
assert.equal(info.eligibility.state, 'ready', '결과가 없으니 다시 누를 수 있다');
const b = (await (await fetch(r.base + '/api/culprit/budget', { headers: { cookie: r.login('user1') } })).json()) as CulpritBudget;
assert.equal(b.monthSpentUsd, 0.1042);
assert.deepEqual(b.running, []);
} finally {
await r.close();
}
// 3) 하루 횟수 · 월 예산
const d = await harness({ calls: [(i) => ok(i)], culprit: { dailyLimit: 0 } });
try {
const res = await d.post(d.login('user1'));
assert.equal(res.status, 429);
assert.equal(((await res.json()) as any).error, 'daily_limit');
} finally {
await d.close();
}
const m = await harness({ calls: [(i) => ok(i)], culprit: { monthLimitUsd: 0.3 } });
try {
const res = await m.post(m.login('user1'));
assert.equal(res.status, 429);
assert.equal(((await res.json()) as any).error, 'budget');
} finally {
await m.close();
}
});
test('범인찾기: 결과 확인 규칙 · 비용 계산 · 프롬프트 조립', () => {
const input: CulpritInput = {
game: 'lol',
text: '',
refs: { u1: { kind: 'utterance', id: 'x', ts: 1 }, e1: { kind: 'event', id: 'k', ts: 2 }, 's:P1': { kind: 'stat', pid: 'P1' }, 's:P2': { kind: 'stat', pid: 'P2' } },
players: [
{ id: 'P1', puuid: 'a', name: 'A', team: 'ally', character: null, userId: 'u', voice: true },
{ id: 'P2', puuid: 'b', name: 'B', team: 'enemy', character: null, userId: null, voice: false },
],
stats: { utterances: 1, utterancesTotal: 1, events: 1, chats: 0, rounds: 0, basic: false },
};
const base = {
summary: 's',
confidence: 'weird',
confidence_note: '',
teams: [
{ team: 'ally', culprit: 'p1', reason: 'r', evidence: [{ ref: 'u1', note: '말' }] },
{ team: 'enemy', culprit: 'P2', reason: 'r', evidence: [{ ref: 's:P2', note: '스탯' }] },
],
players: [
{ id: 'P1', score: 4, tag: '범인', comment: '', evidence: [] },
{ id: 'P2', score: 11, tag: '모름', comment: '', evidence: [] },
],
};
// 음성O 범인에게 말 근거만 있으면 다시 (플레이 근거 필요)
const c1 = checkResult(base, input);
assert.equal(c1.needRetry, true);
assert.equal(c1.result!.confidence, 'medium');
assert.equal(c1.result!.players[1].score, 10);
assert.equal(c1.result!.players[1].tag, '범인', '팀의 범인에게는 범인 태그');
const c2 = checkResult({ ...base, teams: [{ ...base.teams[0], evidence: [{ ref: 'u1', note: '' }, { ref: 'E1', note: '' }] }, base.teams[1]] }, input);
assert.equal(c2.needRetry, false);
// 한 명이라도 빠지면 다시
assert.equal(checkResult({ ...base, players: [base.players[0]] }, input).needRetry, true);
assert.equal(checkResult({ ...base, teams: [{ ...base.teams[0], culprit: 'P2' }, base.teams[1]] }, input).result, null, '다른 팀 사람은 범인이 될 수 없다');
assert.deepEqual(['[u12]', 'U3', 's:p4', ' S : P10 ', 'x9'].map(normRef), ['u12', 'u3', 's:P4', 's:P10', 'x9']);
// 비용: Opus 5.5 $4/$20, 캐시 읽기 0.1배, 쓰기 1.25배. 모르는 모델은 $5/$25
assert.equal(costOf([{ model: 'claude-opus-5-5', input: 26077, output: 13997, cacheRead: 0, cacheWrite: 0 }]), 0.3842);
assert.equal(costOf([{ model: 'claude-opus-5-5', input: 1000, output: 0, cacheRead: 10000, cacheWrite: 4000 }]), 0.028);
assert.equal(costOf([{ model: 'claude-new-x', input: 1e6, output: 0, cacheRead: 0, cacheWrite: 0 }]), 5);
// 프롬프트: 롤 지식 묶음 + 자동 갱신 칸 교체 + 출력 형식
const auto = '## 자동 갱신 (패치 99.1.1, Riot Data Dragon)\n- 챔피언 (분류): 새챔(전사)';
const sys = buildSystemPrompt('lol', 'spicy', auto);
assert.match(sys, /말투: spicy\(매운맛\)/);
assert.match(sys, /## 자동 갱신 \(패치 99\.1\.1, Riot Data Dragon\)\n- 챔피언 \(분류\): 새챔\(전사\)\n<\/knowledge>$/);
assert.ok(!sys.includes('가렌(전사/탱커)'), '스냅샷 칸은 바뀐다');
assert.match(sys, /범인은 아래를 모두 합쳐 종합으로 판단한다/);
assert.equal(replaceAutoSection('a\n</knowledge>', 'x'), 'a\n</knowledge>', '칸이 없으면 그대로');
const schema = outputSchema() as any;
assert.deepEqual(schema.required, ['summary', 'confidence', 'confidence_note', 'teams', 'players']);
});