File size: 48,132 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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
#!/usr/bin/env python3
"""
Generic Langfuse trace tree extraction tool.

Builds a parent-child tree and sorts siblings by timestamp.
"""

import json
import sys
import os
import re
from typing import Dict, List, Tuple, Optional
from datetime import datetime


def format_time(latency_ms: float) -> str:
    """Format latency for display. `latency_ms` is in milliseconds."""
    if latency_ms < 1000:
        return f"{latency_ms:.0f}ms"
    else:
        seconds = latency_ms / 1000
        return f"{seconds:.2f}s"


def format_tokens(
    prompt_tokens: int,
    completion_tokens: int,
    total_tokens: int,
    reasoning_tokens: int = 0,
) -> str:
    """Format token usage. Always shows REASONING tokens (0 for non-reasoning models)."""
    actual_output = completion_tokens - reasoning_tokens
    return f"({prompt_tokens}{completion_tokens} [REASONING:{reasoning_tokens}, OUTPUT:{actual_output}], total: {total_tokens})"


def calculate_subtree_stats(
    obs_id: str, children_map: Dict[str, List[Dict]]
) -> Tuple[int, int, int, int, float]:
    """Compute subtree stats: prompt, completion, reasoning, total tokens, and total time (ms)."""
    total_prompt = 0
    total_completion = 0
    total_reasoning = 0
    total_tokens = 0
    total_time = 0.0

    children = children_map.get(obs_id, [])
    for child in children:
        child_type = child.get("type", "")

        # Accumulate tokens for the current node (LLM only)
        if child_type == "GENERATION":
            total_prompt += child.get("promptTokens", 0)
            total_completion += child.get("completionTokens", 0)
            total_tokens += child.get("totalTokens", 0)

            # Extract REASONING tokens
            usage_details = child.get("usageDetails", {})
            if isinstance(usage_details, dict):
                total_reasoning += usage_details.get("completion_details.reasoning", 0)

        # Accumulate time for the current node (LLM and Tool)
        if child_type in ["GENERATION", "TOOL"]:
            total_time += child.get("latency", 0.0)

        # Recurse into children
        child_stats = calculate_subtree_stats(child["id"], children_map)
        total_prompt += child_stats[0]
        total_completion += child_stats[1]
        total_reasoning += child_stats[2]
        total_tokens += child_stats[3]
        total_time += child_stats[4]

    return total_prompt, total_completion, total_reasoning, total_tokens, total_time


def simplify_name(
    obs_type: str, obs_name: str, obs: Dict, children_map: Dict[str, List[Dict]] = None
) -> str:
    """Build a display name and append token/time information."""
    base_name = ""
    suffix = ""
    error_prefix = ""

    # Error handling
    obs_level = obs.get("level", "DEFAULT")
    status_message = obs.get("statusMessage")
    if obs_level == "ERROR" and status_message:
        error_prefix = "[ERROR] "
        # Keep error text short for readability (cannot update error_stats here)
        if len(status_message) > 80:
            error_msg = status_message[:70] + "[TRUNCATED]"
        else:
            error_msg = status_message
        suffix = f" [ERROR: {error_msg}]" + suffix

    # SPAN
    if obs_type == "SPAN":
        if "Crew Created" in obs_name:
            base_name = "[Crew Created]"
        elif "Task Created" in obs_name:
            base_name = "[Task Created]"
        # Note: check longer strings first to avoid partial matches
        elif "Tool Usage Error" in obs_name:
            base_name = "[Tool Usage Error]"
        elif "Tool Repeated Usage" in obs_name:
            base_name = "[Tool Repeated Usage]"
        elif "Tool Usage" in obs_name:
            base_name = "[Tool Usage]"
        else:
            base_name = f"[SPAN] {obs_name}"

    # AGENT
    elif obs_type == "AGENT":
        base_name = f"[AGENT] {obs_name}"

    # GENERATION (LLM) - token/time
    elif obs_type == "GENERATION":
        model = obs.get("model", "unknown")
        if "/" in model:
            model = model.split("/")[-1]
        base_name = f"[LLM] {model}"

        # Token usage
        prompt_tokens = obs.get("promptTokens", 0)
        completion_tokens = obs.get("completionTokens", 0)
        total_tokens = obs.get("totalTokens", 0)

        # Extract REASONING tokens
        reasoning_tokens = 0
        usage_details = obs.get("usageDetails", {})
        if isinstance(usage_details, dict):
            reasoning_tokens = usage_details.get("completion_details.reasoning", 0)

        if total_tokens > 0:
            suffix += f" {format_tokens(prompt_tokens, completion_tokens, total_tokens, reasoning_tokens)}"

        # Latency
        latency = obs.get("latency", 0.0)
        if latency > 0:
            suffix += f" [{format_time(latency)}]"

    # TOOL - latency
    elif obs_type == "TOOL":
        base_name = f"[Tool] {obs_name}"

        # Latency
        latency = obs.get("latency", 0.0)
        if latency > 0:
            suffix += f" [{format_time(latency)}]"

    # CHAIN
    elif obs_type == "CHAIN":
        base_name = f"[Chain] {obs_name}"

    # Other
    else:
        base_name = f"[{obs_type}] {obs_name}"

    # For parent nodes (SPAN/CHAIN/AGENT), show subtree summary.
    if obs_type in ["SPAN", "CHAIN", "AGENT"] and children_map:
        stats = calculate_subtree_stats(obs["id"], children_map)
        (
            total_prompt,
            total_completion,
            total_reasoning,
            total_tokens_sum,
            total_time,
        ) = stats

        stats_parts = []
        if total_tokens_sum > 0:
            stats_parts.append(
                f"tokens: {format_tokens(total_prompt, total_completion, total_tokens_sum, total_reasoning)}"
            )

        # Time: SPAN/CHAIN/AGENT use their own latency
        node_latency = obs.get("latency", 0.0)
        if node_latency and node_latency > 0:
            stats_parts.append(f"time: {format_time(node_latency)}")

        if stats_parts:
            suffix += f" [∑ {', '.join(stats_parts)}]"

    return error_prefix + base_name + suffix


