agentleFS
gradigitgradigit/claude-skills/.claude/skills/forge-claude-teams/SKILL.md

forge-claude-teams

Skill0 starsChanged 9 months agoMITView on GitHub

Codifies best practices for Claude Code multi-agent features: Agent tool, TeamCreate, SendMessage, task coordination. Reference guide for building effective agent teams with conflict prevention, error recovery, and progress observability. Do NOT use when working with Codex CLI — use forge-codex-multiagent instead.

The file

Show its rules and text

We split this skill into the rules it gives an agent

19 rules. About 0 are common, 15 are distinctive, and 4 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈15

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Rule: Never assign implementation work to read-only agent types.

    line 49
  2. Very specific:

    Never specify model: "haiku" or model: "sonnet" for workers.

    line 59
  3. Distinctive:

    Every sub-agent prompt must include these 5 components:

    line 63
  4. Distinctive:

    Prefer ID order when multiple tasks are available

    line 160
  5. Very specific:

    Never broadcast routine status: If only one teammate needs the info, use "message".

    line 172
  6. Very specific:

    Fallback: If isolation: "worktree" is not supported, instruct the sub-agent to call EnterWorktree as its first action:

    line 266
  7. Distinctive:

    After validation, the orchestrator merges worktree branches sequentially.

    line 278
  8. Distinctive:

    If two agents need to modify the same file, the decomposition is wrong.

    line 305
  9. Distinctive:

    When a sub-agent crashes, overflows context, or produces garbage:

    line 313
  10. Distinctive:

    Never retry the crashed agent instance

    line 330
  11. Distinctive:

    If sequential merge of worktree branches produces conflicts:

    line 336
  12. Distinctive:

    Wait for user resolution before continuing

    line 340
  13. Very specific:

    Update TODO.md after every significant step:

    line 362
  14. Distinctive:

    Before each significant action batch, emit a brief progress note:

    line 400
  15. Distinctive:

    Never run silently for 5+ minutes: If a cycle produces no observable output, write a progress note explaining what is happening and why.

    line 407
  16. Distinctive:

    Update this skill when:

    line 447
  17. Distinctive:

    New anti-pattern discovered: Add to anti-patterns table with fix

    line 449
  18. Distinctive:

    Concurrency limits change: Update parallelism table if rate limits or platform caps change

    line 450
  19. Distinctive:

    New isolation mechanism: If Claude Code adds native worktree parameters to Agent tool, update conflict prevention

    line 451

≈ “Common” is an estimate: at least 1 in 5 of the 372,429 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Forge Claude Teams

Best practices for Claude Code's multi-agent features. Reference guide — read sections as needed, not sequentially.

Agent Tool (Subagents)

When to Use Subagents vs Teams

Use CaseMechanismWhy
Independent task, clear input/outputAgent tool (subagent)No shared state needed, fire-and-collect
Coordinated multi-step workTeamCreate + teammatesShared task list, message passing, lifecycle
Quick read-only lookupAgent tool (Explore type)Lightweight, no tool overhead
Parallel builds with mergingTeam with worktree isolationConflict prevention requires coordination

Subagent Type Selection

Match subagent_type to the tools the agent needs. Wrong type = silent failures.

subagent_typeTools AvailableUse For
"general-purpose"All (Read, Write, Edit, Bash, Grep, Glob)Implementation, fixes, file creation
ExploreRead-only (Read, Grep, Glob, WebSearch)Research, codebase exploration, analysis
PlanRead-only + planning focusArchitecture decisions, approach design
Custom (.claude/agents/)Per agent definitionSpecialized workers with tool restrictions

Rule: Never assign implementation work to read-only agent types. An Explore agent that needs to edit a file will silently skip the edit.

Model Selection

ScenarioModelRationale
All worker agentsinherit (default)Consistency, no degradation
Explore subagentsPlatform default (acceptable)Read-only, lower stakes
Build workersinherit alwaysQuality-critical, must match lead

Never specify model: "haiku" or model: "sonnet" for workers. Let them inherit.

