범인찾기 C1: 경기 지표 보강, 분석 가능 판정, AI 자료 만들기, 결과 저장 + 녹음 안내에 AI 분석 문구

- 발로란트: 준 피해 · 헤드샷 · 첫킬/첫데스 · 설치/해체 · 스킬 사용 · 요원 역할, 라운드별 공수 · 장비 값 · 선수별 킬/피해
- 롤: 포지션(추정) · 챔피언 피해 · 받은 피해 · 시야 · 와드 · 오브젝트/포탑 피해 · CC · 10/15분 CS/골드/경험치
- culprit.ts: 녹음 공백 1분 · 경기 결과 · 음성 변환 판정, 근거 번호([u][e][c][r][s:P])가 달린 압축 텍스트, culprit_analyses 표
- API: /api/culprit/matches(목록 · 상세), /api/culprit/internal/*(사이트 서버 전용, x-gvr-internal 헤더)
- 녹음 안내 기본 문구에 "녹음된 대화는 AI 경기 분석에 쓰일 수 있어요" 추가, 기본 음성 다시 합성, 예전 기본 문구는 자동 교체

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-15 14:20:52 +09:00
parent b22e55cc64
commit de64f9818d
13 changed files with 974 additions and 13 deletions

View File

@@ -1,7 +1,8 @@
import Fastify, { type FastifyInstance } from 'fastify';
import fs from 'node:fs';
import path from 'node:path';
import type { MatchDetail, MatchPlayer, Overview, User, UserProfile, Word } from '@gvr/shared';
import type { CulpritAnalysis, CulpritResult, MatchDetail, MatchPlayer, Overview, User, UserProfile, Word } from '@gvr/shared';
import type { Culprit } from '../culprit.js';
import type { Store, UserRow } from '../db/db.js';
import type { Dictionary } from '../dict/dictionary.js';
import type { GameManager } from '../games/manager.js';
@@ -14,6 +15,7 @@ export interface ApiDeps {
timeline: Timeline;
games: GameManager;
dict: Dictionary;
culprit: Culprit;
bus: Bus;
settings: () => Settings;
trainingDir: () => string;
@@ -166,6 +168,7 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
items: p.items,
rank: p.rank ?? null,
userId: p.puuid ? userOf(p.puuid) : undefined,
stats: p.stats,
}));
const evRows = store.events(m.id);
const utts = store.db.prepare('SELECT rowid,* FROM utterances WHERE match_id=? ORDER BY started_at').all(m.id) as any[];
@@ -251,6 +254,47 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
).map(([key, count]) => ({ key, label: d.dict.labels[key] ?? key, count })),
}));
// ---------------------------------------------------------------- 범인찾기 (계획서 v1.1)
// /api/culprit/matches* : 사이트(브라우저)가 보는 목록 · 상세
// /api/culprit/internal/* : 사이트 서버만 부른다 (AI 자료 만들기 · 결과 저장). 서버가 붙이는 x-gvr-internal 헤더가 있어야 하고,
// 서버 중계는 브라우저 요청의 이 헤더를 넘기지 않는다 (relay 가 range · content-type · accept 만 넘김)
const internalOnly = (req: { headers: Record<string, unknown> }) => req.headers['x-gvr-internal'] === '1';
app.get<{ Querystring: Record<string, string> }>('/api/culprit/matches', async (req) => {
const q = req.query;
return d.culprit.list({ game: q.game === 'valorant' || q.game === 'lol' ? q.game : undefined, limit: q.limit ? Number(q.limit) : 50 });
});
app.get<{ Params: { id: string } }>('/api/culprit/matches/:id', async (req, reply) => {
const m = store.getMatch(req.params.id);
if (!m) return reply.code(404).send({ error: 'not_found' });
return d.culprit.info(m);
});
app.get<{ Params: { id: string } }>('/api/culprit/internal/:id/input', async (req, reply) => {
if (!internalOnly(req)) return reply.code(403).send({ error: 'forbidden' });
const m = store.getMatch(req.params.id);
if (!m) return reply.code(404).send({ error: 'not_found' });
const eligibility = d.culprit.eligibility(m);
if (eligibility.state !== 'ready' && eligibility.state !== 'done') return reply.code(409).send({ error: 'not_ready', eligibility });
return { eligibility, input: d.culprit.buildInput(m) };
});
app.put<{ Params: { id: string }; Body: Partial<CulpritAnalysis> & { result?: CulpritResult } }>('/api/culprit/internal/:id/result', async (req, reply) => {
if (!internalOnly(req)) return reply.code(403).send({ error: 'forbidden' });
const m = store.getMatch(req.params.id);
if (!m) return reply.code(404).send({ error: 'not_found' });
const b = req.body || {};
if (!b.result || !Array.isArray(b.result.players) || !Array.isArray(b.result.teams) || !b.model || !b.createdBy) return reply.code(400).send({ error: 'bad_result' });
const saved = d.culprit.save(m.id, {
createdAt: Date.now(),
createdBy: { id: String(b.createdBy.id), name: String(b.createdBy.name) },
model: String(b.model),
result: b.result,
players: b.players || [],
meta: b.meta || {},
});
d.games.emitMatch(m.id);
return saved;
});
return app;
}

400
app/src/core/culprit.ts Normal file
View File

@@ -0,0 +1,400 @@
import type {
CulpritAnalysis,
CulpritEligibility,
CulpritInput,
CulpritMatchInfo,
CulpritMatchItem,
CulpritPlayer,
CulpritRefTarget,
MatchPlayer,
MatchRound,
} from '@gvr/shared';
import type { EventRow, MatchRow, Store, UtteranceRow } from './db/db.js';
import type { GameManager } from './games/manager.js';
import { safeJson, type Timeline } from './timeline.js';
/**
* 범인찾기 (계획서 v1.1 4장): "분석할 수 있는 경기" 판정, AI 에 보낼 경기 자료(압축 텍스트) 만들기, 결과 저장.
* AI 호출은 사이트 서버가 한다 (API 키는 서버에만 있다). 이 PC 는 자료를 만들고 결과를 저장만 한다.
*/
/** 녹음 공백 허용치: 경기 처음 · 끝 · 중간에 이보다 긴 빈 곳이 있으면 "기록 부족" */
export const COVERAGE_GAP_MS = 60000;
/** 대화가 이보다 많으면 짧은 잡담부터 줄여서 보낸다 (경기당 비용 상한, 계획서 7장) */
export const MAX_UTTERANCES = 2500;
export const CULPRIT_SCHEMA_SQL = `
CREATE TABLE IF NOT EXISTS culprit_analyses (
id TEXT PRIMARY KEY,
match_id TEXT NOT NULL,
created_at INTEGER NOT NULL,
created_by TEXT NOT NULL,
model TEXT NOT NULL,
current INTEGER NOT NULL DEFAULT 1,
result TEXT NOT NULL,
meta TEXT NOT NULL DEFAULT '{}'
);
CREATE INDEX IF NOT EXISTS culprit_match ON culprit_analyses(match_id, created_at);
`;
export class Culprit {
constructor(
private store: Store,
private timeline: Timeline,
private games: GameManager,
) {
store.db.exec(CULPRIT_SCHEMA_SQL);
}
// ---------------------------------------------------------------- 판정
eligibility(m: MatchRow): CulpritEligibility {
const reasons: string[] = [];
if (m.status !== 'complete' || !m.ended_at) return { state: 'pending', reasons: ['경기가 아직 끝나지 않았습니다'] };
const det = safeJson<any>(m.detail, {});
const players: any[] = det.players || [];
const gotResult = !det.live && players.length >= 2 && (m.game !== 'valorant' || (det.roundsDetail || []).length > 0);
if (!gotResult) reasons.push('경기 결과를 받지 못했습니다');
const start = realStart(m);
const end = m.ended_at;
const gap = this.coverageGap(start, end);
if (gap) reasons.push(gap);
const pending = (
this.store.db.prepare(`SELECT count(*) n FROM utterances WHERE match_id=? AND status='pending' AND audio_deleted=0`).get(m.id) as { n: number }
).n;
if (reasons.length) return { state: 'blocked', reasons };
if (pending) return { state: 'pending', reasons: [`음성 변환 중 (${pending}문장 남음)`] };
if (this.current(m.id)) return { state: 'done', reasons: [] };
return { state: 'ready', reasons: [] };
}
/** 녹음(봇이 음성채널에 있던 구간)이 경기를 덮는지. 빈 곳이 1분 넘으면 이유 문장, 아니면 null */
coverageGap(start: number, end: number): string | null {
const sess = this.store.db
.prepare('SELECT started_at, ended_at FROM sessions WHERE started_at < ? AND (ended_at IS NULL OR ended_at > ?) ORDER BY started_at')
.all(end, start) as { started_at: number; ended_at: number | null }[];
if (!sess.length) return '녹음 기록이 없습니다';
let cursor = start;
let worst: { at: number; ms: number } | null = null;
for (const s of sess) {
const gs = Math.max(cursor, start);
if (s.started_at - gs > COVERAGE_GAP_MS && (!worst || s.started_at - gs > worst.ms)) worst = { at: gs, ms: s.started_at - gs };
cursor = Math.max(cursor, s.ended_at ?? Number.MAX_SAFE_INTEGER);
}
if (end - cursor > COVERAGE_GAP_MS && (!worst || end - cursor > worst.ms)) worst = { at: cursor, ms: end - cursor };
if (!worst) return null;
const min = Math.max(1, Math.round(worst.ms / 60000));
if (worst.at <= start) return `녹음이 경기 시작 ${min}분 뒤에 시작됐습니다`;
if (worst.at + worst.ms >= end) return `녹음이 경기 끝나기 ${min}분 전에 끝났습니다`;
return `녹음이 경기 중 ${min}분 끊겼습니다`;
}
// ---------------------------------------------------------------- 목록 · 상세
list(opts: { game?: string; limit?: number }): CulpritMatchItem[] {
const rows = this.store.listMatches({ game: opts.game, limit: Math.min(opts.limit ?? 50, 200) }).filter((m) => m.status !== 'live');
return rows.map((m) => {
const cur = this.current(m.id);
const elig = this.eligibility(m);
return {
match: this.games.summary(m),
eligibility: elig,
culprits: cur
? cur.result.teams.map((t) => {
const p = cur.players.find((x) => x.id === t.culprit);
return { team: t.team, name: p?.name ?? t.culprit, character: p?.character ?? null };
})
: [],
};
});
}
info(m: MatchRow): CulpritMatchInfo {
const det = safeJson<any>(m.detail, {});
const players = this.players(m);
const utts = this.usableUtterances(m.id);
const events = this.store.events(m.id);
const history = (
this.store.db.prepare('SELECT id, created_at, created_by, model, current FROM culprit_analyses WHERE match_id=? ORDER BY created_at DESC').all(m.id) as any[]
).map((r) => ({ id: r.id, at: r.created_at, by: safeJson(r.created_by, { id: '', name: '?' }), model: r.model, current: !!r.current }));
return {
match: this.games.summary(m),
eligibility: this.eligibility(m),
sources: {
rounds: m.game === 'valorant' ? (det.roundsDetail || []).length : null,
events: events.filter((e) => e.type !== 'chat').length,
utterances: utts.length,
chats: events.filter((e) => e.type === 'chat').length,
extraStats: players.some((p) => p.hasExtraStats),
},
players: players.map(({ hasExtraStats: _x, ...p }) => p),
analysis: this.current(m.id),
history,
};
}
// ---------------------------------------------------------------- 결과
current(matchId: string): CulpritAnalysis | null {
const r = this.store.db.prepare('SELECT * FROM culprit_analyses WHERE match_id=? AND current=1 ORDER BY created_at DESC LIMIT 1').get(matchId) as any;
return r ? rowToAnalysis(r) : null;
}
save(matchId: string, a: Omit<CulpritAnalysis, 'id' | 'matchId'>): CulpritAnalysis {
const id = `ca-${matchId}-${a.createdAt}`;
const tx = this.store.db.transaction(() => {
this.store.db.prepare('UPDATE culprit_analyses SET current=0 WHERE match_id=?').run(matchId);
this.store.db
.prepare('INSERT OR REPLACE INTO culprit_analyses(id,match_id,created_at,created_by,model,current,result,meta) VALUES(?,?,?,?,?,1,?,?)')
.run(id, matchId, a.createdAt, JSON.stringify(a.createdBy), a.model, JSON.stringify({ result: a.result, players: a.players }), JSON.stringify(a.meta));
});
tx();
return this.current(matchId)!;
}
// ---------------------------------------------------------------- AI 자료
/** 참가자 번호(P1~P10): 우리 팀 먼저, 팀 안에서는 경기 기록 순서 */
private players(m: MatchRow): (CulpritPlayer & { hasExtraStats: boolean })[] {
const det = safeJson<any>(m.detail, {});
const raw: MatchPlayer[] = det.players || [];
const selfTeam = det.self ? raw.find((p) => p.puuid === det.self)?.team : undefined;
const isAlly = (p: MatchPlayer) => p.ally ?? (selfTeam ? p.team === selfTeam : false);
const sorted = [...raw.filter(isAlly), ...raw.filter((p) => !isAlly(p))];
const accounts = this.store.listAccounts();
const speakers = new Set(this.usableUtterances(m.id).map((u) => u.user_id));
return sorted.map((p, i) => {
const userId = p.puuid ? accounts.find((a) => a.puuid === p.puuid)?.user_id : undefined;
return {
id: `P${i + 1}`,
puuid: p.puuid,
name: p.name ?? '?',
team: isAlly(p) ? 'ally' : 'enemy',
character: p.character ?? null,
userId: userId ?? null,
voice: !!userId && speakers.has(userId),
hasExtraStats: !!p.stats,
};
});
}
private usableUtterances(matchId: string): UtteranceRow[] {
return (
this.store.db
.prepare(`SELECT rowid,* FROM utterances WHERE match_id=? AND text IS NOT NULL AND text<>'' AND (noise=0 OR corrected=1) ORDER BY started_at, id`)
.all(matchId) as UtteranceRow[]
).filter((u) => !this.store.getUser(u.user_id)?.excluded);
}
/** AI 에 보낼 경기 자료. 숫자 덩어리(JSON) 대신 줄글로 보내 토큰을 아낀다 (계획서 5장) */
buildInput(m: MatchRow): CulpritInput {
const det = safeJson<any>(m.detail, {});
const raw: MatchPlayer[] = det.players || [];
const players = this.players(m);
const byPuuid = new Map(players.filter((p) => p.puuid).map((p) => [p.puuid, p]));
const byUser = new Map(players.filter((p) => p.userId).map((p) => [p.userId!, p]));
const statsOf = (p: CulpritPlayer) => raw.find((r) => r.puuid === p.puuid);
const refs: Record<string, CulpritRefTarget> = {};
const out: string[] = [];
const sum = this.games.summary(m);
const rounds: MatchRound[] = m.game === 'valorant' ? det.roundsDetail || [] : [];
const minutes = m.ended_at ? Math.round((m.ended_at - realStart(m)) / 60000) : 0;
const resultKo = sum.win === null ? '결과 모름' : sum.win ? '우리 팀 승리' : '우리 팀 패배';
const score = sum.score ? `${sum.score.ally}:${sum.score.enemy}` : '?';
const basic = !players.some((p) => p.hasExtraStats);
// 대화: 너무 많으면 짧은 말부터 뺀다
let utts = this.usableUtterances(m.id);
const totalUtts = utts.length;
if (utts.length > MAX_UTTERANCES) {
const keep = new Set([...utts].sort((a, b) => [...(b.text ?? '')].length - [...(a.text ?? '')].length).slice(0, MAX_UTTERANCES).map((u) => u.id));
utts = utts.filter((u) => keep.has(u.id));
}
if (m.game === 'valorant') {
out.push(`# 경기 발로란트 ${sum.mode} · ${sum.map.name} · ${score} (${resultKo}) · ${rounds.length}라운드 · ${minutes}분`);
} else {
out.push(`# 경기 리그 오브 레전드 ${sum.mode} · ${sum.map.name} · 킬 ${score} (${resultKo}) · ${minutes}분`);
}
if (basic) out.push('# 이 경기는 기본 기록만 있다 (피해량 · 첫킬 · 시야 같은 추가 지표 없음)');
if (totalUtts > utts.length) out.push(`# 대화가 많아 ${totalUtts}문장 중 짧은 말을 빼고 ${utts.length}문장만 보냄`);
// 참가자
if (m.game === 'valorant') {
const nRounds = rounds.length || 1;
out.push('# 참가자 (번호 이름 팀 요원(역할) K/D/A ACS 라운드당피해 첫킬/첫데스 헤드샷 설치/해체 스킬사용 음성)');
for (const p of players) {
const s = statsOf(p);
const x = s?.stats;
const cols = [
p.id,
p.name,
p.team === 'ally' ? '우리' : '상대',
`${p.character?.name ?? '?'}${x?.role ? `(${x.role})` : ''}`,
`${s?.kills ?? 0}/${s?.deaths ?? 0}/${s?.assists ?? 0}`,
`ACS${Math.round((s?.score ?? 0) / (x?.rounds || nRounds))}`,
x ? `ADR${Math.round((x.damage ?? 0) / (x.rounds || nRounds))}` : 'ADR?',
x ? `첫킬${x.firstKills ?? 0}/첫데스${x.firstDeaths ?? 0}` : '',
x?.headshotPct !== undefined ? `HS${x.headshotPct}%` : '',
x ? `설치${x.plants ?? 0}/해체${x.defuses ?? 0}` : '',
x?.abilityCasts !== undefined ? `스킬${x.abilityCasts}` : '',
s?.rank ? `랭크:${s.rank}` : '',
p.voice ? '음성O' : '음성X',
];
out.push(cols.filter(Boolean).join(' '));
}
} else {
out.push('# 참가자 (번호 이름 팀 챔피언(포지션 추정) K/D/A CS 골드 챔피언피해 받은피해 시야 와드설치/제거/제어와드 10분CS·골드 15분CS·골드 음성)');
for (const p of players) {
const s = statsOf(p);
const x = s?.stats;
const at = (a?: { cs: number; gold: number }) => (a ? `${a.cs}·${a.gold}` : '?');
const cols = [
p.id,
p.name,
p.team === 'ally' ? '우리' : '상대',
`${p.character?.name ?? '?'}${x?.role ? `(${x.role})` : ''}`,
`${s?.kills ?? 0}/${s?.deaths ?? 0}/${s?.assists ?? 0}`,
`CS${s?.cs ?? '?'}`,
`골드${s?.gold ?? '?'}`,
x ? `딜${x.damage ?? '?'} 받은${x.damageTaken ?? '?'} 시야${x.vision ?? '?'} 와드${x.wardsPlaced ?? 0}/${x.wardsKilled ?? 0}/${x.controlWards ?? 0}` : '',
x ? `10분${at(x.at10)} 15분${at(x.at15)}` : '',
p.voice ? '음성O' : '음성X',
];
out.push(cols.filter(Boolean).join(' '));
}
}
for (const p of players) refs[`s:${p.id}`] = { kind: 'stat', pid: p.id };
// 게임 계정이 연결되지 않은 화자
const others = [...new Set(utts.map((u) => u.user_id))].filter((uid) => !byUser.has(uid));
const speakerName = new Map<string, string>();
for (const uid of others) speakerName.set(uid, `${this.store.getUser(uid)?.name ?? uid}(게임 계정 모름)`);
if (others.length) out.push(`# 음성 화자 중 게임 계정을 모르는 사람: ${others.map((u) => speakerName.get(u)).join(', ')}`);
const who = (uid: string) => byUser.get(uid)?.id ?? speakerName.get(uid) ?? uid;
const pRef = (r: any) => (r?.puuid && byPuuid.get(r.puuid)?.id) || r?.name || '?';
if (m.game === 'lol') {
const gd: { t: number; diff: number }[] = det.goldDiff || [];
const pts = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
.map((min) => gd.find((g) => Math.round(g.t / 60000) === min))
.filter(Boolean) as { t: number; diff: number }[];
if (pts.length) out.push(`# 골드 차(우리-상대): ${pts.map((g) => `${Math.round(g.t / 60000)}분 ${g.diff >= 0 ? '+' : ''}${g.diff.toLocaleString('en-US')}`).join(' · ')}`);
}
out.push('# 시간 순서 기록');
type Line = { ts: number; order: number; text: string };
const lines: Line[] = [];
let ei = 0;
let ci = 0;
const events = this.store.events(m.id);
for (const e of events) {
if (e.type === 'round_end' || e.type === 'match_start' || e.type === 'match_end') continue;
if (e.id.includes(':live-round:')) continue;
const d = safeJson<any>(e.data, {});
const t = this.timeline.eventItem(e).time.primary.replace(' · ', ' ');
if (e.type === 'chat') {
const key = `c${++ci}`;
refs[key] = { kind: 'event', id: e.id, ts: e.ts, round: e.round ?? undefined };
const ch = d.channel === 'all' ? '전체채팅' : d.channel === 'party' ? '파티채팅' : '팀채팅';
const sender = (d.sender?.puuid && byPuuid.get(d.sender.puuid)?.id) || d.sender?.name || '?';
lines.push({ ts: e.ts, order: 1, text: `[${key}] ${t} ${ch} ${sender}: ${clip(String(d.text ?? ''), 200)}` });
continue;
}
const desc = describeEvent(e, d, pRef);
if (!desc) continue;
const key = `e${++ei}`;
refs[key] = { kind: 'event', id: e.id, ts: e.ts, round: e.round ?? undefined };
lines.push({ ts: e.ts, order: 0, text: `[${key}] ${t} ${desc}` });
}
// 라운드 요약 (발로란트): 라운드 끝에 넣는다
for (const r of rounds) {
const key = `r${r.num}`;
refs[key] = { kind: 'round', round: r.num, ts: r.startedAt };
lines.push({ ts: r.endedAt, order: 2, text: `[${key}] ${roundLine(r, players)}` });
}
let ui = 0;
for (const u of utts) {
const key = `u${++ui}`;
refs[key] = { kind: 'utterance', id: u.id, ts: u.started_at };
const t = this.timeline.utteranceItem(u).time.primary.replace(' · ', ' ');
lines.push({ ts: u.started_at, order: 1, text: `[${key}] ${t} ${who(u.user_id)}: ${clip(u.text ?? '', 300)}` });
}
lines.sort((a, b) => a.ts - b.ts || a.order - b.order);
for (const l of lines) out.push(l.text);
return {
game: m.game,
text: out.join('\n'),
refs,
players: players.map(({ hasExtraStats: _x, ...p }) => p),
stats: { utterances: utts.length, utterancesTotal: totalUtts, events: ei, chats: ci, rounds: rounds.length, basic },
};
}
}
function realStart(m: MatchRow): number {
return m.started_at + m.clock_offset;
}
function clip(s: string, n: number): string {
const t = s.replace(/\s+/g, ' ').trim();
return [...t].length > n ? [...t].slice(0, n).join('') + '…' : t;
}
function describeEvent(e: EventRow, d: any, pRef: (r: any) => string): string | null {
switch (e.type) {
case 'kill': {
const as = (d.assists || []).map(pRef);
const weapon = d.weapon?.name ? ` (${d.weapon.name})` : '';
return `킬 ${d.killer ? pRef(d.killer) : '?'} → ${pRef(d.victim)}${weapon}${as.length ? ` 어시 ${as.join(',')}` : ''}`;
}
case 'multikill':
return `멀티킬 ${pRef(d.player)} ${d.count}킬`;
case 'ace':
return `에이스 ${pRef(d.player)}`;
case 'spike':
return d.action === 'defuse' ? `스파이크 해체 ${pRef(d.player)}` : `스파이크 설치 ${pRef(d.player)}${d.site ? ` (${d.site})` : ''}`;
case 'object': {
const team = d.ally === true ? '우리 팀' : d.ally === false ? '상대 팀' : '';
const who = d.killer && d.object !== 'tower' && d.object !== 'inhibitor' ? ` · ${pRef(d.killer)}` : '';
return `${d.label || d.object} ${d.object === 'tower' || d.object === 'inhibitor' ? '' : '처치 '}${team}${who}`.replace(/\s+/g, ' ').trim();
}
default:
return null;
}
}
function roundLine(r: MatchRound, players: CulpritPlayer[]): string {
const side = r.allyAttack === undefined ? '' : r.allyAttack ? ' 우리 공격' : ' 우리 수비';
const avg = (team: 'ally' | 'enemy') => {
const vals = players
.filter((p) => p.team === team)
.map((p) => r.economy?.[p.puuid]?.loadout)
.filter((v): v is number => typeof v === 'number');
return vals.length ? Math.round(vals.reduce((a, b) => a + b, 0) / vals.length) : null;
};
const a = avg('ally');
const en = avg('enemy');
const eco = a !== null && en !== null ? ` · 평균 장비 우리 ${a.toLocaleString('en-US')} / 상대 ${en.toLocaleString('en-US')}` : '';
const per = players
.map((p) => {
const ec = r.economy?.[p.puuid];
const st = r.players?.[p.puuid];
if (!ec && !st) return null;
const lo = ec?.loadout !== undefined ? `${(ec.loadout / 1000).toFixed(1)}k` : ec ? `${(ec.spent / 1000).toFixed(1)}k쓴` : '?';
return `${p.id} ${lo}${st ? `/${st.damage}` : ''}`;
})
.filter(Boolean);
return `R${r.num}${side} 라운드 끝 · ${r.win ? '승리' : '패배'}(${r.result}) ${r.score.ally}:${r.score.enemy}${eco}${per.length ? ` · 선수 장비/피해: ${per.join(' ')}` : ''}`;
}
function rowToAnalysis(r: any): CulpritAnalysis {
const body = safeJson<any>(r.result, {});
return {
id: r.id,
matchId: r.match_id,
createdAt: r.created_at,
createdBy: safeJson(r.created_by, { id: '', name: '?' }),
model: r.model,
result: body.result,
players: body.players || [],
meta: safeJson(r.meta, {}),
};
}

