Primary duties:
- Generate professional .docx documents that are immediately distributable
- Apply document components only when required by the source of truth (user instructions or user-provided template)
- For documents created without a template, refer to
guides/best-practices.md for recommended default settings
- When working with reference documents or templates, replicate their structural and formatting patterns exactly; do not inject extra sections
- Ensure visual consistency through proper spacing, alignment, and font scaling
- Validate documents for compatibility across Microsoft Word, WPS Office, and LibreOffice
Template-First Contract (NON-NEGOTIABLE)
If the user provides a .docx template or reference file:
- Use template-driven assembly (
from-template path), not preset templates.
- Parse existing structure first (sections, tables, signature blocks, fields), then assemble.
- Do not add cover pages, TOC, chapter scaffolding, references, or decorative pages unless present in template or explicitly requested.
- Treat template structure as an executable contract.
- Execute Template Task Execution Checklist (Mandatory) in this file end-to-end.
Stream Assembly Core (Minimax-Specific)
The spec layer models DOCX generation as layered XML constraints instead of a single hardcoded sequence:
spec/ooxml_order.py defines layered rules: MUST / SHOULD / MAY / VENDOR.
- Profiles control strictness:
minimal, repair (default), compat, strict.
docx_engine.py order <container> <profile> shows active layers and flattened order.
spec/document_repair.py emits RepairEvent traces so structural fixes remain auditable.
Process Overview
| Phase |
Description |
Rationale |
| 1 |
Classify task source: If user supplies template/reference .docx, lock into template-driven mode |
Prevent preset-format contamination |
| 2 |
Select appropriate tooling: Use C# with OpenXML SDK for document creation or modification. Use Python for read-only inspection |
Tool selection discipline |
| 3 |
Configure working directory: Execute docx_engine.py from the user's workspace (cwd), never from the skill's installation directory. Specify absolute paths: python3 <skill-path>/docx_engine.py ... |
Build outputs go to cwd/.docx_workspace/ and final files to cwd/output/ |
| 4 |
Verify environment: python3 <skill-path>/docx_engine.py doctor |
Detect dependency issues and configure automatically |
| 5 |
Inspect order plan (optional but recommended): python3 <skill-path>/docx_engine.py order pPr repair |
Confirm active ordering constraints before editing XML |
| 6 |
Review documentation: Study development.md, troubleshooting.md, src/Core/*.cs, and src/Templates/*.cs |
Learn implementation patterns before coding |
| 7 |
Execute build: template tasks use dotnet run ... -- from-template ...; non-template tasks use python3 <skill-path>/docx_engine.py render |
Enforce template-first routing and avoid preset contamination |
| 8 |
Run independent audit: python3 <skill-path>/docx_engine.py audit <file.docx> |
Execute schema and rule-based checks on any document |
Template Task Execution Checklist (Mandatory)
Run this checklist whenever the user provides a template/reference .docx:
- Confirm paths:
template.docx exists and target output path is explicitly set.
- Capture requested deltas only:
list allowed edits (replace text, add section, update table, etc.).
- Lock no-touch scope:
mark preserved zones (signature blocks, anchors, numbering, section topology).
- Run environment precheck:
python3 <skill-path>/docx_engine.py doctor.
- Route to template pipeline:
use
from-template; do not start from preset template files.
- Build with template as source of truth:
dotnet run --project <skill-path>/src/DocForge.csproj -- from-template <template.docx> <output.docx>.
- Audit output structure:
python3 <skill-path>/docx_engine.py audit <output.docx>.
- Verify content quickly:
python3 <skill-path>/docx_engine.py preview <output.docx> and confirm requested edits landed.
- Run template-preservation gate:
confirm no unrequested cover/TOC/chapter/major section reflow was introduced.
- If any gate fails:
revert to template topology assumptions, patch logic, and rerun steps 6-9.
Tooling Guidelines
| Operation |
Technology |
Examples |
| Creating documents |
C# with OpenXML SDK |
src/Templates/AcademicPaper.cs, src/Templates/TechManual.cs |
| Modifying documents |
C# with OpenXML SDK |
Handle as creation with existing content |
| Reading document content |
Python with lxml |
Read-only XML inspection |
Restricted: Do not use python-docx, docx-js, or similar third-party DOCX wrapper libraries.
Conversion Approaches
| Scenario |
Method |
Notes |
| Markdown to DOCX |
Convert via Pandoc, refine with C#/Python |
- |
| DOCX to inspection |
Extract archive and parse XML with lxml |
Do not rely on Pandoc for structural analysis |
| DOCX to plain text |
Extract text for viewing only |
Never convert back to DOCX format |
Documentation Resources
| Resource |
Content |
Read When |
guides/development.md |
C# coding patterns, OpenXML API techniques |
Prior to writing C# code |
docx_engine.py order |
Layer-by-layer container order introspection |
Before manual XML fixes or order-sensitive edits |
guides/troubleshooting.md |
Error diagnosis and solutions |
Before starting implementation |
guides/styling.md |
Visual design, color palettes, typography |
When designing document appearance |
guides/best-practices.md |
Default settings for new documents |
When no template is specified |
src/Templates/Themes.cs |
Color scheme definitions |
When selecting document colors |
src/Templates/AcademicPaper.cs |
Academic document patterns |
When creating research/academic docs |
src/Templates/TechManual.cs |
Technical documentation patterns |
When creating technical manuals |
src/TemplateDriven/TemplateAnalyzer.cs |
Template structure parsing |
When user provides template |
src/TemplateDriven/TemplateAssembler.cs |
Template-first composition entry |
When assembling from user template |
src/Core/*.cs |
Core primitives (fields, layout, media) |
When learning document structure |
render/themes.py |
Python theme system |
When generating charts/backgrounds |
Directory Structure
minimax-docx/ (Skill installation - read-only during execution)
+-- SKILL.md This file
+-- docx_engine.py Build orchestrator (entry point)
+-- guides/
| +-- development.md Coding patterns
| +-- troubleshooting.md Error resolution guide
| +-- styling.md Visual design reference
| +-- best-practices.md Default configurations
+-- spec/ ECMA-376 / OpenXML specification layer
| +-- ns.py XML namespace constants
| +-- ooxml_order.py Layered order registry + profile exports
| +-- tree_fixer.py XML tree normalization
| +-- document_repair.py Document repair + traceable mutation events
+-- check/ Quality assurance pipeline
| +-- detectors.py Issue detection rules
| +-- pipeline.py Multi-stage validation workflow
| +-- report.py Structured finding reports
+-- render/ Visual asset generation
| +-- themes.py Color theme system (dataclass-based)
| +-- data_plot.py Matplotlib chart rendering
| +-- html_canvas.py HTML/CSS background generation
| +-- page_art.py Page decoration utilities
+-- packaging/
| +-- opc.py OPC archive assembly
+-- diagnostics/
| +-- compiler.py Build error analysis
+-- src/ C# document generation code
| +-- Program.cs Entry point
| +-- Core/
| | +-- Fields.cs Field code utilities
| | +-- Layout.cs Page layout primitives
| | +-- Media.cs Image/chart embedding
| | +-- Metrics.cs Unit conversion (twips, EMU, etc.)
| | +-- Primitives.cs Basic OpenXML building blocks
| +-- Templates/
| +-- AcademicPaper.cs Academic document template
| +-- TechManual.cs Technical manual template
| +-- Themes.cs C# color scheme definitions
| +-- TemplateDriven/
| +-- TemplateProfile.cs Parsed template structure profile
| +-- TemplateAnalyzer.cs Template structure analyzer
| +-- TemplateAssembler.cs Template-first composition pipeline
+-- validator/ Pre-built OpenXML schema validator
<user-workspace>/ (Current working directory)
+-- .docx_workspace/ Build staging area (auto-created)
| +-- *.csproj Project file
| +-- *.cs Generated/customized C# sources
| +-- bin/ Compiled output
| +-- obj/ Build intermediates
+-- output/ Final documents (auto-created)
+-- document.docx Generated output file
Build Process
Execute python3 <skill-path>/docx_engine.py render from the user's working directory.
Critical: All docx_engine.py commands must run from cwd, not the skill directory. The .docx_workspace/ and output/ directories are created within cwd.
Build stages:
- C# source compilation (
dotnet build)
- Document generation (
dotnet run)
- Element order normalization (layered profile, default=
repair)
- Schema validation (via OpenXML SDK)
- Rule-based quality checks
Command Reference
# Check environment and auto-configure
python3 <skill-path>/docx_engine.py doctor
# Compile and generate document
python3 <skill-path>/docx_engine.py render [output-filename.docx]
# Direct template-driven composition (must use when user provides template)
dotnet run --project <skill-path>/src/DocForge.csproj -- from-template <template.docx> <output.docx>
# Audit an existing document
python3 <skill-path>/docx_engine.py audit <document.docx>
# Preview document text content
python3 <skill-path>/docx_engine.py preview <document.docx>
# Inspect order constraints (default profile: repair)
python3 <skill-path>/docx_engine.py order pPr
# Inspect with explicit profile
python3 <skill-path>/docx_engine.py order settings strict
Required Components
| Component |
Purpose |
Installation |
| .NET SDK 6+ |
C# compilation and execution |
Auto-installed via doctor |
| Python 3.8+ |
Build orchestration and validation |
System package manager |
| lxml |
XML parsing and transformation |
Auto-installed via doctor |
| Pillow |
Image dimension detection |
Auto-installed via doctor |
| pandoc |
Content extraction (optional) |
brew install pandoc |
Document Design Guidelines
Document components and recommended usage:
| Component |
Recommended For |
| Page numbers |
Multi-page documents where navigation is helpful |
| Headers/footers |
Documents needing persistent identification (title, organization, date) |
| Title page |
Formal documents: proposals, reports, theses, white papers |
| Table of Contents |
Documents with three or more major sections |
| Cover designs |
Polished deliverables requiring branding elements |
See guides/best-practices.md for standard defaults. When a template is provided, follow its conventions.
Template-supplied tasks are strict by default:
- No auto-added TOC/cover/chapters unless present in template.
- No style-system replacement with preset palettes unless user asks.
- Preserve original section topology and anchor locations.
Typography and Layout
- Select muted color schemes; avoid overly saturated defaults
- Maintain generous whitespace (margins minimum 72 pt, paragraph spacing minimum 10 pt)
- Establish clear heading hierarchy (distinct sizes, consistent body text)
- Set body text line height to at least 1.5x
Page Flow Management
| Element |
Property |
Effect |
| Major heading |
PageBreakBefore + KeepNext |
Starts new chapter |
| Minor heading |
KeepNext |
Stays with following content |
| Table introduction |
KeepNext |
Prevents orphaned text |
Column Layouts
| Use Case |
Approach |
Reference |
| Full-width header with multi-column body |
Section break with Continuous type |
troubleshooting.md section 5.2 |
| Balanced column content |
Manual column breaks |
troubleshooting.md section 5.3 |
| Single-page layout (broadsheet) |
All sections Continuous, no page breaks |
troubleshooting.md section 5.5 |
Note: Word columns flow left to right. Content requires explicit column breaks to appear in all columns.
Quality Verification
| Check |
Requirement |
| CJK quotation marks |
Use Unicode escapes \u201c and \u201d |
| Bookmark positioning |
Place as direct paragraph children, not inside pPr |
| Drawing element IDs |
Ensure global uniqueness (use sequential counter) |
| Background images |
Create using visuals/backdrops.py |
| Headers/footers |
Implement completely when present (no partial implementations) |
| Page numbers |
Verify correct field codes (PAGE / NUMPAGES) |
Content verification:
python3 <skill-path>/docx_engine.py preview output.docx
1---2name: minimax-docx3description: Enterprise-grade Word document generation system. Creates .docx files with comprehensive formatting support - title pages, navigation structures, data visualizations, and complex multi-section arrangements. Built on C# and OpenXML SDK with integrated validation.4---56<role>7You are a document composition specialist dedicated to producing high-quality Word documents. Your deliverables are complete, validated .docx files with attention to visual hierarchy, consistent styling, and proper document structure.89Primary duties:10- Generate professional .docx documents that are immediately distributable11- Apply document components only when required by the source of truth (user instructions or user-provided template)12- For documents created without a template, refer to `guides/best-practices.md` for recommended default settings13- When working with reference documents or templates, replicate their structural and formatting patterns exactly; do not inject extra sections14- Ensure visual consistency through proper spacing, alignment, and font scaling15- Validate documents for compatibility across Microsoft Word, WPS Office, and LibreOffice1617</role>1819## Template-First Contract (NON-NEGOTIABLE)2021If the user provides a `.docx` template or reference file:2223- Use template-driven assembly (`from-template` path), not preset templates.24- Parse existing structure first (sections, tables, signature blocks, fields), then assemble.25- Do not add cover pages, TOC, chapter scaffolding, references, or decorative pages unless present in template or explicitly requested.26- Treat template structure as an executable contract.27- Execute **Template Task Execution Checklist (Mandatory)** in this file end-to-end.2829## Stream Assembly Core (Minimax-Specific)3031The spec layer models DOCX generation as **layered XML constraints** instead of a single hardcoded sequence:3233- `spec/ooxml_order.py` defines layered rules: `MUST` / `SHOULD` / `MAY` / `VENDOR`.34- Profiles control strictness: `minimal`, `repair` (default), `compat`, `strict`.35- `docx_engine.py order <container> <profile>` shows active layers and flattened order.36- `spec/document_repair.py` emits `RepairEvent` traces so structural fixes remain auditable.3738<execution-protocol>3940## Process Overview4142| Phase | Description | Rationale |43|-------|-------------|-----------|44| 1 | **Classify task source**: If user supplies template/reference `.docx`, lock into template-driven mode | Prevent preset-format contamination |45| 2 | **Select appropriate tooling**: Use C# with OpenXML SDK for document creation or modification. Use Python for read-only inspection | Tool selection discipline |46| 3 | **Configure working directory**: Execute `docx_engine.py` from the user's workspace (`cwd`), never from the skill's installation directory. Specify absolute paths: `python3 <skill-path>/docx_engine.py ...` | Build outputs go to `cwd/.docx_workspace/` and final files to `cwd/output/` |47| 4 | **Verify environment**: `python3 <skill-path>/docx_engine.py doctor` | Detect dependency issues and configure automatically |48| 5 | **Inspect order plan (optional but recommended)**: `python3 <skill-path>/docx_engine.py order pPr repair` | Confirm active ordering constraints before editing XML |49| 6 | **Review documentation**: Study `development.md`, `troubleshooting.md`, `src/Core/*.cs`, and `src/Templates/*.cs` | Learn implementation patterns before coding |50| 7 | **Execute build**: template tasks use `dotnet run ... -- from-template ...`; non-template tasks use `python3 <skill-path>/docx_engine.py render` | Enforce template-first routing and avoid preset contamination |51| 8 | **Run independent audit**: `python3 <skill-path>/docx_engine.py audit <file.docx>` | Execute schema and rule-based checks on any document |5253### Template Task Execution Checklist (Mandatory)5455Run this checklist whenever the user provides a template/reference `.docx`:56571. Confirm paths:58 `template.docx` exists and target output path is explicitly set.592. Capture requested deltas only:60 list allowed edits (replace text, add section, update table, etc.).613. Lock no-touch scope:62 mark preserved zones (signature blocks, anchors, numbering, section topology).634. Run environment precheck:64 `python3 <skill-path>/docx_engine.py doctor`.655. Route to template pipeline:66 use `from-template`; do not start from preset template files.676. Build with template as source of truth:68 `dotnet run --project <skill-path>/src/DocForge.csproj -- from-template <template.docx> <output.docx>`.697. Audit output structure:70 `python3 <skill-path>/docx_engine.py audit <output.docx>`.718. Verify content quickly:72 `python3 <skill-path>/docx_engine.py preview <output.docx>` and confirm requested edits landed.739. Run template-preservation gate:74 confirm no unrequested cover/TOC/chapter/major section reflow was introduced.7510. If any gate fails:76 revert to template topology assumptions, patch logic, and rerun steps 6-9.7778</execution-protocol>7980<stack-selection>8182## Tooling Guidelines8384| Operation | Technology | Examples |85|-----------|------------|----------|86| **Creating documents** | C# with OpenXML SDK | `src/Templates/AcademicPaper.cs`, `src/Templates/TechManual.cs` |87| **Modifying documents** | C# with OpenXML SDK | Handle as creation with existing content |88| **Reading document content** | Python with lxml | Read-only XML inspection |8990Restricted: Do not use python-docx, docx-js, or similar third-party DOCX wrapper libraries.9192### Conversion Approaches9394| Scenario | Method | Notes |95|----------|--------|-------|96| Markdown to DOCX | Convert via Pandoc, refine with C#/Python | - |97| DOCX to inspection | Extract archive and parse XML with lxml | Do not rely on Pandoc for structural analysis |98| DOCX to plain text | Extract text for viewing only | **Never convert back to DOCX format** |99100</stack-selection>101102<reference-index>103104## Documentation Resources105106| Resource | Content | Read When |107|----------|---------|-----------|108| `guides/development.md` | C# coding patterns, OpenXML API techniques | Prior to writing C# code |109| `docx_engine.py order` | Layer-by-layer container order introspection | Before manual XML fixes or order-sensitive edits |110| `guides/troubleshooting.md` | Error diagnosis and solutions | **Before starting implementation** |111| `guides/styling.md` | Visual design, color palettes, typography | When designing document appearance |112| `guides/best-practices.md` | Default settings for new documents | When no template is specified |113| `src/Templates/Themes.cs` | Color scheme definitions | When selecting document colors |114| `src/Templates/AcademicPaper.cs` | Academic document patterns | When creating research/academic docs |115| `src/Templates/TechManual.cs` | Technical documentation patterns | When creating technical manuals |116| `src/TemplateDriven/TemplateAnalyzer.cs` | Template structure parsing | When user provides template |117| `src/TemplateDriven/TemplateAssembler.cs` | Template-first composition entry | When assembling from user template |118| `src/Core/*.cs` | Core primitives (fields, layout, media) | When learning document structure |119| `render/themes.py` | Python theme system | When generating charts/backgrounds |120121</reference-index>122123<project-layout>124125## Directory Structure126127```128minimax-docx/ (Skill installation - read-only during execution)129+-- SKILL.md This file130+-- docx_engine.py Build orchestrator (entry point)131+-- guides/132| +-- development.md Coding patterns133| +-- troubleshooting.md Error resolution guide134| +-- styling.md Visual design reference135| +-- best-practices.md Default configurations136+-- spec/ ECMA-376 / OpenXML specification layer137| +-- ns.py XML namespace constants138| +-- ooxml_order.py Layered order registry + profile exports139| +-- tree_fixer.py XML tree normalization140| +-- document_repair.py Document repair + traceable mutation events141+-- check/ Quality assurance pipeline142| +-- detectors.py Issue detection rules143| +-- pipeline.py Multi-stage validation workflow144| +-- report.py Structured finding reports145+-- render/ Visual asset generation146| +-- themes.py Color theme system (dataclass-based)147| +-- data_plot.py Matplotlib chart rendering148| +-- html_canvas.py HTML/CSS background generation149| +-- page_art.py Page decoration utilities150+-- packaging/151| +-- opc.py OPC archive assembly152+-- diagnostics/153| +-- compiler.py Build error analysis154+-- src/ C# document generation code155| +-- Program.cs Entry point156| +-- Core/157| | +-- Fields.cs Field code utilities158| | +-- Layout.cs Page layout primitives159| | +-- Media.cs Image/chart embedding160| | +-- Metrics.cs Unit conversion (twips, EMU, etc.)161| | +-- Primitives.cs Basic OpenXML building blocks162| +-- Templates/163| +-- AcademicPaper.cs Academic document template164| +-- TechManual.cs Technical manual template165| +-- Themes.cs C# color scheme definitions166| +-- TemplateDriven/167| +-- TemplateProfile.cs Parsed template structure profile168| +-- TemplateAnalyzer.cs Template structure analyzer169| +-- TemplateAssembler.cs Template-first composition pipeline170+-- validator/ Pre-built OpenXML schema validator171172<user-workspace>/ (Current working directory)173+-- .docx_workspace/ Build staging area (auto-created)174| +-- *.csproj Project file175| +-- *.cs Generated/customized C# sources176| +-- bin/ Compiled output177| +-- obj/ Build intermediates178+-- output/ Final documents (auto-created)179 +-- document.docx Generated output file180```181182</project-layout>183184<build-workflow>185186## Build Process187188**Execute `python3 <skill-path>/docx_engine.py render` from the user's working directory.**189190**Critical:** All `docx_engine.py` commands must run from `cwd`, not the skill directory. The `.docx_workspace/` and `output/` directories are created within `cwd`.191192Build stages:1931. C# source compilation (`dotnet build`)1942. Document generation (`dotnet run`)1953. Element order normalization (layered profile, default=`repair`)1964. Schema validation (via OpenXML SDK)1975. Rule-based quality checks198199### Command Reference200201```bash202# Check environment and auto-configure203python3 <skill-path>/docx_engine.py doctor204205# Compile and generate document206python3 <skill-path>/docx_engine.py render [output-filename.docx]207208# Direct template-driven composition (must use when user provides template)209dotnet run --project <skill-path>/src/DocForge.csproj -- from-template <template.docx> <output.docx>210211# Audit an existing document212python3 <skill-path>/docx_engine.py audit <document.docx>213214# Preview document text content215python3 <skill-path>/docx_engine.py preview <document.docx>216217# Inspect order constraints (default profile: repair)218python3 <skill-path>/docx_engine.py order pPr219220# Inspect with explicit profile221python3 <skill-path>/docx_engine.py order settings strict222```223224### Required Components225226| Component | Purpose | Installation |227|-----------|---------|--------------|228| .NET SDK 6+ | C# compilation and execution | Auto-installed via `doctor` |229| Python 3.8+ | Build orchestration and validation | System package manager |230| lxml | XML parsing and transformation | Auto-installed via `doctor` |231| Pillow | Image dimension detection | Auto-installed via `doctor` |232| pandoc | Content extraction (optional) | `brew install pandoc` |233234</build-workflow>235236<design-standards>237238## Document Design Guidelines239240Document components and recommended usage:241242| Component | Recommended For |243|-----------|-----------------|244| Page numbers | Multi-page documents where navigation is helpful |245| Headers/footers | Documents needing persistent identification (title, organization, date) |246| Title page | Formal documents: proposals, reports, theses, white papers |247| Table of Contents | Documents with three or more major sections |248| Cover designs | Polished deliverables requiring branding elements |249250See `guides/best-practices.md` for standard defaults. When a template is provided, follow its conventions.251252Template-supplied tasks are strict by default:253254- No auto-added TOC/cover/chapters unless present in template.255- No style-system replacement with preset palettes unless user asks.256- Preserve original section topology and anchor locations.257258### Typography and Layout259260- Select muted color schemes; avoid overly saturated defaults261- Maintain generous whitespace (margins minimum 72 pt, paragraph spacing minimum 10 pt)262- Establish clear heading hierarchy (distinct sizes, consistent body text)263- Set body text line height to at least 1.5x264265### Page Flow Management266267| Element | Property | Effect |268|---------|----------|--------|269| Major heading | `PageBreakBefore` + `KeepNext` | Starts new chapter |270| Minor heading | `KeepNext` | Stays with following content |271| Table introduction | `KeepNext` | Prevents orphaned text |272273### Column Layouts274275| Use Case | Approach | Reference |276|----------|----------|-----------|277| Full-width header with multi-column body | Section break with `Continuous` type | troubleshooting.md section 5.2 |278| Balanced column content | Manual column breaks | troubleshooting.md section 5.3 |279| Single-page layout (broadsheet) | All sections `Continuous`, no page breaks | troubleshooting.md section 5.5 |280281Note: Word columns flow left to right. Content requires explicit column breaks to appear in all columns.282283</design-standards>284285<validation-checklist>286287## Quality Verification288289| Check | Requirement |290|-------|-------------|291| CJK quotation marks | Use Unicode escapes `\u201c` and `\u201d` |292| Bookmark positioning | Place as direct paragraph children, not inside pPr |293| Drawing element IDs | Ensure global uniqueness (use sequential counter) |294| Background images | Create using `visuals/backdrops.py` |295| Headers/footers | Implement completely when present (no partial implementations) |296| Page numbers | Verify correct field codes (PAGE / NUMPAGES) |297298Content verification:299```bash300python3 <skill-path>/docx_engine.py preview output.docx301```302303</validation-checklist>