Files
game_voice_recorder/site/server/test/culprit.test.ts
EJClaw 0e0a2723e3 범인찾기 v1.3.1: OP.GG 세션 재시작 · 조회 실패 구분 · LOL.PS 라인전 10/15분
- opgg.ts: 세션 404 → 새 initialize 후 한 번 다시 (MCP 규격), 실패를 '경기 없음'과 나눠 meta.opgg.error · 화면 · 지시문에 반영
- rating.ts: 라인전을 LOL.PS 원문 정의대로 10 · 15분 맞라이너 CS · 골드 · 경험치 차로
- tools/opscore-fit/README.md: OP.GG(롤 · 발로란트) · LOL.PS 원문 인용과 구현 대응
- 테스트: 세션 재시작 · 503 · 일부 실패 · 서버 메타, 라인전 10/15분

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

449 lines
24 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';
import { lookupOpgg, opggCaller, parseOpgg, type ToolCaller } from '../src/opgg.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']>>; opgg?: ToolCaller | null }) {
// 앱 코어 (실제 범인찾기 코드 + 시연 경기)
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');
});
// OP.GG: 기본은 "이 경기 없음" (네트워크 안 씀)
const opgg: ToolCaller | null = opts.opgg !== undefined ? opts.opgg : async () => [];
const { app, store, hub } = await buildServer(cfg, { culpritCall: call, culpritKnowledge: knowledge, culpritOpgg: opgg });
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(), ['collect', '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']);
});
test('범인찾기 서버: OP.GG 조회 실패는 "경기 없음"과 따로 저장하고 기록 점수로 분석을 마친다', async () => {
const h = await harness({
calls: [(i) => ok(i)],
opgg: async () => {
throw new Error('OP.GG 503');
},
});
try {
assert.equal((await h.post(h.login('user1'))).status, 202);
await waitFor(() => h.stages().includes('done') || h.stages().includes('failed'));
assert.deepEqual(h.stages(), ['collect', 'thinking', 'verify', 'done']);
assert.ok(!h.seen[0].user.includes('# OP.GG 실제 OP스코어'));
const info = (await (await fetch(`${h.base}/api/culprit/matches/${h.matchId}`, { headers: { cookie: h.login('member1') } })).json()) as CulpritMatchInfo;
assert.equal(info.analysis!.meta.opgg!.found, false);
assert.equal(info.analysis!.meta.opgg!.error, true);
assert.match(info.analysis!.meta.opgg!.note!, /조회 실패/);
} finally {
await h.close();
}
});
test('범인찾기 서버: OP.GG 에 경기가 있으면 실제 OP스코어를 자료 · 결과에 붙인다', async () => {
const puuidOf: Record<string, string> = {};
const calls: string[] = [];
const opgg: ToolCaller = async (name, args: any) => {
calls.push(name);
if (name !== 'valorant_list_player_matches') throw new Error('unexpected');
// 각자 자기 경기 목록에 자기 opScore 만 (OP.GG 와 같은 모양)
return [{ matchId: 'other', puuid: puuidOf[args.game_name], opScore: 100 }, { matchId: 'demo', puuid: puuidOf[args.game_name], opScore: 655 }];
};
const h = await harness({ calls: [(i) => ok(i)], opgg });
try {
const input = (await h.local.inject({ url: `/api/culprit/internal/${h.matchId}/input`, headers: { 'x-gvr-internal': '1' } })).json().input as CulpritInput;
for (const p of input.players) puuidOf[p.name] = p.puuid;
assert.deepEqual(input.lookup?.riotMatchId, 'demo');
assert.equal((await h.post(h.login('user1'))).status, 202);
await waitFor(() => h.stages().includes('done') || h.stages().includes('failed'));
assert.deepEqual(h.stages(), ['collect', 'thinking', 'verify', 'done']);
const user = h.seen[0].user;
const lines = user.split('\n');
const at = lines.findIndex((l) => l.startsWith('# OP.GG 실제 OP스코어'));
assert.ok(at > 0 && at < lines.indexOf('# 시간 순서 기록'), 'OP.GG 줄은 시간 순서 기록 앞');
assert.match(lines[at], /: P1 6\.6 · P2 6\.6 .* · P10 6\.6$/);
assert.ok(lines.some((l) => l.startsWith('# 기록 점수 (0~10, OP.GG OP스코어 방식')), '기록 점수 칸 (앱이 만든다)');
assert.equal(calls.length, 10);
const info = (await (await fetch(`${h.base}/api/culprit/matches/${h.matchId}`, { headers: { cookie: h.login('member1') } })).json()) as CulpritMatchInfo;
assert.deepEqual(info.analysis!.meta.opgg, { found: true });
assert.deepEqual(info.analysis!.players.find((p) => p.id === 'P3')!.opgg, { score: 6.6, rank: null });
assert.ok(info.analysis!.players.every((p) => p.rating && p.rating.score >= 0), '저장된 참가자에 기록 점수');
} finally {
await h.close();
}
});
test('OP.GG: 응답 해석 · 롤 경기 찾기 (시작 시각 · 길이) · 못 찾음 · 연결 실패', async () => {
const text = [
'class L: data',
'class Data: game_history',
'class GameHistory: id,created_at,game_length_second,game_type',
'',
'L(Data([GameHistory("g1","2026-10-15T02:12:05+09:00",1387,"SOLORANKED"),GameHistory("g2","2026-10-15T01:00:00+09:00",900,"NORMAL")]))',
].join('\n');
assert.deepEqual(parseOpgg(text), {
data: {
game_history: [
{ id: 'g1', created_at: '2026-10-15T02:12:05+09:00', game_length_second: 1387, game_type: 'SOLORANKED' },
{ id: 'g2', created_at: '2026-10-15T01:00:00+09:00', game_length_second: 900, game_type: 'NORMAL' },
],
},
});
assert.deepEqual(parseOpgg('X(true,null,-1.5,"a\\"b",[1,2])\n'.replace(/^/, 'class X: a,b,c,d,e\n\n')), { a: true, b: null, c: -1.5, d: 'a"b', e: [1, 2] });
const players = Array.from({ length: 10 }, (_, i) => ({ id: `P${i + 1}`, puuid: `pu${i}`, name: `n${i}`, tag: 'KR1', team: i < 5 ? 'ally' : 'enemy', character: null, userId: i === 2 ? 'u' : null, voice: false })) as CulpritInput['players'];
const input = { game: 'lol', text: '', refs: {}, players, stats: {} as any, lookup: { riotMatchId: '777', startedAt: Date.parse('2026-10-15T02:12:30+09:00'), endedAt: 0, durationSec: 1400 } } as CulpritInput;
const asked: any[] = [];
const caller: ToolCaller = async (name, args) => {
asked.push([name, args]);
if (name === 'lol_list_summoner_matches') return parseOpgg(text);
return {
data: {
game_detail: {
teams: [0, 1].map((t) => ({
participants: players.slice(t * 5, t * 5 + 5).map((p, i) => ({
// 한 명은 puuid 가 달라도 Riot ID 로 맞춘다
summoner: { puuid: p.id === 'P9' ? 'other' : p.puuid, game_name: p.name.toUpperCase(), tagline: 'kr1' },
stats: { op_score: 5 + t + i / 10, op_score_rank: t * 5 + i + 1 },
})),
})),
},
},
};
};
const r = await lookupOpgg(input, caller);
assert.equal(r.found, true);
assert.equal(r.scores.size, 10);
assert.deepEqual(r.scores.get('P9'), { score: 6.3, rank: 9 });
assert.equal(asked[0][1].game_name, 'n2', '우리 사람(앱 계정)부터');
assert.deepEqual(asked[1][1].game_id, 'g1');
// 시작 시각이 다르면 못 찾음 (내전 · 아직 OP.GG 에 없음)
const miss = await lookupOpgg({ ...input, lookup: { ...input.lookup!, startedAt: Date.parse('2026-10-14T10:00:00+09:00') } }, caller);
assert.equal(miss.found, false);
assert.match(miss.note!, /OP\.GG 에 이 경기가 없습니다/);
// 조회가 실패하면 "경기 없음"이 아니라 "확인 못 함" (분석은 멈추지 않는다)
const down = await lookupOpgg(input, async () => {
throw new Error('OP.GG 503');
});
assert.equal(down.found, false);
assert.equal(down.error, true);
assert.match(down.note!, /OP\.GG 조회 실패로 이 경기를 확인하지 못했습니다 \(3번 중 3번 실패: OP\.GG 503\)/);
assert.equal(miss.error, undefined, '조회는 됐는데 없으면 error 아님');
const vMiss = await lookupOpgg({ ...input, game: 'valorant' }, async () => []);
assert.deepEqual([vMiss.found, vMiss.error, /이 경기가 없습니다/.test(vMiss.note!)], [false, undefined, true]);
// 일부만 실패하고 못 찾았으면 확인 못 함
let k = 0;
const vHalf = await lookupOpgg({ ...input, game: 'valorant' }, async () => {
if (k++ % 2) throw new Error('OP.GG 503');
return [];
});
assert.equal(vHalf.error, true);
});
test('OP.GG 클라이언트: 세션이 끝나면(404) 새로 initialize 하고 다시 부른다', async () => {
let serverSid = 's1';
let inits = 0;
const seen: { method: string; sid: string | null }[] = [];
const fetchFn = (async (_url: string, init: any) => {
const body = JSON.parse(init.body);
const sid = init.headers['mcp-session-id'] ?? null;
seen.push({ method: body.method, sid });
if (body.method === 'initialize') {
inits++;
if (sid) return new Response('bad', { status: 400 });
return new Response(JSON.stringify({ jsonrpc: '2.0', id: body.id, result: {} }), { status: 200, headers: { 'mcp-session-id': serverSid } });
}
if (sid !== serverSid) return new Response('session not found', { status: 404 });
if (body.params.name === 'boom') return new Response('unavailable', { status: 503 });
// SSE 로 줄 때도 읽는다
const msg = JSON.stringify({ jsonrpc: '2.0', id: body.id, result: { content: [{ type: 'text', text: JSON.stringify({ ok: body.params.name, sid }) }] } });
return new Response(`event: message\ndata: ${msg}\n\n`, { status: 200, headers: { 'content-type': 'text/event-stream' } });
}) as typeof fetch;
const call = opggCaller({ url: 'http://opgg.test/mcp', fetchFn });
assert.deepEqual(await call('a', {}), { ok: 'a', sid: 's1' });
// 서버가 재시작해 세션이 사라졌다
serverSid = 's2';
assert.deepEqual(await call('b', {}), { ok: 'b', sid: 's2' });
assert.deepEqual(await call('c', {}), { ok: 'c', sid: 's2' }, '새 세션을 계속 쓴다');
assert.equal(inits, 2);
assert.deepEqual(
seen.map((x) => `${x.method}:${x.sid ?? '-'}`),
['initialize:-', 'tools/call:s1', 'tools/call:s1', 'initialize:-', 'tools/call:s2', 'tools/call:s2'],
);
// 세션 문제가 아닌 실패(503)는 다시 initialize 하지 않고 그대로 실패
await assert.rejects(call('boom', {}), /OP\.GG 503/);
assert.equal(inits, 2);
});