def should_filter_observation(obs: Dict, is_a2a_project: bool) -> bool:
    """Return True if an observation should be filtered out."""
    obs_name = obs.get("name", "")
    obs_type = obs.get("type", "")

    # 1) Filter HTTP client tracing nodes (noise)
    metadata = obs.get("metadata", {})
    scope_name = metadata.get("scope", {}).get("name", "")
    if scope_name == "opentelemetry.instrumentation.httpx" and obs_type == "SPAN":
        # HTTP method nodes
        if obs_name in ["POST", "GET", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]:
            return True

    # 2) A2A framework noise patterns
    if is_a2a_project:
        a2a_noise_patterns = [
            "a2a.server.events.event_queue.",
            "a2a.server.events.in_memory_queue_manager.",
            "a2a.server.events.event_consumer.",
            "a2a.server.request_handlers.default_request_handler.",
            "a2a.server.request_handlers.jsonrpc_handler.",
        ]

        # Prefix match
        for pattern in a2a_noise_patterns:
            if obs_name.startswith(pattern):
                return True

    return False


def detect_project_variant_from_path(trace_file: str) -> Optional[str]:
    file_path = os.path.abspath(trace_file)
    path_lower = file_path.lower()

    m = re.search(r"(?:^|/)[^/]+[-_](mcp|a2a_mix|a2a|h_a2a)(?:/|$)", path_lower)
    if m:
        return m.group(1)

    return None


