This view is limited to 50 files because it contains too many changes.  See the raw diff here.
Files changed (50) hide show
  1. rewards/__init__.py +37 -0
  2. rewards/__pycache__/amazon.cpython-312.pyc +0 -0
  3. rewards/__pycache__/game_2048.cpython-312.pyc +0 -0
  4. rewards/__pycache__/jd.cpython-312.pyc +0 -0
  5. rewards/__pycache__/linear.cpython-312.pyc +0 -0
  6. rewards/__pycache__/linkedin.cpython-312.pyc +0 -0
  7. rewards/__pycache__/minesweeper.cpython-312.pyc +0 -0
  8. rewards/__pycache__/salesforce.cpython-312.pyc +0 -0
  9. rewards/__pycache__/tic_tac_toe.cpython-312.pyc +0 -0
  10. rewards/__pycache__/weibo.cpython-312.pyc +0 -0
  11. rewards/__pycache__/xiaohongshu.cpython-312.pyc +0 -0
  12. rewards/amazon.py +2223 -0
  13. rewards/game_2048.py +168 -0
  14. rewards/jd.py +569 -0
  15. rewards/linear.py +255 -0
  16. rewards/linkedin.py +88 -0
  17. rewards/minesweeper.py +255 -0
  18. rewards/salesforce.py +423 -0
  19. rewards/tic_tac_toe.py +82 -0
  20. rewards/weibo.py +924 -0
  21. rewards/xiaohongshu.py +491 -0
  22. tasks/2048/create-two-high-tiles.json +2 -1
  23. tasks/2048/get-128-tile.json +2 -1
  24. tasks/2048/get-2048.json +2 -1
  25. tasks/2048/get-256-tile.json +2 -1
  26. tasks/2048/get-32-tile.json +2 -1
  27. tasks/2048/get-512-tile.json +2 -1
  28. tasks/2048/make-first-move.json +2 -1
  29. tasks/2048/move-tiles-right.json +2 -1
  30. tasks/2048/reach-540-sum.json +2 -1
  31. tasks/2048/strategic-32.json +3 -2
  32. tasks/action-tester/must-click.json +2 -1
  33. tasks/action-tester/must-complete-all-actions.json +2 -1
  34. tasks/action-tester/must-double-click.json +2 -1
  35. tasks/action-tester/must-drag.json +2 -1
  36. tasks/action-tester/must-hotkey.json +2 -1
  37. tasks/action-tester/must-middle-click.json +2 -1
  38. tasks/action-tester/must-perform-three-medium-actions.json +2 -1
  39. tasks/action-tester/must-right-click.json +2 -1
  40. tasks/action-tester/must-scroll.json +2 -1
  41. tasks/action-tester/must-type.json +2 -1
  42. tasks/amazon/customer-reviews-that-have-4-stars-and-above.json +0 -0
  43. tasks/amazon/customer-reviews-that-have-5-stars.json +0 -0
  44. tasks/amazon/entering-pod-in-the-search-bar.json +0 -0
  45. tasks/amazon/filter-on-amazon-global-store.json +0 -0
  46. tasks/amazon/filter-on-include-out-of-stock.json +0 -0
  47. tasks/amazon/filter-on-product-condition-renewed.json +0 -0
  48. tasks/amazon/filter-on-products-condition-new.json +0 -0
  49. tasks/amazon/filter-on-products-condition-used.json +0 -0
  50. tasks/amazon/filter-products-based-on-prime-delivery.json +0 -0
rewards/__init__.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.amazon import REWARD_FUNCTIONS_AMAZON
9
+ from dojo_sdk_core.dojos.rewards.game_2048 import REWARD_FUNCTIONS_2048
10
+ from dojo_sdk_core.dojos.rewards.linear import REWARD_FUNCTIONS_LINEAR
11
+ from dojo_sdk_core.dojos.rewards.linkedin import REWARD_FUNCTIONS_LINKEDIN
12
+ from dojo_sdk_core.dojos.rewards.minesweeper import REWARD_FUNCTIONS_MINESWEEPER
13
+ from dojo_sdk_core.dojos.rewards.salesforce import REWARD_FUNCTIONS_SALESFORCE
14
+ from dojo_sdk_core.dojos.rewards.tic_tac_toe import REWARD_FUNCTIONS_TIC_TAC_TOE
15
+ from dojo_sdk_core.dojos.rewards.xiaohongshu import REWARD_FUNCTIONS_XIAOHONGSHU
16
+ from dojo_sdk_core.dojos.rewards.weibo import REWARD_FUNCTIONS_WEIBO
17
+
18
+ # Unified registry of all reward functions
19
+ REWARD_FUNCTIONS = {
20
+ **REWARD_FUNCTIONS_AMAZON,
21
+ **REWARD_FUNCTIONS_2048,
22
+ **REWARD_FUNCTIONS_LINEAR,
23
+ **REWARD_FUNCTIONS_LINKEDIN,
24
+ **REWARD_FUNCTIONS_SALESFORCE,
25
+ **REWARD_FUNCTIONS_TIC_TAC_TOE,
26
+ **REWARD_FUNCTIONS_MINESWEEPER,
27
+ **REWARD_FUNCTIONS_XIAOHONGSHU,
28
+ **REWARD_FUNCTIONS_WEIBO,
29
+ }
30
+
31
+
32
+ def get_reward_function(name: str):
33
+ """Get a reward function by name from the unified registry."""
34
+ return REWARD_FUNCTIONS.get(name)
35
+
36
+
37
+ __all__ = ["REWARD_FUNCTIONS", "get_reward_function"]
rewards/__pycache__/amazon.cpython-312.pyc ADDED
Binary file (64.7 kB). View file
 
rewards/__pycache__/game_2048.cpython-312.pyc ADDED
Binary file (7.2 kB). View file
 
rewards/__pycache__/jd.cpython-312.pyc ADDED
Binary file (20.6 kB). View file
 
rewards/__pycache__/linear.cpython-312.pyc ADDED
Binary file (13.8 kB). View file
 
rewards/__pycache__/linkedin.cpython-312.pyc ADDED
Binary file (4.13 kB). View file
 
rewards/__pycache__/minesweeper.cpython-312.pyc ADDED
Binary file (9.57 kB). View file
 
rewards/__pycache__/salesforce.cpython-312.pyc ADDED
Binary file (15.5 kB). View file
 
rewards/__pycache__/tic_tac_toe.cpython-312.pyc ADDED
Binary file (3.11 kB). View file
 
rewards/__pycache__/weibo.cpython-312.pyc ADDED
Binary file (37.2 kB). View file
 
rewards/__pycache__/xiaohongshu.cpython-312.pyc ADDED
Binary file (23.8 kB). View file
 
