범인찾기 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>
This commit is contained in:
EJClaw
2026-10-15 14:27:59 +09:00
parent de64f9818d
commit dc67f2105b
17 changed files with 1241 additions and 85 deletions

View File

@@ -4,78 +4,9 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import type { CulpritInput, CulpritMatchInfo, CulpritMatchItem } from '@gvr/shared';
import { Store } from '../src/core/db/db.ts';
import { Timeline } from '../src/core/timeline.ts';
import { GameAssets } from '../src/core/games/assets.ts';
import { GameManager } from '../src/core/games/manager.ts';
import { Culprit } from '../src/core/culprit.ts';
import { buildApi } from '../src/core/api/server.ts';
import { Bus } from '../src/core/util/events.ts';
import { SettingsStore, DEFAULT_TTS_TEXT } from '../src/core/settings.ts';
import { makeDemoLol, makeDemoValorant, AGENT } from './fixtures/demo-matches.ts';
const MIN = 60000;
function setup() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gvr-culprit-'));
const store = new Store(path.join(dir, 'db.sqlite'));
const timeline = new Timeline(store);
const assets = new GameAssets(path.join(dir, 'cache'));
// 네트워크 없이: 요원 이름 · 역할만 넣어 둔다
assets.val = {
at: Date.now(),
agents: {
[AGENT.jett]: { name: '제트', icon: '', role: '타격대', abilities: {} },
[AGENT.sage]: { name: '세이지', icon: '', role: '감시자', abilities: {} },
},
maps: {},
weapons: {},
tiers: {},
modes: {},
clientVersion: null,
} as any;
const bus = new Bus();
const stt: any = { onMatchStart: async () => undefined, onMatchEnd: async () => undefined };
const worker: any = { on: () => undefined, off: () => undefined };
const games = new GameManager(store, assets, worker, stt, timeline, bus, () => ({}) as any, () => null);
const culprit = new Culprit(store, timeline, games);
return { dir, store, timeline, assets, bus, games, culprit };
}
/** 발로란트 시연 경기 + 녹음 세션 + 대화 4문장 */
function seedValorant(ctx: ReturnType<typeof setup>, opts: { sessionStartOffsetMs?: number; pending?: boolean } = {}) {
const { store, games } = ctx;
const VS = Date.now() - 3 * 3600_000;
const md = makeDemoValorant(VS);
const id = 'val-demo';
const users = [
{ id: 'u1', name: '승한', puuid: 'p-sh' },
{ id: 'u2', name: '민수', puuid: 'p-ms' },
{ id: 'u9', name: '도윤', puuid: null },
];
for (const u of users) {
store.upsertUser({ id: u.id, name: u.name, avatar: null });
if (u.puuid) store.setAccounts(u.id, [{ puuid: u.puuid, riotId: `${u.name}#X` }]);
}
store.startSession('s1', 'g', 'c', '음성', VS - 5 * MIN + (opts.sessionStartOffsetMs ?? 0));
games.matchStarted({ id, game: 'valorant', startedAt: VS, map: md.matchInfo.mapId, mode: 'competitive', queue: 'competitive', detail: { live: true } });
games.matchEnded(id, VS + md.matchInfo.gameLengthMillis);
(games.adapters[0] as any).applyDetails(id, md, 'p-sh', VS);
const rounds = store.rounds(id);
const say = (uid: string, round: number, sec: number, text: string, status = 'realtime') => {
const ts = rounds[round - 1].combat_at + sec * 1000;
const uid2 = `${uid}-${round}-${sec}`;
store.insertUtterance({ id: uid2, session_id: 's1', user_id: uid, started_at: ts, ended_at: ts + 1500, audio_path: null, match_id: id });
if (status !== 'pending')
store.updateUtteranceResult(uid2, { text, raw_text: text, words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 0, model: 'small', status: status as any });
};
say('u1', 3, 5, '현우야 같이 가 기다려 둘 있어');
say('u2', 3, 9, '아 그냥 간다 내가 뚫을게');
say('u9', 5, 2, '나 돈 없어 세이브할게');
say('u1', 7, 4, '스파이크 설치됐어 해체 들어가', opts.pending ? 'pending' : 'realtime');
store.endSession('s1', VS + md.matchInfo.gameLengthMillis + 5 * MIN);
return { id, VS, md };
}
import { makeDemoLol } from './fixtures/demo-matches.ts';
import { culpritApi, MIN, seedValorant, setup } from './fixtures/culprit-seed.ts';
test('범인찾기: 발로란트 추가 지표 저장 (피해량 · 첫킬 · 설치 · 역할 · 라운드별 장비)', () => {
const ctx = setup();
@@ -181,18 +112,7 @@ test('범인찾기: 롤 포지션 · 시야 · 10/15분 지표와 골드 차', (
test('범인찾기 API: 목록 · 상세 · 내부 전용 경로', async () => {
const ctx = setup();
const { id } = seedValorant(ctx);
const api = await buildApi({
store: ctx.store,
timeline: ctx.timeline,
games: ctx.games,
dict: {} as any,
culprit: ctx.culprit,
bus: ctx.bus,
settings: () => ({}) as any,
trainingDir: () => ctx.dir,
overviewExtra: () => ({ guild: null, recording: { active: false, channel: null, since: null, participants: [] } }),
version: 'test',
});
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');

92
app/test/fixtures/culprit-seed.ts vendored Normal file
View File

@@ -0,0 +1,92 @@
// 범인찾기 테스트용: 앱 코어 일부(기록 DB · 타임라인 · 게임 관리 · 범인찾기)와 시연 경기 (앱 · 사이트 서버 테스트가 같이 쓴다)
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { Store } from '../../src/core/db/db.ts';
import { Timeline } from '../../src/core/timeline.ts';
import { GameAssets } from '../../src/core/games/assets.ts';
import { GameManager } from '../../src/core/games/manager.ts';
import { Culprit } from '../../src/core/culprit.ts';
import { buildApi } from '../../src/core/api/server.ts';
import { Bus } from '../../src/core/util/events.ts';
import { makeDemoValorant, AGENT } from './demo-matches.ts';
export const MIN = 60000;
export function setup() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gvr-culprit-'));
const store = new Store(path.join(dir, 'db.sqlite'));
const timeline = new Timeline(store);
const assets = new GameAssets(path.join(dir, 'cache'));
// 네트워크 없이: 요원 이름 · 역할만 넣어 둔다
assets.val = {
at: Date.now(),
agents: {
[AGENT.jett]: { name: '제트', icon: '', role: '타격대', abilities: {} },
[AGENT.sage]: { name: '세이지', icon: '', role: '감시자', abilities: {} },
},
maps: {},
weapons: {},
tiers: {},
modes: {},
clientVersion: null,
} as any;
const bus = new Bus();
const stt: any = { onMatchStart: async () => undefined, onMatchEnd: async () => undefined };
const worker: any = { on: () => undefined, off: () => undefined };
const games = new GameManager(store, assets, worker, stt, timeline, bus, () => ({}) as any, () => null);
const culprit = new Culprit(store, timeline, games);
return { dir, store, timeline, assets, bus, games, culprit };
}
/** 발로란트 시연 경기 + 녹음 세션 + 대화 4문장 */
export function seedValorant(ctx: ReturnType<typeof setup>, opts: { sessionStartOffsetMs?: number; pending?: boolean } = {}) {
const { store, games } = ctx;
const VS = Date.now() - 3 * 3600_000;
const md = makeDemoValorant(VS);
const id = 'val-demo';
const users = [
{ id: 'u1', name: '승한', puuid: 'p-sh' },
{ id: 'u2', name: '민수', puuid: 'p-ms' },
{ id: 'u9', name: '도윤', puuid: null },
];
for (const u of users) {
store.upsertUser({ id: u.id, name: u.name, avatar: null });
if (u.puuid) store.setAccounts(u.id, [{ puuid: u.puuid, riotId: `${u.name}#X` }]);
}
store.startSession('s1', 'g', 'c', '음성', VS - 5 * MIN + (opts.sessionStartOffsetMs ?? 0));
games.matchStarted({ id, game: 'valorant', startedAt: VS, map: md.matchInfo.mapId, mode: 'competitive', queue: 'competitive', detail: { live: true } });
games.matchEnded(id, VS + md.matchInfo.gameLengthMillis);
(games.adapters[0] as any).applyDetails(id, md, 'p-sh', VS);
const rounds = store.rounds(id);
const say = (uid: string, round: number, sec: number, text: string, status = 'realtime') => {
const ts = rounds[round - 1].combat_at + sec * 1000;
const uid2 = `${uid}-${round}-${sec}`;
store.insertUtterance({ id: uid2, session_id: 's1', user_id: uid, started_at: ts, ended_at: ts + 1500, audio_path: null, match_id: id });
if (status !== 'pending')
store.updateUtteranceResult(uid2, { text, raw_text: text, words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 0, model: 'small', status: status as any });
};
say('u1', 3, 5, '현우야 같이 가 기다려 둘 있어');
say('u2', 3, 9, '아 그냥 간다 내가 뚫을게');
say('u9', 5, 2, '나 돈 없어 세이브할게');
say('u1', 7, 4, '스파이크 설치됐어 해체 들어가', opts.pending ? 'pending' : 'realtime');
store.endSession('s1', VS + md.matchInfo.gameLengthMillis + 5 * MIN);
return { id, VS, md };
}
/** 앱 로컬 API (사이트 서버가 중계로 부르는 것과 같은 Fastify) */
export function culpritApi(ctx: ReturnType<typeof setup>) {
return buildApi({
store: ctx.store,
timeline: ctx.timeline,
games: ctx.games,
dict: {} as any,
culprit: ctx.culprit,
bus: ctx.bus,
settings: () => ({}) as any,
trainingDir: () => ctx.dir,
overviewExtra: () => ({ guild: null, recording: { active: false, channel: null, since: null, participants: [] } }),
version: 'test',
});
}

View File

@@ -18,6 +18,8 @@ COPY site/server/package.json site/server/package-lock.json ./
RUN npm ci --omit=dev --no-audit --no-fund && npm cache clean --force
COPY --from=build /src/site/server/dist ./dist
COPY --from=build /src/site/web/dist ./web
# 범인찾기 지시문 · 지식 묶음 (dist/main.js 가 ../prompt 에서 읽는다)
COPY site/server/prompt ./prompt
VOLUME /data
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=5s CMD wget -qO- http://127.0.0.1:8080/healthz || exit 1

View File

@@ -13,5 +13,7 @@ print(f"DISCORD_BOT_TOKEN={c['token']}")
print(f"SESSION_SECRET={secrets.token_urlsafe(48)}")
print("ALLOWED_GUILD_IDS=457514742940958731")
print("OWNER_DISCORD_IDS=293719842274541579")
a = json.load(open('/home/claude/.config/ejclaw/secrets.json'))['credentials'].get('anthropic.api/game-voice-recorder')
if a: print(f"ANTHROPIC_API_KEY={a['token']}")
PY
echo ".env 작성 완료"

View File

@@ -0,0 +1,11 @@
#!/usr/bin/env bash
# 범인찾기 Claude API 키를 .5 의 사이트 서버 .env 에 넣거나 바꾼다 (다른 값 · 로그인 세션은 그대로).
# 키는 secrets.json 에서 읽어 원격에 바로 쓰고, 로컬 파일 · 명령줄에 남기지 않는다. 적용: deploy/site/deploy.sh
set -euo pipefail
HOST=root@192.168.10.5
DIR=/root/other/game-voice-recorder
python3 - <<'PY' | ssh -o BatchMode=yes $HOST "cd $DIR && test -f .env && umask 077 && grep -v '^ANTHROPIC_API_KEY=' .env > .env.new; cat >> .env.new && mv .env.new .env && chmod 600 .env"
import json
print(f"ANTHROPIC_API_KEY={json.load(open('/home/claude/.config/ejclaw/secrets.json'))['credentials']['anthropic.api/game-voice-recorder']['token']}")
PY
echo "ANTHROPIC_API_KEY 설정 완료"

View File

@@ -8,6 +8,7 @@
"name": "gvr-site-server",
"version": "1.0.0",
"dependencies": {
"@anthropic-ai/sdk": "^0.134.0",
"@fastify/cookie": "^11.0.2",
"@fastify/static": "^8.2.0",
"discord.js": "^14.27.0",
@@ -22,6 +23,35 @@
"typescript": "^5.9.3"
}
},
"node_modules/@anthropic-ai/sdk": {
"version": "0.134.0",
"resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.134.0.tgz",
"integrity": "sha512-j0DNXXKUKkr3kKyVR/I3pPWVv93g7vgHjgGYgh9uCXv5IKoXZPWmTwXKiVq/SZSbhBaD3KmtKhIszzt8dBnzog==",
"dependencies": {
"@opentelemetry/api": "^1.4.1",
"json-schema-to-ts": "^3.1.1",
"standardwebhooks": "^1.0.0"
},
"bin": {
"anthropic-ai-sdk": "bin/cli"
},
"peerDependencies": {
"zod": "^3.25.0 || ^4.0.0"
},
"peerDependenciesMeta": {
"zod": {
"optional": true
}
}
},
"node_modules/@babel/runtime": {
"version": "7.29.10",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.10.tgz",
"integrity": "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@discordjs/builders": {
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.14.1.tgz",
@@ -790,6 +820,14 @@
"node": ">=8"
}
},
"node_modules/@opentelemetry/api": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz",
"integrity": "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==",
"engines": {
"node": ">=8.0.0"
}
},
"node_modules/@pinojs/redact": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
@@ -825,6 +863,11 @@
"npm": ">=7.0.0"
}
},
"node_modules/@stablelib/base64": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz",
"integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ=="
},
"node_modules/@types/node": {
"version": "22.20.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
@@ -1117,6 +1160,11 @@
"fast-decode-uri-component": "^1.0.1"
}
},
"node_modules/fast-sha256": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz",
"integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ=="
},
"node_modules/fast-uri": {
"version": "4.2.2",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-4.2.2.tgz",
@@ -1321,6 +1369,18 @@
"dequal": "^2.0.3"
}
},
"node_modules/json-schema-to-ts": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",
"integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",
"dependencies": {
"@babel/runtime": "^7.18.3",
"ts-algebra": "^2.0.0"
},
"engines": {
"node": ">=16"
}
},
"node_modules/json-schema-traverse": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
@@ -1658,6 +1718,15 @@
"node": ">= 10.x"
}
},
"node_modules/standardwebhooks": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.1.1.tgz",
"integrity": "sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==",
"dependencies": {
"@stablelib/base64": "^1.0.0",
"fast-sha256": "^1.3.0"
}
},
"node_modules/statuses": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
@@ -1693,6 +1762,11 @@
"node": ">=0.6"
}
},
"node_modules/ts-algebra": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",
"integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw=="
},
"node_modules/ts-mixer": {
"version": "6.0.4",
"resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz",

View File

@@ -12,6 +12,7 @@
"test": "node --import tsx --test test/*.test.ts"
},
"dependencies": {
"@anthropic-ai/sdk": "^0.134.0",
"@fastify/cookie": "^11.0.2",
"@fastify/static": "^8.2.0",
"discord.js": "^14.27.0",

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,42 @@
<!-- 발로란트 지식 묶음 v1 (초안, 2026-10-15). system 프롬프트 뒤에 <knowledge> 로 붙인다.
"자동 갱신" 칸은 valorant-api.com(ko-KR)에서 패치마다 다시 만든다 (tools/gen-dictionary.mjs 와 같은 소스). 아래는 2026-10-15 스냅샷. -->
<knowledge game="valorant">
## 경기 규칙
- 13라운드를 먼저 이기면 승리. 12:12 이면 연장(경쟁전은 2라운드 차가 날 때까지). 12라운드 뒤 공수 교대.
- 1라운드와 13라운드는 권총 라운드. 라운드는 구매 시간 30초 + 교전 1분 40초. 스파이크 설치 뒤 45초면 폭발, 해체는 7초(절반 지점 저장).
- 공격: 스파이크 설치나 전멸로 승리. 수비: 전멸, 해체, 시간 초과로 승리.
## 경제 (패치에 따라 조금 바뀔 수 있음)
- 시작 800, 라운드 승리 3,000, 패배 1,900 → 연패마다 +500 (최대 2,900), 킬 200, 설치 300(공격팀 전원). 최대 9,000.
- 풀바이 = 라이플(밴달·팬텀 2,900) 또는 오퍼레이터(4,700) + 실드 + 스킬, 대략 3,900 이상. 에코(세이브) = 거의 안 삼. 포스바이 = 돈이 모자라도 삼. 하프바이 = 중간.
- 팀이 같이 세이브하는 건 정상 운영이다. 혼자만 사거나 혼자만 안 사서 팀 경제가 어긋나면 감점.
- 상대가 에코인 라운드를 지는 것은 큰 손실. 에코 라운드에서 딴 킬은 가치가 낮다.
## 역할별 기준
- 타격대(제트·레이즈·레이나 등): 진입해서 첫 교전을 열고 공간을 만든다. 첫 데스가 많아도 팀이 바로 복수(트레이드)하면 정상. 트레이드도 안 되는 혼자 진입이 반복되면 감점.
- 척후대(소바·브리치·스카이 등): 정보와 진입 보조. 어시스트, 정찰 정보 콜이 중요.
- 전략가(오멘·브림스톤·아스트라 등): 연막으로 시야를 끊어 진입·리테이크를 돕는다. 오래 살아남는 것이 중요. 킬이 적어도 정상.
- 감시자(킬조이·사이퍼·세이지 등): 사이트 수비, 측면 차단, 리테이크. 전투 점수가 낮은 게 흔하다. 세이지 부활은 큰 기여.
- 역할이 겹치면(타격대 3명 등) 판단을 팀 구성 탓으로 돌리지 말고 각자 맡은 일을 했는지 본다.
## 지표
- 전투 점수(ACS): 라운드당 평균. 보통 200 안팎, 250 넘으면 높음, 150 아래면 낮음.
- 라운드당 피해량: 보통 130~150. 첫 킬 · 첫 데스: 라운드 첫 교전 결과로 라운드 승률에 크게 영향.
- 클러치: 혼자 남아 여러 명을 상대로 라운드를 이김. 멀티킬 · 에이스(5킬).
- 막판 정리 킬(이미 진 라운드에서 도망가는 적을 잡음)은 숫자를 부풀린다.
## 콜아웃 · 은어 (음성·채팅에 나오는 말)
- 장소: A/B/C 사이트, 메인, 롱, 숏(쇼트), 미드, 헤븐, 마켓, 로비, 링크, 백사이트, 개구멍, 문, 계단, 창문, 엘보, 지붕, 하수구, 텔레포터, 로프, 파이프, 정원, 트리, 박스, 기둥.
- 전투: 원탭/투탭(머리 한두 발), 헤드, 퍼블·첫킬, 각(사격 위치), 피킹(엄폐물에서 나와 쏨), 프리파이어(미리 쏨), 트레이드(복수 킬), 리테이크(설치 뒤 사이트 탈환), 로테(다른 사이트로 이동), 스택(한 사이트에 몰림), 디폴트(흩어져 정보 수집), 러시·패스트(빠른 진입), 원웨이(한쪽만 보이는 연막), 몰리(화염), 플래시·섬광, 연막·스모크, 궁(궁극기), 오브.
- 상태: "하나 남았어"(적 1명), "피 30"(체력 30), "깎였어"(맞음), "세이브해"(무기 아끼고 살아라), "에코/이코", "풀바이", "포스".
- 태도: ㅈㅈ·ff(포기), "던졌네"(실수로 경기를 망침), "버스 탔다"(남이 이겨 줌).
## 음성 인식이 자주 틀리는 말
레이저→레이즈, 비 싸이트→B 사이트, 에이 싸이트→A 사이트, 로태→로테, 오퍼래이터→오퍼레이터, 반달→밴달, 펜텀→팬텀, 쉐리프·세리프→셰리프, 디퓨저→디퓨즈, 킬 조이→킬조이, 브림 스톤→브림스톤, 아스트로→아스트라, 클로버→클로브.
숫자·알파벳 콜아웃(A, B, 피 30)은 한글로 받아 적히거나("에이", "비") 빠지기 쉽다.
## 자동 갱신 (2026-10-15 스냅샷)
- 요원 (역할): 척후대: 게코, 브리치, 소바, 스카이, 케이/오, 테호, 페이드 / 감시자: 데드록, 바이스, 비토, 사이퍼, 세이지, 체임버, 킬조이 / 타격대: 네온, 레이나, 레이즈, 아이소, 요루, 웨이레이, 제트, 피닉스 / 전략가: 믹스, 바이퍼, 브림스톤, 아스트라, 오멘, 클로브, 하버
- 맵: 어센트, 스플릿, 프랙처, 바인드, 브리즈, 어비스, 로터스, 선셋, 펄, 서밋, 아이스박스, 코로드, 헤이븐
- 무기 (가격): 오딘 3200, 아레스 1600, 밴달 2900, 워든 2900, 불독 2050, 팬텀 2900, 저지 1850, 버키 850, 프렌지 450, 클래식 0, 밴딧 600, 고스트 500, 셰리프 800, 쇼티 300, 오퍼레이터 4700, 가디언 2250, 아웃로 2400, 마샬 950, 스펙터 1600, 스팅어 1100
</knowledge>

View File

@@ -0,0 +1,52 @@
{
"type": "object",
"additionalProperties": false,
"required": ["summary", "confidence", "confidence_note", "teams", "players"],
"properties": {
"summary": { "type": "string", "description": "경기 한 줄 요약, 1~2문장" },
"confidence": { "type": "string", "enum": ["high", "medium", "low"] },
"confidence_note": { "type": "string", "description": "confidence 가 medium/low 인 이유. high 면 빈 문자열" },
"teams": {
"type": "array",
"description": "우리 팀, 상대 팀 순서로 2개",
"items": {
"type": "object",
"additionalProperties": false,
"required": ["team", "culprit", "reason", "evidence"],
"properties": {
"team": { "type": "string", "enum": ["ally", "enemy"] },
"culprit": { "type": "string", "description": "P1~P10" },
"reason": { "type": "string", "description": "2~3문장" },
"evidence": { "type": "array", "items": { "$ref": "#/$defs/evidence" } }
}
}
},
"players": {
"type": "array",
"description": "P1~P10 순서로 10명",
"items": {
"type": "object",
"additionalProperties": false,
"required": ["id", "score", "tag", "comment", "evidence"],
"properties": {
"id": { "type": "string", "description": "P1~P10" },
"score": { "type": "number", "description": "1.0~10.0, 0.5 단위" },
"tag": { "type": "string", "enum": ["캐리", "숨은 MVP", "클러치", "무난", "아쉬움", "범인"] },
"comment": { "type": "string", "description": "한 줄 평, 40자 안팎" },
"evidence": { "type": "array", "items": { "$ref": "#/$defs/evidence" } }
}
}
}
},
"$defs": {
"evidence": {
"type": "object",
"additionalProperties": false,
"required": ["ref", "note"],
"properties": {
"ref": { "type": "string", "description": "자료의 근거 번호: e123 · u456 · c7 · r21 · s:P4" },
"note": { "type": "string", "description": "이 근거가 뜻하는 것. 대화면 원문 인용" }
}
}
}
}

View File

@@ -0,0 +1,66 @@
<!-- 겜녹이 범인찾기 시스템 프롬프트 v1.1 (2026-10-15, 사용자 결정 반영: 범인 = 종합 판단, 말투 기본 중간맛)
서버가 이 파일 + 게임별 knowledge-*.md 를 system 에 넣고, 경기 자료는 user 메시지로 보낸다.
{{tone}} 은 말투 설정(mild|medium|spicy)으로 바꾼다. 이 파일과 knowledge 는 경기마다 같아서 프롬프트 캐시 대상이다. -->
너는 겜녹이의 경기 분석가다. 디스코드 친구들이 함께 한 발로란트 또는 리그 오브 레전드 경기 한 판의 기록을 읽고, 참가자 10명을 평가하고 팀마다 "범인"을 한 명씩 고른다. 결과는 친구들이 재미로 보는 사이트에 그대로 뜬다. 정확하고 공정해야 웃고 넘길 수 있다.
<input_format>
user 메시지의 <match> 안에 경기 자료가 온다.
- 경기: 게임, 모드, 맵, 최종 점수, 길이. "우리 팀" = 음성을 녹음한 쪽 팀, "상대 팀" = 다른 팀.
- 참가자: P1~P10 번호, 이름, 팀, 요원·챔피언과 역할(포지션), 스탯, 음성 유무(음성O / 음성X).
- 시간 순서의 줄. 줄 앞 번호가 근거 번호다.
- [e번호] 게임 이벤트 (킬, 스파이크, 오브젝트, 라운드 결과 등)
- [u번호] 음성 문장. 디스코드 음성채널에서 자동 음성 인식으로 받아 적은 것이라 글자가 틀릴 수 있다.
- [c번호] 인게임 채팅 (팀 / 전체)
- [r번호] 라운드 요약 (발로란트): 우리 팀 공격/수비, 승패와 끝난 이유, 점수, 팀 평균 장비 값, "선수 장비/피해" = 그 라운드 장비 값(k=1,000 크레드)/준 피해
- [s:P번호] 그 사람의 경기 전체 스탯 (참가자 줄)
- 줄의 시간: 발로란트 "R7 0:42" = 7라운드 교전 시작 뒤 42초("R7 구매" = 구매 시간), 롤 "12:18" = 게임 시간.
- 참가자 줄 약어: ACS = 라운드당 전투 점수, ADR = 라운드당 준 피해, HS = 헤드샷 비율, 롤 "10분 78·3450" = 10분 CS·골드. "?" 는 기록 없음.
- "(게임 계정 모름)" 이 붙은 화자는 디스코드 이름만 알고 어느 참가자인지 모른다. 참가자 평가에 그 사람 말을 붙이지 않는다.
- "기본 기록만 있다" 고 적힌 경기는 피해량·첫킬·시야 같은 지표가 없다. 없는 지표로 판단하지 않는다.
- 음성은 봇이 있던 음성채널 사람만 있다. 상대 팀은 보통 음성이 없다.
</input_format>
<task>
1. 경기 흐름을 먼저 파악한다. 어느 라운드·시간대에서 승부가 갈렸는지 찾는다.
2. 10명 모두 평가한다: 평점(1.0~10.0, 0.5 단위), 태그 하나, 한 줄 평(40자 안팎).
3. 팀마다 범인을 한 명씩 고른다. 범인은 아래를 모두 합쳐 종합으로 판단한다. 한 가지만 보지 않는다.
- 가장 못한 사람: 자기 역할·포지션 기준으로 플레이가 가장 나빴다.
- 가장 발목을 잡은 사람: 팀의 계획·경제·콜을 가장 많이 망쳤다.
- 결과의 원인: 진 팀이면 패배에 가장 큰 책임, 이긴 팀이면 이기는 데 가장 방해가 된 사람.
- 범인은 그 팀에서 평점이 가장 낮아야 한다. 동점이면 근거가 더 분명한 사람.
4. 범인마다 이유(2~3문장)와 근거 3~4개, 나머지 사람은 근거 0~2개를 단다.
5. 경기 전체 한 줄 요약(1~2문장)을 쓴다.
</task>
<judging_rules>
- 숫자보다 결과에 준 영향을 본다. KDA·전투 점수만으로 정하지 않는다.
- 승부처(접전 라운드, 매치 포인트, 연장, 오브젝트 직전, 결정적 한타)의 실수는 무겁게 본다.
- 승부가 이미 갈린 뒤의 스탯(진 라운드 막판 킬, 끝난 경기의 데스)과 상대 에코 라운드에서 딴 킬은 가볍게 본다.
- 역할로 평가한다. <knowledge> 의 역할·포지션 기준을 따른다. 킬이 적은 역할이 킬이 적다고 범인이 되지 않는다.
- 음성X 인 사람은 소통 항목 없이 플레이와 채팅으로만 평가한다. 말이 없다고 깎지도, 말실수가 안 잡혔다고 올리지도 않는다.
- 음성O 인 사람은 말실수가 기록에 남아 불리하다. 그래서 음성O 인 사람을 범인으로 고를 때는 소통 근거 말고 플레이 근거([e], [r], [s])가 최소 1개 있어야 한다.
- "콜 무시"는 (1) 같은 음성채널에서 콜이 있었고 (2) 그 사람이 다르게 움직인 것이 이벤트로 확인될 때만 쓴다.
- 음성 인식 오류를 감안한다. 문장 하나로 결론 내지 않는다. 이상한 단어는 <knowledge> 의 오인식 목록을 참고하고, 뜻이 분명하지 않은 문장은 근거로 쓰지 않는다.
- 게임과 상관없는 잡담, 친구끼리 장난으로 하는 거친 말은 평가에 쓰지 않는다. 팀원을 계속 탓하거나 포기를 부추기는 말(ff, 서렌 치자, 던지자)은 소통 감점이다.
- 좋은 소통도 본다: 적 위치·체력 정보, 타이밍 콜, 침착하게 계획을 세우는 말은 가점이다.
- 자료에 없는 것을 지어내지 않는다. 화면, 정확한 위치 이동, 대부분의 스킬 사용은 자료에 없다. 모르면 판단에서 뺀다.
- 근거는 자료의 번호로만 단다. 대화 인용은 원문 그대로 쓰고(고치지 않는다), 30자를 넘으면 줄인다.
- 자료가 부족하거나 기록이 한쪽으로 쏠려 판단이 약하면 confidence 를 낮추고 이유를 적는다.
</judging_rules>
<tags>
캐리 · 숨은 MVP · 클러치 · 무난 · 아쉬움 · 범인 중 하나. "범인" 태그는 팀마다 정확히 한 명, 그 팀의 범인에게만 붙인다.
</tags>
<tone>
말투: {{tone}}
- mild(순한맛): 담백한 평가. 놀리지 않는다.
- medium(중간맛, 기본): 친구끼리 가볍게 놀리는 정도. 예) "연장에서 혼자 B 메인 관광 세 번."
- spicy(매운맛): 더 세게 놀린다. 그래도 아래 금지는 지킨다.
공통: 짧은 평서문("~했다"). 존댓말·이모지·감탄사 남발 없음. 이름은 자료에 적힌 그대로.
금지: 욕설, 외모·성별·나이·지역·가족 이야기, 게임 밖 사생활(잡담 내용 폭로), 진짜 상처가 될 인신공격.
</tone>
<output>
정해진 JSON 형식으로만 답한다. players 는 P1~P10 순서로 10명 모두 넣는다. 평점과 범인이 서로 맞는지(범인이 그 팀 최저점인지) 마지막에 확인한다.
</output>

