The Complete Production SOP: How to Deploy and Run python-docx Track Changes & Comments Audit in Autonomous AI Agents
Production SOP to install and run python-docx-track-changes-audit in Codex, Claude Code, and Cursor. Audit revisions, extract OpenXML comments, and fix errors.
Technical Overview & Architectural Context
Autonomous coding agents frequently stumble when parsing and sanitizing Microsoft Word (.docx) files because standard libraries like basic `python-docx` completely abstract or strip away the underlying WordprocessingML revision markup. By default, standard paragraph iterators return clean text streams, inadvertently hiding pending insertions (<w:ins>), deletions (<w:del>), and editorial comments (<w:comment>). In corporate, legal, and compliance pipelines, an agent unaware of these low-level OpenXML tags risks publishing confidential annotations, accepting unauthorized redlines, or reporting false-positive document parity. The python-docx-track-changes-audit skill solves this fundamental gap by enforcing deterministic OpenXML parsing boundaries. Instead of relying on naive string matching or high-level document reading, the skill instructs the agent to mount zip-container inspection tools and traverse `word/document.xml` and `word/comments.xml` using XPath queries via `lxml`. This procedural SOP enforces zero-trust redaction, automated change-author attribution, and pre-publication compliance checks before any modified document leaves the workspace sandbox.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Create the local skill manifest directory and inject verified procedural rules into the agent context.
Agent runtimes such as Claude Code, Cursor, and Codex discover tools and procedural SOPs by scanning workspace-level or user-level directories. Mount this skill into your project's `.agents/skills` or `.claude/skills` directory so the runtime parser indexes the triggers and OpenXML traversal constraints during session startup.
mkdir -p .agents/skills/python-docx-track-changes-audit && curl -fsSL https://askills.dev/api/skills/python-docx-track-changes-audit/raw -o .agents/skills/python-docx-track-changes-audit/SKILL.md---
name: "python-docx-track-changes-audit"
description: "Inspect, review, and manipulate Word revisions, track changes, and reviewer comments."
metadata:
author: "python-openxml"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "audit track changes in docx"
- "extract comments from word python"
- "detect unaccepted revisions docx"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---
# python-docx Track Changes & Comments Audit
Parses OpenXML markup in .docx files using Python to detect insertions (<w:ins>), deletions (<w:del>), reviewer comments (<w:comment>), and author metadata for compliance auditing.
## When to Invoke
- audit track changes in docx
- extract comments from word python
- detect unaccepted revisions docx
## Execution SOP & Rules
1. Treat .docx files as zip archives; extract and parse `word/document.xml` using `lxml.etree`.
2. Query namespace `xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"` for `<w:ins>`, `<w:del>`, and `<w:commentReference>`.
3. Read `word/comments.xml` to map comment IDs to original author strings, dates, and comment body text.
4. Produce a structured JSON compliance report containing author, timestamp, change type, and text content before proceeding with any acceptance/rejection write operation.Keep the SKILL.md focused on deterministic OpenXML rules. Agents consume fewer prompt tokens when referencing namespace maps and specific XPath routes rather than generic explanations of DOCX file structures.
Ensure directory permissions permit read access to hidden agent folders. If using Cursor, verify that `.cursorrules` or `.agents` is not ignored in `.cursorignore`.
Environment Secrets & Dependency Validation
Install core OpenXML and XML parsing dependencies within the workspace sandbox without extraneous network access.
Because `python-docx` alone does not natively expose raw revision metadata objects, ensure `lxml` is compiled and available in the virtual environment. Verify that the agent runs under restricted network permissions (`net_access: false`) to ensure proprietary contracts or internal legal briefs do not leak during processing.
python -m venv .venv && source .venv/bin/activate && pip install lxml==5.2.2 python-docx==1.1.2 defusedxml==0.7.1import zipfile
from defusedxml.lxml import fromstring
from typing import Dict, List, Any
NS = {'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
def audit_docx_revisions(docx_path: str) -> Dict[str, Any]:
report = {'insertions': [], 'deletions': [], 'comments': []}
with zipfile.ZipFile(docx_path, 'r') as doc:
if 'word/document.xml' in doc.namelist():
root = fromstring(doc.read('word/document.xml'))
for ins in root.xpath('//w:ins', namespaces=NS):
text = ''.join(ins.xpath('.//w:t/text()', namespaces=NS))
report['insertions'].append({
'author': ins.get(f'{{{NS["w"]}}}author', 'Unknown'),
'date': ins.get(f'{{{NS["w"]}}}date', ''),
'text': text
})
for deletion in root.xpath('//w:del', namespaces=NS):
text = ''.join(deletion.xpath('.//w:delText/text()', namespaces=NS))
report['deletions'].append({
'author': deletion.get(f'{{{NS["w"]}}}author', 'Unknown'),
'date': deletion.get(f'{{{NS["w"]}}}date', ''),
'text': text
})
if 'word/comments.xml' in doc.namelist():
croot = fromstring(doc.read('word/comments.xml'))
for c in croot.xpath('//w:comment', namespaces=NS):
text = ''.join(c.xpath('.//w:t/text()', namespaces=NS))
report['comments'].append({
'id': c.get(f'{{{NS["w"]}}}id'),
'author': c.get(f'{{{NS["w"]}}}author', 'Unknown'),
'text': text
})
return reportUse defusedxml alongside lxml to mitigate billion-laughs and XML entity expansion vulnerabilities when parsing untrusted external Word documents.
Do not attempt to use `docx.Document(file).paragraphs` for audit tasks. Deleted text wrapped in `<w:del>` is invisible to python-docx paragraph blocks, causing silent compliance failures.
Intent Matching & Trigger Invocation
Activate the skill deterministically across Codex, Claude Code, or Cursor using precise semantic triggers.
Provide runtime instructions that align directly with the declared trigger list. The runtime matches intents like 'audit track changes in docx' or 'extract comments from word python' and immediately executes the low-level XML extraction workflow instead of writing fragile regex over binary streams.
claude 'audit track changes in docx legal_draft.docx and output revision-report.json'{
"status": "AUDIT_COMPLETE",
"unacceptedRevisionsCount": 2,
"commentCount": 1,
"revisions": [
{
"type": "w:ins",
"author": "ExternalCounsel",
"date": "2026-03-28T14:12:00Z",
"text": "Liability shall be capped at 50,000 USD."
},
{
"type": "w:del",
"author": "LeadNegotiator",
"date": "2026-03-29T09:20:00Z",
"text": "Unlimited indemnity applies to all breach conditions."
}
],
"comments": [
{
"id": "1",
"author": "SecurityAuditor",
"text": "Verify indemnification terms before signing."
}
]
}Prefix user prompts with exact trigger phrases ('audit track changes in docx') to bypass ambiguous LLM reasoning cycles and force zero-shot SOP invocation.
When working in Claude Code, ensure your target document is in the current working directory; sandboxed runtimes cannot traverse parent directories outside workspace root without explicit flags.
Verification, Linting & Output Quality Gate
Execute automated validation checks to confirm document integrity and verify zero orphaned XML tags.
After inspecting or programmatically accepting/rejecting changes, the agent must run validation scripts to test if the resulting `.docx` archive opens without schema corruption. OpenXML schemas require precise tag balancing when deleting `<w:ins>` or `<w:del>` wrappers.
python -m unittest tests/test_docx_audit.py && ruff check scripts/audit_revisions.pyimport unittest
import zipfile
from scripts.audit_revisions import audit_docx_revisions
class TestDocxAudit(unittest.TestCase):
def test_audit_structure(self):
result = audit_docx_revisions('tests/fixtures/sample_redline.docx')
self.assertIn('insertions', result)
self.assertIn('deletions', result)
self.assertIn('comments', result)
self.assertIsInstance(result['insertions'], list)
def test_zip_integrity(self):
with zipfile.ZipFile('tests/fixtures/sample_redline.docx', 'r') as doc:
self.assertIsNone(doc.testzip(), 'DOCX archive contains corrupted zip headers')
if __name__ == '__main__':
unittest.main()Always verify `doc.testzip()` on updated documents. A single unclosed XML tag causes Microsoft Word to display the critical error 'Word found unreadable content in document.docx'.
Remember that `<w:p>` nodes containing deleted runs still retain run properties `<w:rPr>`. Stripping wrappers naively without re-nesting text nodes breaks OpenXML hierarchy.
Real-World Scenario: Pre-Publication Compliance Audit of Master Services Agreement (MSA)
“We are preparing to sign MSA_Final_v3.docx. Run 'audit track changes in docx' on this file. List every unaccepted insertion, deletion, and comment with author name and timestamp. If any unaccepted changes exist, fail the build and do not proceed with conversion to PDF.”
Runtime Troubleshooting & Failure Modes
Root Cause: The agent attempted to read comments directly without checking if `word/comments.xml` exists. Word documents with zero comments do not allocate a comments part inside the OpenXML package.
if 'word/comments.xml' in doc.namelist():
croot = fromstring(doc.read('word/comments.xml'))
else:
comments = []Root Cause: A script attempted to strip `<w:del>` or `<w:ins>` tags using string replace or naive regular expressions, corrupting interleaved OpenXML run hierarchies.
# Use lxml etree unwrapping instead of regex strings:
for node in root.xpath('//w:ins', namespaces=NS):
parent = node.getparent()
for child in list(node):
node.addprevious(child)
parent.remove(node)Frequently Asked Questions (python-docx Track Changes & Comments Audit SOP)
Q:Can I use python-docx Track Changes & Comments Audit across Codex, Claude Code, and Cursor simultaneously?
Yes. This skill adheres to the universal SKILL.md specification. All modern runtimes (Codex, Claude Code, Cursor, and Windsurf) read the top-level YAML triggers and markdown execution rules uniformly.
Q:Why can't I just use python-docx Document.paragraphs to audit track changes?
Standard python-docx only parses top-level `<w:t>` elements within active runs. Text inside `<w:delText>` and meta-attributes inside `<w:ins>` and `<w:del>` are ignored by high-level abstractions, leaving unaccepted redlines completely undetected.
Q:Does this skill require escalated root or container permissions?
No. The skill has an audited security score of 98/100, requires zero network access (net_access: false), and operates strictly on local workspace files using standard Python XML inspection libraries.
Ready to equip your autonomous agent with python-docx Track Changes & Comments Audit?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.