File size: 24,955 Bytes
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
#!/usr/bin/env python3
"""Analyze RETRY patterns in the SocialMediaManager-A2A project.

This script collects statistics such as:
- Error locations
- Retry counts
- Retry rates

Focus areas:
- BUSINESS-RETRY: a [BUSINESS-RETRY] marker at the end of a Chain line
  indicating a retry within content_generator (ShakespeareGeneratorCrew) or
  post_reviewer (PostReviewCrew)
- Orchestrator / crew_execution retry: e.g., [SPAN] crew_execution (retry N) [RETRYN]
  (if present)
"""

import os
import re
from pathlib import Path
from collections import defaultdict
import json
import csv

# Base path and model list
BASE_DIR = Path("/Users/wzr/TOSEM-2025/RESULTS")
MODELS = [
    "DeepSeek-R1",
    "DeepSeek-V3-1",
    "GPT-4o-mini",
    "GPT-5",
    "Gemini-2.5-flash",
    "Gemini-2.5-flash-nothinking",
    "Qwen3-235b",
]
PROJECT_NAME = "SocialMediaManager-A2A"


def extract_error_info(line: str) -> dict:
    """Extract error information from an error line.

    Returns:
        {'has_error': bool, 'node_type': str, 'node_name': str, 'error_msg': str}
    """
    # Remove tree-drawing characters (including ─)
    clean = re.sub(r"^[│├└─\-\s]+", "", line).strip()

    # Check whether the error marker is present
    if "❌" not in clean:
        return {"has_error": False}

    # Remove the error marker
    clean = clean.split("❌", 1)[1].lstrip()

    # Extract node type and name
    node_match = re.match(
        r"\[(SPAN|Chain|AGENT|Tool|LLM)\]\s+([^\[\]]+?)(?:\s+\[ERROR:(.*))?$",
        clean,
    )
    if not node_match:
        return {
            "has_error": True,
            "node_type": "Unknown",
            "node_name": "Unknown",
            "error_msg": "",
        }

    node_type = node_match.group(1)
    node_name = node_match.group(2).strip()
    error_msg = node_match.group(3).strip() if node_match.group(3) else ""

    # Normalize node name
    if node_type == "AGENT":
        node_name = re.sub(r"\._execute_core$", "", node_name)
    elif node_type == "Tool":
        node_name = re.sub(r"\._use$", "", node_name)
    elif node_type == "Chain":
        node_name = re.sub(r"Crew_[a-f0-9\-]+\.kickoff", "Crew***.kickoff", node_name)

    return {
        "has_error": True,
        "node_type": node_type,
        "node_name": node_name,
        "error_msg": error_msg,
    }


