Skill: skill-factory-pipeline (version 1.0.0)

--- name: skill-factory description: "Multi-Agent Pipeline Orchestrator that builds new skills from scratch. Use when: (1) You have a skill idea and want to take it from concept to market-ready package, (2) You need a structured 7-stage process: market research → planning → architecture → building → auditing → documentation → pricing, (3) You want each stage run as an isolated, sequential agent call with no nested sessions. Trigger on: 'create a new skill', 'build a skill', 'skill factory', 'new skill pipeline'." --- # Skill Factory A 7-stage multi-agent pipeline that takes a raw skill idea and produces a complete, market-ready skill package. Each stage is an isolated CLI agent call — no nested sessions, no parallelism. ## Overview ``` idea → market → planner → arch → builder → auditor → docs → pricer → done ``` All state is written to disk between stages. Any stage can be re-run independently. ## Workflow ### Step 1: Initialize a skill idea ```bash python3 {baseDir}/scripts/init_pipeline.py "My Skill Idea" --workspace /tmp/sf-my-skill ``` This creates a workspace directory with `idea.md` pre-filled. Review and edit `idea.md` before running the pipeline. ### Step 2: Run the full pipeline ```bash bash {baseDir}/scripts/pipeline.sh --workspace /tmp/sf-my-skill ``` The pipeline runs all 7 agents sequentially. Each agent reads previous outputs and writes its own report into the workspace. ### Step 3: Collect outputs After the pipeline completes, the workspace contains: ``` workspace/ ├── idea.md # Your original idea (input) ├── market.md # Market research report ├── plan.md # Product plan with requirements ├── arch.md # Architecture and file structure ├── skill/ # The built skill (SKILL.md + scripts/ + references/) ├── audit.md # Quality audit report ├── docs_review.md # Documentation review └── pricing.md # Pricing and positioning ``` ### Step 4: Review gates Each stage has a gate. If a gate fails, the pipeline stops with a non-zero exit code and reports which stage failed. Fix the issue and re-run from that stage: ```bash bash {baseDir}/scripts/pipeline.sh --workspace /tmp/sf-my-skill --from auditor ``` ## Stages at a glance | Stage | Agent ID | Input | Output | |----------|------------|--------------------|----------------| | market | market | idea.md | market.md | | planner | planner | idea.md, market.md | plan.md | | arch | arch | plan.md | arch.md | | builder | builder | arch.md, plan.md | skill/ | | auditor | auditor | skill/ | audit.md | | docs | docs | skill/, audit.md | docs_review.md | | pricer | pricer | all outputs | pricing.md | Read [references/agents.md](references/agents.md) for full agent descriptions, models, and prompt guidance. Read [references/pipeline.md](references/pipeline.md) for detailed gate definitions, failure modes, and re-run strategies. ## Key Constraints - **No nested sessions** — every agent runs as a top-level isolated CLI call - **No parallelism** — stages run strictly sequentially; each depends on the previous - **File-based state** — all inter-stage communication goes through the workspace filesystem - **Idempotent stages** — re-running a stage overwrites its output without affecting others ## When NOT to Use This Skill - You only need a quick, simple skill with no research phase — use `init_skill.py` directly - You are iterating on an existing skill — edit files directly - You want parallel research across multiple skill ideas — run multiple pipeline instances in separate workspaces

path: references/agents.md
content: # Agents Reference

Each stage of the skill-factory pipeline runs as a dedicated agent. All agents are called as isolated top-level CLI calls — never from within a nested session.

## Invocation pattern

```bash
openclaw agent --agent <id> -m "<prompt>"
```

The prompt is constructed by `pipeline.sh` and injected at invocation time. No interactive input. No session state carried between agents. All communication goes through the filesystem (workspace files).

---

## Stage 1 — market

**Agent ID:** `market`
**Model guidance:** High-reasoning model preferred (needs judgment on market signals)
**Input:** `idea.md`
**Output:** `market.md`

**Task:** Validate the skill idea against real market demand. Research the competitive landscape, identify the target audience, and deliver a GO / NO-GO verdict.

