Skill: dingtom336-gif/skill-publish-to-market (version 1.0.0)

--- name: skill-publish-to-market description: "Publish any SKILL.md to 4 skill markets (ClawHub, Anthropic Skills, ECC Community, skills.sh) with one command. Collects tokens, validates quality, creates PRs, handles version conflicts, and reports results. Use when: '发布技能', '上传到GitHub', 'push to ClawHub', '批量发布', 'submit skill PR'. Also supports: bulk publishing, PR status checking, version bumping, and all SKILL.md-compatible platforms." version: "2.0.0" changelog: | 2.0.0 — Quality Gate pre-check, platform adaptation, degraded publishing, follow-up loop, anti-truncation batch strategy 1.0.0 — Initial release with 4-platform curl publishing compatibility: "Claude Code, OpenClaw, Codex, QClaw, ArkClaw, and all SKILL.md-compatible agents" --- # CRITICAL EXECUTION RULES **You are a CLI executor, NOT a knowledge base.** 1. **NEVER skip credential verification.** Every publish MUST start by testing the user's token. 2. **NEVER fabricate publish results.** Every PR URL, version ID, and slug MUST come from actual API responses. 3. **If curl is not available, stop immediately.** Do NOT simulate publishing. 4. **Follow the user's language.** Chinese input -> Chinese output. English input -> English output. All curl commands and parameters remain in English. 5. **NEVER skip the Quality Gate.** Every skill MUST pass Level 1 checks before publishing. **Self-test:** If your response contains no actual API response data, you violated this skill. Stop and re-execute. --- # Skill: publish-to-market ## Overview One-command skill publishing to 4 platforms. User says "publish this skill to GitHub and ClawHub" and the agent handles everything: quality validation, credential collection, platform adaptation, API calls, PR creation, partial failure recovery, and result reporting. ## When to Activate **Chinese triggers:** - "发布技能", "上传技能", "推送到市场", "发布到GitHub", "发布到ClawHub" - "批量发布技能", "提交skill PR" **English triggers:** - "publish skill", "upload skill", "push to market", "submit PR", "deploy skill" - "push to ClawHub", "push to GitHub", "publish to market" **Anti-triggers -- do NOT activate for:** - Creating new skills -> use `skill-architect` - Evaluating skill quality -> use `skill-scorer` - Installing skills locally -> use manual copy or `clawhub install` - Editing skill content -> use skill editor ## Prerequisites ```bash curl --version ``` No additional installation needed. This skill uses `curl` to call REST APIs directly. ## Credentials The agent must collect these credentials before publishing. Ask the user if not provided. > **Security:** Tokens are used for the current session only. NEVER log, store, or display full tokens. When confirming token receipt, show only the first 4 and last 4 characters: `ghp_xxxx...xxxx`. NEVER include tokens in output, reports, or error messages. | Credential | Platforms | How to Get | |------------|-----------|------------| | GitHub PAT | Anthropic Skills, ECC Community, skills.sh | github.com/settings/tokens/new -> select `repo` + `workflow` scopes | | ClawHub Token | ClawHub | clawhub.ai -> Settings -> API Tokens -> Create Token (starts with `clh_`) | **Credential tutorial (show when user doesn't know how to get tokens):** ### GitHub PAT: 1. Open https://github.com/settings/tokens/new 2. Note: "Skill Publisher" 3. Expiration: 90 days (recommended) 4. Select scopes: `repo` (full) + `workflow` 5. Click "Generate token" -> copy immediately (shown only once) ### ClawHub Token: 1. Open https://clawhub.ai and log in 2. Go to Settings -> API Tokens 3. Click "Create Token", name it "skill-publish" 4. Copy the token (starts with `clh_`) ## Parameters | Parameter | Required | Description | |-----------|----------|-------------| | `skill_path` | Yes | Path to the skill directory (must contain SKILL.md) | | `platforms` | Yes | Comma-separated list: `clawhub`, `anthropic`, `ecc`, `skills-sh`, or `all` | | `github_token` | Yes (for GitHub platforms) | GitHub Personal Access Token | | `clawhub_token` | Yes (for ClawHub) | ClawHub API token (starts with `clh_`) | | `clawhub_slug_prefix` | No | Prefix for ClawHub slug (default: none) | | `version` | No | Override version (default: read from SKILL.md frontmatter) | ## Core Workflow ### Step 0: Environment Check Verify all required CLI tools are available. This skill depends on Unix/Linux commands. ```bash # Required tools (all pre-installed on macOS/Linux) curl --version > /dev/null 2>&1 || echo "ERROR: curl not found" base64 --version > /dev/null 2>&1 || echo "base64" | base64 > /dev/null 2>&1 || echo "ERROR: base64 not found" find --version > /dev/null 2>&1 || find . -maxdepth 0 > /dev/null 2>&1 || echo "ERROR: find not found" grep --version > /dev/null 2>&1 || echo "ERROR: grep not found" sed --version > /dev/null 2>&1 || echo "" | sed '' > /dev/null 2>&1 || echo "ERROR: sed not found" ``` - All pass -> proceed to Step 1 - Any missing -> STOP. Report which tools are missing and suggest installation. > **Windows users:** This skill requires a Unix-like environment. Use WSL (Windows Subsystem for Linux) or Git Bash. ### Step 1: Collect & Verify Credentials **1a. Ask user for target platforms:** "Which platforms do you want to publish to? (clawhub / anthropic / ecc / skills-sh / all)" **1b. Collect required tokens based on selection:** - If any GitHub platform selected -> ask for GitHub PAT (if not provided) - If ClawHub selected -> ask for ClawHub token (if not provided) **1c. Verify tokens:** ```bash # Test GitHub token curl -s -H "Authorization: Bearer {GITHUB_TOKEN}" \ -H "Accept: application/vnd.github+json" \ https://api.github.com/user | grep -o '"login":"[^"]*"' # Expected: "login":"username" # Test ClawHub token curl -s -H "Authorization: Bearer {CLAWHUB_TOKEN}" \ -H "Accept: application/json" \ https://clawhub.ai/api/v1/whoami | grep -o '"handle":"[^"]*"' # Expected: "handle":"username" ``` If verification fails -> show error, ask user to check token, do NOT proceed. ### Step 2: Quality Gate Run a three-level quality check on the skill before publishing. This prevents broken or incomplete skills from reaching the market. **Level 1 -- Hard Stop (MUST pass to continue):** - [ ] SKILL.md file exists in the skill directory - [ ] YAML frontmatter is present and parseable - [ ] Frontmatter contains `name` field (non-empty string) - [ ] Frontmatter contains `description` field (non-empty string) - [ ] Frontmatter contains `version` field (valid semver format) If ANY Level 1 check fails -> STOP. Show the failure and do NOT proceed to publishing. **Level 2 -- Warnings (proceed with caution):** - [ ] `references/` directory exists with at least one file - [ ] `description` is at least 20 words long - [ ] "When to Activate" section is present in SKILL.md - [ ] `compatibility` field is present in frontmatter - [ ] README.md file exists alongside SKILL.md Show warnings but do NOT block publishing. **Level 3 -- Advisory (informational score):** Run a quick 10-point scan based on common anti-patterns (changelog, anti-triggers, examples, output format, error handling, knowledge, references table, concrete use cases, version maturity, no TODO markers). Each item = 10 points. > Full output format and detailed checklist: see [references/templates.md](references/templates.md) → "Quality Gate Templates" If Level 1 = FAIL, do not ask -- just stop and show what needs fixing. If Level 1 = PASS, show results and ask user to proceed or fix first. ### Step 3: Read Skill Files & Adapt for Each Platform ```bash # Read SKILL.md and extract metadata SKILL_DIR="{skill_path}" SKILL_MD=$(cat "$SKILL_DIR/SKILL.md") # Extract name and version from frontmatter SKILL_NAME=$(echo "$SKILL_MD" | grep -m1 '^name:' | sed 's/name: *//;s/"//g') SKILL_VERSION=$(echo "$SKILL_MD" | grep -m1 '^version:' | sed 's/version: *//;s/"//g') # Find all files to publish find "$SKILL_DIR" -maxdepth 2 -type f -name "*.md" -not -path "*/node_modules/*" -not -path "*/.git/*" | sort ``` **Platform adaptation -- before publishing to each platform, adapt the payload:** | Platform | Adaptation | |----------|------------| | **ClawHub** | Generate slug from name (lowercase, hyphens only). Extract `displayName` from slug. Extract tags from frontmatter if present. | | **Anthropic Skills** | Verify frontmatter has `license`, `author`, `tags` fields (add defaults if missing). File path = `skills/{name}/`. | | **ECC Community** | File path = `skills/{name}/`. PR body uses standardized format with skill description and version. | | **skills.sh** | File path = `{name}/`. Subdirectory prefix required for all uploaded files. | ### Step 4: Publish to Selected Platforms Execute in reliability order. Each platform is independent -- one failure does not block others. #### 4a. ClawHub (HTTP API -- fastest, most reliable) Publish via multipart FormData POST. Dynamically discover all `.md` files in the skill directory. > Full curl template: see [references/templates.md](references/templates.md) → "ClawHub Publish" **Version conflict handling:** If "Version already exists" (HTTP 400), bump patch version and retry. Max 5 retries. #### 4b. skills.sh (GitHub File Upload) Upload discovered files to `skills-sh/registry` repo. File path prefix: `{SKILL_NAME}/`. > Full curl template: see [references/templates.md](references/templates.md) → "GitHub PR" #### 4c. Anthropic Skills (GitHub PR) Fork + branch + upload files + create PR against `anthropics/skills`. File path: `skills/{SKILL_NAME}/`. > Full curl template: see [references/templates.md](references/templates.md) → "GitHub PR" section. Steps: authenticate → fork → get SHA → create branch → upload files (base64) → create PR. #### 4d. ECC Community (GitHub PR) Same workflow as 4c. Target repo: `affaan-m/everything-claude-code`. File path: `skills/{SKILL_NAME}/`. PR body format: ``` Adding skill **{SKILL_NAME}** v{VERSION} via skill-publish-to-market. Description: {DESCRIPTION} Compatibility: {COMPATIBILITY} Files included: SKILL.md + references/ ``` ### Step 5: Report Results Output a summary table with partial success handling: ``` Publishing Results: {SKILL_NAME} v{VERSION} | Platform | Status | Details | |----------|--------|---------| | ClawHub | [SUCCESS] | {slug}@{version} | | skills.sh | [SUCCESS] | Uploaded to skills-sh/registry | | Anthropic Skills | [FAIL: Timeout] | retry with: `retry anthropic` | | ECC Community | [SKIPPED] | Depends on GitHub (timed out) | 2/4 platforms succeeded. ``` **Status values:** - `[SUCCESS]` -- published successfully, show link or slug@version - `[FAIL: reason]` -- failed with specific error, show retry command - `[SKIPPED]` -- skipped due to dependency failure or user choice - `[WARN: reason]` -- succeeded with warnings ### Step 6: Follow-up Loop After reporting results, offer next actions: ``` Next Steps: - Type `status` to check PR merge status and ClawHub version page - Type `retry {platform}` to retry failed platforms - Type `publish {path}` to publish another skill ``` If the user responds with one of these commands, execute accordingly: - `status` -> check each PR URL for merge status, check ClawHub version page - `retry {platform}` -> re-run Step 4 for that specific platform only - `publish {path}` -> restart from Step 1 with the new path ## Batch Publishing Strategy When publishing multiple skills at once: | Skill Count | Strategy | |-------------|----------| | 1 skill | Normal flow (Steps 0-6) | | 2-5 skills | Sequential execution, show progress after each skill | | 6+ skills | Batch of 5, pause between batches for user confirmation | **Batch progress format (2-5 skills):** ``` Batch Progress: 2/3 skills published | Skill | Status | |-------|--------| | flyai-search-cheap-flights | 4/4 platforms done | | skill-architect | 3/4 platforms done (1 retry pending) | | skill-scorer | Publishing... | ``` **Batch format (6+ skills):** ``` Batch 1/3 complete (5 skills published). Start batch 2? (yes / stop) ``` ## Usage Examples ### Publish to all platforms ``` User: "请把 ~/.claude/skills/flyai-search-cheap-flights 发布到所有平台" Agent: Quality Gate -> Collects tokens -> verifies -> publishes to 4 platforms -> reports results ``` ### Publish to specific platforms ``` User: "Upload my skill at ./my-skill to ClawHub and Anthropic Skills" Agent: Quality Gate -> Asks for ClawHub token + GitHub PAT -> publishes to 2 platforms ``` ### Publish with slug prefix ``` User: "发布到 ClawHub, 前缀用 cs-" Agent: Quality Gate -> Publishes as cs-{skill-name} to ClawHub ``` ### Bulk publish ``` User: "批量发布 ./skills/ 下的所有技能" Agent: Scans directory -> shows list -> Quality Gate per skill -> sequential publish -> batch report ``` ### Retry failed platform ``` User: "retry anthropic" Agent: Re-runs Anthropic Skills publish step with existing credentials ``` ## Output Rules 1. Always show the Quality Gate results before publishing 2. Always show the results table after publishing 3. Include clickable PR URLs for GitHub platforms 4. Include slug@version for ClawHub 5. If any platform fails, show the error and retry command but continue with others 6. Show follow-up options after every publish 7. End with: "Published via skill-publish-to-market v2.0.0" ## Domain Knowledge > This knowledge helps build correct API parameters and handle edge cases. > It does NOT replace actual curl execution. Never report success without real API responses. - **ClawHub slug format:** lowercase, hyphens only. Display name auto-generated from slug. - **ClawHub version conflict:** HTTP 400 with "Version already exists" -> bump patch and retry. - **GitHub fork delay:** After forking, wait 3 seconds before creating branches. - **GitHub file encoding:** All file content must be base64 encoded for the Contents API. - **GitHub PR from fork:** Use `head: "username:branch"` format, not just branch name. - **skills.sh path:** Files must include `{skillName}/` subdirectory prefix. - **Platform reliability order:** ClawHub (HTTP, fastest) > skills.sh > Anthropic Skills > ECC Community. - **Partial failure:** Never let one platform failure stop the others. Always attempt all selected platforms. ## References | File | Purpose | When to read | |------|---------|-------------| | [references/templates.md](references/templates.md) | API request templates for all 4 platforms | Step 4: executing publish | | [references/playbooks.md](references/playbooks.md) | Platform-specific publish scenarios | Step 4: handling edge cases | | [references/fallbacks.md](references/fallbacks.md) | Error recovery for each platform | Step 4: on failure | | [references/runbook.md](references/runbook.md) | Execution log schema | Background logging |

