Engineering 11 min read Published December 03, 2026

The AI Agent Evaluation Harness: How to Test an Agent Before It Touches Production

Build a deterministic AI agent evaluation harness. Mock external tools with synthetic fixtures, enforce pass thresholds, and block regressions before deploy.

Sarah Chen
Sarah Chen
Lead Systems Architect & AI Reliability Engineer
Share
Architecture diagram of an AI Agent Evaluation Harness showing Trace Input, Synthetic Fixture Mocker intercepting DB and Stripe calls, Assertion and Threshold Gate at 95 percent pass rate, and automated Deploy Gate

CadreGPT deterministic dry-run evaluation pipeline: intercepting mutating tool calls with synthetic fixtures and gating production deployments on quantitative pass thresholds.

Why "Vibe-Checking" Prompts Breaks in Production

Most teams ship changes to an autonomous agent the same way they test a chatbot: an engineer tweaks a system prompt, runs three manual examples in a local notebook, sees plausible outputs, and merges to main.

Within 48 hours, a silent regression surfaces in production:

A one-line prompt edit meant to make customer responses more concise inadvertently caused the agent to skip its `verify_account_ownership` tool call 14% of the time—and invoke `issue_refund` directly with unvalidated parameters.

Manual spot-checks fail because agentic regressions are multi-turn and statistical. Changing one instruction or swapping gpt-4o for a newer model snapshot shifts tool-selection probabilities across dozens of downstream edge cases.

To ship autonomous agents safely, engineering teams need an AI agent evaluation harness—a deterministic dry-run runner that executes every candidate change against a golden test suite before it ever touches a production queue.


Comparing Agent Testing Strategies

Before designing the harness, examine why traditional testing approaches fall short for stateful multi-agent workflows:

DimensionAd-Hoc Prompt Spot-ChecksLive Staging Canary RunsDeterministic Dry-Run Eval Harness
External Side EffectsHigh risk if connected to real toolsMutates staging DBs, webhooks, & APIsZero (100% intercepted via fixtures)
ReproducibilityNon-reproducible manual clicksVulnerable to staging API drift & rate limitsDeterministic replay of exact state
Regression DetectionCatches obvious syntax errors onlySlow feedback; discovered post-mergeCI/CD blocker before merge
Cost per Test RunLow coverage, hidden prod costFull API + external SaaS billing costBounded token cost, zero SaaS fees
Safety / Policy GatesNoneReactive alerting after failureFail-closed threshold enforcement

Architecture of a Production Dry-Run Evaluation Harness

A reliable evaluation harness sits between your agent runtime and external tool connectors. Instead of letting the agent execute real HTTP requests or SQL mutations, the harness swaps the live tool executor for a Synthetic Fixture Mocker and evaluates every turn through an Assertion & Threshold Gate.

typescript
┌───────────────────┐     ┌──────────────────────────────┐     ┌───────────────────────────┐
│  Golden Trace &   │     │   Synthetic Fixture Mocker   │     │ Assertion & Threshold Gate│
│  Prompt Candidate │────▶│  • Intercepts tool calls     │────▶│ • Schema & Zod validity   │
│                   │     │  • Returns mocked JSON/errors│     │ • Tool sequence & budget  │
│  (50+ Scenarios)  │     │  • Records state mutations   │     │ • Pass rate >= 95%        │
└───────────────────┘     └──────────────────────────────┘     └─────────────┬─────────────┘
                                                                             │
                                                               ┌─────────────┴─────────────┐
                                                               ▼                           ▼
                                                       [ PASS: Deploy ]            [ FAIL: Blocked ]

Notice how this builds directly on turn-level execution traces and real-time SSE telemetry: every production failure you capture becomes a permanent regression fixture inside your eval suite.


Step 1: Intercepting Tool Calls with Synthetic Fixtures

Never mock the LLM itself during an evaluation—you are testing how the real model behaves under your new prompt, routing rule, or tool schema. Instead, mock the external environment that the agent interacts with.

In TypeScript, enforce a strict ToolExecutor interface so the agent runtime cannot bypass the gateway:

typescript
// src/evals/fixture-mocker.ts
export interface ToolCallRecord {
  toolName: string;
  args: Record<string, unknown>;
  timestampMs: number;
}