View File

@@ -40,7 +40,7 @@ export function lolObjectIcon(key: string): string {
interface ValCatalog {
at: number;
agents: Record<string, { name: string; icon: string; abilities: Record<string, { name: string; icon: string | null }> }>;
agents: Record<string, { name: string; icon: string; role?: string; abilities: Record<string, { name: string; icon: string | null }> }>;
maps: Record<string, { uuid: string; name: string; image: string | null; xMultiplier: number; yMultiplier: number; xScalarToAdd: number; yScalarToAdd: number }>;
weapons: Record<string, { name: string; icon: string | null }>;
tiers: Record<number, string>;
@@ -81,7 +81,9 @@ export class GameAssets {
}
async refreshVal(force = false): Promise<void> {
if (!force && this.val && Date.now() - this.val.at < DAY) return;
// v1.3: 요원 역할을 저장하지 않던 예전 캐시는 바로 다시 받는다
const hasRoles = this.val && Object.values(this.val.agents).some((a) => a.role);
if (!force && this.val && hasRoles && Date.now() - this.val.at < DAY) return;
const get = async (p: string) => (await request(`https://valorant-api.com/v1/${p}`, { timeoutMs: 20000 })).data?.data;
const [agents, maps, weapons, tiers, modes, version] = await Promise.all([
get('agents?language=ko-KR&isPlayableCharacter=true'),
@@ -95,7 +97,7 @@ export class GameAssets {
for (const a of agents || []) {
const abilities: ValCatalog['agents'][string]['abilities'] = {};
for (const ab of a.abilities || []) abilities[ab.slot] = { name: ab.displayName, icon: assetUrl(ab.displayIcon) };
cat.agents[a.uuid.toLowerCase()] = { name: a.displayName, icon: assetUrl(a.displayIcon)!, abilities };
cat.agents[a.uuid.toLowerCase()] = { name: a.displayName, icon: assetUrl(a.displayIcon)!, role: a.role?.displayName ?? undefined, abilities };
}
for (const m of maps || [])
cat.maps[m.mapUrl] = {
@@ -151,6 +153,10 @@ export class GameAssets {
const a = id ? this.val?.agents[id.toLowerCase()] : undefined;
return { id: id || '', name: a?.name ?? '?', icon: a?.icon ?? null };
}
/** 요원 역할 (타격대 · 척후대 · 전략가 · 감시자). 예전 캐시에는 없다 */
agentRole(id: string | null | undefined): string | null {
return (id && this.val?.agents[id.toLowerCase()]?.role) || null;
}
valMap(mapUrl: string | null | undefined) {
return mapUrl ? this.val?.maps[mapUrl] : undefined;
}

View File

@@ -530,6 +530,20 @@ export function processLolHistory(game: any, timeline: any, host: Pick<AdapterHo
const it = host.assets.item(x);
return { id: x, name: it.name, icon: it.icon };
}),
stats: {
role: lolPosition(p) ?? undefined,
damage: st.totalDamageDealtToChampions,
damageTaken: st.totalDamageTaken,
vision: st.visionScore,
wardsPlaced: st.wardsPlaced,
wardsKilled: st.wardsKilled,
controlWards: st.visionWardsBoughtInGame,
objectiveDamage: st.damageDealtToObjectives,
turretDamage: st.damageDealtToTurrets,
ccSeconds: st.timeCCingOthers,
at10: frameAt(timeline, p.participantId, 10),
at15: frameAt(timeline, p.participantId, 15),
},
};
});
const events: EventRow[] = [];
@@ -602,6 +616,25 @@ export function processLolHistory(game: any, timeline: any, host: Pick<AdapterHo
};
}
/** LCU 경기 기록의 라인 · 역할 → 포지션 (사용자 지정 게임은 틀릴 수 있어 "추정") */
export function lolPosition(p: any): string | null {
const lane = String(p.timeline?.lane || '').toUpperCase();
const role = String(p.timeline?.role || '').toUpperCase();
if (p.spell1Id === 11 || p.spell2Id === 11 || lane === 'JUNGLE') return '정글';
if (lane === 'TOP') return '탑';
if (lane === 'MIDDLE' || lane === 'MID') return '미드';
if (lane === 'BOTTOM' || lane === 'BOT') return role === 'DUO_SUPPORT' || role === 'SUPPORT' ? '서폿' : role === 'DUO_CARRY' || role === 'CARRY' ? '원딜' : '바텀';
return null;
}
/** 타임라인의 N분 프레임에서 그 선수 CS · 골드 · 경험치 */
function frameAt(timeline: any, pid: number, minute: number): { cs: number; gold: number; xp: number } | undefined {
const f = (timeline?.frames || []).find((x: any) => Math.round((x.timestamp ?? 0) / 60000) === minute);
const pf = f?.participantFrames?.[String(pid)] ?? f?.participantFrames?.[pid];
if (!pf) return undefined;
return { cs: (pf.minionsKilled ?? 0) + (pf.jungleMinionsKilled ?? 0), gold: pf.totalGold ?? 0, xp: pf.xp ?? 0 };
}
function prettyUnit(name: string): string {
if (/^Turret_/.test(name)) return '포탑';
if (/Minion/.test(name)) return '미니언';

View File

@@ -1,4 +1,4 @@
import type { KillData, ChatData, RoundEndData, PlayerRef, MatchPlayer, MatchRound } from '@gvr/shared';
import type { KillData, ChatData, RoundEndData, PlayerRef, MatchPlayer, MatchRound, PlayerStats } from '@gvr/shared';
import type { EventRow, RoundRow } from '../db/db.js';
import { logger } from '../util/log.js';
import type { GameAssets } from './assets.js';
@@ -380,6 +380,17 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
}
combat[i] = prev !== null ? prev + avg : next !== null ? next : BUY_MS + i * avg;
}
// 범인찾기용 선수별 누적 지표
const tallies: Record<string, { damage: number; head: number; shots: number; firstKills: number; firstDeaths: number; plants: number; defuses: number }> = {};
const tally = (puuid: string) => (tallies[puuid] ||= { damage: 0, head: 0, shots: 0, firstKills: 0, firstDeaths: 0, plants: 0, defuses: 0 });
// 공격 팀: 전반 12라운드는 Red, 후반은 Blue, 연장은 매 라운드 바뀜. 스파이크를 설치한 팀이 공격이므로 설치 기록이 반대면 뒤집는다
const ruleAttacker = (i: number) => (i < 12 ? 'Red' : i < 24 ? 'Blue' : i % 2 === 0 ? 'Red' : 'Blue');
let agree = 0;
for (let i = 0; i < n; i++) {
const planter = rr[i].bombPlanter ? players[rr[i].bombPlanter]?.teamId : null;
if (planter) agree += planter === ruleAttacker(i) ? 1 : -1;
}
const attackerTeam = (i: number) => (agree >= 0 ? ruleAttacker(i) : ruleAttacker(i) === 'Red' ? 'Blue' : 'Red');
const rounds: RoundRow[] = [];
const roundsDetail: MatchRound[] = [];
const events: EventRow[] = [];
@@ -394,15 +405,27 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
const win = r.winningTeam === selfTeam;
if (win) ally++;
else enemy++;
const economy: Record<string, { spent: number; remaining: number; weapon?: string }> = {};
const economy: Record<string, { spent: number; remaining: number; weapon?: string; loadout?: number }> = {};
const roundPlayers: Record<string, { kills: number; damage: number }> = {};
for (const ps of r.playerStats || []) {
if (ps.economy)
economy[ps.subject] = {
spent: ps.economy.spent ?? 0,
remaining: ps.economy.remaining ?? 0,
weapon: ps.economy.weapon ? assets.damageItem(null, 'Weapon', ps.economy.weapon)?.name : undefined,
loadout: typeof ps.economy.loadoutValue === 'number' ? ps.economy.loadoutValue : undefined,
};
const dmg = (ps.damage || []).reduce((n: number, d: any) => n + (d.damage ?? 0), 0);
roundPlayers[ps.subject] = { kills: (ps.kills || []).length, damage: dmg };
const t = tally(ps.subject);
t.damage += dmg;
for (const d of ps.damage || []) {
t.head += d.headshots ?? 0;
t.shots += (d.headshots ?? 0) + (d.bodyshots ?? 0) + (d.legshots ?? 0);
}
}
if (r.bombPlanter) tally(r.bombPlanter).plants++;
if (r.bombDefuser) tally(r.bombDefuser).defuses++;
rounds.push({
match_id: id,
num,
@@ -415,10 +438,24 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
enemy_score: enemy,
economy: JSON.stringify(economy),
});
roundsDetail.push({ num, startedAt: S + start + clockOffset, endedAt: S + end + clockOffset, win, result: roundResultKo(r.roundResult), score: { ally, enemy }, economy });
roundsDetail.push({
num,
startedAt: S + start + clockOffset,
endedAt: S + end + clockOffset,
win,
result: roundResultKo(r.roundResult),
score: { ally, enemy },
economy,
allyAttack: attackerTeam(i) === selfTeam,
players: roundPlayers,
});
// 킬
const killsBy: Record<string, number> = {};
const kills = (r.playerStats || []).flatMap((ps: any) => ps.kills || []).sort((x: any, y: any) => x.gameTime - y.gameTime);
if (kills[0]) {
if (kills[0].killer) tally(kills[0].killer).firstKills++;
if (kills[0].victim) tally(kills[0].victim).firstDeaths++;
}
for (const k of kills) {
const killer = ref(k.killer);
const victim = ref(k.victim)!;
@@ -516,6 +553,7 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
assists: p.stats?.assists ?? 0,
score: p.stats?.score ?? 0, // 총 전투 점수 (사이트가 라운드 수로 나눠 ACS 표시)
rank: assets.val?.tiers[p.competitiveTier] ?? null,
stats: playerStats(p, tallies[p.subject], assets),
}));
const selfTeamInfo = (md.teams || []).find((t: any) => t.teamId === selfTeam);
const enemyTeamInfo = (md.teams || []).find((t: any) => t.teamId !== selfTeam);
@@ -535,6 +573,21 @@ export function processMatchDetails(md: any, selfPuuid: string, assets: GameAsse
};
}
function playerStats(p: any, t: { damage: number; head: number; shots: number; firstKills: number; firstDeaths: number; plants: number; defuses: number } | undefined, assets: GameAssets): PlayerStats {
const ac = p.stats?.abilityCasts;
return {
role: assets.agentRole(p.characterId) ?? undefined,
rounds: p.stats?.roundsPlayed ?? undefined,
damage: t?.damage ?? 0,
headshotPct: t && t.shots ? Math.round((t.head / t.shots) * 100) : undefined,
firstKills: t?.firstKills ?? 0,
firstDeaths: t?.firstDeaths ?? 0,
plants: t?.plants ?? 0,
defuses: t?.defuses ?? 0,
abilityCasts: ac ? (ac.grenadeCasts ?? 0) + (ac.ability1Casts ?? 0) + (ac.ability2Casts ?? 0) + (ac.ultimateCasts ?? 0) : undefined,
};
}
export function roundResultKo(r: string | undefined): string {
switch (r) {
case 'Eliminated':

View File

@@ -2,6 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import type { FastifyInstance } from 'fastify';
import { buildApi } from './api/server.js';
import { Culprit } from './culprit.js';
import { Store } from './db/db.js';
import { Dictionary } from './dict/dictionary.js';
import { Bot } from './discord/bot.js';
@@ -79,11 +80,13 @@ export async function startCore(opts: CoreOptions) {
if (!S().discord.guildId) settings.update({ discord: { guildId: gid } });
});
const culprit = new Culprit(store, timeline, games);
const api: FastifyInstance = await buildApi({
store,
timeline,
games,
dict,
culprit,
bus,
settings: S,
trainingDir: () => paths().training,

View File

@@ -131,7 +131,7 @@ export class RelayClient {
}
try {
const headers: Record<string, string> = {};
for (const k of ['range', 'content-type', 'accept']) if (req.headers[k]) headers[k] = req.headers[k];
for (const k of ['range', 'content-type', 'accept', 'x-gvr-internal']) if (req.headers[k]) headers[k] = req.headers[k];
if (req.user) headers['x-gvr-user'] = encodeURIComponent(JSON.stringify(req.user));
const res = await this.api.inject({ method: req.method as any, url: req.path, headers, payload: req.body ?? undefined });
const outHeaders: Record<string, string> = {};

View File

@@ -78,7 +78,9 @@ export interface Secrets {
}
export const DEFAULT_TTS_TEXT =
'겜녹이가 이 음성채널을 녹음합니다. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.';
'겜녹이가 이 음성채널을 녹음합니다. 녹음된 대화는 AI 경기 분석에 쓰일 수 있어요. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.';
/** v1.2.2 까지의 기본 문구. 이 문구를 그대로 쓰던 설치는 새 기본 문구(AI 분석 안내 포함)로 바꾼다 */
const OLD_DEFAULT_TTS_TEXTS = ['겜녹이가 이 음성채널을 녹음합니다. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.'];
export function defaultSettings(): Settings {
return {
@@ -178,6 +180,8 @@ export class SettingsStore {
}
// v1.0.0 에서 직접 토큰을 넣어 쓰던 설치는 그 봇을 계속 쓴다
if (saved && !saved.discord?.botMode && this.secrets.botToken) this.cur.discord.botMode = 'custom';
// 범인찾기(AI 분석) 안내: 기본 문구를 바꾸지 않고 쓰던 설치는 새 기본 문구로 (직접 고친 문구는 그대로)
if (OLD_DEFAULT_TTS_TEXTS.includes(this.cur.discord.ttsText)) this.cur.discord.ttsText = DEFAULT_TTS_TEXT;
// 개발/헤드리스: 환경변수 토큰이 있으면 모드와 상관없이 그것을 쓴다
this.envBotToken = process.env.GVR_BOT_TOKEN || null;
// v1.2.0 은 서버에서 받은 겜녹이 봇 토큰을 저장해 두었다. 이제는 서버가 봇을 대신 연결하므로 남기지 않는다

View File

@@ -21,7 +21,7 @@ function defaults(): Settings {
followEnabled: true,
commandsEnabled: true,
ttsEnabled: true,
ttsText: '겜녹이가 이 음성채널을 녹음합니다. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.',
ttsText: '겜녹이가 이 음성채널을 녹음합니다. 녹음된 대화는 AI 경기 분석에 쓰일 수 있어요. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.',
ttsOnNewMember: true,
ttsVoice: 'ko-KR-SunHiNeural',
},

253
app/test/culprit.test.ts Normal file
View File

@@ -0,0 +1,253 @@
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 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 };
}
test('범인찾기: 발로란트 추가 지표 저장 (피해량 · 첫킬 · 설치 · 역할 · 라운드별 장비)', () => {
const ctx = setup();
const { id } = seedValorant(ctx);
const det = JSON.parse(ctx.store.getMatch(id)!.detail!);
const jett = det.players.find((p: any) => p.puuid === 'p-sh');
assert.equal(jett.stats.role, '타격대');
assert.ok(jett.stats.damage > 0, '피해량');
assert.equal(typeof jett.stats.firstKills, 'number');
assert.ok(det.players.reduce((n: number, p: any) => n + p.stats.firstKills, 0) > 0, '첫킬 합 > 0');
const plants = det.players.reduce((n: number, p: any) => n + p.stats.plants, 0);
assert.ok(plants > 0, '설치 기록');
const r = det.roundsDetail[1];
assert.equal(typeof r.allyAttack, 'boolean');
assert.ok(r.players['p-sh'] !== undefined, '라운드별 선수 지표');
assert.ok(Object.values<any>(r.economy).every((e) => typeof e.loadout === 'number'), '라운드 장비 값');
// 전반(1~12)과 후반(13~)은 공수가 바뀐다
assert.notEqual(det.roundsDetail[0].allyAttack, det.roundsDetail[12].allyAttack);
});
test('범인찾기: 분석 가능 판정과 AI 자료', () => {
const ctx = setup();
const { id } = seedValorant(ctx);
const m = ctx.store.getMatch(id)!;
assert.deepEqual(ctx.culprit.eligibility(m), { state: 'ready', reasons: [] });
const input = ctx.culprit.buildInput(m);
const lines = input.text.split('\n');
assert.match(lines[0], /^# 경기 발로란트 .* 13:9 \(우리 팀 승리\) · 22라운드/);
// 우리 팀이 P1~P5, 승한은 음성O, 디스코드 계정이 없는 상대는 음성X
const p1 = lines.find((l) => l.startsWith('P1 '))!;
assert.match(p1, /^P1 승한 우리 제트\(타격대\) \d+\/\d+\/\d+ ACS\d+ ADR\d+ 첫킬\d+\/첫데스\d+ HS\d+% 설치\d+\/해체\d+ .*음성O$/);
assert.match(lines.find((l) => l.startsWith('P6 '))!, /상대 .*음성X$/);
assert.equal(input.players.find((p) => p.id === 'P2')!.voice, true, '민수는 대화가 있다');
assert.equal(input.players.find((p) => p.id === 'P3')!.voice, false);
// 게임 계정이 없는 화자는 디스코드 이름으로
assert.ok(lines.some((l) => l.includes('도윤(게임 계정 모름)')));
// 근거 번호: 대화 · 이벤트 · 라운드 · 스탯
const u1 = lines.find((l) => l.startsWith('[u1] '))!;
assert.match(u1, /^\[u1\] R3 0:05 P1: 현우야 같이 가 기다려 둘 있어$/);
assert.equal(input.refs.u1.kind, 'utterance');
assert.ok(lines.some((l) => /^\[e\d+\] R\d+ \d+:\d+ 킬 P\d+ → P\d+/.test(l)), '킬 줄');
assert.ok(lines.some((l) => /^\[r1\] R1 우리 (공격|수비) 라운드 끝 · (승리|패배)\(.+\) \d+:\d+ · 평균 장비 우리 [\d,]+ \/ 상대 [\d,]+ · 선수 장비\/피해: P1 /.test(l)), '라운드 줄');
assert.deepEqual(input.refs['s:P4'], { kind: 'stat', pid: 'P4' });
assert.equal(input.stats.utterances, 4);
assert.equal(input.stats.basic, false);
// 줄은 시간 순서
const u2Index = lines.findIndex((l) => l.startsWith('[u2] '));
assert.ok(lines.findIndex((l) => l.startsWith('[r2] ')) < lines.findIndex((l) => l.startsWith('[u1] ')));
assert.ok(u2Index > lines.findIndex((l) => l.startsWith('[u1] ')));
});
test('범인찾기: 녹음이 늦게 시작 · 음성 변환 중 · 녹음 제외', () => {
const late = setup();
const a = seedValorant(late, { sessionStartOffsetMs: 17 * MIN });
const e = late.culprit.eligibility(late.store.getMatch(a.id)!);
assert.equal(e.state, 'blocked');
assert.deepEqual(e.reasons, ['녹음이 경기 시작 12분 뒤에 시작됐습니다']);
const pend = setup();
const b = seedValorant(pend, { pending: true });
assert.deepEqual(pend.culprit.eligibility(pend.store.getMatch(b.id)!), { state: 'pending', reasons: ['음성 변환 중 (1문장 남음)'] });
// 녹음 제외한 사람의 대화는 보내지 않는다
const ex = setup();
const c = seedValorant(ex);
ex.store.setExcluded('u2', true);
const input = ex.culprit.buildInput(ex.store.getMatch(c.id)!);
assert.ok(!input.text.includes('내가 뚫을게'));
assert.equal(input.players.find((p) => p.id === 'P2')!.voice, false);
// 경기 결과를 못 받은 경기
const nd = setup();
nd.store.upsertMatch({ id: 'val-x', game: 'valorant', started_at: Date.now() - 50 * MIN, ended_at: Date.now() - 10 * MIN, status: 'complete', detail: JSON.stringify({ live: true }) });
nd.store.startSession('s', 'g', 'c', null, Date.now() - 60 * MIN);
assert.deepEqual(nd.culprit.eligibility(nd.store.getMatch('val-x')!), { state: 'blocked', reasons: ['경기 결과를 받지 못했습니다'] });
});
test('범인찾기: 롤 포지션 · 시야 · 10/15분 지표와 골드 차', () => {
const ctx = setup();
const LS = Date.now() - 80 * MIN;
const lol = makeDemoLol();
ctx.store.setMeta('riot_self_puuid', 'l-sh');
ctx.store.startSession('s', 'g', 'c', null, LS - MIN);
ctx.store.endSession('s', LS + lol.durationMs + MIN);
ctx.games.matchStarted({ id: 'lol-1', game: 'lol', startedAt: LS, map: 'Map11', mode: 'CLASSIC', queue: '420', detail: { live: true } });
ctx.games.matchEnded('lol-1', LS + lol.durationMs);
(ctx.games.adapters[1] as any).applyHistory('lol-1', lol.game, lol.timeline, LS);
const m = ctx.store.getMatch('lol-1')!;
const det = JSON.parse(m.detail!);
assert.deepEqual(
det.players.map((p: any) => p.stats.role),
['미드', '정글', '탑', '원딜', '서폿', '미드', '정글', '탑', '원딜', '서폿'],
);
assert.deepEqual(det.players[1].stats.at10, { cs: 60, gold: det.players[1].stats.at10.gold, xp: 4220 });
assert.equal(ctx.culprit.eligibility(m).state, 'ready');
const input = ctx.culprit.buildInput(m);
assert.match(input.text, /\nP5 Duck 우리 [^ ]+\(서폿\) \d+\/\d+\/\d+ CS\d+ 골드\d+ 딜17500 받은\d+ 시야62 와드48\/4\/9 10분\d+·\d+ 15분\d+·\d+ 음성X\n/);
assert.match(input.text, /\n# 골드 차\(우리-상대\): 5분 [+-][\d,]+ · 10분/);
assert.match(input.text, /\n\[e\d+\] \d+:\d+ 킬 P\d+ → P\d+/);
assert.match(input.text, /\n\[e\d+\] \d+:\d+ 내셔 남작 처치 우리 팀 · P2\n/);
});
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 list = (await api.inject({ url: '/api/culprit/matches' })).json() as CulpritMatchItem[];
assert.equal(list.length, 1);
assert.equal(list[0].eligibility.state, 'ready');
// 브라우저(사이트 중계)는 내부 경로를 쓸 수 없다
assert.equal((await api.inject({ url: `/api/culprit/internal/${id}/input` })).statusCode, 403);
assert.equal((await api.inject({ method: 'PUT', url: `/api/culprit/internal/${id}/result`, payload: {} })).statusCode, 403);
const r = await api.inject({ url: `/api/culprit/internal/${id}/input`, headers: { 'x-gvr-internal': '1' } });
assert.equal(r.statusCode, 200);
const input = r.json().input as CulpritInput;
assert.ok(input.text.length > 1000);
const result = {
summary: '요약',
confidence: 'high',
confidence_note: '',
teams: [
{ team: 'ally', culprit: 'P2', reason: '이유', evidence: [{ ref: 'u2', note: '"아 그냥 간다"', target: input.refs.u2 }] },
{ team: 'enemy', culprit: 'P8', reason: '이유', evidence: [] },
],
players: input.players.map((p) => ({ id: p.id, score: p.id === 'P2' || p.id === 'P8' ? 3 : 7, tag: p.id === 'P2' || p.id === 'P8' ? '범인' : '무난', comment: '평', evidence: [] })),
};
const put = await api.inject({
method: 'PUT',
url: `/api/culprit/internal/${id}/result`,
headers: { 'x-gvr-internal': '1' },
payload: { result, players: input.players, model: 'claude-opus-5-5', createdBy: { id: 'u1', name: '승한' }, meta: { costUsd: 0.41 } },
});
assert.equal(put.statusCode, 200);
const info = (await api.inject({ url: `/api/culprit/matches/${id}` })).json() as CulpritMatchInfo;
assert.equal(info.eligibility.state, 'done');
assert.equal(info.analysis!.result.teams[0].culprit, 'P2');
assert.equal(info.analysis!.meta.costUsd, 0.41);
assert.equal(info.history.length, 1);
assert.equal(info.sources.utterances, 4);
const list2 = (await api.inject({ url: '/api/culprit/matches' })).json() as CulpritMatchItem[];
assert.deepEqual(
list2[0].culprits.map((c) => [c.team, c.name]),
[
['ally', '민수'],
['enemy', 'Kiwi'],
],
);
// 다시 분석하면 이전 결과는 기록으로 남는다
await api.inject({ method: 'PUT', url: `/api/culprit/internal/${id}/result`, headers: { 'x-gvr-internal': '1' }, payload: { result, players: input.players, model: 'm2', createdBy: { id: 'u1', name: '승한' }, meta: {} } });
const info2 = (await api.inject({ url: `/api/culprit/matches/${id}` })).json() as CulpritMatchInfo;
assert.equal(info2.history.length, 2);
assert.equal(info2.analysis!.model, 'm2');
assert.equal(info2.history.filter((h) => h.current).length, 1);
await api.close();
});
test('녹음 안내 문구: 예전 기본 문구는 AI 분석 안내가 들어간 새 기본 문구로, 직접 고친 문구는 그대로', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gvr-tts-'));
fs.writeFileSync(path.join(dir, 'settings.json'), JSON.stringify({ discord: { ttsText: '겜녹이가 이 음성채널을 녹음합니다. 녹음을 원하지 않으시면 녹음제외 명령을 입력해 주세요.' } }));
assert.equal(new SettingsStore(dir).get().discord.ttsText, DEFAULT_TTS_TEXT);
assert.match(DEFAULT_TTS_TEXT, /AI 경기 분석에 쓰일 수 있어요/);
fs.writeFileSync(path.join(dir, 'settings.json'), JSON.stringify({ discord: { ttsText: '녹음 중입니다' } }));
assert.equal(new SettingsStore(dir).get().discord.ttsText, '녹음 중입니다');
});

View File

@@ -100,6 +100,11 @@ export function makeDemoValorant(gameStart: number) {
score: kills.filter((k) => k.killer === p.subject).length * 200 + range(0, 150),
economy: { spent: pistol ? 800 : range(1500, 4700), remaining: range(0, 3000), loadoutValue: 0, weapon: pistol ? WEAPON.classic : pick([WEAPON.vandal, WEAPON.phantom]), armor: '' },
}));
// 피해량 · 장비 값 (난수를 더 쓰지 않는다: 다른 시연 데이터가 바뀌지 않게)
for (const ps of playerStats as any[]) {
ps.damage = ps.kills.map((k: any) => ({ receiver: k.victim, damage: 140 + (k.gameTime % 61), headshots: k.gameTime % 3 === 0 ? 1 : 0, bodyshots: 2, legshots: k.gameTime % 5 === 0 ? 1 : 0 }));
ps.economy.loadoutValue = pistol ? 800 : ps.economy.spent + 900;
}
for (const ps of playerStats) stats[ps.subject].score += ps.score;
roundResults.push({
roundNum: i,
@@ -138,6 +143,13 @@ const LOL = [
{ pid: 9, champ: 222, team: 200, puuid: 'r-4', name: 'Nox', tag: '0420' }, // 징크스
{ pid: 10, champ: 89, team: 200, puuid: 'r-5', name: 'Mint', tag: '7777' }, // 레오나
];
const LANE = [
{ lane: 'MIDDLE', role: 'SOLO' },
{ lane: 'JUNGLE', role: 'NONE' },
{ lane: 'TOP', role: 'SOLO' },
{ lane: 'BOTTOM', role: 'DUO_CARRY' },
{ lane: 'BOTTOM', role: 'DUO_SUPPORT' },
];
export function makeDemoLol() {
seed = 23;
const dur = 28 * 60;
@@ -173,7 +185,13 @@ export function makeDemoLol() {
if ([13, 19].includes(m)) events.push({ type: 'BUILDING_KILL', timestamp: m * 60000 + 15000, killerId: 8, teamId: 100, buildingType: 'TOWER_BUILDING', position: { x: 5846, y: 6396 } });
events.sort((a, b) => a.timestamp - b.timestamp);
const pf: Record<string, any> = {};
for (const p of LOL) pf[String(p.pid)] = { totalGold: Math.round((p.team === 100 ? ga : gr) / 5) };
for (const p of LOL)
pf[String(p.pid)] = {
totalGold: Math.round((p.team === 100 ? ga : gr) / 5),
minionsKilled: (p.pid - 1) % 5 === 4 || (p.pid - 1) % 5 === 1 ? m : m * (6 + (p.pid % 3)),
jungleMinionsKilled: (p.pid - 1) % 5 === 1 ? m * 5 : 0,
xp: m * 420 + p.pid * 10,
};
frames.push({ timestamp: m * 60000, participantFrames: pf, events });
}
const items = [3031, 3089, 3157, 3020, 6655, 3135];
@@ -186,7 +204,31 @@ export function makeDemoLol() {
participantId: p.pid,
championId: p.champ,
teamId: p.team,
stats: { ...st[p.pid], totalMinionsKilled: range(30, 230), neutralMinionsKilled: p.pid === 2 || p.pid === 7 ? range(120, 180) : range(0, 15), goldEarned: Math.round((p.team === 100 ? ga : gr) / 5) + range(-800, 800), item0: pick(items), item1: pick(items), item2: pick(items), champLevel: range(13, 18), win: p.team === 100 },
spell1Id: p.pid === 2 || p.pid === 7 ? 11 : 4,
spell2Id: 14,
// 라인 · 역할 (LCU 경기 기록 형식)
timeline: LANE[(p.pid - 1) % 5],
stats: {
...st[p.pid],
totalMinionsKilled: range(30, 230),
neutralMinionsKilled: p.pid === 2 || p.pid === 7 ? range(120, 180) : range(0, 15),
goldEarned: Math.round((p.team === 100 ? ga : gr) / 5) + range(-800, 800),
item0: pick(items),
item1: pick(items),
item2: pick(items),
champLevel: range(13, 18),
win: p.team === 100,
// 범인찾기용 추가 지표 (난수를 더 쓰지 않는다: 다른 시연 데이터가 바뀌지 않게)
totalDamageDealtToChampions: 9000 + p.pid * 1700,
totalDamageTaken: 15000 + ((p.pid * 3700) % 11000),
visionScore: (p.pid - 1) % 5 === 4 ? 62 : 14 + p.pid * 2,
wardsPlaced: (p.pid - 1) % 5 === 4 ? 48 : 9 + p.pid,
wardsKilled: 3 + (p.pid % 4),
visionWardsBoughtInGame: (p.pid - 1) % 5 === 4 ? 9 : 2,
damageDealtToObjectives: 4000 + p.pid * 900,
damageDealtToTurrets: 1200 + p.pid * 400,
timeCCingOthers: 10 + p.pid * 3,
},
})),
participantIdentities: LOL.map((p) => ({ participantId: p.pid, player: { puuid: p.puuid, gameName: p.name, tagLine: p.tag } })),
teams: [

View File

@@ -146,6 +146,35 @@ export interface MatchPlayer {
items?: { id: number; name: string; icon: string | null }[];
rank?: string | null;
userId?: string;
/** 범인찾기용 추가 지표 (v1.3~ 에 저장한 경기만 있다) */
stats?: PlayerStats;
}
/** 경기 상세에서 더 저장하는 지표. 예전 경기는 없다 (범인찾기는 "기본 기록으로 분석"으로 표시) */
export interface PlayerStats {
/** 발로란트: 요원 역할(타격대·척후대·전략가·감시자) / 롤: 포지션(탑·정글·미드·원딜·서폿, 추정) */
role?: string;
/** 발로란트: 준 피해 합 / 롤: 챔피언에게 준 피해 */
damage?: number;
rounds?: number;
// 발로란트
headshotPct?: number;
firstKills?: number;
firstDeaths?: number;
plants?: number;
defuses?: number;
abilityCasts?: number;
// 롤
damageTaken?: number;
vision?: number;
wardsPlaced?: number;
wardsKilled?: number;
controlWards?: number;
objectiveDamage?: number;
turretDamage?: number;
ccSeconds?: number;
at10?: { cs: number; gold: number; xp: number };
at15?: { cs: number; gold: number; xp: number };
}
export interface MatchRound {
@@ -155,7 +184,11 @@ export interface MatchRound {
win: boolean;
result: string;
score: { ally: number; enemy: number };
economy?: Record<string, { spent: number; remaining: number; weapon?: string }>;
economy?: Record<string, { spent: number; remaining: number; weapon?: string; loadout?: number }>;
/** 이 라운드에서 우리 팀이 공격이었나 (v1.3~) */
allyAttack?: boolean;
/** 선수별 이 라운드 킬 · 준 피해 (v1.3~) */
players?: Record<string, { kills: number; damage: number }>;
}
export interface MatchDetail extends MatchSummary {
@@ -185,7 +218,97 @@ export interface UserProfile {
matches: MatchSummary[];
}
// ------------------------------------------------------------------ 범인찾기 (계획서 v1.1)
/** ready = 분석 가능, done = 분석 완료, pending = 준비 중(경기 진행 · 음성 변환), blocked = 기록 부족 */
export interface CulpritEligibility {
state: 'ready' | 'done' | 'pending' | 'blocked';
reasons: string[];
}
export interface CulpritPlayer {
/** P1~P10 (우리 팀 먼저) */
id: string;
puuid: string;
name: string;
team: 'ally' | 'enemy';
character: { id: string; name: string; icon: string | null } | null;
userId: string | null;
/** 이 경기 음성 대화가 있는지 */
voice: boolean;
}
/** 근거 번호가 가리키는 것 (사이트에서 누르면 그 순간으로 이동) */
export type CulpritRefTarget =
| { kind: 'utterance'; id: string; ts: number }
| { kind: 'event'; id: string; ts: number; round?: number }
| { kind: 'round'; round: number; ts: number }
| { kind: 'stat'; pid: string };
/** 앱이 만든 AI 입력 (사이트 서버만 받는다) */
export interface CulpritInput {
game: GameType;
text: string;
refs: Record<string, CulpritRefTarget>;
players: CulpritPlayer[];
stats: { utterances: number; utterancesTotal: number; events: number; chats: number; rounds: number; basic: boolean };
}
export interface CulpritEvidence {
ref: string;
note: string;
target?: CulpritRefTarget;
}
export const CULPRIT_TAGS = ['캐리', '숨은 MVP', '클러치', '무난', '아쉬움', '범인'] as const;
export interface CulpritResult {
summary: string;
confidence: 'high' | 'medium' | 'low';
confidence_note: string;
teams: { team: 'ally' | 'enemy'; culprit: string; reason: string; evidence: CulpritEvidence[] }[];
players: { id: string; score: number; tag: (typeof CULPRIT_TAGS)[number]; comment: string; evidence: CulpritEvidence[] }[];
}
export interface CulpritAnalysis {
id: string;
matchId: string;
createdAt: number;
createdBy: { id: string; name: string };
model: string;
result: CulpritResult;
players: CulpritPlayer[];
meta: {
tone?: string;
durationMs?: number;
costUsd?: number;
usage?: { input: number; output: number; cacheRead?: number; cacheWrite?: number };
inputStats?: CulpritInput['stats'];
fallback?: boolean;
};
}
export interface CulpritMatchItem {
match: MatchSummary;
eligibility: CulpritEligibility;
culprits: { team: 'ally' | 'enemy'; name: string; character: { id: string; name: string; icon: string | null } | null }[];
}
export interface CulpritMatchInfo {
match: MatchSummary;
eligibility: CulpritEligibility;
sources: { rounds: number | null; events: number; utterances: number; chats: number; extraStats: boolean };
players: CulpritPlayer[];
analysis: CulpritAnalysis | null;
history: { id: string; at: number; by: { id: string; name: string }; model: string; current: boolean }[];
}
/** 사이트 서버의 예산 · 권한 (GET /api/culprit/budget) */
export interface CulpritBudget {
enabled: boolean;
canAnalyze: boolean;
canReanalyze: boolean;
monthSpentUsd: number;
monthLimitUsd: number;
todayCount: number;
dailyLimit: number;
estimateUsd: number;
model: string;
running: string[];
}
export type CulpritStage = 'collect' | 'thinking' | 'verify' | 'done' | 'failed';
export type LiveEvent =
| { type: 'culprit.progress'; data: { matchId: string; stage: CulpritStage; message?: string } }
| { type: 'utterance.created' | 'utterance.updated'; data: UtteranceItem }
| { type: 'event.created'; data: EventItem }
| { type: 'match.updated'; data: MatchSummary }