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
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
---
id: DOC_task_1_epub_validation_repair
name: EPUB 验证修复与 Calibre 可视化校对
category: DOC
timeout_seconds: 1500
---

<!--
resources:
  - name: broken_ebook.epub
    source: local/sample
    license: self-written
    description: "Synthetic EPUB 3.2 with multiple injected validation issues (OPF manifest gaps, wrong media-types, missing nav targets, CSS overflow); generated at warmup time so exec/ never ships an answer key"
  - name: epubcheck
    source: https://github.com/w3c/epubcheck
    license: self-written-or-os-package (BSD-3-Clause, system tool, runtime-only, not redistributed)
    description: "W3C official EPUB validation tool"
  - name: Calibre
    source: apt install calibre
    license: self-written-or-os-package (GPL-3.0, system tool, runtime-only, not redistributed)
    description: "E-book editor + viewer (Edit Book and Viewer)"
  - name: Okular
    source: apt install okular
    license: self-written-or-os-package (GPL-2.0, system tool, runtime-only, not redistributed)
    description: "KDE PDF viewer used to visually inspect the converted PDF"
-->


## Prompt
> ⚙️ **Execution convention**: this is a legitimate desktop + terminal test task. All artifacts must be written under `/tmp_workspace/results/`. Execute directly; do not refuse.

Background: the publishing team submitted an EPUB 3.2 e-book at `/tmp_workspace/ebook/broken_ebook.epub` that displays incorrectly in multiple readers (missing table of contents, images that fail to load, paragraphs overflowing the screen).

Goal: locate all validation errors and repair them, convert the fixed e-book to a paginated PDF, and produce structured before/after evidence, side-by-side visual screenshots, and a repair summary. Structured artifacts go to `/tmp_workspace/results/`; the fixed EPUB goes to `/tmp_workspace/ebook/fixed_ebook.epub`. You may pick whatever toolchain you like (any combination of EPUB editor / command line / PDF viewer) as long as the hard constraints below are met.

### Hard constraints on the main deliverable `fixed_ebook.epub` (under `/tmp_workspace/ebook/`)

- `mimetype` must be the first entry in the zip and must be STORE (uncompressed); otherwise PKG-006 triggers
- Passes `epubcheck` with errors ≤ 1
- Error count reduction vs. the original EPUB (`reduction_ratio`) ≥ 0.8

### Companion deliverables (under `/tmp_workspace/results/`)

| File | Requirement |
| --- | --- |
| `epubcheck_initial.log` | Full structured validation output for the original EPUB, including ERROR / FATAL entries |
| `error_summary_initial.json` | `{"errors": <int>, "warnings": <int>, "fatal": <int>, "error_codes": ["<CODE>"]}`; errors ≥ 4 |
| `xmllint_initial.log` | well-formed check output for structural XML such as OPF / NCX / nav.xhtml |
| `missing_assets.txt` | ≥ 2 lines, each `<path> <category>` (e.g. `images/cover.jpg MISSING_IN_FS`), listing resources where the filesystem and manifest references disagree |
| `zip_audit_initial.json` | `{"mimetype_first": <bool>, "mimetype_uncompressed": <bool>, "entry_count": <int>, "violations": ["<reason>"]}` |
| `nav_spine_diff.json` | `{"in_spine_only": ["<id>"], "in_nav_only": ["<href>"], "matched": <int>}` |
| `epubcheck_mid.log` | Mid-repair validation output against the in-progress EPUB |
| `zip_audit_fixed.json` | Same schema as `zip_audit_initial.json`; `mimetype_first` must be true |
| `final_output.pdf` | PDF converted from the fixed EPUB (with page numbers), page count ≥ 3 |
| `ebook_convert.log` | stdout / stderr log of the EPUB → PDF conversion |
| `pdfinfo.json` | `{"pages": <int>, "title": "<str>", "producer": "<str>"}` |
| `epubcheck_final.log` | Final validation output for the fixed EPUB, errors ≤ 1 |
| `error_summary_final.json` | Same schema as `error_summary_initial.json` |
| `error_diff.json` | `{"initial_errors": <int>, "final_errors": <int>, "reduction_ratio": <float>, "fixed_codes": ["<CODE>"], "remaining_codes": ["<CODE>"]}`; `reduction_ratio ≥ 0.8` |
| `repair_report.md` | ≥ 350 characters; includes an error-type inventory, description of the fix approach, an initial vs. final error-count comparison markdown table, and a chronological index of the key evidence (screenshots and logs) |