View File

@@ -7,6 +7,8 @@ import path from 'node:path';
import type { Config } from './config.js';
import { registerAppAuth } from './app-auth.js';
import { BotBroker, type BotSource } from './bot-broker.js';
import { registerCulprit, type ModelCall } from './culprit.js';
import type { KnowledgeAuto } from './culprit-prompt.js';
import { avatarUrl, DiscordApi } from './discord.js';
import { RateLimiter } from './rate-limit.js';
import { RelayHub } from './relay.js';
@@ -16,7 +18,7 @@ const SID = 'gvr_sid';
const RECHECK_MS = 10 * 60000;
/** botSource: 겜녹이 봇 디스코드 연결 (main.ts 가 discord.js 로 만든다. 없으면 /app/bot/ws 는 503) */
export async function buildServer(cfg: Config, opts: { botSource?: BotSource; botRecheckMs?: number } = {}) {
export async function buildServer(cfg: Config, opts: { botSource?: BotSource; botRecheckMs?: number; culpritCall?: ModelCall; culpritKnowledge?: KnowledgeAuto } = {}) {
const app = Fastify({
logger: {
level: process.env.LOG_LEVEL || 'info',
@@ -174,6 +176,9 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
return r;
});
// ------------------------------------------------------------------ 범인찾기 (Claude API 는 이 서버만 부른다)
const culprit = registerCulprit(app, { cfg, store, hub, requireSession, log: app.log, call: opts.culpritCall, knowledge: opts.culpritKnowledge });
// ------------------------------------------------------------------ 기록 API 중계
const relay = async (req: FastifyRequest, reply: FastifyReply) => {
const s = await requireSession(req, reply);
@@ -281,7 +286,7 @@ export async function buildServer(cfg: Config, opts: { botSource?: BotSource; bo
store.flush();
});
return { app, store, hub, broker };
return { app, store, hub, broker, culprit };
}
/** 로그에 남길 주소: /auth/* 는 쿼리를 지우고 앱 로그인 요청 아이디를 가린다, 다른 주소도 쿼리 값은 지운다 */

View File

@@ -20,8 +20,19 @@ export interface Config {
/** 테스트용: 디스코드 API 주소 바꾸기 */
discordApi: string;
assetUpstream: Record<string, string>;
/** 범인찾기 (Claude API). apiKey 가 없으면 꺼진다 (없으면 CULPRIT_DEFAULTS) */
culprit?: {
apiKey: string | null;
model: string;
effort: 'low' | 'medium' | 'high' | 'xhigh' | 'max';
monthLimitUsd: number;
dailyLimit: number;
tone: 'mild' | 'medium' | 'spicy';
};
}
export const CULPRIT_DEFAULTS: NonNullable<Config['culprit']> = { apiKey: null, model: 'claude-opus-5-5', effort: 'high', monthLimitUsd: 100, dailyLimit: 20, tone: 'medium' };
/** 앱 최고 관리자 (사용자 지정, 고정). SUPER_ADMIN_IDS 환경변수로 더할 수 있다 */
export const SUPER_ADMINS = ['293719842274541579', '1352267557213573160'];
@@ -53,5 +64,14 @@ export function loadConfig(env = process.env): Config {
ddragon: 'https://ddragon.leagueoflegends.com/',
cdragon: 'https://raw.communitydragon.org/',
},
culprit: {
apiKey: env.ANTHROPIC_API_KEY || null,
// 사용자 결정 ③ Opus 5.5 · ⑤ 중간맛. 예산: 월 $100 · 하루 20회 (계획서 7장)
model: env.CULPRIT_MODEL || 'claude-opus-5-5',
effort: (env.CULPRIT_EFFORT as any) || 'high',
monthLimitUsd: Number(env.CULPRIT_MONTH_LIMIT_USD || 100),
dailyLimit: Number(env.CULPRIT_DAILY_LIMIT || 20),
tone: (env.CULPRIT_TONE as any) || 'medium',
},
};
}

View File

@@ -0,0 +1,113 @@
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
/**
* 범인찾기 지시문 · 지식 묶음 (계획서 v1.1 6장, prompt/*.md).
* 지식 묶음의 "## 자동 갱신" 칸은 공식 게임 데이터(valorant-api.com · Riot Data Dragon, 한국어)로 하루에 한 번 다시 만든다.
* 못 받으면 파일에 있는 스냅샷을 그대로 쓴다.
*/
export type Tone = 'mild' | 'medium' | 'spicy';
const TONE_KO: Record<Tone, string> = { mild: 'mild(순한맛)', medium: 'medium(중간맛)', spicy: 'spicy(매운맛)' };
export function promptDir(): string {
if (process.env.PROMPT_DIR) return process.env.PROMPT_DIR;
// 개발: site/server/src → site/server/prompt, 배포: /app/dist → /app/prompt
return path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'prompt');
}
const stripComments = (s: string) => s.replace(/<!--[\s\S]*?-->\n?/g, '').trim();
export function readPromptFile(name: string, dir = promptDir()): string {
return stripComments(fs.readFileSync(path.join(dir, name), 'utf8'));
}
/** 지식 묶음의 "## 자동 갱신 …" 칸을 바꾼다 (없으면 그대로) */
export function replaceAutoSection(knowledge: string, auto: string | null): string {
if (!auto) return knowledge;
const i = knowledge.indexOf('## 자동 갱신');
const j = knowledge.lastIndexOf('</knowledge>');
if (i < 0 || j < i) return knowledge;
return `${knowledge.slice(0, i)}${auto.trim()}\n${knowledge.slice(j)}`;
}
export function buildSystemPrompt(game: 'valorant' | 'lol', tone: Tone, auto: string | null, dir = promptDir()): string {
const system = readPromptFile('system.md', dir).replace('{{tone}}', TONE_KO[tone] ?? TONE_KO.medium);
const knowledge = replaceAutoSection(readPromptFile(game === 'valorant' ? 'knowledge-valorant.md' : 'knowledge-lol.md', dir), auto);
return `${system}\n\n${knowledge}`;
}
export function outputSchema(dir = promptDir()): Record<string, unknown> {
return JSON.parse(fs.readFileSync(path.join(dir, 'output-schema.json'), 'utf8'));
}
// ------------------------------------------------------------------ 자동 갱신
const ROLE_KO: Record<string, string> = { Fighter: '전사', Tank: '탱커', Mage: '마법사', Assassin: '암살자', Marksman: '원거리', Support: '서포터' };
const DAY = 24 * 3600 * 1000;
export class KnowledgeAuto {
private cache: Record<'valorant' | 'lol', { at: number; text: string } | null> = { valorant: null, lol: null };
private inflight: Partial<Record<'valorant' | 'lol', Promise<void>>> = {};
constructor(
private fetchJson: (url: string) => Promise<any> = defaultFetchJson,
private log: { warn: (o: any, m?: string) => void } = { warn: () => undefined },
) {}
/** 하루 지난 칸은 다시 만든다. 실패하면 이전 값(또는 null = 파일 스냅샷) */
async get(game: 'valorant' | 'lol'): Promise<string | null> {
const c = this.cache[game];
if (!c || Date.now() - c.at > DAY) {
this.inflight[game] ??= (game === 'valorant' ? this.buildValorant() : this.buildLol())
.then((text) => {
this.cache[game] = { at: Date.now(), text };
})
.catch((e) => this.log.warn(e, `범인찾기 지식 묶음 자동 갱신 실패 (${game}), 이전 값 사용`))
.finally(() => delete this.inflight[game]);
await this.inflight[game];
}
return this.cache[game]?.text ?? null;
}
async buildValorant(): Promise<string> {
const [agents, maps, weapons] = await Promise.all([
this.fetchJson('https://valorant-api.com/v1/agents?language=ko-KR&isPlayableCharacter=true'),
this.fetchJson('https://valorant-api.com/v1/maps?language=ko-KR'),
this.fetchJson('https://valorant-api.com/v1/weapons?language=ko-KR'),
]);
const byRole = new Map<string, string[]>();
for (const a of agents.data || []) {
const r = a.role?.displayName || '기타';
if (!byRole.has(r)) byRole.set(r, []);
byRole.get(r)!.push(a.displayName);
}
if (!byRole.size) throw new Error('요원 목록이 비었습니다');
// 경쟁 맵만 (미니맵 좌표 변환값이 있는 맵)
const mapNames = [...new Set((maps.data || []).filter((m: any) => m.xMultiplier && m.tacticalDescription).map((m: any) => m.displayName as string))];
const weaponList = (weapons.data || []).map((w: any) => `${w.displayName} ${w.shopData?.cost ?? 0}`);
const today = new Date().toISOString().slice(0, 10);
return [
`## 자동 갱신 (${today}, valorant-api.com)`,
`- 요원 (역할): ${[...byRole.entries()].map(([r, list]) => `${r}: ${list.sort((x, y) => x.localeCompare(y, 'ko')).join(', ')}`).join(' / ')}`,
`- 맵: ${mapNames.join(', ')}`,
`- 무기 (가격): ${weaponList.join(', ')}`,
].join('\n');
}
async buildLol(): Promise<string> {
const versions = await this.fetchJson('https://ddragon.leagueoflegends.com/api/versions.json');
const v = versions[0];
const champs = (await this.fetchJson(`https://ddragon.leagueoflegends.com/cdn/${v}/data/ko_KR/champion.json`)).data;
const list = Object.values<any>(champs)
.map((c) => `${c.name}(${(c.tags || []).map((t: string) => ROLE_KO[t] ?? t).join('/')})`)
.sort((x, y) => x.localeCompare(y, 'ko'));
if (!list.length) throw new Error('챔피언 목록이 비었습니다');
return [`## 자동 갱신 (패치 ${v}, Riot Data Dragon)`, `- 챔피언 (분류): ${list.join(' · ')}`].join('\n');
}
}
async function defaultFetchJson(url: string): Promise<any> {
const r = await fetch(url, { signal: AbortSignal.timeout(20000) });
if (!r.ok) throw new Error(`${url} ${r.status}`);
return r.json();
}

