Comp paper en docx

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

Comp paper en docx is an AI agent skill from the GitHub repository FOURTEEN1416/academic-agent-toolkit. English competition paper (MCM/ICM/APMCM), Word docx mode; docx counterpart of comp-paper-en, produces main.md. 区别于 comp-paper-zh-docx:中文竞赛论文改用 comp-paper-zh-docx。触发词:英文竞赛论文 docx。

How to use this skill

Skill file

Competition Paper Writing (English) — docx mode

Write an MCM/ICM/APMCM paper as Markdown for Word export: $ARGUMENTS

⚡ Fast-mode detection (run first)


FAST_MODE=0

grep -q 'MH_FAST_MODE=1' AGENTS.md 2>/dev/null && FAST_MODE=1

echo "FAST_MODE=$FAST_MODE"

If FAST_MODE=1 (speed priority): still MUST produce a complete paper (all sections present, every sub-problem covered, figures embedded per manifest, body pages within the dispatched page cap, cite real data — no fabrication, pass output verification), but SKIP line-by-line number consistency re-checks and repeated polish for minor issues. If FAST_MODE=0 (default): run all consistency checks as usual.

docx-mode counterpart of comp-paper-en. Keeps COMAP/APMCM structure (Summary Sheet, Assumptions, Notations, sub-problem chapters, Sensitivity Analysis, Strengths & Weaknesses) but produces paper/main.md only.

⛔ NEVER produce .tex / .cls / .sty / .bib. NEVER use LaTeX commands.

Constants

Inputs

  1. PROBLEM_ANALYSIS.md, MODELING_REPORT.md, RESULTS.md
  1. figures/ — .png / .pdf
  1. code/, figures/all_results.json, figures/problem_*_results.json

Load shared rules

writing_rules.md 是共享写作规则的唯一真源(skills/_utils/writing_rules.md,与 skills/shared-scripts/writing_rules.md 同源),不在这里复制正文。先取 tag 目录,再只读本章实际需要的节:

RULES=_utils/writing_rules.md
[ -f "$RULES" ] || RULES=../_utils/writing_rules.md
[ -f "$RULES" ] || RULES=skills/_utils/writing_rules.md
[ -f "$RULES" ] || RULES=academic-toolkit/skills/_utils/writing_rules.md
awk '/^<[a-z_]+>$/ {print NR": "$0}' "$RULES"   # tag 目录;行号随改版漂移,以实跑输出为准

| tag | 何时读 |

|---|---|

| <comp_figure_narrative> | Step 1 建图表嵌入计划后、写任何图前后文字前 |

| <comp_abstract_discipline> | 写 Summary Sheet 的步骤(分段/加粗/数字回验判据) |

| <comp_optimization_writing> | Step 2.9 优化/规划类模型与求解章节 |

| 其余 tag(figure_embedding / latex_constraints / references_workflow / output_conventions 等) | 按需(以 tag 目录实跑输出为准) |

MCM/ICM Paper Structure


Summary Sheet (1 page — most important page)

1. Introduction

2. Assumptions and Justifications

3. Notations

4. Model Design and Solution (per sub-problem)

5. Sensitivity Analysis

6. Model Evaluation (Strengths + Weaknesses)

7. Conclusions

References

Appendix A: Code

Adaptive structure (upstream refinement, incremental): the sequence above lists semantic slots,

not mandatory chapter names. Do not generate a Table of Contents. Follow

_utils/modeling_paper_contract.md and keep each core model connected to its results and validation;

model chapters are named after what they actually contain (see Step 2.9).

⛔⛔⛔ Output Contract (highest priority)

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

Never produce: .tex / .bib / .cls / .sty / .aux / any LaTeX command.

Mandatory verification:


PASS=true

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

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



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

est_pages=$((words / 600))

if [ -n "$PAGE_CAP" ]; then
    echo "words: $words, est pages: ~$est_pages, cap: <= $PAGE_CAP pages (scope: ${PAGE_SCOPE:-UNSPECIFIED -> 待核实})"
else
    echo "words: $words, est pages: ~$est_pages — PAGE_CAP not dispatched, page cap unknown (待核实); no default target."
fi



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

    echo "❌ LaTeX residue:"

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

    PASS=false

fi



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



if [ "$PASS" != true ]; then echo "⛔ verification FAILED"; exit 1; fi

