{"id":"30352123-9819-4866-9551-680f7486012c","entityType":"agent","slug":"clawhub-stephenlzc-docx-trackdiff","name":"docx-trackdiff","canonicalUrl":"https://www.xpersona.co/agent/clawhub-stephenlzc-docx-trackdiff","canonicalPath":"/agent/clawhub-stephenlzc-docx-trackdiff","generatedAt":"2026-10-10T10:42:30.134Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-10T07:00:09.036Z","emptyReason":null},"description":"Compare two versions of a .docx document and produce a single Word file in tracked-changes (revision / tracking) mode, as if a human had edited the old file into the new one with Track Changes turned on. Use whenever the user has two versions of a DOCX (e.g., successive drafts of a paper, report, or contract — often AI-generated or AI-assisted revisions) and wants to see the differences as native Word revisions (insertions/deletions) that can be accepted/rejected in Word. Triggers: \"对比两个版本的 docx\", \"tracked changes\", \"tracking mode\", \"修订模式对比\", \"compare two Word documents\", \"diff two drafts\", \"生成修订对比文件\". Do NOT use for: creating new documents from scratch (use docx skill), single-file editing with revisions (use docx WIR engine), or PDF-only comparisons.","descriptionLabel":"Source description","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 1.6K downloads reported by the source. Last updated 10/10/2026.","installCommand":"clawhub skill install s170nnpqv8ratxbb59qz0zxkp587h65b:docx-trackdiff","sourceUrl":"https://clawhub.ai/stephenlzc/docx-trackdiff","homepage":"https://clawhub.ai/stephenlzc/skills/docx-trackdiff","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/stephenlzc/docx-trackdiff","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/stephenlzc/skills/docx-trackdiff","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":64,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"docx-trackdiff technical dossier on Xpersona with agent coverage, OPENCLEW support, and live trust metadata."},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-10T07:00:09.036Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-10T07:00:09.036Z","emptyReason":null},"stars":null,"forks":null,"downloads":1605,"packageName":null,"latestVersion":"0.1.0","tractionLabel":"1.6K downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-10T07:00:09.035Z","emptyReason":null},"lastUpdatedAt":"2026-10-10T07:00:09.036Z","lastCrawledAt":"2026-10-10T07:00:09.035Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-11T07:00:09.035Z","lastVerifiedAt":null,"highlights":[{"version":"0.1.0","createdAt":"2026-08-15T18:28:08.707Z","changelog":"- Initial release: compare two `.docx` files and generate a single Word document with native tracked changes showing all differences. - Uses the NEW version as the base, preserving all its formatting, images, and styles. - Allows control over diff granularity with a `--threshold` parameter for more accurate paragraph-level or inline changes. - Requires user-supplied author name and revision date for tracked changes (defaults provided if omitted). - Verifies output for document integrity and tracked changes correctness. - Reports change statistics (inserted/deleted/modified paragraphs, fallbacks) after comparison. - Output file opens in Word's revision mode, making it easy to accept or reject individual changes.","fileCount":21,"zipByteSize":1317072}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s170nnpqv8ratxbb59qz0zxkp587h65b:docx-trackdiff","setupComplexity":"low","setupSteps":["Install using `clawhub skill install s170nnpqv8ratxbb59qz0zxkp587h65b:docx-trackdiff` in an isolated environment before connecting it to live workloads.","No published capability contract is available yet, so validate auth and request/response behavior manually.","Review the upstream CLAWHUB listing at https://clawhub.ai/stephenlzc/docx-trackdiff before using production credentials."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-stephenlzc-docx-trackdiff/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-stephenlzc-docx-trackdiff/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-stephenlzc-docx-trackdiff/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-stephenlzc-docx-trackdiff/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-stephenlzc-docx-trackdiff/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-stephenlzc-docx-trackdiff/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-10T10:42:30.133Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-stephenlzc-docx-trackdiff/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-stephenlzc-docx-trackdiff/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-stephenlzc-docx-trackdiff/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-stephenlzc-docx-trackdiff/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-10T07:00:09.036Z","emptyReason":null},"readme":"Skill: docx-trackdiff\n\nOwner: stephenlzc\n\nSummary: Compare two versions of a .docx document and produce a single Word file in tracked-changes (revision / tracking) mode, as if a human had edited the old file into the new one with Track Changes turned on. Use whenever the user has two versions of a DOCX (e.g., successive drafts of a paper, report, or contract — often AI-generated or AI-assisted revisions) and wants to see the differences as native Word revisions (insertions/deletions) that can be accepted/rejected in Word. Triggers: \"对比两个版本的 docx\", \"tracked changes\", \"tracking mode\", \"修订模式对比\", \"compare two Word documents\", \"diff two drafts\", \"生成修订对比文件\". Do NOT use for: creating new documents from scratch (use docx skill), single-file editing with revisions (use docx WIR engine), or PDF-only comparisons.\n\nTags: latest:0.1.0\n\nVersion history:\n\nv0.1.0 | 2026-08-15T18:28:08.707Z | auto\n\n- Initial release: compare two `.docx` files and generate a single Word document with native tracked changes showing all differences.\n- Uses the NEW version as the base, preserving all its formatting, images, and styles.\n- Allows control over diff granularity with a `--threshold` parameter for more accurate paragraph-level or inline changes.\n- Requires user-supplied author name and revision date for tracked changes (defaults provided if omitted).\n- Verifies output for document integrity and tracked changes correctness.\n- Reports change statistics (inserted/deleted/modified paragraphs, fallbacks) after comparison.\n- Output file opens in Word's revision mode, making it easy to accept or reject individual changes.\n\nArchive index:\n\nArchive v0.1.0: 21 files, 1317072 bytes\n\nFiles: .gitignore (29b), docs (0b), docs/banner.png (995788b), docs/demo-1.png (84678b), docs/demo-2.png (63852b), EVALUATION.md (6246b), examples (0b), examples/demo_tracked.docx (59270b), examples/demo_v1.docx (47033b), examples/demo_v2.docx (58701b), LICENSE (1068b), README.md (8711b), README.zh-CN.md (8133b), references (0b), references/ooxml-revision-rules.md (2955b), scripts (0b), scripts/compare_docx_tracked.py (17221b), scripts/verify_tracked.py (7369b), skill-card.md (2331b), SKILL.md (3928b), _meta.json (133b)\n\nFile v0.1.0:SKILL.md\n\n---\nname: docx-trackdiff\ndescription: >\n  Compare two versions of a .docx document and produce a single Word file in\n  tracked-changes (revision / tracking) mode, as if a human had edited the old\n  file into the new one with Track Changes turned on. Use whenever the user has\n  two versions of a DOCX (e.g., successive drafts of a paper, report, or\n  contract — often AI-generated or AI-assisted revisions) and wants to see the\n  differences as native Word revisions (insertions/deletions) that can be\n  accepted/rejected in Word. Triggers: \"对比两个版本的 docx\", \"tracked changes\",\n  \"tracking mode\", \"修订模式对比\", \"compare two Word documents\", \"diff two\n  drafts\", \"生成修订对比文件\". Do NOT use for: creating new documents from\n  scratch (use docx skill), single-file editing with revisions (use docx WIR\n  engine), or PDF-only comparisons.\n---\n\n# DOCX Tracked-Changes Comparison\n\nGiven an OLD and a NEW version of a `.docx`, produce ONE output `.docx` that\nopens in Word with native revision marks (`<w:ins>` / `<w:del>`) showing every\nchange from OLD to NEW. The output uses the NEW file as the base package, so\nall its styles, images, footnotes, tables, and section properties are\npreserved; accepting all revisions yields exactly NEW, rejecting all yields\nexactly OLD.\n\n## Workflow\n\n1. **Run the script** — do not reimplement the diff:\n\n```bash\npython3 scripts/compare_docx_tracked.py OLD.docx NEW.docx OUT.docx \\\n    --author \"Reviser Name\" --date \"2026-08-15T00:00:00Z\"\n```\n\n- Ask the user for the revision **author name** and date if not provided\n  (default author \"Editor\", default date = today). The author is usually the\n  person who made the new draft, not the assistant.\n- `--threshold` (default 0.45) controls when a paragraph pair is treated as\n  \"modified\" (word-level inline revisions) vs \"deleted + inserted\" (two whole\n  paragraphs). Lower it if too many lightly-edited paragraphs show as whole-\n  paragraph replace; raise it if heavily rewritten paragraphs produce noisy\n  inline diffs.\n- The script prints stats (ins/del paragraphs, word-level modified, fallbacks).\n  Report these numbers to the user.\n\n2. **Verify (mandatory)** — run the verifier; all checks must PASS:\n\n```bash\npython3 scripts/verify_tracked.py OUT.docx OLD.docx NEW.docx\n```\n\nIt checks: unique revision ids, no stray `w:t` inside `w:del`, resolvable\nrelationship references, `w:trackChanges` present, accept-all == NEW text,\nreject-all == OLD text, and that OLD-only content is fully covered by\n`w:delText`.\n\n3. **Render check** — convert with LibreOffice to confirm the package opens\n   cleanly and revisions render (strikethrough deletions, marked insertions):\n\n```bash\nsoffice --headless --convert-to pdf --outdir <tmpdir> OUT.docx\n```\n\nIf conversion fails or the verifier fails, consult\n`references/ooxml-revision-rules.md` — it catalogs the exact OOXML rules and\nknown failure modes (stray `w:t` in `w:del`, missing paragraph-mark deletions,\ndangling r:ids, missing `w:trackChanges`).\n\n## Output conventions\n\n- Name the output `<oldTag>-vs-<newTag>-tracked-changes.docx` (e.g.,\n  `20260810-vs-20260815-tracked-changes.docx`) and tell the user it opens in\n  Word's revision (\"所有标记\") view.\n- A few paragraphs containing images/equations/hyperlinks may legitimately\n  appear as whole-paragraph delete+insert instead of inline diffs — this is a\n  designed fallback, mention it if it occurs (the script reports\n  `mod_fallback`).\n\n## Scope & limits\n\n- Both inputs must be valid `.docx` (convert `.doc` first via\n  `libreoffice --headless --convert-to docx`).\n- Comparison covers the main document body (including table cell paragraphs);\n  comments/footnotes content is not diffed (footnotes of the NEW package are\n  preserved as-is).\n- Verified via LibreOffice and XML-level simulation; when the stakes are high,\n  advise the user to eyeball the result in Microsoft Word's \"All Markup\" view.\n\nFile v0.1.0:README.md\n\n# 📝 docx-trackdiff\n\n![docx-trackdiff banner](docs/banner.png)\n\n**Compare two Word documents (.docx) and get a native Track Changes redline — as if a human editor had revised the old draft into the new one with \"Track Changes\" switched on.**\n\nEnglish | [简体中文](README.zh-CN.md)\n\n![Python](https://img.shields.io/badge/python-3.8%2B-blue)\n![License](https://img.shields.io/badge/license-MIT-green)\n![Format](https://img.shields.io/badge/format-DOCX%20%2F%20OOXML-orange)\n![Kimi](https://img.shields.io/badge/built%20with-Kimi%20K3%20Agent%20Swarm-blueviolet)\n![PRs](https://img.shields.io/badge/PRs-welcome-brightgreen)\n\n`track-changes` `docx-diff` `word-compare` `redline` `document-comparison` `ooxml` `kimi-skill` `agent-swarm`\n\n---\n\n## 🤔 Why this exists\n\nIn the age of AI-assisted writing, documents iterate *fast*. A paper, a report, a contract — every prompt produces a new version, and suddenly you have `v3-final-FINAL.docx` chaos. You want to know **exactly what changed** between two drafts, in the one format every collaborator understands: **Word's native revision mode**, where each edit can be individually accepted or rejected.\n\nExisting options fall short:\n\n- ☁️ Online comparison tools require uploading your unpublished manuscript — a privacy no-go for pre-publication research.\n- 📄 Word's built-in *Compare* works, but is manual, GUI-bound, and can't be scripted into an automated pipeline.\n- 🐍 `difflib` & friends give you text diffs, not a Word file with real `<w:ins>` / `<w:del>` revision marks.\n\nThis tool fills the gap: **one command in, one tracked-changes `.docx` out** — open it in Microsoft Word, WPS, or LibreOffice and review every insertion and deletion in the familiar \"All Markup\" view.\n\n## 📸 Demo\n\nTwo synthetic demo documents (text + figure + table) are compared — no real data involved:\n\n| Page 1 — title, inline edits, deleted caption, replaced figure | Page 2 — table cell edit, new row, rewritten conclusion, new section |\n|---|---|\n| ![demo page 1](docs/demo-1.png) | ![demo page 2](docs/demo-2.png) |\n\nNotice the details:\n\n- 🔤 **Word-level inline revisions** — `12%` → ~~12~~`18%`, ~~sharply~~`moderately`\n- 🖼️ **Figure replacement tracked** — the old chart is marked deleted *with its original bytes preserved*, the new chart marked inserted\n- 📊 **Table edits** — a changed cell (`4.5` → `4.3`) and an inserted row (`Delta`)\n- ➕➖ **Whole-paragraph insertions & deletions** — the removed caption, the new \"Next Steps\" section\n\nTry it yourself with the files in [`examples/`](examples/):\n\n```bash\npython3 scripts/compare_docx_tracked.py examples/demo_v1.docx examples/demo_v2.docx out.docx --author \"You\"\n```\n\n## ✨ Features\n\n- ✅ **Native Word revisions** — real `<w:ins>` / `<w:del>` with unique IDs, author, and date; `w:trackChanges` enabled automatically\n- ✅ **Word-level granularity** — modified paragraphs get fine-grained inline diffs, not just whole-paragraph replace\n- ✅ **Structure-aware** — headings, styles, tables, footnotes, hyperlinks, equations (OMML), and section layout are preserved from the new version\n- ✅ **Image fidelity, both directions** — changed figures keep the *old* image bytes inside the deletion mark, so \"reject change\" truly restores the old picture\n- ✅ **Privacy-first** — 100% local, no upload, no network call\n- ✅ **Self-verifying** — bundled verifier simulates *accept all* (must equal the new file) and *reject all* (must equal the old file), plus 5 more structural checks\n- ✅ **Zero config** — one Python file + `lxml`, that's it\n\n## 🚀 Quick Start\n\nRequirements: Python 3.8+, `lxml` (`pip install lxml`). LibreOffice optional (render check only).\n\n```bash\ngit clone https://github.com/stephenlzc/docx-trackdiff.git\ncd docx-trackdiff\n\n# 1. Generate the tracked-changes document\npython3 scripts/compare_docx_tracked.py OLD.docx NEW.docx OUTPUT.docx \\\n    --author \"Your Name\" --date \"2026-08-15T00:00:00Z\"\n\n# 2. Verify (mandatory — 7 automated checks)\npython3 scripts/verify_tracked.py OUTPUT.docx OLD.docx NEW.docx\n\n# 3. Optional render check\nsoffice --headless --convert-to pdf OUTPUT.docx\n```\n\nOpen `OUTPUT.docx` in Word → Review tab → **All Markup**. Accept or reject each change individually.\n\n### Options\n\n| Flag | Default | Meaning |\n|---|---|---|\n| `--author` | `Editor` | Revision author shown in Word's markup panel |\n| `--date` | today | Revision timestamp |\n| `--threshold` | `0.45` | Paragraph similarity cutoff: above → inline word-level diff; below → whole-paragraph delete+insert |\n\n## 🤖 Use as a Kimi Agent Skill\n\nThis repo doubles as a **Kimi agent skill**. Clone it (or download the ZIP) and drop the folder into your Kimi skills directory (`~/.kimi-code/skills/` or `~/.agents/skills/`), then simply say:\n\n> \"对比一下这两个版本的 docx，给我一份修订模式的文件\"\n> \"Compare these two Word documents with track changes\"\n\nThe agent reads `SKILL.md`, runs the bundled scripts, verifies the output, and hands you the redline — no manual steps.\n\n## 🧠 How it works\n\n1. **Paragraph alignment** — `difflib.SequenceMatcher` over normalized text (curly quotes, dashes, spaces folded) aligns paragraphs between versions; a DP second pass pairs up \"modified\" paragraphs inside replace blocks (similarity ≥ threshold).\n2. **Word-level diff** — modified paragraphs are tokenized and diffed; runs are split at diff boundaries while preserving original formatting. Paragraphs whose diff boundary crosses an atomic element (image, equation, hyperlink) fall back to whole-paragraph delete+insert by design.\n3. **OOXML surgery, done right** — deleted paragraphs are deep-copied with their formatting, converted to `w:delText`, paragraph marks flagged, relationship IDs remapped, and *old image bytes copied into the package* so reject-all is lossless. `w:trackChanges` is injected at the schema-correct position in `settings.xml`.\n4. **Verification** — unique revision IDs, no stray `w:t` inside `w:del`, no dangling references, accept/reject round-trip equality, deleted-content coverage, author/date presence, and old-image byte preservation.\n\nSee [`references/ooxml-revision-rules.md`](references/ooxml-revision-rules.md) for the full rulebook and known failure modes.\n\n## ⚠️ Limitations\n\n- Compares the **main document body** (including table cells); comments and footnote *content* are not diffed\n- A few paragraphs containing images/equations may appear as whole-paragraph delete+insert (designed fallback)\n- Verified via LibreOffice + XML-level simulation; for high-stakes use, eyeball the result in desktop Word's All Markup view\n- `.doc` files must be converted to `.docx` first\n\n## 🌱 Origin Story\n\nThis skill was **not** designed in the abstract — it was born from a real workflow. While iterating on an academic paper across multiple AI-assisted revisions, [Big Stephen](https://github.com/stephenlzc) needed to see exactly what changed between drafts. The entire pipeline — diff algorithm, OOXML revision markup, verification harness, and this very skill packaging — was implemented through **Kimi K3's Agent Swarm** (by [Moonshot AI](https://www.moonshot.ai/)): a coder subagent built and hardened the scripts, and a swarm-style evaluation round (paired with-skill vs. baseline runs, blind grading by a verifier subagent) caught and fixed a real image-fidelity bug before release.\n\nThe headline results of that evaluation: the with-skill run finished in **~1 minute** versus **~15 minutes** for a competent from-scratch baseline, with zero judgment errors. And the blind grader earned its keep — it caught a genuine image-fidelity defect (a replaced figure's *old* bytes were silently lost, so \"reject change\" would have restored the wrong picture) that the skill's own text-only verifier could not see. The fix and two hardened verifier checks (now 7 total) came straight out of that loop. Full report: [EVALUATION.md](EVALUATION.md).\n\nIt worked so well in daily use that it was distilled into this reusable skill and open-sourced. **Built with Kimi K3.** 🌒\n\n## 🙌 Credits\n\n- **Author**: Big Stephen — idea, requirements, real-world testing\n- **Co-author**: Kimi K3 Agent Swarm by [Moonshot AI](https://www.moonshot.ai/) ([@MoonshotAI](https://github.com/MoonshotAI) · [Kimi-K3](https://github.com/MoonshotAI/Kimi-K3)) — implementation, verification, packaging\n\n## 📄 License\n\n[MIT](LICENSE) — use it anywhere, attribution appreciated.\n\n## 🔖 Topics\n\n`docx` `track-changes` `word-diff` `redline` `document-comparison` `ooxml` `python` `kimi` `kimi-k3` `moonshot-ai` `agent-skill` `ai-writing` `diff-tool` `word-documents` `revision-tracking`\n\nFile v0.1.0:_meta.json\n\n{\n  \"ownerId\": \"kn77k0qnxvrb2gwbr1132zf7kh80qhny\",\n  \"slug\": \"docx-trackdiff\",\n  \"version\": \"0.1.0\",\n  \"publishedAt\": 1786818488707\n}\n\nFile v0.1.0:references/ooxml-revision-rules.md\n\n# OOXML 修订标记规则速查（失败模式手册）\n\n生成 tracked-changes docx 时必须遵守的硬规则。脚本 `compare_docx_tracked.py` 已实现全部规则；仅当脚本需要修补或需要手工排查时阅读本文件。\n\n## 目录\n1. 修订元素语法\n2. 段落级 vs 行内修订\n3. 包级要求\n4. 已知失败模式\n\n## 1. 修订元素语法\n\n```xml\n<w:ins w:id=\"12\" w:author=\"Name\" w:date=\"2026-08-15T00:00:00Z\">\n  <w:r><w:t>newly added text</w:t></w:r>\n</w:ins>\n<w:del w:id=\"13\" w:author=\"Name\" w:date=\"2026-08-15T00:00:00Z\">\n  <w:r><w:delText xml:space=\"preserve\">removed text</w:delText></w:r>\n</w:del>\n```\n\n- `w:id` 必须全局唯一且递增。\n- `<w:del>` 内的文本节点**必须**是 `<w:delText>`（不是 `<w:t>`），并保留 `xml:space=\"preserve\"`。递归转换整棵子树。\n- `<w:ins>`/`<w:del>` 包裹完整的 `<w:r>`，不得放在 `<w:r>` 内部。\n- 不得出现 ins/del 互相嵌套。\n\n## 2. 段落级 vs 行内修订\n\n**整段插入/删除**：除包裹所有内容 run 外，还必须标记段落标记本身（否则 Word 里会留下空行或不显示为整段增删）：\n\n```xml\n<w:p>\n  <w:pPr>\n    <w:rPr><w:del w:id=\"14\" w:author=\"Name\" w:date=\"...\"/></w:rPr>\n  </w:pPr>\n  <w:del ...><w:r><w:delText xml:space=\"preserve\">...</w:delText></w:r></w:del>\n</w:p>\n```\n\n`w:pPr/w:rPr` 中 ins/del 标记必须是 `rPr` 的第一个子元素。\n\n**行内词级修订**：在新段落内按词级 diff 拆分 run；删除片段生成带 `<w:delText>` 的新 run（继承最近可见的 `rPr` 格式），插入片段包 `<w:ins>`。\n\n**复杂块回退**：含图片、`m:oMath` 公式、超链接等\"原子\"元素且 diff 边界无法对齐时，整段回退为\"删旧段 + 插新段\"，不要强行拆 run。\n\n## 3. 包级要求\n\n- `word/settings.xml` 加入 `<w:trackChanges/>`，位置在 `<w:doNotTrackMoves>` 之前（无则放 `<w:defaultTabStop>` 前，再无则追加）。\n- 被删段落深拷贝自旧文档：剥除 `w:bookmarkStart/End`、`w:proofErr`、`w:permStart/End`（避免 id 冲突）。\n- 旧段落中的 `r:id` / `r:embed` / `r:link` 必须重映射到新包的 rels；图片部件按需复制（前缀 `tracked_` 防重名）。\n- zip 其余部件原样拷贝。\n\n## 4. 已知失败模式\n\n| 症状 | 原因 | 修法 |\n|---|---|---|\n| Word 打开报\"无法读取的内容\" | `<w:del>` 内残留 `<w:t>`；或 id 重复；或 r:id 悬空 | 跑 `verify_tracked.py` 定位 |\n| 删除段落在 Word 中显示为空行 | 段落标记未标 del（缺 `pPr/rPr/del`） | 见第 2 节 |\n| 修订显示但\"拒绝修订\"后文本不对 | 段落边界标记被误判（验证脚本需把 pPr/rPr 内的 ins/del 视为段落级标记） | 用 `verify_tracked.py` 的 accept/reject 模拟核对 |\n| 修订未显示（文档看似干净） | settings.xml 缺 `w:trackChanges` | 见第 3 节 |\n| 引用旧版图片的删除段落图片丢失 | rId 未重映射 / media 未复制 | 见第 3 节 |\n\nFile v0.1.0:EVALUATION.md\n\n# 🧪 Evaluation Report — Swarm-Style Paired Testing\n\nEnglish | [中文摘要](#-中文摘要)\n\nThis document records the evaluation that `docx-trackdiff` went through before\nrelease. The evaluation followed the **skill-creator swarm protocol**: paired\n`with_skill` vs. `baseline` executions on an identical real-world task, blind\ngrading by an independent verifier agent, then a fix-and-re-verify loop.\n\n> **TL;DR** — The skill-produced output passed all checks in ~1 minute. The\n> blind grader caught a genuine image-fidelity defect in the skill's own script\n> that its text-level verifier could not see. The bug was fixed, the verifier\n> was hardened from 5 to 7 checks, and both outputs now pass 7/7.\n\n---\n\n## 1. Setup\n\n| | |\n|---|---|\n| **Eval task** | \"Compare two versions of a paper (.docx) and produce a Word tracked-changes file that can be accepted/rejected per revision.\" |\n| **Inputs** | Two real successive drafts of an academic paper (~6.4k → ~8.0k words, 150 vs 177 paragraphs, 14 tables, embedded figures, footnotes, hyperlinks) |\n| **Revision metadata required** | author `Big Stephen`, date `2026-08-14` |\n| **Run A — with_skill** | Agent reads `SKILL.md`, follows its workflow (bundled scripts only) |\n| **Run B — baseline** | Agent solves from scratch, explicitly forbidden from reading the skill directory |\n| **Grader** | Independent verifier agent; did **not** know which output used the skill |\n\nBoth executors received the same prompt, the same input files, and the same\noutput expectations. The grader received both outputs labeled only A and B.\n\n## 2. Results\n\n| | 🅰️ with_skill | 🅱️ baseline |\n|---|---|---|\n| **Wall-clock effort** | **~1 minute** (script run + verify + render) | ~15 minutes (own implementation, 2 fix-rebuild cycles) |\n| **Revision marks** | 811 `<w:ins>` / 411 `<w:del>` | 2,463 `<w:ins>` / 387 `<w:del>` |\n| **Unique revision IDs** | ✅ 1,222, zero duplicates | ✅ 2,850, zero duplicates |\n| **author / date on every revision** | ✅ | ✅ |\n| **`w:trackChanges` enabled** | ✅ | ✅ |\n| **No stray `w:t` inside `w:del`** | ✅ | ✅ |\n| **Accept-all == NEW text** (728 paras) | ✅ | ✅ |\n| **Reject-all == OLD text** (701 paras) | ✅ | ✅ |\n| **LibreOffice PDF render** | ✅ clean | ✅ clean |\n| **Changed-figure fidelity** | ❌ **defect found** (see §3) | ✅ old bytes preserved |\n| **Spurious revisions** | ✅ none | ⚠️ 1 (byte-identical renumbered image marked del+ins) |\n\n## 3. 🐞 The bug the grader caught\n\nThe skill's script reused relationship targets **by file name** when remapping\ndeleted-paragraph images into the new package. Both drafts contained figures at\nthe same media paths (e.g. `word/media/rId13.png`) but with **different bytes**.\nResult: the deletion mark for a replaced figure pointed at the *new* image —\nthe old figure's bytes were silently lost, and \"reject change\" would have\nrestored the wrong picture.\n\nCrucially, **the skill's own 5-check verifier passed this output**, because its\naccept/reject simulation was text-only. The blind grader caught it by hashing\nmedia parts end-to-end.\n\n**Fix** (`compare_docx_tracked.py`): relationship reuse for images now requires\na **byte-level match**; otherwise the old image is copied into the package\nunder a `tracked_*` name and referenced by a fresh relationship ID.\n\n**Verifier hardening** (`verify_tracked.py`), from 5 to 7 checks:\n\n- ➕ every revision carries `w:author` and `w:date`\n- ➕ every OLD image's bytes survive somewhere in the output package (md5 set comparison)\n\n## 4. Post-fix verification\n\n| Check | with_skill output | baseline output |\n|---|---|---|\n| 1. Structure (unique IDs, no stray `w:t`, no dangling refs) | ✅ | ✅ |\n| 2. `w:trackChanges` present | ✅ | ✅ |\n| 3. Accept-all == NEW (paragraph-exact) | ✅ | ✅ |\n| 4. Reject-all == OLD (paragraph-exact) | ✅ | ✅ |\n| 5. OLD-only paragraphs fully covered by `w:delText` | ✅ | ✅ |\n| 6. author & date on all revisions | ✅ | ✅ |\n| 7. OLD image bytes preserved | ✅ (4 `tracked_*.png` added) | ✅ |\n\n**7 / 7 PASS on both outputs.**\n\n## 5. Takeaways\n\n1. **The skill delivers its promise**: ~15× faster than a competent from-scratch\n   implementation, with zero judgment errors, because the fragile OOXML rules\n   live in tested code instead of the agent's working memory.\n2. **Blind grading earned its keep**: the most serious defect was invisible to\n   the skill's own verifier. An adversarial second pair of eyes — comparing\n   media bytes, not just text — was what caught it.\n3. **Evals should check bidirectional fidelity**: for tracked-changes output,\n   \"reject all\" must restore the old document *completely* — images included.\n   Text-only simulation is not enough.\n4. **Baseline strengths were folded back**: the baseline's correct handling of\n   changed figures became the skill's fix; its one weakness (marking a\n   byte-identical renumbered image as changed) is a case the skill already\n   handled correctly.\n\n---\n\n*Evaluation conducted with the Kimi K3 Agent Swarm: one coder executor\n(with_skill), one general executor (baseline), one independent verifier\n(grader). Prompts, outputs, and grading evidence were produced on 2026-08-16.*\n\n---\n\n## 🇨🇳 中文摘要\n\n本文件记录了 `docx-trackdiff` 发布前的 **swarm 式配对盲测**：同一真实任务\n（对比一份学术论文的两个版本、生成 Word 修订模式文件）分别由\"使用技能的代理\"\n和\"零技能基线代理\"执行，再由不知情的独立评分代理盲评。\n\n- **效率**：with_skill 约 1 分钟完成，baseline 从零实现约 15 分钟\n- **质量**：盲评抓到了技能脚本的一个真实缺陷——同名图片字节不同时旧图会丢失\n  （\"拒绝修订\"无法恢复旧图），技能自带的 5 项纯文本验证器对此不可见\n- **修复闭环**：图片关系复用改为字节级比对；验证器从 5 项加固到 7 项\n  （新增作者/日期检查、旧图字节保留检查）\n- **最终结果**：修复后两个产物均 7/7 全过\n\n结论：技能把脆弱的 OOXML 规则固化进测试过的代码，速度提升约 15 倍且零判断失误；\n而独立盲评证明了自身价值——最严重的缺陷恰恰逃不过第二双眼睛。\n\nFile v0.1.0:README.zh-CN.md\n\n# 📝 docx-trackdiff\n\n![docx-trackdiff banner](docs/banner.png)\n\n**对比两个 Word 文档（.docx），一键生成原生\"修订模式\"（Track Changes）对比文件——就像一位编辑打开\"修订\"后亲手把旧稿改成新稿。**\n\n[English](README.md) | 简体中文\n\n![Python](https://img.shields.io/badge/python-3.8%2B-blue)\n![License](https://img.shields.io/badge/license-MIT-green)\n![Format](https://img.shields.io/badge/format-DOCX%20%2F%20OOXML-orange)\n![Kimi](https://img.shields.io/badge/built%20with-Kimi%20K3%20Agent%20Swarm-blueviolet)\n![PRs](https://img.shields.io/badge/PRs-welcome-brightgreen)\n\n`修订模式` `track-changes` `docx对比` `word文档比较` `红线标注` `ooxml` `kimi技能` `agent-swarm`\n\n---\n\n## 🤔 为什么做这个工具\n\nAI 辅助写作的时代，文档迭代极快：论文、报告、合同——每一轮对话都产出一个新版本。你想知道两版之间**到底改了什么**，而且要用所有人都看得懂的形式：**Word 原生修订视图**，每一条修改都可以逐条接受或拒绝。\n\n现有方案都不够好：\n\n- ☁️ 在线对比工具要上传未发表的手稿——对未发表研究来说隐私不可接受\n- 📄 Word 自带的\"比较\"功能依赖手工 GUI 操作，无法脚本化进自动化流程\n- 🐍 `difflib` 之类的工具只能给文本 diff，给不了带真正 `<w:ins>` / `<w:del>` 修订标记的 Word 文件\n\n这个工具补上了缺口：**一条命令进，一份修订模式 .docx 出**——在 Microsoft Word、WPS 或 LibreOffice 里打开，就是你熟悉的\"所有标记\"视图。\n\n## 📸 效果演示\n\n用两份合成演示文档（含文字、图片、表格）对比，不涉及任何真实数据：\n\n| 第 1 页 —— 标题、行内修改、被删说明段、被替换的图 | 第 2 页 —— 表格单元格修改、新增行、重写的结论、新增章节 |\n|---|---|\n| ![demo page 1](docs/demo-1.png) | ![demo page 2](docs/demo-2.png) |\n\n注意这些细节：\n\n- 🔤 **词级行内修订**——`12%` → ~~12~~`18%`、~~sharply~~`moderately`\n- 🖼️ **图片替换可追踪**——旧图被标为删除且**原始字节完整保留**，\"拒绝修订\"能真正恢复旧图；新图标为插入\n- 📊 **表格修改**——单元格数值变化（`4.5` → `4.3`）和整行插入（`Delta`）\n- ➕➖ **整段增删**——被删的图表说明段、新增的\"Next Steps\"章节\n\n[`examples/`](examples/) 目录里有现成的演示文件，可以自己跑一遍：\n\n```bash\npython3 scripts/compare_docx_tracked.py examples/demo_v1.docx examples/demo_v2.docx out.docx --author \"你的名字\"\n```\n\n## ✨ 特性\n\n- ✅ **原生 Word 修订**——真正的 `<w:ins>` / `<w:del>`，带唯一 ID、作者、日期；自动开启 `w:trackChanges`\n- ✅ **词级粒度**——修改段落做细粒度行内 diff，而不是粗暴的整段替换\n- ✅ **结构感知**——完整保留新版的标题样式、表格、脚注、超链接、OMML 公式和节版式\n- ✅ **图片双向保真**——被替换的旧图字节保留在删除标记内，拒绝修订可无损恢复\n- ✅ **隐私优先**——100% 本地运行，零上传，零网络调用\n- ✅ **自我验证**——内置验证器模拟\"接受全部\"（必须等于新版）和\"拒绝全部\"（必须等于旧版），外加 5 项结构检查\n- ✅ **零配置**——一个 Python 脚本 + `lxml`，没了\n\n## 🚀 快速上手\n\n环境要求：Python 3.8+，`lxml`（`pip install lxml`）。LibreOffice 可选（仅用于渲染检查）。\n\n```bash\ngit clone https://github.com/stephenlzc/docx-trackdiff.git\ncd docx-trackdiff\n\n# 1. 生成修订对比文件\npython3 scripts/compare_docx_tracked.py 旧版.docx 新版.docx 输出.docx \\\n    --author \"你的名字\" --date \"2026-08-15T00:00:00Z\"\n\n# 2. 验证（必做——7 项自动检查）\npython3 scripts/verify_tracked.py 输出.docx 旧版.docx 新版.docx\n\n# 3. 可选：渲染检查\nsoffice --headless --convert-to pdf 输出.docx\n```\n\n在 Word 中打开输出文件 → 审阅选项卡 → **所有标记**，逐条接受或拒绝。\n\n### 参数\n\n| 参数 | 默认值 | 含义 |\n|---|---|---|\n| `--author` | `Editor` | Word 修订面板中显示的修订人 |\n| `--date` | 当天 | 修订时间戳 |\n| `--threshold` | `0.45` | 段落相似度阈值：高于它 → 词级行内 diff；低于它 → 整段删除+插入 |\n\n## 🤖 作为 Kimi Agent 技能使用\n\n本仓库同时是一个 **Kimi agent skill**。克隆本仓库（或下载 ZIP）后，把文件夹放进 Kimi 技能目录（`~/.kimi-code/skills/` 或 `~/.agents/skills/`），然后直接说：\n\n> \"对比一下这两个版本的 docx，给我一份修订模式的文件\"\n> \"Compare these two Word documents with track changes\"\n\nAgent 会读取 `SKILL.md`，调用内置脚本，自动验证，把红线对比文件交给你——全程零手工。\n\n## 🧠 工作原理\n\n1. **段落对齐**——`difflib.SequenceMatcher` 对归一化文本（弯引号、破折号、空白折叠）做全文段落对齐；replace 块内用动态规划二次配对\"修改\"段落（相似度 ≥ 阈值）\n2. **词级 diff**——修改段落分词后做 diff，run 在 diff 边界拆分且保留原格式；diff 边界跨越原子元素（图片、公式、超链接）的段落按设计回退为整段删除+插入\n3. **规范的 OOXML 操作**——被删段落带格式深拷贝、文本转 `w:delText`、段落标记打标、关系 ID 重映射、**旧图字节拷入包内**保证拒绝修订无损；`w:trackChanges` 插入 `settings.xml` 的 schema 正确位置\n4. **七项验证**——修订 ID 唯一、`w:del` 内无残留 `w:t`、引用无悬空、接受/拒绝双向等价、删除内容覆盖、作者日期齐全、旧图字节保留\n\n完整规则与已知失败模式见 [`references/ooxml-revision-rules.md`](references/ooxml-revision-rules.md)。\n\n## ⚠️ 已知限制\n\n- 对比范围为**文档正文**（含表格单元格）；批注和脚注**内容**不参与对比\n- 少数含图片/公式的段落会以整段删除+插入呈现（设计内回退）\n- 通过 LibreOffice + XML 级模拟验证；重要场景建议在桌面版 Word 的\"所有标记\"视图中过目一遍\n- `.doc` 文件需先转换为 `.docx`\n\n## 🌱 诞生故事\n\n这个技能不是凭空设计的，而是从真实工作流里长出来的。Big Stephen 在一篇学术论文的多轮 AI 辅助修订中，需要精确看到每个版本之间的改动。整条流水线——diff 算法、OOXML 修订标记、验证框架、乃至技能打包本身——都是通过 **Kimi K3 的 Agent Swarm**（[Moonshot AI](https://www.moonshot.cn/) 出品）实现的：coder 子代理构建并加固脚本，随后一轮 swarm 式评估（with-skill 与 baseline 配对盲测 + 独立评分代理）在发布前抓出并修复了一个真实的图片保真 bug。\n\n那次评估的关键结论：使用技能的运行**约 1 分钟**完成，而能力不差的从零实现基线用了**约 15 分钟**，且零判断失误。独立盲评也证明了自己的价值——它抓到了一个真实的图片保真缺陷（被替换图片的*旧图字节*被静默丢失，\"拒绝修订\"会恢复成错误的图），而技能自带的纯文本验证器对此完全不可见。修复方案和两项新增的验证检查（从 5 项加固到 7 项）正是来自这个闭环。完整报告见 [EVALUATION.md](EVALUATION.md)。\n\n因为自己在实际场景里用得非常好，所以把它沉淀成可复用的技能并开源。**使用 Kimi K3 构建。** 🌒\n\n## 🙌 致谢\n\n- **作者**：Big Stephen——需求、真实场景测试\n- **共同作者**：Kimi K3 Agent Swarm，由 [Moonshot AI](https://www.moonshot.cn/) 出品（[@MoonshotAI](https://github.com/MoonshotAI) · [Kimi-K3](https://github.com/MoonshotAI/Kimi-K3)）——实现、验证、打包\n\n## 📄 许可证\n\n[MIT](LICENSE)——随意使用，保留署名即可。\n\n## 🔖 关键词\n\n`docx` `修订模式` `track-changes` `word对比` `红线` `文档比较` `ooxml` `python` `kimi` `kimi-k3` `moonshot-ai` `agent-skill` `ai写作` `diff工具` `word文档` `修订追踪`\n\nFile v0.1.0:skill-card.md\n\n## Description:\n\nCompare two versions of a DOCX document and produce a native Word tracked-changes file with insertions and deletions that can be accepted or rejected.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[stephenlzc](https://clawhub.ai/user/stephenlzc)\n\n### License/Terms of Use:\n\nMIT\n\n## Use Case:\n\nDevelopers, editors, and document reviewers use this skill to compare two DOCX drafts and generate one Word redline that shows native tracked insertions and deletions. It is suited for papers, reports, contracts, and other draft-to-draft review workflows where accepting all changes should match the new file and rejecting all changes should match the old file.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: Processing untrusted or unusually large DOCX files can create parser or resource-exhaustion exposure.\n\nMitigation: Run the skill in an isolated, resource-limited worker for untrusted documents.\n\nRisk: An unpinned `lxml` dependency can reduce reproducibility across environments.\n\nMitigation: Use a virtual environment and pin `lxml` when repeatable results matter.\n\nRisk: Tracked-change fidelity matters for high-stakes document review.\n\nMitigation: Run the bundled verifier and inspect important outputs in Microsoft Word's All Markup view.\n\n## Reference(s):\n\n- [ClawHub Skill Page](https://clawhub.ai/stephenlzc/skills/docx-trackdiff)\n- [Server-Resolved GitHub Source](https://github.com/stephenlzc/docx-trackdiff)\n- [OOXML Revision Rules](references/ooxml-revision-rules.md)\n- [Evaluation Report](EVALUATION.md)\n- [README](README.md)\n\n## Skill Output:\n\n**Output Type(s):** [file, text, shell commands, guidance]\n\n**Output Format:** [DOCX file plus concise text status, verification results, and shell commands]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [Produces a tracked-changes DOCX from an old and new DOCX input; requires revision author and date metadata, with defaults available.]\n\n## Skill Version(s):\n\n0.1.0 (source: ClawHub release metadata)\n\n## Ethical Considerations:\n\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.\n\nFile v0.1.0:LICENSE\n\nMIT License\n\nCopyright (c) 2026 Big Stephen\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.","readmeExcerpt":"Skill: docx-trackdiff Owner: stephenlzc Summary: Compare two versions of a .docx document and produce a single Word file in tracked-changes (revision / tracking) mode, as if a human had edited the old file into the new one with Track Changes turned on. Use whenever the user has two versions of a DOCX (e.g., successive drafts of a paper, report, or contract — often AI-generated or AI-assisted revisions) and wants to s","codeSnippets":[],"executableExamples":[{"language":"bash","snippet":"python3 scripts/compare_docx_tracked.py OLD.docx NEW.docx OUT.docx \\\n    --author \"Reviser Name\" --date \"2026-08-15T00:00:00Z\""},{"language":"bash","snippet":"python3 scripts/verify_tracked.py OUT.docx OLD.docx NEW.docx"},{"language":"bash","snippet":"soffice --headless --convert-to pdf --outdir <tmpdir> OUT.docx"},{"language":"bash","snippet":"python3 scripts/compare_docx_tracked.py examples/demo_v1.docx examples/demo_v2.docx out.docx --author \"You\""},{"language":"bash","snippet":"git clone https://github.com/stephenlzc/docx-trackdiff.git\ncd docx-trackdiff\n\n# 1. Generate the tracked-changes document\npython3 scripts/compare_docx_tracked.py OLD.docx NEW.docx OUTPUT.docx \\\n    --author \"Your Name\" --date \"2026-08-15T00:00:00Z\"\n\n# 2. Verify (mandatory — 7 automated checks)\npython3 scripts/verify_tracked.py OUTPUT.docx OLD.docx NEW.docx\n\n# 3. Optional render check\nsoffice --headless --convert-to pdf OUTPUT.docx"},{"language":"xml","snippet":"<w:ins w:id=\"12\" w:author=\"Name\" w:date=\"2026-08-15T00:00:00Z\">\n  <w:r><w:t>newly added text</w:t></w:r>\n</w:ins>\n<w:del w:id=\"13\" w:author=\"Name\" w:date=\"2026-08-15T00:00:00Z\">\n  <w:r><w:delText xml:space=\"preserve\">removed text</w:delText></w:r>\n</w:del>"}],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"SKILL.md","content":"---\nname: docx-trackdiff\ndescription: >\n  Compare two versions of a .docx document and produce a single Word file in\n  tracked-changes (revision / tracking) mode, as if a human had edited the old\n  file into the new one with Track Changes turned on. Use whenever the user has\n  two versions of a DOCX (e.g., successive drafts of a paper, report, or\n  contract — often AI-generated or AI-assisted revisions) and wants to see the\n  differences as native Word revisions (insertions/deletions) that can be\n  accepted/rejected in Word. Triggers: \"对比两个版本的 docx\", \"tracked changes\",\n  \"tracking mode\", \"修订模式对比\", \"compare two Word documents\", \"diff two\n  drafts\", \"生成修订对比文件\". Do NOT use for: creating new documents from\n  scratch (use docx skill), single-file editing with revisions (use docx WIR\n  engine), or PDF-only comparisons.\n---\n\n# DOCX Tracked-Changes Comparison\n\nGiven an OLD and a NEW version of a `.docx`, produce ONE output `.docx` that\nopens in Word with native revision marks (`<w:ins>` / `<w:del>`) showing every\nchange from OLD to NEW. The output uses the NEW file as the base package, so\nall its styles, images, footnotes, tables, and section properties are\npreserved; accepting all revisions yields exactly NEW, rejecting all yields\nexactly OLD.\n\n## Workflow\n\n1. **Run the script** — do not reimplement the diff:\n\n```bash\npython3 scripts/compare_docx_tracked.py OLD.docx NEW.docx OUT.docx \\\n    --author \"Reviser Name\" --date \"2026-08-15T00:00:00Z\"\n```\n\n- Ask the user for the revision **author name** and date if not provided\n  (default author \"Editor\", default date = today). The author is usually the\n  person who made the new draft, not the assistant.\n- `--threshold` (default 0.45) controls when a paragraph pair is treated as\n  \"modified\" (word-level inline revisions) vs \"deleted + inserted\" (two whole\n  paragraphs). Lower it if too many lightly-edited paragraphs show as whole-\n  paragraph replace; raise it if heavily rewritten paragraphs produce noisy\n  inline diffs.\n- The script prints stats (ins/del paragraphs, word-level modified, fallbacks).\n  Report these numbers to the user.\n\n2. **Verify (mandatory)** — run the verifier; all checks must PASS:\n\n```bash\npython3 scripts/verify_tracked.py OUT.docx OLD.docx NEW.docx\n```\n\nIt checks: unique revision ids, no stray `w:t` inside `w:del`, resolvable\nrelationship references, `w:trackChanges` present, accept-all == NEW text,\nreject-all == OLD text, and that OLD-only content is fully covered by\n`w:delText`.\n\n3. **Render check** — convert with LibreOffice to confirm the package opens\n   cleanly and revisions render (strikethrough deletions, marked insertions):\n\n```bash\nsoffice --headless --convert-to pdf --outdir <tmpdir> OUT.docx\n```\n\nIf conversion fails or the verifier fails, consult\n`references/ooxml-revision-rules.md` — it catalogs the exact OOXML rules and\nknown failure modes (stray `w:t` in `w:del`, missing paragraph-mark deletions,\ndangling r:ids, missing `w:trackChanges`).\n\n## Output conventions\n\n- Name the o"},{"path":"README.md","content":"# 📝 docx-trackdiff\n\n![docx-trackdiff banner](docs/banner.png)\n\n**Compare two Word documents (.docx) and get a native Track Changes redline — as if a human editor had revised the old draft into the new one with \"Track Changes\" switched on.**\n\nEnglish | [简体中文](README.zh-CN.md)\n\n![Python](https://img.shields.io/badge/python-3.8%2B-blue)\n![License](https://img.shields.io/badge/license-MIT-green)\n![Format](https://img.shields.io/badge/format-DOCX%20%2F%20OOXML-orange)\n![Kimi](https://img.shields.io/badge/built%20with-Kimi%20K3%20Agent%20Swarm-blueviolet)\n![PRs](https://img.shields.io/badge/PRs-welcome-brightgreen)\n\n`track-changes` `docx-diff` `word-compare` `redline` `document-comparison` `ooxml` `kimi-skill` `agent-swarm`\n\n---\n\n## 🤔 Why this exists\n\nIn the age of AI-assisted writing, documents iterate *fast*. A paper, a report, a contract — every prompt produces a new version, and suddenly you have `v3-final-FINAL.docx` chaos. You want to know **exactly what changed** between two drafts, in the one format every collaborator understands: **Word's native revision mode**, where each edit can be individually accepted or rejected.\n\nExisting options fall short:\n\n- ☁️ Online comparison tools require uploading your unpublished manuscript — a privacy no-go for pre-publication research.\n- 📄 Word's built-in *Compare* works, but is manual, GUI-bound, and can't be scripted into an automated pipeline.\n- 🐍 `difflib` & friends give you text diffs, not a Word file with real `<w:ins>` / `<w:del>` revision marks.\n\nThis tool fills the gap: **one command in, one tracked-changes `.docx` out** — open it in Microsoft Word, WPS, or LibreOffice and review every insertion and deletion in the familiar \"All Markup\" view.\n\n## 📸 Demo\n\nTwo synthetic demo documents (text + figure + table) are compared — no real data involved:\n\n| Page 1 — title, inline edits, deleted caption, replaced figure | Page 2 — table cell edit, new row, rewritten conclusion, new section |\n|---|---|\n| ![demo page 1](docs/demo-1.png) | ![demo page 2](docs/demo-2.png) |\n\nNotice the details:\n\n- 🔤 **Word-level inline revisions** — `12%` → ~~12~~`18%`, ~~sharply~~`moderately`\n- 🖼️ **Figure replacement tracked** — the old chart is marked deleted *with its original bytes preserved*, the new chart marked inserted\n- 📊 **Table edits** — a changed cell (`4.5` → `4.3`) and an inserted row (`Delta`)\n- ➕➖ **Whole-paragraph insertions & deletions** — the removed caption, the new \"Next Steps\" section\n\nTry it yourself with the files in [`examples/`](examples/):\n\n```bash\npython3 scripts/compare_docx_tracked.py examples/demo_v1.docx examples/demo_v2.docx out.docx --author \"You\"\n```\n\n## ✨ Features\n\n- ✅ **Native Word revisions** — real `<w:ins>` / `<w:del>` with unique IDs, author, and date; `w:trackChanges` enabled automatically\n- ✅ **Word-level granularity** — modified paragraphs get fine-grained inline diffs, not just whole-paragraph replace\n- ✅ **Structure-aware** — headings, styles, tables, footnotes, hyperlinks, equa"},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn77k0qnxvrb2gwbr1132zf7kh80qhny\",\n  \"slug\": \"docx-trackdiff\",\n  \"version\": \"0.1.0\",\n  \"publishedAt\": 1786818488707\n}"},{"path":"references/ooxml-revision-rules.md","content":"# OOXML 修订标记规则速查（失败模式手册）\n\n生成 tracked-changes docx 时必须遵守的硬规则。脚本 `compare_docx_tracked.py` 已实现全部规则；仅当脚本需要修补或需要手工排查时阅读本文件。\n\n## 目录\n1. 修订元素语法\n2. 段落级 vs 行内修订\n3. 包级要求\n4. 已知失败模式\n\n## 1. 修订元素语法\n\n```xml\n<w:ins w:id=\"12\" w:author=\"Name\" w:date=\"2026-08-15T00:00:00Z\">\n  <w:r><w:t>newly added text</w:t></w:r>\n</w:ins>\n<w:del w:id=\"13\" w:author=\"Name\" w:date=\"2026-08-15T00:00:00Z\">\n  <w:r><w:delText xml:space=\"preserve\">removed text</w:delText></w:r>\n</w:del>\n```\n\n- `w:id` 必须全局唯一且递增。\n- `<w:del>` 内的文本节点**必须**是 `<w:delText>`（不是 `<w:t>`），并保留 `xml:space=\"preserve\"`。递归转换整棵子树。\n- `<w:ins>`/`<w:del>` 包裹完整的 `<w:r>`，不得放在 `<w:r>` 内部。\n- 不得出现 ins/del 互相嵌套。\n\n## 2. 段落级 vs 行内修订\n\n**整段插入/删除**：除包裹所有内容 run 外，还必须标记段落标记本身（否则 Word 里会留下空行或不显示为整段增删）：\n\n```xml\n<w:p>\n  <w:pPr>\n    <w:rPr><w:del w:id=\"14\" w:author=\"Name\" w:date=\"...\"/></w:rPr>\n  </w:pPr>\n  <w:del ...><w:r><w:delText xml:space=\"preserve\">...</w:delText></w:r></w:del>\n</w:p>\n```\n\n`w:pPr/w:rPr` 中 ins/del 标记必须是 `rPr` 的第一个子元素。\n\n**行内词级修订**：在新段落内按词级 diff 拆分 run；删除片段生成带 `<w:delText>` 的新 run（继承最近可见的 `rPr` 格式），插入片段包 `<w:ins>`。\n\n**复杂块回退**：含图片、`m:oMath` 公式、超链接等\"原子\"元素且 diff 边界无法对齐时，整段回退为\"删旧段 + 插新段\"，不要强行拆 run。\n\n## 3. 包级要求\n\n- `word/settings.xml` 加入 `<w:trackChanges/>`，位置在 `<w:doNotTrackMoves>` 之前（无则放 `<w:defaultTabStop>` 前，再无则追加）。\n- 被删段落深拷贝自旧文档：剥除 `w:bookmarkStart/End`、`w:proofErr`、`w:permStart/End`（避免 id 冲突）。\n- 旧段落中的 `r:id` / `r:embed` / `r:link` 必须重映射到新包的 rels；图片部件按需复制（前缀 `tracked_` 防重名）。\n- zip 其余部件原样拷贝。\n\n## 4. 已知失败模式\n\n| 症状 | 原因 | 修法 |\n|---|---|---|\n| Word 打开报\"无法读取的内容\" | `<w:del>` 内残留 `<w:t>`；或 id 重复；或 r:id 悬空 | 跑 `verify_tracked.py` 定位 |\n| 删除段落在 Word 中显示为空行 | 段落标记未标 del（缺 `pPr/rPr/del`） | 见第 2 节 |\n| 修订显示但\"拒绝修订\"后文本不对 | 段落边界标记被误判（验证脚本需把 pPr/rPr 内的 ins/del 视为段落级标记） | 用 `verify_tracked.py` 的 accept/reject 模拟核对 |\n| 修订未显示（文档看似干净） | settings.xml 缺 `w:trackChanges` | 见第 3 节 |\n| 引用旧版图片的删除段落图片丢失 | rId 未重映射 / media 未复制 | 见第 3 节 |"},{"path":"EVALUATION.md","content":"# 🧪 Evaluation Report — Swarm-Style Paired Testing\n\nEnglish | [中文摘要](#-中文摘要)\n\nThis document records the evaluation that `docx-trackdiff` went through before\nrelease. The evaluation followed the **skill-creator swarm protocol**: paired\n`with_skill` vs. `baseline` executions on an identical real-world task, blind\ngrading by an independent verifier agent, then a fix-and-re-verify loop.\n\n> **TL;DR** — The skill-produced output passed all checks in ~1 minute. The\n> blind grader caught a genuine image-fidelity defect in the skill's own script\n> that its text-level verifier could not see. The bug was fixed, the verifier\n> was hardened from 5 to 7 checks, and both outputs now pass 7/7.\n\n---\n\n## 1. Setup\n\n| | |\n|---|---|\n| **Eval task** | \"Compare two versions of a paper (.docx) and produce a Word tracked-changes file that can be accepted/rejected per revision.\" |\n| **Inputs** | Two real successive drafts of an academic paper (~6.4k → ~8.0k words, 150 vs 177 paragraphs, 14 tables, embedded figures, footnotes, hyperlinks) |\n| **Revision metadata required** | author `Big Stephen`, date `2026-08-14` |\n| **Run A — with_skill** | Agent reads `SKILL.md`, follows its workflow (bundled scripts only) |\n| **Run B — baseline** | Agent solves from scratch, explicitly forbidden from reading the skill directory |\n| **Grader** | Independent verifier agent; did **not** know which output used the skill |\n\nBoth executors received the same prompt, the same input files, and the same\noutput expectations. The grader received both outputs labeled only A and B.\n\n## 2. Results\n\n| | 🅰️ with_skill | 🅱️ baseline |\n|---|---|---|\n| **Wall-clock effort** | **~1 minute** (script run + verify + render) | ~15 minutes (own implementation, 2 fix-rebuild cycles) |\n| **Revision marks** | 811 `<w:ins>` / 411 `<w:del>` | 2,463 `<w:ins>` / 387 `<w:del>` |\n| **Unique revision IDs** | ✅ 1,222, zero duplicates | ✅ 2,850, zero duplicates |\n| **author / date on every revision** | ✅ | ✅ |\n| **`w:trackChanges` enabled** | ✅ | ✅ |\n| **No stray `w:t` inside `w:del`** | ✅ | ✅ |\n| **Accept-all == NEW text** (728 paras) | ✅ | ✅ |\n| **Reject-all == OLD text** (701 paras) | ✅ | ✅ |\n| **LibreOffice PDF render** | ✅ clean | ✅ clean |\n| **Changed-figure fidelity** | ❌ **defect found** (see §3) | ✅ old bytes preserved |\n| **Spurious revisions** | ✅ none | ⚠️ 1 (byte-identical renumbered image marked del+ins) |\n\n## 3. 🐞 The bug the grader caught\n\nThe skill's script reused relationship targets **by file name** when remapping\ndeleted-paragraph images into the new package. Both drafts contained figures at\nthe same media paths (e.g. `word/media/rId13.png`) but with **different bytes**.\nResult: the deletion mark for a replaced figure pointed at the *new* image —\nthe old figure's bytes were silently lost, and \"reject change\" would have\nrestored the wrong picture.\n\nCrucially, **the skill's own 5-check verifier passed this output**, because its\naccept/reject simulation was text-only. The blind grader caught it by hash"}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":null,"editorialQuality":{"score":100,"threshold":65,"status":"thin","wordCount":1768,"uniquenessScore":43,"reasons":["uniqueness-below-45"]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-10T07:00:09.036Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-10-10T07:00:09.036Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-10T10:42:30.134Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}