Claude Code Agent Skill
Operate Claude Code as a managed coding agent — from worktree setup through PR merge.
Prerequisites
CODEBLOCK0
CLI Quick Reference
| Flag | Effect |
|---|
| INLINECODE0 | Non-interactive one-shot, exits when done |
| INLINECODE1 |
Skip all permission prompts (safe in containers/VMs) |
|
--permission-mode acceptEdits | Auto-accept file edits, still prompt for shell commands |
|
--permission-mode plan | Read-only analysis, no modifications |
|
--model <model> | Model selection (e.g.
claude-sonnet-4-6) |
|
--allowedTools "Bash,Read,Write,Edit" | Restrict available tools |
|
--disallowedTools "Bash,Write" | Block specific tools |
|
--append-system-prompt "..." | Add custom instructions to system prompt |
|
--output-format json | Structured JSON output with cost/duration metadata |
|
--output-format stream-json | Streaming JSON (each message as it arrives) |
|
--continue /
-c | Continue most recent conversation |
|
--resume <id> /
-r <id> | Resume specific session by ID |
|
--mcp-config <file> | Load MCP server configuration |
|
--verbose | Enable verbose debug logging |
Execution Modes
Quick Mode — Small Tasks
For trivial fixes, one-file changes, or analysis. Use -p (non-interactive).
Output capture: Always redirect output to a log file so it's readable regardless
of PTY availability. Use --output-format stream-json for structured, parseable
progress events (each message arrives as a separate JSON line).
CODEBLOCK1
PTY fallback: If pty=true is unavailable (some containers, CI runners), the
command still works because -p mode is non-interactive — it doesn't rely on
isatty(stdout). The 2>&1 | tee ensures both stdout and stderr are captured
to the log file regardless of PTY status. Without PTY, you lose color output
but all content is preserved.
Adaptive Timeout (Poll-and-Extend)
Do NOT use timeout= for claude tasks. Instead, use background execution
with periodic polling. This prevents premature kills on long-running tasks:
- 1. Launch with
background=true (no timeout) - Poll every ~5 min with INLINECODE26
- If process is still running → check log file for new output
- If process exited → check exit code and log file, done
- Safety net: if no new output for 12 hours, ask user before killing
- Safety net: if output is repeating (loop detection), ask user
Persistent polling state: Store polling metadata in the task registry so a
restarted orchestrator agent can resume monitoring without losing state:
CODEBLOCK2
CODEBLOCK3
This way tasks that need 5 min or several hours both work without premature kills.
Full Mode — Features, Bugfixes, Refactors
For non-trivial tasks, use the full workflow below. This gives you:
- - Isolated worktree — no conflicts with other work
- tmux session — mid-task steering without killing the agent
- Task tracking — know what's running at all times
- Quality gates — Definition of Done checklist
- Smart retries — don't waste tokens on repeated failures
Full Workflow: Task → Merged PR
Step 1: Create Worktree
Isolate each task in its own worktree and branch:
CODEBLOCK4
Step 2: Launch Agent in tmux
Start Claude Code in interactive mode (no -p) so you can steer mid-task.
Important: Use tmux pipe-pane to log output — do NOT use | tee because it
turns stdout into a pipe, which breaks interactive mode (claude detects !isatty(stdout)
and may disable interactive features, breaking send-keys steering).
Critical: Set up pipe-pane BEFORE sending the command. Otherwise early output
(startup messages, fast crashes) is lost.
CODEBLOCK5
Log file management: For very long-running tasks, the log file can grow large.
Monitor its size and rotate if needed:
CODEBLOCK6
Why interactive mode (no -p)?
- - Allows mid-task steering via INLINECODE34
- Agent can be redirected without killing and restarting
- INLINECODE35 is safe in container/sandbox environments
Note on stdout/stderr: In tmux, both stdout and stderr from the process flow
through the PTY and are captured by pipe-pane. They are mixed together — you
cannot separate them after capture. For error diagnosis, grep for keywords like
error, fail, panic in the clean (ANSI-stripped) log file.
Step 3: Register Task
Track all active tasks in a JSON registry. Use flock for atomic updates to
prevent race conditions when multiple agents run in parallel.
CODEBLOCK7
Step 4: Monitor & Steer
CODEBLOCK8
Monitoring cadence: Check every 5-10 minutes, not every 30 seconds. Agents need time to work.
Step 5: Definition of Done
A PR is NOT ready for review until all checks pass:
CODEBLOCK9
Quick inline check:
CODEBLOCK10
Step 6: Multi-Model Code Review
Review with a different model than the one that wrote the code. Different models catch different issues:
CODEBLOCK11
Post review results to PR:
CODEBLOCK12
Update task registry:
CODEBLOCK13
Step 7: Notify
If you included the notify command in the agent prompt (Step 2), the agent self-notifies on completion.
Otherwise, notify after DoD passes:
CODEBLOCK14
Update task status:
CODEBLOCK15
Step 8: Cleanup
After PR is merged:
git worktree remove "$WORKTREE" 2>/dev/null
git branch -d "$BRANCH" 2>/dev/null
# Remove from registry
(
flock -x 200
jq --arg id "$TASK_ID" '.tasks = [.tasks[] | select(.id != $id)]' \
"$TASKS_FILE" > /tmp/tasks.$$.json && mv /tmp/tasks.$$.json "$TASKS_FILE"
) 200>"$TASKS_FILE.lock"
Smart Retry Strategy
When an agent fails, analyze the failure and adapt the prompt — don't just re-run blindly.
| Failure Type | Symptom | Retry Strategy |
|---|
| Context overflow | Agent loops, produces garbage, or stops mid-task | Narrow scope: "Focus only on files X, Y, Z" |
| Wrong direction |
Agent implements something unrelated to intent | Correct intent:
"Stop. Customer wanted X, not Y. Spec: ..." |
| Missing info | Agent makes wrong assumptions about architecture | Add context:
"Auth uses JWT, see src/auth/jwt.ts" |
| CI failure | Tests, lint, or typecheck fail after PR | Attach CI log:
"Fix these test failures: ..." |
| Build failure | Dependencies missing or incompatible | Pre-install deps before retry |
Max 3 retries. After that, escalate to human.
CODEBLOCK17
Parallel Execution
Run multiple agents simultaneously on different tasks.
Important: Always set up pipe-pane before sending the command to avoid losing
early output. Use ANSI stripping for clean logs.
CODEBLOCK18
Multi-Turn Conversations
For complex tasks that need iterative refinement:
CODEBLOCK19
Best Practices
Prompt Quality
- - Include file paths: "The entry point is src/index.ts, config in src/config/"
- Include schemas/types: Paste relevant type definitions into the prompt
- Include test commands: "Verify with: npm test -- --grep auth"
- Include commit convention: "Use conventional commits: feat:, fix:, chore:"
- Include error logs: When retrying, always attach the failure output
Scope Management
- - One task per agent — don't ask for "refactor everything"
- Pre-install dependencies before launching the agent
- Be specific — "Add rate limiting to POST /api/users" not "improve the API"
When to Interrupt (Ask Human)
- - Destructive operations (drop tables, force push main)
- Security decisions (expose credentials, change auth)
- Ambiguous requirements with significant trade-offs
- All other decisions: proceed autonomously
Examples
See references/examples.md for additional usage scenarios.