[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6HXGXMZ99ZNQSH0TGBTARNA":3,"skill-same:01M6HXGXMZ99ZNQSH0TGBTARNA":79},{"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":26,"publishedAt":40,"linkOnly":41,"markdownContent":42,"markdownBody":43,"frontMatter":44,"refName":45,"commitSha":46,"skillDirectory":47,"forksCount":48,"repositoryHtmlUrl":49,"repositoryHomepageUrl":6,"ownerHtmlUrl":50,"ownerBlogUrl":51,"ownerDescription":6,"updatedAt":52,"install":53,"resources":66},"01M6HXGXMZ99ZNQSH0TGBTARNA","document-gen-resilient-workflow",null,"Robust document generation with engine fallback chain, error diagnostics, and Python alternatives","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\u002Flegacy\u002Fv1\u002Fgdpval_bench\u002Fskills\u002Fdocument-gen-fallback-enhanced-enhanced\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000002","文档处理","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",[27,28,29,30,31,32,33,34,35,36,37,38,39],"workflow","document","document gen resilient workflow","document gen resilient","python","diagnostics","engine","fallback","generation","chain","error","document generation","with","2026-11-10 10:12:30",false,"---\nname: document-gen-resilient-workflow\ndescription: Robust document generation with engine fallback chain, error diagnostics, and Python alternatives\n---\n\n# Resilient Document Generation Workflow\n\n## When to Use\n\nUse this skill when document generation tasks encounter tool errors or failures, especially:\n- `run_shell` commands return 'unknown error' without diagnostic details\n- PDF generation fails with LaTeX encoding or missing engine errors\n- You need fallback options when primary conversion methods fail\n- **Workspace or path issues** cause file access problems\n- Unicode\u002Fspecial characters cause rendering issues in PDF output\n- `shell_agent` has failed multiple times on similar tasks\n\n## Core Technique\n\nSplit document generation into **observable, verifiable steps** with explicit error capture and progressive fallback:\n\n1. **Validate workspace** → Confirm current directory and write permissions\n2. **Pre-flight checks** → Verify required tools (pandoc, LaTeX engines) are available\n3. **Content creation** → Use `write_file` for source Markdown with full visibility\n4. **Unicode sanitization** → Preprocess for PDF conversion when needed\n5. **Progressive conversion** → Try multiple engines\u002Fmethods until one succeeds\n6. **Explicit error capture** → Redirect stderr to diagnose failures\n7. **Verification** → Confirm output files exist and are readable\n\n## ⚠️ Critical: Tool Error Patterns\n\n**'unknown error' from run_shell**: This typically indicates:\n- Sandbox execution context issues (not the command itself)\n- Missing stderr capture preventing diagnosis\n- Transient file access problems\n\n**Solution**: Use explicit error capture with `2>&1` and verify tool availability first:\n```\nrun_shell\ncommand: pandoc --version 2>&1 || echo \"PANDOC NOT AVAILABLE\"\n```\n\n## Pre-Flight Checklist\n\nBefore starting conversion, verify your environment:\n\n```markdown\n## Pre-Flight Checks\n\n### Check 1: Verify working directory\nrun_shell\ncommand: pwd && ls -la\n\n### Check 2: Verify pandoc availability\nrun_shell\ncommand: pandoc --version 2>&1 | head -3 || echo \"PANDOC MISSING\"\n\n### Check 3: Check LaTeX engines\nrun_shell\ncommand: which pdflatex xelatex wkhtmltopdf 2>&1 || echo \"Some engines missing\"\n\n### Check 4: Check Python libraries (fallback option)\nrun_shell\ncommand: python3 -c \"import fpdf; print('fpdf OK')\" 2>&1 || echo \"fpdf missing\"\nrun_shell\ncommand: python3 -c \"import docx; print('python-docx OK')\" 2>&1 || echo \"python-docx missing\"\n```\n\n## Complete Step-by-Step Workflow\n\n### Step 1: Validate Workspace\n\nConfirm you're in the correct directory and can write files:\n\n```\nrun_shell\ncommand: pwd && echo \"Test write\" > \u002Ftmp\u002Fworkspace_test_$$.txt && ls -la \u002Ftmp\u002Fworkspace_test_$$.txt && rm \u002Ftmp\u002Fworkspace_test_$$.txt\n```\n\n**If this fails**, you may have directory permission issues. Use absolute paths for all files.\n\n### Step 2: Create Source Content with write_file\n\nWrite 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\n### Step 3: Unicode Sanitization (PDF Only)\n\n**Only needed for PDF conversion via LaTeX engines**. DOCX and HTML handle Unicode natively.\n\nCreate a sanitized version replacing LaTeX-problematic characters:\n\n```\nwrite_file\npath: \u002Ftmp\u002Fdocument_source_sanitized.md\ncontent: |\n  # Document Title\n  \n  [Same content with: em-dash → --, curly quotes → straight, → arrows → text, etc.]\n```\n\n**Common replacements** (see full table below):\n| Original | Replace With |\n|----------|--------------|\n| `—` (em dash) | `--` |\n| `\" \"` (curly quotes) | `\" \"` (straight) |\n| `…` (ellipsis) | `...` |\n| `→` `←` (arrows) | `->` `\u003C-` |\n| `✓` `✗` | `[x]` `[ ]` |\n| `©` `®` `™` | `(c)` `(r)` `(tm)` |\n\n**Alternative**: Use sanitization script (see Scripts section below).\n\n### Step 4: Progressive Format Conversion\n\nTry multiple methods in order of preference. **Capture stderr explicitly** for diagnosis.\n\n#### Method A: DOCX Conversion (Most Reliable)\n\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source.md -o output.docx 2>&1 && echo \"SUCCESS\" || echo \"FAILED: $?\"\n```\n\nIf this fails, try with explicit UTF-8 flag:\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source.md -f markdown+utf8 -o output.docx 2>&1\n```\n\n#### Method B: PDF Conversion (Progressive Fallback)\n\n**Try engines in this order** until one succeeds:\n\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source_sanitized.md -o output.pdf 2>&1 | tee \u002Ftmp\u002Fpdf_error.log && echo \"PDF SUCCESS\"\n```\n\nIf Method B fails, check error log and try next engine:\n\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source_sanitized.md --pdf-engine=xelatex -o output.pdf 2>&1 | tee \u002Ftmp\u002Fpdf_error.log && echo \"PDF SUCCESS\"\n```\n\nIf xelatex fails:\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source_sanitized.md --pdf-engine=wkhtmltopdf -o output.pdf 2>&1 | tee \u002Ftmp\u002Fpdf_error.log && echo \"PDF SUCCESS\"\n```\n\n#### Method C: Python Library Fallback (When pandoc Unavailable)\n\nIf all pandoc methods fail, use Python libraries:\n\n**Option C1: FPDF2 for PDF**\n```\nexecute_code_sandbox\nlanguage: python\ncode: |\n  from fpdf import FPDF\n  \n  pdf = FPDF()\n  pdf.add_page()\n  pdf.set_font('Arial', 'B', 16)\n  pdf.cell(40, 10, 'Document Title')\n  pdf.ln(20)\n  pdf.set_font('Arial', '', 12)\n  pdf.multi_cell(0, 10, 'Your content here...')\n  pdf.output('output.pdf')\n  print('PDF created successfully')\n```\n\n**Option C2: python-docx for DOCX**\n```\nexecute_code_sandbox\nlanguage: python\ncode: |\n  from docx import Document\n  \n  doc = Document()\n  doc.add_heading('Document Title', 0)\n  doc.add_paragraph('Your content here...')\n  doc.save('output.docx')\n  print('DOCX created successfully')\n```\n\n### Step 5: Verify Output Files\n\nDon't just check existence—verify files are valid:\n\n```\nrun_shell\ncommand: ls -lh output.* 2>&1\n```\n\n```\nrun_shell\ncommand: file output.docx output.pdf 2>&1\n```\n\nFor DOCX, verify content:\n```\nrun_shell\ncommand: unzip -p output.docx word\u002Fdocument.xml 2>&1 | head -50 || echo \"Cannot read DOCX\"\n```\n\nFor PDF, check page count:\n```\nrun_shell\ncommand: pdfinfo output.pdf 2>&1 | grep Pages || echo \"pdfinfo not available\"\n```\n\nAlternative verification via Python:\n```\nexecute_code_sandbox\ncode: |\n  import os\n  for f in ['output.docx', 'output.pdf', 'output.html']:\n    if os.path.exists(f):\n      size = os.path.getsize(f)\n      print(f'{f}: {size} bytes')\n    else:\n      print(f'{f}: NOT FOUND')\n```\n\n## Complete Example: Generating a Report\n\n```markdown\n# Generate Quarterly Report (DOCX + PDF)\n\n## Step 1: Pre-flight checks\nrun_shell\ncommand: pandoc --version 2>&1 | head -1\n\n## Step 2: Write Markdown source\nwrite_file\npath: \u002Ftmp\u002Fquarterly_report.md\ncontent: |\n  # Quarterly Business Report\n  \n  ## Executive Summary\n  Q4 performance exceeded expectations...\n  \n  ## Key Metrics\n  - Revenue: $1.2M\n  - Growth: 15%\n  \n  ## Recommendations\n  Continue current strategy...\n\n## Step 3: Create sanitized version for PDF\nwrite_file\npath: \u002Ftmp\u002Fquarterly_report_sanitized.md\ncontent: |\n  # Quarterly Business Report\n  \n  ## Executive Summary\n  Q4 performance exceeded expectations...\n  \n  [Rest of content with special chars replaced]\n\n## Step 4: Generate DOCX\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fquarterly_report.md -o quarterly_report.docx 2>&1 && echo \"DOCX OK\"\n\n## Step 5: Generate PDF (try xelatex for Unicode safety)\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fquarterly_report_sanitized.md --pdf-engine=xelatex -o quarterly_report.pdf 2>&1 && echo \"PDF OK\"\n\n## Step 6: Verify outputs\nrun_shell\ncommand: ls -lh quarterly_report.* && file quarterly_report.*\n```\n\n## Full Unicode Replacement Table\n\n| Character | Unicode | Issue | Safe Replacement |\n|-----------|---------|-------|------------------|\n| `—` | U+2014 | LaTeX incompatible | `--` |\n| `–` | U+2013 | LaTeX incompatible | `-` |\n| `\"` `\"` | U+201C\u002FU+201D | Encoding errors | `\"` (straight) |\n| `'` `'` | U+2018\u002FU+2019 | Encoding errors | `'` (straight) |\n| `…` | U+2026 | May not render | `...` |\n| `→` | U+2192 | LaTeX incompatible | `->` or `to` |\n| `←` | U+2190 | LaTeX incompatible | `\u003C-` |\n| `↑` `↓` | U+2191\u002FU+2193 | LaTeX incompatible | `^` `v` |\n| `•` | U+2022 | Font-dependent | `-` or `*` |\n| `✓` | U+2713 | May not render | `[x]` |\n| `✗` | U+2717 | May not render | `[ ]` |\n| `★` `●` | U+2605\u002FU+25CF | May not render | `*` `-` |\n| `©` | U+00A9 | May require packages | `(c)` |\n| `®` | U+00AE | May require packages | `(r)` |\n| `™` | U+2122 | May require packages | `(tm)` |\n| `é` `ñ` `ü` | Various | Font-dependent | Use xelatex or replace |\n\n## Reusable Sanitization Script\n\nSave this script for repeated use:\n\n```bash\n#!\u002Fbin\u002Fbash\n# sanitize_for_pdf.sh - Replace problematic unicode chars for LaTeX\u002FPDF\nset -e\nif [ -z \"$1\" ]; then\n  echo \"Usage: $0 \u003Cinput.md> [output.md]\"\n  exit 1\nfi\nINPUT=\"$1\"\nOUTPUT=\"${2:-${1%.md}_sanitized.md}\"\n\nsed -e 's\u002F—\u002F--\u002Fg' \\\n    -e 's\u002F–\u002F-\u002Fg' \\\n    -e 's\u002F\"\\([^\"]*\\)\"\u002F\"\\1\"\u002Fg' \\\n    -e \"s\u002F'\\([^']*\\)'\u002F\\'\\1\\'\u002Fg\" \\\n    -e 's\u002F…\u002F...\u002Fg' \\\n    -e 's\u002F→\u002F->\u002Fg' \\\n    -e 's\u002F←\u002F\u003C-\u002Fg' \\\n    -e 's\u002F↑\u002F^\u002Fg' \\\n    -e 's\u002F↓\u002Fv\u002Fg' \\\n    -e 's\u002F•\u002F-\u002Fg' \\\n    -e 's\u002F✓\u002F[x]\u002Fg' \\\n    -e 's\u002F✗\u002F[ ]\u002Fg' \\\n    -e 's\u002F★\u002F*\u002Fg' \\\n    -e 's\u002F©\u002F(c)\u002Fg' \\\n    -e 's\u002F®\u002F(r)\u002Fg' \\\n    -e 's\u002F™\u002F(tm)\u002Fg' \\\n    \"$INPUT\" > \"$OUTPUT\"\n\necho \"Sanitized: $INPUT -> $OUTPUT\"\n```\n\nUsage:\n```\nrun_shell\ncommand: chmod +x sanitize_for_pdf.sh && .\u002Fsanitize_for_pdf.sh \u002Ftmp\u002Fdocument_source.md \u002Ftmp\u002Fdocument_source_sanitized.md\n```\n\n## Error Diagnosis Guide\n\n### Error: \"unknown error\" from run_shell\n\n**Diagnosis:**\n```\nrun_shell\ncommand: pandoc --version 2>&1\nrun_shell\ncommand: echo \"test\" | pandoc -f markdown -t plain 2>&1\n```\n\n**If pandoc works in isolation**, the issue is likely:\n- File path problems (use absolute paths)\n- Sandbox context issues (retry or use shell_agent)\n- Transient errors (retry the same command)\n\n### Error: \"LaTeX not found\" or \"pdflatex: command not found\"\n\n**Solutions in order:**\n1. Try xelatex: `--pdf-engine=xelatex`\n2. Try wkhtmltopdf: `--pdf-engine=wkhtmltopdf`\n3. Install LaTeX: `apt-get install texlive-latex-recommended texlive-fonts-recommended`\n4. Use Python fpdf2 fallback (see Step 4, Method C)\n\n### Error: \"Encoding error\" or \"Invalid UTF-8\"\n\n**Solutions:**\n1. Add UTF-8 flag: `pandoc -f markdown+utf8`\n2. Check file encoding: `file -i source.md`\n3. Re-save with explicit UTF-8: \n   ```\n   run_shell\n   command: iconv -f UTF-8 -t UTF-8 source.md -o source_utf8.md\n   ```\n4. Use sanitization step\n\n### Error: PDF generated but empty or garbled\n\n**Diagnosis:**\n```\nrun_shell\ncommand: pdfinfo output.pdf 2>&1\n```\n```\nexecute_code_sandbox\ncode: |\n  import fitz  # PyMuPDF\n  doc = fitz.open('output.pdf')\n  print(f'Pages: {doc.page_count}')\n  if doc.page_count > 0:\n      page = doc[0]\n      print(f'Text: {page.get_text()[:200]}')\n```\n\n**Solutions:**\n1. Use xelatex engine with Unicode content\n2. Check sanitization step (if using pdflatex)\n3. Verify source markdown is valid\n\n### Error: DOCX file won't open or shows error\n\n**Diagnosis:**\n```\nrun_shell\ncommand: unzip -l output.docx 2>&1 | head -10\n```\n\n**Solutions:**\n1. Add `--reference-doc` with valid template\n2. Ensure markdown syntax is valid\n3. Try pandoc verbose mode: `pandoc -v input.md -o output.docx 2>&1`\n\n## Workspace Troubleshooting\n\n### Files appearing in wrong directory\n\n**Diagnosis:**\n```\nrun_shell\ncommand: pwd && find \u002Ftmp -name \"*.docx\" -o -name \"*.pdf\" 2>\u002Fdev\u002Fnull | head -10\n```\n\n**Solutions:**\n1. Use absolute paths in all commands\n2. Explicitly change to target directory: `cd \u002Fpath\u002Fto\u002Fworkspace && ...`\n3. After generation, copy files to correct location:\n   ```\n   run_shell\n   command: cp \u002Ftmp\u002Foutput.docx .\u002Foutput.docx\n   ```\n\n### Permission denied errors\n\n**Solutions:**\n1. Use \u002Ftmp directory for intermediate files\n2. Copy final output to target location\n3. Check disk space: `df -h .`\n\n## When to Use shell_agent vs Manual Workflow\n\n| Situation | Recommended Approach |\n|-----------|---------------------|\n| Simple DOCX generation, no special chars | `shell_agent` (faster) |\n| PDF with Unicode\u002Fsymbols | Manual workflow with sanitization |\n| Multiple 'unknown error' failures | Manual workflow with error capture |\n| Need to debug conversion issues | Manual workflow (visible steps) |\n| Time-critical, simple format | `shell_agent` |\n| Critical document, must succeed | Manual workflow with fallbacks |\n\n## Alternative: Hybrid Approach\n\nFor reliability with less manual effort:\n\n```markdown\n## Hybrid Workflow\n\n1. **First attempt**: `shell_agent` with clear task description\n\n2. **On first error**: Switch to manual workflow:\n   - `write_file` for source\n   - `run_shell` with error capture (2>&1)\n   - Verify with explicit checks\n\n3. **On repeated errors**: Use Python library fallback (execute_code_sandbox)\n\nThis balances speed with reliability.\n```\n\n## Related Skills\n\n- `workspace-path-troubleshooting`: For diagnosing file location issues\n- `pdf-verification-cli`: For validating generated PDFs\n- `write-file-fallback-report`: For content-first document creation when web sources fail\n\n## Quick Reference Card\n\n```\nQUICK START: Generate Document in 3 Formats\n\n1. Write source: write_file → \u002Ftmp\u002Fdoc.md\n\n2. Sanitize (PDF only): \n   Replace: — → --, \"\" → \"\", … → ...\n\n3. Convert with error capture:\n   DOCX: pandoc \u002Ftmp\u002Fdoc.md -o out.docx 2>&1\n   PDF:  pandoc \u002Ftmp\u002Fdoc_sanitized.md --pdf-engine=xelatex -o out.pdf 2>&1\n   HTML: pandoc \u002Ftmp\u002Fdoc.md -o out.html 2>&1\n\n4. Verify: ls -lh out.* && file out.*\n\n5. If pandoc fails: Use execute_code_sandbox with fpdf2 or python-docx\n```\n","# Resilient Document Generation Workflow\n\n## When to Use\n\nUse this skill when document generation tasks encounter tool errors or failures, especially:\n- `run_shell` commands return 'unknown error' without diagnostic details\n- PDF generation fails with LaTeX encoding or missing engine errors\n- You need fallback options when primary conversion methods fail\n- **Workspace or path issues** cause file access problems\n- Unicode\u002Fspecial characters cause rendering issues in PDF output\n- `shell_agent` has failed multiple times on similar tasks\n\n## Core Technique\n\nSplit document generation into **observable, verifiable steps** with explicit error capture and progressive fallback:\n\n1. **Validate workspace** → Confirm current directory and write permissions\n2. **Pre-flight checks** → Verify required tools (pandoc, LaTeX engines) are available\n3. **Content creation** → Use `write_file` for source Markdown with full visibility\n4. **Unicode sanitization** → Preprocess for PDF conversion when needed\n5. **Progressive conversion** → Try multiple engines\u002Fmethods until one succeeds\n6. **Explicit error capture** → Redirect stderr to diagnose failures\n7. **Verification** → Confirm output files exist and are readable\n\n## ⚠️ Critical: Tool Error Patterns\n\n**'unknown error' from run_shell**: This typically indicates:\n- Sandbox execution context issues (not the command itself)\n- Missing stderr capture preventing diagnosis\n- Transient file access problems\n\n**Solution**: Use explicit error capture with `2>&1` and verify tool availability first:\n```\nrun_shell\ncommand: pandoc --version 2>&1 || echo \"PANDOC NOT AVAILABLE\"\n```\n\n## Pre-Flight Checklist\n\nBefore starting conversion, verify your environment:\n\n```markdown\n## Pre-Flight Checks\n\n### Check 1: Verify working directory\nrun_shell\ncommand: pwd && ls -la\n\n### Check 2: Verify pandoc availability\nrun_shell\ncommand: pandoc --version 2>&1 | head -3 || echo \"PANDOC MISSING\"\n\n### Check 3: Check LaTeX engines\nrun_shell\ncommand: which pdflatex xelatex wkhtmltopdf 2>&1 || echo \"Some engines missing\"\n\n### Check 4: Check Python libraries (fallback option)\nrun_shell\ncommand: python3 -c \"import fpdf; print('fpdf OK')\" 2>&1 || echo \"fpdf missing\"\nrun_shell\ncommand: python3 -c \"import docx; print('python-docx OK')\" 2>&1 || echo \"python-docx missing\"\n```\n\n## Complete Step-by-Step Workflow\n\n### Step 1: Validate Workspace\n\nConfirm you're in the correct directory and can write files:\n\n```\nrun_shell\ncommand: pwd && echo \"Test write\" > \u002Ftmp\u002Fworkspace_test_$$.txt && ls -la \u002Ftmp\u002Fworkspace_test_$$.txt && rm \u002Ftmp\u002Fworkspace_test_$$.txt\n```\n\n**If this fails**, you may have directory permission issues. Use absolute paths for all files.\n\n### Step 2: Create Source Content with write_file\n\nWrite 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\n### Step 3: Unicode Sanitization (PDF Only)\n\n**Only needed for PDF conversion via LaTeX engines**. DOCX and HTML handle Unicode natively.\n\nCreate a sanitized version replacing LaTeX-problematic characters:\n\n```\nwrite_file\npath: \u002Ftmp\u002Fdocument_source_sanitized.md\ncontent: |\n  # Document Title\n  \n  [Same content with: em-dash → --, curly quotes → straight, → arrows → text, etc.]\n```\n\n**Common replacements** (see full table below):\n| Original | Replace With |\n|----------|--------------|\n| `—` (em dash) | `--` |\n| `\" \"` (curly quotes) | `\" \"` (straight) |\n| `…` (ellipsis) | `...` |\n| `→` `←` (arrows) | `->` `\u003C-` |\n| `✓` `✗` | `[x]` `[ ]` |\n| `©` `®` `™` | `(c)` `(r)` `(tm)` |\n\n**Alternative**: Use sanitization script (see Scripts section below).\n\n### Step 4: Progressive Format Conversion\n\nTry multiple methods in order of preference. **Capture stderr explicitly** for diagnosis.\n\n#### Method A: DOCX Conversion (Most Reliable)\n\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source.md -o output.docx 2>&1 && echo \"SUCCESS\" || echo \"FAILED: $?\"\n```\n\nIf this fails, try with explicit UTF-8 flag:\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source.md -f markdown+utf8 -o output.docx 2>&1\n```\n\n#### Method B: PDF Conversion (Progressive Fallback)\n\n**Try engines in this order** until one succeeds:\n\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source_sanitized.md -o output.pdf 2>&1 | tee \u002Ftmp\u002Fpdf_error.log && echo \"PDF SUCCESS\"\n```\n\nIf Method B fails, check error log and try next engine:\n\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source_sanitized.md --pdf-engine=xelatex -o output.pdf 2>&1 | tee \u002Ftmp\u002Fpdf_error.log && echo \"PDF SUCCESS\"\n```\n\nIf xelatex fails:\n```\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fdocument_source_sanitized.md --pdf-engine=wkhtmltopdf -o output.pdf 2>&1 | tee \u002Ftmp\u002Fpdf_error.log && echo \"PDF SUCCESS\"\n```\n\n#### Method C: Python Library Fallback (When pandoc Unavailable)\n\nIf all pandoc methods fail, use Python libraries:\n\n**Option C1: FPDF2 for PDF**\n```\nexecute_code_sandbox\nlanguage: python\ncode: |\n  from fpdf import FPDF\n  \n  pdf = FPDF()\n  pdf.add_page()\n  pdf.set_font('Arial', 'B', 16)\n  pdf.cell(40, 10, 'Document Title')\n  pdf.ln(20)\n  pdf.set_font('Arial', '', 12)\n  pdf.multi_cell(0, 10, 'Your content here...')\n  pdf.output('output.pdf')\n  print('PDF created successfully')\n```\n\n**Option C2: python-docx for DOCX**\n```\nexecute_code_sandbox\nlanguage: python\ncode: |\n  from docx import Document\n  \n  doc = Document()\n  doc.add_heading('Document Title', 0)\n  doc.add_paragraph('Your content here...')\n  doc.save('output.docx')\n  print('DOCX created successfully')\n```\n\n### Step 5: Verify Output Files\n\nDon't just check existence—verify files are valid:\n\n```\nrun_shell\ncommand: ls -lh output.* 2>&1\n```\n\n```\nrun_shell\ncommand: file output.docx output.pdf 2>&1\n```\n\nFor DOCX, verify content:\n```\nrun_shell\ncommand: unzip -p output.docx word\u002Fdocument.xml 2>&1 | head -50 || echo \"Cannot read DOCX\"\n```\n\nFor PDF, check page count:\n```\nrun_shell\ncommand: pdfinfo output.pdf 2>&1 | grep Pages || echo \"pdfinfo not available\"\n```\n\nAlternative verification via Python:\n```\nexecute_code_sandbox\ncode: |\n  import os\n  for f in ['output.docx', 'output.pdf', 'output.html']:\n    if os.path.exists(f):\n      size = os.path.getsize(f)\n      print(f'{f}: {size} bytes')\n    else:\n      print(f'{f}: NOT FOUND')\n```\n\n## Complete Example: Generating a Report\n\n```markdown\n# Generate Quarterly Report (DOCX + PDF)\n\n## Step 1: Pre-flight checks\nrun_shell\ncommand: pandoc --version 2>&1 | head -1\n\n## Step 2: Write Markdown source\nwrite_file\npath: \u002Ftmp\u002Fquarterly_report.md\ncontent: |\n  # Quarterly Business Report\n  \n  ## Executive Summary\n  Q4 performance exceeded expectations...\n  \n  ## Key Metrics\n  - Revenue: $1.2M\n  - Growth: 15%\n  \n  ## Recommendations\n  Continue current strategy...\n\n## Step 3: Create sanitized version for PDF\nwrite_file\npath: \u002Ftmp\u002Fquarterly_report_sanitized.md\ncontent: |\n  # Quarterly Business Report\n  \n  ## Executive Summary\n  Q4 performance exceeded expectations...\n  \n  [Rest of content with special chars replaced]\n\n## Step 4: Generate DOCX\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fquarterly_report.md -o quarterly_report.docx 2>&1 && echo \"DOCX OK\"\n\n## Step 5: Generate PDF (try xelatex for Unicode safety)\nrun_shell\ncommand: pandoc \u002Ftmp\u002Fquarterly_report_sanitized.md --pdf-engine=xelatex -o quarterly_report.pdf 2>&1 && echo \"PDF OK\"\n\n## Step 6: Verify outputs\nrun_shell\ncommand: ls -lh quarterly_report.* && file quarterly_report.*\n```\n\n## Full Unicode Replacement Table\n\n| Character | Unicode | Issue | Safe Replacement |\n|-----------|---------|-------|------------------|\n| `—` | U+2014 | LaTeX incompatible | `--` |\n| `–` | U+2013 | LaTeX incompatible | `-` |\n| `\"` `\"` | U+201C\u002FU+201D | Encoding errors | `\"` (straight) |\n| `'` `'` | U+2018\u002FU+2019 | Encoding errors | `'` (straight) |\n| `…` | U+2026 | May not render | `...` |\n| `→` | U+2192 | LaTeX incompatible | `->` or `to` |\n| `←` | U+2190 | LaTeX incompatible | `\u003C-` |\n| `↑` `↓` | U+2191\u002FU+2193 | LaTeX incompatible | `^` `v` |\n| `•` | U+2022 | Font-dependent | `-` or `*` |\n| `✓` | U+2713 | May not render | `[x]` |\n| `✗` | U+2717 | May not render | `[ ]` |\n| `★` `●` | U+2605\u002FU+25CF | May not render | `*` `-` |\n| `©` | U+00A9 | May require packages | `(c)` |\n| `®` | U+00AE | May require packages | `(r)` |\n| `™` | U+2122 | May require packages | `(tm)` |\n| `é` `ñ` `ü` | Various | Font-dependent | Use xelatex or replace |\n\n## Reusable Sanitization Script\n\nSave this script for repeated use:\n\n```bash\n#!\u002Fbin\u002Fbash\n# sanitize_for_pdf.sh - Replace problematic unicode chars for LaTeX\u002FPDF\nset -e\nif [ -z \"$1\" ]; then\n  echo \"Usage: $0 \u003Cinput.md> [output.md]\"\n  exit 1\nfi\nINPUT=\"$1\"\nOUTPUT=\"${2:-${1%.md}_sanitized.md}\"\n\nsed -e 's\u002F—\u002F--\u002Fg' \\\n    -e 's\u002F–\u002F-\u002Fg' \\\n    -e 's\u002F\"\\([^\"]*\\)\"\u002F\"\\1\"\u002Fg' \\\n    -e \"s\u002F'\\([^']*\\)'\u002F\\'\\1\\'\u002Fg\" \\\n    -e 's\u002F…\u002F...\u002Fg' \\\n    -e 's\u002F→\u002F->\u002Fg' \\\n    -e 's\u002F←\u002F\u003C-\u002Fg' \\\n    -e 's\u002F↑\u002F^\u002Fg' \\\n    -e 's\u002F↓\u002Fv\u002Fg' \\\n    -e 's\u002F•\u002F-\u002Fg' \\\n    -e 's\u002F✓\u002F[x]\u002Fg' \\\n    -e 's\u002F✗\u002F[ ]\u002Fg' \\\n    -e 's\u002F★\u002F*\u002Fg' \\\n    -e 's\u002F©\u002F(c)\u002Fg' \\\n    -e 's\u002F®\u002F(r)\u002Fg' \\\n    -e 's\u002F™\u002F(tm)\u002Fg' \\\n    \"$INPUT\" > \"$OUTPUT\"\n\necho \"Sanitized: $INPUT -> $OUTPUT\"\n```\n\nUsage:\n```\nrun_shell\ncommand: chmod +x sanitize_for_pdf.sh && .\u002Fsanitize_for_pdf.sh \u002Ftmp\u002Fdocument_source.md \u002Ftmp\u002Fdocument_source_sanitized.md\n```\n\n## Error Diagnosis Guide\n\n### Error: \"unknown error\" from run_shell\n\n**Diagnosis:**\n```\nrun_shell\ncommand: pandoc --version 2>&1\nrun_shell\ncommand: echo \"test\" | pandoc -f markdown -t plain 2>&1\n```\n\n**If pandoc works in isolation**, the issue is likely:\n- File path problems (use absolute paths)\n- Sandbox context issues (retry or use shell_agent)\n- Transient errors (retry the same command)\n\n### Error: \"LaTeX not found\" or \"pdflatex: command not found\"\n\n**Solutions in order:**\n1. Try xelatex: `--pdf-engine=xelatex`\n2. Try wkhtmltopdf: `--pdf-engine=wkhtmltopdf`\n3. Install LaTeX: `apt-get install texlive-latex-recommended texlive-fonts-recommended`\n4. Use Python fpdf2 fallback (see Step 4, Method C)\n\n### Error: \"Encoding error\" or \"Invalid UTF-8\"\n\n**Solutions:**\n1. Add UTF-8 flag: `pandoc -f markdown+utf8`\n2. Check file encoding: `file -i source.md`\n3. Re-save with explicit UTF-8: \n   ```\n   run_shell\n   command: iconv -f UTF-8 -t UTF-8 source.md -o source_utf8.md\n   ```\n4. Use sanitization step\n\n### Error: PDF generated but empty or garbled\n\n**Diagnosis:**\n```\nrun_shell\ncommand: pdfinfo output.pdf 2>&1\n```\n```\nexecute_code_sandbox\ncode: |\n  import fitz  # PyMuPDF\n  doc = fitz.open('output.pdf')\n  print(f'Pages: {doc.page_count}')\n  if doc.page_count > 0:\n      page = doc[0]\n      print(f'Text: {page.get_text()[:200]}')\n```\n\n**Solutions:**\n1. Use xelatex engine with Unicode content\n2. Check sanitization step (if using pdflatex)\n3. Verify source markdown is valid\n\n### Error: DOCX file won't open or shows error\n\n**Diagnosis:**\n```\nrun_shell\ncommand: unzip -l output.docx 2>&1 | head -10\n```\n\n**Solutions:**\n1. Add `--reference-doc` with valid template\n2. Ensure markdown syntax is valid\n3. Try pandoc verbose mode: `pandoc -v input.md -o output.docx 2>&1`\n\n## Workspace Troubleshooting\n\n### Files appearing in wrong directory\n\n**Diagnosis:**\n```\nrun_shell\ncommand: pwd && find \u002Ftmp -name \"*.docx\" -o -name \"*.pdf\" 2>\u002Fdev\u002Fnull | head -10\n```\n\n**Solutions:**\n1. Use absolute paths in all commands\n2. Explicitly change to target directory: `cd \u002Fpath\u002Fto\u002Fworkspace && ...`\n3. After generation, copy files to correct location:\n   ```\n   run_shell\n   command: cp \u002Ftmp\u002Foutput.docx .\u002Foutput.docx\n   ```\n\n### Permission denied errors\n\n**Solutions:**\n1. Use \u002Ftmp directory for intermediate files\n2. Copy final output to target location\n3. Check disk space: `df -h .`\n\n## When to Use shell_agent vs Manual Workflow\n\n| Situation | Recommended Approach |\n|-----------|---------------------|\n| Simple DOCX generation, no special chars | `shell_agent` (faster) |\n| PDF with Unicode\u002Fsymbols | Manual workflow with sanitization |\n| Multiple 'unknown error' failures | Manual workflow with error capture |\n| Need to debug conversion issues | Manual workflow (visible steps) |\n| Time-critical, simple format | `shell_agent` |\n| Critical document, must succeed | Manual workflow with fallbacks |\n\n## Alternative: Hybrid Approach\n\nFor reliability with less manual effort:\n\n```markdown\n## Hybrid Workflow\n\n1. **First attempt**: `shell_agent` with clear task description\n\n2. **On first error**: Switch to manual workflow:\n   - `write_file` for source\n   - `run_shell` with error capture (2>&1)\n   - Verify with explicit checks\n\n3. **On repeated errors**: Use Python library fallback (execute_code_sandbox)\n\nThis balances speed with reliability.\n```\n\n## Related Skills\n\n- `workspace-path-troubleshooting`: For diagnosing file location issues\n- `pdf-verification-cli`: For validating generated PDFs\n- `write-file-fallback-report`: For content-first document creation when web sources fail\n\n## Quick Reference Card\n\n```\nQUICK START: Generate Document in 3 Formats\n\n1. Write source: write_file → \u002Ftmp\u002Fdoc.md\n\n2. Sanitize (PDF only): \n   Replace: — → --, \"\" → \"\", … → ...\n\n3. Convert with error capture:\n   DOCX: pandoc \u002Ftmp\u002Fdoc.md -o out.docx 2>&1\n   PDF:  pandoc \u002Ftmp\u002Fdoc_sanitized.md --pdf-engine=xelatex -o out.pdf 2>&1\n   HTML: pandoc \u002Ftmp\u002Fdoc.md -o out.html 2>&1\n\n4. Verify: ls -lh out.* && file out.*\n\n5. If pandoc fails: Use execute_code_sandbox with fpdf2 or python-docx\n```\n",{"name":5,"description":7},"main","6b84b0689ca0d9e7b1e4061188ff6b60758e0f8a","openspace\u002Flegacy\u002Fv1\u002Fgdpval_bench\u002Fskills\u002Fdocument-gen-fallback-enhanced-enhanced",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":54,"prompt":64,"zipAvailable":65},[55,58,61],{"tool":56,"command":57},"npx","npx skills add HKUDS\u002FAgentPilot --skill document-gen-resilient-workflow",{"tool":59,"command":60},"bunx","bunx skills add HKUDS\u002FAgentPilot --skill document-gen-resilient-workflow",{"tool":62,"command":63},"pnpm","pnpm dlx skills add HKUDS\u002FAgentPilot --skill document-gen-resilient-workflow","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fgdpval_bench\u002Fskills\u002Fdocument-gen-fallback-enhanced-enhanced\u002FSKILL.md",true,[67,73],{"path":68,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":71,"sourceHtmlUrl":72},".skill_id","OTHER","其他",53,"https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fgdpval_bench\u002Fskills\u002Fdocument-gen-fallback-enhanced-enhanced\u002F.skill_id",{"path":74,"resourceType":75,"resourceTypeDesc":76,"sizeBytes":77,"sourceHtmlUrl":78},"sanitize_for_pdf.sh","SCRIPT","脚本",1285,"https:\u002F\u002Fgithub.com\u002FHKUDS\u002FAgentPilot\u002Fblob\u002Fmain\u002Fopenspace\u002Flegacy\u002Fv1\u002Fgdpval_bench\u002Fskills\u002Fdocument-gen-fallback-enhanced-enhanced\u002Fsanitize_for_pdf.sh",[80,99,118,139,163,185],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":40},"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",[],[82,87,88,39,89,90,91,92,93,94,95,96,97,98],"prepare","requests","missing","installation","rsi","up","use","user","work","SET","run","experiments",{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":40},"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",[],[101,106,107,108,109,110,111,112,113,114,115,116,117],"memory","review","auto","openspace","changes","facts","detect","entries","local","conflicts","stale","duplicates",{"skillNo":119,"name":120,"nameZh":6,"description":121,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":122,"categories":123,"keywords":125,"publishedAt":40},"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",[124],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[126,127,128,109,129,130,131,132,133,134,135,136,137,138],"skill discovery","discovery","reusable","step by step","tokens","packages","help","cloud","reliability","capabilities","browse","search","Tools",{"skillNo":140,"name":141,"nameZh":6,"description":142,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":143,"categories":144,"keywords":146,"publishedAt":40},"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",[145],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[147,148,149,109,150,151,152,153,154,128,108,93,155,156,157,158,159,160,161,162],"delegate","task","delegate task","time","improve","desktop automation","worker","community","autonomous","tool","stack","for","share","tasks","automation","MCP",{"skillNo":164,"name":165,"nameZh":6,"description":166,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":167,"categories":168,"keywords":169,"publishedAt":40},"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",[],[170,171,172,173,174,175,176,177,178,31,179,180,181,182,158,183,184],"write special chars ts check","write","check","type","files","filters","only","template","file","typescript","output","Existing","type-checking","errors","script",{"skillNo":186,"name":187,"nameZh":6,"description":188,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":189,"categories":190,"keywords":191,"publishedAt":40},"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",[],[192,193,171,39,158,184,194,195,196,197,198,177,178,199,200,31],"write special chars readback","readback","helper","post","via","scripts","read","verification","cleanup"]