def build_children_map(
    observations: List[Dict], is_a2a_project: bool = False, is_a2a_mix: bool = False
) -> Tuple[Dict[str, List[Dict]], Dict]:
    """Build parent->children mapping; children are sorted by timestamp and name.

    Returns:
        children_map: mapping of parent observation id -> list of child observations
        error_stats: error statistics
    """
    children_map = {}
    filtered_obs = []
    error_stats = {
        "total_errors": 0,
        "filtered_errors": 0,
        "visible_errors": 0,
        "error_messages": [],
        "http_filtered": 0,  # number of filtered HTTP request nodes
        # Error categories
        "a2a_framework_errors": [],  # A2A framework/internal errors
        "http_request_errors": [],  # HTTP request node errors
        "tool_usage_errors": [],  # Tool Usage node errors
        "tool_child_span_errors": [],  # Tool child SPAN errors (A2A_mix only)
        # Context-related errors
        "filtered_errors_no_parent_error": [],  # filtered error node with no ancestor error
        "filtered_errors_no_child_error": [],  # filtered error node with no descendant error
        # Truncation stats
        "truncated_errors_count": 0,  # number of truncated error messages
    }

    # Map id -> observation (for ancestor/descendant lookup)
    all_obs_map = {obs["id"]: obs for obs in observations}

    # Build raw children mapping (for descendant lookup)
    all_children_map = {}
    for obs in observations:
        parent_id = obs.get("parentObservationId")
        if parent_id:
            if parent_id not in all_children_map:
                all_children_map[parent_id] = []
            all_children_map[parent_id].append(obs)

    # Helper: any ancestor has ERROR
    def has_ancestor_error(obs_id: str) -> bool:
        """Check whether any ancestor node has level=ERROR."""
        obs = all_obs_map.get(obs_id)
        if not obs:
            return False

        parent_id = obs.get("parentObservationId")
        while parent_id:
            parent_obs = all_obs_map.get(parent_id)
            if not parent_obs:
                break
            if parent_obs.get("level") == "ERROR":
                return True
            parent_id = parent_obs.get("parentObservationId")
        return False

    # Helper: any descendant has ERROR
    def has_descendant_error(obs_id: str) -> bool:
        """Check whether any descendant node has level=ERROR."""
        children = all_children_map.get(obs_id, [])
        for child in children:
            if child.get("level") == "ERROR":
                return True
            if has_descendant_error(child["id"]):
                return True
        return False

    # Step 1: filter noise observations and collect error statistics
    for obs in observations:
        obs_name = obs.get("name", "")
        obs_type = obs.get("type", "")
        obs_level = obs.get("level", "DEFAULT")
        status_msg = obs.get("statusMessage") or "Unknown error"

        # Count errors
        if obs_level == "ERROR":
            error_stats["total_errors"] += 1

            if should_filter_observation(obs, is_a2a_project):
                error_stats["filtered_errors"] += 1

                # Categorize filtered errors
                metadata = obs.get("metadata", {})
                scope_name = metadata.get("scope", {}).get("name", "")

                # Determine filtered-node type
                obs_id = obs.get("id")
                error_info = {
                    "name": obs_name,
                    "type": obs_type,
                    "message": status_msg,
                    "id": obs_id,
                }

                if (
                    scope_name == "opentelemetry.instrumentation.httpx"
                    and obs_name
                    in ["POST", "GET", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]
                ):
                    error_stats["http_request_errors"].append(error_info)
                else:
                    # A2A framework/internal errors
                    error_stats["a2a_framework_errors"].append(error_info)

                # Check context (ancestors/descendants)
                if not has_ancestor_error(obs_id):
                    error_stats["filtered_errors_no_parent_error"].append(error_info)
                if not has_descendant_error(obs_id):
                    error_stats["filtered_errors_no_child_error"].append(error_info)
            else:
                error_stats["visible_errors"] += 1
                # Record visible errors (for the summary section)
                if status_msg and status_msg not in error_stats["error_messages"]:
                    error_stats["error_messages"].append(status_msg)

        # Filtering
        is_filtered = should_filter_observation(obs, is_a2a_project)
        if is_filtered:
            # Count filtered HTTP request nodes
            metadata = obs.get("metadata", {})
            scope_name = metadata.get("scope", {}).get("name", "")
            if scope_name == "opentelemetry.instrumentation.httpx" and obs_name in [
                "POST",
                "GET",
                "PUT",
                "DELETE",
                "PATCH",
                "HEAD",
                "OPTIONS",
            ]:
                error_stats["http_filtered"] += 1
        else:
            filtered_obs.append(obs)

    # Step 2: rebuild parent-child relationships (skipping filtered nodes)
    # Map id -> filtered observation
    id_to_obs = {obs["id"]: obs for obs in filtered_obs}

    # Helper: check if a node is under Crew***.kickoff chain
    def is_under_crew_chain(obs: Dict, all_observations: List[Dict]) -> bool:
        """Return True if the node is under a Crew_*.kickoff CHAIN."""
        parent_id = obs.get("parentObservationId")
        visited = set()  # avoid cycles

        while parent_id and parent_id not in visited:
            visited.add(parent_id)
            parent = next((o for o in all_observations if o["id"] == parent_id), None)
            if not parent:
                break

            # Check Crew chain
            if parent.get("type") == "CHAIN":
                chain_name = parent.get("name", "")
                # Match Crew_<uuid>.kickoff
                if re.match(r"Crew_[a-f0-9\-]+\.kickoff", chain_name):
                    return True

            parent_id = parent.get("parentObservationId")

        return False

    # Helper: parent-based filtering rules
    def should_filter_by_parent(
        child_obs: Dict, parent_obs: Dict, is_a2a_mix_project: bool
    ) -> bool:
        """Decide whether to filter a child based on its parent and project type."""
        if not parent_obs:
            return False

        parent_type = parent_obs.get("type", "")
        child_name = child_obs.get("name", "")
        child_type = child_obs.get("type", "")

        # Rule 1: all projects - filter [Tool] -> Tool Usage spans
        if parent_type == "TOOL":
            if "Tool Usage" in child_name or "Tool Repeated Usage" in child_name:
                return True

            # Rule 2: A2A_mix only - filter specific MCP spans under [Tool]
            if is_a2a_mix_project and child_type == "SPAN":
                mcp_tool_noise = [
                    "GET",
                    "POST",
                    "mcp client/operation",
                    "mcp initialize",
                    "mcp tools/call",
                    "mcp tools/list",
                ]
                if child_name in mcp_tool_noise:
                    return True

        # Rule 3: only under Crew chain - filter [AGENT] telemetry spans.
        if parent_type == "AGENT":
            if child_type == "SPAN" and (
                "Tool Usage" in child_name or "Tool Repeated Usage" in child_name
            ):
                # Only apply under Crew chain
                if is_under_crew_chain(parent_obs, observations):
                    return True

        return False

    # Build parent-child relationships; if the direct parent is filtered, climb upwards
    for obs in filtered_obs:
        parent_id = obs.get("parentObservationId")

        # Find a valid parent (skip filtered nodes)
        while parent_id and parent_id not in id_to_obs:
            # Lookup parent in the original list
            parent_obs = next((o for o in observations if o["id"] == parent_id), None)
            if parent_obs:
                parent_id = parent_obs.get("parentObservationId")
            else:
                parent_id = None

        # Parent-based filtering
        parent_obs = id_to_obs.get(parent_id) if parent_id else None
        if should_filter_by_parent(obs, parent_obs, is_a2a_mix):
            # If this node has an error, count it into the appropriate category
            if obs.get("level") == "ERROR":
                obs_name = obs.get("name", "")
                obs_type = obs.get("type", "")
                status_msg = obs.get("statusMessage") or "Unknown error"

                obs_id = obs.get("id")
                error_info = {
                    "name": obs_name,
                    "type": obs_type,
                    "message": status_msg,
                    "id": obs_id,
                }

                if "Tool Usage" in obs_name or "Tool Repeated Usage" in obs_name:
                    error_stats["tool_usage_errors"].append(error_info)
                elif is_a2a_mix and parent_obs and parent_obs.get("type") == "TOOL":
                    # Tool child SPAN error (A2A_mix only)
                    error_stats["tool_child_span_errors"].append(error_info)

                # Context checks
                if not has_ancestor_error(obs_id):
                    error_stats["filtered_errors_no_parent_error"].append(error_info)
                if not has_descendant_error(obs_id):
                    error_stats["filtered_errors_no_child_error"].append(error_info)

            continue  # skip this node

        if parent_id:
            if parent_id not in children_map:
                children_map[parent_id] = []
            children_map[parent_id].append(obs)
        else:
            # Root node
            if "ROOT" not in children_map:
                children_map["ROOT"] = []
            children_map["ROOT"].append(obs)

    # Sort children by timestamp, then by name
    for parent_id in children_map:
        children = children_map[parent_id]
        children.sort(key=lambda x: (x.get("startTime", ""), x.get("name", "")))

    return children_map, error_stats