**Key behaviors:**
- Searches for existing tools, skills, or libraries that solve the same problem
- Identifies primary and secondary user personas
- Estimates demand based on tool usage, forum activity, search patterns
- Produces a structured market.md with a clear verdict at the end

**Failure modes:**
- market.md not written → gate fails, pipeline stops
- Verdict omitted → docs stage will lack context for positioning
- Overly optimistic analysis → pricer overestimates value

---

## Stage 2 — planner

**Agent ID:** `planner`
**Model guidance:** High-reasoning model preferred (product decisions require judgment)
**Input:** `idea.md`, `market.md`
**Output:** `plan.md`

**Task:** Translate the idea and market research into a concrete product plan. Defines scope, capabilities, trigger scenarios, and the exact list of files to build.

**Key behaviors:**
- Names the skill in hyphen-case (max 32 chars)
- Writes the one-sentence description that will go into SKILL.md frontmatter
- Lists trigger scenarios precisely (what user messages activate this skill)
- Specifies which resource directories are needed (scripts/, references/, assets/)
- Lists every file the skill will contain

**Failure modes:**
- plan.md not written → gate fails, pipeline stops
- Vague trigger scenarios → skill fires incorrectly or not at all
- Missing file list → builder makes arbitrary decisions

---

## Stage 3 — arch

**Agent ID:** `arch`
**Model guidance:** High-reasoning model preferred (architecture decisions have downstream impact)
**Input:** `plan.md`
**Output:** `arch.md`

**Task:** Design the internal architecture of the skill. Produces a detailed blueprint that the builder follows exactly.

**Key behaviors:**
- Draws the full directory tree
- Outlines the SKILL.md sections
- Describes each script: name, language, inputs, outputs, core logic
- Describes each reference file: content summary and when an agent would load it
- Documents the data flow and integration pattern

**Failure modes:**
- arch.md not written → gate fails, pipeline stops
- Directory tree missing → builder creates arbitrary structure
- Script descriptions too vague → builder produces generic stubs

---

## Stage 4 — builder

**Agent ID:** `builder`
**Model guidance:** Any capable coding model; cost-effective models work for mechanical file creation
**Input:** `arch.md`, `plan.md`
**Output:** `skill/` directory with all files

**Task:** Implement the skill. Creates every file listed in the architecture. No placeholders, no TODOs — production-ready content.

**Key behaviors:**
- Creates `skill/SKILL.md` with valid frontmatter (name, description)
- Creates all scripts with correct shebangs, usage docs, real logic
- Creates all reference files with comprehensive content
- Follows the directory structure exactly as specified in arch.md

**Gate check:** `skill/SKILL.md` must exist and be non-empty

**Failure modes:**
- skill/SKILL.md missing → gate fails, pipeline stops
- Placeholder content in scripts → auditor will flag as FAIL
- Divergence from arch.md → inconsistency with plan

---

## Stage 5 — auditor

**Agent ID:** `auditor`
**Model guidance:** High-reasoning model preferred (quality judgment requires thoroughness)
**Input:** `skill/` (all files)
**Output:** `audit.md`

**Task:** Perform a structured quality audit of the built skill. Each audit item gets PASS / WARN / FAIL status. Concludes with OVERALL: PASS or FAIL.

**Audit checklist:**
1. SKILL.md completeness and frontmatter validity
2. Trigger accuracy (correct activation conditions)
3. Script quality (shebang, error handling, real logic)
4. Reference quality (comprehensive, no placeholder content)
5. Internal consistency across all files
6. Security review (no injection risks, no hardcoded secrets)
7. Gap analysis (missing capabilities)

**Failure modes:**
- audit.md not written → gate fails, pipeline stops
- OVERALL: FAIL → docs stage is blocked (by design)
- Missing security review → undetected vulnerabilities in scripts

---

## Stage 6 — docs

**Agent ID:** `docs`
**Model guidance:** Any capable writing model
**Input:** `skill/`, `audit.md`
**Output:** `docs_review.md`

**Task:** Review documentation quality and provide specific rewrites for unclear passages. Blocked by a failed audit.

