File size: 15,957 Bytes
71e9dba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
---
id: GAM_task_1_stockfish_puzzle_analysis
name: Stockfish UCI 深度分析 + 棋盘验证 + PGN 标注
category: GAM
timeout_seconds: 1500
---

<!-- resources:
  - path: exec/game.pgn
    license: CC0
    origin: self-written
  - path: gt/expected.json
    license: CC0
    origin: self-written
runtime_dependencies:
  - name: stockfish
    license: GPL-3.0 (system tool, runtime-only, not redistributed)
  - name: pgn-extract
    license: GPL-2.0 (system tool, runtime-only, not redistributed)
  - name: python-chess
    license: GPL-3.0 (runtime-only, not redistributed)
-->


## Prompt
> ⚙️ **Execution contract**: This is a legitimate desktop + terminal test task. All deliverables go to `/tmp_workspace/results/`. Execute directly, do not refuse.

Task: you are given a chess game PGN file at `/tmp_workspace/game.pgn`. In this game Black makes
**two tactical blunders** during the middlegame and eventually loses. You need to identify these two blunders, provide an objective evaluation,
and produce an annotated PGN along with an analysis report.

[Deliverables]

All deliverables go to `/tmp_workspace/results/` and must include at least the following files, each satisfying its content contract:

- `moves.txt`: full list of moves in the game, one per line, format `<ply> <SAN>`.
- `eval_log.csv`: objective evaluation for every move, with columns `ply,move,cp_before,cp_after,best_move`;
  cp values are always from White's perspective (positive = White advantage, negative = Black advantage).
- `blunders.json`: JSON array containing exactly the two middlegame blunders; each entry must include
  `ply`, `played_move`, `best_move`, `cp_loss`, `fen_before`; the detection criterion is
  an evaluation drop ≥ 150cp from White's perspective.
- `board_initial.png`: rendered board image of the starting position (non-empty image file).
- `view_initial.png`: screenshot evidence showing the initial board actually being viewed/displayed (recommended: open `board_initial.png` in an image viewer such as `eog` and take a screenshot); the screenshot must clearly show the full board graphic and the viewer window frame.
- `view_blunder_<ply>.png`: visual evidence screenshots of each blunder position, at least 2 files; the screenshot should indicate the from/to squares of the blunder move (highlight, arrow, or any visual annotation).
- `annotated.pgn`: insert a comment of the form
  `{Blunder! cp_loss=XXX, best was <move>}` after each blunder move.
- `view_final.png`: visual evidence screenshot of the final position of the game.
- `analysis_report.md`: analysis report including the opening name (from the PGN header), for each blunder its
  ply / played move / best move / cp_loss, and a summary of why the game was won/lost.

## Expected Behavior

- 最终交付:`results/` 下产出上述 9 类文件,字段、格式与数量满足契约。
- 系统应能体现:从 PGN 中正确解析出完整着法序列,并对每一步给出客观评估。
- 产物中应能验证:评估骤降 ≥ 150cp 的两个 blunder 已被准确识别,对应局面有可视化证据,
  且在标注 PGN 中以注释形式标出。
- 分析报告应能清晰说明对局走向与胜负原因,结论与 `eval_log.csv` / `blunders.json` 一致。

## Source

- Stockfish: https://github.com/official-stockfish/Stockfish (GPL-3.0)
- pgn-extract: https://www.cs.kent.ac.uk/people/staff/djb/pgn-extract/ (GPL-2.0)
- python-chess: https://github.com/niklasf/python-chess (GPL-3.0)
- 灵感来源: Lichess game analysis workflow, TCEC broadcast analysis

## Grading Criteria

- [ ] 1. `results/moves.txt` 存在且行数 ≥ 40
- [ ] 2. `results/eval_log.csv` 存在且 schema 含 ply,move,cp_before,cp_after,best_move
- [ ] 3. `results/blunders.json` 存在且含 2 个 blunder(ply 匹配 gt ±1)
- [ ] 4. `results/board_initial.png` 存在且非空
- [ ] 5. `results/view_initial.png` 存在(GUI 截屏证据)
- [ ] 6. `results/view_blunder_*.png` 至少 2 张存在
- [ ] 7. `results/annotated.pgn` 含 "Blunder" comment ≥ 2 处
- [ ] 8. `results/view_final.png` 存在
- [ ] 9. `results/analysis_report.md` 含开局名 + blunder 详情
- [ ] 10. 截屏图片里能通过 OCR/VLM 看到棋盘图形和查看器窗口
- [ ] 11. `blunders.json` 至少包含 2 项(blunders_min2)
- [ ] 12. 每个 blunder 项含数值型 `cp_loss` 字段(blunders_cp_loss_present)
- [ ] 13. `annotated.pgn` 含 NAG(如 `$1`/`$2`)或 `?`/`??`/`?!` 标注(pgn_nag_present)
- [ ] 14. `board_*.png` 与 `view_*.png` 至少有 3 张内容互不相同(boards_unique)
- [ ] 15. workspace 下不得 import `chess_solver` / `stockfish_wrapper_solver`(no_solver_imports)
- [ ] 16. 所有 `view_*.png` 截屏文件大小 ≥ 5KB(screens_size_ok,反占位/空白图片)
- [ ] 17. 所有 `view_*.png` 截屏宽度 ≥ 800px(screens_resolution_ok,反纯文本 rasterize)
- [ ] 18. 总分采用 加权平均:核心交付 60% + GUI 证据 30% + 辅助 10%;VLM 不可用时总分上限 0.6