Context Handoff Template

Every sub-agent prompt must include these 5 components:

<task>
  Implement the authentication middleware for Express routes.
  Handle JWT validation, token refresh, and role-based access.
</task>

<context>
  Project uses Express 4 + TypeScript. Auth tokens are JWTs signed
  with RS256. Existing user model is in src/models/user.ts.
  Decision: we chose Passport.js over custom middleware (see ADR-003).
</context>

<scope>
FILE SCOPE:
  own: [src/middleware/auth.ts, src/middleware/roles.ts]
  read: [src/models/user.ts, src/config/auth.ts]
  deny: [src/routes/*, src/models/*]
</scope>

<boundaries>
  Do NOT modify routes, models, or config files.
  Another agent owns src/routes/ — do not touch.
</boundaries>

<output-contract>
  Files: src/middleware/auth.ts, src/middleware/roles.ts
  Tests: src/middleware/__tests__/auth.test.ts
  Signal: "AUTH_MIDDLEWARE_COMPLETE" when done
</output-contract>

For orchestrator-level sub-agents: The forge pipeline uses a 7-tag XML template (objective, context, output-format, tools, boundaries, quality-bar, task) for sub-agent spawn prompts. Sub-agent <boundaries> include a structured FILE SCOPE block (own/read/deny) for machine-parseable scope declarations. See sub-agent-template.md for the full template and role-specific contracts.

Parallelism Model

Parallelized serial threads — not pure fan-out.

Orchestrator
  ├── Thread A (auth module): research → implement → test → fix (serial)
  ├── Thread B (API routes):  research → implement → test → fix (serial)
  └── Thread C (database):    research → implement → test → fix (serial)
       ↑ parallel across threads, serial within each thread

Each thread owns a coherent work chunk and accumulates context as it progresses. Threads can spawn sub-agents for research/review within their scope.

Concurrency limits (Gunther's USL — coordination overhead scales N^2):

Agent TypeMax ParallelRationale
Build workers2-3File conflicts, merge complexity
Read-only reviewers3 per batchRate limits; batch as 3+2
Research queries3-5 per threadIndependent, no conflict risk

Background vs Foreground

ModeWhenExample
ForegroundResults needed before next stepCode review before merge
BackgroundIndependent, non-blocking workRunning test suite while building

Never poll background agents. Wait for the notification callback. Polling wastes tokens and can race.


Teams (TeamCreate / SendMessage / TaskList)

Full Lifecycle

1. TeamCreate          → creates team + shared task list
2. TaskCreate (×N)     → define all work items upfront
3. Agent tool (×N)     → spawn teammates (they join the team)
4. TaskUpdate          → assign tasks via `owner` parameter
5. [teammates work]    → claim tasks, implement, coordinate
6. SendMessage         → DMs for coordination, never broadcast routine
7. shutdown_request    → graceful shutdown per teammate
8. TeamDelete          → cleanup after all teammates confirmed shutdown

Task Ownership

# Assign a task to a teammate
TaskUpdate(taskId="3", owner="auth-builder")

# Teammates claim unassigned tasks in ID order
# (lowest ID first — earlier tasks set up context for later ones)
TaskUpdate(taskId="4", owner="my-name", status="in_progress")

Rules:

  • Assign via TaskUpdate with owner, not via messages
  • Teammates should check TaskList after completing each task
  • Prefer ID order when multiple tasks are available
  • Set status: "in_progress" when starting, "completed" when done

Communication

typeUse ForCost
"message"DMs to specific teammate (default)1 message
"broadcast"Critical announcements onlyN messages (1 per teammate)
"shutdown_request"Graceful termination1 message
"plan_approval_response"Approve/reject teammate plans1 message

Never broadcast routine status. If only one teammate needs the info, use "message".

# Good — targeted DM
SendMessage(type="message", recipient="auth-builder",
            content="Auth module ready for review",
            summary="Auth ready for review")

# Bad — broadcasting routine status
SendMessage(type="broadcast",
            content="I finished the auth module")  # Don't do this

Idle Handling

Teammates go idle after every turn. This is normal and expected.

ObservationMeaningAction
Teammate went idleTurn ended, waiting for inputSend message to wake if needed
Teammate idle after sending messageSent message, waiting for responseNormal — respond when ready
Teammate idle for extended periodNo work assigned or blockedCheck TaskList, assign work

Idle does NOT equal done. Send a message to wake an idle teammate.

Plan Mode

Spawn a teammate in plan mode when you want to approve their approach:

# Spawn with plan mode
Agent(name="architect", mode="plan", team_name="my-team", ...)

# When they submit a plan, approve or reject:
SendMessage(type="plan_approval_response", request_id="abc-123",
            recipient="architect", approve=True)

# Or reject with feedback:
SendMessage(type="plan_approval_response", request_id="abc-123",
            recipient="architect", approve=False,
            content="Add error handling for the API calls")

Shutdown Protocol

# 1. Request shutdown for each teammate
SendMessage(type="shutdown_request", recipient="auth-builder",
            content="All tasks complete, wrapping up")

# 2. Teammate responds (automatically via shutdown_response)
# 3. Wait for all approvals
# 4. Only then clean up
TeamDelete()  # Fails if active members remain

Never call TeamDelete before all teammates have confirmed shutdown.


Conflict Prevention

Conflict Prevention Pyramid

                ┌─────────────────────┐
                │  SAME FILE builds   │  ← DO NOT. Redesign or queue.
                │  (never parallel)   │
                ├─────────────────────┤
                │  DIFFERENT FILE     │  ← Worktrees + ownership scoping
                │  builds (parallel)  │
                ├─────────────────────┤
                │  Read-only / research│  ← Shared tree, safe by default
                │  (always parallel)  │
                └─────────────────────┘

Decision Table

Agents DoingIsolationSetup
Research / read-onlyNone neededShared working tree
Build on different filesWorktree per agentisolation: "worktree" or EnterWorktree + file ownership. Use Clash hook for real-time conflict detection if available
Build on same fileDO NOTRedesign decomposition or queue sequentially

Worktree Setup

Primary: Pass isolation: "worktree" in the Agent tool call to run the sub-agent in an isolated git worktree automatically:

Agent(name="auth-builder", subagent_type="general-purpose",
      isolation="worktree", prompt="...")

Fallback: If isolation: "worktree" is not supported, instruct the sub-agent to call EnterWorktree as its first action:

<boundaries>
  Run in an isolated worktree. Call EnterWorktree as your first action.
  FILE SCOPE:
    own: [src/middleware/auth.ts, src/middleware/roles.ts]
    read: [src/models/user.ts, src/config/auth.ts]
    deny: [src/routes/*]
</boundaries>

After validation, the orchestrator merges worktree branches sequentially.

Codex CLI note: No worktree equivalent exists in Codex. Rely on file ownership scoping + sequential execution for build isolation. See forge-codex-multiagent for Codex-specific conflict prevention.

File Ownership Enforcement

Declare ownership in every agent's context handoff. The agent MUST NOT modify files outside its declared scope.

Agent A:
  own: [src/auth/*, src/middleware/auth.*]
  read: [src/config/*, src/types/*]
  deny: [src/routes/*, src/models/*]

Agent B:
  own: [src/routes/*, src/controllers/*]
  read: [src/config/*, src/types/*]
  deny: [src/auth/*, src/models/*]

Agent C:
  own: [src/models/*, src/db/*]
  read: [src/config/*, src/types/*]
  deny: [src/auth/*, src/routes/*]

This format is machine-parseable. The forge-orchestrator writes it to .claude/forge-scopes.json for automated scope validation via the forge-scope-guard hook.

If two agents need to modify the same file, the decomposition is wrong. Refactor the task split.


Error Recovery

Agent Failure

When a sub-agent crashes, overflows context, or produces garbage:

<task>
  [Original task description — copied verbatim]
</task>

<context>
  Previous agent failed with: "Context window exceeded while processing
  auth middleware tests. Last successful output: auth.ts created,
  roles.ts created, tests not started."
  Start fresh. Do not attempt to recover previous agent state.
</context>

Rules:

  • Spawn a fresh agent with the same context handoff + failure note
  • Never retry the crashed agent instance
  • Include what the previous agent accomplished (if anything)
  • Include the failure reason so the new agent can avoid the same path

Merge Conflicts

If sequential merge of worktree branches produces conflicts:

  1. Stop immediately — do not auto-resolve
  2. Present conflicts to the user with full diff context
  3. Wait for user resolution before continuing

Cross-agent merge conflicts are architectural issues. Auto-resolution risks silent data loss.

Quality Gate Failures

Gate fails → re-run agent with feedback → max 2 retries → escalate
AttemptAction
1st failureRe-run with gate feedback appended to context
2nd failureRe-run with both failure contexts
3rd failureEscalate to user — the task decomposition may be wrong

Progress Observability

TODO.md Updates

Update TODO.md after every significant step:

  • Completing a file
  • Passing or failing a test
  • Hitting an error or blocker
  • Finishing a milestone

FORGE-STATUS.md (Orchestrator Only)

For long-running orchestrations, the orchestrator (and only the orchestrator) maintains:

# Forge Status

## Current Milestone
M2: Core Implementation (3 of 5 tasks complete)

## Active Agents
- auth-builder: implementing JWT refresh (worktree: wt-auth)
- api-researcher: exploring rate limiting approaches

## Completed
- [x] Project scaffold
- [x] Database schema
- [x] User model

## Pending
- [ ] Auth middleware (in progress)
- [ ] API routes
- [ ] Integration tests

## Blockers
- None currently

Sub-agents do NOT write to FORGE-STATUS.md. They report status to the orchestrator via SendMessage; the orchestrator updates the file.

Progress Narration

Before each significant action batch, emit a brief progress note:

→ About to spawn 3 build workers for auth, routes, and models.
  Each gets worktree isolation. Expected completion: ~5 minutes.

Never run silently for 5+ minutes. If a cycle produces no observable output, write a progress note explaining what is happening and why.


Quick Reference: Tool Cheat Sheet

ActionToolKey Parameters
Spawn sub-agentAgentname, subagent_type, team_name, mode
Create teamTeamCreateteam_name, description
Create taskTaskCreatesubject, description, activeForm
Assign taskTaskUpdatetaskId, owner
Send DMSendMessagetype: "message", recipient, content, summary
BroadcastSendMessagetype: "broadcast", content, summary
Shutdown agentSendMessagetype: "shutdown_request", recipient
Delete teamTeamDelete(no params — uses current team)
List tasksTaskList(no params)
Enter worktreeEnterWorktreename (optional)

Anti-Patterns

Anti-PatternWhy It FailsDo Instead
Broadcasting routine statusN messages, wastes tokensDM the relevant teammate
Polling background agentsRaces, wastes tokensWait for notification
Same-file parallel buildsMerge conflicts guaranteedRedesign split or queue
model: "haiku" for workersQuality degradationInherit main model
Implementation on Explore agentEdits silently skippedUse general-purpose type
Auto-resolving merge conflictsSilent data lossStop and present to user
Retrying crashed agentsCorrupted state carries overSpawn fresh agent
Force-killing teammatesOrphaned stateUse shutdown_request
No file ownership declaredAgents step on each otherDeclare scope in handoff
Running silent 5+ minutesUser thinks agent is stuckEmit progress narration

Self-Evolution

Update this skill when:

  1. Claude Code API changes: New Agent tool parameters, TeamCreate options, or SendMessage types
  2. New anti-pattern discovered: Add to anti-patterns table with fix
  3. Concurrency limits change: Update parallelism table if rate limits or platform caps change
  4. New isolation mechanism: If Claude Code adds native worktree parameters to Agent tool, update conflict prevention

Current version: 1.0.0. See CHANGELOG.md for history.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.