rewards/amazon.py ADDED
@@ -0,0 +1,2223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward functions for Amazon 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_entering_pod_in_the_search_bar(
12
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
13
+ ) -> Tuple[float, str]:
14
+ """
15
+ Validate that the user successfully entered "pod" in the search bar and navigated to search results.
16
+
17
+ This function checks:
18
+ 1. The currentPage is "search"
19
+ 2. The searchQuery is "pod"
20
+ 3. The filteredProducts contains a product with id "B09G9FPHY6"
21
+
22
+ Args:
23
+ initial_state: The initial state before the search
24
+ final_state: The final state after the search
25
+
26
+ Returns:
27
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
28
+ """
29
+ try:
30
+ logger.debug(f"Running reward function on state: {final_state}")
31
+
32
+ # Check 1: currentPage should be "search"
33
+ current_page = final_state.get("currentPage")
34
+ if current_page != "search":
35
+ return (
36
+ 0.0,
37
+ f"Expected currentPage to be 'search', got '{current_page}'",
38
+ )
39
+
40
+ # Check 2: searchQuery should be "pod"
41
+ search_query = final_state.get("searchQuery", "")
42
+ if search_query.lower() != "pod":
43
+ return (
44
+ 0.0,
45
+ f"Expected searchQuery to be 'pod', got '{search_query}'",
46
+ )
47
+
48
+ # Check 3: filteredProducts should contain product with id "B09G9FPHY6"
49
+ filtered_products = final_state.get("filteredProducts", [])
50
+ if not filtered_products:
51
+ return 0.0, "No filtered products found in final state"
52
+
53
+ product_found = any(
54
+ product.get("id") == "B09G9FPHY6" for product in filtered_products
55
+ )
56
+
57
+ if not product_found:
58
+ return (
59
+ 0.0,
60
+ f"Product with id 'B09G9FPHY6' not found in filteredProducts. Found {len(filtered_products)} products.",
61
+ )
62
+
63
+ # All checks passed
64
+ return 1.0, "Successfully entered 'pod' in search bar and navigated to search results"
65
+
66
+ except Exception as e:
67
+ return 0.0, f"Error during validation: {str(e)}"
68
+
69
+
70
+ def _validate_filter_products_based_on_prime_delivery(
71
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
72
+ ) -> Tuple[float, str]:
73
+ """
74
+ Validate that the user successfully filtered products based on "Ships from United States" filter.
75
+
76
+ This function checks:
77
+ 1. The currentPage is "search"
78
+ 2. The searchQuery is "a"
79
+ 3. The filters object has shipsFromUnitedStates: true, minPrice: 0, maxPrice: 1000000, condition: [],
80
+ and all other keys set to false
81
+ 4. The filteredProducts contains all expected product IDs
82
+
83
+ Args:
84
+ initial_state: The initial state before filtering
85
+ final_state: The final state after filtering
86
+
87
+ Returns:
88
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
89
+ """
90
+ try:
91
+ logger.debug(f"Running reward function on state: {final_state}")
92
+
93
+ # Check 1: currentPage should be "search"
94
+ current_page = final_state.get("currentPage")
95
+ if current_page != "search":
96
+ return (
97
+ 0.0,
98
+ f"Expected currentPage to be 'search', got '{current_page}'",
99
+ )
100
+
101
+ # Check 2: searchQuery should be "a"
102
+ search_query = final_state.get("searchQuery", "")
103
+ if search_query.lower() != "a":
104
+ return (
105
+ 0.0,
106
+ f"Expected searchQuery to be 'a', got '{search_query}'",
107
+ )
108
+
109
+ # Check 3: Validate filters object
110
+ filters = final_state.get("filters", {})
111
+ if not filters:
112
+ return 0.0, "No filters found in final state"
113
+
114
+ errors = []
115
+
116
+ # Check required filter values
117
+ if filters.get("shipsFromUnitedStates") is not True:
118
+ errors.append("shipsFromUnitedStates should be True")
119
+
120
+ if filters.get("minPrice") != 0:
121
+ errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
122
+
123
+ if filters.get("maxPrice") != 1000000:
124
+ errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
125
+
126
+ condition = filters.get("condition", [])
127
+ if not isinstance(condition, list) or len(condition) != 0:
128
+ errors.append(f"condition should be empty array [], got {condition}")
129
+
130
+ # Check that all other boolean filters are False
131
+ boolean_filters_should_be_false = [
132
+ "internationalShipping",
133
+ "deliveryTomorrow",
134
+ "deliveryTwoDays",
135
+ "freeDelivery",
136
+ "isGlobalStore",
137
+ "includeOutOfStock",
138
+ ]
139
+
140
+ for filter_key in boolean_filters_should_be_false:
141
+ if filters.get(filter_key) is not False:
142
+ errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
143
+
144
+ # Check minRating should be null
145
+ if filters.get("minRating") is not None:
146
+ errors.append(f"minRating should be null, got {filters.get('minRating')}")
147
+
148
+ if errors:
149
+ return 0.0, "; ".join(errors)
150
+
151
+ # Check 4: Validate filteredProducts contain expected product IDs
152
+ filtered_products = final_state.get("filteredProducts", [])
153
+ if not filtered_products:
154
+ return 0.0, "No filtered products found in final state"
155
+
156
+ # Expected product IDs
157
+ expected_product_ids = {
158
+ "B08N5WRWNW",
159
+ "B09G9FPHY6",
160
+ "B0BSHF7WHW",
161
+ "B08L5VNJ2P",
162
+ "B0B2QJZF8D",
163
+ "CLOTH001",
164
+ "CLOTH002",
165
+ "ACC001",
166
+ "BOOK001",
167
+ "BEAUTY001",
168
+ "SPORTS001",
169
+ "PET001",
170
+ "GARDEN001",
171
+ "HEALTH001",
172
+ "OFFICE001",
173
+ "CLOTH003",
174
+ "GROCERY001",
175
+ }
176
+
177
+ # Extract product IDs from filtered products
178
+ actual_ids = {product.get("id") for product in filtered_products if product.get("id")}
179
+
180
+ # Check if all expected products are present
181
+ missing_ids = expected_product_ids - actual_ids
182
+
183
+ if missing_ids:
184
+ return (
185
+ 0.0,
186
+ f"Missing {len(missing_ids)} expected products: {sorted(list(missing_ids))[:10]}",
187
+ )
188
+
189
+ # All checks passed
190
+ return (
191
+ 1.0,
192
+ f"Successfully filtered products based on 'Ships from United States'. Found {len(filtered_products)} matching products.",
193
+ )
194
+
195
+ except Exception as e:
196
+ return 0.0, f"Error during validation: {str(e)}"
197
+
198
+
199
+ def _validate_filter_products_based_on_single_day_delivery(
200
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
201
+ ) -> Tuple[float, str]:
202
+ """
203
+ Validate that the user successfully filtered products based on "Get it within two days" filter.
204
+
205
+ This function checks:
206
+ 1. The currentPage is "search"
207
+ 2. The searchQuery is "a"
208
+ 3. The filters object has deliveryTomorrow: true, minPrice: 0, maxPrice: 1000000, condition: [],
209
+ and all other keys set to false
210
+ 4. The filteredProducts contains products with ids: B09G9FPHY6, HEALTH001
211
+
212
+ Args:
213
+ initial_state: The initial state before filtering
214
+ final_state: The final state after filtering
215
+
216
+ Returns:
217
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
218
+ """
219
+ try:
220
+ logger.debug(f"Running reward function on state: {final_state}")
221
+
222
+ # Check 1: currentPage should be "search"
223
+ current_page = final_state.get("currentPage")
224
+ if current_page != "search":
225
+ return (
226
+ 0.0,
227
+ f"Expected currentPage to be 'search', got '{current_page}'",
228
+ )
229
+
230
+ # Check 2: searchQuery should be "a"
231
+ search_query = final_state.get("searchQuery", "")
232
+ if search_query.lower() != "a":
233
+ return (
234
+ 0.0,
235
+ f"Expected searchQuery to be 'a', got '{search_query}'",
236
+ )
237
+
238
+ # Check 3: Validate filters object
239
+ filters = final_state.get("filters", {})
240
+ if not filters:
241
+ return 0.0, "No filters found in final state"
242
+
243
+ errors = []
244
+
245
+ # Check required filter values
246
+ if filters.get("deliveryTomorrow") is not True:
247
+ errors.append("deliveryTomorrow should be True")
248
+
249
+ if filters.get("minPrice") != 0:
250
+ errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
251
+
252
+ if filters.get("maxPrice") != 1000000:
253
+ errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
254
+
255
+ condition = filters.get("condition", [])
256
+ if not isinstance(condition, list) or len(condition) != 0:
257
+ errors.append(f"condition should be empty array [], got {condition}")
258
+
259
+ # Check that all other boolean filters are False
260
+ boolean_filters_should_be_false = [
261
+ "shipsFromUnitedStates",
262
+ "internationalShipping",
263
+ "deliveryTwoDays",
264
+ "freeDelivery",
265
+ "isGlobalStore",
266
+ "includeOutOfStock",
267
+ ]
268
+
269
+ for filter_key in boolean_filters_should_be_false:
270
+ if filters.get(filter_key) is not False:
271
+ errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
272
+
273
+ # Check minRating should be null
274
+ if filters.get("minRating") is not None:
275
+ errors.append(f"minRating should be null, got {filters.get('minRating')}")
276
+
277
+ if errors:
278
+ return 0.0, "; ".join(errors)
279
+
280
+ # Check 4: Validate filteredProducts contain expected product IDs
281
+ filtered_products = final_state.get("filteredProducts", [])
282
+ if not filtered_products:
283
+ return 0.0, "No filtered products found in final state"
284
+
285
+ # Expected product IDs
286
+ expected_product_ids = {
287
+ "B09G9FPHY6",
288
+ "HEALTH001",
289
+ }
290
+
291
+ # Extract product IDs from filtered products
292
+ actual_ids = {product.get("id") for product in filtered_products if product.get("id")}
293
+
294
+ # Check if all expected products are present
295
+ missing_ids = expected_product_ids - actual_ids
296
+
297
+ if missing_ids:
298
+ return (
299
+ 0.0,
300
+ f"Missing {len(missing_ids)} expected products: {sorted(list(missing_ids))}",
301
+ )
302
+
303
+ # All checks passed
304
+ return (
305
+ 1.0,
306
+ f"Successfully filtered products based on 'Get it within two days'. Found {len(filtered_products)} matching products.",
307
+ )
308
+
309
+ except Exception as e:
310
+ return 0.0, f"Error during validation: {str(e)}"
311
+
312
+ def _validate_filter_products_on_two_day_delivery(
313
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
314
+ ) -> Tuple[float, str]:
315
+ """
316
+ Validate that the user successfully filtered products based on "Get it within two days" filter.
317
+
318
+ This function checks:
319
+ 1. The currentPage is "search"
320
+ 2. The searchQuery is "a"
321
+ 3. The filters object has deliveryTwoDays: true, minPrice: 0, maxPrice: 1000000, condition: [],
322
+ and all other keys set to false
323
+ 4. The filteredProducts contains products with ids: B09G9FPHY6, HEALTH001
324
+
325
+ Args:
326
+ initial_state: The initial state before filtering
327
+ final_state: The final state after filtering
328
+
329
+ Returns:
330
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
331
+ """
332
+ try:
333
+ logger.debug(f"Running reward function on state: {final_state}")
334
+
335
+ # Check 1: currentPage should be "search"
336
+ current_page = final_state.get("currentPage")
337
+ if current_page != "search":
338
+ return (
339
+ 0.0,
340
+ f"Expected currentPage to be 'search', got '{current_page}'",
341
+ )
342
+
343
+ # Check 2: searchQuery should be "a"
344
+ search_query = final_state.get("searchQuery", "")
345
+ if search_query.lower() != "a":
346
+ return (
347
+ 0.0,
348
+ f"Expected searchQuery to be 'a', got '{search_query}'",
349
+ )
350
+
351
+ # Check 3: Validate filters object
352
+ filters = final_state.get("filters", {})
353
+ if not filters:
354
+ return 0.0, "No filters found in final state"
355
+
356
+ errors = []
357
+
358
+ # Check required filter values
359
+ if filters.get("deliveryTwoDays") is not True:
360
+ errors.append("deliveryTwoDays should be True")
361
+
362
+ if filters.get("minPrice") != 0:
363
+ errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
364
+
365
+ if filters.get("maxPrice") != 1000000:
366
+ errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
367
+
368
+ condition = filters.get("condition", [])
369
+ if not isinstance(condition, list) or len(condition) != 0:
370
+ errors.append(f"condition should be empty array [], got {condition}")
371
+
372
+ # Check that all other boolean filters are False
373
+ boolean_filters_should_be_false = [
374
+ "shipsFromUnitedStates",
375
+ "internationalShipping",
376
+ "deliveryTomorrow",
377
+ "freeDelivery",
378
+ "isGlobalStore",
379
+ "includeOutOfStock",
380
+ ]
381
+
382
+ for filter_key in boolean_filters_should_be_false:
383
+ if filters.get(filter_key) is not False:
384
+ errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
385
+
386
+ # Check minRating should be null
387
+ if filters.get("minRating") is not None:
388
+ errors.append(f"minRating should be null, got {filters.get('minRating')}")
389
+
390
+ if errors:
391
+ return 0.0, "; ".join(errors)
392
+
393
+ # Check 4: Validate filteredProducts contain expected product IDs
394
+ filtered_products = final_state.get("filteredProducts", [])
395
+ if not filtered_products:
396
+ return 0.0, "No filtered products found in final state"
397
+
398
+ # Expected product IDs
399
+ expected_product_ids = {
400
+ "B09G9FPHY6",
401
+ "HEALTH001",
402
+ }
403
+
404
+ # Extract product IDs from filtered products
405
+ actual_ids = {product.get("id") for product in filtered_products if product.get("id")}
406
+
407
+ # Check if all expected products are present
408
+ missing_ids = expected_product_ids - actual_ids
409
+
410
+ if missing_ids:
411
+ return (
412
+ 0.0,
413
+ f"Missing {len(missing_ids)} expected products: {sorted(list(missing_ids))}",
414
+ )
415
+
416
+ # All checks passed
417
+ return (
418
+ 1.0,
419
+ f"Successfully filtered products based on 'Get it within two days'. Found {len(filtered_products)} matching products.",
420
+ )
421
+
422
+ except Exception as e:
423
+ return 0.0, f"Error during validation: {str(e)}"
424
+
425
+
426
+ def _validate_filter_products_on_free_delivery(
427
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
428
+ ) -> Tuple[float, str]:
429
+ """
430
+ Validate that the user successfully filtered products based on "Free delivery" filter.
431
+
432
+ This function checks:
433
+ 1. The currentPage is "search"
434
+ 2. The searchQuery is "a"
435
+ 3. The filters object has freeDelivery: true, minPrice: 0, maxPrice: 1000000, condition: [],
436
+ and all other keys set to false
437
+ 4. The filteredProducts contains all expected product IDs
438
+
439
+ Args:
440
+ initial_state: The initial state before filtering
441
+ final_state: The final state after filtering
442
+
443
+ Returns:
444
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
445
+ """
446
+ try:
447
+ logger.debug(f"Running reward function on state: {final_state}")
448
+
449
+ # Check 1: currentPage should be "search"
450
+ current_page = final_state.get("currentPage")
451
+ if current_page != "search":
452
+ return (
453
+ 0.0,
454
+ f"Expected currentPage to be 'search', got '{current_page}'",
455
+ )
456
+
457
+ # Check 2: searchQuery should be "a"
458
+ search_query = final_state.get("searchQuery", "")
459
+ if search_query.lower() != "a":
460
+ return (
461
+ 0.0,
462
+ f"Expected searchQuery to be 'a', got '{search_query}'",
463
+ )
464
+
465
+ # Check 3: Validate filters object
466
+ filters = final_state.get("filters", {})
467
+ if not filters:
468
+ return 0.0, "No filters found in final state"
469
+
470
+ errors = []
471
+
472
+ # Check required filter values
473
+ if filters.get("freeDelivery") is not True:
474
+ errors.append("freeDelivery should be True")
475
+
476
+ if filters.get("minPrice") != 0:
477
+ errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
478
+
479
+ if filters.get("maxPrice") != 1000000:
480
+ errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
481
+
482
+ condition = filters.get("condition", [])
483
+ if not isinstance(condition, list) or len(condition) != 0:
484
+ errors.append(f"condition should be empty array [], got {condition}")
485
+
486
+ # Check that all other boolean filters are False
487
+ boolean_filters_should_be_false = [
488
+ "shipsFromUnitedStates",
489
+ "internationalShipping",
490
+ "deliveryTomorrow",
491
+ "deliveryTwoDays",
492
+ "isGlobalStore",
493
+ "includeOutOfStock",
494
+ ]
495
+
496
+ for filter_key in boolean_filters_should_be_false:
497
+ if filters.get(filter_key) is not False:
498
+ errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
499
+
500
+ # Check minRating should be null
501
+ if filters.get("minRating") is not None:
502
+ errors.append(f"minRating should be null, got {filters.get('minRating')}")
503
+
504
+ if errors:
505
+ return 0.0, "; ".join(errors)
506
+
507
+ # Check 4: Validate filteredProducts contain expected product IDs
508
+ filtered_products = final_state.get("filteredProducts", [])
509
+ if not filtered_products:
510
+ return 0.0, "No filtered products found in final state"
511
+
512
+ # Expected product IDs
513
+ expected_product_ids = {
514
+ "B08N5WRWNW",
515
+ "B09G9FPHY6",
516
+ "B0BSHF7WHW",
517
+ "B08L5VNJ2P",
518
+ "B0B2QJZF8D",
519
+ "CLOTH001",
520
+ "CLOTH002",
521
+ "BOOK001",
522
+ "BEAUTY001",
523
+ "SPORTS001",
524
+ "PET001",
525
+ "GARDEN001",
526
+ "HEALTH001",
527
+ "OFFICE001",
528
+ "CLOTH003",
529
+ "GROCERY001",
530
+ }
531
+
532
+ # Extract product IDs from filtered products
533
+ actual_ids = {product.get("id") for product in filtered_products if product.get("id")}
534
+
535
+ # Check if all expected products are present
536
+ missing_ids = expected_product_ids - actual_ids
537
+
538
+ if missing_ids:
539
+ return (
540
+ 0.0,
541
+ f"Missing {len(missing_ids)} expected products: {sorted(list(missing_ids))[:10]}",
542
+ )
543
+
544
+ # All checks passed
545
+ return (
546
+ 1.0,
547
+ f"Successfully filtered products based on 'Free delivery'. Found {len(filtered_products)} matching products.",
548
+ )
549
+
550
+ except Exception as e:
551
+ return 0.0, f"Error during validation: {str(e)}"
552
+
553
+
554
+ def _validate_customer_reviews_that_have_5_stars(
555
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
556
+ ) -> Tuple[float, str]:
557
+ """
558
+ Validate that the user successfully filtered products based on "Top Rated" (5 stars) filter.
559
+
560
+ This function checks:
561
+ 1. The currentPage is "search"
562
+ 2. The searchQuery is "a"
563
+ 3. The filters object has minRating: 5, minPrice: 0, maxPrice: 1000000, condition: [],
564
+ and all other keys set to false
565
+ 4. The filteredProducts contains product with id: B0BSHF7WHW
566
+
567
+ Args:
568
+ initial_state: The initial state before filtering
569
+ final_state: The final state after filtering
570
+
571
+ Returns:
572
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
573
+ """
574
+ try:
575
+ logger.debug(f"Running reward function on state: {final_state}")
576
+
577
+ # Check 1: currentPage should be "search"
578
+ current_page = final_state.get("currentPage")
579
+ if current_page != "search":
580
+ return (
581
+ 0.0,
582
+ f"Expected currentPage to be 'search', got '{current_page}'",
583
+ )
584
+
585
+ # Check 2: searchQuery should be "a"
586
+ search_query = final_state.get("searchQuery", "")
587
+ if search_query.lower() != "a":
588
+ return (
589
+ 0.0,
590
+ f"Expected searchQuery to be 'a', got '{search_query}'",
591
+ )
592
+
593
+ # Check 3: Validate filters object
594
+ filters = final_state.get("filters", {})
595
+ if not filters:
596
+ return 0.0, "No filters found in final state"
597
+
598
+ errors = []
599
+
600
+ # Check required filter values
601
+ if filters.get("minRating") != 5:
602
+ errors.append(f"minRating should be 5, got {filters.get('minRating')}")
603
+
604
+ if filters.get("minPrice") != 0:
605
+ errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
606
+
607
+ if filters.get("maxPrice") != 1000000:
608
+ errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
609
+
610
+ condition = filters.get("condition", [])
611
+ if not isinstance(condition, list) or len(condition) != 0:
612
+ errors.append(f"condition should be empty array [], got {condition}")
613
+
614
+ # Check that all other boolean filters are False
615
+ boolean_filters_should_be_false = [
616
+ "shipsFromUnitedStates",
617
+ "internationalShipping",
618
+ "deliveryTomorrow",
619
+ "deliveryTwoDays",
620
+ "freeDelivery",
621
+ "isGlobalStore",
622
+ "includeOutOfStock",
623
+ ]
624
+
625
+ for filter_key in boolean_filters_should_be_false:
626
+ if filters.get(filter_key) is not False:
627
+ errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
628
+
629
+ if errors:
630
+ return 0.0, "; ".join(errors)
631
+
632
+ # Check 4: Validate filteredProducts contain expected product ID
633
+ filtered_products = final_state.get("filteredProducts", [])
634
+ if not filtered_products:
635
+ return 0.0, "No filtered products found in final state"
636
+
637
+ # Expected product ID
638
+ expected_product_id = "B0BSHF7WHW"
639
+
640
+ # Check if the expected product is present
641
+ product_found = any(
642
+ product.get("id") == expected_product_id for product in filtered_products
643
+ )
644
+
645
+ if not product_found:
646
+ return (
647
+ 0.0,
648
+ f"Product with id '{expected_product_id}' not found in filteredProducts. Found {len(filtered_products)} products.",
649
+ )
650
+
651
+ # All checks passed
652
+ return (
653
+ 1.0,
654
+ f"Successfully filtered products based on 'Top Rated' (5 stars). Found {len(filtered_products)} matching products.",
655
+ )
656
+
657
+ except Exception as e:
658
+ return 0.0, f"Error during validation: {str(e)}"
659
+
660
+
661
+ def _validate_customer_reviews_that_have_4_stars_and_above(
662
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
663
+ ) -> Tuple[float, str]:
664
+ """
665
+ Validate that the user successfully filtered products based on "4 & Up" (4 stars and above) filter.
666
+
667
+ This function checks:
668
+ 1. The currentPage is "search"
669
+ 2. The searchQuery is "a"
670
+ 3. The filters object has minRating: 4, minPrice: 0, maxPrice: 1000000, condition: [],
671
+ and all other keys set to false
672
+ 4. The filteredProducts contains all expected product IDs
673
+
674
+ Args:
675
+ initial_state: The initial state before filtering
676
+ final_state: The final state after filtering
677
+
678
+ Returns:
679
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
680
+ """
681
+ try:
682
+ logger.debug(f"Running reward function on state: {final_state}")
683
+
684
+ # Check 1: currentPage should be "search"
685
+ current_page = final_state.get("currentPage")
686
+ if current_page != "search":
687
+ return (
688
+ 0.0,
689
+ f"Expected currentPage to be 'search', got '{current_page}'",
690
+ )
691
+
692
+ # Check 2: searchQuery should be "a"
693
+ search_query = final_state.get("searchQuery", "")
694
+ if search_query.lower() != "a":
695
+ return (
696
+ 0.0,
697
+ f"Expected searchQuery to be 'a', got '{search_query}'",
698
+ )
699
+
700
+ # Check 3: Validate filters object
701
+ filters = final_state.get("filters", {})
702
+ if not filters:
703
+ return 0.0, "No filters found in final state"
704
+
705
+ errors = []
706
+
707
+ # Check required filter values
708
+ if filters.get("minRating") != 4:
709
+ errors.append(f"minRating should be 4, got {filters.get('minRating')}")
710
+
711
+ if filters.get("minPrice") != 0:
712
+ errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
713
+
714
+ if filters.get("maxPrice") != 1000000:
715
+ errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
716
+
717
+ condition = filters.get("condition", [])
718
+ if not isinstance(condition, list) or len(condition) != 0:
719
+ errors.append(f"condition should be empty array [], got {condition}")
720
+
721
+ # Check that all other boolean filters are False
722
+ boolean_filters_should_be_false = [
723
+ "shipsFromUnitedStates",
724
+ "internationalShipping",
725
+ "deliveryTomorrow",
726
+ "deliveryTwoDays",
727
+ "freeDelivery",
728
+ "isGlobalStore",
729
+ "includeOutOfStock",
730
+ ]
731
+
732
+ for filter_key in boolean_filters_should_be_false:
733
+ if filters.get(filter_key) is not False:
734
+ errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
735
+
736
+ if errors:
737
+ return 0.0, "; ".join(errors)
738
+
739
+ # Check 4: Validate filteredProducts contain expected product IDs
740
+ filtered_products = final_state.get("filteredProducts", [])
741
+ if not filtered_products:
742
+ return 0.0, "No filtered products found in final state"
743
+
744
+ # Expected product IDs
745
+ expected_product_ids = {
746
+ "B09G9FPHY6",
747
+ "B0BSHF7WHW",
748
+ "B09B9VFKH5",
749
+ "B08L5VNJ2P",
750
+ "B0B2QJZF8D",
751
+ "CLOTH001",
752
+ "CLOTH002",
753
+ "ACC001",
754
+ "BOOK001",
755
+ "BEAUTY001",
756
+ "SPORTS001",
757
+ "PET001",
758
+ "GARDEN001",
759
+ "HEALTH001",
760
+ "OFFICE001",
761
+ "CLOTH003",
762
+ "GROCERY001",
763
+ }
764
+
765
+ # Extract product IDs from filtered products
766
+ actual_ids = {product.get("id") for product in filtered_products if product.get("id")}
767
+
768
+ # Check if all expected products are present
769
+ missing_ids = expected_product_ids - actual_ids
770
+
771
+ if missing_ids:
772
+ return (
773
+ 0.0,
774
+ f"Missing {len(missing_ids)} expected products: {sorted(list(missing_ids))[:10]}",
775
+ )
776
+
777
+ # All checks passed
778
+ return (
779
+ 1.0,
780
+ f"Successfully filtered products based on '4 & Up' (4 stars and above). Found {len(filtered_products)} matching products.",
781
+ )
782
+
783
+ except Exception as e:
784
+ return 0.0, f"Error during validation: {str(e)}"
785
+
786
+
787
+ def _validate_filter_products_with_prices_between_99_and_204(
788
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
789
+ ) -> Tuple[float, str]:
790
+ """
791
+ Validate that the user successfully filtered products using price range slider (99-204).
792
+
793
+ This function checks:
794
+ 1. The currentPage is "search"
795
+ 2. The searchQuery is "a"
796
+ 3. The filters object has minPrice: 99, maxPrice: 204, condition: [],
797
+ and all other keys set to false
798
+ 4. The filteredProducts contains all expected product IDs
799
+
800
+ Args:
801
+ initial_state: The initial state before filtering
802
+ final_state: The final state after filtering
803
+
804
+ Returns:
805
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
806
+ """
807
+ try:
808
+ logger.debug(f"Running reward function on state: {final_state}")
809
+
810
+ # Check 1: currentPage should be "search"
811
+ current_page = final_state.get("currentPage")
812
+ if current_page != "search":
813
+ return (
814
+ 0.0,
815
+ f"Expected currentPage to be 'search', got '{current_page}'",
816
+ )
817
+
818
+ # Check 2: searchQuery should be "a"
819
+ search_query = final_state.get("searchQuery", "")
820
+ if search_query.lower() != "a":
821
+ return (
822
+ 0.0,
823
+ f"Expected searchQuery to be 'a', got '{search_query}'",
824
+ )
825
+
826
+ # Check 3: Validate filters object
827
+ filters = final_state.get("filters", {})
828
+ if not filters:
829
+ return 0.0, "No filters found in final state"
830
+
831
+ errors = []
832
+
833
+ # Check required filter values
834
+ if filters.get("minPrice") != 99:
835
+ errors.append(f"minPrice should be 99, got {filters.get('minPrice')}")
836
+
837
+ if filters.get("maxPrice") != 204:
838
+ errors.append(f"maxPrice should be 204, got {filters.get('maxPrice')}")
839
+
840
+ condition = filters.get("condition", [])
841
+ if not isinstance(condition, list) or len(condition) != 0:
842
+ errors.append(f"condition should be empty array [], got {condition}")
843
+
844
+ # Check that all other boolean filters are False
845
+ boolean_filters_should_be_false = [
846
+ "shipsFromUnitedStates",
847
+ "internationalShipping",
848
+ "deliveryTomorrow",
849
+ "deliveryTwoDays",
850
+ "freeDelivery",
851
+ "isGlobalStore",
852
+ "includeOutOfStock",
853
+ ]
854
+
855
+ for filter_key in boolean_filters_should_be_false:
856
+ if filters.get(filter_key) is not False:
857
+ errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
858
+
859
+ # Check minRating should be null
860
+ if filters.get("minRating") is not None:
861
+ errors.append(f"minRating should be null, got {filters.get('minRating')}")
862
+
863
+ if errors:
864
+ return 0.0, "; ".join(errors)
865
+
866
+ # Check 4: Validate filteredProducts contain expected product IDs
867
+ filtered_products = final_state.get("filteredProducts", [])
868
+ if not filtered_products:
869
+ return 0.0, "No filtered products found in final state"
870
+
871
+ # Expected product IDs
872
+ expected_product_ids = {
873
+ "B0BSHF7WHW",
874
+ "B08L5VNJ2P",
875
+ "CLOTH001",
876
+ "CLOTH002",
877
+ "HEALTH001",
878
+ }
879
+
880
+ # Extract product IDs from filtered products
881
+ actual_ids = {product.get("id") for product in filtered_products if product.get("id")}
882
+
883
+ # Check if all expected products are present
884
+ missing_ids = expected_product_ids - actual_ids
885
+
886
+ if missing_ids:
887
+ return (
888
+ 0.0,
889
+ f"Missing {len(missing_ids)} expected products: {sorted(list(missing_ids))}",
890
+ )
891
+
892
+ # All checks passed
893
+ return (
894
+ 1.0,
895
+ f"Successfully filtered products using price range slider (99-204). Found {len(filtered_products)} matching products.",
896
+ )
897
+
898
+ except Exception as e:
899
+ return 0.0, f"Error during validation: {str(e)}"
900
+
901
+
902
+ def _validate_product_prices_up_to_90(
903
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
904
+ ) -> Tuple[float, str]:
905
+ """
906
+ Validate that the user successfully filtered products using "Up to $90" price filter.
907
+
908
+ This function checks:
909
+ 1. The currentPage is "search"
910
+ 2. The searchQuery is "a"
911
+ 3. The filters object has minPrice: 0, maxPrice: 90, condition: [],
912
+ and all other keys set to false
913
+ 4. The filteredProducts contains all expected product IDs
914
+
915
+ Args:
916
+ initial_state: The initial state before filtering
917
+ final_state: The final state after filtering
918
+
919
+ Returns:
920
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
921
+ """
922
+ try:
923
+ logger.debug(f"Running reward function on state: {final_state}")
924
+
925
+ # Check 1: currentPage should be "search"
926
+ current_page = final_state.get("currentPage")
927
+ if current_page != "search":
928
+ return (
929
+ 0.0,
930
+ f"Expected currentPage to be 'search', got '{current_page}'",
931
+ )
932
+
933
+ # Check 2: searchQuery should be "a"
934
+ search_query = final_state.get("searchQuery", "")
935
+ if search_query.lower() != "a":
936
+ return (
937
+ 0.0,
938
+ f"Expected searchQuery to be 'a', got '{search_query}'",
939
+ )
940
+
941
+ # Check 3: Validate filters object
942
+ filters = final_state.get("filters", {})
943
+ if not filters:
944
+ return 0.0, "No filters found in final state"
945
+
946
+ errors = []
947
+
948
+ # Check required filter values
949
+ if filters.get("minPrice") != 0:
950
+ errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
951
+
952
+ if filters.get("maxPrice") != 90:
953
+ errors.append(f"maxPrice should be 90, got {filters.get('maxPrice')}")
954
+
955
+ condition = filters.get("condition", [])
956
+ if not isinstance(condition, list) or len(condition) != 0:
957
+ errors.append(f"condition should be empty array [], got {condition}")
958
+
959
+ # Check that all other boolean filters are False
960
+ boolean_filters_should_be_false = [
961
+ "shipsFromUnitedStates",
962
+ "internationalShipping",
963
+ "deliveryTomorrow",
964
+ "deliveryTwoDays",
965
+ "freeDelivery",
966
+ "isGlobalStore",
967
+ "includeOutOfStock",
968
+ ]
969
+
970
+ for filter_key in boolean_filters_should_be_false:
971
+ if filters.get(filter_key) is not False:
972
+ errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
973
+
974
+ # Check minRating should be null
975
+ if filters.get("minRating") is not None:
976
+ errors.append(f"minRating should be null, got {filters.get('minRating')}")
977
+
978
+ if errors:
979
+ return 0.0, "; ".join(errors)
980
+
981
+ # Check 4: Validate filteredProducts contain expected product IDs
982
+ filtered_products = final_state.get("filteredProducts", [])
983
+ if not filtered_products:
984
+ return 0.0, "No filtered products found in final state"
985
+
986
+ # Expected product IDs
987
+ expected_product_ids = {
988
+ "B0B2QJZF8D",
989
+ "BOOK001",
990
+ "BEAUTY001",
991
+ "SPORTS001",
992
+ "PET001",
993
+ "GARDEN001",
994
+ "OFFICE001",
995
+ "CLOTH003",
996
+ "GROCERY001",
997
+ }
998
+
999
+ # Extract product IDs from filtered products
1000
+ actual_ids = {product.get("id") for product in filtered_products if product.get("id")}
1001
+
1002
+ # Check if all expected products are present
1003
+ missing_ids = expected_product_ids - actual_ids
1004
+
1005
+ if missing_ids:
1006
+ return (
1007
+ 0.0,
1008
+ f"Missing {len(missing_ids)} expected products: {sorted(list(missing_ids))}",
1009
+ )
1010
+
1011
+ # All checks passed
1012
+ return (
1013
+ 1.0,
1014
+ f"Successfully filtered products using price filter (Up to $90). Found {len(filtered_products)} matching products.",
1015
+ )
1016
+
1017
+ except Exception as e:
1018
+ return 0.0, f"Error during validation: {str(e)}"
1019
+
1020
+
1021
+ def _validate_products_prices_between_150_and_300(
1022
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
1023
+ ) -> Tuple[float, str]:
1024
+ """
1025
+ Validate that the user successfully filtered products using price range button ($150 to $350).
1026
+
1027
+ This function checks:
1028
+ 1. The currentPage is "search"
1029
+ 2. The searchQuery is "a"
1030
+ 3. The filters object has minPrice: 150, maxPrice: 300, condition: [],
1031
+ and all other keys set to false
1032
+ 4. The filteredProducts contains all expected product IDs
1033
+
1034
+ Args:
1035
+ initial_state: The initial state before filtering
1036
+ final_state: The final state after filtering
1037
+
1038
+ Returns:
1039
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
1040
+ """
1041
+ try:
1042
+ logger.debug(f"Running reward function on state: {final_state}")
1043
+
1044
+ # Check 1: currentPage should be "search"
1045
+ current_page = final_state.get("currentPage")
1046
+ if current_page != "search":
1047
+ return (
1048
+ 0.0,
1049
+ f"Expected currentPage to be 'search', got '{current_page}'",
1050
+ )
1051
+
1052
+ # Check 2: searchQuery should be "a"
1053
+ search_query = final_state.get("searchQuery", "")
1054
+ if search_query.lower() != "a":
1055
+ return (
1056
+ 0.0,
1057
+ f"Expected searchQuery to be 'a', got '{search_query}'",
1058
+ )
1059
+
1060
+ # Check 3: Validate filters object
1061
+ filters = final_state.get("filters", {})
1062
+ if not filters:
1063
+ return 0.0, "No filters found in final state"
1064
+
1065
+ errors = []
1066
+
1067
+ # Check required filter values
1068
+ if filters.get("minPrice") != 150:
1069
+ errors.append(f"minPrice should be 150, got {filters.get('minPrice')}")
1070
+
1071
+ if filters.get("maxPrice") != 300:
1072
+ errors.append(f"maxPrice should be 300, got {filters.get('maxPrice')}")
1073
+
1074
+ condition = filters.get("condition", [])
1075
+ if not isinstance(condition, list) or len(condition) != 0:
1076
+ errors.append(f"condition should be empty array [], got {condition}")
1077
+
1078
+ # Check that all other boolean filters are False
1079
+ boolean_filters_should_be_false = [
1080
+ "shipsFromUnitedStates",
1081
+ "internationalShipping",
1082
+ "deliveryTomorrow",
1083
+ "deliveryTwoDays",
1084
+ "freeDelivery",
1085
+ "isGlobalStore",
1086
+ "includeOutOfStock",
1087
+ ]
1088
+
1089
+ for filter_key in boolean_filters_should_be_false:
1090
+ if filters.get(filter_key) is not False:
1091
+ errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
1092
+
1093
+ # Check minRating should be null
1094
+ if filters.get("minRating") is not None:
1095
+ errors.append(f"minRating should be null, got {filters.get('minRating')}")
1096
+
1097
+ if errors:
1098
+ return 0.0, "; ".join(errors)
1099
+
1100
+ # Check 4: Validate filteredProducts contain expected product IDs
1101
+ filtered_products = final_state.get("filteredProducts", [])
1102
+ if not filtered_products:
1103
+ return 0.0, "No filtered products found in final state"
1104
+
1105
+ # Expected product IDs
1106
+ expected_product_ids = {
1107
+ "B08L5VNJ2P",
1108
+ "CLOTH002",
1109
+ }
1110
+
1111
+ # Extract product IDs from filtered products
1112
+ actual_ids = {product.get("id") for product in filtered_products if product.get("id")}
1113
+
1114
+ # Check if all expected products are present
1115
+ missing_ids = expected_product_ids - actual_ids
1116
+
1117
+ if missing_ids:
1118
+ return (
1119
+ 0.0,
1120
+ f"Missing {len(missing_ids)} expected products: {sorted(list(missing_ids))}",
1121
+ )
1122
+
1123
+ # All checks passed
1124
+ return (
1125
+ 1.0,
1126
+ f"Successfully filtered products using price range button ($150 to $350). Found {len(filtered_products)} matching products.",
1127
+ )
1128
+
1129
+ except Exception as e:
1130
+ return 0.0, f"Error during validation: {str(e)}"
1131
+
1132
+
1133
+ def _validate_products_with_prices_greater_than_700(
1134
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
1135
+ ) -> Tuple[float, str]:
1136
+ """
1137
+ Validate that the user successfully filtered products using "$700 and above" price filter.
1138
+
1139
+ This function checks:
1140
+ 1. The currentPage is "search"
1141
+ 2. The searchQuery is "a"
1142
+ 3. The filters object has minPrice: 700, maxPrice: 1000000, condition: [],
1143
+ and all other keys set to false
1144
+ 4. The filteredProducts contains product with id: B09B9VFKH5
1145
+
1146
+ Args:
1147
+ initial_state: The initial state before filtering
1148
+ final_state: The final state after filtering
1149
+
1150
+ Returns:
1151
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
1152
+ """
1153
+ try:
1154
+ logger.debug(f"Running reward function on state: {final_state}")
1155
+
1156
+ # Check 1: currentPage should be "search"
1157
+ current_page = final_state.get("currentPage")
1158
+ if current_page != "search":
1159
+ return (
1160
+ 0.0,
1161
+ f"Expected currentPage to be 'search', got '{current_page}'",
1162
+ )
1163
+
1164
+ # Check 2: searchQuery should be "a"
1165
+ search_query = final_state.get("searchQuery", "")
1166
+ if search_query.lower() != "a":
1167
+ return (
1168
+ 0.0,
1169
+ f"Expected searchQuery to be 'a', got '{search_query}'",
1170
+ )
1171
+
1172
+ # Check 3: Validate filters object
1173
+ filters = final_state.get("filters", {})
1174
+ if not filters:
1175
+ return 0.0, "No filters found in final state"
1176
+
1177
+ errors = []
1178
+
1179
+ # Check required filter values
1180
+ if filters.get("minPrice") != 700:
1181
+ errors.append(f"minPrice should be 700, got {filters.get('minPrice')}")
1182
+
1183
+ if filters.get("maxPrice") != 1000000:
1184
+ errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
1185
+
1186
+ condition = filters.get("condition", [])
1187
+ if not isinstance(condition, list) or len(condition) != 0:
1188
+ errors.append(f"condition should be empty array [], got {condition}")
1189
+
1190
+ # Check that all other boolean filters are False
1191
+ boolean_filters_should_be_false = [
1192
+ "shipsFromUnitedStates",
1193
+ "internationalShipping",
1194
+ "deliveryTomorrow",
1195
+ "deliveryTwoDays",
1196
+ "freeDelivery",
1197
+ "isGlobalStore",
1198
+ "includeOutOfStock",
1199
+ ]
1200
+
1201
+ for filter_key in boolean_filters_should_be_false:
1202
+ if filters.get(filter_key) is not False:
1203
+ errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
1204
+
1205
+ # Check minRating should be null
1206
+ if filters.get("minRating") is not None:
1207
+ errors.append(f"minRating should be null, got {filters.get('minRating')}")
1208
+
1209
+ if errors:
1210
+ return 0.0, "; ".join(errors)
1211
+
1212
+ # Check 4: Validate filteredProducts contain expected product ID
1213
+ filtered_products = final_state.get("filteredProducts", [])
1214
+ if not filtered_products:
1215
+ return 0.0, "No filtered products found in final state"
1216
+
1217
+ # Expected product ID
1218
+ expected_product_id = "B09B9VFKH5"
1219
+
1220
+ # Check if the expected product is present
1221
+ product_found = any(
1222
+ product.get("id") == expected_product_id for product in filtered_products
1223
+ )
1224
+
1225
+ if not product_found:
1226
+ return (
1227
+ 0.0,
1228
+ f"Product with id '{expected_product_id}' not found in filteredProducts. Found {len(filtered_products)} products.",
1229
+ )
1230
+
1231
+ # All checks passed
1232
+ return (
1233
+ 1.0,
1234
+ f"Successfully filtered products using '$700 and above' price filter. Found {len(filtered_products)} matching products.",
1235
+ )
1236
+
1237
+ except Exception as e:
1238
+ return 0.0, f"Error during validation: {str(e)}"
1239
+
1240
+
1241
+ def _validate_filter_on_products_condition_new(
1242
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
1243
+ ) -> Tuple[float, str]:
1244
+ """
1245
+ Validate that the user successfully filtered products using "New" condition filter.
1246
+
1247
+ This function checks:
1248
+ 1. The currentPage is "search"
1249
+ 2. The searchQuery is "a"
1250
+ 3. The filters object has condition: ['new'], minPrice: 0, maxPrice: 1000000,
1251
+ and all other keys set to false
1252
+ 4. The filteredProducts contains all expected product IDs
1253
+
1254
+ Args:
1255
+ initial_state: The initial state before filtering
1256
+ final_state: The final state after filtering
1257
+
1258
+ Returns:
1259
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
1260
+ """
1261
+ try:
1262
+ logger.debug(f"Running reward function on state: {final_state}")
1263
+
1264
+ # Check 1: currentPage should be "search"
1265
+ current_page = final_state.get("currentPage")
1266
+ if current_page != "search":
1267
+ return (
1268
+ 0.0,
1269
+ f"Expected currentPage to be 'search', got '{current_page}'",
1270
+ )
1271
+
1272
+ # Check 2: searchQuery should be "a"
1273
+ search_query = final_state.get("searchQuery", "")
1274
+ if search_query.lower() != "a":
1275
+ return (
1276
+ 0.0,
1277
+ f"Expected searchQuery to be 'a', got '{search_query}'",
1278
+ )
1279
+
1280
+ # Check 3: Validate filters object
1281
+ filters = final_state.get("filters", {})
1282
+ if not filters:
1283
+ return 0.0, "No filters found in final state"
1284
+
1285
+ errors = []
1286
+
1287
+ # Check required filter values
1288
+ condition = filters.get("condition", [])
1289
+ if not isinstance(condition, list) or condition != ["new"]:
1290
+ errors.append(f"condition should be ['new'], got {condition}")
1291
+
1292
+ if filters.get("minPrice") != 0:
1293
+ errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
1294
+
1295
+ if filters.get("maxPrice") != 1000000:
1296
+ errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
1297
+
1298
+ # Check that all other boolean filters are False
1299
+ boolean_filters_should_be_false = [
1300
+ "shipsFromUnitedStates",
1301
+ "internationalShipping",
1302
+ "deliveryTomorrow",
1303
+ "deliveryTwoDays",
1304
+ "freeDelivery",
1305
+ "isGlobalStore",
1306
+ "includeOutOfStock",
1307
+ ]
1308
+
1309
+ for filter_key in boolean_filters_should_be_false:
1310
+ if filters.get(filter_key) is not False:
1311
+ errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
1312
+
1313
+ # Check minRating should be null
1314
+ if filters.get("minRating") is not None:
1315
+ errors.append(f"minRating should be null, got {filters.get('minRating')}")
1316
+
1317
+ if errors:
1318
+ return 0.0, "; ".join(errors)
1319
+
1320
+ # Check 4: Validate filteredProducts contain expected product IDs
1321
+ filtered_products = final_state.get("filteredProducts", [])
1322
+ if not filtered_products:
1323
+ return 0.0, "No filtered products found in final state"
1324
+
1325
+ # Expected product IDs
1326
+ expected_product_ids = {
1327
+ "B08N5WRWNW",
1328
+ "B09G9FPHY6",
1329
+ "B0BSHF7WHW",
1330
+ "B09B9VFKH5",
1331
+ "B08L5VNJ2P",
1332
+ "B0B2QJZF8D",
1333
+ "CLOTH001",
1334
+ "CLOTH002",
1335
+ "ACC001",
1336
+ "BOOK001",
1337
+ "BEAUTY001",
1338
+ "SPORTS001",
1339
+ "PET001",
1340
+ "GARDEN001",
1341
+ "HEALTH001",
1342
+ "OFFICE001",
1343
+ "CLOTH003",
1344
+ "GROCERY001",
1345
+ }
1346
+
1347
+ # Extract product IDs from filtered products
1348
+ actual_ids = {product.get("id") for product in filtered_products if product.get("id")}
1349
+
1350
+ # Check if all expected products are present
1351
+ missing_ids = expected_product_ids - actual_ids
1352
+
1353
+ if missing_ids:
1354
+ return (
1355
+ 0.0,
1356
+ f"Missing {len(missing_ids)} expected products: {sorted(list(missing_ids))[:10]}",
1357
+ )
1358
+
1359
+ # All checks passed
1360
+ return (
1361
+ 1.0,
1362
+ f"Successfully filtered products using 'New' condition filter. Found {len(filtered_products)} matching products.",
1363
+ )
1364
+
1365
+ except Exception as e:
1366
+ return 0.0, f"Error during validation: {str(e)}"
1367
+
1368
+
1369
+ def _validate_filter_on_product_condition_renewed(
1370
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
1371
+ ) -> Tuple[float, str]:
1372
+ """
1373
+ Validate that the user successfully filtered products using "Renewed" condition filter.
1374
+
1375
+ This function checks:
1376
+ 1. The currentPage is "search"
1377
+ 2. The searchQuery is "a"
1378
+ 3. The filters object has condition: ['renewed'], minPrice: 0, maxPrice: 1000000,
1379
+ and all other keys set to false
1380
+ 4. The filteredProducts contains objects that have condition 'renewed'
1381
+
1382
+ Args:
1383
+ initial_state: The initial state before filtering
1384
+ final_state: The final state after filtering
1385
+
1386
+ Returns:
1387
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
1388
+ """
1389
+ try:
1390
+ logger.debug(f"Running reward function on state: {final_state}")
1391
+
1392
+ # Check 1: currentPage should be "search"
1393
+ current_page = final_state.get("currentPage")
1394
+ if current_page != "search":
1395
+ return (
1396
+ 0.0,
1397
+ f"Expected currentPage to be 'search', got '{current_page}'",
1398
+ )
1399
+
1400
+ # Check 2: searchQuery should be "a"
1401
+ search_query = final_state.get("searchQuery", "")
1402
+ if search_query.lower() != "a":
1403
+ return (
1404
+ 0.0,
1405
+ f"Expected searchQuery to be 'a', got '{search_query}'",
1406
+ )
1407
+
1408
+ # Check 3: Validate filters object
1409
+ filters = final_state.get("filters", {})
1410
+ if not filters:
1411
+ return 0.0, "No filters found in final state"
1412
+
1413
+ errors = []
1414
+
1415
+ # Check required filter values
1416
+ condition = filters.get("condition", [])
1417
+ if not isinstance(condition, list) or condition != ["renewed"]:
1418
+ errors.append(f"condition should be ['renewed'], got {condition}")
1419
+
1420
+ if filters.get("minPrice") != 0:
1421
+ errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
1422
+
1423
+ if filters.get("maxPrice") != 1000000:
1424
+ errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
1425
+
1426
+ # Check that all other boolean filters are False
1427
+ boolean_filters_should_be_false = [
1428
+ "shipsFromUnitedStates",
1429
+ "internationalShipping",
1430
+ "deliveryTomorrow",
1431
+ "deliveryTwoDays",
1432
+ "freeDelivery",
1433
+ "isGlobalStore",
1434
+ "includeOutOfStock",
1435
+ ]
1436
+
1437
+ for filter_key in boolean_filters_should_be_false:
1438
+ if filters.get(filter_key) is not False:
1439
+ errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
1440
+
1441
+ # Check minRating should be null
1442
+ if filters.get("minRating") is not None:
1443
+ errors.append(f"minRating should be null, got {filters.get('minRating')}")
1444
+
1445
+ if errors:
1446
+ return 0.0, "; ".join(errors)
1447
+
1448
+ # Check 4: Validate filteredProducts contain objects with condition 'renewed'
1449
+ filtered_products = final_state.get("filteredProducts", [])
1450
+ if not filtered_products:
1451
+ return 0.0, "No filtered products found in final state"
1452
+
1453
+ # Check that all products have condition 'renewed'
1454
+ products_without_renewed = [
1455
+ product.get("id", "unknown")
1456
+ for product in filtered_products
1457
+ if product.get("condition") != "renewed"
1458
+ ]
1459
+
1460
+ if products_without_renewed:
1461
+ return (
1462
+ 0.0,
1463
+ f"Found {len(products_without_renewed)} products without condition 'renewed': {products_without_renewed[:5]}",
1464
+ )
1465
+
1466
+ # All checks passed
1467
+ return (
1468
+ 1.0,
1469
+ f"Successfully filtered products using 'Renewed' condition filter. Found {len(filtered_products)} matching products.",
1470
+ )
1471
+
1472
+ except Exception as e:
1473
+ return 0.0, f"Error during validation: {str(e)}"
1474
+
1475
+
1476
+ def _validate_filter_on_products_condition_used(
1477
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
1478
+ ) -> Tuple[float, str]:
1479
+ """
1480
+ Validate that the user successfully filtered products using "Used" condition filter.
1481
+
1482
+ This function checks:
1483
+ 1. The currentPage is "search"
1484
+ 2. The searchQuery is "a"
1485
+ 3. The filters object has condition: ['used'], minPrice: 0, maxPrice: 1000000,
1486
+ and all other keys set to false
1487
+ 4. The filteredProducts contains objects that have condition 'used'
1488
+
1489
+ Args:
1490
+ initial_state: The initial state before filtering
1491
+ final_state: The final state after filtering
1492
+
1493
+ Returns:
1494
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
1495
+ """
1496
+ try:
1497
+ logger.debug(f"Running reward function on state: {final_state}")
1498
+
1499
+ # Check 1: currentPage should be "search"
1500
+ current_page = final_state.get("currentPage")
1501
+ if current_page != "search":
1502
+ return (
1503
+ 0.0,
1504
+ f"Expected currentPage to be 'search', got '{current_page}'",
1505
+ )
1506
+
1507
+ # Check 2: searchQuery should be "a"
1508
+ search_query = final_state.get("searchQuery", "")
1509
+ if search_query.lower() != "a":
1510
+ return (
1511
+ 0.0,
1512
+ f"Expected searchQuery to be 'a', got '{search_query}'",
1513
+ )
1514
+
1515
+ # Check 3: Validate filters object
1516
+ filters = final_state.get("filters", {})
1517
+ if not filters:
1518
+ return 0.0, "No filters found in final state"
1519
+
1520
+ errors = []
1521
+
1522
+ # Check required filter values
1523
+ condition = filters.get("condition", [])
1524
+ if not isinstance(condition, list) or condition != ["used"]:
1525
+ errors.append(f"condition should be ['used'], got {condition}")
1526
+
1527
+ if filters.get("minPrice") != 0:
1528
+ errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
1529
+
1530
+ if filters.get("maxPrice") != 1000000:
1531
+ errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
1532
+
1533
+ # Check that all other boolean filters are False
1534
+ boolean_filters_should_be_false = [
1535
+ "shipsFromUnitedStates",
1536
+ "internationalShipping",
1537
+ "deliveryTomorrow",
1538
+ "deliveryTwoDays",
1539
+ "freeDelivery",
1540
+ "isGlobalStore",
1541
+ "includeOutOfStock",
1542
+ ]
1543
+
1544
+ for filter_key in boolean_filters_should_be_false:
1545
+ if filters.get(filter_key) is not False:
1546
+ errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
1547
+
1548
+ # Check minRating should be null
1549
+ if filters.get("minRating") is not None:
1550
+ errors.append(f"minRating should be null, got {filters.get('minRating')}")
1551
+
1552
+ if errors:
1553
+ return 0.0, "; ".join(errors)
1554
+
1555
+ # Check 4: Validate filteredProducts contain objects with condition 'used'
1556
+ filtered_products = final_state.get("filteredProducts", [])
1557
+ if not filtered_products:
1558
+ return 0.0, "No filtered products found in final state"
1559
+
1560
+ # Check that all products have condition 'used'
1561
+ products_without_used = [
1562
+ product.get("id", "unknown")
1563
+ for product in filtered_products
1564
+ if product.get("condition") != "used"
1565
+ ]
1566
+
1567
+ if products_without_used:
1568
+ return (
1569
+ 0.0,
1570
+ f"Found {len(products_without_used)} products without condition 'used': {products_without_used[:5]}",
1571
+ )
1572
+
1573
+ # All checks passed
1574
+ return (
1575
+ 1.0,
1576
+ f"Successfully filtered products using 'Used' condition filter. Found {len(filtered_products)} matching products.",
1577
+ )
1578
+
1579
+ except Exception as e:
1580
+ return 0.0, f"Error during validation: {str(e)}"
1581
+
1582
+
1583
+ def _validate_filter_on_include_out_of_stock(
1584
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
1585
+ ) -> Tuple[float, str]:
1586
+ """
1587
+ Validate that the user successfully enabled "Include Out of Stock" filter.
1588
+
1589
+ This function checks:
1590
+ 1. The currentPage is "search"
1591
+ 2. The searchQuery is "a"
1592
+ 3. The filters object has includeOutOfStock: true, minPrice: 0, maxPrice: 1000000, condition: [],
1593
+ and all other keys set to false
1594
+ 4. The filteredProducts contains objects that have inStock key (can be True or False)
1595
+
1596
+ Args:
1597
+ initial_state: The initial state before filtering
1598
+ final_state: The final state after filtering
1599
+
1600
+ Returns:
1601
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
1602
+ """
1603
+ try:
1604
+ logger.debug(f"Running reward function on state: {final_state}")
1605
+
1606
+ # Check 1: currentPage should be "search"
1607
+ current_page = final_state.get("currentPage")
1608
+ if current_page != "search":
1609
+ return (
1610
+ 0.0,
1611
+ f"Expected currentPage to be 'search', got '{current_page}'",
1612
+ )
1613
+
1614
+ # Check 2: searchQuery should be "a"
1615
+ search_query = final_state.get("searchQuery", "")
1616
+ if search_query.lower() != "a":
1617
+ return (
1618
+ 0.0,
1619
+ f"Expected searchQuery to be 'a', got '{search_query}'",
1620
+ )
1621
+
1622
+ # Check 3: Validate filters object
1623
+ filters = final_state.get("filters", {})
1624
+ if not filters:
1625
+ return 0.0, "No filters found in final state"
1626
+
1627
+ errors = []
1628
+
1629
+ # Check required filter values
1630
+ if filters.get("includeOutOfStock") is not True:
1631
+ errors.append("includeOutOfStock should be True")
1632
+
1633
+ if filters.get("minPrice") != 0:
1634
+ errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
1635
+
1636
+ if filters.get("maxPrice") != 1000000:
1637
+ errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
1638
+
1639
+ condition = filters.get("condition", [])
1640
+ if not isinstance(condition, list) or len(condition) != 0:
1641
+ errors.append(f"condition should be empty array [], got {condition}")
1642
+
1643
+ # Check that all other boolean filters are False
1644
+ boolean_filters_should_be_false = [
1645
+ "shipsFromUnitedStates",
1646
+ "internationalShipping",
1647
+ "deliveryTomorrow",
1648
+ "deliveryTwoDays",
1649
+ "freeDelivery",
1650
+ "isGlobalStore",
1651
+ ]
1652
+
1653
+ for filter_key in boolean_filters_should_be_false:
1654
+ if filters.get(filter_key) is not False:
1655
+ errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
1656
+
1657
+ # Check minRating should be null
1658
+ if filters.get("minRating") is not None:
1659
+ errors.append(f"minRating should be null, got {filters.get('minRating')}")
1660
+
1661
+ if errors:
1662
+ return 0.0, "; ".join(errors)
1663
+
1664
+ # Check 4: Validate filteredProducts contain objects with inStock key
1665
+ filtered_products = final_state.get("filteredProducts", [])
1666
+ if not filtered_products:
1667
+ return 0.0, "No filtered products found in final state"
1668
+
1669
+ # Check that all products have inStock key (can be True or False)
1670
+ products_without_inStock = [
1671
+ product.get("id", "unknown")
1672
+ for product in filtered_products
1673
+ if "inStock" not in product
1674
+ ]
1675
+
1676
+ if products_without_inStock:
1677
+ return (
1678
+ 0.0,
1679
+ f"Found {len(products_without_inStock)} products without 'inStock' key: {products_without_inStock[:5]}",
1680
+ )
1681
+
1682
+ # All checks passed
1683
+ return (
1684
+ 1.0,
1685
+ f"Successfully enabled 'Include Out of Stock' filter. Found {len(filtered_products)} matching products.",
1686
+ )
1687
+
1688
+ except Exception as e:
1689
+ return 0.0, f"Error during validation: {str(e)}"
1690
+
1691
+
1692
+ def _validate_filter_on_amazon_global_store(
1693
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
1694
+ ) -> Tuple[float, str]:
1695
+ """
1696
+ Validate that the user successfully filtered products using "Amazon Global Store" filter.
1697
+
1698
+ This function checks:
1699
+ 1. The currentPage is "search"
1700
+ 2. The searchQuery is "a"
1701
+ 3. The filters object has isGlobalStore: true, minPrice: 0, maxPrice: 1000000, condition: [],
1702
+ and all other keys set to false
1703
+ 4. The filteredProducts contains objects that have isGlobalStore: True
1704
+
1705
+ Args:
1706
+ initial_state: The initial state before filtering
1707
+ final_state: The final state after filtering
1708
+
1709
+ Returns:
1710
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
1711
+ """
1712
+ try:
1713
+ logger.debug(f"Running reward function on state: {final_state}")
1714
+
1715
+ # Check 1: currentPage should be "search"
1716
+ current_page = final_state.get("currentPage")
1717
+ if current_page != "search":
1718
+ return (
1719
+ 0.0,
1720
+ f"Expected currentPage to be 'search', got '{current_page}'",
1721
+ )
1722
+
1723
+ # Check 2: searchQuery should be "a"
1724
+ search_query = final_state.get("searchQuery", "")
1725
+ if search_query.lower() != "a":
1726
+ return (
1727
+ 0.0,
1728
+ f"Expected searchQuery to be 'a', got '{search_query}'",
1729
+ )
1730
+
1731
+ # Check 3: Validate filters object
1732
+ filters = final_state.get("filters", {})
1733
+ if not filters:
1734
+ return 0.0, "No filters found in final state"
1735
+
1736
+ errors = []
1737
+
1738
+ # Check required filter values
1739
+ if filters.get("isGlobalStore") is not True:
1740
+ errors.append("isGlobalStore should be True")
1741
+
1742
+ if filters.get("minPrice") != 0:
1743
+ errors.append(f"minPrice should be 0, got {filters.get('minPrice')}")
1744
+
1745
+ if filters.get("maxPrice") != 1000000:
1746
+ errors.append(f"maxPrice should be 1000000, got {filters.get('maxPrice')}")
1747
+
1748
+ condition = filters.get("condition", [])
1749
+ if not isinstance(condition, list) or len(condition) != 0:
1750
+ errors.append(f"condition should be empty array [], got {condition}")
1751
+
1752
+ # Check that all other boolean filters are False
1753
+ boolean_filters_should_be_false = [
1754
+ "shipsFromUnitedStates",
1755
+ "internationalShipping",
1756
+ "deliveryTomorrow",
1757
+ "deliveryTwoDays",
1758
+ "freeDelivery",
1759
+ "includeOutOfStock",
1760
+ ]
1761
+
1762
+ for filter_key in boolean_filters_should_be_false:
1763
+ if filters.get(filter_key) is not False:
1764
+ errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
1765
+
1766
+ # Check minRating should be null
1767
+ if filters.get("minRating") is not None:
1768
+ errors.append(f"minRating should be null, got {filters.get('minRating')}")
1769
+
1770
+ if errors:
1771
+ return 0.0, "; ".join(errors)
1772
+
1773
+ # Check 4: Validate filteredProducts contain objects with isGlobalStore: True
1774
+ filtered_products = final_state.get("filteredProducts", [])
1775
+ if not filtered_products:
1776
+ return 0.0, "No filtered products found in final state"
1777
+
1778
+ # Check that all products have isGlobalStore: True
1779
+ products_without_global_store = [
1780
+ product.get("id", "unknown")
1781
+ for product in filtered_products
1782
+ if product.get("isGlobalStore") is not True
1783
+ ]
1784
+
1785
+ if products_without_global_store:
1786
+ return (
1787
+ 0.0,
1788
+ f"Found {len(products_without_global_store)} products without isGlobalStore=True: {products_without_global_store[:5]}",
1789
+ )
1790
+
1791
+ # All checks passed
1792
+ return (
1793
+ 1.0,
1794
+ f"Successfully filtered products using 'Amazon Global Store' filter. Found {len(filtered_products)} matching products.",
1795
+ )
1796
+
1797
+ except Exception as e:
1798
+ return 0.0, f"Error during validation: {str(e)}"
1799
+
1800
+
1801
+ def _validate_multiple_filters(
1802
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
1803
+ ) -> Tuple[float, str]:
1804
+ """
1805
+ Validate that the user successfully applied multiple filters simultaneously.
1806
+
1807
+ This function checks:
1808
+ 1. The currentPage is "search"
1809
+ 2. The searchQuery is "a"
1810
+ 3. The filters object has shipsFromUnitedStates: true, freeDelivery: true, minRating: 4,
1811
+ minPrice: 90, maxPrice: 150, condition: [], and all other keys set to false
1812
+ 4. The filteredProducts contains objects that match all filter criteria
1813
+
1814
+ Args:
1815
+ initial_state: The initial state before filtering
1816
+ final_state: The final state after filtering
1817
+
1818
+ Returns:
1819
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
1820
+ """
1821
+ try:
1822
+ logger.debug(f"Running reward function on state: {final_state}")
1823
+
1824
+ # Check 1: currentPage should be "search"
1825
+ current_page = final_state.get("currentPage")
1826
+ if current_page != "search":
1827
+ return (
1828
+ 0.0,
1829
+ f"Expected currentPage to be 'search', got '{current_page}'",
1830
+ )
1831
+
1832
+ # Check 2: searchQuery should be "a"
1833
+ search_query = final_state.get("searchQuery", "")
1834
+ if search_query.lower() != "a":
1835
+ return (
1836
+ 0.0,
1837
+ f"Expected searchQuery to be 'a', got '{search_query}'",
1838
+ )
1839
+
1840
+ # Check 3: Validate filters object
1841
+ filters = final_state.get("filters", {})
1842
+ if not filters:
1843
+ return 0.0, "No filters found in final state"
1844
+
1845
+ errors = []
1846
+
1847
+ # Check required filter values
1848
+ if filters.get("shipsFromUnitedStates") is not True:
1849
+ errors.append("shipsFromUnitedStates should be True")
1850
+
1851
+ if filters.get("freeDelivery") is not True:
1852
+ errors.append("freeDelivery should be True")
1853
+
1854
+ if filters.get("minRating") != 4:
1855
+ errors.append(f"minRating should be 4, got {filters.get('minRating')}")
1856
+
1857
+ if filters.get("minPrice") != 90:
1858
+ errors.append(f"minPrice should be 90, got {filters.get('minPrice')}")
1859
+
1860
+ if filters.get("maxPrice") != 150:
1861
+ errors.append(f"maxPrice should be 150, got {filters.get('maxPrice')}")
1862
+
1863
+ condition = filters.get("condition", [])
1864
+ if not isinstance(condition, list) or len(condition) != 0:
1865
+ errors.append(f"condition should be empty array [], got {condition}")
1866
+
1867
+ # Check that all other boolean filters are False
1868
+ boolean_filters_should_be_false = [
1869
+ "internationalShipping",
1870
+ "deliveryTomorrow",
1871
+ "deliveryTwoDays",
1872
+ "isGlobalStore",
1873
+ "includeOutOfStock",
1874
+ ]
1875
+
1876
+ for filter_key in boolean_filters_should_be_false:
1877
+ if filters.get(filter_key) is not False:
1878
+ errors.append(f"{filter_key} should be False, got {filters.get(filter_key)}")
1879
+
1880
+ if errors:
1881
+ return 0.0, "; ".join(errors)
1882
+
1883
+ # Check 4: Validate filteredProducts match all filter criteria
1884
+ filtered_products = final_state.get("filteredProducts", [])
1885
+ if not filtered_products:
1886
+ return 0.0, "No filtered products found in final state"
1887
+
1888
+ # Validate each product matches all criteria
1889
+ invalid_products = []
1890
+
1891
+ for product in filtered_products:
1892
+ product_id = product.get("id", "unknown")
1893
+ product_errors = []
1894
+
1895
+ # Check shipsFromUnitedStates
1896
+ if product.get("shipsFromUnitedStates") is not True:
1897
+ product_errors.append("shipsFromUnitedStates != True")
1898
+
1899
+ # Check rating >= 4
1900
+ rating = product.get("rating")
1901
+ if rating is None or rating < 4:
1902
+ product_errors.append(f"rating={rating} (expected >= 4)")
1903
+
1904
+ # Check price between 90 and 150 (inclusive)
1905
+ price = product.get("price")
1906
+ if price is None or price < 90 or price > 150:
1907
+ product_errors.append(f"price={price} (expected 90 <= price <= 150)")
1908
+
1909
+ # Check freeDelivery
1910
+ if product.get("freeDelivery") is not True:
1911
+ product_errors.append("freeDelivery != True")
1912
+
1913
+ if product_errors:
1914
+ invalid_products.append(f"{product_id}: {', '.join(product_errors)}")
1915
+
1916
+ if invalid_products:
1917
+ return (
1918
+ 0.0,
1919
+ f"Found {len(invalid_products)} products that don't match all filter criteria: {invalid_products[:3]}",
1920
+ )
1921
+
1922
+ # All checks passed
1923
+ return (
1924
+ 1.0,
1925
+ f"Successfully applied multiple filters (Ships from United States, Free Delivery, 4* & Up, $90-$150). Found {len(filtered_products)} matching products.",
1926
+ )
1927
+
1928
+ except Exception as e:
1929
+ return 0.0, f"Error during validation: {str(e)}"
1930
+
1931
+
1932
+ def _validate_navigate_from_search_page_to_product_page(
1933
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
1934
+ ) -> Tuple[float, str]:
1935
+ """
1936
+ Validate that the user successfully navigated from search page to a product page.
1937
+
1938
+ This function checks:
1939
+ 1. The currentPage is "product"
1940
+ 2. The selectedProduct has id "OFFICE001"
1941
+ 3. The searchQuery is "book" (preserved from search page)
1942
+
1943
+ Args:
1944
+ initial_state: The initial state before navigation
1945
+ final_state: The final state after navigation
1946
+
1947
+ Returns:
1948
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
1949
+ """
1950
+ try:
1951
+ logger.debug(f"Running reward function on state: {final_state}")
1952
+
1953
+ # Check 1: currentPage should be "product"
1954
+ current_page = final_state.get("currentPage")
1955
+ if current_page != "product":
1956
+ return (
1957
+ 0.0,
1958
+ f"Expected currentPage to be 'product', got '{current_page}'",
1959
+ )
1960
+
1961
+ # Check 2: selectedProduct should have id "OFFICE001"
1962
+ selected_product = final_state.get("selectedProduct")
1963
+ if selected_product is None:
1964
+ return 0.0, "Expected selectedProduct to be set, got null"
1965
+
1966
+ product_id = selected_product.get("id")
1967
+ if product_id != "OFFICE001":
1968
+ return (
1969
+ 0.0,
1970
+ f"Expected selectedProduct id to be 'OFFICE001', got '{product_id}'",
1971
+ )
1972
+
1973
+ # Check 3: searchQuery should be "book" (preserved from search page)
1974
+ search_query = final_state.get("searchQuery", "")
1975
+ if search_query.lower() != "book":
1976
+ return (
1977
+ 0.0,
1978
+ f"Expected searchQuery to be 'book', got '{search_query}'",
1979
+ )
1980
+
1981
+ # All checks passed
1982
+ product_name = selected_product.get("name", "Unknown Product")
1983
+ return (
1984
+ 1.0,
1985
+ f"Successfully navigated from search page to product page for '{product_name}' (ID: {product_id})",
1986
+ )
1987
+
1988
+ except Exception as e:
1989
+ return 0.0, f"Error during validation: {str(e)}"
1990
+
1991
+
1992
+ def _validate_navigate_from_home_to_product_page(
1993
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
1994
+ ) -> Tuple[float, str]:
1995
+ """
1996
+ Validate that the user successfully navigated from home page to a product page.
1997
+
1998
+ This function checks:
1999
+ 1. The currentPage is "product"
2000
+ 2. The selectedProduct has id "CLOTH002"
2001
+ 3. The searchQuery is empty string "" (since navigation is from home page)
2002
+
2003
+ Args:
2004
+ initial_state: The initial state before navigation
2005
+ final_state: The final state after navigation
2006
+
2007
+ Returns:
2008
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
2009
+ """
2010
+ try:
2011
+ logger.debug(f"Running reward function on state: {final_state}")
2012
+
2013
+ # Check 1: currentPage should be "product"
2014
+ current_page = final_state.get("currentPage")
2015
+ if current_page != "product":
2016
+ return (
2017
+ 0.0,
2018
+ f"Expected currentPage to be 'product', got '{current_page}'",
2019
+ )
2020
+
2021
+ # Check 2: selectedProduct should have id "CLOTH002"
2022
+ selected_product = final_state.get("selectedProduct")
2023
+ if selected_product is None:
2024
+ return 0.0, "Expected selectedProduct to be set, got null"
2025
+
2026
+ product_id = selected_product.get("id")
2027
+ if product_id != "CLOTH002":
2028
+ return (
2029
+ 0.0,
2030
+ f"Expected selectedProduct id to be 'CLOTH002', got '{product_id}'",
2031
+ )
2032
+
2033
+ # Check 3: searchQuery should be empty string (from home page)
2034
+ search_query = final_state.get("searchQuery", "")
2035
+ if search_query != "":
2036
+ return (
2037
+ 0.0,
2038
+ f"Expected searchQuery to be empty string '', got '{search_query}'",
2039
+ )
2040
+
2041
+ # All checks passed
2042
+ product_name = selected_product.get("name", "Unknown Product")
2043
+ return (
2044
+ 1.0,
2045
+ f"Successfully navigated from home page to product page for '{product_name}' (ID: {product_id})",
2046
+ )
2047
+
2048
+ except Exception as e:
2049
+ return 0.0, f"Error during validation: {str(e)}"
2050
+
2051
+
2052
+ def _validate_navigate_from_product_page_to_product_page(
2053
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
2054
+ ) -> Tuple[float, str]:
2055
+ """
2056
+ Validate that the user successfully navigated from one product page to another product page.
2057
+
2058
+ This function checks:
2059
+ 1. The currentPage is "product"
2060
+ 2. The selectedProduct has id "B08N5WRWNW"
2061
+ 3. The searchQuery is empty string "" (since navigation is from product page)
2062
+
2063
+ Args:
2064
+ initial_state: The initial state before navigation
2065
+ final_state: The final state after navigation
2066
+
2067
+ Returns:
2068
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
2069
+ """
2070
+ try:
2071
+ logger.debug(f"Running reward function on state: {final_state}")
2072
+
2073
+ # Check 1: currentPage should be "product"
2074
+ current_page = final_state.get("currentPage")
2075
+ if current_page != "product":
2076
+ return (
2077
+ 0.0,
2078
+ f"Expected currentPage to be 'product', got '{current_page}'",
2079
+ )
2080
+
2081
+ # Check 2: selectedProduct should have id "B08N5WRWNW"
2082
+ selected_product = final_state.get("selectedProduct")
2083
+ if selected_product is None:
2084
+ return 0.0, "Expected selectedProduct to be set, got null"
2085
+
2086
+ product_id = selected_product.get("id")
2087
+ if product_id != "B08N5WRWNW":
2088
+ return (
2089
+ 0.0,
2090
+ f"Expected selectedProduct id to be 'B08N5WRWNW', got '{product_id}'",
2091
+ )
2092
+
2093
+ # Check 3: searchQuery should be empty string (from product page)
2094
+ search_query = final_state.get("searchQuery", "")
2095
+ if search_query != "":
2096
+ return (
2097
+ 0.0,
2098
+ f"Expected searchQuery to be empty string '', got '{search_query}'",
2099
+ )
2100
+
2101
+ # All checks passed
2102
+ product_name = selected_product.get("name", "Unknown Product")
2103
+ return (
2104
+ 1.0,
2105
+ f"Successfully navigated from product page to product page for '{product_name}' (ID: {product_id})",
2106
+ )
2107
+
2108
+ except Exception as e:
2109
+ return 0.0, f"Error during validation: {str(e)}"
2110
+
2111
+
2112
+ def _validate_navigate_from_product_page_to_search_page(
2113
+ initial_state: Dict[str, Any], final_state: Dict[str, Any]
2114
+ ) -> Tuple[float, str]:
2115
+ """
2116
+ Validate that the user successfully navigated from product page to search page.
2117
+
2118
+ This function checks:
2119
+ 1. The currentPage is "search"
2120
+ 2. The searchQuery is "seven" (case-insensitive)
2121
+ 3. The filteredProducts contains a product with id "BOOK001"
2122
+
2123
+ Args:
2124
+ initial_state: The initial state before navigation
2125
+ final_state: The final state after navigation
2126
+
2127
+ Returns:
2128
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
2129
+ """
2130
+ try:
2131
+ logger.debug(f"Running reward function on state: {final_state}")
2132
+
2133
+ # Check 1: currentPage should be "search"
2134
+ current_page = final_state.get("currentPage")
2135
+ if current_page != "search":
2136
+ return (
2137
+ 0.0,
2138
+ f"Expected currentPage to be 'search', got '{current_page}'",
2139
+ )
2140
+
2141
+ # Check 2: searchQuery should be "seven" (case-insensitive)
2142
+ search_query = final_state.get("searchQuery", "")
2143
+ if search_query.lower() != "seven":
2144
+ return (
2145
+ 0.0,
2146
+ f"Expected searchQuery to be 'seven', got '{search_query}'",
2147
+ )
2148
+
2149
+ # Check 3: filteredProducts should contain product with id "BOOK001"
2150
+ filtered_products = final_state.get("filteredProducts", [])
2151
+ if not filtered_products:
2152
+ return 0.0, "No filtered products found in final state"
2153
+
2154
+ product_found = any(
2155
+ product.get("id") == "BOOK001" for product in filtered_products
2156
+ )
2157
+
2158
+ if not product_found:
2159
+ return (
2160
+ 0.0,
2161
+ f"Product with id 'BOOK001' not found in filteredProducts. Found {len(filtered_products)} products.",
2162
+ )
2163
+
2164
+ # All checks passed
2165
+ return (
2166
+ 1.0,
2167
+ f"Successfully navigated from product page to search page with query 'seven'. Found {len(filtered_products)} products.",
2168
+ )
2169
+
2170
+ except Exception as e:
2171
+ return 0.0, f"Error during validation: {str(e)}"
2172
+
2173
+
2174
+ # Registry of all Amazon reward functions
2175
+ REWARD_FUNCTIONS_AMAZON = {
2176
+ "_validate_entering_pod_in_the_search_bar": _validate_entering_pod_in_the_search_bar,
2177
+ "_validate_filter_products_based_on_prime_delivery": _validate_filter_products_based_on_prime_delivery,
2178
+ "_validate_filter_products_based_on_single_day_delivery": _validate_filter_products_based_on_single_day_delivery,
2179
+ "_validate_filter_products_on_two_day_delivery": _validate_filter_products_on_two_day_delivery,
2180
+ "_validate_filter_products_on_free_delivery": _validate_filter_products_on_free_delivery,
2181
+ "_validate_customer_reviews_that_have_5_stars": _validate_customer_reviews_that_have_5_stars,
2182
+ "_validate_customer_reviews_that_have_4_stars_and_above": _validate_customer_reviews_that_have_4_stars_and_above,
2183
+ "_validate_filter_products_with_prices_between_99_and_204": _validate_filter_products_with_prices_between_99_and_204,
2184
+ "_validate_product_prices_up_to_90": _validate_product_prices_up_to_90,
2185
+ "_validate_products_prices_between_150_and_300": _validate_products_prices_between_150_and_300,
2186
+ "_validate_products_with_prices_greater_than_700": _validate_products_with_prices_greater_than_700,
2187
+ "_validate_filter_on_products_condition_new": _validate_filter_on_products_condition_new,
2188
+ "_validate_filter_on_product_condition_renewed": _validate_filter_on_product_condition_renewed,
2189
+ "_validate_filter_on_products_condition_used": _validate_filter_on_products_condition_used,
2190
+ "_validate_filter_on_include_out_of_stock": _validate_filter_on_include_out_of_stock,
2191
+ "_validate_filter_on_amazon_global_store": _validate_filter_on_amazon_global_store,
2192
+ "_validate_multiple_filters": _validate_multiple_filters,
2193
+ "_validate_navigate_from_search_page_to_product_page": _validate_navigate_from_search_page_to_product_page,
2194
+ "_validate_navigate_from_home_to_product_page": _validate_navigate_from_home_to_product_page,
2195
+ "_validate_navigate_from_product_page_to_product_page": _validate_navigate_from_product_page_to_product_page,
2196
+ "_validate_navigate_from_product_page_to_search_page": _validate_navigate_from_product_page_to_search_page,
2197
+ }
2198
+
2199
+ __all__ = [
2200
+ "REWARD_FUNCTIONS_AMAZON",
2201
+ "_validate_entering_pod_in_the_search_bar",
2202
+ "_validate_filter_products_based_on_prime_delivery",
2203
+ "_validate_filter_products_based_on_single_day_delivery",
2204
+ "_validate_filter_products_on_two_day_delivery",
2205
+ "_validate_filter_products_on_free_delivery",
2206
+ "_validate_customer_reviews_that_have_5_stars",
2207
+ "_validate_customer_reviews_that_have_4_stars_and_above",
2208
+ "_validate_filter_products_with_prices_between_99_and_204",
2209
+ "_validate_product_prices_up_to_90",
2210
+ "_validate_products_prices_between_150_and_300",
2211
+ "_validate_products_with_prices_greater_than_700",
2212
+ "_validate_filter_on_products_condition_new",
2213
+ "_validate_filter_on_product_condition_renewed",
2214
+ "_validate_filter_on_products_condition_used",
2215
+ "_validate_filter_on_include_out_of_stock",
2216
+ "_validate_filter_on_amazon_global_store",
2217
+ "_validate_multiple_filters",
2218
+ "_validate_navigate_from_search_page_to_product_page",
2219
+ "_validate_navigate_from_home_to_product_page",
2220
+ "_validate_navigate_from_product_page_to_product_page",
2221
+ "_validate_navigate_from_product_page_to_search_page",
2222
+ ]
2223
+
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/jd.py ADDED
@@ -0,0 +1,569 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward functions for JD (JingDong) e-commerce SPA tasks.
3
+ """
4
+
5
+ import logging
6
+ from typing import Tuple
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ def _validate_go_to_the_cart_page_from_the_homepage(
12
+ initial_state: dict, final_state: dict
13
+ ) -> Tuple[float, str]:
14
+ """Validate navigation from homepage to cart page."""
15
+ try:
16
+ if "page" not in final_state:
17
+ return 0.0, "Missing 'page' field in final state"
18
+
19
+ if final_state["page"] != "cart":
20
+ return 0.0, f"Expected page='cart', got page='{final_state['page']}'"
21
+
22
+ return 1.0, "Successfully navigated to cart page"
23
+ except Exception as e:
24
+ logger.error(f"Error in _validate_go_to_the_cart_page_from_the_homepage: {e}")
25
+ return 0.0, f"Validation error: {str(e)}"
26
+
27
+
28
+ def _validate_go_to_a_product_page_from_home(
29
+ initial_state: dict, final_state: dict
30
+ ) -> Tuple[float, str]:
31
+ """Validate navigation from homepage to a product page."""
32
+ try:
33
+ if "page" not in final_state:
34
+ return 0.0, "Missing 'page' field in final state"
35
+
36
+ if final_state["page"] != "product":
37
+ return 0.0, f"Expected page='product', got page='{final_state['page']}'"
38
+
39
+ if "selectedProductId" not in final_state:
40
+ return 0.0, "Missing 'selectedProductId' in final state"
41
+
42
+ if final_state["selectedProductId"] != "2":
43
+ return 0.0, f"Expected selectedProductId='2', got '{final_state['selectedProductId']}'"
44
+
45
+ return 1.0, "Successfully navigated to product page with correct product"
46
+ except Exception as e:
47
+ logger.error(f"Error in _validate_go_to_a_product_page_from_home: {e}")
48
+ return 0.0, f"Validation error: {str(e)}"
49
+
50
+
51
+ def _validate_go_to_homepage_from_product_page(
52
+ initial_state: dict, final_state: dict
53
+ ) -> Tuple[float, str]:
54
+ """Validate navigation from product page to homepage."""
55
+ try:
56
+ if "page" not in final_state:
57
+ return 0.0, "Missing 'page' field in final state"
58
+
59
+ if final_state["page"] != "home":
60
+ return 0.0, f"Expected page='home', got page='{final_state['page']}'"
61
+
62
+ return 1.0, "Successfully navigated to homepage"
63
+ except Exception as e:
64
+ logger.error(f"Error in _validate_go_to_homepage_from_product_page: {e}")
65
+ return 0.0, f"Validation error: {str(e)}"
66
+
67
+
68
+ def _validate_go_to_cart_page_from_product_detail_page(
69
+ initial_state: dict, final_state: dict
70
+ ) -> Tuple[float, str]:
71
+ """Validate navigation from product detail page to cart page."""
72
+ try:
73
+ if "page" not in final_state:
74
+ return 0.0, "Missing 'page' field in final state"
75
+
76
+ if final_state["page"] != "cart":
77
+ return 0.0, f"Expected page='cart', got page='{final_state['page']}'"
78
+
79
+ return 1.0, "Successfully navigated to cart page from product detail"
80
+ except Exception as e:
81
+ logger.error(f"Error in _validate_go_to_cart_page_from_product_detail_page: {e}")
82
+ return 0.0, f"Validation error: {str(e)}"
83
+
84
+
85
+ def _validate_go_to_product_detail_from_search(
86
+ initial_state: dict, final_state: dict
87
+ ) -> Tuple[float, str]:
88
+ """Validate navigation from search page to product detail page."""
89
+ try:
90
+ if "page" not in final_state:
91
+ return 0.0, "Missing 'page' field in final state"
92
+
93
+ if final_state["page"] != "product":
94
+ return 0.0, f"Expected page='product', got page='{final_state['page']}'"
95
+
96
+ if "selectedProductId" not in final_state:
97
+ return 0.0, "Missing 'selectedProductId' in final state"
98
+
99
+ if not final_state["selectedProductId"]:
100
+ return 0.0, "selectedProductId is empty"
101
+
102
+ return 1.0, "Successfully navigated to product detail from search"
103
+ except Exception as e:
104
+ logger.error(f"Error in _validate_go_to_product_detail_from_search: {e}")
105
+ return 0.0, f"Validation error: {str(e)}"
106
+
107
+
108
+ def _validate_find_a_product_using_search_from_homepage(
109
+ initial_state: dict, final_state: dict
110
+ ) -> Tuple[float, str]:
111
+ """Validate searching for a product and navigating to its detail page."""
112
+ try:
113
+ if "page" not in final_state:
114
+ return 0.0, "Missing 'page' field in final state"
115
+
116
+ if final_state["page"] != "product":
117
+ return 0.0, f"Expected page='product', got page='{final_state['page']}'"
118
+
119
+ if "searchQuery" not in final_state:
120
+ return 0.0, "Missing 'searchQuery' in final state"
121
+
122
+ if "吉普衬衫" not in final_state["searchQuery"]:
123
+ return 0.0, f"Expected search query to contain '吉普衬衫', got '{final_state['searchQuery']}'"
124
+
125
+ if "selectedProductId" not in final_state:
126
+ return 0.0, "Missing 'selectedProductId' in final state"
127
+
128
+ if final_state["selectedProductId"] != "2":
129
+ return 0.0, f"Expected selectedProductId='2', got '{final_state['selectedProductId']}'"
130
+
131
+ return 1.0, "Successfully searched for product and navigated to detail page"
132
+ except Exception as e:
133
+ logger.error(f"Error in _validate_find_a_product_using_search_from_homepage: {e}")
134
+ return 0.0, f"Validation error: {str(e)}"
135
+
136
+
137
+ def _validate_search_吉普衬衫(
138
+ initial_state: dict, final_state: dict
139
+ ) -> Tuple[float, str]:
140
+ """Validate searching for '吉普衬衫' (JEEP shirt)."""
141
+ try:
142
+ if "searchQuery" not in final_state:
143
+ return 0.0, "Missing 'searchQuery' in final state"
144
+
145
+ if "吉普衬衫" not in final_state["searchQuery"]:
146
+ return 0.0, f"Expected search query to contain '吉普衬衫', got '{final_state['searchQuery']}'"
147
+
148
+ if "page" not in final_state:
149
+ return 0.0, "Missing 'page' field in final state"
150
+
151
+ if final_state["page"] != "search":
152
+ return 0.0, f"Expected page='search', got page='{final_state['page']}'"
153
+
154
+ return 1.0, "Successfully searched for 吉普衬衫"
155
+ except Exception as e:
156
+ logger.error(f"Error in _validate_search_吉普衬衫: {e}")
157
+ return 0.0, f"Validation error: {str(e)}"
158
+
159
+
160
+ def _validate_search_a_product_from_another_product_page(
161
+ initial_state: dict, final_state: dict
162
+ ) -> Tuple[float, str]:
163
+ """Validate searching for a product from another product page and navigating to it."""
164
+ try:
165
+ if "page" not in final_state:
166
+ return 0.0, "Missing 'page' field in final state"
167
+
168
+ if final_state["page"] != "product":
169
+ return 0.0, f"Expected page='product', got page='{final_state['page']}'"
170
+
171
+ if "searchQuery" not in final_state:
172
+ return 0.0, "Missing 'searchQuery' in final state"
173
+
174
+ if not final_state["searchQuery"]:
175
+ return 0.0, "searchQuery is empty"
176
+
177
+ if "selectedProductId" not in final_state:
178
+ return 0.0, "Missing 'selectedProductId' in final state"
179
+
180
+ if final_state["selectedProductId"] != "3":
181
+ return 0.0, f"Expected selectedProductId='3', got '{final_state['selectedProductId']}'"
182
+
183
+ return 1.0, "Successfully searched for product and navigated to detail page"
184
+ except Exception as e:
185
+ logger.error(f"Error in _validate_search_a_product_from_another_product_page: {e}")
186
+ return 0.0, f"Validation error: {str(e)}"
187
+
188
+
189
+ def _validate_add_a_product_to_cart(
190
+ initial_state: dict, final_state: dict
191
+ ) -> Tuple[float, str]:
192
+ """Validate adding a product to cart."""
193
+ try:
194
+ if "cart" not in final_state:
195
+ return 0.0, "Missing 'cart' field in final state"
196
+
197
+ cart = final_state["cart"]
198
+ if not isinstance(cart, list):
199
+ return 0.0, "cart is not a list"
200
+
201
+ # Check if product with id "2" is in cart with qty=1
202
+ product_in_cart = False
203
+ for item in cart:
204
+ if item.get("productId") == "2" and item.get("qty") == 1:
205
+ product_in_cart = True
206
+ break
207
+
208
+ if not product_in_cart:
209
+ return 0.0, "Expected product with id '2' and qty=1 in cart"
210
+
211
+ return 1.0, "Successfully added product to cart"
212
+ except Exception as e:
213
+ logger.error(f"Error in _validate_add_a_product_to_cart: {e}")
214
+ return 0.0, f"Validation error: {str(e)}"
215
+
216
+
217
+ def _validate_add_a_product_from_search_result_to_cart(
218
+ initial_state: dict, final_state: dict
219
+ ) -> Tuple[float, str]:
220
+ """Validate adding a product from search results to cart."""
221
+ try:
222
+ if "cart" not in final_state:
223
+ return 0.0, "Missing 'cart' field in final state"
224
+
225
+ cart = final_state["cart"]
226
+ if not isinstance(cart, list):
227
+ return 0.0, "cart is not a list"
228
+
229
+ # Check if any product is in cart
230
+ if len(cart) == 0:
231
+ return 0.0, "Cart is empty"
232
+
233
+ # Check if at least one item has qty >= 1
234
+ has_valid_item = False
235
+ for item in cart:
236
+ if item.get("qty", 0) >= 1:
237
+ has_valid_item = True
238
+ break
239
+
240
+ if not has_valid_item:
241
+ return 0.0, "No valid items in cart"
242
+
243
+ return 1.0, "Successfully added product from search to cart"
244
+ except Exception as e:
245
+ logger.error(f"Error in _validate_add_a_product_from_search_result_to_cart: {e}")
246
+ return 0.0, f"Validation error: {str(e)}"
247
+
248
+
249
+ def _validate_add_an_item_from_the_homepage(
250
+ initial_state: dict, final_state: dict
251
+ ) -> Tuple[float, str]:
252
+ """Validate adding an item from the homepage to cart."""
253
+ try:
254
+ if "cart" not in final_state:
255
+ return 0.0, "Missing 'cart' field in final state"
256
+
257
+ cart = final_state["cart"]
258
+ if not isinstance(cart, list):
259
+ return 0.0, "cart is not a list"
260
+
261
+ if len(cart) == 0:
262
+ return 0.0, "Cart is empty"
263
+
264
+ # Check if any item was added
265
+ initial_cart_len = len(initial_state.get("cart", []))
266
+ if len(cart) <= initial_cart_len:
267
+ return 0.0, "No new items added to cart"
268
+
269
+ return 1.0, "Successfully added item from homepage to cart"
270
+ except Exception as e:
271
+ logger.error(f"Error in _validate_add_an_item_from_the_homepage: {e}")
272
+ return 0.0, f"Validation error: {str(e)}"
273
+
274
+
275
+ def _validate_add_an_item_with_3_quantity(
276
+ initial_state: dict, final_state: dict
277
+ ) -> Tuple[float, str]:
278
+ """Validate adding an item with quantity 3 to cart."""
279
+ try:
280
+ if "cart" not in final_state:
281
+ return 0.0, "Missing 'cart' field in final state"
282
+
283
+ cart = final_state["cart"]
284
+ if not isinstance(cart, list):
285
+ return 0.0, "cart is not a list"
286
+
287
+ # Check if any item has qty=3
288
+ has_qty_3 = False
289
+ for item in cart:
290
+ if item.get("qty") == 3:
291
+ has_qty_3 = True
292
+ break
293
+
294
+ if not has_qty_3:
295
+ return 0.0, "No item with qty=3 found in cart"
296
+
297
+ return 1.0, "Successfully added item with quantity 3"
298
+ except Exception as e:
299
+ logger.error(f"Error in _validate_add_an_item_with_3_quantity: {e}")
300
+ return 0.0, f"Validation error: {str(e)}"
301
+
302
+
303
+ def _validate_remove_one_item_from_cart(
304
+ initial_state: dict, final_state: dict
305
+ ) -> Tuple[float, str]:
306
+ """Validate removing one item from cart."""
307
+ try:
308
+ if "cart" not in final_state:
309
+ return 0.0, "Missing 'cart' field in final state"
310
+
311
+ cart = final_state["cart"]
312
+ if not isinstance(cart, list):
313
+ return 0.0, "cart is not a list"
314
+
315
+ if len(cart) != 0:
316
+ return 0.0, f"Expected empty cart, but found {len(cart)} items"
317
+
318
+ return 1.0, "Successfully removed item from cart"
319
+ except Exception as e:
320
+ logger.error(f"Error in _validate_remove_one_item_from_cart: {e}")
321
+ return 0.0, f"Validation error: {str(e)}"
322
+
323
+
324
+ def _validate_remove_multiple_items_in_the_cart(
325
+ initial_state: dict, final_state: dict
326
+ ) -> Tuple[float, str]:
327
+ """Validate removing multiple items from cart."""
328
+ try:
329
+ if "cart" not in final_state:
330
+ return 0.0, "Missing 'cart' field in final state"
331
+
332
+ cart = final_state["cart"]
333
+ if not isinstance(cart, list):
334
+ return 0.0, "cart is not a list"
335
+
336
+ if len(cart) != 0:
337
+ return 0.0, f"Expected empty cart, but found {len(cart)} items"
338
+
339
+ return 1.0, "Successfully removed all items from cart"
340
+ except Exception as e:
341
+ logger.error(f"Error in _validate_remove_multiple_items_in_the_cart: {e}")
342
+ return 0.0, f"Validation error: {str(e)}"
343
+
344
+
345
+ def _validate_increase_an_item_and_reduce_another_item(
346
+ initial_state: dict, final_state: dict
347
+ ) -> Tuple[float, str]:
348
+ """Validate increasing quantity of one item and reducing another."""
349
+ try:
350
+ if "cart" not in final_state or "cart" not in initial_state:
351
+ return 0.0, "Missing 'cart' field in states"
352
+
353
+ initial_cart = initial_state["cart"]
354
+ final_cart = final_state["cart"]
355
+
356
+ if not isinstance(initial_cart, list) or not isinstance(final_cart, list):
357
+ return 0.0, "cart is not a list"
358
+
359
+ # Build dictionaries for comparison
360
+ initial_quantities = {item["productId"]: item["qty"] for item in initial_cart}
361
+ final_quantities = {item["productId"]: item["qty"] for item in final_cart}
362
+
363
+ increased_count = 0
364
+ decreased_count = 0
365
+
366
+ for product_id in set(initial_quantities.keys()) | set(final_quantities.keys()):
367
+ initial_qty = initial_quantities.get(product_id, 0)
368
+ final_qty = final_quantities.get(product_id, 0)
369
+
370
+ if final_qty > initial_qty:
371
+ increased_count += 1
372
+ elif final_qty < initial_qty:
373
+ decreased_count += 1
374
+
375
+ if increased_count < 1:
376
+ return 0.0, "No item quantity was increased"
377
+
378
+ if decreased_count < 1:
379
+ return 0.0, "No item quantity was decreased"
380
+
381
+ return 1.0, "Successfully increased one item and reduced another"
382
+ except Exception as e:
383
+ logger.error(f"Error in _validate_increase_an_item_and_reduce_another_item: {e}")
384
+ return 0.0, f"Validation error: {str(e)}"
385
+
386
+
387
+ def _validate_reduce_an_item_quantity_in_the_cart(
388
+ initial_state: dict, final_state: dict
389
+ ) -> Tuple[float, str]:
390
+ """Validate reducing quantity of an item in cart."""
391
+ try:
392
+ if "cart" not in final_state or "cart" not in initial_state:
393
+ return 0.0, "Missing 'cart' field in states"
394
+
395
+ initial_cart = initial_state["cart"]
396
+ final_cart = final_state["cart"]
397
+
398
+ if not isinstance(initial_cart, list) or not isinstance(final_cart, list):
399
+ return 0.0, "cart is not a list"
400
+
401
+ # Build dictionaries for comparison
402
+ initial_quantities = {item["productId"]: item["qty"] for item in initial_cart}
403
+ final_quantities = {item["productId"]: item["qty"] for item in final_cart}
404
+
405
+ # Check if any item quantity was reduced
406
+ reduced = False
407
+ for product_id in initial_quantities:
408
+ if final_quantities.get(product_id, 0) < initial_quantities[product_id]:
409
+ reduced = True
410
+ break
411
+
412
+ if not reduced:
413
+ return 0.0, "No item quantity was reduced"
414
+
415
+ return 1.0, "Successfully reduced item quantity"
416
+ except Exception as e:
417
+ logger.error(f"Error in _validate_reduce_an_item_quantity_in_the_cart: {e}")
418
+ return 0.0, f"Validation error: {str(e)}"
419
+
420
+
421
+ def _validate_search_and_add_two_items_to_cart(
422
+ initial_state: dict, final_state: dict
423
+ ) -> Tuple[float, str]:
424
+ """Validate searching and adding two items to cart."""
425
+ try:
426
+ if "cart" not in final_state:
427
+ return 0.0, "Missing 'cart' field in final state"
428
+
429
+ cart = final_state["cart"]
430
+ if not isinstance(cart, list):
431
+ return 0.0, "cart is not a list"
432
+
433
+ if len(cart) < 2:
434
+ return 0.0, f"Expected at least 2 items in cart, found {len(cart)}"
435
+
436
+ return 1.0, "Successfully added two items to cart"
437
+ except Exception as e:
438
+ logger.error(f"Error in _validate_search_and_add_two_items_to_cart: {e}")
439
+ return 0.0, f"Validation error: {str(e)}"
440
+
441
+
442
+ def _validate_search_and_add_item_to_cart_and_back_to_home(
443
+ initial_state: dict, final_state: dict
444
+ ) -> Tuple[float, str]:
445
+ """Validate searching, adding item to cart, and returning to homepage."""
446
+ try:
447
+ if "page" not in final_state:
448
+ return 0.0, "Missing 'page' field in final state"
449
+
450
+ if final_state["page"] != "home":
451
+ return 0.0, f"Expected page='home', got page='{final_state['page']}'"
452
+
453
+ if "cart" not in final_state:
454
+ return 0.0, "Missing 'cart' field in final state"
455
+
456
+ cart = final_state["cart"]
457
+ if not isinstance(cart, list):
458
+ return 0.0, "cart is not a list"
459
+
460
+ if len(cart) == 0:
461
+ return 0.0, "Cart is empty"
462
+
463
+ return 1.0, "Successfully added item to cart and returned to homepage"
464
+ except Exception as e:
465
+ logger.error(f"Error in _validate_search_and_add_item_to_cart_and_back_to_home: {e}")
466
+ return 0.0, f"Validation error: {str(e)}"
467
+
468
+
469
+ def _validate_remove_item_from_cart_then_search_and_add_item(
470
+ initial_state: dict, final_state: dict
471
+ ) -> Tuple[float, str]:
472
+ """Validate removing item from cart, then searching and adding new item."""
473
+ try:
474
+ if "cart" not in final_state:
475
+ return 0.0, "Missing 'cart' field in final state"
476
+
477
+ cart = final_state["cart"]
478
+ if not isinstance(cart, list):
479
+ return 0.0, "cart is not a list"
480
+
481
+ # Verify cart has items (should have new item added)
482
+ if len(cart) == 0:
483
+ return 0.0, "Cart is empty, expected new item"
484
+
485
+ return 1.0, "Successfully removed old item and added new item"
486
+ except Exception as e:
487
+ logger.error(f"Error in _validate_remove_item_from_cart_then_search_and_add_item: {e}")
488
+ return 0.0, f"Validation error: {str(e)}"
489
+
490
+
491
+ def _validate_use_homepage_to_navigate_and_add_items(
492
+ initial_state: dict, final_state: dict
493
+ ) -> Tuple[float, str]:
494
+ """Validate using homepage to navigate and add multiple items to cart."""
495
+ try:
496
+ if "page" not in final_state:
497
+ return 0.0, "Missing 'page' field in final state"
498
+
499
+ if final_state["page"] != "cart":
500
+ return 0.0, f"Expected page='cart', got page='{final_state['page']}'"
501
+
502
+ if "cart" not in final_state:
503
+ return 0.0, "Missing 'cart' field in final state"
504
+
505
+ cart = final_state["cart"]
506
+ if not isinstance(cart, list):
507
+ return 0.0, "cart is not a list"
508
+
509
+ if len(cart) < 2:
510
+ return 0.0, f"Expected at least 2 items in cart, found {len(cart)}"
511
+
512
+ # Check for specific product IDs (3 and 4)
513
+ product_ids = [item.get("productId") for item in cart]
514
+ if "4" not in product_ids or "3" not in product_ids:
515
+ return 0.0, "Expected products with IDs '3' and '4' in cart"
516
+
517
+ return 1.0, "Successfully navigated and added multiple items to cart"
518
+ except Exception as e:
519
+ logger.error(f"Error in _validate_use_homepage_to_navigate_and_add_items: {e}")
520
+ return 0.0, f"Validation error: {str(e)}"
521
+
522
+
523
+ # Registry of all reward functions
524
+ REWARD_FUNCTIONS_JD = {
525
+ "_validate_go_to_the_cart_page_from_the_homepage": _validate_go_to_the_cart_page_from_the_homepage,
526
+ "_validate_go_to_a_product_page_from_home": _validate_go_to_a_product_page_from_home,
527
+ "_validate_go_to_homepage_from_product_page": _validate_go_to_homepage_from_product_page,
528
+ "_validate_go_to_cart_page_from_product_detail_page": _validate_go_to_cart_page_from_product_detail_page,
529
+ "_validate_go_to_product_detail_from_search": _validate_go_to_product_detail_from_search,
530
+ "_validate_find_a_product_using_search_from_homepage": _validate_find_a_product_using_search_from_homepage,
531
+ "_validate_search_吉普衬衫": _validate_search_吉普衬衫,
532
+ "_validate_search_a_product_from_another_product_page": _validate_search_a_product_from_another_product_page,
533
+ "_validate_add_a_product_to_cart": _validate_add_a_product_to_cart,
534
+ "_validate_add_a_product_from_search_result_to_cart": _validate_add_a_product_from_search_result_to_cart,
535
+ "_validate_add_an_item_from_the_homepage": _validate_add_an_item_from_the_homepage,
536
+ "_validate_add_an_item_with_3_quantity": _validate_add_an_item_with_3_quantity,
537
+ "_validate_remove_one_item_from_cart": _validate_remove_one_item_from_cart,
538
+ "_validate_remove_multiple_items_in_the_cart": _validate_remove_multiple_items_in_the_cart,
539
+ "_validate_increase_an_item_and_reduce_another_item": _validate_increase_an_item_and_reduce_another_item,
540
+ "_validate_reduce_an_item_quantity_in_the_cart": _validate_reduce_an_item_quantity_in_the_cart,
541
+ "_validate_search_and_add_two_items_to_cart": _validate_search_and_add_two_items_to_cart,
542
+ "_validate_search_and_add_item_to_cart_and_back_to_home": _validate_search_and_add_item_to_cart_and_back_to_home,
543
+ "_validate_remove_item_from_cart_then_search_and_add_item": _validate_remove_item_from_cart_then_search_and_add_item,
544
+ "_validate_use_homepage_to_navigate_and_add_items": _validate_use_homepage_to_navigate_and_add_items,
545
+ }
546
+
547
+ __all__ = [
548
+ "_validate_go_to_the_cart_page_from_the_homepage",
549
+ "_validate_go_to_a_product_page_from_home",
550
+ "_validate_go_to_homepage_from_product_page",
551
+ "_validate_go_to_cart_page_from_product_detail_page",
552
+ "_validate_go_to_product_detail_from_search",
553
+ "_validate_find_a_product_using_search_from_homepage",
554
+ "_validate_search_吉普衬衫",
555
+ "_validate_search_a_product_from_another_product_page",
556
+ "_validate_add_a_product_to_cart",
557
+ "_validate_add_a_product_from_search_result_to_cart",
558
+ "_validate_add_an_item_from_the_homepage",
559
+ "_validate_add_an_item_with_3_quantity",
560
+ "_validate_remove_one_item_from_cart",
561
+ "_validate_remove_multiple_items_in_the_cart",
562
+ "_validate_increase_an_item_and_reduce_another_item",
563
+ "_validate_reduce_an_item_quantity_in_the_cart",
564
+ "_validate_search_and_add_two_items_to_cart",
565
+ "_validate_search_and_add_item_to_cart_and_back_to_home",
566
+ "_validate_remove_item_from_cart_then_search_and_add_item",
567
+ "_validate_use_homepage_to_navigate_and_add_items",
568
+ "REWARD_FUNCTIONS_JD",
569
+ ]
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
+ }
rewards/weibo.py ADDED
@@ -0,0 +1,924 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward functions for Weibo 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_navigateprofile(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
12
+ """
13
+ Validate that the user successfully navigated to a profile page.
14
+
15
+ This function validates the final state matches the expected target state:
16
+ - currentView should be "profile"
17
+ - viewedUserId should match the expected user ID
18
+ - profileTab should be set appropriately
19
+
20
+ Args:
21
+ initial_state: The initial state before navigation
22
+ final_state: The final state after navigation
23
+
24
+ Returns:
25
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
26
+ """
27
+ logger.debug(f"Running reward function on state: {final_state}")
28
+
29
+ # Check 1: currentView is "profile"
30
+ current_view = final_state.get("currentView")
31
+ if current_view != "profile":
32
+ return 0.0, f"Not on profile page, current view: {current_view}"
33
+
34
+ # Check 2: viewedUserId is "user2"
35
+ viewed_user_id = final_state.get("viewedUserId")
36
+ if viewed_user_id != "user2":
37
+ return 0.0, f"Expected viewedUserId to be 'user2', got '{viewed_user_id}'"
38
+
39
+ # Check 3: profileTab is "posts" (optional but good to validate)
40
+ profile_tab = final_state.get("profileTab")
41
+ if profile_tab != "posts":
42
+ return 0.0, f"Expected profileTab to be 'posts', got '{profile_tab}'"
43
+
44
+ return 1.0, "Successfully navigated to user2's profile page"
45
+
46
+
47
+ def _validate_navigatepost(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
48
+ """
49
+ Validate that the user successfully navigated to a post detail page.
50
+
51
+ This function validates the final state matches the expected target state:
52
+ - currentView should be "post"
53
+ - viewedPostId should match the expected post ID
54
+ - commentTab should be set appropriately
55
+
56
+ Args:
57
+ initial_state: The initial state before navigation
58
+ final_state: The final state after navigation
59
+
60
+ Returns:
61
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
62
+ """
63
+ logger.debug(f"Running reward function on state: {final_state}")
64
+
65
+ # Check 1: currentView is "post"
66
+ current_view = final_state.get("currentView")
67
+ if current_view != "post":
68
+ return 0.0, f"Not on post detail page, current view: {current_view}"
69
+
70
+ # Check 2: viewedPostId is "4"
71
+ viewed_post_id = final_state.get("viewedPostId")
72
+ if viewed_post_id != "4":
73
+ return 0.0, f"Expected viewedPostId to be '4', got '{viewed_post_id}'"
74
+
75
+ # Check 3: commentTab is "hot" (default tab for post detail)
76
+ comment_tab = final_state.get("commentTab")
77
+ if comment_tab != "hot":
78
+ return 0.0, f"Expected commentTab to be 'hot', got '{comment_tab}'"
79
+
80
+ return 1.0, "Successfully navigated to post 4 detail page"
81
+
82
+
83
+ def _validate_loadmoreposts(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
84
+ """
85
+ Validate that more posts were successfully loaded in the feed.
86
+
87
+ This function validates the final state matches the expected target state:
88
+ - currentView should remain "feed"
89
+ - displayedPosts should have increased (from 10 to 30 posts)
90
+ - isLoadingPosts should be False (loading completed)
91
+
92
+ Args:
93
+ initial_state: The initial state before loading more posts
94
+ final_state: The final state after loading more posts
95
+
96
+ Returns:
97
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
98
+ """
99
+ logger.debug(f"Running reward function on state: {final_state}")
100
+
101
+ # Check 1: currentView is "feed"
102
+ current_view = final_state.get("currentView")
103
+ if current_view != "feed":
104
+ return 0.0, f"Not on feed page, current view: {current_view}"
105
+
106
+ # Check 2: displayedPosts has increased
107
+ initial_posts = initial_state.get("displayedPosts", [])
108
+ final_posts = final_state.get("displayedPosts", [])
109
+
110
+ initial_count = len(initial_posts)
111
+ final_count = len(final_posts)
112
+
113
+ if final_count <= initial_count:
114
+ return 0.0, f"Posts did not increase: {initial_count} -> {final_count} (expected increase)"
115
+
116
+ # Check 3: Final count should be 30 posts
117
+ if final_count != 30:
118
+ return 0.0, f"Expected 30 posts in final state, got {final_count}"
119
+
120
+ # Check 4: isLoadingPosts should be False (loading completed)
121
+ is_loading = final_state.get("isLoadingPosts")
122
+ if is_loading:
123
+ return 0.0, f"Expected isLoadingPosts to be False after loading, got {is_loading}"
124
+
125
+ return 1.0, f"Successfully loaded more posts: {initial_count} -> {final_count} posts"
126
+
127
+
128
+ def _validate_postfromprofile(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
129
+ """
130
+ Validate that the user successfully navigated to a post detail page from a profile page.
131
+
132
+ This function validates the final state matches the expected target state:
133
+ - currentView should be "post"
134
+ - viewedPostId should match the expected post ID (31)
135
+ - commentTab should be "hot" (default tab)
136
+ - viewedUserId should be None (cleared when navigating to post detail)
137
+ - displayedPosts should remain unchanged (persisted across pages)
138
+
139
+ Args:
140
+ initial_state: The initial state before navigation
141
+ final_state: The final state after navigation
142
+
143
+ Returns:
144
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
145
+ """
146
+ logger.debug(f"Running reward function on state: {final_state}")
147
+
148
+ # Check 1: currentView is "post"
149
+ current_view = final_state.get("currentView")
150
+ if current_view != "post":
151
+ return 0.0, f"Not on post detail page, current view: {current_view}"
152
+
153
+ # Check 2: viewedPostId is "31"
154
+ viewed_post_id = final_state.get("viewedPostId")
155
+ if viewed_post_id != "31":
156
+ return 0.0, f"Expected viewedPostId to be '31', got '{viewed_post_id}'"
157
+
158
+ # Check 3: commentTab is "hot" (default tab for post detail)
159
+ comment_tab = final_state.get("commentTab")
160
+ if comment_tab != "hot":
161
+ return 0.0, f"Expected commentTab to be 'hot', got '{comment_tab}'"
162
+
163
+ # Check 4: viewedUserId should be None (cleared when navigating to post)
164
+ viewed_user_id = final_state.get("viewedUserId")
165
+ if viewed_user_id is not None:
166
+ return 0.0, f"Expected viewedUserId to be None after navigating to post, got '{viewed_user_id}'"
167
+
168
+ # Check 5: displayedPosts should remain unchanged (persisted across pages)
169
+ initial_posts = initial_state.get("displayedPosts", [])
170
+ final_posts = final_state.get("displayedPosts", [])
171
+
172
+ initial_count = len(initial_posts)
173
+ final_count = len(final_posts)
174
+
175
+ if initial_count != final_count:
176
+ return 0.0, f"displayedPosts count changed: {initial_count} -> {final_count} (should remain unchanged)"
177
+
178
+ return 1.0, "Successfully navigated to post 31 detail page from profile"
179
+
180
+
181
+ def _validate_partialsearchquery(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
182
+ """
183
+ Validate that the user successfully typed a partial search query and the dropdown shows results.
184
+
185
+ This function validates the final state matches the expected target state:
186
+ - searchQuery should be "电影"
187
+ - searchDropdownOpen should be True
188
+ - searchBarFocused should be True
189
+ - searchDropdownResults.suggestions should have exactly 1 item containing "电影"
190
+ - searchDropdownResults.users should have exactly 1 user whose name or bio contains "电影"
191
+
192
+ Args:
193
+ initial_state: The initial state before typing the query
194
+ final_state: The final state after typing the query
195
+
196
+ Returns:
197
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
198
+ """
199
+ logger.debug(f"Running reward function on state: {final_state}")
200
+
201
+ # Check 1: searchQuery is "电影"
202
+ search_query = final_state.get("searchQuery")
203
+ if search_query != "电影":
204
+ return 0.0, f"Expected searchQuery to be '电影', got '{search_query}'"
205
+
206
+ # Check 2: searchDropdownOpen is True
207
+ search_dropdown_open = final_state.get("searchDropdownOpen")
208
+ if search_dropdown_open is not True:
209
+ return 0.0, f"Expected searchDropdownOpen to be True, got {search_dropdown_open}"
210
+
211
+ # Check 3: searchBarFocused is True
212
+ search_bar_focused = final_state.get("searchBarFocused")
213
+ if search_bar_focused is not True:
214
+ return 0.0, f"Expected searchBarFocused to be True, got {search_bar_focused}"
215
+
216
+ # Check 4: searchDropdownResults exists and has suggestions
217
+ search_dropdown_results = final_state.get("searchDropdownResults", {})
218
+ suggestions = search_dropdown_results.get("suggestions", [])
219
+
220
+ if len(suggestions) != 1:
221
+ return 0.0, f"Expected 1 search suggestion, got {len(suggestions)}"
222
+
223
+ # Check 5: The suggestion contains "电影" as a substring
224
+ suggestion = suggestions[0]
225
+ if "电影" not in suggestion:
226
+ return 0.0, f"Expected suggestion to contain '电影', got '{suggestion}'"
227
+
228
+ # Check 6: searchDropdownResults has users
229
+ users = search_dropdown_results.get("users", [])
230
+
231
+ if len(users) != 1:
232
+ return 0.0, f"Expected 1 suggested user, got {len(users)}"
233
+
234
+ # Check 7: The user's name or bio contains "电影" as a substring
235
+ user = users[0]
236
+ user_name = user.get("name", "")
237
+ user_bio = user.get("bio", "")
238
+
239
+ if "电影" not in user_name and "电影" not in user_bio:
240
+ return 0.0, f"Expected user name or bio to contain '电影', got name='{user_name}', bio='{user_bio}'"
241
+
242
+ return 1.0, f"Successfully typed search query '电影' with 1 suggestion '{suggestion}' and 1 user '{user_name}'"
243
+
244
+
245
+ def _validate_searchdropdownprofile(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
246
+ """
247
+ Validate that the user successfully navigated to a profile page from the search dropdown.
248
+
249
+ This function validates the final state matches the expected target state:
250
+ - currentView should be "profile"
251
+ - viewedUserId should match the expected user ID (user13)
252
+ - profileTab should be "posts" (default tab)
253
+ - searchQuery should be empty (cleared after navigation)
254
+ - searchDropdownOpen should be False (closed after navigation)
255
+
256
+ Args:
257
+ initial_state: The initial state before navigation
258
+ final_state: The final state after navigation
259
+
260
+ Returns:
261
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
262
+ """
263
+ logger.debug(f"Running reward function on state: {final_state}")
264
+
265
+ # Check 1: currentView is "profile"
266
+ current_view = final_state.get("currentView")
267
+ if current_view != "profile":
268
+ return 0.0, f"Not on profile page, current view: {current_view}"
269
+
270
+ # Check 2: viewedUserId is "user13"
271
+ viewed_user_id = final_state.get("viewedUserId")
272
+ if viewed_user_id != "user13":
273
+ return 0.0, f"Expected viewedUserId to be 'user13', got '{viewed_user_id}'"
274
+
275
+ # Check 3: profileTab is "posts" (default tab)
276
+ profile_tab = final_state.get("profileTab")
277
+ if profile_tab != "posts":
278
+ return 0.0, f"Expected profileTab to be 'posts', got '{profile_tab}'"
279
+
280
+ # Check 4: searchQuery should be empty (cleared after navigation)
281
+ search_query = final_state.get("searchQuery")
282
+ if search_query != "":
283
+ return 0.0, f"Expected searchQuery to be empty after navigation, got '{search_query}'"
284
+
285
+ # Check 5: searchDropdownOpen should be False (closed after navigation)
286
+ search_dropdown_open = final_state.get("searchDropdownOpen")
287
+ if search_dropdown_open is not False:
288
+ return 0.0, f"Expected searchDropdownOpen to be False after navigation, got {search_dropdown_open}"
289
+
290
+ return 1.0, "Successfully navigated to user13's profile page from search dropdown"
291
+
292
+
293
+ def _validate_profilefrompost(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
294
+ """
295
+ Validate that the user successfully navigated to a profile page from a post detail page.
296
+
297
+ This function validates the final state matches the expected target state:
298
+ - currentView should be "profile"
299
+ - viewedUserId should match the expected user ID (user5)
300
+ - profileTab should be "posts" (default tab)
301
+ - viewedPostId should be None (cleared when navigating to profile)
302
+
303
+ Args:
304
+ initial_state: The initial state before navigation (on post detail page)
305
+ final_state: The final state after navigation (on profile page)
306
+
307
+ Returns:
308
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
309
+ """
310
+ logger.debug(f"Running reward function on state: {final_state}")
311
+
312
+ # Check 1: currentView is "profile"
313
+ current_view = final_state.get("currentView")
314
+ if current_view != "profile":
315
+ return 0.0, f"Not on profile page, current view: {current_view}"
316
+
317
+ # Check 2: viewedUserId is "user5"
318
+ viewed_user_id = final_state.get("viewedUserId")
319
+ if viewed_user_id != "user5":
320
+ return 0.0, f"Expected viewedUserId to be 'user5', got '{viewed_user_id}'"
321
+
322
+ # Check 3: profileTab is "posts" (default tab)
323
+ profile_tab = final_state.get("profileTab")
324
+ if profile_tab != "posts":
325
+ return 0.0, f"Expected profileTab to be 'posts', got '{profile_tab}'"
326
+
327
+ # Check 4: viewedPostId should be None (cleared when navigating to profile)
328
+ viewed_post_id = final_state.get("viewedPostId")
329
+ if viewed_post_id is not None:
330
+ return 0.0, f"Expected viewedPostId to be None after navigating to profile, got '{viewed_post_id}'"
331
+
332
+ return 1.0, "Successfully navigated to user5's profile page from post detail page"
333
+
334
+
335
+ def _validate_nosearchsuggestions(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
336
+ """
337
+ Validate that the user typed a search query that yields no suggestions or users in the dropdown.
338
+
339
+ This function validates the final state matches the expected target state:
340
+ - searchQuery should be "asdf"
341
+ - searchDropdownOpen should be True
342
+ - searchBarFocused should be True
343
+ - searchDropdownResults.suggestions should be empty (no suggestions)
344
+ - searchDropdownResults.users should be empty (no users)
345
+
346
+ Args:
347
+ initial_state: The initial state before typing the query
348
+ final_state: The final state after typing the query
349
+
350
+ Returns:
351
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
352
+ """
353
+ logger.debug(f"Running reward function on state: {final_state}")
354
+
355
+ # Check 1: searchQuery is "asdf"
356
+ search_query = final_state.get("searchQuery")
357
+ if search_query != "asdf":
358
+ return 0.0, f"Expected searchQuery to be 'asdf', got '{search_query}'"
359
+
360
+ # Check 2: searchDropdownOpen is True
361
+ search_dropdown_open = final_state.get("searchDropdownOpen")
362
+ if search_dropdown_open is not True:
363
+ return 0.0, f"Expected searchDropdownOpen to be True, got {search_dropdown_open}"
364
+
365
+ # Check 3: searchBarFocused is True
366
+ search_bar_focused = final_state.get("searchBarFocused")
367
+ if search_bar_focused is not True:
368
+ return 0.0, f"Expected searchBarFocused to be True, got {search_bar_focused}"
369
+
370
+ # Check 4: searchDropdownResults exists and has no suggestions
371
+ search_dropdown_results = final_state.get("searchDropdownResults", {})
372
+ suggestions = search_dropdown_results.get("suggestions", [])
373
+
374
+ if len(suggestions) != 0:
375
+ return 0.0, f"Expected 0 search suggestions, got {len(suggestions)}"
376
+
377
+ # Check 5: searchDropdownResults has no users
378
+ users = search_dropdown_results.get("users", [])
379
+
380
+ if len(users) != 0:
381
+ return 0.0, f"Expected 0 suggested users, got {len(users)}"
382
+
383
+ return 1.0, "Successfully typed search query 'asdf' with no suggestions or users in dropdown"
384
+
385
+
386
+ def _validate_postfromsearch(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
387
+ """
388
+ Validate that the user successfully navigated to a post detail page from the search results page.
389
+
390
+ This function validates the final state matches the expected target state:
391
+ - currentView should be "post"
392
+ - viewedPostId should match the expected post ID (35)
393
+ - commentTab should be "hot" (default tab)
394
+ - searchQuery should be empty (cleared after navigation)
395
+ - viewedUserId should be None (cleared when navigating to post detail)
396
+
397
+ Args:
398
+ initial_state: The initial state before navigation (on search results page)
399
+ final_state: The final state after navigation (on post detail page)
400
+
401
+ Returns:
402
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
403
+ """
404
+ logger.debug(f"Running reward function on state: {final_state}")
405
+
406
+ # Check 1: currentView is "post"
407
+ current_view = final_state.get("currentView")
408
+ if current_view != "post":
409
+ return 0.0, f"Not on post detail page, current view: {current_view}"
410
+
411
+ # Check 2: viewedPostId is "35"
412
+ viewed_post_id = final_state.get("viewedPostId")
413
+ if viewed_post_id != "35":
414
+ return 0.0, f"Expected viewedPostId to be '35', got '{viewed_post_id}'"
415
+
416
+ # Check 3: commentTab is "hot" (default tab for post detail)
417
+ comment_tab = final_state.get("commentTab")
418
+ if comment_tab != "hot":
419
+ return 0.0, f"Expected commentTab to be 'hot', got '{comment_tab}'"
420
+
421
+ # Check 4: searchQuery should be empty (cleared after navigation)
422
+ search_query = final_state.get("searchQuery")
423
+ if search_query != "":
424
+ return 0.0, f"Expected searchQuery to be empty after navigation, got '{search_query}'"
425
+
426
+ # Check 5: viewedUserId should be None (cleared when navigating to post)
427
+ viewed_user_id = final_state.get("viewedUserId")
428
+ if viewed_user_id is not None:
429
+ return 0.0, f"Expected viewedUserId to be None after navigating to post, got '{viewed_user_id}'"
430
+
431
+ return 1.0, "Successfully navigated to post 35 detail page from search results"
432
+
433
+
434
+ def _validate_acceptsearchsuggestion(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
435
+ """
436
+ Validate that the user successfully selected a search suggestion and navigated to search results.
437
+
438
+ This function validates the final state matches the expected target state:
439
+ - currentView should be "search" (navigated to search results page)
440
+ - searchQuery should match the selected suggestion ("用户小王")
441
+ - searchCategory should be "comprehensive" (default category)
442
+ - searchDropdownOpen should be False (closed after selection)
443
+
444
+ Args:
445
+ initial_state: The initial state before selecting the suggestion
446
+ final_state: The final state after selecting the suggestion
447
+
448
+ Returns:
449
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
450
+ """
451
+ logger.debug(f"Running reward function on state: {final_state}")
452
+
453
+ # Check 1: currentView is "search"
454
+ current_view = final_state.get("currentView")
455
+ if current_view != "search":
456
+ return 0.0, f"Not on search results page, current view: {current_view}"
457
+
458
+ # Check 2: searchQuery is "用户小王" (the selected suggestion)
459
+ search_query = final_state.get("searchQuery")
460
+ if search_query != "用户小王":
461
+ return 0.0, f"Expected searchQuery to be '用户小王', got '{search_query}'"
462
+
463
+ # Check 3: searchCategory is "comprehensive" (default category)
464
+ search_category = final_state.get("searchCategory")
465
+ if search_category != "comprehensive":
466
+ return 0.0, f"Expected searchCategory to be 'comprehensive', got '{search_category}'"
467
+
468
+ # Check 4: searchDropdownOpen should be False (closed after selection)
469
+ search_dropdown_open = final_state.get("searchDropdownOpen")
470
+ if search_dropdown_open is not False:
471
+ return 0.0, f"Expected searchDropdownOpen to be False after selection, got {search_dropdown_open}"
472
+
473
+ return 1.0, "Successfully selected search suggestion '用户小王' and navigated to search results"
474
+
475
+
476
+ def _validate_changesearchcategories(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
477
+ """
478
+ Validate that the user successfully changed the search category from comprehensive to users.
479
+
480
+ This function validates the final state matches the expected target state:
481
+ - currentView should remain "search" (stays on search page)
482
+ - searchQuery should remain unchanged ("用户小王")
483
+ - searchCategory should be "users" (changed from comprehensive)
484
+ - searchPageResults.users should have exactly 1 user
485
+
486
+ Args:
487
+ initial_state: The initial state before changing category (comprehensive)
488
+ final_state: The final state after changing category (users)
489
+
490
+ Returns:
491
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
492
+ """
493
+ logger.debug(f"Running reward function on state: {final_state}")
494
+
495
+ # Check 1: currentView is "search" (stays on search page)
496
+ current_view = final_state.get("currentView")
497
+ if current_view != "search":
498
+ return 0.0, f"Not on search results page, current view: {current_view}"
499
+
500
+ # Check 2: searchQuery remains unchanged ("用户小王")
501
+ search_query = final_state.get("searchQuery")
502
+ if search_query != "用户小王":
503
+ return 0.0, f"Expected searchQuery to remain '用户小王', got '{search_query}'"
504
+
505
+ # Check 3: searchCategory is "users" (changed from comprehensive)
506
+ search_category = final_state.get("searchCategory")
507
+ if search_category != "users":
508
+ return 0.0, f"Expected searchCategory to be 'users', got '{search_category}'"
509
+
510
+ # Check 4: searchPageResults has exactly 1 user
511
+ search_page_results = final_state.get("searchPageResults", {})
512
+ users = search_page_results.get("users", [])
513
+
514
+ if len(users) != 1:
515
+ return 0.0, f"Expected 1 user in search results, got {len(users)}"
516
+
517
+ return 1.0, "Successfully changed search category from comprehensive to users"
518
+
519
+
520
+ def _validate_profilefromsearch(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
521
+ """
522
+ Validate that the user successfully navigated to a profile page from the search results page.
523
+
524
+ This function validates the final state matches the expected target state:
525
+ - currentView should be "profile"
526
+ - viewedUserId should match the expected user ID (user16 - 新用户)
527
+ - profileTab should be "posts" (default tab)
528
+ - searchQuery should be empty (cleared after navigation)
529
+
530
+ Args:
531
+ initial_state: The initial state before navigation (on search results page)
532
+ final_state: The final state after navigation (on profile page)
533
+
534
+ Returns:
535
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
536
+ """
537
+ logger.debug(f"Running reward function on state: {final_state}")
538
+
539
+ # Check 1: currentView is "profile"
540
+ current_view = final_state.get("currentView")
541
+ if current_view != "profile":
542
+ return 0.0, f"Not on profile page, current view: {current_view}"
543
+
544
+ # Check 2: viewedUserId is "user16" (the user with name "新用户")
545
+ viewed_user_id = final_state.get("viewedUserId")
546
+ if viewed_user_id != "user16":
547
+ return 0.0, f"Expected viewedUserId to be 'user16', got '{viewed_user_id}'"
548
+
549
+ # Check 3: profileTab is "posts" (default tab)
550
+ profile_tab = final_state.get("profileTab")
551
+ if profile_tab != "posts":
552
+ return 0.0, f"Expected profileTab to be 'posts', got '{profile_tab}'"
553
+
554
+ # Check 4: searchQuery should be empty (cleared after navigation)
555
+ search_query = final_state.get("searchQuery")
556
+ if search_query != "":
557
+ return 0.0, f"Expected searchQuery to be empty after navigation, got '{search_query}'"
558
+
559
+ return 1.0, "Successfully navigated to user16's (新用户) profile page from search results"
560
+
561
+
562
+ def _validate_profilefromcomments(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
563
+ """
564
+ Validate that the user successfully navigated to a profile page from a comment on a post detail page.
565
+
566
+ This function validates the final state matches the expected target state:
567
+ - currentView should be "profile"
568
+ - viewedUserId should match the expected user ID (user14 - 日常分享)
569
+ - profileTab should be "posts" (default tab)
570
+ - viewedPostId should be None (cleared when navigating to profile)
571
+
572
+ Args:
573
+ initial_state: The initial state before navigation (on post detail page with comments)
574
+ final_state: The final state after navigation (on profile page)
575
+
576
+ Returns:
577
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
578
+ """
579
+ logger.debug(f"Running reward function on state: {final_state}")
580
+
581
+ # Check 1: currentView is "profile"
582
+ current_view = final_state.get("currentView")
583
+ if current_view != "profile":
584
+ return 0.0, f"Not on profile page, current view: {current_view}"
585
+
586
+ # Check 2: viewedUserId is "user14" (the user with name "日常分享")
587
+ viewed_user_id = final_state.get("viewedUserId")
588
+ if viewed_user_id != "user14":
589
+ return 0.0, f"Expected viewedUserId to be 'user14', got '{viewed_user_id}'"
590
+
591
+ # Check 3: profileTab is "posts" (default tab)
592
+ profile_tab = final_state.get("profileTab")
593
+ if profile_tab != "posts":
594
+ return 0.0, f"Expected profileTab to be 'posts', got '{profile_tab}'"
595
+
596
+ # Check 4: viewedPostId should be None (cleared when navigating to profile)
597
+ viewed_post_id = final_state.get("viewedPostId")
598
+ if viewed_post_id is not None:
599
+ return 0.0, f"Expected viewedPostId to be None after navigating to profile, got '{viewed_post_id}'"
600
+
601
+ return 1.0, "Successfully navigated to user14's (日常分享) profile page from comments"
602
+
603
+
604
+ def _validate_loadmanyposts(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
605
+ """
606
+ Validate that the user successfully loaded more posts and navigated to a specific post detail page.
607
+
608
+ This function validates the final state matches the expected target state:
609
+ - currentView should be "post"
610
+ - viewedPostId should match the expected post ID (23)
611
+ - commentTab should be "hot" (default tab)
612
+ - The post should be from user "读书笔记"
613
+ - The post should have exactly 3 attachments (media items)
614
+
615
+ Args:
616
+ initial_state: The initial state before loading more posts (on feed page)
617
+ final_state: The final state after navigating to post detail page
618
+
619
+ Returns:
620
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
621
+ """
622
+ logger.debug(f"Running reward function on state: {final_state}")
623
+
624
+ # Check 1: currentView is "post"
625
+ current_view = final_state.get("currentView")
626
+ if current_view != "post":
627
+ return 0.0, f"Not on post detail page, current view: {current_view}"
628
+
629
+ # Check 2: viewedPostId is "23"
630
+ viewed_post_id = final_state.get("viewedPostId")
631
+ if viewed_post_id != "23":
632
+ return 0.0, f"Expected viewedPostId to be '23', got '{viewed_post_id}'"
633
+
634
+ # Check 3: commentTab is "hot" (default tab for post detail)
635
+ comment_tab = final_state.get("commentTab")
636
+ if comment_tab != "hot":
637
+ return 0.0, f"Expected commentTab to be 'hot', got '{comment_tab}'"
638
+
639
+ # Check 4: Find the post in allPosts and validate user name and attachments
640
+ all_posts = final_state.get("allPosts", [])
641
+ target_post = next((p for p in all_posts if p.get("id") == "23"), None)
642
+
643
+ if target_post is None:
644
+ return 0.0, "Post with ID '23' not found in allPosts"
645
+
646
+ # Check 5: Post should be from user "读书笔记"
647
+ post_user = target_post.get("user", {})
648
+ user_name = post_user.get("name", "")
649
+ if user_name != "读书笔记":
650
+ return 0.0, f"Expected post to be from user '读书笔记', got '{user_name}'"
651
+
652
+ # Check 6: Post should have exactly 3 attachments (media items)
653
+ media = target_post.get("media", [])
654
+ media_count = len(media)
655
+ if media_count != 3:
656
+ return 0.0, f"Expected post to have 3 attachments, got {media_count}"
657
+
658
+ return 1.0, f"Successfully navigated to post 23 detail page (from 读书笔记 with {media_count} attachments)"
659
+
660
+
661
+ def _validate_profilefromsortedcomments(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
662
+ """
663
+ Validate that the user successfully navigated to a profile page from a comment after sorting comments by time.
664
+
665
+ This function validates the final state matches the expected target state:
666
+ - currentView should be "profile"
667
+ - viewedUserId should match the expected user ID (user13 - 电影评论)
668
+ - profileTab should be "posts" (default tab)
669
+ - viewedPostId should be None (cleared when navigating to profile)
670
+
671
+ Args:
672
+ initial_state: The initial state before navigation (on post detail page with sorted comments)
673
+ final_state: The final state after navigation (on profile page)
674
+
675
+ Returns:
676
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
677
+ """
678
+ logger.debug(f"Running reward function on state: {final_state}")
679
+
680
+ # Check 1: currentView is "profile"
681
+ current_view = final_state.get("currentView")
682
+ if current_view != "profile":
683
+ return 0.0, f"Not on profile page, current view: {current_view}"
684
+
685
+ # Check 2: viewedUserId is "user13" (the user with name "电影评论")
686
+ viewed_user_id = final_state.get("viewedUserId")
687
+ if viewed_user_id != "user13":
688
+ return 0.0, f"Expected viewedUserId to be 'user13', got '{viewed_user_id}'"
689
+
690
+ # Check 3: profileTab is "posts" (default tab)
691
+ profile_tab = final_state.get("profileTab")
692
+ if profile_tab != "posts":
693
+ return 0.0, f"Expected profileTab to be 'posts', got '{profile_tab}'"
694
+
695
+ # Check 4: viewedPostId should be None (cleared when navigating to profile)
696
+ viewed_post_id = final_state.get("viewedPostId")
697
+ if viewed_post_id is not None:
698
+ return 0.0, f"Expected viewedPostId to be None after navigating to profile, got '{viewed_post_id}'"
699
+
700
+ return 1.0, "Successfully navigated to user13's (电影评论) profile page from sorted comments"
701
+
702
+
703
+ def _validate_switchtheme(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
704
+ """
705
+ Validate that the user successfully switched the theme from light mode to dark mode.
706
+
707
+ This function validates the final state matches the expected target state:
708
+ - theme should be "dark" (changed from "light")
709
+
710
+ Args:
711
+ initial_state: The initial state before switching theme (light mode)
712
+ final_state: The final state after switching theme (dark mode)
713
+
714
+ Returns:
715
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
716
+ """
717
+ logger.debug(f"Running reward function on state: {final_state}")
718
+
719
+ # Check 1: theme is "dark"
720
+ theme = final_state.get("theme")
721
+ if theme != "dark":
722
+ return 0.0, f"Expected theme to be 'dark', got '{theme}'"
723
+
724
+ return 1.0, "Successfully switched theme from light to dark"
725
+
726
+
727
+ def _validate_homefromsearch(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
728
+ """
729
+ Validate that the user successfully navigated from the search results page to the home feed.
730
+
731
+ This function validates the final state matches the expected target state:
732
+ - currentView should be "feed" (navigated to home feed)
733
+ - searchQuery should be empty (cleared after navigation)
734
+
735
+ Args:
736
+ initial_state: The initial state before navigation (on search results page)
737
+ final_state: The final state after navigation (on home feed)
738
+
739
+ Returns:
740
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
741
+ """
742
+ logger.debug(f"Running reward function on state: {final_state}")
743
+
744
+ # Check 1: currentView is "feed"
745
+ current_view = final_state.get("currentView")
746
+ if current_view != "feed":
747
+ return 0.0, f"Not on home feed page, current view: {current_view}"
748
+
749
+ # Check 2: searchQuery should be empty (cleared after navigation)
750
+ search_query = final_state.get("searchQuery")
751
+ if search_query != "":
752
+ return 0.0, f"Expected searchQuery to be empty after navigation, got '{search_query}'"
753
+
754
+ return 1.0, "Successfully navigated from search results to home feed"
755
+
756
+
757
+ def _validate_videopostfromprofile(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
758
+ """
759
+ Validate that the user successfully navigated to a video post detail page from a profile page.
760
+
761
+ This function validates the final state matches the expected target state:
762
+ - currentView should be "post"
763
+ - viewedPostId should match the expected post ID (23)
764
+ - commentTab should be "hot" (default tab)
765
+ - The post should be from user "读书笔记"
766
+ - The post should have at least one video attachment (media item with type "video")
767
+
768
+ Args:
769
+ initial_state: The initial state before navigation (on profile page with video tab selected)
770
+ final_state: The final state after navigation (on post detail page)
771
+
772
+ Returns:
773
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
774
+ """
775
+ logger.debug(f"Running reward function on state: {final_state}")
776
+
777
+ # Check 1: currentView is "post"
778
+ current_view = final_state.get("currentView")
779
+ if current_view != "post":
780
+ return 0.0, f"Not on post detail page, current view: {current_view}"
781
+
782
+ # Check 2: viewedPostId is "23"
783
+ viewed_post_id = final_state.get("viewedPostId")
784
+ if viewed_post_id != "23":
785
+ return 0.0, f"Expected viewedPostId to be '23', got '{viewed_post_id}'"
786
+
787
+ # Check 3: commentTab is "hot" (default tab for post detail)
788
+ comment_tab = final_state.get("commentTab")
789
+ if comment_tab != "hot":
790
+ return 0.0, f"Expected commentTab to be 'hot', got '{comment_tab}'"
791
+
792
+ # Check 4: Find the post in allPosts and validate user name and video attachment
793
+ all_posts = final_state.get("allPosts", [])
794
+ target_post = next((p for p in all_posts if p.get("id") == "23"), None)
795
+
796
+ if target_post is None:
797
+ return 0.0, "Post with ID '23' not found in allPosts"
798
+
799
+ # Check 5: Post should be from user "读书笔记"
800
+ post_user = target_post.get("user", {})
801
+ user_name = post_user.get("name", "")
802
+ if user_name != "读书笔记":
803
+ return 0.0, f"Expected post to be from user '读书笔记', got '{user_name}'"
804
+
805
+ # Check 6: Post should have at least one video attachment
806
+ media = target_post.get("media", [])
807
+ video_media = [m for m in media if m.get("type") == "video"]
808
+
809
+ if len(video_media) == 0:
810
+ return 0.0, f"Expected post to have at least one video attachment, got {len(media)} media items with {len(video_media)} videos"
811
+
812
+ return 1.0, f"Successfully navigated to post 23 detail page (from 读书笔记 with video attachment)"
813
+
814
+
815
+ def _validate_profilefromreply(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
816
+ """
817
+ Validate that the user successfully navigated to a profile page from a reply to a comment on a post detail page.
818
+
819
+ This function validates the final state matches the expected target state:
820
+ - currentView should be "profile"
821
+ - viewedUserId should match the expected user ID (user4 - 旅行达人)
822
+ - profileTab should be "posts" (default tab)
823
+ - viewedPostId should be None (cleared when navigating to profile)
824
+
825
+ Args:
826
+ initial_state: The initial state before navigation (on post detail page with replies)
827
+ final_state: The final state after navigation (on profile page)
828
+
829
+ Returns:
830
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
831
+ """
832
+ logger.debug(f"Running reward function on state: {final_state}")
833
+
834
+ # Check 1: currentView is "profile"
835
+ current_view = final_state.get("currentView")
836
+ if current_view != "profile":
837
+ return 0.0, f"Not on profile page, current view: {current_view}"
838
+
839
+ # Check 2: viewedUserId is "user4" (the user with name "旅行达人")
840
+ viewed_user_id = final_state.get("viewedUserId")
841
+ if viewed_user_id != "user4":
842
+ return 0.0, f"Expected viewedUserId to be 'user4', got '{viewed_user_id}'"
843
+
844
+ # Check 3: profileTab is "posts" (default tab)
845
+ profile_tab = final_state.get("profileTab")
846
+ if profile_tab != "posts":
847
+ return 0.0, f"Expected profileTab to be 'posts', got '{profile_tab}'"
848
+
849
+ # Check 4: viewedPostId should be None (cleared when navigating to profile)
850
+ viewed_post_id = final_state.get("viewedPostId")
851
+ if viewed_post_id is not None:
852
+ return 0.0, f"Expected viewedPostId to be None after navigating to profile, got '{viewed_post_id}'"
853
+
854
+ return 1.0, "Successfully navigated to user4's (旅行达人) profile page from reply"
855
+
856
+
857
+ def _validate_searchusers(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
858
+ """
859
+ Validate that the user successfully searched for users and navigated to the users category of search results.
860
+
861
+ This function validates the final state matches the expected target state:
862
+ - currentView should be "search" (navigated to search results page)
863
+ - searchQuery should be "好" (the search term)
864
+ - searchCategory should be "users" (users category selected)
865
+ - searchPageResults.users should have at least one user (list of users in search results)
866
+
867
+ Args:
868
+ initial_state: The initial state before searching (on feed page)
869
+ final_state: The final state after navigating to users search results
870
+
871
+ Returns:
872
+ Tuple of (score, reason) where score is 1.0 for success, 0.0 for failure
873
+ """
874
+ logger.debug(f"Running reward function on state: {final_state}")
875
+
876
+ # Check 1: currentView is "search" (navigated to search results page)
877
+ current_view = final_state.get("currentView")
878
+ if current_view != "search":
879
+ return 0.0, f"Not on search results page, current view: {current_view}"
880
+
881
+ # Check 2: searchQuery is "好" (the search term)
882
+ search_query = final_state.get("searchQuery")
883
+ if search_query != "好":
884
+ return 0.0, f"Expected searchQuery to be '好', got '{search_query}'"
885
+
886
+ # Check 3: searchCategory is "users" (users category selected)
887
+ search_category = final_state.get("searchCategory")
888
+ if search_category != "users":
889
+ return 0.0, f"Expected searchCategory to be 'users', got '{search_category}'"
890
+
891
+ # Check 4: searchPageResults has at least one user (list of users in search results)
892
+ search_page_results = final_state.get("searchPageResults", {})
893
+ users = search_page_results.get("users", [])
894
+
895
+ if len(users) == 0:
896
+ return 0.0, f"Expected at least one user in search results, got {len(users)} users"
897
+
898
+ return 1.0, f"Successfully navigated to users search results page with {len(users)} users"
899
+
900
+
901
+ # Registry of all Weibo reward functions
902
+ REWARD_FUNCTIONS_WEIBO = {
903
+ "_validate_navigateprofile": _validate_navigateprofile,
904
+ "_validate_navigatepost": _validate_navigatepost,
905
+ "_validate_loadmoreposts": _validate_loadmoreposts,
906
+ "_validate_postfromprofile": _validate_postfromprofile,
907
+ "_validate_partialsearchquery": _validate_partialsearchquery,
908
+ "_validate_searchdropdownprofile": _validate_searchdropdownprofile,
909
+ "_validate_profilefrompost": _validate_profilefrompost,
910
+ "_validate_nosearchsuggestions": _validate_nosearchsuggestions,
911
+ "_validate_postfromsearch": _validate_postfromsearch,
912
+ "_validate_acceptsearchsuggestion": _validate_acceptsearchsuggestion,
913
+ "_validate_changesearchcategories": _validate_changesearchcategories,
914
+ "_validate_profilefromsearch": _validate_profilefromsearch,
915
+ "_validate_profilefromcomments": _validate_profilefromcomments,
916
+ "_validate_loadmanyposts": _validate_loadmanyposts,
917
+ "_validate_profilefromsortedcomments": _validate_profilefromsortedcomments,
918
+ "_validate_switchtheme": _validate_switchtheme,
919
+ "_validate_homefromsearch": _validate_homefromsearch,
920
+ "_validate_videopostfromprofile": _validate_videopostfromprofile,
921
+ "_validate_profilefromreply": _validate_profilefromreply,
922
+ "_validate_searchusers": _validate_searchusers,
923
+ }
924
+
rewards/xiaohongshu.py ADDED
@@ -0,0 +1,491 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward functions for Xiaohongshu (Little Red Book) app tasks.
3
+ """
4
+
5
+ import logging
6
+ from typing import Any, Dict, Optional, Tuple
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ def _find_post(final_state: Dict[str, Any], post_id: str) -> Tuple[Optional[Dict[str, Any]], str]:
12
+ posts = final_state.get("posts")
13
+ if not isinstance(posts, list):
14
+ return None, "Posts array missing in final state"
15
+ for post in posts:
16
+ if post.get("id") == post_id:
17
+ return post, ""
18
+ return None, f"Post with id '{post_id}' not found in final state"
19
+
20
+
21
+ def _find_user(final_state: Dict[str, Any], user_id: str) -> Tuple[Optional[Dict[str, Any]], str]:
22
+ users = final_state.get("users")
23
+ if not isinstance(users, list):
24
+ return None, "Users array missing in final state"
25
+ for user in users:
26
+ if user.get("id") == user_id:
27
+ return user, ""
28
+ return None, f"User with id '{user_id}' not found in final state"
29
+
30
+
31
+ def _get_current_user(final_state: Dict[str, Any]) -> Tuple[Optional[Dict[str, Any]], str]:
32
+ current_user = final_state.get("currentUser")
33
+ if not isinstance(current_user, dict):
34
+ return None, "currentUser object missing in final state"
35
+ return current_user, ""
36
+
37
+
38
+ def _validate_single_comment(
39
+ post: Dict[str, Any], expected_text: str, *, expected_author: Optional[str] = None
40
+ ) -> Tuple[bool, str]:
41
+ comments = post.get("comments")
42
+ if not isinstance(comments, list):
43
+ return False, f"Post {post.get('id')} comments array missing"
44
+ if len(comments) != 1:
45
+ return False, f"Post {post.get('id')} has {len(comments)} comments, expected 1"
46
+ comment = comments[0]
47
+ content = comment.get("content", "")
48
+ if expected_text.lower() not in content.lower():
49
+ return False, f"Post {post.get('id')} comment content '{content}' missing '{expected_text}'"
50
+ if expected_author is not None and comment.get("authorId") != expected_author:
51
+ return False, f"Post {post.get('id')} comment authorId={comment.get('authorId')} expected {expected_author}"
52
+ return True, ""
53
+
54
+
55
+ def _check_exact_list(values: Any, expected: Tuple[str, ...], field_name: str) -> Tuple[bool, str]:
56
+ if not isinstance(values, list):
57
+ return False, f"{field_name} is not a list"
58
+ if len(values) != len(expected):
59
+ return False, f"{field_name} has length {len(values)}, expected {len(expected)}"
60
+ if sorted(values) != sorted(expected):
61
+ return False, f"{field_name}={values} does not match expected {list(expected)}"
62
+ return True, ""
63
+
64
+
65
+ def _validate_bookmarkpost(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
66
+ current_user, error = _get_current_user(final_state)
67
+ if not current_user:
68
+ return 0.0, error
69
+
70
+ ok, error = _check_exact_list(current_user.get("bookmarks"), ("1",), "currentUser.bookmarks")
71
+ if not ok:
72
+ return 0.0, error
73
+
74
+ post, error = _find_post(final_state, "1")
75
+ if not post:
76
+ return 0.0, error
77
+ if post.get("bookmarks") != 1:
78
+ return 0.0, f"Post 1 bookmarks={post.get('bookmarks')} expected 1"
79
+
80
+ user, error = _find_user(final_state, "1")
81
+ if not user:
82
+ return 0.0, error
83
+ if user.get("bookmarkedCount") != 1:
84
+ return 0.0, f"User 1 bookmarkedCount={user.get('bookmarkedCount')} expected 1"
85
+
86
+ return 1.0, "Post 1 bookmarked and counts updated"
87
+
88
+
89
+ def _validate_commentontwoseparateposts(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
90
+ post1, error = _find_post(final_state, "1")
91
+ if not post1:
92
+ return 0.0, error
93
+ ok, error = _validate_single_comment(post1, "nice song!")
94
+ if not ok:
95
+ return 0.0, error
96
+
97
+ post2, error = _find_post(final_state, "2")
98
+ if not post2:
99
+ return 0.0, error
100
+ ok, error = _validate_single_comment(post2, "what the dog doing?")
101
+ if not ok:
102
+ return 0.0, error
103
+
104
+ if final_state.get("page") != "explore":
105
+ return 0.0, f"page is {final_state.get('page')} expected 'explore'"
106
+
107
+ return 1.0, "Posted correct comments on posts 1 and 2 while staying on explore page"
108
+
109
+
110
+ def _validate_commentonvideo(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
111
+ post, error = _find_post(final_state, "4")
112
+ if not post:
113
+ return 0.0, error
114
+ ok, error = _validate_single_comment(post, "this cat so cute!", expected_author="0")
115
+ if not ok:
116
+ return 0.0, error
117
+ return 1.0, "Successfully commented 'this cat so cute!' on post 4"
118
+
119
+
120
+ def _validate_comprehensiveuserinteraction(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
121
+ if final_state.get("page") != "explore":
122
+ return 0.0, f"page is {final_state.get('page')} expected 'explore'"
123
+
124
+ post1, error = _find_post(final_state, "1")
125
+ if not post1:
126
+ return 0.0, error
127
+ if post1.get("likes") != 1:
128
+ return 0.0, f"Post 1 likes={post1.get('likes')} expected 1"
129
+ ok, error = _validate_single_comment(post1, "nice")
130
+ if not ok:
131
+ return 0.0, error
132
+
133
+ post2, error = _find_post(final_state, "2")
134
+ if not post2:
135
+ return 0.0, error
136
+ if post2.get("likes") != 1 or post2.get("bookmarks") != 1:
137
+ return 0.0, f"Post 2 likes={post2.get('likes')} bookmarks={post2.get('bookmarks')} expected 1/1"
138
+
139
+ post7, error = _find_post(final_state, "7")
140
+ if not post7:
141
+ return 0.0, error
142
+ if post7.get("likes") != 1:
143
+ return 0.0, f"Post 7 likes={post7.get('likes')} expected 1"
144
+
145
+ user1, error = _find_user(final_state, "1")
146
+ if not user1:
147
+ return 0.0, error
148
+ if user1.get("likeCount") != 1:
149
+ return 0.0, f"User 1 likeCount={user1.get('likeCount')} expected 1"
150
+
151
+ user2, error = _find_user(final_state, "2")
152
+ if not user2:
153
+ return 0.0, error
154
+ if user2.get("likeCount") != 2 or user2.get("bookmarkedCount") != 1:
155
+ return 0.0, (
156
+ f"User 2 likeCount={user2.get('likeCount')} bookmarkedCount={user2.get('bookmarkedCount')} expected 2/1"
157
+ )
158
+
159
+ current_user, error = _get_current_user(final_state)
160
+ if not current_user:
161
+ return 0.0, error
162
+ ok, error = _check_exact_list(current_user.get("likedPosts"), ("1", "2", "7"), "currentUser.likedPosts")
163
+ if not ok:
164
+ return 0.0, error
165
+ ok, error = _check_exact_list(current_user.get("following"), ("2",), "currentUser.following")
166
+ if not ok:
167
+ return 0.0, error
168
+
169
+ return 1.0, "Completed comprehensive multi-post interaction requirements"
170
+
171
+
172
+ def _validate_crossuserengagement(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
173
+ post_ids = {
174
+ "1": {"likes": 1},
175
+ "2": {"likes": 1, "bookmarks": 1},
176
+ "3": {"likes": 1},
177
+ "4": {"likes": 1, "bookmarks": 1},
178
+ "5": {"likes": 1},
179
+ }
180
+
181
+ for pid, expectations in post_ids.items():
182
+ post, error = _find_post(final_state, pid)
183
+ if not post:
184
+ return 0.0, error
185
+ for field, expected_value in expectations.items():
186
+ if post.get(field) != expected_value:
187
+ return 0.0, f"Post {pid} {field}={post.get(field)} expected {expected_value}"
188
+
189
+ post3, _ = _find_post(final_state, "3")
190
+ ok, error = _validate_single_comment(post3, "nice")
191
+ if not ok:
192
+ return 0.0, error
193
+
194
+ post4, _ = _find_post(final_state, "4")
195
+ ok, error = _validate_single_comment(post4, "meow")
196
+ if not ok:
197
+ return 0.0, error
198
+
199
+ user5, error = _find_user(final_state, "5")
200
+ if not user5:
201
+ return 0.0, error
202
+ followers = user5.get("followers")
203
+ if not isinstance(followers, list) or "0" not in followers:
204
+ return 0.0, f"User 5 followers={followers} expected to include '0'"
205
+
206
+ if final_state.get("page") != "profile" or final_state.get("profileUserId") != "5":
207
+ return 0.0, (
208
+ f"page={final_state.get('page')} profileUserId={final_state.get('profileUserId')} expected profile/5"
209
+ )
210
+
211
+ return 1.0, "Completed cross-user engagement interactions and viewed user 5 profile"
212
+
213
+
214
+ def _validate_follownavigatehome(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
215
+ current_user, error = _get_current_user(final_state)
216
+ if not current_user:
217
+ return 0.0, error
218
+ following = current_user.get("following")
219
+ if not isinstance(following, list) or "2" not in following:
220
+ return 0.0, f"currentUser.following={following} expected to include '2'"
221
+
222
+ user2, error = _find_user(final_state, "2")
223
+ if not user2:
224
+ return 0.0, error
225
+ followers = user2.get("followers")
226
+ if not isinstance(followers, list) or "0" not in followers:
227
+ return 0.0, f"User 2 followers={followers} expected to include '0'"
228
+
229
+ if final_state.get("page") != "explore":
230
+ return 0.0, f"page is {final_state.get('page')} expected 'explore'"
231
+
232
+ return 1.0, "Followed user 2 and returned to explore page"
233
+
234
+
235
+ def _validate_followuser(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
236
+ current_user, error = _get_current_user(final_state)
237
+ if not current_user:
238
+ return 0.0, error
239
+ ok, err = _check_exact_list(current_user.get("following"), ("1",), "currentUser.following")
240
+ if not ok:
241
+ return 0.0, err
242
+
243
+ user1, error = _find_user(final_state, "1")
244
+ if not user1:
245
+ return 0.0, error
246
+ ok, err = _check_exact_list(user1.get("followers"), ("0",), "User 1 followers")
247
+ if not ok:
248
+ return 0.0, err
249
+
250
+ return 1.0, "Successfully followed user 1"
251
+
252
+
253
+ def _validate_like3sequential(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
254
+ for pid in ("1", "2", "3"):
255
+ post, error = _find_post(final_state, pid)
256
+ if not post:
257
+ return 0.0, error
258
+ if post.get("likes") != 1:
259
+ return 0.0, f"Post {pid} likes={post.get('likes')} expected 1"
260
+
261
+ current_user, error = _get_current_user(final_state)
262
+ if not current_user:
263
+ return 0.0, error
264
+ ok, err = _check_exact_list(current_user.get("likedPosts"), ("1", "2", "3"), "currentUser.likedPosts")
265
+ if not ok:
266
+ return 0.0, err
267
+
268
+ for uid in ("1", "2", "3"):
269
+ user, error = _find_user(final_state, uid)
270
+ if not user:
271
+ return 0.0, error
272
+ if user.get("likeCount") != 1:
273
+ return 0.0, f"User {uid} likeCount={user.get('likeCount')} expected 1"
274
+
275
+ return 1.0, "Sequentially liked posts 1, 2, and 3"
276
+
277
+
278
+ def _validate_likeandbookmark(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
279
+ post, error = _find_post(final_state, "2")
280
+ if not post:
281
+ return 0.0, error
282
+ if post.get("likes") != 1 or post.get("bookmarks") != 1:
283
+ return 0.0, f"Post 2 likes={post.get('likes')} bookmarks={post.get('bookmarks')} expected 1/1"
284
+
285
+ user2, error = _find_user(final_state, "2")
286
+ if not user2:
287
+ return 0.0, error
288
+ if user2.get("likeCount") != 1 or user2.get("bookmarkedCount") != 1:
289
+ return 0.0, (
290
+ f"User 2 likeCount={user2.get('likeCount')} bookmarkedCount={user2.get('bookmarkedCount')} expected 1/1"
291
+ )
292
+
293
+ current_user, error = _get_current_user(final_state)
294
+ if not current_user:
295
+ return 0.0, error
296
+ ok, err = _check_exact_list(current_user.get("likedPosts"), ("2",), "currentUser.likedPosts")
297
+ if not ok:
298
+ return 0.0, err
299
+ ok, err = _check_exact_list(current_user.get("bookmarks"), ("2",), "currentUser.bookmarks")
300
+ if not ok:
301
+ return 0.0, err
302
+
303
+ return 1.0, "Liked and bookmarked post 2 with correct counts"
304
+
305
+
306
+ def _validate_likepost(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
307
+ post, error = _find_post(final_state, "1")
308
+ if not post:
309
+ return 0.0, error
310
+ if post.get("likes") != 1:
311
+ return 0.0, f"Post 1 likes={post.get('likes')} expected 1"
312
+
313
+ user1, error = _find_user(final_state, "1")
314
+ if not user1:
315
+ return 0.0, error
316
+ if user1.get("likeCount") != 1:
317
+ return 0.0, f"User 1 likeCount={user1.get('likeCount')} expected 1"
318
+
319
+ return 1.0, "Liked post 1"
320
+
321
+
322
+ def _validate_navigateownprofile(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
323
+ if final_state.get("page") != "profile":
324
+ return 0.0, f"page is {final_state.get('page')} expected 'profile'"
325
+ if final_state.get("profileUserId") != "0":
326
+ return 0.0, f"profileUserId={final_state.get('profileUserId')} expected '0'"
327
+ return 1.0, "Navigated to current user's profile"
328
+
329
+
330
+ def _validate_openpostmodal(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
331
+ if not final_state.get("activePostId"):
332
+ return 0.0, "activePostId is missing or null"
333
+ if final_state.get("isVideoPaused") is True:
334
+ return 0.0, "isVideoPaused is True; expected False while modal open"
335
+ return 1.0, "Opened a post modal with video playing"
336
+
337
+
338
+ def _validate_openvideopause(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
339
+ if final_state.get("activePostId") != "2":
340
+ return 0.0, f"activePostId={final_state.get('activePostId')} expected '2'"
341
+ if final_state.get("isVideoPaused") is not True:
342
+ return 0.0, "Video is not paused after opening post 2"
343
+ return 1.0, "Opened post 2 video and paused it"
344
+
345
+
346
+ def _validate_searchandfollowall(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
347
+ current_user, error = _get_current_user(final_state)
348
+ if not current_user:
349
+ return 0.0, error
350
+ ok, err = _check_exact_list(
351
+ current_user.get("following"),
352
+ ("1", "2", "3", "4", "5"),
353
+ "currentUser.following",
354
+ )
355
+ if not ok:
356
+ return 0.0, err
357
+
358
+ for uid in ("1", "2", "3", "4", "5"):
359
+ user, error = _find_user(final_state, uid)
360
+ if not user:
361
+ return 0.0, error
362
+ followers = user.get("followers")
363
+ if not isinstance(followers, list) or "0" not in followers:
364
+ return 0.0, f"User {uid} followers={followers} expected to include '0'"
365
+
366
+ if final_state.get("page") != "explore":
367
+ return 0.0, f"page is {final_state.get('page')} expected 'explore'"
368
+
369
+ return 1.0, "Followed all users 1-5 and returned to explore"
370
+
371
+
372
+ def _validate_search_and_like(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
373
+ post, error = _find_post(final_state, "1")
374
+ if not post:
375
+ return 0.0, error
376
+ if post.get("likes") != 1:
377
+ return 0.0, f"Post 1 likes={post.get('likes')} expected 1"
378
+
379
+ user1, error = _find_user(final_state, "1")
380
+ if not user1:
381
+ return 0.0, error
382
+ if user1.get("likeCount") != 1:
383
+ return 0.0, f"User 1 likeCount={user1.get('likeCount')} expected 1"
384
+
385
+ return 1.0, "Searched and liked post 1"
386
+
387
+
388
+ def _validate_search_input(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
389
+ if final_state.get("searchQuery") != "hello":
390
+ return 0.0, f"searchQuery={final_state.get('searchQuery')} expected 'hello'"
391
+ return 1.0, "Updated search input to 'hello'"
392
+
393
+
394
+ def _validate_searchuserandlikeall(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
395
+ target_posts = ("2", "7", "12", "17")
396
+ for pid in target_posts:
397
+ post, error = _find_post(final_state, pid)
398
+ if not post:
399
+ return 0.0, error
400
+ if post.get("likes") != 1:
401
+ return 0.0, f"Post {pid} likes={post.get('likes')} expected 1"
402
+
403
+ user2, error = _find_user(final_state, "2")
404
+ if not user2:
405
+ return 0.0, error
406
+ if user2.get("likeCount") != 4:
407
+ return 0.0, f"User 2 likeCount={user2.get('likeCount')} expected 4"
408
+
409
+ current_user, error = _get_current_user(final_state)
410
+ if not current_user:
411
+ return 0.0, error
412
+ ok, err = _check_exact_list(current_user.get("likedPosts"), target_posts, "currentUser.likedPosts")
413
+ if not ok:
414
+ return 0.0, err
415
+
416
+ return 1.0, "Liked all posts from user 2"
417
+
418
+
419
+ def _validate_unfollowuser(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
420
+ current_user, error = _get_current_user(final_state)
421
+ if not current_user:
422
+ return 0.0, error
423
+ following = current_user.get("following")
424
+ if not isinstance(following, list) or len(following) != 0:
425
+ return 0.0, f"currentUser.following={following} expected empty list"
426
+
427
+ user1, error = _find_user(final_state, "1")
428
+ if not user1:
429
+ return 0.0, error
430
+ followers = user1.get("followers")
431
+ if not isinstance(followers, list) or len(followers) != 0:
432
+ return 0.0, f"User 1 followers={followers} expected empty list"
433
+
434
+ if final_state.get("page") != "profile" or final_state.get("profileUserId") != "1":
435
+ return 0.0, (
436
+ f"page={final_state.get('page')} profileUserId={final_state.get('profileUserId')} expected profile/1"
437
+ )
438
+
439
+ return 1.0, "Successfully unfollowed user 1 while viewing their profile"
440
+
441
+
442
+ def _validate_unlikepost(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
443
+ post, error = _find_post(final_state, "10")
444
+ if not post:
445
+ return 0.0, error
446
+ if post.get("likes") != 0:
447
+ return 0.0, f"Post 10 likes={post.get('likes')} expected 0"
448
+
449
+ current_user, error = _get_current_user(final_state)
450
+ if not current_user:
451
+ return 0.0, error
452
+ liked_posts = current_user.get("likedPosts")
453
+ if not isinstance(liked_posts, list) or len(liked_posts) != 0:
454
+ return 0.0, f"currentUser.likedPosts={liked_posts} expected empty list"
455
+
456
+ return 1.0, "Unliked post 10 and cleared likedPosts"
457
+
458
+
459
+ def _validate_watchfullvideo(initial_state: Dict[str, Any], final_state: Dict[str, Any]) -> Tuple[float, str]:
460
+ if final_state.get("activePostId") != "2":
461
+ return 0.0, f"activePostId={final_state.get('activePostId')} expected '2'"
462
+ if final_state.get("isVideoPaused") is not True:
463
+ return 0.0, "Video is not paused at completion"
464
+ if final_state.get("isVideoEnded") is not True:
465
+ return 0.0, "isVideoEnded is not True after watching video"
466
+ return 1.0, "Watched post 2 video through completion"
467
+
468
+
469
+ # Registry of all Xiaohongshu reward functions
470
+ REWARD_FUNCTIONS_XIAOHONGSHU = {
471
+ "_validate_bookmarkpost": _validate_bookmarkpost,
472
+ "_validate_commentontwoseparateposts": _validate_commentontwoseparateposts,
473
+ "_validate_commentonvideo": _validate_commentonvideo,
474
+ "_validate_comprehensiveuserinteraction": _validate_comprehensiveuserinteraction,
475
+ "_validate_crossuserengagement": _validate_crossuserengagement,
476
+ "_validate_follownavigatehome": _validate_follownavigatehome,
477
+ "_validate_followuser": _validate_followuser,
478
+ "_validate_like3sequential": _validate_like3sequential,
479
+ "_validate_likeandbookmark": _validate_likeandbookmark,
480
+ "_validate_likepost": _validate_likepost,
481
+ "_validate_navigateownprofile": _validate_navigateownprofile,
482
+ "_validate_openpostmodal": _validate_openpostmodal,
483
+ "_validate_openvideopause": _validate_openvideopause,
484
+ "_validate_searchandfollowall": _validate_searchandfollowall,
485
+ "_validate_search_and_like": _validate_search_and_like,
486
+ "_validate_search_input": _validate_search_input,
487
+ "_validate_searchuserandlikeall": _validate_searchuserandlikeall,
488
+ "_validate_unfollowuser": _validate_unfollowuser,
489
+ "_validate_unlikepost": _validate_unlikepost,
490
+ "_validate_watchfullvideo": _validate_watchfullvideo,
491
+ }
tasks/2048/create-two-high-tiles.json CHANGED
@@ -3,6 +3,7 @@
3
  "id": "create-two-high-tiles",
4
  "name": "Create Two 128 Tiles",
5
  "description": "Get at least two tiles with value 128 or higher on the board",
 
6
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}",
7
  "initial_state": "{\"board\": [64, 64, 0, 0, 32, 32, 0, 0, 16, 16, 0, 0, 16, 4, 0, 0], \"gameOver\": false, \"gameInitialized\": true}",
8
  "instructions": "{\"user_prompt\": \"Create at least two tiles with value 128 or higher on the board. You'll need to combine smaller tiles strategically to reach this goal.\", \"success_criteria\": \"The board must contain at least two tiles with value 128 or higher.\"}",
@@ -11,4 +12,4 @@
11
  "max_steps": 10,
12
  "timeout_seconds": 120,
13
  "metadata": "{\"category\": \"games\", \"difficulty\": \"medium\", \"action\": \"two_high_tiles\"}"
14
- }
 
3
  "id": "create-two-high-tiles",
4
  "name": "Create Two 128 Tiles",
5
  "description": "Get at least two tiles with value 128 or higher on the board",
6
+ "tier": "free",
7
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}",
8
  "initial_state": "{\"board\": [64, 64, 0, 0, 32, 32, 0, 0, 16, 16, 0, 0, 16, 4, 0, 0], \"gameOver\": false, \"gameInitialized\": true}",
9
  "instructions": "{\"user_prompt\": \"Create at least two tiles with value 128 or higher on the board. You'll need to combine smaller tiles strategically to reach this goal.\", \"success_criteria\": \"The board must contain at least two tiles with value 128 or higher.\"}",
 
12
  "max_steps": 10,
13
  "timeout_seconds": 120,
14
  "metadata": "{\"category\": \"games\", \"difficulty\": \"medium\", \"action\": \"two_high_tiles\"}"
15
+ }
tasks/2048/get-128-tile.json CHANGED
@@ -3,6 +3,7 @@
3
  "id": "get-128-tile",
4
  "name": "Get 128 Tile",
5
  "description": "Create a 128 tile in one move",
 
6
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}",
7
  "initial_state": "{\"board\": [0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0], \"gameOver\": false, \"gameInitialized\": true}",
8
  "instructions": "{\"user_prompt\": \"Create a 128 tile by combining the two 64-tiles in the middle column. Make the move that will merge them together.\", \"success_criteria\": \"The board must contain a 128-tile after the move.\"}",
@@ -11,4 +12,4 @@
11
  "max_steps": 2,
12
  "timeout_seconds": 60,
13
  "metadata": "{\"category\": \"games\", \"difficulty\": \"easy\", \"action\": \"create_128\"}"
14
- }
 
3
  "id": "get-128-tile",
4
  "name": "Get 128 Tile",
5
  "description": "Create a 128 tile in one move",
6
+ "tier": "free",
7
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}",
8
  "initial_state": "{\"board\": [0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0], \"gameOver\": false, \"gameInitialized\": true}",
9
  "instructions": "{\"user_prompt\": \"Create a 128 tile by combining the two 64-tiles in the middle column. Make the move that will merge them together.\", \"success_criteria\": \"The board must contain a 128-tile after the move.\"}",
 
12
  "max_steps": 2,
13
  "timeout_seconds": 60,
14
  "metadata": "{\"category\": \"games\", \"difficulty\": \"easy\", \"action\": \"create_128\"}"
15
+ }
tasks/2048/get-2048.json CHANGED
@@ -3,6 +3,7 @@
3
  "id": "get-2048",
4
  "name": "Get 2048 in one move",
5
  "description": "Make the next move to score 2048.",
 
6
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}",
7
  "initial_state": "{\"board\": [0, 0, 0, 0, 0, 1024, 0, 1024, 0, 0, 0, 0, 0, 0, 0, 0], \"gameOver\": false, \"gameInitialized\": true}",
8
  "instructions": "{\"user_prompt\": \"Play 2048 and make the next move that would cause a 2048 tile to appear.\", \"success_criteria\": \"The game board must contain a 2048 tile.\"}",
@@ -11,4 +12,4 @@
11
  "max_steps": 2,
12
  "timeout_seconds": 120,
13
  "metadata": "{\"category\": \"games\", \"difficulty\": \"easy\"}"
14
- }
 
3
  "id": "get-2048",
4
  "name": "Get 2048 in one move",
5
  "description": "Make the next move to score 2048.",
6
+ "tier": "free",
7
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}",
8
  "initial_state": "{\"board\": [0, 0, 0, 0, 0, 1024, 0, 1024, 0, 0, 0, 0, 0, 0, 0, 0], \"gameOver\": false, \"gameInitialized\": true}",
9
  "instructions": "{\"user_prompt\": \"Play 2048 and make the next move that would cause a 2048 tile to appear.\", \"success_criteria\": \"The game board must contain a 2048 tile.\"}",
 
12
  "max_steps": 2,
13
  "timeout_seconds": 120,
14
  "metadata": "{\"category\": \"games\", \"difficulty\": \"easy\"}"
15
+ }
tasks/2048/get-256-tile.json CHANGED
@@ -3,6 +3,7 @@
3
  "id": "get-256-tile",
4
  "name": "Get 256 Tile",
5
  "description": "Create a 256 tile in three moves",
 
6
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}",
7
  "initial_state": "{\"board\": [0, 0, 32, 32, 0, 0, 32, 32, 0, 32, 0, 32, 0, 0, 32, 32], \"gameOver\": false, \"gameInitialized\": true}",
8
  "instructions": "{\"user_prompt\": \"Create a 256 tile by combining 32-tiles to make 64-tiles, then combining those 64-tiles to make 128-tiles, and finally combining those 128-tiles to make a 256-tile. This requires three strategic moves.\", \"success_criteria\": \"The board must contain a 256-tile after completing the three moves.\"}",
@@ -11,4 +12,4 @@
11
  "max_steps": 10,
12
  "timeout_seconds": 60,
13
  "metadata": "{\"category\": \"games\", \"difficulty\": \"medium\", \"action\": \"create_256\"}"
14
- }
 
3
  "id": "get-256-tile",
4
  "name": "Get 256 Tile",
5
  "description": "Create a 256 tile in three moves",
6
+ "tier": "free",
7
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}",
8
  "initial_state": "{\"board\": [0, 0, 32, 32, 0, 0, 32, 32, 0, 32, 0, 32, 0, 0, 32, 32], \"gameOver\": false, \"gameInitialized\": true}",
9
  "instructions": "{\"user_prompt\": \"Create a 256 tile by combining 32-tiles to make 64-tiles, then combining those 64-tiles to make 128-tiles, and finally combining those 128-tiles to make a 256-tile. This requires three strategic moves.\", \"success_criteria\": \"The board must contain a 256-tile after completing the three moves.\"}",
 
12
  "max_steps": 10,
13
  "timeout_seconds": 60,
14
  "metadata": "{\"category\": \"games\", \"difficulty\": \"medium\", \"action\": \"create_256\"}"
15
+ }
tasks/2048/get-32-tile.json CHANGED
@@ -3,6 +3,7 @@
3
  "id": "get-32-tile",
4
  "name": "Get 32 Tile",
5
  "description": "Combine two 16-tiles to create a 32-tile",
 
6
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}",
7
  "initial_state": "{\"board\": [0, 0, 0, 0, 0, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0], \"gameOver\": false, \"gameInitialized\": true}",
8
  "instructions": "{\"user_prompt\": \"Combine the two 16-tiles in the middle row to create a 32-tile. Move the tiles so they merge together.\", \"success_criteria\": \"The board must contain a 32-tile after the move.\"}",
@@ -11,4 +12,4 @@
11
  "max_steps": 3,
12
  "timeout_seconds": 30,
13
  "metadata": "{\"category\": \"games\", \"difficulty\": \"easy\", \"action\": \"create_32\"}"
14
- }
 
3
  "id": "get-32-tile",
4
  "name": "Get 32 Tile",
5
  "description": "Combine two 16-tiles to create a 32-tile",
6
+ "tier": "free",
7
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}",
8
  "initial_state": "{\"board\": [0, 0, 0, 0, 0, 16, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0], \"gameOver\": false, \"gameInitialized\": true}",