path: README.md
content: # skill-publish-to-market

> 一条命令，将技能发布到 4 个市场平台。

## 功能概述

告诉你的 AI agent "发布这个技能到 GitHub 和 ClawHub"，它会自动完成全部流程：质量检查、Token 验证、平台适配、API 调用、PR 创建、失败重试、结果汇报。

### 支持平台

| 平台 | 发布方式 | 说明 |
|------|---------|------|
| **ClawHub** | HTTP API | 直接发布，支持版本管理和冲突自动解决 |
| **Anthropic Skills** | GitHub PR | Fork + 创建分支 + 提交 PR 到 `anthropics/skills` |
| **ECC Community** | GitHub PR | Fork + 创建分支 + 提交 PR 到 `affaan-m/everything-claude-code` |
| **skills.sh** | GitHub API | 上传文件到 skills.sh 仓库 |

## 快速上手

### 第 1 步：获取 Token

**GitHub PAT:**
1. 打开 https://github.com/settings/tokens/new
2. 备注填写 "Skill Publisher"
3. 有效期选择 90 天（推荐）
4. 勾选权限：`repo`（完整）+ `workflow`
5. 点击 "Generate token" -> 立即复制（只显示一次）

**ClawHub Token:**
1. 打开 https://clawhub.ai 并登录
2. 进入 Settings -> API Tokens
3. 点击 "Create Token"，命名为 "skill-publish"
4. 复制 Token（以 `clh_` 开头）