def print_tree_recursive(
    obs: Dict,
    children_map: Dict[str, List[Dict]],
    prefix: str,
    is_last: bool,
    output_lines: List[str],
    batch_info: Dict[str, Dict] = None,
    self_eval_retry_info: Dict[str, bool] = None,
):
    """Recursively render the tree."""
    obs_type = obs.get("type", "UNKNOWN")
    obs_name = obs.get("name", "unnamed")
    obs_id = obs["id"]

    # Display name (pass children_map to compute subtree stats)
    display_name = simplify_name(obs_type, obs_name, obs, children_map)

    # SQL series: detect business_retry (can appear at any level)
    if obs_type == "SPAN" and "business_retry" in obs_name.lower():
        m_business = re.search(r"\bbusiness_retry\s*(\d+)\b", obs_name, re.IGNORECASE)
        if m_business and "[BUSINESS-RETRY]" not in display_name:
            display_name = f"{display_name} [BUSINESS-RETRY]"

    # Add batch annotation (write_a_book_with_flows only)
    if batch_info and obs_id in batch_info:
        info = batch_info[obs_id]
        batch_str = f"BATCH{info['batch']}"
        if info["is_retry"]:
            batch_str += " [BUSINESS-RETRY]"
        if info["chapter_title"]:
            batch_str += f" ({info['chapter_title']})"
        display_name = f"{display_name} {batch_str}"

    # Add self_evaluation_loop retry annotations
    if self_eval_retry_info and obs_id in self_eval_retry_info:
        if self_eval_retry_info[obs_id]:
            display_name = f"{display_name} [BUSINESS-RETRY]"

    # Current line
    connector = "└─ " if is_last else "├─ "
    output_lines.append(f"{prefix}{connector}{display_name}")

    # Prefix for children
    if is_last:
        new_prefix = prefix + "   "  # 3 spaces
    else:
        new_prefix = prefix + "│  "  # │ + 2 spaces

    # Recurse into children
    children = children_map.get(obs_id, [])

    # Filter nested LLM calls: for a GENERATION node, hide its GENERATION children
    if obs_type == "GENERATION":
        children = [child for child in children if child.get("type") != "GENERATION"]

    for i, child in enumerate(children):
        is_last_child = i == len(children) - 1
        print_tree_recursive(
            child,
            children_map,
            new_prefix,
            is_last_child,
            output_lines,
            batch_info,
            self_eval_retry_info,
        )


def build_tree_structure(
    observations: List[Dict],
    is_a2a_project: bool = False,
    is_a2a_mix: bool = False,
    project_type: Optional[str] = None,
    self_eval_project_type: Optional[str] = None,
) -> Tuple[List[str], Dict]:
    """Build the tree output lines."""
    output_lines = []

    # Parent-child map
    children_map, error_stats = build_children_map(
        observations, is_a2a_project, is_a2a_mix
    )

    # Batch analysis (write_a_book_with_flows only)
    batch_info = {}
    if project_type:
        batch_info = analyze_write_chapters_batches(
            observations, children_map, project_type
        )

    # Retry analysis (self_evaluation_loop_flow only)
    self_eval_retry_info = {}
    if self_eval_project_type:
        self_eval_retry_info = analyze_self_evaluation_retries(
            observations, children_map, self_eval_project_type
        )

    # Render from root nodes
    root_nodes = children_map.get("ROOT", [])

    for i, root in enumerate(root_nodes):
        obs_type = root.get("type", "UNKNOWN")
        obs_name = root.get("name", "unnamed")
        display_name = simplify_name(obs_type, obs_name, root, children_map)

        # Root node (no prefix)
        output_lines.append(display_name)

        # Children
        children = children_map.get(root["id"], [])
        for j, child in enumerate(children):
            # Detect RETRY on the first layer SPAN under root
            if child.get("type") == "SPAN":
                name = child.get("name", "")

                # Detect business_retry N (SQL series)
                m_business = re.search(
                    r"\bbusiness_retry\s*(\d+)\b", name, re.IGNORECASE
                )
                if (
                    m_business
                    and "[BUSINESS-RETRY]" not in name
                    and "[RETRY" not in name
                ):
                    child["name"] = f"{name} [BUSINESS-RETRY]"

                # Detect retry N (orchestrator-level)
                elif not m_business:
                    m = re.search(r"\bretry\s*(\d+)\b", name, re.IGNORECASE)
                    if m:
                        retry_idx = m.group(1)
                        # Add marker if missing
                        if "[RETRY" not in name:
                            child["name"] = f"{name} [RETRY{retry_idx}]"
            is_last_child = j == len(children) - 1
            print_tree_recursive(
                child,
                children_map,
                "",
                is_last_child,
                output_lines,
                batch_info,
                self_eval_retry_info,
            )

    return output_lines, error_stats


def detect_a2a_project(trace_file: str) -> bool:
    """Detect whether the trace belongs to an A2A/A2A_mix project (by path)."""
    file_path = os.path.abspath(trace_file)
    path_lower = file_path.lower()

    variant = detect_project_variant_from_path(file_path)
    if variant in {"a2a", "a2a_mix", "h_a2a"}:
        return True

    if "-a2a" in path_lower or "_a2a" in path_lower:
        return True
    if "a2a-" in path_lower or "a2a_" in path_lower:
        return True

    return False


