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>)[]; culprit?: Partial> }) { // 앱 코어 (실제 범인찾기 코드 + 시연 경기) 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[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']); // 보낸 프롬프트: 지시문 + 발로란트 지식 묶음(파일 스냅샷) + 말투 중간맛, 경기 자료는 안 const sent = h.seen[0]; assert.match(sent.system, /^너는 겜녹이의 경기 분석가다/); assert.match(sent.system, /말투: medium\(중간맛\)/); assert.match(sent.system, /[\s\S]*## 자동 갱신 \(2026-10-15 스냅샷\)/); assert.ok(!sent.system.includes('