SuperAPI AI Directory

elements-complaint-generator

Writing & research

View repository

Updated 10-15 20:10

About this skill

Elements-Based Complaint Generation Skill (elements-complaint-generator)

I. Positioning

Perform anchor replacement on the Supreme People's Court's 67-category official elements-based complaint/defense templates (Fa [2025] No. 82, nationwide rollout on 2025-07-14), extract information from the "conventional complaint (Markdown or docx)/natural conversation/structured elements checklist" provided by the lawyer, and output an elements-based Word candidate document that passes DOCX structural checks and real PDF rendering gates. Legal content and case-specific filing requirements are still subject to lawyer review.

1.1 Iron Rules of Division of Labor (Agent and Code Each Fulfill Their Roles)

普通起诉状/对话 --[Agent(LLM) 抽取]--> elements.json --[纯代码(lxml) 替换]--> 要素式 docx
                    语义理解                                确定性模板填充
  • Agent is responsible for "extraction": read the conventional complaint → produce elements.json according to the cause-of-action Schema (human-reviewable). Semantic understanding is an LLM strength; regex only serves as a fallback (extract_from_markdown.py)。
  • Code is responsible for "filling and objective layout gates":fill_template.py perform on the template XML <w:t> cross-run precise replacement, then an independent checker verifies the structure and real PDF geometry; the LLM does not directly modify OOXML.

1.2 Current Scope (v0.16.1)

Dimension Scope
Templates All 113 trees fully included in the repository(complete version of Fa [2025] No. 82: Volume I 42 + Volume II 28 + Volume III 43, numbered 01-68 in the order of Volumes I, II, and III)
Extraction Mainly extraction within the Agent session;extract_from_markdown.py regex as fallback
Template form Unpacked OOXML source tree(git-diffable), rendering copies → edits → packages;22 causes of action have been replaced with the benchmark of documents actually issued by courts(2-table structure, DEC-011)
Replacement engine lxml directly edits <w:t>(cross-run precise replacement, multi-part coverage,--verify-residual residual verification)
Layout gates By default, the candidate DOCX is handed to the formal version of LibreOffice for real rendering, then checks are performed for A4, centering/column positions of each table, cross-page continuation, semantic headers, survival of Chinese glyphs, continuous page numbers, publication residual codes, and blank pages; on failure, the target file is not overwritten
Template version Fa [2025] No. 82, 2025-07-14 rollout version (consistent across multi-channel cross-comparison)

1.3 Inapplicable Scenarios

  • What the user wants is not the "elements-based" format (e.g., a free-form complaint) → use legal-proposal-generator or manual drafting
  • The user only has scanned PDFs → first use legal-ocr to convert to md, then use this skill
  • The user wants to batch-generate 100+ documents for the same cause of action → not currently supported (batch mode to be added later)

II. Architecture

┌────────────────────────────────────────────────┐
│ 输入:常规起诉状(md/docx) / 对话 / 要素文件      │
└───────────────────────┬────────────────────────┘
                        ▼
          ┌───────────────────────────┐
          │ Agent 按 Schema 抽要素     │ ← 语义理解(LLM)
          │ (regex 脚本兜底)           │
          └─────────────┬─────────────┘
                        ▼
          ┌───────────────────────────┐
          │ elements.json(人可复核)  │
          └─────────────┬─────────────┘
                        ▼
┌────────────────────────────────────────────────┐
│ fill_template.py(纯代码,确定性)              │
│  复制 templates/<案由>/ → lxml 编辑 <w:t>       │
│  <w:t> 跨 run 精确替换 → pack_docx 打包         │
│  → 残留校验 → DOCX 静态门禁 → PDF 真实渲染门禁 │
└───────────────────────┬────────────────────────┘
                        ▼
          ┌───────────────────────────┐
          │ 要素式起诉状.docx          │ ← 候选交付件,律师复核
          └───────────────────────────┘

III. Operation Flow (three stages: cause-of-action matching → two-stage extraction → rendering)

