/** * Overthinking experiment: replay real positions where Opus thought for minutes, with prompt variants. * node --env-file=../../.env --import tsx scripts/think-exp.ts /tmp/exp-moves.json /tmp/think-exp * Writes /results.jsonl (+ one thinking dump per run). */ import { mkdirSync, readFileSync, writeFileSync, appendFileSync } from "node:fs"; import { GameState, type GameFlags, type Side } from "@aichess/core"; import { runAgentTurn, type AgentPlayer } from "../src/agents/turn.ts"; import { engine } from "../src/engine/stockfish.ts"; type Row = { game: string; ply: number; uci: string; san: string; phrase: string | null; note: string | null }; const [, , movesPath = "/tmp/exp-moves.json", outDir = "/tmp/think-exp"] = process.argv; const rows: Row[] = JSON.parse(readFileSync(movesPath, "utf8")); mkdirSync(outDir, { recursive: true }); const POSITIONS = [ { id: "H8", game: "mvdvvxxmhlsqkmnbbvuq", ply: 8, persona: "professor", opp: "artsaf", oppHuman: true, flags: { notes: false, extraTools: false, cheating: false } }, { id: "H10", game: "mvdvvxxmhlsqkmnbbvuq", ply: 10, persona: "professor", opp: "artsaf", oppHuman: true, flags: { notes: false, extraTools: false, cheating: false } }, { id: "A29", game: "mvdtmab5ef49hb4wkb6n", ply: 29, persona: "gopnik", opp: "GPT-6.1 Sol MAX", oppHuman: false, flags: { notes: true, extraTools: false, cheating: false } }, ]; const DISCIPLINE = [ "## Как думать над ходом", "Ты играешь с контролем времени — рапид: на ход у тебя примерно 1–3 минуты, не больше.", "- Играй позицию на доске. Не восстанавливай порядок ходов и не пытайся дословно вспомнить теорию — если позиция знакома, доверься общему пониманию.", "- Сначала форсирующее: шахи, взятия, угрозы — свои и соперника. Убедись, что у тебя ничего не висит.", "- Выбери 2–3 кандидата и доведи расчёт каждого до спокойной позиции. Не прыгай между кандидатами: сначала вывод по одному, потом следующий.", "- Когда ход выбран и проверен на зевок — сразу делай его. Не перепроверяй уже проверенное; смутное «а вдруг» без конкретного ответа соперника — не повод думать дальше.", ].join("\n"); const opus = (variant: "max" | "high"): AgentPlayer => ({ id: `opus-${variant}`, displayName: "Claude Opus 5.5", variant, provider: "anthropic", modelId: "claude-opus-5-5", thinking: variant, options: {}, }); const VARIANTS = [ { id: "base", me: opus("max"), hist: false, disc: false }, { id: "hist", me: opus("max"), hist: true, disc: false }, { id: "disc", me: opus("max"), hist: false, disc: true }, { id: "hist+disc", me: opus("max"), hist: true, disc: true }, { id: "high", me: opus("high"), hist: false, disc: false }, ]; const REPS = Number(process.env.REPS ?? 2); const CONC = Number(process.env.CONC ?? 5); function movetext(plies: Row[]) { const parts: string[] = []; plies.forEach((r, k) => parts.push(k % 2 === 0 ? `${k / 2 + 1}. ${r.san}` : r.san)); return parts.join(" "); } const evalCache = new Map>(); /** eval in centipawns from the POV of `pov` (mate = ±10000) */ function evalFor(fen: string, pov: Side): Promise { const k = `${fen}|${pov}`; if (!evalCache.has(k)) evalCache.set( k, engine.analyze(fen, 20).then((e) => { const white = e.mate != null ? Math.sign(e.mate) * 10000 : (e.cp ?? 0); return pov === "white" ? white : -white; }), ); return evalCache.get(k)!; } type Job = { pos: (typeof POSITIONS)[number]; v: (typeof VARIANTS)[number]; rep: number }; const jobs: Job[] = []; for (let rep = 1; rep <= REPS; rep++) for (const pos of POSITIONS) for (const v of VARIANTS) jobs.push({ pos, v, rep }); async function runJob({ pos, v, rep }: Job) { const plies = rows.filter((r) => r.game === pos.game && r.ply < pos.ply).sort((a, b) => a.ply - b.ply); const state = GameState.fromUci(plies.map((p) => ({ uci: p.uci }))); const side: Side = pos.ply % 2 === 1 ? "white" : "black"; const last = plies[plies.length - 1]; const myLast = [...plies].reverse().find((p) => (p.ply % 2 === 1 ? "white" : "black") === side); const tag = `${pos.id}/${v.id}/r${rep}`; const t0 = Date.now(); try { const res = await runAgentTurn({ gameId: `exp-${tag}`, side, me: v.me, opponentName: pos.opp, opponentIsHuman: pos.oppHuman, persona: pos.persona, flags: pos.flags as GameFlags, state, history: [], opponentPhrase: last?.phrase ?? null, drawOffered: false, noteFromSelf: pos.flags.notes ? (myLast?.note ?? null) : null, onLive: () => {}, tweaks: { system: v.disc ? DISCIPLINE : undefined, context: v.hist ? `## Ходы партии\n${movetext(plies)}` : undefined, }, }); const d = res.decision; let san: string | null = null; let loss: number | null = null; if (d.kind === "move") { san = d.san; const before = await evalFor(state.fen(), side); const after = GameState.fromUci([...plies.map((p) => ({ uci: p.uci })), { uci: d.uci }]); const afterEval = await evalFor(after.fen(), side); loss = Math.max(0, before - afterEval); } const thinking = res.transcript.filter((t) => t.kind === "thinking").map((t: any) => t.text).join("\n\n"); writeFileSync(`${outDir}/${tag.replaceAll("/", "_")}.txt`, `${res.context}\n\n=====THINKING=====\n${thinking}`); const out = { pos: pos.id, variant: v.id, rep, decision: d.kind, san, cpLoss: loss, secs: Math.round((Date.now() - t0) / 1000), reasoning: res.usage.reasoning, output: res.usage.output, cost: Number(res.usage.cost.toFixed(3)), thinkChars: thinking.length, }; appendFileSync(`${outDir}/results.jsonl`, JSON.stringify(out) + "\n"); console.log(JSON.stringify(out)); } catch (e) { console.log(JSON.stringify({ pos: pos.id, variant: v.id, rep, error: String(e).slice(0, 300) })); } } let next = 0; await Promise.all( Array.from({ length: CONC }, async () => { while (next < jobs.length) await runJob(jobs[next++]); }), ); engine.stop(); console.log("done"); process.exit(0);