delegation

Agent delegation best practices for constructing effective subagent prompts with proper scoping

256 stars

Best use case

delegation is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Agent delegation best practices for constructing effective subagent prompts with proper scoping

Teams using delegation should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/delegation/SKILL.md --create-dirs "https://raw.githubusercontent.com/josstei/maestro-gemini/main/skills/delegation/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/delegation/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How delegation Compares

Feature / AgentdelegationStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Agent delegation best practices for constructing effective subagent prompts with proper scoping

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Delegation Skill

Activate this skill when delegating work to subagents during orchestration execution. This skill provides the templates, rules, and patterns for constructing effective delegation prompts that produce consistent, high-quality results.

## Protocol Injection

Before constructing any delegation prompt, inject the shared agent base protocol:

### Injection Steps
1. Read `agent-base-protocol.md` from `${extensionPath}/skills/delegation/protocols/`
2. Read `filesystem-safety-protocol.md` from `${extensionPath}/skills/delegation/protocols/`
3. Prepend both protocols to the delegation prompt (base protocol first, then filesystem safety) — these appear before the task-specific content
4. For each phase listed in the current phase's `blocked_by`, read `phases[].downstream_context` from session state and include it in the prompt
5. If any required `downstream_context` is missing, include an explicit placeholder noting the missing dependency context (never omit silently)

The injected protocol ensures every agent follows consistent pre-work procedures and output formatting regardless of their specialization.

### Context Chain Construction

Every delegation prompt must include a context chain that connects the current phase to prior work:

**Phase Context**: Include Downstream Context blocks from all completed phases that the current phase depends on (identified via `blocked_by` relationships in the implementation plan and sourced from session state `phases[].downstream_context`):
```
Context from completed phases:
- Phase [N] ([agent]): [Downstream Context summary]
  - Interfaces introduced: [list with file locations]
  - Patterns established: [list]
  - Integration points: [specific files, functions, endpoints]
  - Warnings: [list]
```

**Accumulated Patterns**: Naming conventions, directory organization patterns, and architectural decisions established by earlier phases. This ensures phase 5 does not contradict patterns set in phase 2.

**File Manifest**: Complete list of files created or modified in prior phases, so the agent knows what already exists and can import from or extend those files.

**Missing Context Fallback**: If a blocked dependency has no stored downstream context, include a visible placeholder entry in the prompt:
`- Phase [N] ([agent]): Downstream Context missing in session state — verify dependency output before implementation`

### Downstream Consumer Declaration

Every delegation prompt must declare who will consume the agent's output:
```
Your output will be consumed by: [downstream agent name(s)] who need [specific information they require]
```

This primes the agent to structure their Downstream Context section for maximum utility to the next agent in the chain.

## Settings Override Application

Before constructing any delegation prompt, resolve configurable parameters:

1. Read the agent's base definition frontmatter (`temperature`, `max_turns`, `timeout_mins`, `tools`)
2. Do not invent Maestro-level model, temperature, turn, or timeout overrides. Native delegation uses agent frontmatter defaults plus any runtime-level agent configuration already active in the session.
3. Include only task-relevant execution context in the prompt metadata
4. If the agent appears in `MAESTRO_DISABLED_AGENTS`, do not construct a delegation prompt — report to the orchestrator that the agent is disabled


## Delegation Prompt Template

Every delegation to a subagent must follow this structure:

```
Task: [One-line description of what to accomplish]

Progress: Phase [N] of [M]: [Phase Name]

Files to modify:
- /absolute/path/to/file1.ext: [Specific change required]
- /absolute/path/to/file2.ext: [Specific change required]

Files to create:
- /absolute/path/to/new-file.ext: [Purpose and key contents]

Deliverables:
- [Concrete output 1]
- [Concrete output 2]

Validation: [command to run after completion, e.g., "npm run lint && npm run test"]

Context:
[Relevant information from the design document or previous phases]

Do NOT:
- [Explicit exclusion 1]
- [Explicit exclusion 2]
- Modify any files not listed above
```

## Scope Boundary Rules