3.1 ① Cause-of-Action Matching

读用户材料(起诉状 md/docx / 口述)→ 对照 references/case-routing.md
→ 确定案由编号 + case-type key + 模板树 + reference 文档
→ 拿不准时列 2-3 个候选案由请用户选

3.2 ② Elements Extraction (common block + cause-of-action-specific block)

According to references/extraction-prompt-template.md execute:

  • Common block(common-elements.md): parties / agents / willingness to mediate / petitioner
  • Cause-of-action-specific block(case-types/{{key}}.md §I): litigation request checkboxes and amounts / preservation / facts and reasons
  • Discipline: no material → leave blank; for enumerations use the original option text; dates in ISO; after producing elements.jsonuser review is required
  • Fallback: when the Agent is unavailable extract_from_markdown.py(regex fallback implemented on 09/05)

3.3 ③ Rendering (pure code)

# 精调 key 示例:09-private-lending / 22-copyright / 60-enforcement / 65-objection;两位编号(如 06)走通用级
python scripts/fill_template.py \
  --case-type 09-private-lending \
  --elements <案件>/elements.json \
  --output <案件>/要素式起诉状.docx \
  --verify-residual "旧当事人名,旧电话"
  • Copy templates/<tree>/ → lxml edit <w:t>(precise cross-run replacement, multi-part coverage) → package
  • General rules (parties/mediation/pleading) and cause-of-action rules are layered and reused (DEC-001/002 iron rules)
  • --verify-residual residual validation prevents leakage of old case information
  • Default --layout-check rendered: first run the DOCX invariant check on a temporary candidate, then use LibreOffice to convert to PDF and check the actual pages; failure at any step exits non-zero and does not overwrite an existing target file.
  • --layout-check docx is only for batch regression during development and must not be used as a basis for delivery;--layout-check off is only used to locate problems in the gate itself and must not be used to claim that the layout passes.
  • Layout exceptions are uniformly written to config/layout-policy.json. Currently only the 22 copyright court benchmark documents explicitly do not carry page numbers; adding page numbers via a global rule on one's own is prohibited.

3.4 Regression

bash tests/run_e2e.sh — content assertions and 68-number smoke test + long-text matrix fast contract + 113-tree DOCX layout static gate + real PDF rendering of 21 document types + positive and negative examples of layout violations.

The release-level long-text matrix for the 68 main documents runs independently and is not stuffed into the daily E2E:

python tests/smoke_render_longtext.py \
  --rounds 3 --require-full \
  --json-output tests/output/longtext-report.json \
  --evidence-dir tests/output/longtext-evidence

This entry point generates deterministic long party, long claim, and long fact inputs for each main document, warming up once per category, then measuring three consecutive rounds; each round reuses the formal DOCX/PDF gate and records page count, consecutive page numbers, blank pages, glyph survival, candidate content hashes, and stable fingerprints. The evidence directory must be empty, and reusing old artifacts is rejected; when locating fluctuations, you may add --evidence-all-rounds to retain the DOCX, PDF, and key page screenshots for each round.

IV. Dependencies and Template Assets

4.1 Runtime Dependencies

Tool macOS installation Purpose
Python 3.11+ Built into the system Run scripts
lxml pip3 install lxml XML editing and DOCX layout checking (hard dependency)
PyMuPDF pip3 install pymupdf Read the page geometry and page numbers of the actual rendered PDF (required by the default delivery path)
LibreOffice stable release brew install --cask libreofficeLinux: sudo apt-get install libreoffice Real DOCX→PDF rendering for the default delivery path; dev/alpha builds cannot be used as the basis for Chinese visual acceptance

Install Python dependencies before the first run of the default rendering path:pip3 install lxml pymupdf. When LibreOffice or PyMuPDF is missing, the script will clearly report an error and refuse to publish the target file, and will not silently degrade to "verified".

4.2 Template Assets

