FullStack AI Hub
Studio
Reference architecture

Governed Agent Architecture

Production control-plane architecture for AI agents: bounded ReAct/DAG loops, per-call tool authorization, brokered credentials, checkpoints, and postcondition verification.

18 minVerified 2026-11-254 primary sources
Governed Agent Architecture
On This Page

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.

Intent and policy
Validated request
Controlled execution
Independent verification
Telemetry and response
Conceptual teaching model synthesized from:Building Effective AI AgentsTrustworthy Agents in PracticeModel Context Protocol Architecture and Tools SpecificationOAuth 2.0 Security Best Current Practice

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)

Quadrant 1THOUGHT● CURRENT
Quadrant 2ACTIONWAITING
Quadrant 3TOOL_EXECUTIONWAITING
Quadrant 4OBSERVATIONWAITING
Agent Execution Trace (Step 1/6)250 Tokens in Context
THOUGHTUser requested cluster health report. Need to inspect node status table.
Current PhaseTHOUGHT
Total Steps0 / 6
Accumulated Tokens250 tokens
Loop TrapNormal

1. Deterministic State Boundaries vs Probabilistic Proposals

Architectural LayerOwner (Deterministic vs LLM)Enforced InvariantsFailure Contained
Planner / Next-Action ProposalProbabilistic LLMConstrained JSON Schema (additionalProperties: false)Eliminates malformed argument syntax
Budget & Loop BreakerDeterministic HarnessHard max_steps, max_usd, deadline_ms, repeated-call fingerprint checkHalts runaway infinite loops cleanly
Policy Enforcement Point (PEP)Deterministic BrokerSigned OAuth session identity + argument realpath/allowlist validationStops prompt-injected privilege escalation
Checkpointing & Side-Effect LogDeterministic Store (Postgres)Idempotency keys written pre-dispatch (PENDING -> COMMITTED)Prevents duplicate charges/mutations on resume
Postcondition VerifierDeterministic Oracle / TestPrimary 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 NN turns: ∑t=1N(25,000+2,500(t−1))\sum_{t=1}^{N} (25,000 + 2,500(t - 1)). At N=10N = 10 turns, input consumption totals 362,500 tokens (\$1.09 @ \$3/1M); left unguarded to N=40N = 40 turns during a build error oscillation loop, consumption explodes quadratically to 2,950,000 tokens (\$8.85 per 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 over 8x cleanly.
Architecture claim
Representative test
Production signal
Decision gate
Review or rollback
Conceptual teaching model synthesized from:Building Effective AI AgentsTrustworthy Agents in PracticeModel Context Protocol Architecture and Tools SpecificationOAuth 2.0 Security Best Current Practice

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

typescript
import 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

DecisionRequired evidenceReview trigger
Separate probabilistic model proposals cleanly from out-of-model RBAC policy & payload digest checks.Negative IDOR + indirect prompt injection security suite passAdding 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 effectChanging 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 | COMPENSATED states.
  • 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

Sources

  • Governed agent primary references: anthropic-trustworthy-agents, nist-ai-rmf, owasp-llm, openai-agent-builder-safety
Agent Runtime Workbench

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.

Weekly Engineering Dispatch

Subscribe to Engineering Briefings

Join AI systems engineers receiving architecture teardowns, benchmark notes, and new simulator releases. Unsubscribe anytime.