Agentic Engineering with Claude Code: Swarms & Safety
AI coding agents change where engineering effort is spent: the hard problem moves from typing code to defining boundaries, checking outputs, and recovering from unsafe or incorrect actions. The useful mental model is a controlled execution loop—request, plan, tool call, verification, and human review—not a group of agents that can be trusted because they are autonomous.
This guide maps delegation topologies, Claude Code extension points, state coordination, and isolation. It uses a small hypothetical finance-analysis service as a running example; provider names and performance figures are intentionally omitted unless they are measured for a stated workload.
Mindset & Feedback Control: From Code Author to System Director
The primary barrier for engineers transitioning to agentic workflows is psychological: attempting to micro-manage AI agents line by line. Agentic engineering relies on controlled chaos—granting agents wide operational freedom inside tightly scoped system boundaries. Learn more about core runtime context in our Claude Code Context Window Guide.
Positive vs. Negative Feedback Loops
Agentic execution is governed by control systems theory:
- Positive Feedback Loops (Runaway Drift): When an agent produces an unverified assumption, feeding that output back into subsequent prompts compounds error rates. Without intervention, hallucination cascades cause severe codebase degradation.
- Negative Feedback Loops (Dampening Forces): Deterministic evaluation gates—such as TypeScript compilers, linters, unit tests, and pre-commit hooks—provide corrective friction. They force the agent to iterate locally until outputs satisfy rigid criteria.
The 'Be the Boss' Engineering Mentality
As an Agentic Engineer, your role shifts from writing syntax to designing contracts, evaluating outputs, and defining state boundaries. You act as the executive architect: setting clear goal definitions, establishing safety guardrails, and evaluating pull requests.
Quick reference
- Controlled chaos balances creative problem solving with deterministic validation gates.
- Positive feedback loops cause compound errors; negative feedback loops (tests/linters) steer agents back to truth.
- The Agentic Engineer focuses on architecture, interfaces, state schemas, and verification suites.
- Establishing explicit goal contracts prevents agent context drift across multi-step execution sessions.
- Human oversight focuses on high-level design review rather than manual code typing.
Remember this
Operate as a system director: let agents explore solution spaces while enforcing negative feedback loops through automated testing.
Multi-Agent Topologies & Orchestration Mechanics
Complex software engineering tasks exceed single-agent context limits. Multi-agent architectures divide objectives across specialized roles, managing state through explicit communication boundaries.
Topologies: Sub-Agents vs. Agent Teams vs. Swarms
- Sub-Agents: Hierarchical tree topology where a lead agent spawns isolated worker agents for zero-shot subtasks and aggregates results.
- Agent Teams: Peer-to-peer mesh topology where specialized agents (e.g., Architect, Tester, Security Reviewer) communicate over shared message channels.
- Swarms (Gastown / GSD): Spec-driven orchestrators managing autonomous worker pools (polecat, rig, mayor, crew, convoy, sling) isolated by Git branches.
GSD Full Flow (Sequential Spec & Verification)
In Get Stuff Done (GSD), execution follows a strict phase-by-phase verification checklist: 1. Discuss: Clarify requirements and define what is being built. 2. Plan: Break requirements into ordered phases (Phase 1: DB $\rightarrow$ Phase 2: Backend $\rightarrow$ Phase 3: UI). 3. Execute Phase: Coding agent builds exclusively Phase 1 in fresh context. 4. Verify Phase: Test execution output against plan. If verification fails, fix/replan; if it passes, proceed to Phase 2.
Gas Town Full Flow (Mayor & Parallel Polecats)
In Gas Town, orchestration shifts to an asynchronous worker swarm managed by a central coordinator: 1. You $\rightarrow$ Mayor: You assign high-level tasks to the Mayor (coordinator). 2. Mayor (Beads & Convoys): Mayor breaks tasks into beads, groups them into a Convoy, and slings work items to parallel workers. 3. Polecat Swarm: Polecat A (Task 1), Polecat B (Task 2), and Polecat C (Task 3) work simultaneously in isolated Git worktrees. 4. Refinery Merge Queue: Completed Polecat branches open PRs into the Refinery for automated merging into the primary project Rig. 5. Mayor Reports Completion: Mayor notifies you when the full convoy completes.
| Execution Lifecycle Step | GSD (Phase-Driven) | Gas Town (Swarm-Driven) | Primary Memory Rule |
|---|---|---|---|
| 1. Task Initialization | You start GSD & discuss requirements | You assign high-level goals to the Mayor | GSD = Sequential / Gas Town = Swarm |
| 2. Planning & Dispatch | Create ordered Phase 1, 2, 3 spec plan | Mayor creates beads & slings convoy tasks | Plan.md vs. Convoy Sling |
| 3. Execution Topology | Single coding agent builds active phase | Polecats (A, B, C) build in parallel worktrees | Fresh Phase Context vs. Parallel Polecats |
| 4. Quality Gate & Merge | Verify phase tests before starting next phase | Refinery queue merges finished PRs to Rig | Verify Phase vs. Refinery Merge Queue |
| 5. Finalizing Project | App completes step by step across phases | Mayor notifies you when convoy is done | Sequential Verification vs. Mayor Convoy |
Quick reference
- GSD flow: Discuss → Plan → Execute phase → Verify phase → Proceed to next phase.
- Gas Town flow: You → Mayor → Sling → Polecats parallel worktrees → Refinery merge → Done.
- GSD isolates context sequentially per phase; Gas Town isolates context concurrently per Git worktree.
- Use GSD when requirements require strict ordered phase verification (e.g. schema first, then backend).
- Use Gas Town when multiple independent modules can be built simultaneously by parallel Polecats.
Remember this
Choose GSD for disciplined phase-by-phase verification, and Gas Town when parallel Polecats can build independent feature branches concurrently.
Claude Code Pro Engineering: Custom Skills, Hooks, and Agents
Maximizing productivity with Claude Code requires leveraging advanced extension primitives: custom slash commands with $ARGUMENTS, project-specific agents in .claude/agents/, CLAUDE.md operational guidelines, and deterministic shell hooks. Explore plugin architectures in our Claude Code MCP Plugins Guide.
Shell hooks in .claude/hooks.json trigger executable commands during key lifecycle events such as pre_file_edit, post_file_edit, and pre_commit. Post-edit hooks automatically run formatters to ensure instant consistency, while Codex CLI interop enables multi-tool agent collaboration.
Skills and Custom Agents
Beyond hooks, Claude Code supports slash commands (skills) that expand with dynamic $ARGUMENTS and custom agents stored in .claude/agents/. These primitives let you encode team workflows—code review processes, deployment checklists, security audits—as reusable building blocks. When a team member types /review-pr, Claude executes the skill configuration, inheriting the full CLAUDE.md ruleset and your project's MCP connections. Custom agents in .claude/agents/ take this further by creating separate, specialized personas for specific roles: an architect agent for design reviews, a security agent for threat modeling, a performance agent for benchmarking.
| Primitive | Execution Mode | Context Boundary | Tool Access | Primary Use Case |
|---|---|---|---|---|
| Slash Command / Skill | Inline prompt expansion | Shares main session context | Full session tools & MCP | Reusable team prompts & standards |
| Sub-Agent | Isolated background process | Fresh, isolated context window | Scoped tool permissions | Parallel investigation & subtasks |
Quick reference
- Slash commands parse $ARGUMENTS to turn dynamic CLI inputs into structured prompts.
- Placing agents in .claude/agents/ defines pre-configured role profiles for specialized tasks.
- CLAUDE.md provides global project constraints that guide every session startup automatically.
- Post-edit hooks guarantee that formatting and linting rules are enforced deterministically.
- Codex CLI interop demonstrates how Claude Code acts as a universal orchestrator for external utilities.
Remember this
Combine CLAUDE.md guidelines with deterministic shell hooks and custom skills to build reproducible agent environments.
Real-World Case Study: FiNALLY (Finance Ally) Architecture
To understand agentic orchestration in production, consider FiNALLY (Finance Ally)—an autonomous financial analysis platform. FiNALLY ingests market data from Polygon/Massive APIs, processes financial reasoning via Cerebras ultra-fast LLM inference, coordinates multi-step tasks through plan.md, and streams live UI updates via Server-Sent Events (SSE).
State Coordination & Ultra-Fast Inference
FiNALLY coordinates state across processes using structured filesystem files (plan.md) and strictly validated JSON schemas:
1import { Cerebras } from "@cerebras/cerebras_cloud_sdk";2import { z } from "zod";3 4// 1. Define Strict Pydantic/Zod Financial Schema5const FinancialAnalysisSchema = z.object({6 ticker: z.string(),7 marketCap: z.number(),8 sentimentScore: z.number().min(-1).max(1),9 keyRisks: z.array(z.string()),10 recommendation: z.enum(["BUY", "HOLD", "SELL"]),11});12 13type FinancialAnalysis = z.infer<typeof FinancialAnalysisSchema>;14 15// 2. Cerebras Ultra-Fast LLM Inference Call (~2000 tokens/sec)16export async function analyzeTicker(ticker: string, marketData: object): Promise<FinancialAnalysis> {17 const client = new Cerebras({ apiKey: process.env.CEREBRAS_API_KEY });18 19 const response = await client.chat.completions.create({20 model: "llama3.1-70b",21 response_format: { type: "json_object" },22 messages: [23 {24 role: "system",25 content: "You are an expert financial analyst. Analyze ticker data and return JSON matching the required schema.",26 },27 {28 role: "user",29 content: `Ticker: ${ticker}. Market Data: ${JSON.stringify(marketData)}`,30 },31 ],32 });33 34 const rawJson = JSON.parse(response.choices[0].message.content ?? "{}");35 return FinancialAnalysisSchema.parse(rawJson);36}SSE Event Streaming & Filesystem Coordination
As the agent executes tasks listed in plan.md, it emits SSE events to update client interfaces in real time. This pattern decouples heavy agentic execution from reactive web interfaces.
Quick reference
- The finance example is hypothetical; production claims require a source or a reproducible benchmark.
- Market-data freshness, provider quotas, and error responses must be part of the contract.
- Filesystem coordination via plan.md is simple to inspect but needs locking and recovery when workers overlap.
- Server-Sent Events (SSE) push live task progression updates directly to client UI dashboards.
- Strict Pydantic/Zod schemas prevent unstructured LLM outputs from breaking downstream services.
Remember this
Pair ultra-fast inference engines (Cerebras) with structured outputs and SSE streaming to build responsive agent applications.
Remote Sandboxing, Safety & YOLO Execution
Granting AI agents full terminal execution capabilities introduces safety risks. Autonomous agents can accidentally delete files or expose environment variables. Establishing strict safety boundaries is mandatory for production workflows. For sandbox details, see our Sandboxing & Isolation Guide.
Isolation Layers: /sandbox vs. Cloud Containers
- Local
/sandbox: Restricts command execution to safe paths and white-listed bash utilities on your host machine. - Remote MicroVMs (Sprites.dev / Fly.io): Ephemeral Firecracker containers that execute code in complete hardware isolation.
- Claude Code Web & GitHub PR Workflows: Automated cloud routines that run off-hours in managed cloud containers.
| Feature / Dimension | Local /sandbox Boundary | Remote Container (Sprites.dev / Fly.io) |
|---|---|---|
| Isolation Strength | Process & filesystem path restriction | Hardware-level Firecracker MicroVM |
| Network Policy | Host network pass-through (configurable) | Strict zero-trust outbound proxy |
| YOLO Execution Risk | Medium (host environment side-effects possible) | Zero (ephemeral environment destroyed on exit) |
| Cold Start Latency | Instant (<10ms) | Fast (<300ms) |
Quick reference
- Local
/sandboxprevents accidental destructive shell commands during everyday local development. - Sprites.dev and Fly.io supply ephemeral MicroVMs ideal for unconstrained 'YOLO' agent execution.
- GitHub PR automated workflows run agent code reviews in isolated runner containers.
- Claude Code Web enables cloud routines to run background tasks without keeping local hardware powered on.
- Network egress controls reduce exfiltration risk; they do not make it zero, especially when secrets are mounted.
Remember this
Use local /sandbox for everyday development, and deploy ephemeral cloud containers (Sprites.dev/Fly.io) for unconstrained YOLO automation.
Hands-on Practice: Build a Multi-Agent Swarm with Local Safety Hook and Plan Coordination
Consolidate your knowledge by configuring a local agent workspace equipped with a plan.md coordinator, a post-edit formatting hook, and a simulated sub-agent task:
1# 1. Create project directory2mkdir -p agentic-masterclass-demo && cd agentic-masterclass-demo3 4# 2. Define plan.md State Coordinator5cat << 'EOF' > plan.md6# Execution Plan7- [ ] Task 1: Audit project structure8- [ ] Task 2: Generate TypeScript interface contract9- [ ] Task 3: Run post-edit formatting hook10EOF11 12# 3. Create .claude/hooks.json for Post-Edit Auto-Formatting13mkdir -p .claude14cat << 'EOF' > .claude/hooks.json15{16 "hooks": {17 "post_file_edit": [18 {19 "command": "npx prettier --write $CLAUDE_EDITED_FILE"20 }21 ]22 }23}24EOF25 26# 4. Trigger Claude Code execution with plan coordination27claude -p "Read plan.md, execute Task 1 and Task 2, and update checkboxes in plan.md"Executing this workflow verifies that plan.md maintains state progression while shell hooks enforce formatting rules automatically.
Quick reference
- Creating plan.md establishes a human-readable state machine across multi-step agent executions.
- Configuring
PostToolUsein.claude/settings.jsoncan run project-specific formatting after supported tool calls. - Piping tasks through
claude -pdemonstrates automated, headless agent script execution.
Remember this
A plan file is useful only when every step has an observable result, an intentional failure, and a recovery rule.
Key takeaway
Practice task: deliberately break the formatter command or leave Task 2 unchecked. The expected symptom is a non-zero hook or incomplete plan. Restore the command, rerun the check, and pass only when the plan records the result and the working tree passes the project formatter and tests.
Polo Khan
Lead Author & Systems ArchitectSoftware engineer and distributed systems architect specializing in backend scalability, cloud-native infrastructure, databases, and AI engineering workflows. Author and maintainer of Core Concept Learning.
Related Articles
Explore this topic