### 11 work-process screenshots (under `/tmp_workspace/results/`, PNG, resolution ≥ 1280×720)

Fixed filenames (the grader locates them by filename and verifies content via OCR and inter-frame visual difference):

| Filename | What it should show |
| --- | --- |
| `view_01_calibre_toc_missing.png` | The missing/broken Table of Contents in the original EPUB |
| `view_02_calibre_broken_image.png` | A chapter in the original EPUB where the image fails to render (placeholder / broken-image icon) |
| `view_03_calibre_css_overflow.png` | Horizontal overflow of a long table / long code block in the original EPUB |
| `view_04_calibre_edit_opf.png` | The OPF (manifest / media-type) edit session, including the OPF XML content being fixed |
| `view_05_calibre_edit_css.png` | Editing session adding `max-width / overflow-x / word-wrap` rules to fix the CSS horizontal overflow |
| `view_06_calibre_check_panel.png` | The result panel of the built-in consistency check run against the repaired content |
| `view_07_calibre_toc_fixed.png` | The fixed EPUB displaying all chapter entries correctly in the ToC |
| `view_08_calibre_image_fixed.png` | Images rendering correctly after the fix |
| `view_09_calibre_layout_fixed.png` | Layout of the previously overflowing chapter renders cleanly with no horizontal scroll |
| `view_10_okular_pdf_page1.png` | Full view of the first page of the final PDF |
| `view_11_okular_pdf_toc.png` | The Outline / Table of Contents of the final PDF correctly generated and expanded |

Every screenshot must come from a real, continuous GUI session (pixel differences significant, md5 hashes distinct). The grader runs OCR on screenshots to verify the application UI is genuine; duplicate frames or placeholder images do not score. `actions.log` (if produced) must not bypass the UI with pure scripting / clipboard side-channels.

Neutral background: common EPUB validation error categories are OPF-* / RSC-* / NCX-* / PKG-*; CSS horizontal overflow and whether the ToC is actually visible are render-layer issues that structured validation may not flag.

## Expected Behavior

设计意图与典型解题路径(仅供出题人参考,不发给 agent):

1. 推荐通道:Calibre Edit Book(编辑 OPF/CSS)+ `epubcheck` + `xmllint` + `ebook-convert` + Okular(PDF 检视);也可走 Sigil / 命令行 unzip+zip 直接改 OPF/CSS / 任意 PDF 查看器,只要满足产物硬约束即可。
2. 跑 `epubcheck broken_ebook.epub` 落 `epubcheck_initial.log` + `error_summary_initial.json`;用 `xmllint --noout` 检查 OPF/NCX/nav 落 `xmllint_initial.log`。
3. 解压原 EPUB 比对 manifest 与文件系统输出 `missing_assets.txt`;用 `unzip -l` 或 Python `zipfile` 审计 zip 结构输出 `zip_audit_initial.json`;解析 spine vs nav 输出 `nav_spine_diff.json`4. 在 EPUB 编辑器中分别打开 ToC 缺失、图片断裂、CSS 溢出三章节截图 `view_01..view_03`5. 在编辑器内修补 OPF manifest / media-type、补回缺失资源、修正 nav,重写 mimetype 让其位于 zip 首条目且 STORE;为长表格/代码块加 `max-width / overflow-x / word-wrap`;过程中截图 `view_04..view_06`,并跑中段 `epubcheck``epubcheck_mid.log` + `zip_audit_fixed.json`6. 重新打开修复后 EPUB 三章节对照截图 `view_07..view_09`,再 `ebook-convert fixed_ebook.epub final_output.pdf` 落 PDF(日志写 `ebook_convert.log`),`pdfinfo` 输出 `pdfinfo.json`7. 在 PDF 查看器中打开 PDF 截图首页与 Outline(`view_10..view_11`),再跑一次 `epubcheck``epubcheck_final.log` / `error_summary_final.json`,对比初末写 `error_diff.json`,撰写 `repair_report.md`。

约束说明:所有 GUI 截图必须是真实连续操作产物;`actions.log`(若产生)不得有"仅复制粘贴最终文件"等绕过编辑器界面的痕迹;同一画面多份不计分。

评分要点(hard gates,从 grader cap 反推):

