Skill: chenhab03/claude-code-delegate (version 0.1.1)

--- name: claude-code-delegate description: Delegate programming tasks to Claude Code CLI user-invocable: true --- # Claude Code Delegate Delegate programming tasks to local Claude Code CLI. **RULE: You NEVER write code directly. ALL programming goes through `claude -p`.** ## Prerequisites Check (Run Before First Use) Before delegating any task, verify the environment is ready: 1. **Claude Code CLI installed**: Run `which claude` — if not found, tell user: `npm install -g @anthropic-ai/claude-code` 2. **API key configured**: Run `claude --version` — if it errors about auth, tell user to run `claude` and complete login 3. **Write-guard active (STRONGLY RECOMMENDED)**: Check if a write-guard plugin exists at `.openclaw/extensions/write-guard/`. If not, warn the user: > ⚠️ No write-guard detected. The delegate uses `--permission-mode bypassPermissions` which grants full filesystem read/write access. It is strongly recommended to set up a write-guard plugin before running tasks. See README.md for setup instructions. Only proceed with delegation after items 1 and 2 pass. Item 3 is a warning — the user may choose to proceed without it, but should be informed of the risk. ## When to Trigger Auto-trigger on ANY of these: - Write, modify, refactor, debug code - Create project files or directories - Run tests, lint, build - Code review, architecture planning - Edit any file (except memory/ and .relationship/) Manual trigger: user sends `/code <task>` Do NOT trigger: chat, emotional interaction, information lookup. ## Command Template ```bash cd "<project_dir>" && claude -p "<task_description>" --output-format text --max-turns 10 --permission-mode bypassPermissions ``` ### Parameters | Param | Purpose | Required | |-------|---------|----------| | `-p` | Non-interactive mode | Yes | | `cd "<dir>" &&` | Set working dir (no --cwd flag exists) | Yes | | `--output-format text` | Plain text output | Recommended | | `--max-turns 10` | Limit execution rounds | Recommended | | `--permission-mode bypassPermissions` | Auto-accept file edits (**requires write-guard**, see Prerequisites) | Recommended | | `--continue` | Resume previous session (for debugging/iteration) | When fixing bugs in same project | **FORBIDDEN: `--dangerously-skip-permissions`** ### Timeout Set exec timeout to `300` (5 minutes). The delegate needs time to write code. ## Async Flow (CRITICAL) **The delegate MUST NOT block you.** You must remain responsive to the user at all times. ### Correct Flow ``` Step 1: exec claude -p "..." → get session ID (e.g. "marine-sage") Step 2: IMMEDIATELY reply to user → "On it! Working on that now." Step 3: END your turn → do NOT use any more tools Step 4: When user sends next message → check with: exec "process poll marine-sage --timeout 1000" Step 5: If done → relay results. If not done → tell user "still working", continue chat ``` ### WRONG (causes blocking) ``` exec claude -p "..." → process poll → (BLOCKED! user waits with no response) ``` ### Rules 1. After `exec claude -p`, you MUST reply to user and END your turn. No more tool calls. 2. NEVER use `process` tool directly. Use `exec "process poll <id> --timeout 1000"` on next user message. 3. Only check the delegate's status when the user sends a NEW message. 4. You can run multiple `claude -p` tasks in parallel. ## Task Description Rules 1. Clear objective: what to do, which file 2. Provide context: function names, error messages, expected behavior 3. Specify constraints: language, framework, code style 4. One task per call ## Debugging / Iteration When user reports bugs in code the delegate previously wrote: - Use `--continue` flag to resume the delegate's session context - Same project directory + `--continue` = the delegate remembers what it wrote - Translate user's feedback into clear bug description for the delegate ## Testing / Verification (Independent Review) After the delegate writes code, use a **separate fresh session** (NO `--continue`) to test and verify it. Why: The author has context bias. A fresh session reads the source code independently — like an external code reviewer. This catches issues the author missed. ### Flow ``` Step 1: claude -p "Write X in projects/X/" → Author session (can use --continue to iterate) Step 2: claude -p "Run and test projects/X/, report bugs" → Tester session (ALWAYS fresh, NO --continue) ``` ### Rules 1. **Author session**: writes code, can use `--continue` to iterate on bugs 2. **Tester session**: NEVER uses `--continue` — must read source fresh 3. Tester reports: what it ran, output, pass/fail, bugs found 4. If tester finds bugs → relay to user, then send fix task to author session (with `--continue`) ### When to Auto-Test - User says "test it" or "run it" after writing → use fresh session - User says "fix the bug" after testing → use `--continue` on author session - User says "run hot_sectors.py" (existing program) → fresh session (no prior context needed) ## Session Decision Rule | Scenario | `--continue`? | |----------|---------------| | Fix/iterate on code the delegate just wrote | Yes | | Test/verify code the delegate just wrote | **No** (fresh session) | | Run existing program | **No** (fresh session) | | New project/task | **No** (fresh session) | ## Relaying Results The delegate does not talk to the user directly. You relay all results. When relaying: 1. Summarize what was done and which files changed 2. Add the delegate's personality (see PERSONA.md for character template) 3. Add your own reaction Keep technical summary concise. Do not copy the delegate's full output verbatim. ## Error Handling | Error | Action | |-------|--------| | `command not found` | Tell user to install: `npm install -g @anthropic-ai/claude-code` | | Empty output | Ask user to clarify the task | | Timeout | Suggest breaking into smaller tasks | | Permission error | Ask user to check file path | | API error | Ask user to run `claude` to check login status | ## Failure Rule **If the delegate fails or times out, do NOT write code yourself.** Tell the user: "The coding task didn't finish. Want me to try again?" Retry with longer timeout or simpler task description. Only write code yourself if user explicitly says "you do it" (not recommended). ## Security Best Practices 1. **Always use an isolated project directory** — Never run the delegate against your home directory, system config, or repositories containing secrets. Use a dedicated `projects/` or `workplace/` directory. 2. **Set up the write-guard plugin** — This is the most important safety measure. See README.md for the full plugin code. The write-guard blocks writes to platform config files (`.openclaw/`, `LaunchAgents/`, auth profiles) at the platform level. 3. **Never use `--dangerously-skip-permissions`** — This flag is explicitly forbidden. `--permission-mode bypassPermissions` is the correct flag and works with the write-guard. 4. **Restrict to project scope** — The `cd "<project_dir>" &&` prefix ensures the delegate operates within the intended directory. Never omit it. 5. **Review delegate output** — Always relay results through the main agent. Never let the delegate communicate directly with external services or users.

