loopcircuit 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.4
2
+ Name: loopcircuit
3
+ Version: 0.1.0
4
+ Summary: Autonomous agent loop governor, circuit-breaker, and anti-thrashing engine for AI agents
5
+ Author: loopcircuit Contributors
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/VikasPatel22/loopcircuit
8
+ Project-URL: Repository, https://github.com/VikasPatel22/loopcircuit.git
9
+ Keywords: agent,circuit-breaker,loop-detection,ai-safety,reliability,llm-governance
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+
21
+ # loopcircuit
22
+
23
+ Autonomous agent loop governor, circuit-breaker, and anti-thrashing engine for AI agents and LLM execution pipelines.
24
+
25
+ Zero hard dependencies. Framework-agnostic. Runs in sub-millisecond execution time.
26
+
27
+ ---
28
+
29
+ ## The Problem in 2026
30
+
31
+ Frontier AI agents (Claude Code, Cursor, AutoGen, CrewAI, or custom `while` loops) frequently suffer from **runaway execution traps**:
32
+ 1. **Exact Repetition**: Invoking the exact same broken tool with identical arguments 20 times in a row.
33
+ 2. **Ping-Pong Oscillation**: Flip-flopping between two tools (e.g. `edit_file` ➔ `run_test` ➔ `revert` ➔ `edit_file`) without making forward progress.
34
+ 3. **Error Vortices**: Trapped repeatedly hitting the same underlying exception.
35
+ 4. **Budget Blowouts**: Burning through $50+ in LLM API credits overnight while unsupervised.
36
+
37
+ `loopcircuit` provides a deterministic safety net and circuit breaker that halts runaway loops and dynamically injects surgical interventions to snap agents back on track.
38
+
39
+ ---
40
+
41
+ ## Key Capabilities
42
+
43
+ - **Cycle & Oscillation Detection**: Identifies periodic cycles of length 1 (repetition), length 2 (ping-pong), and length 3+ (wandering) via canonical argument hashing.
44
+ - **Error Vortex Recognition**: Normalizes stack traces (stripping memory addresses, line numbers, and timestamps) to detect recurring root causes.
45
+ - **Multi-Policy Actions**:
46
+ - `raise`: Immediately trips and raises structured exceptions (`ThrashDetectedError`, `BudgetExceededError`, `MaxStepsExceededError`).
47
+ - `intervene`: Injects a structured system intervention prompt directly into the agent's context to mandate a strategy change.
48
+ - `warn`: Half-opens the circuit, logging telemetry while allowing execution to proceed with probation.
49
+ - **Financial & Token Caps**: Hard limits on dollar costs and cumulative token consumption.
50
+ - **Drop-in `@governed` Decorator & Context Manager**: Works seamlessly across sync and async loops.
51
+
52
+ ---
53
+
54
+ ## Installation
55
+
56
+ ```bash
57
+ pip install loopcircuit
58
+ ```
59
+
60
+ ---
61
+
62
+ ## Quickstart
63
+
64
+ ### As an Interactive Circuit Breaker
65
+
66
+ ```python
67
+ from loopcircuit import CircuitBreaker
68
+
69
+ # Configure safety thresholds
70
+ breaker = CircuitBreaker(
71
+ max_steps=20,
72
+ max_cost_usd=2.00,
73
+ repetition_threshold=3,
74
+ on_trip="intervene" # Injects corrective prompt instead of crashing
75
+ )
76
+
77
+ for step in agent_execution:
78
+ # Record each tool invocation
79
+ intervention = breaker.record(
80
+ tool_name=step.tool,
81
+ arguments=step.args,
82
+ result=step.output,
83
+ cost_usd=step.cost
84
+ )
85
+
86
+ if intervention.is_warning:
87
+ # Feed the generated pattern-breaking prompt back to the LLM
88
+ step.inject_system_prompt(intervention.recovery_prompt)
89
+ ```
90
+
91
+ ---
92
+
93
+ ### As a Decorator
94
+
95
+ ```python
96
+ from loopcircuit import governed
97
+
98
+ @governed(max_steps=15, max_cost_usd=1.00, on_trip="raise")
99
+ def run_agent_loop(task: str, breaker=None):
100
+ while True:
101
+ action = planner(task)
102
+ result = execute(action)
103
+ breaker.record(action.tool, action.args, result=result)
104
+ ```
105
+
106
+ ---
107
+
108
+ ## CLI Trace Auditor
109
+
110
+ Replay and audit agent trace logs (`.jsonl`) to detect loops and calculate spend:
111
+
112
+ ```bash
113
+ loopcircuit audit agent_run.jsonl
114
+ loopcircuit audit agent_run.jsonl --max-cost 2.50 --json
115
+ ```
116
+
117
+ ---
118
+
119
+ ## License
120
+
121
+ MIT License.
@@ -0,0 +1,101 @@
1
+ # loopcircuit
2
+
3
+ Autonomous agent loop governor, circuit-breaker, and anti-thrashing engine for AI agents and LLM execution pipelines.
4
+
5
+ Zero hard dependencies. Framework-agnostic. Runs in sub-millisecond execution time.
6
+
7
+ ---
8
+
9
+ ## The Problem in 2026
10
+
11
+ Frontier AI agents (Claude Code, Cursor, AutoGen, CrewAI, or custom `while` loops) frequently suffer from **runaway execution traps**:
12
+ 1. **Exact Repetition**: Invoking the exact same broken tool with identical arguments 20 times in a row.
13
+ 2. **Ping-Pong Oscillation**: Flip-flopping between two tools (e.g. `edit_file` ➔ `run_test` ➔ `revert` ➔ `edit_file`) without making forward progress.
14
+ 3. **Error Vortices**: Trapped repeatedly hitting the same underlying exception.
15
+ 4. **Budget Blowouts**: Burning through $50+ in LLM API credits overnight while unsupervised.
16
+
17
+ `loopcircuit` provides a deterministic safety net and circuit breaker that halts runaway loops and dynamically injects surgical interventions to snap agents back on track.
18
+
19
+ ---
20
+
21
+ ## Key Capabilities
22
+
23
+ - **Cycle & Oscillation Detection**: Identifies periodic cycles of length 1 (repetition), length 2 (ping-pong), and length 3+ (wandering) via canonical argument hashing.
24
+ - **Error Vortex Recognition**: Normalizes stack traces (stripping memory addresses, line numbers, and timestamps) to detect recurring root causes.
25
+ - **Multi-Policy Actions**:
26
+ - `raise`: Immediately trips and raises structured exceptions (`ThrashDetectedError`, `BudgetExceededError`, `MaxStepsExceededError`).
27
+ - `intervene`: Injects a structured system intervention prompt directly into the agent's context to mandate a strategy change.
28
+ - `warn`: Half-opens the circuit, logging telemetry while allowing execution to proceed with probation.
29
+ - **Financial & Token Caps**: Hard limits on dollar costs and cumulative token consumption.
30
+ - **Drop-in `@governed` Decorator & Context Manager**: Works seamlessly across sync and async loops.
31
+
32
+ ---
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ pip install loopcircuit
38
+ ```
39
+
40
+ ---
41
+
42
+ ## Quickstart
43
+
44
+ ### As an Interactive Circuit Breaker
45
+
46
+ ```python
47
+ from loopcircuit import CircuitBreaker
48
+
49
+ # Configure safety thresholds
50
+ breaker = CircuitBreaker(
51
+ max_steps=20,
52
+ max_cost_usd=2.00,
53
+ repetition_threshold=3,
54
+ on_trip="intervene" # Injects corrective prompt instead of crashing
55
+ )
56
+
57
+ for step in agent_execution:
58
+ # Record each tool invocation
59
+ intervention = breaker.record(
60
+ tool_name=step.tool,
61
+ arguments=step.args,
62
+ result=step.output,
63
+ cost_usd=step.cost
64
+ )
65
+
66
+ if intervention.is_warning:
67
+ # Feed the generated pattern-breaking prompt back to the LLM
68
+ step.inject_system_prompt(intervention.recovery_prompt)
69
+ ```
70
+
71
+ ---
72
+
73
+ ### As a Decorator
74
+
75
+ ```python
76
+ from loopcircuit import governed
77
+
78
+ @governed(max_steps=15, max_cost_usd=1.00, on_trip="raise")
79
+ def run_agent_loop(task: str, breaker=None):
80
+ while True:
81
+ action = planner(task)
82
+ result = execute(action)
83
+ breaker.record(action.tool, action.args, result=result)
84
+ ```
85
+
86
+ ---
87
+
88
+ ## CLI Trace Auditor
89
+
90
+ Replay and audit agent trace logs (`.jsonl`) to detect loops and calculate spend:
91
+
92
+ ```bash
93
+ loopcircuit audit agent_run.jsonl
94
+ loopcircuit audit agent_run.jsonl --max-cost 2.50 --json
95
+ ```
96
+
97
+ ---
98
+
99
+ ## License
100
+
101
+ MIT License.
@@ -0,0 +1,43 @@
1
+ """
2
+ loopcircuit: Enterprise-grade autonomous agent circuit breaker and loop governor.
3
+ """
4
+
5
+ from loopcircuit.circuit import CircuitBreaker
6
+ from loopcircuit.detector import canonical_action_hash, normalize_error_signature
7
+ from loopcircuit.exceptions import (
8
+ BudgetExceededError,
9
+ CircuitTrippedError,
10
+ ErrorVortexError,
11
+ LoopCircuitError,
12
+ MaxStepsExceededError,
13
+ ThrashDetectedError,
14
+ )
15
+ from loopcircuit.governor import governed
16
+ from loopcircuit.types import (
17
+ ActionRecord,
18
+ CircuitMetrics,
19
+ CircuitState,
20
+ Intervention,
21
+ ThrashType,
22
+ )
23
+
24
+ __version__ = "0.1.0"
25
+ __author__ = "Vikas Patel"
26
+
27
+ __all__ = [
28
+ "CircuitBreaker",
29
+ "governed",
30
+ "CircuitState",
31
+ "ThrashType",
32
+ "ActionRecord",
33
+ "Intervention",
34
+ "CircuitMetrics",
35
+ "LoopCircuitError",
36
+ "CircuitTrippedError",
37
+ "ThrashDetectedError",
38
+ "BudgetExceededError",
39
+ "MaxStepsExceededError",
40
+ "ErrorVortexError",
41
+ "canonical_action_hash",
42
+ "normalize_error_signature",
43
+ ]
@@ -0,0 +1,270 @@
1
+ """Enterprise CircuitBreaker engine for autonomous agent loop governance."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from typing import Any, Dict, List, Optional, Tuple
7
+
8
+ from loopcircuit.detector import ThrashDetector, canonical_action_hash
9
+ from loopcircuit.exceptions import (
10
+ BudgetExceededError,
11
+ CircuitTrippedError,
12
+ ErrorVortexError,
13
+ MaxStepsExceededError,
14
+ ThrashDetectedError,
15
+ )
16
+ from loopcircuit.intervention import generate_recovery_prompt
17
+ from loopcircuit.types import (
18
+ ActionRecord,
19
+ CircuitMetrics,
20
+ CircuitState,
21
+ Intervention,
22
+ ThrashType,
23
+ )
24
+
25
+
26
+ class CircuitBreaker:
27
+ """
28
+ Enterprise-grade, zero-dependency circuit breaker and reliability governor for AI agent loops.
29
+ Protects against infinite loops, oscillating state traps, error cascades, and budget blowouts.
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ max_steps: int = 30,
35
+ max_cost_usd: float = 5.00,
36
+ max_tokens: int = 200_000,
37
+ repetition_threshold: int = 3,
38
+ oscillation_threshold: int = 2,
39
+ max_consecutive_errors: int = 3,
40
+ on_trip: str = "raise", # "raise", "intervene", "warn", "silent"
41
+ window_size: int = 15,
42
+ ) -> None:
43
+ """
44
+ Args:
45
+ max_steps: Maximum allowable agent iterations before tripping (default: 30).
46
+ max_cost_usd: Hard financial spend ceiling in USD (default: $5.00).
47
+ max_tokens: Cumulative token consumption threshold (default: 200,000).
48
+ repetition_threshold: Number of identical consecutive tool calls to trip (default: 3).
49
+ oscillation_threshold: Number of repeated 2-4 step cycles to trip (default: 2).
50
+ max_consecutive_errors: Consecutive identical error signatures to trip (default: 3).
51
+ on_trip: Action policy when breaker trips ("raise", "intervene", "warn", "silent").
52
+ window_size: History depth for cyclic detection.
53
+ """
54
+ self.max_steps = max_steps
55
+ self.max_cost_usd = max_cost_usd
56
+ self.max_tokens = max_tokens
57
+ self.on_trip = on_trip
58
+
59
+ self.detector = ThrashDetector(
60
+ repetition_threshold=repetition_threshold,
61
+ oscillation_threshold=oscillation_threshold,
62
+ max_consecutive_errors=max_consecutive_errors,
63
+ window_size=window_size,
64
+ )
65
+
66
+ self._state = CircuitState.CLOSED
67
+ self._step_counter = 0
68
+ self._total_cost_usd = 0.0
69
+ self._total_tokens = 0
70
+ self._thrash_events_count = 0
71
+ self._interventions_count = 0
72
+ self._last_intervention: Optional[Intervention] = None
73
+ self._history: List[ActionRecord] = []
74
+ self._violations: List[Dict[str, Any]] = []
75
+
76
+ @property
77
+ def state(self) -> CircuitState:
78
+ return self._state
79
+
80
+ @property
81
+ def is_healthy(self) -> bool:
82
+ return self._state in (CircuitState.CLOSED, CircuitState.HALF_OPEN)
83
+
84
+ @property
85
+ def is_tripped(self) -> bool:
86
+ return self._state == CircuitState.OPEN
87
+
88
+ def record(
89
+ self,
90
+ tool_name: str,
91
+ arguments: Optional[Dict[str, Any]] = None,
92
+ result: Any = None,
93
+ error: Optional[str] = None,
94
+ cost_usd: float = 0.0,
95
+ tokens_used: int = 0,
96
+ ) -> Intervention:
97
+ """
98
+ Records an agent action step, updates financial and step telemetry, and evaluates
99
+ cycle and loop health. Returns an Intervention indicating whether the agent should halt
100
+ or receive a corrective prompt.
101
+
102
+ Args:
103
+ tool_name: Name of the invoked tool or action.
104
+ arguments: Tool parameters dictionary.
105
+ result: Return value or observation from the action.
106
+ error: Error message string if the action threw an exception.
107
+ cost_usd: Financial cost incurred by this step (e.g. LLM API cost).
108
+ tokens_used: Tokens consumed by this step.
109
+
110
+ Returns:
111
+ Intervention decision with status, thrash type, and recovery prompt.
112
+ """
113
+ self._step_counter += 1
114
+ self._total_cost_usd += max(0.0, cost_usd)
115
+ self._total_tokens += max(0, tokens_used)
116
+ now = time.time()
117
+
118
+ args = arguments or {}
119
+ a_hash = canonical_action_hash(tool_name, args)
120
+
121
+ record = ActionRecord(
122
+ step_index=self._step_counter,
123
+ tool_name=tool_name,
124
+ arguments=args,
125
+ result=result,
126
+ error=error,
127
+ cost_usd=cost_usd,
128
+ tokens_used=tokens_used,
129
+ timestamp=now,
130
+ action_hash=a_hash,
131
+ )
132
+
133
+ self._history.append(record)
134
+ self.detector.record_action(record)
135
+
136
+ # 1. Budget Checks
137
+ if self._total_cost_usd > self.max_cost_usd:
138
+ return self._handle_trip(
139
+ ThrashType.BUDGET_EXCEEDED,
140
+ f"Financial budget exceeded: ${self._total_cost_usd:.4f} > ${self.max_cost_usd:.4f}",
141
+ {"cost_usd": self._total_cost_usd, "max_cost_usd": self.max_cost_usd},
142
+ BudgetExceededError,
143
+ )
144
+
145
+ if self._total_tokens > self.max_tokens:
146
+ return self._handle_trip(
147
+ ThrashType.BUDGET_EXCEEDED,
148
+ f"Token budget exceeded: {self._total_tokens} > {self.max_tokens} tokens",
149
+ {"tokens": self._total_tokens, "max_tokens": self.max_tokens},
150
+ BudgetExceededError,
151
+ )
152
+
153
+ # 2. Step Limit Check
154
+ if self._step_counter > self.max_steps:
155
+ return self._handle_trip(
156
+ ThrashType.STEP_LIMIT_EXCEEDED,
157
+ f"Execution step limit exceeded: {self._step_counter} > {self.max_steps} steps",
158
+ {"steps": self._step_counter, "max_steps": self.max_steps},
159
+ MaxStepsExceededError,
160
+ )
161
+
162
+ # 3. Thrash & Loop Checks
163
+ has_thrashed, thrash_type, reason, details = self.detector.detect_thrash()
164
+ if has_thrashed and thrash_type:
165
+ exc_class = ErrorVortexError if thrash_type == ThrashType.ERROR_VORTEX else ThrashDetectedError
166
+ return self._handle_trip(thrash_type, reason, details, exc_class)
167
+
168
+ # Healthy continuation
169
+ self._state = CircuitState.CLOSED
170
+ return Intervention(should_trip=False, is_warning=False)
171
+
172
+ def _handle_trip(
173
+ self,
174
+ thrash_type: ThrashType,
175
+ reason: str,
176
+ details: Dict[str, Any],
177
+ exc_class: type[CircuitTrippedError],
178
+ ) -> Intervention:
179
+ self._thrash_events_count += 1
180
+ prompt = generate_recovery_prompt(thrash_type, details)
181
+
182
+ violation = {
183
+ "step": self._step_counter,
184
+ "thrash_type": thrash_type.value,
185
+ "reason": reason,
186
+ "details": details,
187
+ }
188
+ self._violations.append(violation)
189
+
190
+ if self.on_trip == "raise":
191
+ self._state = CircuitState.OPEN
192
+ intervention = Intervention(
193
+ should_trip=True,
194
+ thrash_type=thrash_type,
195
+ reason=reason,
196
+ recovery_prompt=prompt,
197
+ details=details,
198
+ )
199
+ self._last_intervention = intervention
200
+ raise exc_class(
201
+ message=reason,
202
+ reason=thrash_type.value,
203
+ metrics=self.metrics.to_dict(),
204
+ recovery_prompt=prompt,
205
+ )
206
+
207
+ elif self.on_trip == "intervene":
208
+ self._state = CircuitState.RECOVERING
209
+ self._interventions_count += 1
210
+ intervention = Intervention(
211
+ should_trip=False,
212
+ is_warning=True,
213
+ thrash_type=thrash_type,
214
+ reason=reason,
215
+ recovery_prompt=prompt,
216
+ details=details,
217
+ )
218
+ self._last_intervention = intervention
219
+ return intervention
220
+
221
+ elif self.on_trip == "warn":
222
+ self._state = CircuitState.HALF_OPEN
223
+ intervention = Intervention(
224
+ should_trip=False,
225
+ is_warning=True,
226
+ thrash_type=thrash_type,
227
+ reason=reason,
228
+ recovery_prompt=prompt,
229
+ details=details,
230
+ )
231
+ self._last_intervention = intervention
232
+ return intervention
233
+
234
+ else: # silent
235
+ self._state = CircuitState.HALF_OPEN
236
+ return Intervention(should_trip=False)
237
+
238
+ @property
239
+ def metrics(self) -> CircuitMetrics:
240
+ """Returns comprehensive telemetry for the current breaker session."""
241
+ return CircuitMetrics(
242
+ total_steps=self._step_counter,
243
+ total_cost_usd=self._total_cost_usd,
244
+ total_tokens=self._total_tokens,
245
+ thrash_events_count=self._thrash_events_count,
246
+ interventions_count=self._interventions_count,
247
+ state=self._state,
248
+ history_length=len(self._history),
249
+ violations=list(self._violations),
250
+ )
251
+
252
+ def reset(self) -> None:
253
+ """Resets breaker state, history, and counters to fresh initialized state."""
254
+ self._state = CircuitState.CLOSED
255
+ self._step_counter = 0
256
+ self._total_cost_usd = 0.0
257
+ self._total_tokens = 0
258
+ self._thrash_events_count = 0
259
+ self._interventions_count = 0
260
+ self._last_intervention = None
261
+ self._history.clear()
262
+ self._violations.clear()
263
+ self.detector.history.clear()
264
+
265
+ def __enter__(self) -> CircuitBreaker:
266
+ return self
267
+
268
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool:
269
+ # Pass through exceptions naturally
270
+ return False
@@ -0,0 +1,127 @@
1
+ """Command-line interface (CLI) and trace auditor for loopcircuit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from pathlib import Path
9
+ from typing import List, Optional
10
+
11
+ from loopcircuit.circuit import CircuitBreaker
12
+
13
+
14
+ def audit_trace_file(
15
+ file_path: str,
16
+ max_steps: int = 30,
17
+ max_cost: float = 5.0,
18
+ repetition_thresh: int = 3,
19
+ output_json: bool = False
20
+ ) -> int:
21
+ """Replays an agent execution log (JSONL) through CircuitBreaker to identify thrash events."""
22
+ path = Path(file_path)
23
+ if not path.is_file():
24
+ print(f"Error: Trace file not found: {file_path}", file=sys.stderr)
25
+ return 1
26
+
27
+ breaker = CircuitBreaker(
28
+ max_steps=max_steps,
29
+ max_cost_usd=max_cost,
30
+ repetition_threshold=repetition_thresh,
31
+ on_trip="intervene",
32
+ )
33
+
34
+ events: List[dict] = []
35
+ line_num = 0
36
+
37
+ with path.open(encoding="utf-8") as f:
38
+ for line in f:
39
+ line = line.strip()
40
+ if not line:
41
+ continue
42
+ line_num += 1
43
+ try:
44
+ item = json.loads(line)
45
+ except json.JSONDecodeError:
46
+ continue
47
+
48
+ tool = item.get("tool") or item.get("tool_name") or item.get("action") or "unknown"
49
+ args = item.get("args") or item.get("arguments") or {}
50
+ result = item.get("result") or item.get("observation")
51
+ error = item.get("error")
52
+ cost = float(item.get("cost") or item.get("cost_usd") or 0.0)
53
+ tokens = int(item.get("tokens") or item.get("tokens_used") or 0)
54
+
55
+ intervention = breaker.record(
56
+ tool_name=tool,
57
+ arguments=args,
58
+ result=result,
59
+ error=error,
60
+ cost_usd=cost,
61
+ tokens_used=tokens,
62
+ )
63
+
64
+ if intervention.thrash_type:
65
+ events.append({
66
+ "line": line_num,
67
+ "step": breaker.metrics.total_steps,
68
+ "type": intervention.thrash_type.value,
69
+ "reason": intervention.reason,
70
+ })
71
+
72
+ metrics = breaker.metrics.to_dict()
73
+
74
+ if output_json:
75
+ print(json.dumps({"metrics": metrics, "thrash_events": events}, indent=2))
76
+ else:
77
+ print("=" * 65)
78
+ print("loopcircuit Trace Audit Summary")
79
+ print("=" * 65)
80
+ print(f"Total Steps Replayed: {metrics['total_steps']}")
81
+ print(f"Total Cost Incurred: ${metrics['total_cost_usd']:.4f}")
82
+ print(f"Tokens Consumed: {metrics['total_tokens']}")
83
+ print(f"Thrash Events Caught: {len(events)}")
84
+ print(f"Final Circuit State: {metrics['state'].upper()}")
85
+
86
+ if events:
87
+ print("\n[!] DETECTED FAILURE PATTERNS:")
88
+ for ev in events:
89
+ print(f" - Step {ev['step']} (line {ev['line']}): [{ev['type'].upper()}] {ev['reason']}")
90
+ else:
91
+ print("\n✅ Trace is clean: No repetitive loops, oscillations, or vortex traps found.")
92
+ print("=" * 65)
93
+
94
+ return 0 if not events else 1
95
+
96
+
97
+ def main(argv: Optional[List[str]] = None) -> int:
98
+ parser = argparse.ArgumentParser(
99
+ prog="loopcircuit",
100
+ description="Autonomous agent loop governor, circuit-breaker, and trace auditor."
101
+ )
102
+ subparsers = parser.add_subparsers(dest="command", required=True)
103
+
104
+ # Subcommand: audit
105
+ audit_cmd = subparsers.add_parser("audit", help="Audit an agent JSONL execution trace for loop patterns.")
106
+ audit_cmd.add_argument("file", help="Path to agent execution trace (.jsonl).")
107
+ audit_cmd.add_argument("--max-steps", type=int, default=30, help="Max step budget threshold.")
108
+ audit_cmd.add_argument("--max-cost", type=float, default=5.0, help="Max financial budget threshold.")
109
+ audit_cmd.add_argument("--repeat-limit", type=int, default=3, help="Consecutive repetition threshold.")
110
+ audit_cmd.add_argument("--json", action="store_true", help="Output audit report as formatted JSON.")
111
+
112
+ args = parser.parse_args(argv)
113
+
114
+ if args.command == "audit":
115
+ return audit_trace_file(
116
+ file_path=args.file,
117
+ max_steps=args.max_steps,
118
+ max_cost=args.max_cost,
119
+ repetition_thresh=args.repeat_limit,
120
+ output_json=args.json,
121
+ )
122
+
123
+ return 0
124
+
125
+
126
+ if __name__ == "__main__":
127
+ sys.exit(main())