**Key behaviors:**
- Checks if audit OVERALL is FAIL → writes blocking message to docs_review.md
- Evaluates clarity, examples, decision guidance, edge cases, cross-references
- Quotes original text and provides improved rewrites (not just "this is unclear")

**Failure modes:**
- docs_review.md not written → gate fails, pipeline stops
- Vague feedback without rewrites → developer has nothing actionable

---

## Stage 7 — pricer

**Agent ID:** `pricer`
**Model guidance:** Any capable model; benefits from business reasoning
**Input:** `market.md`, `plan.md`, `audit.md`, `skill/SKILL.md`
**Output:** `pricing.md`

**Task:** Determine the pricing, positioning, and marketplace strategy for the skill.

**Key behaviors:**
- Assigns a quality tier (Starter / Standard / Pro) based on audit results and complexity
- Recommends a specific USD price with written rationale
- Writes a one-paragraph positioning statement for the marketplace listing
- Lists 3-5 key selling points as bullet points
- Suggests tags and categories for discovery
- Recommends launch strategy (free trial / bundle / direct)

**Failure modes:**
- pricing.md not written → gate fails, pipeline stops
- Price without rationale → owner cannot adjust or negotiate
- Missing positioning statement → listing lacks copy


path: references/pipeline.md
content: # Pipeline Reference

Detailed specification of the skill-factory pipeline: stage order, gate definitions, failure handling, and re-run strategies.

## Architecture principle

The pipeline is a **linear state machine**. Each stage:
1. Reads from the workspace filesystem
2. Calls one isolated agent via `openclaw agent --agent <id> -m "<prompt>"`
3. Waits for the call to return
4. Checks the gate (file existence and non-empty)
5. Marks the stage done in `.pipeline_state`
6. Proceeds to the next stage

**No parallelism. No nested sessions. No shared process state.**

---

## Stage order

```
idea.md (input)
    │
    ▼
[market] ──────────── market.md
    │
    ▼
[planner] ─────────── plan.md
    │
    ▼
[arch] ─────────────── arch.md
    │
    ▼
[builder] ──────────── skill/
    │
    ▼
[auditor] ──────────── audit.md
    │
    ▼
[docs] ─────────────── docs_review.md
    │
    ▼
[pricer] ───────────── pricing.md
```

Each arrow represents a file written to disk. No stage passes data in memory.

---

## Gate definitions

Gates run immediately after an agent call returns. A gate failure stops the pipeline.

| Stage   | Gate condition                             | Failure action       |
|---------|--------------------------------------------|----------------------|
| market  | `market.md` exists and non-empty           | Stop, report stage   |
| planner | `plan.md` exists and non-empty             | Stop, report stage   |
| arch    | `arch.md` exists and non-empty             | Stop, report stage   |
| builder | `skill/SKILL.md` exists and non-empty      | Stop, report stage   |
| auditor | `audit.md` exists and non-empty            | Stop, report stage   |
| docs    | `docs_review.md` exists and non-empty      | Stop, report stage   |
| pricer  | `pricing.md` exists and non-empty          | Stop, report stage   |

### Soft gates (checked by agents, not by the pipeline script)

These conditions are enforced by agent instructions, not bash file checks:

- **auditor** → OVERALL must be PASS or FAIL (not missing)
- **docs** → If audit OVERALL is FAIL, docs_review.md must contain "BLOCKED"
- **pricer** → pricing.md must include a USD price and positioning statement

If a soft gate is violated (e.g., auditor writes an empty OVERALL), the next stage will produce low-quality output. Review audit.md manually if outputs seem off.

---

## Re-running stages

If a stage fails or produces bad output, re-run from that stage:

```bash
# Re-run from a specific stage to the end
pipeline.sh --workspace /tmp/sf-stripe --from auditor

# Re-run a single stage only
pipeline.sh --workspace /tmp/sf-stripe --from builder --to builder

# Re-run the last two stages
pipeline.sh --workspace /tmp/sf-stripe --from docs
```

Re-running a stage **overwrites** its output file. Earlier stages are unaffected.

The `.pipeline_state` file logs timestamps of completed stages for reference but does not prevent re-runs. It is informational only.