def extract_retry_info(line: str) -> dict:
    """Extract retry information from a line.

    In SocialMediaManager-A2A:
    - BUSINESS-RETRY: a Chain line ending with [BUSINESS-RETRY]
      Example: [Chain] Crew_xxx.kickoff [...] [BUSINESS-RETRY]
    - Orchestrator retry (if any): e.g.
      [SPAN] crew_execution (retry 1) [RETRY1] ...

    Returns:
        {
            'is_retry': bool,
            'retry_type': str ('orchestrator' or 'business_logic'),
            'retry_number': int (for BUSINESS-RETRY, inferred from appearance order),
            'node_type': str,
            'node_name': str,
            'agent_name': str (inferred from related AGENT for grouping)
        }
    """
    # Remove tree-drawing characters (including ─)
    clean = re.sub(r"^[│├└─\-\s]+", "", line).strip()

    # BUSINESS-RETRY marker: [BUSINESS-RETRY]
    has_business_retry_flag = "[BUSINESS-RETRY]" in clean

    # Orchestrator retry markers: (retry N) or [RETRYN]
    orchestrator_retry_match = re.search(r"\(retry\s+(\d+)\)", clean)
    if not orchestrator_retry_match:
        orchestrator_retry_match = re.search(r"\[RETRY(\d+)\]", clean)

    # If neither retry type is present, return False
    if not has_business_retry_flag and not orchestrator_retry_match:
        return {"is_retry": False}

    # Determine retry type and number
    if orchestrator_retry_match:
        retry_type = "orchestrator"
        retry_number = int(orchestrator_retry_match.group(1))
    else:
        retry_type = "business_logic"
        # BUSINESS-RETRY has no explicit number; infer from appearance order
        retry_number = 0  # Set later during post-processing

    # Extract node type and name (may have a leading ❌)
    node_match = re.match(
        r"(?:❌\s*)?\[(SPAN|Chain|AGENT)\]\s+([^\[\]]+?)(?:\s+\[.*)?$",
        clean,
    )
    if not node_match:
        return {
            "is_retry": True,
            "retry_type": retry_type,
            "retry_number": retry_number,
            "node_type": "Unknown",
            "node_name": "Unknown",
            "agent_name": "",
        }

    node_type = node_match.group(1)
    node_name = node_match.group(2).strip()

    # For Chain nodes, infer which Crew (i.e., which Agent) it belongs to
    agent_name = ""
    if node_type == "Chain" and "Crew" in node_name:
        # Normalize UUID
        node_name = re.sub(r"Crew_[a-f0-9\-]+\.kickoff", "Crew***.kickoff", node_name)
        # BUSINESS-RETRY happens in ShakespeareGeneratorCrew or PostReviewCrew.
        # Infer from surrounding context; leave empty here and set later in analyze_session.
        agent_name = ""  # Set later

    return {
        "is_retry": True,
        "retry_type": retry_type,
        "retry_number": retry_number,
        "node_type": node_type,
        "node_name": node_name,
        "agent_name": agent_name,
    }


def analyze_session(md_file: str) -> dict:
    """Analyze a single session's `execution_path.md`.

    Returns:
        {
            'has_error': bool,
            'has_retry': bool,
            'has_orchestrator_retry': bool,
            'has_business_retry': bool,
            'max_retry_number': int,
            'total_orchestrator_retries': int,
            'total_business_retries': int,
            'generator_retry_count': int (number of ShakespeareGeneratorCrew retries),
            'reviewer_retry_count': int (number of PostReviewCrew retries),
            'errors': [{'node_type': str, 'node_name': str, 'error_msg': str}, ...],
            'retries': [{
                'retry_type': str,
                'retry_number': int,
                'node_type': str,
                'node_name': str,
                'agent_name': str
            }, ...]
        }
    """
    if not os.path.exists(md_file):
        return None

    with open(md_file, "r", encoding="utf-8") as f:
        content = f.read()

    # Extract the Execution Path Tree section
    tree_match = re.search(
        r"## Execution Path Tree.*?```\n(.*?)```", content, re.DOTALL
    )
    if not tree_match:
        return None

    tree_content = tree_match.group(1)
    lines = tree_content.split("\n")

    errors = []
    retries = []
    current_agent = None  # Used to associate Chain entries with the current AGENT

    for i, line in enumerate(lines):
        if not line.strip():
            continue

        # Check errors
        error_info = extract_error_info(line)
        if error_info["has_error"]:
            errors.append(
                {
                    "node_type": error_info.get("node_type", "Unknown"),
                    "node_name": error_info.get("node_name", "Unknown"),
                    "error_msg": error_info.get("error_msg", ""),
                }
            )

        # Track the current AGENT (used to associate subsequent Chain nodes)
        if "[AGENT]" in line:
            agent_match = re.search(
                r"\[AGENT\]\s+([^\._]+)", re.sub(r"^[│├└─\-\s]+", "", line).strip()
            )
            if agent_match:
                current_agent = agent_match.group(1).strip()

        # Check retries
        retry_info = extract_retry_info(line)
        if retry_info["is_retry"]:
            # For BUSINESS-RETRY, infer agent info
            if retry_info["retry_type"] == "business_logic":
                # If it is a Chain node, use the current AGENT
                if retry_info["node_type"] == "Chain":
                    retry_info["agent_name"] = (
                        current_agent if current_agent else "Unknown"
                    )
                # If it is a SPAN node, infer agent from the SPAN name
                elif retry_info["node_type"] == "SPAN":
                    node_name = retry_info.get("node_name", "")
                    if "content_generator" in node_name:
                        retry_info["agent_name"] = "Shakespearean Bard"
                    elif "post_reviewer" in node_name:
                        retry_info["agent_name"] = "X Post Verifier"
                    else:
                        retry_info["agent_name"] = "Unknown"

            retries.append(retry_info)

    # Assign sequence numbers for BUSINESS-RETRY (by appearance order)
    business_retry_counter = {}
    for retry in retries:
        if retry["retry_type"] == "business_logic":
            agent_name = retry["agent_name"]
            if agent_name not in business_retry_counter:
                business_retry_counter[agent_name] = 0
            business_retry_counter[agent_name] += 1
            retry["retry_number"] = business_retry_counter[agent_name]

    # Summarize retry types
    orchestrator_retries = [r for r in retries if r["retry_type"] == "orchestrator"]
    business_retries = [r for r in retries if r["retry_type"] == "business_logic"]

    max_retry = (
        max([r["retry_number"] for r in orchestrator_retries])
        if orchestrator_retries
        else 0
    )

    # Count retries for Generator and Reviewer
    generator_retries = [
        r for r in business_retries if "Shakespearean Bard" in r.get("agent_name", "")
    ]
    reviewer_retries = [
        r for r in business_retries if "X Post Verifier" in r.get("agent_name", "")
    ]

    return {
        "has_error": len(errors) > 0,
        "has_retry": len(retries) > 0,
        "has_orchestrator_retry": len(orchestrator_retries) > 0,
        "has_business_retry": len(business_retries) > 0,
        "max_retry_number": max_retry,
        "total_orchestrator_retries": len(orchestrator_retries),
        "total_business_retries": len(business_retries),
        "generator_retry_count": len(generator_retries),
        "reviewer_retry_count": len(reviewer_retries),
        "errors": errors,
        "retries": retries,
    }


