WeaveBench / tasks /DOC /DOC_task_17_print_pdf_pagination_audit.md
wanlilll's picture
Add 114 tasks under 8-domain flat layout
71e9dba verified
metadata
id: DOC_task_17_print_pdf_pagination_audit
name: HTML 长文 print-to-PDF 双引擎分页:CSS @page 修与浏览器预览交叉验证
category: DOC
timeout_seconds: 1500

Prompt

Task background: The editorial team receives a long-form article /tmp_workspace/article/longform_article.html (10 sections, several <figure> + <figcaption> pairs) ready for print. The same stylesheet /tmp_workspace/article/article.css must feed two independent print-to-PDF rendering pipelines: one is a CSS Paged Media engine (consumes @page rules directly, output can have its page count and per-page text extracted by structured PDF tools, hereafter referred to as engine=weasy), the other is a headless browser print pipeline (also the renderer behind the print-preview pane, hereafter referred to as engine=chromium). The default @page size on the two sides is not consistent (A4 vs Letter), and the current article.css is known to contain at least 3 @page / break-related bugs, so that in the baseline state the two pipelines' outputs differ noticeably in total page count, figure/caption co-location, and section start positions.

Ticket PRINT-PAG-024 requires: the two sides must have a total page-count difference ≤ 1, and every <figure> together with its <figcaption> must land on the same page — a figure at the bottom of page N with the caption alone at the top of page N+1 is not allowed.

Task goal: complete the "evidence collection → localization → repair → re-verification" loop, with structured artifacts (dual-engine PDFs + page-count metadata + per-page text diff + per-page rasterized bitmaps + fixed CSS + report) and rendered-state visual evidence (multi-page thumbnails in the print-preview pane, PDF reader sidebar showing the orphan caption across pages) cross-verified across two channels. All deliverables go uniformly under /tmp_workspace/results/.

Hard constraints on the main deliverable pagination_report.json

The schema must be:

{
  "weasy_pages":    <int>,
  "chromium_pages": <int>,
  "page_diff_abs":  <int>,
  "parity_ok":      true|false,
  "figure_caption_same_page": {
    "weasy":    [true|false, ...],
    "chromium": [true|false, ...]
  },
  "all_figures_intact": true|false
}
  • weasy_pages / chromium_pages must match the real page counts of the fixed PDFs (read from structured PDF metadata);
  • page_diff_abs == |weasy_pages - chromium_pages|, parity_ok == (page_diff_abs <= 1), and must finally be true;
  • The length of figure_caption_same_page.<engine> arrays must equal the actual figure count in the document; each element indicates whether the i-th figure and its caption land on the same page in the fixed PDF;
  • all_figures_intact is true if and only if all elements of both arrays are true, and must finally be true.

Companion deliverables (under /tmp_workspace/results/)