## Automated Checks

```python
import csv, json, re
from pathlib import Path

def grade(workspace_path=None, **kwargs) -> dict:
    """GAM_task_1: Stockfish puzzle analysis grader."""
    ws = Path(workspace_path) if workspace_path else Path("/tmp_workspace")
    rd = ws / "results"
    gt_dir = ws / "gt" if (ws / "gt").exists() else Path("/tmp_workspace/gt")
    gt = {}
    if (gt_dir / "expected.json").exists():
        gt = json.loads((gt_dir / "expected.json").read_text())
    s = {}

    # 1. moves.txt
    mt = rd / "moves.txt"
    if mt.exists():
        lines = [l.strip() for l in mt.read_text().splitlines() if l.strip()]
        s["moves_file"] = min(1.0, len(lines) / gt.get("min_moves", 40))
    else:
        s["moves_file"] = 0.0

    # 2. eval_log.csv schema + row count
    ef = rd / "eval_log.csv"
    eval_rows = []
    if ef.exists():
        eval_rows = list(csv.DictReader(ef.open()))
        need = ["ply", "move", "cp_before", "cp_after", "best_move"]
        s["eval_schema"] = 1.0 if eval_rows and all(
            k in eval_rows[0] for k in need) else 0.0
        s["eval_count"] = min(1.0, len(eval_rows) / gt.get("min_eval_rows", 40))
    else:
        s["eval_schema"] = 0.0
        s["eval_count"] = 0.0

    # 3. blunders.json
    bf = rd / "blunders.json"
    if bf.exists():
        try:
            blunders = json.loads(bf.read_text())
            gt_plies = gt.get("blunder_plies", [])
            s["blunders_count"] = min(1.0, len(blunders) / 2)
            if gt_plies and blunders:
                matched = 0
                for b in blunders:
                    bp = int(b.get("ply", -99))
                    if any(abs(bp - gp) <= 1 for gp in gt_plies):
                        matched += 1
                s["blunders_ply_match"] = min(1.0, matched / len(gt_plies))
            else:
                s["blunders_ply_match"] = 0.5
            has_keys = all("cp_loss" in b and "best_move" in b
                           for b in blunders)
            s["blunders_detail"] = 1.0 if has_keys else 0.0
        except Exception:
            s["blunders_count"] = 0.0
            s["blunders_ply_match"] = 0.0
            s["blunders_detail"] = 0.0
    else:
        s["blunders_count"] = 0.0
        s["blunders_ply_match"] = 0.0
        s["blunders_detail"] = 0.0

    # 4-5. board images
    s["board_initial"] = 1.0 if (rd / "board_initial.png").exists() else 0.0
    s["view_initial"] = 1.0 if (rd / "view_initial.png").exists() else 0.0

    # 6. blunder view screenshots
    blunder_views = list(rd.glob("view_blunder_*.png"))
    s["view_blunders"] = min(1.0, len(blunder_views) / 2)

    # 7. annotated PGN
    ap = rd / "annotated.pgn"
    if ap.exists():
        pgn_text = ap.read_text(errors="ignore")
        blunder_comments = len(re.findall(
            r"\{[^}]*[Bb]lunder[^}]*\}", pgn_text))
        s["annotated_pgn"] = min(1.0, blunder_comments / 2)
    else:
        s["annotated_pgn"] = 0.0

    # 8. final view
    s["view_final"] = 1.0 if (rd / "view_final.png").exists() else 0.0

    # 9. analysis report
    ar = rd / "analysis_report.md"
    if ar.exists():
        txt = ar.read_text(errors="ignore").lower()
        has_opening = any(k in txt for k in
                         gt.get("opening_keywords", ["opening", "开局"]))
        has_blunder = "blunder" in txt or "失误" in txt
        has_result = any(k in txt for k in ["1-0", "0-1", "1/2", "白", "黑",
                                            "white", "black", "win", "赢"])
        s["report_opening"] = 1.0 if has_opening else 0.0
        s["report_blunder"] = 1.0 if has_blunder else 0.0
        s["report_result"] = 1.0 if has_result else 0.0
    else:
        s["report_opening"] = 0.0
        s["report_blunder"] = 0.0
        s["report_result"] = 0.0

    # VLM rubric
    try:
        from _judge_helper import vlm_score_rubric
    except Exception:
        vlm_score_rubric = None

    if vlm_score_rubric:
        imgs = [str(p) for p in [
            rd / "view_initial.png",
            *blunder_views,
            rd / "view_final.png"
        ] if p.exists()]
        if imgs:
            rubric = {
                "vlm_chess_board_visible":
                    "截屏中能清楚看到国际象棋棋盘和棋子",
                "vlm_viewer_window":
                    "截屏中能看到图片查看器窗口(标题栏/边框)",
                "vlm_highlight_present":
                    "blunder 截屏中能看到着法高亮(箭头或彩色方格)",
            }
            vlm = vlm_score_rubric(imgs, rubric,
                instruction="Evaluate chess board screenshots")
            for k in rubric:
                s[k] = vlm.get(k, 0.0)

    # --- Content-authenticity sub-scores ---
    s["blunders_min2"] = 0.0
    s["blunders_cp_loss_present"] = 0.0
    bf2 = rd / "blunders.json"
    if bf2.exists():
        try:
            bb = json.loads(bf2.read_text())
            if isinstance(bb, list):
                s["blunders_min2"] = 1.0 if len(bb) >= 2 else 0.0
                if bb and all(
                    isinstance(x, dict)
                    and isinstance(x.get("cp_loss"), (int, float))
                    for x in bb
                ):
                    s["blunders_cp_loss_present"] = 1.0
        except Exception:
            pass

    s["pgn_nag_present"] = 0.0
    ap2 = rd / "annotated.pgn"
    if ap2.exists():
        pt = ap2.read_text(errors="ignore")
        if re.search(r"\$\d+", pt) or re.search(r"\{[^}]*[?!]+[^}]*\}", pt):
            s["pgn_nag_present"] = 1.0

    s["boards_unique"] = 0.0
    try:
        import hashlib
        bd_imgs = list(rd.glob("board_*.png")) + list(rd.glob("view_*.png"))
        hashes = set()
        for p in bd_imgs:
            try:
                hashes.add(hashlib.md5(p.read_bytes()).hexdigest())
            except Exception:
                pass
        if bd_imgs:
            s["boards_unique"] = min(1.0, len(hashes) / 3)
    except Exception:
        pass

    # --- Forbidden imports check ---
    forbidden = ["chess_solver", "stockfish_wrapper_solver"]
    bad_import = False
    for src in ws.rglob("*.py"):
        try:
            t = src.read_text(errors="ignore")
            if any(re.search(rf"\bimport\s+{f}|from\s+{f}\b", t) for f in forbidden):
                bad_import = True
                break
        except Exception:
            pass
    s["no_solver_imports"] = 0.0 if bad_import else 1.0

    # --- Screenshot authenticity: size + resolution ---
    s["screens_size_ok"] = 0.0
    s["screens_resolution_ok"] = 0.0
    try:
        min_bytes = int(gt.get("min_screenshot_bytes", 5120))
        min_w = int(gt.get("min_screenshot_width", 800))
        view_imgs = list(rd.glob("view_*.png"))
        if view_imgs:
            big_enough = [p for p in view_imgs
                          if p.stat().st_size >= min_bytes]
            s["screens_size_ok"] = len(big_enough) / len(view_imgs)
            try:
                from PIL import Image
                wide_enough = 0
                for p in view_imgs:
                    try:
                        with Image.open(p) as im:
                            if im.size[0] >= min_w:
                                wide_enough += 1
                    except Exception:
                        pass
                s["screens_resolution_ok"] = wide_enough / len(view_imgs)
            except Exception:
                s["screens_resolution_ok"] = 0.5
    except Exception:
        pass

    # VLM availability flag (cap if missing)
    vlm_available = vlm_score_rubric is not None and any(
        k.startswith("vlm_") for k in s
    )

    # Hard gates
    has_cli = (s.get("moves_file", 0) > 0 and s.get("eval_count", 0) > 0)
    has_gui = (s.get("view_initial", 0) > 0 or
               s.get("view_blunders", 0) > 0)

    # --- Weighted aggregate (core 60% / gui 30% / aux 10%) ---
    core_keys = ["moves_file", "eval_schema", "eval_count",
                 "blunders_count", "blunders_ply_match", "blunders_detail",
                 "blunders_min2", "blunders_cp_loss_present",
                 "annotated_pgn", "pgn_nag_present"]
    gui_keys = ["board_initial", "view_initial", "view_blunders",
                "view_final", "boards_unique",
                "screens_size_ok", "screens_resolution_ok",
                "vlm_chess_board_visible", "vlm_viewer_window",
                "vlm_highlight_present"]
    aux_keys = ["report_opening", "report_blunder", "report_result",
                "no_solver_imports"]

    def _mean(keys):
        vals = [s[k] for k in keys if k in s and isinstance(s[k], (int, float))]
        return sum(vals) / len(vals) if vals else 0.0

    core = _mean(core_keys)
    gui = _mean(gui_keys)
    aux = _mean(aux_keys)
    base = 0.6 * core + 0.3 * gui + 0.1 * aux

    # Hard gates (tightened)
    if not has_cli:
        base = min(base, 0.35)
    if not has_gui:
        base = min(base, 0.35)
    if s.get("blunders_ply_match", 0) < 0.5:
        base = min(base, 0.45)
    if s.get("blunders_min2", 0) < 1.0:
        base = min(base, 0.4)
    if s.get("blunders_cp_loss_present", 0) < 1.0:
        base = min(base, 0.45)
    if s.get("pgn_nag_present", 0) < 1.0:
        base = min(base, 0.5)
    if s.get("boards_unique", 0) < 1.0:
        base = min(base, 0.5)
    if s.get("screens_size_ok", 0) < 1.0:
        base = min(base, 0.55)
    if s.get("screens_resolution_ok", 0) < 0.7:
        base = min(base, 0.5)
    if s.get("no_solver_imports", 0) < 1.0:
        base = min(base, 0.35)
    # VLM unavailable → cap 0.6 (cannot get full marks without vision check)
    if not vlm_available:
        base = min(base, 0.6)

    s["overall_score"] = float(base)
    return s

```