docx-cn-engine markdown conventions

(See paper-write-docx for the full reference.)

Workflow

Step 0: Upstream check + resume


echo "=== Upstream check ==="

for f in PROBLEM_ANALYSIS.md MODELING_REPORT.md RESULTS.md; do

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

done

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

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 — backup created"

fi

Step 1: Figure inventory + embedding plan


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  # caption reference only

⛔ Build figure embedding plan before writing:

| ID | File | Section | Caption |

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

| Fig 1 | figures/fig_roadmap.png | 1. Introduction | Figure 1: Solution roadmap |

| Fig 2 | figures/fig_flow_q1.png | 4.1 Sub-problem 1 | Figure 2: Sub-problem 1 algorithm flow |

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

⛔ Only embed figures whose files exist. ⛔ DrawIO figures (roadmap/flow) MUST be embedded into proper sections.

⛔⛔ Figure-text narrative hard rules: load and follow the <comp_figure_narrative> tag in _utils/writing_rules.md — the shared contract across comp-paper-en / comp-paper-en-docx / comp-paper-zh-docx (figures drawn out by the argument; depth floor = concrete numbers + comparison/trend + inference/linkage, never one flat sentence; no formulaic "[type] (Fig. N) + verb + conclusion" openers; figure numbers always cited with rotated entry styles; no boilerplate placeholders; short captions; no two images directly adjacent). This skill is the docx variant: captions via ![alt](path) alt text (body ≤14 words), no LaTeX floats.

RULES=_utils/writing_rules.md
[ -f "$RULES" ] || RULES=../_utils/writing_rules.md
[ -f "$RULES" ] || RULES=skills/_utils/writing_rules.md
[ -f "$RULES" ] || RULES=academic-toolkit/skills/_utils/writing_rules.md
for t in comp_figure_narrative; do
  awk -v s="<$t>" -v e="</$t>" '$0==s{f=1} $0==e{f=0} f' "$RULES"
done

Step 1.5: Pre-fetch verified reference pool


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, save verified entries to _tmp/_verified_refs.txt

Step 2: Write the paper

Order: Body chapters first → References → Summary Sheet last.

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

Skeleton (one paper/main.md):


# [Paper Title]



## Summary Sheet



[Placeholder — write LAST in Step 5.6, after all chapters complete and numerical results known]



**Keywords**: ...



## 1. Introduction



### 1.1 Problem Background



[2-3 paragraphs of real-world context, references to prior work]



### 1.2 Restatement of the Problem



[Restate in own words, NOT copy the problem statement]



### 1.3 Our Approach



[Use a paragraph or two to explain how the three sub-problems build on one another, letting the prose settle into "the overall pipeline can be summarized as follows" before the figure — do NOT open with "As shown in Figure 1"]



![Figure 1: Solution roadmap.](figures/fig_roadmap.png)



[After the figure: highlight the pivotal stage of the pipeline and lead into the first sub-problem. Vary the entry for every figure — never a uniform "As shown in Figure X / Figure X shows"]



## 2. Assumptions and Justifications



We make the following assumptions:



(1) [Assumption]. This assumption is justified because... [1-2 sentences]

(2) ...

(3) ...

(4) ...

(5) ...



⛔ 4-6 assumptions. Each 1-2 sentences (assumption + justification).



## 3. Notations



**Table 1: Key Notations**



| Symbol | Meaning | Unit |

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

| $N$ | Total quantity | items |

| $x_i$ | Decision variable for item $i$ | --- |

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



⛔ 15-20 symbols max — only those actually used in body.



## 4. Sub-Problem 1



### 4.1 Problem Analysis



[1-2 paragraphs]



### 4.2 Model Formulation



[Transition from the problem analysis: since the crux is X, the solution proceeds in several stages — describe them, then bring in the figure. Use a different opener, not "Figure 2 illustrates"]



![Figure 2: Sub-problem 1 algorithm flow.](figures/fig_flow_q1.png)



We formulate the model as:



$$\min \sum_{i=1}^n c_i x_i \quad (1)$$



$$\text{s.t.} \quad \sum_i a_{ij} x_i \leq b_j, \quad j=1,\dots,m \quad (2)$$