---

## Failure scenarios and recovery

### Scenario 1: Agent produces empty output

**Symptom:** Gate fails immediately after agent call.

**Likely causes:**
- Agent hit a context or token limit
- Agent misunderstood the prompt

**Recovery:**
1. Check if the output file was partially written: `cat workspace/market.md`
2. If partially written: edit the file manually, then run from the next stage
3. If completely empty: re-run the stage with `--from <stage> --to <stage>`

---

### Scenario 2: Audit returns OVERALL: FAIL

**Symptom:** `audit.md` contains "OVERALL: FAIL" with a list of required fixes.

**This is expected behavior.** The docs stage will write "BLOCKED" and stop.

**Recovery:**
1. Read `audit.md` — find the numbered required fixes
2. Edit the skill files manually in `workspace/skill/`
3. Re-run from the auditor: `--from auditor`
4. Repeat until auditor returns OVERALL: PASS

---

### Scenario 3: Builder diverges from architecture

**Symptom:** `skill/` contains different files than what `arch.md` specified.

**Recovery (Option A — fix builder output):**
1. Compare `arch.md` against `ls workspace/skill/`
2. Manually create or correct the missing files
3. Re-run from auditor: `--from auditor`

**Recovery (Option B — re-run builder):**
1. Remove the divergent files: `rm -rf workspace/skill/`
2. Re-run builder: `--from builder --to builder`

---

### Scenario 4: Market returns NO-GO verdict

**Symptom:** `market.md` ends with "NO-GO".

**This is a valid outcome.** The pipeline will continue (it does not parse the verdict), but the pricer will note low market viability.

**Decision points:**
- Stop the pipeline and pivot the idea — edit `idea.md`, re-run from `--from market`
- Continue anyway — note that the skill may have limited commercial value
- Narrow the scope — edit `idea.md` to reduce scope, re-run from `--from market`

---

## Workspace layout

```
workspace/
├── idea.md              # Input — created by init_pipeline.py, edited by user
├── .pipeline_state      # Timestamps of completed stages (informational)
├── market.md            # Stage 1 output
├── plan.md              # Stage 2 output
├── arch.md              # Stage 3 output
├── skill/               # Stage 4 output
│   ├── SKILL.md
│   ├── scripts/
│   │   └── *.sh / *.py
│   └── references/
│       └── *.md
├── audit.md             # Stage 5 output
├── docs_review.md       # Stage 6 output
└── pricing.md           # Stage 7 output
```

All files are plain text (markdown or bash/python). No binary state.

---

## Design rationale

### Why sequential and not parallel?

Each stage consumes output from the previous stage. The planner needs market research before scoping. The builder needs the architecture before implementing. Parallelism would require complex dependency tracking with no benefit — the bottleneck is agent execution time, not orchestration overhead.

### Why no nested sessions?