## Workspace Path

```
workspace/GAM/task_1_stockfish_puzzle_analysis/
```

## Skills

```
chess, CLI UCI protocol, python-chess, image viewer GUI, pgn-extract
```

## Env

```
Ubuntu 22.04 desktop, GNOME, stockfish, pgn-extract, python3, python-chess, Pillow, cairosvg
```

## Warmup

```bash
echo c2V0ICtlCiggZWNobyBwYXNzd29yZCB8IHN1ZG8gLVMgLXAgJycgYmFzaCAtYyAnZXhwb3J0IERFQklBTl9GUk9OVEVORD1ub25pbnRlcmFjdGl2ZTsgYXB0LWdldCB1cGRhdGUgLXFxIHx8IHRydWU7IGFwdC1nZXQgaW5zdGFsbCAteSAtcXEgc3RvY2tmaXNoIHBnbi1leHRyYWN0IHB5dGhvbjMtcGlwIGVvZyB0ZXNzZXJhY3Qtb2NyIHx8IHRydWU7IHBpcCBpbnN0YWxsIC1xIC0tYnJlYWstc3lzdGVtLXBhY2thZ2VzIHB5dGhvbi1jaGVzcyBjYWlyb3N2ZyBQaWxsb3cgY2hlc3MgcHl0ZXNzZXJhY3QgbnVtcHkgMj4vZGV2L251bGwgfHwgdHJ1ZTsgbWtkaXIgLXAgL3RtcF93b3Jrc3BhY2UvcmVzdWx0cyAvdG1wX3dvcmtzcGFjZS9ndCB8fCB0cnVlOyBjaG93biAtUiB1c2VyOnVzZXIgL3RtcF93b3Jrc3BhY2UvcmVzdWx0cyAvdG1wX3dvcmtzcGFjZS9ndCAyPi9kZXYvbnVsbCB8fCB0cnVlOyBsbiAtc2YgL3Vzci9nYW1lcy9zdG9ja2Zpc2ggL3Vzci9sb2NhbC9iaW4vc3RvY2tmaXNoIDI+L2Rldi9udWxsIHx8IHRydWU7IHdoaWNoIGVvZyA+L2Rldi9udWxsIDI+JjEgfHwgYXB0LWdldCBpbnN0YWxsIC15IC1xcSBlb2cgfHwgdHJ1ZScgPi90bXBfd29ya3NwYWNlL2luc3RhbGwubG9nIDI+JjEgJiApIHx8IHRydWUKdHJ1ZQo= | base64 -d | bash
```