Architecture
A governed agent architecture strictly separates probabilistic model reasoning (proposing plans, search queries, and structured tool arguments) from a deterministic application control plane that enforces hard turn/spend budgets, per-call parameter authorization, brokered short-lived credentials, idempotent checkpoint recovery, and independent postcondition verification before terminating any run.
Prototype autonomous agents fail in production along predictable systemic axes whenever prompts hold ambient secrets and unconstrained retry authority: hallucinated repetitive search loops exhaust token budgets without advancing task progress (oscillation failure), indirect prompt injections embedded in tool outputs hijack downstream write capabilities (confused-deputy failure), and mid-flight network crashes trigger duplicate non-idempotent API mutations (billing/ledger corruption). Governing execution through deterministic state-machine guardrails contains blast radius unconditionally even under adversarial inputs.
ReAct Agent State Machine (Thought → Action → Tool → Observation)
1. Deterministic State Boundaries vs Probabilistic Proposals
| Architectural Layer | Owner (Deterministic vs LLM) | Enforced Invariants | Failure Contained |
|---|---|---|---|
| Planner / Next-Action Proposal | Probabilistic LLM | Constrained JSON Schema (additionalProperties: false) | Eliminates malformed argument syntax |
| Budget & Loop Breaker | Deterministic Harness | Hard max_steps, max_usd, deadline_ms, repeated-call fingerprint check | Halts runaway infinite loops cleanly |
Policy Enforcement Point (PEP) | Deterministic Broker | Signed OAuth session identity + argument realpath/allowlist validation | Stops prompt-injected privilege escalation |
| Checkpointing & Side-Effect Log | Deterministic Store (Postgres) | Idempotency keys written pre-dispatch (PENDING -> COMMITTED) | Prevents duplicate charges/mutations on resume |
| Postcondition Verifier | Deterministic Oracle / Test | Primary DB/CI/state read confirms real external change (not LLM prose) | Rejects premature hallucinated success reports |
Worked Runaway Loop Containment Calculation
Consider a coding agent operating in a 32-turn ReAct loop feeding cumulative codebase files (25,000 tokens initial + 2,500 appended tool output per turn). Without loop compaction or turn caps:
- Cumulative uncached input tokens over turns: . At turns, input consumption totals
362,500tokens (\$1.09@\$3/1M); left unguarded to turns during a build error oscillation loop, consumption explodes quadratically to2,950,000tokens (\$8.85per failed session)! - Enforcing hard budget bounds (
max_turns = 12,repeated_call_limit = 2, truncated tool output<= 4,000 chars) paired with explicit context compaction slashes worst-case stalled burn by over8xcleanly.
2. Workflow DAGs vs Autonomous ReAct Trade-Offs
- Explicit Workflow Graphs (
LangGraph / DAG): Deterministic state nodes dictate fixed sequential control (Classify -> Retrieve -> Verify -> Escalate), keeping latency tight, audit trails reproducible, and tool scope tightly bound per node. Choose explicit graphs whenever domain SOP steps are known up front. - Bounded Autonomous Loops (
Codex / Coding Harnesses): Let the LLM select tools dynamically within a sandboxed loop only when open-ended discovery paths (debugging unfamiliar stack traces, multi-file refactors) cannot be enumerated statically, backed by container isolation, digest-bound HITL approvals for remote side effects, and hard stop predicates.
3. Bounded Agent Controller with Idempotency & Oscillation Guard in TypeScript
typescriptimport crypto from "node:crypto";export interface AgentBudgetEnvelope {maxSteps: number;maxToolCalls: number;maxCostUsd: number;deadlineEpochMs: number;}export interface ToolProposal {toolName: string;normalizedArgs: Record<string, unknown>;blastRadius: "read" | "write_idempotent" | "mutate_irreversible";}export class GovernedAgentController {private readonly seenFingerprints = new Map<string, number>();private steps = 0;private toolCalls = 0;private spentUsd = 0;constructor(private readonly budget: AgentBudgetEnvelope,private readonly allowedTools: Set<string>,) {}public authorizeAndTrack(proposal: ToolProposal, approvalDigest?: string): string {if (Date.now() > this.budget.deadlineEpochMs) throw new Error("HALTS_DEADLINE_EXCEEDED");if (++this.steps > this.budget.maxSteps) throw new Error("HALTS_MAX_STEPS_EXCEEDED");if (++this.toolCalls > this.budget.maxToolCalls) throw new Error("HALTS_MAX_TOOL_CALLS");if (this.spentUsd > this.budget.maxCostUsd) throw new Error("HALTS_COST_BUDGET_EXCEEDED");if (!this.allowedTools.has(proposal.toolName)) throw new Error(`PEP_DENY_${proposal.toolName}`);const canonicalPayload = JSON.stringify({ tool: proposal.toolName, args: proposal.normalizedArgs });const fp = crypto.createHash("sha256").update(canonicalPayload).digest("hex");const hits = (this.seenFingerprints.get(fp) ?? 0) + 1;this.seenFingerprints.set(fp, hits);if (hits > 2) throw new Error("HALTS_OSCILLATION_LOOP_DETECTED");if (proposal.blastRadius === "mutate_irreversible" && approvalDigest !== fp) {throw new Error("HITL_APPROVAL_DIGEST_MISMATCH");}return fp; // Used as deterministic idempotency key in transactional store}}
Decisions
| Decision | Required evidence | Review trigger |
|---|---|---|
| Separate probabilistic model proposals cleanly from out-of-model RBAC policy & payload digest checks. | Negative IDOR + indirect prompt injection security suite pass | Adding new write or financial tool permissions |
| Persist pre-flight transactional idempotency keys ahead of every side-effect HTTP/DB mutation. | Timeout & duplicate retry replay tests showing single side effect | Changing upstream payment/ERP client timeouts |
Alternatives and trade-offs
- Deterministic State Machines (
StateGraph+ Policy Hooks) vs. Autonomous Free-Form ReAct: Governed state machines trade open-ended conversational autonomy for verifiable retry ceilings, audit logs, and digest-locked human approvals on state-changing tool boundaries.
Failure modes
- Treating model visibility of a tool schema as authorization: Allowing callers with restricted scopes to invoke privileged tools simply because the system prompt included the tool definition breaks tenant RBAC on the very first prompt injection.
- Missing payload binding on human approval gates: Approving
"Send refund email"broadly allows an injected parameter override on turn 2 ("amount: $50,000"instead of"$50") unless approval signatures bind over the exact hashed canonical JSON payload. - Retrying ambiguous timeouts without idempotency keys: When a Stripe/ERP write times out after committing upstream, naive agent retries charge users twice! Record idempotency tokens persistently before firing side-effect HTTP calls.
- Self-graded task completion: Accepting
"I fixed all tests and verified deployment"blindly in final output instead of running real test suites and verifying DB/HTTP state independently.
Operational checklist
- Every agent session instantiates explicit turn, tool-call, USD spend, and wall-clock deadline limits.
- Policy checks verify server-injected caller identity + normalized payload bounds out-of-model.
- All write tools persist pre-flight idempotency keys and track
PENDING | COMMITTED | COMPENSATEDstates. - Irreversible actions require digest-bound human approval tokens tied strictly to payload hashes.
- Terminal completion states execute independent deterministic postcondition verification (
tests pass,DB state matches).
Connected Practice
- Labs: /labs/agent-loop-tool-selection, /labs/prompt-injection-threat-model
- Projects: /projects/governed-agent-reliability
- System breakdowns: /systems/inside-openai-codex
Sources
- Governed agent primary references:
anthropic-trustworthy-agents,nist-ai-rmf,owasp-llm,openai-agent-builder-safety
Debug live agent loops & tool-call failure recovery
Inject schema mismatches, 429 rate limits, and timeout circuit breakers inside the ReAct Agent Loop Debugger — or query this knowledge inside Cursor/Claude via MCP.
Subscribe to Engineering Briefings
Join AI systems engineers receiving architecture teardowns, benchmark notes, and new simulator releases. Unsubscribe anytime.
