{
  "schemaVersion": "1.0",
  "item": {
    "slug": "git-repo-to-book",
    "name": "Git Repo to Book",
    "source": "tencent",
    "type": "skill",
    "category": "开发工具",
    "sourceUrl": "https://clawhub.ai/chunhualiao/git-repo-to-book",
    "canonicalUrl": "https://clawhub.ai/chunhualiao/git-repo-to-book",
    "targetPlatform": "OpenClaw"
  },
  "install": {
    "downloadMode": "redirect",
    "downloadUrl": "/downloads/git-repo-to-book",
    "sourceDownloadUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=git-repo-to-book",
    "sourcePlatform": "tencent",
    "targetPlatform": "OpenClaw",
    "installMethod": "Manual import",
    "extraction": "Extract archive",
    "prerequisites": [
      "OpenClaw"
    ],
    "packageFormat": "ZIP package",
    "includedAssets": [
      "CHANGELOG.md",
      "README.md",
      "SKILL.md",
      "scripts/convert_to_html.py",
      "scripts/merge_chapters.py",
      "scripts/polish_manuscript.py"
    ],
    "primaryDoc": "SKILL.md",
    "quickSetup": [
      "Download the package from Yavira.",
      "Extract the archive and review SKILL.md first.",
      "Import or place the package into your OpenClaw setup."
    ],
    "agentAssist": {
      "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
      "steps": [
        "Download the package from Yavira.",
        "Extract it into a folder your agent can access.",
        "Paste one of the prompts below and point your agent at the extracted folder."
      ],
      "prompts": [
        {
          "label": "New install",
          "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete."
        },
        {
          "label": "Upgrade existing",
          "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run."
        }
      ]
    },
    "sourceHealth": {
      "source": "tencent",
      "status": "healthy",
      "reason": "direct_download_ok",
      "recommendedAction": "download",
      "checkedAt": "2026-04-30T16:55:25.780Z",
      "expiresAt": "2026-05-07T16:55:25.780Z",
      "httpStatus": 200,
      "finalUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=network",
      "contentType": "application/zip",
      "probeMethod": "head",
      "details": {
        "probeUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=network",
        "contentDisposition": "attachment; filename=\"network-1.0.0.zip\"",
        "redirectLocation": null,
        "bodySnippet": null
      },
      "scope": "source",
      "summary": "Source download looks usable.",
      "detail": "Yavira can redirect you to the upstream package for this source.",
      "primaryActionLabel": "Download for OpenClaw",
      "primaryActionHref": "/downloads/git-repo-to-book"
    },
    "validation": {
      "installChecklist": [
        "Use the Yavira download entry.",
        "Review SKILL.md after the package is downloaded.",
        "Confirm the extracted package contains the expected setup assets."
      ],
      "postInstallChecks": [
        "Confirm the extracted package includes the expected docs or setup files.",
        "Validate the skill or prompts are available in your target agent workspace.",
        "Capture any manual follow-up steps the agent could not complete."
      ]
    },
    "downloadPageUrl": "https://openagent3.xyz/downloads/git-repo-to-book",
    "agentPageUrl": "https://openagent3.xyz/skills/git-repo-to-book/agent",
    "manifestUrl": "https://openagent3.xyz/skills/git-repo-to-book/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/git-repo-to-book/agent.md"
  },
  "agentAssist": {
    "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
    "steps": [
      "Download the package from Yavira.",
      "Extract it into a folder your agent can access.",
      "Paste one of the prompts below and point your agent at the extracted folder."
    ],
    "prompts": [
      {
        "label": "New install",
        "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete."
      },
      {
        "label": "Upgrade existing",
        "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run."
      }
    ]
  },
  "documentation": {
    "source": "clawhub",
    "primaryDoc": "SKILL.md",
    "sections": [
      {
        "title": "Git Repo to Book",
        "body": "Write a full-length technical book using multi-agent AI orchestration. Based on the\nreal workflow that produced The OpenClaw Paradigm\n— 88,000+ words, 14 chapters, 42 diagrams in under 18 hours."
      },
      {
        "title": "Scope & Boundaries",
        "body": "This skill handles:\n\nPlanning, researching, writing, reviewing, and publishing multi-chapter technical books\nRevising individual chapters of existing books (review → rewrite → re-integrate)\nOrchestrating parallel sub-agents for each phase\nMerging chapters into a polished manuscript with TOC, metadata, and HTML export\nManaging the WORKLOG protocol for agent coordination\n\nThis skill does NOT handle:\n\nCover design or artwork generation (use an illustration skill)\nPublishing to Amazon/Kindle/bookstores (output is Markdown + HTML)\nFiction/creative writing (optimized for technical/non-fiction)\nTranslation to other languages"
      },
      {
        "title": "Inputs",
        "body": "InputRequiredDescriptionTopic/subjectYesWhat the book is aboutSource repoNoGitHub URL to analyze as source materialChapter countNoAuto-scaled from repo size (see below), or user overrideTarget lengthNoAuto-scaled from repo size (see below), or user overrideBudget limitNoMax API cost in dollars. Default: $100. Agent pauses if exceededOutput formatsNoMarkdown (always), HTML (optional), PDF (optional)Model preferencesNoDefaults in Agent Model Recommendations section"
      },
      {
        "title": "Outputs",
        "body": "book/final-manuscript.md — polished, publication-ready manuscript\nbook/illustrated-manuscript.md — manuscript with scrapbook illustrations (if article-illustrator available)\nbook/metadata.json — title, author, word count, chapter count, date\nbook/book.html — HTML export (optional)\nGit repository with full project history"
      },
      {
        "title": "Auto-Scaling: Repo Size → Book Size",
        "body": "When a source repo is provided, automatically assess its scope before planning:\n\n# Count source files and total lines\nfind <repo> -name '*.py' -o -name '*.ts' -o -name '*.js' -o -name '*.go' -o -name '*.rs' -o -name '*.md' | wc -l\nfind <repo> -name '*.py' -o -name '*.ts' -o -name '*.js' -o -name '*.go' -o -name '*.rs' -o -name '*.md' | xargs wc -l 2>/dev/null | tail -1\n\nRepo SizeSource FilesLines of CodeRecommended ChaptersTarget WordsEstimated CostSmall<50 files<5K lines5-6 chapters~30,000$5-15Medium50-200 files5K-30K lines8-10 chapters~55,000$15-35Large200-500 files30K-100K lines12-14 chapters~80,000$30-60Very Large>500 files>100K lines14-18 chapters~100,000+$50-100\n\nIf no source repo is provided (topic-only book), default to Medium (10 chapters, ~55K words).\n\nThe user can always override these defaults."
      },
      {
        "title": "Pre-Flight Cost Estimation",
        "body": "Before starting any work, present the user with a cost estimate and get confirmation:\n\n## Book Project Estimate\n\n**Topic:** [topic]\n**Source:** [repo URL or \"topic-only\"]\n**Repo size:** [Small/Medium/Large/Very Large] ([N] files, [N] lines)\n\n**Plan:**\n- Chapters: [N]\n- Target words: ~[N]\n- Writing agents: [N] parallel\n- Estimated API cost: $[X]-$[Y]\n\n**Budget limit:** $[user-set or 100 default]\n\n**Models:**\n- Writing: claude-sonnet-4-6 (~$0.003/1K input, $0.015/1K output)\n- Research: gemini-2.5-pro (~$0.002/1K input, $0.012/1K output)\n- Review: deepseek-v3.2 (~$0.001/1K input, $0.003/1K output)\n\nProceed? (yes / adjust budget / change chapter count)\n\nCost tracking during execution: After each phase, log cumulative spend in WORKLOG.md:\n\n## Cost Checkpoint - Phase [N] Complete\n**Phase cost:** $X.XX\n**Cumulative:** $XX.XX / $[budget] budget\n**Remaining budget:** $XX.XX\n**Projected total:** $XX.XX (on track / over budget)\n\nIf projected total exceeds budget by >20%, pause and ask the user before continuing."
      },
      {
        "title": "Why an Orchestrator Subagent (not direct Director control)",
        "body": "The naive approach is: Director spawns research agents, waits for completion announce,\nspawns writing agents, waits again, etc. This breaks in practice because:\n\nAnnounce-to-action gap: When a subagent finishes, OpenClaw sends a completion\nmessage to the parent session. The parent gets a new turn, but it must choose to\nchain the next phase. If it treats the announce as informational (reports results to\nuser and stops), the pipeline stalls. There is no guaranteed hook that forces the\nnext action.\n\n\nContext loss between turns: Each turn the Director takes is a fresh LLM call.\nBetween subagent completion and the next turn, there's no persistent state machine\ntracking \"we're in phase 3 of 7.\" The Director must re-derive pipeline state from\nWORKLOG.md every time, which is fragile.\n\n\nUser messages interrupt: If the user sends a message between phases, the Director's\nnext turn handles that message instead of continuing the pipeline. The pipeline stalls\nuntil another trigger arrives.\n\nSolution: Orchestrator subagent pattern. The Director spawns a single orchestrator\nsubagent (maxSpawnDepth: 2) that owns the entire pipeline lifecycle. The orchestrator\nruns as a continuous session, spawning worker sub-sub-agents for each phase and\nimmediately chaining the next phase when workers complete. Because it's a single\ncontinuous run, there's no announce-to-action gap — the orchestrator never yields\ncontrol between phases.\n\nDirector (main agent, depth 0)\n    │\n    └── Orchestrator (subagent, depth 1) ← owns entire pipeline\n        │\n        ├── Phase 1: RESEARCH workers (depth 2, parallel)\n        │   └── research/*.md → pattern-synthesis.md\n        │\n        ├── Phase 2: OUTLINE workers (depth 2, parallel)\n        │   └── chapters/*-outline.md\n        │\n        ├── Phase 3: WRITING workers (depth 2, 3 chapters each)\n        │   └── chapters/chapter-NN.md\n        │\n        ├── Phase 4: REVIEW workers (depth 2, parallel)\n        │   └── reviews/quality-review-*.md\n        │\n        ├── Phase 5: INTEGRATION (orchestrator does this directly)\n        │   └── book/manuscript.md\n        │\n        ├── Phase 6: POLISH (orchestrator does this directly)\n        │   └── book/final-manuscript.md + metadata.json\n        │\n        ├── Phase 7: ILLUSTRATE (orchestrator invokes article-illustrator per chapter)\n        │   └── book/illustrated-manuscript.md (scrapbook images at section breaks)\n        │\n        └── Phase 8: PUBLISH (orchestrator does this directly)\n            └── git commit + push + report"
      },
      {
        "title": "Depth Model",
        "body": "DepthRoleSpawns children?Has session tools?0Director (main agent)Yes — spawns orchestratorFull tools1OrchestratorYes — spawns workersGets sessions_spawn, subagents, sessions_list, sessions_history2Workers (research, writing, review)NoFile I/O + exec only\n\nRequires: agents.defaults.subagents.maxSpawnDepth: 2 in OpenClaw config.\n\nIf maxSpawnDepth is 1 (default), the skill falls back to Director-controlled mode\n(see Fallback section below)."
      },
      {
        "title": "Fallback: Director-Controlled Mode (maxSpawnDepth: 1)",
        "body": "If nested subagents are not available, the Director orchestrates directly:\n\nSpawns each phase's workers as depth-1 subagents\nWhen completion announces arrive, must immediately chain the next phase\nPipeline state tracked via WORKLOG.md\nRisk: announce-to-action gap if Director doesn't chain (see justification above)\n\nTo mitigate, set a cron safety net after spawning:\n\ncron: \"Check book pipeline state in WORKLOG.md. If last phase completed but next\nphase not started, resume the pipeline.\" (fire 15 minutes after spawn)"
      },
      {
        "title": "Agent Coordination",
        "body": "All agents coordinate via WORKLOG.md (append-only). The orchestrator (or Director\nin fallback mode) reads WORKLOG to track progress. Workers append entries when starting\nand finishing work."
      },
      {
        "title": "End-to-End Example",
        "body": "User says: \"Write a technical book about AI-native software development. Source: https://github.com/openclaw/openclaw\"\n\nStep 1 — Gather requirements:\n\nTopic: AI-native software development\nSource repo: openclaw/openclaw\nChapters: 12 (default)\nTarget: ~80,000 words\n\nStep 2 — Set up repo and spawn orchestrator:\n\nmkdir -p book-project/{chapters,book,diagrams,research,reviews,scripts,project-notes}\ncd book-project && git init\n\nCopy templates, then spawn the orchestrator subagent (depth 1) which manages all\nremaining phases. The orchestrator spawns worker sub-sub-agents (depth 2) in parallel.\n\nStep 3 — Research phase (orchestrator spawns 3 parallel workers):\n\nAgent A task: \"Analyze openclaw/openclaw architecture. Focus on session management,\ntool system, and agent lifecycle. Output: research/architecture-analysis.md. \nRead WORKLOG.md first. Update WORKLOG.md when complete.\"\n\nAgent B task: \"Analyze openclaw/openclaw skills system and plugin architecture.\nOutput: research/skills-analysis.md. Read WORKLOG.md first.\"\n\nAgent C (synthesis): \"Read all files in research/. Synthesize into \nresearch/pattern-synthesis.md. Identify 6-10 core patterns and 3-5 anti-patterns.\"\n\nStep 4 — Outline phase (spawn 2 agents):\n\nAgent 1: \"Write detailed outlines for intro + chapters 1-6. Reference pattern-synthesis.md.\nOutput: chapters/chapter-NN-outline.md per chapter.\"\n\nAgent 2: \"Write detailed outlines for chapters 7-12.\"\n\nReview and commit outlines.\n\nStep 5 — Writing phase (spawn 4 parallel agents, 3 chapters each):\n\nAgent 1: \"Write intro + chapters 1-3. Read outlines and pattern-synthesis.md.\nTarget: 6,000-8,000 words per chapter. Update WORKLOG.md when each chapter is complete.\"\n\nAgent 2: \"Write chapters 4-6.\"\nAgent 3: \"Write chapters 7-9.\"\nAgent 4: \"Write chapters 10-12.\"\n\nModel: anthropic/claude-sonnet-4-6\n\nStep 6 — Review phase (spawn 2 agents):\n\nAgent A: \"Review intro + chapters 1-6. Check: logical flow, unsupported claims,\ncontradictions, missing examples. Output: reviews/quality-review-01-06.md.\nMark issues CRITICAL or MINOR.\"\n\nFix CRITICAL issues before proceeding.\n\nStep 7 — Integration:\n\npython3 <skill_dir>/scripts/merge_chapters.py --title \"AI-Native Development\" --author \"Author Name\"\n\nStep 8 — Polish:\n\npython3 <skill_dir>/scripts/polish_manuscript.py --title \"AI-Native Development\" --author \"Author Name\"\n\nStep 9 — HTML export:\n\npython3 <skill_dir>/scripts/convert_to_html.py\n\nStep 10 — Commit and report:\n\ngit add -A && git commit -m \"book: complete manuscript\" && git push\n\nReport: chapter count, word count, file locations, GitHub URL."
      },
      {
        "title": "Chapter Revision Mode",
        "body": "Revise a single chapter of an existing book without regenerating the entire manuscript."
      },
      {
        "title": "When to Use",
        "body": "A chapter is outdated (new features, changed APIs)\nQuality is below standard (reviewer scored it low)\nUser wants a different angle or deeper coverage\nNew information needs to be incorporated"
      },
      {
        "title": "Revision Inputs",
        "body": "InputRequiredDescriptionBook repoYesLocal path or GitHub URL of the existing bookChapter numberYesWhich chapter to revise (e.g., 3 or chapter-03)Revision instructionsNoSpecific guidance: \"add more examples\", \"update for v2 API\", \"make it more practical\"Budget limitNoDefault: $5 per chapter revision"
      },
      {
        "title": "Revision Workflow",
        "body": "Step R1 — Clone and Analyze\n\ngit clone <repo_url> /tmp/book-revision\ncd /tmp/book-revision\n\nRead the target chapter + its outline + adjacent chapters (N-1 and N+1) for context continuity.\n\nStep R2 — Review Current Chapter\n\nSpawn a reviewer agent to score the existing chapter on the standard rubric:\n\nTechnical accuracy\nCompleteness (are topics from the outline covered?)\nCode examples (working? up to date?)\nFlow and readability\nConsistency with adjacent chapters\n\nThe reviewer produces reviews/revision-review-chapter-NN.md with:\n\nScore per dimension\nSpecific issues found\nRecommended changes\n\nStep R3 — Research Updates (if needed)\n\nIf the revision requires new information (updated APIs, new features, recent events):\n\nSpawn a research agent to:\n\nQuery DeepWiki MCP (curl https://api.deepwiki.com/v1/chat) for current repo architecture and features\nAnalyze the source repo (if provided) for changes since the chapter was written\nWeb search for updated information and external context\nProduce research/revision-research-chapter-NN.md\n\nDeepWiki is the preferred research source for GitHub repo-based books — it provides deep, structured answers about architecture, components, and patterns.\n\nSkip if the revision is purely stylistic (rewrite for clarity, add examples from existing content).\n\nStep R4 — Rewrite\n\nSpawn a writer agent with:\n\nThe existing chapter text\nThe review (from R2)\nResearch updates (from R3, if any)\nThe chapter outline\nAdjacent chapters (for tone/style consistency)\nUser's revision instructions\n\nThe writer produces a new version: chapters/chapter-NN-revised.md\n\nKey constraints for the writer:\n\nPreserve the chapter's position in the book narrative (don't contradict adjacent chapters)\nKeep the same heading structure unless the outline changed\nMaintain consistent terminology with the rest of the book\nIf the original had diagrams, preserve or update diagram references\n\nStep R5 — Review (Mobile-Friendly)\n\nUsers often review from a phone (iPhone/Android via Discord, Signal, or Telegram). The review workflow adapts to the platform:\n\nPath A — GitHub PR (preferred, best for diff review):\n\ncd /tmp/book-revision\ngit checkout -b revise/chapter-NN\n\n# Backup original\ncp chapters/chapter-NN.md chapters/chapter-NN-pre-revision.md\n\n# Replace with revised version\ncp chapters/chapter-NN-revised.md chapters/chapter-NN.md\n\ngit add -A\ngit commit -m \"revise: chapter NN - [summary of changes]\"\ngit push origin revise/chapter-NN\n\n# Open PR with summary as description\ngh pr create --title \"Revise Chapter NN: [title]\" \\\n  --body \"$(cat reviews/revision-summary-chapter-NN.md)\" \\\n  --base main --head revise/chapter-NN\n\nThe user reviews the diff in GitHub mobile app (excellent diff viewer), then:\n\nComments \"LGTM\" or \"approve\" → agent merges PR and re-generates manuscript\nComments with feedback → agent makes changes, pushes to same branch\nCloses PR → revision discarded\n\nPath B — Obsidian sync (for offline reading):\n\nIf the user has Obsidian configured (e.g., via save-to-obsidian.sh):\n\n# Send revised chapter + summary to Obsidian vault\nsave-to-obsidian.sh chapters/chapter-NN-revised.md\nsave-to-obsidian.sh reviews/revision-summary-chapter-NN.md\n\nUser reads the full chapter on Obsidian mobile, replies via chat.\n\nPath C — Chat summary (quickest):\n\nPost a concise summary (≤500 words) directly in chat:\n\n📝 Chapter NN Revision Summary\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nWords: 3,510 → 5,200 (+48%)\n\n✅ Sections rewritten:\n  - 2.1: Updated architecture description\n  - 2.3: Added 3 new code examples\n\n➕ Sections added:\n  - 2.6: New \"Deployment Models\" section\n\n🔗 Full diff: [GitHub PR link]\n📖 Full chapter: [Obsidian / GitHub link]\n\nReply \"approve\", \"changes needed\", or specific feedback.\n\nAuto-detect by content type:\n\nText-only revision (no new diagrams/images): Default to Path A (PR) + Path C (chat summary). GitHub diff is ideal for text changes.\nIllustrated revision (new or updated diagrams/images): Default to Path B (Obsidian) + Path C (chat summary). Obsidian renders images inline — you see the chapter exactly as it appears in the book. GitHub PR diffs show images as \"binary file changed\" which is useless for review.\nUser preference overrides — if they ask for a specific path, use it.\n\nRecommendation: For chapters with diagrams (most technical books), Obsidian preview is the best experience on mobile. Use the PR for the final merge step after Obsidian review.\n\nStep R6 — Integrate\n\nOn user approval (via PR merge, chat reply, or Obsidian feedback):\n\nBest practice: Replace in-place, never create -new or -v2 suffixes.\n\nchapters/chapter-NN.md ← always overwrite the current file\ndiagrams/chapter-NN/ ← always replace diagrams in the same directory\nNo backups (-pre-revision, -old, -v2) — git history IS the backup\nNo new directories (chapter-02-new/) — the PR diff shows what changed\n\nThis prevents suffix accumulation (-new, -new-new, -new-v3) across revisions.\n\n# If using PR workflow, the merge already happened. Just regenerate manuscript:\ncd /tmp/book-revision\ngit checkout main && git pull\n\n# Re-merge all chapters into manuscript\npython3 <skill_dir>/scripts/merge_chapters.py --title \"[Title]\" --author \"[Author]\" --output book/manuscript.md\npython3 <skill_dir>/scripts/polish_manuscript.py --title \"[Title]\" --author \"[Author]\" --output book/final-manuscript.md\n\n# Commit updated manuscript\ngit add book/\ngit commit -m \"book: regenerate manuscript after chapter NN revision\"\ngit push\n\nStep R6.5 — Validate Links (automated)\n\nAfter integration, run the link validator to catch broken references:\n\npython3 <skill_dir>/scripts/validate_links.py --book-dir /path/to/book\n\nThis checks:\n\nAll ![image](path) references point to existing files\nAll [link](file.md) references resolve\nNo orphaned diagram directories\nSuggests fixes for broken links (fuzzy match on filenames)\n\nMust pass with 0 broken links before proceeding to R7 or committing.\n\nAlso verify metadata block exists:\n\ngrep -c \"## Chapter Metadata\" chapters/chapter-NN.md || echo \"ERROR: Missing metadata block\"\n\nIf missing, add it before committing.\n\nIf broken links are found:\n\nFix image paths to match actual filenames in diagrams/chapter-NN/\nRe-run validator until clean\nAlso run on book/final-manuscript-with-diagrams.md if it exists (merged manuscript may have stale refs)\n\nStep R7 — Re-illustrate (Optional)\n\nIf the chapter content changed significantly (>30% rewritten), regenerate diagrams:\n\nWith image API key: Re-run article-illustrator for the revised chapter\nWithout image API key: Re-run skill-mermaid-diagrams for the revised chapter"
      },
      {
        "title": "Revision Cost Estimate",
        "body": "ComponentModelEst. CostReviewdeepseek$0.01-0.02Research (if needed)gemini-pro$0.05-0.10Rewriteclaude-sonnet$0.10-0.30Re-illustrate (if needed)Z.AI$0.03-0.06Total per chapter$0.15-0.50"
      },
      {
        "title": "Example: Revise Chapter 3",
        "body": "User: \"Revise chapter 3 of https://github.com/chunhualiao/openclaw-paradigm-book\n       — it needs more real-world case studies and the code examples are outdated\"\n\nAgent:\n1. Clone repo, read chapter-03.md + chapter-02.md + chapter-04.md + chapter-03-outline.md\n2. Spawn reviewer → scores chapter, finds: \"only 2 case studies, code uses deprecated API\"\n3. Spawn research agent → checks OpenClaw repo for current API, finds 3 new case studies\n4. Spawn writer → rewrites chapter with 5 case studies, updated code, same structure\n5. Present diff summary to user\n6. On approval: replace chapter, re-merge manuscript, commit + push"
      },
      {
        "title": "Chapter Metadata Block (Required)",
        "body": "Every chapter must end with a metadata block providing provenance and reproducibility information. This is critical because source repos evolve fast — readers need to know which version the chapter describes.\n\nTemplate (append to end of each chapter):\n\n---\n\n## Chapter Metadata\n\n> **This section is auto-generated by the book-writer skill.**\n\n| Field | Value |\n|-------|-------|\n| **Subject Repo** | [owner/repo](https://github.com/owner/repo) |\n| **Subject Repo Commit** | [`abc1234`](https://github.com/owner/repo/commit/abc1234) |\n| **Subject Repo Version** | vX.Y.Z (or \"latest as of YYYY-MM-DD\") |\n| **Book Repo** | [owner/book-repo](https://github.com/owner/book-repo) |\n| **Book-Writer Skill** | [git-repo-to-book](https://clawhub.ai/YOUR_HANDLE/git-repo-to-book) |\n| **Research Source** | DeepWiki / web search / direct repo analysis |\n| **Diagrams** | N × type (skill used) |\n| **Writer Model** | model name |\n| **Reviewer Model** | model name |\n| **Generated/Revised** | YYYY-MM-DD |\n| **Word Count** | X,XXX |\n\n**⚠️ Freshness Note:** This chapter describes [repo] as of commit `abc1234`.\nVerify current state at [docs link] or [DeepWiki link].\n\nWhy this matters:\n\nSource repos change daily — without a commit pin, the chapter becomes unreproducible\nModel attribution helps readers understand potential biases\nFreshness warnings prevent readers from treating outdated info as current\nSkill version enables reproducing the exact pipeline\n\nWhen revising: Update all metadata fields. The old commit → new commit change is the most important field to update."
      },
      {
        "title": "Step 0 — Environment Discovery (run before every book/revision)",
        "body": "Before starting any pipeline, discover available API keys and expose them as environment variables. The skill uses multiple external services — some required, some optional.\n\nRun this discovery check:\n\n# === REQUIRED ===\n# At least one LLM provider must be configured (check OpenClaw config)\necho \"=== LLM Providers ===\"\ngrep -o '\"openrouter_api_key\"\\|\"anthropic_api_key\"\\|\"openai_api_key\"' ~/.openclaw/config.json 2>/dev/null && echo \"✅ LLM provider found\" || echo \"❌ No LLM provider in config\"\n\n# === OPTIONAL: Image Generation ===\necho \"=== Image Generation (for scrapbook illustrations) ===\"\n# Check all possible locations: env vars, config.json, .env files\nZAI=$(grep -o '\"zai_api_key\"' ~/.openclaw/config.json 2>/dev/null)\nGLM=$(grep -o '\"glm_api_key\"' ~/.openclaw/config.json 2>/dev/null)\nOR=$(grep -o '\"openrouter_api_key\"' ~/.openclaw/config.json 2>/dev/null)\n[ -n \"$ZAI\" ] && echo \"✅ Z.AI ($0.015/image)\" || echo \"⬜ Z.AI not configured\"\n[ -n \"$GLM\" ] && echo \"✅ GLM ($0.014/image)\" || echo \"⬜ GLM not configured\"\n[ -n \"$OR\" ] && echo \"✅ OpenRouter ($0.045/image)\" || echo \"⬜ OpenRouter not configured\"\n[ -z \"$ZAI\" ] && [ -z \"$GLM\" ] && [ -z \"$OR\" ] && echo \"→ Will use Mermaid diagrams (free) instead of scrapbook images\"\n\n# === OPTIONAL: Mermaid Diagrams ===\necho \"=== Mermaid CLI (for diagram generation) ===\"\nwhich mmdc >/dev/null 2>&1 && echo \"✅ mmdc $(mmdc --version 2>/dev/null)\" || echo \"⬜ mmdc not installed (run: npm install -g @mermaid-js/mermaid-cli)\"\n\n# === OPTIONAL: DeepWiki ===\necho \"=== DeepWiki MCP (for repo research) ===\"\ncurl -s --max-time 3 https://api.deepwiki.com/v1/health >/dev/null 2>&1 && echo \"✅ DeepWiki API reachable\" || echo \"⬜ DeepWiki unreachable (will use direct repo analysis)\"\n\n# === OPTIONAL: GitHub CLI ===\necho \"=== GitHub CLI (for PR workflow) ===\"\ngh auth status >/dev/null 2>&1 && echo \"✅ gh authenticated as $(gh api user -q .login 2>/dev/null)\" || echo \"⬜ gh not authenticated (PR review workflow unavailable)\"\n\n# === OPTIONAL: Obsidian sync ===\necho \"=== Obsidian (for mobile preview) ===\"\n[ -f ~/.openclaw/scripts/save-to-obsidian.sh ] && echo \"✅ Obsidian sync script found\" || echo \"⬜ No Obsidian sync (chat-only review)\"\n\nExpose keys as env vars (so subagents/scripts can access them):\n\n# Extract from OpenClaw config and export\nexport ZAI_API_KEY=$(python3 -c \"import json; c=json.load(open('$HOME/.openclaw/config.json')); print(c.get('zai_api_key',''))\" 2>/dev/null)\nexport GLM_API_KEY=$(python3 -c \"import json; c=json.load(open('$HOME/.openclaw/config.json')); print(c.get('glm_api_key',''))\" 2>/dev/null)\nexport OPENROUTER_API_KEY=$(python3 -c \"import json; c=json.load(open('$HOME/.openclaw/config.json')); print(c.get('openrouter_api_key',''))\" 2>/dev/null)"
      },
      {
        "title": "What Happens When Keys Are Missing",
        "body": "Missing KeyImpactFallbackAll LLM providersFatal — cannot proceedAsk user to configure at least one provider in ~/.openclaw/config.jsonAll image keys (ZAI, GLM, OR)No scrapbook illustrationsMermaid diagrams via skill-mermaid-diagrams (free)mmdc CLINo rendered diagram PNGs/SVGsRaw mermaid code blocks in markdown (still renders in GitHub/Obsidian)DeepWikiWeaker research for repo-based booksDirect repo analysis + web searchgh CLINo PR review workflowObsidian preview or chat summary onlyObsidian syncNo mobile preview with imagesGitHub PR + chat summary\n\nThe skill always works — missing optional keys degrade gracefully to free alternatives. Only LLM provider keys are required."
      },
      {
        "title": "Step 1 — Gather Requirements and Estimate Cost",
        "body": "Ask the user (or infer from context):\n\nTopic/subject — what is the book about?\nSource repo (optional) — GitHub URL to analyze as source material\nBudget limit — how much are they willing to spend? (default: $100)\nOutput formats — Markdown (always), HTML, PDF (optional)\n\nIf a source repo is provided, run the auto-scaling assessment (see above) to determine chapter count and target length. Then present the Pre-Flight Cost Estimation and wait for user confirmation before proceeding.\n\nIf the user sets a budget below the estimated cost, suggest reducing chapter count or using cheaper models (e.g., deepseek for writing instead of claude)."
      },
      {
        "title": "Step 2 — Set Up Repo and Spawn Orchestrator",
        "body": "mkdir -p book-project/{chapters,book,diagrams,research,reviews,scripts,project-notes}\ncd book-project && git init\n\nCopy templates from <skill_dir>/templates/ into project-notes/ and edit for your project. Replace <skill_dir> with the directory containing this SKILL.md.\n\nThen spawn the orchestrator subagent (preferred, requires maxSpawnDepth: 2):\n\nsessions_spawn(\n  task: \"You are the book pipeline orchestrator. Run all phases (research → outlines →\n    writing → review → integration → polish → publish) for [Book Title].\n    \n    Project dir: /path/to/book-project\n    Chapters: [N]\n    Target: ~[N] words\n    Budget: $[N]\n    Source: [repo URL or topic]\n    \n    You have sessions_spawn to create worker subagents. Spawn workers in parallel\n    for each phase. When workers finish, immediately start the next phase. Never\n    stop between phases. Track costs in WORKLOG.md after each phase.\n    \n    When all phases complete, report: chapter count, word count, total cost, file paths.\",\n  model: \"anthropic/claude-sonnet-4-6\",\n  mode: \"run\"\n)\n\nThe orchestrator handles Steps 3-10 autonomously. The Director only needs to relay\nthe final report to the user.\n\nIf maxSpawnDepth is 1 (fallback), the Director runs Steps 3-10 directly,\nspawning workers as depth-1 subagents and chaining phases on each completion announce."
      },
      {
        "title": "Step 3 — Research Phase",
        "body": "DeepWiki MCP (preferred for GitHub repos):\n\nIf the book's source material is a GitHub repo, use the deepwiki-mcp skill (clawhub install deepwiki-mcp) for deep research:\n\n# Query DeepWiki for detailed repo analysis\ncurl -s https://api.deepwiki.com/v1/chat \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"repo\": \"owner/repo\",\n    \"messages\": [{\"role\": \"user\", \"content\": \"Describe the architecture, key components, and design patterns\"}]\n  }'\n\nDeepWiki provides structured, authoritative answers about any public GitHub repo — its architecture, components, patterns, and implementation details. This is far more reliable than generic web search for repo-specific questions.\n\nResearch agent should query DeepWiki for each chapter's topics, then supplement with web_search for broader context (industry trends, comparisons, external references).\n\nFallback: If DeepWiki is unavailable, fall back to direct repo analysis (clone + read files) and web search.\n\nSpawn 2-3 research agents in parallel:\n\nTask: Analyze [source_repo/topic]. Identify key patterns, concepts, and examples.\nOutput: research/[topic-area]-analysis.md\nFormat: Numbered findings, specific examples, 2000-4000 words.\nRead WORKLOG.md first to avoid duplicating work.\nUpdate WORKLOG.md when complete.\n\nThen spawn one synthesis agent:\n\nTask: Read all files in research/. Synthesize into research/pattern-synthesis.md.\nIdentify 6-10 core patterns and 3-5 anti-patterns.\n\nDone when: research/pattern-synthesis.md exists and covers 6+ patterns."
      },
      {
        "title": "Step 4 — Outline Phase",
        "body": "Spawn outline agents (batch 5-6 outlines per agent):\n\nTask: Write detailed chapter outlines for Chapters N through M.\nReference: research/pattern-synthesis.md\nOutput: chapters/chapter-NN-outline.md per chapter\nFormat: H2 sections, 6-8 sections, 1-2 sentence description each\n\nReview and commit outlines before writing.\n\nDone when: All chapter-NN-outline.md files exist and reviewed."
      },
      {
        "title": "Step 5 — Writing Phase",
        "body": "Assign 3 chapters per writing agent — this is where parallelism pays off:\n\nTask: Write Chapters X, Y, Z of [Book Title].\nRead outlines and research/pattern-synthesis.md.\nOutput: chapters/chapter-NN.md per chapter.\nTarget: ~6,000-8,000 words per chapter.\nStyle: Technical but accessible. Use concrete examples, headers, code blocks, tables.\nUpdate WORKLOG.md when each chapter is complete.\n\nModel: anthropic/claude-sonnet-4-6\n\nDone when: All chapter files exist and WORKLOG shows completion."
      },
      {
        "title": "Step 6 — Review Phase",
        "body": "Spawn 1-2 review agents:\n\nTask: Review chapters [list]. Check: logical flow, unsupported claims, contradictions,\nmissing examples. Output: reviews/quality-review-[range].md\nFormat: Per-chapter bullet list. Mark CRITICAL / MINOR.\n\nFix CRITICAL issues. MINOR issues can be addressed in polish.\n\nDone when: Reviews exist and no open CRITICAL issues."
      },
      {
        "title": "Step 7 — Integration Phase",
        "body": "Run the merge script:\n\npython3 <skill_dir>/scripts/merge_chapters.py --title \"[Title]\" --author \"[Author]\" --output book/manuscript.md\n\nOr spawn an integration agent to merge manually and fix cross-references.\n\nDone when: book/manuscript.md exists with all chapters in order."
      },
      {
        "title": "Step 8 — Polish Phase",
        "body": "Run the polish script:\n\npython3 <skill_dir>/scripts/polish_manuscript.py --title \"[Title]\" --author \"[Author]\" --output book/final-manuscript.md\n\nThis adds title page, copyright, TOC with anchor links, and writes book/metadata.json.\n\nDone when: book/final-manuscript.md and book/metadata.json exist.\n\nThen validate links:\n\npython3 <skill_dir>/scripts/validate_links.py --book-dir .\n\nMust pass with 0 broken links before publishing."
      },
      {
        "title": "Step 8.5 — Illustrate (Optional)",
        "body": "Add scrapbook-style illustrations to the manuscript using the article-illustrator skill.\n\nPrerequisites: article-illustrator skill installed, at least one image API key set (ZAI_API_KEY, GLM_API_KEY, or OPENROUTER_API_KEY).\n\nProcess:\n\nCheck for image API key — if none found, skip this step (book works fine without images).\n\n\nSplit manuscript into chapters for illustration planning:\nThe orchestrator processes each chapter section from book/final-manuscript.md directly.\nNo splitting needed — feed each chapters/chapter-NN.md file to the illustrator.\n\n\nDetermine diagram count and placement (REQUIRED before generating):\nDiagram count by chapter length:\nChapter LengthMin DiagramsTarget< 3,000 words233,000–5,000 words34–55,000–8,000 words45–7> 8,000 words57–10\nPlacement rules:\n\nOverview diagram: Always first — within the first 200 words / before first H2. Type: concept-map, radial-concept, or architecture. Purpose: bird's-eye view of the whole chapter.\nPer-section diagrams: 1 per major H2 section, placed after the first paragraph of that section.\nMax gap: No stretch longer than 2,000 words without a diagram.\n\nDiagram type by section content:\nContent TypeZ.AI (scrapbook)MermaidSystem/architectureabstract tech scrapbookarchitectureProcess/workflowsteps/flow scrapbookflowchart, sequenceComparison/tradeoffsbalance/scale scrapbookcomparison-tableData/trends/metricschart/graph scrapbooktimeline, ganttConcepts/relationshipsabstract concept scrapbookconcept-map, radial-concept\n\n\nFor each chapter, invoke the article-illustrator workflow:\n\nRead article-illustrator/references/scrapbook-prompt.md for the system prompt\nRead the scrapbook system prompt from the article-illustrator skill:\ncat <article_illustrator_dir>/references/scrapbook-prompt.md\n\n\nAnalyze the chapter text and generate a JSON illustration plan:\n{\n  \"project_title\": \"Chapter N — Scrapbook Style\",\n  \"style\": \"Physical Mixed-Media Scrapbook\",\n  \"total_images\": 2,\n  \"images\": [\n    {\n      \"image_id\": 1,\n      \"title\": \"Caption\",\n      \"description\": \"300-500 char scrapbook visual description...\",\n      \"insert_after\": \"Exact heading or sentence\"\n    }\n  ]\n}\n\n\nTarget: 1 image per 1,500-2,000 words (books are less dense than articles)\nGenerate all images in parallel using the article-illustrator script:\ncd <article_illustrator_dir>\npython3 scripts/generate.py \"<description_1>\" --language en --size 1088x1920 &\npython3 scripts/generate.py \"<description_2>\" --language en --size 1088x1920 &\nwait  # Both images generate concurrently (~20-40s each)\n\nThe script reads ZAI_API_KEY, GLM_API_KEY, or OPENROUTER_API_KEY automatically.\nInsert images at designated anchor points\n\n\n\nCompose illustrated manuscript:\nInsert each image after its designated insert_after anchor:\n![Caption](diagrams/chapter-NN/image-01.png)\n\nSave the illustrated chapter to chapters/chapter-NN.md (replace in-place).\nThen re-run merge to update the full manuscript:\npython3 <skill_dir>/scripts/merge_chapters.py --title \"Title\" --author \"Author\" \\\n  --output book/illustrated-manuscript.md\n\n\n\nCost tracking: ~$0.015/image (Z.AI) × images. For a 10-chapter book with 1-2 images each: ~$0.15-0.30.\n\nImage count guidelines by book size:\n\nBook SizeChaptersImages/ChapterTotal ImagesEst. Cost (Z.AI)Small (2-3)2-31-22-6$0.03-0.09Medium (5-8)5-81-25-16$0.08-0.24Large (10-15)10-151-210-30$0.15-0.45\n\nDone when: book/illustrated-manuscript.md exists with images embedded.\n\nFallback — Mermaid diagrams via skill-mermaid-diagrams (no image API key needed):\n\nIf no image API key is available (ZAI_API_KEY, GLM_API_KEY, OPENROUTER_API_KEY all missing), use the skill-mermaid-diagrams skill (clawhub install skill-mermaid-diagrams) to generate professional, template-based diagrams:\n\nInstall if needed:\nclawhub install skill-mermaid-diagrams\n\n\n\nFor each chapter, spawn a subagent:\nGenerate 2-3 Mermaid diagrams for /path/to/chapters/chapter-NN.md\nand save to /path/to/diagrams/chapter-NN/\n\n\n\nThe subagent will:\n\nRead chapter content\nSelect from 12 available templates: architecture, flowchart, sequence, concept-map, radial-concept, timeline, comparison, comparison-table, gantt, mindmap, class-diagram, state-diagram\nGenerate content.json with placeholder values\nRun node $SKILL_DIR/scripts/generate.mjs --content content.json --out diagrams/chapter-NN\nValidate: node $SKILL_DIR/scripts/validate.mjs --dir diagrams/chapter-NN\nOutput: .mmd source + .svg vector + .png raster for each diagram\n\n\n\nInsert into manuscript: Reference generated images in markdown:\n![Architecture Overview](diagrams/chapter-01/diagram-01-architecture.png)\n\n\n\nCost: ~$0.002/chapter (LLM tokens only) — rendering is free (local mmdc).\nFor a 10-chapter book: ~$0.02 total (vs $0.15-0.45 for AI images).\n\n\nConsistent styling: All diagrams share a unified color scheme across chapters.\n\nDecision logic:\n\nif image API key exists AND user did not pass --no-illustrations:\n    → Path A: scrapbook illustrations (article-illustrator, ~$0.015/image)\nelif user passed --no-illustrations:\n    → skip entirely\nelse:\n    → Path B: Mermaid diagrams (free, LLM-generated)\n\nSkip entirely when: User specified --no-illustrations --no-diagrams."
      },
      {
        "title": "Step 9 — HTML Export (Optional)",
        "body": "python3 <skill_dir>/scripts/convert_to_html.py --input book/illustrated-manuscript.md --output book/book.html\n# Falls back to final-manuscript.md if illustrated version doesn't exist\n\nRequires either pandoc or pip install markdown2."
      },
      {
        "title": "Step 10 — Commit and Report",
        "body": "git add -A\ngit commit -m \"book: complete manuscript - [word_count] words, [chapter_count] chapters\"\ngit push\n\nReport to user: chapter count, word count, file locations, GitHub URL."
      },
      {
        "title": "Agent Model Recommendations",
        "body": "RoleModelWhyDirector (you)anthropic/claude-sonnet-4-6Planning, coordinationResearchopenrouter/google/gemini-2.5-pro-previewLarge context, data synthesisWritinganthropic/claude-sonnet-4-6Coherent long-form proseReviewopenrouter/deepseek/deepseek-v3.2Cost-effective, thoroughIntegration/Polishanthropic/claude-sonnet-4-6Consistent merging"
      },
      {
        "title": "Cost Estimates",
        "body": "Book SizeApprox. API CostTime (parallel)5 chapters, ~30K words$5-152-4 hours10 chapters, ~60K words$15-354-8 hours14 chapters, ~88K words$30-606-12 hours"
      },
      {
        "title": "Directory Structure",
        "body": "book-project/\n├── project-notes/\n│   ├── SYSTEM.md         # State machine, agent roles, safety rules\n│   ├── AGENDA.md         # Sprint plan, daily tasks, success metrics\n│   └── WORKLOG.md        # Append-only execution log\n├── chapters/\n│   ├── introduction.md\n│   ├── chapter-01-outline.md\n│   ├── chapter-01.md\n│   └── ...\n├── book/\n│   ├── manuscript.md        # Merged pre-polish\n│   ├── final-manuscript.md  # Final polished\n│   ├── book.html\n│   └── metadata.json\n├── diagrams/\n├── research/\n│   ├── [topic]-analysis.md\n│   └── pattern-synthesis.md\n├── reviews/\n│   └── quality-review-*.md\n└── scripts/\n    ├── merge_chapters.py\n    ├── polish_manuscript.py\n    └── convert_to_html.py"
      },
      {
        "title": "WORKLOG Protocol",
        "body": "Every agent must append to WORKLOG.md at start and finish:\n\n## [YYYY-MM-DD HH:MM TZ] - [Agent Name] - [Action]\n**State:** WRITING\n**Completed:** chapter-07.md (6,847 words)\n**Next:** chapter-08.md\n**Issues:** None\n\nDirector reads this to know what's done without polling agents."
      },
      {
        "title": "Error Handling",
        "body": "ProblemDetectionActionAgent fails mid-chapterWORKLOG shows no update for >2 hoursRespawn agent with same taskChapter too short<4,000 wordsRespawn writing agent with explicit \"expand\" instructionQuality review fails>3 CRITICAL issues per chapterRespawn writing agent to rewrite sectionMerge script failsPython errorCheck chapter file naming (must be chapter-NN.md)Cost exceeds budgetTrack cumulative spendPause and consult userCross-reference brokenReview shows \"Chapter N\" pointing nowhereFix manually in integration phase"
      },
      {
        "title": "Success Criteria",
        "body": "All chapters drafted (target: ~6,000-8,000 words each)\nQuality review: >85% of issues marked RESOLVED\nFinal manuscript: single cohesive document with TOC\nHTML export renders correctly (if requested)\nGit committed and pushed\nTotal word count within 20% of target"
      },
      {
        "title": "Configuration",
        "body": "No persistent configuration required. The skill uses:\n\nRecommended config (enables orchestrator pattern):\n\n{\n  \"agents\": {\n    \"defaults\": {\n      \"subagents\": {\n        \"maxSpawnDepth\": 2,\n        \"maxChildrenPerAgent\": 5,\n        \"maxConcurrent\": 8\n      }\n    }\n  }\n}\n\nWithout maxSpawnDepth: 2, the skill falls back to Director-controlled mode (see\nArchitecture section for tradeoffs).\n\nRequired tools:\n\nToolPurposeexecRun Python scripts, git commandssessions_spawnSpawn orchestrator and/or worker sub-agentsread / writeRead/write chapter files\n\nOptional tools:\n\nToolPurposeweb_searchResearch phase (if no source repo provided)web_fetchFetch source repo content\n\nSystem dependencies:\n\nDependencyPurposePython 3.8+merge, polish, HTML conversion scriptsgitVersion controlpandoc (optional)Better HTML conversion"
      },
      {
        "title": "Notes",
        "body": "Set cost_limit: $100 in SYSTEM.md as a safety guard\nThe WORKLOG protocol is critical — agents that don't update WORKLOG create blind spots\nCommit to git after every phase, not just at the end\nFor very long books (>100K words), increase chapter count rather than word-per-chapter target\nThe reference implementation at openclaw-paradigm-book includes all project notes for study"
      }
    ],
    "body": "Git Repo to Book\n\nWrite a full-length technical book using multi-agent AI orchestration. Based on the real workflow that produced The OpenClaw Paradigm — 88,000+ words, 14 chapters, 42 diagrams in under 18 hours.\n\nScope & Boundaries\n\nThis skill handles:\n\nPlanning, researching, writing, reviewing, and publishing multi-chapter technical books\nRevising individual chapters of existing books (review → rewrite → re-integrate)\nOrchestrating parallel sub-agents for each phase\nMerging chapters into a polished manuscript with TOC, metadata, and HTML export\nManaging the WORKLOG protocol for agent coordination\n\nThis skill does NOT handle:\n\nCover design or artwork generation (use an illustration skill)\nPublishing to Amazon/Kindle/bookstores (output is Markdown + HTML)\nFiction/creative writing (optimized for technical/non-fiction)\nTranslation to other languages\nInputs\nInput\tRequired\tDescription\nTopic/subject\tYes\tWhat the book is about\nSource repo\tNo\tGitHub URL to analyze as source material\nChapter count\tNo\tAuto-scaled from repo size (see below), or user override\nTarget length\tNo\tAuto-scaled from repo size (see below), or user override\nBudget limit\tNo\tMax API cost in dollars. Default: $100. Agent pauses if exceeded\nOutput formats\tNo\tMarkdown (always), HTML (optional), PDF (optional)\nModel preferences\tNo\tDefaults in Agent Model Recommendations section\nOutputs\nbook/final-manuscript.md — polished, publication-ready manuscript\nbook/illustrated-manuscript.md — manuscript with scrapbook illustrations (if article-illustrator available)\nbook/metadata.json — title, author, word count, chapter count, date\nbook/book.html — HTML export (optional)\nGit repository with full project history\nAuto-Scaling: Repo Size → Book Size\n\nWhen a source repo is provided, automatically assess its scope before planning:\n\n# Count source files and total lines\nfind <repo> -name '*.py' -o -name '*.ts' -o -name '*.js' -o -name '*.go' -o -name '*.rs' -o -name '*.md' | wc -l\nfind <repo> -name '*.py' -o -name '*.ts' -o -name '*.js' -o -name '*.go' -o -name '*.rs' -o -name '*.md' | xargs wc -l 2>/dev/null | tail -1\n\nRepo Size\tSource Files\tLines of Code\tRecommended Chapters\tTarget Words\tEstimated Cost\nSmall\t<50 files\t<5K lines\t5-6 chapters\t~30,000\t$5-15\nMedium\t50-200 files\t5K-30K lines\t8-10 chapters\t~55,000\t$15-35\nLarge\t200-500 files\t30K-100K lines\t12-14 chapters\t~80,000\t$30-60\nVery Large\t>500 files\t>100K lines\t14-18 chapters\t~100,000+\t$50-100\n\nIf no source repo is provided (topic-only book), default to Medium (10 chapters, ~55K words).\n\nThe user can always override these defaults.\n\nPre-Flight Cost Estimation\n\nBefore starting any work, present the user with a cost estimate and get confirmation:\n\n## Book Project Estimate\n\n**Topic:** [topic]\n**Source:** [repo URL or \"topic-only\"]\n**Repo size:** [Small/Medium/Large/Very Large] ([N] files, [N] lines)\n\n**Plan:**\n- Chapters: [N]\n- Target words: ~[N]\n- Writing agents: [N] parallel\n- Estimated API cost: $[X]-$[Y]\n\n**Budget limit:** $[user-set or 100 default]\n\n**Models:**\n- Writing: claude-sonnet-4-6 (~$0.003/1K input, $0.015/1K output)\n- Research: gemini-2.5-pro (~$0.002/1K input, $0.012/1K output)\n- Review: deepseek-v3.2 (~$0.001/1K input, $0.003/1K output)\n\nProceed? (yes / adjust budget / change chapter count)\n\n\nCost tracking during execution: After each phase, log cumulative spend in WORKLOG.md:\n\n## Cost Checkpoint - Phase [N] Complete\n**Phase cost:** $X.XX\n**Cumulative:** $XX.XX / $[budget] budget\n**Remaining budget:** $XX.XX\n**Projected total:** $XX.XX (on track / over budget)\n\n\nIf projected total exceeds budget by >20%, pause and ask the user before continuing.\n\nArchitecture\nWhy an Orchestrator Subagent (not direct Director control)\n\nThe naive approach is: Director spawns research agents, waits for completion announce, spawns writing agents, waits again, etc. This breaks in practice because:\n\nAnnounce-to-action gap: When a subagent finishes, OpenClaw sends a completion message to the parent session. The parent gets a new turn, but it must choose to chain the next phase. If it treats the announce as informational (reports results to user and stops), the pipeline stalls. There is no guaranteed hook that forces the next action.\n\nContext loss between turns: Each turn the Director takes is a fresh LLM call. Between subagent completion and the next turn, there's no persistent state machine tracking \"we're in phase 3 of 7.\" The Director must re-derive pipeline state from WORKLOG.md every time, which is fragile.\n\nUser messages interrupt: If the user sends a message between phases, the Director's next turn handles that message instead of continuing the pipeline. The pipeline stalls until another trigger arrives.\n\nSolution: Orchestrator subagent pattern. The Director spawns a single orchestrator subagent (maxSpawnDepth: 2) that owns the entire pipeline lifecycle. The orchestrator runs as a continuous session, spawning worker sub-sub-agents for each phase and immediately chaining the next phase when workers complete. Because it's a single continuous run, there's no announce-to-action gap — the orchestrator never yields control between phases.\n\nDirector (main agent, depth 0)\n    │\n    └── Orchestrator (subagent, depth 1) ← owns entire pipeline\n        │\n        ├── Phase 1: RESEARCH workers (depth 2, parallel)\n        │   └── research/*.md → pattern-synthesis.md\n        │\n        ├── Phase 2: OUTLINE workers (depth 2, parallel)\n        │   └── chapters/*-outline.md\n        │\n        ├── Phase 3: WRITING workers (depth 2, 3 chapters each)\n        │   └── chapters/chapter-NN.md\n        │\n        ├── Phase 4: REVIEW workers (depth 2, parallel)\n        │   └── reviews/quality-review-*.md\n        │\n        ├── Phase 5: INTEGRATION (orchestrator does this directly)\n        │   └── book/manuscript.md\n        │\n        ├── Phase 6: POLISH (orchestrator does this directly)\n        │   └── book/final-manuscript.md + metadata.json\n        │\n        ├── Phase 7: ILLUSTRATE (orchestrator invokes article-illustrator per chapter)\n        │   └── book/illustrated-manuscript.md (scrapbook images at section breaks)\n        │\n        └── Phase 8: PUBLISH (orchestrator does this directly)\n            └── git commit + push + report\n\nDepth Model\nDepth\tRole\tSpawns children?\tHas session tools?\n0\tDirector (main agent)\tYes — spawns orchestrator\tFull tools\n1\tOrchestrator\tYes — spawns workers\tGets sessions_spawn, subagents, sessions_list, sessions_history\n2\tWorkers (research, writing, review)\tNo\tFile I/O + exec only\n\nRequires: agents.defaults.subagents.maxSpawnDepth: 2 in OpenClaw config.\n\nIf maxSpawnDepth is 1 (default), the skill falls back to Director-controlled mode (see Fallback section below).\n\nFallback: Director-Controlled Mode (maxSpawnDepth: 1)\n\nIf nested subagents are not available, the Director orchestrates directly:\n\nSpawns each phase's workers as depth-1 subagents\nWhen completion announces arrive, must immediately chain the next phase\nPipeline state tracked via WORKLOG.md\nRisk: announce-to-action gap if Director doesn't chain (see justification above)\n\nTo mitigate, set a cron safety net after spawning:\n\ncron: \"Check book pipeline state in WORKLOG.md. If last phase completed but next\nphase not started, resume the pipeline.\" (fire 15 minutes after spawn)\n\nAgent Coordination\n\nAll agents coordinate via WORKLOG.md (append-only). The orchestrator (or Director in fallback mode) reads WORKLOG to track progress. Workers append entries when starting and finishing work.\n\nEnd-to-End Example\n\nUser says: \"Write a technical book about AI-native software development. Source: https://github.com/openclaw/openclaw\"\n\nStep 1 — Gather requirements:\n\nTopic: AI-native software development\nSource repo: openclaw/openclaw\nChapters: 12 (default)\nTarget: ~80,000 words\n\nStep 2 — Set up repo and spawn orchestrator:\n\nmkdir -p book-project/{chapters,book,diagrams,research,reviews,scripts,project-notes}\ncd book-project && git init\n\n\nCopy templates, then spawn the orchestrator subagent (depth 1) which manages all remaining phases. The orchestrator spawns worker sub-sub-agents (depth 2) in parallel.\n\nStep 3 — Research phase (orchestrator spawns 3 parallel workers):\n\nAgent A task: \"Analyze openclaw/openclaw architecture. Focus on session management,\ntool system, and agent lifecycle. Output: research/architecture-analysis.md. \nRead WORKLOG.md first. Update WORKLOG.md when complete.\"\n\nAgent B task: \"Analyze openclaw/openclaw skills system and plugin architecture.\nOutput: research/skills-analysis.md. Read WORKLOG.md first.\"\n\nAgent C (synthesis): \"Read all files in research/. Synthesize into \nresearch/pattern-synthesis.md. Identify 6-10 core patterns and 3-5 anti-patterns.\"\n\n\nStep 4 — Outline phase (spawn 2 agents):\n\nAgent 1: \"Write detailed outlines for intro + chapters 1-6. Reference pattern-synthesis.md.\nOutput: chapters/chapter-NN-outline.md per chapter.\"\n\nAgent 2: \"Write detailed outlines for chapters 7-12.\"\n\n\nReview and commit outlines.\n\nStep 5 — Writing phase (spawn 4 parallel agents, 3 chapters each):\n\nAgent 1: \"Write intro + chapters 1-3. Read outlines and pattern-synthesis.md.\nTarget: 6,000-8,000 words per chapter. Update WORKLOG.md when each chapter is complete.\"\n\nAgent 2: \"Write chapters 4-6.\"\nAgent 3: \"Write chapters 7-9.\"\nAgent 4: \"Write chapters 10-12.\"\n\n\nModel: anthropic/claude-sonnet-4-6\n\nStep 6 — Review phase (spawn 2 agents):\n\nAgent A: \"Review intro + chapters 1-6. Check: logical flow, unsupported claims,\ncontradictions, missing examples. Output: reviews/quality-review-01-06.md.\nMark issues CRITICAL or MINOR.\"\n\n\nFix CRITICAL issues before proceeding.\n\nStep 7 — Integration:\n\npython3 <skill_dir>/scripts/merge_chapters.py --title \"AI-Native Development\" --author \"Author Name\"\n\n\nStep 8 — Polish:\n\npython3 <skill_dir>/scripts/polish_manuscript.py --title \"AI-Native Development\" --author \"Author Name\"\n\n\nStep 9 — HTML export:\n\npython3 <skill_dir>/scripts/convert_to_html.py\n\n\nStep 10 — Commit and report:\n\ngit add -A && git commit -m \"book: complete manuscript\" && git push\n\n\nReport: chapter count, word count, file locations, GitHub URL.\n\nChapter Revision Mode\n\nRevise a single chapter of an existing book without regenerating the entire manuscript.\n\nWhen to Use\nA chapter is outdated (new features, changed APIs)\nQuality is below standard (reviewer scored it low)\nUser wants a different angle or deeper coverage\nNew information needs to be incorporated\nRevision Inputs\nInput\tRequired\tDescription\nBook repo\tYes\tLocal path or GitHub URL of the existing book\nChapter number\tYes\tWhich chapter to revise (e.g., 3 or chapter-03)\nRevision instructions\tNo\tSpecific guidance: \"add more examples\", \"update for v2 API\", \"make it more practical\"\nBudget limit\tNo\tDefault: $5 per chapter revision\nRevision Workflow\nStep R1 — Clone and Analyze\ngit clone <repo_url> /tmp/book-revision\ncd /tmp/book-revision\n\n\nRead the target chapter + its outline + adjacent chapters (N-1 and N+1) for context continuity.\n\nStep R2 — Review Current Chapter\n\nSpawn a reviewer agent to score the existing chapter on the standard rubric:\n\nTechnical accuracy\nCompleteness (are topics from the outline covered?)\nCode examples (working? up to date?)\nFlow and readability\nConsistency with adjacent chapters\n\nThe reviewer produces reviews/revision-review-chapter-NN.md with:\n\nScore per dimension\nSpecific issues found\nRecommended changes\nStep R3 — Research Updates (if needed)\n\nIf the revision requires new information (updated APIs, new features, recent events):\n\nSpawn a research agent to:\n\nQuery DeepWiki MCP (curl https://api.deepwiki.com/v1/chat) for current repo architecture and features\nAnalyze the source repo (if provided) for changes since the chapter was written\nWeb search for updated information and external context\nProduce research/revision-research-chapter-NN.md\n\nDeepWiki is the preferred research source for GitHub repo-based books — it provides deep, structured answers about architecture, components, and patterns.\n\nSkip if the revision is purely stylistic (rewrite for clarity, add examples from existing content).\n\nStep R4 — Rewrite\n\nSpawn a writer agent with:\n\nThe existing chapter text\nThe review (from R2)\nResearch updates (from R3, if any)\nThe chapter outline\nAdjacent chapters (for tone/style consistency)\nUser's revision instructions\n\nThe writer produces a new version: chapters/chapter-NN-revised.md\n\nKey constraints for the writer:\n\nPreserve the chapter's position in the book narrative (don't contradict adjacent chapters)\nKeep the same heading structure unless the outline changed\nMaintain consistent terminology with the rest of the book\nIf the original had diagrams, preserve or update diagram references\nStep R5 — Review (Mobile-Friendly)\n\nUsers often review from a phone (iPhone/Android via Discord, Signal, or Telegram). The review workflow adapts to the platform:\n\nPath A — GitHub PR (preferred, best for diff review):\n\ncd /tmp/book-revision\ngit checkout -b revise/chapter-NN\n\n# Backup original\ncp chapters/chapter-NN.md chapters/chapter-NN-pre-revision.md\n\n# Replace with revised version\ncp chapters/chapter-NN-revised.md chapters/chapter-NN.md\n\ngit add -A\ngit commit -m \"revise: chapter NN - [summary of changes]\"\ngit push origin revise/chapter-NN\n\n# Open PR with summary as description\ngh pr create --title \"Revise Chapter NN: [title]\" \\\n  --body \"$(cat reviews/revision-summary-chapter-NN.md)\" \\\n  --base main --head revise/chapter-NN\n\n\nThe user reviews the diff in GitHub mobile app (excellent diff viewer), then:\n\nComments \"LGTM\" or \"approve\" → agent merges PR and re-generates manuscript\nComments with feedback → agent makes changes, pushes to same branch\nCloses PR → revision discarded\n\nPath B — Obsidian sync (for offline reading):\n\nIf the user has Obsidian configured (e.g., via save-to-obsidian.sh):\n\n# Send revised chapter + summary to Obsidian vault\nsave-to-obsidian.sh chapters/chapter-NN-revised.md\nsave-to-obsidian.sh reviews/revision-summary-chapter-NN.md\n\n\nUser reads the full chapter on Obsidian mobile, replies via chat.\n\nPath C — Chat summary (quickest):\n\nPost a concise summary (≤500 words) directly in chat:\n\n📝 Chapter NN Revision Summary\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nWords: 3,510 → 5,200 (+48%)\n\n✅ Sections rewritten:\n  - 2.1: Updated architecture description\n  - 2.3: Added 3 new code examples\n\n➕ Sections added:\n  - 2.6: New \"Deployment Models\" section\n\n🔗 Full diff: [GitHub PR link]\n📖 Full chapter: [Obsidian / GitHub link]\n\nReply \"approve\", \"changes needed\", or specific feedback.\n\n\nAuto-detect by content type:\n\nText-only revision (no new diagrams/images): Default to Path A (PR) + Path C (chat summary). GitHub diff is ideal for text changes.\nIllustrated revision (new or updated diagrams/images): Default to Path B (Obsidian) + Path C (chat summary). Obsidian renders images inline — you see the chapter exactly as it appears in the book. GitHub PR diffs show images as \"binary file changed\" which is useless for review.\nUser preference overrides — if they ask for a specific path, use it.\n\nRecommendation: For chapters with diagrams (most technical books), Obsidian preview is the best experience on mobile. Use the PR for the final merge step after Obsidian review.\n\nStep R6 — Integrate\n\nOn user approval (via PR merge, chat reply, or Obsidian feedback):\n\nBest practice: Replace in-place, never create -new or -v2 suffixes.\n\nchapters/chapter-NN.md ← always overwrite the current file\ndiagrams/chapter-NN/ ← always replace diagrams in the same directory\nNo backups (-pre-revision, -old, -v2) — git history IS the backup\nNo new directories (chapter-02-new/) — the PR diff shows what changed\n\nThis prevents suffix accumulation (-new, -new-new, -new-v3) across revisions.\n\n# If using PR workflow, the merge already happened. Just regenerate manuscript:\ncd /tmp/book-revision\ngit checkout main && git pull\n\n# Re-merge all chapters into manuscript\npython3 <skill_dir>/scripts/merge_chapters.py --title \"[Title]\" --author \"[Author]\" --output book/manuscript.md\npython3 <skill_dir>/scripts/polish_manuscript.py --title \"[Title]\" --author \"[Author]\" --output book/final-manuscript.md\n\n# Commit updated manuscript\ngit add book/\ngit commit -m \"book: regenerate manuscript after chapter NN revision\"\ngit push\n\nStep R6.5 — Validate Links (automated)\n\nAfter integration, run the link validator to catch broken references:\n\npython3 <skill_dir>/scripts/validate_links.py --book-dir /path/to/book\n\n\nThis checks:\n\nAll ![image](path) references point to existing files\nAll [link](file.md) references resolve\nNo orphaned diagram directories\nSuggests fixes for broken links (fuzzy match on filenames)\n\nMust pass with 0 broken links before proceeding to R7 or committing.\n\nAlso verify metadata block exists:\n\ngrep -c \"## Chapter Metadata\" chapters/chapter-NN.md || echo \"ERROR: Missing metadata block\"\n\n\nIf missing, add it before committing.\n\nIf broken links are found:\n\nFix image paths to match actual filenames in diagrams/chapter-NN/\nRe-run validator until clean\nAlso run on book/final-manuscript-with-diagrams.md if it exists (merged manuscript may have stale refs)\nStep R7 — Re-illustrate (Optional)\n\nIf the chapter content changed significantly (>30% rewritten), regenerate diagrams:\n\nWith image API key: Re-run article-illustrator for the revised chapter\nWithout image API key: Re-run skill-mermaid-diagrams for the revised chapter\nRevision Cost Estimate\nComponent\tModel\tEst. Cost\nReview\tdeepseek\t$0.01-0.02\nResearch (if needed)\tgemini-pro\t$0.05-0.10\nRewrite\tclaude-sonnet\t$0.10-0.30\nRe-illustrate (if needed)\tZ.AI\t$0.03-0.06\nTotal per chapter\t\t$0.15-0.50\nExample: Revise Chapter 3\nUser: \"Revise chapter 3 of https://github.com/chunhualiao/openclaw-paradigm-book\n       — it needs more real-world case studies and the code examples are outdated\"\n\nAgent:\n1. Clone repo, read chapter-03.md + chapter-02.md + chapter-04.md + chapter-03-outline.md\n2. Spawn reviewer → scores chapter, finds: \"only 2 case studies, code uses deprecated API\"\n3. Spawn research agent → checks OpenClaw repo for current API, finds 3 new case studies\n4. Spawn writer → rewrites chapter with 5 case studies, updated code, same structure\n5. Present diff summary to user\n6. On approval: replace chapter, re-merge manuscript, commit + push\n\nChapter Metadata Block (Required)\n\nEvery chapter must end with a metadata block providing provenance and reproducibility information. This is critical because source repos evolve fast — readers need to know which version the chapter describes.\n\nTemplate (append to end of each chapter):\n\n---\n\n## Chapter Metadata\n\n> **This section is auto-generated by the book-writer skill.**\n\n| Field | Value |\n|-------|-------|\n| **Subject Repo** | [owner/repo](https://github.com/owner/repo) |\n| **Subject Repo Commit** | [`abc1234`](https://github.com/owner/repo/commit/abc1234) |\n| **Subject Repo Version** | vX.Y.Z (or \"latest as of YYYY-MM-DD\") |\n| **Book Repo** | [owner/book-repo](https://github.com/owner/book-repo) |\n| **Book-Writer Skill** | [git-repo-to-book](https://clawhub.ai/YOUR_HANDLE/git-repo-to-book) |\n| **Research Source** | DeepWiki / web search / direct repo analysis |\n| **Diagrams** | N × type (skill used) |\n| **Writer Model** | model name |\n| **Reviewer Model** | model name |\n| **Generated/Revised** | YYYY-MM-DD |\n| **Word Count** | X,XXX |\n\n**⚠️ Freshness Note:** This chapter describes [repo] as of commit `abc1234`.\nVerify current state at [docs link] or [DeepWiki link].\n\n\nWhy this matters:\n\nSource repos change daily — without a commit pin, the chapter becomes unreproducible\nModel attribution helps readers understand potential biases\nFreshness warnings prevent readers from treating outdated info as current\nSkill version enables reproducing the exact pipeline\n\nWhen revising: Update all metadata fields. The old commit → new commit change is the most important field to update.\n\nSetup & Configuration\nStep 0 — Environment Discovery (run before every book/revision)\n\nBefore starting any pipeline, discover available API keys and expose them as environment variables. The skill uses multiple external services — some required, some optional.\n\nRun this discovery check:\n\n# === REQUIRED ===\n# At least one LLM provider must be configured (check OpenClaw config)\necho \"=== LLM Providers ===\"\ngrep -o '\"openrouter_api_key\"\\|\"anthropic_api_key\"\\|\"openai_api_key\"' ~/.openclaw/config.json 2>/dev/null && echo \"✅ LLM provider found\" || echo \"❌ No LLM provider in config\"\n\n# === OPTIONAL: Image Generation ===\necho \"=== Image Generation (for scrapbook illustrations) ===\"\n# Check all possible locations: env vars, config.json, .env files\nZAI=$(grep -o '\"zai_api_key\"' ~/.openclaw/config.json 2>/dev/null)\nGLM=$(grep -o '\"glm_api_key\"' ~/.openclaw/config.json 2>/dev/null)\nOR=$(grep -o '\"openrouter_api_key\"' ~/.openclaw/config.json 2>/dev/null)\n[ -n \"$ZAI\" ] && echo \"✅ Z.AI ($0.015/image)\" || echo \"⬜ Z.AI not configured\"\n[ -n \"$GLM\" ] && echo \"✅ GLM ($0.014/image)\" || echo \"⬜ GLM not configured\"\n[ -n \"$OR\" ] && echo \"✅ OpenRouter ($0.045/image)\" || echo \"⬜ OpenRouter not configured\"\n[ -z \"$ZAI\" ] && [ -z \"$GLM\" ] && [ -z \"$OR\" ] && echo \"→ Will use Mermaid diagrams (free) instead of scrapbook images\"\n\n# === OPTIONAL: Mermaid Diagrams ===\necho \"=== Mermaid CLI (for diagram generation) ===\"\nwhich mmdc >/dev/null 2>&1 && echo \"✅ mmdc $(mmdc --version 2>/dev/null)\" || echo \"⬜ mmdc not installed (run: npm install -g @mermaid-js/mermaid-cli)\"\n\n# === OPTIONAL: DeepWiki ===\necho \"=== DeepWiki MCP (for repo research) ===\"\ncurl -s --max-time 3 https://api.deepwiki.com/v1/health >/dev/null 2>&1 && echo \"✅ DeepWiki API reachable\" || echo \"⬜ DeepWiki unreachable (will use direct repo analysis)\"\n\n# === OPTIONAL: GitHub CLI ===\necho \"=== GitHub CLI (for PR workflow) ===\"\ngh auth status >/dev/null 2>&1 && echo \"✅ gh authenticated as $(gh api user -q .login 2>/dev/null)\" || echo \"⬜ gh not authenticated (PR review workflow unavailable)\"\n\n# === OPTIONAL: Obsidian sync ===\necho \"=== Obsidian (for mobile preview) ===\"\n[ -f ~/.openclaw/scripts/save-to-obsidian.sh ] && echo \"✅ Obsidian sync script found\" || echo \"⬜ No Obsidian sync (chat-only review)\"\n\n\nExpose keys as env vars (so subagents/scripts can access them):\n\n# Extract from OpenClaw config and export\nexport ZAI_API_KEY=$(python3 -c \"import json; c=json.load(open('$HOME/.openclaw/config.json')); print(c.get('zai_api_key',''))\" 2>/dev/null)\nexport GLM_API_KEY=$(python3 -c \"import json; c=json.load(open('$HOME/.openclaw/config.json')); print(c.get('glm_api_key',''))\" 2>/dev/null)\nexport OPENROUTER_API_KEY=$(python3 -c \"import json; c=json.load(open('$HOME/.openclaw/config.json')); print(c.get('openrouter_api_key',''))\" 2>/dev/null)\n\nWhat Happens When Keys Are Missing\nMissing Key\tImpact\tFallback\nAll LLM providers\tFatal — cannot proceed\tAsk user to configure at least one provider in ~/.openclaw/config.json\nAll image keys (ZAI, GLM, OR)\tNo scrapbook illustrations\tMermaid diagrams via skill-mermaid-diagrams (free)\nmmdc CLI\tNo rendered diagram PNGs/SVGs\tRaw mermaid code blocks in markdown (still renders in GitHub/Obsidian)\nDeepWiki\tWeaker research for repo-based books\tDirect repo analysis + web search\ngh CLI\tNo PR review workflow\tObsidian preview or chat summary only\nObsidian sync\tNo mobile preview with images\tGitHub PR + chat summary\n\nThe skill always works — missing optional keys degrade gracefully to free alternatives. Only LLM provider keys are required.\n\nFull Book Workflow (New Books)\nStep 1 — Gather Requirements and Estimate Cost\n\nAsk the user (or infer from context):\n\nTopic/subject — what is the book about?\nSource repo (optional) — GitHub URL to analyze as source material\nBudget limit — how much are they willing to spend? (default: $100)\nOutput formats — Markdown (always), HTML, PDF (optional)\n\nIf a source repo is provided, run the auto-scaling assessment (see above) to determine chapter count and target length. Then present the Pre-Flight Cost Estimation and wait for user confirmation before proceeding.\n\nIf the user sets a budget below the estimated cost, suggest reducing chapter count or using cheaper models (e.g., deepseek for writing instead of claude).\n\nStep 2 — Set Up Repo and Spawn Orchestrator\nmkdir -p book-project/{chapters,book,diagrams,research,reviews,scripts,project-notes}\ncd book-project && git init\n\n\nCopy templates from <skill_dir>/templates/ into project-notes/ and edit for your project. Replace <skill_dir> with the directory containing this SKILL.md.\n\nThen spawn the orchestrator subagent (preferred, requires maxSpawnDepth: 2):\n\nsessions_spawn(\n  task: \"You are the book pipeline orchestrator. Run all phases (research → outlines →\n    writing → review → integration → polish → publish) for [Book Title].\n    \n    Project dir: /path/to/book-project\n    Chapters: [N]\n    Target: ~[N] words\n    Budget: $[N]\n    Source: [repo URL or topic]\n    \n    You have sessions_spawn to create worker subagents. Spawn workers in parallel\n    for each phase. When workers finish, immediately start the next phase. Never\n    stop between phases. Track costs in WORKLOG.md after each phase.\n    \n    When all phases complete, report: chapter count, word count, total cost, file paths.\",\n  model: \"anthropic/claude-sonnet-4-6\",\n  mode: \"run\"\n)\n\n\nThe orchestrator handles Steps 3-10 autonomously. The Director only needs to relay the final report to the user.\n\nIf maxSpawnDepth is 1 (fallback), the Director runs Steps 3-10 directly, spawning workers as depth-1 subagents and chaining phases on each completion announce.\n\nStep 3 — Research Phase\n\nDeepWiki MCP (preferred for GitHub repos):\n\nIf the book's source material is a GitHub repo, use the deepwiki-mcp skill (clawhub install deepwiki-mcp) for deep research:\n\n# Query DeepWiki for detailed repo analysis\ncurl -s https://api.deepwiki.com/v1/chat \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"repo\": \"owner/repo\",\n    \"messages\": [{\"role\": \"user\", \"content\": \"Describe the architecture, key components, and design patterns\"}]\n  }'\n\n\nDeepWiki provides structured, authoritative answers about any public GitHub repo — its architecture, components, patterns, and implementation details. This is far more reliable than generic web search for repo-specific questions.\n\nResearch agent should query DeepWiki for each chapter's topics, then supplement with web_search for broader context (industry trends, comparisons, external references).\n\nFallback: If DeepWiki is unavailable, fall back to direct repo analysis (clone + read files) and web search.\n\nSpawn 2-3 research agents in parallel:\n\nTask: Analyze [source_repo/topic]. Identify key patterns, concepts, and examples.\nOutput: research/[topic-area]-analysis.md\nFormat: Numbered findings, specific examples, 2000-4000 words.\nRead WORKLOG.md first to avoid duplicating work.\nUpdate WORKLOG.md when complete.\n\n\nThen spawn one synthesis agent:\n\nTask: Read all files in research/. Synthesize into research/pattern-synthesis.md.\nIdentify 6-10 core patterns and 3-5 anti-patterns.\n\n\nDone when: research/pattern-synthesis.md exists and covers 6+ patterns.\n\nStep 4 — Outline Phase\n\nSpawn outline agents (batch 5-6 outlines per agent):\n\nTask: Write detailed chapter outlines for Chapters N through M.\nReference: research/pattern-synthesis.md\nOutput: chapters/chapter-NN-outline.md per chapter\nFormat: H2 sections, 6-8 sections, 1-2 sentence description each\n\n\nReview and commit outlines before writing.\n\nDone when: All chapter-NN-outline.md files exist and reviewed.\n\nStep 5 — Writing Phase\n\nAssign 3 chapters per writing agent — this is where parallelism pays off:\n\nTask: Write Chapters X, Y, Z of [Book Title].\nRead outlines and research/pattern-synthesis.md.\nOutput: chapters/chapter-NN.md per chapter.\nTarget: ~6,000-8,000 words per chapter.\nStyle: Technical but accessible. Use concrete examples, headers, code blocks, tables.\nUpdate WORKLOG.md when each chapter is complete.\n\n\nModel: anthropic/claude-sonnet-4-6\n\nDone when: All chapter files exist and WORKLOG shows completion.\n\nStep 6 — Review Phase\n\nSpawn 1-2 review agents:\n\nTask: Review chapters [list]. Check: logical flow, unsupported claims, contradictions,\nmissing examples. Output: reviews/quality-review-[range].md\nFormat: Per-chapter bullet list. Mark CRITICAL / MINOR.\n\n\nFix CRITICAL issues. MINOR issues can be addressed in polish.\n\nDone when: Reviews exist and no open CRITICAL issues.\n\nStep 7 — Integration Phase\n\nRun the merge script:\n\npython3 <skill_dir>/scripts/merge_chapters.py --title \"[Title]\" --author \"[Author]\" --output book/manuscript.md\n\n\nOr spawn an integration agent to merge manually and fix cross-references.\n\nDone when: book/manuscript.md exists with all chapters in order.\n\nStep 8 — Polish Phase\n\nRun the polish script:\n\npython3 <skill_dir>/scripts/polish_manuscript.py --title \"[Title]\" --author \"[Author]\" --output book/final-manuscript.md\n\n\nThis adds title page, copyright, TOC with anchor links, and writes book/metadata.json.\n\nDone when: book/final-manuscript.md and book/metadata.json exist.\n\nThen validate links:\n\npython3 <skill_dir>/scripts/validate_links.py --book-dir .\n\n\nMust pass with 0 broken links before publishing.\n\nStep 8.5 — Illustrate (Optional)\n\nAdd scrapbook-style illustrations to the manuscript using the article-illustrator skill.\n\nPrerequisites: article-illustrator skill installed, at least one image API key set (ZAI_API_KEY, GLM_API_KEY, or OPENROUTER_API_KEY).\n\nProcess:\n\nCheck for image API key — if none found, skip this step (book works fine without images).\n\nSplit manuscript into chapters for illustration planning: The orchestrator processes each chapter section from book/final-manuscript.md directly. No splitting needed — feed each chapters/chapter-NN.md file to the illustrator.\n\nDetermine diagram count and placement (REQUIRED before generating):\n\nDiagram count by chapter length:\n\nChapter Length\tMin Diagrams\tTarget\n< 3,000 words\t2\t3\n3,000–5,000 words\t3\t4–5\n5,000–8,000 words\t4\t5–7\n> 8,000 words\t5\t7–10\n\nPlacement rules:\n\nOverview diagram: Always first — within the first 200 words / before first H2. Type: concept-map, radial-concept, or architecture. Purpose: bird's-eye view of the whole chapter.\nPer-section diagrams: 1 per major H2 section, placed after the first paragraph of that section.\nMax gap: No stretch longer than 2,000 words without a diagram.\n\nDiagram type by section content:\n\nContent Type\tZ.AI (scrapbook)\tMermaid\nSystem/architecture\tabstract tech scrapbook\tarchitecture\nProcess/workflow\tsteps/flow scrapbook\tflowchart, sequence\nComparison/tradeoffs\tbalance/scale scrapbook\tcomparison-table\nData/trends/metrics\tchart/graph scrapbook\ttimeline, gantt\nConcepts/relationships\tabstract concept scrapbook\tconcept-map, radial-concept\n\nFor each chapter, invoke the article-illustrator workflow:\n\nRead article-illustrator/references/scrapbook-prompt.md for the system prompt\nRead the scrapbook system prompt from the article-illustrator skill:\ncat <article_illustrator_dir>/references/scrapbook-prompt.md\n\nAnalyze the chapter text and generate a JSON illustration plan:\n{\n  \"project_title\": \"Chapter N — Scrapbook Style\",\n  \"style\": \"Physical Mixed-Media Scrapbook\",\n  \"total_images\": 2,\n  \"images\": [\n    {\n      \"image_id\": 1,\n      \"title\": \"Caption\",\n      \"description\": \"300-500 char scrapbook visual description...\",\n      \"insert_after\": \"Exact heading or sentence\"\n    }\n  ]\n}\n\nTarget: 1 image per 1,500-2,000 words (books are less dense than articles)\nGenerate all images in parallel using the article-illustrator script:\ncd <article_illustrator_dir>\npython3 scripts/generate.py \"<description_1>\" --language en --size 1088x1920 &\npython3 scripts/generate.py \"<description_2>\" --language en --size 1088x1920 &\nwait  # Both images generate concurrently (~20-40s each)\n\nThe script reads ZAI_API_KEY, GLM_API_KEY, or OPENROUTER_API_KEY automatically.\nInsert images at designated anchor points\n\nCompose illustrated manuscript: Insert each image after its designated insert_after anchor:\n\n![Caption](diagrams/chapter-NN/image-01.png)\n\n\nSave the illustrated chapter to chapters/chapter-NN.md (replace in-place). Then re-run merge to update the full manuscript:\n\npython3 <skill_dir>/scripts/merge_chapters.py --title \"Title\" --author \"Author\" \\\n  --output book/illustrated-manuscript.md\n\n\nCost tracking: ~$0.015/image (Z.AI) × images. For a 10-chapter book with 1-2 images each: ~$0.15-0.30.\n\nImage count guidelines by book size:\n\nBook Size\tChapters\tImages/Chapter\tTotal Images\tEst. Cost (Z.AI)\nSmall (2-3)\t2-3\t1-2\t2-6\t$0.03-0.09\nMedium (5-8)\t5-8\t1-2\t5-16\t$0.08-0.24\nLarge (10-15)\t10-15\t1-2\t10-30\t$0.15-0.45\n\nDone when: book/illustrated-manuscript.md exists with images embedded.\n\nFallback — Mermaid diagrams via skill-mermaid-diagrams (no image API key needed):\n\nIf no image API key is available (ZAI_API_KEY, GLM_API_KEY, OPENROUTER_API_KEY all missing), use the skill-mermaid-diagrams skill (clawhub install skill-mermaid-diagrams) to generate professional, template-based diagrams:\n\nInstall if needed:\n\nclawhub install skill-mermaid-diagrams\n\n\nFor each chapter, spawn a subagent:\n\nGenerate 2-3 Mermaid diagrams for /path/to/chapters/chapter-NN.md\nand save to /path/to/diagrams/chapter-NN/\n\n\nThe subagent will:\n\nRead chapter content\nSelect from 12 available templates: architecture, flowchart, sequence, concept-map, radial-concept, timeline, comparison, comparison-table, gantt, mindmap, class-diagram, state-diagram\nGenerate content.json with placeholder values\nRun node $SKILL_DIR/scripts/generate.mjs --content content.json --out diagrams/chapter-NN\nValidate: node $SKILL_DIR/scripts/validate.mjs --dir diagrams/chapter-NN\nOutput: .mmd source + .svg vector + .png raster for each diagram\n\nInsert into manuscript: Reference generated images in markdown:\n\n![Architecture Overview](diagrams/chapter-01/diagram-01-architecture.png)\n\n\nCost: ~$0.002/chapter (LLM tokens only) — rendering is free (local mmdc). For a 10-chapter book: ~$0.02 total (vs $0.15-0.45 for AI images).\n\nConsistent styling: All diagrams share a unified color scheme across chapters.\n\nDecision logic:\n\nif image API key exists AND user did not pass --no-illustrations:\n    → Path A: scrapbook illustrations (article-illustrator, ~$0.015/image)\nelif user passed --no-illustrations:\n    → skip entirely\nelse:\n    → Path B: Mermaid diagrams (free, LLM-generated)\n\n\nSkip entirely when: User specified --no-illustrations --no-diagrams.\n\nStep 9 — HTML Export (Optional)\npython3 <skill_dir>/scripts/convert_to_html.py --input book/illustrated-manuscript.md --output book/book.html\n# Falls back to final-manuscript.md if illustrated version doesn't exist\n\n\nRequires either pandoc or pip install markdown2.\n\nStep 10 — Commit and Report\ngit add -A\ngit commit -m \"book: complete manuscript - [word_count] words, [chapter_count] chapters\"\ngit push\n\n\nReport to user: chapter count, word count, file locations, GitHub URL.\n\nAgent Model Recommendations\nRole\tModel\tWhy\nDirector (you)\tanthropic/claude-sonnet-4-6\tPlanning, coordination\nResearch\topenrouter/google/gemini-2.5-pro-preview\tLarge context, data synthesis\nWriting\tanthropic/claude-sonnet-4-6\tCoherent long-form prose\nReview\topenrouter/deepseek/deepseek-v3.2\tCost-effective, thorough\nIntegration/Polish\tanthropic/claude-sonnet-4-6\tConsistent merging\nCost Estimates\nBook Size\tApprox. API Cost\tTime (parallel)\n5 chapters, ~30K words\t$5-15\t2-4 hours\n10 chapters, ~60K words\t$15-35\t4-8 hours\n14 chapters, ~88K words\t$30-60\t6-12 hours\nDirectory Structure\nbook-project/\n├── project-notes/\n│   ├── SYSTEM.md         # State machine, agent roles, safety rules\n│   ├── AGENDA.md         # Sprint plan, daily tasks, success metrics\n│   └── WORKLOG.md        # Append-only execution log\n├── chapters/\n│   ├── introduction.md\n│   ├── chapter-01-outline.md\n│   ├── chapter-01.md\n│   └── ...\n├── book/\n│   ├── manuscript.md        # Merged pre-polish\n│   ├── final-manuscript.md  # Final polished\n│   ├── book.html\n│   └── metadata.json\n├── diagrams/\n├── research/\n│   ├── [topic]-analysis.md\n│   └── pattern-synthesis.md\n├── reviews/\n│   └── quality-review-*.md\n└── scripts/\n    ├── merge_chapters.py\n    ├── polish_manuscript.py\n    └── convert_to_html.py\n\nWORKLOG Protocol\n\nEvery agent must append to WORKLOG.md at start and finish:\n\n## [YYYY-MM-DD HH:MM TZ] - [Agent Name] - [Action]\n**State:** WRITING\n**Completed:** chapter-07.md (6,847 words)\n**Next:** chapter-08.md\n**Issues:** None\n\n\nDirector reads this to know what's done without polling agents.\n\nError Handling\nProblem\tDetection\tAction\nAgent fails mid-chapter\tWORKLOG shows no update for >2 hours\tRespawn agent with same task\nChapter too short\t<4,000 words\tRespawn writing agent with explicit \"expand\" instruction\nQuality review fails\t>3 CRITICAL issues per chapter\tRespawn writing agent to rewrite section\nMerge script fails\tPython error\tCheck chapter file naming (must be chapter-NN.md)\nCost exceeds budget\tTrack cumulative spend\tPause and consult user\nCross-reference broken\tReview shows \"Chapter N\" pointing nowhere\tFix manually in integration phase\nSuccess Criteria\nAll chapters drafted (target: ~6,000-8,000 words each)\nQuality review: >85% of issues marked RESOLVED\nFinal manuscript: single cohesive document with TOC\nHTML export renders correctly (if requested)\nGit committed and pushed\nTotal word count within 20% of target\nConfiguration\n\nNo persistent configuration required. The skill uses:\n\nRecommended config (enables orchestrator pattern):\n\n{\n  \"agents\": {\n    \"defaults\": {\n      \"subagents\": {\n        \"maxSpawnDepth\": 2,\n        \"maxChildrenPerAgent\": 5,\n        \"maxConcurrent\": 8\n      }\n    }\n  }\n}\n\n\nWithout maxSpawnDepth: 2, the skill falls back to Director-controlled mode (see Architecture section for tradeoffs).\n\nRequired tools:\n\nTool\tPurpose\nexec\tRun Python scripts, git commands\nsessions_spawn\tSpawn orchestrator and/or worker sub-agents\nread / write\tRead/write chapter files\n\nOptional tools:\n\nTool\tPurpose\nweb_search\tResearch phase (if no source repo provided)\nweb_fetch\tFetch source repo content\n\nSystem dependencies:\n\nDependency\tPurpose\nPython 3.8+\tmerge, polish, HTML conversion scripts\ngit\tVersion control\npandoc (optional)\tBetter HTML conversion\nNotes\nSet cost_limit: $100 in SYSTEM.md as a safety guard\nThe WORKLOG protocol is critical — agents that don't update WORKLOG create blind spots\nCommit to git after every phase, not just at the end\nFor very long books (>100K words), increase chapter count rather than word-per-chapter target\nThe reference implementation at openclaw-paradigm-book includes all project notes for study"
  },
  "trust": {
    "sourceLabel": "tencent",
    "provenanceUrl": "https://clawhub.ai/chunhualiao/git-repo-to-book",
    "publisherUrl": "https://clawhub.ai/chunhualiao/git-repo-to-book",
    "owner": "chunhualiao",
    "version": "1.0.0",
    "license": null,
    "verificationStatus": "Indexed source record"
  },
  "links": {
    "detailUrl": "https://openagent3.xyz/skills/git-repo-to-book",
    "downloadUrl": "https://openagent3.xyz/downloads/git-repo-to-book",
    "agentUrl": "https://openagent3.xyz/skills/git-repo-to-book/agent",
    "manifestUrl": "https://openagent3.xyz/skills/git-repo-to-book/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/git-repo-to-book/agent.md"
  }
}