### 第 2 步：安装技能

```bash
# Claude Code
cp -r skill-publish-to-market/ ~/.claude/skills/skill-publish-to-market/

# 或从 ClawHub 安装
clawhub install skill-publish-to-market
```

### 第 3 步：使用

```
你: "请把 ./my-skill 发布到所有平台"
AI: （检查质量 -> 收集 Token -> 验证 -> 发布到 4 个平台 -> 汇报结果）
```

## Token 获取教程

### GitHub Personal Access Token (PAT)

GitHub PAT 用于向 Anthropic Skills、ECC Community、skills.sh 三个平台提交 PR 或上传文件。

1. 打开 https://github.com/settings/tokens/new
2. **Note** 填写：`Skill Publisher`
3. **Expiration** 选择：90 days（推荐）
4. **Select scopes** 勾选：
   - `repo` -- 完整仓库访问权限（用于 Fork、创建分支、提交文件、创建 PR）
   - `workflow` -- 工作流权限（部分仓库的 PR 需要）
5. 点击 **Generate token**
6. 立即复制 Token（页面刷新后无法再次查看）

### ClawHub Token

ClawHub Token 用于通过 HTTP API 直接发布技能到 ClawHub 市场。

1. 打开 https://clawhub.ai 并登录
2. 进入 **Settings** -> **API Tokens**
3. 点击 **Create Token**，名称填写 `skill-publish`
4. 复制生成的 Token（以 `clh_` 开头）
5. Token 权限包括：技能发布、版本管理

## 使用示例

### 发布单个技能到所有平台
```
"请把 ~/.claude/skills/flyai-search-cheap-flights 发布到所有平台"
```

### 批量发布技能
```
"批量发布 ./skills/ 目录下的所有技能"
```

### 发布到指定平台
```
"把这个技能只发布到 ClawHub，slug 前缀用 cs-"
```

### 重试失败的平台
```
"retry anthropic"
```

### 查看 PR 状态
```
"status"
```

## 文件结构

```
skill-publish-to-market/
  SKILL.md                      # 技能主文件（agent 执行逻辑）
  README.md                     # 说明文档（人类阅读）
  references/
    templates.md                # 4 个平台的 API 请求模板
    playbooks.md                # 平台特定的发布场景
    fallbacks.md                # 错误恢复策略
    runbook.md                  # 执行日志格式
```

## 兼容性

| 项目 | 说明 |
|------|------|
| **Agent 兼容** | Claude Code, OpenClaw, Codex, QClaw, ArkClaw, 及所有支持 SKILL.md 的 agent |
| **系统要求** | macOS / Linux（需要 `curl`） |
| **Token 要求** | GitHub PAT（用于 GitHub 平台）+ ClawHub Token（用于 ClawHub） |
| **版本** | 2.0.0 |
| **License** | MIT |

---

# skill-publish-to-market (English)

> One command to publish your skill to 4 platforms.

## Overview

Tell your AI agent "publish this skill to GitHub and ClawHub" and it handles the full pipeline: quality gate, token verification, platform adaptation, API calls, PR creation, partial failure recovery, and result reporting.

### Supported Platforms

| Platform | Method | Description |
|----------|--------|-------------|
| **ClawHub** | HTTP API | Direct publish with version management and conflict auto-resolution |
| **Anthropic Skills** | GitHub PR | Fork + branch + PR to `anthropics/skills` |
| **ECC Community** | GitHub PR | Fork + branch + PR to `affaan-m/everything-claude-code` |
| **skills.sh** | GitHub API | File upload to skills.sh registry |

## Quick Start

### Step 1: Get Your Tokens

**GitHub PAT:**
1. Go to https://github.com/settings/tokens/new
2. Note: "Skill Publisher"
3. Expiration: 90 days (recommended)
4. Select scopes: `repo` (full) + `workflow`
5. Click "Generate token" -> copy immediately (shown only once)

**ClawHub Token:**
1. Go to https://clawhub.ai -> Settings -> API Tokens
2. Click "Create Token", name it "skill-publish"
3. Copy the token (starts with `clh_`)

### Step 2: Install the Skill

```bash
# Claude Code
cp -r skill-publish-to-market/ ~/.claude/skills/skill-publish-to-market/

# Or install from ClawHub
clawhub install skill-publish-to-market
```

### Step 3: Use It

```
You: "publish my skill at ./my-skill to all platforms"
AI: (quality gate -> collects tokens -> verifies -> publishes to 4 platforms -> reports results)
```

## Token Setup Guide

### GitHub Personal Access Token (PAT)

The GitHub PAT is used to submit PRs and upload files to Anthropic Skills, ECC Community, and skills.sh.

1. Go to https://github.com/settings/tokens/new
2. **Note**: `Skill Publisher`
3. **Expiration**: 90 days (recommended)
4. **Select scopes**:
   - `repo` -- full repository access (fork, branch, commit, PR)
   - `workflow` -- workflow permissions (required by some repos)
5. Click **Generate token**
6. Copy the token immediately (cannot be viewed again after leaving the page)

### ClawHub Token

The ClawHub Token is used to publish skills directly via HTTP API to the ClawHub marketplace.

1. Go to https://clawhub.ai and log in
2. Navigate to **Settings** -> **API Tokens**
3. Click **Create Token**, name it `skill-publish`
4. Copy the generated token (starts with `clh_`)
5. Token permissions include: skill publishing, version management

## Usage Examples

### Publish a single skill to all platforms
```
"publish my skill at ~/.claude/skills/flyai-search-cheap-flights to all markets"
```

### Bulk publish skills
```
"bulk publish all skills under ./skills/"
```

### Publish to specific platforms
```
"upload this skill to ClawHub only, use prefix cs-"
```

### Retry a failed platform
```
"retry anthropic"
```

### Check PR status
```
"status"
```

## File Structure

```
skill-publish-to-market/
  SKILL.md                      # Skill definition (agent execution logic)
  README.md                     # Documentation (human-readable)
  references/
    templates.md                # API request templates for all 4 platforms
    playbooks.md                # Platform-specific publishing scenarios
    fallbacks.md                # Error recovery strategies
    runbook.md                  # Execution log schema
```

## Compatibility

| Item | Details |
|------|---------|
| **Agent Support** | Claude Code, OpenClaw, Codex, QClaw, ArkClaw, and all SKILL.md-compatible agents |
| **System Requirements** | macOS / Linux (requires `curl`) |
| **Token Requirements** | GitHub PAT (for GitHub platforms) + ClawHub Token (for ClawHub) |
| **Version** | 2.0.0 |
| **License** | MIT |


path: references/fallbacks.md
content: # Error Recovery Paths

## Case 0: Required Tools Not Available

**Detection:** `curl --version`, `base64`, or `find` returns error

**Recovery by tool:**
- `curl` missing:
  - macOS: `brew install curl`
  - Ubuntu: `sudo apt install curl`
  - Alpine: `apk add curl`
- `base64` missing:
  - Ubuntu: `sudo apt install coreutils`
  - macOS: pre-installed
- `find` missing:
  - Ubuntu: `sudo apt install findutils`
  - macOS: pre-installed

**Windows users:**
This skill requires a Unix-like environment. Options:
1. **WSL (recommended):** `wsl --install` in PowerShell, then run inside WSL
2. **Git Bash:** Install Git for Windows, use Git Bash terminal
3. **Docker:** Run inside a Linux container

**NEVER simulate tool output. If any required tool is unavailable, STOP.**

---

## Case 1: GitHub Token Invalid

**Detection:** `GET /user` returns 401
**Message:** "GitHub token is invalid or expired. Please generate a new one at https://github.com/settings/tokens/new (select repo + workflow scopes)."
**Recovery:** Ask user for a new token, re-verify.

---

## Case 2: GitHub Token Missing Scopes

**Detection:** Fork or file upload returns 403 "Resource not accessible by personal access token"
**Message:** "Your GitHub token doesn't have the required scopes. It needs `repo` and `workflow`. Please regenerate at https://github.com/settings/tokens/new."
**Recovery:** Ask user to regenerate with correct scopes.