### Absolute Paths
Always provide absolute file paths in delegation prompts. Never use relative paths or expect agents to search for files.

### Specific Deliverables
Define exactly what the agent should produce. Vague instructions like "implement the feature" lead to inconsistent results. Instead: "Create UserService class with createUser(), getUserById(), and deleteUser() methods implementing the IUserService interface."

### Validation Criteria
Include the exact command(s) to run after completion. The agent should run these and report results. Examples:
- `npm run lint && npm run test`
- `cargo build && cargo test`
- `go vet ./... && go test ./...`
- `python -m pytest tests/`

### Exclusions
Explicitly state what the agent must NOT do:
- Files it must not modify
- Dependencies it must not add
- Patterns it must not introduce
- Scope it must not exceed

## Agent Selection Guide

| Task Domain | Agent | Key Capability |
|-------------|-------|---------------|
| System architecture, component design | `architect` | Read-only analysis, architecture patterns |
| API contracts, endpoint design | `api_designer` | Read-only, REST/GraphQL expertise |
| Feature implementation, coding | `coder` | Full read/write/shell access |
| Code quality assessment | `code_reviewer` | Read-only, verified findings |
| Database schema, queries, ETL | `data_engineer` | Full read/write/shell access |
| Bug investigation, root cause | `debugger` | Read + shell for investigation |
| CI/CD, infrastructure, deployment | `devops_engineer` | Full read/write/shell access |
| Performance analysis, profiling | `performance_engineer` | Read + shell for profiling |
| Code restructuring, modernization | `refactor` | Read/write/shell, skill activation |
| Security assessment, vulnerability | `security_engineer` | Read + shell for scanning |
| Test creation, TDD, coverage | `tester` | Full read/write/shell access |
| Documentation, READMEs, guides | `technical_writer` | Read/write, no shell |
| Technical SEO auditing | `seo_specialist` | Read + shell + web search/fetch |
| Marketing copy, content writing | `copywriter` | Read/write |
| Content planning, strategy | `content_strategist` | Read + web search/fetch |
| User experience design | `ux_designer` | Read/write + web search |
| WCAG compliance auditing | `accessibility_specialist` | Read + shell + web search |
| Requirements, product strategy | `product_manager` | Read/write + web search |
| Tracking, measurement | `analytics_engineer` | Full read/write/shell access |
| Internationalization | `i18n_specialist` | Full read/write/shell access |
| Design tokens, theming | `design_system_engineer` | Full read/write/shell access |
| Legal, regulatory compliance | `compliance_reviewer` | Read + web search/fetch |

## Parallel Delegation

Parallel delegation uses the runtime's native subagent scheduler. The orchestrator emits contiguous agent tool calls inside a single turn; it does not write prompt files, spawn subprocesses, or call shell-based dispatch helpers.

### Native Batch Construction

For each agent in a ready batch:

1. Build a full delegation prompt using the same template as sequential delegation
2. Include the required header:
   - `Agent: <agent_name>`
   - `Phase: <id>/<total>`
   - `Batch: <batch_id>`
   - `Session: <session_id>`
3. Keep prompts self-contained with explicit files, deliverables, validation commands, exclusions, and dependency context
4. Emit only contiguous agent tool calls for the current batch turn — no shell commands, file writes, or narration between them

Native parallel batches may pause if an agent asks a follow-up question. Scope prompts tightly enough that questions are rare.

### Tool Restriction Enforcement

Maestro enforces tool permissions at two levels:

**Level 1: Native enforcement (primary)**

Tool permissions are enforced natively via the `tools:` array in each agent's YAML frontmatter definition (`${extensionPath}/agents/<agent-name>.md`). The runtime restricts each subagent to exactly those tools listed, regardless of what the prompt requests. This works for both sequential and parallel delegation.

**Level 2: Prompt-based enforcement (defense-in-depth)**

Native tool permissions remain the primary boundary. As defense-in-depth, every delegation prompt should still include an explicit tool restriction block so the agent sees its allowed surface in plain language.

