범인찾기 v1.3.2: 외부 전적 사이트 접속 제거 — OP.GG · LOL.PS 는 계산법만 참고

- 사용자 결정: 실제 OP.GG 연결이 아니라 계산법 참고 → 분석 때 OP.GG 를 찾아보던 opgg.ts · 결과의 OP.GG 점수 · 조회 상태 · 지시문 줄 · Riot 태그/경기 찾기 정보 제거
- 남은 것: 기록 점수(OP.GG OP스코어 계산법, 앱이 경기 기록으로 계산) · 10/15분 라인전(LOL.PS 정의)
- 실제 E2E (Claude Opus 5.5 high, 외부 접속 없음): 발로란트 33초 $0.138, 롤 36초 $0.123
- 테스트: 앱 40 · 서버 16 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-15 16:11:53 +09:00
parent 2ddba2e4e5
commit b8e76aba25
17 changed files with 88 additions and 600 deletions

View File

@@ -9,7 +9,6 @@ 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-'));
@@ -39,7 +38,7 @@ function answer(input: CulpritInput, opts: { badRefs?: boolean; culpritScore?: n
};
}
async function harness(opts: { calls: ((input: CulpritInput) => Awaited<ReturnType<ModelCall>>)[]; culprit?: Partial<NonNullable<Config['culprit']>>; opgg?: ToolCaller | null }) {
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();
@@ -75,9 +74,7 @@ async function harness(opts: { calls: ((input: CulpritInput) => Awaited<ReturnTy
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 });
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) => {
@@ -145,7 +142,7 @@ test('범인찾기 서버: 권한 · 분석 · 근거 확인 · 결과 저장 ·
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']);
assert.deepEqual(h.stages(), ['thinking', 'verify', 'done']);
// 보낸 프롬프트: 지시문 + 발로란트 지식 묶음(파일 스냅샷) + 말투 중간맛, 경기 자료는 <match> 안
const sent = h.seen[0];
@@ -154,6 +151,10 @@ test('범인찾기 서버: 권한 · 분석 · 근거 확인 · 결과 저장 ·
assert.match(sent.system, /<knowledge game="valorant">[\s\S]*## 자동 갱신 \(2026-10-15 스냅샷\)/);
assert.ok(!sent.system.includes('<!--'), 'HTML 주석은 빼고 보낸다');
assert.match(sent.user, /^<match>\n# 경기 발로란트 /);
// 기록 점수(OP.GG 계산법)는 앱이 경기 기록으로 계산해 자료에 넣는다 (외부 사이트 접속 없음)
assert.match(sent.user, /\n# 기록 점수 \(0~10, OP\.GG OP스코어 계산법: 라운드 승률 · KAST · ACS · 피해 격차로 계산/);
assert.match(sent.system, /평점은 기록 점수에서 출발한다/);
assert.ok(!/OP\.GG 실제/.test(sent.system + sent.user));
assert.equal(sent.effort, 'high');
assert.equal(sent.maxTokens, 32000);
assert.equal(sent.schema.type, 'object');
@@ -290,159 +291,3 @@ test('범인찾기: 결과 확인 규칙 · 비용 계산 · 프롬프트 조립
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);
});