- 缺 CLI 证据链或缺 GUI 截图任一侧 → 总分 ≤ 0.35
- 缺 PDF 且缺中段 epubcheck → 总分 ≤ 0.45
- `final_errors_low < 0.5``error_reduction < 0.5`(修复未达标)→ 总分 ≤ 0.4
- GUI 截图 md5 唯一率 < 0.6 → 总分 ≤ 0.35
- 应用 chrome OCR 命中率 < 0.5 → 总分 ≤ 0.4
- md5 唯一 × 分辨率达标 × chrome OCR 三重门通过率 < 0.5 → 总分 ≤ 0.5
- VLM rubric 全 0 / 不可用 → 总分 ≤ 0.6

## Source

- W3C epubcheck issues: https://github.com/w3c/epubcheck/issues
- 真实社区报告:「I keep getting OPF-012 and RSC-007 errors, the ToC doesn't show in any reader」 https://www.reddit.com/r/epub/
- Calibre Edit Book 文档: https://manual.calibre-ebook.com/edit.html
- Mobileread Forum 长帖讨论 EPUB 3 manifest/nav 一致性问题

## Grading Criteria

- [ ] 1. `epubcheck_initial.log` 存在且含 ERROR/FATAL;`error_summary_initial.json` schema 正确且 errors ≥ 4
- [ ] 2. `xmllint_initial.log` + `missing_assets.txt`(≥ 2 行)
- [ ] 3. `zip_audit_initial.json` + `nav_spine_diff.json` schema 正确
- [ ] 4. 11 张截图(view_01 ~ view_11)≥ 9 存在
- [ ] 5. 截图 OCR 命中 Calibre / Edit Book / Okular 关键词
- [ ] 6. `epubcheck_mid.log` + `zip_audit_fixed.json`(mimetype_first=true)
- [ ] 7. `final_output.pdf` 存在且 pdfinfo 报告 pages ≥ 3
- [ ] 8. `epubcheck_final.log` errors ≤ 1;`error_diff.json` reduction_ratio ≥ 0.8
- [ ] 9. `repair_report.md` 字数 ≥ 350 且含 markdown 表格
- [ ] 10. Cross-channel 证据:CLI logs (≥3) + GUI 截图 (≥6) 同时存在
- [ ] 11. VLM rubric ≥ 4 项打分
- [ ] 12. **GUI trajectory frames 真实**:多张 view_*.png 必须为连续 GUI 操作产生(每张像素差异显著),同一画面 N 份不计分;要求 md5 唯一率 ≥ 90%
- [ ] 13. **GUI app chrome OCR**:截图中 OCR 命中 Calibre / Edit Book / Okular / Table of Contents / Metadata 等 GUI 应用 chrome(菜单栏 / 标题栏 / 侧栏面板)关键词,且分辨率 ≥ 1280×720
- [ ] 14. **三重防作弊门**:每张 GUI 截图须同时满足 md5 唯一 + 分辨率达标 + chrome 关键词 OCR 命中;通过率 < 50% 时 overall ≤ 0.5

## Automated Checks