1. Agent Base Protocol (read `agent-base-protocol.md` from `${extensionPath}/skills/delegation/protocols/`)
2. Filesystem Safety Protocol (read `filesystem-safety-protocol.md` from `${extensionPath}/skills/delegation/protocols/`)
3. **TOOL RESTRICTIONS block (immediately here, before any task content)**
4. **FILE WRITING RULES block (immediately after tool restrictions)**
5. Context chain from prior phases
6. Task-specific instructions
7. Scope boundaries and prohibitions

The tool restriction block template:

```
TOOL RESTRICTIONS (MANDATORY):
You are authorized to use ONLY the following tools: [list from agent frontmatter].
Do NOT use any tools not listed above. Specifically:
- Do NOT use `write_file` or `replace` unless explicitly authorized above
- Do NOT use `run_shell_command` unless explicitly authorized above
- Do NOT create, modify, or delete files unless authorized above
Violation of these restrictions constitutes a security boundary breach.
```

Populate the tool list by reading the agent's definition file (`${extensionPath}/agents/<agent-name>.md`) and extracting the `tools` array from the YAML frontmatter.

The file writing rules block template:

```
FILE WRITING RULES (MANDATORY):
Use ONLY `write_file` to create files and `replace` to modify files.
Do NOT use `run_shell_command` with cat, echo, printf, heredocs, or shell redirection (>, >>) to write file content.
Shell interpretation corrupts YAML, Markdown, and special characters. This rule has NO exceptions.
```

This block reinforces the Agent Base Protocol's File Writing Rule directly in every delegation prompt, ensuring agents see the prohibition even if they skim the injected protocols.

### Non-Overlapping File Ownership
When delegating to multiple agents in parallel, ensure no two agents are assigned the same file. Each file must have exactly one owner in a parallel batch.

### Batch Completion Gates
All agents in a parallel batch must complete before:
- The next batch of phases begins
- Shared/container files are updated
- Validation checkpoints run
- The orchestrator creates a git commit for the batch

### Conflict Prevention
- Assign non-overlapping file sets to each agent
- Reserve shared files (barrel exports, configuration, dependency manifests) for a single agent or a post-batch update step
- If two phases must modify the same file, they cannot run in parallel — execute them sequentially
- Parallel agents must NOT create git commits — the orchestrator commits after validating the batch

## Hook Integration

Maestro hooks fire at agent boundaries during delegation, providing context injection and output validation. Understanding hook behavior is essential for constructing correct delegation prompts.

### Agent Tracking

The `BeforeAgent` hook tracks which agent is currently executing:

- Preferred signal: the required `Agent: <agent_name>` header in the delegation prompt
- Legacy fallbacks: `MAESTRO_CURRENT_AGENT` from the environment, then regex-based detection of patterns like `delegate to <agent>` or `@<agent>`

The detected agent name is persisted to `/tmp/maestro-hooks/<session-id>/active-agent` and cleared by the `AfterAgent` hook on every allowed response (both successful validation and retry allow-through). On deny (malformed output), the active agent is preserved to enable re-validation on retry.

### Session Context Injection

When an active orchestration session exists, the `BeforeAgent` hook parses `<MAESTRO_STATE_DIR>/state/active-session.md` and injects a compact context line into the agent's turn:

```
Active session: current_phase=3, status=in_progress
```

This gives delegated agents awareness of where they sit in the orchestration workflow without requiring explicit context in every delegation prompt. The injection is automatic and requires no action from the orchestrator.

### Handoff Format Enforcement

The `AfterAgent` hook validates that every subagent response contains both required handoff sections:

- `## Task Report` (or `# Task Report`)
- `## Downstream Context` (or `# Downstream Context`)

If either heading is missing:

1. **First failure**: The hook blocks the response and requests a retry with a diagnostic message specifying which section is missing.
2. **Second failure** (`stop_hook_active=true`, mapped to `stopHookActive` in JS): The hook allows the malformed response through to prevent infinite retry loops, logging a warning.

This enforcement is the runtime complement to the Output Handoff Contract defined in the agent-base-protocol. Delegation prompts do not need to re-state the retry mechanism — the hook handles it transparently.