templates/                     # ★ 模板唯一权威源(113 棵 OOXML 源码树,git 可 diff)
  01-侮辱案刑事附带民事-刑事附带民事自诉状/   # 上册 01-21:刑事自诉4+民事9+商事8
  05-离婚纠纷-民事起诉状/                     #   (起诉状+答辩状成对)
  09-民间借贷纠纷-民事起诉状/                 # ← 规则已实现
  30-垄断纠纷-民事起诉状/                     # 中册 22-36:知产民事9+知产行政6+垄断行政
  44-行政处罚-行政起诉状/                     # 下册 37-68:海事4+环资3+行政11+行政答辩+国赔4+执行9
  55-行政答辩状/  60-强制执行申请书/           #   单文书目录(树名=编号-案由)

templates/templates-manifest.json             # v2 清单:树↔源文件↔SHA-256 溯源 + 命名规范化记录

Why use unpacked trees instead of docx: docx is a zip binary (git diff is garbled); after unpacking it is plain-text XML, so template iteration, official version updates, and every fill difference are all diffable/reviewable/rollbackable.Store a complete tree per cause of action(self-contained, mutually non-polluting, and no shared base is extracted to prevent breaking format iron rules).

4.3 Template Intake Process (for new causes of action / official updates)

# 完整版为原生 OOXML docx,直接批量解包入库(上中下顺序,编号 01-68):
python scripts/ingest_full_templates.py \
  --source "~/Desktop/要素式起诉状模板/67类完整版(起诉状+答辩状+第三人意见陈述书)" \
  --templates templates --overwrite
# 若源是 OLE2 老格式(如 67类/ 平铺目录),先转再入:
python scripts/ole2_to_docx.py --input ~/Desktop/要素式起诉状模板/67类 --output /tmp/ecg-docx \
  --manifest templates/templates-manifest.json --include 'NN-*'
python scripts/unpack_docx.py --input /tmp/ecg-docx --output templates --overwrite
# ③ 反向打包(校验/出件用)
python scripts/pack_docx.py --tree templates/06-买卖合同纠纷-民事起诉状 --output 检查.docx

V. Element Schema (three-layer reference)

Layer Document Coverage
General layer references/common-elements.md Cross-cause elements such as parties/agents/mediation willingness/signature block (evidence: 113-tree scan, 28 signature groups)
Routing layer references/case-routing.md(script-generated, do not edit manually) 113 tree index: cause of action/book/document/tree/key/support status/keywords
Cause of action layer references/case-types/NN-*.md Cause-of-action-specific elements;the skeleton is generated by dump_template_fields.py reverse-deriving from the template tree, humans/Agents fill in element paths and extraction hints

68/68 all finalized: the case-types/ directory covers all numbers (14 handwritten detailed versions + 54 programmatically generated simplified versions); skeleton skeletons/ 66 full-field checklists.

  • Top level:当事人 / 诉讼请求 / 约定管辖和诉前保全 / 事实与理由 / 对纠纷解决方式的意愿 / 具状人_签字_盖章 / 具状日期
  • 09-private-lending: plaintiff/defendant are single natural-person objects; agents are an array of zero or one object. Third parties, organizations and additional parties are rejected; follow the 09 cause-of-action reference as authoritative, and do not apply the generic engine array Schema.
  • Field types: str / bool (checkbox) / enum / list

Six, Template Version Management

  • Current version: Fa [2025] No. 82, nationwide rollout on 2025-07-14
  • Next review: 2026-11-17 (check official updates every six months)
  • On official update: rerun the §4.3 ingestion process → git diff templates/ directly see what the official changed → check whether rules need adjustment → run regression

Seven, Cause-of-Action Extension Steps