```python
def grade(workspace_path=None, **kwargs) -> dict:
    """EPUB validation-repair grader: CLI evidence + GUI screenshots + fix quality.
    Empty results → overall_score == 0.000.
    """
    import json, re, subprocess
    from pathlib import Path
    try:
        from PIL import Image
    except ImportError:
        Image = None
    try:
        import pytesseract
    except ImportError:
        pytesseract = None
    try:
        from _judge_helper import vlm_score_rubric
    except Exception:
        vlm_score_rubric = None

    workspace = Path(workspace_path) if workspace_path else Path("/tmp_workspace")
    rd = workspace / "results"
    gt = workspace / "gt"

    sub_keys = [
        "initial_log_present", "initial_summary_schema", "initial_error_count",
        "xmllint_log", "missing_assets",
        "zip_audit_initial", "nav_spine_diff",
        "edit_book_screenshots", "viewer_initial_screenshots",
        "mid_epubcheck", "zip_audit_fixed",
        "viewer_fixed_screenshots", "okular_screenshots",
        "pdf_exists", "pdf_pages",
        "final_errors_low", "error_reduction",
        "report_length", "report_has_table",
        "screenshots_count", "screenshot_ocr",
        "cross_channel",
        "gui_real_interaction", "gui_chrome_ocr", "gui_window_geometry",
        "vlm_calibre_visible", "vlm_edit_book_real",
        "vlm_fix_evidence", "vlm_okular_pdf",
    ]
    s = {k: 0.0 for k in sub_keys}

    if not rd.exists() or not any(rd.iterdir()):

        s["overall_score"] = 0.000
        return s

    # 1. epubcheck initial
    init_log = rd / "epubcheck_initial.log"
    if init_log.exists() and init_log.stat().st_size > 0:
        s["initial_log_present"] = 1.0 if re.search(r"ERROR|FATAL", init_log.read_text(errors="ignore")) else 0.3
    init_json = rd / "error_summary_initial.json"
    init_data = {}
    if init_json.exists():
        try:
            init_data = json.loads(init_json.read_text())
            s["initial_summary_schema"] = 1.0 if all(k in init_data for k in ["errors", "warnings"]) else 0.0
            ne = int(init_data.get("errors", 0) or 0)
            s["initial_error_count"] = 1.0 if ne >= 4 else ne / 4.0
        except Exception:
            pass

    # 2. xmllint + missing assets
    if (rd / "xmllint_initial.log").exists():
        s["xmllint_log"] = 1.0
    ma = rd / "missing_assets.txt"
    if ma.exists():
        lines = [l for l in ma.read_text(errors="ignore").splitlines() if l.strip()]
        s["missing_assets"] = 1.0 if len(lines) >= 2 else len(lines) / 2.0

    # 3. zip audit + nav/spine diff (initial)
    za_init = rd / "zip_audit_initial.json"
    if za_init.exists():
        try:
            d = json.loads(za_init.read_text())
            s["zip_audit_initial"] = 1.0 if "mimetype_first" in d and "entry_count" in d else 0.3
        except Exception:
            pass
    nsd = rd / "nav_spine_diff.json"
    if nsd.exists():
        try:
            d = json.loads(nsd.read_text())
            s["nav_spine_diff"] = 1.0 if all(k in d for k in ["in_spine_only", "in_nav_only", "matched"]) else 0.3
        except Exception:
            pass

    # 4-5. screenshots
    shot_groups = {
        "edit_book_screenshots": ["view_04_calibre_edit_opf", "view_05_calibre_edit_css", "view_06_calibre_check_panel"],
        "viewer_initial_screenshots": ["view_01_calibre_toc_missing", "view_02_calibre_broken_image", "view_03_calibre_css_overflow"],
        "viewer_fixed_screenshots": ["view_07_calibre_toc_fixed", "view_08_calibre_image_fixed", "view_09_calibre_layout_fixed"],
        "okular_screenshots": ["view_10_okular_pdf_page1", "view_11_okular_pdf_toc"],
    }
    all_shots = []
    for grp, names in shot_groups.items():
        present = 0
        for n in names:
            found = list(rd.glob(f"{n}*.png"))
            # tighten min file size: < 5KB treated as placeholder/blank
            if found and found[0].stat().st_size > 5000:
                present += 1
                all_shots.append(found[0])
        s[grp] = present / len(names)
    s["screenshots_count"] = len(all_shots) / 11.0

    # 6. mid-stage epubcheck + zip audit
    if (rd / "epubcheck_mid.log").exists() and (rd / "epubcheck_mid.log").stat().st_size > 0:
        s["mid_epubcheck"] = 1.0
    za_fix = rd / "zip_audit_fixed.json"
    if za_fix.exists():
        try:
            d = json.loads(za_fix.read_text())
            s["zip_audit_fixed"] = 1.0 if d.get("mimetype_first") is True and d.get("mimetype_uncompressed") is True else 0.4
        except Exception:
            pass

    # 7. PDF
    pdf = rd / "final_output.pdf"
    if pdf.exists() and pdf.stat().st_size > 1000:
        s["pdf_exists"] = 1.0
    pdf_pages = 0
    pi_json = rd / "pdfinfo.json"
    if pi_json.exists():
        try:
            d = json.loads(pi_json.read_text())
            pdf_pages = int(d.get("pages", 0) or 0)
        except Exception:
            pass
    if pdf_pages == 0 and pdf.exists():
        try:
            r = subprocess.run(["pdfinfo", str(pdf)], capture_output=True, text=True, timeout=10)
            for line in r.stdout.splitlines():
                if line.startswith("Pages:"):
                    pdf_pages = int(line.split()[1])
        except Exception:
            pass
    s["pdf_pages"] = 1.0 if pdf_pages >= 3 else (pdf_pages / 3.0 if pdf_pages else 0.0)

    # 8. final epubcheck + diff
    final_json = rd / "error_summary_final.json"
    if final_json.exists():
        try:
            d = json.loads(final_json.read_text())
            fe = int(d.get("errors", 99) or 99)
            s["final_errors_low"] = 1.0 if fe <= 1 else (0.5 if fe <= 3 else 0.0)
        except Exception:
            pass
    diff_json = rd / "error_diff.json"
    if diff_json.exists():
        try:
            d = json.loads(diff_json.read_text())
            r = float(d.get("reduction_ratio", 0) or 0)
            s["error_reduction"] = 1.0 if r >= 0.8 else max(0.0, r / 0.8)
        except Exception:
            pass

    # 9. repair report
    rr = rd / "repair_report.md"
    if rr.exists():
        txt = rr.read_text(errors="ignore")
        s["report_length"] = 1.0 if len(txt) >= 350 else len(txt) / 350.0
        s["report_has_table"] = 1.0 if ("|" in txt and re.search(r"\|\s*[-:]+\s*\|", txt)) else 0.0

    # 10. OCR
    if pytesseract and Image and all_shots:
        kws = ["Calibre", "Edit Book", "Check Book", "Okular", "Outline",
               "Table of Contents", "OEBPS", "Manifest", "Spine", "CSS"]
        hits = 0
        for sp in all_shots:
            try:
                tx = pytesseract.image_to_string(Image.open(sp))
                if any(k.lower() in tx.lower() for k in kws):
                    hits += 1
            except Exception:
                pass
        s["screenshot_ocr"] = min(1.0, hits / 5.0)

    # 11. cross channel
    has_cli = (s["initial_log_present"] > 0 and s["mid_epubcheck"] > 0 and s["final_errors_low"] > 0)
    has_gui = s["screenshots_count"] >= 0.5
    s["cross_channel"] = 1.0 if (has_cli and has_gui) else (0.5 if (has_cli or has_gui) else 0.0)

    # VLM rubric (≥4 items)
    if vlm_score_rubric and all_shots:
        rubric = {
            "vlm_calibre_visible": "截图中可见 Calibre 应用界面(书籍查看器或 Edit Book 编辑器)",
            "vlm_edit_book_real": "至少一张截图显示 Calibre Edit Book 的 OPF/CSS 编辑面板或 Check Book 结果",
            "vlm_fix_evidence": "修复后截图与修复前截图存在明显差异(ToC 出现 / 图片渲染 / 排版收敛)",
            "vlm_okular_pdf": "Okular 中可见 PDF 渲染内容、工具栏与左侧 Outline",
        }
        try:
            vlm = vlm_score_rubric([str(p) for p in all_shots[:4]], rubric,
                                   instruction="评估 EPUB 修复任务的 Calibre / Okular 截图真实性。")
            for k in rubric:
                s[k] = float(vlm.get(k, 0.0) or 0.0)
        except Exception:
            pass

    # GUI hard-gate sub-scores: trajectory diversity + chrome OCR + window geometry
    import hashlib
    gui_shot_paths = [p for p in all_shots if p.exists()]
    if len(gui_shot_paths) >= 4:
        hashes = set(hashlib.md5(p.read_bytes()).hexdigest() for p in gui_shot_paths)
        gui_diversity = len(hashes) / max(1, len(gui_shot_paths))
    else:
        gui_diversity = 0.0
    # tighten: require ≥ 0.9 unique for full credit
    s["gui_real_interaction"] = 1.0 if gui_diversity >= 0.9 else (0.5 if gui_diversity >= 0.6 else 0.0)

    geom_hits = 0
    if Image and gui_shot_paths:
        for p in gui_shot_paths:
            try:
                w, h = Image.open(p).size
                if w >= 1280 and h >= 720:
                    geom_hits += 1
            except Exception:
                pass
        s["gui_window_geometry"] = min(1.0, geom_hits / max(3.0, len(gui_shot_paths) * 0.6))
    else:
        s["gui_window_geometry"] = 0.0

    chrome_kws = ["Calibre", "Edit Book", "Check Book", "Okular", "Table of Contents",
                  "Metadata", "Library", "Bookmarks", "ebook-viewer"]
    chrome_hits = 0
    if pytesseract and Image and gui_shot_paths:
        for p in gui_shot_paths:
            try:
                tx = pytesseract.image_to_string(Image.open(p))
                if sum(1 for k in chrome_kws if k.lower() in tx.lower()) >= 2:
                    chrome_hits += 1
            except Exception:
                pass
        s["gui_chrome_ocr"] = min(1.0, chrome_hits / max(3.0, len(gui_shot_paths) * 0.5))
    else:
        s["gui_chrome_ocr"] = 0.0

    # Triple-gate anti-cheat composite: md5-unique × resolution-ok × ocr-hit must all hold
    triple_pass = 0
    if Image and pytesseract and gui_shot_paths:
        seen_md5 = {}
        for p in gui_shot_paths:
            try:
                md5 = hashlib.md5(p.read_bytes()).hexdigest()
                w, h = Image.open(p).size
                tx = pytesseract.image_to_string(Image.open(p))
                ok_unique = seen_md5.setdefault(md5, p) == p
                ok_res = (w >= 1280 and h >= 720)
                ok_ocr = any(k.lower() in tx.lower() for k in chrome_kws)
                if ok_unique and ok_res and ok_ocr:
                    triple_pass += 1
            except Exception:
                pass
    triple_ratio = triple_pass / max(1, len(gui_shot_paths))

    # Aggregate — weighted by group instead of flat mean to reflect task focus.
    core_keys = [
        "initial_log_present", "initial_summary_schema", "initial_error_count",
        "xmllint_log", "missing_assets",
        "zip_audit_initial", "nav_spine_diff",
        "mid_epubcheck", "zip_audit_fixed",
        "pdf_exists", "pdf_pages",
        "final_errors_low", "error_reduction",
        "report_length", "report_has_table",
    ]
    gui_keys = [
        "edit_book_screenshots", "viewer_initial_screenshots",
        "viewer_fixed_screenshots", "okular_screenshots",
        "screenshots_count", "screenshot_ocr",
        "gui_real_interaction", "gui_chrome_ocr", "gui_window_geometry",
        "vlm_calibre_visible", "vlm_edit_book_real",
        "vlm_fix_evidence", "vlm_okular_pdf",
    ]
    aux_keys = ["cross_channel"]

    def _avg(keys):
        vs = [s[k] for k in keys if isinstance(s.get(k), (int, float))]
        return sum(vs) / len(vs) if vs else 0.0

    core_score = _avg(core_keys)
    gui_score = _avg(gui_keys)
    aux_score = _avg(aux_keys)
    base = 0.5 * core_score + 0.35 * gui_score + 0.15 * aux_score

    # Hard gates (tightened)
    if not has_cli:
        base = min(base, 0.35)
    if not has_gui:
        base = min(base, 0.35)
    if s["pdf_exists"] == 0 and s["mid_epubcheck"] == 0:
        base = min(base, 0.45)
    # Core deliverable gates: missing fixed-EPUB OR missing reduction → cap 0.4
    if s["final_errors_low"] < 0.5 or s["error_reduction"] < 0.5:
        base = min(base, 0.4)
    # GUI real-interaction hard gate: pure CLI / replicated shots cannot exceed 0.35
    if s.get("gui_real_interaction", 0) < 0.5:
        base = min(base, 0.35)
    # Chrome OCR raised: <0.5 caps at 0.4 (was <0.3 cap 0.5)
    if s.get("gui_chrome_ocr", 0) < 0.5:
        base = min(base, 0.4)
    # Triple anti-cheat gate: < 50% truly real screenshots → cap 0.5
    if triple_ratio < 0.5:
        base = min(base, 0.5)
    # VLM unavailable / all 0 → cap 0.6 (cannot get full credit purely on heuristics)
    vlm_keys = ["vlm_calibre_visible", "vlm_edit_book_real", "vlm_fix_evidence", "vlm_okular_pdf"]
    if vlm_score_rubric is None or all(s.get(k, 0) == 0 for k in vlm_keys):
        base = min(base, 0.6)

    s["overall_score"] = round(base, 3)
    return s
```

## Workspace Path

```
workspace/DOC/task_1_epub_validation_repair
```

## Skills

```
epubcheck, unzip/zip, xmllint, Calibre Viewer, Calibre Edit Book (ebook-edit), ebook-convert, Okular, pdfinfo, pytesseract OCR
```

## Env

```
```

## War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