Files
game_voice_recorder/app/scripts/culprit-real-e2e.mts
EJClaw be893173a1 앱 v1.3.0: 범인찾기 실제 E2E (Claude Opus 5.5 high + OP.GG) · README · 테스트 기록
- app/scripts/culprit-real-e2e.mts: 실제 앱 코어 → 사이트 서버 → 실제 Claude API · 실제 OP.GG MCP → 결과 화면
  발로란트 시연 경기 42초 $0.146 (OP.GG 없음 → 기록 점수), 롤 실제 랭크 경기 36초 $0.109 (OP.GG 10명 찾음)
- 버전 1.3.0

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

216 lines
12 KiB
TypeScript

// 범인찾기 실제 E2E: 실제 앱 코어 + 실제 사이트 서버 + 실제 Claude API(Opus 5.5, 생각 high) + 실제 OP.GG MCP + 헤드리스 브라우저.
// 1) 발로란트 시연 경기 (22라운드 · 대화) → OP.GG 에 없는 경기 → 기록 점수만으로 분석
// 2) 롤: OP.GG 에서 받은 실제 랭크 경기(10명 실제 스탯)에 우리 팀 2명의 대화를 붙인 경기 → OP.GG 실제 OP스코어를 찾아 같이 분석
// 비용이 든다 (경기당 약 $0.4). API 키는 secrets.json 에서 읽어 이 프로세스 안에서만 쓴다.
// node --import tsx scripts/culprit-real-e2e.mts [결과 폴더]
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import type { CulpritInput, CulpritMatchInfo, MatchPlayer } from '@gvr/shared';
import { culpritApi, MIN, seedValorant, setup } from '../test/fixtures/culprit-seed.ts';
const outDir = process.argv[2] || path.join(os.homedir(), '.tmp', 'culprit-real');
fs.mkdirSync(outDir, { recursive: true });
const root = path.resolve(import.meta.dirname, '..', '..');
const apiKey = JSON.parse(fs.readFileSync(path.join(os.homedir(), '.config/ejclaw/secrets.json'), 'utf8')).credentials['anthropic.api/game-voice-recorder'].token as string;
const { opggCaller } = await import('../../site/server/src/opgg.ts');
const opgg = opggCaller();
const core = setup();
await core.assets.refresh(true).catch(() => undefined);
const { id: valId } = seedValorant(core);
// ---------------------------------------------------------------- 롤: OP.GG 의 실제 랭크 경기
const POS: Record<string, string> = { TOP: '탑', JUNGLE: '정글', MID: '미드', ADC: '원딜', SUPPORT: '서폿' };
const listOf = async (name: string, tag: string) =>
((await opgg('lol_list_summoner_matches', { game_name: name, tag_line: tag, region: 'KR', limit: 10, desired_output_fields: ['data.game_history[].{created_at,game_length_second,game_type,id}'] })) as any).data.game_history as any[];
const detailOf = async (g: any) =>
((await opgg('lol_get_summoner_game_detail', {
region: 'KR',
game_id: g.id,
created_at: g.created_at,
desired_output_fields: [
'data.game_detail.teams[].participants[].stats.{assist,champion_level,death,gold_earned,kill,minion_kill,neutral_minion_kill,op_score,time_ccing_others,total_damage_dealt_to_champions,total_damage_taken,vision_wards_bought_in_game,ward_place}',
'data.game_detail.teams[].participants[].{position,team_key,champion_id,champion_name}',
'data.game_detail.teams[].participants[].summoner.{puuid,game_name,tagline,player}',
'data.game_detail.teams[].game_stat.{champion_kill,is_win}',
],
})) as any).data.game_detail;
// 프로 선수가 아닌 사람의 최근 솔로 랭크 (15분 이상)
const seedGame = (await listOf('Hide on bush', 'KR1')).find((g) => g.game_type === 'SOLORANKED')!;
const seedDet = await detailOf(seedGame);
const pick = seedDet.teams.flatMap((t: any) => t.participants).find((p: any) => !p.summoner.player && p.summoner.game_name !== 'Hide on bush');
const g = (await listOf(pick.summoner.game_name, pick.summoner.tagline)).find((x) => x.game_type === 'SOLORANKED' && x.game_length_second > 1200)!;
const det = await detailOf(g);
const all = det.teams.flatMap((t: any) => t.participants.map((p: any) => ({ ...p, win: t.game_stat.is_win, teamKills: t.game_stat.champion_kill })));
const selfP = all.find((p: any) => p.summoner.puuid === pick.summoner.puuid) ?? all[0];
const opggTruth = new Map<string, number>(all.map((p: any) => [p.summoner.puuid, p.stats.op_score]));
const players: MatchPlayer[] = all.map((p: any) => ({
puuid: p.summoner.puuid,
name: p.summoner.game_name,
tag: p.summoner.tagline,
team: p.team_key,
ally: p.team_key === selfP.team_key,
character: { id: String(p.champion_id), name: p.champion_name, icon: null },
kills: p.stats.kill,
deaths: p.stats.death,
assists: p.stats.assist,
cs: (p.stats.minion_kill ?? 0) + (p.stats.neutral_minion_kill ?? 0),
gold: p.stats.gold_earned,
level: p.stats.champion_level,
stats: {
role: POS[p.position],
damage: p.stats.total_damage_dealt_to_champions,
damageTaken: p.stats.total_damage_taken,
ccSeconds: p.stats.time_ccing_others ?? 0,
wardsPlaced: p.stats.ward_place ?? 0,
controlWards: p.stats.vision_wards_bought_in_game ?? 0,
},
}));
const LS = Date.parse(g.created_at) + 60000;
const LEN = g.game_length_second * 1000;
const allyWin = !!selfP.win;
const allyKills = all.filter((p: any) => p.team_key === selfP.team_key)[0].teamKills;
const enemyKills = all.filter((p: any) => p.team_key !== selfP.team_key)[0].teamKills;
const lolId = `lol-${g.id.replace(/[^\w]/g, '').slice(0, 20)}`;
core.store.upsertMatch({
id: lolId,
game: 'lol',
started_at: LS,
ended_at: LS + LEN,
status: 'complete',
map: 'Map11',
mode: 'CLASSIC',
queue: '420',
result: JSON.stringify({ win: allyWin, score: { ally: allyKills, enemy: enemyKills } }),
detail: JSON.stringify({ live: false, players, goldDiff: [], self: selfP.summoner.puuid }),
});
// 우리 팀 두 명이 음성채널에 있었다고 하고 대화를 붙인다 (실제 경기 기록 + 시험용 대화)
const mates = players.filter((p) => p.ally);
const [a, b] = [mates.find((p) => p.puuid === selfP.summoner.puuid)!, mates.find((p) => p.puuid !== selfP.summoner.puuid)!];
core.store.upsertUser({ id: 'ua', name: '승한', avatar: null });
core.store.upsertUser({ id: 'ub', name: '민수', avatar: null });
core.store.setAccounts('ua', [{ puuid: a.puuid, riotId: `${a.name}#${a.tag}` }]);
core.store.setAccounts('ub', [{ puuid: b.puuid, riotId: `${b.name}#${b.tag}` }]);
core.store.startSession('s-lol', 'g', 'c', '음성', LS - MIN);
const talk: [string, number, string][] = [
['ua', 2.5, '정글 위쪽에서 시작했어 바텀 조심해'],
['ub', 6.2, '용 앞에 와드 박아 줘 시야 없어'],
['ua', 6.5, '알았어 지금 갈게'],
['ub', 11.0, '미드 미아 미드 미아 내려간다'],
['ua', 14.8, '용 한타 열지 마 아직 우리 텔 없어'],
['ub', 15.1, '아 들어갔다 아 죽었다 미안'],
['ua', 19.5, '바론 시야 먼저 잡고 하자 혼자 가지 마'],
['ub', 24.0, allyWin ? '좋아 한타 이겼다 미드 밀자' : '아 또 잡혔네 이거 그냥 서렌 치자'],
['ua', 24.3, allyWin ? '억제기 깨고 바로 빠지자' : '아직 안 끝났어 수비하자'],
];
for (const [uid, min, text] of talk) {
if (min * MIN > LEN) continue;
const ts = LS + min * MIN;
const id = `lol-${uid}-${min}`;
core.store.insertUtterance({ id, session_id: 's-lol', user_id: uid, started_at: ts, ended_at: ts + 1800, audio_path: null, match_id: lolId });
core.store.updateUtteranceResult(id, { text, raw_text: text, words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 0, model: 'large-v3', status: 'precise' });
}
core.store.endSession('s-lol', LS + LEN + MIN);
// ---------------------------------------------------------------- 사이트 서버 (실제 Claude · 실제 OP.GG)
const local = await culpritApi(core);
const { buildServer } = await import('../../site/server/src/app.ts');
const port = 18961;
const site = await buildServer({
port, host: '127.0.0.1', publicUrl: `http://127.0.0.1:${port}`, clientId: 'x', clientSecret: 'x', botToken: 'x', allowedGuilds: [], owners: ['u1'], superAdmins: ['u1'],
sessionSecret: 'real-e2e-secret-'.repeat(3), dataDir: fs.mkdtempSync(path.join(os.tmpdir(), 'gvr-real-')), webDir: path.join(root, 'site', 'web', 'dist'), version: 't', discordApi: 'http://127.0.0.1:1',
assetUpstream: { valmedia: 'https://media.valorant-api.com/', ddragon: 'https://ddragon.leagueoflegends.com/', cdragon: 'https://raw.communitydragon.org/' },
culprit: { apiKey, model: 'claude-opus-5-5', effort: 'high', monthLimitUsd: 100, dailyLimit: 20, tone: 'medium', opgg: true },
});
site.app.log.level = 'info';
await site.app.listen({ host: '127.0.0.1', port });
const base = `http://127.0.0.1:${port}`;
const code = site.store.createCode('real');
const reg = site.store.redeem(code.code, 'GAME-PC')!;
const { RelayClient } = await import('../src/core/relay/client.ts');
const rc = new RelayClient(local as any, core.bus, () => ({ serverUrl: base, deviceId: reg.deviceId, deviceKey: reg.deviceKey, name: 'GAME-PC', version: 't', guildId: 'g' }));
rc.start();
while (!site.hub.status().online) await new Promise((r) => setTimeout(r, 100));
const sess = site.store.createSession({ id: 'u1', name: '승한', avatar: null });
const cookieHeader = `gvr_sid=${encodeURIComponent(site.app.signCookie(sess.token))}`;
const stages: Record<string, string[]> = {};
// 진행 단계 기록 (실시간 알림을 가로챈다)
const pub = site.hub.publish.bind(site.hub);
site.hub.publish = (e: any) => {
if (e.type === 'culprit.progress') (stages[e.data.matchId] ||= []).push(`${e.data.stage}${e.data.message ? `(${e.data.message})` : ''}`);
pub(e);
};
async function analyze(matchId: string) {
const input = (await local.inject({ url: `/api/culprit/internal/${matchId}/input`, headers: { 'x-gvr-internal': '1' } })).json().input as CulpritInput;
fs.writeFileSync(path.join(outDir, `${matchId}.input.txt`), input.text);
const t0 = Date.now();
const r = await fetch(`${base}/api/culprit/matches/${matchId}/analyze`, { method: 'POST', headers: { cookie: cookieHeader, 'content-type': 'application/json' }, body: '{}' });
if (r.status !== 202) throw new Error(`analyze ${r.status} ${await r.text()}`);
for (;;) {
await new Promise((res) => setTimeout(res, 3000));
const info = (await (await fetch(`${base}/api/culprit/matches/${matchId}`, { headers: { cookie: cookieHeader } })).json()) as CulpritMatchInfo;
if (info.analysis) return { info, ms: Date.now() - t0 };
if (Date.now() - t0 > 10 * MIN) throw new Error('10분 안에 끝나지 않음');
const b = await (await fetch(`${base}/api/culprit/budget`, { headers: { cookie: cookieHeader } })).json();
if (!b.running.includes(matchId)) {
// 실패
throw new Error(`분석 실패: ${JSON.stringify(stages[matchId] ?? [])}`);
}
}
}
const report: any = {};
for (const id of [valId, lolId]) {
console.log(`\n=== ${id} 분석 시작`);
const { info, ms } = await analyze(id);
const a = info.analysis!;
fs.writeFileSync(path.join(outDir, `${id}.result.json`), JSON.stringify(a, null, 1));
const ref = (pid: string) => a.players.find((p) => p.id === pid)!;
const rows = a.result.players.map((p) => {
const pl = ref(p.id);
return { id: p.id, team: pl.team, ai: p.score, rating: pl.rating?.score ?? null, opgg: pl.opgg?.score ?? null, truth: opggTruth.get(pl.puuid) ?? null, tag: p.tag, comment: p.comment };
});
const teamLowest = (team: string, key: 'rating' | 'opgg') => {
const ps = rows.filter((r) => r.team === team && r[key] !== null);
return ps.length ? ps.reduce((x, y) => ((x[key] as number) <= (y[key] as number) ? x : y)).id : null;
};
report[id] = {
seconds: Math.round(ms / 1000),
model: a.model,
costUsd: a.meta.costUsd,
usage: a.meta.usage,
opgg: a.meta.opgg,
stages: stages[id],
summary: a.result.summary,
confidence: a.result.confidence,
culprits: a.result.teams.map((t) => ({ team: t.team, culprit: t.culprit, reason: t.reason, evidence: t.evidence.map((e) => e.ref), lowestRating: teamLowest(t.team, 'rating'), lowestOpgg: teamLowest(t.team, 'opgg') })),
players: rows,
};
console.log(JSON.stringify(report[id], null, 1));
}
fs.writeFileSync(path.join(outDir, 'report.json'), JSON.stringify(report, null, 1));
// ---------------------------------------------------------------- 화면
const puppeteer = (await import(path.join(os.homedir(), '.tmp/gvr-shot/node_modules/puppeteer-core/lib/esm/puppeteer/puppeteer-core.js'))).default;
const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: true, args: ['--no-sandbox', '--lang=ko-KR'] });
const page = await browser.newPage();
await page.setCookie({ name: 'gvr_sid', value: site.app.signCookie(sess.token), url: base });
const errs: string[] = [];
page.on('pageerror', (e: any) => errs.push(e.message));
for (const [id, name] of [[valId, 'real-val.png'], [lolId, 'real-lol.png']] as const) {
await page.setViewport({ width: 1440, height: 2000 });
await page.goto(`${base}/culprit/${id}`, { waitUntil: 'networkidle2' });
await page.waitForSelector('.cu-card', { timeout: 20000 });
await new Promise((r) => setTimeout(r, 1500));
await page.screenshot({ path: path.join(outDir, name), fullPage: true });
}
console.log('\n화면 오류:', errs);
await browser.close();
rc.stop();
await site.app.close();
await local.close();
console.log('결과:', outDir);