def collect_model_stats(model_name: str) -> dict:
    """Collect retry statistics for a single model.

    Returns:
        {
            'model': str,
            'total_sessions': int,
            'sessions_with_error': int,
            'sessions_with_retry': int,
            'sessions_with_orchestrator_retry': int,
            'sessions_with_business_retry': int,
            'total_orchestrator_retry_attempts': int,
            'total_business_retry_attempts': int,
            'total_generator_retries': int,
            'total_reviewer_retries': int,
            'error_by_agent': {agent_name: count},
            'error_types': {error_msg: count},
            'max_retry_number': int,
            'business_retry_by_agent': {agent_name: count},
            'session_details': [...]
        }
    """
    test_results_dir = BASE_DIR / model_name / PROJECT_NAME / "test_results"

    if not test_results_dir.exists():
        return None

    stats = {
        "model": model_name,
        "total_sessions": 0,
        "sessions_with_error": 0,
        "sessions_with_retry": 0,
        "sessions_with_orchestrator_retry": 0,
        "sessions_with_business_retry": 0,
        "sessions_with_only_orchestrator_retry": 0,
        "sessions_with_only_business_retry": 0,
        "sessions_with_both_retries": 0,
        "total_orchestrator_retry_attempts": 0,
        "total_business_retry_attempts": 0,
        "total_generator_retries": 0,
        "total_reviewer_retries": 0,
        "error_by_agent": defaultdict(int),
        "error_by_node_type": defaultdict(int),
        "error_types": defaultdict(int),
        "max_retry_number": 0,
        "business_retry_by_agent": defaultdict(int),
        "session_details": [],
    }

    for session_dir in sorted(test_results_dir.iterdir()):
        if not session_dir.is_dir():
            continue

        exec_path_file = session_dir / "execution_path.md"
        if not exec_path_file.exists():
            continue

        stats["total_sessions"] += 1

        analysis = analyze_session(str(exec_path_file))
        if not analysis:
            continue

        # Aggregate errors and retries
        if analysis["has_error"]:
            stats["sessions_with_error"] += 1

        if analysis["has_retry"]:
            stats["sessions_with_retry"] += 1

        if analysis["has_orchestrator_retry"]:
            stats["sessions_with_orchestrator_retry"] += 1
            stats["total_orchestrator_retry_attempts"] += analysis[
                "total_orchestrator_retries"
            ]
            stats["max_retry_number"] = max(
                stats["max_retry_number"], analysis["max_retry_number"]
            )

        if analysis["has_business_retry"]:
            stats["sessions_with_business_retry"] += 1
            stats["total_business_retry_attempts"] += analysis["total_business_retries"]
            stats["total_generator_retries"] += analysis["generator_retry_count"]
            stats["total_reviewer_retries"] += analysis["reviewer_retry_count"]

        # Count sessions with only one retry type vs both
        if analysis["has_orchestrator_retry"] and not analysis["has_business_retry"]:
            stats["sessions_with_only_orchestrator_retry"] += 1
        elif analysis["has_business_retry"] and not analysis["has_orchestrator_retry"]:
            stats["sessions_with_only_business_retry"] += 1
        elif analysis["has_orchestrator_retry"] and analysis["has_business_retry"]:
            stats["sessions_with_both_retries"] += 1

        # Count error locations
        for error in analysis["errors"]:
            if error["node_type"] == "AGENT":
                stats["error_by_agent"][error["node_name"]] += 1
            stats["error_by_node_type"][error["node_type"]] += 1

            # Build a short error-type signature
            error_msg = error["error_msg"]
            if error_msg:
                # Use the first 100 characters as an error-type identifier
                error_type = (
                    error_msg[:100]
                    if len(error_msg) <= 100
                    else error_msg[:100] + "..."
                )
                stats["error_types"][error_type] += 1

        # Count BUSINESS-RETRY by agent
        for retry in analysis["retries"]:
            if retry["retry_type"] == "business_logic" and retry["agent_name"]:
                stats["business_retry_by_agent"][retry["agent_name"]] += 1

        # Store per-session details
        stats["session_details"].append(
            {
                "session": session_dir.name,
                "has_error": analysis["has_error"],
                "has_retry": analysis["has_retry"],
                "has_orchestrator_retry": analysis["has_orchestrator_retry"],
                "has_business_retry": analysis["has_business_retry"],
                "orchestrator_retry_count": analysis["total_orchestrator_retries"],
                "business_retry_count": analysis["total_business_retries"],
                "generator_retry_count": analysis["generator_retry_count"],
                "reviewer_retry_count": analysis["reviewer_retry_count"],
                "errors": analysis["errors"],
                "retries": analysis["retries"],
            }
        )

    # Compute retry rates
    total = stats["total_sessions"]
    stats["retry_rate"] = (
        (stats["sessions_with_retry"] / total * 100) if total > 0 else 0
    )
    stats["orchestrator_retry_rate"] = (
        (stats["sessions_with_orchestrator_retry"] / total * 100) if total > 0 else 0
    )
    stats["business_retry_rate"] = (
        (stats["sessions_with_business_retry"] / total * 100) if total > 0 else 0
    )
    stats["error_rate"] = (
        (stats["sessions_with_error"] / total * 100) if total > 0 else 0
    )

    # Convert defaultdict to plain dict
    stats["error_by_agent"] = dict(stats["error_by_agent"])
    stats["error_by_node_type"] = dict(stats["error_by_node_type"])
    stats["error_types"] = dict(stats["error_types"])
    stats["business_retry_by_agent"] = dict(stats["business_retry_by_agent"])

    return stats