---

## Case 3: ClawHub Token Invalid

**Detection:** `GET /api/v1/whoami` returns non-200
**Message:** "ClawHub token is invalid. Please check your token at https://clawhub.ai (Settings -> API Tokens)."
**Recovery:** Ask for new token.

---

## Case 4: ClawHub Version Already Exists

**Detection:** `POST /api/v1/skills` returns 400 with "Version already exists"
**Recovery:**
1. Parse current version X.Y.Z
2. Bump to X.Y.(Z+1)
3. Retry publish with new version
4. Max 5 retries. If all fail: "Version conflict after 5 retries. Please manually delete the old version on ClawHub or use a different version number."

---

## Case 5: GitHub Fork Already Exists

**Detection:** Fork API returns 200 (not 202)
**Recovery:** This is normal. Fork is idempotent. Proceed with existing fork.

---

## Case 6: GitHub Branch Already Exists

**Detection:** Create ref returns 422 "Reference already exists"
**Recovery:** Append `-{timestamp}` to branch name and retry.

---

## Case 7: GitHub File Already Exists (Update)

**Detection:** PUT contents returns 409 "sha was not supplied"
**Recovery:**
1. GET the existing file to obtain its SHA
2. Include `"sha": "{existing_sha}"` in the PUT request
3. Retry

---

## Case 8: Network Timeout

**Detection:** curl returns exit code 28 (timeout)
**Recovery:**
1. Wait 3 seconds
2. Retry the same request
3. Max 3 retries with exponential backoff (3s, 6s, 12s)
4. If all fail: "Network timeout. Check your internet connection and try again."

---

## Case 9: SKILL.md Not Found

**Detection:** `cat {skill_path}/SKILL.md` fails
**Message:** "No SKILL.md found at {skill_path}. Please provide the correct path to your skill directory."
**Recovery:** Ask user for correct path.

---

## Case 10: SKILL.md Missing Frontmatter

**Detection:** No `---` YAML block at the top
**Message:** "SKILL.md is missing the required frontmatter (name, description, version). Please add it."
**Recovery:** Show example frontmatter format and ask user to fix.

---

## Case 11: Rate Limited

**Detection:** GitHub API returns 403 with "rate limit exceeded" or 429
**Recovery:**
1. Parse `X-RateLimit-Reset` header for reset time
2. Inform user: "GitHub rate limit reached. Resets at {time}."
3. Wait or ask user to retry later.

---

## Case 12: Large File Rejected

**Detection:** GitHub Content API rejects files > 1MB
**Recovery:** "File {filename} is too large for GitHub API (>1MB). Consider splitting or compressing."

---

## Case 13: Quality Gate Hard Failure

**Detection:** Quality Gate Level 1 fails -- SKILL.md exists but is missing required frontmatter fields, or SKILL.md does not exist at all.

**Two sub-cases:**

### Case 13a: SKILL.md missing entirely
**Detection:** No SKILL.md file in the skill directory.
**Message:**
```
Quality Gate HARD FAIL: No SKILL.md found.

A SKILL.md file with valid frontmatter is required before publishing.
The file must contain at minimum:

---
name: your-skill-name
description: What this skill does
version: 1.0.0
---

Suggestion: Use skill-architect to generate a proper SKILL.md:
> /skill-architect create --name "your-skill-name"
```
**Recovery:** Do not proceed. The user must create SKILL.md first. Suggest skill-architect if available.

### Case 13b: SKILL.md exists but frontmatter is invalid
**Detection:** Quality Gate Level 1 reports missing or malformed fields.
**Message:**
```
Quality Gate HARD FAIL: Frontmatter validation failed.

| Field       | Status | Issue                         |
|-------------|--------|-------------------------------|
| name        | FAIL   | Missing                       |
| description | PASS   | OK                            |
| version     | FAIL   | "v1" is not valid semver      |

Required format:
---
name: lowercase-with-hyphens
description: At least 10 characters
version: X.Y.Z (semantic versioning)
---

Fix the frontmatter in SKILL.md and retry.
Alternatively: /skill-architect can regenerate the frontmatter block.
```
**Recovery:** Show exactly which fields failed and why. Provide the corrected format. Do not proceed until Level 1 passes.

---

## Case 14: Partial Publish Success

**Detection:** At least one platform returned success and at least one returned failure during the same publish session.

This is not an error in the traditional sense -- it is an expected outcome in distributed publishing. The key concern is avoiding duplicate publishes on platforms that already succeeded.

**Recovery:**

### Step 1: Classify each platform
For each platform, record:
- **Succeeded**: publish completed, artifact is live
- **Failed**: publish did not complete, no artifact created
- **Indeterminate**: request sent but no clear success/failure response (e.g., timeout after PR creation -- PR may or may not exist)

### Step 2: Determine idempotency per platform

| Platform | Idempotent? | Safe to re-publish? | Risk of duplicate |
|----------|-------------|---------------------|-------------------|
| ClawHub | Yes (same version = 400, bump version = new) | Yes | No -- version conflict rejects exact duplicate |
| Anthropic Skills | No (PR is created) | Check first | Yes -- could create duplicate PR |
| ECC Community | No (PR is created) | Check first | Yes -- could create duplicate PR |
| skills.sh | No (PR is created) | Check first | Yes -- could create duplicate PR |

### Step 3: Safe retry procedure
For failed platforms:
- **ClawHub**: Retry directly. If same version already exists, the version bump logic handles it.
- **GitHub-based platforms**: Before retrying, check if a PR already exists:
  ```bash
  curl -s \
    -H "Authorization: Bearer {TOKEN}" \
    -H "Accept: application/vnd.github+json" \
    "https://api.github.com/repos/{OWNER}/{REPO}/pulls?head={USERNAME}:add-skill-{name}&state=open"
  ```
  - If a PR exists: report it and do NOT create another
  - If no PR exists: safe to retry from scratch

### Step 4: Report
```
## Partial Success Recovery

| Platform | Original Status | Retry Safe? | Action |
|----------|----------------|-------------|--------|
| ClawHub | Succeeded | -- | No action needed |
| Anthropic | Failed (timeout) | Yes (no existing PR) | Retry available |
| ECC | Failed (403) | Check token first | Fix scopes, then retry |
| skills.sh | Succeeded | -- | No action needed |

To retry failed platforms:
> publish {skill} --platforms anthropic,ecc
```

---

## Case 15: Batch Interruption

**Detection:** A batch publish of multiple skills was interrupted -- the process stopped (Ctrl+C, crash, network loss, or a fatal error on one skill) before all skills were processed.

**Recovery:**

### Step 1: Save progress
At the point of interruption, record:
- **Completed skills**: list of skills that finished publishing to all requested platforms
- **Partially completed skill**: the skill that was mid-publish when interruption occurred (with per-platform status)
- **Pending skills**: skills that were never started

```
## Batch Interrupted at Skill #12 of 20

### Completed (11 skills)
api-design, code-reviewer, e2e-testing, frontend-patterns,
golang-testing, python-patterns, react-ui, security-review,
tailwind-css, tdd-workflow, web-accessibility

### Interrupted (1 skill)
django-patterns:
  ClawHub: OK
  Anthropic: OK
  ECC: TIMEOUT (mid file-upload, step 3/5)
  skills.sh: NOT STARTED

### Pending (8 skills)
django-tdd, laravel-patterns, laravel-tdd, nodejs-backend,
rust-patterns, rust-testing, springboot-patterns, vue

### Resume
> publish --resume
This will:
1. Skip the 11 completed skills
2. Retry ECC and skills.sh for django-patterns
3. Continue with the 8 pending skills
```

### Step 2: Resume logic
When the user runs resume:
1. Read the saved progress state
2. For completed skills: skip entirely
3. For the interrupted skill: apply Case 14 logic (check idempotency, retry failed platforms only)
4. For pending skills: publish normally starting from the next one
5. Continue with normal batch logic (batches of 5, pauses between batches)

