.M
AboutSkillsExperienceEducationContactBlog
Resume
.M
© 2026 Muhammad Muneeb. All rights reserved.Powered by cipheraft.com
Hierarchical AI Agent Orchestration: Building Software with Supervisor and Worker Agents
All posts
Claude CodeAgentic AIAI AgentsMulti-Agent SystemsAgent OrchestrationSoftware ArchitectureAI-Assisted DevelopmentDeveloper ProductivityToken OptimizationPrompt EngineeringCode ReviewQuality AssurancePlaywrightNext.jsNestJSDevOps

Hierarchical AI Agent Orchestration: Building Software with Supervisor and Worker Agents

Muhammad MuneebOctober 15, 202618 min read

A practical methodology for building software with a Claude Code supervisor, specialist engineers, independent QA, and gated reviews—while controlling context, token spend, and delivery risk.

Introduction

Imagine giving an AI coding assistant a request such as “Build an inpatient admission workflow, including the API, patient-facing forms, validation, end-to-end tests, and documentation.” One assistant can attempt the entire feature. But as files, exceptions, tool output, and decisions accumulate, its context becomes a mixture of architecture discussions, implementation details, and test logs. It also ends up reviewing code it wrote itself.

My research into hierarchical AI agent orchestration explores a different model: organize a Claude Code session like a small engineering team. A Supervisor owns planning and decisions; specialist Senior Engineers own coherent units of work; Junior Engineers execute precisely defined slices; and independent QA, Reviewer, Researcher, and Docs Writer agents each operate within explicit boundaries.

The goal is not to create the largest possible number of agents. It is to improve development throughput and reduce wasted tokens without handing the decision to ship over to the agents. This article explains the architecture, the entire delivery lifecycle, configuration patterns, cost controls, and where the approach is—and is not—worth using.

Scope: This is a design methodology distilled from my October 2026 research, not a published performance benchmark. Exact Claude Code tools, limits, model identifiers, and hook behavior can change between versions; validate them against the version you deploy.

Background

Why one general-purpose coding agent becomes a bottleneck

A single assistant is often ideal for a small bug, a one-file refactor, or a script. Coordination overhead would be wasteful in those cases. Problems appear when a feature crosses frontend, backend, data, testing, and documentation boundaries. Three pressures accumulate:

  • Context pressure: file reads, searches, logs, and diffs consume the same conversational context needed for high-level reasoning.

  • Role conflicts: the same agent designs, writes, tests, and approves its own changes; self-checking is useful but not genuinely independent.

  • Unnecessary serial execution: unrelated tasks wait for each other, even when they could be completed safely in parallel.

Subagents address these pressures by working in isolated contexts and returning compact reports. The Supervisor can then retain the intent, checklist, dependencies, risks, and verdicts rather than the entire implementation transcript. Different model tiers can also be assigned according to how much judgment a task requires.

The primitives behind the system

The methodology relies on ordinary Claude Code configuration concepts rather than pretending that agents are permanent employees:

