/ai-agent-skills:agent-architecture-designfrom ai-agent-skills
Guides designing control loops, state/memory models, and tool boundaries for LLM-driven agents. Covers ReAct, plan-and-execute, and finite-state patterns.
Ships in ai-agent-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
An "agent" is a loop: an LLM repeatedly observes state, decides on an action (call a tool, ask the user, or finish), and updates state based on the result, until some termination condition is met. Getting this loop's shape wrong is the single biggest source of production incidents in agentic systems — not model quality. Agents that loop forever, that accumulate unbounded context, that hold too many high-privilege tools in one prompt, or that have no checkpoint for a human to intervene, fail in ways that are expensive, hard to debug, and sometimes destructive. This skill defines a small set of proven architecture patterns (ReAct-style loop, plan-and-execute, finite-state/graph) and the state, memory, and control-flow decisions that make an agent safe and debuggable to operate, independent of which model or vendor SDK is driving it.
Write down the termination condition before writing any prompt. Every agent loop needs an explicit "done" signal: a tool call that means completion, a structured final-answer format, or a supervisor check. If you cannot state in one sentence how the loop knows to stop, do not start building.
Pick a control-flow pattern that matches the task's shape:
triage → gather_info → draft → approve → send);
best for compliance-sensitive or repeatable business processes where
you want to reason about which states can reach which other states.Bound the loop explicitly. Set a hard maximum iteration count and a wall-clock timeout, independent of the model's own judgment about when it's done. Fail closed (stop and surface an error) rather than fail open (silently keep going or silently give up and claim success).
MAX_ITERATIONS = 12
TIMEOUT_SECONDS = 180
def run_agent_loop(task, tools):
start = time.monotonic()
for i in range(MAX_ITERATIONS):
if time.monotonic() - start > TIMEOUT_SECONDS:
return AgentResult(status="timeout", partial=state.transcript)
response = llm.call(messages=state.messages, tools=tools)
if response.stop_reason == "end_turn":
return AgentResult(status="done", output=response.text)
if response.stop_reason == "tool_use":
for call in response.tool_calls:
result = dispatch_tool(call, allowlist=tools) # see agent-tool-use-patterns
state.messages.append(tool_result_message(call, result))
return AgentResult(status="max_iterations_exceeded", partial=state.transcript)
Design the state/memory model as two tiers. Keep a small working state (current task, plan, last N tool results) that lives in the context window, and a separate persisted memory (a database, vector store, or file) for anything that must survive across sessions or is too large to keep in-context. Never treat the raw conversation transcript as your only memory store — it grows unbounded and degrades reasoning quality long before it hits a hard token limit.
Define tool boundaries per agent, not per task. List every tool the agent can call and classify each as read-only, reversible-write, or irreversible-write. Irreversible-write tools (send email, delete resource, execute payment) should require either a dedicated confirmation step in the state machine or a human-in-the-loop gate — do not rely on prompt instructions alone to prevent misuse.
Add a human checkpoint at the highest-leverage point, not
everywhere. For a finite-state design, this is usually a dedicated state
(awaiting_approval) the graph cannot exit without external input. For
a ReAct loop, it's a policy check inside dispatch_tool that intercepts
specific tool names.
Instrument before you optimize. Log, at minimum: the input to each LLM call, the tool calls it emitted, the tool results, and the final stop reason. Without this, pitfalls like loops and context bloat are invisible until they cause an incident.
Decide single-agent vs multi-agent last, not first. Start with the simplest single agent with a well-scoped tool set; only split into multiple agents once you have concrete evidence of context overload, role confusion, or the need for parallel independent workstreams (see multi-agent-orchestration for when that split is justified).
Symptom: Agent runs for minutes issuing tool calls that don't make progress, eventually timing out or exhausting a rate limit. Fix: Enforce a hard iteration cap and a "no progress" detector (e.g. compare the last two tool calls; if identical, break and surface the stall rather than retrying silently).
Symptom: Agent's context window fills with entire raw outputs of every tool call (full file contents, entire API responses), degrading reasoning quality on later turns even though the token limit hasn't been hit yet. Fix: Summarize or truncate tool results before appending to state; keep only what later steps actually need, and move anything bulky to persisted memory that can be fetched again on demand.
Symptom: A single "god agent" with 30+ tools spanning unrelated domains (billing, infra, customer messaging) occasionally calls the wrong tool for a superficially similar request. Fix: Split by domain into narrower agents or narrower tool subsets activated per task, rather than exposing the full tool surface on every call.
Symptom: An irreversible action (e.g. deleting a cloud resource, sending a customer email) executes because the agent "decided" the task was done, with no external checkpoint. Fix: Move irreversible tools behind an explicit approval state or a policy layer in the dispatcher, never rely on prompt wording ("ask before deleting") as the only safeguard.
Symptom: Errors from a tool call are swallowed and the agent reports
success anyway.
Fix: Propagate tool errors into the next model turn as explicit
failure content (not silently retried or hidden), and require the loop's
terminal state to distinguish done, failed, and partial.
Task: an internal agent that triages incoming support tickets, drafts a reply, and — only after a human approves — sends it.
Finite-state design:
states:
triage: classify ticket category + urgency (read-only tools: search_kb, get_ticket)
gather_info: pull account/order history if category requires it (read-only tools)
draft_reply: produce a draft reply grounded in gathered context
awaiting_approval: present draft to a human reviewer; no tools available here
send: call send_reply tool (irreversible-write, only reachable from awaiting_approval)
escalate: hand off to a human agent directly (terminal state, no send)
transitions:
triage -> gather_info | escalate
gather_info -> draft_reply | escalate
draft_reply -> awaiting_approval
awaiting_approval -> send | draft_reply (reviewer requests changes)
Loop bound: max 6 state transitions per ticket, 60s timeout per LLM call.
Every transition emits a ticket.state_changed event with ticket id, from
state, to state, and the tool calls made in that state — this is what an
observability dashboard and later
agent-evaluation-and-guardrails
checks consume. The send state is the only place send_reply (an
irreversible-write tool) is even present in the tool list passed to the
model, so a prompt-injection attempt from ticket content cannot cause a
send from an earlier state — the tool literally isn't offered.
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub selvarajmurugesan90/ops-engineering-skills --plugin ai-agent-skills20 skills in this plugin
/agent-bad-response-triage-and-root-cause-classificationGuides triaging a single reported bad, wrong, or harmful agent response: reproducing it deterministically and classifying the root cause into one of five buckets — prompt issue, tool failure, retrieval issue, model behavior change, or genuine edge case — so the fix targets the actual cause instead of the symptom. Use when a user asks to "investigate this bad agent response," "why did the agent say/do that," "triage this reported hallucination/harmful output," "figure out if this is a prompt bug or a model regression," or files an incident about a single problematic agent interaction that needs root-causing before a fix ships.
/agent-cost-and-latency-spike-investigationGuides rapidly triaging a sudden cost or latency spike affecting one specific agent workflow — scoping it, correlating it against recent changes, and applying a fast, safe stopgap — before launching a full optimization pass. Use when a user asks "why did our LLM bill jump overnight," "this one workflow got slow/expensive all of a sudden," "investigate a cost/latency spike," or reports an alert/invoice surprise for a single agent or task type, as distinct from a deliberate, scheduled effort to reduce baseline cost or latency.
/agent-evaluation-and-guardrailsGuides building evaluation harnesses, regression test suites, and runtime guardrails for LLM agents. Use when a user asks to "evaluate this agent," "write test cases for a prompt change," "set up an eval harness," "add guardrails to prevent unsafe output," "detect prompt injection at runtime," or needs to know whether a prompt/model/tool change made an agent better or worse before shipping it.
/agent-tool-call-loop-diagnosis-and-circuit-breakingGuides diagnosing an active or recurring runaway agent tool-call loop and stopping it safely with a bounded retry policy and a hard ceiling — distinct from raising the iteration limit. Use when a user asks to "figure out why the agent is stuck calling the same tool," "safely kill a runaway agent session," "the agent keeps retrying the same failing action," "someone just raised the retry limit and it's still looping," or needs to design a circuit breaker so a stalled agent fails closed instead of burning cost/quota indefinitely.
/agent-tool-use-patternsGuides designing safe, reliable tool/function-calling interfaces and loops for LLM agents. Use when a user asks to "design tool schemas," fix an agent that hallucinates tool calls or arguments, prevent infinite tool-call loops, decide how much autonomy to give an agent's tool use, handle untrusted tool output safely, or add confirmation gates before destructive tool actions.
/code-knowledge-graph-tools-for-ai-agentsCompares GitNexus, Graphify, and CodeGraph — tools that precompute a structural knowledge graph of a codebase and expose it to AI coding agents via MCP, replacing repeated grep/file-read exploration with direct impact-radius, call-chain, and dependency queries. Use when a user asks to "give my coding agent a code graph," "reduce how many tool calls/tokens my agent burns exploring the repo," "set up GitNexus/Graphify/CodeGraph," "find an MCP tool for codebase structure," or is choosing between these three tools based on license, language coverage, or query model.
Other plugins' skills for the same job