def print_summary(all_stats):
    """Print the statistics summary."""
    print("\n" + "=" * 130)
    print(f"RETRY Pattern Analysis Summary - {PROJECT_NAME}")
    print("=" * 130 + "\n")

    # Overall stats table
    print("## Per-model statistics\n")
    header = f"{'Model':<30} {'TotalSessions':<12} {'ErrorRate':<10} {'TotalRetryRate':<14} {'BusinessRetryRate':<16} {'GeneratorRetry':<15} {'ReviewerRetry':<15}"
    print(header)
    print("-" * 130)

    for stats in all_stats:
        if stats:
            print(
                f"{stats['model']:<30} {stats['total_sessions']:<10} "
                f"{stats['error_rate']:>8.1f}% {stats['retry_rate']:>8.1f}% "
                f"{stats['business_retry_rate']:>10.1f}% {stats['total_generator_retries']:<13} {stats['total_reviewer_retries']:<13}"
            )

    print("\n" + "=" * 130)

    # Per-model details
    for stats in all_stats:
        if not stats:
            continue

        print(f"\n### 📊 {stats['model']}\n")
        print(f"- **Total sessions**: {stats['total_sessions']}")
        print(
            f"- **Sessions with errors**: {stats['sessions_with_error']} ({stats['error_rate']:.1f}%)"
        )
        print(
            f"- **Sessions with retries**: {stats['sessions_with_retry']} ({stats['retry_rate']:.1f}%)"
        )
        if stats["sessions_with_orchestrator_retry"] > 0:
            print(
                f"  - Orchestrator retries: {stats['sessions_with_orchestrator_retry']} ({stats['orchestrator_retry_rate']:.1f}%) "
                f"[only orchestrator: {stats['sessions_with_only_orchestrator_retry']}]"
            )
        print(
            f"  - BUSINESS-RETRY: {stats['sessions_with_business_retry']} ({stats['business_retry_rate']:.1f}%) "
            f"[only business: {stats['sessions_with_only_business_retry']}]"
        )
        if stats["sessions_with_both_retries"] > 0:
            print(f"  - Both types present: {stats['sessions_with_both_retries']}")

        print("- **Total retry attempts**:")
        if stats["total_orchestrator_retry_attempts"] > 0:
            print(
                f"  - Orchestrator retries: {stats['total_orchestrator_retry_attempts']}"
            )
        print(
            f"  - BUSINESS-RETRY: {stats['total_business_retry_attempts']} "
            f"(Generator: {stats['total_generator_retries']}, Reviewer: {stats['total_reviewer_retries']})"
        )
        if stats["max_retry_number"] > 0:
            print(f"- **Max orchestrator retry index**: {stats['max_retry_number']}")

        if stats["error_by_agent"]:
            print("\n**Agents where errors occurred**:")
            for agent, count in sorted(
                stats["error_by_agent"].items(), key=lambda x: x[1], reverse=True
            )[:5]:
                print(f"  - {agent}: {count}")

        if stats["business_retry_by_agent"]:
            print("\n**Agents with BUSINESS-RETRY (sorted by count)**:")
            for agent, count in sorted(
                stats["business_retry_by_agent"].items(),
                key=lambda x: x[1],
                reverse=True,
            ):
                print(f"  - {agent}: {count}")

        if stats["error_types"]:
            print("\n**Error types (top 3)**:")
            for error_type, count in sorted(
                stats["error_types"].items(), key=lambda x: x[1], reverse=True
            )[:3]:
                print(f"  - [{count}] {error_type}")

        print("\n" + "-" * 130)