def detect_a2a_mix_project(trace_file: str) -> bool:
    """Detect whether the trace belongs to an A2A_mix project (by path)."""
    file_path = os.path.abspath(trace_file)
    path_lower = file_path.lower()

    variant = detect_project_variant_from_path(file_path)
    if variant == "a2a_mix":
        return True

    # Check A2A_mix markers
    if "-a2a_mix" in path_lower or "_a2a_mix" in path_lower:
        return True
    if "a2a-mix" in path_lower or "a2a_mix" in path_lower:
        return True

    return False


def detect_write_book_project(trace_file: str) -> Optional[str]:
    """Detect write_a_book_with_flows traces and return project type (MCP/A2A/A2A_mix) or None."""
    file_path = os.path.abspath(trace_file)
    path_lower = file_path.lower()

    if (
        "write_a_book_with_flows" not in path_lower
        and "write-a-book-with-flows" not in path_lower
    ):
        return None

    variant = detect_project_variant_from_path(file_path)
    if variant == "a2a_mix":
        return "A2A_mix"
    if variant in {"a2a", "h_a2a"}:
        return "A2A"
    if variant == "mcp":
        return "MCP"

    if (
        "-a2a_mix" in path_lower
        or "_a2a_mix" in path_lower
        or "a2a-mix" in path_lower
        or "a2a_mix" in path_lower
    ):
        return "A2A_mix"
    elif (
        "-a2a" in path_lower
        or "_a2a" in path_lower
        or "a2a-" in path_lower
        or "a2a_" in path_lower
    ):
        return "A2A"
    elif (
        "-mcp" in path_lower
        or "_mcp" in path_lower
        or "mcp-" in path_lower
        or "mcp_" in path_lower
    ):
        return "MCP"

    return None


def detect_self_evaluation_project(trace_file: str) -> Optional[str]:
    """Detect self_evaluation_loop_flow traces and return project type MCP/A2A/A2A_mix."""
    path_lower = trace_file.lower()

    # Check marker
    if (
        "self_evaluation_loop_flow" not in path_lower
        and "self-evaluation-loop-flow" not in path_lower
    ):
        return None

    # Detect concrete type
    if (
        "-a2a_mix" in path_lower
        or "_a2a_mix" in path_lower
        or "a2a-mix" in path_lower
        or "a2a_mix" in path_lower
    ):
        return "A2A_mix"
    elif (
        "-a2a" in path_lower
        or "_a2a" in path_lower
        or "a2a-" in path_lower
        or "a2a_" in path_lower
    ):
        return "A2A"
    elif (
        "-mcp" in path_lower
        or "_mcp" in path_lower
        or "mcp-" in path_lower
        or "mcp_" in path_lower
    ):
        return "MCP"

    return None


def analyze_self_evaluation_retries(
    observations: List[Dict],
    children_map: Dict[str, List[Dict]],
    project_type: str,
) -> Dict[str, bool]:
    """Analyze RETRY behavior for self_evaluation_loop_flow.

    Returns: {obs_id: is_retry}
    """
    retry_info = {}

    # Find all content_generation_loop SPANs
    content_loop_nodes = []
    for obs in observations:
        if (
            obs.get("type") == "SPAN"
            and "content_generation_loop" in obs.get("name", "").lower()
        ):
            content_loop_nodes.append(obs)

    if not content_loop_nodes:
        return {}

    if project_type == "MCP":
        # MCP: detect retries within each loop
        for content_loop_node in content_loop_nodes:
            # Recursively find CHAIN kickoff nodes under the loop
            chain_nodes = []

            def find_chain_nodes(parent_id: str, depth: int = 0, max_depth: int = 5):
                if depth > max_depth:
                    return
                children = children_map.get(parent_id, [])
                for child in children:
                    if (
                        child.get("type") == "CHAIN"
                        and "kickoff" in child.get("name", "").lower()
                    ):
                        chain_nodes.append(child)
                    else:
                        find_chain_nodes(child["id"], depth + 1, max_depth)

            find_chain_nodes(content_loop_node["id"])

            # Extract agent role from each CHAIN node (retry detection within this loop)
            role_seen = {}  # role -> first-seen node

            for node in chain_nodes:
                # Try to extract role from AGENT children
                agent_children = children_map.get(node["id"], [])
                for agent in agent_children:
                    if agent.get("type") == "AGENT":
                        agent_name = agent.get("name", "")
                        # Extract role name (before _execute_core)
                        role = (
                            agent_name.split("._execute_core")[0]
                            if "._execute_core" in agent_name
                            else agent_name
                        )

                        # Target roles
                        if "Shakespearean Bard" in role or "X Post Verifier" in role:
                            if role in role_seen:
                                # Second occurrence => RETRY
                                retry_info[node["id"]] = True
                            else:
                                # First occurrence
                                role_seen[role] = node
                                retry_info[node["id"]] = False
                        break

    else:
        # A2A/A2A_mix: detect retries within each loop
        for content_loop_node in content_loop_nodes:
            # Find a2a_call_content_generator / a2a_call_post_reviewer spans under the loop
            target_spans = []

            def find_target_spans(parent_id: str, depth: int = 0, max_depth: int = 5):
                if depth > max_depth:
                    return
                children = children_map.get(parent_id, [])
                for child in children:
                    if child.get("type") == "SPAN":
                        name = child.get("name", "").lower()
                        if (
                            "a2a_call_content_generator" in name
                            or "a2a_call_post_reviewer" in name
                        ):
                            target_spans.append(child)
                        else:
                            find_target_spans(child["id"], depth + 1, max_depth)

            find_target_spans(content_loop_node["id"])

            # Sort by time
            target_spans_with_time = []
            for node in target_spans:
                start_time = node.get("startTime", "")
                if start_time:
                    try:
                        dt = datetime.fromisoformat(start_time.replace("Z", "+00:00"))
                        target_spans_with_time.append((node, dt))
                    except:
                        pass

            target_spans_with_time.sort(key=lambda x: x[1])

            # Detect retry within the loop
            span_type_seen = {}  # span_type -> first-seen

            for node, dt in target_spans_with_time:
                name = node.get("name", "").lower()

                # Determine type
                if "content_generator" in name:
                    span_type = "content_generator"
                elif "post_reviewer" in name:
                    span_type = "post_reviewer"
                else:
                    continue

                if span_type in span_type_seen:
                    # Second occurrence => RETRY
                    retry_info[node["id"]] = True
                else:
                    # First occurrence
                    span_type_seen[span_type] = node
                    retry_info[node["id"]] = False

    return retry_info