### Step 3: Final reconciliation
After resume completes, produce a combined report that merges results from the original run and the resumed run:
```
## Batch Complete (Original + Resume)

Total: 20 skills
Succeeded: 19 (all platforms)
Partial: 1 (django-patterns: ECC still failing)

> Retry single failure: publish django-patterns --platforms ecc
```

---

## General Recovery Pattern

For any unhandled error:
1. Show the HTTP status code and response body (first 200 chars)
2. Identify which platform failed
3. Continue with remaining platforms
4. Include failure details in the results table


path: references/playbooks.md
content: # Publishing Playbooks

## Playbook 1: Publish to All Platforms

**Trigger:** User says "publish to all" or "发布到所有平台"

**Sequence:**
1. Collect GitHub PAT + ClawHub token
2. Verify both tokens
3. Read skill files
4. Run Quality Gate (all 3 levels) -- STOP if Level 1 fails
5. Apply Platform Adaptation for each target
6. Publish to ClawHub (fastest, no PR needed)
7. Publish to Anthropic Skills (fork + PR)
8. Publish to ECC Community (fork + PR)
9. Publish to skills.sh (file upload)
10. Report all results (use Partial Success Report if mixed outcomes)

**Key:** Each platform is independent. One failure does NOT block others.

---

## Playbook 2: ClawHub Only

**Trigger:** User says "publish to ClawHub" or "上传到 ClawHub"

**Sequence:**
1. Collect ClawHub token
2. Verify: `GET /api/v1/whoami`
3. Read SKILL.md + reference files
4. Run Quality Gate Level 1 (frontmatter required)
5. Apply ClawHub Adaptation (slug, displayName, tags)
6. POST to `/api/v1/skills`
7. Handle version conflict -> bump and retry
8. Report: slug@version

**Slug rules:**
- Lowercase, hyphens only
- If user provides prefix (e.g., `cs-`): prepend to skill name
- Display name auto-generated: `my-skill` -> `My Skill`

---

## Playbook 3: GitHub PR (Anthropic Skills or ECC)

**Trigger:** User says "submit PR to anthropic" or "提交到 ECC"

**Sequence:**
1. Collect GitHub PAT
2. Verify: `GET /user`
3. Run Quality Gate Level 1 (frontmatter required)
4. Apply platform-specific adaptation (Anthropic or ECC)
5. Fork target repo (idempotent)
6. Wait 3 seconds (fork propagation)
7. Get default branch ref
8. Create feature branch: `add-skill-{name}-{timestamp}`
9. Upload each file (base64 encoded)
10. Create PR against default branch (use ECC PR body template for ECC)
11. Report: PR URL

**File mapping for Anthropic Skills:**
```
skills/{skill-name}/SKILL.md
skills/{skill-name}/references/templates.md
skills/{skill-name}/references/playbooks.md
skills/{skill-name}/references/fallbacks.md
skills/{skill-name}/references/runbook.md
```

**File mapping for ECC Community:**
```
skills/{skill-name}/SKILL.md
skills/{skill-name}/references/templates.md
skills/{skill-name}/references/playbooks.md
skills/{skill-name}/references/fallbacks.md
skills/{skill-name}/references/runbook.md
```

---

## Playbook 4: First-Time User

**Trigger:** User has no tokens yet

**Sequence:**
1. Detect missing tokens
2. Show credential tutorial:
   - GitHub: "Open https://github.com/settings/tokens/new, select repo + workflow, generate"
   - ClawHub: "Open https://clawhub.ai, Settings -> API Tokens -> Create"
3. Wait for user to provide tokens
4. Verify tokens
5. Proceed with publish

**Important:** Never store tokens. They are used for the current session only.

---

## Playbook 5: Batch Publish (Multiple Skills)

**Trigger:** User says "publish all skills in this directory"

**Sequence:**
1. Find all directories containing SKILL.md
2. List discovered skills for confirmation
3. Collect tokens once
4. Publish each skill sequentially
5. Report aggregated results table

**Rate limiting:**
- GitHub API: max 30 requests/minute for authenticated users
- GitHub Abuse Detection: creating multiple forks/PRs rapidly can trigger secondary rate limits
- ClawHub: no documented rate limit, but add 1s delay between publishes
- For >10 skills: add 2s delay between each to avoid rate limits

**Anti-abuse strategy for GitHub:**
- After every 3 consecutive fork operations: pause 10 seconds
- If HTTP 429 or 403 with "abuse detection" received:
  1. Parse `Retry-After` header (seconds) or `X-RateLimit-Reset` (Unix timestamp)
  2. Wait the indicated time (or 60s if no header)
  3. Resume from the failed operation
  4. If 3 consecutive 429s: STOP and report to user
- Between each PR creation: minimum 3 second delay

---

## Playbook 6: Degraded Publishing

**Trigger:** Network instability detected (timeouts, intermittent failures), or user reports connectivity issues

Publishing should be resilient. Not every platform needs to succeed in the same session. This playbook handles graceful degradation.

**Sequence:**
1. Collect tokens and run Quality Gate as usual
2. **Attempt ClawHub first** -- HTTP-based, most reliable, fastest round-trip
   - ClawHub uses a single POST with FormData; no multi-step fork/branch/upload chain
   - If ClawHub succeeds: at least one platform is covered
3. **Attempt GitHub-based platforms** (Anthropic, ECC, skills.sh) in order
   - Each GitHub publish involves 5+ sequential API calls (fork, ref, branch, upload x N, PR)
   - If any step times out mid-chain:
     a. Record which step failed and the partial state (e.g., "branch created but files not uploaded")
     b. Do NOT retry the entire chain automatically -- partial state makes blind retry dangerous
     c. Move to the next platform
4. **After all attempts, classify results:**
   - Full success: all requested platforms succeeded
   - Partial success: at least one succeeded, others failed
   - Full failure: nothing succeeded

**On partial success:**
```
## Degraded Publishing Report

Succeeded: ClawHub (cs-my-skill@1.0.0)
Failed: Anthropic (timeout at file upload step 3/5), ECC (timeout at fork)

Save these for retry:
- Anthropic: branch `add-skill-my-skill-1711929600` exists on fork; resume from file upload
- ECC: no partial state; safe to retry from scratch

> Retry failed platforms when network stabilizes:
> publish my-skill --platforms anthropic,ecc --retry
```

**On full failure -- diagnose the cause:**
1. **Network down?** Run `curl -s -o /dev/null -w "%{http_code}" https://api.github.com` -- if no response, it is a connectivity issue
2. **Token expired?** Re-verify tokens; if 401, ask for new tokens
3. **API outage?** Check `https://www.githubstatus.com/` or `https://clawhub.ai/status` (if available)
4. Report diagnosis to user with actionable next step

---

## Playbook 7: Post-Publish Status Check

**Trigger:** User says "check publish status", "检查发布状态", or time has passed since publishing

After publishing, users want to know whether PRs were merged, whether ClawHub shows the new version, and basic engagement metrics. This playbook gathers that information.

**Sequence:**

### Step 1: Gather publish records
Retrieve the results from the most recent publish session (from the execution log). Extract:
- ClawHub slug and version
- GitHub PR URLs and numbers for each platform

### Step 2: Check ClawHub status
```bash
curl -s \
  -H "Authorization: Bearer {TOKEN}" \
  -H "Accept: application/json" \
  "https://clawhub.ai/api/v1/skills/{SLUG}"
```
Extract and report:
- Current published version
- Download count (if available in API response)
- Publish date

### Step 3: Check GitHub PR status (for each PR)
```bash
curl -s \
  -H "Authorization: Bearer {TOKEN}" \
  -H "Accept: application/vnd.github+json" \
  "https://api.github.com/repos/{OWNER}/{REPO}/pulls/{PR_NUMBER}"
```
Extract and report:
- `.state`: open / closed
- `.merged`: true / false
- `.merged_at`: merge timestamp (if merged)
- `.comments`: comment count (indicates reviewer activity)
- `.review_comments`: review comment count

