--- id: DOC_task_10_lo_writer_trackchanges_audit name: 合同 docx track-changes 多作者审计与策略性接受拒绝 category: DOC timeout_seconds: 1500 --- ## Prompt Task background: The legal team has delivered a contract draft at `/tmp_workspace/contract_project/contract_v3.docx`, on which 3 reviewers have left a large number of OOXML tracked changes (`` / ``). The reviewer identities are fixed: - `Senior Partner` - `Reviewer B` (business side) - `Reviewer C` (compliance side) Decision policy: 1. All revisions from `Senior Partner` are **accepted**. 2. Revisions from `Reviewer B` are split by content: any that touch money (`$` or `USD`, raw numeric amounts, interest rates such as `1.5% per month`) are **rejected**; non-money revisions are accepted. 3. Revisions from `Reviewer C` are split by section: any that fall inside the `3. Confidentiality` section are **rejected**; revisions in other sections are accepted. Task goal: enumerate every revision and apply the policy decision → apply the decisions to produce a clean final docx → simultaneously export the PDF / text / XML audit / screenshot evidence / markdown audit report. All deliverables go to `/tmp_workspace/results/`. ### Hard constraints on the primary deliverable `final.docx` - After unzipping, `word/document.xml` must not contain any ` `, ≥ 25 lines | | `audit_report.md` | ≥ 400 characters; contains a markdown table (≥ 4 columns) summarizing the decisions for the three reviewers; itemizes ≥ 3 money-related rejections from `Reviewer B` (must include concrete strings like `150,000`/`12,000`/`1.5% per month`); ≥ 2 `Reviewer C` revisions rejected for falling in `Confidentiality` / Section 3; visual sign-off conclusion + process recap | | `deliverables.json` | `{"final_docx_sha256":"","final_pdf_sha256":"","screenshots":[...],"files":[...]}` | ### 6 process screenshots (PNG, resolution ≥ 1280×720, mutually distinct md5) | Filename | Content | | --- | --- | | `view_01_manage_panel_initial.png` | Initial state of the word processor's Manage Track Changes panel, with multiple revision entries from the three authors visible | | `view_02_panel_filter_author_a.png` | Panel filtered/highlighted by `Senior Partner`, or the edit view positioned on that author's first revision | | `view_03_money_redline_zoom.png` | Close-up of a `Reviewer B` money-related revision with its colored markup in the body | | `view_04_section3_redline_zoom.png` | Close-up of a `Reviewer C` revision marked up in the body inside the `3. Confidentiality` section | | `view_05_panel_after_apply.png` | After all accept/reject have been applied, the Manage Track Changes panel is essentially empty | | `view_06_final_clean_layout.png` | Overall layout preview of the final document, with no remaining redlines / revision marks | Screenshots must come from real GUI interaction; grading performs OCR + visual inspection, and blank / placeholder images or screenshots that are all identical will score 0. The screenshots should at least let the grader recognize the word processor in use from the window chrome (menu / toolbar / title bar text being visible is enough). Anti-cheat: do not copy any file from `/tmp_workspace/gt/` (grader-only) into `results/`. Neutral background: OOXML revision semantics are persisted in `word/document.xml` as ``/`` elements. Structured XML parsing and the GUI Manage Track Changes panel corroborate each other. ## Expected Behavior 设计意图与典型解题路径(仅供出题人参考,不发给 agent): 1. 推荐用 LibreOffice Writer GUI 打开 docx,通过 Edit → Track Changes → Manage 面板观察修订;也可走 python-docx / 直接解 `word/document.xml` 的 CLI 通道,或两者混合(CLI 枚举 + GUI 截图佐证)。 2. step 1:打开 `contract_v3.docx`,用 unzip + xmllint / python-docx 解析 `word/document.xml`,按 `` / `` 的 `w:author` 属性归类,逐条提取所在 section(按 Heading 1 节号反查 1–6)和文本片段,写出 `redlines_raw.json` 与 `redlines_full.csv`,同时按政策算 `is_money_related` 与 `planned_decision`。 3. step 2:在 GUI 中截 `view_01`(面板初始)、`view_02`(按作者过滤)、`view_03`(金额修订特写)、`view_04`(§3 修订特写)。 4. step 3:按 `planned_decision` 在 GUI 或脚本里 accept/reject 每条修订,生成 `final.docx`;GUI 路径建议在 Manage 面板逐条点击或借助批量按钮。脚本路径可重写 `word/document.xml`,删 `` 元素体并把 `` 改为 reject 时移除、accept 时保留其内文 run。 5. step 4:截 `view_05`(面板清空)、`view_06`(终稿排版);用 `libreoffice --headless --convert-to pdf` 导出 `final.pdf`,提取 `final_text.txt`,dump `final_document_xml.txt`。 6. step 5:算 `policy_audit.json`、写 `redline_diff.txt`、撰写 `audit_report.md`、生成 `deliverables.json`(含两个 sha256)。 约束说明:截图必须来自真实交互。不得复制 `/tmp_workspace/gt/` 下任何文件进 `results/`。`actions.log` 中不得出现 `expected.json` 等 grader-only 字面量。 评分要点(hard gates): - CLI 通道 5 件齐 + GUI 截图 ≥ 5 张,缺其一总分被 cap 0.4。 - `final.docx` 仍残留 ` dict: """Track-changes audit grader. Sub-scores cover: CLI redline parsing, policy decision audit, GUI screenshot count + OCR + diversity, final.docx structural cleanup, money-phrase fidelity, PDF export, audit report content, and a VLM rubric. Empty results dir -> overall_score == 0.000. """ import json, re, hashlib, subprocess, zipfile from pathlib import Path try: from PIL import Image except Exception: Image = None try: import pytesseract except Exception: 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" # Prefer root-only /opt/doc10_gt to prevent answer leakage; fall back # to /tmp_workspace/gt for legacy mounts. gt = Path("/opt/doc10_gt") if Path("/opt/doc10_gt/expected.json").exists() else workspace / "gt" sub_keys = [ "redlines_raw_schema", "redlines_raw_total", "redlines_full_csv", "policy_audit_schema", "policy_audit_match", "screenshots_count", "screenshot_ocr", "gui_diversity", "gui_chrome_ocr", "gui_resolution", "final_docx_exists", "final_docx_no_ins_del", "final_text_money_kept", "final_text_money_rejected", "final_pdf_pages", "redline_diff_lines", "audit_report_len", "audit_report_table", "audit_report_money_listed", "audit_report_sec3_listed", "deliverables_schema", "cross_channel", "vlm_panel_visible", "vlm_redline_marks", "vlm_after_clean", "vlm_layout_final", ] 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. redlines_raw.json # ------------------------------------------------------------------ raw = rd / "redlines_raw.json" raw_total = 0 if raw.exists(): try: d = json.loads(raw.read_text()) need = {"total", "ins", "del", "by_author"} if need.issubset(d.keys()) and isinstance(d["by_author"], dict): s["redlines_raw_schema"] = 1.0 raw_total = int(d.get("total", 0)) except Exception: pass # GT total ~30; tolerate ±2 (the generator may not place every anchor) if 27 <= raw_total <= 32: s["redlines_raw_total"] = 1.0 elif raw_total > 0: s["redlines_raw_total"] = max(0.0, 1.0 - abs(raw_total - 29) / 10.0) # ------------------------------------------------------------------ # 2. redlines_full.csv # ------------------------------------------------------------------ csv_path = rd / "redlines_full.csv" if csv_path.exists(): import csv as _csv try: rows = list(_csv.DictReader(csv_path.open())) need_cols = {"id", "kind", "author", "section", "text_preview", "is_money_related", "planned_decision"} if rows and need_cols.issubset(set(rows[0].keys())) and len(rows) >= 25: good = sum(1 for r in rows if r.get("author") in {"Senior Partner", "Reviewer B", "Reviewer C"} and r.get("kind") in {"ins", "del"} and str(r.get("is_money_related", "")).lower() in {"true", "false"} and str(r.get("planned_decision", "")).lower() in {"accept", "reject"} and str(r.get("section", "")).strip().startswith(tuple("123456"))) s["redlines_full_csv"] = good / len(rows) elif rows: s["redlines_full_csv"] = 0.2 except Exception: pass # ------------------------------------------------------------------ # 3. policy_audit.json # ------------------------------------------------------------------ pa = rd / "policy_audit.json" pa_data = {} if pa.exists(): try: pa_data = json.loads(pa.read_text()) authors = ["Senior Partner", "Reviewer B", "Reviewer C"] if all(a in pa_data and "accept" in pa_data[a] and "reject" in pa_data[a] for a in authors): s["policy_audit_schema"] = 1.0 except Exception: pass expected = {} ej = gt / "expected.json" if ej.exists(): try: expected = json.loads(ej.read_text()) except Exception: pass if pa_data and expected.get("by_author"): # Match within ±1 per cell hits = 0; total = 0 for a, d in expected["by_author"].items(): for k, v in d.items(): total += 1 if int(pa_data.get(a, {}).get(k, -99)) == int(v): hits += 1 s["policy_audit_match"] = hits / total if total else 0.0 # ------------------------------------------------------------------ # 4. screenshots # ------------------------------------------------------------------ shots_planned = ["view_01_manage_panel_initial", "view_02_panel_filter_author_a", "view_03_money_redline_zoom", "view_04_section3_redline_zoom", "view_05_panel_after_apply", "view_06_final_clean_layout"] shots = [] for n in shots_planned: f = list(rd.glob(f"{n}*.png")) if f and f[0].stat().st_size > 3000: shots.append(f[0]) s["screenshots_count"] = min(1.0, len(shots) / 5.0) if Image and shots: ok = 0 for p in shots: try: w, h = Image.open(p).size if w >= 1280 and h >= 720: ok += 1 except Exception: pass s["gui_resolution"] = ok / max(1, len(shots)) if shots: hashes = {hashlib.md5(p.read_bytes()).hexdigest() for p in shots} s["gui_diversity"] = 1.0 if len(hashes) / len(shots) >= 0.8 else ( 0.5 if len(hashes) / len(shots) >= 0.5 else 0.0) if pytesseract and Image and shots: body_kws = ["Manage", "Track", "Changes", "Author", "Confidential", "USD", "Reviewer", "Senior", "Accept", "Reject", "Redline"] chrome_kws = ["Writer", "LibreOffice", "File", "Edit", "Format", "Insert", "View", "Tools"] body_hits = 0 chrome_hits = 0 for p in shots: try: tx = pytesseract.image_to_string(Image.open(p)) if any(k in tx for k in body_kws): body_hits += 1 if sum(1 for k in chrome_kws if k.lower() in tx.lower()) >= 2: chrome_hits += 1 except Exception: pass s["screenshot_ocr"] = min(1.0, body_hits / 4.0) s["gui_chrome_ocr"] = min(1.0, chrome_hits / 2.0) # ------------------------------------------------------------------ # 5. final.docx structural cleanup # ------------------------------------------------------------------ final_doc = rd / "final.docx" final_xml_text = "" if final_doc.exists() and final_doc.stat().st_size > 500: s["final_docx_exists"] = 1.0 try: with zipfile.ZipFile(final_doc) as z: if "word/document.xml" in z.namelist(): final_xml_text = z.read("word/document.xml").decode("utf-8", errors="ignore") except Exception: pass if final_xml_text and "]+>", " ", final_xml_text) must_keep = expected.get("expected_money_phrases_remaining", ["USD 120,000", "USD 8,500", "USD 250 per week"]) must_absent = expected.get("expected_money_phrases_added_must_be_absent", ["150,000", "12,000", "1.5% per month"]) if final_text: xml_clean = bool(final_xml_text) and " 500: try: r = subprocess.run(["pdfinfo", str(fpdf)], capture_output=True, text=True, timeout=10) n = 0 for line in r.stdout.splitlines(): if line.startswith("Pages:"): n = int(line.split()[1]) tx = subprocess.run(["pdftotext", str(fpdf), "-"], capture_output=True, text=True, timeout=15).stdout if n >= 1 and len(tx.strip()) >= 200: s["final_pdf_pages"] = 1.0 elif n >= 1: s["final_pdf_pages"] = 0.5 except Exception: pass # ------------------------------------------------------------------ # 8. redline_diff.txt # ------------------------------------------------------------------ rdf = rd / "redline_diff.txt" if rdf.exists(): nl = sum(1 for _ in rdf.open(errors="ignore")) s["redline_diff_lines"] = 1.0 if nl >= 25 else nl / 25.0 # ------------------------------------------------------------------ # 9. audit_report.md # ------------------------------------------------------------------ ar = rd / "audit_report.md" if ar.exists(): txt = ar.read_text(errors="ignore") s["audit_report_len"] = 1.0 if len(txt) >= 400 else len(txt) / 400.0 if "|" in txt and re.search(r"\|\s*[-:]+\s*\|.*\|\s*[-:]+\s*\|", txt): s["audit_report_table"] = 1.0 rejected_money = ["150,000", "12,000", "1.5% per month"] money_hits = sum(1 for t in rejected_money if t in txt and "Reviewer B" in txt.split(t)[0][-200:]) s["audit_report_money_listed"] = money_hits / len(rejected_money) sec3_blocks = re.findall(r"Reviewer C[^\n]{0,300}?(Confidentiality|Section\s*3)", txt, re.I) s["audit_report_sec3_listed"] = min(1.0, len(sec3_blocks) / 2.0) # ------------------------------------------------------------------ # 10. deliverables.json # ------------------------------------------------------------------ dl = rd / "deliverables.json" if dl.exists(): try: d = json.loads(dl.read_text()) sha_hits = sum(1 for k in ["final_docx_sha256", "final_pdf_sha256"] if isinstance(d.get(k), str) and len(d[k]) >= 32) list_ok = isinstance(d.get("screenshots"), list) and isinstance(d.get("files"), list) s["deliverables_schema"] = (sha_hits / 2.0) * (1.0 if list_ok else 0.5) except Exception: pass # ------------------------------------------------------------------ # 11. cross-channel # ------------------------------------------------------------------ required_cli = ["redlines_raw.json", "redlines_full.csv", "policy_audit.json", "redline_diff.txt", "final_document_xml.txt"] has_cli = all((rd / n).exists() for n in required_cli) has_gui = len(shots) >= 5 s["cross_channel"] = 1.0 if (has_cli and has_gui) else (0.5 if (has_cli or has_gui) else 0.0) # ------------------------------------------------------------------ # 12. VLM rubric # ------------------------------------------------------------------ if vlm_score_rubric and shots: rubric = { "vlm_panel_visible": "截图中可见 Manage Track Changes 面板,列出按作者归类的多条修订条目", "vlm_redline_marks": "正文中可见红色 / 彩色 ins/del 修订标注(删除线 / 下划线 / 边栏条)", "vlm_after_clean": "处理完毕后的截图中 Track Changes 面板基本清空,正文几乎无残留修订", "vlm_layout_final": "最终文档截图整体排版整齐,章节标题与正文清晰", } try: vlm = vlm_score_rubric([str(p) for p in shots[:4]], rubric, instruction="评估合同 docx 修订审计任务的 GUI 截图真实性。") for k in rubric: s[k] = float(vlm.get(k, 0.0) or 0.0) except Exception: pass # ------------------------------------------------------------------ # 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 if not has_cli: base = min(base, 0.4) # NOTE: We deliberately do NOT cap on missing GUI screenshots — # whether the agent invokes Writer UI tooling is not a scoring axis. # Missing PNGs already cost the screenshots_count / OCR / VLM # sub_scores; no additional hard cap is applied here. if s.get("final_docx_no_ins_del", 0) < 0.5 and s.get("final_docx_exists", 0) > 0: base = min(base, 0.55) if s.get("final_text_money_rejected", 0) < 0.5 and s.get("final_docx_exists", 0) > 0: base = min(base, 0.55) if s.get("gui_diversity", 0) < 0.5 and len(shots) >= 3: base = min(base, 0.4) if s.get("gui_chrome_ocr", 0) < 0.3 and len(shots) >= 3: base = min(base, 0.5) vlm_avg = sum(s.get(k, 0) for k in ["vlm_panel_visible", "vlm_redline_marks", "vlm_after_clean", "vlm_layout_final"]) / 4.0 # Only enforce the VLM cap when the helper actually ran — otherwise # the 0.0 fallback would unfairly cap correct runs. if vlm_score_rubric is not None and vlm_avg < 0.6 and shots: base = min(base, 0.6) s["overall_score"] = round(base, 3) return s ``` ## Workspace Path ``` workspace/DOC/task_10_lo_writer_trackchanges_audit ``` ## Skills ``` unzip, xmllint, grep, python-docx, libreoffice --headless, LibreOffice Writer GUI, pdftotext, pdfinfo, sha256sum, pytesseract OCR ``` ## Env ``` ``` ## Warmup ```bash mkdir -p /tmp_workspace/results /tmp_workspace/state /tmp_workspace/contract_project /opt/doc10_gt # Move expected.json to a root-only path so the agent cannot read the # per-author accept/reject counts, money-phrase answers, or policy keys. if [ -f /tmp_workspace/gt/expected.json ]; then mv /tmp_workspace/gt/expected.json /opt/doc10_gt/expected.json 2>/dev/null || true chown -R root:root /opt/doc10_gt 2>/dev/null || true chmod 700 /opt/doc10_gt 2>/dev/null || true chmod 600 /opt/doc10_gt/expected.json 2>/dev/null || true rmdir /tmp_workspace/gt 2>/dev/null || true fi which unzip || (apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq unzip zip) which xmllint || (apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq libxml2-utils) which pdftotext || (apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq poppler-utils) pip3 install --break-system-packages --quiet pdfminer.six pillow pytesseract python-docx lxml 2>/dev/null || pip3 install --quiet pdfminer.six pillow pytesseract python-docx lxml [ -f /tmp_workspace/contract_project/contract_v3.docx ] || python3 /tmp_workspace/contract_project/generate_contract.py /tmp_workspace/contract_project/contract_v3.docx 2>/dev/null || true ```