def extract_chapter_title(obs: Dict) -> Optional[str]:
    """Extract chapter_title from an observation."""
    # Try `input`
    obs_input = obs.get("input")
    if obs_input:
        if isinstance(obs_input, dict):
            return obs_input.get("chapter_title")
        elif isinstance(obs_input, str):
            try:
                input_dict = json.loads(obs_input)
                if isinstance(input_dict, dict):
                    return input_dict.get("chapter_title")
            except:
                pass

    # Try `metadata`
    metadata = obs.get("metadata", {})
    if isinstance(metadata, dict):
        return metadata.get("chapter_title")

    return None


def analyze_write_chapters_batches(
    observations: List[Dict],
    children_map: Dict[str, List[Dict]],
    project_type: str,
) -> Dict[str, Dict]:
    """Analyze batch info under write_chapters.

    Returns: {obs_id: {'batch': batch_no, 'is_retry': is_retry, 'chapter_title': chapter_title}}
    """
    # Find all write_chapters SPANs
    write_chapters_nodes = []
    for obs in observations:
        if (
            obs.get("type") == "SPAN"
            and "write_chapters" in obs.get("name", "").lower()
        ):
            write_chapters_nodes.append(obs)

    if not write_chapters_nodes:
        return {}

    # Locate crew nodes based on project type.
    # Collect all crew nodes to detect retries across orchestrator retries.
    crew_nodes = []

    if project_type == "MCP":
        # MCP: CHAIN kickoff nodes are directly under write_chapters
        for write_chapters_node in write_chapters_nodes:
            children = children_map.get(write_chapters_node["id"], [])
            for child in children:
                if (
                    child.get("type") == "CHAIN"
                    and "kickoff" in child.get("name", "").lower()
                ):
                    crew_nodes.append(child)
    else:
        # A2A/A2A_mix: write_chapters has extra SPAN wrappers; find CHAIN kickoff recursively
        def find_crew_nodes(parent_id: str, depth: int = 0, max_depth: int = 3):
            if depth > max_depth:
                return
            children = children_map.get(parent_id, [])
            for child in children:
                if (
                    child.get("type") == "CHAIN"
                    and "kickoff" in child.get("name", "").lower()
                ):
                    crew_nodes.append(child)
                elif child.get("type") == "SPAN":
                    # Keep searching
                    find_crew_nodes(child["id"], depth + 1, max_depth)

        for write_chapters_node in write_chapters_nodes:
            find_crew_nodes(write_chapters_node["id"])

    if not crew_nodes:
        return {}

    # Sort by start time
    crew_nodes_with_time = []
    for node in crew_nodes:
        start_time = node.get("startTime", "")
        if start_time:
            try:
                dt = datetime.fromisoformat(start_time.replace("Z", "+00:00"))
                crew_nodes_with_time.append((node, dt))
            except:
                pass

    crew_nodes_with_time.sort(key=lambda x: x[1])

    # Extract chapter_title and detect retry
    crew_info = []
    chapter_titles_seen = {}

    for node, dt in crew_nodes_with_time:
        chapter_title = extract_chapter_title(node)
        is_retry = False
        is_error = node.get("level") == "ERROR"

        # Method 1: retry by repeated chapter_title (A2A/A2A_mix)
        if chapter_title and chapter_title in chapter_titles_seen:
            is_retry = True

        # Method 2: without chapter_title, infer from failure + large time gap (MCP)
        if not chapter_title and crew_info:
            # Heuristic: if the previous task failed and the gap is large, treat as retry
            prev_info = crew_info[-1]
            time_diff = (dt - prev_info["dt"]).total_seconds()
            # If the gap is large (>60s) and previous failed, this may be a retry
            if time_diff > 60 and prev_info.get("is_error"):
                is_retry = True

        crew_info.append(
            {
                "node": node,
                "dt": dt,
                "chapter_title": chapter_title,
                "is_retry": is_retry,
                "is_error": is_error,
            }
        )

        if chapter_title:
            chapter_titles_seen[chapter_title] = True

    # Batch assignment logic:
    # 1) group by time (starts within 10s belong to the same batch for initial tasks)
    # 2) retry tasks inherit the original chapter's batch number
    # 3) each batch has at most 4 distinct chapters; retries do not count as new chapters
    batch_info = {}
    current_batch = 1
    batch_start_time = None
    batch_chapters = set()  # chapters in the current batch (excluding retries)
    chapter_to_batch = {}  # chapter_title -> batch_no

    for info in crew_info:
        node = info["node"]
        dt = info["dt"]
        chapter_title = info["chapter_title"]
        is_retry = info["is_retry"]

        assigned_batch = current_batch

        if is_retry and chapter_title:
            # Retry: inherit original batch
            if chapter_title in chapter_to_batch:
                assigned_batch = chapter_to_batch[chapter_title]
            # If not found (shouldn't happen), use the current batch
        else:
            # Non-retry: batch by time and capacity
            if batch_start_time is None:
                # First task starts batch 1
                batch_start_time = dt
                batch_chapters = {chapter_title} if chapter_title else set()
            else:
                time_diff = (dt - batch_start_time).total_seconds()

                # Start a new batch if >10s or batch already has 4 chapters
                if time_diff > 10 or len(batch_chapters) >= 4:
                    current_batch += 1
                    batch_start_time = dt
                    batch_chapters = {chapter_title} if chapter_title else set()
                else:
                    # Add to current batch
                    if chapter_title:
                        batch_chapters.add(chapter_title)

            assigned_batch = current_batch

            # Record mapping
            if chapter_title:
                chapter_to_batch[chapter_title] = assigned_batch

        batch_info[node["id"]] = {
            "batch": assigned_batch,
            "is_retry": is_retry,
            "chapter_title": chapter_title,
        }

    return batch_info