9
  "instructions": "{\"user_prompt\": \"Combine the two 16-tiles in the middle row to create a 32-tile. Move the tiles so they merge together.\", \"success_criteria\": \"The board must contain a 32-tile after the move.\"}",
 
12
  "max_steps": 3,
13
  "timeout_seconds": 30,
14
  "metadata": "{\"category\": \"games\", \"difficulty\": \"easy\", \"action\": \"create_32\"}"
15
+ }
tasks/2048/get-512-tile.json CHANGED
@@ -3,6 +3,7 @@
3
  "id": "get-512-tile",
4
  "name": "Get 512 Tile",
5
  "description": "Create a 512 tile in three moves",
 
6
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}",
7
  "initial_state": "{\"board\": [64, 64, 0, 0, 64, 0, 64, 0, 64, 64, 0, 0, 64, 0, 0, 64], \"gameOver\": false, \"gameInitialized\": true}",
8
  "instructions": "{\"user_prompt\": \"Create a 512 tile by combining 64-tiles to make 128-tiles, then combining those 128-tiles to make 256-tiles, and finally combining those 256-tiles to make a 512-tile. This requires three strategic moves.\", \"success_criteria\": \"The board must contain a 512-tile after completing the three moves.\"}",
@@ -11,4 +12,4 @@
11
  "max_steps": 10,