Using 06 sales contract dispute as an example:

  1. Template ingestion: §4.3 process (ole2_to_docx → unpack_docx)
  2. Write Schema document:python scripts/dump_template_fields.py --tree templates/06-买卖合同纠纷-民事起诉状 --output references/case-types/06-sale-skeleton.md generate skeleton → fill in element paths/occurrence mappings/extraction hints (for common blocks directly reference common-elements.md, do not redefine)
  3. Write rule set:fill_template.py add build_rules_06_sale() + CASE_TYPE_TO_TREE mapping
  4. Extraction: Agent extracts directly according to the 06 Schema; if a regex fallback is needed, then in extract_from_markdown.py 's CASE_TYPE_TO_EXTRACTOR add
  5. Testing:tests/fixtures/ add samples; run tests/run_e2e.sh regression

Eight, Limitations and Known Issues

  • The 09 fix only validates field positioning, input types and options; it does not validate the lending legal relationship, consistency between claims, amount calculations, or case-filing requirements. Unfilled dates/amounts, selecting "Other", etc. still require manual completion; DOCX_VERIFIED cannot be taken as content or court submission certification.

  • 68/68 all causes of action fine-tuned: 63 build_rules builders (stacking mode: common layer + family factory + cause-of-action-specific) cover all numbers

  • Generic-level parties use sequential semantics (natural person 1/natural person 2) — in legal-person plaintiff causes of action (property management/public interest litigation/enforcement types), natural person 1 may be the opposing party; Agent extraction follows the skeleton guidance

  • Statements of defense/third-party opinion statements have been connected via NN-answer routing; their roles and mediation block differences must still be extracted according to the corresponding skeleton, and the field meanings of the complaint must not be applied.

  • Natural persons, legal persons/unincorporated organizations, and natural person/legal person blocks 3—4 are already supported; agents remain the template's original single slot, and multiple agents are not automatically expanded.

  • Paragraph-count preservation for long-text multi-paragraph cells (such as the 12-paragraph structure of "Facts and Reasons") is not yet implemented (v0.3 plan: XML reconstruction of multiple paragraphs)

  • The 68 main-document long-text matrices have completed per-category warm-up and three rounds of measurement under the official LibreOffice 26.2.3.2: 204/204 renders passed, 0 failures, 0 instability, and the input hashes, candidate DOCX content hashes and structural fingerprints are all consistent; the current environment state is DOMAIN_VERIFIED。

  • The 45 answer/third-party opinion statements have not yet entered the same-level long-text matrix; the 68 main document results must not be expanded into an interpretation that all 113 templates have been verified at extreme lengths.

  • The generator will, according to policy, map unavailable Founder font aliases to proven fc-match candidate fonts that cover Chinese, and fail closed via the character survival rate gate;DOMAIN_VERIFIED this still only proves the current official LibreOffice environment and does not mean that the font appearance is completely identical on all machines or in Word/WPS. Before formal submission, the content, signature/seal positions, and local court requirements should still be checked.

IX. Permissions and Data Boundaries

  • The script only copies and renders the template tree within the tempfile.mkdtemp() temporary directory, and after rendering automatically shutil.rmtree() cleans up the temporary directory (without touching user data).
  • ingest_full_templates.py --overwrite can override templates/ the specified template tree under it (explicit parameter, not default behavior).
  • No case content is sent over the network;--verify-residual only local scanning is performed.