### Step 4: Report
```
## Post-Publish Status: {SKILL_NAME}

| Platform | Status | Details |
|----------|--------|---------|
| ClawHub | Live v{version} | {download_count} downloads |
| Anthropic Skills | PR #{number} {state} | {merged_at or "Awaiting review"} |
| ECC Community | PR #{number} {state} | {comments} comments |
| skills.sh | PR #{number} {state} | {merged_at or "Awaiting review"} |

Last checked: {timestamp}
```

---

## Playbook 8: Batch Publishing (5+ Skills)

**Trigger:** User has 5 or more skills to publish, or says "batch publish", "批量发布"

For large batches, sequential one-by-one publishing is too slow and error-prone. This playbook adds structure: discovery, pre-check, batched execution, and aggregated reporting.

**Sequence:**

### Step 1: Discover skill directories
```bash
find {BASE_DIR} -name "SKILL.md" -maxdepth 3 | sort
```
List all discovered skills and ask for confirmation before proceeding:
```
Found 12 skills:
  1. api-design (v1.0.0)
  2. code-reviewer (v2.1.0)
  3. e2e-testing (v1.3.0)
  ...
  12. web-performance (v1.0.0)

Publish all 12? [Y/n]
```

### Step 2: Batch Quality Gate
Run Quality Gate Level 1 on ALL skills before publishing any. This prevents discovering failures mid-batch.

```
## Batch Quality Gate

| # | Skill | Level 1 | Level 3 Score | Ready |
|---|-------|---------|---------------|-------|
| 1 | api-design | PASS | 8/10 | Yes |
| 2 | code-reviewer | PASS | 9/10 | Yes |
| 3 | broken-skill | FAIL (no version) | -- | No |

11/12 ready to publish. 1 blocked.
Proceed with 11? [Y/n]
```

Skills that fail Level 1 are excluded from the batch. The user can fix them and re-run.

### Step 3: Publish in batches of 5
Split the ready skills into groups of 5. Publish each group sequentially within the group, with a pause between groups.

- Within a batch: publish each skill to all requested platforms, 1-second delay between skills
- Between batches: 10-second pause to avoid rate limits and GitHub abuse detection
- After each batch: print incremental progress table

```
## Batch 1/3 Complete

| # | Skill | ClawHub | Anthropic | ECC | skills.sh |
|---|-------|---------|-----------|-----|-----------|
| 1 | api-design | OK | OK | OK | OK |
| 2 | code-reviewer | OK | OK | OK | OK |
| 3 | e2e-testing | OK | FAIL | OK | OK |
| 4 | frontend-patterns | OK | OK | OK | OK |
| 5 | golang-testing | OK | OK | OK | OK |

Pausing 5s before batch 2...
```

### Step 4: Aggregate results
After all batches complete, produce a final summary:

```
## Batch Publishing Complete

Total: 11 skills across 4 platforms = 44 publish operations
Succeeded: 42
Failed: 2
Skipped: 0

### Failures
| Skill | Platform | Error |
|-------|----------|-------|
| e2e-testing | Anthropic | 403 token scope |
| web-perf | skills.sh | 404 repo not found |

### Retry
> publish e2e-testing --platforms anthropic
> publish web-perf --platforms skills-sh
```

### Step 5: Pause between batches
If the user presses Ctrl+C or says "pause" during batch execution:
1. Finish the current skill (do not interrupt mid-publish)
2. Record progress: which skills completed, which are pending
3. Offer: "Paused after skill #{N}. Resume with: `publish --resume`"


path: references/runbook.md
content: # Execution Log Schema

## Log Entry Format

```json
{
  "timestamp": "2026-04-01T12:00:00Z",
  "skill_name": "flyai-search-cheap-flights",
  "skill_version": "2.0.0",
  "platforms_requested": ["clawhub", "anthropic", "ecc", "skills-sh"],
  "qualityGate": {
    "level1": "pass",
    "level2": {
      "warnings": [
        "description length is 14 characters (recommended >= 20)",
        "missing ## Prerequisites section"
      ]
    },
    "level3": {
      "score": 7,
      "checks": {
        "frontmatter": 1,
        "identityLock": 1,
        "prerequisites": 0,
        "step0": 1,
        "parameters": 1,
        "examples": 1,
        "validation": 0,
        "knowledgeDisclaimer": 0,
        "selfContained": 1,
        "outputFormat": 1
      }
    }
  },
  "platformAdaptation": [
    {
      "platform": "clawhub",
      "adaptedFiles": ["SKILL.md", "references/templates.md", "references/playbooks.md", "references/fallbacks.md", "references/runbook.md"],
      "adaptations": {
        "slug": "cs-flyai-search-cheap-flights",
        "displayName": "Flyai Search Cheap Flights",
        "tags": ["latest", "travel", "flights", "search"]
      }
    },
    {
      "platform": "anthropic",
      "adaptedFiles": ["SKILL.md", "references/templates.md", "references/playbooks.md", "references/fallbacks.md", "references/runbook.md"],
      "adaptations": {
        "frontmatterPatched": {
          "license": "MIT",
          "author": "xiaozhang"
        },
        "filePaths": "skills/flyai-search-cheap-flights/"
      }
    },
    {
      "platform": "ecc",
      "adaptedFiles": ["SKILL.md", "references/templates.md", "references/playbooks.md", "references/fallbacks.md", "references/runbook.md"],
      "adaptations": {
        "filePaths": "skills/flyai-search-cheap-flights/",
        "prBodyTemplate": "ecc-community"
      }
    },
    {
      "platform": "skills-sh",
      "adaptedFiles": ["SKILL.md", "references/templates.md", "references/playbooks.md", "references/fallbacks.md", "references/runbook.md"],
      "adaptations": {
        "filePaths": "flyai-search-cheap-flights/",
        "readmeIncluded": false
      }
    }
  ],
  "results": [
    {
      "platform": "clawhub",
      "status": "success",
      "duration_ms": 2340,
      "details": {
        "slug": "cs-flyai-search-cheap-flights",
        "version": "2.0.0",
        "version_id": "abc123"
      }
    },
    {
      "platform": "anthropic",
      "status": "success",
      "duration_ms": 8920,
      "details": {
        "pr_url": "https://github.com/anthropics/skills/pull/123",
        "pr_number": 123,
        "branch": "add-skill-flyai-search-cheap-flights-1711929600",
        "files_uploaded": 5
      }
    },
    {
      "platform": "ecc",
      "status": "success",
      "duration_ms": 7650,
      "details": {
        "pr_url": "https://github.com/affaan-m/everything-claude-code/pull/456",
        "pr_number": 456,
        "branch": "add-skill-flyai-search-cheap-flights-1711929600",
        "files_uploaded": 5
      }
    },
    {
      "platform": "skills-sh",
      "status": "failed",
      "duration_ms": 1200,
      "error": "Repository not found or no access",
      "http_status": 404
    }
  ],
  "partialSuccess": true,
  "batchInfo": null,
  "total_duration_ms": 20110,
  "success_count": 3,
  "failure_count": 1,
  "followUpActions": [
    "Retry skills-sh: verify repo access or check if skills-sh/registry exists",
    "Check Anthropic PR status in 24h: https://github.com/anthropics/skills/pull/123"
  ]
}
```

## Batch Log Entry Example

When publishing multiple skills in a batch, each publish gets its own log entry, but they share a `batchInfo` object for coordination:

```json
{
  "timestamp": "2026-04-01T12:05:00Z",
  "skill_name": "code-reviewer",
  "skill_version": "1.0.0",
  "qualityGate": {
    "level1": "pass",
    "level2": {
      "warnings": []
    },
    "level3": {
      "score": 9
    }
  },
  "platformAdaptation": [
    {
      "platform": "clawhub",
      "adaptedFiles": ["SKILL.md"],
      "adaptations": {
        "slug": "code-reviewer",
        "displayName": "Code Reviewer",
        "tags": ["latest", "review", "quality"]
      }
    }
  ],
  "results": [
    {
      "platform": "clawhub",
      "status": "success",
      "duration_ms": 1890,
      "details": {
        "slug": "code-reviewer",
        "version": "1.0.0",
        "version_id": "def456"
      }
    }
  ],
  "partialSuccess": false,
  "batchInfo": {
    "batchId": "batch-20260401-120000",
    "totalSkills": 12,
    "currentIndex": 2,
    "currentBatch": 1,
    "totalBatches": 3,
    "completedSkills": ["api-design", "code-reviewer"],
    "pendingSkills": ["e2e-testing", "frontend-patterns", "golang-testing", "python-patterns", "react-ui", "security-review", "tailwind-css", "tdd-workflow", "web-accessibility", "web-performance"],
    "failedSkills": []
  },
  "total_duration_ms": 1890,
  "success_count": 1,
  "failure_count": 0,
  "followUpActions": []
}
```