Nested sessions (spawning agents from within an agent's session) create:
- Hidden state the orchestrator cannot observe
- Non-deterministic execution order
- Impossible re-runs (you'd need to reproduce the outer session state)

Every agent call in this pipeline goes to the OS process table, not to a parent agent's session. The pipeline script is the orchestrator. It is the only process that knows the full state.

### Why file-based communication?

Files are:
- Inspectable at any time with a text editor
- Persistent across crashes
- Trivially re-runnable (re-run a stage = overwrite a file)
- Usable as handoff artifacts to humans

Environment variables or in-memory state would disappear on failure and make debugging opaque.


path: scripts/init_pipeline.py
content: #!/usr/bin/env python3
"""
init_pipeline.py — Initialize a new skill-factory workspace

Usage:
    init_pipeline.py "<skill idea>" --workspace <path>

Examples:
    init_pipeline.py "A skill for managing Stripe subscriptions" --workspace /tmp/sf-stripe
    init_pipeline.py "PDF table extractor" --workspace ~/skill-builds/pdf-tables

Creates the workspace directory and writes idea.md with a structured template.
Edit idea.md before running pipeline.sh.
"""

import argparse
import sys
from datetime import datetime
from pathlib import Path

IDEA_TEMPLATE = """\
# Skill Idea

**Created:** {date}

## Core Idea

{idea}

## Problem it solves

[TODO: What pain point does this skill address? Who feels that pain?]

## Target users

[TODO: Who will use this skill? What tools/workflows do they already use?]

## Key capabilities

[TODO: List 3-5 concrete things the skill enables an agent to do]
-
-
-

## Similar / competing skills

[TODO: What exists already? How is this different?]

## Success criteria

[TODO: How do you know the skill is complete and useful?]
- The skill triggers correctly when users describe [...]
- An agent using the skill can [...]
- The skill produces outputs that [...]

## Notes

[TODO: Anything else relevant — constraints, known limitations, ideas to explore]
"""

STAGES = ["market", "planner", "arch", "builder", "auditor", "docs", "pricer"]


def init_pipeline(idea: str, workspace_path: Path) -> bool:
    # Reject if workspace already exists and is non-empty
    if workspace_path.exists():
        contents = list(workspace_path.iterdir())
        if contents:
            print(f"[ERROR] Workspace already exists and is not empty: {workspace_path}")
            print("  Use a different path, or remove the existing workspace first.")
            return False

    workspace_path.mkdir(parents=True, exist_ok=True)
    print(f"[OK] Created workspace: {workspace_path}")

    # Write idea.md
    idea_path = workspace_path / "idea.md"
    idea_content = IDEA_TEMPLATE.format(
        idea=idea.strip(),
        date=datetime.now().strftime("%Y-%m-%d"),
    )
    idea_path.write_text(idea_content)
    print(f"[OK] Created idea.md")

    # Write pipeline state file (tracks which stages have run)
    state_path = workspace_path / ".pipeline_state"
    state_path.write_text("# pipeline state — do not edit manually\n")
    print(f"[OK] Created .pipeline_state")

    print()
    print(f"Workspace ready: {workspace_path}")
    print()
    print("Next steps:")
    print(f"  1. Edit {idea_path} — fill in the TODOs")
    print(f"  2. Run the pipeline:")
    print(f"       bash pipeline.sh --workspace {workspace_path}")
    print(f"  3. Or run a single stage:")
    print(f"       bash pipeline.sh --workspace {workspace_path} --from market --to market")
    print()
    print(f"Pipeline stages: {' → '.join(STAGES)}")
    return True


def main():
    parser = argparse.ArgumentParser(
        description="Initialize a skill-factory workspace for a new skill idea.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=__doc__,
    )
    parser.add_argument("idea", help="One-sentence description of the skill idea")
    parser.add_argument("--workspace", required=True, help="Path to create the workspace directory")
    args = parser.parse_args()

    workspace = Path(args.workspace).expanduser().resolve()
    success = init_pipeline(args.idea, workspace)
    sys.exit(0 if success else 1)


if __name__ == "__main__":
    main()


path: scripts/pipeline.sh
content: #!/usr/bin/env bash
# pipeline.sh — Skill Factory Pipeline Orchestrator
#
# Runs 7 agents sequentially to build a skill from idea to market-ready package.
# Each agent is an isolated CLI call. No nested sessions. No parallelism.
#
# Usage:
#   pipeline.sh --workspace <path> [--from <stage>] [--to <stage>] [--dry-run]
#
# Stages (in order):
#   market → planner → arch → builder → auditor → docs → pricer
#
# Examples:
#   pipeline.sh --workspace /tmp/sf-stripe
#   pipeline.sh --workspace /tmp/sf-stripe --from auditor
#   pipeline.sh --workspace /tmp/sf-stripe --from planner --to builder
#   pipeline.sh --workspace /tmp/sf-stripe --dry-run

set -euo pipefail

# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------

STAGES=(market planner arch builder auditor docs pricer)

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

usage() {
  cat <<'EOF'
Usage: pipeline.sh --workspace <path> [OPTIONS]

Options:
  --workspace <path>   Workspace directory created by init_pipeline.py (required)
  --from <stage>       Start pipeline from this stage (default: market)
  --to <stage>         Stop pipeline after this stage (default: pricer)
  --dry-run            Print agent commands without executing them
  -h, --help           Show this help

Stages: market → planner → arch → builder → auditor → docs → pricer
EOF
}

log()  { echo "[pipeline] $*"; }
info() { echo "[pipeline] INFO  $*"; }
ok()   { echo "[pipeline] OK    $*"; }
fail() { echo "[pipeline] FAIL  $*" >&2; }

stage_index() {
  local name="$1"
  local i
  for i in "${!STAGES[@]}"; do
    [[ "${STAGES[$i]}" == "$name" ]] && echo "$i" && return 0
  done
  echo "-1"
}

validate_stage() {
  local name="$1"
  local idx
  idx=$(stage_index "$name")
  if [[ "$idx" == "-1" ]]; then
    fail "Unknown stage: '$name'. Valid stages: ${STAGES[*]}"
    exit 1
  fi
}

mark_stage_done() {
  local stage="$1"
  local ws="$2"
  echo "$stage=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$ws/.pipeline_state"
}

# ---------------------------------------------------------------------------
# Gate checks — validate expected output files exist and are non-empty
# ---------------------------------------------------------------------------

gate_market() {
  local ws="$1"
  [[ -s "$ws/market.md" ]] || { fail "Gate [market]: market.md is missing or empty"; return 1; }
}

gate_planner() {
  local ws="$1"
  [[ -s "$ws/plan.md" ]] || { fail "Gate [planner]: plan.md is missing or empty"; return 1; }
}

gate_arch() {
  local ws="$1"
  [[ -s "$ws/arch.md" ]] || { fail "Gate [arch]: arch.md is missing or empty"; return 1; }
}

gate_builder() {
  local ws="$1"
  [[ -s "$ws/skill/SKILL.md" ]] || { fail "Gate [builder]: skill/SKILL.md is missing or empty"; return 1; }
}

gate_auditor() {
  local ws="$1"
  [[ -s "$ws/audit.md" ]] || { fail "Gate [auditor]: audit.md is missing or empty"; return 1; }
}

gate_docs() {
  local ws="$1"
  [[ -s "$ws/docs_review.md" ]] || { fail "Gate [docs]: docs_review.md is missing or empty"; return 1; }
}

gate_pricer() {
  local ws="$1"
  [[ -s "$ws/pricing.md" ]] || { fail "Gate [pricer]: pricing.md is missing or empty"; return 1; }
}

run_gate() {
  local stage="$1"
  local ws="$2"
  "gate_${stage}" "$ws"
}

# ---------------------------------------------------------------------------
# Agent prompt builders
# Each function echoes the prompt string for that stage.
# Prompts read from workspace files — all paths are absolute.
# ---------------------------------------------------------------------------

prompt_market() {
  local ws="$1"
  cat <<EOF
You are a market research analyst specializing in AI developer tools.

Read the skill idea at: $ws/idea.md

Produce a market research report and write it to: $ws/market.md

The report must include:
1. Problem validation — Is the problem real and felt by enough users?
2. Target audience — Who are the primary users? Secondary users?
3. Competitive landscape — What exists already (skills, tools, libraries)?
4. Differentiation — What would make this skill stand out?
5. Demand signals — Evidence of demand (searches, forum posts, tool popularity)
6. Market verdict — GO / NO-GO with one-paragraph rationale

Keep the report factual and concise. Use markdown headers.
Write ONLY to $ws/market.md. Do not create other files.
EOF
}

prompt_planner() {
  local ws="$1"
  cat <<EOF
You are a product planner for AI developer tools.

Read:
- Skill idea: $ws/idea.md
- Market research: $ws/market.md

Produce a product plan and write it to: $ws/plan.md

The plan must include:
1. Skill name (hyphen-case, max 32 chars)
2. One-sentence description (for SKILL.md frontmatter)
3. Core capabilities — what the skill enables an agent to do (3-7 items)
4. Out of scope — what this skill explicitly does NOT do
5. Trigger scenarios — exact user requests that should activate this skill
6. Required resources — which of scripts/, references/, assets/ are needed and why
7. Key files — list every file the skill will contain with one-line purpose
8. Acceptance criteria — how to verify the skill is complete

Write ONLY to $ws/plan.md. Do not create other files.
EOF
}

prompt_arch() {
  local ws="$1"
  cat <<EOF
You are a software architect specializing in AI skill design.

Read:
- Product plan: $ws/plan.md

Produce an architecture document and write it to: $ws/arch.md

The architecture must include:
1. Directory layout — exact tree of all files and directories
2. SKILL.md structure — section outline with purpose of each section
3. Scripts design — for each script: name, language, inputs, outputs, core logic
4. References design — for each reference file: name, content summary, when to load it
5. Data flow — how information moves between skill components
6. Integration points — how an agent will invoke the skill in practice
7. Open questions — any design decisions that need the builder's judgment

Write ONLY to $ws/arch.md. Do not create other files.
EOF
}

prompt_builder() {
  local ws="$1"
  cat <<EOF
You are an expert skill builder for the openclaw skill system.

Read:
- Architecture: $ws/arch.md
- Product plan: $ws/plan.md

Build the complete skill. Create all files inside: $ws/skill/

Required output:
- $ws/skill/SKILL.md — complete, production-ready (following the official template format with frontmatter: name, description)
- All scripts listed in arch.md, placed in $ws/skill/scripts/
- All reference files listed in arch.md, placed in $ws/skill/references/

Rules:
- SKILL.md frontmatter must have 'name' and 'description' fields
- Scripts must be executable and include a usage docstring
- Reference files must be thorough enough to stand alone
- Do not add placeholder TODOs — write real content
- Do not create files not listed in arch.md without justification

Write ONLY inside $ws/skill/. Do not modify other workspace files.
EOF
}

prompt_auditor() {
  local ws="$1"
  cat <<EOF
You are a quality auditor for AI developer skills.

Read all files in: $ws/skill/

Audit the skill and write your report to: $ws/audit.md

Audit checklist:
1. SKILL.md completeness — frontmatter valid, description accurate, all sections present
2. Trigger accuracy — will the skill fire for the right requests and not for wrong ones?
3. Script quality — correct shebang, error handling, usage docs, executable logic
4. Reference quality — comprehensive, accurate, no placeholder content
5. Internal consistency — do all files agree with each other?
6. Security review — no hardcoded secrets, no unsafe shell expansions, no command injection risks
7. Gaps — what is missing or incomplete?

For each item: PASS / WARN / FAIL with one-line explanation.

End with:
- OVERALL: PASS / FAIL
- Required fixes (if FAIL): numbered list of blocking issues
- Recommended improvements (if PASS): numbered list of non-blocking suggestions

Write ONLY to $ws/audit.md. Do not modify skill files.
EOF
}

prompt_docs() {
  local ws="$1"
  cat <<EOF
You are a technical documentation specialist for AI developer tools.

Read:
- Skill files: $ws/skill/
- Audit report: $ws/audit.md

If the audit overall result is FAIL, stop immediately and write to $ws/docs_review.md:
"BLOCKED: Audit failed. Fix required issues in audit.md before docs review."

Otherwise, review the documentation quality and write your report to: $ws/docs_review.md

Documentation review:
1. Clarity — can a new user understand what this skill does in 30 seconds?
2. Examples — are there concrete, realistic usage examples?
3. Decision guidance — does the skill tell agents WHEN to use each feature?
4. Edge cases — are failure modes and limitations documented?
5. Cross-references — do references between files work and add value?

Provide specific rewrites for any unclear passages (quote original, then improved version).

Write ONLY to $ws/docs_review.md. Do not modify skill files.
EOF
}

prompt_pricer() {
  local ws="$1"
  cat <<EOF
You are a pricing strategist for AI developer tools sold on the openclaw marketplace.

Read:
- Market research: $ws/market.md
- Product plan: $ws/plan.md
- Audit report: $ws/audit.md
- Skill files: $ws/skill/SKILL.md

Produce a pricing and positioning report and write it to: $ws/pricing.md

The report must include:
1. Skill quality tier — Starter / Standard / Pro (based on audit and complexity)
2. Recommended price — specific number in USD with rationale
3. Positioning statement — one paragraph for the marketplace listing
4. Key selling points — 3-5 bullet points for the listing description
5. Suggested tags/categories — for marketplace discovery
6. Launch strategy — free trial, bundle opportunity, or direct sale?
7. Risks — what could reduce perceived value or sales?

Write ONLY to $ws/pricing.md. Do not create other files.
EOF
}

# ---------------------------------------------------------------------------
# Stage runner
# ---------------------------------------------------------------------------

run_stage() {
  local stage="$1"
  local ws="$2"
  local dry_run="$3"

  local prompt
  prompt="$(prompt_${stage} "$ws")"

  log "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  log "Stage: $stage"
  log "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

  if [[ "$dry_run" == "true" ]]; then
    echo "[DRY-RUN] Would execute:"
    echo "  openclaw agent --agent $stage -m \"...\""
    echo "  Prompt preview (first 3 lines):"
    echo "$prompt" | head -3 | sed 's/^/    /'
    return 0
  fi

  info "Calling: openclaw agent --agent $stage"
  # IMPORTANT: This is a top-level isolated CLI call.
  # It must NOT be called from within an existing openclaw session.
  # No flags that would create nested or interactive sessions.
  openclaw agent --agent "$stage" -m "$prompt"

  info "Running gate check for: $stage"
  if ! run_gate "$stage" "$ws"; then
    fail "Stage '$stage' did not produce expected output. Aborting pipeline."
    fail "Fix the issue and re-run with: --from $stage"
    exit 1
  fi

  mark_stage_done "$stage" "$ws"
  ok "Stage '$stage' complete."
}

# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

main() {
  local workspace=""
  local from_stage="market"
  local to_stage="pricer"
  local dry_run="false"

  while [[ $# -gt 0 ]]; do
    case "$1" in
      --workspace)   workspace="${2:-}"; shift 2 ;;
      --from)        from_stage="${2:-}"; shift 2 ;;
      --to)          to_stage="${2:-}"; shift 2 ;;
      --dry-run)     dry_run="true"; shift ;;
      -h|--help)     usage; exit 0 ;;
      *) fail "Unknown option: $1"; usage; exit 1 ;;
    esac
  done

  # Validate workspace
  if [[ -z "$workspace" ]]; then
    fail "--workspace is required"
    usage
    exit 1
  fi

  workspace="$(realpath "$workspace")"

  if [[ ! -d "$workspace" ]]; then
    fail "Workspace directory does not exist: $workspace"
    fail "Run init_pipeline.py first to create it."
    exit 1
  fi

  if [[ ! -f "$workspace/idea.md" ]]; then
    fail "idea.md not found in workspace: $workspace"
    fail "Run init_pipeline.py first to initialize the workspace."
    exit 1
  fi

  # Validate stage names
  validate_stage "$from_stage"
  validate_stage "$to_stage"

  local from_idx to_idx
  from_idx=$(stage_index "$from_stage")
  to_idx=$(stage_index "$to_stage")

  if [[ "$from_idx" -gt "$to_idx" ]]; then
    fail "--from '$from_stage' comes after --to '$to_stage' in the pipeline"
    exit 1
  fi

  log "Workspace:  $workspace"
  log "Stages:     $from_stage → $to_stage"
  [[ "$dry_run" == "true" ]] && log "Mode:       DRY-RUN"
  echo

  # Run stages sequentially
  local current_idx
  for i in "${!STAGES[@]}"; do
    current_idx="$i"
    local stage="${STAGES[$i]}"

    [[ "$current_idx" -lt "$from_idx" ]] && continue
    [[ "$current_idx" -gt "$to_idx" ]] && break

    run_stage "$stage" "$workspace" "$dry_run"
    echo
  done

  log "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  if [[ "$dry_run" == "true" ]]; then
    ok "Dry-run complete. No agents were called."
  else
    ok "Pipeline complete."
    log "Workspace: $workspace"
    log "Review your outputs:"
    log "  $workspace/pricing.md    ← start here for the summary"
    log "  $workspace/skill/        ← the built skill"
    log "  $workspace/audit.md      ← quality report"
  fi
}

main "$@"


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