Surgical XML-level editing of existing DOCX, PPTX, XLSX with bundled scripts: run merging, repacking, numbering, sanitizing, validation, the doc_gate.py pre-delivery gate, PDF QA. Use to patch, correct, version-bump or finalize Office documents, to compare two versions into a tracked-changes redline and changelog rows, and to run the mechanical gate on any DOCX, PPTX, PDF or Markdown deliverable.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Ooxml Surgeon?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/bhesaniaaarish-ooxml-surgeon)
---
name: "ooxml-surgeon"
description: "Surgical XML-level editing of existing DOCX, PPTX, XLSX with bundled scripts: run merging, repacking, numbering, sanitizing, validation, the doc_gate.py pre-delivery gate, PDF QA. Use to patch, correct, version-bump or finalize Office documents, to compare two versions into a tracked-changes redline and changelog rows, and to run the mechanical gate on any DOCX, PPTX, PDF or Markdown deliverable."
---
# OOXML Surgeon
Persistent home for the proven pipeline, so scripts are never regenerated per session. Bundled scripts live in this skill's scripts directory; copy them to the working folder at session start. For document creation from scratch, use the docx or pptx skills instead; their validators and LibreOffice wrappers are also used here.
## Pipeline, every edit run, no shortcuts
1. Fresh unzip of the source file into a working directory (a per-document name such as spec_x/). Keep a pristine copy of the unpack beside it; every rerun starts from the pristine copy. Never edit a stale unpack.
2. Run scripts/merge_runs.py on word/document.xml and every header and footer XML before any text edit. Word splits identical text across runs and inserts proofErr noise; unmerged, plain-text search and replace silently misses targets.
3. Edit the XML with a script, not by hand. Rules for the edit step:
- Edit by assertion: every substitution must find its exact target or raise. A blind replace that silently misses is the commonest silent defect.
- Address body elements by their index in the pristine unpack, collect deletions, apply them last.
- Coloured code blocks (VS Code Dark+): rebuild a changed line by re-tokenising it into runs (element 569CD6, attribute name 9CDCFE, attribute value CE9178, comment 6A9955, punctuation and whitespace uncoloured), copying the base run properties of that line. Carry the line's highlight into every rebuilt run; the user's yellow highlights are review marks and must survive.
- Cloning list paragraphs: take the numbering instance from a bullet list (numFmt bullet), never from a numbered one, or new bullets render as 3), 4).
- Renamed or removed headings: sync the TOC. Map each TOC entry by its hyperlink anchor to the heading bookmark, rewrite the entry text from the heading, drop entries whose anchor no longer exists, add an entry and a bookmark for any new heading. Renumber cached SEQ Figure results in document order. Set w:updateFields true in settings.xml (before hdrShapeDefaults, footnotePr, endnotePr or compat) so Word refreshes page numbers on open.
- numbering.xml: w:num elements must precede w:numIdMacAtCleanup; mint new abstractNumId and numId above the existing maximum.
After the edits, run scripts/char_sweep.py on the unpacked directory and fix every hard-fail (dashes, zero-widths) before packing.
4. House style: run scripts/apply_house_style.py only on documents built from the skeleton or plain documents. Never run it on a designed document (glass-docs White Glass, any glass-design theme, any custom cover or section-opener styling) and never on a scoped patch: it rewrites Heading1 to Heading4, body size and spacing. On those, styles.xml must stay byte identical to the source; doc_gate.py --source checks the hash. deliver.sh skips the script unless --house-style is passed and refuses --house-style together with --source.
5. Repack with scripts/pack.py from the unpacked directory (canonical zip: [Content_Types].xml first, uniform timestamps, Windows create_system, no directory entries).
6. Sanitize the packed file with scripts/sanitize_docx.py: rewrites metadata to a Word-native fingerprint (Application Microsoft Office Word, author from --author or DOC_AUTHOR), strips every machine-generated trace (rsids, proofErr, customXml, generator strings, thumbnails), and repacks canonically. This is what clears corporate AV/DLP flags. Never deliver an unsanitized file. An MSIP sensitivity label in docProps/custom.xml is kept automatically with its content type override and package relationship (it prints "kept MSIP sensitivity label"); other custom parts are stripped; --drop-label only on the user's instruction.
7. Validate with the docx or pptx skill's validate.py. Fix every reported item. Its paragraph count reads word/glossary/document.xml last, so a figure such as 4103 to 2 is not content loss; compare word/document.xml paragraph and table counts directly.
8. Content gate: scripts/doc_gate.py on the packed file, zero FAIL lines. It sweeps the reader-visible text for dashes, banned words, [unverified], emoji, self-reference and narration, citation tags and banned section headings (References, Design principles, Scope); --brand NAME adds logo-only headers and Source-column rules, and each --forbid TEXT fails any occurrence of that name (for example a sister company in a co-branded set); --canon FILE adds project tokens that are retired or misspelt; --source adds styles.xml identity and label parity; --api parses every XML and JSON sample after stripping # comments (prefixes bound automatically), correlates every reqMsgId with a msgId, lists orgIds per role, and fails project tokens listed in --canon. WARN lines are judgment calls: fix or keep deliberately. The semantic items of the tech-doc-author review gate (same structure per API, field tables match payloads) remain a reading task.
9. QA render to PDF via the skill's soffice wrapper; text-searching the PDF requires whitespace normalization (collapse all whitespace before matching). Look at every changed page as an image, not only the XML; on a patch compare page counts with the source render. When the PDF itself is a deliverable (certificate, filled PDF, exported report), run scripts/pdf_sanitize.py on it and doc_gate.py on the sanitized PDF; never ship a PDF carrying the LibreOffice Producer string.
10. Deliver to the output folder and record the version lineage (file name, version, date, what changed) wherever the project keeps it.
## Delivery pipeline order (both created and patched DOCX)
One command: `scripts/deliver.sh <unpacked_dir> <Name_VX.Y_DDMonYYYY.docx> "<Title>" [--pdf] [--source ORIGINAL.docx] [--brand NAME] [--api] [--house-style]`. Order: char_sweep, apply_house_style (only with --house-style), pack, sanitize_docx (label kept), validate, doc_gate, QA render with page count (source comparison on patches), then with --pdf pdf_sanitize and a PDF gate, then copy to outputs. Nothing reaches outputs until every gate passes; QA renders stay in <unpacked_dir>_qa/ for page review. A from-scratch docx-js build is unzipped first, then runs the same order. The raw docx-js or LibreOffice output is never the delivery copy. Kits with their own finish scripts (glass-docs) still run doc_gate.py on the final DOCX and PDF.
## Why files get flagged, and the residual limit
Generated DOCX carry a non-Word Application string, empty author, edit-session rsids, and sometimes customXml or a python-docx tell; corporate gateways score these as anomalous. sanitize_docx.py removes all of them and makes the package byte-pattern match a Word save. What it cannot change is first-seen or reputation scoring on the gateway itself. If a fully sanitized file still flags, the fix is an infosec hash whitelist, not another metadata edit; halt and report rather than looping.
## Version discipline
Every patched document gets its changelog row and version bump in the same edit run as the content change, never as a separate pass. Version substitution is anchored to the exact cover and title strings, never a bare version number, and the change log row of the previous version is never touched. Sequence diagrams touched by an edit are re-rendered and re-embedded, not left stale.
## Version compare and changelog
`python3 scripts/version_diff.py OLD.docx NEW.docx --out DIR --version VX.Y --date YYYY-MM-DD [--author NAME] [--pdf]` writes a redline DOCX with native Word tracked changes (author and date set on every revision; Word accept and reject work), changes.md and changes.json attributing every insertion, deletion and move to its numbered section and to table row and column, and a draft changelog row. The version history section is listed apart. Classes: a whole section added is New scope, a whole section removed is Removal, everything else is Revision for the author to confirm as new scope or rework (report the two apart). Rewrite the draft row's Change cell in the document's register from changes.md; never paste the draft. Use it before every version bump to write the changelog row from evidence, on request to compare two uploads, and to prove a scoped patch touched only its scope (any change outside the named sections is a defect). Engine: scripts/redline.mjs (docxodus, MIT, Word-grade compare, offline once installed into ~/.cache/vd-docxodus). The originals are never modified.
## Scripts bundled
scripts/merge_runs.py: merges adjacent runs with identical rPr, strips proofErr, preserves xml space; safe across bookmarks, resets at non-run elements. scripts/pack.py: repacks an unpacked directory into a valid, canonically ordered OOXML zip. scripts/apply_house_style.py: patches styles.xml and theme1.xml to the house typography standard (schema-correct child ordering, idempotent); restricted by step 4. scripts/sanitize_docx.py: rewrites core.xml/app.xml to a Word-native metadata fingerprint, strips machine-generated traces, keeps an MSIP sensitivity label, and repacks canonically; the AV-clearing step. scripts/doc_gate.py: the mechanical pre-delivery gate (step 8) for DOCX, PPTX, PDF, Markdown and HTML; exit 1 on any hard fail. scripts/deliver.sh: the one-command finalizer above. scripts/char_sweep.py: codepoint sweep on w:t text only; hard-fails en/em dash, non-breaking hyphen, and zero-width characters, warns on non-breaking space, ellipsis, and curly/straight quote mixing; run on the unpacked directory before pack.py. scripts/pdf_sanitize.py: rewrites a rendered PDF's Info dictionary and XMP stream to a Word-native fingerprint, clearing the LibreOffice Producer/Creator tell that soffice writes on every render plus any AI or tooling tell, and verifies both layers before exit; run only when the PDF itself is delivered (pikepdf). scripts/seq_diagram.py: renders a house-style sequence diagram from a JSON flow spec and machine-enforces the gap-free rule, contiguous numbering, and known actors before rendering, so a whole document's diagram set is uniform by construction; two-pass layout (rows and actor boxes sized from the wrapped text), accent title banner, tinted actor boxes, dotted lifelines, true-circle step badges on the message line near its origin with every label clear above its badge; author the flow as JSON (skeleton/flow_example.json), never hand-place arrows; --drawio out.drawio also writes the editable diagrams.net source from the same geometry and style (every actor, arrow, label and badge a separate cell). scripts/glass_seq.mjs: the same JSON flow spec and the same validation as seq_diagram.py, rendered in a glass look (--look white-glass for White Glass documents, blue-glass for navy document body pages, aurora for dark keynote decks): frosted actor cards with role glyphs, activation bars from request to response, badges on the message line near the origin, frosted label pills with API names in bold, glass notes, footer pills and a key; --svg also writes the vector; seq_diagram.py stays the plain renderer and the --drawio source. scripts/version_diff.py and scripts/redline.mjs: the version compare above. Never regenerate these; edit and re-upload only.
## Skeleton bundled
skeleton/TSD_Skeleton.docx: the sanctioned BRD/TSD start, already through the full pipeline (fixed reading order, version-control table, live TOC field, running header, page X of Y footer, seven-column field table, one complete API subsection block, FR/AS/OI/configurables stubs). A plain BRD/TSD working draft copies this and fills it; never author section structure from a blank docx-js build. Designed deliverables come from the glass-docs kit instead, with six-column field tables and no Source column. skeleton/make_skeleton.js regenerates it; skeleton/flow_example.json is a working seq_diagram.py spec.