X. Version

  • Current version:0.16.1(2026-09-30)
  • 0.16.1: Fixed the 09 dedicated path's party column crossing, principal currency endnote, cross-cell interest, amount unit, Boolean/enum, and mediation misalignment; locate by answer row and reject unsupported subjects/fields. The per-column real OOXML and structural gating regression is independent of legal review; the formal PDF acceptance for this time was not run, see 09 Fix Verification Boundaries。
  • 0.16.0: Added the 68 main document long party/claims/facts real rendering matrix and structural stability fingerprint; fixed clipping caused by long fields inheriting an enormous right indent, terminal empty section tail pages, legitimate cross-page grid refinement, false positives in adjacent cells, and LibreOffice font substitution drift; lines longer than 300 characters are allowed to naturally cross pages; the full 204 measurements had 0 failures and 0 instabilities, and the status is DOMAIN_VERIFIED
  • 0.15.2: Fixed the issue where E2E Harness incorrectly split paths when the repository path or fake artifact filenames contain spaces; the fake artifact manifest was changed to be restored item by item using a Bash array, and an explicit space-in-filename regression was added to avoid accidental deletion, incorrect moves, and leftover fake DOCX files
  • 0.15.1: Strengthened full input consumption, batch parameter passthrough, and atomic publishing; fail closed on the formal renderer and Chinese fonts; per-table centering, cross-page column positions, and cell boundary gates; 24/25 publication residual code cleanup and semantic duplicate table headers; eliminated occasional blank pages caused by attachment section stacking, same-direction booklet sections, and trailing empty paragraphs; 113/113 static matrix, three rounds of 21/21 family matrix, and full E2E passed
  • 0.15.0: Added independent DOCX/PDF layout gates and per-template exception policies; unified explicit table centering, fixed column widths, zero indentation, and prohibition of unnecessary line breaks; retained landscape/portrait boundaries and fixed wide-table orientation; changed page numbers to continuous PAGE fields and completed section footer references; candidates are verified before release; 113/113 static checks, 21/21 document family real PDF rendering, and 10 positive and negative examples passed
  • 0.14.0: Replaced the 22 template sources with court document benchmarks (DEC-011); geometry width-aware margins (overturning 1800 normalization); engine supplementary chain (22 claims/subject matter/cessation of infringement/no relation/expense line layout independence/agent checkboxes/domicile field name mapping fix/skipped details); the 250612 case 260826 MD end-to-end 48/48 assertions passed
  • 0.13.5: Added a mandatory post-rendering QA checklist (references/qa-checklist.md), converging on real-world issues in the 250612 case (template geometry/table merging/third-party column filling/engine rule gaps/manual patching iron rules)
  • 0.13.4(2026-08-22)
  • Coverage: 113/113 template trees (68 main documents finely tuned + 45 answer statements)
  • Format fix: section merging (continuous main body + separate pagination for mediation/evidence), margin normalization (25mm), footer PAGE field
  • Design draft:docs/plans/2026-08-17-elements-complaint-generator-design.md(not committed to repository)

XI. Mandatory Post-Render QA (added 2026-08-28, v0.13.5)

Any rendered output must first pass the automated layout gate before delivery, then fully execute the Post-Render QA Checklist(derived from the five-round rework practical retrospective of the 250612 Wu Jingyi case). Manual visual review only supplements legal content, signature/seal positions, and local visual impressions that are difficult for machines to judge; it cannot replace the automated gate. Key points:

  1. Three-way attribution of issues: repository templates (table splitting/table width 9344 overflow/fields spanning tc), rendering engine (intellectual property cause-of-action rule gaps, third-party string filling, labels swallowed, checkboxes silently skipped), manual patching (\u0001 backreference literals, lax regex erroneous insertion) — assign responsibility first when troubleshooting.
  2. Baseline principle: geometry and the three-table form are based onactual documents issued by the court(measured court document table width ~7008, repository template 9344 overflows A4).
  3. Six-step QA: geometry → structure (3 tables/row width verification) → checkboxes (including third party both □ empty, agent has ☑ special authorization ☑) → fields (domicile/five elements of the object/amount label + value) → uniqueness (each of the defendant's three elements appears 1 time, \u0001=0) → only after all 20 automated assertions pass may the target document be overwritten.
  4. Iron rules for manual patching: modify text only within cells, repl must not use backreferences, overwrite in one go after passing checks in /tmp.

For the engine-layer to-fix list, see qa-checklist.md Section 4 (intellectual property item rule chain, agent checkbox rules, occurrence string filling, label retention, built-in geometry post-processing, skipped detail printing).

09 Security boundary:--allow-unknown-fields Retain an explicit debug pass-through for genuinely unknown fields; debug artifacts must not be delivered; this flag does not bypass 09 checks for known but unsupported fields, subject shapes, types, enums, or template integrity. DSH does not use this flag.