[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6HWC3TB5C0JAVFXXZ8NZ22G":3,"skill-same:01M6HWC3TB5C0JAVFXXZ8NZ22G":62},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":29,"linkOnly":30,"markdownContent":31,"markdownBody":32,"frontMatter":33,"refName":34,"commitSha":35,"skillDirectory":36,"forksCount":37,"repositoryHtmlUrl":38,"repositoryHomepageUrl":6,"ownerHtmlUrl":39,"ownerBlogUrl":40,"ownerDescription":6,"updatedAt":41,"install":42,"resources":55},"01M6HWC3TB5C0JAVFXXZ8NZ22G","document-gen-resilient-workflow",null,"Multi-engine document generation with cascading PDF fallbacks and robust Unicode handling","HKUDS\u002FAgentPilot","HKUDS","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F118165258?v=4","01M6HW8VRNZP64G0P4MVJW2KKQ","✨Data Intelligence Lab@HKU✨","01M6HW8VWZVHBRHYH3T330PFWV",8029,"MIT","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fbenchmarks\u002Fgdpval\u002Fskills\u002Fdocument-gen-fallback-enhanced-enhanced-2794b4\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28],"workflow","document","document gen resilient workflow","PDF","engine","generation","multi","Unicode","document generation","with","2026-11-10 10:12:30",false,"---\nname: document-gen-resilient-workflow\ndescription: Multi-engine document generation with cascading PDF fallbacks and robust Unicode handling\n---\n\n# Resilient Document Generation Workflow (Multi-Engine Fallback)\n\n## When to Use\n\nUse this skill when document generation tasks fail or when `shell_agent` returns unknown errors, especially for:\n- Generating documents in multiple formats (`.docx`, `.pdf`, `.html`)\n- **PDF generation fails due to missing LaTeX, encoding issues, or tool errors**\n- Documents contain special characters, symbols, or non-ASCII text\n- You need maximum reliability with automatic fallback options\n\n## Core Technique\n\nSplit document generation into discrete, observable steps with **cascading fallbacks** for PDF generation:\n1. **Content creation** → Use `write_file` to create source Markdown\n2. **Unicode sanitization** → Use Python script for reliable character replacement\n3. **Format conversion** → Try multiple PDF engines in sequence until one succeeds\n4. **Verification** → Check file exists, has non-zero size, and is valid\n\n## ⚠️ Unicode & PDF Engine Guide\n\nDifferent PDF engines have different Unicode support:\n\n| Engine | Unicode Support | Best For | Fallback Position |\n|--------|----------------|----------|-------------------|\n| `pdflatex` | Limited (ASCII-focused) | Simple documents | 1st (fastest) |\n| `xelatex` | Full Unicode | Documents with non-ASCII | 2nd |\n| `wkhtmltopdf` | Good Unicode | Web-style documents | 3rd |\n| `reportlab` (Python) | Full control | Programmatic PDFs | 4th |\n| `fpdf2` (Python) | Full control | Simple text PDFs | 5th (last resort) |\n\n### Character Replacement Table\n\n| Character | Issue | Safe Replacement |\n|-----------|-------|------------------|\n| `—` (em dash) | LaTeX incompatibility | `--` |\n| `–` (en dash) | LaTeX incompatibility | `-` |\n| `\" \"` (curly quotes) | Encoding errors | `\" \"` (straight) |\n| `' '` (curly apostrophe) | Encoding errors | `'` (straight) |\n| `…` (ellipsis) | May not render | `...` |\n| `→` `←` `↑` `↓` | LaTeX incompatibility | `->` `\u003C-` `^` `v` |\n| `✓` `✗` | May not render | `[x]` `[ ]` |\n| `★` `●` | May not render | `*` `-` |\n| `©` `®` `™` | May require packages | `(c)` `(r)` `(tm)` |\n| `é` `ñ` `ü` | Font-dependent | Keep for xelatex, replace for pdflatex |\n\n## Step-by-Step Workflow\n\n### Step 1: Create Source Content with write_file\n\nWrite your document content as Markdown to a source file:\n\n```\nwrite_file\npath: \u002Ftmp\u002Fdocument_source.md\ncontent: |\n  # Document Title\n  \n  ## Section 1\n  Content here...\n  \n  ## Section 2\n  More content...\n```\n\n### Step 2: Sanitize Unicode with Python Script\n\n**Create a reusable Python sanitizer** for reliable character replacement:\n\n```\nwrite_file\npath: \u002Ftmp\u002Fsanitize_unicode.py\ncontent: |\n  #!\u002Fusr\u002Fbin\u002Fenv python3\n  import sys\n  import re\n  \n  if len(sys.argv) \u003C 2:\n      print(\"Usage: sanitize_unicode.py \u003Cinput.md> [output.md]\")\n      sys.exit(1)\n  \n  input_file = sys.argv[1]\n  output_file = sys.argv[2] if len(sys.argv) > 2 else input_file.replace('.md', '_sanitized.md')\n  \n  replacements = {\n      '—': '--',    # em dash\n      '–': '-',     # en dash\n      '\"': '\"',     # left curly quote\n      '\"': '\"',     # right curly quote\n      \"'\": \"'\",     # left curly apostrophe\n      \"'\": \"'\",     # right curly apostrophe\n      '…': '...',   # ellipsis\n      '→': '->',    # right arrow\n      '←': '\u003C-',    # left arrow\n      '↑': '^',     # up arrow\n      '↓': 'v',     # down arrow\n      '✓': '[x]',   # checkmark\n      '✗': '[ ]',   # cross\n      '★': '*',     # star\n      '●': '-',     # bullet\n      '©': '(c)',   # copyright\n      '®': '(r)',   # registered\n      '™': '(tm)',  # trademark\n  }\n  \n  with open(input_file, 'r', encoding='utf-8') as f:\n      content = f.read()\n  \n  for old, new in replacements.items():\n      content = content.replace(old, new)\n  \n  with open(output_file, 'w', encoding='utf-8') as f:\n      f.write(content)\n  \n  print(f\"Sanitized: {input_file} -> {output_file}\")\n```\n\n**Apply sanitization for PDF:**\n\n```\nrun_shell\ncommand: python3 \u002Ftmp\u002Fsanitize_unicode.py \u002Ftmp\u002Fdocument_source.md \u002Ftmp\u002Fdocument_source_sanitized.md\n```\n\n**Note**: Keep original for DOCX\u002FHTML (these formats handle Unicode well).\n\n### Step 3: Convert to Target Formats with Cascading Fallbacks\n\n#### For DOCX (from original, no sanitization needed):\n\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source.md -o output.docx\n```\n\n#### For PDF (try multiple engines in sequence):\n\n**Attempt 1: pdflatex (fastest, limited Unicode)**\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source_sanitized.md -o output.pdf --pdf-engine=pdflatex\n```\n\n**If pdflatex fails, Attempt 2: xelatex (full Unicode)**\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source.md -o output.pdf --pdf-engine=xelatex\n```\n\n**If xelatex fails, Attempt 3: wkhtmltopdf (web-based)**\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source.md -o output.pdf --pdf-engine=wkhtmltopdf\n```\n\n**If all pandoc engines fail, Attempt 4: Python reportlab**\n```\nwrite_file\npath: \u002Ftmp\u002Fgenerate_pdf_reportlab.py\ncontent: |\n  #!\u002Fusr\u002Fbin\u002Fenv python3\n  from reportlab.lib.pagesizes import letter\n  from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer\n  from reportlab.lib.styles import getSampleStyleSheet\n  import markdown\n  \n  input_md = '\u002Ftmp\u002Fdocument_source.md'\n  output_pdf = 'output.pdf'\n  \n  with open(input_md, 'r', encoding='utf-8') as f:\n      md_content = f.read()\n  \n  html_content = markdown.markdown(md_content)\n  \n  doc = SimpleDocTemplate(output_pdf, pagesize=letter)\n  styles = getSampleStyleSheet()\n  story = []\n  \n  # Simple HTML to flowables (basic implementation)\n  for line in html_content.split('\\n'):\n      if line.strip():\n          story.append(Paragraph(line, styles['Normal']))\n          story.append(Spacer(1, 6))\n  \n  doc.build(story)\n  print(f\"PDF created: {output_pdf}\")\n```\n\n```\nrun_shell\ncommand: python3 \u002Ftmp\u002Fgenerate_pdf_reportlab.py\n```\n\n**If reportlab fails, Attempt 5: Python fpdf2 (simpler)**\n```\nwrite_file\npath: \u002Ftmp\u002Fgenerate_pdf_fpdf.py\ncontent: |\n  #!\u002Fusr\u002Fbin\u002Fenv python3\n  from fpdf import FPDF\n  \n  input_md = '\u002Ftmp\u002Fdocument_source.md'\n  output_pdf = 'output.pdf'\n  \n  pdf = FPDF()\n  pdf.add_page()\n  pdf.set_font('Helvetica', '', 12)\n  \n  with open(input_md, 'r', encoding='utf-8') as f:\n      for line in f:\n          # Simple line-by-line, escape special chars\n          safe_line = line.encode('latin-1', 'replace').decode('latin-1')\n          pdf.cell(0, 10, safe_line[:180], ln=True)\n  \n  pdf.output(output_pdf)\n  print(f\"PDF created: {output_pdf}\")\n```\n\n```\nrun_shell\ncommand: python3 \u002Ftmp\u002Fgenerate_pdf_fpdf.py\n```\n\n#### For HTML (from original):\n\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source.md -o output.html\n```\n\n### Step 4: Verify Outputs with Multiple Checks\n\n**Check 1: Files exist and have size**\n```\nrun_shell\ncommand: ls -lh output.docx output.pdf output.html 2>\u002Fdev\u002Fnull && echo \"FILES_OK\" || echo \"FILES_MISSING\"\n```\n\n**Check 2: Validate PDF is not corrupted**\n```\nrun_shell\ncommand: python3 -c \"import fitz; doc=fitz.open('output.pdf'); print(f'PDF_VALID: {doc.page_count} pages')\" 2>\u002Fdev\u002Fnull || echo \"PDF_CHECK_SKIPPED\"\n```\n\n**Check 3: Validate DOCX**\n```\nrun_shell\ncommand: python3 -c \"from docx import Document; d=Document('output.docx'); print(f'DOCX_VALID: {len(d.paragraphs)} paragraphs')\" 2>\u002Fdev\u002Fnull || echo \"DOCX_CHECK_SKIPPED\"\n```\n\n**Check 4: Read back content for manual verification**\n```\nread_file\nfiletype: md\nfile_path: output.html\n```\n\n## Complete Example\n\n```markdown\n# Generate Negotiation Strategy Document (Resilient Workflow)\n\n## Step 1: Write Markdown source\nwrite_file\npath: \u002Ftmp\u002Fnegotiation_strategy.md\ncontent: |\n  # Negotiation Strategy\n  \n  ## Executive Summary\n  Content with original unicode characters...\n  \n  ## Resolution Path\n  More content...\n\n## Step 2: Sanitize for PDF\nwrite_file\npath: \u002Ftmp\u002Fsanitize_unicode.py\ncontent: |\n  [Python sanitizer script from Step 2 above]\n\nrun_shell\ncommand: python3 \u002Ftmp\u002Fsanitize_unicode.py \u002Ftmp\u002Fnegotiation_strategy.md \u002Ftmp\u002Fnegotiation_strategy_sanitized.md\n\n## Step 3: Convert to DOCX (original, Unicode-safe format)\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fnegotiation_strategy.md -o negotiation_strategy.docx\n\n## Step 4: Convert to PDF (try pdflatex first)\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fnegotiation_strategy_sanitized.md -o negotiation_strategy.pdf --pdf-engine=pdflatex\n\n## Step 4b: If pdflatex failed, try xelatex\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fnegotiation_strategy.md -o negotiation_strategy.pdf --pdf-engine=xelatex\n\n## Step 4c: If xelatex failed, try wkhtmltopdf\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fnegotiation_strategy.md -o negotiation_strategy.pdf --pdf-engine=wkhtmltopdf\n\n## Step 5: Convert to HTML (original)\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fnegotiation_strategy.md -o negotiation_strategy.html\n\n## Step 6: Verify all outputs\nrun_shell\ncommand: ls -lh negotiation_strategy.* && echo \"ALL_FILES_CREATED\"\n\nrun_shell\ncommand: python3 -c \"import fitz; d=fitz.open('negotiation_strategy.pdf'); print(f'PDF: {d.page_count} pages')\"\n```\n\n## Advantages Over shell_agent\n\n| Aspect | shell_agent | Resilient Manual Workflow |\n|--------|-------------|---------------------------|\n| Error visibility | Opaque, may retry silently | Each step shows explicit output |\n| PDF fallback | May give up after first failure | Cascading engine attempts |\n| Debugging | Hard to isolate | Clear which engine\u002Fstep failed |\n| Unicode control | Agent-dependent | You control sanitization |\n| Recovery | Automatic but may loop | Manual intervention at known points |\n| Tool requirements | Assumes pandoc works | Multiple engine options |\n\n## Troubleshooting by Error Type\n\n### \"LaTeX not found\" or \"pdflatex: command not found\"\n- **Solution**: Try `--pdf-engine=xelatex` or `--pdf-engine=wkhtmltopdf`\n- **Install LaTeX**: `apt-get install texlive-latex-recommended texlive-fonts-recommended`\n- **Or fallback to Python**: Use reportlab\u002Ffpdf2 approach\n\n### \"Encoding error\" or \"UnicodeDecodeError\"\n- **Solution**: Use sanitized markdown file (Step 2)\n- **Or**: Add `-f markdown+utf8` to pandoc command\n- **Or**: Try xelatex engine (better Unicode support)\n\n### \"wkhtmltopdf not found\"\n- **Solution**: Install via `apt-get install wkhtmltopdf` or fallback to Python\n\n### \"ModuleNotFoundError: No module named 'reportlab'\"\n- **Solution**: `pip install reportlab` or fallback to fpdf2\n\n### \"Invalid PDF\" or corrupted output\n- **Diagnosis**: Run `pdftotext output.pdf -` to check if text extracts\n- **Solution**: Try different PDF engine from fallback chain\n\n### DOCX formatting issues\n- **Solution**: Add `--reference-doc=template.docx` for custom styles\n- **Or**: Fix markdown structure in source file\n\n### All pandoc commands fail\n- **Check**: `pandoc --version` to verify installation\n- **Fallback**: Use Python-based PDF generation (reportlab\u002Ffpdf2)\n- **For DOCX**: Try `python-docx` library directly\n\n## Pre-Flight Checks (Optional but Recommended)\n\nBefore starting, verify required tools are available:\n\n```\nrun_shell\ncommand: pandoc --version && echo \"PANDOC_OK\" || echo \"PANDOC_MISSING\"\nrun_shell\ncommand: pdflatex --version && echo \"PDFLATEX_OK\" || echo \"PDFLATEX_MISSING\"\nrun_shell\ncommand: python3 -c \"import reportlab\" && echo \"REPORTLAB_OK\" || echo \"REPORTLAB_MISSING\"\n```\n\nThis helps you know which fallback path will be needed.\n\n## Related Skills\n\n- `document-gen-unicode-safe`: Parent skill with basic Unicode guidance\n- `document-gen-fallback`: Original fallback without Unicode or multi-engine support\n- Use this skill when you need maximum reliability with automatic fallbacks\n\n## When to Return to shell_agent\n\nAfter manually completing this workflow successfully once for a document type, you can attempt `shell_agent` for similar tasks with reduced risk (you now know the fallback path). However, for critical documents or those with heavy Unicode content, consider always using this resilient manual workflow.\n","# Resilient Document Generation Workflow (Multi-Engine Fallback)\n\n## When to Use\n\nUse this skill when document generation tasks fail or when `shell_agent` returns unknown errors, especially for:\n- Generating documents in multiple formats (`.docx`, `.pdf`, `.html`)\n- **PDF generation fails due to missing LaTeX, encoding issues, or tool errors**\n- Documents contain special characters, symbols, or non-ASCII text\n- You need maximum reliability with automatic fallback options\n\n## Core Technique\n\nSplit document generation into discrete, observable steps with **cascading fallbacks** for PDF generation:\n1. **Content creation** → Use `write_file` to create source Markdown\n2. **Unicode sanitization** → Use Python script for reliable character replacement\n3. **Format conversion** → Try multiple PDF engines in sequence until one succeeds\n4. **Verification** → Check file exists, has non-zero size, and is valid\n\n## ⚠️ Unicode & PDF Engine Guide\n\nDifferent PDF engines have different Unicode support:\n\n| Engine | Unicode Support | Best For | Fallback Position |\n|--------|----------------|----------|-------------------|\n| `pdflatex` | Limited (ASCII-focused) | Simple documents | 1st (fastest) |\n| `xelatex` | Full Unicode | Documents with non-ASCII | 2nd |\n| `wkhtmltopdf` | Good Unicode | Web-style documents | 3rd |\n| `reportlab` (Python) | Full control | Programmatic PDFs | 4th |\n| `fpdf2` (Python) | Full control | Simple text PDFs | 5th (last resort) |\n\n### Character Replacement Table\n\n| Character | Issue | Safe Replacement |\n|-----------|-------|------------------|\n| `—` (em dash) | LaTeX incompatibility | `--` |\n| `–` (en dash) | LaTeX incompatibility | `-` |\n| `\" \"` (curly quotes) | Encoding errors | `\" \"` (straight) |\n| `' '` (curly apostrophe) | Encoding errors | `'` (straight) |\n| `…` (ellipsis) | May not render | `...` |\n| `→` `←` `↑` `↓` | LaTeX incompatibility | `->` `\u003C-` `^` `v` |\n| `✓` `✗` | May not render | `[x]` `[ ]` |\n| `★` `●` | May not render | `*` `-` |\n| `©` `®` `™` | May require packages | `(c)` `(r)` `(tm)` |\n| `é` `ñ` `ü` | Font-dependent | Keep for xelatex, replace for pdflatex |\n\n## Step-by-Step Workflow\n\n### Step 1: Create Source Content with write_file\n\nWrite your document content as Markdown to a source file:\n\n```\nwrite_file\npath: \u002Ftmp\u002Fdocument_source.md\ncontent: |\n  # Document Title\n  \n  ## Section 1\n  Content here...\n  \n  ## Section 2\n  More content...\n```\n\n### Step 2: Sanitize Unicode with Python Script\n\n**Create a reusable Python sanitizer** for reliable character replacement:\n\n```\nwrite_file\npath: \u002Ftmp\u002Fsanitize_unicode.py\ncontent: |\n  #!\u002Fusr\u002Fbin\u002Fenv python3\n  import sys\n  import re\n  \n  if len(sys.argv) \u003C 2:\n      print(\"Usage: sanitize_unicode.py \u003Cinput.md> [output.md]\")\n      sys.exit(1)\n  \n  input_file = sys.argv[1]\n  output_file = sys.argv[2] if len(sys.argv) > 2 else input_file.replace('.md', '_sanitized.md')\n  \n  replacements = {\n      '—': '--',    # em dash\n      '–': '-',     # en dash\n      '\"': '\"',     # left curly quote\n      '\"': '\"',     # right curly quote\n      \"'\": \"'\",     # left curly apostrophe\n      \"'\": \"'\",     # right curly apostrophe\n      '…': '...',   # ellipsis\n      '→': '->',    # right arrow\n      '←': '\u003C-',    # left arrow\n      '↑': '^',     # up arrow\n      '↓': 'v',     # down arrow\n      '✓': '[x]',   # checkmark\n      '✗': '[ ]',   # cross\n      '★': '*',     # star\n      '●': '-',     # bullet\n      '©': '(c)',   # copyright\n      '®': '(r)',   # registered\n      '™': '(tm)',  # trademark\n  }\n  \n  with open(input_file, 'r', encoding='utf-8') as f:\n      content = f.read()\n  \n  for old, new in replacements.items():\n      content = content.replace(old, new)\n  \n  with open(output_file, 'w', encoding='utf-8') as f:\n      f.write(content)\n  \n  print(f\"Sanitized: {input_file} -> {output_file}\")\n```\n\n**Apply sanitization for PDF:**\n\n```\nrun_shell\ncommand: python3 \u002Ftmp\u002Fsanitize_unicode.py \u002Ftmp\u002Fdocument_source.md \u002Ftmp\u002Fdocument_source_sanitized.md\n```\n\n**Note**: Keep original for DOCX\u002FHTML (these formats handle Unicode well).\n\n### Step 3: Convert to Target Formats with Cascading Fallbacks\n\n#### For DOCX (from original, no sanitization needed):\n\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source.md -o output.docx\n```\n\n#### For PDF (try multiple engines in sequence):\n\n**Attempt 1: pdflatex (fastest, limited Unicode)**\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source_sanitized.md -o output.pdf --pdf-engine=pdflatex\n```\n\n**If pdflatex fails, Attempt 2: xelatex (full Unicode)**\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source.md -o output.pdf --pdf-engine=xelatex\n```\n\n**If xelatex fails, Attempt 3: wkhtmltopdf (web-based)**\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source.md -o output.pdf --pdf-engine=wkhtmltopdf\n```\n\n**If all pandoc engines fail, Attempt 4: Python reportlab**\n```\nwrite_file\npath: \u002Ftmp\u002Fgenerate_pdf_reportlab.py\ncontent: |\n  #!\u002Fusr\u002Fbin\u002Fenv python3\n  from reportlab.lib.pagesizes import letter\n  from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer\n  from reportlab.lib.styles import getSampleStyleSheet\n  import markdown\n  \n  input_md = '\u002Ftmp\u002Fdocument_source.md'\n  output_pdf = 'output.pdf'\n  \n  with open(input_md, 'r', encoding='utf-8') as f:\n      md_content = f.read()\n  \n  html_content = markdown.markdown(md_content)\n  \n  doc = SimpleDocTemplate(output_pdf, pagesize=letter)\n  styles = getSampleStyleSheet()\n  story = []\n  \n  # Simple HTML to flowables (basic implementation)\n  for line in html_content.split('\\n'):\n      if line.strip():\n          story.append(Paragraph(line, styles['Normal']))\n          story.append(Spacer(1, 6))\n  \n  doc.build(story)\n  print(f\"PDF created: {output_pdf}\")\n```\n\n```\nrun_shell\ncommand: python3 \u002Ftmp\u002Fgenerate_pdf_reportlab.py\n```\n\n**If reportlab fails, Attempt 5: Python fpdf2 (simpler)**\n```\nwrite_file\npath: \u002Ftmp\u002Fgenerate_pdf_fpdf.py\ncontent: |\n  #!\u002Fusr\u002Fbin\u002Fenv python3\n  from fpdf import FPDF\n  \n  input_md = '\u002Ftmp\u002Fdocument_source.md'\n  output_pdf = 'output.pdf'\n  \n  pdf = FPDF()\n  pdf.add_page()\n  pdf.set_font('Helvetica', '', 12)\n  \n  with open(input_md, 'r', encoding='utf-8') as f:\n      for line in f:\n          # Simple line-by-line, escape special chars\n          safe_line = line.encode('latin-1', 'replace').decode('latin-1')\n          pdf.cell(0, 10, safe_line[:180], ln=True)\n  \n  pdf.output(output_pdf)\n  print(f\"PDF created: {output_pdf}\")\n```\n\n```\nrun_shell\ncommand: python3 \u002Ftmp\u002Fgenerate_pdf_fpdf.py\n```\n\n#### For HTML (from original):\n\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source.md -o output.html\n```\n\n### Step 4: Verify Outputs with Multiple Checks\n\n**Check 1: Files exist and have size**\n```\nrun_shell\ncommand: ls -lh output.docx output.pdf output.html 2>\u002Fdev\u002Fnull && echo \"FILES_OK\" || echo \"FILES_MISSING\"\n```\n\n**Check 2: Validate PDF is not corrupted**\n```\nrun_shell\ncommand: python3 -c \"import fitz; doc=fitz.open('output.pdf'); print(f'PDF_VALID: {doc.page_count} pages')\" 2>\u002Fdev\u002Fnull || echo \"PDF_CHECK_SKIPPED\"\n```\n\n**Check 3: Validate DOCX**\n```\nrun_shell\ncommand: python3 -c \"from docx import Document; d=Document('output.docx'); print(f'DOCX_VALID: {len(d.paragraphs)} paragraphs')\" 2>\u002Fdev\u002Fnull || echo \"DOCX_CHECK_SKIPPED\"\n```\n\n**Check 4: Read back content for manual verification**\n```\nread_file\nfiletype: md\nfile_path: output.html\n```\n\n## Complete Example\n\n```markdown\n# Generate Negotiation Strategy Document (Resilient Workflow)\n\n## Step 1: Write Markdown source\nwrite_file\npath: \u002Ftmp\u002Fnegotiation_strategy.md\ncontent: |\n  # Negotiation Strategy\n  \n  ## Executive Summary\n  Content with original unicode characters...\n  \n  ## Resolution Path\n  More content...\n\n## Step 2: Sanitize for PDF\nwrite_file\npath: \u002Ftmp\u002Fsanitize_unicode.py\ncontent: |\n  [Python sanitizer script from Step 2 above]\n\nrun_shell\ncommand: python3 \u002Ftmp\u002Fsanitize_unicode.py \u002Ftmp\u002Fnegotiation_strategy.md \u002Ftmp\u002Fnegotiation_strategy_sanitized.md\n\n## Step 3: Convert to DOCX (original, Unicode-safe format)\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fnegotiation_strategy.md -o negotiation_strategy.docx\n\n## Step 4: Convert to PDF (try pdflatex first)\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fnegotiation_strategy_sanitized.md -o negotiation_strategy.pdf --pdf-engine=pdflatex\n\n## Step 4b: If pdflatex failed, try xelatex\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fnegotiation_strategy.md -o negotiation_strategy.pdf --pdf-engine=xelatex\n\n## Step 4c: If xelatex failed, try wkhtmltopdf\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fnegotiation_strategy.md -o negotiation_strategy.pdf --pdf-engine=wkhtmltopdf\n\n## Step 5: Convert to HTML (original)\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fnegotiation_strategy.md -o negotiation_strategy.html\n\n## Step 6: Verify all outputs\nrun_shell\ncommand: ls -lh negotiation_strategy.* && echo \"ALL_FILES_CREATED\"\n\nrun_shell\ncommand: python3 -c \"import fitz; d=fitz.open('negotiation_strategy.pdf'); print(f'PDF: {d.page_count} pages')\"\n```\n\n## Advantages Over shell_agent\n\n| Aspect | shell_agent | Resilient Manual Workflow |\n|--------|-------------|---------------------------|\n| Error visibility | Opaque, may retry silently | Each step shows explicit output |\n| PDF fallback | May give up after first failure | Cascading engine attempts |\n| Debugging | Hard to isolate | Clear which engine\u002Fstep failed |\n| Unicode control | Agent-dependent | You control sanitization |\n| Recovery | Automatic but may loop | Manual intervention at known points |\n| Tool requirements | Assumes pandoc works | Multiple engine options |\n\n## Troubleshooting by Error Type\n\n### \"LaTeX not found\" or \"pdflatex: command not found\"\n- **Solution**: Try `--pdf-engine=xelatex` or `--pdf-engine=wkhtmltopdf`\n- **Install LaTeX**: `apt-get install texlive-latex-recommended texlive-fonts-recommended`\n- **Or fallback to Python**: Use reportlab\u002Ffpdf2 approach\n\n### \"Encoding error\" or \"UnicodeDecodeError\"\n- **Solution**: Use sanitized markdown file (Step 2)\n- **Or**: Add `-f markdown+utf8` to pandoc command\n- **Or**: Try xelatex engine (better Unicode support)\n\n### \"wkhtmltopdf not found\"\n- **Solution**: Install via `apt-get install wkhtmltopdf` or fallback to Python\n\n### \"ModuleNotFoundError: No module named 'reportlab'\"\n- **Solution**: `pip install reportlab` or fallback to fpdf2\n\n### \"Invalid PDF\" or corrupted output\n- **Diagnosis**: Run `pdftotext output.pdf -` to check if text extracts\n- **Solution**: Try different PDF engine from fallback chain\n\n### DOCX formatting issues\n- **Solution**: Add `--reference-doc=template.docx` for custom styles\n- **Or**: Fix markdown structure in source file\n\n### All pandoc commands fail\n- **Check**: `pandoc --version` to verify installation\n- **Fallback**: Use Python-based PDF generation (reportlab\u002Ffpdf2)\n- **For DOCX**: Try `python-docx` library directly\n\n## Pre-Flight Checks (Optional but Recommended)\n\nBefore starting, verify required tools are available:\n\n```\nrun_shell\ncommand: pandoc --version && echo \"PANDOC_OK\" || echo \"PANDOC_MISSING\"\nrun_shell\ncommand: pdflatex --version && echo \"PDFLATEX_OK\" || echo \"PDFLATEX_MISSING\"\nrun_shell\ncommand: python3 -c \"import reportlab\" && echo \"REPORTLAB_OK\" || echo \"REPORTLAB_MISSING\"\n```\n\nThis helps you know which fallback path will be needed.\n\n## Related Skills\n\n- `document-gen-unicode-safe`: Parent skill with basic Unicode guidance\n- `document-gen-fallback`: Original fallback without Unicode or multi-engine support\n- Use this skill when you need maximum reliability with automatic fallbacks\n\n## When to Return to shell_agent\n\nAfter manually completing this workflow successfully once for a document type, you can attempt `shell_agent` for similar tasks with reduced risk (you now know the fallback path). However, for critical documents or those with heavy Unicode content, consider always using this resilient manual workflow.\n",{"name":5,"description":7},"main","6b84b0689ca0d9e7b1e4061188ff6b60758e0f8a","openspace\u002Fbenchmarks\u002Fgdpval\u002Fskills\u002Fdocument-gen-fallback-enhanced-enhanced-2794b4",944,"https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot","https:\u002F\u002Fgithub.com\u002FHKUDS","https:\u002F\u002Fsites.google.com\u002Fview\u002Fchaoh","2026-11-12 22:26:39",{"source":8,"skillName":5,"commands":43,"prompt":53,"zipAvailable":54},[44,47,50],{"tool":45,"command":46},"npx","npx skills add HKUDS\u002FAgentPilot --skill document-gen-resilient-workflow",{"tool":48,"command":49},"bunx","bunx skills add HKUDS\u002FAgentPilot --skill document-gen-resilient-workflow",{"tool":51,"command":52},"pnpm","pnpm dlx skills add HKUDS\u002FAgentPilot --skill document-gen-resilient-workflow","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fbenchmarks\u002Fgdpval\u002Fskills\u002Fdocument-gen-fallback-enhanced-enhanced-2794b4\u002FSKILL.md",true,[56],{"path":57,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":60,"sourceHtmlUrl":61},".skill_id","OTHER","其他",60,"https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fbenchmarks\u002Fgdpval\u002Fskills\u002Fdocument-gen-fallback-enhanced-enhanced-2794b4\u002F.skill_id",[63,82,101,121,144,167],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":29},"01M6HYB297NDABRERJRVG0K8R0","agentpilot","Set up AgentPilot and use its single entry to prepare missing inputs and run configured RSI experiments. Use when the user requests AgentPilot installation or work with AgentPilot.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fplugins\u002Fagentpilot\u002Fskills\u002Fagentpilot\u002FSKILL.md",[],[65,70,71,28,72,73,74,75,76,77,78,79,80,81],"prepare","requests","missing","installation","rsi","up","use","user","work","SET","run","experiments",{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":29},"01M6HYAYWXTTE1J7DJM0MFNQ4H","remember","Review auto-memory entries and propose promotions to OPENSPACE.md, OPENSPACE.local.md, or retained auto-memory topics; detect duplicates, stale facts, conflicts, and ambiguous entries before making changes.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fskills\u002Fremember\u002FSKILL.md",[],[84,89,90,91,92,93,94,95,96,97,98,99,100],"memory","review","auto","openspace","changes","facts","detect","entries","local","conflicts","stale","duplicates",{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":29},"01M6HYAVMPM4SBDV60R2B5HPV8","skill-discovery","Search reusable OpenSpace skills locally, and browse cloud packages step by step when a cloud skill may help. Reusing proven skills saves tokens, improves reliability, and extends your capabilities beyond built-in tools.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fhost_skills\u002Fskill-discovery\u002FSKILL.md",[],[108,109,110,92,111,112,113,114,115,116,117,118,119,120],"skill discovery","discovery","reusable","step by step","tokens","packages","help","cloud","reliability","capabilities","browse","search","Tools",{"skillNo":122,"name":123,"nameZh":6,"description":124,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":125,"categories":126,"keywords":127,"publishedAt":29},"01M6HYAR811B3RB0M50RBEDGN6","delegate-task","Delegate tasks to OpenSpace — a full-stack autonomous worker for coding, DevOps, web research, and desktop automation, backed by an extensive MCP tool and skill library. Skills auto-improve through use, reducing token consumption over time. A cloud community lets agents share and collectively evolve reusable skills.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Fopenspace\u002Fhost_skills\u002Fdelegate-task\u002FSKILL.md",[],[128,129,130,92,131,132,133,134,135,110,91,76,136,137,138,139,140,141,142,143],"delegate","task","delegate task","time","improve","desktop automation","worker","community","autonomous","tool","stack","for","share","tasks","automation","MCP",{"skillNo":145,"name":146,"nameZh":6,"description":147,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":148,"categories":149,"keywords":150,"publishedAt":29},"01M6HYAM9FSGV6E52AYENDQXYH","write-special-chars-ts-check","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) using a Python heredoc script, plus a reliable TypeScript type-checking step that filters output to only the newly-written files to avoid being misled by pre-existing errors.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-ts-check\u002FSKILL.md",[],[151,152,153,154,155,156,157,158,159,160,161,162,163,164,139,165,166],"write special chars ts check","write","check","type","files","filters","only","template","file","python","typescript","output","Existing","type-checking","errors","script",{"skillNo":168,"name":169,"nameZh":6,"description":170,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":171,"categories":172,"keywords":173,"publishedAt":29},"01M6HYAH05HGV7SVWSVR8PJRQD","write-special-chars-readback","Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) using a Python heredoc script, with mandatory post-write verification via read_file and cleanup of \u002Ftmp helper scripts.","https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fshowcase\u002Fskills\u002Fwrite-special-chars-readback\u002FSKILL.md",[],[174,175,152,28,139,166,176,177,178,179,180,158,159,181,182,160],"write special chars readback","readback","helper","post","via","scripts","read","verification","cleanup"]