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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Trajectory evaluation script - RecruitmentAssistant-H_A2A project

Evaluates 6 trajectory metrics:
1. Exact match
2. In-order match
3. Any-order match
4. Precision
5. Recall
6. Single-tool use

A2A_mix hybrid architecture notes:
- LangGraph (Job Analysis): dynamic matching for batched tool execution
- CrewAI (Candidate Evaluation): standard CrewAI structure
- AutoGen (Interview Communication): ignore create_agent and keep only invoke_agent
"""

import os
import re
import yaml
from pathlib import Path
from typing import List, Dict, Tuple, Set
from collections import defaultdict
import pandas as pd
import math
from itertools import permutations, product


class TrajectoryParser:
    """Parse execution_path.md and extract the full execution trajectory."""

    def __init__(self, md_file_path: str, extract_types: List[str] = None):
        """
        Args:
            md_file_path: Path to execution_path.md
            extract_types: Node types to extract. Default: ['Tool']
                           Options: 'SPAN', 'Chain', 'Tool', 'AGENT', 'LLM', 'Task Created', 'Crew Created'
        """
        self.md_file_path = md_file_path
        self.extract_types = extract_types or ["Tool"]
        self.trajectory = []

    def parse(self) -> List[str]:
        """Parse the file and return the execution trajectory sequence."""
        if not os.path.exists(self.md_file_path):
            return []

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

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

        tree_content = tree_match.group(1)
        trajectory = []

        for line in tree_content.split("\n"):
            # Remove tree-structure characters and keep the node content
            clean_line = re.sub(r"^[│├└─\s]+", "", line).strip()
            if not clean_line:
                continue

            # Remove error marker
            clean_line = re.sub(r"^❌\s+", "", clean_line)

            # Remove retry markers: (retry N) and [RETRYN]
            clean_line = re.sub(r"\s*\(retry\s+\d+\)", "", clean_line)
            clean_line = re.sub(r"\s*\[RETRY\d+\]", "", clean_line)

            # Remove ERROR info (keep node type/name; drop the [ERROR:...] part)
            clean_line = re.sub(r"\s*\[ERROR:[^\]]*\]", "", clean_line)

            # Extract node info
            node_info = self._extract_node_info(clean_line)

            if node_info and node_info["type"] in self.extract_types:
                trajectory.append(node_info["action"])

        self.trajectory = trajectory
        return trajectory

    def _extract_node_info(self, line: str) -> dict:
        """Extract node information from one line.

        Note: the input line is expected to have removed the  marker, retry markers,
        and ERROR info.

        Returns:
            {'type': str, 'action': str} or None
        """
        # SPAN node: [SPAN] span_name [stats]
        # Use a looser match to tolerate residual special characters
        span_match = re.match(r"\[SPAN\]\s+([^\[]+?)(?:\s+\[.*?\])*\s*$", line)
        if span_match:
            span_name = span_match.group(1).strip()
            return {"type": "SPAN", "action": f"SPAN: {span_name}"}

        # Chain node: [Chain] chain_name [stats]
        # For Crew_xxx.kickoff, use wildcard Crew***.kickoff
        chain_match = re.match(r"\[Chain\]\s+([^\[]+?)(?:\s+\[.*?\])*\s*$", line)
        if chain_match:
            chain_name = chain_match.group(1).strip()
            # Wildcard normalization: Crew_UUID.kickoff -> Crew***.kickoff
            chain_name = re.sub(
                r"Crew_[a-f0-9\-]+\.kickoff", "Crew***.kickoff", chain_name
            )
            return {"type": "Chain", "action": f"Chain: {chain_name}"}

        # AGENT node: [AGENT] agent_name._execute_core [stats]
        # A2A_mix special case: ignore AutoGen create_agent and keep only invoke_agent
        agent_match = re.match(r"\[AGENT\]\s+([^\[]+?)(?:\s+\[.*?\])*\s*$", line)
        if agent_match:
            agent_name = agent_match.group(1).strip()
            # Ignore create_agent (AutoGen-specific, excluded from evaluation)
            if agent_name.startswith("create_agent"):
                return None
            # Remove ._execute_core suffix
            agent_name = re.sub(r"\._execute_core$", "", agent_name)
            return {"type": "AGENT", "action": f"AGENT: {agent_name}"}

        # Tool node: [Tool] tool_name._use [time]
        tool_match = re.match(
            r"\[Tool\]\s+([^\[\]]+?)(?:\s+\[[\d.]+(?:ms|s)\])?(?:\s*@@@)?\s*$", line
        )
        if tool_match:
            tool_name = tool_match.group(1).strip()
            # Remove ._use suffix
            tool_name = re.sub(r"\._use$", "", tool_name)
            return {"type": "Tool", "action": f"Tool: {tool_name}"}

        # LLM node: [LLM] model_name (tokens) [time]
        llm_match = re.match(r"\[LLM\]\s+([^\(\[]+)", line)
        if llm_match:
            model_name = llm_match.group(1).strip()
            return {"type": "LLM", "action": f"LLM: {model_name}"}

        # Task Created node: [Task Created] [time]
        task_match = re.match(r"\[Task Created\]", line)
        if task_match:
            return {"type": "Task Created", "action": "Task Created"}

        # Crew Created node: [Crew Created] [time]
        crew_match = re.match(r"\[Crew Created\]", line)
        if crew_match:
            return {"type": "Crew Created", "action": "Crew Created"}

        return None


class TrajectoryEvaluator:
    """Trajectory evaluator implementing 6 metrics.

    A2A_mix: supports dynamic reference-trajectory selection.
    """

    def __init__(self, reference_trajectory: List[str]):
        """
        Args:
            reference_trajectory: Reference trajectory (ground truth)
        """
        self.reference = reference_trajectory

    @staticmethod
    def detect_job_analysis_tools_pattern(predicted: List[str]) -> List[int]:
        """Detect the tools grouping pattern in the LangGraph Job Analysis stage.

        Returns a list such as [1,1,1] / [2,1] / [3], where each number is the count
        of Tool nodes under one Chain: tools block.
        Returns an empty list if detection fails or the pattern is invalid.
        """
        # Locate Chain: LangGraph
        start_idx = -1
        for i, s in enumerate(predicted):
            if s == "Chain: LangGraph":
                start_idx = i
                break

        if start_idx == -1:
            return []

        # Count Chain: tools blocks and the unified_web_search under them
        group_counts = []
        i = start_idx

        while i < len(predicted):
            s = predicted[i]

            # On Chain: tools, count unified_web_search under it
            if s == "Chain: tools":
                count = 0
                i += 1
                # Count until the next Chain or AGENT
                while i < len(predicted):
                    if predicted[i].startswith("Chain: ") or predicted[i].startswith(
                        "AGENT: "
                    ):
                        break
                    if predicted[i] == "Tool: unified_web_search":
                        count += 1
                    i += 1

                if count > 0:
                    group_counts.append(count)
            # Chain: format_output indicates the end of the LangGraph stage
            elif s == "Chain: format_output":
                break
            else:
                i += 1

        # Validate grouping pattern
        if not group_counts:
            return []

        total = sum(group_counts)
        # Accept only 3 or 4 searches
        if total not in [3, 4]:
            return []

        # Validate grouping is within the allowed set
        if total == 3:
            allowed = {(1, 1, 1), (1, 2), (2, 1), (3,)}
        else:  # total == 4
            allowed = {
                (1, 1, 1, 1),
                (2, 1, 1),
                (1, 2, 1),
                (1, 1, 2),
                (3, 1),
                (1, 3),
                (4,),
            }

        if tuple(group_counts) not in allowed:
            return []

        return group_counts

    @staticmethod
    def build_job_analysis_reference_variant(
        base_reference: List[str], pattern: List[int]
    ) -> List[str]:
        """Build a Job Analysis reference variant based on a tools-grouping pattern.

        Args:
            base_reference: Base reference trajectory (3x or 4x)
            pattern: Tools grouping pattern. For example, [1,2] means 1 tool in the first
                     group and 2 tools in the second group.

        Returns:
            The adjusted full reference trajectory
        """
        try:
            # Locate Job Analysis start/end
            start_idx = base_reference.index("Chain: LangGraph")

            # Find Chain: format_output (end of Job Analysis)
            end_idx = -1
            for i in range(start_idx, len(base_reference)):
                if base_reference[i] == "Chain: format_output":
                    end_idx = i
                    break

            if end_idx == -1:
                return base_reference

            # Split into three parts: before / Job Analysis / after
            before = base_reference[: start_idx + 1]  # includes Chain: LangGraph
            after = base_reference[end_idx:]  # starts from format_output

            # Build a new Job Analysis part
            job_analysis_part = [
                "AGENT: agent",
                "LLM: *",
                "Chain: _should_continue",
            ]

            # Add Chain: tools and Tool nodes according to the pattern
            for count in pattern:
                job_analysis_part.append("Chain: tools")
                for _ in range(count):
                    job_analysis_part.append("Tool: unified_web_search")

            # Add the second agent pass
            job_analysis_part.extend(
                [
                    "AGENT: agent",
                    "LLM: *",
                    "Chain: _should_continue",
                ]
            )

            # Compose the full trajectory
            return before + job_analysis_part + after

        except (ValueError, IndexError):
            # If parsing fails, return the original reference
            return base_reference

    @staticmethod
    def detect_autogen_interview_tools(predicted: List[str]) -> List[str]:
        """Detect the tool list in the AutoGen Interview Communication stage.

        Returns:
            A list of tool strings (in order of appearance). Returns an empty list if not found.
            Example: ['Tool: execute_tool comprehensive_interview_material_generator',
                      'Tool: execute_tool email_template_generator']
        """
        # Locate invoke_agent interview_coordinator
        start_idx = -1
        for i, s in enumerate(predicted):
            if s == "AGENT: invoke_agent interview_coordinator":
                start_idx = i
                break

        if start_idx == -1:
            return []

        # Extract tools under invoke_agent
        tools = []
        i = start_idx + 1

        # Stop at the next SPAN (end of Interview Communication stage)
        while i < len(predicted):
            s = predicted[i]
            if s.startswith("SPAN: "):
                break

            if s.startswith("Tool: execute_tool "):
                tools.append(s)

            i += 1

        return tools

    @staticmethod
    def generate_autogen_llm_patterns(num_tools: int) -> List[List[int]]:
        """Generate all possible AutoGen LLM-insertion patterns between tools.

        Args:
            num_tools: Number of tools

        Returns:
            A list of patterns. Each pattern is a list indicating whether to insert an LLM between
            each adjacent pair of tools.

            Example for num_tools=2: [[0], [1]]
            - [0] = Tool1 → Tool2 (no insertion)
            - [1] = Tool1 → LLM → Tool2 (insert 1 LLM)
        """
        if num_tools < 2:
            return [[]]  # fewer than 2 tools: no gaps

        # n tools have (n-1) gaps
        num_gaps = num_tools - 1

        # Enumerate all 0/1 combinations: 2^(n-1)
        patterns = []
        for i in range(2**num_gaps):
            pattern = []
            for j in range(num_gaps):
                # Extract the j-th bit (0 or 1)
                pattern.append((i >> j) & 1)
            patterns.append(pattern)

        return patterns

    @staticmethod
    def build_autogen_interview_reference_variant(
        base_reference: List[str], llm_pattern: List[int]
    ) -> List[str]:
        """Build an Interview Communication reference variant based on an LLM-insertion pattern.

        Args:
            base_reference: Base reference trajectory
            llm_pattern: LLM insertion pattern. For example, [0] means no LLM between tools,
                         [1] means insert one LLM.

        Returns:
            The adjusted full reference trajectory
        """
        try:
            # Locate invoke_agent interview_coordinator
            start_idx = base_reference.index(
                "AGENT: invoke_agent interview_coordinator"
            )

            # Find the end of this stage (next SPAN or end-of-list)
            end_idx = len(base_reference)
            for i in range(start_idx + 1, len(base_reference)):
                if base_reference[i].startswith("SPAN: "):
                    end_idx = i
                    break

            # Extract tools from the base reference
            tools = []
            for i in range(start_idx + 1, end_idx):
                if base_reference[i].startswith("Tool: execute_tool "):
                    tools.append(base_reference[i])

            if not tools:
                return base_reference

            # Split into three parts: before / Interview Communication / after
            before = base_reference[: start_idx + 1]  # includes AGENT
            after = base_reference[end_idx:]  # starts from the next SPAN

            # Build Interview Communication part based on llm_pattern
            interview_part = ["LLM: *"]  # leading LLM

            for i, tool in enumerate(tools):
                interview_part.append(tool)

                # If not the last tool, decide whether to insert an LLM
                if i < len(tools) - 1 and i < len(llm_pattern):
                    if llm_pattern[i] == 1:
                        interview_part.append("LLM: *")

            interview_part.append("LLM: *")  # trailing LLM

            # Compose full trajectory
            return before + interview_part + after

        except (ValueError, IndexError):
            # If parsing fails, return the original reference
            return base_reference

    def _match_action(self, predicted_action: str, reference_action: str) -> bool:
        """
        Match two actions with wildcard support.

        Args:
            predicted_action: Observed action
            reference_action: Reference action (may contain wildcards)

        Returns:
            True if match, False otherwise
        """
        # Exact match
        if predicted_action == reference_action:
            return True

        # Wildcard match: "LLM: *" matches any "LLM: <model_name>"
        if reference_action == "LLM: *" and predicted_action.startswith("LLM: "):
            return True

        return False

    def exact_match(self, predicted: List[str]) -> int:
        """
        Exact match: the predicted trajectory must be identical to the reference (with wildcard support).

        Returns:
            1 if exact match, 0 otherwise
        """
        if len(predicted) != len(self.reference):
            return 0

        for i in range(len(predicted)):
            if not self._match_action(predicted[i], self.reference[i]):
                return 0

        return 1

    def in_order_match(self, predicted: List[str]) -> int:
        """
        In-order match: the reference must be a subsequence of the predicted trajectory (with wildcard support).
        Extra actions are allowed, but required steps must appear in order.

        Returns:
            1 if in-order match, 0 otherwise
        """
        if not self.reference:
            return 1  # empty reference always matches

        ref_idx = 0
        for pred_action in predicted:
            if ref_idx < len(self.reference) and self._match_action(
                pred_action, self.reference[ref_idx]
            ):
                ref_idx += 1

        # Check whether all reference steps were found in order
        return 1 if ref_idx == len(self.reference) else 0

    def any_order_match(self, predicted: List[str]) -> int:
        """
        Any-order match: the predicted trajectory must contain all required actions (with wildcard support).
        Order is ignored; extra actions are allowed.

        Returns:
            1 if any-order match, 0 otherwise
        """
        if not self.reference:
            return 1

        # Copy predicted actions for matching
        pred_remaining = predicted.copy()

        # For each reference action, try to find a match in the prediction
        for ref_action in self.reference:
            matched = False
            for i, pred_action in enumerate(pred_remaining):
                if self._match_action(pred_action, ref_action):
                    pred_remaining.pop(i)  # remove matched action
                    matched = True
                    break

            if not matched:
                return 0  # a reference action was not matched

        return 1

    def precision(self, predicted: List[str]) -> float:
        """
        Precision: fraction of predicted actions that are considered correct by the reference (with wildcard support).

        Precision = TP / (TP + FP)
        TP: Correct actions in prediction
        FP: Incorrect/extra actions in prediction

        Returns:
            precision value (0.0 - 1.0)
        """
        if not predicted:
            return 1.0  # no prediction -> no false positives

        if not self.reference:
            return 0.0  # empty reference but non-empty prediction -> all are incorrect

        # Copy reference actions for matching
        ref_remaining = self.reference.copy()

        tp = 0  # True Positives
        for pred_action in predicted:
            # Try to find a match in the reference
            for i, ref_action in enumerate(ref_remaining):
                if self._match_action(pred_action, ref_action):
                    tp += 1
                    ref_remaining.pop(i)  # remove matched action
                    break

        fp = len(predicted) - tp  # False Positives

        return tp / (tp + fp) if (tp + fp) > 0 else 0.0

    def recall(self, predicted: List[str]) -> float:
        """
        Recall: fraction of reference actions covered by the predicted trajectory (with wildcard support).

        Recall = TP / (TP + FN)
        TP: Covered required actions
        FN: Missing required actions

        Returns:
            recall value (0.0 - 1.0)
        """
        if not self.reference:
            return 1.0  # empty reference -> nothing to recall

        if not predicted:
            return 0.0  # no prediction -> recall is 0

        # Copy predicted actions for matching
        pred_remaining = predicted.copy()

        tp = 0  # True Positives
        for ref_action in self.reference:
            # Try to find a match in the prediction
            for i, pred_action in enumerate(pred_remaining):
                if self._match_action(pred_action, ref_action):
                    tp += 1
                    pred_remaining.pop(i)  # remove matched action
                    break

        fn = len(self.reference) - tp  # False Negatives

        return tp / (tp + fn) if (tp + fn) > 0 else 0.0

    def single_tool_use(self, predicted: List[str], tool_name: str) -> int:
        """
        Single-tool use: check whether a specific tool appears in the trajectory (with wildcard support).

        Args:
            predicted: Predicted trajectory
            tool_name: Target tool name

        Returns:
            1 if tool is used, 0 otherwise
        """
        # Check whether any predicted action matches the target tool
        for pred_action in predicted:
            if self._match_action(pred_action, tool_name):
                return 1
        return 0

    def evaluate_all(
        self, predicted: List[str], target_tools: List[str] = None
    ) -> Dict[str, float]:
        """
        Evaluate all metrics.

        Args:
            predicted: Predicted trajectory
            target_tools: Tools to check for single-tool use

        Returns:
            A dictionary of metric results
        """
        results = {
            "exact_match": self.exact_match(predicted),
            "in_order_match": self.in_order_match(predicted),
            "any_order_match": self.any_order_match(predicted),
            "precision": self.precision(predicted),
            "recall": self.recall(predicted),
        }

        # Single-tool use: average usage rate across all target tools
        if target_tools:
            tool_usage_count = sum(
                self.single_tool_use(predicted, tool) for tool in target_tools
            )
            results["single_tool_use"] = (
                tool_usage_count / len(target_tools) if target_tools else 0.0
            )

        return results


class DatasetEvaluator:
    """Dataset-level evaluator."""

    def __init__(self, config_file: str):
        """
        Args:
            config_file: Path to the YAML config file that defines reference trajectories
        """
        self.config_file = config_file
        self.config = self._load_config()
        self.reference_trajectory = self.config.get("reference_trajectory", [])
        # Dynamic reference trajectory: choose based on unified_web_search count
        self.reference_trajectory_3x = self.config.get("reference_trajectory_3x", None)
        self.reference_trajectory_4x = self.config.get("reference_trajectory_4x", None)
        self.use_dynamic_reference = (
            self.reference_trajectory_3x is not None
            and self.reference_trajectory_4x is not None
        )
        self.target_tools = self.config.get("target_tools", [])
        self.models = self.config.get("models", [])
        self.project_name = self.config.get(
            "project_name", "RecruitmentAssistant-H_A2A"
        )
        # Extract types: default is Tool only; can be configured to include others
        self.extract_types = self.config.get("extract_types", ["Tool"])

        # A2A_mix: enable dynamic matching for LangGraph batched tool execution
        # Enabled by default when dynamic reference is available
        self.enable_tools_pattern_matching = self.use_dynamic_reference

        # A2A_mix: enable dynamic matching for AutoGen Interview LLM/Tool patterns
        # Enabled by default when dynamic reference is available
        self.enable_autogen_pattern_matching = self.use_dynamic_reference

        # Permutable tool groups (for dynamic tool-order optimization)
        self.permutable_tool_groups = self.config.get("permutable_tool_groups", {})

    def _load_config(self) -> Dict:
        """Load the YAML config file."""
        if not os.path.exists(self.config_file):
            print(f"⚠️  Config file does not exist: {self.config_file}")
            return {}

        with open(self.config_file, "r", encoding="utf-8") as f:
            return yaml.safe_load(f)

    def _count_unified_web_search_in_analyze_job(self, exec_path_file: str) -> int:
        """
        Count unified_web_search occurrences under the analyze_job SPAN.

        Args:
            exec_path_file: Path to execution_path.md

        Returns:
            Number of unified_web_search calls
        """
        if not os.path.exists(exec_path_file):
            return 0

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

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

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

        # Locate the analyze_job SPAN range
        in_analyze_job = False
        analyze_job_level = -1
        count = 0

        for line in lines:
            # Compute current line level (via leading tree characters)
            level = len(re.match(r"^([│├└─\s]*)", line).group(1))

            # Normalize line content
            clean_line = re.sub(r"^[│├└─\s]+", "", line).strip()
            clean_line = re.sub(r"^❌\s+", "", clean_line)

            # Enter analyze_job SPAN
            if "[SPAN] analyze_job" in clean_line:
                in_analyze_job = True
                analyze_job_level = level
                continue

            # While inside analyze_job SPAN
            if in_analyze_job:
                # If we hit a SPAN at the same/higher level, we've left analyze_job
                if "[SPAN]" in clean_line and level <= analyze_job_level:
                    break

                # Count unified_web_search
                if "[Tool] unified_web_search" in clean_line:
                    count += 1

        return count

    def _generate_permuted_trajectories(
        self, base_trajectory: List[str]
    ) -> List[List[str]]:
        """
        Generate all possible permuted trajectories based on permutable_tool_groups.

        Args:
            base_trajectory: Base reference trajectory

        Returns:
            A list of all possible permuted trajectories (including the original one)
        """
        if not self.permutable_tool_groups:
            # No permutable tool groups configured; return the original trajectory
            return [base_trajectory]

        # Collect all permutable tool groups and their positions in the trajectory
        tool_groups_positions = []

        for group_name, tools in self.permutable_tool_groups.items():
            # Find positions of this tool group in the trajectory
            positions = []
            tool_indices = {}

            for i, action in enumerate(base_trajectory):
                for tool in tools:
                    if action == tool:
                        positions.append(i)
                        tool_indices[i] = tool
                        break

            # Only permute if all tools are found
            if len(positions) == len(tools):
                # Record positions and tools for this group
                tools_at_positions = [tool_indices[pos] for pos in positions]
                tool_groups_positions.append((positions, tools_at_positions))

        if not tool_groups_positions:
            # No complete permutable tool group found
            return [base_trajectory]

        # Generate all possible permutation combinations
        all_trajectories = []

        # Generate permutations for each tool group
        group_permutations = []
        for positions, tools in tool_groups_positions:
            # Generate all permutations for this tool group
            perms = list(permutations(tools))
            group_permutations.append([(positions, perm) for perm in perms])

        # Cartesian product: combine permutations across tool groups
        all_group_combinations = list(product(*group_permutations))

        # Create a new trajectory for each combination
        for combination in all_group_combinations:
            new_trajectory = base_trajectory.copy()

            # Apply all tool permutations in this combination
            for positions, perm in combination:
                for pos, tool in zip(positions, perm):
                    new_trajectory[pos] = tool

            all_trajectories.append(new_trajectory)

        return all_trajectories

    def _find_best_reference_trajectory(
        self, predicted: List[str], candidate_references: List[List[str]]
    ) -> Tuple[List[str], Dict[str, float]]:
        """
        Select the best reference trajectory from multiple candidates.

        Args:
            predicted: Predicted trajectory
            candidate_references: Candidate reference trajectories

        Returns:
            (best reference trajectory, corresponding match-score dict)
        """
        best_reference = candidate_references[0]
        best_score = -1
        best_metrics = {}

        for ref_trajectory in candidate_references:
            evaluator = TrajectoryEvaluator(ref_trajectory)

            # Compute three key match metrics
            exact = evaluator.exact_match(predicted)
            in_order = evaluator.in_order_match(predicted)
            any_order = evaluator.any_order_match(predicted)

            # Weighted score: exact_match has the highest weight
            # score = exact*3 + in_order*2 + any_order*1
            score = exact * 3 + in_order * 2 + any_order * 1

            if score > best_score:
                best_score = score
                best_reference = ref_trajectory
                best_metrics = {
                    "exact_match": exact,
                    "in_order_match": in_order,
                    "any_order_match": any_order,
                }

        return best_reference, best_metrics

    def collect_execution_paths(
        self, model_name: str, base_dir: str
    ) -> List[Tuple[str, List[str]]]:
        """
        Collect and parse all execution_path.md files for a given model.

        Args:
            model_name: Model name
            base_dir: RESULTS directory path

        Returns:
            A list of (session_id, trajectory)
        """
        model_dir = Path(base_dir) / model_name / self.project_name / "test_results"

        if not model_dir.exists():
            print(f"⚠️  Model directory does not exist: {model_dir}")
            return []

        results = []

        # Iterate over session subdirectories
        for session_dir in sorted(model_dir.iterdir()):
            if not session_dir.is_dir():
                continue

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

            # Parse trajectory using configured extract types
            parser = TrajectoryParser(
                str(exec_path_file), extract_types=self.extract_types
            )
            trajectory = parser.parse()

            results.append((session_dir.name, trajectory))

        return results

    def evaluate_model(self, model_name: str, base_dir: str) -> Dict[str, float]:
        """
        Evaluate one model across all samples.

        Args:
            model_name: Model name
            base_dir: RESULTS directory path

        Returns:
            A dictionary of averaged metrics
        """
        model_dir = Path(base_dir) / model_name / self.project_name / "test_results"

        if not model_dir.exists():
            print(f"⚠️  No trajectory data found for model {model_name}")
            return {}

        # Accumulate metrics across samples
        all_metrics = defaultdict(list)
        trajectories = []

        # Iterate over sessions
        for session_dir in sorted(model_dir.iterdir()):
            if not session_dir.is_dir():
                continue

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

            # Parse trajectory
            parser = TrajectoryParser(
                str(exec_path_file), extract_types=self.extract_types
            )
            predicted = parser.parse()

            # Dynamically select the reference trajectory
            if self.use_dynamic_reference:
                # Count unified_web_search occurrences in analyze_job
                search_count = self._count_unified_web_search_in_analyze_job(
                    str(exec_path_file)
                )

                # Choose the base reference trajectory based on the count
                if search_count <= 3:
                    base_reference = self.reference_trajectory_3x
                else:
                    base_reference = self.reference_trajectory_4x

                # A2A_mix: dynamic matching (LangGraph + AutoGen)
                if (
                    self.enable_tools_pattern_matching
                    or self.enable_autogen_pattern_matching
                ):
                    # 1) Detect LangGraph tools grouping pattern
                    langgraph_pattern = None
                    if self.enable_tools_pattern_matching:
                        langgraph_pattern = (
                            TrajectoryEvaluator.detect_job_analysis_tools_pattern(
                                predicted
                            )
                        )

                    # 2) Detect tools in the AutoGen Interview stage
                    autogen_tools = None
                    if self.enable_autogen_pattern_matching:
                        autogen_tools = (
                            TrajectoryEvaluator.detect_autogen_interview_tools(
                                predicted
                            )
                        )

                    # 3) Generate all possible reference-variant combinations

                    # All possible LangGraph patterns
                    if langgraph_pattern:
                        total = sum(langgraph_pattern)
                        if total == 3:
                            langgraph_patterns = [[1, 1, 1], [1, 2], [2, 1], [3]]
                        else:  # total == 4
                            langgraph_patterns = [
                                [1, 1, 1, 1],
                                [2, 1, 1],
                                [1, 2, 1],
                                [1, 1, 2],
                                [3, 1],
                                [1, 3],
                                [4],
                            ]
                    else:
                        langgraph_patterns = [None]  # unchanged

                    # All possible AutoGen LLM insertion patterns
                    if autogen_tools:
                        num_tools = len(autogen_tools)
                        autogen_llm_patterns = (
                            TrajectoryEvaluator.generate_autogen_llm_patterns(num_tools)
                        )
                    else:
                        autogen_llm_patterns = [None]  # unchanged

                    # 4) Enumerate all combinations and select the highest-scoring one
                    best_reference = base_reference
                    best_score = -1

                    for lg_pat in langgraph_patterns:
                        for ag_llm_pat in autogen_llm_patterns:
                            # Build a variant
                            variant = base_reference

                            # Apply LangGraph variant
                            if lg_pat is not None:
                                variant = TrajectoryEvaluator.build_job_analysis_reference_variant(
                                    variant, lg_pat
                                )

                            # Apply AutoGen LLM-insertion variant
                            if ag_llm_pat is not None:
                                variant = TrajectoryEvaluator.build_autogen_interview_reference_variant(
                                    variant, ag_llm_pat
                                )

                            # Compute score
                            test_evaluator = TrajectoryEvaluator(variant)
                            exact = test_evaluator.exact_match(predicted)
                            in_order = test_evaluator.in_order_match(predicted)
                            any_order = test_evaluator.any_order_match(predicted)
                            score = max(exact, in_order, any_order)

                            # Keep the best-scoring variant
                            if score > best_score:
                                best_score = score
                                best_reference = variant

                    reference = best_reference
                else:
                    reference = base_reference
            else:
                # Use the default reference trajectory
                reference = self.reference_trajectory

            # Tool-order permutation optimization (after LangGraph+AutoGen pattern matching)
            if self.permutable_tool_groups:
                # Generate all possible tool-order permutations
                candidate_references = self._generate_permuted_trajectories(reference)

                # Select the best reference trajectory from candidates
                if len(candidate_references) > 1:
                    reference, _ = self._find_best_reference_trajectory(
                        predicted, candidate_references
                    )
                # else: keep reference unchanged

            # Create evaluator and compute metrics
            evaluator = TrajectoryEvaluator(reference)
            metrics = evaluator.evaluate_all(predicted, self.target_tools)

            for key, value in metrics.items():
                all_metrics[key].append(value)

            trajectories.append((session_dir.name, predicted))

        # Compute averages
        avg_metrics = {}
        for key, values in all_metrics.items():
            avg_metrics[key] = sum(values) / len(values) if values else 0.0

        num_samples = len(trajectories)

        if num_samples > 0:
            path_counter = defaultdict(int)
            for session_id, predicted in trajectories:
                path_key = tuple(predicted)
                path_counter[path_key] += 1

            unique_paths = len(path_counter)
            unique_path_ratio = unique_paths / num_samples if num_samples > 0 else 0.0

            probs = [count / num_samples for count in path_counter.values()]
            H = -sum(p * math.log(p) for p in probs if p > 0)
            if len(probs) > 1:
                path_entropy = H / math.log(len(probs))
            else:
                path_entropy = 0.0
        else:
            unique_path_ratio = 0.0
            path_entropy = 0.0

        avg_metrics["unique_path_ratio"] = unique_path_ratio
        avg_metrics["path_entropy"] = path_entropy

        # Add sample count
        avg_metrics["num_samples"] = num_samples

        return avg_metrics

    def evaluate_all_models(self, base_dir: str = None) -> pd.DataFrame:
        """
        Evaluate all models and generate a summary table.

        Args:
            base_dir: RESULTS directory path (default: two levels above this script)

        Returns:
            A DataFrame containing evaluation results for all models
        """
        if base_dir is None:
            # Default path: two levels above this script
            base_dir = Path(__file__).parent.parent.parent

        results = []

        for model_name in self.models:
            print(f"\n📊 Evaluating model: {model_name}")
            metrics = self.evaluate_model(model_name, str(base_dir))

            if metrics:
                metrics["model"] = model_name
                results.append(metrics)
                print(f"  ✅ Done, samples: {metrics['num_samples']}")
            else:
                print("  ❌ Skipped (no data)")

        if not results:
            print("\n❌ No model data found")
            return pd.DataFrame()

        # Create DataFrame
        df = pd.DataFrame(results)

        # Reorder columns: put model name first
        cols = [
            "model",
            "num_samples",
            "exact_match",
            "in_order_match",
            "any_order_match",
            "precision",
            "recall",
            "single_tool_use",
            "unique_path_ratio",
            "path_entropy",
        ]

        # Keep only existing columns
        cols = [col for col in cols if col in df.columns]

        df = df[cols]

        return df


def main():
    """Main entry point."""
    import argparse

    parser = argparse.ArgumentParser(
        description="Evaluate trajectory metrics for the RecruitmentAssistant-H_A2A project"
    )
    parser.add_argument(
        "--config",
        type=str,
        default="reference_trajectory.yaml",
        help="Path to the reference-trajectory config file (YAML)",
    )
    parser.add_argument(
        "--base-dir",
        type=str,
        default=None,
        help="Path to the RESULTS directory (default: two levels above this script)",
    )
    parser.add_argument(
        "--output",
        type=str,
        default="evaluation_results.csv",
        help="Output CSV file path",
    )

    args = parser.parse_args()

    # If config path is relative, resolve it against the script directory
    config_path = args.config
    if not os.path.isabs(config_path):
        config_path = os.path.join(os.path.dirname(__file__), config_path)

    print("=" * 80)
    print("Trajectory Evaluation Tool - RecruitmentAssistant-H_A2A")
    print("=" * 80)
    print(f"\n📁 Config file: {config_path}")

    # Create evaluator
    evaluator = DatasetEvaluator(config_path)

    print(f"📋 Project: {evaluator.project_name}")

    # Reference trajectory info
    if evaluator.use_dynamic_reference:
        print("🎯 Reference trajectory: dynamic selection")
        print(
            f"   - 3x version (unified_web_search<=3): {len(evaluator.reference_trajectory_3x)} steps"
        )
        print(
            f"   - 4x version (unified_web_search>=4): {len(evaluator.reference_trajectory_4x)} steps"
        )
    else:
        print(f"🎯 Reference trajectory: {evaluator.reference_trajectory}")

    print(f"🔧 Target tools: {evaluator.target_tools}")
    print(f"🤖 Models: {evaluator.models}")

    # Dynamic optimization info
    if evaluator.use_dynamic_reference:
        print("\n🧠 Dynamic reference-trajectory optimization: enabled (3 layers)")
        print("   - Layer 1: LangGraph tools batching pattern")
        print("     * 3 searches: 4 grouping patterns")
        print("     * 4 searches: 7 grouping patterns")
        print("   - Layer 2: AutoGen LLM insertion pattern between tools")
        print("     * 2 tools: 2^1 = 2 patterns (0 or 1 LLM between tools)")
        print("     * 3 tools: 2^2 = 4 patterns")
        print("   - Layer 3: tool-call order permutation optimization")

    # Permutation info
    if evaluator.permutable_tool_groups:
        if not evaluator.use_dynamic_reference:
            print("\n🔀 Tool-order permutation optimization: enabled")
        total_permutations = 1
        for group_name, tools in evaluator.permutable_tool_groups.items():
            num_perms = math.factorial(len(tools))
            total_permutations *= num_perms
            print(f"     * {group_name}: {len(tools)} tools, {num_perms} permutations")
        print(
            f"   - Total combinations (upper bound): 7 × 2 × {total_permutations} = {7 * 2 * total_permutations}"
        )
        print(
            "   - Strategy: select the best-matching reference combination per sample"
        )
    else:
        if not evaluator.use_dynamic_reference:
            print("\n🔀 Tool-order permutation optimization: disabled")

    # Evaluate all models
    df = evaluator.evaluate_all_models(args.base_dir)

    if df.empty:
        print("\n❌ Evaluation failed: no data")
        return

    print("\n" + "=" * 80)
    print("📊 Evaluation results")
    print("=" * 80)

    # Display formatting
    pd.set_option("display.max_columns", None)
    pd.set_option("display.width", None)
    pd.set_option("display.float_format", lambda x: f"{x:.4f}")

    print("\n" + df.to_string(index=False))

    # Save results
    output_dir = os.path.dirname(args.output) or "."
    os.makedirs(output_dir, exist_ok=True)

    csv_file = args.output
    df.to_csv(csv_file, index=False)
    print(f"\n✅ CSV saved: {csv_file}")

    print("\n" + "=" * 80)
    print("✅ Done")
    print("=" * 80)


if __name__ == "__main__":
    main()