export type FixtureResponse =
  | { status: 'ok'; payload: Record<string, unknown> }
  | { status: 'error'; code: string; message: string };

export class SyntheticFixtureMocker {
  private readonly callLog: ToolCallRecord[] = [];
  private readonly fixtures: Map<string, FixtureResponse[]>;

  constructor(initialFixtures: Record<string, FixtureResponse[]>) {
    this.fixtures = new Map(Object.entries(initialFixtures));
  }

  async execute(toolName: string, args: Record<string, unknown>): Promise<FixtureResponse> {
    this.callLog.push({
      toolName,
      args,
      timestampMs: Date.now(),
    });

    const queue = this.fixtures.get(toolName);
    if (!queue || queue.length === 0) {
      return {
        status: 'error',
        code: 'FIXTURE_EXHAUSTED',
        message: `No synthetic fixture remaining for tool "${toolName}".`,
      };
    }

    // Pop sequential responses so retries and multi-turn mutations behave realistically
    return queue.shift()!;
  }

  getRecordedCalls(): ReadonlyArray<ToolCallRecord> {
    return this.callLog;
  }
}

Why Sequential Fixture Queues Matter

Real tools do not always return the same response twice. By storing an ordered array of FixtureResponse objects per tool, a single dry-run scenario can test retry resilience:

  • Call 1: github_create_pr returns { status: 'error', code: '429_RATE_LIMIT' }.
  • Call 2: github_create_pr returns { status: 'ok', payload: { prNumber: 412 } }.

If the agent panics on the first 429 or enters an infinite loop calling a different mutating tool, the harness catches it immediately without touching GitHub.


Step 2: Writing Deterministic Assertions (Not String Equality)

Checking whether an agent's final summary equals an exact paragraph fails constantly due to harmless phrasing variations. Instead, grade every dry-run execution across four orthogonal assertion layers:

  1. Structural & Schema Validity (Must be 100%): Every tool argument emitted by the model passes strict Zod / JSON Schema validation.
  2. Precondition & Ordering Invariants (Must be 100%): Sensitive tools (e.g., transfer_funds, delete_record) never execute unless a required read/approval tool (verify_identity, request_human_approval) succeeded earlier in getRecordedCalls().
  3. Resource & Token Budgets (Must be 100%): Total turns, tool calls, and token spend stay strictly below hard ceilings.
  4. Semantic Outcome Accuracy (>= 95%): The final structured state or an LLM-as-judge rubric confirms the user's goal was solved.

Here is a clean assertion runner that enforces those invariants:

typescript
// src/evals/assertions.ts
import { ToolCallRecord } from './fixture-mocker';

export interface EvalCase {
  id: string;
  requiredOrder: string[];        // e.g. ['verify_account', 'issue_refund']
  forbiddenTools: string[];       // e.g. ['drop_table']
  maxTokens: number;
  maxToolCalls: number;
}

export interface EvalRunResult {
  caseId: string;
  calls: ReadonlyArray<ToolCallRecord>;
  totalTokens: number;
  schemaErrors: number;
  passedSemanticCheck: boolean;
}

export interface AssertionReport {
  passed: boolean;
  failures: string[];
}

export function evaluateRun(testCase: EvalCase, run: EvalRunResult): AssertionReport {
  const failures: string[] = [];

  if (run.schemaErrors > 0) {
    failures.push(`Schema validation failed ${run.schemaErrors} time(s).`);
  }

  if (run.totalTokens > testCase.maxTokens) {
    failures.push(`Token budget exceeded: ${run.totalTokens} > ${testCase.maxTokens}.`);
  }

  if (run.calls.length > testCase.maxToolCalls) {
    failures.push(`Tool call loop detected: ${run.calls.length} > ${testCase.maxToolCalls}.`);
  }

  const calledNames = run.calls.map((c) => c.toolName);

  for (const forbidden of testCase.forbiddenTools) {
    if (calledNames.includes(forbidden)) {
      failures.push(`Forbidden tool invoked: ${forbidden}.`);
    }
  }

  // Verify required precondition ordering
  let lastIndex = -1;
  for (const requiredTool of testCase.requiredOrder) {
    const idx = calledNames.indexOf(requiredTool, lastIndex + 1);
    if (idx === -1) {
      failures.push(`Missing or out-of-order required tool: ${requiredTool}.`);
      break;
    }
    lastIndex = idx;
  }

  if (!run.passedSemanticCheck) {
    failures.push('Semantic outcome rubric did not pass.');
  }

  return {
    passed: failures.length === 0,
    failures,
  };
}