12
  "timeout_seconds": 60,
13
  "metadata": "{\"category\": \"games\", \"difficulty\": \"medium\", \"action\": \"create_512\"}"
14
- }
 
3
  "id": "get-512-tile",
4
  "name": "Get 512 Tile",
5
  "description": "Create a 512 tile in three moves",
6
+ "tier": "free",
7
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}",
8
  "initial_state": "{\"board\": [64, 64, 0, 0, 64, 0, 64, 0, 64, 64, 0, 0, 64, 0, 0, 64], \"gameOver\": false, \"gameInitialized\": true}",
9
  "instructions": "{\"user_prompt\": \"Create a 512 tile by combining 64-tiles to make 128-tiles, then combining those 128-tiles to make 256-tiles, and finally combining those 256-tiles to make a 512-tile. This requires three strategic moves.\", \"success_criteria\": \"The board must contain a 512-tile after completing the three moves.\"}",
 
12
  "max_steps": 10,
13
  "timeout_seconds": 60,
14
  "metadata": "{\"category\": \"games\", \"difficulty\": \"medium\", \"action\": \"create_512\"}"
15
+ }
tasks/2048/make-first-move.json CHANGED
@@ -3,6 +3,7 @@
3
  "id": "make-first-move",
4
  "name": "Make First Move",
