# Munder Difflin Circuit Breaker Trip Conditions: 7 Runtime Thresholds Explained

> Understand Munder Difflin Circuit Breaker trip conditions. Learn about 7 runtime thresholds like API error storms and budget caps that automate agent states.

- Repository: [Chaitanya Giri/munder-difflin](https://github.com/chaitanyagiri/munder-difflin)
- Tags: deep-dive
- Published: 2026-08-22

---

**The Munder Difflin Circuit Breaker monitors seven distinct trip conditions—including repeated tool loops, API error storms, token velocity spikes, and budget caps—to automatically escalate agents from healthy through steering to constrained or stopped states.**

The `chaitanyagiri/munder-difflin` repository implements a production-grade circuit breaker for AI agent orchestration. Located in [`src/main/breaker.ts`](https://github.com/chaitanyagiri/munder-difflin/blob/main/src/main/breaker.ts), the `CircuitBreaker` class evaluates runtime signals every heartbeat through its `evaluate()` method, triggering protective measures when specific operational thresholds are breached.

## The Seven Core Trip Conditions

The `evaluate()` method in [`src/main/breaker.ts`](https://github.com/chaitanyagiri/munder-difflin/blob/main/src/main/breaker.ts) checks seven independent conditions that signal degraded agent behavior. When any condition evaluates true, the breaker returns a `tripping` flag with a human-readable reason, initiating escalation up the protection ladder.

### 1. Repeated Identical Tool Calls

The breaker detects infinite loops by tracking consecutive identical tool invocations. At lines 94-96, the implementation compares `s.repeatCount` against `cfg.repeatedToolLimit`, triggering when an agent executes the **same tool with identical inputs 8 consecutive times** (default threshold). This prevents runaway recursive searches or hallucinated tool loops.

### 2. API Error Storms

Consecutive failure states without successful operations indicate systemic issues. The breaker tracks `s.errorCount` and compares against `cfg.errorStormLimit` at lines 98-100, tripping after **5 consecutive `api_error` or retry events**. This protects against cascading failures when external APIs degrade.

### 3. Per-Agent Token Cap

Individual budget enforcement occurs when an agent's cumulative consumption exceeds its allocation. The logic at lines 103-105 calculates total tokens via `tokensOf(input.sample)` and validates against the agent-specific `perAgentCap` configured in `agentTokenCaps`. This threshold is user-defined per agent identity.

### 4. Floor-Wide Cost Cap

Cross-agent budget protection triggers when the `isTopSpender` flag is true and total USD expenditure exceeds `costCapUsd`. Lines 108-110 implement this check, ensuring the highest-spending agent faces constraints first when global budgets are exceeded, preventing floor-wide cost overruns.

### 5. Floor-Wide Token Cap

Complementary to cost caps, this condition monitors aggregate token consumption. When `isTopTokenSpender` is active and total usage exceeds `costCapTokens` (lines 112-114), the breaker constrains the highest-volume agent to protect infrastructure quotas across the entire agent floor.

### 6. Token Velocity Spike

Rapid output generation indicates potential runaway generation or token stuffing attacks. The breaker calculates velocity as **Δoutput tokens / Δminutes**, comparing against `cfg.tokenVelocityPerMin` at lines 124-126. The default threshold of **60,000 tokens per minute** catches exponential generation curves before they overwhelm systems.

### 7. No-Progress Conditions

Stagnation detection identifies agents consuming tokens without advancing coordination state. When `!input.progressing && !toolActive` remains true across beats, the breaker increments `s.noProgressBeats` (lines 132-138), escalating after **2 consecutive beats** of generation without file-mtime progress or tool activity.

## Implementation and Configuration

The circuit breaker consumes `AgentUsageSample` data defined in [`src/main/usage.ts`](https://github.com/chaitanyagiri/munder-difflin/blob/main/src/main/usage.ts) and runtime configuration from [`src/main/config.ts`](https://github.com/chaitanyagiri/munder-difflin/blob/main/src/main/config.ts). Each heartbeat invokes `breaker.tick(inputs, Date.now())`, returning an array of decisions requiring corrective action.

```typescript
import { CircuitBreaker } from './src/main/breaker';
import { getConfig } from './src/main/config';

// Initialize with live configuration getter
const breaker = new CircuitBreaker(() => getConfig());

// Collect samples from all agents each heartbeat
const inputs = [
  {
    agentId: 'agent-42',
    sample: {
      input: 1200,
      output: 8000,
      cacheRead: 300,
      cacheCreation: 200,
      usd: 0.45,
      ts: Date.now()
    },
    progressing: true  // True when coordination files changed recently
  }
];

// Evaluate current tick
const decisions = breaker.tick(inputs, Date.now());

// Process escalations
for (const d of decisions) {
  if (d.action !== 'none') {
    console.log(`[Breaker] ${d.state.agentId} → ${d.state.level}: ${d.state.reason}`);
  }
}

```

To manually trigger the repeated-tool condition for testing, use `recordToolUse()`:

```typescript
// Simulate 8 identical calls to trigger looping detection
for (let i = 0; i < 8; i++) {
  breaker.recordToolUse('agent-42', 'search', { query: 'foo' });
}
// Next tick() will return: "looping: 8× identical tool call (search)"

```

## Escalation Ladder and Compaction Exemptions

The breaker implements a four-level escalation ladder: **healthy → steering → constrained → stopped**. The system escalates one level per violating beat and recovers one level per healthy beat.

During compaction operations, indicated by `s.compactingUntil`, the velocity spike and no-progress trip arms are temporarily disabled at lines 78-81. This prevents false positives when the system intentionally pauses coordination file updates during maintenance windows.

The optional `hardStop` configuration flag modifies the maximum reachable level from `constrained` (throttled operation) to `stopped` (complete termination), enabling irreversible circuit breaking for critical budget or safety violations.

## Summary

- **Repeated tool loops** trigger after 8 identical consecutive calls (lines 94-96).
- **API error storms** activate at 5 consecutive failures (lines 98-100).
- **Per-agent caps** enforce individual token budgets (lines 103-105).
- **Floor-wide caps** constrain top spenders by cost (lines 108-110) or tokens (lines 112-114).
- **Velocity spikes** trip at 60,000 tokens/minute (lines 124-126).
- **No-progress states** escalate after 2 stagnant beats (lines 132-138).
- **Compaction exemptions** temporarily disable velocity and progress checks to avoid false positives.

## Frequently Asked Questions

### What is the default threshold for repeated tool calls in the Munder Difflin Circuit Breaker?

The default threshold is **8 identical consecutive calls**, configurable via the `repeatedToolLimit` parameter in the breaker configuration. This detects when an agent enters a hallucinated tool loop, executing the same function with identical arguments without progressing toward the goal.

### How does the circuit breaker handle temporary compaction operations?

While `s.compactingUntil` is set (lines 78-81 in [`src/main/breaker.ts`](https://github.com/chaitanyagiri/munder-difflin/blob/main/src/main/breaker.ts)), the token velocity and no-progress trip conditions are temporarily exempted from evaluation. This prevents false positives during intentional maintenance windows when coordination file updates are paused but token generation continues.

### Can the circuit breaker fully terminate an agent, or does it only throttle performance?

The breaker supports both throttling and termination through the **escalation ladder**. By default, the maximum level is `constrained` (throttled operation). However, when the `hardStop` flag is enabled in the configuration, the breaker can escalate to the `stopped` level, triggering irreversible agent termination rather than mere rate limiting.

### Where are the trip condition thresholds configured in the source code?

Thresholds are defined in [`src/main/config.ts`](https://github.com/chaitanyagiri/munder-difflin/blob/main/src/main/config.ts) and consumed by [`src/main/breaker.ts`](https://github.com/chaitanyagiri/munder-difflin/blob/main/src/main/breaker.ts). Key parameters include `repeatedToolLimit` (default 8), `errorStormLimit` (default 5), `tokenVelocityPerMin` (default 60000), and user-defined caps `agentTokenCaps`, `costCapUsd`, and `costCapTokens`. The actual evaluation logic resides in the `evaluate()` method at lines 94-138 of [`src/main/breaker.ts`](https://github.com/chaitanyagiri/munder-difflin/blob/main/src/main/breaker.ts).