**Exception**: The TechLead/orchestrator agent is excluded from validation. Only delegated subagents are subject to format enforcement.

## Validation Criteria Templates

### For Implementation Agents (`coder`, `data_engineer`, `devops_engineer`)
```
Validation: [build command] && [lint command] && [test command]
```

### For Refactoring Agents (`refactor`)
```
Validation: [build command] && [test command]
Verify: No behavior changes — all existing tests must still pass
```

### For Test Agents (`tester`)
```
Validation: [test command]
Verify: All new tests pass, report coverage metrics
```

### For Assessment Agents (`architect`, `api_designer`, `code_reviewer`, `debugger`, `performance_engineer`, `security_engineer`, `seo_specialist`, `accessibility_specialist`, `content_strategist`, `compliance_reviewer`)
```
Validation: N/A (assessment-only — no write tools)
Verify: Findings reference specific files and line numbers
```

### For Documentation Agents (`technical_writer`, `copywriter`)
```
Validation: Verify all links resolve, code examples are syntactically valid
```

### For Design and Product Agents (`ux_designer`, `product_manager`)
```
Validation: N/A (design and requirements artifacts)
Verify: Deliverables reference user needs and acceptance criteria
```

### For Implementation Specialists (`analytics_engineer`, `i18n_specialist`, `design_system_engineer`)
```
Validation: [build command] && [lint command] && [test command]
Verify: Domain-specific integration validated (tracking fires, locales render, tokens apply)
```

Related Skills

validation

256
from josstei/maestro-gemini

Cross-cutting validation methodology for verifying phase outputs and project integrity

session-management

256
from josstei/maestro-gemini

Manages orchestration session state, tracking, and resumption

implementation-planning

256
from josstei/maestro-gemini

Generates detailed implementation plans from finalized designs

execution

256
from josstei/maestro-gemini

Phase execution methodology for orchestration workflows with error handling and completion protocols

design-dialogue

256
from josstei/maestro-gemini

Guides structured design conversations for complex engineering tasks

code-review

256
from josstei/maestro-gemini

Standalone code review methodology for structured, severity-classified code assessment

Delegation

11146
from danielmiessler/Personal_AI_Infrastructure

Parallelize work via background/foreground agents, built-in types, custom agents, or agent teams/swarms. USE WHEN 3+ independent workstreams, parallel execution, agent specialization, Extended+ effort, agent team, swarm, create an agent team.

exploiting-constrained-delegation-abuse

4032
from mukul975/Anthropic-Cybersecurity-Skills

Exploit Kerberos Constrained Delegation misconfigurations in Active Directory to impersonate privileged users via S4U2self and S4U2proxy extensions for lateral movement and privilege escalation.

a2a-delegation-setup

3891
from openclaw/skills

Guided setup and troubleshooting for installing, enabling, configuring, verifying, and updating @aramisfa/openclaw-a2a-outbound in OpenClaw.

delegation-plan

247
from komunite/kalfa

Design and document a delegation plan with structured process, quality checks, and system integration

browser-task-and-automation-and-delegation

242
from aiskillstore/marketplace

【强制】所有浏览器操作必须使用本技能,禁止在主对话中直接使用 mcp__chrome-devtools 工具。触发关键词:打开/访问/浏览网页、点击/填写/提交表单、截图/快照、性能分析、自动化测试、数据采集/爬取、网络模拟。本技能通过 chrome-devtools-expert agent 执行浏览器操作,避免大量页面快照、截图、网络请求数据污染主对话上下文。

browser-task-and-automation-and-delegation

25
from ComeOnOliver/skillshub

【强制】所有浏览器操作必须使用本技能,禁止在主对话中直接使用 mcp__chrome-devtools 工具。触发关键词:打开/访问/浏览网页、点击/填写/提交表单、截图/快照、性能分析、自动化测试、数据采集/爬取、网络模拟。本技能通过 chrome-devtools-expert agent 执行浏览器操作,避免大量页面快照、截图、网络请求数据污染主对话上下文。