5
  "description": "Make any valid move from the initial board state",
 
6
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}",
7
  "initial_state": "{\"board\": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], \"gameOver\": false, \"gameInitialized\": true}",
8
  "instructions": "{\"user_prompt\": \"Make any valid move in the 2048 game. Use the arrow keys to move tiles in any direction (up, down, left, or right).\", \"success_criteria\": \"The board must change from its initial state after making a move.\"}",
@@ -11,4 +12,4 @@
11
  "max_steps": 5,
12
  "timeout_seconds": 30,
13
  "metadata": "{\"category\": \"games\", \"difficulty\": \"easy\", \"action\": \"first_move\"}"
14
- }
 
3
  "id": "make-first-move",
4
  "name": "Make First Move",
5
  "description": "Make any valid move from the initial board state",
6
+ "tier": "free",
7
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}",
8
  "initial_state": "{\"board\": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], \"gameOver\": false, \"gameInitialized\": true}",
9
  "instructions": "{\"user_prompt\": \"Make any valid move in the 2048 game. Use the arrow keys to move tiles in any direction (up, down, left, or right).\", \"success_criteria\": \"The board must change from its initial state after making a move.\"}",
 
12
  "max_steps": 5,
13
  "timeout_seconds": 30,
14
  "metadata": "{\"category\": \"games\", \"difficulty\": \"easy\", \"action\": \"first_move\"}"