PrimitivePurpose in the methodology.claude/agents/*.mdVersioned role definitions with YAML frontmatter and instructionsmodel and effortAllocate stronger reasoning where decisions are consequentialtools / disallowedToolsSeparate read-only investigation, implementation, testing, and review permissionsIsolated agent contextKeep large searches and raw test output out of the Supervisor's working contextisolation: worktreeReduce file-edit collisions for independent parallel changes, where supportedBackground executionLet independent workers operate without blocking the whole runProject ledgerPersist plans, statuses, reviewer decisions, and handover information outside chat history

An agent definition persists in a file. An agent instance is created on demand for a specific assignment, returns a result, and finishes. The roster is not a standing pool of idle agents.

Main Section: Designing the Agent Hierarchy

Seven responsibilities, one accountable workflow

The hierarchy uses seven types of responsibility, with multiple named Senior specializations where necessary:

refined-01-agent-roster

Figure 1. The human approves milestones; the Supervisor routes work; Senior Engineers delegate bounded implementation; verification remains independent.

RoleTypical tier in the researchResponsibilityCan edit application code?SupervisorOpus-classInterpret requirements, derive checklist, size units, route work, maintain ledger, request human approvalNoSenior EngineerOpus-class; optional lean Sonnet profileDesign a unit, implement critical logic, delegate mechanical slices, integrate, self-auditYes, within scopeJunior EngineerSonnet-class floorImplement clearly specified and repetitive changesYes, within assigned filesResearcherSonnet-classExplore code, docs, and logs; return condensed findingsNoQA EngineerSonnet-classWrite and execute end-to-end tests for user-visible criteriaTest files onlyReviewerOpus-classIndependently inspect behavior, changes, and acceptance evidence; issue ship or iterateNoDocs WriterSonnet-classUpdate project docs after a unit clears the gateDocumentation only

In a full-stack project, the Senior role can be expressed as separate definitions: senior-frontend, senior-backend, and senior-auth-security. This is specialization, not a reason to create a new agent for every ticket.

The important boundary is that the Supervisor does not become the feature developer, and the Reviewer is neither a builder nor a code fixer. The Senior's self-audit improves delivery quality, but it cannot replace an independent quality gate.

What the Supervisor actually owns

The Supervisor receives an outcome, not a prewritten task list. It first restates the goal, records assumptions, investigates blockers through a Researcher, compares feasible approaches, and develops a checklist with measurable acceptance criteria.

For example, “add appointment rescheduling” is too broad to give blindly to a worker. A useful decomposition might be:

  1. Define the backend rescheduling contract, authorization rules, and conflict response.

  2. Implement service validation and persistence against that contract.

  3. Build the frontend experience against the published contract, including loading, conflict, and success states.

  4. Validate user-visible behavior with end-to-end tests and an independent review.

Those are illustrative units; the actual boundaries depend on the repository. The Supervisor records dependencies and decides what can run in parallel. The human approves the plan before build work begins.

Make work units big enough to matter—and small enough to finish

In the research, a unit is the smallest work package a Senior can design, build, self-check, and hand to an independent Reviewer without needing a new milestone decision halfway through.

SizeScopeTypical delegationSOne narrow behavior or fileSenior works directlyMOne feature slice across a handful of filesSenior with zero to two JuniorsLSeveral related integration seams with one coherent acceptance boundarySenior with a few independent Juniors

A broad goal must be decomposed before delegation; a trivial task should not be fragmented just to make the roster look busy. Every brief should include the goal, in/out of scope, contracts, constraints, files or boundaries, observable acceptance criteria, and required result schema.

From Requirement to Approved Commit

The workflow deliberately separates implementation completion, quality approval, and human authorization.

refined-02-delivery-lifecycle

Figure 2. A unit advances through analysis, design, build, QA, independent review, documentation, and explicit human approval.

  1. Analyze and brainstorm. The Supervisor defines the outcome, constraints, uncertainties, and candidate designs.

  2. Derive and size the checklist. Items are classified as goals, features, or tasks, then broken into S/M/L units only where needed.

  3. Approve the plan. The human checks scope, trade-offs, and acceptance criteria.

  4. Brief and route a Senior. The Supervisor provides a self-contained brief and model-appropriate check commands.

  5. Implement and self-audit. The Senior owns architecture and integration, delegates well-specified work, and returns a concise evidence report.

  6. Test user-visible behavior. The QA Engineer writes and runs Playwright checks where the unit has a UI or an end-to-end user journey. Backend-only units need appropriate backend checks instead.

  7. Review independently. The read-only Reviewer inspects criteria, diff, and test evidence, issuing ship or iterate with prioritized findings.

  8. Fix with a limit. iterate goes back to the Senior and then the Reviewer. The proposed default is no more than three rounds before escalation.

  9. Update documentation. The Docs Writer aligns docs and API notes with the accepted changes.

  10. Get human approval and commit. Only after a milestone report is reviewed does a person authorize the commit, PR, or deployment action.

  11. Record the handover. The ledger captures what is done, blocked, deferred, and next.

The process is gated, not an autonomous pipeline that can silently deploy a risky change. A Reviewer saying ship means the criteria passed the methodology's review, not that production deployment is automatically authorized.

Inside one Senior Engineer's unit

The Senior performs a smaller, disciplined workflow: investigate contracts, design the critical flow, build the judgment-heavy parts, delegate truly mechanical slices, audit the returned edits, integrate, and verify once after integration.

refined-03-senior-delegation

Figure 3. Only independent, fully specified slices are parallelized; the Senior integrates them and remains responsible for the unit.

A Junior assignment should be checkable without requiring a design meeting. Good examples are “add these exact DTO fields,” “create typed client wrappers from this published contract,” or “generate test fixtures matching this schema.” Bad examples are “design permissions” or “figure out the data model.” If writing the delegation spec would take longer than implementing the slice, the Senior should simply keep the work.

Parallel writers need disjoint file sets or isolated worktrees. A worktree can isolate edits, but the Senior still needs to audit and integrate the changes. Worktree coverage and concurrency limits should be verified in the installed Claude Code version.

Native, Workflow-Driven, or Hybrid Orchestration?

The methodology compares three execution strategies:

ApproachBest forMain trade-offNative gated rosterCoupled features, sensitive work, frequent human decisionsClear control but more serial coordinationDeterministic workflow fan-outLarge, independent research sweeps, repeated migrations, parallel auditsEfficient breadth but less mid-run interventionHybrid (recommended)Real projects mixing dependent milestones and independent sub-phasesMore orchestration configuration to maintain

refined-04-hybrid-orchestration

Figure 4. The hybrid pattern preserves gated decisions while using fan-out only for genuinely independent batches.

The hybrid is the default proposed in the research. Keep the Supervisor's gated loop as the outer structure. Within an approved unit, allow a bounded fan-out for clearly independent tasks—such as scanning multiple modules or creating separate fixtures—then collect those results into one reviewable milestone.

A deterministic workflow should not bundle multiple approval-dependent units into one run. Missing or failed fan-out results must be treated as failures, not silently omitted from the combined output.

Token Economy: Spend Reasoning Where It Matters

The objective is to improve total cost to an accepted change, not simply lower the price of an individual model call. A weak worker that repeatedly breaks a contract may be more expensive after rework than a stronger worker with a clear specification.

refined-05-token-economy

Figure 5. Large searches, edits, and logs remain inside worker contexts; short decision-ready results return to the Supervisor.

The research identifies several compounding controls:

  • Context isolation: Researcher and builder transcripts remain in their own windows; the Supervisor receives short, structured outputs.

  • Model tiering: Opus-class reasoning handles planning, technical ownership, and independent judgment. Sonnet-class models handle scoped implementation, research, QA, and docs. The research uses Sonnet as a policy floor, not Haiku.

  • Stable agent definitions: Reuse consistent agent instructions and pass changing task details in the brief. This improves the opportunity for prompt caching.

  • Preloaded project skills: Teach agents repeated repository conventions without requiring them to rediscover the same rules on every unit.

  • Structured results: Return status, criteria, changed files, risks, and verdicts—not raw command output.

  • Selective parallelism: Fan out only if dependencies, file ownership, and acceptance criteria permit it.

  • Right-sized checks: Have the Senior run unit verification once after integration; QA runs relevant end-to-end tests; Reviewer verifies important evidence. Avoid running the full suite after every Junior edit.

  • Explicit budgets: Check time, tokens, and review progress between units, and stop when the remaining budget cannot support a safe gate.

These are design hypotheses and operational levers. Without measurements from your own repositories, they do not justify a claim such as “50% cheaper” or “3× faster.” Track cost per accepted unit, time to accepted unit, rework rounds, escaped defects, and total agent usage before claiming an improvement.

The Quality Gate Is a Separate Job

A builder's tests passed report is useful evidence, but it is still a builder's report. The Reviewer should examine actual changes and acceptance criteria from an independent context, with no write permission to application code.

refined-06-quality-gate

Figure 6. QA supplies behavior evidence, the Reviewer returns a verdict, and only the human authorizes the next milestone.

The Reviewer returns a compact, prioritized decision record. For example:

unit_id: appointment-reschedule-ui
verdict: iterate
criteria:
  - name: conflict-state-visible
    status: pass
    evidence: playwright-trace
  - name: forbidden-user-blocked
    status: fail
    evidence: route-access-check
findings:
  - severity: high
    issue: unauthorized users can still submit the form
    required_fix: enforce the permission check before submit
open_risks: []

The QA Engineer creates or updates user-visible tests (for example, Playwright tests), executes them against a running app, and reports results and reproduction evidence. The Reviewer judges the entire unit, including non-UI acceptance criteria. QA testing and Reviewer judgment are complementary, not interchangeable.

Limit the fix loop—for example, three rounds in the proposed roster. If a unit cannot pass, the Supervisor reports unresolved findings to the human rather than continuing to spend tokens indefinitely. The human decides whether to redesign, defer, or stop.

Practical Claude Code Setup

Recommended repository layout

The research uses project-scoped configuration so a team can version and review the roster along with its application, instead of relying on machine-specific personal agents.

project-root/
├── .claude/
│   ├── agents/
│   │   ├── core/
│   │   │   ├── supervisor.md
│   │   │   ├── junior-implementer.md
│   │   │   ├── qa-engineer.md
│   │   │   ├── reviewer.md
│   │   │   ├── researcher.md
│   │   │   └── docs-writer.md
│   │   └── seniors/
│   │       ├── senior-frontend.md
│   │       ├── senior-backend.md
│   │       └── senior-auth-security.md
│   ├── hooks/
│   │   └── enforce-agent-policy.mjs
│   ├── skills/
│   │   └── agent-roster-setup/
│   └── settings.json
├── agent-runs/
│   └── ledger.md
└── ... application code ...

The nine named definitions above represent one proposed full-stack roster, not a minimum required by Claude Code. A smaller project should use fewer specializations.

A minimal Senior definition

One custom agent is a Markdown file with YAML frontmatter and an instruction body. The following is an illustrative starter, not a substitute for the research's full role definitions and policy hook:

---
name: senior-backend
description: Owns one backend unit, its contracts, implementation, integration and structured handoff.
model: opus
effort: medium
tools: Read, Grep, Glob, Edit, Write, Bash, Agent
---
You are responsible for one bounded backend unit.
Investigate the existing contracts before changing code.
Implement high-risk logic yourself. Delegate only exact, testable slices.
Audit and integrate every returned change.
Run the unit's prescribed checks once after integration.
Return: unit_id, status, contracts, files_changed, criteria, open_risks.
Never claim independent review approval.

For a Reviewer, choose a separate definition with read-only tools (plus carefully scoped commands for running checks), and do not give it Edit or Write. In practice, restrictions must be enforced through the available tool permissions and hooks—not merely written as instructions. Frontmatter and hook support are version-sensitive.

Preserve the run ledger

The ledger is the durable source of truth, rather than a chat transcript. Its minimal form might be:

# Agent run ledger

| id | unit | size | owner | state | review | next action |
| --- | --- | --- | --- | --- | --- | --- |
| U01 | Reschedule API contract | M | senior-backend | done | ship | approve commit |
| U02 | Reschedule UI | M | senior-frontend | in-review | pending | run reviewer |

## Lessons
- Re-check role permissions for every write-capable workflow.

## Next
- Wait for the U02 review verdict; do not advance without approval.

Statuses are deliberately explicit: backlog, briefed, in-progress, in-review, iterate, blocked, done, or dropped. A real ledger should also record agent IDs, iterations, evidence references, and a reconciliation of claims against actual diffs and commits.

Guard the spawn and model policy

The research proposes a Sonnet minimum for worker roles and a named hierarchy of who may spawn whom. This should be enforced where possible with a PreToolUse policy hook, not assumed because a system prompt says so.

A project settings fragment in the research uses this shape:

{
  "env": {
    "CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH": "3"
  },
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Agent|Task|Workflow",
        "hooks": [
          {
            "type": "command",
            "command": "node \"${CLAUDE_PROJECT_DIR}/.claude/hooks/enforce-agent-policy.mjs\"",
            "timeout": 10
          }
        ]
      }
    ]
  }
}

Important: This JSON is only a registration example. It does not implement the policy by itself. The referenced script must exist, validate spawn permissions/model choices, handle malformed input, and be tested with allowed and denied cases. The research also notes that a missing Node runtime or broken hook path may prevent the hook from enforcing the intended restriction. Merge into existing settings rather than overwriting them. Confirm how your installed Claude Code version handles these hooks and nesting limits.

Full-stack example: Next.js, NestJS, and a BFF

For a system with a Next.js frontend, a NestJS BFF/API gateway, and backend domain services, the most important rule is contract-first sequencing.

refined-07-fullstack-architecture

Figure 7. One Supervisor coordinates both codebases; the backend Senior publishes the contract before the frontend Senior consumes it.

The Supervisor can split a cross-stack feature into two dependency-ordered units: (1) the backend Senior defines and implements the DTO and BFF contract, then (2) the frontend Senior builds against that agreed contract. The frontend does not invent missing response fields, and the Senior responsible for auth/security is routed to changes with a high security blast radius.

In the research's separate-repository example, the command is:

claude --agent supervisor --add-dir ../ehr-microservices/opus

The external directory is an example path, not a universal directory name. In the suggested arrangement, the roster and policy settings live in the frontend repository while --add-dir grants the session access to the backend. An alternative is a parent project root that holds both repositories and the shared roster.

Example unit checks proposed for that stack include:

# Frontend (inside the frontend repository)
pnpm check-types && pnpm lint && pnpm test && pnpm build

# Backend (inside the changed NestJS service)
npm run lint && npm run test:unit && npm run build

# UI end-to-end tests, after the app is ready
pnpm test:e2e

Only use commands actually defined in your package.json. Backend integration tests that require Kafka, a database, or other infrastructure need an environment capable of running them; a successful unit build must not be presented as proof that those integration paths work.

Portable installation and verification

The research also proposes a single portable setup file, agent-roster-setup.md, that installs a project-local setup skill, agents, hook, settings, and ledger after a human-approved plan. That setup file is described in the research, but is not included among the files attached to this blog package. The PDF alone is not an executable installer.

The proposed installer performs one final verification covering agent definitions, unique names, YAML validity, tool/model policy, hook behavior, command placeholders, and the ledger. Treat its checks as a checklist for your own setup; use a smoke test before allowing real feature work.

Observability, Handover, and Failure Modes

A managed roster should expose: current agent, assigned unit, elapsed time, model tier, token consumption, return status, review verdict, and unresolved risks. The research discusses Claude Code's task/agent views and optional tracing integrations; their availability and exact screens depend on tooling and version. In sensitive repositories, scrutinize whether telemetry exports source code, prompts, or file content before connecting a third-party tracing platform.

Several practical failure modes deserve explicit rules:

  • Conflicting edits: never run two write-capable agents against overlapping files in the same checkout.

  • Stale contracts: if backend work changes the interface, rebrief dependent frontend work; do not expect isolated workers to notice silently.

  • Unbounded delegation: use a small fan-out and cap the nested agent depth according to the installed runtime.

  • Missing fan-out results: treat absent, canceled, or failed worker responses as incomplete work.

  • Self-approval: the Senior's audit never substitutes for a separate read-only Reviewer.

  • Over-verification: prioritize security, data correctness, irreversible effects, and customer-visible behavior instead of blindly rerunning every check.

  • Opaque handover: record the exact next unit, blockers, review status, and commit reconciliation in the ledger.

Persistent context matters as much as clever delegation. The ledger should survive a restart; lessons from review should be short and evidence-based; and worker claims should be checked against the actual repository state before the Supervisor records a unit as complete.

When Should You Use This Architecture?

This hierarchy is a good fit for large or risky changes: multi-module features, frontend/backend integration, authentication, complex migrations, a production healthcare or financial workflow, or work where independent acceptance review is valuable. It is also useful when the team needs an explicit audit trail for how AI-generated changes are accepted.

For a small, clear, reversible patch, use one agent. The hierarchy adds briefing, coordination, verification, and approval latency. It also does not make ambiguous requirements magically precise: a bad Supervisor brief can systematically produce bad output across multiple workers. Human judgment remains an essential input.

Key Takeaways

  • Design the organization around responsibilities, not agent count. Separate planning, implementation, test execution, judgment, and authorization.

  • Keep the Supervisor's context small. Agents should return actionable summaries, not exploration transcripts.

  • Delegate by precision and independence. Seniors keep integration and security decisions; Juniors handle exact, bounded tasks.

  • Make QA and review separate gates. A builder's self-audit is not independent approval.

  • Prefer a hybrid run model. Maintain human-controlled milestones, but parallelize independent research or mechanical work within them.

  • Optimize accepted outcomes, not raw token price. Measure overall rework, review passes, latency, and cost before claiming efficiency gains.

  • Keep the system recoverable. Version agent definitions, enforce permissions, maintain a ledger, and reconcile results with real commits.

Conclusion

Hierarchical AI agent orchestration is less about asking several models to write code and more about engineering a reliable decision and delivery process around those models. A strong Supervisor can keep the goal coherent, a specialist Senior can protect integration boundaries, Juniors can accelerate repetitive work, and independent QA and review can make the result easier to trust.

The approach becomes useful when its boundaries are real: briefs contain measurable outcomes; write permissions follow roles; parallel changes are isolated; review results are independent; and a human can stop, change, or approve the run at every consequential milestone.

Start small: implement a Supervisor, one Senior, a Researcher, and an independent Reviewer on one moderate feature. Measure the results. Add Juniors, QA, documentation automation, and hybrid fan-out only when the work genuinely benefits from them.


Research basis: “Hierarchical AI Agent Orchestration — A Methodology for Building Software with a Supervisor and Worker Agents,” October 2026 (65-page user-provided methodology). This article is an editorial adaptation; example snippets are illustrative and must be checked against your Claude Code installation before production use.

Claude CodeAgentic AIAI AgentsMulti-Agent SystemsAgent OrchestrationSoftware ArchitectureAI-Assisted DevelopmentDeveloper ProductivityToken OptimizationPrompt EngineeringCode ReviewQuality AssurancePlaywrightNext.jsNestJSDevOps
Back to all posts