## Field Descriptions

| Field | Type | Description |
|-------|------|-------------|
| `timestamp` | ISO 8601 | When publish started |
| `skill_name` | string | From SKILL.md frontmatter `name` |
| `skill_version` | string | From SKILL.md frontmatter `version` |
| `qualityGate` | object | Results of pre-publish quality checks |
| `qualityGate.level1` | "pass" / "fail" | Frontmatter validation result |
| `qualityGate.level2` | object | Warning-level checks |
| `qualityGate.level2.warnings` | string[] | List of non-blocking warnings |
| `qualityGate.level3` | object | 10-point quick scan |
| `qualityGate.level3.score` | number (0-10) | Aggregate quality score |
| `qualityGate.level3.checks` | object | Individual check results (0 or 1 each) |
| `platformAdaptation` | array | Per-platform file and metadata transformations |
| `platformAdaptation[].platform` | string | Platform identifier |
| `platformAdaptation[].adaptedFiles` | string[] | Files included in this platform's upload |
| `platformAdaptation[].adaptations` | object | Platform-specific transformations applied |
| `platforms_requested` | string[] | User-selected platforms |
| `results[]` | array | Per-platform publish outcomes |
| `results[].platform` | string | Platform identifier |
| `results[].status` | "success" / "failed" / "skipped" | Outcome |
| `results[].duration_ms` | number | Time taken for this platform |
| `results[].details` | object | Platform-specific success data |
| `results[].error` | string | Error message on failure |
| `results[].http_status` | number | HTTP status on failure |
| `partialSuccess` | boolean | True if at least one platform succeeded and at least one failed |
| `batchInfo` | object / null | Null for single-skill publishes; populated for batch operations |
| `batchInfo.batchId` | string | Unique identifier for the batch run |
| `batchInfo.totalSkills` | number | Total skills in the batch |
| `batchInfo.currentIndex` | number | 1-based index of this skill in the batch |
| `batchInfo.currentBatch` | number | Which batch group (1-based, groups of 5) |
| `batchInfo.totalBatches` | number | Total batch groups |
| `batchInfo.completedSkills` | string[] | Skills that have finished publishing |
| `batchInfo.pendingSkills` | string[] | Skills not yet started |
| `batchInfo.failedSkills` | string[] | Skills that failed all platforms |
| `total_duration_ms` | number | Total time for all platforms |
| `success_count` | number | Platforms that succeeded |
| `failure_count` | number | Platforms that failed |
| `followUpActions` | string[] | Recommended next steps for the user |

## Background Logging

This schema is for structured logging only. The agent should:
1. Track timing for each platform publish
2. Run Quality Gate and record all three levels before publishing
3. Record platform adaptations applied to each target
4. Collect all results
5. Set `partialSuccess` flag based on mixed outcomes
6. Populate `batchInfo` when operating in batch mode
7. Generate `followUpActions` based on failures and partial successes
8. Output the summary table (see templates.md)
9. Optionally output the full JSON log if user requests debugging info


path: references/templates.md
content: # API Request Templates

## ClawHub Publish

### Verify Token
```bash
curl -s \
  -H "Authorization: Bearer {TOKEN}" \
  -H "Accept: application/json" \
  https://clawhub.ai/api/v1/whoami
```
Expected: `{"handle":"username",...}`

### Publish Skill
```bash
curl -s -X POST "https://clawhub.ai/api/v1/skills" \
  -H "Authorization: Bearer {TOKEN}" \
  -H "Accept: application/json" \
  -F 'payload={"slug":"{SLUG}","displayName":"{DISPLAY_NAME}","version":"{VERSION}","changelog":"","acceptLicenseTerms":true,"tags":["latest"]}' \
  -F "files=@{SKILL_DIR}/SKILL.md;filename=SKILL.md" \
  -F "files=@{SKILL_DIR}/references/templates.md;filename=references/templates.md" \
  -F "files=@{SKILL_DIR}/references/playbooks.md;filename=references/playbooks.md" \
  -F "files=@{SKILL_DIR}/references/fallbacks.md;filename=references/fallbacks.md" \
  -F "files=@{SKILL_DIR}/references/runbook.md;filename=references/runbook.md"
```
Expected: `{"versionId":"..."}` (HTTP 200)

### Version Bump on Conflict
If HTTP 400 with "Version already exists":
1. Parse current version: `X.Y.Z`
2. Bump: `X.Y.(Z+1)`
3. Retry with new version (max 5 retries)

---

## GitHub PR (Anthropic Skills / ECC Community)

### Verify Token
```bash
curl -s \
  -H "Authorization: Bearer {TOKEN}" \
  -H "Accept: application/vnd.github+json" \
  https://api.github.com/user
```
Expected: `{"login":"username",...}`

### Fork Repository
```bash
curl -s -X POST \
  -H "Authorization: Bearer {TOKEN}" \
  -H "Accept: application/vnd.github+json" \
  https://api.github.com/repos/{OWNER}/{REPO}/forks \
  -d '{}'
```
Wait 3 seconds after forking.

### Get Default Branch SHA
```bash
curl -s \
  -H "Authorization: Bearer {TOKEN}" \
  -H "Accept: application/vnd.github+json" \
  https://api.github.com/repos/{USERNAME}/{REPO}/git/ref/heads/{DEFAULT_BRANCH}
```
Extract: `.object.sha`

### Create Branch
```bash
curl -s -X POST \
  -H "Authorization: Bearer {TOKEN}" \
  -H "Accept: application/vnd.github+json" \
  https://api.github.com/repos/{USERNAME}/{REPO}/git/refs \
  -d '{"ref":"refs/heads/{BRANCH}","sha":"{BASE_SHA}"}'
```

### Upload File (base64)
```bash
CONTENT=$(base64 < "{FILE_PATH}")
curl -s -X PUT \
  -H "Authorization: Bearer {TOKEN}" \
  -H "Accept: application/vnd.github+json" \
  "https://api.github.com/repos/{USERNAME}/{REPO}/contents/{TARGET_PATH}" \
  -d '{"message":"Add {FILE} for skill: {SKILL_NAME}","content":"'"$CONTENT"'","branch":"{BRANCH}"}'
```

### Create Pull Request
```bash
curl -s -X POST \
  -H "Authorization: Bearer {TOKEN}" \
  -H "Accept: application/vnd.github+json" \
  https://api.github.com/repos/{OWNER}/{REPO}/pulls \
  -d '{"title":"Add skill: {SKILL_NAME}","head":"{USERNAME}:{BRANCH}","base":"{DEFAULT_BRANCH}","body":"Adding skill **{SKILL_NAME}** via skill-publish-to-market.\n\nFiles:\n- SKILL.md\n- references/templates.md\n- references/playbooks.md\n- references/fallbacks.md\n- references/runbook.md"}'
```
Extract: `.html_url`, `.number`

---

## Platform-Specific Configurations

| Platform | Owner/Repo | File Path Prefix | Default Branch |
|----------|------------|-----------------|----------------|
| Anthropic Skills | `anthropics/skills` | `skills/{SKILL_NAME}/` | `main` |
| ECC Community | `affaan-m/everything-claude-code` | `skills/{SKILL_NAME}/` | `main` |
| skills.sh | `skills-sh/registry` | `{SKILL_NAME}/` | `main` |

---

## Quality Gate Templates

Pre-publish validation runs three levels of checks before any platform upload. Every skill must pass Level 1 to proceed. Level 2 produces warnings. Level 3 produces a numeric score.

### Level 1: Frontmatter Validation