[≥ 5 lines explaining each symbol's meaning]



### 4.3 Solution Algorithm



[Algorithm steps + complexity analysis]



### 4.4 Results



**Table 2: Comparison of algorithms for Sub-problem 1**



| Algorithm | Fitness | Time(s) |

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

| GA | 0.823 | 12.3 |

| PSO | 0.811 | 10.8 |

| Ours | **0.917** | **9.4** |



Table 2 shows that our method... [≥ 2 paragraphs of analysis]



![Figure 3: Convergence curves.](figures/fig_results_q1.png)



[Change the entry again: e.g. pose the question "where does the gap in Table 2 come from?" and let the convergence curves answer it, folding the figure into the ongoing argument rather than a "Figure 3 shows…" label. Follow with enough numerical interpretation and reasoning to make the point fully.]



## 5. Sub-Problem 2



[Same structure]



## 6. Sub-Problem 3



[Same structure]



## 7. Sensitivity Analysis



[≥ 2 key parameters, each with variation curve + analysis]



## 8. Model Evaluation



### 8.1 Strengths



[3-4 strengths, each one paragraph]



### 8.2 Weaknesses



[2-3 weaknesses]



### 8.3 Future Work



[1-2 paragraphs]



## 9. Conclusions



[Summary + main contributions + practical implications]



## 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.



## Appendix A: Code


Code listings or file inventory

Step 2.9: Optimization-model writing refinement (upstream, incremental)

⛔⛔ The full writing contract for optimization models — section titles naming the model, decision-variable five factors (symbol/meaning/type/index range/why that type), objective traceability to MODELING_REPORT.md, constraint numbering with real-world meaning, linearization justification with data-derived M, model class/size, the anti-pattern, the solution-credibility hard ratio (credibility words ≥ algorithm words), no padding pseudocode, the relaxation-bound honesty boundary, and the required Innovations items — is the shared <comp_optimization_writing> tag in _utils/writing_rules.md (single source for comp-paper-en / comp-paper-en-docx / comp-paper-zh-docx). Load before writing any model/solution section:

RULES=_utils/writing_rules.md
[ -f "$RULES" ] || RULES=../_utils/writing_rules.md
[ -f "$RULES" ] || RULES=skills/_utils/writing_rules.md
[ -f "$RULES" ] || RULES=academic-toolkit/skills/_utils/writing_rules.md
for t in comp_optimization_writing; do
  awk -v s="<$t>" -v e="</$t>" '$0==s{f=1} $0==e{f=0} f' "$RULES"
done

Step 3: Writing discipline

⛔ Style rules:

⛔ Numbers from data only.

⛔ 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"):


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

python3 - <<'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 python3 -c "import json;d=json.load(open('figures/all_results.json'));print(d['key'])" — still never read the whole file. Copy exact numbers from data. No memory-based estimation.

⛔ Figure-text discipline:

⛔ Long tables (>15 rows):

After each section:


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

echo "running word count: $words"

<exemplar_depth>

Writing depth reference

MCM/ICM Outstanding Paper (~25 pages, ~15000 words total):

APMCM First Prize (25-30 pages): similar but can be longer, 5-6 pages per sub-problem with more detailed analysis.

</exemplar_depth>

Expansion strategies (not padding — substantive content):

Summary Sheet is the most important page — invest the most effort here. Must be self-contained, one page, ≥ 300 words, with quantitative results.

Each sub-problem chapter: model formulation → solution method → results (table + figure + numbers) → result analysis (2-3 paragraphs of interpretation)

Sensitivity Analysis: parameter sensitivity + robustness + error analysis

Model Evaluation: Strengths 3-5 points + Weaknesses 2-3 points (honest) — do not write token weaknesses like "limited by time"

Step 4: Reference numbering


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"

⛔ Numbering must be strictly increasing by first appearance ([1] before [2] before [3]). No gaps.

⛔ MCM/ICM ≥ 10 references; APMCM ≥ 10.

Step 4.5: Verify references with scholar_fetch (mandatory)

⛔ All references MUST be fetched via scholar_fetch.py. NEVER fabricate BibTeX from memory.

Use descriptive citation keys while drafting: LastName_Year_topic_keywords.

After drafting, 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

SCHOLAR_SCRIPT="tools/scholar_fetch.py"

mkdir -p _tmp

# Place descriptive keys in _tmp/_topics.txt (one per line)

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 result:

  1. Check match_label: "good" → use; "partial" → verify title; "low" → retry or use WebSearch.
  1. Check match_score: < 0.3 → don't blindly trust.
  1. Format result as [N] Author A, Author B. Title. Venue, Year, vol(issue): pages. under ## References.
  1. References order in ## References MUST match first-appearance order in body.

Fallback: If scholar_fetch.py fails or match_label="low", use WebSearch on Google Scholar / Semantic Scholar to verify title + authors + year manually.

Step 4.6: Claims-Evidence Matrix Verification

Before each chapter, re-read the claims-evidence matrix in PROBLEM_ANALYSIS.md / MODELING_REPORT.md / PAPER_PLAN.md:


grep -A 100 'Claims-Evidence\|claim.*evidence\|claim-evidence' PROBLEM_ANALYSIS.md MODELING_REPORT.md PAPER_PLAN.md 2>/dev/null | head -50

Discipline:

If a planned claim has no data evidence, write "preliminary results suggest X, formal validation left to future work" instead of fabricating evidence.

Step 5: De-AI polish

See <de_ai_polish> in writing_rules.md. Key:

Step 5.5: Cross-review (optional)


mkdir -p _tmp

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

Review this MCM/ICM/APMCM paper draft. Focus on:

1. Sub-problem coverage (does each sub-problem have explicit numerical results?)

2. Claim-evidence alignment (every conclusion supported by data?)

3. Chapter structure vs MCM/ICM standard

4. Writing clarity (any meta-narrative leaks / boilerplate openings?)

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

REVIEWER_SCRIPT="tools/reviewer_client.py"

$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.6: Write Summary Sheet LAST

⛔ NOW write the Summary Sheet (replace the placeholder from Step 2).

The Summary Sheet is the most important page. Read RESULTS.md and all body chapters to extract specific numerical results for each sub-problem.


## Summary Sheet



[1-page summary covering:

- Background and problem context (1 short paragraph)

- Approach/methodology summary (1 paragraph)

- Sub-problem 1: method + key result with specific number (1 paragraph)

- Sub-problem 2: method + key result with specific number (1 paragraph)

- Sub-problem 3: method + key result with specific number (1 paragraph)

- Model evaluation: strengths + weaknesses (1 short paragraph)]



**Keywords**: keyword1; keyword2; keyword3; keyword4; keyword5

⛔⛔ Summary Sheet bold & paragraphing discipline: load and follow the <comp_abstract_discipline> tag in _utils/writing_rules.md — the shared contract across comp-paper-en / comp-paper-en-docx / comp-paper-zh-docx (bold only the three conclusion anchors — key result numbers / core method names / the single critical noun; 1~3 bolds per paragraph, ≤12 total; never bold whole sentences/background/connectives; per-problem paragraphs separated by blank lines, never cram two "For Sub-problem X" into one paragraph; per-paragraph content criteria; numbers must match paper/main.md body text exactly). This skill is the docx variant: bold with markdown **...** only (never \textbf{} — it renders as literal garbage in docx), openers "For Sub-problem X". Load before writing the Summary Sheet:

RULES=_utils/writing_rules.md
[ -f "$RULES" ] || RULES=../_utils/writing_rules.md
[ -f "$RULES" ] || RULES=skills/_utils/writing_rules.md
[ -f "$RULES" ] || RULES=academic-toolkit/skills/_utils/writing_rules.md
for t in comp_abstract_discipline; do
  awk -v s="<$t>" -v e="</$t>" '$0==s{f=1} $0==e{f=0} f' "$RULES"
done

⛔ Run the paragraph self-check (detect → fix → recheck loop; use python, not python3):


python - <<'PY'

import re, sys

text = open('paper/main.md', encoding='utf-8').read()

m = re.search(r'^##\s*(Summary Sheet|Abstract)[\s\S]*?(?=^##\s|\Z)', text, re.MULTILINE)

if not m:

    print('⚠ Summary Sheet section not found'); sys.exit(0)

section = m.group(0)

bad = []

for i, para in enumerate(re.split(r'\n\s*\n', section), 1):

    if len(re.findall(r'[Ff]or [Ss]ub-?problem', para)) > 1:

        bad.append((i, para.strip()[:80]))

if bad:

    print(f"❌ {len(bad)} paragraph(s) cram multiple 'For Sub-problem' openers — split each into its own paragraph:")

    for i, snip in bad:

        print(f"  para {i}: {snip}...")

    sys.exit(1)

print('✓ Summary Sheet is split per sub-problem')

PY

⛔ Loop rule: if the check exits 1, go back to the ## Summary Sheet section in paper/main.md, insert a blank line before each "For Sub-problem X" so it becomes its own paragraph, then rerun the check until it prints "✓ Summary Sheet is split per sub-problem" before moving on.

Step 5.7: AI tool usage statement (only when the user enabled it)

AI_DISC=off
grep -q 'AI_DISCLOSURE=used' AGENTS.md 2>/dev/null && AI_DISC=used
grep -q 'AI_DISCLOSURE=none' AGENTS.md 2>/dev/null && AI_DISC=none
echo "AI_DISC=$AI_DISC"

```bash

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

```

The official CUMCM statement and standalone detail PDF remain in Chinese even when the paper body is English. Never randomize or infer tools, dates, purposes, or interaction records. Do not put details in the Word appendix or list AI tools as academic references. Invalid records or a failed PDF check must fail this step.

Step 6: Final verification

Data closeout (upstream, incremental): if PAPER_DATA_CHECKLIST.md exists, read it before finishing and reconcile every reported result, comparison, error, and optimum against the real JSON/TABLE sources. Fix paper/main.md only; never change result data to make prose agree. After the reconciliation is complete, append <!-- DATA_CHECK_PASSED --> to paper/main.md (an invisible HTML comment in the Word export). The engine still verifies this independently. Do not defer this audit to another model session or rerun checks that already passed.

⛔ Capability-claim gate (full-chain contract; zero-cost, both modes): The Word paper must not claim capabilities that failed acceptance in coding.


FAST_MODE=0; grep -q 'MH_FAST_MODE=1' AGENTS.md 2>/dev/null && FAST_MODE=1

python _utils/paper_claim_check.py --audit CAPABILITY_AUDIT.md --checklist CAPABILITY_CHECKLIST.json --sections paper --fast $FAST_MODE

PCC=$?   # 0=all passed 1=some capability FAIL/PENDING (do not finalize) 2=no audit, skip

PCC=1: make the failed capability truly PASS in comp-code before finalizing. WARN: a not-passed capability name appears in the body (main.md) — ensure it isn't written as done unless honestly under Limitations. Chain: analysis→modeling→code-audit→paper reports only passed.


echo "=== Final verification ==="



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

echo "paper/main.md: $SZ bytes"



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

est_pages=$((words / 600))

# Length follows modeling and evidence: no per-section quota, no "below target must expand" floor.



# Sub-problem coverage

for n in 1 2 3; do

    if grep -qE "^## [0-9]+\. Sub-Problem ${n}|^## [0-9]+\. Problem ${n}" paper/main.md; then

        echo "✅ Sub-Problem ${n} present"

    else

        echo "⚠ Sub-Problem ${n} missing"

    fi

done



# Figure embedding

missing_img=0

for img in figures/*.png figures/*.pdf; do

    [ -f "$img" ] || continue

    bn=$(basename "$img")

    [ "$bn" = "latex_includes.tex" ] && continue

    if ! grep -q "$bn" paper/main.md; then

        echo "⚠ unembedded: $bn"

        missing_img=$((missing_img + 1))

    fi

done

[ "$missing_img" -gt 0 ] && echo "⛔ embed missing figures"



# ⛔ Adjacent-image check (prevents "two figures stuck together with no text between")

echo "=== Adjacent-image check ==="

python - paper/main.md << 'PYEOF'

import re, sys

try:

    t = open(sys.argv[1], encoding='utf-8', errors='ignore').read()

except FileNotFoundError:

    sys.exit(0)

imgs = list(re.finditer(r'!\[[^\]]*\]\([^)]*\)', t))

bad = 0

for i in range(len(imgs) - 1):

    gap = t[imgs[i].end():imgs[i+1].start()]

    body = re.sub(r'\s+', '', gap)

    if len(body) < 150:

        bad += 1

if bad:

    print("  X paper/main.md: %d figure gaps with too little prose (<150 chars, likely perfunctory/one-liner) — each figure needs full analysis: concrete numbers + comparison/trend + inference/linkage, never a lone sentence" % bad)

PYEOF

echo "(no output = no adjacency found)"



# ⛔ FIGURE_MANIFEST audit: planned figures must all be produced AND embedded

PLAN_FILE=""

for f in PROBLEM_ANALYSIS.md PAPER_PLAN.md MODELING_REPORT.md; do

  [ -f "$f" ] && grep -q '<!-- BEGIN FIGURE_MANIFEST -->' "$f" && { PLAN_FILE="$f"; break; }

done

if [ -n "$PLAN_FILE" ]; then

    START=$(grep -n '<!-- BEGIN FIGURE_MANIFEST -->' "$PLAN_FILE" | head -1 | cut -d: -f1)

    END=$(grep -n '<!-- END FIGURE_MANIFEST -->' "$PLAN_FILE" | head -1 | cut -d: -f1)

    EXPECTED_FIGS=$(sed -n "${START},${END}p" "$PLAN_FILE" | grep -oE '^[[:space:]]*-[[:space:]]+(fig_[a-zA-Z0-9_]+|tikz_[a-zA-Z0-9_]+)' | sed 's/^[[:space:]]*-[[:space:]]*//')

    manifest_missing=0

    for name in $EXPECTED_FIGS; do

        if ! ls figures/${name}.png figures/${name}.pdf figures/${name}.drawio 2>/dev/null | head -1 | grep -q .; then

            echo "❌ MANIFEST: $name file missing"

            manifest_missing=$((manifest_missing + 1))

        elif ! grep -qE "${name}\.(png|pdf)" paper/main.md; then

            echo "❌ MANIFEST: $name exists but not embedded in paper/main.md"

            manifest_missing=$((manifest_missing + 1))

        fi

    done

    [ "$manifest_missing" -gt 0 ] && echo "⛔ FIGURE_MANIFEST audit failed ($manifest_missing missing): must produce + embed all planned figures"

fi



# Citation continuity

max_cited=$(grep -oE '\[[0-9]+\]' paper/main.md | grep -v '^## ' | tr -d '[]' | sort -n | tail -1)

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

echo "max cited: ${max_cited:-0}, refs: $ref_lines"

[ -n "$max_cited" ] && [ "$ref_lines" -lt "$max_cited" ] && echo "⛔ refs less than cited"



# LaTeX residue

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

    echo "⛔ LaTeX residue:"

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

fi



# .tex residue

ls paper/*.tex paper/sections/*.tex 2>/dev/null | head -1 | grep -q . && echo "⛔ .tex files detected" || echo "✅ no .tex"



# Summary Sheet not placeholder

if grep -A 3 '^## Summary Sheet' paper/main.md | grep -qiE 'placeholder|TODO'; then

    echo "⛔ Summary Sheet still placeholder — must fill in"

fi



# ⛔ Figure-opener de-templating check (docx-only: the LaTeX contest flow is covered by

#    writing_check.sh, but the docx flow was not — so prose ended up opening every figure with

#    "Figure N shows…/Fig. N depicts…". This adds the same guard, matching the LaTeX version.)

echo "=== Figure-opener de-templating check ==="

PYTHONIOENCODING=utf-8 python - paper/main.md << 'PYEOF'

import re, sys

try:

    text = open(sys.argv[1], encoding='utf-8', errors='ignore').read().replace('\r\n', '\n')

except FileNotFoundError:

    sys.exit(0)

# Body only: cut at "## Appendix"/"## References" (figure numbers in code/refs don't count)

m = re.search(r'\n##\s*(Appendix|References)', text)

body = text[:m.start()] if m else text

# Opening with "Figure N…/Fig. N…/Table N…" = the most monotonous AI tell.

# Lead-ins that bury the number mid-sentence ("as shown in Fig. 2", "observing Fig. 4",

# "in the pipeline of Fig. 3") are fine and must NOT be flagged.

open_re = re.compile(r'^(Figure|Fig\.?|Table|Tab\.?)\s*\d', re.I)

leadin_re = re.compile(r'^(as\s|in\s|observing\b|from\b|see\b|per\b|following\b)', re.I)

def is_prose(p):

    s = p.strip()

    if len(s) < 15:

        return False

    if s[0] in '#>|`!*-\\%{}$&':          # heading/quote/table/code/image(![)/list/bold/LaTeX

        return False

    if re.match(r'^\d+\.', s):             # ordered list "1."

        return False

    return True

sections = re.split(r'(?m)^##\s', body)

adj_pairs = 0

heavy_secs = []

for sec in sections:

    flags = []

    for p in re.split(r'\n\s*\n', sec):

        if not is_prose(p):

            continue

        s = p.strip()

        flags.append(bool(open_re.match(s)) and not bool(leadin_re.match(s)))

    adj_pairs += sum(1 for i in range(len(flags) - 1) if flags[i] and flags[i + 1])

    n_open = sum(flags)

    if n_open >= 3:

        heavy_secs.append(n_open)

if adj_pairs or heavy_secs:

    if adj_pairs:

        print(f"  X {adj_pairs} adjacent paragraph pair(s) both open with 'Figure N…/Table N…' — the worst tell; sink the number mid-sentence or into a trailing parenthetical")

    if heavy_secs:

        print(f"  X {len(heavy_secs)} section(s) with >=3 figure-number openers ({heavy_secs}) — opening every figure with 'Fig. N' is monotonous; vary the entry")

    print("  Fix: parenthetical (preferred, '…(Fig. 3)'), verb-led ('Observing Fig. 4…'), or post-hoc ('…confirmed in Fig. 5'); figure-as-subject at most once per section")

    sys.exit(3)

print("  OK: figure citations are not templated")

PYEOF

fig_rc=$?

[ "$fig_rc" -eq 3 ] && echo "⛔ Templated figure openers: rewrite per the hints above, then re-run this check until it prints OK"



# Caption-too-long check (alt text is a short label; criteria/params/conclusions go in the body)

echo "=== Caption-too-long check ==="

python - paper/main.md << 'PYEOF'

import re, sys

LIMIT = 14  # word cap after stripping the "Figure N:" prefix (matches spec; over 14 = violation)

try:

    text = open(sys.argv[1], encoding='utf-8', errors='ignore').read()

except FileNotFoundError:

    sys.exit(0)

# Body only (cut at Appendix/References), matching writing_check.sh 7b3

m = re.search(r'(?m)^##\s*(Appendix|References)', text)

body_text = text[:m.start()] if m else text

bad = []

for alt in re.findall(r'!\[([^\]]*)\]\([^)]*\)', body_text):

    body = re.sub(r'^\s*(Figure|Fig\.?|Table|Tab\.?)\s*\d+\s*[:..、]?\s*', '', alt, flags=re.I)

    words = re.findall(r'[A-Za-z][A-Za-z-]*', body)

    if len(words) > LIMIT:

        bad.append((len(words), ' '.join(words[:12])))

if bad:

    for n, preview in bad:

        print(f"  X caption {n} words (>{LIMIT}): {preview}...")

    print(f"  {len(bad)} caption(s) too long — keep alt text to a short label (<=14 words); move criteria/params/conclusions into the body")

    sys.exit(3)

print("  OK captions are concise")

PYEOF

cap_rc=$?

[ "$cap_rc" -eq 3 ] && echo "⛔ Captions too long: shorten the alt text and move detail into the body, then re-run until it prints OK"

If any ⛔ appears, fix and re-run verification.

⛔ The figure-opener check is a detect → fix → recheck loop: whenever it reports X (exit 3), go back to paper/main.md, rewrite the flagged "Figure N…/Table N…" openers into parenthetical / verb-led / post-hoc forms (figure-as-subject at most once per section), then re-run this check until it prints "OK: figure citations are not templated" before finishing. This mirrors writing_check.sh in the LaTeX contest flow so the docx export matches the PDF export in quality.

Step 7: Compliance check (MCM/ICM specific)

Before submitting, verify against contest rules:

If any box is ❌, fix before submission.

Key Rules (docx mode)

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

Before finishing writing / compiling, run the universal audit. Works without PROBLEM_FACTS.json:


# Universal paper audit:

#   [13] Conclusion consistency: paper text ↔ results.json (prevent "optimal=X but paper says Y")

#   [14] Event source attribution (prevent "guessing source from variable name")

# Falls back to simplified mode if no PROBLEM_FACTS.json (general academic / course / humanities).

if [ -f _utils/facts_audit.py ]; then

    python3 _utils/facts_audit.py --stage paper 2>&1 | tee -a AUDIT_REPORT.md

    PRC=${PIPESTATUS[0]}

    if [ "$PRC" = "1" ]; then

        echo "❌ Universal paper-stage audit failed — fix paper text / results.json before finishing"

    fi

fi
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.