def save_results(all_stats):
    """Save results to files."""
    output_dir = Path(__file__).parent

    # Save detailed JSON
    json_file = output_dir / "retry_analysis.json"
    json_data = []
    for stats in all_stats:
        if stats:
            json_data.append(stats)

    with open(json_file, "w", encoding="utf-8") as f:
        json.dump(json_data, f, indent=2, ensure_ascii=False)
    print(f"\n✅ Detailed JSON saved: {json_file}")

    # Save CSV summary
    csv_file = output_dir / "retry_summary.csv"
    with open(csv_file, "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(
            [
                "Model",
                "Total_Sessions",
                "Sessions_With_Error",
                "Error_Rate(%)",
                "Sessions_With_Retry",
                "Retry_Rate(%)",
                "Orchestrator_Retry_Sessions",
                "Orchestrator_Retry_Rate(%)",
                "Only_Orchestrator_Retry_Sessions",
                "Business_Retry_Sessions",
                "Business_Retry_Rate(%)",
                "Only_Business_Retry_Sessions",
                "Both_Retries_Sessions",
                "Total_Orchestrator_Retries",
                "Total_Business_Retries",
                "Total_Generator_Retries",
                "Total_Reviewer_Retries",
                "Max_Retry_Number",
            ]
        )

        for stats in all_stats:
            if stats:
                writer.writerow(
                    [
                        stats["model"],
                        stats["total_sessions"],
                        stats["sessions_with_error"],
                        f"{stats['error_rate']:.2f}",
                        stats["sessions_with_retry"],
                        f"{stats['retry_rate']:.2f}",
                        stats["sessions_with_orchestrator_retry"],
                        f"{stats['orchestrator_retry_rate']:.2f}",
                        stats["sessions_with_only_orchestrator_retry"],
                        stats["sessions_with_business_retry"],
                        f"{stats['business_retry_rate']:.2f}",
                        stats["sessions_with_only_business_retry"],
                        stats["sessions_with_both_retries"],
                        stats["total_orchestrator_retry_attempts"],
                        stats["total_business_retry_attempts"],
                        stats["total_generator_retries"],
                        stats["total_reviewer_retries"],
                        stats["max_retry_number"],
                    ]
                )

    print(f"✅ CSV summary saved: {csv_file}")

    # Save error-location stats (by AGENT)
    error_csv_file = output_dir / "error_by_agent.csv"
    with open(error_csv_file, "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["Model", "Agent_Name", "Error_Count"])

        for stats in all_stats:
            if stats and stats["error_by_agent"]:
                for agent, count in sorted(
                    stats["error_by_agent"].items(), key=lambda x: x[1], reverse=True
                ):
                    writer.writerow([stats["model"], agent, count])

    print(f"✅ Error-location stats (by AGENT) saved: {error_csv_file}")

    # Save BUSINESS-RETRY stats by agent
    retry_agent_csv_file = output_dir / "business_retry_by_agent.csv"
    with open(retry_agent_csv_file, "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["Model", "Agent_Name", "Retry_Count"])

        for stats in all_stats:
            if stats and stats["business_retry_by_agent"]:
                for agent, count in sorted(
                    stats["business_retry_by_agent"].items(),
                    key=lambda x: x[1],
                    reverse=True,
                ):
                    writer.writerow([stats["model"], agent, count])

    print(f"✅ BUSINESS-RETRY stats by agent saved: {retry_agent_csv_file}")


if __name__ == "__main__":
    print(f"Starting RETRY pattern analysis - {PROJECT_NAME}...")
    print("Retry types:")
    print(
        "  1. Orchestrator retry: e.g., [SPAN] crew_execution (retry N) [RETRYN] (if present)"
    )
    print(
        "  2. BUSINESS-RETRY: a Chain line ending with [BUSINESS-RETRY]\n"
        "     - ShakespeareGeneratorCrew (content_generator) retries\n"
        "     - PostReviewCrew (post_reviewer) retries\n"
    )

    all_stats = []
    for model in MODELS:
        print(f"\n📊 Analyzing model: {model}")
        stats = collect_model_stats(model)
        if stats:
            all_stats.append(stats)
            print(
                f"  ✅ Done: {stats['total_sessions']} sessions, "
                f"{stats['sessions_with_error']} errors, "
                f"{stats['sessions_with_business_retry']} business-retries "
                f"(Gen: {stats['total_generator_retries']}, Rev: {stats['total_reviewer_retries']})"
            )
        else:
            print("  ⚠️  Skipped (directory not found)")

    print_summary(all_stats)
    save_results(all_stats)

    print("\n" + "=" * 130)
    print("✅ Analysis completed!")
    print("=" * 130)