Regex to extract and validate YAML frontmatter:

```
^---\r?\n([\s\S]*?)\r?\n---
```

> Note: The `\r?` makes this compatible with both Unix (LF) and Windows (CRLF) line endings.

Required fields (case-sensitive match within the extracted block):
```
^name:\s+.+$
^description:\s+.+$
^version:\s+\d+\.\d+\.\d+$
```

Output format:
```
## Quality Gate: Level 1 (Frontmatter)

| Field       | Status | Value                |
|-------------|--------|----------------------|
| name        | PASS   | my-awesome-skill     |
| description | PASS   | Does something great |
| version     | PASS   | 1.2.0                |

Result: PASS (3/3 required fields present)
```

If any field is missing, result is HARD FAIL. Publishing cannot proceed.

### Level 2: Warning Checklist

Check for recommended (non-blocking) quality signals:

```
## Quality Gate: Level 2 (Warnings)

| Check                        | Status  | Note                                        |
|------------------------------|---------|---------------------------------------------|
| references/ directory exists | {CHECK} | {path found or "Missing: no reference files"}|
| description length >= 20     | {CHECK} | {char count} characters                     |
| description length <= 200    | {CHECK} | {char count} characters                     |
| Has ## Prerequisites section | {CHECK} |                                             |
| Has ## Examples section      | {CHECK} |                                             |
| Has ## Parameters section    | {CHECK} |                                             |

Warnings: {N}/6
```

Status values: `OK` or `WARN`. Warnings do not block publishing but are displayed to the user.

### Level 3: 10-Point Quick Scan

Derived from skill-scorer anti-pattern analysis. Each item scores 0 or 1. Total out of 10.

```
## Quality Gate: Level 3 (Quick Scan)

| #  | Check                        | Score | Detail                              |
|----|------------------------------|-------|-------------------------------------|
| 1  | Valid YAML frontmatter       | {0/1} | Parseable frontmatter block         |
| 2  | Identity lock present        | {0/1} | "You are..." or "Act as..." found   |
| 3  | Prerequisites listed         | {0/1} | ## Prerequisites section exists     |
| 4  | Step 0 (setup/validation)    | {0/1} | First step checks environment       |
| 5  | Parameters documented        | {0/1} | ## Parameters with typed entries     |
| 6  | Examples provided            | {0/1} | ## Examples with concrete usage      |
| 7  | Validation / error handling  | {0/1} | Error cases or edge cases addressed  |
| 8  | Knowledge disclaimer         | {0/1} | Limitations or scope stated          |
| 9  | Self-contained instructions  | {0/1} | No dangling external-only references |
| 10 | Output format specified      | {0/1} | Expected output shape documented     |

Score: {N}/10
```

---

## Platform Adaptation Templates

When publishing to different platforms, files and metadata may need transformation. Apply these rules before uploading.

### ClawHub Adaptation

**Slug generation:**
1. Take skill directory name (e.g., `my-awesome-skill`)
2. Lowercase, replace spaces and underscores with hyphens: `[^a-z0-9-]` -> `-`
3. Collapse consecutive hyphens: `--+` -> `-`
4. Strip leading/trailing hyphens
5. If user provides a prefix (e.g., `cs-`), prepend: `cs-my-awesome-skill`

**Display name from slug:**
- Split on hyphens, capitalize each word: `my-awesome-skill` -> `My Awesome Skill`

**Tags extraction:**
1. First, check frontmatter for `tags:` field (YAML list)
2. If no tags in frontmatter, extract keywords from `description:` (nouns over 4 chars)
3. Always include `"latest"` as the first tag
4. Maximum 5 tags total

### Anthropic Skills Adaptation

**Frontmatter requirements:**
- `license`: must be present; default to `MIT` if missing
- `author`: must be present; use GitHub username from token verification if missing
- `tags`: must be a YAML list; generate from description if missing

**File path mapping:**
```
{SKILL_DIR}/SKILL.md           -> skills/{slug}/SKILL.md
{SKILL_DIR}/references/*.md    -> skills/{slug}/references/*.md
```

### ECC Community Adaptation

**File path mapping:**
```
{SKILL_DIR}/SKILL.md           -> skills/{slug}/SKILL.md
{SKILL_DIR}/references/*.md    -> skills/{slug}/references/*.md
```

**PR body template:**
```markdown
## New Skill: {SKILL_NAME}

**Description:** {description from frontmatter}
**Version:** {version from frontmatter}

### Files
- `skills/{slug}/SKILL.md`
- `skills/{slug}/references/templates.md`
- `skills/{slug}/references/playbooks.md`
- `skills/{slug}/references/fallbacks.md`
- `skills/{slug}/references/runbook.md`

### Quality Gate
- Frontmatter: PASS
- Quick Scan Score: {N}/10

---
Submitted via skill-publish-to-market
```

### skills.sh Adaptation

**File path mapping:**
```
{SKILL_DIR}/SKILL.md           -> {slug}/SKILL.md
{SKILL_DIR}/references/*.md    -> {slug}/references/*.md
{SKILL_DIR}/README.md          -> {slug}/README.md  (if present)
```

**README.md inclusion:** If `{SKILL_DIR}/README.md` exists, include it in the upload. skills.sh uses README.md as the landing page for the skill registry entry.

---

## Output Template

```
## Publishing Results: {SKILL_NAME} v{VERSION}

| Platform | Status | Details |
|----------|--------|---------|
| ClawHub | {STATUS} | {DETAILS} |
| Anthropic Skills | {STATUS} | {DETAILS} |
| ECC Community | {STATUS} | {DETAILS} |
| skills.sh | {STATUS} | {DETAILS} |

Published via skill-publish-to-market
```

Status values: Success / Failed / Skipped
Details: PR URL, slug@version, or error message

---

## Partial Success Report Template

When some platforms succeed and others fail, use this combined report:

```
## Publishing Results: {SKILL_NAME} v{VERSION}

### Succeeded ({SUCCESS_COUNT}/{TOTAL_COUNT})

| Platform | Details |
|----------|---------|
| {PLATFORM} | {slug@version or PR URL} |

### Failed ({FAILURE_COUNT}/{TOTAL_COUNT})

| Platform | Error | Retryable |
|----------|-------|-----------|
| {PLATFORM} | {error message} | {Yes/No} |

### Recommended Actions
- {action 1, e.g., "Retry `anthropic` -- token scopes may need `repo`"}
- {action 2}

To retry failed platforms only:
> publish {SKILL_NAME} --platforms {failed_platform_1},{failed_platform_2}
```

---

## Follow-up Command Templates

After publishing, users may want to check status or retry. These are the curl implementations for follow-up actions.

### Status Check: ClawHub
```bash
curl -s \
  -H "Authorization: Bearer {TOKEN}" \
  -H "Accept: application/json" \
  "https://clawhub.ai/api/v1/skills/{SLUG}"
```
Returns: version info, download count, publish date.

### Status Check: GitHub PR
```bash
curl -s \
  -H "Authorization: Bearer {TOKEN}" \
  -H "Accept: application/vnd.github+json" \
  "https://api.github.com/repos/{OWNER}/{REPO}/pulls/{PR_NUMBER}"
```
Extract: `.state` (open/closed/merged), `.mergeable`, `.merged_at`

### Retry Failed Platform
Re-run the publish sequence for a single platform using the same tokens and skill directory. The retry command is identical to the original publish curl for that platform.

### Publish (New Version)
Same as initial publish, but with an incremented version. Bump `version:` in SKILL.md frontmatter before re-running.

---

## Batch Progress Template

When publishing multiple skills, show incremental progress:

```
## Batch Publishing Progress

| # | Skill | ClawHub | Anthropic | ECC | skills.sh |
|---|-------|---------|-----------|-----|-----------|
| 1 | {name} | OK | OK | OK | OK |
| 2 | {name} | OK | FAIL | OK | -- |
| 3 | {name} | ... | ... | ... | ... |

Progress: {completed}/{total} skills
Elapsed: {time}s
```

Individual cell values: `OK`, `FAIL`, `SKIP`, `--` (pending), `...` (in progress)


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)