Paper write docx

From FOURTEEN1416/academic-agent-toolkit · View interactive version

Paper write docx is an AI agent skill from the GitHub repository FOURTEEN1416/academic-agent-toolkit. Draft an English academic paper as Markdown for Word (docx) export. Use when params.output_format == 'docx',produces main.md only;中文论文改用 paper-write-zh-docx。

How to use this skill

Skill file

Paper Write — Markdown for Word (docx mode)

Draft an English academic paper as Markdown: $ARGUMENTS

docx-mode counterpart of paper-write. Keeps all writing principles (claims-evidence, story arc, citation discipline, venue checklists) but produces paper/main.md only. The downstream docx-export step runs third_party/docx-cn-engine/md_to_docx.js to convert it.

⛔ NEVER produce paper/main.tex / paper/sections/*.tex / .cls / .sty / .bib. NEVER run XeLaTeX.

Constants

Inputs

  1. PAPER_PLAN.md — outline with claims-evidence matrix, figure plan
  1. NARRATIVE_REPORT.md — research narrative
  1. experiment_results.md / RESULTS.md / figures/all_results.json
  1. figures/ — .png / .pdf files
  1. Verified reference pool

Load shared rules


cat _utils/writing_rules.md 2>/dev/null || cat skills/shared-scripts/writing_rules.md

The LaTeX-specific bits in shared rules don't apply here; the writing principles do.

Orchestra References

⛔⛔⛔ Output Contract (highest priority)

Single artifact: paper/main.md (UTF-8, complete paper, ≥ 5KB)

Never produce: paper/main.tex, paper/sections/*.tex, paper/references.bib, .cls, .sty, .aux, any LaTeX command (\begin, \input, \cite, \section, \includegraphics, ...).

Mandatory verification before ending:


echo "=== Output verification (must be all ✅) ==="

PASS=true



[ -f paper/main.md ] && SZ=$(wc -c < paper/main.md) || SZ=0

[ "$SZ" -ge 5120 ] && echo "✅ paper/main.md ($SZ bytes)" || { echo "❌ paper/main.md missing or too small ($SZ bytes)"; PASS=false; }



words=$(wc -w < paper/main.md 2>/dev/null || echo 0)

est_pages=$((words / 600))   # ~600 words/page for English

target_pages="${MAX_PAGES:-9}"

echo "words: $words, est pages: ~$est_pages, target: ≥ $target_pages"

[ "$est_pages" -lt "$((target_pages * 80 / 100))" ] && echo "⚠ below 80% target — expand thinnest sections"



# No LaTeX residue

if grep -qE '\\(begin|end|input|cite|ref|label|includegraphics|section|chapter|subsection)\{' paper/main.md; then

    echo "❌ LaTeX command residue in paper/main.md:"

    grep -nE '\\(begin|end|input|cite|ref|label|includegraphics|section|chapter|subsection)\{' paper/main.md | head -5

    PASS=false

fi



# No .tex

ls paper/*.tex paper/sections/*.tex 2>/dev/null | head -1 | grep -q . && { echo "❌ .tex files detected"; ls paper/*.tex paper/sections/*.tex 2>/dev/null; PASS=false; } || true



if [ "$PASS" != true ]; then echo "⛔ verification FAILED — fix and re-run before ending"; exit 1; fi

docx-cn-engine markdown conventions

The downstream docx-export step uses third_party/docx-cn-engine/md_to_docx.js. Follow these conventions:

1. Headings

2. Abstract (engine auto-centers)


## Abstract



[150-250 word abstract]



**Keywords**: kw1; kw2; kw3

3. Math

right-aligns it as (n). Multi-line form:

$$
\min_{\mathbf{x}} \sum_{i=1}^{n} c_i x_i \tag{2}
$$

⛔ Never put the number on the closing-delimiter line ($$ (1)). An earlier

revision of this file said "append (1) after $$ ... $$", which is exactly the

instruction that caused a production incident. Once the number is not a plain

integer — (8'), full-width (5), or trailing words after it — the engine fails

to recognise that line as the closing delimiter and swallows everything after it:

body text, later formulas and ![](figures/xxx.png) image refs all get parsed as

math → formulas render one character per line, images fail to load (measured: 17

of 17 display formulas in one paper). The engine now treats any line starting with

$$ as closing, but still write \tag{n} — it is the form KaTeX / MathJax /

Pandoc all accept. (modex-3 同源吸收 2026-09-22,本段精确取代旧"append (1) after $$"口径。)

⛔ Never use \begin{equation}, \begin{align} — the engine does not process these LaTeX environments.

⛔ Do not use \[...\] for display math — the engine recognises it but renders it inline (not centered, no number), so it will not look like a display equation.

4. Figures


![Figure 1: Architecture overview.](figures/fig_arch.png)

5. Tables (3-line academic style)


**Table 1: Main results.**



| Method | Accuracy | F1 | Time(s) |

|--------|----------|----|---------|

| Baseline | 0.823 | 0.811 | 124 |

| Ours | **0.917** | **0.905** | 132 |

⛔ Never use \begin{table} or \input{figures/TABLE_x.tex}. If figures/TABLE_*.md exists, paste its content.

6. References


## References



[1] LeSage J P, Pace R K. Introduction to Spatial Econometrics. CRC Press, 2009.

[2] Vaswani A, Shazeer N, Parmar N, et al. Attention is all you need. NeurIPS, 2017.

In-text citations use [1], [1, 2], [1-3] — not \cite{key}.

The engine detects ## References and renders the following [N] ... lines with hanging indent.

Workflow

Step 0: Upstream check + resume


echo "=== Upstream check ==="

for f in PAPER_PLAN.md RESULTS.md NARRATIVE_REPORT.md experiment_results.md; do

    [ -f "$f" ] && echo "✅ $f ($(wc -c < $f) chars)" || echo "  $f not found"

done

[ -f figures/all_results.json ] && echo "✅ figures/all_results.json" || echo "⚠ no all_results.json"

PNG_COUNT=$(ls figures/*.png 2>/dev/null | wc -l)

PDF_COUNT=$(ls figures/*.pdf 2>/dev/null | wc -l)

echo "figures: PNG=$PNG_COUNT, PDF=$PDF_COUNT"



if [ -f paper/main.md ]; then

    cp paper/main.md "paper/main-backup-$(date +%s).md.bak"

    echo "Resume mode — backed up existing main.md"

fi

⛔ Numbers come from data, not memory.

⛔ NEVER cat figures/*_results.json. These result files often contain full-precision time-series arrays (tens of MB / hundreds of thousands of lines); reading them whole blows up the context — local models fail outright, and GPT-via-transit chokes on protocol translation of the oversized payload and stalls on repeated api_retry. The paper text only uses scalar values; the giant arrays are for figures, not prose. Before writing any results section, run the summarize script below for a KB-level overview (scalars shown verbatim — zero precision loss — only big arrays compressed to "length + range + first 3 samples"):


PYTHON=""; for _c in "$MH_PYTHON" python python3; do [ -z "$_c" ] && continue; if $_c -c "import sys" >/dev/null 2>&1; then PYTHON="$_c"; break; fi; done; [ -z "$PYTHON" ] && PYTHON=python

[ -f RESULTS.md ] && cat RESULTS.md

$PYTHON - <<'PY'

import json, os, glob

def summarize(v, depth=0):

    if isinstance(v, list):

        n=len(v); nums=[x for x in v if isinstance(x,(int,float))]

        if nums: return f'list[{n}] range=[{min(nums):.4g},{max(nums):.4g}] sample={v[:3]}'

        if v and isinstance(v[0], (list,dict)): return f'list[{n}] of {type(v[0]).__name__}, first_shape={len(v[0]) if hasattr(v[0],"__len__") else "?"}'

        return f'list[{n}] sample={str(v[:3])[:80]}'

    if isinstance(v, dict) and depth<2:

        return 'dict{'+', '.join(f'{k}: {summarize(x,depth+1)}' for k,x in list(v.items())[:6])+'}'

    return f'{type(v).__name__}={str(v)[:60]}'

for f in sorted(glob.glob('figures/*_results.json')):

    sz=os.path.getsize(f); d=json.load(open(f,encoding='utf-8'))

    print(f'\n=== {os.path.basename(f)} ({sz//1024}KB) ===')

    if isinstance(d, dict):

        for k,v in d.items(): print(f'  {k}: {summarize(v)}')

    else: print(f'  {summarize(d)}')

PY

Every scalar you need is in RESULTS.md or the range/sample above. If one scalar isn't fully shown, fetch just that value with $PYTHON -c "import json;d=json.load(open('figures/all_results.json'));print(d['key'])" — still never read the whole file.

⛔ Claims-Evidence discipline: re-read PAPER_PLAN.md claims-evidence matrix before each section. Every claim must be supported by data. If evidence is missing for a planned claim, write an honest "preliminary results suggest X, formal validation left to future work" instead of fabricating.

Step 1: Figure inventory


ls -la figures/*.png figures/*.pdf 2>/dev/null

ls -la figures/TABLE_*.md 2>/dev/null

cat figures/latex_includes.tex 2>/dev/null  # reference only — DO NOT use the LaTeX commands

Build a mapping: figure ID → file → target section. Only embed figures whose files exist.

Step 1.5: Pre-fetch verified reference pool

⛔ Build a verified pool before writing any [N] citations.


PYTHON=""; for _c in "$MH_PYTHON" python python3; do [ -z "$_c" ] && continue; if $_c -c "import sys" >/dev/null 2>&1; then PYTHON="$_c"; break; fi; done; [ -z "$PYTHON" ] && PYTHON=python

mkdir -p _tmp

# Search by topic:

#   $PYTHON "$SCHOLAR_SCRIPT" bibtex "transformer attention" --max 5

Save the verified list to _tmp/_verified_refs.txt with one entry per line.

Step 2: Write the paper

Order: Method/core → Experiments → Introduction → Related Work → Conclusion → Abstract (last).

⛔ Cross-section context + figure-data binding (prevents the "two-layers" disconnect):

Save everything in paper/main.md (single file). Suggested skeleton:


# [Paper Title]



[Author placeholders]



## Abstract



[150-250 words]



**Keywords**: kw1; kw2; kw3



## 1. Introduction



[Hook → gap → contribution → results preview, ~1.5 pages]



## 2. Related Work



[Synthesize by category, not by paper, ~1-1.5 pages]



## 3. Method



### 3.1 Notation



### 3.2 Formulation



$$ \mathcal{L}(\theta) = \mathbb{E}_{x \sim \mathcal{D}} [\ell(f_\theta(x), y)] \tag{1} $$



### 3.3 Algorithm



![Figure 1: Method overview.](figures/fig_arch.png)



As shown in Figure 1, ... [≥ 5 lines analysis]



## 4. Experiments



### 4.1 Setup



### 4.2 Main results



**Table 1: Comparison with baselines.**



| Method | Acc | F1 |

|--------|-----|-----|

| ... | ... | ... |



Table 1 shows ... [numerical interpretation + comparison + reasoning, ≥ 2 paragraphs]



![Figure 2: Ablation.](figures/fig_ablation.png)



Figure 2 reveals ... [≥ 5 lines]



### 4.3 Ablation



### 4.4 Discussion



## 5. Conclusion



[Rephrase contributions + limitations + future work, ~0.5 page]



## References



[1] LeSage J P, Pace R K. Introduction to Spatial Econometrics. CRC Press, 2009.

[2] Vaswani A, et al. Attention is all you need. NeurIPS 2017.

⛔ Style discipline:

After each section:


words=$(wc -w < paper/main.md)

echo "running word count: $words"

<exemplar_depth>

Writing depth by venue

ICLR/NeurIPS/ICML (9 pages main body, ~5400-6300 words for body):

JMLR/TPAMI journal (15-20 pages, ~9000-12000 words):

</exemplar_depth>

Expansion strategies (not padding — substantive content):

Section guidelines (per-section minimums)
Per-section minimum figures/citations

Step 3: Reference numbering

After writing prose:


grep -oE '\[[0-9]+(-[0-9]+)?(, *[0-9]+)*\]' paper/main.md | sort -u > _tmp/_cited.txt

ref_count=$(awk '/^## References/,0' paper/main.md | grep -cE '^\[[0-9]+\]')

echo "Cited tokens vs reference entries: $(wc -l < _tmp/_cited.txt) vs $ref_count"

Make every [N] in body match an entry in ## References. No gaps.

⛔ Numbering must be strictly increasing by first appearance: [1] before [2] before [3]. No regression.

⛔ Multi-cite merging: [1, 2, 3] requires ascending order; non-adjacent IDs can be split [1] [5].

Step 3.5: Build verified BibTeX entries (citation discipline)

⛔ Use scholar_fetch.py for ALL reference retrieval. NEVER fabricate BibTeX from memory.

While drafting, use descriptive citation keys so you can search them later: LastName_Year_topic_keywords.

When all draft text is done, search and verify each citation:


PYTHON=""; for _c in "$MH_PYTHON" python python3; do [ -z "$_c" ] && continue; if $_c -c "import sys" >/dev/null 2>&1; then PYTHON="$_c"; break; fi; done; [ -z "$PYTHON" ] && PYTHON=python

mkdir -p _tmp



# Collect citation keys / topic descriptors (you maintained while writing)

# For each, search scholar_fetch:

while IFS= read -r key; do

    query=$(echo "$key" | sed 's/^TODO__//; s/_/ /g')

    echo "--- Fetching: $key (query: $query) ---"

    $PYTHON "$SCHOLAR_SCRIPT" bibtex "$query" --max 3

    sleep 0.5

done < _tmp/_topics.txt

For each search result:

  1. Check match_label: "good" → use; "partial" → verify title matches; "low" → likely wrong paper, retry with better keywords or use WebSearch.
  1. Check match_score: < 0.3 → don't blindly trust.
  1. Format the BibTeX result as a [N] LastName F M, ... Title. Venue, Year. line under ## References.
  1. If bibtex_source=auto, add <!-- VERIFY --> comment in the source markdown next to the citation.

⛔ References: journal venues 参考区间 30–40 entries, conferences 20–30 entries(经验参考区间,非硬下限)。⛔ Authenticity over count: 只收真实检索核验过的文献——检索结果不足时保留真实条目并在文内注明差距,NEVER fabricate entries to hit the number。

Step 4: De-AI polish

See <de_ai_polish> in writing_rules.md. Key:

Step 5: Cross-review


mkdir -p _tmp

cat << 'EOF' > _tmp/_review_prompt.txt

Review this academic paper draft. Focus on:

1. Logic flow and argument structure

2. Claim-evidence alignment

3. Clarity and concision

4. Missing/weak sections

5. Score (1-10) + top-3 improvements



## Paper:

EOF

cat paper/main.md >> _tmp/_review_prompt.txt

PYTHON=""; for _c in "$MH_PYTHON" python python3; do [ -z "$_c" ] && continue; if $_c -c "import sys" >/dev/null 2>&1; then PYTHON="$_c"; break; fi; done; [ -z "$PYTHON" ] && PYTHON=python

$PYTHON "$REVIEWER_SCRIPT" --prompt-file _tmp/_review_prompt.txt --thread-file _tmp/_reviewer_thread.json 2>&1 | tee _tmp/_cross_review.txt

Skip if reviewer script unavailable.

Step 5.5: Reverse outline test

Extract topic sentences from each paragraph → read them in sequence → check claim coverage → fix gaps.


# Extract first sentence of every paragraph (paragraphs separated by blank line)

awk 'BEGIN{RS=""} {print substr($0, 1, index($0,"\n")?index($0,"\n")-1:length($0)) }' paper/main.md | grep -v '^#' | grep -v '^!' | grep -v '^|' | head -50

Reading just topic sentences should still tell the paper's story. If gaps exist (claim made but evidence missing, or evidence presented but claim not stated), fix them.

Step 6: Final verification

Run the full output-contract verification block (top of this SKILL). Any ⛔ → go back, fix, re-verify.

Key Rules (docx mode)


⛔ Figure embedding verification (MUST pass before finishing — file existence + actual reference in paper/main.md both required)

已并入共享脚本 paper_write_audit.sh(paper-write 族单一实现,_utils/ 与 shared-scripts/ 双副本)。怎么跑:

bash _utils/paper_write_audit.sh --mode docx   # 本目录无 _utils 时: bash skills/shared-scripts/paper_write_audit.sh --mode docx

怎么读结果:任何 MISSING: / ❌ 行或 Total missing embeddings > 0 都表示有图/表未嵌入 paper/main.md——逐项补齐后重跑至 0;⛔ DO NOT finish until missing = 0.。题注过长(>14 词)会报 Captions too long,把判据/参数/结论移入正文后重跑。该脚本同时执行下方 FIGURE_MANIFEST audit 与 universal paper audit;审计留痕由程序采集,不再手写 AUDIT_REPORT 审计文件;有引擎 finish 时以 output_contract/paper_write_gate 自动核验为准,本脚本为无引擎合同场景的兜底预检。

⛔ FIGURE_MANIFEST audit (run before finishing — must produce + embed every planned figure)

已并入共享脚本 paper_write_audit.sh(见上节,随 bash _utils/paper_write_audit.sh --mode docx 一并执行)。怎么读结果:✅ FIGURE_MANIFEST fully embedded = 通过;❌ MANIFEST: ... / ⛔ FIGURE_MANIFEST audit failed (N missing) = 计划图缺文件(.png/.pdf/.drawio)或未嵌入 paper/main.md——补产/补嵌后重跑。判据与原内联版逐项一致。

⛔ Universal paper-stage audit (shared across all writing steps)

已并入共享脚本 paper_write_audit.sh(见上节,随 bash _utils/paper_write_audit.sh --mode docx 一并执行;内部调 _utils/facts_audit.py --stage paper,无 PROBLEM_FACTS.json 时自动走简化模式)。检查项:[13] 正文结论与 results.json 一致(防"最优解 X 但正文写 Y");[14] 事件源归属。怎么读结果:输出 ❌ Universal paper-stage audit failed = 修正正文/results.json 后重跑。审计输出由程序采集留痕,不再手写 AUDIT_REPORT 审计文件。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.