15
+ }
tasks/2048/move-tiles-right.json CHANGED
@@ -3,6 +3,7 @@
3
  "id": "move-tiles-right",
4
  "name": "Move Tiles Right",
5
  "description": "Move all tiles to the right side of the board",
 
6
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}",
7
  "initial_state": "{\"board\": [2, 0, 0, 0, 4, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0], \"gameOver\": false, \"gameInitialized\": true}",
8
  "instructions": "{\"user_prompt\": \"Move all tiles to the right side of the board using the right arrow key. All tiles should be positioned in the rightmost column.\", \"success_criteria\": \"All tiles must be in the rightmost column (positions 3, 7, 11, 15).\"}",
@@ -11,4 +12,4 @@
11
  "max_steps": 3,
12
  "timeout_seconds": 30,
13
  "metadata": "{\"category\": \"games\", \"difficulty\": \"easy\", \"action\": \"move_right\"}"
14
- }
 
3
  "id": "move-tiles-right",
4
  "name": "Move Tiles Right",
5
  "description": "Move all tiles to the right side of the board",
6
+ "tier": "free",
7
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}",
8
  "initial_state": "{\"board\": [2, 0, 0, 0, 4, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0], \"gameOver\": false, \"gameInitialized\": true}",
9
  "instructions": "{\"user_prompt\": \"Move all tiles to the right side of the board using the right arrow key. All tiles should be positioned in the rightmost column.\", \"success_criteria\": \"All tiles must be in the rightmost column (positions 3, 7, 11, 15).\"}",
 
