File size: 5,495 Bytes
93131a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import { readFile } from 'node:fs/promises';
import { REFEREE_ONLY_MODE, REFEREE_ONLY_PROTOCOL, TACTICAL_MODE, TACTICAL_DEMO_MODE } from './arena.mjs';
import { createArenaHarness, REFEREE_RULE_CARD_VERSION, SELF_REVIEW_VERSION } from './arena-harness.mjs';
import { routes, hasKey, TIME_BUDGET_MS } from './providers.mjs';
import { readRun, runTournament, reviewRun } from './records.mjs';
import { createStorageGuard } from '../benchmark/scripts/run-guards.mjs';

const [command, first, name = REFEREE_ONLY_MODE, effort = 'low', extra] = process.argv.slice(2);
const arenaConfig = new URL('../config/models.openrouter.json', import.meta.url);
const onGame = (game, done, total) => {
  const winner = game.winner === 1 ? game.black : game.white;
  console.log('[' + done + '/' + total + '] ' + game.black + ' vs ' + game.white + ' · ' + (game.winner ? winner : '和棋') + ' · ' + game.reason);
};

function onReview(game) {
  const accepted = game.events.filter(event => event.engine);
  const scored = accepted.filter(event => event.engine.status === 'scored').length;
  const firstIssue = accepted.find(event => event.engine.status === 'unavailable')?.engine.reason;
  console.log('Rapfi · 第 ' + game.id + ' 局 · 已评 ' + scored + '/' + accepted.length + ' 手'
    + (firstIssue ? ' · ' + firstIssue : ''));
}

function printReview(analysis, { tactical = false } = {}) {
  const { scored, total } = analysis.coverage;
  console.log('Rapfi 评分覆盖 ' + scored + '/' + total + ' 手');
  for (const row of analysis.summary) {
    console.log(row.id + ' · 均分 ' + (row.meanGrade?.toFixed(2) ?? '待评') + '/3 · ' + JSON.stringify(row.errors));
    console.log(`  漏一手胜 ${row.errors['missed-win'] ?? 0}/${row.winOpportunities} · 漏唯一防守 ${row.errors['missed-only-block'] ?? 0}/${row.onlyBlockOpportunities}`);
  }
  if (scored !== total) {
    if (tactical) {
      const provenLosses = analysis.games.flatMap(game => game.events).filter(event =>
        event.engine?.status === 'unavailable' && event.decision?.reason === 'unavoidable-win-next').length;
      if (provenLosses === total - scored) {
        console.log('另有 ' + provenLosses + ' 手无可用 Rapfi 估值,棋规已确认对方下一手有无法防住的胜点。');
        return;
      }
    }
    console.error('评棋尚未完成。可使用 npm run review 重跑评棋。');
    process.exitCode = 1;
  }
}

async function runBenchmark() {
  if (extra !== undefined) throw new Error('参数过多');
  if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(name) || name === 'demo') {
    throw new Error('赛事名称只接受英文字母、数字、下划线和连字符,且 demo 为保留名称');
  }
  const config = JSON.parse(await readFile(first ?? arenaConfig, 'utf8'));
  const models = routes(config, { reasoning: effort });
  if (models.length < 2) throw new Error('比赛至少需要两个模型');
  if (models.some(route => route.provider !== 'openrouter')) {
    throw new Error('纯裁判赛请使用 config/models.openrouter.json 或同格式的 OpenRouter 配置');
  }
  const missing = [...new Set(models.filter(route => !hasKey(route)).map(route => route.key))];
  if (missing.length) throw new Error('缺少 API 凭据:' + missing.join(', '));

  const selfReview = command === 'bench-self-review';
  const concurrency = Number(process.env.GOMOKU_PARALLEL_GAMES ?? 1);
  const beforeWrite = process.platform === 'win32' ? createStorageGuard() : undefined;
  const harness = createArenaHarness(async (url, options) => {
    await beforeWrite?.();
    return fetch(url, options);
  }, { selfReview });
  const entries = models.map(route => ({
    id: route.id,
    version: route.version,
    protocol: REFEREE_ONLY_PROTOCOL,
    ruleCardVersion: REFEREE_RULE_CARD_VERSION,
    reasoning: route.reasoning,
    control: route.thinking,
    routing: route.routing,
    limits: { maxTokens: route.maxTokens ?? null, timeoutMs: route.timeoutMs ?? TIME_BUDGET_MS },
    ...(selfReview && { selfReview: SELF_REVIEW_VERSION }),
    move: (game, submission, previousPlan) => harness.move(route, game, submission, previousPlan),
  }));
  const result = await runTournament({ name, mode: REFEREE_ONLY_MODE, entries, concurrency, onGame, beforeWrite });
  console.table(result.leaderboard);
  console.log(result.path);
}

async function main() {
  if (command === 'bench' || command === 'bench-self-review') return runBenchmark();
  if (!['verify', 'review'].includes(command) || !first || process.argv.length !== 4) {
    throw new Error('命令:bench 或 bench-self-review [配置] [赛事名] [off|low|medium|high] | verify <棋谱路径> | review <棋谱路径>');
  }
  const original = await readRun(first, { includeAnalysis: false });
  if (command === 'verify') {
    console.log('复核 ' + original.games.length + '/' + original.total + ' 局 · ' + (original.complete ? '赛事结束' : '赛程未完'));
    console.table(original.leaderboard);
    return;
  }
  if (!original.games.length) throw new Error('没有已完成的对局可评');
  const { createRapfi } = await import('./rapfi.mjs');
  const engine = await createRapfi();
  try {
    const run = await reviewRun(first, engine, onReview);
    printReview(run.analysis, { tactical: [TACTICAL_MODE, TACTICAL_DEMO_MODE].includes(run.mode) });
  } finally {
    await engine.close();
  }
}

main().catch(error => { console.error(error.message); process.exitCode = 1; });