File Requirement
baseline_weasy.pdf / baseline_chromium.pdf PDFs rendered by each pipeline with the unfixed CSS; > 1 KB, page count readable by structured tools; in the baseline stage the page-count difference between the two sides should be ≥ 2
baseline_weasy.log / baseline_chromium.log Full stdout+stderr of the above two renders
baseline_pages.jsonl Exactly two JSON Lines, schema {"engine":"weasy"|"chromium","pages":<int>,"sha256":"<hex>"}; pages truly read from PDF metadata, sha256 is the sha256 of the corresponding PDF byte stream
baseline_text_diff.txt First 200 lines of unified diff between the two baseline PDFs after extracting text with layout preservation split by form-feed; contains ≥ 8 lines of real diff (starting with + or - and not the +++/--- file headers), of which ≥ 2 lines hit section names / Figure / page numbers / form-feed markers
weasy_pages/page-*.png Per-page rasterized bitmaps of baseline_weasy.pdf (DPI ≈ 90), ≥ 3 images, file names like page-1.png / page-2.png / …
preview_save.pdf PDF exported through the browser print-preview pane's Save as PDF channel; > 5 KB and sha256 different from baseline_chromium.pdf (must come from the rendered-state channel; do not overwrite this file name with a headless PDF output)
article.fixed.css A minimal-patch copy of /tmp_workspace/article/article.css, modifying only the 3 bugs and leaving all other non-bug lines as-is (the grader checks that non-bug lines are preserved at ≥ 80%):
bug-A — the @page { ... } block contains both an explicit size: Letter (or A4) and margin: ...
bug-B — the figure selector contains break-inside: avoid (or alias page-break-inside: avoid)
bug-C — the h2 selector contains break-before: page/always (or alias page-break-before: always)
Wholesale CSS rewrites are not allowed
fixed_weasy.pdf / fixed_chromium.pdf + same-name .log PDFs and logs from re-running both engines after applying article.fixed.css
fixed_pages.jsonl Two records with the same schema as baseline (sourced from the fixed PDFs), `
pagination_report.json See the "main deliverable" hard constraints above
notes.md ≥ 250 characters, based on actual run output (do not copy the prompt), describing how you cross-located the @page / figure / h2 CSS lines corresponding to bug-A / bug-B / bug-C across the structured channel (PDF metadata + per-page text diff) and the rendered-state channel (print preview + PDF reader sidebar)

3 work-process screenshots (under /tmp_workspace/results/, each > 3 KB)

File name Content requirement
view_chromium_preview_before.png Full-window screenshot after opening file:///tmp_workspace/article/longform_article.html in the browser print-preview pane before fixing: contains the main window (title bar + print-preview pane), ≥ 3 multi-page thumbnails, output destination settings area (Save as PDF or similar), and genuinely shows visual evidence of at least one <figure> / <figcaption> split across pages
view_okular_orphan_caption.png Full-window screenshot after opening baseline_weasy.pdf in a PDF reader, enabling the page-thumbnail sidebar, and navigating to the broken page: contains the main window (with thumbnail sidebar) + an orphan <figcaption> in the main display area (caption alone at the top of one page, separated from the figure at the bottom of the previous page)
view_chromium_preview_after.png Full-window screenshot of the print-preview pane after re-rendering with the fixed CSS: ≥ 3 multi-page thumbnails, output destination settings area, all visible figures together with their captions on the same page (no orphaned figures)

The grader runs both OCR and VLM dual-channel review on the 3 screenshots, requiring real interactive UI; white background / collage / placeholder images, or screenshots that do not actually show multi-page thumbnails + output destination settings + cross-page or same-page figures, will be scored 0.

Anti-cheat and isolation

  • It is not allowed to copy any file from /tmp_workspace/setup_gt/ (grader-only) into /tmp_workspace/results/; the grader reads only /tmp_workspace/results/.
  • actions.log must not contain the literals bug-A / bug-B / bug-C; the agent must locate them by observation.
  • preview_save.pdf must truly be exported through the print-preview pane's Save as PDF channel; do not overwrite that file name with a headless PDF render output (the grader compares sha256).

Neutral background knowledge: CSS Paged Media (W3C css-page-3) declares paper size and margins via @page rules, and break-inside: avoid / break-before: page (and the legacy aliases page-break-*) control element behavior relative to page boundaries. The default @page size of the two mainstream print-to-PDF implementations is not consistent — the CSS Paged Media engine defaults to A4, whereas the headless browser print pipeline defaults to Letter — so if @page does not explicitly set size:, the same HTML will drift between the two sides in total page count and per-page start positions. <figure> / <figcaption> are independent blocks; without break-inside: avoid, page splits are common. Without break-before: page on h2, section start positions land on different page numbers depending on font metrics differences between the two sides. Structured artifacts can only tell you "page counts don't match / a piece of text landed on page X", but the human-readable "orphan figure" phenomenon can only be seen directly in multi-page thumbnails / PDF reader sidebars — the two channels must corroborate each other to attribute the bug to a specific CSS selector and a specific break rule.

Expected Behavior

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

  1. 推荐工具组合(agent 可自由替换任意等价通道):CSS Paged Media 引擎可走 WeasyPrint(weasyprint==60.2),headless 浏览器 print pipeline 可走 Chromium --headless --print-to-pdf;GUI 排版预览可走 Chromium 的 Ctrl+P,PDF 阅读器侧栏可走 Okular 或同等带缩略图侧栏的阅读器;结构化分析可走 poppler-utils(pdfinfo / pdftotext -layout / pdftoppm)或同等工具。
  2. baseline 阶段:分别用两条管线对 /tmp_workspace/article/longform_article.html 渲染出 baseline_weasy.pdf / baseline_chromium.pdf;用结构化工具抽页数(写入 baseline_pages.jsonl)、按 form-feed 抽文本做 diff(写入 baseline_text_diff.txt)、把 weasy 输出栅格化(写入 weasy_pages/page-*.png)。
  3. GUI 取证阶段:在浏览器里打开 file:///tmp_workspace/article/longform_article.html,开排版预览面板,多页缩略图里能直接看到 figure 与 caption 被分到不同页,截图为 view_chromium_preview_before.png,从 Save as PDF 通道导出 preview_save.pdf;在 PDF 阅读器里打开 baseline_weasy.pdf,开缩略图侧栏定位到断页那页,截图为 view_okular_orphan_caption.png
  4. 定位阶段:交叉对比两端页数差与 diff 行的章节 / Figure / 页号信号,定位到 @page(缺 size/margin)、figure(缺 break-inside)、h2(缺 break-before)三个选择器各自的 break 规则缺失。
  5. 修复阶段:对 article.css 做最小补丁生成 article.fixed.css,只动 3 处 bug,其它非 bug 行字节级保留(保留率 ≥ 80%)。
  6. 复验阶段:用 fixed CSS 重渲两端,写出 fixed_weasy.pdf / fixed_chromium.pdf / fixed_pages.jsonl / pagination_report.json;在排版预览面板再次取一张全 figure+caption 同页的 view_chromium_preview_after.png;最后写 ≥ 250 字符的 notes.md 复盘。

约束说明:

  • agent 自由选择渲染、分析、查看通道,但 preview_save.pdf 必须真正经过排版预览面板的 Save as PDF 通道导出(与无头管线产物 sha256 不同),不得伪造或用无头 PDF 覆盖。
  • 视觉证据须为真实 GUI 交互整窗截图;不得以纯文本拼图、占位图、或剪裁过的局部图替代。
  • actions.log 不得直接出现 bug-A / bug-B / bug-C 字面量。

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

  • 缺 baseline 或 fixed PDF(无 CLI 证据)→ 总分 cap 0.4。
  • 3 张 GUI 截图任一缺失或字节数过小 → cap 0.4 / 0.55。
  • VLM 对 print preview 多页缩略图、figure 跨页/同页的 rubric 平均分 < 0.6 → cap 0.6。
  • pagination_report.jsonparity_okall_figures_intact 不为 true、或 fixed PDF 真实页数差 > 1、或 figure_caption_same_page 数组长度与文档真实 figure 数不一致、或元素未全部为 true → cap 0.45。
  • article.fixed.css 三处 bug 补丁缺任一项,或非 bug 行保留率 < 80% → cap 0.45。
  • preview_save.pdf 不存在、字节 < 5 KB、或 sha256 与 baseline_chromium.pdf 相同 → cap 0.5。

Source

Grading Criteria

    1. results/ 下所有 14 个文本/PDF artefact 存在且非空
    1. 3 张截图存在
    1. baseline_pages.jsonl 两条记录, schema 完整
    1. baseline_text_diff.txt 非空(差异确实存在)
    1. weasy_pages/page-*.png 至少 3 张
    1. article.fixed.css 含 size: Letter(或 A4)、break-inside: avoidbreak-before: page(或 page-break alias)
    1. fixed_pages.jsonl 两条记录, page_diff_abs ≤ 1
    1. pagination_report.json schema + parity_ok=true + all_figures_intact=true
    1. preview_save.pdf 字节数 > 1000
    1. 截图 OCR 命中 GUI-only 关键词(Print / Save as PDF / Pages / Figure)
    1. notes.md 字符 ≥ 250
    1. VLM 评 print preview 截图通过

Automated Checks

def grade(workspace_path=None, **kwargs) -> dict:
    """Multi sub-score grader for DOC_task_17_print_pdf_pagination_audit.

    Hard gates:
      - no CLI evidence (baseline + fixed pdfs)            -> cap 0.4
      - no GUI screenshot present                          -> cap 0.4
      - VLM rubric < 0.6 on the two print-preview shots    -> cap 0.6
      - parity_ok != True OR figure/caption split          -> cap 0.55
    """
    import json, re, hashlib, subprocess, shutil
    from pathlib import Path

    ws = Path(workspace_path or ".").resolve()
    rd = ws / "results"
    # Prefer root-only /opt/doc17_gt to prevent answer leakage; fall back
    # to the in-workspace gt for legacy mounts.
    gt = Path("/opt/doc17_gt") if Path("/opt/doc17_gt/expected.json").exists() else ws / "gt"
    s = {}

    expected = {}
    ej = gt / "expected.json"
    if ej.exists():
        try: expected = json.loads(ej.read_text())
        except Exception: expected = {}

    # --------------------------------------------- 1. file presence
    base_files = [
        "baseline_weasy.pdf", "baseline_chromium.pdf",
        "baseline_weasy.log", "baseline_chromium.log",
        "baseline_pages.jsonl", "baseline_text_diff.txt",
        "preview_save.pdf",
        "fixed_weasy.pdf", "fixed_chromium.pdf", "fixed_pages.jsonl",
        "pagination_report.json", "article.fixed.css", "notes.md",
    ]
    present = sum(1 for n in base_files if (rd / n).exists() and (rd / n).stat().st_size > 0)
    s["files_present"] = present / len(base_files)

    # weasy_pages dir
    wp_dir = rd / "weasy_pages"
    pngs = sorted(wp_dir.glob("page-*.png")) if wp_dir.exists() else []
    s["weasy_pages_dir"] = 1.0 if len(pngs) >= 3 else (0.5 if pngs else 0.0)

    shots = ["view_chromium_preview_before.png",
             "view_okular_orphan_caption.png",
             "view_chromium_preview_after.png"]
    shot_paths = [rd / n for n in shots if (rd / n).exists() and (rd / n).stat().st_size > 3000]
    s["screenshots_present"] = len(shot_paths) / len(shots)

    # --------------------------------------------- 2. baseline_pages.jsonl
    def _read_jsonl(p):
        out = []
        if not p.exists(): return out
        for ln in p.read_text(errors="ignore").splitlines():
            ln = ln.strip()
            if not ln: continue
            try: out.append(json.loads(ln))
            except Exception: pass
        return out

    bj = _read_jsonl(rd / "baseline_pages.jsonl")
    eng = {x.get("engine"): x for x in bj if isinstance(x, dict)}
    if {"weasy", "chromium"}.issubset(eng.keys()) and \
       all(isinstance(eng[e].get("pages"), int) and eng[e].get("sha256") for e in ("weasy", "chromium")):
        s["baseline_pages_schema"] = 1.0
    elif bj:
        s["baseline_pages_schema"] = 0.5
    else:
        s["baseline_pages_schema"] = 0.0

    # baseline diff non-empty
    btd = (rd / "baseline_text_diff.txt").read_text(errors="ignore") if (rd / "baseline_text_diff.txt").exists() else ""
    diff_lines = [l for l in btd.splitlines() if l.startswith(("+","-")) and not l.startswith(("+++","---"))]
    has_section = sum(1 for l in diff_lines if re.search(r"(Section|Figure|\f|page\s*\d)", l, re.I)) >= 2
    s["baseline_diff_nonempty"] = 1.0 if (len(diff_lines) >= 8 and has_section) else (0.5 if diff_lines else 0.0)

    # --------------------------------------------- 3. fixed_pages.jsonl
    fj = _read_jsonl(rd / "fixed_pages.jsonl")
    feng = {x.get("engine"): x for x in fj if isinstance(x, dict)}
    diff_abs = None
    if {"weasy", "chromium"}.issubset(feng.keys()):
        try:
            diff_abs = abs(int(feng["weasy"]["pages"]) - int(feng["chromium"]["pages"]))
        except Exception:
            diff_abs = None
    s["fixed_pages_schema"]   = 1.0 if diff_abs is not None else 0.0
    s["fixed_pages_parity"]   = 1.0 if (diff_abs is not None and diff_abs <= 1) else 0.0

    # --------------------------------------------- 4. pagination_report.json
    pr = {}
    if (rd / "pagination_report.json").exists():
        try: pr = json.loads((rd / "pagination_report.json").read_text())
        except Exception: pr = {}
    need_keys = {"weasy_pages", "chromium_pages", "page_diff_abs",
                 "parity_ok", "figure_caption_same_page", "all_figures_intact"}
    s["pagination_report_schema"] = 1.0 if need_keys.issubset(set(pr.keys())) else (0.5 if pr else 0.0)
    def _pdf_pages(p):
        try: return int(re.search(r"Pages:\s*(\d+)", subprocess.check_output(["pdfinfo",str(p)],stderr=subprocess.DEVNULL).decode()).group(1))
        except Exception: return None
    wp,cp = _pdf_pages(rd/"fixed_weasy.pdf"), _pdf_pages(rd/"fixed_chromium.pdf")
    real_parity = (wp is not None and cp is not None and abs(wp-cp) <= 1)
    s["pagination_parity_ok"]   = 1.0 if (pr.get("parity_ok") is True and real_parity and pr.get("weasy_pages")==wp and pr.get("chromium_pages")==cp) else 0.0
    s["pagination_figs_intact"] = 1.0 if (pr.get("all_figures_intact") is True and isinstance(pr.get("figure_caption_same_page",{}).get("weasy"),list) and len(pr["figure_caption_same_page"]["weasy"])==expected.get("expected_figures",4) and all(pr["figure_caption_same_page"]["weasy"]) and all(pr["figure_caption_same_page"]["chromium"])) else 0.0

    # --------------------------------------------- 5. article.fixed.css patches
    css = (rd / "article.fixed.css").read_text(errors="ignore") if (rd / "article.fixed.css").exists() else ""
    orig_css = (Path("/tmp_workspace/article/article.css").read_text(errors="ignore")
                if Path("/tmp_workspace/article/article.css").exists() else "")
    nonbug_lines = [l.strip() for l in orig_css.splitlines() if l.strip() and "@page" not in l and "figure" not in l and "h2" not in l]
    preserved = sum(1 for l in nonbug_lines if l in css) / max(1,len(nonbug_lines))
    bug_a = bool(re.search(r"@page[^{]*\{[^}]*\bsize\s*:\s*(letter|a4)\b[^}]*\bmargin\s*:", css, re.I | re.S))
    bug_b = bool(re.search(r"\bfigure\b[^{]*\{[^}]*((page-)?break-inside\s*:\s*avoid)", css, re.I | re.S))
    bug_c = bool(re.search(r"\bh2\b[^{]*\{[^}]*((page-)?break-before\s*:\s*(always|page))", css, re.I | re.S))
    s["css_bug_a_page_size"]      = 1.0 if (bug_a and preserved >= 0.8) else 0.0
    s["css_bug_b_figure_avoid"]   = 1.0 if (bug_b and preserved >= 0.8) else 0.0
    s["css_bug_c_h2_pagebreak"]   = 1.0 if (bug_c and preserved >= 0.8) else 0.0

    # --------------------------------------------- 6. preview_save.pdf bytes
    ps = rd / "preview_save.pdf"; bc = rd / "baseline_chromium.pdf"
    def _sha(p):
        try: return hashlib.sha256(p.read_bytes()).hexdigest()
        except Exception: return None
    s["preview_save_bytes"] = 1.0 if (ps.exists() and ps.stat().st_size > 5000
        and bc.exists() and _sha(ps) != _sha(bc)) else 0.0

    # --------------------------------------------- 7. notes.md length
    nm = (rd / "notes.md").read_text(errors="ignore") if (rd / "notes.md").exists() else ""
    s["notes_len"] = 1.0 if len(nm) >= 250 else len(nm) / 250.0

    # --------------------------------------------- 8. OCR over screenshots
    ocr_hits = 0
    try:
        import pytesseract
        from PIL import Image
        kws = {
            "view_chromium_preview_before.png": ["Print", "Save as PDF", "Pages", "Destination", "Total"],
            "view_okular_orphan_caption.png":   ["Figure", "Okular", "Pages", "thumbnail", "Section"],
            "view_chromium_preview_after.png":  ["Print", "Save as PDF", "Pages", "Destination", "Figure"],
        }
        for n, ks in kws.items():
            p = rd / n
            if not p.exists(): continue
            try:
                tx = pytesseract.image_to_string(Image.open(p))
                if any(k.lower() in tx.lower() for k in ks): ocr_hits += 1
            except Exception:
                pass
        s["screenshots_ocr"] = ocr_hits / len(kws)
    except Exception:
        s["screenshots_ocr"] = 0.5

    # --------------------------------------------- 9. VLM rubric
    try:
        from _judge_helper import vlm_score_rubric
    except Exception:
        vlm_score_rubric = None
    vlm_imgs = [str(rd / n) for n in
                ["view_chromium_preview_before.png",
                 "view_okular_orphan_caption.png",
                 "view_chromium_preview_after.png"]
                if (rd / n).exists()]
    if vlm_score_rubric and vlm_imgs:
        rubric = {
            "vlm_print_preview_visible":  "Chromium 截图里能看到 print preview 面板(多页缩略图 + Destination=Save as PDF 设置)",
            "vlm_before_orphan_visible":  "before 截图里能看到至少一处 figure 与 caption 被分到不同页",
            "vlm_after_intact":           "after 截图里所有 figure 与 caption 都同页,排版整齐",
            "vlm_okular_orphan_visible":  "Okular 截图能清晰显示 orphan caption(figure 与 caption 跨页)",
            "vlm_layout_clean":           "截图布局清晰、无截断、无遮挡",
        }
        try:
            vlm = vlm_score_rubric(vlm_imgs[:2], rubric,
                instruction="判断 Chromium print preview 是否真正显示了多页缩略图,以及修复前/后 figure+caption 是否同页。")
            for k in rubric: s[k] = vlm.get(k, 0.0)
        except Exception:
            for k in rubric: s[k] = 0.0

    # --------------------------------------------- aggregate + hard gates
    nums = [v for v in s.values() if isinstance(v, (int, float))]
    base = sum(nums) / len(nums) if nums else 0.0

    has_cli = (rd / "baseline_weasy.pdf").exists() and (rd / "fixed_weasy.pdf").exists()
    has_gui = any((rd / n).exists() and (rd / n).stat().st_size > 3000 for n in shots)
    vlm_keys = ["vlm_print_preview_visible", "vlm_before_orphan_visible", "vlm_after_intact", "vlm_okular_orphan_visible"]
    vk = [s.get(k, 0.0) for k in vlm_keys if k in s]
    vlm_avg = sum(vk) / len(vk) if vk else 1.0

    if not has_cli: base = min(base, 0.4)
    # NOTE: We deliberately do NOT cap on missing GUI screenshots —
    # whether the agent invokes Chromium / Okular UI is not a scoring
    # axis. Missing PNGs already cost the screenshots_present /
    # screenshots_ocr / vlm_* sub_scores; no additional hard cap here.
    if vlm_score_rubric is not None and vk and vlm_avg < 0.6: base = min(base, 0.6)
    if s.get("screenshots_present", 0) < 0.66: base = min(base, 0.55)
    if s.get("pagination_parity_ok", 0) + s.get("pagination_figs_intact", 0) < 2.0:
        base = min(base, 0.45)
    if s.get("css_bug_a_page_size", 0) + s.get("css_bug_b_figure_avoid", 0) + s.get("css_bug_c_h2_pagebreak", 0) < 3:
        base = min(base, 0.45)
    if s.get("preview_save_bytes", 0) < 1.0:
        base = min(base, 0.5)

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

Workspace Path

workspace/DOC/task_17_print_pdf_pagination_audit

Skills


Env


Warmup

mkdir -p /tmp_workspace/results /tmp_workspace/state /tmp_workspace/gt /tmp_workspace/article /opt/doc17_gt
which pdfinfo || (apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq poppler-utils imagemagick python3-pip tesseract-ocr fonts-dejavu-core libpango-1.0-0 libcairo2) || true
which diff-pdf || (apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq diff-pdf) || true
pip3 install --break-system-packages --quiet --ignore-installed blinker 2>/dev/null || true
pip3 install --break-system-packages --quiet pdfminer.six pillow pytesseract pymupdf 'weasyprint==60.2' 2>/dev/null || pip3 install --quiet pdfminer.six pillow pytesseract pymupdf 'weasyprint==60.2' 2>/dev/null || true
# Move expected.json to a root-only path so the agent cannot read the
# expected_css_keys (which directly enumerates the @page bugs to fix).
if [ -f /tmp_workspace/gt/expected.json ]; then
  mv /tmp_workspace/gt/expected.json /opt/doc17_gt/expected.json 2>/dev/null || true
  chown -R root:root /opt/doc17_gt 2>/dev/null || true
  chmod 700 /opt/doc17_gt 2>/dev/null || true
  chmod 600 /opt/doc17_gt/expected.json 2>/dev/null || true
  rmdir /tmp_workspace/gt 2>/dev/null || true
fi
# Move generate_article.py out of agent-visible /tmp_workspace (its source comment
# `# --- CSS with 3 deliberate bugs ---` and the subsequent rules document exactly
# which @page bugs the agent must find). Pattern mirrors DAV_10.
mkdir -p /opt/doc17_priv
chmod 700 /opt/doc17_priv
[ -f /tmp_workspace/generate_article.py ] && mv /tmp_workspace/generate_article.py /opt/doc17_priv/generate_article.py
chown -R root:root /opt/doc17_priv 2>/dev/null || true
[ -s /tmp_workspace/article/longform_article.html ] || (cd /tmp_workspace/article && python3 /opt/doc17_priv/generate_article.py --html longform_article.html --css article.css 2>/dev/null) || true
rm -f /opt/doc17_priv/generate_article.py 2>/dev/null || true
# belt-and-suspenders: ensure source never lands back in /tmp_workspace
rm -f /tmp_workspace/generate_article.py 2>/dev/null || true