12
  "max_steps": 3,
13
  "timeout_seconds": 30,
14
  "metadata": "{\"category\": \"games\", \"difficulty\": \"easy\", \"action\": \"move_right\"}"
15
+ }
tasks/2048/reach-540-sum.json CHANGED
@@ -3,6 +3,7 @@
3
  "id": "reach-540-sum",
4
  "name": "Reach 540 Sum",
5
  "description": "Achieve a board with tiles summing to 540 or more",
 
6
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}",
7
  "initial_state": "{\"board\": [256, 128, 64, 32, 16, 8, 4, 2, 2, 2, 0, 0, 0, 0, 0, 0], \"gameOver\": false, \"gameInitialized\": true}",
8
  "instructions": "{\"user_prompt\": \"Achieve a board where the sum of all tile values is 540 or more. Combine tiles strategically to increase the total value.\", \"success_criteria\": \"The sum of all tile values on the board must be 540 or greater.\"}",
@@ -11,4 +12,4 @@
11
  "max_steps": 20,
12
  "timeout_seconds": 120,
13
  "metadata": "{\"category\": \"games\", \"difficulty\": \"hard\", \"action\": \"target_540_sum\"}"
14
- }
 
3
  "id": "reach-540-sum",
4
  "name": "Reach 540 Sum",