def extract_trace_tree(trace_file: str) -> None:
    """Extract and render the trace tree."""

    # Validate file
    if not os.path.exists(trace_file):
        print(f"ERROR: File not found: {trace_file}")
        return

    # Detect project type
    is_a2a_project = detect_a2a_project(trace_file)
    is_a2a_mix = detect_a2a_mix_project(trace_file)
    write_book_project_type = detect_write_book_project(trace_file)
    self_eval_project_type = detect_self_evaluation_project(trace_file)

    # Read JSON
    try:
        with open(trace_file, "r", encoding="utf-8") as f:
            data = json.load(f)
    except json.JSONDecodeError as e:
        print(f"ERROR: JSON parse error: {e}")
        return
    except Exception as e:
        print(f"ERROR: Failed to read file: {e}")
        return

    # Basic info
    trace_id = data.get("id", "N/A")
    timestamp = data.get("timestamp", "N/A")
    observations = data.get("observations", [])

    if not observations:
        print("WARNING: This trace has no observations")
        return

    # Build tree
    tree_lines, error_stats = build_tree_structure(
        observations,
        is_a2a_project,
        is_a2a_mix,
        write_book_project_type,
        self_eval_project_type,
    )

    # Helper: truncate error messages and count truncations (display-stage only)
    def truncate_error_msg(msg: str, max_length: int = 80) -> str:
        """Truncate error message and update truncation counter."""
        if len(msg) > max_length:
            error_stats["truncated_errors_count"] += 1
            return msg[: max_length - 10] + "[TRUNCATED]"
        return msg

    # Build full output (Markdown)
    header_lines = [
        f"# Trace Execution Path",
        f"",
        f"**Trace ID**: `{trace_id}`",
        f"",
        f"**Time**: {timestamp}",
        f"",
    ]

    if is_a2a_project:
        header_lines.append("**Project Type**: A2A (framework noise filtered)")
        header_lines.append(f"")

    if write_book_project_type:
        header_lines.append(
            f"**write_a_book_with_flows Project Type**: {write_book_project_type}"
        )
        header_lines.append(
            "**Batch Annotation**: enabled (concurrent writing batch analysis)"
        )
        header_lines.append(f"")

    if self_eval_project_type:
        header_lines.append(
            f"**self_evaluation_loop_flow Project Type**: {self_eval_project_type}"
        )
        header_lines.append(
            "**RETRY Annotation**: enabled (content_generator and post_reviewer retry detection)"
        )
        header_lines.append(f"")

    # Statistics
    original_count = len(observations)
    filtered_count = len(
        [
            obs
            for obs in observations
            if not should_filter_observation(obs, is_a2a_project)
        ]
    )

    # Tree section
    header_lines.append("## Execution Path Tree")
    header_lines.append(f"")
    header_lines.append(f"```")

    # Tree block (code fenced)
    tree_block = tree_lines

    # Summary
    footer_lines = [
        f"```",
        f"",
        f"## Statistics",
        f"",
    ]

    if is_a2a_project:
        footer_lines.append(f"- **Original observations**: {original_count}")
        footer_lines.append(f"- **Observations after filtering**: {filtered_count}")
        a2a_filtered = original_count - filtered_count - error_stats["http_filtered"]
        footer_lines.append(f"- **Filtered**: {original_count - filtered_count} nodes")
        if error_stats["http_filtered"] > 0:
            footer_lines.append(f"  - A2A framework internals: {a2a_filtered} nodes")
            footer_lines.append(
                f'  - HTTP request nodes: {error_stats["http_filtered"]} nodes'
            )
    else:
        footer_lines.append(f"- **Total observations**: {original_count}")
        if error_stats["http_filtered"] > 0:
            footer_lines.append(
                f'- **Filtered HTTP request nodes**: {error_stats["http_filtered"]} nodes'
            )

    # Error summary
    if error_stats["total_errors"] > 0:
        footer_lines.append(f"")
        footer_lines.append("### Error Summary")
        footer_lines.append(f"")
        footer_lines.append(f'- **Total errors**: {error_stats["total_errors"]}')
        footer_lines.append(f'- **Visible errors**: {error_stats["visible_errors"]}')

        if error_stats["filtered_errors"] > 0:
            footer_lines.append(
                f'- **Filtered errors**: {error_stats["filtered_errors"]}'
            )
            if error_stats["visible_errors"] == 0:
                footer_lines.append(
                    "- **Note**: All errors are inside filtered nodes; the tree does not show error nodes"
                )

        # Truncation stats
        if error_stats["truncated_errors_count"] > 0:
            footer_lines.append(
                f'- **Truncated error messages**: {error_stats["truncated_errors_count"]}'
            )

        if error_stats["filtered_errors"] > 0:
            # Details of errors inside filtered nodes
            footer_lines.append(f"")
            footer_lines.append("#### Errors Inside Filtered Nodes")
            footer_lines.append(f"")

            # A2A framework/internal errors
            if error_stats["a2a_framework_errors"]:
                footer_lines.append(
                    f'**A2A framework/internal errors** ({len(error_stats["a2a_framework_errors"])}):'
                )
                for i, err in enumerate(error_stats["a2a_framework_errors"], 1):
                    msg = truncate_error_msg(err["message"])
                    footer_lines.append(f'{i}. `[{err["type"]}] {err["name"]}`: {msg}')
                footer_lines.append(f"")

            # HTTP request node errors
            if error_stats["http_request_errors"]:
                footer_lines.append(
                    f'**HTTP request node errors** ({len(error_stats["http_request_errors"])}):'
                )
                for i, err in enumerate(error_stats["http_request_errors"], 1):
                    msg = truncate_error_msg(err["message"])
                    footer_lines.append(f'{i}. `[{err["type"]}] {err["name"]}`: {msg}')
                footer_lines.append(f"")

            # Tool Usage node errors
            if error_stats["tool_usage_errors"]:
                footer_lines.append(
                    f'**Tool Usage node errors** ({len(error_stats["tool_usage_errors"])}):'
                )
                for i, err in enumerate(error_stats["tool_usage_errors"], 1):
                    msg = truncate_error_msg(err["message"])
                    footer_lines.append(f'{i}. `[{err["type"]}] {err["name"]}`: {msg}')
                footer_lines.append(f"")

            # Tool child SPAN errors
            if error_stats["tool_child_span_errors"]:
                footer_lines.append(
                    f'**Tool child SPAN errors (A2A_mix only)** ({len(error_stats["tool_child_span_errors"])}):'
                )
                for i, err in enumerate(error_stats["tool_child_span_errors"], 1):
                    msg = truncate_error_msg(err["message"])
                    footer_lines.append(f'{i}. `[{err["type"]}] {err["name"]}`: {msg}')
                footer_lines.append(f"")

            # Context notes
            if error_stats["filtered_errors_no_parent_error"]:
                footer_lines.append("#### Context Notes")
                footer_lines.append(f"")
                footer_lines.append(
                    f'**Filtered error nodes with no ancestor error** ({len(error_stats["filtered_errors_no_parent_error"])}):'
                )
                # De-duplicate (a node may appear in multiple categories)
                unique_errors = {
                    err["id"]: err
                    for err in error_stats["filtered_errors_no_parent_error"]
                }.values()
                for i, err in enumerate(unique_errors, 1):
                    footer_lines.append(f'{i}. `[{err["type"]}] {err["name"]}`')
                footer_lines.append(f"")

            if error_stats["filtered_errors_no_child_error"]:
                if not error_stats["filtered_errors_no_parent_error"]:
                    footer_lines.append("#### Context Notes")
                    footer_lines.append(f"")
                footer_lines.append(
                    f'**Filtered error nodes with no descendant error** ({len(error_stats["filtered_errors_no_child_error"])}):'
                )
                # De-duplicate (a node may appear in multiple categories)
                unique_errors = {
                    err["id"]: err
                    for err in error_stats["filtered_errors_no_child_error"]
                }.values()
                for i, err in enumerate(unique_errors, 1):
                    footer_lines.append(f'{i}. `[{err["type"]}] {err["name"]}`')
                footer_lines.append(f"")

        if error_stats["error_messages"]:
            footer_lines.append("**Visible error types**:")
            for i, msg in enumerate(error_stats["error_messages"], 1):
                # Show full messages in the summary (do not truncate)
                if not msg:
                    msg = "Unknown error"
                footer_lines.append(f"{i}. `{msg}`")
            footer_lines.append(f"")

    output_lines = header_lines + tree_block + footer_lines

    # Print to console
    print("\n".join(output_lines))

    # Write Markdown file next to the trace file
    output_file = os.path.join(os.path.dirname(trace_file), "execution_path.md")
    try:
        with open(output_file, "w", encoding="utf-8") as f:
            f.write("\n".join(output_lines))
        print(f"\nSaved: {os.path.basename(output_file)}")
    except Exception as e:
        print(f"\nERROR: Failed to write output file: {e}")


def main():
    """CLI entrypoint."""
    if len(sys.argv) < 2:
        print("Usage: python3 extract_trace_tree.py <trace_file.json>")
        print("\nNotes:")
        print("  - Extracts the tree from langfuse_trace.json")
        print("  - Sorts by timestamp and renders a hierarchy")
        print("  - Writes execution_path.md next to the trace file")
        sys.exit(1)

    trace_file = sys.argv[1]
    extract_trace_tree(trace_file)


if __name__ == "__main__":
    main()