rewards/__init__.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Modular reward functions organized by game/application.
3
+
4
+ This package contains reward validation functions for different dojos,
5
+ organized into separate modules for maintainability.
6
+ """
7
+
8
+ from dojo_sdk_core.dojos.rewards.game_2048 import REWARD_FUNCTIONS_2048
9
+ from dojo_sdk_core.dojos.rewards.linear import REWARD_FUNCTIONS_LINEAR
10
+ from dojo_sdk_core.dojos.rewards.linkedin import REWARD_FUNCTIONS_LINKEDIN
11
+ from dojo_sdk_core.dojos.rewards.minesweeper import REWARD_FUNCTIONS_MINESWEEPER
12
+ from dojo_sdk_core.dojos.rewards.salesforce import REWARD_FUNCTIONS_SALESFORCE
13
+ from dojo_sdk_core.dojos.rewards.tic_tac_toe import REWARD_FUNCTIONS_TIC_TAC_TOE
14
+
15
+ # Unified registry of all reward functions
16
+ REWARD_FUNCTIONS = {
17
+ **REWARD_FUNCTIONS_2048,
18
+ **REWARD_FUNCTIONS_LINEAR,
19
+ **REWARD_FUNCTIONS_LINKEDIN,
20
+ **REWARD_FUNCTIONS_SALESFORCE,
21
+ **REWARD_FUNCTIONS_TIC_TAC_TOE,
22
+ **REWARD_FUNCTIONS_MINESWEEPER,
23
+ }
24
+
25
+
26
+ def get_reward_function(name: str):
27
+ """Get a reward function by name from the unified registry."""
28
+ return REWARD_FUNCTIONS.get(name)
29
+
30
+
31
+ __all__ = ["REWARD_FUNCTIONS", "get_reward_function"]
rewards/game_2048.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward functions for 2048 game tasks.
3
+
4
+ All functions validate the final board state, accounting for randomly spawned tiles.
5
+ Board is a 16-element array representing a 4x4 grid:
6
+ [0, 1, 2, 3,
7
+ 4, 5, 6, 7,
8
+ 8, 9, 10, 11,
9
+ 12, 13, 14, 15]
10
+ """
11
+
12
+ import logging
13
+ from typing import Any, Dict, Tuple
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ def _validate_get_2048(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
19
+ """Validate that a 2048 tile is present on the board."""
20
+ if "board" not in final_state:
21
+ return 0.0, "No board in final state"
22
+
23
+ logger.debug(f"running reward function on state: {final_state}")
24
+ if 2048 in final_state["board"]:
25
+ return 1.0, "A 2048 tile is present."
26
+ return 0.0, "No 2048 tile is present."
27
+
28
+
29
+ def _validate_2048_make_first_move(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
30
+ """Validate that any valid move was made from the initial board state."""
31
+ if "board" not in final_state:
32
+ return 0.0, "No board in final state"
33
+
34
+ logger.debug(f"running reward function on state: {final_state}")
35
+
36
+ # Check if board changed (has non-zero tiles)
37
+ if any(tile != 0 for tile in final_state["board"]):
38
+ return 1.0, "Board changed from initial state - move was made successfully."
39
+
40
+ return 0.0, "Board is still empty - no move was made."
41
+
42
+
43
+ def _validate_move_tiles_right(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
44
+ """Validate that all tiles are in the rightmost column (positions 3, 7, 11, 15)."""
45
+ if "board" not in final_state:
46
+ return 0.0, "No board in final state"
47
+
48
+ logger.debug(f"running reward function on state: {final_state}")
49
+
50
+ board = final_state["board"]
51
+ rightmost_positions = [3, 7, 11, 15]
52
+
53
+ # Get all non-zero tiles and their positions
54
+ non_zero_positions = [i for i, tile in enumerate(board) if tile != 0]
55
+
56
+ # Check if all non-zero tiles are in rightmost column
57
+ if all(pos in rightmost_positions for pos in non_zero_positions):
58
+ return 1.0, f"All tiles successfully moved to rightmost column at positions {non_zero_positions}."
59
+
60
+ # Find which tiles are not in the rightmost column
61
+ misplaced = [pos for pos in non_zero_positions if pos not in rightmost_positions]
62
+ return 0.0, f"Some tiles are not in rightmost column. Misplaced at positions: {misplaced}"
63
+
64
+
65
+ def _validate_get_32_tile(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
66
+ """Validate that a 32 tile is present on the board."""
67
+ if "board" not in final_state:
68
+ return 0.0, "No board in final state"
69
+
70
+ logger.debug(f"running reward function on state: {final_state}")
71
+
72
+ if 32 in final_state["board"]:
73
+ return 1.0, "A 32 tile is present."
74
+ return 0.0, "No 32 tile is present."
75
+
76
+
77
+ def _validate_get_128_tile(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
78
+ """Validate that a 128 tile is present on the board."""
79
+ if "board" not in final_state:
80
+ return 0.0, "No board in final state"
81
+
82
+ logger.debug(f"running reward function on state: {final_state}")
83
+
84
+ if 128 in final_state["board"]:
85
+ return 1.0, "A 128 tile is present."
86
+ return 0.0, "No 128 tile is present."
87
+
88
+
89
+ def _validate_get_256_tile(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
90
+ """Validate that a 256 tile is present on the board."""
91
+ if "board" not in final_state:
92
+ return 0.0, "No board in final state"
93
+
94
+ logger.debug(f"running reward function on state: {final_state}")
95
+
96
+ if 256 in final_state["board"]:
97
+ return 1.0, "A 256 tile is present."
98
+ return 0.0, "No 256 tile is present."
99
+
100
+
101
+ def _validate_get_512_tile(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
102
+ """Validate that a 512 tile is present on the board."""
103
+ if "board" not in final_state:
104
+ return 0.0, "No board in final state"
105
+
106
+ logger.debug(f"running reward function on state: {final_state}")
107
+
108
+ if 512 in final_state["board"]:
109
+ return 1.0, "A 512 tile is present."
110
+ return 0.0, "No 512 tile is present."
111
+
112
+
113
+ def _validate_create_two_high_tiles(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
114
+ """Validate that at least two tiles with value 128 or higher are present."""
115
+ if "board" not in final_state:
116
+ return 0.0, "No board in final state"
117
+
118
+ logger.debug(f"running reward function on state: {final_state}")
119
+
120
+ high_tiles = [tile for tile in final_state["board"] if tile >= 128]
121
+ count = len(high_tiles)
122
+
123
+ if count >= 2:
124
+ return 1.0, f"Board contains {count} tiles with value 128 or higher: {high_tiles}."
125
+
126
+ return 0.0, f"Board contains only {count} tile(s) with value 128 or higher. Need at least 2."
127
+
128
+
129
+ def _validate_reach_540_sum(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
130
+ """Validate that the sum of all tile values is 540 or greater."""
131
+ if "board" not in final_state:
132
+ return 0.0, "No board in final state"
133
+
134
+ logger.debug(f"running reward function on state: {final_state}")
135
+
136
+ total_sum = sum(final_state["board"])
137
+
138
+ if total_sum >= 540:
139
+ return 1.0, f"Board sum is {total_sum}, which meets the requirement of 540 or greater."
140
+
141
+ return 0.0, f"Board sum is {total_sum}, which is below the required 540."
142
+
143
+
144
+ def _validate_strategic_32(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
145
+ """Validate that a 32 tile was created strategically from an empty board."""
146
+ if "board" not in final_state:
147
+ return 0.0, "No board in final state"
148
+
149
+ logger.debug(f"running reward function on state: {final_state}")
150
+
151
+ if 32 in final_state["board"]:
152
+ return 1.0, "A 32 tile was successfully created from empty board."
153
+ return 0.0, "No 32 tile is present."
154
+
155
+
156
+ # Registry of all 2048 reward functions
157
+ REWARD_FUNCTIONS_2048 = {
158
+ "_validate_get_2048": _validate_get_2048,
159
+ "_validate_2048_make_first_move": _validate_2048_make_first_move,
160
+ "_validate_move_tiles_right": _validate_move_tiles_right,
161
+ "_validate_get_32_tile": _validate_get_32_tile,
162
+ "_validate_get_128_tile": _validate_get_128_tile,
163
+ "_validate_get_256_tile": _validate_get_256_tile,
164
+ "_validate_get_512_tile": _validate_get_512_tile,
165
+ "_validate_create_two_high_tiles": _validate_create_two_high_tiles,
166
+ "_validate_reach_540_sum": _validate_reach_540_sum,
167
+ "_validate_strategic_32": _validate_strategic_32,
168
+ }
rewards/linear.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward functions for Linear app tasks.
3
+ """
4
+
5
+ import logging
6
+ from typing import Any, Dict, Tuple
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ def _validate_drag_to_different_column(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
12
+ """Validate that an issue was moved to a different column."""
13
+ if "issues" not in final_state:
14
+ return 0.0, "No issues in final state"
15
+
16
+ logger.debug(f"Running reward function on state: {final_state}")
17
+
18
+ # Find the issue we're tracking (VSS-101)
19
+ target_issue = next((issue for issue in final_state["issues"] if issue.get("identifier") == "VSS-101"), None)
20
+
21
+ if not target_issue:
22
+ return 0.0, "Target issue VSS-101 not found in final state"
23
+
24
+ # Check if it moved to in_progress status
25
+ if target_issue.get("status") == "in_progress" and target_issue.get("assigneeId") == "1":
26
+ return 1.0, "Issue VSS-101 successfully moved to In Progress column for user 1"
27
+
28
+ return (
29
+ 0.0,
30
+ f"Issue VSS-101 has status={target_issue.get('status')}, "
31
+ f"assigneeId={target_issue.get('assigneeId')}, expected status=in_progress, assigneeId=1",
32
+ )
33
+
34
+
35
+ def _validate_drag_two_issues_same_user(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
36
+ """Validate that two issues were moved within the same user's board."""
37
+ if "issues" not in final_state:
38
+ return 0.0, "No issues in final state"
39
+
40
+ logger.debug(f"Running reward function on state: {final_state}")
41
+
42
+ # Find both target issues
43
+ issue_101 = next((issue for issue in final_state["issues"] if issue.get("identifier") == "VSS-101"), None)
44
+ issue_106 = next((issue for issue in final_state["issues"] if issue.get("identifier") == "VSS-106"), None)
45
+
46
+ if not issue_101:
47
+ return 0.0, "Target issue VSS-101 not found in final state"
48
+ if not issue_106:
49
+ return 0.0, "Target issue VSS-106 not found in final state"
50
+
51
+ # Check both issues
52
+ issue_101_correct = issue_101.get("status") == "in_progress" and issue_101.get("assigneeId") == "1"
53
+ issue_106_correct = issue_106.get("status") == "queued" and issue_106.get("assigneeId") == "1"
54
+
55
+ if issue_101_correct and issue_106_correct:
56
+ return 1.0, "Both issues successfully moved to target columns for user 1"
57
+
58
+ errors = []
59
+ if not issue_101_correct:
60
+ errors.append(
61
+ f"VSS-101: status={issue_101.get('status')}, assigneeId={issue_101.get('assigneeId')} (expected in_progress, 1)"
62
+ )
63
+ if not issue_106_correct:
64
+ errors.append(
65
+ f"VSS-106: status={issue_106.get('status')}, assigneeId={issue_106.get('assigneeId')} (expected queued, 1)"
66
+ )
67
+
68
+ return 0.0, "; ".join(errors)
69
+
70
+
71
+ def _validate_create_new_issue(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
72
+ """Validate that a new issue was created with correct properties."""
73
+ if "issues" not in final_state:
74
+ return 0.0, "No issues in final state"
75
+
76
+ logger.debug(f"Running reward function on state: {final_state}")
77
+
78
+ # Find issue by title
79
+ target_issue = next(
80
+ (issue for issue in final_state["issues"] if issue.get("title") == "Implement user authentication system"), None
81
+ )
82
+
83
+ if not target_issue:
84
+ return 0.0, "Issue with title 'Implement user authentication system' not found in final state"
85
+
86
+ # Validate properties
87
+ errors = []
88
+
89
+ if target_issue.get("assigneeId") != "2":
90
+ errors.append(f"assigneeId={target_issue.get('assigneeId')} (expected '2')")
91
+
92
+ if target_issue.get("priority") != "high":
93
+ errors.append(f"priority={target_issue.get('priority')} (expected 'high')")
94
+
95
+ description = target_issue.get("description", "")
96
+ if "JWT-based authentication" not in description:
97
+ errors.append("description does not contain 'JWT-based authentication'")
98
+
99
+ if errors:
100
+ return 0.0, "; ".join(errors)
101
+
102
+ return 1.0, "Issue successfully created with correct properties"
103
+
104
+
105
+ def _validate_drag_and_reassign_issue(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
106
+ """Validate that issue VSS-106 was dragged to different status and assignee."""
107
+ if "issues" not in final_state:
108
+ return 0.0, "No issues in final state"
109
+
110
+ logger.debug(f"Running reward function on state: {final_state}")
111
+
112
+ # Find the target issue
113
+ target_issue = next((issue for issue in final_state["issues"] if issue.get("identifier") == "VSS-106"), None)
114
+
115
+ if not target_issue:
116
+ return 0.0, "Target issue VSS-106 not found in final state"
117
+
118
+ # Check if it has correct status and assigneeId
119
+ if target_issue.get("status") == "in_progress" and target_issue.get("assigneeId") == "2":
120
+ return 1.0, "Issue VSS-106 successfully moved to In Progress column for Chen (assigneeId=2)"
121
+
122
+ return (
123
+ 0.0,
124
+ f"Issue VSS-106 has status={target_issue.get('status')}, "
125
+ f"assigneeId={target_issue.get('assigneeId')}, expected status=in_progress, assigneeId=2",
126
+ )
127
+
128
+
129
+ def _validate_update_issue_properties(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
130
+ """Validate that issue VSS-105 has updated priority and label."""
131
+ if "issues" not in final_state:
132
+ return 0.0, "No issues in final state"
133
+
134
+ logger.debug(f"Running reward function on state: {final_state}")
135
+
136
+ # Find the target issue
137
+ target_issue = next((issue for issue in final_state["issues"] if issue.get("identifier") == "VSS-105"), None)
138
+
139
+ if not target_issue:
140
+ return 0.0, "Target issue VSS-105 not found in final state"
141
+
142
+ # Validate properties
143
+ errors = []
144
+
145
+ if target_issue.get("priority") != "urgent":
146
+ errors.append(f"priority={target_issue.get('priority')} (expected 'urgent')")
147
+
148
+ labels = target_issue.get("labels", [])
149
+ has_operations_label = any(label.get("id") == "label2" for label in labels)
150
+ if not has_operations_label:
151
+ errors.append("Operations label (id='label2') not found in labels array")
152
+
153
+ if errors:
154
+ return 0.0, "; ".join(errors)
155
+
156
+ return 1.0, "Issue VSS-105 successfully updated with urgent priority and Operations label"
157
+
158
+
159
+ def _validate_multi_issue_reorganization(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
160
+ """Validate that three issues were reorganized to different columns and assignees."""
161
+ if "issues" not in final_state:
162
+ return 0.0, "No issues in final state"
163
+
164
+ logger.debug(f"Running reward function on state: {final_state}")
165
+
166
+ # Find all three target issues
167
+ issue_101 = next((issue for issue in final_state["issues"] if issue.get("identifier") == "VSS-101"), None)
168
+ issue_102 = next((issue for issue in final_state["issues"] if issue.get("identifier") == "VSS-102"), None)
169
+ issue_103 = next((issue for issue in final_state["issues"] if issue.get("identifier") == "VSS-103"), None)
170
+
171
+ if not issue_101:
172
+ return 0.0, "Target issue VSS-101 not found in final state"
173
+ if not issue_102:
174
+ return 0.0, "Target issue VSS-102 not found in final state"
175
+ if not issue_103:
176
+ return 0.0, "Target issue VSS-103 not found in final state"
177
+
178
+ # Check all issues
179
+ issue_101_correct = issue_101.get("status") == "in_progress" and issue_101.get("assigneeId") == "2"
180
+ issue_102_correct = issue_102.get("status") == "blocked" and issue_102.get("assigneeId") == "3"
181
+ issue_103_correct = issue_103.get("status") == "in_review" and issue_103.get("assigneeId") == "1"
182
+
183
+ if issue_101_correct and issue_102_correct and issue_103_correct:
184
+ return 1.0, "All three issues successfully reorganized to target columns and assignees"
185
+
186
+ errors = []
187
+ if not issue_101_correct:
188
+ errors.append(
189
+ f"VSS-101: status={issue_101.get('status')}, assigneeId={issue_101.get('assigneeId')} (expected in_progress, 2)"
190
+ )
191
+ if not issue_102_correct:
192
+ errors.append(
193
+ f"VSS-102: status={issue_102.get('status')}, assigneeId={issue_102.get('assigneeId')} (expected blocked, 3)"
194
+ )
195
+ if not issue_103_correct:
196
+ errors.append(
197
+ f"VSS-103: status={issue_103.get('status')}, assigneeId={issue_103.get('assigneeId')} (expected in_review, 1)"
198
+ )
199
+
200
+ return 0.0, "; ".join(errors)
201
+
202
+
203
+ def _validate_complete_issue_workflow(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
204
+ """Validate that a complete issue workflow was executed."""
205
+ if "issues" not in final_state:
206
+ return 0.0, "No issues in final state"
207
+
208
+ logger.debug(f"Running reward function on state: {final_state}")
209
+
210
+ # Find issue by title
211
+ target_issue = next(
212
+ (issue for issue in final_state["issues"] if issue.get("title") == "Fix critical database connection bug"), None
213
+ )
214
+
215
+ if not target_issue:
216
+ return 0.0, "Issue with title 'Fix critical database connection bug' not found in final state"
217
+
218
+ # Validate all properties
219
+ errors = []
220
+
221
+ if target_issue.get("priority") != "high":
222
+ errors.append(f"priority={target_issue.get('priority')} (expected 'high')")
223
+
224
+ if target_issue.get("assigneeId") != "2":
225
+ errors.append(f"assigneeId={target_issue.get('assigneeId')} (expected '2')")
226
+
227
+ if target_issue.get("status") != "in_progress":
228
+ errors.append(f"status={target_issue.get('status')} (expected 'in_progress')")
229
+
230
+ labels = target_issue.get("labels", [])
231
+ has_bug_label = any(label.get("id") == "label1" for label in labels)
232
+ if not has_bug_label:
233
+ errors.append("Bug label (id='label1') not found in labels array")
234
+
235
+ comments = target_issue.get("comments", [])
236
+ has_comment = any("Starting investigation" in comment.get("text", "") for comment in comments)
237
+ if not has_comment:
238
+ errors.append("Comment containing 'Starting investigation' not found")
239
+
240
+ if errors:
241
+ return 0.0, "; ".join(errors)
242
+
243
+ return 1.0, "Complete issue workflow successfully executed"
244
+
245
+
246
+ # Registry of all Linear reward functions
247
+ REWARD_FUNCTIONS_LINEAR = {
248
+ "_validate_drag_to_different_column": _validate_drag_to_different_column,
249
+ "_validate_drag_two_issues_same_user": _validate_drag_two_issues_same_user,
250
+ "_validate_create_new_issue": _validate_create_new_issue,
251
+ "_validate_drag_and_reassign_issue": _validate_drag_and_reassign_issue,
252
+ "_validate_update_issue_properties": _validate_update_issue_properties,
253
+ "_validate_multi_issue_reorganization": _validate_multi_issue_reorganization,
254
+ "_validate_complete_issue_workflow": _validate_complete_issue_workflow,
255
+ }
rewards/linkedin.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward functions for LinkedIn app tasks.
3
+ """
4
+
5
+ import logging
6
+ from typing import Any, Dict, Tuple
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ def _validate_search_for_dzaka(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
12
+ """Validate that the user successfully searched for Dzaka Athif."""
13
+ logger.debug(f"Running reward function on state: {final_state}")
14
+
15
+ # Check 1: currentView is "search"
16
+ if final_state.get("currentView") != "search":
17
+ return 0.0, f"Not on search page, current view: {final_state.get('currentView')}"
18
+
19
+ # Check 2: searchQuery contains "dzaka" (case insensitive)
20
+ query = final_state.get("searchQuery", "").lower()
21
+ if "dzaka" not in query:
22
+ return 0.0, f"Search query doesn't contain 'dzaka': {final_state.get('searchQuery')}"
23
+
24
+ # Check 3: Dzaka Athif in search results
25
+ search_results = final_state.get("searchResults", {})
26
+ people = search_results.get("allPeople", [])
27
+
28
+ dzaka_found = any(user.get("name") == "Dzaka Athif" for user in people)
29
+
30
+ if dzaka_found:
31
+ return 1.0, "Successfully searched for Dzaka Athif"
32
+
33
+ return 0.0, f"Dzaka Athif not found in search results. Found {len(people)} people."
34
+
35
+
36
+ def _validate_fractional_find_user_profile(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
37
+ """Validate LinkedIn profile navigation with fractional scoring.
38
+
39
+ Awards 0.33 points for each criterion met:
40
+ - currentView is 'profile'
41
+ - viewedUserId is '2' (John Smith)
42
+ - searchQuery contains 'john smith'
43
+ """
44
+ logger.debug(f"Running reward function on state: {final_state}")
45
+
46
+ score = 0.0
47
+ passed = []
48
+ failed = []
49
+
50
+ # Check 1: currentView is 'profile' (0.33 points)
51
+ if final_state.get("currentView") == "profile":
52
+ score += 0.33
53
+ passed.append("currentView='profile'")
54
+ else:
55
+ failed.append(f"currentView='{final_state.get('currentView')}' (expected 'profile')")
56
+
57
+ # Check 2: viewedUserId is '2' (0.33 points)
58
+ if final_state.get("viewedUserId") == "2":
59
+ score += 0.33
60
+ passed.append("viewedUserId='2'")
61
+ else:
62
+ failed.append(f"viewedUserId='{final_state.get('viewedUserId')}' (expected '2')")
63
+
64
+ # Check 3: searchQuery contains 'john smith' (0.33 points)
65
+ query = final_state.get("searchQuery", "").lower()
66
+ if "john smith" in query:
67
+ score += 0.34 # Make it add up to 1.0
68
+ passed.append("searchQuery contains 'john smith'")
69
+ else:
70
+ failed.append(f"searchQuery='{final_state.get('searchQuery')}' (expected to contain 'john smith')")
71
+
72
+ # Build reason string
73
+ reason_parts = []
74
+ if passed:
75
+ reason_parts.append(f"Passed: {', '.join(passed)}")
76
+ if failed:
77
+ reason_parts.append(f"Failed: {', '.join(failed)}")
78
+
79
+ reason = "; ".join(reason_parts) if reason_parts else "No criteria evaluated"
80
+
81
+ return round(score, 2), reason
82
+
83
+
84
+ # Registry of all LinkedIn reward functions
85
+ REWARD_FUNCTIONS_LINKEDIN = {
86
+ "_validate_search_for_dzaka": _validate_search_for_dzaka,
87
+ "_validate_fractional_find_user_profile": _validate_fractional_find_user_profile,
88
+ }
rewards/minesweeper.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward functions for Minesweeper game tasks.
3
+
4
+ Board is a 9x9 grid (2D array) of Cell objects:
5
+ Cell: {
6
+ isMine: boolean,
7
+ isRevealed: boolean,
8
+ isFlagged: boolean,
9
+ neighborMineCount: number
10
+ }
11
+
12
+ Game statuses: "not_started", "playing", "won", "lost"
13
+ """
14
+
15
+ import logging
16
+ from typing import Any, Dict, List, Tuple
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ # Helper functions for common validation patterns
22
+
23
+
24
+ def _check_cells_flagged(board: List[List[Dict[str, Any]]], positions: List[Tuple[int, int]]) -> Tuple[float, str]:
25
+ """
26
+ Helper function to check if specific cells are flagged.
27
+
28
+ Args:
29
+ board: The game board (2D array)
30
+ positions: List of (row, col) tuples to check
31
+
32
+ Returns:
33
+ (1.0, success_message) if all positions are flagged
34
+ (0.0, error_message) otherwise
35
+ """
36
+ flagged = []
37
+ unflagged = []
38
+
39
+ for row, col in positions:
40
+ # Check if position exists
41
+ if row >= len(board) or col >= len(board[row]):
42
+ return 0.0, f"Position [{row}][{col}] does not exist on board"
43
+
44
+ if board[row][col].get("isFlagged"):
45
+ flagged.append(f"[{row}][{col}]")
46
+ else:
47
+ unflagged.append(f"[{row}][{col}]")
48
+
49
+ if len(flagged) == len(positions):
50
+ cells_str = ", ".join(flagged)
51
+ return 1.0, f"All {len(positions)} cell(s) flagged successfully: {cells_str}."
52
+
53
+ return 0.0, f"Not all cells flagged. Flagged: {flagged}, Not flagged: {unflagged}"
54
+
55
+
56
+ def _check_cells_revealed(board: List[List[Dict[str, Any]]], min_count: int, check_for_mines: bool = True) -> Tuple[float, str]:
57
+ """
58
+ Helper function to check if minimum number of cells are revealed.
59
+
60
+ Args:
61
+ board: The game board (2D array)
62
+ min_count: Minimum number of cells that should be revealed
63
+ check_for_mines: If True, fail if any revealed cell is a mine
64
+
65
+ Returns:
66
+ (1.0, success_message) if criteria met
67
+ (0.0, error_message) otherwise
68
+ """
69
+ revealed_count = 0
70
+ revealed_mine = False
71
+
72
+ for row in board:
73
+ for cell in row:
74
+ if cell.get("isRevealed"):
75
+ revealed_count += 1
76
+ if check_for_mines and cell.get("isMine"):
77
+ revealed_mine = True
78
+
79
+ if check_for_mines and revealed_mine:
80
+ return 0.0, "A mine was revealed - task failed"
81
+
82
+ if revealed_count >= min_count:
83
+ return 1.0, f"Successfully revealed {revealed_count} safe cells (target: {min_count}+)."
84
+
85
+ return 0.0, f"Only {revealed_count} cells revealed, need at least {min_count}"
86
+
87
+
88
+ # Task-specific validation functions
89
+
90
+
91
+ def _validate_minesweeper_reveal_first_cell(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
92
+ """Validate that first move was made - at least one cell revealed and game is playing."""
93
+ if "gameStatus" not in final_state:
94
+ return 0.0, "No gameStatus in final state"
95
+
96
+ if "board" not in final_state:
97
+ return 0.0, "No board in final state"
98
+
99
+ logger.debug(f"running reward function on state: {final_state}")
100
+
101
+ # Check if game status changed to playing
102
+ if final_state["gameStatus"] != "playing":
103
+ return 0.0, f"Game status is '{final_state['gameStatus']}', expected 'playing'"
104
+
105
+ # Check if at least one cell is revealed
106
+ board = final_state["board"]
107
+ revealed_count = 0
108
+
109
+ for row in board:
110
+ for cell in row:
111
+ if cell.get("isRevealed"):
112
+ revealed_count += 1
113
+
114
+ if revealed_count > 0:
115
+ return 1.0, f"First move successful - {revealed_count} cell(s) revealed and game is playing."
116
+
117
+ return 0.0, "No cells revealed yet."
118
+
119
+
120
+ def _validate_minesweeper_reveal_numbered_cell(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
121
+ """Validate that a numbered cell (with neighborMineCount > 0) was revealed at position [1][1]."""
122
+ if "board" not in final_state:
123
+ return 0.0, "No board in final state"
124
+
125
+ logger.debug(f"running reward function on state: {final_state}")
126
+
127
+ board = final_state["board"]
128
+
129
+ # Check if position [1][1] exists
130
+ if len(board) < 2 or len(board[1]) < 2:
131
+ return 0.0, "Board does not have position [1][1]"
132
+
133
+ target_cell = board[1][1]
134
+
135
+ # Check if cell is revealed
136
+ if not target_cell.get("isRevealed"):
137
+ return 0.0, "Cell at [1][1] is not revealed"
138
+
139
+ # Check if cell shows a number (neighborMineCount > 0)
140
+ neighbor_count = target_cell.get("neighborMineCount", 0)
141
+
142
+ if neighbor_count > 0:
143
+ return 1.0, f"Cell at [1][1] revealed successfully showing {neighbor_count} neighboring mine(s)."
144
+
145
+ return 0.0, f"Cell at [1][1] has neighborMineCount of {neighbor_count}, expected > 0"
146
+
147
+
148
+ def _validate_minesweeper_reveal_10_cells(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
149
+ """Validate that at least 10 cells are revealed, none are mines, and game is still playing."""
150
+ if "board" not in final_state:
151
+ return 0.0, "No board in final state"
152
+
153
+ if "gameStatus" not in final_state:
154
+ return 0.0, "No gameStatus in final state"
155
+
156
+ logger.debug(f"running reward function on state: {final_state}")
157
+
158
+ # Check if game is still playing
159
+ if final_state["gameStatus"] != "playing":
160
+ return 0.0, f"Game status is '{final_state['gameStatus']}', expected 'playing'"
161
+
162
+ return _check_cells_revealed(final_state["board"], 10, check_for_mines=True)
163
+
164
+
165
+ def _validate_minesweeper_reveal_20_cells(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
166
+ """Validate that at least 20 cells are revealed and game is still playing."""
167
+ if "board" not in final_state:
168
+ return 0.0, "No board in final state"
169
+
170
+ if "gameStatus" not in final_state:
171
+ return 0.0, "No gameStatus in final state"
172
+
173
+ logger.debug(f"running reward function on state: {final_state}")
174
+
175
+ # Check if game is still playing
176
+ if final_state["gameStatus"] != "playing":
177
+ return 0.0, f"Game status is '{final_state['gameStatus']}', expected 'playing' (game should not be won or lost yet)"
178
+
179
+ return _check_cells_revealed(final_state["board"], 20, check_for_mines=True)
180
+
181
+
182
+ def _validate_minesweeper_flag_single_mine(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
183
+ """Validate that cell at position [0][0] is flagged."""
184
+ if "board" not in final_state:
185
+ return 0.0, "No board in final state"
186
+
187
+ logger.debug(f"running reward function on state: {final_state}")
188
+
189
+ return _check_cells_flagged(final_state["board"], [(0, 0)])
190
+
191
+
192
+ def _validate_minesweeper_flag_three_mines(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
193
+ """Validate that cells at [0][0], [0][8], and [8][0] are all flagged."""
194
+ if "board" not in final_state:
195
+ return 0.0, "No board in final state"
196
+
197
+ logger.debug(f"running reward function on state: {final_state}")
198
+
199
+ target_positions = [(0, 0), (0, 8), (8, 0)]
200
+ return _check_cells_flagged(final_state["board"], target_positions)
201
+
202
+
203
+ def _validate_minesweeper_flag_corner_mines(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
204
+ """Validate that all four corner cells [0][0], [0][8], [8][0], [8][8] are flagged."""
205
+ if "board" not in final_state:
206
+ return 0.0, "No board in final state"
207
+
208
+ logger.debug(f"running reward function on state: {final_state}")
209
+
210
+ corner_positions = [(0, 0), (0, 8), (8, 0), (8, 8)]
211
+ return _check_cells_flagged(final_state["board"], corner_positions)
212
+
213
+
214
+ def _validate_minesweeper_reveal_safe_cell(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
215
+ """Validate that cell at position [4][4] is revealed and has 0 neighboring mines."""
216
+ if "board" not in final_state:
217
+ return 0.0, "No board in final state"
218
+
219
+ logger.debug(f"running reward function on state: {final_state}")
220
+
221
+ board = final_state["board"]
222
+
223
+ # Check if position [4][4] exists
224
+ if len(board) < 5 or len(board[4]) < 5:
225
+ return 0.0, "Board does not have position [4][4]"
226
+
227
+ target_cell = board[4][4]
228
+
229
+ # Check if cell is revealed
230
+ if not target_cell.get("isRevealed"):
231
+ return 0.0, "Cell at [4][4] is not revealed"
232
+
233
+ # Check if it's not a mine
234
+ if target_cell.get("isMine"):
235
+ return 0.0, "Cell at [4][4] is a mine - task failed!"
236
+
237
+ # Check if it has 0 neighboring mines
238
+ neighbor_count = target_cell.get("neighborMineCount", -1)
239
+ if neighbor_count == 0:
240
+ return 1.0, "Cell at [4][4] revealed successfully with 0 neighboring mines."
241
+
242
+ return 0.0, f"Cell at [4][4] has {neighbor_count} neighboring mines, expected 0"
243
+
244
+
245
+ # Registry of all minesweeper reward functions
246
+ REWARD_FUNCTIONS_MINESWEEPER = {
247
+ "_validate_minesweeper_reveal_first_cell": _validate_minesweeper_reveal_first_cell,
248
+ "_validate_minesweeper_reveal_numbered_cell": _validate_minesweeper_reveal_numbered_cell,
249
+ "_validate_minesweeper_reveal_10_cells": _validate_minesweeper_reveal_10_cells,
250
+ "_validate_minesweeper_reveal_20_cells": _validate_minesweeper_reveal_20_cells,
251
+ "_validate_minesweeper_flag_single_mine": _validate_minesweeper_flag_single_mine,
252
+ "_validate_minesweeper_flag_three_mines": _validate_minesweeper_flag_three_mines,
253
+ "_validate_minesweeper_flag_corner_mines": _validate_minesweeper_flag_corner_mines,
254
+ "_validate_minesweeper_reveal_safe_cell": _validate_minesweeper_reveal_safe_cell,
255
+ }
rewards/salesforce.py ADDED
@@ -0,0 +1,423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Salesforce reward functions for CRM task validation.
3
+
4
+ This module contains reward validation functions for Salesforce CRM tasks,
5
+ particularly for complex workflows like lead conversion.
6
+ """
7
+
8
+ from typing import Any, Dict, Tuple
9
+
10
+
11
+ def _validate_salesforce_convert_lead(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
12
+ """
13
+ Validate that a lead has been successfully converted to a contact.
14
+
15
+ This function checks:
16
+ 1. The active tab is the leads list page
17
+ 2. The lead has status 'Converted' and a convertedToContactId
18
+ 3. A new contact exists with the lead's information (name: Michael Brown)
19
+
20
+ Args:
21
+ initial_state: The initial state before the conversion
22
+ final_state: The final state after the conversion
23
+
24
+ Returns:
25
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
26
+ """
27
+ try:
28
+ # Check 1: Active tab should be the leads list page
29
+ active_tab_id = final_state.get("activeTabId")
30
+ if active_tab_id != "home-listLeads":
31
+ return 0.0, f"Expected activeTabId to be 'home-listLeads', got '{active_tab_id}'"
32
+
33
+ # Check 2: Lead should be marked as converted
34
+ leads = final_state.get("leads", [])
35
+ if not leads:
36
+ return 0.0, "No leads found in final state"
37
+
38
+ # Find the lead (should be lead-001)
39
+ lead = None
40
+ for temp_lead in leads:
41
+ if temp_lead.get("id") == "lead-001":
42
+ lead = temp_lead
43
+ break
44
+
45
+ if not lead:
46
+ return 0.0, "Lead with id 'lead-001' not found"
47
+
48
+ # Check lead status and convertedToContactId
49
+ lead_status = lead.get("leadStatus")
50
+ converted_to_contact_id = lead.get("convertedToContactId")
51
+
52
+ if lead_status != "Converted":
53
+ return 0.0, f"Expected leadStatus to be 'Converted', got '{lead_status}'"
54
+
55
+ if not converted_to_contact_id:
56
+ return 0.0, "Expected convertedToContactId to be set, but it's missing"
57
+
58
+ # Check 3: Contact should exist with the lead's information
59
+ contacts = final_state.get("contacts", [])
60
+ if not contacts:
61
+ return 0.0, "No contacts found in final state"
62
+
63
+ # Find the contact by the convertedToContactId
64
+ contact = None
65
+ for c in contacts:
66
+ if c.get("id") == converted_to_contact_id:
67
+ contact = c
68
+ break
69
+
70
+ if not contact:
71
+ return 0.0, f"Contact with id '{converted_to_contact_id}' not found"
72
+
73
+ # Verify the contact has the correct information (name should be Michael Brown)
74
+ contact_name = contact.get("name")
75
+ if contact_name != "Michael Brown":
76
+ return 0.0, f"Expected contact name to be 'Michael Brown', got '{contact_name}'"
77
+
78
+ # Additional validation: check that contact has the lead's company
79
+ contact_company = contact.get("company")
80
+ lead_company = lead.get("company")
81
+ if contact_company != lead_company:
82
+ return 0.0, f"Contact company '{contact_company}' doesn't match lead company '{lead_company}'"
83
+
84
+ # All checks passed
85
+ return 1.0, "Lead successfully converted to contact with correct information"
86
+
87
+ except Exception as e:
88
+ return 0.0, f"Error during validation: {str(e)}"
89
+
90
+
91
+ def _validate_salesforce_create_and_convert_lead(
92
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
93
+ ) -> Tuple[float, str]:
94
+ """
95
+ Validate that a lead has been created and successfully converted to a contact.
96
+
97
+ This function checks:
98
+ 1. The active tab is the leads list page
99
+ 2. A lead exists with name 'Robert Taylor' and status 'Converted'
100
+ 3. The lead has a convertedToContactId set
101
+ 4. A new contact exists with the lead's information
102
+ 5. The contact has the correct name and company
103
+
104
+ Args:
105
+ initial_state: The initial state before the creation and conversion
106
+ final_state: The final state after the creation and conversion
107
+
108
+ Returns:
109
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
110
+ """
111
+ try:
112
+ # Check 1: Active tab should be the leads list page
113
+ active_tab_id = final_state.get("activeTabId")
114
+ if active_tab_id != "home-listLeads":
115
+ return 0.0, f"Expected activeTabId to be 'home-listLeads', got '{active_tab_id}'"
116
+
117
+ # Check 2: Lead should exist and be marked as converted
118
+ leads = final_state.get("leads", [])
119
+ if not leads:
120
+ return 0.0, "No leads found in final state"
121
+
122
+ # Find the lead with name 'Robert Taylor'
123
+ robert_lead = None
124
+ for lead in leads:
125
+ if lead.get("name") == "Robert Taylor":
126
+ robert_lead = lead
127
+ break
128
+
129
+ if not robert_lead:
130
+ return 0.0, "Lead with name 'Robert Taylor' not found"
131
+
132
+ # Check lead status and convertedToContactId
133
+ lead_status = robert_lead.get("leadStatus")
134
+ converted_to_contact_id = robert_lead.get("convertedToContactId")
135
+
136
+ if lead_status != "Converted":
137
+ return 0.0, f"Expected leadStatus to be 'Converted', got '{lead_status}'"
138
+
139
+ if not converted_to_contact_id:
140
+ return 0.0, "Expected convertedToContactId to be set, but it's missing"
141
+
142
+ # Check 3: Contact should exist with the lead's information
143
+ contacts = final_state.get("contacts", [])
144
+ if not contacts:
145
+ return 0.0, "No contacts found in final state"
146
+
147
+ # Find the contact by the convertedToContactId
148
+ contact = None
149
+ for c in contacts:
150
+ if c.get("id") == converted_to_contact_id:
151
+ contact = c
152
+ break
153
+
154
+ if not contact:
155
+ return 0.0, f"Contact with id '{converted_to_contact_id}' not found"
156
+
157
+ # Verify the contact has the correct information
158
+ contact_name = contact.get("name")
159
+ if contact_name != "Robert Taylor":
160
+ return 0.0, f"Expected contact name to be 'Robert Taylor', got '{contact_name}'"
161
+
162
+ # Check that contact has the lead's company
163
+ contact_company = contact.get("company")
164
+ lead_company = robert_lead.get("company")
165
+ if contact_company != lead_company:
166
+ return 0.0, f"Contact company '{contact_company}' doesn't match lead company '{lead_company}'"
167
+
168
+ # Additional validation: check that contact has the lead's email
169
+ contact_email = contact.get("email")
170
+ lead_email = robert_lead.get("email")
171
+ if contact_email != lead_email:
172
+ return 0.0, f"Contact email '{contact_email}' doesn't match lead email '{lead_email}'"
173
+
174
+ # Verify the lead was created from scratch (not in initial state)
175
+ initial_leads = initial_state.get("leads", [])
176
+ initial_robert_exists = any(lead.get("name") == "Robert Taylor" for lead in initial_leads)
177
+ if initial_robert_exists:
178
+ return 0.0, "Lead 'Robert Taylor' already existed in initial state - should be newly created"
179
+
180
+ # All checks passed
181
+ return 1.0, "Lead 'Robert Taylor' successfully created and converted to contact with correct information"
182
+
183
+ except Exception as e:
184
+ return 0.0, f"Error during validation: {str(e)}"
185
+
186
+
187
+ def _validate_salesforce_create_new_lead(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
188
+ """
189
+ Validate that a new lead has been successfully created.
190
+
191
+ This function checks:
192
+ 1. The active tab is a lead details page
193
+ 2. A lead exists with name 'Jane Smith' and company 'Innovation Labs'
194
+ 3. The lead was not in the initial state (proves it was created)
195
+
196
+ Args:
197
+ initial_state: The initial state before the lead creation
198
+ final_state: The final state after the lead creation
199
+
200
+ Returns:
201
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
202
+ """
203
+ try:
204
+ # Check 1: Active tab should be a lead details page
205
+ active_tab_id = final_state.get("activeTabId")
206
+ if not active_tab_id or not active_tab_id.startswith("lead-"):
207
+ return 0.0, f"Expected activeTabId to start with 'lead-', got '{active_tab_id}'"
208
+
209
+ # Check 2: Lead should exist with correct information
210
+ leads = final_state.get("leads", [])
211
+ if not leads:
212
+ return 0.0, "No leads found in final state"
213
+
214
+ # Find the lead with name 'Jane Smith'
215
+ jane_lead = None
216
+ for lead in leads:
217
+ if lead.get("name") == "Jane Smith":
218
+ jane_lead = lead
219
+ break
220
+
221
+ if not jane_lead:
222
+ return 0.0, "Lead with name 'Jane Smith' not found"
223
+
224
+ # Check company
225
+ if jane_lead.get("company") != "Innovation Labs":
226
+ return 0.0, f"Expected company to be 'Innovation Labs', got '{jane_lead.get('company')}'"
227
+
228
+ # Check 3: Verify the lead was created from scratch
229
+ initial_leads = initial_state.get("leads", [])
230
+ initial_jane_exists = any(lead.get("name") == "Jane Smith" for lead in initial_leads)
231
+ if initial_jane_exists:
232
+ return 0.0, "Lead 'Jane Smith' already existed in initial state - should be newly created"
233
+
234
+ # All checks passed
235
+ return 1.0, "Lead 'Jane Smith' successfully created with correct information"
236
+
237
+ except Exception as e:
238
+ return 0.0, f"Error during validation: {str(e)}"
239
+
240
+
241
+ def _validate_salesforce_create_new_case(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
242
+ """
243
+ Validate that a new case has been successfully created.
244
+
245
+ This function checks:
246
+ 1. The active tab is a case details page
247
+ 2. A case exists with subject 'Technical support request'
248
+ 3. The case was not in the initial state (proves it was created)
249
+
250
+ Args:
251
+ initial_state: The initial state before the case creation
252
+ final_state: The final state after the case creation
253
+
254
+ Returns:
255
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
256
+ """
257
+ try:
258
+ # Check 1: Active tab should be a case details page
259
+ active_tab_id = final_state.get("activeTabId")
260
+ if not active_tab_id or not active_tab_id.startswith("case-"):
261
+ return 0.0, f"Expected activeTabId to start with 'case-', got '{active_tab_id}'"
262
+
263
+ # Check 2: Case should exist with correct subject
264
+ cases = final_state.get("cases", [])
265
+ if not cases:
266
+ return 0.0, "No cases found in final state"
267
+
268
+ # Find the case with subject 'Technical support request'
269
+ support_case = None
270
+ for case in cases:
271
+ if case.get("subject") == "Technical support request":
272
+ support_case = case
273
+ break
274
+
275
+ if not support_case:
276
+ return 0.0, "Case with subject 'Technical support request' not found"
277
+
278
+ # Check 3: Verify the case was created from scratch
279
+ initial_cases = initial_state.get("cases", [])
280
+ initial_case_exists = any(case.get("subject") == "Technical support request" for case in initial_cases)
281
+ if initial_case_exists:
282
+ return 0.0, "Case 'Technical support request' already existed in initial state - should be newly created"
283
+
284
+ # All checks passed
285
+ return 1.0, "Case 'Technical support request' successfully created"
286
+
287
+ except Exception as e:
288
+ return 0.0, f"Error during validation: {str(e)}"
289
+
290
+
291
+ def _validate_salesforce_edit_lead_inline(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
292
+ """
293
+ Validate that a lead's title has been successfully edited inline.
294
+
295
+ This function checks:
296
+ 1. Lead with id 'lead-001' exists
297
+ 2. The lead's title has been changed from 'VP of Sales' to 'Senior VP of Sales'
298
+ 3. Other lead fields remain unchanged
299
+
300
+ Args:
301
+ initial_state: The initial state before the edit
302
+ final_state: The final state after the edit
303
+
304
+ Returns:
305
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
306
+ """
307
+ try:
308
+ # Get the lead from both states
309
+ initial_leads = initial_state.get("leads", [])
310
+ final_leads = final_state.get("leads", [])
311
+
312
+ initial_lead = None
313
+ for lead in initial_leads:
314
+ if lead.get("id") == "lead-001":
315
+ initial_lead = lead
316
+ break
317
+
318
+ final_lead = None
319
+ for lead in final_leads:
320
+ if lead.get("id") == "lead-001":
321
+ final_lead = lead
322
+ break
323
+
324
+ if not initial_lead:
325
+ return 0.0, "Lead 'lead-001' not found in initial state"
326
+
327
+ if not final_lead:
328
+ return 0.0, "Lead 'lead-001' not found in final state"
329
+
330
+ # Check that title was updated correctly
331
+ if initial_lead.get("title") != "VP of Sales":
332
+ return 0.0, f"Initial title should be 'VP of Sales', got '{initial_lead.get('title')}'"
333
+
334
+ if final_lead.get("title") != "Senior VP of Sales":
335
+ return 0.0, f"Expected title to be 'Senior VP of Sales', got '{final_lead.get('title')}'"
336
+
337
+ # Check that other important fields remain unchanged
338
+ fields_to_check = ["name", "company", "email", "phone", "leadStatus"]
339
+ for field in fields_to_check:
340
+ if initial_lead.get(field) != final_lead.get(field):
341
+ return 0.0, f"Field '{field}' should not have changed, but it did"
342
+
343
+ # All checks passed
344
+ return 1.0, "Lead title successfully updated to 'Senior VP of Sales'"
345
+
346
+ except Exception as e:
347
+ return 0.0, f"Error during validation: {str(e)}"
348
+
349
+
350
+ def _validate_salesforce_create_and_close_case(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
351
+ """
352
+ Validate that a case has been created and successfully closed.
353
+
354
+ This function checks:
355
+ 1. The active tab is still a case details page
356
+ 2. A case exists with subject 'Customer complaint resolved' and status 'Closed'
357
+ 3. The case was not in the initial state (proves it was created)
358
+
359
+ Args:
360
+ initial_state: The initial state before the case creation and closure
361
+ final_state: The final state after the case creation and closure
362
+
363
+ Returns:
364
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
365
+ """
366
+ try:
367
+ # Check 1: Active tab should still be a case details page
368
+ active_tab_id = final_state.get("activeTabId")
369
+ if not active_tab_id or not active_tab_id.startswith("case-"):
370
+ return 0.0, f"Expected activeTabId to start with 'case-', got '{active_tab_id}'"
371
+
372
+ # Check 2: Case should exist with correct subject and be closed
373
+ cases = final_state.get("cases", [])
374
+ if not cases:
375
+ return 0.0, "No cases found in final state"
376
+
377
+ # Find the case with subject 'Customer complaint resolved'
378
+ complaint_case = None
379
+ for case in cases:
380
+ if case.get("subject") == "Customer complaint resolved":
381
+ complaint_case = case
382
+ break
383
+
384
+ if not complaint_case:
385
+ return 0.0, "Case with subject 'Customer complaint resolved' not found"
386
+
387
+ # Check case status
388
+ case_status = complaint_case.get("status")
389
+ if case_status != "Closed":
390
+ return 0.0, f"Expected case status to be 'Closed', got '{case_status}'"
391
+
392
+ # Check 3: Verify the case was created from scratch
393
+ initial_cases = initial_state.get("cases", [])
394
+ initial_case_exists = any(case.get("subject") == "Customer complaint resolved" for case in initial_cases)
395
+ if initial_case_exists:
396
+ return 0.0, "Case 'Customer complaint resolved' already existed in initial state - should be newly created"
397
+
398
+ # All checks passed
399
+ return 1.0, "Case 'Customer complaint resolved' successfully created and closed"
400
+
401
+ except Exception as e:
402
+ return 0.0, f"Error during validation: {str(e)}"
403
+
404
+
405
+ # Registry of Salesforce reward functions
406
+ REWARD_FUNCTIONS_SALESFORCE = {
407
+ "_validate_salesforce_convert_lead": _validate_salesforce_convert_lead,
408
+ "_validate_salesforce_create_and_convert_lead": _validate_salesforce_create_and_convert_lead,
409
+ "_validate_salesforce_create_new_lead": _validate_salesforce_create_new_lead,
410
+ "_validate_salesforce_create_new_case": _validate_salesforce_create_new_case,
411
+ "_validate_salesforce_edit_lead_inline": _validate_salesforce_edit_lead_inline,
412
+ "_validate_salesforce_create_and_close_case": _validate_salesforce_create_and_close_case,
413
+ }
414
+
415
+ __all__ = [
416
+ "REWARD_FUNCTIONS_SALESFORCE",
417
+ "_validate_salesforce_convert_lead",
418
+ "_validate_salesforce_create_and_convert_lead",
419
+ "_validate_salesforce_create_new_lead",
420
+ "_validate_salesforce_create_new_case",
421
+ "_validate_salesforce_edit_lead_inline",
422
+ "_validate_salesforce_create_and_close_case",
423
+ ]
rewards/tic_tac_toe.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward functions for tic-tac-toe game tasks.
3
+
4
+ Board is a 9-element array representing a 3x3 grid:
5
+ [0, 1, 2,
6
+ 3, 4, 5,
7
+ 6, 7, 8]
8
+
9
+ Players: "X" (human), "O" (computer), or null (empty)
10
+ """
11
+
12
+ import logging
13
+ from typing import Any, Dict, Tuple
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ def _validate_tic_tac_toe_make_first_move(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
19
+ """Validate that a move was made on previously empty board."""
20
+ if "board" not in final_state:
21
+ return 0.0, "No board in final state"
22
+
23
+ logger.debug(f"running reward function on state: {final_state}")
24
+
25
+ board = final_state["board"]
26
+
27
+ # Check if board has any non-null values
28
+ if all(cell is None for cell in board):
29
+ return 0.0, "Board is still empty - no move was made."
30
+
31
+ # Check if board has at least one X
32
+ if "X" in board:
33
+ return 1.0, "First move made successfully - X placed on board."
34
+
35
+ return 0.0, "No X found on board."
36
+
37
+
38
+ def _validate_take_center(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
39
+ """Validate that X was placed in center position (index 4)."""
40
+ if "board" not in final_state:
41
+ return 0.0, "No board in final state"
42
+
43
+ logger.debug(f"running reward function on state: {final_state}")
44
+
45
+ board = final_state["board"]
46
+
47
+ # Check if center position (index 4) contains X
48
+ if board[4] == "X":
49
+ return 1.0, "Center square successfully taken by X."
50
+
51
+ center_value = board[4] if board[4] is not None else "empty"
52
+ return 0.0, f"Center square not taken by X. Center is: {center_value}"
53
+
54
+
55
+ def _validate_block_computer_win(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
56
+ """Validate that X blocked computer's win at position 2."""
57
+ if "board" not in final_state:
58
+ return 0.0, "No board in final state"
59
+
60
+ logger.debug(f"running reward function on state: {final_state}")
61
+
62
+ board = final_state["board"]
63
+
64
+ # Check if position 2 (top-right) contains X
65
+ if board[2] != "X":
66
+ position_value = board[2] if board[2] is not None else "empty"
67
+ return 0.0, f"Position 2 not blocked by X. Position 2 is: {position_value}"
68
+
69
+ # Check that game is still ongoing (player hasn't lost)
70
+ winner = final_state.get("winner")
71
+ if winner == "O":
72
+ return 0.0, "Computer (O) won - blocking was unsuccessful."
73
+
74
+ return 1.0, "Successfully blocked computer's winning move at position 2."
75
+
76
+
77
+ # Registry of all tic-tac-toe reward functions
78
+ REWARD_FUNCTIONS_TIC_TAC_TOE = {
79
+ "_validate_tic_tac_toe_make_first_move": _validate_tic_tac_toe_make_first_move,
80
+ "_validate_take_center": _validate_take_center,
81
+ "_validate_block_computer_win": _validate_block_computer_win,
82
+ }