Step 3: Gating CI/CD Deployments on Pass Thresholds

An evaluation harness only protects production when it blocks bad deploys automatically. Wire the runner into your pull-request pipeline with two distinct severity tiers:

  • Zero-Tolerance Safety Gates (100% Required): Schema violations, forbidden tool calls, or prompt-injection bypasses fail the build on 1 single failure.
  • Behavioral Accuracy Gates (>= 95% Required): Semantic quality and multi-step reasoning scores must clear the suite-wide pass threshold.
typescript
// src/evals/gate.ts
export interface SuiteSummary {
  totalCases: number;
  passedCases: number;
  safetyViolations: number;
}

export function assertDeployGate(summary: SuiteSummary, minPassRate = 0.95): void {
  if (summary.safetyViolations > 0) {
    throw new Error(
      `DEPLOY BLOCKED: ${summary.safetyViolations} safety/schema violation(s) detected.`
    );
  }

  const passRate = summary.totalCases === 0 ? 0 : summary.passedCases / summary.totalCases;
  if (passRate < minPassRate) {
    throw new Error(
      `DEPLOY BLOCKED: Pass rate ${(passRate * 100).toFixed(1)}% is below required ${(
        minPassRate * 100
      ).toFixed(1)}% threshold.`
    );
  }
}

Turning Production Incidents into Permanent Fixtures

The highest-leverage workflow in eval-driven development is the incident-to-fixture loop:

  1. An agent fails on an unexpected customer payload in production.
  2. Export the sanitized execution trace from your observability store.
  3. Strip credentials and PII at the gateway boundary (you can verify your own payloads and code before committing with our zero-retention AI Code Review & Secret Leak Auditor).
  4. Commit the JSON trace as a new EvalCase in tests/evals/golden-traces/.

That failure class can never silently regress again.


Summary: The Dry-Run Checklist Before Every Agent Release

  • [ ] Isolate External Side Effects: Route 100% of tool executions through a synthetic fixture mocker during CI.
  • [ ] Test Failure Modes Explicitly: Include fixtures for HTTP 429 rate limits, 503 timeouts, and malformed third-party JSON responses.
  • [ ] Assert Preconditions, Not Prose: Enforce tool call ordering, Zod schema validity, and token ceilings deterministically.
  • [ ] Fail Closed on Regressions: Require 100% pass on safety invariants and >= 95% overall suite pass rate before promoting prompt or model changes.

Ready to test multi-step agent workflows without risking live production systems? Launch a CadreGPT Dry-Run Sandbox and run deterministic governance checks before your agents ever touch production.

Sarah Chen

Sarah Chen

Verified Enterprise Author

Lead Systems Architect & AI Reliability Engineer

Distributed systems architect focused on formal verification, state-machine orchestration, and deterministic replay debugging for autonomous AI workforces.

Frequently Asked Questions

An AI agent evaluation harness is an automated testing framework that runs an agent against a curated suite of input scenarios and mocked tool responses, then grades the agent’s multi-turn decisions against deterministic assertions (JSON schema validity, tool call ordering, token limits, and expected state outcomes) before deployment.
Related Topics:#AI Agent Evaluation#Dry-Run Testing#Regression Testing#CI/CD for AI#Fixture Mocking#Reliability Engineering
Dry-Run Eval Sandbox

Test Agents Before Production Deploy

Run deterministic dry-run previews with mocked tool fixtures, pass-threshold gates, and $1.00 free starter credit.

Recommended Architectural Deep Dives

Engineering

How to Debug AI Agents with Execution Traces

Master non-deterministic AI agent debugging. Learn how to record turn-level execution traces, capture tool diffs, and create deterministic replay fixtures.

10 min readRead Deep Dive
Engineering

Real-Time SSE Telemetry & Thought Streaming: Architecting Observability for Autonomous Workforces

Architect sub-15ms agent telemetry, thought streaming, and execution diffs using Redis Pub/Sub and Server-Sent Events instead of HTTP polling.

9 min readRead Deep Dive