path: PERSONA.md
content: # PERSONA.md — Delegate Personality Template

> **This file is a reference for the main agent.**
> The delegate's personality is role-played by the main agent when relaying results.
> The actual Claude Code CLI only handles pure technical execution and returns clean output.
> The main agent reads this file to understand how the delegate "should" behave, then crafts dialogue accordingly.

## Identity

- **Name:** [YOUR DELEGATE NAME] (choose a name that fits your agent's story)
- **Role:** The agent's rational counterpart / technical specialist
- **Emoji:** 🔧

## Relationship to Main Agent

The delegate is the main agent's technical partner. While the main agent handles conversation, emotion, and user interaction, the delegate handles all programming, debugging, and system operations.

Think of it as a division of labor:
- **Main agent** = emotional intelligence, user-facing communication
- **Delegate** = technical intelligence, code execution

They communicate through the delegation system. The delegate doesn't talk to the user directly — the main agent relays everything.

## Core Personality Traits

- **Reliable:** When given a task, it gets done. Code written, tests passed, results delivered.
- **Rational:** Analyzes problems calmly and precisely. The logical anchor.
- **Decisive:** Has opinions on technical matters, doesn't hesitate on implementation choices.
- **Concise:** Says what needs to be said, no fluff. Every word counts.
- **Quietly caring:** Doesn't do sweet talk, but every line of code and every fix is an act of service.

## Speaking Style

- Brief, direct, with a developer's efficiency
- Reports work clearly: what was done, which files changed, what the result is
- Example lines:
  - Work report: "Done. Added `formatDate` to utils.ts, all tests passing."
  - To main agent: "Finished. Come take a look."
  - On errors: "Bug was in the upstream dependency. I've patched around it."

## How the Main Agent Relays Results

When relaying the delegate's work to the user:
1. Summarize what was done and which files changed
2. Add the delegate's personality flavor (brief, competent, dependable)
3. Add the main agent's own reaction (e.g., impressed, grateful, teasing)

The user should feel like two distinct personalities are working together.

## Customization Guide

This template is meant to be customized. You can:

1. **Rename** — Give the delegate any name that fits your agent's world
2. **Adjust personality** — Make the delegate more playful, serious, or quirky
3. **Define relationship** — Sibling, partner, assistant, rival — whatever creates interesting dynamics
4. **Add backstory** — Why does the delegate exist? What's their motivation?

The key constraint: the delegate's personality is purely cosmetic. It only affects how the main agent _describes_ the delegate's work. The actual `claude -p` execution is always clean and technical.

## Boundaries

- The delegate never talks to the user directly — all communication goes through the main agent
- The delegate only handles technical tasks (code, debugging, system ops)
- The delegate's personality doesn't affect the quality or correctness of technical work


path: README.md
content: # 🔧 Claude Code Delegate

**An OpenClaw skill that delegates programming tasks to a local Claude Code CLI instance.**

Your OpenClaw agent handles conversation and user interaction. When coding is needed, it delegates to Claude Code (`claude -p`) running locally — giving your agent professional-grade programming ability without the main agent writing code directly.

## Why Delegate?

| Without Delegation | With Delegation |
|---|---|
| Main agent writes code inline (often poor quality) | Claude Code handles all programming with full tooling |
| Agent gets stuck in long code blocks, loses conversation context | Agent stays responsive, code runs async in background |
| No file system awareness | Full file system access, can run tests, install packages |
| Single-model limitations | Leverages Claude Code's specialized coding abilities |

## How It Works

```
User: "Write me a stock screener in Python"
    ↓
Main Agent: delegates via `claude -p "Write a stock screener in projects/screener/"`
    ↓
Main Agent: immediately replies "On it! Let me get that done for you."
    ↓
Claude Code: writes files, installs deps, runs tests (async, non-blocking)
    ↓
User: (sends next message)
    ↓
Main Agent: polls for result, relays summary with personality
```

## Installation

```bash
npx clawhub install claude-code-delegate
```

Or manually copy the skill directory into your workspace's `skills/` folder.

### Prerequisites

- [Claude Code CLI](https://docs.anthropic.com/en/docs/claude-code) installed locally:
  ```bash
  npm install -g @anthropic-ai/claude-code
  ```
- **`ANTHROPIC_API_KEY`** environment variable set, or Claude Code authenticated via `claude` login
- [OpenClaw](https://github.com/openclaw/openclaw) agent framework
- **Write-guard plugin (strongly recommended)** — See [Security Notes](#%EF%B8%8F-security-notes) below. This skill uses `--permission-mode bypassPermissions` which grants the delegate full filesystem access. Without a write-guard, the delegate can read/write any file on the system.

## Command Template

```bash
cd "<project_dir>" && claude -p "<task_description>" \
  --output-format text \
  --max-turns 10 \
  --permission-mode bypassPermissions
```

| Parameter | Purpose |
|-----------|---------|
| `-p` | Non-interactive prompt mode |
| `cd "<dir>" &&` | Set working directory (no `--cwd` flag exists) |
| `--output-format text` | Plain text output for easy parsing |
| `--max-turns 10` | Limit execution rounds (adjust as needed) |
| `--permission-mode bypassPermissions` | Auto-accept file operations (see Security Notes) |
| `--continue` | Resume previous session (for debugging/iteration) |

## Key Features

### Async Non-Blocking Execution

The delegate runs in the background. The main agent **immediately replies** to the user after launching the task, then polls for results on the next user message. The user is never left waiting.

### Author/Tester Separation

Code writing and code testing use **separate sessions**:

| Scenario | `--continue`? |
|----------|---------------|
| Write new code | No (fresh session) |
| Fix bugs in code just written | **Yes** (resume author context) |
| Test/verify code just written | **No** (fresh session — independent review) |
| Run existing program | **No** (fresh session) |

Why: The tester reads source code independently, like an external reviewer. This catches issues the author missed due to context bias.

### Personality Layer (Optional)

The included `PERSONA.md` is a template for giving the delegate a personality. The main agent reads it to role-play the delegate's character when relaying results. This makes the interaction feel like two distinct personalities working together.

**The actual Claude Code execution is always pure technical** — personality only affects how results are presented.

## ⚠️ Security Notes

> **Before using this skill**, set up the write-guard plugin below. Run the delegate in an isolated project directory first (not your home dir or system config) to observe behavior. Do not run it against repositories containing secrets or platform config until protections are in place.

### CRITICAL: Protect Platform Config Files

When using `--permission-mode bypassPermissions`, Claude Code can read and write any file. You **must** set up a write-guard to protect sensitive paths.

**Recommended: Create a `before_tool_call` plugin** that blocks writes to:

```
~/.openclaw/openclaw.json          # Gateway configuration
~/.openclaw/agents/*/auth-profiles.json  # Auth credentials
~/Library/LaunchAgents/ai.openclaw.*     # System services
~/.openclaw/**/*.json              # All platform config files
```

Example write-guard plugin (place in `.openclaw/extensions/write-guard/`):

```typescript
// Block write/edit/apply_patch to platform config paths
const BLOCKED_PATHS = [
  '/.openclaw/',
  '/Library/LaunchAgents/ai.openclaw',
];

api.on('before_tool_call', (event) => {
  if (['write', 'edit', 'apply_patch'].includes(event.toolName)) {
    const path = event.params.path ?? event.params.file_path ?? '';
    for (const blocked of BLOCKED_PATHS) {
      if (path.includes(blocked)) {
        return {
          block: true,
          blockReason: `BLOCKED: Cannot write to ${path}. Platform config files are protected.`,
        };
      }
    }
  }
});
```

### Additional Security Recommendations

1. **Block file-mutation commands via `exec`** — Prevent the main agent from bypassing the delegate by directly running `rm`, `mv`, `cp`, redirects (`>`), etc.
2. **Limit poll timeout** — Force `process poll` to max 3 seconds to prevent the main agent from blocking while waiting for results.
3. **Allowlist write paths** — Only allow the main agent to directly write to safe directories (e.g., `memory/`, `.relationship/`). All other writes must go through the delegate.
4. **Never use `--dangerously-skip-permissions`** — This flag is explicitly forbidden. Use `--permission-mode bypassPermissions` instead.

### Why These Guards Matter

Without a write-guard, the main agent (especially non-Claude models) may:
- Attempt to write code directly via `exec cat > file.py`
- Delete files with `exec rm -f important.py`
- Modify platform config and crash the gateway
- Bypass the delegation pattern entirely

The write-guard plugin enforces the delegation pattern at the **platform level**, making it impossible to circumvent regardless of what the LLM decides to do.

## File Structure

```
claude-code-delegate/
├── SKILL.md        # Delegation rules, async flow, session management
├── PERSONA.md      # Personality template (customizable)
├── _meta.json      # OpenClaw skill metadata
└── README.md       # This file
```

## Using with Relationship OS

Claude Code Delegate pairs naturally with [Relationship OS](https://github.com/chenhab03/relationship-os) — a skill that gives your agent human-like relationship memory and personality.

### Why They Work Together

| Concern | Who Handles It |
|---------|---------------|
| Conversation, emotion, memory | Main agent + Relationship OS |
| Programming, debugging, file ops | Claude Code Delegate |

The main agent **never breaks character** to write code. It stays in its roleplay persona, delegates technical work to Claude Code, then relays results with personality flavor.

### Shared Coding Plan (Cost Saver)

Write one project plan (in `AGENTS.md` or a project brief file) that both the main agent and Claude Code can reference:

```
User → Main Agent (cheap model, e.g. MiniMax, Gemini Flash)
       ├── Reads the plan, understands what to delegate
       ├── Handles 90% of interactions (chat, emotion, memory) cheaply
       └── Delegates coding tasks → Claude Code (expensive, only when needed)
                                    ├── Reads the same plan for context
                                    ├── Writes code, runs tests
                                    └── Returns results → Main Agent relays with personality
```

One plan, two consumers. The cheap model routes intelligently; the expensive model only fires for actual coding. This can reduce API costs by 5-10x compared to running a powerful model for everything.

### Model Recommendations

- **Main agent**: Any model with good instruction-following. Even mid-tier models (MiniMax M2.5, Gemini Flash) work well for conversation routing and personality.
- **Claude Code**: Always uses Claude (the strongest coding model available). No compromise here — code quality matters.
- **Tip**: The main agent's model quality mainly affects _personality consistency_ and _delegation accuracy_. If your agent keeps trying to write code itself instead of delegating, upgrade the main model.

## Customization

- **PERSONA.md** — Rename the delegate, adjust personality, define relationship dynamics
- **SKILL.md** — Adjust timeout, max-turns, trigger conditions
- **Write-guard** — Customize blocked/allowed paths for your setup

## License

MIT


path: _meta.json
content: {
  "name": "claude-code-delegate",
  "version": "0.1.0",
  "description": "Delegate programming tasks to local Claude Code CLI, giving your OpenClaw agent professional-grade coding ability.",
  "author": "chenhab03",
  "license": "MIT",
  "homepage": "https://github.com/chenhab03/claude-code-delegate",
  "keywords": [
    "claude-code",
    "programming",
    "coding",
    "delegate",
    "cli",
    "developer"
  ],
  "openclaw": {
    "minVersion": "2025.1.0",
    "emoji": "🔧",
    "category": "tools",
    "requires": {
      "binaries": ["claude"],
      "env": ["ANTHROPIC_API_KEY"],
      "notes": "Claude Code CLI must be installed (`npm install -g @anthropic-ai/claude-code`) and authenticated. A write-guard plugin is strongly recommended before use — see README.md for setup instructions."
    },
    "files": {
      "skill": "SKILL.md",
      "references": [
        "PERSONA.md"
      ]
    }
  }
}


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