426
site/server/src/culprit.ts Normal file
View File

@@ -0,0 +1,426 @@
import fs from 'node:fs';
import path from 'node:path';
import Anthropic from '@anthropic-ai/sdk';
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
import {
CULPRIT_TAGS,
type CulpritBudget,
type CulpritEligibility,
type CulpritEvidence,
type CulpritInput,
type CulpritResult,
type CulpritStage,
type LiveEvent,
} from '@gvr/shared';
import { CULPRIT_DEFAULTS, type Config } from './config.js';
import { buildSystemPrompt, KnowledgeAuto, outputSchema } from './culprit-prompt.js';
import type { RelayHub } from './relay.js';
import type { ServerStore, Session } from './store.js';
/**
* 범인찾기 서버 쪽 (계획서 v1.1 5장).
* - Claude API 키는 이 서버에만 있다 (환경변수 ANTHROPIC_API_KEY). 앱 · 브라우저로 가지 않는다
* - 순서: 권한 · 예산 · 하루 횟수 · 중복 확인 → 게임 PC 에서 AI 자료 받기 → Claude 호출(구조화 출력) → 근거 번호 확인 → 게임 PC 에 결과 저장
* - 서버에는 비용 장부만 남긴다 (경기 번호 · 누른 사람 · 토큰 수 · 비용 · 시각). 대화 내용은 저장하지 않고 로그에도 남기지 않는다
*/
/** 100만 토큰당 달러 (입력, 출력). 모르는 모델은 비싼 쪽으로 잡는다 */
const PRICES: Record<string, [number, number]> = {
'claude-opus-5-5': [4, 20],
'claude-sonnet-5-5': [2, 10],
'claude-haiku-4-5': [1, 5],
'claude-opus-5': [5, 25],
'claude-opus-4-8': [5, 25],
};
const UNKNOWN_PRICE: [number, number] = [5, 25];
/** 출력 상한 (생각 포함). 경기 하나가 약 $1 을 넘지 않게 (계획서 7장) */
const MAX_TOKENS = 32000;
const DEFAULT_ESTIMATE = 0.45;
export interface Usage {
model: string;
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
}
export function costOf(usages: Usage[]): number {
let usd = 0;
for (const u of usages) {
const [inp, out] = PRICES[u.model] ?? PRICES[u.model.replace(/-\d{8}$/, '')] ?? UNKNOWN_PRICE;
usd += (u.input * inp + u.cacheWrite * inp * 1.25 + u.cacheRead * inp * 0.1 + u.output * out) / 1e6;
}
return Math.round(usd * 10000) / 10000;
}
/** Claude 를 부르는 부분 (테스트에서 바꿔 끼운다) */
export interface ModelCall {
(req: { model: string; system: string; user: string; schema: Record<string, unknown>; effort: string; maxTokens: number }): Promise<{
text: string | null;
stopReason: string | null;
usages: Usage[];
fallback: boolean;
}>;
}
export function anthropicCall(apiKey: string): ModelCall {
const client = new Anthropic({ apiKey, timeout: 6 * 60000, maxRetries: 2 });
return async (req) => {
const stream = client.beta.messages.stream({
model: req.model,
max_tokens: req.maxTokens,
thinking: { type: 'adaptive' },
output_config: { effort: req.effort as any, format: { type: 'json_schema', schema: req.schema } },
// 안전 분류기가 거절하면 서버가 권장 모델로 한 번 다시 돌린다
betas: ['server-side-fallback-2026-07-01'],
fallbacks: 'default',
system: [{ type: 'text', text: req.system, cache_control: { type: 'ephemeral' } }],
messages: [{ role: 'user', content: req.user }],
});
const msg = await stream.finalMessage();
const iters = (msg.usage.iterations ?? []) as any[];
const usages: Usage[] = iters.length
? iters.map((it) => ({
model: it.model || msg.model,
input: it.input_tokens ?? 0,
output: it.output_tokens ?? 0,
cacheRead: it.cache_read_input_tokens ?? 0,
cacheWrite: it.cache_creation_input_tokens ?? 0,
}))
: [
{
model: msg.model,
input: msg.usage.input_tokens,
output: msg.usage.output_tokens,
cacheRead: msg.usage.cache_read_input_tokens ?? 0,
cacheWrite: msg.usage.cache_creation_input_tokens ?? 0,
},
];
const text = msg.content
.filter((b: any) => b.type === 'text')
.map((b: any) => b.text)
.join('');
return { text: text || null, stopReason: msg.stop_reason, usages, fallback: iters.some((it) => it.type === 'fallback_message') };
};
}
// ------------------------------------------------------------------ 결과 확인
/** 근거 번호 모양 맞추기: "[u12]" · "U12" · "s:p4" → "u12" · "s:P4" */
export function normRef(ref: string): string {
const r = String(ref ?? '').trim().replace(/^\[|\]$/g, '');
const s = /^s\s*:\s*p(\d+)$/i.exec(r);
if (s) return `s:P${s[1]}`;
const m = /^([uecr])\s*(\d+)$/i.exec(r);
return m ? `${m[1].toLowerCase()}${m[2]}` : r;
}
const PLAY_REF = /^(e|r|s:)/;
/**
* AI 답을 확인한다: 10명이 빠짐없이 한 번씩, 점수 1~10 (0.5 단위), 태그 목록 안, 팀마다 범인 1명(그 팀 사람, 그 팀 최저점),
* 근거 번호는 이 경기 자료에 있는 것만 (없는 번호는 뺀다). 범인 근거가 하나도 안 남으면 needRetry.
*/
export function checkResult(raw: unknown, input: CulpritInput): { result: CulpritResult | null; problems: string[]; needRetry: boolean } {
const problems: string[] = [];
const r = raw as any;
if (!r || typeof r !== 'object' || !Array.isArray(r.players) || !Array.isArray(r.teams)) return { result: null, problems: ['형식이 맞지 않음'], needRetry: true };
const ids = input.players.map((p) => p.id);
const teamOf = new Map(input.players.map((p) => [p.id, p.team]));
const fixEvidence = (list: any[]): CulpritEvidence[] => {
const out: CulpritEvidence[] = [];
for (const e of Array.isArray(list) ? list : []) {
const ref = normRef(e?.ref);
const target = input.refs[ref];
if (!target) {
problems.push(`없는 근거 ${String(e?.ref)}`);
continue;
}
if (out.some((x) => x.ref === ref)) continue;
out.push({ ref, note: String(e?.note ?? '').slice(0, 300), target });
}
return out;
};
const players: CulpritResult['players'] = [];
for (const id of ids) {
const p = r.players.find((x: any) => String(x?.id).toUpperCase() === id);
if (!p) return { result: null, problems: [...problems, `${id} 평가 없음`], needRetry: true };
let score = Number(p.score);
if (!Number.isFinite(score)) return { result: null, problems: [...problems, `${id} 점수 없음`], needRetry: true };
score = Math.min(10, Math.max(1, Math.round(score * 2) / 2));
const tag = (CULPRIT_TAGS as readonly string[]).includes(p.tag) ? p.tag : '무난';
players.push({ id, score, tag, comment: String(p.comment ?? '').slice(0, 120), evidence: fixEvidence(p.evidence) });
}
const sides = [...new Set(input.players.map((p) => p.team))];
const teams: CulpritResult['teams'] = [];
let needRetry = false;
for (const side of (['ally', 'enemy'] as const).filter((s) => sides.includes(s))) {
const t = r.teams.find((x: any) => x?.team === side);
const culprit = String(t?.culprit ?? '').toUpperCase();
if (!t || teamOf.get(culprit) !== side) return { result: null, problems: [...problems, `${side} 팀 범인이 없거나 다른 팀 사람`], needRetry: true };
const evidence = fixEvidence(t.evidence);
if (!evidence.length) {
problems.push(`${side} 팀 범인 근거가 모두 없는 번호`);
needRetry = true;
}
// 음성O 인 범인은 플레이 근거([e] [r] [s:])가 하나는 있어야 한다 (말이 기록된 사람이 불리하지 않게)
const cp = input.players.find((p) => p.id === culprit)!;
if (cp.voice && evidence.length && !evidence.some((e) => PLAY_REF.test(e.ref))) {
problems.push(`${culprit} 은 음성O 인데 플레이 근거가 없음`);
needRetry = true;
}
teams.push({ team: side, culprit, reason: String(t.reason ?? '').slice(0, 600), evidence });
// 범인 태그는 팀마다 범인 한 명에게만, 범인은 그 팀 최저점
for (const p of players) {
if (teamOf.get(p.id) !== side) continue;
if (p.id === culprit) p.tag = '범인';
else if (p.tag === '범인') p.tag = '아쉬움';
}
const others = players.filter((p) => teamOf.get(p.id) === side && p.id !== culprit);
const me = players.find((p) => p.id === culprit)!;
const min = Math.min(...others.map((p) => p.score));
if (others.length && me.score > min) {
problems.push(`${culprit} 점수 ${me.score} → ${min} (팀 최저점으로)`);
me.score = min;
}
}
const confidence = ['high', 'medium', 'low'].includes(r.confidence) ? r.confidence : 'medium';
return {
result: { summary: String(r.summary ?? '').slice(0, 400), confidence, confidence_note: String(r.confidence_note ?? '').slice(0, 300), teams, players },
problems,
needRetry,
};
}
// ------------------------------------------------------------------ 비용 장부
export interface LedgerEntry {
at: number;
matchId: string;
by: string;
model: string;
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
costUsd: number;
ok: boolean;
/** 하루 횟수에 세는 요청인지 (자동 재시도는 세지 않는다) */
counted: boolean;
}
const kstDate = (t: number) => new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Seoul', year: 'numeric', month: '2-digit', day: '2-digit' }).format(t);
export class Ledger {
private file: string;
private entries: LedgerEntry[];
constructor(dir: string) {
fs.mkdirSync(dir, { recursive: true });
this.file = path.join(dir, 'culprit-ledger.json');
try {
this.entries = JSON.parse(fs.readFileSync(this.file, 'utf8'));
} catch {
this.entries = [];
}
}
add(e: LedgerEntry): void {
this.entries.push(e);
const tmp = this.file + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(this.entries), { mode: 0o600 });
fs.renameSync(tmp, this.file);
}
/** 이번 달(한국 시간) 쓴 돈 */
monthSpent(now = Date.now()): number {
const m = kstDate(now).slice(0, 7);
return Math.round(this.entries.filter((e) => kstDate(e.at).slice(0, 7) === m).reduce((n, e) => n + e.costUsd, 0) * 10000) / 10000;
}
/** 오늘(한국 시간) 누른 횟수 */
todayCount(now = Date.now()): number {
const d = kstDate(now);
return this.entries.filter((e) => e.counted && kstDate(e.at) === d).length;
}
/** 최근 성공한 분석 비용 평균 (예상 비용 표시) */
estimate(): number {
const ok = this.entries.filter((e) => e.ok).slice(-10);
if (!ok.length) return DEFAULT_ESTIMATE;
return Math.round((ok.reduce((n, e) => n + e.costUsd, 0) / ok.length) * 100) / 100;
}
}
// ------------------------------------------------------------------ 서비스
export interface CulpritOptions {
cfg: Config;
store: ServerStore;
hub: RelayHub;
requireSession: (req: FastifyRequest, reply: FastifyReply) => Promise<Session | null>;
log: { info: (o: any, m?: string) => void; warn: (o: any, m?: string) => void; error: (o: any, m?: string) => void };
call?: ModelCall;
knowledge?: KnowledgeAuto;
}
export function registerCulprit(app: FastifyInstance, o: CulpritOptions) {
const { cfg, store, hub, log } = o;
const c = cfg.culprit ?? CULPRIT_DEFAULTS;
const ledger = new Ledger(cfg.dataDir);
const call: ModelCall | null = o.call ?? (c.apiKey ? anthropicCall(c.apiKey) : null);
const knowledge = o.knowledge ?? new KnowledgeAuto(undefined, log);
const running = new Map<string, { by: string; at: number; stage: CulpritStage }>();
/** (가) 등록된 앱 유저 이상만 분석 버튼, 다시 분석은 관리자 이상 (사용자 결정 ②) */
const roleOf = (uid: string): 'superadmin' | 'admin' | 'user' | null =>
cfg.superAdmins.includes(uid) ? 'superadmin' : (store.appUser(uid)?.role ?? null);
const budget = (uid: string): CulpritBudget => {
const role = roleOf(uid);
return {
enabled: !!call,
canAnalyze: !!role,
canReanalyze: role === 'admin' || role === 'superadmin',
monthSpentUsd: ledger.monthSpent(),
monthLimitUsd: c.monthLimitUsd,
todayCount: ledger.todayCount(),
dailyLimit: c.dailyLimit,
estimateUsd: ledger.estimate(),
model: c.model,
running: [...running.keys()],
};
};
const publish = (matchId: string, stage: CulpritStage, message?: string) => {
const r = running.get(matchId);
if (r) r.stage = stage;
hub.publish({ type: 'culprit.progress', data: { matchId, stage, ...(message ? { message } : {}) } } satisfies LiveEvent);
};
const internal = async (method: string, p: string, body: unknown, timeoutMs = 30000) => {
const r = await hub.request(method, p, { 'x-gvr-internal': '1', 'content-type': 'application/json', accept: 'application/json' }, { id: 'server', name: '사이트 서버', avatar: null }, body === null ? null : JSON.stringify(body), timeoutMs);
let data: any = null;
try {
data = JSON.parse(r.body.toString('utf8'));
} catch {
/* JSON 아님 */
}
return { status: r.status, data };
};
app.get('/api/culprit/budget', async (req, reply) => {
const s = await o.requireSession(req, reply);
if (!s) return;
return budget(s.user.id);
});
// 브라우저는 앱의 내부 경로를 부를 수 없다 (중계도 x-gvr-internal 헤더를 넘기지 않지만 한 번 더 막는다)
app.route({ method: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], url: '/api/culprit/internal/*', handler: async (_req, reply) => reply.code(404).send({ error: 'not_found' }) });
app.post<{ Params: { id: string }; Body: { reanalyze?: boolean } }>('/api/culprit/matches/:id/analyze', async (req, reply) => {
const s = await o.requireSession(req, reply);
if (!s) return;
const origin = String(req.headers.origin || '');
if (origin && origin !== cfg.publicUrl) return reply.code(403).send({ error: 'bad_origin' });
const matchId = req.params.id;
if (!/^[\w.:-]{1,80}$/.test(matchId)) return reply.code(400).send({ error: 'bad_id' });
const b = budget(s.user.id);
const reanalyze = !!req.body?.reanalyze;
if (!b.enabled) return reply.code(503).send({ error: 'disabled', message: '범인찾기가 아직 설정되지 않았습니다 (API 키 없음)' });
if (!b.canAnalyze) return reply.code(403).send({ error: 'forbidden', message: '등록된 앱 유저만 분석할 수 있습니다' });
if (reanalyze && !b.canReanalyze) return reply.code(403).send({ error: 'forbidden', message: '다시 분석은 관리자만 할 수 있습니다' });
if (running.has(matchId)) return reply.code(409).send({ error: 'running', message: '이 경기는 이미 분석 중입니다' });
if (b.todayCount >= b.dailyLimit) return reply.code(429).send({ error: 'daily_limit', message: `오늘 분석 횟수(${b.dailyLimit}회)를 다 썼습니다` });
if (b.monthLimitUsd - b.monthSpentUsd < b.estimateUsd) return reply.code(429).send({ error: 'budget', message: '이번 달 분석 예산을 다 썼습니다' });
// 잠금을 먼저 걸고 (동시에 눌러도 한 번만), 게임 PC 에서 분석 자료를 받는다
running.set(matchId, { by: s.user.id, at: Date.now(), stage: 'collect' });
let input: CulpritInput;
try {
const r = await internal('GET', `/api/culprit/internal/${encodeURIComponent(matchId)}/input`, null);
// 예전 앱은 이 경로가 없다 (Fastify 기본 404 { error: 'Not Found' })
if (r.status === 404 && r.data?.error === 'not_found') throw Object.assign(new Error('not_found'), { code: 'not_found' });
if (r.status === 404) throw Object.assign(new Error('old_app'), { code: 'old_app' });
if (r.status === 409) throw Object.assign(new Error('not_ready'), { code: 'not_ready', eligibility: r.data?.eligibility });
if (r.status !== 200 || !r.data?.input) throw new Error(`input ${r.status}`);
const elig = r.data.eligibility as CulpritEligibility;
if (elig.state === 'done' && !reanalyze) throw Object.assign(new Error('done'), { code: 'done' });
input = r.data.input;
} catch (e: any) {
running.delete(matchId);
if (e.message === 'device_offline') return reply.code(503).send({ error: 'device_offline', message: '게임 PC 가 꺼져 있습니다' });
if (e.code === 'old_app') return reply.code(426).send({ error: 'old_app', message: '게임 PC 앱을 업데이트해 주세요' });
if (e.code === 'not_found') return reply.code(404).send({ error: 'not_found' });
if (e.code === 'not_ready') return reply.code(409).send({ error: 'not_ready', eligibility: e.eligibility, message: e.eligibility?.reasons?.join(', ') || '분석할 수 없는 경기입니다' });
if (e.code === 'done') return reply.code(409).send({ error: 'done', message: '이미 분석한 경기입니다. 다시 분석은 관리자만 할 수 있습니다' });
log.error(e, '범인찾기 자료 받기 실패');
return reply.code(502).send({ error: 'input_failed' });
}
publish(matchId, 'thinking');
void run(matchId, input, { id: s.user.id, name: s.user.name }).finally(() => running.delete(matchId));
return reply.code(202).send({ ok: true });
});
/** AI 분석 (버튼 응답 뒤에 돈다. 창을 닫아도 계속, 끝나면 실시간 알림) */
async function run(matchId: string, input: CulpritInput, by: { id: string; name: string }): Promise<void> {
const started = Date.now();
const usages: Usage[] = [];
let fallback = false;
try {
const system = buildSystemPrompt(input.game, c.tone, await knowledge.get(input.game));
const schema = outputSchema();
const user = `<match>\n${input.text}\n</match>`;
let checked: ReturnType<typeof checkResult> | null = null;
for (let attempt = 1; attempt <= 2; attempt++) {
if (attempt > 1 && c.monthLimitUsd - ledger.monthSpent() < ledger.estimate()) break;
const res = await call!({ model: c.model, system, user, schema, effort: c.effort, maxTokens: MAX_TOKENS });
usages.push(...res.usages);
fallback ||= res.fallback;
const cost = costOf(res.usages);
ledger.add({ at: Date.now(), matchId, by: by.id, model: res.usages.at(-1)?.model ?? c.model, ...sumUsage(res.usages), costUsd: cost, ok: res.stopReason === 'end_turn', counted: attempt === 1 });
if (res.stopReason === 'refusal') throw new Error('AI 가 이 경기 분석을 거절했습니다');
if (res.stopReason === 'max_tokens') throw new Error('AI 답이 너무 길어 잘렸습니다');
publish(matchId, 'verify');
let parsed: unknown = null;
try {
parsed = JSON.parse(res.text ?? '');
} catch {
/* 아래에서 다시 시도 */
}
checked = checkResult(parsed, input);
if (checked.problems.length) log.warn({ matchId, attempt, problems: checked.problems.slice(0, 10) }, '범인찾기 결과 확인');
if (checked.result && !checked.needRetry) break;
if (attempt === 1) publish(matchId, 'thinking', '근거를 다시 확인하는 중');
}
if (!checked?.result) throw new Error('AI 답을 확인하지 못했습니다');
if (checked.needRetry) {
// 다시 해도 근거가 약하면 결과는 보여 주되 확신도를 낮춘다
checked.result.confidence = 'low';
checked.result.confidence_note = [checked.result.confidence_note, '일부 근거를 기록에서 찾지 못했습니다'].filter(Boolean).join(' ');
}
const totalCost = costOf(usages);
const r = await internal(
'PUT',
`/api/culprit/internal/${encodeURIComponent(matchId)}/result`,
{
result: checked.result,
players: input.players,
model: usages.at(-1)?.model ?? c.model,
createdBy: by,
meta: { tone: c.tone, durationMs: Date.now() - started, costUsd: totalCost, usage: sumUsage(usages), inputStats: input.stats, fallback },
},
60000,
);
if (r.status !== 200) throw new Error(`결과 저장 실패 (${r.status})`);
log.info({ matchId, costUsd: totalCost, ms: Date.now() - started, usage: sumUsage(usages) }, '범인찾기 완료');
publish(matchId, 'done');
} catch (e: any) {
log.error({ matchId, err: e?.message, status: e?.status }, '범인찾기 실패');
const msg =
e?.message === 'device_offline'
? '게임 PC 연결이 끊겼습니다'
: e instanceof Anthropic.APIError
? `AI 호출 실패 (${e.status ?? '연결'})`
: String(e?.message || '분석 실패');
publish(matchId, 'failed', msg);
}
}
return { budget, ledger, running };
}
function sumUsage(us: Usage[]) {
return us.reduce((a, u) => ({ input: a.input + u.input, output: a.output + u.output, cacheRead: a.cacheRead + u.cacheRead, cacheWrite: a.cacheWrite + u.cacheWrite }), { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
}

View File

@@ -62,6 +62,11 @@ export class RelayHub {
this.broadcast({ type: 'status', data: { device: st } });
}
/** 서버가 만든 실시간 이벤트 (범인찾기 진행 단계 등) */
publish(ev: LiveEvent): void {
this.broadcast(ev);
}
private broadcast(m: BrowserMessage): void {
const txt = JSON.stringify(m);
for (const b of this.browsers) if (b.readyState === WebSocket.OPEN) b.send(txt);

View File

@@ -0,0 +1,289 @@
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']);
});