# Sub-Agent Delegation

cicaddy-action v0.5.0+ supports AI-powered sub-agent delegation via cicaddy>=0.8.0. Instead of a single AI pass, the framework uses a triage AI to select specialized sub-agents that run in parallel.

## How It Works

1. **Triage** — An AI call analyzes the PR diff and context, then selects which sub-agents to activate from the registry
2. **Parallel Execution** — Selected sub-agents run concurrently with focused prompts, filtered tools, and divided token budgets
3. **Aggregation** — Results are merged into a unified PR comment with per-agent sections

Sub-agents share the parent's MCP connections and tool registry. Side-effect tools (posting PR comments, submitting reviews, etc.) are blocked via the `cicaddy.delegation_blocked_tools` entry point.

## Quick Start

### GitHub Actions

Add `delegation_mode` and `max_sub_agents` inputs:

```yaml
- uses: redhat-community-ai-tools/cicaddy-action@main
  with:
    ai_provider: gemini
    ai_model: gemini-3-flash-preview
    ai_api_key: ${{ secrets.AI_API_KEY }}
    task_file: tasks/pr_review.yml
    post_pr_comment: 'true'
    delegation_mode: 'auto'
    max_sub_agents: '3'
```

### Running Locally

```bash
# Add to your .env file:
DELEGATION_MODE=auto
MAX_SUB_AGENTS=3

# Or use CLI flags:
uv run cicaddy run --env-file .env.my-review --delegation-mode auto --max-sub-agents 2
```

## Configuration

| Variable / Input | Default | Description |
|-----------------|---------|-------------|
| `DELEGATION_MODE` / `delegation_mode` | `none` | `none` (single-agent) or `auto` (AI-powered delegation) |
| `MAX_SUB_AGENTS` / `max_sub_agents` | `3` | Maximum concurrent sub-agents (1-10) |
| `SUB_AGENT_MAX_ITERS` | `10` | Max inference iterations per sub-agent (1-15, env var only) |
| `DELEGATION_AGENTS_DIR` | `.agents/delegation` | Directory for user-defined sub-agent YAML files (env var only) |
| `DELEGATION_AGENTS` | (empty) | JSON config for inline custom sub-agent definitions (env var only) |
| `TRIAGE_PROMPT` | (empty) | Optional custom instructions for the triage AI (env var only) |

### CLI Flags

```bash
cicaddy run --env-file .env --delegation-mode auto --max-sub-agents 2
```

These override the corresponding environment variables.

## Built-in Sub-Agents

### Review Agents

Activated automatically for PR code review (`github_pr` agent type):

| Agent | Focus Areas |
|-------|-------------|
| `security-reviewer` | Auth, crypto, secrets, injection, access control |
| `architecture-reviewer` | Design patterns, module boundaries, interfaces |
| `api-reviewer` | Endpoints, schemas, versioning, backward compat |
| `database-reviewer` | Queries, migrations, schema changes, indexes |
| `ui-reviewer` | Frontend components, accessibility, UX |
| `devops-reviewer` | CI/CD pipelines, Docker, deployment configs |
| `performance-reviewer` | Algorithms, caching, concurrency, resource usage |
| `general-reviewer` | Catch-all for anything not covered above |

### Task Agents

Activated for scheduled jobs (`github_task` agent type):

| Agent | Focus Areas |
|-------|-------------|
| `data-analyst` | Data processing, statistics, pattern recognition |
| `report-writer` | Report generation, formatting, documentation |
| `general-task` | General-purpose catch-all |

## Custom Sub-Agents

### YAML Files

Place YAML files in `.agents/delegation/review/` (or `task/`) in your repository:

```yaml
# .agents/delegation/review/compliance-reviewer.yaml
name: compliance-reviewer
agent_type: review
persona: compliance engineer specializing in regulatory requirements
description: Reviews changes for regulatory and compliance impact
categories: [security, configuration]
constraints:
  - Focus on regulatory compliance (SOC2, GDPR, HIPAA)
  - Flag any PII handling changes
  - Check audit logging requirements
output_sections:
  - Compliance Impact
  - Regulatory Risks
  - Required Controls
priority: 15
```

### JSON Inline

Define agents via the `DELEGATION_AGENTS` environment variable:

```bash
DELEGATION_AGENTS='[{"name": "compliance-reviewer", "agent_type": "review", "persona": "compliance engineer", "description": "Reviews compliance impact", "categories": ["security"]}]'
```

### Merge Precedence

1. Built-in agents (lowest priority)
2. User YAML files from `DELEGATION_AGENTS_DIR`
3. `DELEGATION_AGENTS` JSON overrides (highest priority)

User-defined agents with the same name as a built-in agent replace it.

## Tool Filtering

Sub-agents receive a filtered subset of the parent's tools:

1. **Base blocked**: `delegate_task` (prevents recursive delegation)
2. **Plugin blocked**: cicaddy-action registers write and side-effect operations (posting comments, submitting reviews, merging PRs, managing labels, sending Slack notifications, etc.)
3. **Per-agent**: `SubAgentSpec.allowed_tools` (strict whitelist) and `blocked_tools` (additional blocks)

## PR Comment Output

When delegation is active, the PR comment includes a collapsible details block:

```markdown
<details><summary>Delegation details: 2 agent(s) succeeded (8.3s)</summary>

Agents: security-reviewer, general-reviewer

- **security-reviewer**: PR modifies authentication middleware
- **general-reviewer**: General code quality review

</details>
```

If any agents fail, the summary shows: `2 agent(s) succeeded, 1 failed (12.4s)`.

## DSPy Task Files + Delegation

When using `task_file` with `delegation_mode: auto`, the task definition is provided to the triage agent as context for task-aware sub-agent selection. The task's `forbidden_tools` cascade to all sub-agents.

## Cost Considerations

Delegation multiplies AI inference calls. With defaults (`MAX_SUB_AGENTS=3`, `SUB_AGENT_MAX_ITERS=10`), a single PR review can use up to 1 (triage) + 3×10 (sub-agents) + 1 (aggregation) = **32 AI calls** versus 1-15 for single-agent mode. Tune `MAX_SUB_AGENTS` and `SUB_AGENT_MAX_ITERS` based on your AI provider tier and rate limits.

## Troubleshooting

- **Disable delegation**: Set `DELEGATION_MODE` to `none` — no redeployment needed
- **Sub-agent failures**: If sub-agents fail, the parent agent still posts a comment with results from successful agents. Failed agent count is shown in the delegation details block
- **Rate limits**: With `MAX_SUB_AGENTS` concurrent API calls, shared API keys may hit RPM limits. Reduce `MAX_SUB_AGENTS` if you see rate-limit errors

See cicaddy's [sub-agent delegation docs](https://github.com/waynesun09/cicaddy/blob/main/docs/sub-agent-delegation.md) for the full specification.