5
  "description": "Achieve a board with tiles summing to 540 or more",
6
+ "tier": "free",
7
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}",
8
  "initial_state": "{\"board\": [256, 128, 64, 32, 16, 8, 4, 2, 2, 2, 0, 0, 0, 0, 0, 0], \"gameOver\": false, \"gameInitialized\": true}",
9
  "instructions": "{\"user_prompt\": \"Achieve a board where the sum of all tile values is 540 or more. Combine tiles strategically to increase the total value.\", \"success_criteria\": \"The sum of all tile values on the board must be 540 or greater.\"}",
 
12
  "max_steps": 20,
13
  "timeout_seconds": 120,
14
  "metadata": "{\"category\": \"games\", \"difficulty\": \"hard\", \"action\": \"target_540_sum\"}"
15
+ }
tasks/2048/strategic-32.json CHANGED
@@ -3,12 +3,13 @@
3
  "id": "strategic-32",
4
  "name": "Strategic 32",
5
  "description": "Create a 32 tile from a sparse board with strategic moves",
 
6
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}",
7
  "initial_state": "{\"board\": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], \"gameOver\": false, \"gameInitialized\": true}",
8
- "instructions": "{\"user_prompt\": \"Starting from an empty board, strategically create a 32 tile. You'll need to build up from smaller tiles through careful planning and multiple moves. This requires combining tiles multiple times: 2\u21924\u21928\u219216\u219232.\", \"success_criteria\": \"The board must contain a 32-tile after completing the strategic moves.\"}",
9
  "reward_function": "_validate_strategic_32",
10
  "valid_target_states": "",
11
  "max_steps": 40,
12
  "timeout_seconds": 180,
13
  "metadata": "{\"category\": \"games\", \"difficulty\": \"hard\", \"action\": \"strategic_32\"}"
14
- }
 
3
  "id": "strategic-32",
4
  "name": "Strategic 32",
5
  "description": "Create a 32 tile from a sparse board with strategic moves",
6
+ "tier": "free",
7
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/2048/index.html\"}",
8
  "initial_state": "{\"board\": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], \"gameOver\": false, \"gameInitialized\": true}",
9
+ "instructions": "{\"user_prompt\": \"Starting from an empty board, strategically create a 32 tile. You'll need to build up from smaller tiles through careful planning and multiple moves. This requires combining tiles multiple times: 2→4→8→16→32.\", \"success_criteria\": \"The board must contain a 32-tile after completing the strategic moves.\"}",
10
  "reward_function": "_validate_strategic_32",
11
  "valid_target_states": "",
12
  "max_steps": 40,
13
  "timeout_seconds": 180,
14
  "metadata": "{\"category\": \"games\", \"difficulty\": \"hard\", \"action\": \"strategic_32\"}"
15
+ }
tasks/action-tester/must-click.json CHANGED
@@ -3,6 +3,7 @@
3
  "id": "must-click",
4
  "name": "Click Action Test",
5
  "description": "Test the agent's ability to perform a single click action on a button",
 
6
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}",
7
  "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}",
8
  "instructions": "{\"user_prompt\": \"Click the blue 'Click Me!' button to complete this task. You need to perform a single left-click on the button.\", \"success_criteria\": \"The hasClicked state must be set to True after clicking the button\"}",
@@ -11,4 +12,4 @@
11
  "max_steps": 5,
12
  "timeout_seconds": 30,
13
  "metadata": "{\"difficulty\": \"easy\", \"action_type\": \"click\", \"target_element\": \"blue button with text 'Click Me!'\"}"
14
- }
 
3
  "id": "must-click",
4
  "name": "Click Action Test",
5
  "description": "Test the agent's ability to perform a single click action on a button",
6
+ "tier": "free",
7
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}",
8
  "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}",
9
  "instructions": "{\"user_prompt\": \"Click the blue 'Click Me!' button to complete this task. You need to perform a single left-click on the button.\", \"success_criteria\": \"The hasClicked state must be set to True after clicking the button\"}",
 
12
  "max_steps": 5,
13
  "timeout_seconds": 30,
14
  "metadata": "{\"difficulty\": \"easy\", \"action_type\": \"click\", \"target_element\": \"blue button with text 'Click Me!'\"}"
15
+ }
tasks/action-tester/must-complete-all-actions.json CHANGED
@@ -3,6 +3,7 @@
3
  "id": "must-complete-all-actions",
4
  "name": "Complete All Actions Test",
5
  "description": "Test the agent's ability to perform all computer use actions in sequence - click, double-click, right-click, middle-click, drag, type, hotkey, and scroll",
 
6
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}",
7
  "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}",
8
  "instructions": "{\"user_prompt\": \"Complete all 8 computer use actions to finish this comprehensive test: 1) Click the blue 'Click Me!' button, 2) Double-click the purple 'Double Click Me!' button, 3) Right-click the orange area, 4) Middle-click the teal area, 5) Drag the red box to a new position, 6) Type at least 5 characters in the input field, 7) Press Ctrl+S (or Cmd+S on Mac), and 8) Scroll down the page by at least 100 pixels. All actions must be completed successfully.\", \"success_criteria\": \"All action states must be set to True: hasClicked, hasDoubleClicked, hasRightClicked, hasMiddleClicked, hasDragged, hasTyped, hasHotkeyed, and hasScrolled\"}",
@@ -11,4 +12,4 @@
11
  "max_steps": 15,
12
  "timeout_seconds": 120,
13
  "metadata": "{\"difficulty\": \"hard\", \"action_type\": \"comprehensive\", \"target_element\": \"all interactive elements in the action tester\", \"actions_required\": [\"click\", \"double_click\", \"right_click\", \"middle_click\", \"drag\", \"type\", \"hotkey\", \"scroll\"]}"
14
- }
 
3
  "id": "must-complete-all-actions",
4
  "name": "Complete All Actions Test",
5
  "description": "Test the agent's ability to perform all computer use actions in sequence - click, double-click, right-click, middle-click, drag, type, hotkey, and scroll",
6
+ "tier": "free",
7
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}",
8
  "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}",
9
  "instructions": "{\"user_prompt\": \"Complete all 8 computer use actions to finish this comprehensive test: 1) Click the blue 'Click Me!' button, 2) Double-click the purple 'Double Click Me!' button, 3) Right-click the orange area, 4) Middle-click the teal area, 5) Drag the red box to a new position, 6) Type at least 5 characters in the input field, 7) Press Ctrl+S (or Cmd+S on Mac), and 8) Scroll down the page by at least 100 pixels. All actions must be completed successfully.\", \"success_criteria\": \"All action states must be set to True: hasClicked, hasDoubleClicked, hasRightClicked, hasMiddleClicked, hasDragged, hasTyped, hasHotkeyed, and hasScrolled\"}",
 
12
  "max_steps": 15,
13
  "timeout_seconds": 120,
14
  "metadata": "{\"difficulty\": \"hard\", \"action_type\": \"comprehensive\", \"target_element\": \"all interactive elements in the action tester\", \"actions_required\": [\"click\", \"double_click\", \"right_click\", \"middle_click\", \"drag\", \"type\", \"hotkey\", \"scroll\"]}"
15
+ }
tasks/action-tester/must-double-click.json CHANGED
@@ -3,6 +3,7 @@
3
  "id": "must-double-click",
4
  "name": "Double Click Action Test",
5
  "description": "Test the agent's ability to perform a double-click action on a button",
 
6
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}",
7
  "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}",
8
  "instructions": "{\"user_prompt\": \"Double-click the purple 'Double Click Me!' button to complete this task. You need to perform two quick clicks in succession on the button.\", \"success_criteria\": \"The hasDoubleClicked state must be set to True after double-clicking the button\"}",
@@ -11,4 +12,4 @@
11
  "max_steps": 5,
12
  "timeout_seconds": 30,
13
  "metadata": "{\"difficulty\": \"easy\", \"action_type\": \"double_click\", \"target_element\": \"purple button with text 'Double Click Me!'\"}"
14
- }
 
3
  "id": "must-double-click",
4
  "name": "Double Click Action Test",
5
  "description": "Test the agent's ability to perform a double-click action on a button",
6
+ "tier": "free",
7
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}",
8
  "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}",
9
  "instructions": "{\"user_prompt\": \"Double-click the purple 'Double Click Me!' button to complete this task. You need to perform two quick clicks in succession on the button.\", \"success_criteria\": \"The hasDoubleClicked state must be set to True after double-clicking the button\"}",
 
12
  "max_steps": 5,
13
  "timeout_seconds": 30,
14
  "metadata": "{\"difficulty\": \"easy\", \"action_type\": \"double_click\", \"target_element\": \"purple button with text 'Double Click Me!'\"}"
15
+ }
tasks/action-tester/must-drag.json CHANGED
@@ -3,6 +3,7 @@
3
  "id": "must-drag",
4
  "name": "Drag Action Test",
5
  "description": "Test the agent's ability to perform a drag and drop action",
 
6
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}",
7
  "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}",
8
  "instructions": "{\"user_prompt\": \"Drag the red 'Drag Me' box to a new position to complete this task. You need to click and hold the red box, then move it to a different location (at least 10 pixels away) before releasing.\", \"success_criteria\": \"The hasDragged state must be set to True after successfully dragging the red box to a new position\"}",
@@ -11,4 +12,4 @@
11
  "max_steps": 10,
12
  "timeout_seconds": 45,
13
  "metadata": "{\"difficulty\": \"medium\", \"action_type\": \"drag\", \"target_element\": \"red draggable box with text 'Drag Me'\"}"
14
- }
 
3
  "id": "must-drag",
4
  "name": "Drag Action Test",
5
  "description": "Test the agent's ability to perform a drag and drop action",
6
+ "tier": "free",
7
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}",
8
  "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}",
9
  "instructions": "{\"user_prompt\": \"Drag the red 'Drag Me' box to a new position to complete this task. You need to click and hold the red box, then move it to a different location (at least 10 pixels away) before releasing.\", \"success_criteria\": \"The hasDragged state must be set to True after successfully dragging the red box to a new position\"}",
 
12
  "max_steps": 10,
13
  "timeout_seconds": 45,
14
  "metadata": "{\"difficulty\": \"medium\", \"action_type\": \"drag\", \"target_element\": \"red draggable box with text 'Drag Me'\"}"
15
+ }
tasks/action-tester/must-hotkey.json CHANGED
@@ -3,6 +3,7 @@
3
  "id": "must-hotkey",
4
  "name": "Hotkey Action Test",
5
  "description": "Test the agent's ability to use keyboard shortcuts (hotkeys)",
 
6
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}",
7
  "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}",
8
  "instructions": "{\"user_prompt\": \"Press the keyboard shortcut Ctrl+S (or Cmd+S on Mac) to complete this task. You need to hold down the Ctrl key (or Cmd key on Mac) and press the S key simultaneously.\", \"success_criteria\": \"The hasHotkeyed state must be set to True after pressing the Ctrl+S (or Cmd+S) key combination\"}",
@@ -11,4 +12,4 @@
11
  "max_steps": 5,
12
  "timeout_seconds": 30,
13
  "metadata": "{\"difficulty\": \"medium\", \"action_type\": \"hotkey\", \"target_element\": \"keyboard shortcut Ctrl+S or Cmd+S\"}"
14
- }
 
3
  "id": "must-hotkey",
4
  "name": "Hotkey Action Test",
5
  "description": "Test the agent's ability to use keyboard shortcuts (hotkeys)",
6
+ "tier": "free",
7
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}",
8
  "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}",
9
  "instructions": "{\"user_prompt\": \"Press the keyboard shortcut Ctrl+S (or Cmd+S on Mac) to complete this task. You need to hold down the Ctrl key (or Cmd key on Mac) and press the S key simultaneously.\", \"success_criteria\": \"The hasHotkeyed state must be set to True after pressing the Ctrl+S (or Cmd+S) key combination\"}",
 
12
  "max_steps": 5,
13
  "timeout_seconds": 30,
14
  "metadata": "{\"difficulty\": \"medium\", \"action_type\": \"hotkey\", \"target_element\": \"keyboard shortcut Ctrl+S or Cmd+S\"}"
15
+ }
tasks/action-tester/must-middle-click.json CHANGED
@@ -3,6 +3,7 @@
3
  "id": "must-middle-click",
4
  "name": "Middle Click Action Test",
5
  "description": "Test the agent's ability to perform a middle-click (scroll wheel click) action",
 
6
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}",
7
  "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}",
8
  "instructions": "{\"user_prompt\": \"Middle-click (scroll wheel click) on the teal area labeled 'Middle Click Here' to complete this task. You need to press down the scroll wheel on the designated area.\", \"success_criteria\": \"The hasMiddleClicked state must be set to True after middle-clicking the teal area\"}",
@@ -11,4 +12,4 @@
11
  "max_steps": 5,
12
  "timeout_seconds": 30,
13
  "metadata": "{\"difficulty\": \"medium\", \"action_type\": \"middle_click\", \"target_element\": \"teal area with text 'Middle Click Here'\"}"
14
- }
 
3
  "id": "must-middle-click",
4
  "name": "Middle Click Action Test",
5
  "description": "Test the agent's ability to perform a middle-click (scroll wheel click) action",
6
+ "tier": "free",
7
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}",
8
  "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}",
9
  "instructions": "{\"user_prompt\": \"Middle-click (scroll wheel click) on the teal area labeled 'Middle Click Here' to complete this task. You need to press down the scroll wheel on the designated area.\", \"success_criteria\": \"The hasMiddleClicked state must be set to True after middle-clicking the teal area\"}",
 
12
  "max_steps": 5,
13
  "timeout_seconds": 30,
14
  "metadata": "{\"difficulty\": \"medium\", \"action_type\": \"middle_click\", \"target_element\": \"teal area with text 'Middle Click Here'\"}"
15
+ }
tasks/action-tester/must-perform-three-medium-actions.json CHANGED
@@ -3,6 +3,7 @@
3
  "id": "must-perform-three-medium-actions",
4
  "name": "Three Medium Actions Test",
5
  "description": "Test the agent's ability to perform three medium-difficulty actions in sequence: drag, hotkey, and middle-click",
 
6
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}",
7
  "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}",
8
  "instructions": "{\"user_prompt\": \"Complete three medium-difficulty computer use actions to finish this test: 1) Drag the red 'Drag Me' box to a new position (at least 10 pixels away), 2) Press the keyboard shortcut Ctrl+S (or Cmd+S on Mac), and 3) Middle-click (scroll wheel click) on the teal area labeled 'Middle Click Here'. All three actions must be completed successfully in any order.\", \"success_criteria\": \"The hasDragged, hasHotkeyed, and hasMiddleClicked states must all be set to True\"}",
@@ -11,4 +12,4 @@
11
  "max_steps": 15,
12
  "timeout_seconds": 90,
13
  "metadata": "{\"difficulty\": \"hard\", \"action_type\": \"combined_medium_actions\", \"target_element\": \"multiple interactive elements requiring drag, hotkey, and middle-click\", \"actions_required\": [\"drag\", \"hotkey\", \"middle_click\"]}"
14
- }
 
3
  "id": "must-perform-three-medium-actions",
4
  "name": "Three Medium Actions Test",
5
  "description": "Test the agent's ability to perform three medium-difficulty actions in sequence: drag, hotkey, and middle-click",
6
+ "tier": "free",
7
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}",
8
  "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}",
9
  "instructions": "{\"user_prompt\": \"Complete three medium-difficulty computer use actions to finish this test: 1) Drag the red 'Drag Me' box to a new position (at least 10 pixels away), 2) Press the keyboard shortcut Ctrl+S (or Cmd+S on Mac), and 3) Middle-click (scroll wheel click) on the teal area labeled 'Middle Click Here'. All three actions must be completed successfully in any order.\", \"success_criteria\": \"The hasDragged, hasHotkeyed, and hasMiddleClicked states must all be set to True\"}",
 
12
  "max_steps": 15,
13
  "timeout_seconds": 90,
14
  "metadata": "{\"difficulty\": \"hard\", \"action_type\": \"combined_medium_actions\", \"target_element\": \"multiple interactive elements requiring drag, hotkey, and middle-click\", \"actions_required\": [\"drag\", \"hotkey\", \"middle_click\"]}"
15
+ }
tasks/action-tester/must-right-click.json CHANGED
@@ -3,6 +3,7 @@
3
  "id": "must-right-click",
4
  "name": "Right Click Action Test",
5
  "description": "Test the agent's ability to perform a right-click (context menu) action",
 
6
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}",
7
  "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}",
8
  "instructions": "{\"user_prompt\": \"Right-click on the orange area labeled 'Right Click Here' to complete this task. You need to perform a right-click (context menu click) on the designated area.\", \"success_criteria\": \"The hasRightClicked state must be set to True after right-clicking the orange area\"}",
@@ -11,4 +12,4 @@
11
  "max_steps": 5,
12
  "timeout_seconds": 30,
13
  "metadata": "{\"difficulty\": \"easy\", \"action_type\": \"right_click\", \"target_element\": \"orange area with text 'Right Click Here'\"}"
14
- }
 
3
  "id": "must-right-click",
4
  "name": "Right Click Action Test",
5
  "description": "Test the agent's ability to perform a right-click (context menu) action",
6
+ "tier": "free",
7
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}",
8
  "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}",
9
  "instructions": "{\"user_prompt\": \"Right-click on the orange area labeled 'Right Click Here' to complete this task. You need to perform a right-click (context menu click) on the designated area.\", \"success_criteria\": \"The hasRightClicked state must be set to True after right-clicking the orange area\"}",
 
12
  "max_steps": 5,
13
  "timeout_seconds": 30,
14
  "metadata": "{\"difficulty\": \"easy\", \"action_type\": \"right_click\", \"target_element\": \"orange area with text 'Right Click Here'\"}"
15
+ }
tasks/action-tester/must-scroll.json CHANGED
@@ -3,6 +3,7 @@
3
  "id": "must-scroll",
4
  "name": "Scroll Action Test",
5
  "description": "Test the agent's ability to scroll the page",
 
6
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}",
7
  "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}",
8
  "instructions": "{\"user_prompt\": \"Scroll down on the page by at least 100 pixels to complete this task. You can use the scroll wheel, arrow keys, or drag the scrollbar to scroll down the page.\", \"success_criteria\": \"The hasScrolled state must be set to True after scrolling down the page by 100 pixels or more\"}",
@@ -11,4 +12,4 @@
11
  "max_steps": 5,
12
  "timeout_seconds": 30,
13
  "metadata": "{\"difficulty\": \"easy\", \"action_type\": \"scroll\", \"target_element\": \"page scroll area\"}"
14
- }
 
3
  "id": "must-scroll",
4
  "name": "Scroll Action Test",
5
  "description": "Test the agent's ability to scroll the page",
6
+ "tier": "free",
7
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}",
8
  "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}",
9
  "instructions": "{\"user_prompt\": \"Scroll down on the page by at least 100 pixels to complete this task. You can use the scroll wheel, arrow keys, or drag the scrollbar to scroll down the page.\", \"success_criteria\": \"The hasScrolled state must be set to True after scrolling down the page by 100 pixels or more\"}",
 
12
  "max_steps": 5,
13
  "timeout_seconds": 30,
14
  "metadata": "{\"difficulty\": \"easy\", \"action_type\": \"scroll\", \"target_element\": \"page scroll area\"}"
15
+ }
tasks/action-tester/must-type.json CHANGED
@@ -3,6 +3,7 @@
3
  "id": "must-type",
4
  "name": "Type Action Test",
5
  "description": "Test the agent's ability to type text into an input field",
 
6
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}",
7
  "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}",
8
  "instructions": "{\"user_prompt\": \"Type at least 5 characters in the text input field to complete this task. Click on the input field with placeholder 'Type here...' and enter at least 5 characters of text.\", \"success_criteria\": \"The hasTyped state must be set to True after typing at least 5 characters in the input field\"}",
@@ -11,4 +12,4 @@
11
  "max_steps": 10,
12
  "timeout_seconds": 30,
13
  "metadata": "{\"difficulty\": \"easy\", \"action_type\": \"type\", \"target_element\": \"text input field with placeholder 'Type here...'\"}"
14
- }
 
3
  "id": "must-type",
4
  "name": "Type Action Test",
5
  "description": "Test the agent's ability to type text into an input field",
6
+ "tier": "free",
7
  "environment": "{\"type\": \"url\", \"path\": \"https://dojo-spas-production.s3.us-east-1.amazonaws.com/action-tester/index.html\"}",
8
  "initial_state": "{\"hasClicked\": false, \"hasDoubleClicked\": false, \"hasDragged\": false, \"hasHotkeyed\": false, \"hasMiddleClicked\": false, \"hasRightClicked\": false, \"hasScrolled\": false, \"hasTyped\": false}",
9
  "instructions": "{\"user_prompt\": \"Type at least 5 characters in the text input field to complete this task. Click on the input field with placeholder 'Type here...' and enter at least 5 characters of text.\", \"success_criteria\": \"The hasTyped state must be set to True after typing at least 5 characters in the input field\"}",
 
12
  "max_steps": 10,
13
  "timeout_seconds": 30,
14
  "metadata": "{\"difficulty\": \"easy\", \"action_type\": \"type\", \"target_element\": \"text input field with placeholder 'Type here...'\"}"
15
+ }
tasks/amazon/customer-reviews-that-have-4-stars-and-above.json ADDED
The diff for this file is too large to render. See raw diff
 
tasks/amazon/customer-reviews-that-have-5-stars.json ADDED
The diff for this file is too large to render. See raw diff
 
tasks/amazon/entering-pod-in-the-search-bar.json ADDED
The diff for this file is too large to render. See raw diff
 
tasks/amazon/filter-on-amazon-global-store.json ADDED
The diff for this file is too large to render. See raw diff
 
tasks/amazon/filter-on-include-out-of-stock.json ADDED
The diff for this file is too large to render. See raw diff
 
tasks/amazon/filter-on-product-condition-renewed.json ADDED
The diff for this file is too large to render. See raw diff
 
tasks/amazon/filter-on-products-condition-new.json ADDED
The diff for this file is too large to render. See raw diff
 
tasks/amazon/filter-on-products-condition-used.json ADDED
The diff for this file is too large to render. See raw diff
 
tasks/amazon/filter-products-based-on-prime-delivery.json ADDED
The diff for this file is too large to render. See raw diff