lkeab commited on
Commit
e5d5706
·
verified ·
1 Parent(s): 8d6954b

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. .MOCK_HOST.applied +98 -0
  2. .gitattributes +3 -0
  3. .mock_endpoint_remap.lock +0 -0
  4. LICENSE +137 -0
  5. LICENSE.osworker +201 -0
  6. NOTICE.cua-gym +31 -0
  7. README.md +165 -0
  8. TRADEMARKS.cua-gym.md +79 -0
  9. ar_signature_005/_cua_gym_vm_bridge.sh +106 -0
  10. ar_signature_005/initial_setup.py +336 -0
  11. ar_signature_005/reward.py +190 -0
  12. ar_signature_005/reward_label.json +73 -0
  13. calc_employee_roles_003__long/.PLACEHOLDER +5 -0
  14. calc_employee_roles_003__long/2b91e566-64fb-51d8-90c6-e534370d1020_Employee_Roles_and_Ranks_1.xlsx +0 -0
  15. calc_employee_roles_003__long/Employee_Roles_and_Ranks_gold_1.xlsx +0 -0
  16. calc_employee_roles_003__long/Employee_Roles_and_Ranks_gold_2.xlsx +0 -0
  17. calc_employee_roles_003__long/Employee_Roles_and_Ranks_gold_3.xlsx +0 -0
  18. calc_employee_roles_003__long/Employee_Roles_and_Ranks_gold_4.xlsx +0 -0
  19. calc_employee_roles_003__long/Employee_Roles_and_Ranks_gold_5.xlsx +0 -0
  20. calc_employee_roles_003__long/cfebbe10-8574-50f8-89ac-4adbc38c6713_Employee_Roles_and_Ranks_2.xlsx +0 -0
  21. calc_employee_roles_003__long/d2218574-2113-5bc6-9304-dd4fc048bb44_Employee_Roles_and_Ranks_5.xlsx +0 -0
  22. calc_employee_roles_003__long/d7bc84eb-e864-507e-a3bb-11f4b5a44d58_Employee_Roles_and_Ranks_4.xlsx +0 -0
  23. calc_employee_roles_003__long/f1da68fd-9e78-5d2b-983d-166ae7f7607b_Employee_Roles_and_Ranks_3.xlsx +0 -0
  24. csops_email_to_crm_case_001/_cua_gym_vm_bridge.sh +106 -0
  25. csops_email_to_crm_case_001/initial_setup.py +591 -0
  26. csops_email_to_crm_case_001/reward.py +461 -0
  27. csops_email_to_crm_case_001/reward_label.json +90 -0
  28. csops_sla_queue_triage_003/_cua_gym_vm_bridge.sh +106 -0
  29. csops_sla_queue_triage_003/initial_setup.py +601 -0
  30. csops_sla_queue_triage_003/reward.py +594 -0
  31. csops_sla_queue_triage_003/reward_label.json +78 -0
  32. fin_expense_claim_001__long__cond/.PLACEHOLDER +5 -0
  33. fin_expense_claim_001__long__cond/19c19c59-8dab-5287-9f11-546056a463b0_oa_server.py +779 -0
  34. fin_expense_claim_001__long__cond/87712b8f-fa0d-5df1-8c79-dd0c877ab6a7_invoice_2.pdf +80 -0
  35. fin_expense_claim_001__long__cond/8fc9101a-9ae0-52e6-9d9f-6cf7033d05ff_invoice_1.pdf +80 -0
  36. fin_expense_claim_001__long__cond/ef610de1-d103-514c-9ddd-9fda1b34d5c2_mentor_id_and_approval_code.xlsx +0 -0
  37. hr_onboarding_003/_cua_gym_vm_bridge.sh +106 -0
  38. hr_onboarding_003/initial_setup.py +184 -0
  39. hr_onboarding_003/reward.py +171 -0
  40. hr_onboarding_003/reward_label.json +62 -0
  41. ops_shift_cover_005/_cua_gym_vm_bridge.sh +106 -0
  42. ops_shift_cover_005/initial_setup.py +228 -0
  43. ops_shift_cover_005/reward.py +231 -0
  44. ops_shift_cover_005/reward_label.json +53 -0
  45. sdr_lead_import_004__long/_cua_gym_vm_bridge.sh +106 -0
  46. sdr_lead_import_004__long/initial_setup.py +334 -0
  47. sdr_lead_import_004__long/reward.py +353 -0
  48. sre_change_review_002__long/_cua_gym_vm_bridge.sh +106 -0
  49. sre_change_review_002__long/initial_setup.py +692 -0
  50. sre_change_review_002__long/reward.py +410 -0
.MOCK_HOST.applied ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 12306_mock: http://28.7.184.198:8100
2
+ Canvas-LMS_mock: http://28.7.184.198:8101
3
+ Expensify_mock: http://28.7.184.198:8102
4
+ PACS-viewer_mock: http://28.7.184.198:8103
5
+ SAP_mock: http://28.7.184.198:8104
6
+ ServiceNow_mock: http://28.7.184.198:8105
7
+ TradingView_mock: http://28.7.184.198:8106
8
+ Zendesk_mock: http://28.7.184.198:8107
9
+ adp_mock: http://28.7.184.198:8108
10
+ airtable_mock: http://28.7.184.198:8109
11
+ aliyun_mock: http://28.7.184.198:8110
12
+ amazon_mock: http://28.7.184.198:8111
13
+ amazon_seller_mock: http://28.7.184.198:8112
14
+ amplitude_mock: http://28.7.184.198:8113
15
+ asana_mock: http://28.7.184.198:8114
16
+ aws_console_mock: http://28.7.184.198:8115
17
+ azure_mock: http://28.7.184.198:8116
18
+ bamboohr_mock: http://28.7.184.198:8117
19
+ booking_com_mock: http://28.7.184.198:8118
20
+ canva_mock: http://28.7.184.198:8119
21
+ canvas_mock: http://28.7.184.198:8120
22
+ circleci_mock: http://28.7.184.198:8121
23
+ clio_mock: http://28.7.184.198:8122
24
+ cloudflare_mock: http://28.7.184.198:8123
25
+ coinbase_mock: http://28.7.184.198:8124
26
+ confluence_mock: http://28.7.184.198:8125
27
+ contractbook_mock: http://28.7.184.198:8126
28
+ datadog_mock: http://28.7.184.198:8127
29
+ dingtalk_mock: http://28.7.184.198:8128
30
+ discord_mock: http://28.7.184.198:8129
31
+ docusign_mock: http://28.7.184.198:8130
32
+ ebay_mock: http://28.7.184.198:8131
33
+ epic-health_mock: http://28.7.184.198:8132
34
+ expedia_mock: http://28.7.184.198:8133
35
+ facebook_mock: http://28.7.184.198:8134
36
+ feishu_mock: http://28.7.184.198:8135
37
+ github_mock: http://28.7.184.198:8136
38
+ gitlab_mock: http://28.7.184.198:8137
39
+ gmail_mock: http://28.7.184.198:8138
40
+ google_ads_mock: http://28.7.184.198:8139
41
+ google_analytics_mock: http://28.7.184.198:8140
42
+ google_calendar_mock: http://28.7.184.198:8141
43
+ google_docs_mock: http://28.7.184.198:8142
44
+ google_drive_mock: http://28.7.184.198:8143
45
+ google_flights_mock: http://28.7.184.198:8144
46
+ google_sheets_mock: http://28.7.184.198:8145
47
+ greenhouse_mock: http://28.7.184.198:8146
48
+ gusto_mock: http://28.7.184.198:8147
49
+ hotjar_mock: http://28.7.184.198:8148
50
+ hubspot_marketing_mock: http://28.7.184.198:8149
51
+ hubspot_mock: http://28.7.184.198:8150
52
+ instacart_mock: http://28.7.184.198:8151
53
+ instagram_mock: http://28.7.184.198:8152
54
+ jira_mock: http://28.7.184.198:8153
55
+ klaviyo_mock: http://28.7.184.198:8154
56
+ lattice_mock: http://28.7.184.198:8155
57
+ linear_mock: http://28.7.184.198:8156
58
+ linkedin_mock: http://28.7.184.198:8157
59
+ looker_studio_mock: http://28.7.184.198:8158
60
+ lucidchart_mock: http://28.7.184.198:8159
61
+ mailchimp_mock: http://28.7.184.198:8160
62
+ meta_ads_mock: http://28.7.184.198:8161
63
+ microsoft_teams_mock: http://28.7.184.198:8162
64
+ miro_mock: http://28.7.184.198:8163
65
+ mixpanel_mock: http://28.7.184.198:8164
66
+ monday_mock: http://28.7.184.198:8165
67
+ notion_mock: http://28.7.184.198:8166
68
+ openreview_mock: http://28.7.184.198:8167
69
+ outlook_web_mock: http://28.7.184.198:8168
70
+ paypal_mock: http://28.7.184.198:8169
71
+ pinterest_mock: http://28.7.184.198:8170
72
+ postman_mock: http://28.7.184.198:8171
73
+ quickbooks_mock: http://28.7.184.198:8172
74
+ reddit_mock: http://28.7.184.198:8173
75
+ robinhood_mock: http://28.7.184.198:8174
76
+ salesforce_mock: http://28.7.184.198:8175
77
+ sentry_mock: http://28.7.184.198:8176
78
+ shopify_admin_mock: http://28.7.184.198:8177
79
+ slack_mock: http://28.7.184.198:8178
80
+ stripe_dashboard_mock: http://28.7.184.198:8179
81
+ tableau_mock: http://28.7.184.198:8180
82
+ taobao_seller_mock: http://28.7.184.198:8181
83
+ trello_mock: http://28.7.184.198:8182
84
+ tripadvisor_mock: http://28.7.184.198:8183
85
+ twitter_mock: http://28.7.184.198:8184
86
+ uber_eats_mock: http://28.7.184.198:8185
87
+ vercel_mock: http://28.7.184.198:8186
88
+ wandb_mock: http://28.7.184.198:8187
89
+ wechat_mock: http://28.7.184.198:8188
90
+ weibo_mock: http://28.7.184.198:8189
91
+ westlaw_mock: http://28.7.184.198:8190
92
+ woocommerce_mock: http://28.7.184.198:8191
93
+ workday_mock: http://28.7.184.198:8192
94
+ xiaohongshu_mock: http://28.7.184.198:8193
95
+ youtube_mock: http://28.7.184.198:8194
96
+ zhihu_mock: http://28.7.184.198:8195
97
+ zillow_mock: http://28.7.184.198:8196
98
+ zoom_web_mock: http://28.7.184.198:8197
.gitattributes CHANGED
@@ -58,3 +58,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ _setup_nonzero_stderr.txt filter=lfs diff=lfs merge=lfs -text
62
+ _setup_nonzero_stdout.txt filter=lfs diff=lfs merge=lfs -text
63
+ images/Ubuntu_openpyxl.qcow2 filter=lfs diff=lfs merge=lfs -text
.mock_endpoint_remap.lock ADDED
File without changes
LICENSE ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Tencent is pleased to support the community by making UI Mate available.
2
+
3
+ Copyright (C) 2026 Tencent. All rights reserved.
4
+
5
+ The open-source software and/or model(s) included in this distribution may have been modified by Tencent ("Tencent Modifications"). All Tencent Modifications are Copyright (C) Tencent.
6
+
7
+ UI Mate is licensed under Apache-2.0, except for the third-party components listed below, which remain licensed under their respective original terms. UI Mate does not impose any additional restrictions beyond those specified in the original licenses of these third-party components. Users are required to comply with all applicable terms and conditions of the original licenses and to ensure that the use of these third-party components conforms to all relevant laws and regulations.
8
+
9
+ For the avoidance of doubt, UI Mate refers solely to the inference-enabling code, parameters, and weights made publicly available by Tencent in accordance with Apache-2.0.
10
+
11
+ Terms of the Apache-2.0 License:
12
+ --------------------------------------------------------------------
13
+ Apache License
14
+ Version 2.0, January 2004
15
+ http://www.apache.org/licenses/
16
+
17
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
18
+
19
+ 1. Definitions.
20
+
21
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
22
+
23
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
24
+
25
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
26
+
27
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
28
+
29
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
32
+
33
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
34
+
35
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
36
+
37
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
38
+
39
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
40
+
41
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
42
+
43
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
44
+
45
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
46
+
47
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
48
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
49
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
50
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
51
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
52
+
53
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
54
+
55
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
56
+
57
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
58
+
59
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
60
+
61
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
62
+
63
+ END OF TERMS AND CONDITIONS
64
+
65
+
66
+ Dependencies and Licenses:
67
+
68
+ This open-source project builds upon the following open-source model(s) and/or software, each of which remains licensed under its original license(s). Certain component(s) may include modifications made by Tencent ("Tencent Modifications"), which are Copyright (C) Tencent.
69
+
70
+ In case you believe there have been errors in the attribution below, you may submit the concerns to us for review and correction.
71
+
72
+
73
+ Open Source Model(s)/Software Licensed under the Apache-2.0:
74
+ --------------------------------------------------------------------
75
+ 1. Qwen3.6-27B
76
+ Copyright 2026 Alibaba Cloud
77
+ Please note this model has been modified by Tencent in this distribution.
78
+
79
+ 2. Qwen3.5-9B
80
+ Copyright 2026 Alibaba Cloud
81
+ Please note this model has been modified by Tencent in this distribution.
82
+ Terms of the Apache-2.0:
83
+ --------------------------------------------------------------------
84
+ Apache License
85
+ Version 2.0, January 2004
86
+ http://www.apache.org/licenses/
87
+
88
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
89
+
90
+ 1. Definitions.
91
+
92
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
93
+
94
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
95
+
96
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
97
+
98
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
99
+
100
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
101
+
102
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
103
+
104
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
105
+
106
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
107
+
108
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
109
+
110
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
111
+
112
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
113
+
114
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
115
+
116
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
117
+
118
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
119
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
120
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
121
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
122
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
123
+
124
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
125
+
126
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
127
+
128
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
129
+
130
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
131
+
132
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
133
+
134
+ END OF TERMS AND CONDITIONS
135
+
136
+ ==================================================
137
+ End of the Attribution Notice of this project.
LICENSE.osworker ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2024 XLANG NLP Lab
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
NOTICE.cua-gym ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CUA-Gym-Hub
2
+ Copyright 2026 XLang Lab, The University of Hong Kong, and contributors.
3
+
4
+ This product is part of CUA-Gym (https://github.com/xlang-ai/CUA-Gym) and is
5
+ distributed under the Apache License, Version 2.0 (LICENSE).
6
+
7
+ ────────────────────────────────────────────────────────────────────────────
8
+ Trademark Notice
9
+ ────────────────────────────────────────────────────────────────────────────
10
+
11
+ This repository contains mock web applications whose visual design and
12
+ interactive structure are inspired by real third-party products. The
13
+ names, logos, and trade dress of those products are trademarks of their
14
+ respective holders.
15
+
16
+ Mock app names rendered in the UI are intentionally altered (e.g.,
17
+ "Xmail" rather than "Gmail") to avoid implying any affiliation,
18
+ endorsement, or sponsorship by the trademark holders. Where original
19
+ brand names appear in this repository (in directory names, comments,
20
+ or documentation), they are used solely for identification under
21
+ nominative fair use.
22
+
23
+ See TRADEMARKS.md for the full list of acknowledged third-party marks
24
+ and the takedown procedure for rights holders.
25
+
26
+ ────────────────────────────────────────────────────────────────────────────
27
+ Apache 2.0 § 4(d) Notice Inclusion
28
+ ────────────────────────────────────────────────────────────────────────────
29
+
30
+ This NOTICE file MUST be included with any derivative works of this
31
+ project, as required by Section 4(d) of the Apache License 2.0.
README.md CHANGED
@@ -1,3 +1,168 @@
1
  ---
 
 
 
2
  license: apache-2.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ language:
3
+ - en
4
+ - zh
5
  license: apache-2.0
6
+ pretty_name: OSWorkerBench
7
+ tags:
8
+ - computer-use
9
+ - gui-agent
10
+ - desktop-automation
11
+ - benchmark
12
+ - multimodal
13
+ - demonstrations
14
+ configs:
15
+ - config_name: tasks
16
+ default: true
17
+ data_files:
18
+ - split: test
19
+ path: data/tasks/test-00000-of-00001.parquet
20
+ - config_name: demonstrations
21
+ data_files:
22
+ - split: test
23
+ path: data/demonstrations/test-00000-of-00001.parquet
24
  ---
25
+
26
+ # OSWorkerBench
27
+
28
+ OSWorkerBench is an office-centric desktop GUI-agent benchmark introduced in
29
+ [UI-Mate: Advancing Open-Weight Foundation GUI Agents with In-Context Demonstrations](https://arxiv.org/abs/2608.15930).
30
+ It contains 100 long-horizon tasks across 17 business tracks and 41 applications,
31
+ with executable evaluators and demonstration-guided evaluation.
32
+
33
+ See the [Hugging Face paper page](https://huggingface.co/papers/2608.15930) and
34
+ the [benchmark implementation](https://github.com/Tencent/UI-Mate/tree/main/osworker_bench).
35
+
36
+ ## Load with Datasets
37
+
38
+ The default `tasks` configuration contains one row per benchmark task:
39
+
40
+ ```python
41
+ from datasets import load_dataset
42
+
43
+ dataset = load_dataset("tencent/OSWorkerBench")
44
+ first_task = dataset["test"][0]
45
+ ```
46
+
47
+ The `demonstrations` configuration exposes the released self-demonstrations as
48
+ one row per recorded GUI step:
49
+
50
+ ```python
51
+ demonstrations = load_dataset("tencent/OSWorkerBench", "demonstrations")
52
+ first_step = demonstrations["test"][0]
53
+ ```
54
+
55
+ While this repository is private, authenticate with the Hugging Face CLI or set
56
+ `HF_TOKEN` in the environment. The same calls work without authentication if the
57
+ repository is later made public.
58
+
59
+ ## Configurations and splits
60
+
61
+ | Configuration | Split | Rows | Unit |
62
+ | --- | --- | ---: | --- |
63
+ | `tasks` (default) | `test` | 100 | One OSWorkerBench task |
64
+ | `demonstrations` | `test` | 3,989 | One captioned GUI action step |
65
+
66
+ The 33 released self-demonstrations contain 212 subtasks and 3,989 steps. The
67
+ 45 variant-task demonstrations described by the paper and project README are
68
+ not present in the released `osworker_bench/` tree and are therefore not
69
+ included here.
70
+
71
+ ### `tasks` schema
72
+
73
+ The leading columns (`id`, `domain`, `instruction`, `app_type`, `difficulty`)
74
+ are intended for browsing. `config_json`, `evaluator_json`, and `task_json`
75
+ preserve the heterogeneous benchmark structures as lossless JSON strings.
76
+ `source_path` points to the original task JSON and `cache_path` points to its
77
+ same-named runtime-cache directory.
78
+
79
+ ### `demonstrations` schema
80
+
81
+ Each row identifies a task, subtask, and step and flattens the recorded
82
+ `observation`, planner intent/thought/expectation, executor action, and
83
+ post-action validation. `step_json` preserves the original step object and
84
+ `source_path` points to the complete trajectory.
85
+
86
+ ## Repository layout
87
+
88
+ ```text
89
+ data/
90
+ tasks/test-00000-of-00001.parquet
91
+ demonstrations/test-00000-of-00001.parquet
92
+ raw/evaluation_examples/
93
+ OSWorker/ # full manifest and 100 task JSON files
94
+ democua/ # 33 task configs and raw trajectories
95
+ metadata/
96
+ source_cache_manifest.json
97
+ build_summary.json
98
+ <task-id>/ # runtime setup/reward/cache files
99
+ legacy/ # mirrored legacy cache files
100
+ images/osworld_image.tar
101
+ ```
102
+
103
+ The README metadata explicitly maps `load_dataset()` to the two Parquet files,
104
+ so the mixed runtime files are not interpreted as tabular data.
105
+
106
+ ## Runtime assets
107
+
108
+ The runtime cache is mirrored from
109
+ [`SamuelGuo/OSworker_cache`](https://huggingface.co/datasets/SamuelGuo/OSworker_cache/tree/b6753bc357a756301f3429a95b38362da6035030)
110
+ at immutable revision `b6753bc357a756301f3429a95b38362da6035030`. All files from that revision are
111
+ included with their original paths except the large qcow2 VM image.
112
+ `metadata/source_cache_manifest.json` records the source file list.
113
+
114
+ The omitted VM image is 27,445,690,368 bytes and can be downloaded directly
115
+ from the pinned source revision:
116
+
117
+ - [`images/Ubuntu_openpyxl.qcow2`](https://huggingface.co/datasets/SamuelGuo/OSworker_cache/resolve/b6753bc357a756301f3429a95b38362da6035030/images/Ubuntu_openpyxl.qcow2)
118
+ - SHA-256: `ec20b56ed19d2fe2cca0f11d8fb3564cfd2926996a4a984ad12ace5af73acb5d`
119
+
120
+ `images/osworld_image.tar` is mirrored in this repository. Running the benchmark
121
+ also requires the harness and 98 mock applications from the UI-Mate GitHub
122
+ repository. Of the 100 tasks, 88 use the mock applications and 12 are
123
+ local-file/OSWorld-style tasks.
124
+
125
+ For the normative task-id, config, cache, and endpoint rules, use the
126
+ [OSWorker task specification](https://github.com/Tencent/UI-Mate/blob/main/osworker_bench/evaluation_examples/OSWorker/README.md).
127
+
128
+ ## Data provenance and privacy
129
+
130
+ Task prompts, executable evaluators, and released demonstrations come from the
131
+ UI-Mate OSWorkerBench release. The benchmark uses synthetic enterprise records
132
+ and fictional names/contact details; it is not intended to contain real
133
+ personal data. Some inherited OSWorld-style tasks reference upstream Hugging
134
+ Face assets, and those URLs are retained verbatim for reproducibility.
135
+
136
+ Runtime files are preserved from the pinned source-cache revision, including
137
+ its legacy files and generation logs. Do not treat mock credentials or fixture
138
+ values as production secrets.
139
+
140
+ ## Limitations
141
+
142
+ - This dataset provides benchmark definitions and assets, not a ready-to-run
143
+ hosted environment. Docker/VM support and separately deployed mock apps are
144
+ required for execution.
145
+ - Browser and desktop interactions may depend on UI versions, timing, network
146
+ access, and the configured mock host.
147
+ - The default table serializes heterogeneous executable setup/evaluator objects
148
+ as JSON strings; use `json.loads` or the raw files to reconstruct them.
149
+ - Only the 33 self-demonstrations present in the released repository are
150
+ included.
151
+
152
+ ## License and attribution
153
+
154
+ The benchmark release is provided under Apache-2.0. See `LICENSE`,
155
+ `LICENSE.osworker`, `NOTICE.cua-gym`, and `TRADEMARKS.cua-gym.md` for upstream
156
+ attribution and trademark terms. Bundled runtime images and third-party
157
+ software/assets remain subject to their respective upstream licenses.
158
+
159
+ ## Citation
160
+
161
+ ```bibtex
162
+ @article{uimate2026,
163
+ title = {UI-Mate: Advancing Open-Weight Foundation GUI Agents with In-Context Demonstrations},
164
+ author = {Tencent HY Frontier Team},
165
+ journal = {arXiv preprint arXiv:2608.15930},
166
+ year = {2026},
167
+ }
168
+ ```
TRADEMARKS.cua-gym.md ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Trademark Notice
2
+
3
+ CUA-Gym-Hub is a research project: a suite of mock web applications used to
4
+ train and evaluate computer-use AI agents under controlled, reproducible
5
+ conditions. None of the mocks in this repository are real products. They
6
+ do not connect to the services of any third party, do not transmit data
7
+ to any third party, and are not affiliated with, endorsed by, or sponsored
8
+ by any trademark holder.
9
+
10
+ ## Naming
11
+
12
+ To reduce any risk of confusion with real-world products, every mock
13
+ displays a deliberately altered brand name in its UI — e.g., a session
14
+ labelled `gmail_mock` renders as "Xmail", a session labelled `slack_mock`
15
+ renders as "Xlack", and so on. Directory names retain the original
16
+ identifiers only for engineering reference (`gmail_mock` is shorter and
17
+ clearer than `xmail_email_client_mock`); they are not surfaced to users
18
+ of the running mock.
19
+
20
+ ## Third-Party Marks
21
+
22
+ The mocks in this repository are visually inspired by, and structurally
23
+ modelled after, products published by their respective owners. All
24
+ product names, brand names, logos, and trademarks of those products
25
+ remain the property of their respective holders, including but not
26
+ limited to:
27
+
28
+ - Google LLC (Gmail, Google Docs, Google Drive, Google Sheets,
29
+ Google Calendar, Google Ads, Google Analytics, Google Flights)
30
+ - Microsoft Corporation (Microsoft Teams, Outlook, Azure)
31
+ - Slack Technologies, LLC
32
+ - Atlassian Pty Ltd (Jira)
33
+ - Salesforce, Inc.
34
+ - Adobe Inc.
35
+ - Notion Labs, Inc.
36
+ - Shopify Inc.
37
+ - Meta Platforms, Inc. (Facebook, Instagram, WhatsApp)
38
+ - X Corp. (formerly Twitter)
39
+ - LinkedIn Corporation
40
+ - Stripe, Inc.
41
+ - PayPal, Inc.
42
+ - Amazon.com, Inc. (Amazon, AWS)
43
+ - Alibaba Group (Aliyun, Taobao, DingTalk)
44
+ - ByteDance (Feishu)
45
+ - Tencent (WeChat)
46
+ - ServiceNow, Inc.
47
+ - SAP SE
48
+ - HubSpot, Inc.
49
+ - Reddit, Inc.
50
+ - Pinterest, Inc.
51
+ - Discord Inc.
52
+ - Zoom Communications, Inc.
53
+ - and all other product-name holders not enumerated above.
54
+
55
+ Use of these names in this repository is solely for the purpose of
56
+ identifying the simulated environment so that researchers can match
57
+ training tasks to the real-world products they approximate. This is
58
+ nominative fair use under U.S. trademark law (and analogous fair-use
59
+ doctrines in other jurisdictions). It does not imply endorsement,
60
+ affiliation, or sponsorship.
61
+
62
+ ## Takedown Policy
63
+
64
+ If you are a rights holder and would like a specific mock removed,
65
+ renamed, or modified, please open a GitHub issue in this repository
66
+ using the **Trademark Takedown** template, or email
67
+ **bryanwang.nlp@connect.hku.hk**. We will respond within **7 days** and
68
+ remove or modify the offending material upon valid request — typically
69
+ within 7 days of acknowledgement.
70
+
71
+ We have no commercial interest in retaining any particular mock; this
72
+ project's value is in the pipeline, not in the specific brand
73
+ identities of any individual environment.
74
+
75
+ ## License
76
+
77
+ All code in this repository is released under the [Apache License 2.0](LICENSE).
78
+ The trademark notices above apply only to third-party marks and do not
79
+ restrict the Apache 2.0 grant.
ar_signature_005/_cua_gym_vm_bridge.sh ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # CUA-Gym VM-side network fix (direct-IP mock access).
3
+ #
4
+ # Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by
5
+ # their real IDC address (http://28.7.184.198:81xx) instead of the old
6
+ # localhost:9000-9097 socat bridge, so the VM only needs two fixes:
7
+ #
8
+ # 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's
9
+ # cluster DNS, which is unreachable from QEMU SLIRP NAT
10
+ # ("Temporary failure in name resolution").
11
+ # 2. The mock host excluded from the woa http proxy — otherwise the VM's
12
+ # Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403
13
+ # from the proxy when hitting 28.7.184.198:81xx. (The old socat path never
14
+ # hit this because localhost is bypassed by default.)
15
+ #
16
+ # Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic
17
+ # OSWorld setup pipeline.
18
+ #
19
+ # Argv:
20
+ # $1 optional sudo password (default "password"; SetupController
21
+ # substitutes {CLIENT_PASSWORD} when uploaded as a cache file).
22
+ # $2 unused (kept for backward compat — was socat first port 9000).
23
+ # $3 unused (kept for backward compat — was socat last port 9097).
24
+ # $4 optional mock host IP (default 28.7.184.198).
25
+
26
+ set +e
27
+
28
+ PASS="${1:-password}"
29
+ MOCK_HOST="${4:-28.7.184.198}"
30
+ # Derive the /16 IDC subnet so future port/host tweaks on the same segment
31
+ # stay bypassed too (28.7.184.198 -> 28.7.0.0/16).
32
+ MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')"
33
+
34
+ run_root() {
35
+ echo "$PASS" | sudo -S -p "" bash -c "$1"
36
+ }
37
+
38
+ # Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2.
39
+ GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')"
40
+ GW="${GW:-10.0.2.2}"
41
+
42
+ # ─── CUA-Gym network fix (Taiji-specific) ─────────────────────────────
43
+ fix_vm_network() {
44
+ # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP
45
+ # DNS forwarder. Nothing hardcoded except the mock host above.
46
+ local GW_NET="${GW%.*}"
47
+ local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3
48
+ local OWN_CIDR
49
+ OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \
50
+ | awk '{print $4; exit}')"
51
+ local OWN_IP="${OWN_CIDR%/*}"
52
+ local OWN_NET=""
53
+ [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24"
54
+
55
+ # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps
56
+ # systemd-resolved/NetworkManager from clobbering it.
57
+ if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf
58
+ chattr +i /etc/resolv.conf 2>/dev/null || true"; then
59
+ echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})"
60
+ else
61
+ echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf"
62
+ fi
63
+
64
+ # 2) Build the proxy bypass list from detected values + the direct-IP
65
+ # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx
66
+ # reachable from inside the VM — without it the woa proxy 403s it.
67
+ local ignore_list="['localhost', '127.0.0.0/8', '${GW}'"
68
+ [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'"
69
+ [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'"
70
+ [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'"
71
+ [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'"
72
+ [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'"
73
+ ignore_list="${ignore_list}]"
74
+
75
+ # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these.
76
+ if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then
77
+ echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}"
78
+ else
79
+ echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)"
80
+ fi
81
+
82
+ # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl).
83
+ local NP="localhost,127.0.0.1,${GW}"
84
+ [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}"
85
+ [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}"
86
+ [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24"
87
+ [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}"
88
+ [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}"
89
+
90
+ for var in no_proxy NO_PROXY; do
91
+ if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then
92
+ echo "export ${var}=${NP}" >> /home/user/.bashrc
93
+ fi
94
+ done
95
+ run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \
96
+ && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \
97
+ || echo 'no_proxy=\"${NP}\"' >> /etc/environment
98
+ grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \
99
+ && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \
100
+ || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1
101
+ echo "[cua_gym_vm_bridge] no_proxy=${NP}"
102
+ }
103
+
104
+ fix_vm_network
105
+
106
+ echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed"
ar_signature_005/initial_setup.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: Weekly contract signature sweep (PRE-task state)
3
+ Task ID: ar_signature_005
4
+ Domain: mock_websites
5
+ Mocks: docusign_mock, gmail_mock, slack_mock
6
+
7
+ PRE-task state:
8
+ - DocuSign: 3 envelopes for this week's contracts:
9
+ * 'Stark Industries SOW' = completed (Tony Stark signed)
10
+ * 'Oscorp License Agreement' = delivered (Norman Osborn, NOT signed)
11
+ * 'Tyrell Corp MSA' = sent (Eldon Tyrell, NOT signed)
12
+ - Gmail: baseline inbox (manager request + unrelated mail). NO reminder emails sent yet.
13
+ - Slack #finance: baseline chatter asking for the sweep. NO roundup posted yet.
14
+
15
+ Negative constraints (must NOT be present initially):
16
+ - NO 'sent'-folder reminder emails to n.osborn@oscorp.com or e.tyrell@tyrellcorp.com
17
+ - NO roundup message in Slack #finance
18
+ """
19
+
20
+ import os
21
+ import shlex
22
+ import subprocess
23
+ import time
24
+ import uuid
25
+
26
+ import requests
27
+
28
+ TASK_ID = "ar_signature_002"
29
+
30
+ MOCKS = {
31
+ "docusign_mock": "http://28.7.184.198:8130",
32
+ "gmail_mock": "http://28.7.184.198:8138",
33
+ "slack_mock": "http://28.7.184.198:8178",
34
+ }
35
+
36
+
37
+ # --------------------------------------------------------------------------
38
+ # Baseline state builders (MUST be identical in golden_patch.py)
39
+ # --------------------------------------------------------------------------
40
+ def docusign_baseline():
41
+ return {
42
+ "user": {
43
+ "id": "user_dana",
44
+ "name": "Dana Whitman",
45
+ "email": "dana.whitman@vertexpartners.com",
46
+ "title": "Finance Operations Manager",
47
+ "company": "Vertex Partners",
48
+ "avatar": "https://ui-avatars.com/api/?name=Dana+Whitman&background=0875E1&color=fff&size=128",
49
+ "memberSince": "2023-02-01",
50
+ "settings": {"defaultReminderDays": 3, "defaultExpirationDays": 120, "timezone": "America/New_York"},
51
+ },
52
+ "envelopes": [
53
+ # 1) Stark Industries SOW — COMPLETED (signed)
54
+ {
55
+ "id": "env_stark_sow",
56
+ "subject": "Stark Industries SOW",
57
+ "message": "Please review and sign the Statement of Work.",
58
+ "status": "completed",
59
+ "createdAt": "2026-06-22T09:00:00Z",
60
+ "sentAt": "2026-06-22T09:10:00Z",
61
+ "completedAt": "2026-06-24T15:42:00Z",
62
+ "voidedAt": None,
63
+ "declinedAt": None,
64
+ "lastActivityAt": "2026-06-24T15:42:00Z",
65
+ "expiresAt": "2026-10-20T09:10:00Z",
66
+ "senderId": "user_dana",
67
+ "folderId": None,
68
+ "templateId": None,
69
+ "reminderEnabled": True,
70
+ "reminderDays": 3,
71
+ "reminderFrequency": 2,
72
+ "documents": [
73
+ {"id": "doc_stark", "name": "Stark Industries SOW.pdf", "pageCount": 6, "order": 1,
74
+ "fileUrl": "https://picsum.photos/seed/starksow/800/1100", "fileType": "pdf"}
75
+ ],
76
+ "recipients": [
77
+ {"id": "rec_stark", "name": "Tony Stark", "email": "tony.stark@stark-ind.com",
78
+ "role": "signer", "routingOrder": 1, "status": "signed",
79
+ "signedAt": "2026-06-24T15:42:00Z", "viewedAt": "2026-06-24T15:30:00Z",
80
+ "deliveredAt": "2026-06-22T09:15:00Z", "declinedAt": None, "declineReason": None}
81
+ ],
82
+ "fields": [],
83
+ "history": [
84
+ {"id": "evt_stark_1", "timestamp": "2026-06-22T09:00:00Z", "action": "created",
85
+ "actorName": "Dana Whitman", "actorEmail": "dana.whitman@vertexpartners.com",
86
+ "details": "Envelope created"},
87
+ {"id": "evt_stark_2", "timestamp": "2026-06-22T09:10:00Z", "action": "sent",
88
+ "actorName": "Dana Whitman", "actorEmail": "dana.whitman@vertexpartners.com",
89
+ "details": "Envelope sent to Tony Stark"},
90
+ {"id": "evt_stark_3", "timestamp": "2026-06-24T15:42:00Z", "action": "completed",
91
+ "actorName": "Tony Stark", "actorEmail": "tony.stark@stark-ind.com",
92
+ "details": "Envelope completed and signed"},
93
+ ],
94
+ },
95
+ # 2) Oscorp License Agreement — DELIVERED (not signed)
96
+ {
97
+ "id": "env_oscorp_license",
98
+ "subject": "Oscorp License Agreement",
99
+ "message": "Please review and sign the License Agreement.",
100
+ "status": "delivered",
101
+ "createdAt": "2026-06-23T10:30:00Z",
102
+ "sentAt": "2026-06-23T10:35:00Z",
103
+ "completedAt": None,
104
+ "voidedAt": None,
105
+ "declinedAt": None,
106
+ "lastActivityAt": "2026-06-23T14:05:00Z",
107
+ "expiresAt": "2026-10-21T10:35:00Z",
108
+ "senderId": "user_dana",
109
+ "folderId": None,
110
+ "templateId": None,
111
+ "reminderEnabled": True,
112
+ "reminderDays": 3,
113
+ "reminderFrequency": 2,
114
+ "documents": [
115
+ {"id": "doc_oscorp", "name": "Oscorp License Agreement.pdf", "pageCount": 9, "order": 1,
116
+ "fileUrl": "https://picsum.photos/seed/oscorplicense/800/1100", "fileType": "pdf"}
117
+ ],
118
+ "recipients": [
119
+ {"id": "rec_oscorp", "name": "Norman Osborn", "email": "n.osborn@oscorp.com",
120
+ "role": "signer", "routingOrder": 1, "status": "delivered",
121
+ "signedAt": None, "viewedAt": "2026-06-23T14:05:00Z",
122
+ "deliveredAt": "2026-06-23T10:40:00Z", "declinedAt": None, "declineReason": None}
123
+ ],
124
+ "fields": [],
125
+ "history": [
126
+ {"id": "evt_oscorp_1", "timestamp": "2026-06-23T10:30:00Z", "action": "created",
127
+ "actorName": "Dana Whitman", "actorEmail": "dana.whitman@vertexpartners.com",
128
+ "details": "Envelope created"},
129
+ {"id": "evt_oscorp_2", "timestamp": "2026-06-23T10:35:00Z", "action": "sent",
130
+ "actorName": "Dana Whitman", "actorEmail": "dana.whitman@vertexpartners.com",
131
+ "details": "Envelope sent to Norman Osborn"},
132
+ {"id": "evt_oscorp_3", "timestamp": "2026-06-23T14:05:00Z", "action": "delivered",
133
+ "actorName": "Norman Osborn", "actorEmail": "n.osborn@oscorp.com",
134
+ "details": "Envelope viewed by recipient"},
135
+ ],
136
+ },
137
+ # 3) Tyrell Corp MSA — SENT (not signed, not yet viewed)
138
+ {
139
+ "id": "env_tyrell_msa",
140
+ "subject": "Tyrell Corp MSA",
141
+ "message": "Please review and sign the Master Service Agreement.",
142
+ "status": "sent",
143
+ "createdAt": "2026-06-24T08:15:00Z",
144
+ "sentAt": "2026-06-24T08:20:00Z",
145
+ "completedAt": None,
146
+ "voidedAt": None,
147
+ "declinedAt": None,
148
+ "lastActivityAt": "2026-06-24T08:20:00Z",
149
+ "expiresAt": "2026-10-22T08:20:00Z",
150
+ "senderId": "user_dana",
151
+ "folderId": None,
152
+ "templateId": None,
153
+ "reminderEnabled": True,
154
+ "reminderDays": 3,
155
+ "reminderFrequency": 2,
156
+ "documents": [
157
+ {"id": "doc_tyrell", "name": "Tyrell Corp MSA.pdf", "pageCount": 12, "order": 1,
158
+ "fileUrl": "https://picsum.photos/seed/tyrellmsa/800/1100", "fileType": "pdf"}
159
+ ],
160
+ "recipients": [
161
+ {"id": "rec_tyrell", "name": "Eldon Tyrell", "email": "e.tyrell@tyrellcorp.com",
162
+ "role": "signer", "routingOrder": 1, "status": "sent",
163
+ "signedAt": None, "viewedAt": None,
164
+ "deliveredAt": None, "declinedAt": None, "declineReason": None}
165
+ ],
166
+ "fields": [],
167
+ "history": [
168
+ {"id": "evt_tyrell_1", "timestamp": "2026-06-24T08:15:00Z", "action": "created",
169
+ "actorName": "Dana Whitman", "actorEmail": "dana.whitman@vertexpartners.com",
170
+ "details": "Envelope created"},
171
+ {"id": "evt_tyrell_2", "timestamp": "2026-06-24T08:20:00Z", "action": "sent",
172
+ "actorName": "Dana Whitman", "actorEmail": "dana.whitman@vertexpartners.com",
173
+ "details": "Envelope sent to Eldon Tyrell"},
174
+ ],
175
+ },
176
+ ],
177
+ "templates": [],
178
+ "folders": [],
179
+ "contacts": [
180
+ {"id": "c1", "name": "Tony Stark", "email": "tony.stark@stark-ind.com", "company": "Stark Industries", "title": "CEO"},
181
+ {"id": "c2", "name": "Norman Osborn", "email": "n.osborn@oscorp.com", "company": "Oscorp", "title": "CEO"},
182
+ {"id": "c3", "name": "Eldon Tyrell", "email": "e.tyrell@tyrellcorp.com", "company": "Tyrell Corp", "title": "Founder"},
183
+ ],
184
+ "auditLog": [],
185
+ }
186
+
187
+
188
+ def gmail_baseline():
189
+ return {
190
+ "user": {"userId": "u1", "username": "Dana Whitman", "email": "dana.whitman@vertexpartners.com"},
191
+ "emails": [
192
+ {
193
+ "id": "email_1", "threadId": "thread_1",
194
+ "from": {"name": "Rebecca Liu", "email": "rebecca.liu@vertexpartners.com"},
195
+ "to": [{"name": "Dana Whitman", "email": "dana.whitman@vertexpartners.com"}],
196
+ "cc": [], "bcc": [],
197
+ "subject": "Weekly contract signature sweep",
198
+ "body": "<p>Hi Dana,</p><p>Can you run the signature sweep on this week's contracts in "
199
+ "DocuSign? Please nudge anyone who hasn't signed and post a roundup in #finance. "
200
+ "The three to watch are the Stark Industries SOW, the Oscorp License Agreement, and "
201
+ "the Tyrell Corp MSA.</p><p>Thanks,<br>Rebecca</p>",
202
+ "timestamp": "2026-06-29T08:05:00Z",
203
+ "read": False, "starred": True, "important": True,
204
+ "labels": ["l1"], "category": "primary", "folder": "inbox", "attachments": [],
205
+ },
206
+ {
207
+ "id": "email_2", "threadId": "thread_2",
208
+ "from": {"name": "DocuSign", "email": "dse@docusign.net"},
209
+ "to": [{"name": "Dana Whitman", "email": "dana.whitman@vertexpartners.com"}],
210
+ "cc": [], "bcc": [],
211
+ "subject": "Completed: Stark Industries SOW",
212
+ "body": "<p>Your envelope <strong>Stark Industries SOW</strong> has been completed. "
213
+ "All recipients have signed.</p>",
214
+ "timestamp": "2026-06-24T15:43:00Z",
215
+ "read": True, "starred": False, "important": False,
216
+ "labels": ["l4"], "category": "primary", "folder": "inbox", "attachments": [],
217
+ },
218
+ {
219
+ "id": "email_3", "threadId": "thread_3",
220
+ "from": {"name": "Vertex IT", "email": "it@vertexpartners.com"},
221
+ "to": [{"name": "Dana Whitman", "email": "dana.whitman@vertexpartners.com"}],
222
+ "cc": [], "bcc": [],
223
+ "subject": "Scheduled maintenance this weekend",
224
+ "body": "<p>Reminder: VPN maintenance Saturday 02:00–04:00 ET.</p>",
225
+ "timestamp": "2026-06-27T16:20:00Z",
226
+ "read": True, "starred": False, "important": False,
227
+ "labels": [], "category": "primary", "folder": "inbox", "attachments": [],
228
+ },
229
+ ],
230
+ "labels": [
231
+ {"id": "l1", "name": "Work", "color": "#ef4444"},
232
+ {"id": "l2", "name": "Personal", "color": "#3b82f6"},
233
+ {"id": "l3", "name": "Travel", "color": "#22c55e"},
234
+ {"id": "l4", "name": "Finance", "color": "#eab308"},
235
+ ],
236
+ "drafts": [],
237
+ }
238
+
239
+
240
+ def slack_baseline():
241
+ users = [
242
+ {"userId": "user_1", "fullName": "Dana Whitman", "displayName": "Dana", "email": "dana.whitman@vertexpartners.com",
243
+ "avatar": "https://picsum.photos/200/200?random=1", "title": "Finance Operations Manager",
244
+ "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"},
245
+ {"userId": "user_2", "fullName": "Rebecca Liu", "displayName": "Rebecca", "email": "rebecca.liu@vertexpartners.com",
246
+ "avatar": "https://picsum.photos/200/200?random=2", "title": "Controller",
247
+ "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"},
248
+ {"userId": "user_3", "fullName": "Marcus Hale", "displayName": "Marcus", "email": "marcus.hale@vertexpartners.com",
249
+ "avatar": "https://picsum.photos/200/200?random=3", "title": "Legal Counsel",
250
+ "status": "away", "statusMessage": "", "statusEmoji": "", "timeZone": "America/Chicago"},
251
+ ]
252
+ channels = [
253
+ {"channelId": "general", "name": "general", "description": "Company-wide announcements", "topic": "",
254
+ "isPrivate": False, "isStarred": False, "members": ["user_1", "user_2", "user_3"],
255
+ "createdBy": "user_2", "createdAt": "2026-01-05T10:00:00Z", "pinnedMessages": [], "unreadCount": 0},
256
+ {"channelId": "random", "name": "random", "description": "Non-work banter", "topic": "",
257
+ "isPrivate": False, "isStarred": False, "members": ["user_1", "user_2", "user_3"],
258
+ "createdBy": "user_2", "createdAt": "2026-01-05T10:00:00Z", "pinnedMessages": [], "unreadCount": 0},
259
+ {"channelId": "finance", "name": "finance", "description": "Finance & contracts coordination",
260
+ "topic": "Contracts, signatures, invoicing", "isPrivate": False, "isStarred": True,
261
+ "members": ["user_1", "user_2", "user_3"], "createdBy": "user_2", "createdAt": "2026-02-01T09:00:00Z",
262
+ "pinnedMessages": [], "unreadCount": 0},
263
+ ]
264
+ messages = {
265
+ "general": [
266
+ {"messageId": "msg_g1", "senderId": "user_2", "content": "Morning all — quarter close prep starts this week.",
267
+ "timestamp": "2026-06-29T13:30:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False},
268
+ ],
269
+ "random": [
270
+ {"messageId": "msg_r1", "senderId": "user_3", "content": "Anyone up for lunch at the new place on 5th?",
271
+ "timestamp": "2026-06-28T16:05:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False},
272
+ ],
273
+ "finance": [
274
+ {"messageId": "msg_f1", "senderId": "user_2",
275
+ "content": "Reminder: run the signature sweep on this week's DocuSign contracts and post a roundup here.",
276
+ "timestamp": "2026-06-29T08:10:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False},
277
+ {"messageId": "msg_f2", "senderId": "user_1", "content": "On it — checking the three envelopes now.",
278
+ "timestamp": "2026-06-29T08:22:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False},
279
+ ],
280
+ }
281
+ return {
282
+ "currentUser": users[0],
283
+ "workspace": {"workspaceId": "ws_1", "workspaceName": "Vertex Partners", "icon": ""},
284
+ "users": users,
285
+ "channels": channels,
286
+ "messages": messages,
287
+ "threads": {},
288
+ "dms": [],
289
+ "bookmarkedMessages": [],
290
+ "callHistory": [],
291
+ "settings": {"theme": "light", "notifications": "all", "displayDensity": "comfortable",
292
+ "showAvatars": True, "use24Hour": False},
293
+ "invitations": [],
294
+ "notifications": [],
295
+ }
296
+
297
+
298
+ def launch_gui(command, delay_sec=1.0):
299
+ env = os.environ.copy()
300
+ env["DISPLAY"] = ":0"
301
+ subprocess.Popen(shlex.split(command), stdout=subprocess.DEVNULL,
302
+ stderr=subprocess.DEVNULL, env=env)
303
+ time.sleep(delay_sec)
304
+
305
+
306
+ def main():
307
+ # Generate and persist sid for golden_patch.py and reward.py
308
+ sid = str(uuid.uuid4())
309
+ with open("/tmp/task_web_sid", "w") as f:
310
+ f.write(sid)
311
+ print(f"Session ID generated: {sid}")
312
+
313
+ specs = [
314
+ ("docusign_mock", MOCKS["docusign_mock"], docusign_baseline()),
315
+ ("gmail_mock", MOCKS["gmail_mock"], gmail_baseline()),
316
+ ("slack_mock", MOCKS["slack_mock"], slack_baseline()),
317
+ ]
318
+
319
+ for name, url, state in specs:
320
+ resp = requests.post(f"{url}/post?sid={sid}",
321
+ json={"action": "set", "state": state}, timeout=30)
322
+ assert resp.status_code == 200, f"State injection failed for {name}: {resp.text}"
323
+ go = requests.get(f"{url}/go?sid={sid}", timeout=15).json()
324
+ assert go["initial_state"] is not None, f"initial_state is None after injection for {name}"
325
+ print(f" {name}: state injected and verified")
326
+
327
+ print("All initial states injected successfully!")
328
+
329
+ # GUI-ready: DocuSign primary, then Gmail and Slack
330
+ launch_gui(f'google-chrome "{MOCKS["docusign_mock"]}/?sid={sid}"', delay_sec=2.0)
331
+ launch_gui(f'google-chrome "{MOCKS["gmail_mock"]}/?sid={sid}"', delay_sec=1.0)
332
+ launch_gui(f'google-chrome "{MOCKS["slack_mock"]}/?sid={sid}"', delay_sec=1.0)
333
+ print(f"GUI_READY: launched Chrome (docusign, gmail, slack) with sid={sid} on DISPLAY=:0")
334
+
335
+
336
+ main()
ar_signature_005/reward.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: Signature sweep — check 3 DocuSign envelopes, email reminders to
3
+ incomplete signers via Gmail, post a roundup in Slack #finance.
4
+ Task ID: ar_signature_005
5
+ Domain: mock_websites (docusign + gmail + slack)
6
+
7
+ Scoring (all deterministic / programmatic — no LLM judge):
8
+ C1 (0.25) Gmail: signing reminder sent to Oscorp signer n.osborn@oscorp.com
9
+ C2 (0.25) Gmail: signing reminder sent to Tyrell signer e.tyrell@tyrellcorp.com
10
+ C3 (0.10) Gmail: reminders sent ONLY to the two incomplete signers
11
+ (NO reminder to the completed Stark signer tony.stark@stark-ind.com)
12
+ C4 (0.15) Slack #finance roundup: Stark SOW reported as signed/completed
13
+ C5 (0.25) Slack #finance roundup: Oscorp & Tyrell reported as still outstanding
14
+ Total: 1.0
15
+
16
+ Only task-INTRODUCED changes are scored:
17
+ - Gmail 'sent' folder is empty in initial_env -> any sent reminder is a change.
18
+ - Slack #finance gains a NEW message (compared to that env's own initial_state).
19
+ - DocuSign envelopes are unchanged by the task, so they are used only as a
20
+ sanity precondition gate, never as a scoring component.
21
+ """
22
+ import sys
23
+ import json
24
+
25
+ try:
26
+ import requests
27
+ except Exception as e:
28
+ print(f"CRITICAL: requests not available: {e}")
29
+ print("REWARD: 0.0")
30
+ sys.exit(0)
31
+
32
+ DOCUSIGN_URL = 'http://28.7.184.198:8130'
33
+ GMAIL_URL = 'http://28.7.184.198:8138'
34
+ SLACK_URL = 'http://28.7.184.198:8178'
35
+
36
+ # Ground-truth values from task context
37
+ STARK_EMAIL = 'tony.stark@stark-ind.com' # Completed — must NOT be reminded
38
+ OSCORP_EMAIL = 'n.osborn@oscorp.com' # Delivered/not signed — must be reminded
39
+ TYRELL_EMAIL = 'e.tyrell@tyrellcorp.com' # Sent/not signed — must be reminded
40
+
41
+
42
+ # --- Read sid ---
43
+ try:
44
+ with open('/tmp/task_web_sid') as f:
45
+ sid = f.read().strip()
46
+ if not sid:
47
+ raise ValueError('sid is empty')
48
+ except Exception as e:
49
+ print(f"CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}")
50
+ print("REWARD: 0.0")
51
+ sys.exit(0)
52
+
53
+
54
+ def fetch(url):
55
+ try:
56
+ r = requests.get(f'{url}/go', params={'sid': sid}, timeout=120)
57
+ r.raise_for_status()
58
+ return r.json()
59
+ except Exception as e:
60
+ print(f"CRITICAL: cannot fetch {url}: {e}")
61
+ return None
62
+
63
+
64
+ gmail = fetch(GMAIL_URL)
65
+ slack = fetch(SLACK_URL)
66
+ docusign = fetch(DOCUSIGN_URL)
67
+
68
+ if gmail is None or slack is None:
69
+ print("REWARD: 0.0")
70
+ sys.exit(0)
71
+
72
+
73
+ def emails_to(rec, target):
74
+ """True if recipient list `rec` contains the target email (case-insensitive)."""
75
+ for r in (rec or []):
76
+ if isinstance(r, dict) and str(r.get('email', '')).strip().lower() == target.lower():
77
+ return True
78
+ return False
79
+
80
+
81
+ def text_of(email):
82
+ return (str(email.get('subject', '')) + ' ' + str(email.get('body', ''))).lower()
83
+
84
+
85
+ def is_reminder(email):
86
+ """Heuristic: the email reads as a signing reminder/nudge."""
87
+ t = text_of(email)
88
+ return ('remind' in t) or ('sign' in t) or ('signature' in t) or ('await' in t)
89
+
90
+
91
+ def verify_task():
92
+ total = 0.0
93
+
94
+ # ---- Gather Gmail 'sent' reminders (current state) ----
95
+ gcur = gmail.get('current_state') or {}
96
+ sent_emails = [e for e in (gcur.get('emails') or []) if e.get('folder') == 'sent']
97
+
98
+ reminded_oscorp = any(emails_to(e.get('to'), OSCORP_EMAIL) and is_reminder(e) for e in sent_emails)
99
+ reminded_tyrell = any(emails_to(e.get('to'), TYRELL_EMAIL) and is_reminder(e) for e in sent_emails)
100
+ reminded_stark = any(emails_to(e.get('to'), STARK_EMAIL) for e in sent_emails)
101
+
102
+ # Component 1: reminder to Oscorp signer (0.25)
103
+ try:
104
+ if reminded_oscorp:
105
+ print(f"PASS: C1 — signing reminder sent to {OSCORP_EMAIL} (0.25 pts)")
106
+ total += 0.25
107
+ else:
108
+ print(f"FAIL: C1 — no signing reminder to {OSCORP_EMAIL} in sent folder")
109
+ except Exception as e:
110
+ print(f"ERROR: C1 — {e}")
111
+
112
+ # Component 2: reminder to Tyrell signer (0.25)
113
+ try:
114
+ if reminded_tyrell:
115
+ print(f"PASS: C2 — signing reminder sent to {TYRELL_EMAIL} (0.25 pts)")
116
+ total += 0.25
117
+ else:
118
+ print(f"FAIL: C2 — no signing reminder to {TYRELL_EMAIL} in sent folder")
119
+ except Exception as e:
120
+ print(f"ERROR: C2 — {e}")
121
+
122
+ # Component 3: reminders ONLY to the two incomplete signers, NOT to Stark (0.10)
123
+ # Anchored to the change: requires both reminders to exist AND no Stark reminder,
124
+ # so it fails on initial_env (0 sent emails).
125
+ try:
126
+ if reminded_oscorp and reminded_tyrell and not reminded_stark:
127
+ print(f"PASS: C3 — reminders sent only to incomplete signers; none to {STARK_EMAIL} (0.10 pts)")
128
+ total += 0.10
129
+ else:
130
+ print(f"FAIL: C3 — exclusivity not satisfied "
131
+ f"(oscorp={reminded_oscorp}, tyrell={reminded_tyrell}, stark_reminded={reminded_stark})")
132
+ except Exception as e:
133
+ print(f"ERROR: C3 — {e}")
134
+
135
+ # ---- Slack #finance roundup: find NEW message(s) vs this env's own initial_state ----
136
+ sini = slack.get('initial_state') or {}
137
+ scur = slack.get('current_state') or {}
138
+ cur_user = (scur.get('currentUser') or {}).get('userId')
139
+ fin_init = (sini.get('messages') or {}).get('finance', [])
140
+ fin_cur = (scur.get('messages') or {}).get('finance', [])
141
+ new_msgs = fin_cur[len(fin_init):] if len(fin_cur) > len(fin_init) else []
142
+ # Concatenate content of new messages posted by the current user (the roundup)
143
+ roundup_text = ' '.join(
144
+ str(m.get('content', '')) for m in new_msgs
145
+ if (cur_user is None or m.get('senderId') == cur_user)
146
+ ).lower()
147
+
148
+ # Component 4: roundup reports Stark SOW as signed/completed (0.15)
149
+ try:
150
+ stark_signed = ('stark' in roundup_text) and (
151
+ 'sign' in roundup_text or 'complete' in roundup_text)
152
+ if new_msgs and stark_signed:
153
+ print(f"PASS: C4 — roundup reports Stark SOW signed/completed (0.15 pts)")
154
+ total += 0.15
155
+ else:
156
+ print(f"FAIL: C4 — roundup missing or does not report Stark as signed/completed")
157
+ except Exception as e:
158
+ print(f"ERROR: C4 — {e}")
159
+
160
+ # Component 5: roundup reports Oscorp & Tyrell as still outstanding (0.25)
161
+ try:
162
+ mentions_both = ('oscorp' in roundup_text) and ('tyrell' in roundup_text)
163
+ outstanding_kw = any(k in roundup_text for k in
164
+ ('outstanding', 'still', 'pending', 'await', 'unsigned',
165
+ 'not signed', 'reminder', 'sent reminder', 'remind'))
166
+ if new_msgs and mentions_both and outstanding_kw:
167
+ print(f"PASS: C5 — roundup reports Oscorp & Tyrell still outstanding (0.25 pts)")
168
+ total += 0.25
169
+ else:
170
+ print(f"FAIL: C5 — roundup does not report both Oscorp & Tyrell as outstanding "
171
+ f"(both_mentioned={mentions_both}, outstanding_kw={outstanding_kw})")
172
+ except Exception as e:
173
+ print(f"ERROR: C5 — {e}")
174
+
175
+ # ---- Sanity gate: DocuSign envelopes must not be modified (not scored) ----
176
+ if docusign is not None:
177
+ try:
178
+ dcur = docusign.get('current_state') or {}
179
+ statuses = {e.get('subject'): e.get('status') for e in dcur.get('envelopes', [])}
180
+ print(f"INFO: DocuSign envelope statuses (should be unchanged): {statuses}")
181
+ except Exception as e:
182
+ print(f"INFO: could not read DocuSign state: {e}")
183
+
184
+ final = round(min(total, 1.0), 4)
185
+ print(f"\nScore: {total}/1.0")
186
+ print(f"REWARD: {final}")
187
+ return final
188
+
189
+
190
+ verify_task()
ar_signature_005/reward_label.json ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/ar_signature_002/reward.py",
3
+ "api_url": "http://28.7.184.184:8000/v1/chat/completions",
4
+ "model": "Kimi-K2.6",
5
+ "max_code_chars": 100000,
6
+ "created_at": "2026-07-14 10:22:49",
7
+ "label": {
8
+ "task_id": "ar_signature_005",
9
+ "domain": "mock_websites",
10
+ "summary": "验证通过Gmail向DocuSign未完成签名者发送签署提醒,并在Slack #finance频道发布签名状态汇总",
11
+ "is_placeholder": false,
12
+ "data_sources": [
13
+ "/tmp/task_web_sid",
14
+ "docusign_mock (http://28.7.186.212:8150)",
15
+ "gmail_mock (http://28.7.186.212:8158)",
16
+ "slack_mock (http://28.7.186.212:8198)"
17
+ ],
18
+ "scoring_components": [
19
+ {
20
+ "name": "Component 1",
21
+ "weight": 0.25,
22
+ "description": "Gmail向Oscorp未完成签名者发送签署提醒",
23
+ "check_logic": "遍历 Gmail current_state 中 folder 为 'sent' 的邮件,检查是否存在收件人包含 n.osborn@oscorp.com(不区分大小写)且 is_reminder() 返回 True 的邮件;is_reminder() 检查 subject 与 body 拼接文本是否包含 'remind'、'sign'、'signature' 或 'await'",
24
+ "pass_condition": "sent 文件夹中存在一封发给 n.osborn@oscorp.com 的提醒邮件"
25
+ },
26
+ {
27
+ "name": "Component 2",
28
+ "weight": 0.25,
29
+ "description": "Gmail向Tyrell未完成签名者发送签署提醒",
30
+ "check_logic": "遍历 Gmail current_state 中 folder 为 'sent' 的邮件,检查是否存在收件人包含 e.tyrell@tyrellcorp.com(不区分大小写)且 is_reminder() 返回 True 的邮件",
31
+ "pass_condition": "sent 文件夹中存在一封发给 e.tyrell@tyrellcorp.com 的提醒邮件"
32
+ },
33
+ {
34
+ "name": "Component 3",
35
+ "weight": 0.1,
36
+ "description": "Gmail提醒仅发送给两位未完成签名者,未发送给已完成的Stark",
37
+ "check_logic": "检查 reminded_oscorp 与 reminded_tyrell 均为 True,且 reminded_stark 为 False;其中 reminded_stark 仅检查 sent 文件夹中是否存在发给 tony.stark@stark-ind.com 的邮件(不调用 is_reminder)",
38
+ "pass_condition": "同时满足:已发送 Oscorp 提醒、已发送 Tyrell 提醒、未向 Stark 发送任何邮件"
39
+ },
40
+ {
41
+ "name": "Component 4",
42
+ "weight": 0.15,
43
+ "description": "Slack #finance汇总报告Stark SOW已签署/完成",
44
+ "check_logic": "对比 Slack initial_state 与 current_state 的 finance 频道消息,取新增消息 new_msgs = fin_cur[len(fin_init):];筛选 senderId 为 currentUser 的消息并拼接 content 得到 roundup_text;检查 new_msgs 非空且 roundup_text 包含 'stark',同时包含 'sign' 或 'complete'",
45
+ "pass_condition": "finance 频道有新增消息,且内容提到 Stark 并包含 sign/complete 相关词汇"
46
+ },
47
+ {
48
+ "name": "Component 5",
49
+ "weight": 0.25,
50
+ "description": "Slack #finance汇总报告Oscorp和Tyrell仍未完成",
51
+ "check_logic": "在新增用户消息拼接的 roundup_text 上,检查是否同时包含 'oscorp' 和 'tyrell',且包含 'outstanding'、'still'、'pending'、'await'、'unsigned'、'not signed'、'reminder'、'sent reminder'、'remind' 中任一关键词",
52
+ "pass_condition": "finance 频道有新增消息,内容同时提到 Oscorp 和 Tyrell,并包含未完成/待处理相关关键词"
53
+ }
54
+ ],
55
+ "total_max_score": 1.0,
56
+ "score_aggregation": "各组件分数相加,最终通过 min(total, 1.0) 钳制到上限并四舍五入到4位小数",
57
+ "failure_modes": [
58
+ "读取 /tmp/task_web_sid 失败或为空,脚本打印 CRITICAL 并返回 0.0",
59
+ "requests 库未安装,脚本打印 CRITICAL 并返回 0.0",
60
+ "Gmail 或 Slack mock 服务拉取失败返回 None,脚本直接返回 0.0",
61
+ "DocuSign mock 拉取失败不会导致返回 0.0,仅打印 INFO 跳过 sanity gate",
62
+ "未发送给 Oscorp 的提醒邮件,C1 失败不得分",
63
+ "未发送给 Tyrell 的提醒邮件,C2 失败不得分",
64
+ "向 Stark 发送了任何邮件(无论是否为提醒),C3 失败不得分",
65
+ "Slack #finance 无新增消息,C4 和 C5 失败不得分",
66
+ "新增汇总消息未包含 Stark 已完成信息,C4 失败不得分",
67
+ "新增汇总消息未同时包含 Oscorp 和 Tyrell 未完成信息,C5 失败不得分"
68
+ ],
69
+ "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话标识,失败则直接返回 0.0。随后向 Gmail、Slack、DocuSign 三个 mock 服务拉取状态;若 Gmail 或 Slack 拉取失败,直接返回 0.0。评分分为五个组件累加:前三个组件检查 Gmail sent 文件夹,通过遍历邮件、匹配收件人邮箱(不区分大小写)并调用 is_reminder 启发式函数(检查 subject+body 是否含 remind/sign/signature/await)判断是否发送了签署提醒;C3 额外要求未向已完���的 Stark 发送任何邮件。第四、五组件检查 Slack #finance 频道相对于 initial_state 的新增消息,筛选当前用户发送的内容,拼接后检查是否分别正确报告了 Stark 已完成、Oscorp 与 Tyrell 仍 outstanding。DocuSign 仅作为 sanity precondition 打印信封状态,不参与计分。各组件通过则累加对应分值,最终用 min(total, 1.0) 钳制并四舍五入到 4 位小数输出。",
70
+ "confidence": 1.0
71
+ },
72
+ "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码:\n\n1. **任务信息提取**:\n - Task ID: ar_signature_002\n - Domain: mock_websites (docusign + gmail + slack)\n - 这是一个签名扫描任务,检查3个DocuSign信封,通过Gmail给未完成签名者发送邮件提醒,在Slack #finance发布汇总。\n\n2. **数据源**:\n - `/tmp/task_web_sid`:读取会话ID\n - DocuSign mock服务:`http://28.7.186.212:8150`\n - Gmail mock服务:`http://28.7.186.212:8158`\n - Slack mock服务:`http://28.7.186.212:8198`\n\n3. **评分组件**:\n - C1 (0.25): Gmail发送提醒给 Oscorp 签名者 n.osborn@oscorp.com\n - C2 (0.25): Gmail发送提醒给 Tyrell 签名者 e.tyrell@tyrellcorp.com\n - C3 (0.10): Gmail只发送给两个未完成签名者,没有发送给已完成的Stark签名者 tony.stark@stark-ind.com\n - C4 (0.15): Slack #finance 汇总报告 Stark SOW 已签名/完成\n - C5 (0.25): Slack #finance 汇总报告 Oscorp & Tyrell 仍然未完成\n\n4. **评分逻辑**:\n - 读取 sid 文件,失败则返回 0.0\n - 获取 gmail、slack、docusign 状态\n - gmail 或 slack 获取失败返回 0.0\n - 检查 Gmail sent 文件夹中的邮件:\n - 判断是否是提醒邮件(subject + body 包含 remind/sign/signature/await)\n - 检查收件人是否匹配目标邮箱\n - 检查 Slack #finance 新消息(与 initial_state 对比,取新增消息):\n - 只考虑当前用户发送的消息\n - 检查文本内容是否包含关键词\n - DocuSign 仅作为 sanity check,不评分\n - 总分累加,最后 min(total, 1.0) 并四舍五入到4位小数\n\n5. **失败模式**:\n - 读取 sid 失败:CRITICAL,返回 0.0\n - requests 不可用:CRITICAL,返回 0.0\n - 获取 gmail 或 slack 失败:返回 0.0\n - 各组件失败会打印 FAIL 但不提前退出,只是不加分\n - DocuSign 获取失败不会导致返回 0.0(只是打印 INFO)\n\n6. **is_placeholder**:false,这是一个真正的评分脚本。\n\n7. **score_aggregation**:各组件分数相加,最终用 min(total, 1.0) 钳制到上限。\n\n8. **confidence**:1.0,因为代码清晰完整。\n\n现在构建 JSON:\n\n- task_id: \"ar_signature_002\"\n- domain: \"mock_websites\"\n- summary: \"验证通过Gmail向DocuSign未完成签名者发送提醒邮件,并在Slack #finance频道发布签名状态汇总\"\n- is_placeholder: false\n- data_sources: [\"/tmp/task_web_sid\", \"docusign_mock (http://28.7.186.212:8150)\", \"gmail_mock (http://28.7.186.212:8158)\", \"slack_mock (http://28.7.186.212:8198)\"]\n- scoring_components: 5个组件\n- total_max_score: 1.0\n- score_aggregation: \"各组件分数相加,最终通过 min(total, 1.0) 钳制到上限\"\n- failure_modes: [\"读取 /tmp/task_web_sid 失败\", \"requests 库不可用\", \"Gmail 或 Slack mock 状态拉取失败\", \"未发送 Oscorp 提醒\", \"未发送 Tyrell 提醒\", \"向已完成签名的 Stark 发送了提醒\", \"Slack #finance 无新增消息\", \"汇总消息未正确报告 Stark 已完成\", \"汇总消息未正确报告 Oscorp 和 Tyrell 未完成\"]\n- scoring_logic_explanation: 详细说明执行顺序...\n- confidence: 1.0\n\n确保所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样。\n\n检查 JSON 格式要求:\n- 不要输出 Markdown 代码块标记\n- 不要输出额外解释\n- 不要输出思考过程\n- 不要输出 <thinking> 标签\n- 第一个字符必须是 {,最后一个字符必须是 }\n\n让我仔细构建每个组件:\n\nComponent 1:\n- name: \"Component 1\"\n- weight: 0.25\n- description: \"Gmail向Oscorp未完成签名者发送签署提醒\"\n- check_logic: \"遍历 Gmail current_state 中 folder 为 'sent' 的邮件,检查是否存在收件人包含 n.osborn@oscorp.com(不区分大小写)且 is_reminder() 返回 True 的邮件。is_reminder() 检查 subject 与 body 拼接后的文本是否包含 'remind'、'sign'、'signature' 或 'await'。\"\n- pass_condition: \"sent 文件夹中存在一封发给 n.osborn@oscorp.com 的提醒邮件\"\n\nComponent 2:\n- name: \"Component 2\"\n- weight: 0.25\n- description: \"Gmail向Tyrell未完成签名者发送签署提醒\"\n- check_logic: \"遍历 Gmail current_state 中 folder 为 'sent' 的邮件,检查是否存在收件人包含 e.tyrell@tyrellcorp.com(不区分大小写)且 is_reminder() 返回 True 的邮件。\"\n- pass_condition: \"sent 文件夹中存在一封发给 e.tyrell@tyrellcorp.com 的提醒邮件\"\n\nComponent 3:\n- name: \"Component 3\"\n- weight: 0.10\n- description: \"Gmail提醒仅发送给两位未完成签名者,未发送给已完成的Stark\"\n- check_logic: \"检查 reminded_oscorp 和 reminded_tyrell 均为 True,且 reminded_stark 为 False。reminded_stark 检查 sent 文件夹中是否存在发给 tony.stark@stark-ind.com 的邮件(不检查 is_reminder,仅检查收件人)。\"\n- pass_condition: \"同时满足:已发送 Oscorp 提醒、已发送 Tyrell 提醒、未发送 Stark 邮件\"\n\nComponent 4:\n- name: \"Component 4\"\n- weight: 0.15\n- description: \"Slack #finance 汇总消息报告 Stark SOW 已签署/完成\"\n- check_logic: \"对比 Slack initial_state 与 current_state 的 finance 频道消息,取新增消息 new_msgs(fin_cur[len(fin_init):])。筛选 senderId 为 currentUser 的消息,拼接 content 得到 roundup_text。检查 new_msgs 非空且 roundup_text 包含 'stark',同时包含 'sign' 或 'complete'。\"\n- pass_condition: \"finance 频道有新增消息,且内容同时提到 Stark 以及 sign/complete 相关词汇\"\n\nComponent 5:\n- name: \"Component 5\"\n- weight: 0.25\n- description: \"Slack #finance 汇总消息报告 Oscorp 和 Tyrell 仍未完成\"\n- check_logic: \"在新增用户消息拼接的 roundup_text 上,检查是否同时包含 'oscorp' 和 'tyrell',且包含 outstanding/still/pending/await/unsigned/not signed/reminder/sent reminder/remind 中任一关键词。\"\n- pass_condition: \"finance 频道有新增消息,内容同时提到 Oscorp 和 Tyrell,并包含未完成/待处理相关关键词\"\n\nfailure_modes:\n- \"读取 /tmp/task_web_sid 失败或为空,脚本打印 CRITICAL 并返回 0.0\"\n- \"requests 库未安装,脚本打印 CRITICAL 并返回 0.0\"\n- \"Gmail 或 Slack mock 服务拉取失败返回 None,脚本直接返回 0.0\"\n- \"DocuSign mock 拉取失败不会导致返回 0.0,仅打印 INFO 跳过 sanity gate\"\n- \"未发送给 Oscorp 的提醒邮件,C1 失败不得分\"\n- \"未发送给 Tyrell 的提醒邮件,C2 失败不得分\"\n- \"向 Stark 发送了任何邮件(无论是否为提醒),C3 失败不得分\"\n- \"Slack #finance 无新增消息,C4 和 C5 失败不得分\"\n- \"新增汇总消息未包含 Stark 已完成信息,C4 失败不得分\"\n- \"新增汇总消息未同时包含 Oscorp 和 Tyrell 未完成信息,C5 失败不得分\"\n\nscoring_logic_explanation:\n脚本首先读取 /tmp/task_web_sid 获取会话标识,失败则直接返回 0.0。随后并行向 Gmail、Slack、DocuSign 三个 mock 服务拉取当前状态;若 Gmail 或 Slack 拉取失败,直接返回 0.0。评分分为五个组件累加:前三个组件检查 Gmail sent 文件夹,通过遍历邮件、匹配收件人邮箱(不区分大小写)并调用 is_reminder 启发式函数(检查 subject+body 是否含 remind/sign/signature/await)判断是否发送了签署提醒;C3 额外要求未向已完成的 Stark 发送任何邮件。第四、五组件检查 Slack #finance 频道相对于 initial_state 的新增消息,筛选当前用户发送的内容,拼接后检查是否分别正确报告了 Stark 已完成、Oscorp 与 Tyrell 仍 outstanding。DocuSign 仅作为 sanity precondition 打印信封状态,不参与计分。各组件通过则累加对应分值,最终用 min(total, 1.0) 钳制并四舍五入到 4 位小数输出。\n\n确保 JSON 合法,没有尾随逗号。 </think> {\"task_id\":\"ar_signature_002\",\"domain\":\"mock_websites\",\"summary\":\"验证通过Gmail向DocuSign未完成签名者发送签署提醒,并在Slack #finance频道发布签名状态汇总\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"docusign_mock (http://28.7.186.212:8150)\",\"gmail_mock (http://28.7.186.212:8158)\",\"slack_mock (http://28.7.186.212:8198)\"],\"scoring_components\":[{\"name\":\"Component 1\",\"weight\":0.25,\"description\":\"Gmail向Oscorp未完成签名者发送签署提醒\",\"check_logic\":\"遍历 Gmail current_state 中 folder 为 'sent' 的邮件,检查是否存在收件人包含 n.osborn@oscorp.com(不区分大小写)且 is_reminder() 返回 True 的邮件;is_reminder() 检查 subject 与 body 拼接文本是否包含 'remind'、'sign'、'signature' 或 'await'\",\"pass_condition\":\"sent 文件夹中存在一封发给 n.osborn@oscorp.com 的提醒邮件\"},{\"name\":\"Component 2\",\"weight\":0.25,\"description\":\"Gmail向Tyrell未完成签名者发送签署提醒\",\"check_logic\":\"遍历 Gmail current_state 中 folder 为 'sent' 的邮件,检查是否存在收件人包含 e.tyrell@tyrellcorp.com(不区分大小写)且 is_reminder() 返回 True 的邮件\",\"pass_condition\":\"sent 文件夹中存在一封发给 e.tyrell@tyrellcorp.com 的提醒邮件\"},{\"name\":\"Component 3\",\"weight\":0.10,\"description\":\"Gmail提醒仅发送给两位未完成签名者,未发送给已完成的Stark\",\"check_logic\":\"检查 reminded_oscorp 与 reminded_tyrell 均为 True,且 reminded_stark 为 False;其中 reminded_stark 仅检查 sent 文件夹中是否存在发给 tony.stark@stark-ind.com 的邮件(不调用 is_reminder)\",\"pass_condition\":\"同时满足:已发送 Oscorp 提醒、已发送 Tyrell 提醒、未向 Stark 发送任何邮件\"},{\"name\":\"Component 4\",\"weight\":0.15,\"description\":\"Slack #finance汇总报告Stark SOW已签署/完成\",\"check_logic\":\"对比 Slack initial_state 与 current_state 的 finance 频道消息,取新增消息 new_msgs = fin_cur[len(fin_init):];筛选 senderId 为 currentUser 的消息并拼接 content 得到 roundup_text;检查 new_msgs 非空且 roundup_text 包含 'stark',同时包含 'sign' 或 'complete'\",\"pass_condition\":\"finance 频道有新增消息,且内容提到 Stark 并包含 sign/complete 相关词汇\"},{\"name\":\"Component 5\",\"weight\":0.25,\"description\":\"Slack #finance汇总报告Oscorp和Tyrell仍未完成\",\"check_logic\":\"在新增用户消息拼接的 roundup_text 上,检查是否同时包含 'oscorp' 和 'tyrell',且包含 'outstanding'、'still'、'pending'、'await'、'unsigned'、'not signed'、'reminder'、'sent reminder'、'remind' 中任一关键词\",\"pass_condition\":\"finance 频道有新增消息,内容同时提到 Oscorp 和 Tyrell,并包含未完成/待处理相关关键词\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最终通过 min(total, 1.0) 钳制到上限并四舍五入到4位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空,脚本打印 CRITICAL 并返回 0.0\",\"requests 库未安装,脚本打印 CRITICAL 并返回 0.0\",\"Gmail 或 Slack mock 服务拉取失败返回 None,脚本直接返回 0.0\",\"DocuSign mock 拉取失败不会导致返回 0.0,仅打印 INFO 跳过 sanity gate\",\"未发送给 Oscorp 的提醒邮件,C1 失败不得分\",\"未发送给 Tyrell 的提醒邮件,C2 失败不得分\",\"向 Stark 发送了任何邮件(无论是否为提醒),C3 失败不得分\",\"Slack #finance 无新增消息,C4 和 C5 失败不得分\",\"新增汇总消息未包含 Stark 已完成信息,C4 失败不得分\",\"新增汇总消息未同时包含 Oscorp 和 Tyrell 未完成信息,C5 失败不得分\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话标识,失败则直接返回 0.0。随后向 Gmail、Slack、DocuSign 三个 mock 服务拉取状态;若 Gmail 或 Slack 拉取失败,直接返回 0.0。评分分为五个组件累加:前三个组件检查 Gmail sent 文件夹,通过遍历邮件、匹配收件人邮箱(不区分大小写)并调用 is_reminder 启发式函数(检查 subject+body 是否含 remind/sign/signature/await)判断是否发送了签署提醒;C3 额外要求未向已完成的 Stark 发送任何邮件。第四、五组件检查 Slack #finance 频道相对于 initial_state 的新增消息,筛选当前用户发送的内容,拼接后检查是否分别正确报告了 Stark 已完成、Oscorp 与 Tyrell 仍 outstanding。DocuSign 仅作为 sanity precondition 打印信封状态,不参与计分。各组件通过则累加对应分值,最终用 min(total, 1.0) 钳制并四舍五入到 4 位小数输出。\",\"confidence\":1.0}"
73
+ }
calc_employee_roles_003__long/.PLACEHOLDER ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ This directory is intentionally empty.
2
+ It exists only to satisfy start_our_benchmark_test.sh's uniform
3
+ 'cache_dir/<tid>/ must exist' precheck. Non-mock tasks do not use
4
+ cua_gym cache; their evaluators read a vm_file tarball instead.
5
+ See docs/0716_迁移执行日志.md § S15 for details.
calc_employee_roles_003__long/2b91e566-64fb-51d8-90c6-e534370d1020_Employee_Roles_and_Ranks_1.xlsx ADDED
Binary file (5.9 kB). View file
 
calc_employee_roles_003__long/Employee_Roles_and_Ranks_gold_1.xlsx ADDED
Binary file (6.45 kB). View file
 
calc_employee_roles_003__long/Employee_Roles_and_Ranks_gold_2.xlsx ADDED
Binary file (6.45 kB). View file
 
calc_employee_roles_003__long/Employee_Roles_and_Ranks_gold_3.xlsx ADDED
Binary file (6.45 kB). View file
 
calc_employee_roles_003__long/Employee_Roles_and_Ranks_gold_4.xlsx ADDED
Binary file (6.45 kB). View file
 
calc_employee_roles_003__long/Employee_Roles_and_Ranks_gold_5.xlsx ADDED
Binary file (6.45 kB). View file
 
calc_employee_roles_003__long/cfebbe10-8574-50f8-89ac-4adbc38c6713_Employee_Roles_and_Ranks_2.xlsx ADDED
Binary file (5.9 kB). View file
 
calc_employee_roles_003__long/d2218574-2113-5bc6-9304-dd4fc048bb44_Employee_Roles_and_Ranks_5.xlsx ADDED
Binary file (5.9 kB). View file
 
calc_employee_roles_003__long/d7bc84eb-e864-507e-a3bb-11f4b5a44d58_Employee_Roles_and_Ranks_4.xlsx ADDED
Binary file (5.9 kB). View file
 
calc_employee_roles_003__long/f1da68fd-9e78-5d2b-983d-166ae7f7607b_Employee_Roles_and_Ranks_3.xlsx ADDED
Binary file (5.9 kB). View file
 
csops_email_to_crm_case_001/_cua_gym_vm_bridge.sh ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # CUA-Gym VM-side network fix (direct-IP mock access).
3
+ #
4
+ # Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by
5
+ # their real IDC address (http://28.7.184.198:81xx) instead of the old
6
+ # localhost:9000-9097 socat bridge, so the VM only needs two fixes:
7
+ #
8
+ # 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's
9
+ # cluster DNS, which is unreachable from QEMU SLIRP NAT
10
+ # ("Temporary failure in name resolution").
11
+ # 2. The mock host excluded from the woa http proxy — otherwise the VM's
12
+ # Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403
13
+ # from the proxy when hitting 28.7.184.198:81xx. (The old socat path never
14
+ # hit this because localhost is bypassed by default.)
15
+ #
16
+ # Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic
17
+ # OSWorld setup pipeline.
18
+ #
19
+ # Argv:
20
+ # $1 optional sudo password (default "password"; SetupController
21
+ # substitutes {CLIENT_PASSWORD} when uploaded as a cache file).
22
+ # $2 unused (kept for backward compat — was socat first port 9000).
23
+ # $3 unused (kept for backward compat — was socat last port 9097).
24
+ # $4 optional mock host IP (default 28.7.184.198).
25
+
26
+ set +e
27
+
28
+ PASS="${1:-password}"
29
+ MOCK_HOST="${4:-28.7.184.198}"
30
+ # Derive the /16 IDC subnet so future port/host tweaks on the same segment
31
+ # stay bypassed too (28.7.184.198 -> 28.7.0.0/16).
32
+ MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')"
33
+
34
+ run_root() {
35
+ echo "$PASS" | sudo -S -p "" bash -c "$1"
36
+ }
37
+
38
+ # Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2.
39
+ GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')"
40
+ GW="${GW:-10.0.2.2}"
41
+
42
+ # ─── CUA-Gym network fix (Taiji-specific) ─────────────────────────────
43
+ fix_vm_network() {
44
+ # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP
45
+ # DNS forwarder. Nothing hardcoded except the mock host above.
46
+ local GW_NET="${GW%.*}"
47
+ local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3
48
+ local OWN_CIDR
49
+ OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \
50
+ | awk '{print $4; exit}')"
51
+ local OWN_IP="${OWN_CIDR%/*}"
52
+ local OWN_NET=""
53
+ [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24"
54
+
55
+ # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps
56
+ # systemd-resolved/NetworkManager from clobbering it.
57
+ if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf
58
+ chattr +i /etc/resolv.conf 2>/dev/null || true"; then
59
+ echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})"
60
+ else
61
+ echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf"
62
+ fi
63
+
64
+ # 2) Build the proxy bypass list from detected values + the direct-IP
65
+ # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx
66
+ # reachable from inside the VM — without it the woa proxy 403s it.
67
+ local ignore_list="['localhost', '127.0.0.0/8', '${GW}'"
68
+ [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'"
69
+ [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'"
70
+ [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'"
71
+ [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'"
72
+ [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'"
73
+ ignore_list="${ignore_list}]"
74
+
75
+ # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these.
76
+ if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then
77
+ echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}"
78
+ else
79
+ echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)"
80
+ fi
81
+
82
+ # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl).
83
+ local NP="localhost,127.0.0.1,${GW}"
84
+ [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}"
85
+ [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}"
86
+ [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24"
87
+ [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}"
88
+ [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}"
89
+
90
+ for var in no_proxy NO_PROXY; do
91
+ if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then
92
+ echo "export ${var}=${NP}" >> /home/user/.bashrc
93
+ fi
94
+ done
95
+ run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \
96
+ && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \
97
+ || echo 'no_proxy=\"${NP}\"' >> /etc/environment
98
+ grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \
99
+ && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \
100
+ || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1
101
+ echo "[cua_gym_vm_bridge] no_proxy=${NP}"
102
+ }
103
+
104
+ fix_vm_network
105
+
106
+ echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed"
csops_email_to_crm_case_001/initial_setup.py ADDED
@@ -0,0 +1,591 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --- MOCK_HOST_NO_PROXY_OVERRIDE: bypass woa proxy for locally-deployed mocks ---
2
+ import os as _os
3
+ _np = _os.environ.get("no_proxy", _os.environ.get("NO_PROXY", ""))
4
+ for _h in ("127.0.0.1", "localhost", "28.7.184.198"):
5
+ if _h not in _np:
6
+ _np = (_np + "," + _h).lstrip(",")
7
+ _os.environ["no_proxy"] = _np
8
+ _os.environ["NO_PROXY"] = _np
9
+ # --- end override ---
10
+
11
+ # --- wait_mocks_loaded: wait for mock backends ready AND browser tabs rendered ---
12
+ def wait_mocks_loaded(timeout=60, render_buffer=12):
13
+ """Wait for mock backends ready AND browser tabs rendered (via CDP).
14
+
15
+ Phase 1 — backend readiness: poll each mock's /state?sid= until it
16
+ returns 200 with 'stored_state' in the body.
17
+
18
+ Phase 2 — browser render verification: connect to Chrome's CDP
19
+ endpoint and wait for every open tab to reach 'networkidle' load
20
+ state with a non-trivial DOM element count. This confirms the SPA
21
+ has fetched its /go?sid= data and actually painted, not just that
22
+ the backend is up.
23
+
24
+ CDP port auto-detection: checks globals for _chrome_debug_port /
25
+ cdp_port / debug_port (set by tasks that use a dynamic port, e.g.
26
+ se_hard_008's launch_chrome_with_urls); defaults to 1337 for tasks
27
+ that use launch_gui's --remote-debugging-port injection.
28
+
29
+ Falls back to the old render_buffer sleep if Playwright or the CDP
30
+ endpoint is unavailable.
31
+ """
32
+ import urllib.request as _u, time as _t
33
+ g = globals()
34
+ _urls = {}
35
+ for _k, _v in list(g.items()):
36
+ if isinstance(_v, dict) and _v and all(isinstance(x, str) and x.startswith("http://") for x in _v.values()):
37
+ _urls.update(_v)
38
+ elif isinstance(_v, str) and _v.startswith("http://") and (_k.endswith("_URL") or _k.endswith("_url")):
39
+ _urls[_k] = _v
40
+ _sid = ""
41
+ for _k in ("sid", "SID", "task_sid", "session_id"):
42
+ if isinstance(g.get(_k), str) and g[_k]:
43
+ _sid = g[_k]; break
44
+ if not _sid:
45
+ for _k, _v in g.items():
46
+ if "sid" in _k.lower() and isinstance(_v, str) and _v:
47
+ _sid = _v; break
48
+ if not _urls or not _sid:
49
+ print(" wait_mocks_loaded: no mocks/sid found (%d urls, sid=%r), skipping" % (len(_urls), bool(_sid)))
50
+ return
51
+
52
+ # ---- Phase 1: backend readiness ----
53
+ _op = _u.build_opener(_u.ProxyHandler({}))
54
+ _dl = _t.time() + timeout
55
+ _todo = list(_urls.items())
56
+ while _todo and _t.time() < _dl:
57
+ _rest = []
58
+ for _n2, _uu in _todo:
59
+ try:
60
+ _r = _op.open("%s/state?sid=%s" % (_uu, _sid), timeout=5)
61
+ if _r.status == 200 and b"stored_state" in _r.read():
62
+ print(" %s: backend ready" % _n2); continue
63
+ except Exception:
64
+ pass
65
+ _rest.append((_n2, _uu))
66
+ _todo = _rest
67
+ if _todo:
68
+ _t.sleep(2)
69
+ _done = len(_urls) - len(_todo)
70
+ _pend = (" (pending: %s)" % [n for n, _ in _todo]) if _todo else ""
71
+ print(" mocks backend ready: %d/%d%s" % (_done, len(_urls), _pend))
72
+
73
+ # ---- Phase 2: browser render verification via CDP ----
74
+ # Auto-detect CDP port from globals (set by launch_chrome_with_urls
75
+ # in tasks that use a dynamic port); default to 1337.
76
+ _cdp_port = 1337
77
+ for _pk in ("_chrome_debug_port", "chrome_debug_port", "cdp_port", "debug_port"):
78
+ _pv = g.get(_pk)
79
+ if isinstance(_pv, int) and 0 < _pv < 65536:
80
+ _cdp_port = _pv; break
81
+ _cdp_ok = False
82
+ try:
83
+ from playwright.sync_api import sync_playwright
84
+ _cdp_dl = _t.time() + max(10.0, _dl - _t.time()) # leftover budget, floor 10s
85
+ with sync_playwright() as _p:
86
+ _br = None
87
+ # Retry-connect: Chrome may still be starting up.
88
+ while _t.time() < _cdp_dl:
89
+ try:
90
+ _br = _p.chromium.connect_over_cdp("http://localhost:%d" % _cdp_port)
91
+ break
92
+ except Exception:
93
+ _t.sleep(0.5)
94
+ if _br is None:
95
+ print(" wait_mocks_loaded: CDP connect to localhost:%d failed; "
96
+ "is Chrome launched with --remote-debugging-port?" % _cdp_port)
97
+ else:
98
+ # Wait for ALL expected tabs to appear, then verify each renders.
99
+ _n_expected = len(_urls)
100
+ _pages = []
101
+ _pg_dl = _t.time() + 15
102
+ _last_count = -1
103
+ _stable_since = None
104
+ while _t.time() < _pg_dl:
105
+ _pages = []
106
+ for _c in _br.contexts:
107
+ _pages.extend(_c.pages)
108
+ _cnt = len(_pages)
109
+ if _n_expected > 0 and _cnt >= _n_expected:
110
+ break # all expected tabs are open
111
+ if _cnt > 0 and _cnt == _last_count:
112
+ if _stable_since is None:
113
+ _stable_since = _t.time()
114
+ elif _t.time() - _stable_since >= 1.5:
115
+ break # tab count stable -> no more tabs opening
116
+ else:
117
+ _stable_since = None
118
+ _last_count = _cnt
119
+ _t.sleep(0.5)
120
+ # Re-fetch final snapshot so late-opening tabs are included.
121
+ _pages = []
122
+ for _c in _br.contexts:
123
+ _pages.extend(_c.pages)
124
+ if not _pages:
125
+ print(" wait_mocks_loaded: CDP connected but no open tabs found")
126
+ else:
127
+ print(" wait_mocks_loaded: %d tab(s) open (expected %d); "
128
+ "verifying render" % (len(_pages), _n_expected))
129
+ _ok_cnt = 0
130
+ for _pg in _pages:
131
+ _ttl = ""
132
+ try:
133
+ _ttl = _pg.title()
134
+ except Exception:
135
+ pass
136
+ try:
137
+ _pg.wait_for_load_state(
138
+ "networkidle",
139
+ timeout=int(max(5000, (_cdp_dl - _t.time()) * 1000)))
140
+ _n = _pg.evaluate("document.querySelectorAll('*').length")
141
+ if _n < 20:
142
+ print(" wait_mocks_loaded: WARNING tab %r has only %d "
143
+ "elements (render stall?)" % (_ttl, _n))
144
+ else:
145
+ print(" wait_mocks_loaded: tab %r rendered (%d elements)"
146
+ % (_ttl, _n))
147
+ _ok_cnt += 1
148
+ except Exception as _e:
149
+ print(" wait_mocks_loaded: tab %r render wait failed: %r"
150
+ % (_ttl, _e))
151
+ # Require ALL open tabs to render before skipping the
152
+ # render_buffer fallback, so no tab is left half-loaded.
153
+ if _ok_cnt > 0 and _ok_cnt == len(_pages):
154
+ _cdp_ok = True
155
+ else:
156
+ print(" wait_mocks_loaded: %d/%d tabs rendered, will fall back"
157
+ % (_ok_cnt, len(_pages)))
158
+ except ImportError:
159
+ print(" wait_mocks_loaded: playwright not installed; cannot verify browser render")
160
+ except Exception as _e:
161
+ print(" wait_mocks_loaded: CDP phase error (%r)" % _e)
162
+
163
+ if not _cdp_ok:
164
+ print(" wait_mocks_loaded: falling back to render_buffer=%ds sleep" % render_buffer)
165
+ _t.sleep(render_buffer)
166
+ else:
167
+ print(" wait_mocks_loaded: browser render verified, skipping render_buffer")
168
+ # --- end wait_mocks_loaded ---
169
+
170
+ # --- _open_remaining_mock_tabs: open all auto-detected mock URLs in new Chrome tabs ---
171
+ def _open_remaining_mock_tabs(primary_url=""):
172
+ """Open all auto-detected mock URLs in Chrome --new-tab, except primary_url."""
173
+ g = globals()
174
+ _urls = set()
175
+ for _k, _v in list(g.items()):
176
+ if "PROBE" in _k.upper() or _k.startswith("_"):
177
+ continue
178
+ if isinstance(_v, str) and _v.startswith("http://") and (_k.endswith("_URL") or _k.endswith("_url")):
179
+ _urls.add(_v)
180
+ elif isinstance(_v, dict) and _v and all(isinstance(x, str) and x.startswith("http://") for x in _v.values()):
181
+ _urls.update(_v.values())
182
+ _sid = ""
183
+ for _k in ("sid", "SID", "task_sid", "session_id"):
184
+ if isinstance(g.get(_k), str) and g[_k]:
185
+ _sid = g[_k]; break
186
+ for _u in sorted(_urls):
187
+ if _u != primary_url:
188
+ launch_gui(f'google-chrome --new-tab "{_u}/?sid={_sid}"', delay_sec=1.0)
189
+ # --- end _open_remaining_mock_tabs ---
190
+
191
+
192
+ """
193
+ Initial Setup: Urgent customer email -> log CRM support case, escalate, acknowledge.
194
+ Task ID: csops_email_to_crm_case_001
195
+ Domain: mock_websites
196
+ Mocks: gmail_mock, salesforce_mock
197
+ """
198
+ import json
199
+ import os
200
+ import shlex
201
+ import subprocess
202
+ import time
203
+ import uuid
204
+ from datetime import datetime, timezone
205
+
206
+ import requests
207
+
208
+ # --- Config ---
209
+ GMAIL_URL = 'http://28.7.184.198:8138'
210
+ SF_URL = 'http://28.7.184.198:8175'
211
+
212
+ sid = str(uuid.uuid4())
213
+
214
+ # --- §1.5 Egress proxy helper ---
215
+ PROXY_CANDIDATES = [
216
+ os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy'),
217
+ None,
218
+ ]
219
+
220
+
221
+ def resolve_proxy(probe_url):
222
+ try:
223
+ requests.get(probe_url, timeout=8)
224
+ return None
225
+ except Exception:
226
+ pass
227
+ for candidate in PROXY_CANDIDATES:
228
+ if not candidate:
229
+ continue
230
+ try:
231
+ requests.get(
232
+ probe_url,
233
+ timeout=12,
234
+ proxies={'http': candidate, 'https': candidate},
235
+ )
236
+ return candidate
237
+ except Exception:
238
+ continue
239
+ raise RuntimeError('No working route to mock servers; direct and proxy attempts failed')
240
+
241
+
242
+ PROXY = resolve_proxy(f'{SF_URL}/go?sid=conn-probe')
243
+ PROXIES = None
244
+ print(f'Egress proxy: {PROXY or "direct"}')
245
+
246
+ # --- Persist sid for golden_patch.py and reward.py ---
247
+ with open('/tmp/task_web_sid', 'w') as f:
248
+ f.write(sid)
249
+
250
+
251
+ def launch_gui(command, delay_sec=1.0):
252
+ env = os.environ.copy()
253
+ env['DISPLAY'] = ':0'
254
+ # Accept both a command string and a pre-split arg list (some tasks
255
+ # build arg lists themselves, e.g. se_hard_008).
256
+ if isinstance(command, str):
257
+ _parts = shlex.split(command)
258
+ else:
259
+ _parts = list(command)
260
+ # Inject CDP debug port so wait_mocks_loaded can verify browser render
261
+ # via Playwright connect_over_cdp. Idempotent: skip if any arg already
262
+ # starts with --remote-debugging-port (some tasks inject their own
263
+ # dynamic port, e.g. se_hard_008).
264
+ if _parts and 'google-chrome' in _parts[0] \
265
+ and not any(p.startswith('--remote-debugging-port') for p in _parts):
266
+ _parts[1:1] = ['--no-first-run', '--no-default-browser-check',
267
+ '--remote-debugging-port=1337']
268
+ _proc = subprocess.Popen(_parts, stdin=subprocess.DEVNULL,
269
+ stdout=subprocess.DEVNULL,
270
+ stderr=subprocess.DEVNULL, env=env,
271
+ start_new_session=True)
272
+ time.sleep(delay_sec)
273
+ if _proc.poll() is not None:
274
+ print(' WARNING: launch_gui process exited early (code=%s)'
275
+ % _proc.returncode)
276
+ return _proc
277
+
278
+
279
+ def today_at_utc(hour, minute):
280
+ return (
281
+ datetime.now(timezone.utc)
282
+ .replace(hour=hour, minute=minute, second=0, microsecond=0)
283
+ .isoformat()
284
+ .replace('+00:00', 'Z')
285
+ )
286
+
287
+
288
+ def build_gmail_state():
289
+ return {
290
+ "user": {
291
+ "userId": "u1",
292
+ "username": "Acme Support",
293
+ "email": "demo@acme-support.com",
294
+ "avatar": "https://i.pravatar.cc/150?u=acme-support",
295
+ },
296
+ "emails": [
297
+ {
298
+ "id": "email_esc",
299
+ "threadId": "thread_esc",
300
+ "from": {"name": "Dana Reeves", "email": "ops@brightwave.io"},
301
+ "to": [{"name": "Acme Support", "email": "demo@acme-support.com"}],
302
+ "cc": [],
303
+ "bcc": [],
304
+ "subject": "URGENT: Dashboard PDF exports broken since this morning",
305
+ "body": (
306
+ "<p>Hi Acme Support,</p>"
307
+ "<p>Since ~8am ET none of our scheduled dashboard PDF exports are "
308
+ "generating &mdash; every user gets a spinner that never finishes. "
309
+ "We present these to our board tomorrow morning, so this is blocking. "
310
+ "Please help ASAP. For the Salesforce support case, please mark the "
311
+ "case priority as High and the case status as Working.</p>"
312
+ "<p>&mdash; Dana, Ops, Brightwave Media.</p>"
313
+ ),
314
+ "timestamp": today_at_utc(12, 14),
315
+ "read": False,
316
+ "starred": False,
317
+ "important": False,
318
+ "labels": [],
319
+ "category": "primary",
320
+ "folder": "inbox",
321
+ "attachments": [],
322
+ },
323
+ {
324
+ "id": "email_news",
325
+ "threadId": "thread_news",
326
+ "from": {"name": "Analytics Weekly", "email": "newsletter@analyticsweekly.com"},
327
+ "to": [{"name": "Acme Support", "email": "demo@acme-support.com"}],
328
+ "cc": [],
329
+ "bcc": [],
330
+ "subject": "This week in dashboards: 5 visualization tips",
331
+ "body": (
332
+ "<p>Welcome to your weekly digest! This week we cover heatmaps, "
333
+ "small multiples, and choosing the right chart type for time series "
334
+ "data. Read on for our editor's picks.</p>"
335
+ ),
336
+ "timestamp": "2026-06-24T07:02:00Z",
337
+ "read": False,
338
+ "starred": False,
339
+ "important": False,
340
+ "labels": [],
341
+ "category": "promotions",
342
+ "folder": "inbox",
343
+ "attachments": [],
344
+ },
345
+ {
346
+ "id": "email_allhands",
347
+ "threadId": "thread_allhands",
348
+ "from": {"name": "People Ops", "email": "people@acme-support.com"},
349
+ "to": [{"name": "Acme Support", "email": "demo@acme-support.com"}],
350
+ "cc": [],
351
+ "bcc": [],
352
+ "subject": "Reminder: Company all-hands Friday at 10am",
353
+ "body": (
354
+ "<p>Hi team,</p>"
355
+ "<p>A quick reminder that our monthly all-hands is this Friday at "
356
+ "10am in the main hall. Agenda includes the Q2 roadmap and a live "
357
+ "Q&amp;A with leadership. See you there!</p>"
358
+ ),
359
+ "timestamp": "2026-06-23T16:45:00Z",
360
+ "read": True,
361
+ "starred": False,
362
+ "important": False,
363
+ "labels": [],
364
+ "category": "primary",
365
+ "folder": "inbox",
366
+ "attachments": [],
367
+ },
368
+ ],
369
+ "labels": [
370
+ {"id": "l1", "name": "Work", "color": "#ef4444"},
371
+ {"id": "l2", "name": "Personal", "color": "#3b82f6"},
372
+ {"id": "l3", "name": "Travel", "color": "#22c55e"},
373
+ {"id": "l4", "name": "Finance", "color": "#eab308"},
374
+ ],
375
+ "drafts": [],
376
+ }
377
+
378
+
379
+ # ======================================================================
380
+ # SALESFORCE INITIAL STATE
381
+ # ======================================================================
382
+ def build_salesforce_state():
383
+ users = [
384
+ {
385
+ "userId": "user-1", "firstName": "Jordan", "lastName": "Blake",
386
+ "email": "jordan.blake@acme-support.com", "phone": "(555) 123-4567",
387
+ "title": "Support Manager", "department": "Customer Support", "role": "Manager",
388
+ "avatar": "https://i.pravatar.cc/150?u=user-1",
389
+ "timezone": "America/New_York", "locale": "en-US", "theme": "lightning",
390
+ },
391
+ {
392
+ "userId": "user-2", "firstName": "Priya", "lastName": "Nair",
393
+ "email": "priya.nair@acme-support.com", "phone": "(555) 234-5678",
394
+ "title": "Customer Success Manager", "department": "Customer Success", "role": "CSM",
395
+ "avatar": "https://i.pravatar.cc/150?u=user-2",
396
+ "timezone": "America/New_York", "locale": "en-US", "theme": "lightning",
397
+ },
398
+ {
399
+ "userId": "user-3", "firstName": "Michael", "lastName": "Chen",
400
+ "email": "michael.chen@acme-support.com", "phone": "(555) 345-6789",
401
+ "title": "Support Engineer", "department": "Customer Support", "role": "Engineer",
402
+ "avatar": "https://i.pravatar.cc/150?u=user-3",
403
+ "timezone": "America/Chicago", "locale": "en-US", "theme": "lightning",
404
+ },
405
+ {
406
+ "userId": "user-4", "firstName": "Sarah", "lastName": "Davis",
407
+ "email": "sarah.davis@acme-support.com", "phone": "(555) 456-7890",
408
+ "title": "Support Engineer", "department": "Customer Support", "role": "Engineer",
409
+ "avatar": "https://i.pravatar.cc/150?u=user-4",
410
+ "timezone": "America/Los_Angeles", "locale": "en-US", "theme": "lightning",
411
+ },
412
+ {
413
+ "userId": "user-5", "firstName": "David", "lastName": "Brown",
414
+ "email": "david.brown@acme-support.com", "phone": "(555) 567-8901",
415
+ "title": "Customer Success Manager", "department": "Customer Success", "role": "CSM",
416
+ "avatar": "https://i.pravatar.cc/150?u=user-5",
417
+ "timezone": "America/Denver", "locale": "en-US", "theme": "lightning",
418
+ },
419
+ ]
420
+
421
+ accounts = [
422
+ {
423
+ "accountId": "account-1", "name": "Acme Corporation", "phone": "(555) 100-2000",
424
+ "website": "https://acme.com", "type": "Customer", "industry": "Technology",
425
+ "revenue": 50000000, "employees": 500,
426
+ "description": "Enterprise software company. Long-standing customer since 2020.",
427
+ "ownerId": "user-5",
428
+ "billingStreet": "100 Main St", "billingCity": "New York", "billingState": "NY",
429
+ "billingZip": "10001", "billingCountry": "United States",
430
+ "shippingStreet": "100 Main St", "shippingCity": "New York", "shippingState": "NY",
431
+ "shippingZip": "10001", "shippingCountry": "United States",
432
+ "createdDate": "2025-06-24T11:05:10.692Z", "modifiedDate": "2026-05-25T11:05:10.692Z",
433
+ },
434
+ {
435
+ "accountId": "account-2", "name": "Global Enterprises", "phone": "(555) 200-3000",
436
+ "website": "https://globalenterprises.com", "type": "Customer", "industry": "Finance",
437
+ "revenue": 120000000, "employees": 2000,
438
+ "description": "Multinational financial services firm with multiple product lines.",
439
+ "ownerId": "user-5",
440
+ "billingStreet": "500 Wall St", "billingCity": "New York", "billingState": "NY",
441
+ "billingZip": "10005", "billingCountry": "United States",
442
+ "shippingStreet": "500 Wall St", "shippingCity": "New York", "shippingState": "NY",
443
+ "shippingZip": "10005", "shippingCountry": "United States",
444
+ "createdDate": "2025-08-28T11:05:10.692Z", "modifiedDate": "2026-06-09T11:05:10.692Z",
445
+ },
446
+ {
447
+ "accountId": "account-6", "name": "Brightwave Media", "phone": "(555) 880-1144",
448
+ "website": "https://brightwave.io", "type": "Customer", "industry": "Media",
449
+ "revenue": 8500000, "employees": 140,
450
+ "description": "Digital media analytics company. Uses scheduled dashboard PDF "
451
+ "exports for executive and board reporting. Assigned CSM: Priya Nair.",
452
+ "ownerId": "user-2",
453
+ "billingStreet": "22 Harbor View", "billingCity": "Seattle", "billingState": "WA",
454
+ "billingZip": "98101", "billingCountry": "United States",
455
+ "shippingStreet": "22 Harbor View", "shippingCity": "Seattle", "shippingState": "WA",
456
+ "shippingZip": "98101", "shippingCountry": "United States",
457
+ "createdDate": "2025-09-12T11:05:10.692Z", "modifiedDate": "2026-06-01T11:05:10.692Z",
458
+ },
459
+ {
460
+ "accountId": "account-3", "name": "Northwind Logistics", "phone": "(555) 300-4000",
461
+ "website": "https://northwind.com", "type": "Customer", "industry": "Logistics",
462
+ "revenue": 30000000, "employees": 850,
463
+ "description": "Regional freight and logistics provider.",
464
+ "ownerId": "user-5",
465
+ "billingStreet": "9 Cargo Way", "billingCity": "Chicago", "billingState": "IL",
466
+ "billingZip": "60601", "billingCountry": "United States",
467
+ "shippingStreet": "9 Cargo Way", "shippingCity": "Chicago", "shippingState": "IL",
468
+ "shippingZip": "60601", "shippingCountry": "United States",
469
+ "createdDate": "2025-10-02T11:05:10.692Z", "modifiedDate": "2026-04-18T11:05:10.692Z",
470
+ },
471
+ ]
472
+
473
+ contacts = [
474
+ {
475
+ "contactId": "contact-1", "accountId": "account-1", "firstName": "Alice",
476
+ "lastName": "Williams", "title": "CTO", "department": "Engineering",
477
+ "email": "alice.w@acme.com", "phone": "(555) 100-2001", "mobile": "(555) 100-2002",
478
+ "mailingStreet": "100 Main St", "mailingCity": "New York", "mailingState": "NY",
479
+ "mailingZip": "10001", "mailingCountry": "United States", "ownerId": "user-5",
480
+ "createdDate": "2025-07-09T11:05:10.692Z", "modifiedDate": "2026-06-04T11:05:10.692Z",
481
+ },
482
+ {
483
+ "contactId": "contact-2", "accountId": "account-2", "firstName": "Robert",
484
+ "lastName": "Lang", "title": "VP Finance", "department": "Finance",
485
+ "email": "rlang@globalenterprises.com", "phone": "(555) 200-3001",
486
+ "mobile": "(555) 200-3002", "mailingStreet": "500 Wall St", "mailingCity": "New York",
487
+ "mailingState": "NY", "mailingZip": "10005", "mailingCountry": "United States",
488
+ "ownerId": "user-5", "createdDate": "2025-09-01T11:05:10.692Z",
489
+ "modifiedDate": "2026-05-12T11:05:10.692Z",
490
+ },
491
+ {
492
+ "contactId": "contact-7", "accountId": "account-6", "firstName": "Dana",
493
+ "lastName": "Reeves", "title": "Head of Operations", "department": "Operations",
494
+ "email": "ops@brightwave.io", "phone": "(555) 880-1150", "mobile": "(555) 880-1151",
495
+ "mailingStreet": "22 Harbor View", "mailingCity": "Seattle", "mailingState": "WA",
496
+ "mailingZip": "98101", "mailingCountry": "United States", "ownerId": "user-2",
497
+ "createdDate": "2025-09-15T11:05:10.692Z", "modifiedDate": "2026-06-01T11:05:10.692Z",
498
+ },
499
+ ]
500
+
501
+ cases = [
502
+ {
503
+ "caseId": "case-1", "caseNumber": "00001001", "subject": "Dashboard access error",
504
+ "status": "New", "priority": "High", "origin": "Phone", "type": "Problem",
505
+ "accountId": "account-1", "contactId": "contact-1",
506
+ "description": "Customer reports 403 Forbidden error when accessing the analytics "
507
+ "dashboard. Affects all admin users.",
508
+ "ownerId": "user-4", "createdDate": "2026-06-23T11:05:10.692Z",
509
+ "modifiedDate": "2026-06-23T11:05:10.692Z",
510
+ },
511
+ {
512
+ "caseId": "case-2", "caseNumber": "00001002", "subject": "Billing invoice discrepancy",
513
+ "status": "Working", "priority": "Medium", "origin": "Email", "type": "Question",
514
+ "accountId": "account-2", "contactId": "contact-2",
515
+ "description": "Customer questions a line item on the May invoice.",
516
+ "ownerId": "user-3", "createdDate": "2026-06-20T11:05:10.692Z",
517
+ "modifiedDate": "2026-06-22T11:05:10.692Z",
518
+ },
519
+ {
520
+ "caseId": "case-3", "caseNumber": "00001003", "subject": "Feature request: dark mode",
521
+ "status": "New", "priority": "Low", "origin": "Web", "type": "Feature Request",
522
+ "accountId": "account-3", "contactId": "contact-1",
523
+ "description": "Customer requests a dark theme for the reporting console.",
524
+ "ownerId": "user-4", "createdDate": "2026-06-18T11:05:10.692Z",
525
+ "modifiedDate": "2026-06-18T11:05:10.692Z",
526
+ },
527
+ {
528
+ "caseId": "case-4", "caseNumber": "00001004", "subject": "SSO login intermittently fails",
529
+ "status": "Working", "priority": "High", "origin": "Phone", "type": "Problem",
530
+ "accountId": "account-2", "contactId": "contact-2",
531
+ "description": "Some users are intermittently bounced back to the login screen "
532
+ "when authenticating via SSO.",
533
+ "ownerId": "user-3", "createdDate": "2026-06-19T11:05:10.692Z",
534
+ "modifiedDate": "2026-06-21T11:05:10.692Z",
535
+ },
536
+ {
537
+ "caseId": "case-5", "caseNumber": "00001005", "subject": "Onboarding walkthrough request",
538
+ "status": "Closed", "priority": "Low", "origin": "Email", "type": "Question",
539
+ "accountId": "account-3", "contactId": "contact-1",
540
+ "description": "New admin requested a guided onboarding session. Session scheduled "
541
+ "and completed.",
542
+ "ownerId": "user-4", "createdDate": "2026-06-10T11:05:10.692Z",
543
+ "modifiedDate": "2026-06-15T11:05:10.692Z", "closedDate": "2026-06-15T11:05:10.692Z",
544
+ },
545
+ ]
546
+
547
+ return {
548
+ "user": users[0],
549
+ "users": users,
550
+ "leads": [],
551
+ "accounts": accounts,
552
+ "contacts": contacts,
553
+ "opportunities": [],
554
+ "cases": cases,
555
+ "activities": [],
556
+ "chatterPosts": [],
557
+ "files": [],
558
+ "following": ["user-2", "user-3"],
559
+ "recentlyViewed": [],
560
+ "dismissedNotifications": [],
561
+ }
562
+
563
+
564
+ # ======================================================================
565
+ # Inject state into both mocks (same sid)
566
+ # ======================================================================
567
+ mocks = {
568
+ GMAIL_URL: build_gmail_state(),
569
+ SF_URL: build_salesforce_state(),
570
+ }
571
+
572
+ for url, state in mocks.items():
573
+ resp = requests.post(
574
+ f'{url}/post?sid={sid}',
575
+ json={'action': 'set', 'state': state},
576
+ timeout=30,
577
+ proxies=PROXIES,
578
+ )
579
+ assert resp.status_code == 200, f'State injection failed for {url}: {resp.text}'
580
+ go = requests.get(f'{url}/go?sid={sid}', timeout=10, proxies=PROXIES).json()
581
+ assert go['initial_state'] is not None, f'initial_state is None after injection for {url}'
582
+ print(f'State injected & verified: {url} sid={sid}')
583
+
584
+ # ======================================================================
585
+ # Launch browsers (Gmail + Salesforce), Gmail focused last/primary
586
+ # ======================================================================
587
+ chrome_proxy = f'--proxy-server={PROXY}' if PROXY else ''
588
+ launch_gui(f'google-chrome "{SF_URL}/?sid={sid}"', delay_sec=2.0)
589
+ launch_gui(f'google-chrome "{GMAIL_URL}/?sid={sid}"', delay_sec=2.0)
590
+ wait_mocks_loaded()
591
+ print(f'GUI_READY: launched Salesforce and Gmail with sid={sid}')
csops_email_to_crm_case_001/reward.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --- MOCK_HOST_NO_PROXY_OVERRIDE: bypass woa proxy for locally-deployed mocks ---
2
+ import os as _os
3
+ _np = _os.environ.get("no_proxy", _os.environ.get("NO_PROXY", ""))
4
+ for _h in ("127.0.0.1", "localhost", "28.7.184.198"):
5
+ if _h not in _np:
6
+ _np = (_np + "," + _h).lstrip(",")
7
+ _os.environ["no_proxy"] = _np
8
+ _os.environ["NO_PROXY"] = _np
9
+ # --- end override ---
10
+
11
+ """
12
+ Reward Script: Log an urgent customer email as a CRM support case, route it to the
13
+ account's CSM at high urgency, and send the customer an acknowledgement reply.
14
+ Task ID: csops_email_to_crm_case_001
15
+ Domain: mock_websites
16
+ Mocks: salesforce_mock (cua-gym-salesforce), gmail_mock (cua-gym-gmail)
17
+
18
+ Scoring rubric (sums to 1.0). Every component is anchored to a task-introduced
19
+ change so it FAILS on initial_env and PASSES on golden_env.
20
+
21
+ Salesforce (new case creation & routing) — 0.60 programmatic
22
+ C1 (0.20) A NEW case (not in initial) is linked to the Brightwave Media
23
+ account (account-6) AND the Dana Reeves contact (contact-7),
24
+ with origin 'Email'.
25
+ C2 (0.15) That new case uses Salesforce Case enum values priority
26
+ 'High' AND status 'Working'.
27
+ C3 (0.15) That new case is owned by the account CSM Priya Nair (user-2).
28
+ C4 (0.10) That new case's subject reflects the dashboard PDF export outage.
29
+
30
+ Gmail (acknowledgement reply & triage) — 0.40 programmatic
31
+ C5 (0.15) A NEW email in folder 'sent' is addressed to ops@brightwave.io.
32
+ C6 (0.10) The original inbound email 'email_esc' is now marked read.
33
+ C7 (0.15) The sent reply (a) references the logged case by its case number
34
+ AND (b) acknowledges the export issue is received / being worked.
35
+ Split 0.075 / 0.075 for partial credit.
36
+
37
+ Programmatic share = 1.0. No LLM judge needed: the case reference is a
38
+ contains-check on the deterministic case number, and the acknowledgement is a
39
+ keyword check — both reducible to programmatic verification, so per the
40
+ reward-gen rules an LLM judge is not warranted (and is unavailable here).
41
+ """
42
+
43
+ import html
44
+ import json
45
+ import os
46
+ import re
47
+ import sys
48
+
49
+ import requests
50
+
51
+ SF_URL = 'http://28.7.184.198:8155'
52
+ GM_URL = 'http://28.7.184.198:8118'
53
+
54
+ # --- Read sid (written by initial_setup.py) ---
55
+ try:
56
+ with open('/tmp/task_web_sid') as f:
57
+ sid = f.read().strip()
58
+ if not sid:
59
+ raise ValueError('sid is empty')
60
+ except Exception as e:
61
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
62
+ print('REWARD: 0.0')
63
+ sys.exit(0)
64
+
65
+ # --- Egress proxy helper (mandatory in this cluster) ---
66
+ PROXY_CANDIDATES = [
67
+ os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy'),
68
+ None,
69
+ ]
70
+
71
+
72
+ def resolve_proxy(probe_url):
73
+ try:
74
+ requests.get(probe_url, timeout=8)
75
+ return None
76
+ except Exception:
77
+ pass
78
+ for candidate in PROXY_CANDIDATES:
79
+ if not candidate:
80
+ continue
81
+ try:
82
+ requests.get(probe_url, timeout=12,
83
+ proxies={'http': candidate, 'https': candidate})
84
+ return candidate
85
+ except Exception:
86
+ continue
87
+ return None
88
+
89
+
90
+ PROXY = resolve_proxy(f'{SF_URL}/go?sid=conn-probe')
91
+ PROXIES = None
92
+
93
+
94
+ def fetch(url):
95
+ resp = requests.get(f'{url}/go?sid={sid}', timeout=15, proxies=PROXIES)
96
+ resp.raise_for_status()
97
+ return resp.json()
98
+
99
+
100
+ # --- Fetch state from both mocks ---
101
+ try:
102
+ sf = fetch(SF_URL)
103
+ gm = fetch(GM_URL)
104
+ except Exception as e:
105
+ print(f'CRITICAL: Cannot fetch state: {e}')
106
+ print('REWARD: 0.0')
107
+ sys.exit(0)
108
+
109
+ sf_initial = sf.get('initial_state') or {}
110
+ sf_current = sf.get('current_state') or {}
111
+ gm_initial = gm.get('initial_state') or {}
112
+ gm_current = gm.get('current_state') or {}
113
+
114
+ if not sf_current or not gm_current:
115
+ print('CRITICAL: current_state missing for one of the mocks')
116
+ print('REWARD: 0.0')
117
+ sys.exit(0)
118
+
119
+ BRIGHTWAVE_ACCOUNT = 'account-6' # Brightwave Media
120
+ DANA_CONTACT = 'contact-7' # Dana Reeves <ops@brightwave.io>
121
+ CSM_USER = 'user-2' # Priya Nair (account relationship owner / CSM)
122
+ CUSTOMER_EMAIL = 'ops@brightwave.io'
123
+ CUSTOMER_NAME = 'Dana Reeves'
124
+ CUSTOMER_ACCOUNT_NAME = 'Brightwave Media'
125
+ CSM_NAME = 'Priya Nair'
126
+ CSM_EMAIL = 'priya.nair@acme-support.com'
127
+ INBOUND_EMAIL_ID = 'email_esc'
128
+ EXPECTED_CASE_PRIORITY = 'High'
129
+ EXPECTED_CASE_STATUS = 'Working'
130
+
131
+
132
+ def normalize_text(*values):
133
+ raw = ' '.join(str(v) for v in values if v is not None)
134
+ raw = html.unescape(raw)
135
+ raw = re.sub(r'<[^>]+>', ' ', raw)
136
+ raw = raw.replace('\u2019', "'").replace('\u2018', "'")
137
+ raw = raw.lower()
138
+ raw = re.sub(r'[^a-z0-9@._+#]+', ' ', raw)
139
+ return re.sub(r'\s+', ' ', raw).strip()
140
+
141
+
142
+ def has_any(text, phrases):
143
+ norm_text = normalize_text(text)
144
+ return any(normalize_text(phrase) in norm_text for phrase in phrases)
145
+
146
+
147
+ def count_matches(text, phrases):
148
+ norm_text = normalize_text(text)
149
+ return sum(1 for phrase in phrases if normalize_text(phrase) in norm_text)
150
+
151
+
152
+ def matches_id_or_text(value, expected_id, *phrases):
153
+ norm_value = normalize_text(value)
154
+ if norm_value == normalize_text(expected_id):
155
+ return True
156
+ return any(normalize_text(phrase) in norm_value for phrase in phrases if phrase)
157
+
158
+
159
+ def case_observable_text(case):
160
+ if not case:
161
+ return ''
162
+ return normalize_text(
163
+ case.get('subject'),
164
+ case.get('description'),
165
+ case.get('type'),
166
+ case.get('origin'),
167
+ case.get('accountName'),
168
+ case.get('contactName'),
169
+ case.get('contactEmail'),
170
+ )
171
+
172
+
173
+ def text_reflects_export_issue(text):
174
+ topic_terms = [
175
+ 'dashboard', 'dashboards', 'pdf', 'export', 'exports',
176
+ 'report', 'reports', 'scheduled export', 'scheduled report',
177
+ ]
178
+ problem_terms = [
179
+ 'broken', 'outage', 'fail', 'failure', 'not generating',
180
+ 'spinner', 'never finishes', 'stuck', 'blocked', 'issue',
181
+ 'problem', 'error', 'unable', 'not working',
182
+ ]
183
+ # Accept either a topic + problem wording, or multiple distinctive topic
184
+ # terms such as "dashboard PDF exports".
185
+ return ((has_any(text, topic_terms) and has_any(text, problem_terms))
186
+ or count_matches(text, topic_terms) >= 2)
187
+
188
+
189
+ def origin_is_email(case):
190
+ return normalize_text(case.get('origin')) in {'email', 'e mail'}
191
+
192
+
193
+ def priority_is_high(case):
194
+ return normalize_text(case.get('priority')) == normalize_text(EXPECTED_CASE_PRIORITY)
195
+
196
+
197
+ def status_is_working(case):
198
+ return normalize_text(case.get('status')) == normalize_text(EXPECTED_CASE_STATUS)
199
+
200
+
201
+ def case_customer_score(case):
202
+ text = case_observable_text(case)
203
+ score = 0
204
+ if case.get('accountId') == BRIGHTWAVE_ACCOUNT:
205
+ score += 4
206
+ elif has_any(text, [CUSTOMER_ACCOUNT_NAME, 'brightwave.io']):
207
+ score += 2
208
+ if case.get('contactId') == DANA_CONTACT:
209
+ score += 3
210
+ elif has_any(text, [CUSTOMER_NAME, CUSTOMER_EMAIL]):
211
+ score += 2
212
+ return score
213
+
214
+
215
+ def case_quality_score(case):
216
+ text = case_observable_text(case)
217
+ owner_text = normalize_text(
218
+ case.get('ownerId'),
219
+ case.get('ownerName'),
220
+ case.get('ownerEmail'),
221
+ case.get('assignedTo'),
222
+ case.get('assignee'),
223
+ )
224
+ score = case_customer_score(case)
225
+ score += int(origin_is_email(case))
226
+ score += int(priority_is_high(case))
227
+ score += int(status_is_working(case))
228
+ score += int(matches_id_or_text(owner_text, CSM_USER, CSM_NAME, CSM_EMAIL))
229
+ score += int(text_reflects_export_issue(text))
230
+ return score
231
+
232
+
233
+ def email_text(email):
234
+ if not email:
235
+ return ''
236
+ return normalize_text(email.get('subject'), email.get('body'), email.get('snippet'))
237
+
238
+
239
+ def reply_case_reference_flags(text, target_case):
240
+ if not target_case:
241
+ return False, False
242
+ case_no = normalize_text(target_case.get('caseNumber')) if target_case else ''
243
+ ref_by_number = bool(case_no) and case_no in normalize_text(text)
244
+ case_word = has_any(text, ['case', 'ticket', 'support request', 'crm case', 'salesforce case'])
245
+ logged_word = has_any(text, [
246
+ 'opened', 'created', 'logged', 'filed', 'raised', 'recorded',
247
+ 'submitted', 'set up',
248
+ ])
249
+ customer_or_issue = (
250
+ has_any(text, [CUSTOMER_ACCOUNT_NAME, CUSTOMER_NAME, CUSTOMER_EMAIL])
251
+ or text_reflects_export_issue(text)
252
+ )
253
+ ref_by_semantics = case_word and (logged_word or customer_or_issue)
254
+ return ref_by_number, ref_by_semantics
255
+
256
+
257
+ def reply_ack_flags(text):
258
+ ack_recv = has_any(text, [
259
+ 'received', 'receive', 'got your', 'got it', 'thanks for',
260
+ 'thank you for', 'flagging', 'reaching out', 'reported',
261
+ 'message', 'email', 'note', 'aware', 'acknowledge', 'acknowledged',
262
+ '已收到', '收到', '感谢',
263
+ ])
264
+ ack_work = has_any(text, [
265
+ 'working on', 'work on', 'looking into', 'look into', 'investigat',
266
+ 'on it', 'being worked', 'actively', 'prioriti', 'team is',
267
+ 'team has', 'escalated', 'assigned', 'routed', 'handling',
268
+ 'reviewing', 'digging', 'high priority', 'will update',
269
+ 'keep you updated', 'follow up', '处理中', '正在处理', '跟进', '优先',
270
+ ])
271
+ return ack_recv, ack_work
272
+
273
+
274
+ def reply_quality_score(email, target_case):
275
+ text = email_text(email)
276
+ ref_by_number, ref_by_semantics = reply_case_reference_flags(text, target_case)
277
+ ack_recv, ack_work = reply_ack_flags(text)
278
+ return sum([ref_by_number, ref_by_semantics, ack_recv, ack_work])
279
+
280
+
281
+ def verify_task():
282
+ total_score = 0.0
283
+
284
+ # ----- Identify the task-introduced NEW Salesforce case -----
285
+ init_cases = sf_initial.get('cases', []) or []
286
+ cur_cases = sf_current.get('cases', []) or []
287
+ init_case_ids = {c.get('caseId') for c in init_cases}
288
+ new_cases = [c for c in cur_cases if c.get('caseId') not in init_case_ids]
289
+
290
+ # Prefer the new case that most clearly corresponds to Dana/Brightwave's
291
+ # inbound email. This avoids over-penalizing runs that create multiple cases.
292
+ customer_cases = [c for c in new_cases if case_customer_score(c) > 0]
293
+ target_case = max(customer_cases, key=case_quality_score) if customer_cases else None
294
+
295
+ # Component 1: a genuinely new case linked to the right account AND contact,
296
+ # origin 'Email'. (0.20)
297
+ try:
298
+ if target_case is not None:
299
+ acct_ok = target_case.get('accountId') == BRIGHTWAVE_ACCOUNT
300
+ contact_ok = target_case.get('contactId') == DANA_CONTACT
301
+ origin_ok = origin_is_email(target_case)
302
+ if acct_ok and contact_ok and origin_ok:
303
+ print('PASS: C1 — new case linked to Brightwave (account-6) + '
304
+ f'Dana (contact-7), origin Email (0.20) [case {target_case.get("caseNumber")}]')
305
+ total_score += 0.20
306
+ else:
307
+ print(f'FAIL: C1 — new case found but mismatch: account={target_case.get("accountId")} '
308
+ f'(want {BRIGHTWAVE_ACCOUNT}), contact={target_case.get("contactId")} '
309
+ f'(want {DANA_CONTACT}), origin={target_case.get("origin")} (want Email)')
310
+ else:
311
+ print(f'FAIL: C1 — no NEW case linked to {BRIGHTWAVE_ACCOUNT} '
312
+ f'(new cases: {[c.get("caseId") for c in new_cases]})')
313
+ except Exception as e:
314
+ print(f'ERROR: C1 — {e}')
315
+
316
+ # Component 2: new case priority High AND status Working (0.15)
317
+ try:
318
+ if target_case is not None:
319
+ prio_ok = priority_is_high(target_case)
320
+ status_ok = status_is_working(target_case)
321
+ if prio_ok and status_ok:
322
+ print('PASS: C2 — new case priority High AND status Working (0.15)')
323
+ total_score += 0.15
324
+ else:
325
+ print(f'FAIL: C2 — priority={target_case.get("priority")} '
326
+ f'(want {EXPECTED_CASE_PRIORITY}), '
327
+ f'status={target_case.get("status")} (want {EXPECTED_CASE_STATUS})')
328
+ else:
329
+ print('FAIL: C2 — no target case to evaluate')
330
+ except Exception as e:
331
+ print(f'ERROR: C2 — {e}')
332
+
333
+ # Component 3: new case owned by the account CSM Priya Nair (user-2) (0.15)
334
+ try:
335
+ if target_case is not None:
336
+ owner_text = normalize_text(
337
+ target_case.get('ownerId'),
338
+ target_case.get('ownerName'),
339
+ target_case.get('ownerEmail'),
340
+ target_case.get('assignedTo'),
341
+ target_case.get('assignee'),
342
+ )
343
+ if matches_id_or_text(owner_text, CSM_USER, CSM_NAME, CSM_EMAIL):
344
+ print('PASS: C3 — new case owned by Priya Nair / user-2 (0.15)')
345
+ total_score += 0.15
346
+ else:
347
+ print(f'FAIL: C3 — owner={owner_text!r} '
348
+ f'(want {CSM_USER} / {CSM_NAME} / {CSM_EMAIL})')
349
+ else:
350
+ print('FAIL: C3 — no target case to evaluate')
351
+ except Exception as e:
352
+ print(f'ERROR: C3 — {e}')
353
+
354
+ # Component 4: new case observable text reflects the dashboard/PDF export issue (0.10)
355
+ # Check subject + description so a concise subject with detail in description
356
+ # is accepted; matching is case/punctuation insensitive and synonym tolerant.
357
+ try:
358
+ if target_case is not None:
359
+ case_text = case_observable_text(target_case)
360
+ if text_reflects_export_issue(case_text):
361
+ print(f'PASS: C4 — case text reflects export issue (0.10) '
362
+ f'[subject: {target_case.get("subject")!r}]')
363
+ total_score += 0.10
364
+ else:
365
+ print('FAIL: C4 — case subject/description does not reflect '
366
+ f'export issue: subject={target_case.get("subject")!r}, '
367
+ f'description={target_case.get("description")!r}')
368
+ else:
369
+ print('FAIL: C4 — no target case to evaluate')
370
+ except Exception as e:
371
+ print(f'ERROR: C4 — {e}')
372
+
373
+ # ----- Identify the task-introduced sent reply in Gmail -----
374
+ init_emails = gm_initial.get('emails', []) or []
375
+ cur_emails = gm_current.get('emails', []) or []
376
+ init_email_ids = {e.get('id') for e in init_emails}
377
+
378
+ def addressed_to(email, addr):
379
+ for r in (email.get('to') or []):
380
+ if normalize_text(r.get('email')) == normalize_text(addr):
381
+ return True
382
+ return False
383
+
384
+ new_sent = [
385
+ e for e in cur_emails
386
+ if e.get('id') not in init_email_ids
387
+ and str(e.get('folder', '')).strip().lower() == 'sent'
388
+ ]
389
+ customer_replies = [e for e in new_sent if addressed_to(e, CUSTOMER_EMAIL)]
390
+ reply_email = (max(customer_replies, key=lambda e: reply_quality_score(e, target_case))
391
+ if customer_replies else None)
392
+
393
+ # Component 5: a NEW sent email addressed to ops@brightwave.io (0.15)
394
+ try:
395
+ if reply_email is not None:
396
+ print('PASS: C5 — new sent email addressed to ops@brightwave.io (0.15) '
397
+ f'[id {reply_email.get("id")}]')
398
+ total_score += 0.15
399
+ else:
400
+ print('FAIL: C5 — no NEW sent email addressed to ops@brightwave.io '
401
+ f'(new sent ids: {[e.get("id") for e in new_sent]})')
402
+ except Exception as e:
403
+ print(f'ERROR: C5 — {e}')
404
+
405
+ # Component 6: original inbound email_esc now marked read (0.10)
406
+ # Anchored to a change: read goes false (initial) -> true (golden).
407
+ try:
408
+ cur_esc = next((e for e in cur_emails if e.get('id') == INBOUND_EMAIL_ID), None)
409
+ init_esc = next((e for e in init_emails if e.get('id') == INBOUND_EMAIL_ID), None)
410
+ was_unread = (init_esc is not None) and (init_esc.get('read') is False)
411
+ now_read = (cur_esc is not None) and (cur_esc.get('read') is True)
412
+ if was_unread and now_read:
413
+ print('PASS: C6 — email_esc marked read (false -> true) (0.10)')
414
+ total_score += 0.10
415
+ else:
416
+ print(f'FAIL: C6 — email_esc read state: initial={init_esc.get("read") if init_esc else "missing"}, '
417
+ f'current={cur_esc.get("read") if cur_esc else "missing"}')
418
+ except Exception as e:
419
+ print(f'ERROR: C6 — {e}')
420
+
421
+ # Component 7 (0.15): the sent reply both references the logged case AND
422
+ # acknowledges the export issue is being handled. Split into two 0.075 halves
423
+ # for partial credit. Both are programmatic:
424
+ # (a) case reference — prefer the deterministic case number, but accept
425
+ # common case/ticket wording tied to the customer or issue.
426
+ # (b) acknowledgement — synonym-tolerant receipt + in-progress wording.
427
+ try:
428
+ if reply_email is not None:
429
+ text = email_text(reply_email)
430
+ # (a) case reference. Prefer the deterministic case number, but
431
+ # also accept normal customer-facing wording such as "opened a
432
+ # support ticket/case" plus customer or issue context.
433
+ case_no = normalize_text(target_case.get('caseNumber')) if target_case else ''
434
+ ref_by_number, ref_by_semantics = reply_case_reference_flags(text, target_case)
435
+ ref_ok = ref_by_number or ref_by_semantics
436
+ if ref_ok:
437
+ print(f'PASS: C7a — reply references logged case (0.075) '
438
+ f'[by_number={ref_by_number}, by_semantics={ref_by_semantics}]')
439
+ total_score += 0.075
440
+ else:
441
+ print(f'FAIL: C7a — reply does not reference the logged case (case# {case_no!r})')
442
+ # (b) acknowledgement of receipt / work in progress
443
+ ack_recv, ack_work = reply_ack_flags(text)
444
+ if ack_recv and ack_work:
445
+ print('PASS: C7b — reply acknowledges receipt AND work in progress (0.075)')
446
+ total_score += 0.075
447
+ else:
448
+ print(f'FAIL: C7b — acknowledgement incomplete '
449
+ f'(received={ack_recv}, working={ack_work})')
450
+ else:
451
+ print('FAIL: C7 — no sent reply to evaluate')
452
+ except Exception as e:
453
+ print(f'ERROR: C7 — {e}')
454
+
455
+ final_score = round(min(total_score, 1.0), 4)
456
+ print(f'\nScore: {total_score}/1.0')
457
+ print(f'REWARD: {final_score}')
458
+ return final_score
459
+
460
+
461
+ verify_task()
csops_email_to_crm_case_001/reward_label.json ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/csops_email_to_crm_case_002/reward.py",
3
+ "api_url": "http://28.7.184.184:8000/v1/chat/completions",
4
+ "model": "Kimi-K2.6",
5
+ "max_code_chars": 100000,
6
+ "created_at": "2026-07-03 20:24:00",
7
+ "label": {
8
+ "task_id": "csops_email_to_crm_case_001",
9
+ "domain": "mock_websites",
10
+ "summary": "验证是否将紧急客户邮件记录为 Salesforce CRM 支持案例并路由给账户 CSM 且标记高优先级,同时在 Gmail 中向客户发送包含案例引用和问题确认的处理回复。",
11
+ "is_placeholder": false,
12
+ "data_sources": [
13
+ "/tmp/task_web_sid",
14
+ "salesforce_mock",
15
+ "gmail_mock"
16
+ ],
17
+ "scoring_components": [
18
+ {
19
+ "name": "C1",
20
+ "weight": 0.2,
21
+ "description": "验证新创建的 Salesforce Case 关联到正确的账户和联系人且来源为 Email",
22
+ "check_logic": "对比 sf_initial['cases'] 与 sf_current['cases'] 找出 caseId 不在初始集合中的 new_cases,筛选 case_customer_score > 0 的 customer_cases,取 case_quality_score 最大者作为 target_case;检查 target_case.accountId == 'account-6'、target_case.contactId == 'contact-7' 且 origin_is_email(target_case) 为真",
23
+ "pass_condition": "存在新 case,其 accountId 为 account-6,contactId 为 contact-7,origin 为 Email"
24
+ },
25
+ {
26
+ "name": "C2",
27
+ "weight": 0.15,
28
+ "description": "验证新 case 的优先级为 High 且状态为 Working",
29
+ "check_logic": "在 target_case 存在时,检查 priority_is_high(target_case)(归一化后等于 'high')和 status_is_working(target_case)(归一化后等于 'working')均为真",
30
+ "pass_condition": "priority 为 High 且 status 为 Working"
31
+ },
32
+ {
33
+ "name": "C3",
34
+ "weight": 0.15,
35
+ "description": "验证新 case 的所有者是账户 CSM Priya Nair (user-2)",
36
+ "check_logic": "在 target_case 存在时,归一化 ownerId/ownerName/ownerEmail/assignedTo/assignee 文本,通过 matches_id_or_text 检查是否匹配 CSM_USER ('user-2')、CSM_NAME ('Priya Nair') 或 CSM_EMAIL ('priya.nair@acme-support.com')",
37
+ "pass_condition": "所有者字段匹配 user-2 或其姓名/邮箱"
38
+ },
39
+ {
40
+ "name": "C4",
41
+ "weight": 0.1,
42
+ "description": "验证新 case 的可观测文本反映 dashboard PDF 导出中断问题",
43
+ "check_logic": "在 target_case 存在时,提取 case_observable_text(subject/description/type/origin/accountName/contactName/contactEmail),通过 text_reflects_export_issue 检查是否同时包含主题词(dashboard/pdf/export 等)和问题词(broken/outage/failure 等),或至少包含两个主题词",
44
+ "pass_condition": "case 文本包含 dashboard/pdf/export 等主题词以及 broken/outage/failure 等问题词"
45
+ },
46
+ {
47
+ "name": "C5",
48
+ "weight": 0.15,
49
+ "description": "验证 Gmail 中存在新的 sent 文件夹邮件发送给 ops@brightwave.io",
50
+ "check_logic": "对比 gm_initial['emails'] 与 gm_current['emails'],筛选 id 不在初始集合中、folder 为 'sent' 且 addressed_to(e, 'ops@brightwave.io') 为真的邮件,取 reply_quality_score 最大者作为 reply_email;检查 reply_email 非 None",
51
+ "pass_condition": "存在新的 sent 邮件且收件人包含 ops@brightwave.io"
52
+ },
53
+ {
54
+ "name": "C6",
55
+ "weight": 0.1,
56
+ "description": "验证原始入站邮件 email_esc 已从 unread 变为 read",
57
+ "check_logic": "在 initial_emails 和 current_emails 中查找 id 为 'email_esc' 的邮件,确认 initial 中 read 为 False 且 current 中 read 为 True",
58
+ "pass_condition": "email_esc 的 read 状态从 false 变为 true"
59
+ },
60
+ {
61
+ "name": "C7a",
62
+ "weight": 0.075,
63
+ "description": "验证回复邮件引用了已记录的 case",
64
+ "check_logic": "在 reply_email 存在时,提取 email_text,通过 reply_case_reference_flags 检查 ref_by_number(包含目标 case 的 caseNumber)或 ref_by_semantics(包含 case/ticket 等词且与 logged/created 等词及客户/问题上下文同时出现)为真",
65
+ "pass_condition": "回复文本通过编号或语义引用已创建的 case"
66
+ },
67
+ {
68
+ "name": "C7b",
69
+ "weight": 0.075,
70
+ "description": "验证回复邮件确认收到问题并正在处理",
71
+ "check_logic": "在 reply_email 存在时,通过 reply_ack_flags 检查 ack_recv(received/thanks for 等收到词)和 ack_work(working on/looking into 等处理词)均为真",
72
+ "pass_condition": "ack_recv 和 ack_work 同时为真"
73
+ }
74
+ ],
75
+ "total_max_score": 1.0,
76
+ "score_aggregation": "各组件分数累加求和,最终通过 round(min(total_score, 1.0), 4) 钳制到上限 1.0 并四舍五入保留四位小数",
77
+ "failure_modes": [
78
+ "无法从 /tmp/task_web_sid 读�� sid 或 sid 为空:打印 CRITICAL 和 REWARD: 0.0 后 sys.exit(0)",
79
+ "无法从 salesforce_mock 或 gmail_mock 获取状态:打印 CRITICAL 和 REWARD: 0.0 后 sys.exit(0)",
80
+ "sf_current 或 gm_current 缺失:打印 CRITICAL 和 REWARD: 0.0 后 sys.exit(0)",
81
+ "未找到关联 Brightwave/Dana 的新 case:C1-C4 失败,对应分数无法获得",
82
+ "未找到新的 sent 邮件:C5、C7 失败,对应分数无法获得",
83
+ "email_esc 未从 unread 变为 read:C6 失败",
84
+ "回复未引用 case 或未确认处理:C7a/C7b 失败或仅部分通过"
85
+ ],
86
+ "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,若失败则直接返回 0.0。随后通过 HTTP GET 请求从 salesforce_mock 和 gmail_mock 分别拉取 initial_state 与 current_state,若拉取失败或 current_state 缺失也直接返回 0.0。评分阶段分为 Salesforce 和 Gmail 两条线:1) 在 Salesforce 侧,对比初始与当前的 cases 列表找出新创建的 case,通过 case_customer_score 与 case_quality_score 选出最匹配 Dana Reeves / Brightwave Media 的目标 case,然后依次检查 C1(关联正确账户、联系人、来源 Email)、C2(优先级 High 且状态 Working)、C3(所有者为 CSM Priya Nair / user-2)、C4(主题/描述反映 dashboard PDF export 问题);2) 在 Gmail 侧,对比初始与当前的 emails 列表,筛选出 folder 为 sent 且收件人为 ops@brightwave.io 的新邮件,通过 reply_quality_score 选出最佳回复邮件,然后依次检查 C5(存在新 sent 邮件)、C6(原始邮件 email_esc 从 unread 变为 read)、C7a(回复引用已记录 case,支持 caseNumber 或语义匹配)、C7b(回复同时确认收到并正在处理)。各组件得分累加后,使用 min(total_score, 1.0) 钳制上限并四舍五入到四位小数作为最终分数。",
87
+ "confidence": 1.0
88
+ },
89
+ "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码并提取所需信息:\n\n1. **task_id**: 从 docstring 中可以看到 \"Task ID: csops_email_to_crm_case_002\"\n2. **domain**: 从 docstring 中可以看到 \"Domain: mock_websites\"\n3. **summary**: 一句话概括:验证是否将紧急客户邮件记录为 CRM 支持案例,路由给账户的 CSM 并标记为高优先级,同时向客户发送确认回复。\n4. **is_placeholder**: false,因为脚本有详细的评分逻辑,不是占位脚本。\n5. **data_sources**: \n - /tmp/task_web_sid (读取 sid)\n - salesforce_mock (cua-gym-salesforce) 在 28.7.186.212:8175\n - gmail_mock (cua-gym-gmail) 在 28.7.186.212:8138\n6. **scoring_components**: \n - C1 (0.20): 新案例链接到 Brightwave Media (account-6) 和 Dana Reeves (contact-7),来源为 Email\n - C2 (0.15): 新案例优先级为 High 且状态为 Working\n - C3 (0.15): 新案例所有者是账户 CSM Priya Nair (user-2)\n - C4 (0.10): 新案例主题反映 dashboard PDF 导出中断问题\n - C5 (0.15): 新的 sent 文件夹邮件发送给 ops@brightwave.io\n - C6 (0.10): 原始入站邮件 email_esc 已标记为已读\n - C7 (0.15): 发送的回复 (a) 引用记录的案例编号 AND (b) 确认收到/正在处理导出问题。分为两个 0.075 的部分。\n\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 各组件分数相加,最后用 round(min(total_score, 1.0), 4) 钳制到上限 1.0。\n9. **failure_modes**: \n - 无法从 /tmp/task_web_sid 读取 sid -> 打印 REWARD: 0.0 并退出\n - 无法从 mock 服务获取状态 -> 打印 REWARD: 0.0 并退出\n - current_state 缺失 -> 打印 REWARD: 0.0 并退出\n - 各组件失败会打印 FAIL 但不提前退出(除了上面的 critical 错误)\n \n10. **scoring_logic_explanation**: 详细解释执行顺序:\n - 读取 /tmp/task_web_sid 获取会话 ID\n - 通过 HTTP GET 请求从 salesforce_mock 和 gmail_mock 获取初始状态和当前状态\n - 在 Salesforce 中找出新创建的 case(对比 initial 和 current)\n - 通过 case_customer_score 和 case_quality_score 选择最匹配的目标 case\n - 逐项检查 C1-C4(账户/联系人/来源、优先级/状态、所有者、主题内容)\n - 在 Gmail 中找出新的 sent 邮件(对比 initial 和 current,筛选 sent 文件夹且收件人为 ops@brightwave.io)\n - 通过 reply_quality_score 选择最佳回复邮件\n - 检查 C5(新邮件)、C6(原邮件标记已读)、C7(回复内容:引用案例 + 确认处理)\n - 累加各组件得分,钳制到 1.0 并四舍五入到 4 位小数\n\n11. **confidence**: 1.0,因为代码非常清晰完整。\n\n现在构建 JSON。注意:\n- 所有字符串 value 使用中文\n- task_id、domain、字段名、代码标识符保留原样\n- 不要输出 Markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 不要额外解释\n\n让我确保每个字段都正确:\n\ntask_id: \"csops_email_to_crm_case_002\"\ndomain: \"mock_websites\"\nsummary: \"验证是否将紧急客户邮件记录为 Salesforce CRM 支持案例并路由给账户 CSM 且标记高优先级,同时在 Gmail 中向客户发送包含案例引用和问题确认的处理回复。\"\nis_placeholder: false\ndata_sources: [\"/tmp/task_web_sid\", \"salesforce_mock\", \"gmail_mock\"]\n\nscoring_components:\n- name: \"C1\", weight: 0.20, description: \"验证新创建的 Salesforce Case 关联到正确的账户和联系人且来源为 Email\", check_logic: \"对比 initial_state 和 current_state 的 cases 列表找出新 case,检查 target_case.accountId == 'account-6' 且 target_case.contactId == 'contact-7' 且 origin_is_email(target_case) 为真\", pass_condition: \"存在新 case,其 accountId 为 account-6,contactId 为 contact-7,origin 为 Email\"\n- name: \"C2\", weight: 0.15, description: \"验证新 case 的优先级为 High 且状态为 Working\", check_logic: \"检查 target_case.priority 归一化后等于 'high' 且 target_case.status 归一化后等于 'working'\", pass_condition: \"priority 为 High 且 status 为 Working\"\n- name: \"C3\", weight: 0.15, description: \"验证新 case 的所有者是账户 CSM Priya Nair (user-2)\", check_logic: \"归一化 ownerId/ownerName/ownerEmail/assignedTo/assignee 字段,检查是否匹配 user-2、Priya Nair 或 priya.nair@acme-support.com\", pass_condition: \"所有者字段匹配 CSM_USER (user-2) 或其姓名/邮箱\"\n- name: \"C4\", weight: 0.10, description: \"验证新 case 的可观测文本反映 dashboard PDF 导出中断问题\", check_logic: \"对 case 的 subject/description/type/origin/accountName/contactName/contactEmail 进行归一化,使用 text_reflects_export_issue 检查是否同时包含主题词(dashboard/pdf/export 等)和问题词(broken/outage/failure 等),或至少两个主题词\", pass_condition: \"case 文本包含 dashboard/pdf/export 等主题词以及 broken/outage/failure 等问题词\"\n- name: \"C5\", weight: 0.15, description: \"验证 Gmail 中存在新的 sent 文件夹邮件发送给 ops@brightwave.io\", check_logic: \"对比 initial 和 current 的 emails,筛选 id 不在 initial 中、folder 为 'sent' 且 to 列表包含 ops@brightwave.io 的邮件\", pass_condition: \"存在新的 sent 邮件且收件人包含 ops@brightwave.io\"\n- name: \"C6\", weight: 0.10, description: \"验证原始入站邮件 email_esc 已从 unread 变为 read\", check_logic: \"检查 initial_emails 中 id 为 email_esc 的邮件 read 为 False,且 current_emails 中同一 id 的邮件 read 为 True\", pass_condition: \"email_esc 的 read 状态从 false 变为 true\"\n- name: \"C7a\", weight: 0.075, description: \"验证回复邮件引用了已记录的 case\", check_logic: \"检查回复文本是否包含目标 case 的 caseNumber(ref_by_number),或包含 case/ticket 等词汇且与 logged/created 等词及客户/问题上下文同时出现(ref_by_semantics)\", pass_condition: \"回复文本通过编号或语义引用已创建的 case\"\n- name: \"C7b\", weight: 0.075, description: \"验证回复邮件确认收到问题并正在处理\", check_logic: \"使用 reply_ack_flags 检查文本是否包含 received/thanks for 等收到确认词(ack_recv),以及 working on/looking into 等处理中词汇(ack_work)\", pass_condition: \"ack_recv 和 ack_work 同时为真\"\n\nscore_aggregation: \"各组件分数累加求和,最终通过 round(min(total_score, 1.0), 4) 钳制到上限 1.0 并四舍五入保留四位小数\"\n\nfailure_modes: [\n \"无法从 /tmp/task_web_sid 读取 sid 或 sid 为空:打印 CRITICAL 和 REWARD: 0.0 后 sys.exit(0)\",\n \"无法从 salesforce_mock 或 gmail_mock 获取状态:打印 CRITICAL 和 REWARD: 0.0 后 sys.exit(0)\",\n \"sf_current 或 gm_current 缺失:打印 CRITICAL 和 REWARD: 0.0 后 sys.exit(0)\",\n \"未找到关联 Brightwave/Dana 的新 case:C1-C4 失败,对应分数无法获得\",\n \"未找到新的 sent 邮件:C5、C7 失败,对应分数无法获得\",\n \"email_esc 未从 unread 变为 read:C6 失败\",\n \"回复未引用 case 或未确认处理:C7a/C7b 失败或仅部分通过\"\n]\n\nscoring_logic_explanation: 需要详细中文解释,按执行顺序。\n\nconfidence: 1.0\n\n检查 JSON 格式是否合法。确保没有 trailing commas。\n\n所有 value 应该是中文,但代码中的标识符保留。\n\n让我再仔细检查一下 C7 的描述。代码中 C7 是 0.15,拆分为 C7a 0.075 和 C7b 0.075。我应该把它们作为两个独立的组件,还是作为一个组件?JSON 格式要求每个组件有 weight,如果拆分的话,两个都是 0.075 比较准确。因为 docstring 说 \"Split 0.075 / 0.075 for partial credit\",而且代码中也是分别加 0.075。所以拆成两个组件更好。\n\n再检查一下 data_sources。代码中明确使用了 /tmp/task_web_sid、SF_URL (salesforce_mock)、GM_URL (gmail_mock)。所以 data_sources 应该包含这些。\n\n再检查一下 summary。需要一句话概括。\n\n再检查一下 is_placeholder。false。\n\n再检查一下 pass_condition 和 check_logic 是否准确引用了代码逻辑。\n\nC1 check_logic: \"从 sf_initial['cases'] 和 sf_current['cases'] 中筛选出 caseId 不在 initial 中的 new_cases,再筛选 case_customer_score > 0 的 customer_cases,取 case_quality_score 最大者作为 target_case;检查 target_case.accountId == 'account-6'、target_case.contactId == 'contact-7' 且 origin_is_email(target_case) 为真\"\n\nC2 check_logic: \"在 target_case 存在时,检查 priority_is_high(target_case) 和 status_is_working(target_case) 均为真\"\n\nC3 check_logic: \"在 target_case 存在时,归一化 ownerId/ownerName/ownerEmail/assignedTo/assignee 文本,通过 matches_id_or_text 检查是否匹配 CSM_USER ('user-2')、CSM_NAME ('Priya Nair') 或 CSM_EMAIL ('priya.nair@acme-support.com')\"\n\nC4 check_logic: \"在 target_case 存在时,提取 case_observable_text(subject/description/type/origin/accountName/contactName/contactEmail),通过 text_reflects_export_issue 检查是否包含 dashboard/pdf/export 等主题词与 broken/outage/failure 等问题词,或至少两个主题词\"\n\nC5 check_logic: \"从 gm_initial['emails'] 和 gm_current['emails'] 中筛选 id 不在 initial 中、folder 为 'sent' 且 addressed_to(e, 'ops@brightwave.io') 为真的邮件,取 reply_quality_score 最大者作为 reply_email;检查 reply_email 非 None\"\n\nC6 check_logic: \"在 initial_emails 和 current_emails 中查找 id 为 'email_esc' 的邮件,确认 initial 中 read 为 False 且 current 中 read 为 True\"\n\nC7a check_logic: \"在 reply_email 存在时,提取 email_text,通过 reply_case_reference_flags 检查 ref_by_number(包含 caseNumber)或 ref_by_semantics(包含 case/ticket 等词且与 logged/created 等词及客户/问题上下文同时出现)为真\"\n\nC7b check_logic: \"在 reply_email 存在时,通过 reply_ack_flags 检查 ack_recv(received/thanks for 等收到词)和 ack_work(working on/looking into 等处理词)均为真\"\n\n看起来都准确。\n\n现在组织 JSON。 </think> {\"task_id\":\"csops_email_to_crm_case_002\",\"domain\":\"mock_websites\",\"summary\":\"验证是否将紧急客户邮件记录为 Salesforce CRM 支持案例并路由给账户 CSM 且标记高优先级,同时在 Gmail 中向客户发送包含案例引用和问题确认的处理回复。\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"salesforce_mock\",\"gmail_mock\"],\"scoring_components\":[{\"name\":\"C1\",\"weight\":0.2,\"description\":\"验证新创建的 Salesforce Case 关联到正确的账户和联系人且来源为 Email\",\"check_logic\":\"对比 sf_initial['cases'] 与 sf_current['cases'] 找出 caseId 不在初始集合中的 new_cases,筛选 case_customer_score > 0 的 customer_cases,取 case_quality_score 最大者作为 target_case;检查 target_case.accountId == 'account-6'、target_case.contactId == 'contact-7' 且 origin_is_email(target_case) 为真\",\"pass_condition\":\"存在新 case,其 accountId 为 account-6,contactId 为 contact-7,origin 为 Email\"},{\"name\":\"C2\",\"weight\":0.15,\"description\":\"验证新 case 的优先级为 High 且状态为 Working\",\"check_logic\":\"在 target_case 存在时,检查 priority_is_high(target_case)(归一化后等于 'high')和 status_is_working(target_case)(归一化后等于 'working')均为真\",\"pass_condition\":\"priority 为 High 且 status 为 Working\"},{\"name\":\"C3\",\"weight\":0.15,\"description\":\"验证新 case 的所有者是账户 CSM Priya Nair (user-2)\",\"check_logic\":\"在 target_case 存在时,归一化 ownerId/ownerName/ownerEmail/assignedTo/assignee 文本,通过 matches_id_or_text 检查是否匹配 CSM_USER ('user-2')、CSM_NAME ('Priya Nair') 或 CSM_EMAIL ('priya.nair@acme-support.com')\",\"pass_condition\":\"所有者字段匹配 user-2 或其姓名/邮箱\"},{\"name\":\"C4\",\"weight\":0.1,\"description\":\"验证新 case 的可观测文本反映 dashboard PDF 导出中断问题\",\"check_logic\":\"在 target_case 存在时,提取 case_observable_text(subject/description/type/origin/accountName/contactName/contactEmail),通过 text_reflects_export_issue 检查是否同时包含主题词(dashboard/pdf/export 等)和问题词(broken/outage/failure 等),或至少包含两个主题词\",\"pass_condition\":\"case 文本包含 dashboard/pdf/export 等主题词以及 broken/outage/failure 等问题词\"},{\"name\":\"C5\",\"weight\":0.15,\"description\":\"验证 Gmail 中存在新的 sent 文件夹邮件发送给 ops@brightwave.io\",\"check_logic\":\"对比 gm_initial['emails'] 与 gm_current['emails'],筛选 id 不在初始集合中、folder 为 'sent' 且 addressed_to(e, 'ops@brightwave.io') 为真的邮件,取 reply_quality_score 最大者作为 reply_email;检查 reply_email 非 None\",\"pass_condition\":\"存在新的 sent 邮件且收件人包含 ops@brightwave.io\"},{\"name\":\"C6\",\"weight\":0.1,\"description\":\"验证原始入站邮件 email_esc 已从 unread 变为 read\",\"check_logic\":\"在 initial_emails 和 current_emails 中查找 id 为 'email_esc' 的邮件,确认 initial 中 read 为 False 且 current 中 read 为 True\",\"pass_condition\":\"email_esc 的 read 状态从 false 变为 true\"},{\"name\":\"C7a\",\"weight\":0.075,\"description\":\"验证回复邮件引用了已记录的 case\",\"check_logic\":\"在 reply_email 存在时,提取 email_text,通过 reply_case_reference_flags 检查 ref_by_number(包含目标 case 的 caseNumber)或 ref_by_semantics(包含 case/ticket 等词且与 logged/created 等词及客户/问题上下文同时出现)为真\",\"pass_condition\":\"回复文本通过编号或语义引用已创建的 case\"},{\"name\":\"C7b\",\"weight\":0.075,\"description\":\"验证回复邮件确认收到问题并正在处理\",\"check_logic\":\"在 reply_email 存在时,通过 reply_ack_flags 检查 ack_recv(received/thanks for 等收到词)和 ack_work(working on/looking into 等处理词)均为真\",\"pass_condition\":\"ack_recv 和 ack_work 同时为真\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数累加求和,最终通过 round(min(total_score, 1.0), 4) 钳制到上限 1.0 并四舍五入保留四位小数\",\"failure_modes\":[\"无法从 /tmp/task_web_sid 读取 sid 或 sid 为空:打印 CRITICAL 和 REWARD: 0.0 后 sys.exit(0)\",\"无法从 salesforce_mock 或 gmail_mock 获取状态:打印 CRITICAL 和 REWARD: 0.0 后 sys.exit(0)\",\"sf_current 或 gm_current 缺失:打印 CRITICAL 和 REWARD: 0.0 后 sys.exit(0)\",\"未找到关联 Brightwave/Dana 的新 case:C1-C4 失败,对应分数无法获得\",\"未找到新的 sent 邮件:C5、C7 失败,对应分数无法获得\",\"email_esc 未从 unread 变为 read:C6 失败\",\"回复未引用 case 或未确认处理:C7a/C7b 失败或仅部分通过\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,若失败则直接返回 0.0。随后通过 HTTP GET 请求从 salesforce_mock 和 gmail_mock 分别拉取 initial_state 与 current_state,若拉取失败或 current_state 缺失也直接返回 0.0。评分阶段分为 Salesforce 和 Gmail 两条线:1) 在 Salesforce 侧,对比初始与当前的 cases 列表找出新创建的 case,通过 case_customer_score 与 case_quality_score 选出最匹配 Dana Reeves / Brightwave Media 的目标 case,然后依次检查 C1(关联正确账户、联系人、来源 Email)、C2(优先级 High 且状态 Working)、C3(所有者为 CSM Priya Nair / user-2)、C4(主题/描述反映 dashboard PDF export 问题);2) 在 Gmail 侧,对比初始与当前的 emails 列表,筛选出 folder 为 sent 且收件人为 ops@brightwave.io 的新邮件,通过 reply_quality_score 选出最佳回复邮件,然后依次检查 C5(存在新 sent 邮件)、C6(原始邮件 email_esc 从 unread 变为 read)、C7a(回复引用已记录 case,支持 caseNumber 或语义匹配)、C7b(回复同时确认收到并正在处理)。各组件得分累加后,使用 min(total_score, 1.0) 钳制上限并四舍五入到四位小数作为最终分数。\",\"confidence\":1.0}"
90
+ }
csops_sla_queue_triage_003/_cua_gym_vm_bridge.sh ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # CUA-Gym VM-side network fix (direct-IP mock access).
3
+ #
4
+ # Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by
5
+ # their real IDC address (http://28.7.184.198:81xx) instead of the old
6
+ # localhost:9000-9097 socat bridge, so the VM only needs two fixes:
7
+ #
8
+ # 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's
9
+ # cluster DNS, which is unreachable from QEMU SLIRP NAT
10
+ # ("Temporary failure in name resolution").
11
+ # 2. The mock host excluded from the woa http proxy — otherwise the VM's
12
+ # Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403
13
+ # from the proxy when hitting 28.7.184.198:81xx. (The old socat path never
14
+ # hit this because localhost is bypassed by default.)
15
+ #
16
+ # Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic
17
+ # OSWorld setup pipeline.
18
+ #
19
+ # Argv:
20
+ # $1 optional sudo password (default "password"; SetupController
21
+ # substitutes {CLIENT_PASSWORD} when uploaded as a cache file).
22
+ # $2 unused (kept for backward compat — was socat first port 9000).
23
+ # $3 unused (kept for backward compat — was socat last port 9097).
24
+ # $4 optional mock host IP (default 28.7.184.198).
25
+
26
+ set +e
27
+
28
+ PASS="${1:-password}"
29
+ MOCK_HOST="${4:-28.7.184.198}"
30
+ # Derive the /16 IDC subnet so future port/host tweaks on the same segment
31
+ # stay bypassed too (28.7.184.198 -> 28.7.0.0/16).
32
+ MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')"
33
+
34
+ run_root() {
35
+ echo "$PASS" | sudo -S -p "" bash -c "$1"
36
+ }
37
+
38
+ # Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2.
39
+ GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')"
40
+ GW="${GW:-10.0.2.2}"
41
+
42
+ # ─── CUA-Gym network fix (Taiji-specific) ─────────────────────────────
43
+ fix_vm_network() {
44
+ # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP
45
+ # DNS forwarder. Nothing hardcoded except the mock host above.
46
+ local GW_NET="${GW%.*}"
47
+ local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3
48
+ local OWN_CIDR
49
+ OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \
50
+ | awk '{print $4; exit}')"
51
+ local OWN_IP="${OWN_CIDR%/*}"
52
+ local OWN_NET=""
53
+ [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24"
54
+
55
+ # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps
56
+ # systemd-resolved/NetworkManager from clobbering it.
57
+ if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf
58
+ chattr +i /etc/resolv.conf 2>/dev/null || true"; then
59
+ echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})"
60
+ else
61
+ echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf"
62
+ fi
63
+
64
+ # 2) Build the proxy bypass list from detected values + the direct-IP
65
+ # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx
66
+ # reachable from inside the VM — without it the woa proxy 403s it.
67
+ local ignore_list="['localhost', '127.0.0.0/8', '${GW}'"
68
+ [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'"
69
+ [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'"
70
+ [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'"
71
+ [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'"
72
+ [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'"
73
+ ignore_list="${ignore_list}]"
74
+
75
+ # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these.
76
+ if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then
77
+ echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}"
78
+ else
79
+ echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)"
80
+ fi
81
+
82
+ # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl).
83
+ local NP="localhost,127.0.0.1,${GW}"
84
+ [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}"
85
+ [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}"
86
+ [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24"
87
+ [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}"
88
+ [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}"
89
+
90
+ for var in no_proxy NO_PROXY; do
91
+ if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then
92
+ echo "export ${var}=${NP}" >> /home/user/.bashrc
93
+ fi
94
+ done
95
+ run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \
96
+ && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \
97
+ || echo 'no_proxy=\"${NP}\"' >> /etc/environment
98
+ grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \
99
+ && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \
100
+ || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1
101
+ echo "[cua_gym_vm_bridge] no_proxy=${NP}"
102
+ }
103
+
104
+ fix_vm_network
105
+
106
+ echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed"
csops_sla_queue_triage_003/initial_setup.py ADDED
@@ -0,0 +1,601 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --- MOCK_HOST_NO_PROXY_OVERRIDE: bypass woa proxy for locally-deployed mocks ---
2
+ import os as _os
3
+ _np = _os.environ.get("no_proxy", _os.environ.get("NO_PROXY", ""))
4
+ for _h in ("127.0.0.1", "localhost", "28.7.184.198", "28.7.184.198"):
5
+ if _h not in _np:
6
+ _np = (_np + "," + _h).lstrip(",")
7
+ _os.environ["no_proxy"] = _np
8
+ _os.environ["NO_PROXY"] = _np
9
+ # --- end override ---
10
+
11
+ # --- wait_mocks_loaded: wait for mock backends ready AND browser tabs rendered ---
12
+ def wait_mocks_loaded(timeout=60, render_buffer=12):
13
+ """Wait for mock backends ready AND browser tabs rendered (via CDP).
14
+
15
+ Phase 1 — backend readiness: poll each mock's /state?sid= until it
16
+ returns 200 with 'stored_state' in the body.
17
+
18
+ Phase 2 — browser render verification: connect to Chrome's CDP
19
+ endpoint and wait for every open tab to reach 'networkidle' load
20
+ state with a non-trivial DOM element count. This confirms the SPA
21
+ has fetched its /go?sid= data and actually painted, not just that
22
+ the backend is up.
23
+
24
+ CDP port auto-detection: checks globals for _chrome_debug_port /
25
+ cdp_port / debug_port (set by tasks that use a dynamic port, e.g.
26
+ se_hard_008's launch_chrome_with_urls); defaults to 1337 for tasks
27
+ that use launch_gui's --remote-debugging-port injection.
28
+
29
+ Falls back to the old render_buffer sleep if Playwright or the CDP
30
+ endpoint is unavailable.
31
+ """
32
+ import urllib.request as _u, time as _t
33
+ g = globals()
34
+ _urls = {}
35
+ for _k, _v in list(g.items()):
36
+ if isinstance(_v, dict) and _v and all(isinstance(x, str) and x.startswith("http://") for x in _v.values()):
37
+ _urls.update(_v)
38
+ elif isinstance(_v, str) and _v.startswith("http://") and (_k.endswith("_URL") or _k.endswith("_url")):
39
+ _urls[_k] = _v
40
+ _sid = ""
41
+ for _k in ("sid", "SID", "task_sid", "session_id"):
42
+ if isinstance(g.get(_k), str) and g[_k]:
43
+ _sid = g[_k]; break
44
+ if not _sid:
45
+ for _k, _v in g.items():
46
+ if "sid" in _k.lower() and isinstance(_v, str) and _v:
47
+ _sid = _v; break
48
+ if not _urls or not _sid:
49
+ print(" wait_mocks_loaded: no mocks/sid found (%d urls, sid=%r), skipping" % (len(_urls), bool(_sid)))
50
+ return
51
+
52
+ # ---- Phase 1: backend readiness ----
53
+ _op = _u.build_opener(_u.ProxyHandler({}))
54
+ _dl = _t.time() + timeout
55
+ _todo = list(_urls.items())
56
+ while _todo and _t.time() < _dl:
57
+ _rest = []
58
+ for _n2, _uu in _todo:
59
+ try:
60
+ _r = _op.open("%s/state?sid=%s" % (_uu, _sid), timeout=5)
61
+ if _r.status == 200 and b"stored_state" in _r.read():
62
+ print(" %s: backend ready" % _n2); continue
63
+ except Exception:
64
+ pass
65
+ _rest.append((_n2, _uu))
66
+ _todo = _rest
67
+ if _todo:
68
+ _t.sleep(2)
69
+ _done = len(_urls) - len(_todo)
70
+ _pend = (" (pending: %s)" % [n for n, _ in _todo]) if _todo else ""
71
+ print(" mocks backend ready: %d/%d%s" % (_done, len(_urls), _pend))
72
+
73
+ # ---- Phase 2: browser render verification via CDP ----
74
+ # Auto-detect CDP port from globals (set by launch_chrome_with_urls
75
+ # in tasks that use a dynamic port); default to 1337.
76
+ _cdp_port = 1337
77
+ for _pk in ("_chrome_debug_port", "chrome_debug_port", "cdp_port", "debug_port"):
78
+ _pv = g.get(_pk)
79
+ if isinstance(_pv, int) and 0 < _pv < 65536:
80
+ _cdp_port = _pv; break
81
+ _cdp_ok = False
82
+ try:
83
+ from playwright.sync_api import sync_playwright
84
+ _cdp_dl = _t.time() + max(10.0, _dl - _t.time()) # leftover budget, floor 10s
85
+ with sync_playwright() as _p:
86
+ _br = None
87
+ # Retry-connect: Chrome may still be starting up.
88
+ while _t.time() < _cdp_dl:
89
+ try:
90
+ _br = _p.chromium.connect_over_cdp("http://localhost:%d" % _cdp_port)
91
+ break
92
+ except Exception:
93
+ _t.sleep(0.5)
94
+ if _br is None:
95
+ print(" wait_mocks_loaded: CDP connect to localhost:%d failed; "
96
+ "is Chrome launched with --remote-debugging-port?" % _cdp_port)
97
+ else:
98
+ # Wait for ALL expected tabs to appear, then verify each renders.
99
+ _n_expected = len(_urls)
100
+ _pages = []
101
+ _pg_dl = _t.time() + 15
102
+ _last_count = -1
103
+ _stable_since = None
104
+ while _t.time() < _pg_dl:
105
+ _pages = []
106
+ for _c in _br.contexts:
107
+ _pages.extend(_c.pages)
108
+ _cnt = len(_pages)
109
+ if _n_expected > 0 and _cnt >= _n_expected:
110
+ break # all expected tabs are open
111
+ if _cnt > 0 and _cnt == _last_count:
112
+ if _stable_since is None:
113
+ _stable_since = _t.time()
114
+ elif _t.time() - _stable_since >= 1.5:
115
+ break # tab count stable -> no more tabs opening
116
+ else:
117
+ _stable_since = None
118
+ _last_count = _cnt
119
+ _t.sleep(0.5)
120
+ # Re-fetch final snapshot so late-opening tabs are included.
121
+ _pages = []
122
+ for _c in _br.contexts:
123
+ _pages.extend(_c.pages)
124
+ if not _pages:
125
+ print(" wait_mocks_loaded: CDP connected but no open tabs found")
126
+ else:
127
+ print(" wait_mocks_loaded: %d tab(s) open (expected %d); "
128
+ "verifying render" % (len(_pages), _n_expected))
129
+ _ok_cnt = 0
130
+ for _pg in _pages:
131
+ _ttl = ""
132
+ try:
133
+ _ttl = _pg.title()
134
+ except Exception:
135
+ pass
136
+ try:
137
+ _pg.wait_for_load_state(
138
+ "networkidle",
139
+ timeout=int(max(5000, (_cdp_dl - _t.time()) * 1000)))
140
+ _n = _pg.evaluate("document.querySelectorAll('*').length")
141
+ if _n < 20:
142
+ print(" wait_mocks_loaded: WARNING tab %r has only %d "
143
+ "elements (render stall?)" % (_ttl, _n))
144
+ else:
145
+ print(" wait_mocks_loaded: tab %r rendered (%d elements)"
146
+ % (_ttl, _n))
147
+ _ok_cnt += 1
148
+ except Exception as _e:
149
+ print(" wait_mocks_loaded: tab %r render wait failed: %r"
150
+ % (_ttl, _e))
151
+ # Require ALL open tabs to render before skipping the
152
+ # render_buffer fallback, so no tab is left half-loaded.
153
+ if _ok_cnt > 0 and _ok_cnt == len(_pages):
154
+ _cdp_ok = True
155
+ else:
156
+ print(" wait_mocks_loaded: %d/%d tabs rendered, will fall back"
157
+ % (_ok_cnt, len(_pages)))
158
+ except ImportError:
159
+ print(" wait_mocks_loaded: playwright not installed; cannot verify browser render")
160
+ except Exception as _e:
161
+ print(" wait_mocks_loaded: CDP phase error (%r)" % _e)
162
+
163
+ if not _cdp_ok:
164
+ print(" wait_mocks_loaded: falling back to render_buffer=%ds sleep" % render_buffer)
165
+ _t.sleep(render_buffer)
166
+ else:
167
+ print(" wait_mocks_loaded: browser render verified, skipping render_buffer")
168
+ # --- end wait_mocks_loaded ---
169
+
170
+ # --- _open_remaining_mock_tabs: open all auto-detected mock URLs in new Chrome tabs ---
171
+ def _open_remaining_mock_tabs(primary_url=""):
172
+ """Open all auto-detected mock URLs in Chrome --new-tab, except primary_url."""
173
+ g = globals()
174
+ _urls = set()
175
+ for _k, _v in list(g.items()):
176
+ if "PROBE" in _k.upper() or _k.startswith("_"):
177
+ continue
178
+ if isinstance(_v, str) and _v.startswith("http://") and (_k.endswith("_URL") or _k.endswith("_url")):
179
+ _urls.add(_v)
180
+ elif isinstance(_v, dict) and _v and all(isinstance(x, str) and x.startswith("http://") for x in _v.values()):
181
+ _urls.update(_v.values())
182
+ _sid = ""
183
+ for _k in ("sid", "SID", "task_sid", "session_id"):
184
+ if isinstance(g.get(_k), str) and g[_k]:
185
+ _sid = g[_k]; break
186
+ for _u in sorted(_urls):
187
+ if _u != primary_url:
188
+ launch_gui(f'google-chrome --new-tab "{_u}/?sid={_sid}"', delay_sec=1.0)
189
+ # --- end _open_remaining_mock_tabs ---
190
+
191
+
192
+ """
193
+ Initial Setup: Start-of-day support queue SLA triage.
194
+ Task ID: csops_sla_queue_triage_003
195
+ Domain: mock_websites (multi-mock)
196
+ Mocks: salesforce_mock, gmail_mock, jira_mock, notion_mock, slack_mock
197
+
198
+ Pre-task state (BEFORE the agent acts):
199
+ - Salesforce: 5 open cases. case-1 (Helios, Critical, New) and case-2
200
+ (Brightwave, High, New) are SLA-breached but NOT escalated and owned by
201
+ the admin/triage queue (user-1). case-3/4/5 are on-track.
202
+ - Gmail: two unread inbox emails (Helios outage echo + a newsletter). Context only.
203
+ - Jira: 'Support Engineering' (SUP) project with engineer Raj Patel (u_eng).
204
+ Two pre-existing SUP issues, but NO CSV-export defect bug.
205
+ - Notion: 'Support Ops' workspace with empty parent page 'Daily Triage'. No tracker.
206
+ - Slack: '#support' channel with prior chatter, but NO triage digest yet.
207
+ """
208
+ import os
209
+ import shlex
210
+ import subprocess
211
+ import time
212
+ import uuid
213
+
214
+ import requests
215
+
216
+ # --- Mock registry ---
217
+ MOCKS = {
218
+ 'salesforce': 'http://28.7.184.198:8175',
219
+ 'gmail': 'http://28.7.184.198:8138',
220
+ 'jira': 'http://28.7.184.198:8153',
221
+ 'notion': 'http://28.7.184.198:8166',
222
+ 'slack': 'http://28.7.184.198:8178',
223
+ }
224
+
225
+ # --- §1.5 Egress proxy helper ---
226
+ PROXY_CANDIDATES = [
227
+ os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy'),
228
+ None,
229
+ ]
230
+
231
+
232
+ def resolve_proxy(probe_url):
233
+ try:
234
+ requests.get(probe_url, timeout=8)
235
+ return None
236
+ except Exception:
237
+ pass
238
+ for candidate in PROXY_CANDIDATES:
239
+ if not candidate:
240
+ continue
241
+ try:
242
+ requests.get(probe_url, timeout=12,
243
+ proxies={'http': candidate, 'https': candidate})
244
+ return candidate
245
+ except Exception:
246
+ continue
247
+ raise RuntimeError('No working route to mock servers; direct and proxy attempts failed')
248
+
249
+
250
+ PROXY = resolve_proxy(f"{MOCKS['salesforce']}/go?sid=conn-probe")
251
+ PROXIES = None
252
+ print(f'Egress proxy: {PROXY or "direct"}')
253
+
254
+ # --- Persist sid for golden_patch.py and reward.py ---
255
+ sid = str(uuid.uuid4())
256
+ with open('/tmp/task_web_sid', 'w') as f:
257
+ f.write(sid)
258
+ print(f'sid = {sid}')
259
+
260
+
261
+ def launch_gui(command, delay_sec=1.0):
262
+ env = os.environ.copy()
263
+ env['DISPLAY'] = ':0'
264
+ # Accept both a command string and a pre-split arg list (some tasks
265
+ # build arg lists themselves, e.g. se_hard_008).
266
+ if isinstance(command, str):
267
+ _parts = shlex.split(command)
268
+ else:
269
+ _parts = list(command)
270
+ # Inject CDP debug port so wait_mocks_loaded can verify browser render
271
+ # via Playwright connect_over_cdp. Idempotent: skip if any arg already
272
+ # starts with --remote-debugging-port (some tasks inject their own
273
+ # dynamic port, e.g. se_hard_008).
274
+ if _parts and 'google-chrome' in _parts[0] \
275
+ and not any(p.startswith('--remote-debugging-port') for p in _parts):
276
+ _parts[1:1] = ['--no-first-run', '--no-default-browser-check',
277
+ '--remote-debugging-port=1337']
278
+ _proc = subprocess.Popen(_parts, stdin=subprocess.DEVNULL,
279
+ stdout=subprocess.DEVNULL,
280
+ stderr=subprocess.DEVNULL, env=env,
281
+ start_new_session=True)
282
+ time.sleep(delay_sec)
283
+ if _proc.poll() is not None:
284
+ print(' WARNING: launch_gui process exited early (code=%s)'
285
+ % _proc.returncode)
286
+ return _proc
287
+ def build_salesforce_state():
288
+ users = [
289
+ {"userId": "user-1", "firstName": "Alex", "lastName": "Morgan",
290
+ "email": "alex.morgan@company.com", "phone": "(555) 100-0001",
291
+ "title": "Support Operations Lead", "department": "Customer Support",
292
+ "role": "Manager", "avatar": "https://i.pravatar.cc/150?u=user-1",
293
+ "timezone": "America/New_York", "locale": "en-US", "theme": "lightning"},
294
+ {"userId": "user-2", "firstName": "Priya", "lastName": "Nair",
295
+ "email": "priya.nair@company.com", "phone": "(555) 100-0002",
296
+ "title": "Customer Success Manager", "department": "Customer Success",
297
+ "role": "CSM", "avatar": "https://i.pravatar.cc/150?u=user-2",
298
+ "timezone": "America/New_York", "locale": "en-US", "theme": "lightning"},
299
+ {"userId": "user-3", "firstName": "Marcus", "lastName": "Reid",
300
+ "email": "marcus.reid@company.com", "phone": "(555) 100-0003",
301
+ "title": "Customer Success Manager", "department": "Customer Success",
302
+ "role": "CSM", "avatar": "https://i.pravatar.cc/150?u=user-3",
303
+ "timezone": "America/Chicago", "locale": "en-US", "theme": "lightning"},
304
+ {"userId": "user-4", "firstName": "Dana", "lastName": "Lopez",
305
+ "email": "dana.lopez@company.com", "phone": "(555) 100-0004",
306
+ "title": "Support Engineer", "department": "Customer Support",
307
+ "role": "Engineer", "avatar": "https://i.pravatar.cc/150?u=user-4",
308
+ "timezone": "America/Los_Angeles", "locale": "en-US", "theme": "lightning"},
309
+ {"userId": "user-5", "firstName": "Sam", "lastName": "Patel",
310
+ "email": "sam.patel@company.com", "phone": "(555) 100-0005",
311
+ "title": "Customer Success Manager", "department": "Customer Success",
312
+ "role": "CSM", "avatar": "https://i.pravatar.cc/150?u=user-5",
313
+ "timezone": "America/Denver", "locale": "en-US", "theme": "lightning"},
314
+ ]
315
+
316
+ def acct(aid, name, industry, rev, emp, owner, city, state, zip_):
317
+ return {"accountId": aid, "name": name, "phone": "(555) 200-0000",
318
+ "website": f"https://{name.split()[0].lower()}.example.com",
319
+ "type": "Customer", "industry": industry, "revenue": rev,
320
+ "employees": emp,
321
+ "description": f"{name} — active support customer.",
322
+ "ownerId": owner,
323
+ "billingStreet": "1 Market St", "billingCity": city,
324
+ "billingState": state, "billingZip": zip_, "billingCountry": "United States",
325
+ "shippingStreet": "1 Market St", "shippingCity": city,
326
+ "shippingState": state, "shippingZip": zip_, "shippingCountry": "United States",
327
+ "createdDate": "2025-08-01T10:00:00.000Z",
328
+ "modifiedDate": "2026-06-01T10:00:00.000Z"}
329
+
330
+ accounts = [
331
+ acct("account-1", "Helios Retail", "Retail", 42000000, 600, "user-3", "Boston", "MA", "02110"),
332
+ acct("account-2", "Brightwave Media", "Media", 8500000, 140, "user-2", "Seattle", "WA", "98101"),
333
+ acct("account-3", "Nimbus Co", "Technology", 12000000, 90, "user-3", "Austin", "TX", "73301"),
334
+ acct("account-4", "Orbit Labs", "Technology", 6000000, 55, "user-1", "Denver", "CO", "80202"),
335
+ acct("account-5", "Contoso Bank", "Finance", 210000000, 3400, "user-2", "New York", "NY", "10005"),
336
+ ]
337
+
338
+ def contact(cid, aid, fn, ln, title, email, owner):
339
+ return {"contactId": cid, "accountId": aid, "firstName": fn, "lastName": ln,
340
+ "title": title, "department": "Operations", "email": email,
341
+ "phone": "(555) 300-0000", "mobile": "(555) 300-0001",
342
+ "mailingStreet": "1 Market St", "mailingCity": "—", "mailingState": "—",
343
+ "mailingZip": "00000", "mailingCountry": "United States", "ownerId": owner,
344
+ "createdDate": "2025-09-01T10:00:00.000Z",
345
+ "modifiedDate": "2026-06-01T10:00:00.000Z"}
346
+
347
+ contacts = [
348
+ contact("contact-1", "account-1", "Helen", "Ross", "Ops Lead", "helen.ross@helios-retail.example.com", "user-3"),
349
+ contact("contact-2", "account-2", "Ben", "Wells", "Analytics Manager", "ben.wells@brightwave.example.com", "user-2"),
350
+ contact("contact-3", "account-3", "Nadia", "Kim", "IT Admin", "nadia.kim@nimbus.example.com", "user-3"),
351
+ contact("contact-4", "account-4", "Omar", "Diaz", "Product Owner", "omar.diaz@orbitlabs.example.com", "user-1"),
352
+ contact("contact-5", "account-5", "Carla", "Bishop", "Security Lead", "carla.bishop@contoso.example.com", "user-2"),
353
+ ]
354
+
355
+ # NOTE: breached cases (case-1, case-2) are NEW and admin-owned (user-1) — NOT escalated.
356
+ cases = [
357
+ {"caseId": "case-1", "caseNumber": "00001001",
358
+ "subject": "Checkout payment declined for all EU cards",
359
+ "status": "New", "priority": "Critical", "origin": "Web", "type": "Problem",
360
+ "accountId": "account-1", "contactId": "contact-1",
361
+ "description": "All EU card payments at checkout are being declined since early "
362
+ "this morning. Complete payment outage for European customers.",
363
+ "ownerId": "user-1",
364
+ "createdDate": "2026-06-24T02:30:00.000Z", "modifiedDate": "2026-06-24T02:30:00.000Z"},
365
+ {"caseId": "case-2", "caseNumber": "00001002",
366
+ "subject": "Reports export to CSV produces empty file",
367
+ "status": "New", "priority": "High", "origin": "Email", "type": "Problem",
368
+ "accountId": "account-2", "contactId": "contact-2",
369
+ "description": "Exporting any report to CSV downloads a 0-byte / empty file. "
370
+ "Reproducible every time on all report types. Customer is blocked.",
371
+ "ownerId": "user-1",
372
+ "createdDate": "2026-06-22T20:00:00.000Z", "modifiedDate": "2026-06-22T20:00:00.000Z"},
373
+ {"caseId": "case-3", "caseNumber": "00001003",
374
+ "subject": "How do I rename a workspace?",
375
+ "status": "Working", "priority": "Medium", "origin": "Web", "type": "Question",
376
+ "accountId": "account-3", "contactId": "contact-3",
377
+ "description": "Customer asks how to rename their workspace in the admin settings.",
378
+ "ownerId": "user-3",
379
+ "createdDate": "2026-06-24T07:00:00.000Z", "modifiedDate": "2026-06-24T07:15:00.000Z"},
380
+ {"caseId": "case-4", "caseNumber": "00001004",
381
+ "subject": "Feature request: dark mode",
382
+ "status": "Working", "priority": "Low", "origin": "Web", "type": "Feature Request",
383
+ "accountId": "account-4", "contactId": "contact-4",
384
+ "description": "Customer requests a dark theme option for the dashboard.",
385
+ "ownerId": "user-1",
386
+ "createdDate": "2026-06-21T13:00:00.000Z", "modifiedDate": "2026-06-21T13:00:00.000Z"},
387
+ {"caseId": "case-5", "caseNumber": "00001005",
388
+ "subject": "SSO occasionally logs users out",
389
+ "status": "Working", "priority": "High", "origin": "Phone", "type": "Problem",
390
+ "accountId": "account-5", "contactId": "contact-5",
391
+ "description": "A handful of users are intermittently logged out of SSO sessions. "
392
+ "Under investigation; not yet reproducible at scale.",
393
+ "ownerId": "user-2",
394
+ "createdDate": "2026-06-24T06:00:00.000Z", "modifiedDate": "2026-06-24T06:30:00.000Z"},
395
+ ]
396
+
397
+ return {
398
+ "user": users[0], "users": users, "leads": [],
399
+ "accounts": accounts, "contacts": contacts, "opportunities": [],
400
+ "cases": cases, "activities": [], "chatterPosts": [], "files": [],
401
+ "following": ["user-2", "user-3"], "recentlyViewed": [], "dismissedNotifications": [],
402
+ }
403
+
404
+
405
+ # ======================================================================
406
+ # GMAIL — two unread inbox emails (context only)
407
+ # ======================================================================
408
+ def build_gmail_state():
409
+ return {
410
+ "user": {"userId": "u1", "username": "Support Inbox",
411
+ "email": "support@company.com", "avatar": "https://i.pravatar.cc/150?u=support"},
412
+ "emails": [
413
+ {"id": "email_helios", "threadId": "thread_helios",
414
+ "from": {"name": "Helen Ross", "email": "helen.ross@helios-retail.example.com"},
415
+ "to": [{"name": "Support Inbox", "email": "support@company.com"}],
416
+ "cc": [], "bcc": [],
417
+ "subject": "URGENT: EU card payments all failing at checkout",
418
+ "body": ("<p>Hi Support,</p><p>Since early this morning every EU customer is "
419
+ "getting their card declined at checkout — it's a total payment outage "
420
+ "for our European storefront. We're losing sales by the minute. Please "
421
+ "escalate immediately.</p><p>— Helen, Ops Lead, Helios Retail</p>"),
422
+ "timestamp": "2026-06-24T03:05:00Z", "read": False, "starred": False,
423
+ "important": False, "labels": [], "category": "primary", "folder": "inbox",
424
+ "attachments": []},
425
+ {"id": "email_news", "threadId": "thread_news",
426
+ "from": {"name": "SaaS Weekly", "email": "newsletter@saasweekly.example.com"},
427
+ "to": [{"name": "Support Inbox", "email": "support@company.com"}],
428
+ "cc": [], "bcc": [],
429
+ "subject": "This week: 7 onboarding tips and a product teardown",
430
+ "body": ("<p>Welcome to your weekly digest! This week we cover activation "
431
+ "metrics, onboarding checklists, and a teardown of a popular dashboard. "
432
+ "Enjoy the read.</p>"),
433
+ "timestamp": "2026-06-24T07:30:00Z", "read": False, "starred": False,
434
+ "important": False, "labels": [], "category": "promotions", "folder": "inbox",
435
+ "attachments": []},
436
+ ],
437
+ "labels": [
438
+ {"id": "l1", "name": "Work", "color": "#ef4444"},
439
+ {"id": "l2", "name": "Personal", "color": "#3b82f6"},
440
+ {"id": "l3", "name": "Travel", "color": "#22c55e"},
441
+ {"id": "l4", "name": "Finance", "color": "#eab308"},
442
+ ],
443
+ "drafts": [],
444
+ }
445
+
446
+
447
+ # ======================================================================
448
+ # JIRA — Support Engineering (SUP) project + Raj Patel; NO CSV bug yet
449
+ # ======================================================================
450
+ def build_jira_state():
451
+ users = [
452
+ {"id": "u1", "name": "Admin User", "email": "admin@company.com",
453
+ "avatar": "https://picsum.photos/100/100?random=u1"},
454
+ {"id": "u_eng", "name": "Raj Patel", "email": "raj.patel@company.com",
455
+ "avatar": "https://picsum.photos/100/100?random=ueng"},
456
+ {"id": "u_eng2", "name": "Lena Vogt", "email": "lena.vogt@company.com",
457
+ "avatar": "https://picsum.photos/100/100?random=ueng2"},
458
+ ]
459
+ projects = [
460
+ {"id": "p_sup", "key": "SUP", "name": "Support Engineering", "leadId": "u_eng",
461
+ "category": "Software", "icon": "https://picsum.photos/64/64?random=psup"},
462
+ ]
463
+ issues = [
464
+ {"id": "sup1", "key": "SUP-1", "projectId": "p_sup",
465
+ "summary": "Investigate intermittent webhook delivery delays",
466
+ "description": "Some outbound webhooks are delayed by several minutes under load.",
467
+ "type": "Bug", "status": "In Progress", "priority": "Medium", "storyPoints": 3,
468
+ "reporterId": "u1", "assigneeId": "u_eng", "sprintId": None, "epicId": None,
469
+ "labels": ["backend"], "subtasks": [], "linkedIssueIds": [],
470
+ "createdAt": "2026-06-18T10:00:00.000Z", "updatedAt": "2026-06-20T10:00:00.000Z"},
471
+ {"id": "sup2", "key": "SUP-2", "projectId": "p_sup",
472
+ "summary": "Add retry logic to email notification worker",
473
+ "description": "Notification worker should retry transient SMTP failures.",
474
+ "type": "Task", "status": "To Do", "priority": "Low", "storyPoints": 2,
475
+ "reporterId": "u1", "assigneeId": "u_eng2", "sprintId": None, "epicId": None,
476
+ "labels": ["infra"], "subtasks": [], "linkedIssueIds": [],
477
+ "createdAt": "2026-06-19T11:00:00.000Z", "updatedAt": "2026-06-19T11:00:00.000Z"},
478
+ ]
479
+ return {
480
+ "currentUser": users[0], "users": users, "projects": projects,
481
+ "sprints": [], "issues": issues, "comments": [],
482
+ "workflows": [{"id": "w1", "name": "Software Workflow", "transitions": [
483
+ {"from": "To Do", "to": ["In Progress"]},
484
+ {"from": "In Progress", "to": ["In Review", "To Do", "Done"]},
485
+ {"from": "In Review", "to": ["Done", "In Progress"]},
486
+ {"from": "Done", "to": ["In Progress", "To Do"]}]}],
487
+ "notifications": [],
488
+ }
489
+
490
+
491
+ # ======================================================================
492
+ # NOTION — Support Ops workspace, empty 'Daily Triage' page, NO tracker
493
+ # ======================================================================
494
+ DAILY_TRIAGE_ID = "page-daily-triage"
495
+
496
+
497
+ def build_notion_state(extra_pages=None, page_order=None):
498
+ pages = {
499
+ DAILY_TRIAGE_ID: {
500
+ "id": DAILY_TRIAGE_ID, "title": "Daily Triage", "icon": "\U0001F4CB",
501
+ "cover": None, "parentId": None, "blockIds": [], "favorite": False,
502
+ "createdDate": "2026-06-01T09:00:00.000Z",
503
+ "lastEditedDate": "2026-06-24T08:00:00.000Z", "properties": {}},
504
+ }
505
+ if extra_pages:
506
+ pages.update(extra_pages)
507
+ return {
508
+ "user": {"id": "user-1", "name": "Alex Morgan",
509
+ "email": "alex.morgan@company.com", "avatar": ""},
510
+ "workspace": {"id": "ws-1", "name": "Support Ops", "icon": "\U0001F3E2",
511
+ "members": ["user-1"]},
512
+ "pages": pages, "blocks": {}, "trash": [], "comments": {},
513
+ "settings": {"appearance": "light", "startWeekMonday": False, "fontSize": "default"},
514
+ "notifications": [],
515
+ "pageOrder": page_order if page_order else [DAILY_TRIAGE_ID],
516
+ }
517
+
518
+
519
+ # ======================================================================
520
+ # SLACK — #support channel with prior chatter, NO digest yet
521
+ # ======================================================================
522
+ def build_slack_state():
523
+ users = [
524
+ {"userId": "user_1", "fullName": "Alex Morgan", "displayName": "Alex",
525
+ "email": "alex.morgan@company.com", "avatar": "https://picsum.photos/200/200?random=1",
526
+ "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"},
527
+ {"userId": "user_2", "fullName": "Priya Nair", "displayName": "Priya",
528
+ "email": "priya.nair@company.com", "avatar": "https://picsum.photos/200/200?random=2",
529
+ "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"},
530
+ {"userId": "user_3", "fullName": "Marcus Reid", "displayName": "Marcus",
531
+ "email": "marcus.reid@company.com", "avatar": "https://picsum.photos/200/200?random=3",
532
+ "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/Chicago"},
533
+ ]
534
+ return {
535
+ "currentUser": users[0],
536
+ "workspace": {"workspaceId": "ws_1", "workspaceName": "Company Support", "icon": ""},
537
+ "users": users,
538
+ "channels": [
539
+ {"channelId": "support", "name": "support", "description": "Customer support team",
540
+ "topic": "Triage and escalations", "isPrivate": False, "isStarred": False,
541
+ "members": ["user_1", "user_2", "user_3"], "createdBy": "user_1",
542
+ "createdAt": "2026-01-01T10:00:00Z", "pinnedMessages": [], "unreadCount": 0},
543
+ {"channelId": "general", "name": "general", "description": "Company-wide chat",
544
+ "topic": "", "isPrivate": False, "isStarred": False,
545
+ "members": ["user_1", "user_2", "user_3"], "createdBy": "user_1",
546
+ "createdAt": "2026-01-01T10:00:00Z", "pinnedMessages": [], "unreadCount": 0},
547
+ ],
548
+ "messages": {
549
+ "support": [
550
+ {"messageId": "msg_s1", "senderId": "user_2",
551
+ "content": "Morning all — starting on the queue once standup wraps.",
552
+ "timestamp": "2026-06-24T08:45:00Z", "threadId": None,
553
+ "reactions": [], "attachments": [], "isEdited": False},
554
+ {"messageId": "msg_s2", "senderId": "user_3",
555
+ "content": "Sounds good, ping me if anything critical comes in.",
556
+ "timestamp": "2026-06-24T08:50:00Z", "threadId": None,
557
+ "reactions": [], "attachments": [], "isEdited": False},
558
+ ],
559
+ "general": [
560
+ {"messageId": "msg_g1", "senderId": "user_1",
561
+ "content": "Reminder: SLA policy doc is pinned in #support.",
562
+ "timestamp": "2026-06-23T17:00:00Z", "threadId": None,
563
+ "reactions": [], "attachments": [], "isEdited": False},
564
+ ],
565
+ },
566
+ "threads": {}, "dms": [], "bookmarkedMessages": [], "callHistory": [],
567
+ "settings": {"theme": "light", "notifications": "all", "displayDensity": "comfortable",
568
+ "showAvatars": True, "use24Hour": False},
569
+ "invitations": [], "notifications": [],
570
+ }
571
+
572
+
573
+ # ======================================================================
574
+ # Inject state into all five mocks (same sid)
575
+ # ======================================================================
576
+ STATES = {
577
+ 'salesforce': build_salesforce_state(),
578
+ 'gmail': build_gmail_state(),
579
+ 'jira': build_jira_state(),
580
+ 'notion': build_notion_state(),
581
+ 'slack': build_slack_state(),
582
+ }
583
+
584
+ for name, state in STATES.items():
585
+ url = MOCKS[name]
586
+ resp = requests.post(f'{url}/post?sid={sid}',
587
+ json={'action': 'set', 'state': state},
588
+ timeout=30, proxies=PROXIES)
589
+ assert resp.status_code == 200, f'State injection failed for {name}: {resp.text}'
590
+ go = requests.get(f'{url}/go?sid={sid}', timeout=10, proxies=PROXIES).json()
591
+ assert go['initial_state'] is not None, f'initial_state is None for {name}'
592
+ print(f'State injected & verified: {name} ({url}) sid={sid}')
593
+
594
+ # ======================================================================
595
+ # Launch browsers — Salesforce focused last/primary
596
+ # ======================================================================
597
+ chrome_proxy = f'--proxy-server={PROXY}' if PROXY else ''
598
+ for name in ['slack', 'notion', 'jira', 'gmail', 'salesforce']:
599
+ launch_gui(f'google-chrome "{MOCKS[name]}/?sid={sid}"', delay_sec=1.5)
600
+ wait_mocks_loaded()
601
+ print(f'GUI_READY: launched all 5 mocks with sid={sid}')
csops_sla_queue_triage_003/reward.py ADDED
@@ -0,0 +1,594 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --- MOCK_HOST_NO_PROXY_OVERRIDE: bypass woa proxy for locally-deployed mocks ---
2
+ import os as _os
3
+ _np = _os.environ.get("no_proxy", _os.environ.get("NO_PROXY", ""))
4
+ for _h in ("127.0.0.1", "localhost", "28.7.184.198", "28.7.184.198"):
5
+ if _h not in _np:
6
+ _np = (_np + "," + _h).lstrip(",")
7
+ _os.environ["no_proxy"] = _np
8
+ _os.environ["NO_PROXY"] = _np
9
+ # --- end override ---
10
+
11
+ """
12
+ Reward Script: Start-of-day SLA support-queue triage across 5 mocks
13
+ Task ID: csops_sla_queue_triage_003
14
+ Domain: mock_websites (salesforce, jira, notion, slack)
15
+
16
+ Scoring rubric (1.0 total) — every component verifies a task-introduced change
17
+ (fails on initial_env, passes on golden_env):
18
+
19
+ Salesforce (0.30) — escalate the two breached cases with the right owners
20
+ 1a. case-1 (Helios payment) status == 'Escalated' AND owner == user-3 (0.15)
21
+ 1b. case-2 (Brightwave CSV) status == 'Escalated' AND owner == user-2 (0.15)
22
+ GATE: if any on-track case (3/4/5) is Escalated, Salesforce score is zeroed.
23
+
24
+ Jira (0.25) — file an engineering bug for the reproducible CSV defect
25
+ 2. NEW issue in project 'SUP', type Bug, High priority, assignee u_eng,
26
+ description naming 'Brightwave Media' (0.25)
27
+
28
+ Notion (0.25) — capture the active queue in a shared tracker
29
+ 3a. NEW database 'Support SLA Tracker' under the 'Daily Triage' page with
30
+ the required columns and >= 5 rows (one per open case) (0.13)
31
+ 3b. The two breached rows (Helios, Brightwave) marked SLA Status 'Breached'
32
+ AND on-track rows NOT marked Breached (0.12)
33
+
34
+ Slack (0.20) — post the triage digest
35
+ 4. NEW message in #support that names both breached customers, says they
36
+ were escalated, and references the engineering ticket (0.20)
37
+
38
+ All scoring is programmatic. Reward derived purely from task_config.json
39
+ ground truth + VM state exploration, not from setup-gen source.
40
+ """
41
+ import sys
42
+ import os
43
+ import re
44
+
45
+ import requests
46
+
47
+ # --- Read sid ---
48
+ try:
49
+ with open('/tmp/task_web_sid') as f:
50
+ sid = f.read().strip()
51
+ if not sid:
52
+ raise ValueError('sid is empty')
53
+ except Exception as e:
54
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
55
+ print('REWARD: 0.0')
56
+ sys.exit(0)
57
+
58
+ MOCKS = {
59
+ 'salesforce': 'http://28.7.184.198:8175',
60
+ 'jira': 'http://28.7.184.198:8153',
61
+ 'notion': 'http://28.7.184.198:8166',
62
+ 'slack': 'http://28.7.184.198:8178',
63
+ }
64
+
65
+ # --- Egress proxy helper (MANDATORY) ---
66
+ PROXY_CANDIDATES = [
67
+ os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy'),
68
+ None,
69
+ ]
70
+
71
+
72
+ def resolve_proxy(probe_url):
73
+ try:
74
+ requests.get(probe_url, timeout=8)
75
+ return None
76
+ except Exception:
77
+ pass
78
+ for candidate in PROXY_CANDIDATES:
79
+ if not candidate:
80
+ continue
81
+ try:
82
+ requests.get(
83
+ probe_url,
84
+ timeout=12,
85
+ proxies={'http': candidate, 'https': candidate},
86
+ )
87
+ return candidate
88
+ except Exception:
89
+ continue
90
+ return None
91
+
92
+
93
+ PROXY = resolve_proxy(f"{MOCKS['salesforce']}/go?sid=conn-probe")
94
+ PROXIES = None
95
+ print(f'Egress proxy: {PROXY or "direct"}')
96
+
97
+
98
+ def fetch(name):
99
+ """Fetch /go state for a mock. Returns dict or None on failure."""
100
+ url = MOCKS[name]
101
+ try:
102
+ resp = requests.get(f'{url}/go?sid={sid}', timeout=15, proxies=PROXIES)
103
+ resp.raise_for_status()
104
+ return resp.json()
105
+ except Exception as e:
106
+ print(f'CRITICAL: Cannot fetch state from {name}: {e}')
107
+ return None
108
+
109
+
110
+ EXPECTED_CASES = [
111
+ {
112
+ 'case_id': 'case-1',
113
+ 'case_number': '00001001',
114
+ 'customer_terms': ('helios', 'retail'),
115
+ 'priority': 'critical',
116
+ 'owner_id': 'user-3',
117
+ 'owner_terms': ('marcus', 'reid'),
118
+ 'breached': True,
119
+ 'problem_terms': ('payment', 'checkout', 'card'),
120
+ },
121
+ {
122
+ 'case_id': 'case-2',
123
+ 'case_number': '00001002',
124
+ 'customer_terms': ('brightwave', 'media'),
125
+ 'priority': 'high',
126
+ 'owner_id': 'user-2',
127
+ 'owner_terms': ('priya', 'nair'),
128
+ 'breached': True,
129
+ 'problem_terms': ('csv', 'export', 'empty'),
130
+ },
131
+ {
132
+ 'case_id': 'case-3',
133
+ 'case_number': '00001003',
134
+ 'customer_terms': ('nimbus',),
135
+ 'priority': 'medium',
136
+ 'owner_id': 'user-3',
137
+ 'owner_terms': ('marcus', 'reid'),
138
+ 'breached': False,
139
+ 'problem_terms': ('rename', 'workspace'),
140
+ },
141
+ {
142
+ 'case_id': 'case-4',
143
+ 'case_number': '00001004',
144
+ 'customer_terms': ('orbit', 'labs'),
145
+ 'priority': 'low',
146
+ 'owner_id': 'user-1',
147
+ 'owner_terms': ('alex', 'morgan'),
148
+ 'breached': False,
149
+ 'problem_terms': ('dark', 'mode'),
150
+ },
151
+ {
152
+ 'case_id': 'case-5',
153
+ 'case_number': '00001005',
154
+ 'customer_terms': ('contoso', 'bank'),
155
+ 'priority': 'high',
156
+ 'owner_id': 'user-2',
157
+ 'owner_terms': ('priya', 'nair'),
158
+ 'breached': False,
159
+ 'problem_terms': ('sso', 'logout'),
160
+ },
161
+ ]
162
+
163
+
164
+ def norm(value):
165
+ """Case/space/punctuation-insensitive text normalization."""
166
+ text = str(value or '').casefold()
167
+ text = re.sub(r'[^a-z0-9]+', ' ', text)
168
+ return re.sub(r'\s+', ' ', text).strip()
169
+
170
+
171
+ def compact(value):
172
+ return re.sub(r'[^a-z0-9]+', '', str(value or '').casefold())
173
+
174
+
175
+ def value_text(value):
176
+ """Serialize Notion/Slack/Jira values, including typed property objects."""
177
+ if value is None:
178
+ return ''
179
+ if isinstance(value, dict):
180
+ return ' '.join(value_text(v) for v in value.values())
181
+ if isinstance(value, (list, tuple, set)):
182
+ return ' '.join(value_text(v) for v in value)
183
+ return str(value)
184
+
185
+
186
+ def contains_all(text, terms):
187
+ haystack = norm(text)
188
+ return all(norm(term) in haystack for term in terms)
189
+
190
+
191
+ def contains_any(text, terms):
192
+ haystack = norm(text)
193
+ return any(norm(term) in haystack for term in terms)
194
+
195
+
196
+ def case_identity_ok(case_obj, spec):
197
+ return (
198
+ str(case_obj.get('caseNumber', '')).strip() == spec['case_number']
199
+ and norm(case_obj.get('priority')) == spec['priority']
200
+ )
201
+
202
+
203
+ def issue_text(issue):
204
+ return f"{issue.get('summary', '')} {issue.get('description', '')}"
205
+
206
+
207
+ def is_csv_empty_problem(text):
208
+ return (
209
+ contains_any(text, ('csv', 'comma separated', 'report export', 'reports export'))
210
+ and contains_any(text, (
211
+ 'empty', 'blank', '0 byte', 'zero byte', '0byte', 'zero-byte',
212
+ 'no data', 'nothing in file', 'file has no rows',
213
+ ))
214
+ )
215
+
216
+
217
+ def prop_name_map(db):
218
+ mapping = {}
219
+ props = db.get('properties', []) or []
220
+ if isinstance(props, dict):
221
+ for pid, prop in props.items():
222
+ if isinstance(prop, dict):
223
+ mapping[str(pid)] = str(prop.get('name') or pid)
224
+ else:
225
+ mapping[str(pid)] = str(prop)
226
+ else:
227
+ for prop in props:
228
+ if isinstance(prop, dict):
229
+ pid = str(prop.get('id') or prop.get('name') or '')
230
+ if pid:
231
+ mapping[pid] = str(prop.get('name') or pid)
232
+ elif prop:
233
+ mapping[str(prop)] = str(prop)
234
+ return mapping
235
+
236
+
237
+ def prop_defs_text(db):
238
+ props = db.get('properties', []) or []
239
+ if isinstance(props, dict):
240
+ return value_text([
241
+ {'id': k, 'definition': v} for k, v in props.items()
242
+ ])
243
+ return value_text(props)
244
+
245
+
246
+ def row_pages(db, pages):
247
+ rows = []
248
+ for item in db.get('items', []) or []:
249
+ if isinstance(item, dict):
250
+ rows.append(item)
251
+ elif item in pages:
252
+ rows.append(pages[item])
253
+ return rows
254
+
255
+
256
+ def page_blob(page):
257
+ parts = [page.get('title', '')]
258
+ props = page.get('properties', {}) or {}
259
+ if isinstance(props, dict):
260
+ for key, value in props.items():
261
+ parts.extend([str(key), value_text(value)])
262
+ else:
263
+ parts.append(value_text(props))
264
+ return ' '.join(parts)
265
+
266
+
267
+ def status_blob(row, db):
268
+ props = row.get('properties', {}) or {}
269
+ names = prop_name_map(db)
270
+ values = []
271
+ if isinstance(props, dict):
272
+ for key, value in props.items():
273
+ key_text = norm(f"{key} {names.get(str(key), '')}")
274
+ value_str = value_text(value)
275
+ combined = f"{key_text} {norm(value_str)}"
276
+ if contains_any(combined, ('sla', 'status', 'breach', 'breached')):
277
+ values.append(value_str)
278
+ if not values:
279
+ values.append(page_blob(row))
280
+ return ' '.join(values)
281
+
282
+
283
+ def is_breached_status(text):
284
+ lowered = norm(text)
285
+ if contains_any(lowered, (
286
+ 'not breached', 'non breached', 'no breach', 'within sla',
287
+ 'on track', 'ontrack', 'in sla', 'normal', 'ok',
288
+ )):
289
+ return False
290
+ return contains_any(lowered, (
291
+ 'breached', 'breach', 'sla breach', 'violated', 'violation',
292
+ 'missed sla', 'overdue', 'expired', 'late',
293
+ ))
294
+
295
+
296
+ def row_matches_case(row, spec):
297
+ blob = page_blob(row)
298
+ return (
299
+ spec['case_number'] in compact(blob)
300
+ or contains_all(blob, spec['customer_terms'])
301
+ or contains_any(blob, spec['problem_terms'])
302
+ )
303
+
304
+
305
+ def support_messages(state):
306
+ messages = state.get('messages', {}) or {}
307
+ channels = state.get('channels', []) or []
308
+ support_ids = {
309
+ str(ch.get('channelId'))
310
+ for ch in channels
311
+ if norm(ch.get('name')) == 'support' or norm(ch.get('channelId')) == 'support'
312
+ }
313
+ support_ids.add('support')
314
+ out = []
315
+ for channel_id in support_ids:
316
+ out.extend(messages.get(channel_id, []) or [])
317
+ return out
318
+
319
+
320
+ def new_by_id(current, initial, key):
321
+ init_ids = {item.get(key) for item in initial if isinstance(item, dict)}
322
+ return [
323
+ item for item in current
324
+ if isinstance(item, dict) and item.get(key) not in init_ids
325
+ ]
326
+
327
+
328
+ def verify_task():
329
+ total_score = 0.0
330
+
331
+ states = {name: fetch(name) for name in MOCKS}
332
+ # Hard gate: if any mock unreachable, we cannot verify -> 0.0
333
+ if any(states[n] is None for n in MOCKS):
334
+ print('CRITICAL: one or more mock states unavailable')
335
+ print('REWARD: 0.0')
336
+ return 0.0
337
+
338
+ # ============================================================
339
+ # Salesforce (0.30) — escalate the two breached cases w/ owners
340
+ # ============================================================
341
+ try:
342
+ sf_cur = states['salesforce'].get('current_state', {}) or {}
343
+ cases = {c['caseId']: c for c in sf_cur.get('cases', [])}
344
+
345
+ c1_spec, c2_spec = EXPECTED_CASES[0], EXPECTED_CASES[1]
346
+ c1 = cases.get(c1_spec['case_id'], {})
347
+ c2 = cases.get(c2_spec['case_id'], {})
348
+
349
+ # Component 1a: case-1 escalated AND owned by Marcus Reid (user-3)
350
+ c1_ok = (norm(c1.get('status')) == 'escalated'
351
+ and c1.get('ownerId') == c1_spec['owner_id']
352
+ and case_identity_ok(c1, c1_spec))
353
+ # Component 1b: case-2 escalated AND owned by Priya Nair (user-2)
354
+ c2_ok = (norm(c2.get('status')) == 'escalated'
355
+ and c2.get('ownerId') == c2_spec['owner_id']
356
+ and case_identity_ok(c2, c2_spec))
357
+
358
+ # GATE: on-track cases (3,4,5) must NOT be escalated. This is true on
359
+ # initial too (precondition), so it only acts as a penalty gate — it
360
+ # never awards points on its own.
361
+ ontrack_clean = all(
362
+ norm(cases.get(spec['case_id'], {}).get('status')) != 'escalated'
363
+ for spec in EXPECTED_CASES if not spec['breached']
364
+ )
365
+
366
+ if not ontrack_clean:
367
+ print('GATE FAIL: an on-track case was wrongly escalated — '
368
+ 'Salesforce component zeroed')
369
+ else:
370
+ if c1_ok:
371
+ print('PASS: case-1 Escalated and assigned to Marcus Reid '
372
+ '(user-3) (+0.15)')
373
+ total_score += 0.15
374
+ else:
375
+ print(f'FAIL: case-1 expected Escalated+owner user-3, '
376
+ f"caseNumber=00001001 priority=Critical; found "
377
+ f"status={c1.get('status')} owner={c1.get('ownerId')} "
378
+ f"caseNumber={c1.get('caseNumber')} "
379
+ f"priority={c1.get('priority')}")
380
+ if c2_ok:
381
+ print('PASS: case-2 Escalated and assigned to Priya Nair '
382
+ '(user-2) (+0.15)')
383
+ total_score += 0.15
384
+ else:
385
+ print(f'FAIL: case-2 expected Escalated+owner user-2, '
386
+ f"caseNumber=00001002 priority=High; found "
387
+ f"status={c2.get('status')} owner={c2.get('ownerId')} "
388
+ f"caseNumber={c2.get('caseNumber')} "
389
+ f"priority={c2.get('priority')}")
390
+ except Exception as e:
391
+ print(f'ERROR: Salesforce component — {e}')
392
+
393
+ # ============================================================
394
+ # Jira (0.25) — new engineering bug for the CSV-export defect
395
+ # ============================================================
396
+ try:
397
+ jira = states['jira']
398
+ init_issues = jira.get('initial_state', {}).get('issues', []) or []
399
+ cur_issues = jira.get('current_state', {}).get('issues', []) or []
400
+ init_ids = {i.get('id') for i in init_issues}
401
+ # New issues = present in current but not in initial
402
+ new_issues = [i for i in cur_issues if i.get('id') not in init_ids]
403
+
404
+ # Identify the SUP project id(s)
405
+ projects = jira.get('current_state', {}).get('projects', []) or []
406
+ sup_pids = {p.get('id') for p in projects
407
+ if str(p.get('key', '')).upper() == 'SUP'}
408
+
409
+ match = None
410
+ for iss in new_issues:
411
+ in_sup = (iss.get('projectId') in sup_pids
412
+ or norm(iss.get('key')).startswith('sup'))
413
+ is_bug = norm(iss.get('type')) == 'bug'
414
+ is_high = norm(iss.get('priority')) == 'high'
415
+ assigned = iss.get('assigneeId') == 'u_eng'
416
+ text = issue_text(iss)
417
+ names_customer = contains_all(text, ('brightwave',))
418
+ if (in_sup and is_bug and is_high and assigned and names_customer
419
+ and is_csv_empty_problem(text)):
420
+ match = iss
421
+ break
422
+
423
+ if match:
424
+ print(f"PASS: new SUP Bug (High) for CSV defect filed and assigned "
425
+ f"to Raj Patel — {match.get('key')} (+0.25)")
426
+ total_score += 0.25
427
+ else:
428
+ # Diagnostic: report best partial match for feedback
429
+ print('FAIL: no NEW SUP Bug matching all criteria '
430
+ '(project SUP, type Bug, High priority, assignee u_eng, '
431
+ 'text names Brightwave Media and the empty CSV export defect)')
432
+ for iss in new_issues:
433
+ print(f" candidate new issue: key={iss.get('key')} "
434
+ f"type={iss.get('type')} priority={iss.get('priority')} "
435
+ f"assignee={iss.get('assigneeId')} "
436
+ f"project={iss.get('projectId')}")
437
+ except Exception as e:
438
+ print(f'ERROR: Jira component — {e}')
439
+
440
+ # ============================================================
441
+ # Notion (0.25) — shared SLA tracker under Daily Triage
442
+ # ============================================================
443
+ try:
444
+ notion = states['notion']
445
+ init_pages = notion.get('initial_state', {}).get('pages', {}) or {}
446
+ cur_pages = notion.get('current_state', {}).get('pages', {}) or {}
447
+
448
+ # Locate the parent 'Daily Triage' page id
449
+ triage_id = None
450
+ for pid, pg in cur_pages.items():
451
+ if norm(pg.get('title')) == 'daily triage':
452
+ triage_id = pid
453
+ break
454
+
455
+ # Find a NEW database titled 'Support SLA Tracker'
456
+ db = None
457
+ for pid, pg in cur_pages.items():
458
+ if pid in init_pages:
459
+ continue # must be newly created
460
+ title_norm = norm(pg.get('title'))
461
+ is_tracker_title = (
462
+ 'support sla tracker' in title_norm
463
+ or ('sla' in title_norm and 'tracker' in title_norm)
464
+ )
465
+ if norm(pg.get('type')) == 'database' and is_tracker_title:
466
+ db = pg
467
+ break
468
+
469
+ # Component 3a: DB exists, under Daily Triage, has columns + >=5 rows
470
+ if db is not None:
471
+ prop_names = prop_defs_text(db)
472
+ has_customer = contains_any(prop_names, ('customer', 'account'))
473
+ has_case = contains_any(prop_names, ('case number', 'case #', 'case no', 'case'))
474
+ has_priority = contains_any(prop_names, ('priority', 'severity'))
475
+ has_sla = contains_any(prop_names, ('sla status', 'sla', 'status', 'breach'))
476
+ has_owner = contains_any(prop_names, ('owner', 'assignee', 'assigned'))
477
+ has_action = contains_any(prop_names, ('action', 'next step', 'follow up', 'notes'))
478
+ cols_ok = all([has_customer, has_case, has_priority, has_sla,
479
+ has_owner, has_action])
480
+ rows = row_pages(db, cur_pages)
481
+ represented_cases = {
482
+ spec['case_id']
483
+ for spec in EXPECTED_CASES
484
+ if any(row_matches_case(row, spec) for row in rows)
485
+ }
486
+ under_triage = (triage_id is not None
487
+ and db.get('parentId') == triage_id)
488
+ rows_ok = len(rows) >= 5 and len(represented_cases) == 5
489
+ if cols_ok and rows_ok and under_triage:
490
+ print(f'PASS: "Support SLA Tracker" database under Daily Triage '
491
+ f'with required columns and {len(rows)} case rows (+0.13)')
492
+ total_score += 0.13
493
+ else:
494
+ print(f'FAIL: tracker structure incomplete — cols_ok={cols_ok} '
495
+ f'rows={len(rows)} represented_cases={len(represented_cases)}/5 '
496
+ f'under_triage={under_triage}')
497
+ else:
498
+ print('FAIL: no NEW database titled "Support SLA Tracker" found')
499
+
500
+ # Component 3b: breached rows marked Breached; on-track not breached
501
+ if db is not None:
502
+ rows = row_pages(db, cur_pages)
503
+ matched = {}
504
+ breached_ok = True
505
+ ontrack_ok = True
506
+ priority_ok = True
507
+ owner_hint_ok = True
508
+ for spec in EXPECTED_CASES:
509
+ row = next((r for r in rows if row_matches_case(r, spec)), None)
510
+ if row is None:
511
+ continue
512
+ matched[spec['case_id']] = row
513
+ blob = page_blob(row)
514
+ priority_ok = priority_ok and contains_any(blob, (spec['priority'],))
515
+ owner_hint_ok = owner_hint_ok and (
516
+ spec['owner_id'] in blob or contains_any(blob, spec['owner_terms'])
517
+ )
518
+ row_is_breached = is_breached_status(status_blob(row, db))
519
+ if spec['breached']:
520
+ breached_ok = breached_ok and row_is_breached
521
+ else:
522
+ ontrack_ok = ontrack_ok and not row_is_breached
523
+
524
+ if (len(matched) == 5 and breached_ok and ontrack_ok
525
+ and priority_ok and owner_hint_ok):
526
+ print('PASS: both breached rows (Helios, Brightwave) marked '
527
+ 'Breached; all five rows keep case priority/owner context '
528
+ 'and on-track rows are not flagged (+0.12)')
529
+ total_score += 0.12
530
+ else:
531
+ print(f'FAIL: SLA marking — matched_cases={len(matched)}/5 '
532
+ f'breached_ok={breached_ok} ontrack_clean={ontrack_ok} '
533
+ f'priority_ok={priority_ok} owner_hint_ok={owner_hint_ok}')
534
+ except Exception as e:
535
+ print(f'ERROR: Notion component — {e}')
536
+
537
+ # ============================================================
538
+ # Slack (0.20) — triage digest in #support
539
+ # ============================================================
540
+ try:
541
+ slack = states['slack']
542
+ init_msgs = slack.get('initial_state', {}).get('messages', {}) or {}
543
+ cur_msgs = slack.get('current_state', {}).get('messages', {}) or {}
544
+ init_support = support_messages({'messages': init_msgs,
545
+ 'channels': slack.get('initial_state', {}).get('channels', [])})
546
+ cur_support = support_messages({'messages': cur_msgs,
547
+ 'channels': slack.get('current_state', {}).get('channels', [])})
548
+
549
+ new_support = new_by_id(cur_support, init_support, 'messageId')
550
+ if not new_support and len(cur_support) > len(init_support):
551
+ new_support = cur_support[len(init_support):]
552
+
553
+ digest_ok = False
554
+ for m in new_support:
555
+ content = m.get('content', '')
556
+ names_both = (
557
+ contains_all(content, ('helios',))
558
+ or contains_any(content, ('payment declined', 'eu cards', 'checkout payment'))
559
+ ) and (
560
+ contains_all(content, ('brightwave',))
561
+ or contains_any(content, ('csv export', 'empty csv', '0 byte csv'))
562
+ )
563
+ says_escalated = contains_any(content, (
564
+ 'escalated', 'escalation', 'raised', 'elevated',
565
+ 'routed', 'assigned to', 'handed off',
566
+ ))
567
+ refs_ticket = bool(re.search(r'\bSUP\s*[-#]?\s*\d+\b', content, re.I)) \
568
+ or contains_any(content, ('jira', 'sup ticket', 'engineering ticket',
569
+ 'support engineering ticket'))
570
+ if names_both and says_escalated and refs_ticket:
571
+ digest_ok = True
572
+ break
573
+
574
+ if digest_ok:
575
+ print('PASS: new #support digest names both breached cases, states '
576
+ 'escalation, and references the engineering ticket (+0.20)')
577
+ total_score += 0.20
578
+ else:
579
+ if not new_support:
580
+ print('FAIL: no new message posted in #support')
581
+ else:
582
+ print('FAIL: new #support message(s) found but do not satisfy '
583
+ 'digest criteria (name both breached cases + escalation + '
584
+ 'ticket reference)')
585
+ except Exception as e:
586
+ print(f'ERROR: Slack component — {e}')
587
+
588
+ final_score = round(min(total_score, 1.0), 4)
589
+ print(f'\nScore: {total_score}/1.0')
590
+ print(f'REWARD: {final_score}')
591
+ return final_score
592
+
593
+
594
+ verify_task()
csops_sla_queue_triage_003/reward_label.json ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/csops_sla_queue_triage_004/reward.py",
3
+ "api_url": "http://28.7.184.184:8000/v1/chat/completions",
4
+ "model": "Kimi-K2.6",
5
+ "max_code_chars": 100000,
6
+ "created_at": "2026-07-03 20:25:55",
7
+ "label": {
8
+ "task_id": "csops_sla_queue_triage_003",
9
+ "domain": "mock_websites",
10
+ "summary": "对跨 Salesforce、Jira、Notion、Slack 四个 mock 服务的 SLA 支持队列分类任务进行评分,验证是否正确升级两个 breached case、提交工程 bug、创建共享追踪数据库并发布 triage 摘要",
11
+ "is_placeholder": false,
12
+ "data_sources": [
13
+ "/tmp/task_web_sid",
14
+ "salesforce_mock",
15
+ "jira_mock",
16
+ "notion_mock",
17
+ "slack_mock"
18
+ ],
19
+ "scoring_components": [
20
+ {
21
+ "name": "Salesforce Component 1a",
22
+ "weight": 0.15,
23
+ "description": "验证 case-1 (Helios payment) 被正确升级并分配给指定负责人",
24
+ "check_logic": "从 salesforce current_state 的 cases 列表中获取 case-1,检查 norm(status) == 'escalated'、ownerId == 'user-3' 且 caseNumber/priority 与 EXPECTED_CASES[0] 一致;若 on-track case (3/4/5) 任一被升级,则整个 Salesforce 部分被置零",
25
+ "pass_condition": "case-1 状态为 Escalated,ownerId 为 user-3,且 on-track cases 均未被升级"
26
+ },
27
+ {
28
+ "name": "Salesforce Component 1b",
29
+ "weight": 0.15,
30
+ "description": "验证 case-2 (Brightwave CSV) 被正确升级并分配给指定负责人",
31
+ "check_logic": "从 salesforce current_state 的 cases 列表中获取 case-2,检查 norm(status) == 'escalated'、ownerId == 'user-2' 且 caseNumber/priority 与 EXPECTED_CASES[1] 一致;受同一 GATE 约束",
32
+ "pass_condition": "case-2 状态为 Escalated,ownerId 为 user-2,且 on-track cases 均未被升级"
33
+ },
34
+ {
35
+ "name": "Jira Component 2",
36
+ "weight": 0.25,
37
+ "description": "验证在 SUP 项目中新建了一个针对 Brightwave CSV 空导出缺陷的工程 Bug",
38
+ "check_logic": "对比 initial_state 与 current_state 的 issues,筛选出 id 为新的 issue;检查其 projectId 属于 SUP 项目(或 key 以 sup 开头)、type 为 Bug、priority 为 High、assigneeId 为 u_eng、summary/description 包含 Brightwave 且符合 is_csv_empty_problem(提及 csv/export 与 empty/blank/0 byte 等)",
39
+ "pass_condition": "存在一个新的 SUP 项目 Bug,优先级 High,分配给 u_eng,文本提及 Brightwave 且描述 CSV 空导出缺陷"
40
+ },
41
+ {
42
+ "name": "Notion Component 3a",
43
+ "weight": 0.13,
44
+ "description": "验证在 Daily Triage 页面下新建了 Support SLA Tracker 数据库,具备必要列且包含全部 5 个 case",
45
+ "check_logic": "在 notion current_state 的 pages 中查找 parentId 为 Daily Triage 页面、type 为 database 且标题包含 support sla tracker 的新建数据库;检查 properties 包含 customer/account、case number、priority/severity、sla status/breach、owner/assignee、action/next step 等列;通过 row_pages 获取行数 >=5 且 5 个 EXPECTED_CASES 均被 row_matches_case 匹配到",
46
+ "pass_condition": "新建 Support SLA Tracker 数据库位于 Daily Triage 下,具备 6 类必要列,且至少有 5 行分别对应 5 个 case"
47
+ },
48
+ {
49
+ "name": "Notion Component 3b",
50
+ "weight": 0.12,
51
+ "description": "验证数据库中 breached 行被标记为 Breached,on-track 行未被错误标记,且保留优先级与负责人信息",
52
+ "check_logic": "遍历数据库各行,通过 row_matches_case 匹配到 5 个 case;对每行使用 status_blob 提取 SLA 相关文本,用 is_breached_status 判断:breached cases 必须为 breached 状态,on-track cases 必须不为 breached;同时检查每行文本包含对应 priority 及 owner_id/owner_terms",
53
+ "pass_condition": "5 个 case 全部匹配到,两个 breached case 行标记为 Breached,三个 on-track case 行未标记为 Breached,且所有行保留 priority 与 owner 上下文"
54
+ },
55
+ {
56
+ "name": "Slack Component 4",
57
+ "weight": 0.2,
58
+ "description": "验证在 #support 频道发布了新的 triage digest,提及两个 breached 客户、说明已升级并引用工程工单",
59
+ "check_logic": "对比 slack initial_state 与 current_state 的 #support 频道消息,通过 messageId 识别新消息;检查消息内容:同时提及 Helios(或 payment declined/eu cards/checkout payment)与 Brightwave(或 csv export/empty csv/0 byte csv);包含 escalated/escalation/raised/elevated/routed/assigned to/handed off 等升级表述;引用工程工单(匹配 SUP-#digits 或包含 jira/sup ticket/engineering ticket)",
60
+ "pass_condition": "#support 存在新消息,同时命名两个 breached 客户、声明已升级并引用工程 ticket"
61
+ }
62
+ ],
63
+ "total_max_score": 1.0,
64
+ "score_aggregation": "各组件分数累加,最终通过 round(min(total_score, 1.0), 4) 计算并输出,上限钳制在 1.0",
65
+ "failure_modes": [
66
+ "读取 /tmp/task_web_sid 失败或为空时,打印 CRITICAL 并直接返回 0.0",
67
+ "任一 mock 状态 fetch 返回 None 时,打印 CRITICAL 并直接返回 0.0",
68
+ "Salesforce 的 GATE:若 case-3/4/5 任一状态被升级为 Escalated,则 Salesforce 两个组件均不得分(总分扣 0.30)",
69
+ "Jira 中未找到符合全部条件的新 issue,则该 0.25 分不得",
70
+ "Notion 中未找到新建的 Support SLA Tracker 数据库,则 3a 与 3b 均不得分",
71
+ "Slack 中 #support 无新消息或新消息不满足 digest 条件,则 0.20 分不得",
72
+ "各组件内部异常被 try/except 捕获,打印 ERROR 但不影响其他组件评分"
73
+ ],
74
+ "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话标识,然后依次向 salesforce、jira、notion、slack 四个 mock 的 /go 端点拉取 current_state 与 initial_state。若 sid 读取失败或任一 mock 拉取失败,立即返回 0.0。随后按顺序执行四个大模块:1) Salesforce:检查 case-1 与 case-2 是否升级为 Escalated 且 owner 正确,同时设置 GATE——若 on-track case 被错误升级则整个 Salesforce 0 分;2) Jira:找出新增 issue,验证其属于 SUP 项目、类型 Bug、优先级 High、分配给 u_eng、提及 Brightwave 且描述 CSV 空导出问题;3) Notion:查找 Daily Triage 下新建的 Support SLA Tracker 数据库,验证列结构完整且包含 5 行 case(3a),再验证 breached 行标记为 Breached、on-track 行未标记且保留 priority/owner(3b);4) Slack:提取 #support 频道新消息,验证内容同时提及两个 breached 客户、说明已升级并引用工程 ticket。各模块通过则累加对应分数,最终取 min(total, 1.0) 并四舍五入到 4 位小数输出。",
75
+ "confidence": 1.0
76
+ },
77
+ "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出分析结果。\n\n让我仔细阅读代码并提取关键信息:\n\n1. **Task ID**: 从 docstring 中可以看到 `Task ID: csops_sla_queue_triage_004`\n2. **Domain**: `Domain: mock_websites (salesforce, jira, notion, slack)`\n3. **Summary**: 这是一个跨多个 mock 服务的 SLA 支持队列分类任务评分脚本\n4. **is_placeholder**: false,因为脚本有详细的评分逻辑\n5. **data_sources**: \n - `/tmp/task_web_sid` (读取 sid)\n - `salesforce` mock (http://28.7.186.212:8175)\n - `jira` mock (http://28.7.186.212:8153)\n - `notion` mock (http://28.7.186.212:8166)\n - `slack` mock (http://28.7.186.212:8178)\n\n6. **Scoring components**:\n - Salesforce (0.30 total):\n - Component 1a: case-1 escalated + owner user-3 (0.15)\n - Component 1b: case-2 escalated + owner user-2 (0.15)\n - GATE: on-track cases must NOT be escalated (否则 Salesforce 0 分)\n - Jira (0.25): new SUP Bug, High priority, assignee u_eng, mentions Brightwave, CSV empty problem\n - Notion (0.25 total):\n - Component 3a: NEW database 'Support SLA Tracker' under 'Daily Triage' with required columns and >=5 rows (0.13)\n - Component 3b: breached rows marked Breached, on-track not breached, priority/owner hints preserved (0.12)\n - Slack (0.20): NEW message in #support naming both breached customers, says escalated, references engineering ticket\n\n7. **Score aggregation**: 各组件分数相加,最后 `round(min(total_score, 1.0), 4)`\n\n8. **Failure modes**:\n - 读取 sid 失败 -> 0.0\n - 任何 mock 状态获取失败 -> 0.0\n - on-track case 被错误 escalate -> Salesforce 部分 0 分\n - 各组件内部异常会被捕获并打印,但不影响其他组件\n\n9. **Scoring logic explanation**: 需要详细描述执行顺序和逻辑\n\n10. **Confidence**: 1.0 (代码非常清晰)\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"csops_sla_queue_triage_004\",\n \"domain\": \"mock_websites\",\n \"summary\": \"对跨 Salesforce、Jira、Notion、Slack 四个 mock 服务的 SLA 支持队列分类任务进行评分,验证是否正确升级两个 breached case、提交工程 bug、创建共享追踪数据库并发布 triage 摘要\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"salesforce_mock\", \"jira_mock\", \"notion_mock\", \"slack_mock\"],\n ...\n}\n```\n\n等等,data_sources 应该更具体,按照要求写 mock 服务的地址或标识。代码中 MOCKS 定义了具体的 URL,但通常我们写标识符即可。让我看看要求:\"如 slack_mock、github_mock、salesforce_mock、/tmp/task_web_sid 等\"。我会写具体的 mock 名称。\n\n对于 scoring_components,我需要列出每个组件。Salesforce 实际上有 3 个检查点(1a, 1b, gate),但 gate 是惩罚性的。让我看看怎么组织:\n\n- Component 1: Salesforce case-1 升级 (0.15)\n- Component 2: Salesforce case-2 升级 (0.15) \n- Component 3: Jira 新建 Bug (0.25)\n- Component 4: Notion 数据库结构 (0.13)\n- Component 5: Notion SLA 标记 (0.12)\n- Component 6: Slack 消息 (0.20)\n\n但是 gate 怎么办?gate 会导致 Salesforce 部分归零。我可以在 Component 1 或单独说明。让我把 Salesforce 拆成两个组件,并在 check_logic 中说明 gate。\n\n实际上,仔细看代码:\n```python\nif not ontrack_clean:\n print('GATE FAIL...')\nelse:\n if c1_ok: total_score += 0.15\n if c2_ok: total_score += 0.15\n```\n\n所以 gate 失败会导致两个 case 的分数都拿不到。我可以:\n- 写两个组件,每个 0.15,在 check_logic 中说明\"若 on-track case 被错误升级,则整个 Salesforce 部分得 0 分\"\n- 或者把 Salesforce 作为一个整体组件 0.30\n\n我觉得拆成两个组件更清晰,但 gate 是共享的。让我看看 weight 字段的要求:\"weight 字段填写代码中显式给出的分值(如 0.3)\"。代码中显式给出的是 0.15 和 0.15。\n\n让我这样组织:\n\nComponent 1: Salesforce case-1 升级验证 (0.15)\nComponent 2: Salesforce case-2 升级验证 (0.15)\nComponent 3: Jira 新建工程 Bug (0.25)\nComponent 4: Notion 追踪数据库结构与内容 (0.13)\nComponent 5: Notion SLA 状态标记 (0.12)\nComponent 6: Slack 分类摘要消息 (0.20)\n\n对于 Component 1 和 2,在 check_logic 中说明 gate 条件。\n\nFailure modes:\n- /tmp/task_web_sid 读取失败 -> 0.0\n- 任一 mock 状态获取失败 -> 0.0\n- on-track case 被错误升级 -> Salesforce 0 分\n- 无新消息/新 issue/新数据库 -> 对应组件失败\n\nScore aggregation: 各组件分数累加,最终 `round(min(total_score, 1.0), 4)`\n\n让我再仔细检查一下 Notion 的 Component 3b 逻辑:\n- 需要 matched 5 个 cases\n- breached_ok: breached cases 必须标记为 breached\n- ontrack_ok: on-track cases 必须 NOT 标记为 breached\n- priority_ok: 所有行包含对应 priority\n- owner_hint_ok: 所有行包含 owner_id 或 owner_terms\n\nSlack 的 check:\n- new_support 消息\n- names_both: Helios (或 payment declined/eu cards/checkout payment) AND Brightwave (或 csv export/empty csv/0 byte csv)\n- says_escalated: escalated/escalation/raised/elevated/routed/assigned to/handed off\n- refs_ticket: SUP-#digits 或 jira/sup ticket/engineering ticket/support engineering ticket\n\nJira 的 check:\n- new issue (id 不在 initial)\n- projectId 在 sup_pids 中 或 key 以 sup 开头\n- type == 'bug'\n- priority == 'high'\n- assigneeId == 'u_eng'\n- text 包含 'brightwave'\n- is_csv_empty_problem: 包含 csv/comma separated/report export/reports export 且包含 empty/blank/0 byte 等\n\n好的,我现在可以构建完整的 JSON 了。\n\n注意:用户要求\"不要输出 Markdown 代码块标记,不要输出额外解释,不要输出思考过程,不要输出 thinking 标签。输出的第一个字符必须是 {,最后一个字符必须是 }。\"\n\n所以我直接输出 JSON。\n\n让我确保所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样。\n\ndata_sources 列表:我会写 [\"salesforce_mock\", \"jira_mock\", \"notion_mock\", \"slack_mock\", \"/tmp/task_web_sid\"]\n\n等等,代码中 MOCKS 的 URL 是 http://28.7.186.212:8175 等。我应该写 URL 还是名称?要求说:\"如 slack_mock、github_mock、salesforce_mock、/tmp/task_web_sid 等\"。我写标识符加 URL 可能更好,但格式是字符串列表。我写 [\"salesforce_mock (http://28.7.186.212:8195)\", ...] 或者就写 [\"salesforce_mock\", \"jira_mock\", \"notion_mock\", \"slack_mock\", \"/tmp/task_web_sid\"]。我觉得写 mock 名称即可。\n\n再检查一下 total_max_score: 1.0\n\nconfidence: 1.0\n\n让我写 JSON 内容。 </think> {\n \"task_id\": \"csops_sla_queue_triage_004\",\n \"domain\": \"mock_websites\",\n \"summary\": \"对跨 Salesforce、Jira、Notion、Slack 四个 mock 服务的 SLA 支持队列分类任务进行评分,验证是否正确升级两个 breached case、提交工程 bug、创建共享追踪数据库并发布 triage 摘要\",\n \"is_placeholder\": false,\n \"data_sources\": [\n \"/tmp/task_web_sid\",\n \"salesforce_mock\",\n \"jira_mock\",\n \"notion_mock\",\n \"slack_mock\"\n ],\n \"scoring_components\": [\n {\n \"name\": \"Salesforce Component 1a\",\n \"weight\": 0.15,\n \"description\": \"验证 case-1 (Helios payment) 被正确升级并分配给指定负责人\",\n \"check_logic\": \"从 salesforce current_state 的 cases 列表中获取 case-1,检查 norm(status) == 'escalated'、ownerId == 'user-3' 且 caseNumber/priority 与 EXPECTED_CASES[0] 一致;若 on-track case (3/4/5) 任一被升级,则整个 Salesforce 部分被置零\",\n \"pass_condition\": \"case-1 状态为 Escalated,ownerId 为 user-3,且 on-track cases 均未被升级\"\n },\n {\n \"name\": \"Salesforce Component 1b\",\n \"weight\": 0.15,\n \"description\": \"验证 case-2 (Brightwave CSV) 被正确升级并分配给指定负责人\",\n \"check_logic\": \"从 salesforce current_state 的 cases 列表中获取 case-2,检查 norm(status) == 'escalated'、ownerId == 'user-2' 且 caseNumber/priority 与 EXPECTED_CASES[1] 一致;受同一 GATE 约束\",\n \"pass_condition\": \"case-2 状态为 Escalated,ownerId 为 user-2,且 on-track cases 均未被升级\"\n },\n {\n \"name\": \"Jira Component 2\",\n \"weight\": 0.25,\n \"description\": \"验证在 SUP 项目中新建了一个针对 Brightwave CSV 空导出缺陷的工程 Bug\",\n \"check_logic\": \"对比 initial_state 与 current_state 的 issues,筛选出 id 为新的 issue;检查其 projectId 属于 SUP 项目(或 key 以 sup 开头)、type 为 Bug、priority 为 High、assigneeId 为 u_eng、summary/description 包含 Brightwave 且符合 is_csv_empty_problem(提及 csv/export 与 empty/blank/0 byte 等)\",\n \"pass_condition\": \"存在一个新的 SUP 项目 Bug,优先级 High,分配给 u_eng,文本提及 Brightwave 且描述 CSV 空导出缺陷\"\n },\n {\n \"name\": \"Notion Component 3a\",\n \"weight\": 0.13,\n \"description\": \"验证在 Daily Triage 页面下新建了 Support SLA Tracker 数据库,具备必要列且包含全部 5 个 case\",\n \"check_logic\": \"在 notion current_state 的 pages 中查找 parentId 为 Daily Triage 页面、type 为 database 且标题包含 support sla tracker 的新建数据库;检查 properties 包含 customer/account、case number、priority/severity、sla status/breach、owner/assignee、action/next step 等列;通过 row_pages 获取行数 >=5 且 5 个 EXPECTED_CASES 均被 row_matches_case 匹配到\",\n \"pass_condition\": \"新建 Support SLA Tracker 数据库位于 Daily Triage 下,具备 6 类必要列,且至少有 5 行分别对应 5 个 case\"\n },\n {\n \"name\": \"Notion Component 3b\",\n \"weight\": 0.12,\n \"description\": \"验证数据库中 breached 行被标记为 Breached,on-track 行未被错误标记,且保留优先级与负责人信息\",\n \"check_logic\": \"遍历数据库各行,通过 row_matches_case 匹配到 5 个 case;对每行使用 status_blob 提取 SLA 相关文本,用 is_breached_status 判断:breached cases 必须为 breached 状态,on-track cases 必须不为 breached;同时检查每行文本包含对应 priority 及 owner_id/owner_terms\",\n \"pass_condition\": \"5 个 case 全部匹配到,两个 breached case 行标记为 Breached,三个 on-track case 行未标记为 Breached,且所有行保留 priority 与 owner 上下文\"\n },\n {\n \"name\": \"Slack Component 4\",\n \"weight\": 0.2,\n \"description\": \"验证在 #support 频道发布了新的 triage digest,提及两个 breached 客户、说明已升级并引用工程工单\",\n \"check_logic\": \"对比 slack initial_state 与 current_state 的 #support 频道消息,通过 messageId 识别新消息;检查消息内容:同时提及 Helios(或 payment declined/eu cards/checkout payment)与 Brightwave(或 csv export/empty csv/0 byte csv);包含 escalated/escalation/raised/elevated/routed/assigned to/handed off 等升级表述;引用工程工单(匹配 SUP-#digits 或包含 jira/sup ticket/engineering ticket)\",\n \"pass_condition\": \"#support 存在新消息,同时命名两个 breached 客户、声明已升级并引用工程 ticket\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数累加,最终通过 round(min(total_score, 1.0), 4) 计算并输出,上限钳制在 1.0\",\n \"failure_modes\": [\n \"读取 /tmp/task_web_sid 失败或为空时,打印 CRITICAL 并直接返回 0.0\",\n \"任一 mock 状态 fetch 返回 None 时,打印 CRITICAL 并直接返回 0.0\",\n \"Salesforce 的 GATE:若 case-3/4/5 任一状态被升级为 Escalated,则 Salesforce 两个组件均不得分(总分扣 0.30)\",\n \"Jira 中未找到符合全部条件的新 issue,则该 0.25 分不得\",\n \"Notion 中未找到新建的 Support SLA Tracker 数据库,则 3a 与 3b 均不得分\",\n \"Slack 中 #support 无新消息或新消息不满足 digest 条件,则 0.20 分不得\",\n \"各组件内部异常被 try/except 捕获,打印 ERROR 但不影响其他组件评分\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话标识,然后依次向 salesforce、jira、notion、slack 四个 mock 的 /go 端点拉取 current_state 与 initial_state。若 sid 读取失败或任一 mock 拉取失败,立即返回 0.0。随后按顺序执行四个大模块:1) Salesforce:检查 case-1 与 case-2 是否升级为 Escalated 且 owner 正确,同时设置 GATE——若 on-track case 被错误升级则整个 Salesforce 0 分;2) Jira:找出新增 issue,验证其属于 SUP 项目、类型 Bug、优先级 High、分配给 u_eng、提及 Brightwave 且描述 CSV 空导出问题;3) Notion:查找 Daily Triage 下新建的 Support SLA Tracker 数据库,验证列结构完整且包含 5 行 case(3a),再验证 breached 行标记为 Breached、on-track 行未标记且保留 priority/owner(3b);4) Slack:提取 #support 频道新消息,验证内容同时提及两个 breached 客户、说明已升级并引用工程 ticket。各模块通过则累加对应分数,最终取 min(total, 1.0) 并四舍五入到 4 位小数输出。\",\n \"confidence\": 1.0\n}"
78
+ }
fin_expense_claim_001__long__cond/.PLACEHOLDER ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ This directory is intentionally empty.
2
+ It exists only to satisfy start_our_benchmark_test.sh's uniform
3
+ 'cache_dir/<tid>/ must exist' precheck. Non-mock tasks do not use
4
+ cua_gym cache; their evaluators read a vm_file tarball instead.
5
+ See docs/0716_迁移执行日志.md § S15 for details.
fin_expense_claim_001__long__cond/19c19c59-8dab-5287-9f11-546056a463b0_oa_server.py ADDED
@@ -0,0 +1,779 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ TechCorp Expense Reimbursement System - Fake OA Server
4
+ ======================================================
5
+ A single-file, zero-dependency web server for OSWorld condition-branch tasks.
6
+
7
+ Usage:
8
+ python3 oa_server.py --user zhang_wei --role employee --port 8765
9
+ python3 oa_server.py --user li_ming --role intern --port 8765
10
+
11
+ All submitted data is persisted to DATA_DIR (default: /home/user/oa_data/).
12
+ """
13
+
14
+ import argparse
15
+ import json
16
+ import os
17
+ import re
18
+ import sys
19
+ import time
20
+ from http.server import HTTPServer, BaseHTTPRequestHandler
21
+ from urllib.parse import urlparse, parse_qs
22
+
23
+
24
+ # --- Multipart Form Data Parser (replaces deprecated cgi module) ---
25
+
26
+ class UploadedFile:
27
+ """Represents an uploaded file from multipart form data."""
28
+ def __init__(self, filename, data):
29
+ self.filename = filename
30
+ self.data = data
31
+
32
+ def read(self):
33
+ return self.data
34
+
35
+
36
+ def parse_multipart(body, boundary):
37
+ """
38
+ Parse multipart/form-data body into a dict.
39
+ Returns: {field_name: value_or_UploadedFile_or_list}
40
+ For file fields: value is UploadedFile (or list of UploadedFile)
41
+ For text fields: value is string (or list of strings)
42
+ """
43
+ result = {}
44
+ # Boundary comes as string, body is bytes
45
+ if isinstance(boundary, str):
46
+ boundary = boundary.encode()
47
+
48
+ # Split by boundary
49
+ delimiter = b"--" + boundary
50
+ parts = body.split(delimiter)
51
+
52
+ for part in parts:
53
+ # Skip preamble and epilogue
54
+ if part in (b"", b"--", b"--\r\n", b"\r\n"):
55
+ continue
56
+ if part.startswith(b"--"):
57
+ continue
58
+
59
+ # Strip leading \r\n
60
+ if part.startswith(b"\r\n"):
61
+ part = part[2:]
62
+
63
+ # Split headers from body
64
+ header_end = part.find(b"\r\n\r\n")
65
+ if header_end == -1:
66
+ continue
67
+
68
+ header_data = part[:header_end].decode("utf-8", errors="replace")
69
+ file_data = part[header_end + 4:]
70
+
71
+ # Remove trailing \r\n from file_data
72
+ if file_data.endswith(b"\r\n"):
73
+ file_data = file_data[:-2]
74
+
75
+ # Parse Content-Disposition header
76
+ name = None
77
+ filename = None
78
+ for line in header_data.split("\r\n"):
79
+ if line.lower().startswith("content-disposition"):
80
+ # Extract name
81
+ name_match = re.search(r'name="([^"]*)"', line)
82
+ if name_match:
83
+ name = name_match.group(1)
84
+ # Extract filename
85
+ filename_match = re.search(r'filename="([^"]*)"', line)
86
+ if filename_match:
87
+ filename = filename_match.group(1)
88
+
89
+ if name is None:
90
+ continue
91
+
92
+ # Determine if this is a file upload or text field
93
+ if filename is not None:
94
+ # File field (could be empty filename for no file selected)
95
+ if filename:
96
+ value = UploadedFile(filename, file_data)
97
+ else:
98
+ continue # Skip empty file fields
99
+ else:
100
+ # Text field
101
+ value = file_data.decode("utf-8", errors="replace")
102
+
103
+ # Append to result (support multiple values for same name)
104
+ if name in result:
105
+ existing = result[name]
106
+ if isinstance(existing, list):
107
+ existing.append(value)
108
+ else:
109
+ result[name] = [existing, value]
110
+ else:
111
+ result[name] = value
112
+
113
+ return result
114
+
115
+ # --- Configuration ---
116
+ DEFAULT_PORT = 8765
117
+ DATA_DIR = os.environ.get("OA_DATA_DIR", "/home/user/oa_data")
118
+
119
+ # --- HTML Templates ---
120
+
121
+ HOMEPAGE_HTML = """<!DOCTYPE html>
122
+ <html lang="en">
123
+ <head>
124
+ <meta charset="UTF-8">
125
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
126
+ <title>TechCorp Expense Reimbursement System</title>
127
+ <style>
128
+ * { margin: 0; padding: 0; box-sizing: border-box; }
129
+ body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #f0f2f5; color: #333; }
130
+ .header { background: linear-gradient(135deg, #1a237e, #283593); color: white; padding: 12px 40px; box-shadow: 0 2px 8px rgba(0,0,0,0.15); }
131
+ .header h1 { font-size: 22px; font-weight: 600; }
132
+ .header .subtitle { font-size: 13px; opacity: 0.85; margin-top: 2px; }
133
+ .container { max-width: 900px; margin: 16px auto; padding: 0 20px; }
134
+ .welcome-card { background: white; border-radius: 8px; padding: 14px 28px; margin-bottom: 12px; box-shadow: 0 1px 4px rgba(0,0,0,0.08); display: flex; align-items: center; gap: 12px; }
135
+ .welcome-card h2 { color: #1a237e; margin-bottom: 0; font-size: 18px; }
136
+ .welcome-card .role-badge { display: inline-block; padding: 4px 14px; border-radius: 12px; font-size: 13px; font-weight: 600; letter-spacing: 0.3px; }
137
+ .welcome-card .role-badge.employee { background: #1a237e; color: #fff; }
138
+ .welcome-card .role-badge.intern { background: #00796b; color: #fff; }
139
+ .guide-card { background: white; border-radius: 8px; padding: 16px 28px; margin-bottom: 12px; box-shadow: 0 1px 4px rgba(0,0,0,0.08); }
140
+ .guide-card h3 { color: #1a237e; margin-bottom: 8px; font-size: 16px; }
141
+ .guide-card ol { padding-left: 22px; line-height: 1.6; font-size: 14px; }
142
+ .guide-card li { margin-bottom: 2px; }
143
+ .guide-card .note { background: #fff3e0; border-left: 4px solid #ff9800; padding: 8px 14px; margin-top: 10px; border-radius: 4px; font-size: 13px; }
144
+ .guide-card .warning { background: #fce4ec; border-left: 4px solid #e53935; padding: 8px 14px; margin-top: 8px; border-radius: 4px; font-size: 13px; }
145
+ .portals { display: flex; gap: 20px; justify-content: center; margin-bottom: 12px; background: white; border-radius: 8px; padding: 16px 28px; box-shadow: 0 1px 4px rgba(0,0,0,0.08); }
146
+ .portal-btn { display: inline-flex; align-items: center; gap: 8px; padding: 14px 36px; border-radius: 8px; font-size: 16px; font-weight: 600; text-decoration: none; cursor: pointer; transition: all 0.2s; border: none; }
147
+ .portal-btn.employee { background: #1a237e; color: white; }
148
+ .portal-btn.employee:hover { background: #283593; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(26,35,126,0.3); }
149
+ .portal-btn.intern { background: #00695c; color: white; }
150
+ .portal-btn.intern:hover { background: #00796b; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,105,92,0.3); }
151
+ .modal-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; justify-content: center; align-items: center; }
152
+ .modal-overlay.active { display: flex; }
153
+ .modal { background: white; border-radius: 12px; padding: 32px; max-width: 480px; width: 90%; box-shadow: 0 8px 32px rgba(0,0,0,0.2); text-align: center; }
154
+ .modal .icon { font-size: 48px; margin-bottom: 16px; }
155
+ .modal h3 { color: #c62828; margin-bottom: 12px; }
156
+ .modal p { color: #555; line-height: 1.6; margin-bottom: 20px; }
157
+ .modal button { background: #c62828; color: white; border: none; padding: 10px 24px; border-radius: 6px; font-size: 14px; cursor: pointer; }
158
+ .modal button:hover { background: #b71c1c; }
159
+ </style>
160
+ </head>
161
+ <body>
162
+ <div class="header">
163
+ <h1>&#127970; TechCorp Expense Reimbursement System</h1>
164
+ <div class="subtitle">Internal Finance Portal</div>
165
+ </div>
166
+ <div class="container">
167
+ <div class="welcome-card">
168
+ <h2>Welcome, {display_name}</h2>
169
+ <span class="role-badge {role}">{role_label}</span>
170
+ </div>
171
+ <div class="portals">
172
+ <button class="portal-btn employee" onclick="tryPortal('employee')">&#128188; Employee Portal</button>
173
+ <button class="portal-btn intern" onclick="tryPortal('intern')">&#127891; Intern Portal</button>
174
+ </div>
175
+ <div class="guide-card">
176
+ <h3>&#128203; How to Submit a Reimbursement</h3>
177
+ <ol>
178
+ <li><strong>Choose the portal that matches your role</strong></li>
179
+ <li><strong>Upload your invoice files</strong> (PDF or image format)</li>
180
+ <li><strong>Fill in the details:</strong> total amount, expense category, and a brief description</li>
181
+ <li><strong>If your total amount exceeds &yen;1,000:</strong>
182
+ <ul style="list-style: none; padding-left: 16px; margin-top: 4px;">
183
+ <li>&#8226; You must provide a written justification (at least 20 characters)</li>
184
+ <li>&#8226; You must upload a manager-approved report (PDF)</li>
185
+ </ul>
186
+ </li>
187
+ <li><strong>(Interns only)</strong> Provide your mentor's ID and department approval code</li>
188
+ <li><strong>Click "Submit Reimbursement"</strong></li>
189
+ </ol>
190
+ <div class="note">&#128161; <strong>Tip:</strong> Have all your documents ready before starting. You can find invoice files and any required documents in your designated folder.</div>
191
+ </div>
192
+ </div>
193
+
194
+ <div class="modal-overlay" id="warningModal">
195
+ <div class="modal">
196
+ <div class="icon">&#9888;&#65039;</div>
197
+ <h3>Access Denied</h3>
198
+ <p id="warningMsg"></p>
199
+ <button onclick="closeModal()">OK, I understand</button>
200
+ </div>
201
+ </div>
202
+
203
+ <script>
204
+ var USER_ROLE = "{role}";
205
+ function tryPortal(portal) {
206
+ if (portal !== USER_ROLE) {
207
+ var roleLabel = USER_ROLE === 'employee' ? 'a Full-time Employee' : 'an Intern';
208
+ var correctPortal = USER_ROLE === 'employee' ? 'Employee Portal' : 'Intern Portal';
209
+ document.getElementById('warningMsg').textContent =
210
+ 'You are logged in as ' + roleLabel + '. Please use the ' + correctPortal + ' instead.';
211
+ document.getElementById('warningModal').classList.add('active');
212
+ } else {
213
+ window.location.href = '/form?portal=' + portal;
214
+ }
215
+ }
216
+ function closeModal() {
217
+ document.getElementById('warningModal').classList.remove('active');
218
+ }
219
+ </script>
220
+ </body>
221
+ </html>"""
222
+
223
+ FORM_HTML = """<!DOCTYPE html>
224
+ <html lang="en">
225
+ <head>
226
+ <meta charset="UTF-8">
227
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
228
+ <title>Reimbursement Form - TechCorp</title>
229
+ <style>
230
+ * { margin: 0; padding: 0; box-sizing: border-box; }
231
+ body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #f0f2f5; color: #333; }
232
+ .header { background: linear-gradient(135deg, #1a237e, #283593); color: white; padding: 20px 40px; box-shadow: 0 2px 8px rgba(0,0,0,0.15); }
233
+ .header h1 { font-size: 24px; font-weight: 600; }
234
+ .breadcrumb { font-size: 13px; opacity: 0.8; margin-top: 4px; }
235
+ .breadcrumb a { color: white; text-decoration: underline; }
236
+ .container { max-width: 720px; margin: 30px auto; padding: 0 20px; }
237
+ .form-card { background: white; border-radius: 8px; padding: 32px; box-shadow: 0 1px 4px rgba(0,0,0,0.08); }
238
+ .form-card h2 { color: #1a237e; margin-bottom: 24px; font-size: 20px; }
239
+ .form-group { margin-bottom: 20px; }
240
+ .form-group label { display: block; font-weight: 600; margin-bottom: 6px; font-size: 14px; }
241
+ .form-group label .required { color: #c62828; }
242
+ .form-group input[type="text"],
243
+ .form-group input[type="number"],
244
+ .form-group textarea,
245
+ .form-group select { width: 100%; padding: 10px 14px; border: 1px solid #ccc; border-radius: 6px; font-size: 14px; transition: border-color 0.2s; }
246
+ .form-group input:focus, .form-group textarea:focus, .form-group select:focus { border-color: #1a237e; outline: none; box-shadow: 0 0 0 2px rgba(26,35,126,0.1); }
247
+ .form-group textarea { resize: vertical; min-height: 80px; }
248
+ .form-group input[type="file"] { padding: 8px; }
249
+ .form-group .help-text { font-size: 12px; color: #777; margin-top: 4px; }
250
+ .section-divider { border: none; border-top: 1px solid #e0e0e0; margin: 24px 0; }
251
+ .intern-section { background: #e0f2f1; border: 1px solid #80cbc4; border-radius: 8px; padding: 20px; margin-bottom: 20px; }
252
+ .intern-section h3 { color: #00695c; margin-bottom: 12px; font-size: 16px; }
253
+ .high-value-section { background: #fff3e0; border: 1px solid #ffb74d; border-radius: 8px; padding: 20px; margin-bottom: 20px; display: none; }
254
+ .high-value-section.visible { display: block; }
255
+ .high-value-section h3 { color: #e65100; margin-bottom: 12px; font-size: 16px; }
256
+ .submit-btn { background: #1a237e; color: white; border: none; padding: 14px 32px; border-radius: 8px; font-size: 16px; font-weight: 600; cursor: pointer; width: 100%; margin-top: 16px; transition: all 0.2s; }
257
+ .submit-btn:hover { background: #283593; transform: translateY(-1px); box-shadow: 0 4px 12px rgba(26,35,126,0.3); }
258
+ .error-msg { color: #c62828; font-size: 13px; margin-top: 4px; display: none; }
259
+ .error-msg.visible { display: block; }
260
+ .form-error-banner { background: #fce4ec; border: 1px solid #ef9a9a; border-radius: 8px; padding: 16px; margin-bottom: 20px; display: none; }
261
+ .form-error-banner.visible { display: block; }
262
+ .form-error-banner p { color: #c62828; font-size: 14px; }
263
+ </style>
264
+ </head>
265
+ <body>
266
+ <div class="header">
267
+ <h1>&#127970; TechCorp Expense Reimbursement System</h1>
268
+ <div class="breadcrumb"><a href="/">Home</a> &rarr; {portal_label} &rarr; Reimbursement Form</div>
269
+ </div>
270
+ <div class="container">
271
+ <div class="form-card">
272
+ <h2>&#128221; Expense Reimbursement Form</h2>
273
+ <p style="margin-bottom: 20px; color: #555;">Logged in as: <strong>{display_name}</strong> ({role_label})</p>
274
+
275
+ <div class="form-error-banner" id="errorBanner">
276
+ <p id="errorBannerMsg">&#9888;&#65039; Please fix the errors below before submitting.</p>
277
+ </div>
278
+
279
+ <form id="reimbursementForm" action="/submit" method="POST" enctype="multipart/form-data">
280
+ <input type="hidden" name="portal_used" value="{portal}">
281
+
282
+ <div class="form-group">
283
+ <label>Invoice Files <span class="required">*</span></label>
284
+ <input type="file" name="invoices" id="invoices" multiple accept=".pdf,.png,.jpg,.jpeg">
285
+ <div class="help-text">Upload your invoice files (PDF or image). You can select multiple files.</div>
286
+ <div class="error-msg" id="err-invoices">Please upload at least one invoice file.</div>
287
+ </div>
288
+
289
+ <div class="form-group">
290
+ <label>Total Amount (&yen;) <span class="required">*</span></label>
291
+ <input type="number" name="amount" id="amount" step="0.01" min="0.01" placeholder="e.g. 605.00" oninput="checkAmount()">
292
+ <div class="help-text">Enter the combined total of all invoices.</div>
293
+ <div class="error-msg" id="err-amount">Please enter a valid amount greater than 0.</div>
294
+ </div>
295
+
296
+ <div class="form-group">
297
+ <label>Expense Category <span class="required">*</span></label>
298
+ <select name="category" id="category">
299
+ <option value="">-- Select a category --</option>
300
+ <option value="Transportation">Transportation</option>
301
+ <option value="Meals">Meals</option>
302
+ <option value="Office Supplies">Office Supplies</option>
303
+ <option value="Training">Training</option>
304
+ <option value="Other">Other</option>
305
+ </select>
306
+ <div class="error-msg" id="err-category">Please select a category.</div>
307
+ </div>
308
+
309
+ <div class="form-group">
310
+ <label>Description <span class="required">*</span></label>
311
+ <input type="text" name="description" id="description" placeholder="Brief description of the expense">
312
+ <div class="error-msg" id="err-description">Please enter a description.</div>
313
+ </div>
314
+
315
+ {intern_section}
316
+
317
+ <div class="high-value-section" id="highValueSection">
318
+ <h3>&#9888;&#65039; High-Value Expense (Amount exceeds &yen;1,000)</h3>
319
+ <p style="margin-bottom: 16px; font-size: 14px; color: #555;">Additional documentation is required for expenses over &yen;1,000.</p>
320
+
321
+ <div class="form-group">
322
+ <label>Justification Statement <span class="required">*</span></label>
323
+ <textarea name="justification" id="justification" placeholder="Explain why this expense is necessary (at least 20 characters)"></textarea>
324
+ <div class="help-text">Minimum 20 characters. Explain the business necessity of this expense.</div>
325
+ <div class="error-msg" id="err-justification">Justification must be at least 20 characters.</div>
326
+ </div>
327
+
328
+ <div class="form-group">
329
+ <label>Approval Report <span class="required">*</span></label>
330
+ <input type="file" name="approval_report" id="approval_report" accept=".pdf">
331
+ <div class="help-text">Upload the manager-signed approval document (PDF only).</div>
332
+ <div class="error-msg" id="err-approval">Please upload the approval report.</div>
333
+ </div>
334
+ </div>
335
+
336
+ <button type="submit" class="submit-btn" onclick="return validateForm()">Submit Reimbursement</button>
337
+ </form>
338
+ </div>
339
+ </div>
340
+
341
+ <script>
342
+ function checkAmount() {
343
+ var amount = parseFloat(document.getElementById('amount').value);
344
+ var section = document.getElementById('highValueSection');
345
+ if (amount > 1000) {
346
+ section.classList.add('visible');
347
+ } else {
348
+ section.classList.remove('visible');
349
+ }
350
+ }
351
+
352
+ function validateForm() {
353
+ var valid = true;
354
+ var errors = [];
355
+
356
+ // Reset all error messages
357
+ document.querySelectorAll('.error-msg').forEach(function(el) { el.classList.remove('visible'); });
358
+ document.getElementById('errorBanner').classList.remove('visible');
359
+
360
+ // Check invoices
361
+ var invoices = document.getElementById('invoices');
362
+ if (!invoices.files || invoices.files.length === 0) {
363
+ document.getElementById('err-invoices').classList.add('visible');
364
+ valid = false;
365
+ errors.push('Invoice files are required');
366
+ }
367
+
368
+ // Check amount
369
+ var amount = parseFloat(document.getElementById('amount').value);
370
+ if (isNaN(amount) || amount <= 0) {
371
+ document.getElementById('err-amount').classList.add('visible');
372
+ valid = false;
373
+ errors.push('Valid amount is required');
374
+ }
375
+
376
+ // Check category
377
+ if (!document.getElementById('category').value) {
378
+ document.getElementById('err-category').classList.add('visible');
379
+ valid = false;
380
+ errors.push('Category is required');
381
+ }
382
+
383
+ // Check description
384
+ if (!document.getElementById('description').value.trim()) {
385
+ document.getElementById('err-description').classList.add('visible');
386
+ valid = false;
387
+ errors.push('Description is required');
388
+ }
389
+
390
+ // Check intern fields if present
391
+ var mentorField = document.getElementById('mentor_id');
392
+ if (mentorField) {
393
+ if (!mentorField.value.trim()) {
394
+ document.getElementById('err-mentor').classList.add('visible');
395
+ valid = false;
396
+ errors.push('Mentor ID is required');
397
+ }
398
+ var deptCode = document.getElementById('dept_approval_code');
399
+ if (!deptCode.value.trim()) {
400
+ document.getElementById('err-deptcode').classList.add('visible');
401
+ valid = false;
402
+ errors.push('Department approval code is required');
403
+ }
404
+ }
405
+
406
+ // Check high-value fields if amount > 1000
407
+ if (amount > 1000) {
408
+ var justification = document.getElementById('justification').value.trim();
409
+ if (justification.length < 20) {
410
+ document.getElementById('err-justification').classList.add('visible');
411
+ valid = false;
412
+ errors.push('Justification must be at least 20 characters');
413
+ }
414
+ var approvalReport = document.getElementById('approval_report');
415
+ if (!approvalReport.files || approvalReport.files.length === 0) {
416
+ document.getElementById('err-approval').classList.add('visible');
417
+ valid = false;
418
+ errors.push('Approval report is required for amounts over 1000');
419
+ }
420
+ }
421
+
422
+ if (!valid) {
423
+ var banner = document.getElementById('errorBanner');
424
+ document.getElementById('errorBannerMsg').textContent = '\\u26a0\\ufe0f ' + errors.join('; ') + '. Please fix before submitting.';
425
+ banner.classList.add('visible');
426
+ banner.scrollIntoView({ behavior: 'smooth' });
427
+ }
428
+
429
+ return valid;
430
+ }
431
+ </script>
432
+ </body>
433
+ </html>"""
434
+
435
+ INTERN_SECTION_HTML = """
436
+ <hr class="section-divider">
437
+ <div class="intern-section">
438
+ <h3>&#128218; Intern Additional Information</h3>
439
+ <p style="margin-bottom: 16px; font-size: 14px; color: #555;">As an intern, you need to provide the following additional details.</p>
440
+
441
+ <div class="form-group">
442
+ <label>Mentor ID <span class="required">*</span></label>
443
+ <input type="text" name="mentor_id" id="mentor_id" placeholder="e.g. EMP-20180042">
444
+ <div class="help-text">Enter your mentor's employee ID as shown in your internship agreement.</div>
445
+ <div class="error-msg" id="err-mentor">Please enter your mentor's ID.</div>
446
+ </div>
447
+
448
+ <div class="form-group">
449
+ <label>Department Approval Code <span class="required">*</span></label>
450
+ <input type="text" name="dept_approval_code" id="dept_approval_code" placeholder="e.g. DEPT-2026-0517">
451
+ <div class="help-text">Your department approval code (format: DEPT-XXXX). Check your approval documents.</div>
452
+ <div class="error-msg" id="err-deptcode">Please enter the department approval code.</div>
453
+ </div>
454
+ </div>
455
+ """
456
+
457
+ SUCCESS_HTML = """<!DOCTYPE html>
458
+ <html lang="en">
459
+ <head>
460
+ <meta charset="UTF-8">
461
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
462
+ <title>Submission Successful - TechCorp</title>
463
+ <style>
464
+ * { margin: 0; padding: 0; box-sizing: border-box; }
465
+ body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #f0f2f5; color: #333; }
466
+ .header { background: linear-gradient(135deg, #1a237e, #283593); color: white; padding: 20px 40px; box-shadow: 0 2px 8px rgba(0,0,0,0.15); }
467
+ .header h1 { font-size: 24px; font-weight: 600; }
468
+ .container { max-width: 720px; margin: 30px auto; padding: 0 20px; }
469
+ .success-card { background: white; border-radius: 8px; padding: 40px 32px; box-shadow: 0 1px 4px rgba(0,0,0,0.08); text-align: center; }
470
+ .success-icon { font-size: 64px; margin-bottom: 16px; }
471
+ .success-card h2 { color: #2e7d32; margin-bottom: 12px; }
472
+ .success-card .ref-number { background: #e8f5e9; display: inline-block; padding: 8px 20px; border-radius: 20px; font-family: monospace; font-size: 16px; color: #1b5e20; margin: 12px 0; }
473
+ .details-table { margin: 24px auto; text-align: left; border-collapse: collapse; width: 80%; }
474
+ .details-table td { padding: 8px 12px; border-bottom: 1px solid #eee; font-size: 14px; }
475
+ .details-table td:first-child { font-weight: 600; color: #555; width: 40%; }
476
+ .back-link { display: inline-block; margin-top: 24px; color: #1a237e; text-decoration: none; font-weight: 500; }
477
+ .back-link:hover { text-decoration: underline; }
478
+ </style>
479
+ </head>
480
+ <body>
481
+ <div class="header">
482
+ <h1>&#127970; TechCorp Expense Reimbursement System</h1>
483
+ </div>
484
+ <div class="container">
485
+ <div class="success-card">
486
+ <div class="success-icon">&#9989;</div>
487
+ <h2>Reimbursement Submitted Successfully!</h2>
488
+ <div class="ref-number">{reference_number}</div>
489
+ <table class="details-table">
490
+ <tr><td>Amount:</td><td>&yen;{amount}</td></tr>
491
+ <tr><td>Category:</td><td>{category}</td></tr>
492
+ <tr><td>Description:</td><td>{description}</td></tr>
493
+ <tr><td>Invoice Files:</td><td>{invoice_count} file(s) uploaded</td></tr>
494
+ <tr><td>Status:</td><td><span style="color: #2e7d32; font-weight: 600;">Pending Review</span></td></tr>
495
+ </table>
496
+ <p style="margin-top: 20px; color: #555; font-size: 14px;">Your submission has been recorded and is awaiting review.</p>
497
+ <a href="/" class="back-link">&larr; Back to Home</a>
498
+ </div>
499
+ </div>
500
+ </body>
501
+ </html>"""
502
+
503
+
504
+ class OARequestHandler(BaseHTTPRequestHandler):
505
+ """HTTP request handler for the OA reimbursement system."""
506
+
507
+ def log_message(self, format, *args):
508
+ """Override to log to stderr with timestamp."""
509
+ sys.stderr.write("[%s] %s\n" % (
510
+ time.strftime("%Y-%m-%d %H:%M:%S"), format % args))
511
+
512
+ def do_GET(self):
513
+ parsed = urlparse(self.path)
514
+ path = parsed.path
515
+
516
+ if path == "/" or path == "":
517
+ self._serve_homepage()
518
+ elif path == "/form":
519
+ params = parse_qs(parsed.query)
520
+ portal = params.get("portal", [""])[0]
521
+ self._serve_form(portal)
522
+ else:
523
+ self._send_404()
524
+
525
+ def do_POST(self):
526
+ parsed = urlparse(self.path)
527
+ if parsed.path == "/submit":
528
+ self._handle_submit()
529
+ else:
530
+ self._send_404()
531
+
532
+ def _serve_homepage(self):
533
+ """Serve the homepage with guide and portal buttons."""
534
+ user_config = self.server.user_config
535
+ role = user_config["role"]
536
+ display_name = user_config["display_name"]
537
+
538
+ if role == "employee":
539
+ role_label = "Full-time Employee"
540
+ else:
541
+ role_label = "Intern"
542
+
543
+ html = HOMEPAGE_HTML.replace(
544
+ "{display_name}", display_name
545
+ ).replace(
546
+ "{role_label}", role_label
547
+ ).replace(
548
+ "{role}", role
549
+ )
550
+ self._send_html(html)
551
+
552
+ def _serve_form(self, portal):
553
+ """Serve the reimbursement form."""
554
+ user_config = self.server.user_config
555
+ role = user_config["role"]
556
+ display_name = user_config["display_name"]
557
+
558
+ if role == "employee":
559
+ role_label = "Full-time Employee"
560
+ else:
561
+ role_label = "Intern"
562
+
563
+ if portal == "employee":
564
+ portal_label = "Employee Portal"
565
+ else:
566
+ portal_label = "Intern Portal"
567
+
568
+ # Determine if intern section should be shown
569
+ intern_section = ""
570
+ if portal == "intern":
571
+ intern_section = INTERN_SECTION_HTML
572
+
573
+ html = FORM_HTML.replace(
574
+ "{display_name}", display_name
575
+ ).replace(
576
+ "{role_label}", role_label
577
+ ).replace(
578
+ "{portal_label}", portal_label
579
+ ).replace(
580
+ "{portal}", portal
581
+ ).replace(
582
+ "{intern_section}", intern_section
583
+ )
584
+ self._send_html(html)
585
+
586
+ def _handle_submit(self):
587
+ """Handle form submission: save data + files to DATA_DIR."""
588
+ content_type = self.headers.get("Content-Type", "")
589
+ if "multipart/form-data" not in content_type:
590
+ self._send_error(400, "Invalid content type")
591
+ return
592
+
593
+ # Extract boundary from content-type header
594
+ boundary = None
595
+ for part in content_type.split(";"):
596
+ part = part.strip()
597
+ if part.startswith("boundary="):
598
+ boundary = part[len("boundary="):].strip('"')
599
+ break
600
+
601
+ if not boundary:
602
+ self._send_error(400, "Missing boundary in content type")
603
+ return
604
+
605
+ # Read request body
606
+ content_length = int(self.headers.get("Content-Length", 0))
607
+ body = self.rfile.read(content_length)
608
+
609
+ # Parse multipart form data
610
+ form = parse_multipart(body, boundary)
611
+
612
+ # Ensure data directory exists
613
+ os.makedirs(DATA_DIR, exist_ok=True)
614
+
615
+ # Extract form fields
616
+ portal_used = self._get_field(form, "portal_used", "")
617
+ amount_str = self._get_field(form, "amount", "0")
618
+ category = self._get_field(form, "category", "")
619
+ description = self._get_field(form, "description", "")
620
+ justification = self._get_field(form, "justification", "")
621
+ mentor_id = self._get_field(form, "mentor_id", "")
622
+ dept_approval_code = self._get_field(form, "dept_approval_code", "")
623
+
624
+ try:
625
+ amount = float(amount_str)
626
+ except (ValueError, TypeError):
627
+ amount = 0.0
628
+
629
+ # Save uploaded invoice files
630
+ invoice_files = []
631
+ if "invoices" in form:
632
+ invoices_field = form["invoices"]
633
+ if not isinstance(invoices_field, list):
634
+ invoices_field = [invoices_field]
635
+ for item in invoices_field:
636
+ if isinstance(item, UploadedFile) and item.filename:
637
+ filename = os.path.basename(item.filename)
638
+ filepath = os.path.join(DATA_DIR, filename)
639
+ with open(filepath, "wb") as f:
640
+ f.write(item.read())
641
+ invoice_files.append(filename)
642
+
643
+ # Save approval report if present
644
+ approval_report_filename = None
645
+ if "approval_report" in form:
646
+ ar_field = form["approval_report"]
647
+ if isinstance(ar_field, list):
648
+ ar_field = ar_field[0]
649
+ if isinstance(ar_field, UploadedFile) and ar_field.filename:
650
+ filename = os.path.basename(ar_field.filename)
651
+ filepath = os.path.join(DATA_DIR, filename)
652
+ with open(filepath, "wb") as f:
653
+ f.write(ar_field.read())
654
+ approval_report_filename = filename
655
+
656
+ # Build submission record
657
+ user_config = self.server.user_config
658
+ ref_number = "EXP-%s-%03d" % (
659
+ time.strftime("%Y%m%d"), int(time.time()) % 1000)
660
+
661
+ submission = {
662
+ "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
663
+ "user": user_config["user"],
664
+ "role": user_config["role"],
665
+ "portal_used": portal_used,
666
+ "amount": amount,
667
+ "category": category,
668
+ "description": description,
669
+ "justification": justification if justification else None,
670
+ "mentor_id": mentor_id if mentor_id else None,
671
+ "dept_approval_code": dept_approval_code if dept_approval_code else None,
672
+ "invoice_files": invoice_files,
673
+ "approval_report_filename": approval_report_filename,
674
+ "reference_number": ref_number,
675
+ "status": "submitted"
676
+ }
677
+
678
+ # Write submission.json
679
+ submission_path = os.path.join(DATA_DIR, "submission.json")
680
+ with open(submission_path, "w", encoding="utf-8") as f:
681
+ json.dump(submission, f, indent=2, ensure_ascii=False)
682
+
683
+ # Serve success page
684
+ html = SUCCESS_HTML.replace(
685
+ "{reference_number}", ref_number
686
+ ).replace(
687
+ "{amount}", "%.2f" % amount
688
+ ).replace(
689
+ "{category}", category
690
+ ).replace(
691
+ "{description}", description
692
+ ).replace(
693
+ "{invoice_count}", str(len(invoice_files))
694
+ )
695
+ self._send_html(html)
696
+
697
+ self.log_message("Submission saved: %s (amount=%.2f, invoices=%d)",
698
+ ref_number, amount, len(invoice_files))
699
+
700
+ def _get_field(self, form, name, default=""):
701
+ """Safely get a form field value from parsed multipart data."""
702
+ if name in form:
703
+ field = form[name]
704
+ if isinstance(field, list):
705
+ field = field[0]
706
+ if isinstance(field, UploadedFile):
707
+ return field.filename # For file fields, return filename
708
+ return str(field)
709
+ return default
710
+
711
+ def _send_html(self, html, status=200):
712
+ """Send an HTML response."""
713
+ encoded = html.encode("utf-8")
714
+ self.send_response(status)
715
+ self.send_header("Content-Type", "text/html; charset=utf-8")
716
+ self.send_header("Content-Length", str(len(encoded)))
717
+ self.end_headers()
718
+ self.wfile.write(encoded)
719
+
720
+ def _send_error(self, code, message):
721
+ """Send a simple error response."""
722
+ self._send_html("<h1>Error %d</h1><p>%s</p>" % (code, message), code)
723
+
724
+ def _send_404(self):
725
+ """Send 404 response."""
726
+ self._send_html("<h1>404 Not Found</h1><p>The requested page does not exist.</p>", 404)
727
+
728
+
729
+ def format_display_name(user_id):
730
+ """Convert user_id like 'zhang_wei' to 'Zhang Wei'."""
731
+ return " ".join(part.capitalize() for part in user_id.split("_"))
732
+
733
+
734
+ def main():
735
+ global DATA_DIR
736
+
737
+ parser = argparse.ArgumentParser(
738
+ description="TechCorp Expense Reimbursement System (Fake OA Server)")
739
+ parser.add_argument("--user", required=True,
740
+ help="User ID (e.g. zhang_wei)")
741
+ parser.add_argument("--role", required=True, choices=["employee", "intern"],
742
+ help="User role: employee or intern")
743
+ parser.add_argument("--port", type=int, default=DEFAULT_PORT,
744
+ help="Port to listen on (default: %d)" % DEFAULT_PORT)
745
+ parser.add_argument("--data-dir", default=DATA_DIR,
746
+ help="Directory to save submission data (default: %s)" % DATA_DIR)
747
+ args = parser.parse_args()
748
+
749
+ DATA_DIR = args.data_dir
750
+ os.makedirs(DATA_DIR, exist_ok=True)
751
+
752
+ # Configure server
753
+ server = HTTPServer(("0.0.0.0", args.port), OARequestHandler)
754
+ server.user_config = {
755
+ "user": args.user,
756
+ "role": args.role,
757
+ "display_name": format_display_name(args.user),
758
+ }
759
+
760
+ url = "http://localhost:%d/" % args.port
761
+
762
+ print("=" * 60)
763
+ print(" TechCorp Expense Reimbursement System")
764
+ print(" " + "-" * 56)
765
+ print(" User: %s (%s)" % (server.user_config["display_name"], args.role))
766
+ print(" Port: %d" % args.port)
767
+ print(" Data: %s" % DATA_DIR)
768
+ print(" URL: %s" % url)
769
+ print("=" * 60)
770
+ print("\nServer is running. Press Ctrl+C to stop.\n")
771
+ try:
772
+ server.serve_forever()
773
+ except KeyboardInterrupt:
774
+ print("\nShutting down server...")
775
+ server.shutdown()
776
+
777
+
778
+ if __name__ == "__main__":
779
+ main()
fin_expense_claim_001__long__cond/87712b8f-fa0d-5df1-8c79-dd0c877ab6a7_invoice_2.pdf ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ %PDF-1.3
2
+ %���� ReportLab Generated PDF document (opensource)
3
+ 1 0 obj
4
+ <<
5
+ /F1 2 0 R /F2 3 0 R /F3 4 0 R
6
+ >>
7
+ endobj
8
+ 2 0 obj
9
+ <<
10
+ /BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font
11
+ >>
12
+ endobj
13
+ 3 0 obj
14
+ <<
15
+ /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font
16
+ >>
17
+ endobj
18
+ 4 0 obj
19
+ <<
20
+ /BaseFont /Symbol /Name /F3 /Subtype /Type1 /Type /Font
21
+ >>
22
+ endobj
23
+ 5 0 obj
24
+ <<
25
+ /Contents 9 0 R /MediaBox [ 0 0 419.5276 595.2756 ] /Parent 8 0 R /Resources <<
26
+ /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
27
+ >> /Rotate 0 /Trans <<
28
+
29
+ >>
30
+ /Type /Page
31
+ >>
32
+ endobj
33
+ 6 0 obj
34
+ <<
35
+ /PageMode /UseNone /Pages 8 0 R /Type /Catalog
36
+ >>
37
+ endobj
38
+ 7 0 obj
39
+ <<
40
+ /Author (anonymous) /CreationDate (D:20260517171538+08'00') /Creator (anonymous) /Keywords () /ModDate (D:20260517171538+08'00') /Producer (ReportLab PDF Library - \(opensource\))
41
+ /Subject (unspecified) /Title (untitled) /Trapped /False
42
+ >>
43
+ endobj
44
+ 8 0 obj
45
+ <<
46
+ /Count 1 /Kids [ 5 0 R ] /Type /Pages
47
+ >>
48
+ endobj
49
+ 9 0 obj
50
+ <<
51
+ /Filter [ /ASCII85Decode /FlateDecode ] /Length 610
52
+ >>
53
+ stream
54
+ Gat=h95g=S'LqipMS#BZ)TNA)E-Kc&P>*,r_P2s)&9qelJXq*0C&WO?+c4;d<J@Z=Fch`GD>Y!]rZU6+[/cg,34g:u-kn`c.8$</$=AZ9e0tq@l4VL23ggP4;FDeVJQ"cC90]e;<T-Pk]X+ak4)GF3X%MWgmK40<T_LJX&;.5n?RCTH6Xh17L_D3_E.S[5JjKhrb7MZr<,:D=H.'YtMnY?;WBR;%JV9h^5ai!I.HWp=EeEfrI>S0bS`>"S)+HU/ZT5/_\YbaO2<KR#ns]<&G.u#&4Q+N.:+`i1.$N&IY[p-p+O9b,Z8]q^lUo!YZhM%3DP:?p4P-uqm@jQTc$l'')11Chg4&R``LKT!P\E`g_m[t8FKkEkjWKZ20%^TB\trY*?fk:hi5]^oCfk*fr92D""YqN'cLJDM=63pRpj?#r_:He13Wj9%o2jKBBs=QdgRIU?a#B1?e5B,-ZW%(kVB&2TFrlnQPb7t_IPL,RVOUNOKA`:#M6_agn!N:Em!,[%foZdX&rF`H8'ooD55(*f@eju$(s+lAZgj%toFZI$%B)`rS[1deA^`cY?5YV:A.<EM($&j.Nd>WdY'8#iJ+qZr)FY$bj=`+o8Rq~>endstream
55
+ endobj
56
+ xref
57
+ 0 10
58
+ 0000000000 65535 f
59
+ 0000000061 00000 n
60
+ 0000000112 00000 n
61
+ 0000000219 00000 n
62
+ 0000000331 00000 n
63
+ 0000000408 00000 n
64
+ 0000000611 00000 n
65
+ 0000000679 00000 n
66
+ 0000000940 00000 n
67
+ 0000000999 00000 n
68
+ trailer
69
+ <<
70
+ /ID
71
+ [<3c423d3a52fb79513e627cf7857e10c9><3c423d3a52fb79513e627cf7857e10c9>]
72
+ % ReportLab generated PDF document -- digest (opensource)
73
+
74
+ /Info 7 0 R
75
+ /Root 6 0 R
76
+ /Size 10
77
+ >>
78
+ startxref
79
+ 1699
80
+ %%EOF
fin_expense_claim_001__long__cond/8fc9101a-9ae0-52e6-9d9f-6cf7033d05ff_invoice_1.pdf ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ %PDF-1.3
2
+ %���� ReportLab Generated PDF document (opensource)
3
+ 1 0 obj
4
+ <<
5
+ /F1 2 0 R /F2 3 0 R /F3 4 0 R
6
+ >>
7
+ endobj
8
+ 2 0 obj
9
+ <<
10
+ /BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font
11
+ >>
12
+ endobj
13
+ 3 0 obj
14
+ <<
15
+ /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font
16
+ >>
17
+ endobj
18
+ 4 0 obj
19
+ <<
20
+ /BaseFont /Symbol /Name /F3 /Subtype /Type1 /Type /Font
21
+ >>
22
+ endobj
23
+ 5 0 obj
24
+ <<
25
+ /Contents 9 0 R /MediaBox [ 0 0 419.5276 595.2756 ] /Parent 8 0 R /Resources <<
26
+ /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
27
+ >> /Rotate 0 /Trans <<
28
+
29
+ >>
30
+ /Type /Page
31
+ >>
32
+ endobj
33
+ 6 0 obj
34
+ <<
35
+ /PageMode /UseNone /Pages 8 0 R /Type /Catalog
36
+ >>
37
+ endobj
38
+ 7 0 obj
39
+ <<
40
+ /Author (anonymous) /CreationDate (D:20260517171538+08'00') /Creator (anonymous) /Keywords () /ModDate (D:20260517171538+08'00') /Producer (ReportLab PDF Library - \(opensource\))
41
+ /Subject (unspecified) /Title (untitled) /Trapped /False
42
+ >>
43
+ endobj
44
+ 8 0 obj
45
+ <<
46
+ /Count 1 /Kids [ 5 0 R ] /Type /Pages
47
+ >>
48
+ endobj
49
+ 9 0 obj
50
+ <<
51
+ /Filter [ /ASCII85Decode /FlateDecode ] /Length 609
52
+ >>
53
+ stream
54
+ Gat=h95iT.&:j6K'm&/2=os>mVRPriaeb%HnY(_C/=YIlZ>n%@8b;D/+%^E0W@H'sTg='R"(iBHs087NC4OVJS6[gV#h]\i9Oc)W_NueliWr3fECK@Cc6`Z],YX%/"T!7?q5#sM17-bU?/sYO23!<*?"e<2IXpc$A06."i@q_+bD6FKLb-J8"B/3L@$De##W;)s+d=<>XFcr*8XBojpe(6*qP5SdOU;hU30=?+MEuB*KC99F'F;Fba)g5H,rA2W3A(-=7Z)4\"[gF=oD[(]O*Hft\F[A`$`sKQA@,sY9Sc=c\/9/X7_="GBXi*-]d^?nBGVl=9ke!^kl)F2?REk6d<M9X\+n06cB$eacSK>X["Aer^p=D4j/d,qaD#8#_[8#ef!`_<$/<U9gVVNcg+>pY.nNW)a5abR+7#Nm9t,nT>aFU_\8@acWr>eH9i3a<D;T;[UGA?C8gGjHjT+,d4mBo1UZ)=9p]$ReLq:Q-@-VCg3s?n.*LqJs1nE0Wk?(PBdU#6P3B?jI1cDfRI8imbg:niW&s&]5I,bHQ"Q+5-]$a%5)Jb5CWZGTPXmQ_*"?0?ril_ZKc/.T"kHp<LmYoU@#nhgQ0?#qC@K~>endstream
55
+ endobj
56
+ xref
57
+ 0 10
58
+ 0000000000 65535 f
59
+ 0000000061 00000 n
60
+ 0000000112 00000 n
61
+ 0000000219 00000 n
62
+ 0000000331 00000 n
63
+ 0000000408 00000 n
64
+ 0000000611 00000 n
65
+ 0000000679 00000 n
66
+ 0000000940 00000 n
67
+ 0000000999 00000 n
68
+ trailer
69
+ <<
70
+ /ID
71
+ [<1a1da6c4435a41804a3be76f63a50f95><1a1da6c4435a41804a3be76f63a50f95>]
72
+ % ReportLab generated PDF document -- digest (opensource)
73
+
74
+ /Info 7 0 R
75
+ /Root 6 0 R
76
+ /Size 10
77
+ >>
78
+ startxref
79
+ 1698
80
+ %%EOF
fin_expense_claim_001__long__cond/ef610de1-d103-514c-9ddd-9fda1b34d5c2_mentor_id_and_approval_code.xlsx ADDED
Binary file (4.97 kB). View file
 
hr_onboarding_003/_cua_gym_vm_bridge.sh ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # CUA-Gym VM-side network fix (direct-IP mock access).
3
+ #
4
+ # Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by
5
+ # their real IDC address (http://28.7.184.198:81xx) instead of the old
6
+ # localhost:9000-9097 socat bridge, so the VM only needs two fixes:
7
+ #
8
+ # 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's
9
+ # cluster DNS, which is unreachable from QEMU SLIRP NAT
10
+ # ("Temporary failure in name resolution").
11
+ # 2. The mock host excluded from the woa http proxy — otherwise the VM's
12
+ # Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403
13
+ # from the proxy when hitting 28.7.184.198:81xx. (The old socat path never
14
+ # hit this because localhost is bypassed by default.)
15
+ #
16
+ # Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic
17
+ # OSWorld setup pipeline.
18
+ #
19
+ # Argv:
20
+ # $1 optional sudo password (default "password"; SetupController
21
+ # substitutes {CLIENT_PASSWORD} when uploaded as a cache file).
22
+ # $2 unused (kept for backward compat — was socat first port 9000).
23
+ # $3 unused (kept for backward compat — was socat last port 9097).
24
+ # $4 optional mock host IP (default 28.7.184.198).
25
+
26
+ set +e
27
+
28
+ PASS="${1:-password}"
29
+ MOCK_HOST="${4:-28.7.184.198}"
30
+ # Derive the /16 IDC subnet so future port/host tweaks on the same segment
31
+ # stay bypassed too (28.7.184.198 -> 28.7.0.0/16).
32
+ MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')"
33
+
34
+ run_root() {
35
+ echo "$PASS" | sudo -S -p "" bash -c "$1"
36
+ }
37
+
38
+ # Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2.
39
+ GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')"
40
+ GW="${GW:-10.0.2.2}"
41
+
42
+ # ─── CUA-Gym network fix (Taiji-specific) ─────────────────────────────
43
+ fix_vm_network() {
44
+ # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP
45
+ # DNS forwarder. Nothing hardcoded except the mock host above.
46
+ local GW_NET="${GW%.*}"
47
+ local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3
48
+ local OWN_CIDR
49
+ OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \
50
+ | awk '{print $4; exit}')"
51
+ local OWN_IP="${OWN_CIDR%/*}"
52
+ local OWN_NET=""
53
+ [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24"
54
+
55
+ # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps
56
+ # systemd-resolved/NetworkManager from clobbering it.
57
+ if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf
58
+ chattr +i /etc/resolv.conf 2>/dev/null || true"; then
59
+ echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})"
60
+ else
61
+ echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf"
62
+ fi
63
+
64
+ # 2) Build the proxy bypass list from detected values + the direct-IP
65
+ # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx
66
+ # reachable from inside the VM — without it the woa proxy 403s it.
67
+ local ignore_list="['localhost', '127.0.0.0/8', '${GW}'"
68
+ [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'"
69
+ [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'"
70
+ [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'"
71
+ [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'"
72
+ [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'"
73
+ ignore_list="${ignore_list}]"
74
+
75
+ # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these.
76
+ if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then
77
+ echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}"
78
+ else
79
+ echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)"
80
+ fi
81
+
82
+ # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl).
83
+ local NP="localhost,127.0.0.1,${GW}"
84
+ [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}"
85
+ [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}"
86
+ [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24"
87
+ [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}"
88
+ [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}"
89
+
90
+ for var in no_proxy NO_PROXY; do
91
+ if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then
92
+ echo "export ${var}=${NP}" >> /home/user/.bashrc
93
+ fi
94
+ done
95
+ run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \
96
+ && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \
97
+ || echo 'no_proxy=\"${NP}\"' >> /etc/environment
98
+ grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \
99
+ && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \
100
+ || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1
101
+ echo "[cua_gym_vm_bridge] no_proxy=${NP}"
102
+ }
103
+
104
+ fix_vm_network
105
+
106
+ echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed"
hr_onboarding_003/initial_setup.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: HR onboarding for Priya Sharma — Gusto (Xusto) + Google Calendar.
3
+ Task ID: hr_onboarding_003
4
+ Domain: mock_websites (gusto[xusto=8218] + google_calendar[8161])
5
+
6
+ Real mocks used:
7
+ Gusto/Xusto (8218) — HR/payroll app. Priya Sharma exists as a NEW hire WITHOUT a
8
+ department assignment and with NO onboarding checklist yet.
9
+ Google Calendar (8161) — recruiter/HR calendar; NO 'Onboarding Check-in' event yet.
10
+
11
+ Pre-task invariants (so reward scores ONLY task-introduced deltas):
12
+ - Gusto: Priya Sharma employee record, department = "" (unassigned), status 'Onboarding';
13
+ onboardingChecklists has NO entry for Priya.
14
+ - Calendar: realistic events on other days; no recurring Onboarding Check-in.
15
+ """
16
+ import os
17
+ import shlex
18
+ import subprocess
19
+ import time
20
+ import uuid
21
+
22
+ import requests
23
+
24
+ GUSTO_URL = 'http://28.7.184.198:8147' # "Xusto — HR, Payroll & Benefits" (Gusto clone)
25
+ CALENDAR_URL = 'http://28.7.184.198:8141'
26
+
27
+ sid = str(uuid.uuid4())
28
+ with open('/tmp/task_web_sid', 'w') as f:
29
+ f.write(sid)
30
+ print(f'Generated session ID: {sid}')
31
+
32
+
33
+ # =====================================================================
34
+ # Gusto/Xusto — minimal HR state with Priya as an unassigned new hire.
35
+ # =====================================================================
36
+ def build_gusto_state():
37
+ company = {"id": "comp_1", "name": "Horizon Tech Solutions",
38
+ "legalName": "Horizon Tech Solutions, LLC", "ein": "12-3456789",
39
+ "industry": "Technology", "entityType": "LLC",
40
+ "phone": "(415) 555-0192", "email": "hr@horizontech.com",
41
+ "locations": [
42
+ {"id": "loc_1", "name": "HQ - San Francisco",
43
+ "address": {"street1": "742 Innovation Drive", "street2": "Suite 300",
44
+ "city": "San Francisco", "state": "CA", "zip": "94107"},
45
+ "isMain": True},
46
+ ],
47
+ "departments": [
48
+ {"id": "dept_1", "name": "Engineering", "headcount": 1},
49
+ {"id": "dept_2", "name": "Sales", "headcount": 1},
50
+ {"id": "dept_3", "name": "Marketing", "headcount": 1},
51
+ {"id": "dept_4", "name": "Operations", "headcount": 1},
52
+ {"id": "dept_5", "name": "Finance", "headcount": 0},
53
+ ]}
54
+ current_user = {"id": "emp_hr", "firstName": "Jessica", "lastName": "Jackson",
55
+ "name": "Jessica Jackson", "email": "jessica.jackson@horizontech.com",
56
+ "role": "admin", "department": "Operations", "jobTitle": "HR Director"}
57
+
58
+ def emp(eid, first, last, dept, deptid, title, start, status="Active"):
59
+ return {
60
+ "id": eid, "firstName": first, "lastName": last, "middleName": "",
61
+ "email": f"{first.lower()}.{last.lower()}@horizontech.com",
62
+ "personalEmail": f"{first.lower()}.{last.lower()}@gmail.com",
63
+ "phone": "(415) 555-0100", "dateOfBirth": "1990-01-01", "ssn": "***-**-0000",
64
+ "address": {"street1": "1 Main St", "street2": "", "city": "San Francisco",
65
+ "state": "CA", "zip": "94105"},
66
+ "department": dept, "departmentId": deptid, "jobTitle": title,
67
+ "managerId": None, "managerName": None, "employmentType": "Full-time",
68
+ "compensation": {"type": "Salary", "amount": 120000, "per": "Year"},
69
+ "startDate": start, "status": status, "location": "HQ - San Francisco",
70
+ "locationId": "loc_1", "payMethod": "Direct Deposit",
71
+ "federalFilingStatus": "Single", "stateFilingStatus": "Single",
72
+ "allowances": 0, "benefits": [],
73
+ "pto": {"vacationBalance": 0, "sickBalance": 0,
74
+ "vacationAccrualRate": 6.67, "sickAccrualRate": 3.33},
75
+ "avatar": "",
76
+ }
77
+
78
+ employees = [
79
+ current_user | {"middleName": "", "personalEmail": "jessica.j@gmail.com",
80
+ "phone": "(415) 555-0101", "dateOfBirth": "1988-06-15",
81
+ "ssn": "***-**-1234",
82
+ "address": {"street1": "123 Market St", "street2": "Apt 4B",
83
+ "city": "San Francisco", "state": "CA", "zip": "94105"},
84
+ "departmentId": "dept_4", "employmentType": "Full-time",
85
+ "compensation": {"type": "Salary", "amount": 125000, "per": "Year"},
86
+ "startDate": "2019-03-15", "status": "Active",
87
+ "location": "HQ - San Francisco", "locationId": "loc_1",
88
+ "payMethod": "Direct Deposit", "federalFilingStatus": "Single",
89
+ "stateFilingStatus": "Single", "allowances": 0, "benefits": [],
90
+ "pto": {"balance": 80, "used": 0}, "avatar": ""},
91
+ emp("emp_eng1", "Alex", "Morgan", "Engineering", "dept_1", "Senior Engineer", "2021-05-01"),
92
+ emp("emp_sales1", "Sam", "Lee", "Sales", "dept_2", "Account Executive", "2022-02-01"),
93
+ emp("emp_mkt1", "Dana", "Cruz", "Marketing", "dept_3", "Marketing Specialist", "2023-09-01"),
94
+ # --- The new hire: NO department yet, onboarding status ---
95
+ emp("emp_priya", "Priya", "Sharma", "", "", "Marketing Manager", "2026-07-06",
96
+ status="Onboarding"),
97
+ ]
98
+
99
+ return {
100
+ "company": company,
101
+ "currentUser": current_user,
102
+ "employees": employees,
103
+ "contractors": [],
104
+ "payrolls": [],
105
+ "timeEntries": [],
106
+ "timeOffRequests": [],
107
+ "benefitPlans": [],
108
+ "taxForms": [],
109
+ "documents": [],
110
+ "todoItems": [],
111
+ "onboardingChecklists": [],
112
+ "performanceReviews": [],
113
+ "companyHolidays": [],
114
+ "notifications": [],
115
+ "reportHistory": [],
116
+ "referrals": [],
117
+ }
118
+
119
+
120
+ # =====================================================================
121
+ # Google Calendar — no Onboarding Check-in event yet.
122
+ # =====================================================================
123
+ def build_calendar_state():
124
+ return {
125
+ "user": {"id": "u1", "username": "Jessica Jackson",
126
+ "email": "jessica.jackson@horizontech.com",
127
+ "avatar": "https://picsum.photos/100/100?random=user1"},
128
+ "calendars": [
129
+ {"id": "c1", "name": "Personal", "color": "#039BE5", "visible": True,
130
+ "userId": "u1", "isDefault": True},
131
+ {"id": "c2", "name": "Work", "color": "#33B679", "visible": True,
132
+ "userId": "u1", "isDefault": False},
133
+ ],
134
+ "events": [
135
+ {"id": "evt_001", "calendarId": "c2", "title": "HR Staff Meeting",
136
+ "start": "2026-07-01T14:00:00.000Z", "end": "2026-07-01T15:00:00.000Z",
137
+ "allDay": False, "location": "Conference Room B", "description": "Weekly HR sync",
138
+ "guests": [], "color": "#33B679", "recurring": "weekly",
139
+ "reminders": [{"type": "popup", "minutes": 10}], "meetLink": "", "status": "confirmed"},
140
+ ],
141
+ "view": "week",
142
+ "currentDate": "2026-07-06T00:00:00.000Z",
143
+ "sidebarOpen": True,
144
+ "settings": {"weekStart": 0, "defaultDuration": 60, "defaultView": "week",
145
+ "defaultReminder": {"type": "popup", "minutes": 10}, "timeFormat": "12h",
146
+ "showWeekNumbers": False, "showDeclinedEvents": False},
147
+ }
148
+
149
+
150
+ # =====================================================================
151
+ # Inject baseline state (action: "set")
152
+ # =====================================================================
153
+ mocks = [
154
+ ("Gusto", GUSTO_URL, build_gusto_state()),
155
+ ("Calendar", CALENDAR_URL, build_calendar_state()),
156
+ ]
157
+ for name, url, state in mocks:
158
+ print(f'Injecting initial state into {name} mock...')
159
+ resp = requests.post(f'{url}/post?sid={sid}', json={'action': 'set', 'state': state}, timeout=30)
160
+ assert resp.status_code == 200, f'{name} state injection failed: {resp.status_code} {resp.text}'
161
+ for name, url, _ in mocks:
162
+ go = requests.get(f'{url}/go?sid={sid}', timeout=15).json()
163
+ assert go.get('initial_state'), f'{name} initial_state is None after injection'
164
+ assert go.get('current_state'), f'{name} current_state is None after injection'
165
+ print(f'States injected + verified: sid={sid}')
166
+
167
+
168
+ # =====================================================================
169
+ # Launch GUI (Chrome) with DISPLAY=:0
170
+ # =====================================================================
171
+ def launch_gui(command, delay_sec=1.0):
172
+ env = os.environ.copy()
173
+ env['DISPLAY'] = ':0'
174
+ subprocess.Popen(shlex.split(command), stdout=subprocess.DEVNULL,
175
+ stderr=subprocess.DEVNULL, env=env)
176
+ time.sleep(delay_sec)
177
+
178
+
179
+ launch_gui(f'google-chrome "{GUSTO_URL}/?sid={sid}"', delay_sec=2.5)
180
+ print(f'GUI_READY: launched Gusto at {GUSTO_URL}/?sid={sid}')
181
+ launch_gui(f'google-chrome "{CALENDAR_URL}/?sid={sid}"', delay_sec=1.5)
182
+ print(f'GUI_READY: launched Google Calendar at {CALENDAR_URL}/?sid={sid}')
183
+
184
+ print('Initial setup complete - Gusto and Google Calendar are ready for the agent')
hr_onboarding_003/reward.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: HR onboarding for Priya Sharma — Gusto (Xusto) + Google Calendar.
3
+ Task ID: hr_onboarding_003
4
+ Domain: mock_websites (gusto[xusto=8218] + google_calendar[8161])
5
+
6
+ All checks are DELTA vs initial_state, so reward(initial_env) == 0.0.
7
+ Fully deterministic / rule-based.
8
+
9
+ Scoring (total 1.0):
10
+ Component 1 — GUSTO department (0.40):
11
+ Priya Sharma's department changed to 'Marketing' (was unassigned in initial).
12
+ Component 2 — GUSTO onboarding (0.30):
13
+ A NEW onboarding checklist for Priya Sharma exists (absent in initial).
14
+ Component 3 — CALENDAR event (0.20):
15
+ A NEW 'Onboarding Check-in' event with Priya as a guest exists.
16
+ Component 4 — CALENDAR recurrence (0.10):
17
+ That event recurs weekly (and starts around Monday 09:00).
18
+ """
19
+ import re
20
+ import sys
21
+
22
+ import requests
23
+
24
+ GUSTO_URL = 'http://28.7.184.198:8147'
25
+ CALENDAR_URL = 'http://28.7.184.198:8141'
26
+
27
+ PRIYA_NAME = 'priya sharma'
28
+ PRIYA_EMAILS = {'priya.sharma@horizontech.com', 'priya.sharma@gmail.com',
29
+ 'priya.sharma@company.com'}
30
+ EVENT_KEY = 'onboarding check-in'
31
+
32
+
33
+ def read_sid():
34
+ try:
35
+ with open('/tmp/task_web_sid') as f:
36
+ sid = f.read().strip()
37
+ if not sid:
38
+ raise ValueError('sid empty')
39
+ return sid
40
+ except Exception as e:
41
+ print(f'CRITICAL: cannot read sid: {e}')
42
+ return None
43
+
44
+
45
+ def fetch(url, sid):
46
+ try:
47
+ data = requests.get(f'{url}/go?sid={sid}', timeout=20).json()
48
+ return data.get('initial_state') or {}, data.get('current_state') or {}
49
+ except Exception as e:
50
+ print(f'ERROR: cannot fetch {url}: {e}')
51
+ return None, None
52
+
53
+
54
+ def find_priya(state):
55
+ for e in (state.get('employees') or []):
56
+ nm = f"{e.get('firstName','')} {e.get('lastName','')}".strip().lower()
57
+ if nm == PRIYA_NAME or (e.get('name') or '').strip().lower() == PRIYA_NAME:
58
+ return e
59
+ return None
60
+
61
+
62
+ def verify_gusto(sid):
63
+ """Components 1 (0.40) + 2 (0.30)."""
64
+ init, cur = fetch(GUSTO_URL, sid)
65
+ if cur is None:
66
+ print('FAIL: Gusto unreachable')
67
+ return 0.0
68
+ score = 0.0
69
+ try:
70
+ p_init = find_priya(init) or {}
71
+ p_cur = find_priya(cur) or {}
72
+ init_dept = (p_init.get('department') or '').strip().lower()
73
+ cur_dept = (p_cur.get('department') or '').strip().lower()
74
+
75
+ # Component 1: department changed to Marketing (delta) (0.40)
76
+ if cur_dept == 'marketing' and init_dept != 'marketing':
77
+ print(f'PASS: C1 — Priya assigned to Marketing (init={init_dept!r} cur={cur_dept!r}) (0.40)')
78
+ score += 0.40
79
+ else:
80
+ print(f'FAIL: C1 — department. init={init_dept!r} cur={cur_dept!r} (expected Marketing)')
81
+
82
+ # Component 2: NEW onboarding checklist for Priya (0.30)
83
+ def priya_checklists(state):
84
+ out = []
85
+ p = find_priya(state) or {}
86
+ pid = p.get('id')
87
+ for c in (state.get('onboardingChecklists') or []):
88
+ nm = str(c.get('employeeName', '')).strip().lower()
89
+ if pid and c.get('employeeId') == pid:
90
+ out.append(c)
91
+ elif PRIYA_NAME in nm:
92
+ out.append(c)
93
+ return out
94
+
95
+ init_ids = {c.get('id') for c in priya_checklists(init)}
96
+ new_lists = [c for c in priya_checklists(cur) if c.get('id') not in init_ids]
97
+ if new_lists:
98
+ print(f'PASS: C2 — new onboarding checklist for Priya (0.30)')
99
+ score += 0.30
100
+ else:
101
+ print('FAIL: C2 — no new onboarding checklist for Priya')
102
+ return score
103
+ except Exception as e:
104
+ print(f'ERROR: Gusto component — {e}')
105
+ return score
106
+
107
+
108
+ def verify_calendar(sid):
109
+ """Components 3 (0.20) + 4 (0.10)."""
110
+ init, cur = fetch(CALENDAR_URL, sid)
111
+ if cur is None:
112
+ print('FAIL: Calendar unreachable')
113
+ return 0.0
114
+ score = 0.0
115
+ try:
116
+ init_ids = {e.get('id') for e in (init.get('events') or [])}
117
+ new_events = [e for e in (cur.get('events') or []) if e.get('id') not in init_ids]
118
+
119
+ # Locate the new Onboarding Check-in event with Priya as guest.
120
+ checkin = None
121
+ for e in new_events:
122
+ title = (e.get('title') or '').strip().lower()
123
+ guests = [str(g).strip().lower() for g in (e.get('guests') or [])]
124
+ has_priya = any(g in PRIYA_EMAILS or 'priya' in g for g in guests)
125
+ if EVENT_KEY in title and has_priya:
126
+ checkin = e
127
+ break
128
+
129
+ # Component 3: event created with Priya guest (0.20)
130
+ if checkin is not None:
131
+ print(f"PASS: C3 — Onboarding Check-in event created with Priya "
132
+ f"(guests={checkin.get('guests')}) (0.20)")
133
+ score += 0.20
134
+ else:
135
+ print(f'FAIL: C3 — no new Onboarding Check-in event with Priya as guest '
136
+ f'({len(new_events)} new events)')
137
+ return score
138
+
139
+ # Component 4: recurs weekly, ~Monday 09:00 (0.10)
140
+ recurring = str(checkin.get('recurring') or '').strip().lower()
141
+ weekly_ok = recurring == 'weekly'
142
+ start = str(checkin.get('start') or '')
143
+ m = re.search(r'T(\d{2}):(\d{2})', start)
144
+ time_ok = bool(m) and int(m.group(1)) == 9 and int(m.group(2)) == 0
145
+ print(f'CALENDAR: recurring={recurring!r} weekly_ok={weekly_ok} start={start!r} '
146
+ f'time_ok={time_ok}')
147
+ if weekly_ok and time_ok:
148
+ print('PASS: C4 — weekly recurrence at 09:00 (0.10)')
149
+ score += 0.10
150
+ else:
151
+ print('FAIL: C4 — expected weekly recurrence starting at 09:00')
152
+ return score
153
+ except Exception as e:
154
+ print(f'ERROR: Calendar component — {e}')
155
+ return score
156
+
157
+
158
+ def main():
159
+ sid = read_sid()
160
+ if not sid:
161
+ print('REWARD: 0.0')
162
+ return
163
+ total = 0.0
164
+ total += verify_gusto(sid)
165
+ total += verify_calendar(sid)
166
+ final = round(min(total, 1.0), 4)
167
+ print(f'\nScore: {total}/1.0')
168
+ print(f'REWARD: {final}')
169
+
170
+
171
+ main()
hr_onboarding_003/reward_label.json ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/hr_onboarding_002/reward.py",
3
+ "api_url": "http://28.7.184.184:8000/v1/chat/completions",
4
+ "model": "Kimi-K2.6",
5
+ "max_code_chars": 100000,
6
+ "created_at": "2026-07-14 10:26:46",
7
+ "label": {
8
+ "task_id": "hr_onboarding_003",
9
+ "domain": "mock_websites",
10
+ "summary": "验证在 Gusto (Xusto) 和 Google Calendar 上完成 Priya Sharma 的 HR 入职流程,包括将其部门设为 Marketing、创建入职清单、新建名为 Onboarding Check-in 的日历事件并设置为每周 09:00 重复",
11
+ "is_placeholder": false,
12
+ "data_sources": [
13
+ "/tmp/task_web_sid",
14
+ "http://28.7.186.212:8218 (Gusto/Xusto mock)",
15
+ "http://28.7.186.212:8161 (Google Calendar mock)"
16
+ ],
17
+ "scoring_components": [
18
+ {
19
+ "name": "Component 1 — GUSTO department",
20
+ "weight": 0.4,
21
+ "description": "检查 Priya Sharma 在 Gusto 中的部门是否从初始状态变更为 Marketing",
22
+ "check_logic": "通过 find_priya 在 initial_state 和 current_state 中定位员工,比较 department 字段:cur_dept == 'marketing' 且 init_dept != 'marketing'",
23
+ "pass_condition": "当前 department 为 'marketing',且初始 department 不是 'marketing'"
24
+ },
25
+ {
26
+ "name": "Component 2 — GUSTO onboarding",
27
+ "weight": 0.3,
28
+ "description": "检查是否为 Priya Sharma 新建了入职清单(onboarding checklist)",
29
+ "check_logic": "分别提取 initial_state 和 current_state 中属于 Priya 的 checklist(按 employeeId 或 employeeName 匹配),用 id 集合去重,判断 current_state 中是否存在 initial_state 里没有的新 checklist",
30
+ "pass_condition": "current_state 中存在至少一个 initial_state 中没有的、属于 Priya Sharma 的 onboarding checklist"
31
+ },
32
+ {
33
+ "name": "Component 3 — CALENDAR event",
34
+ "weight": 0.2,
35
+ "description": "检查是否新建了标题包含 Onboarding Check-in 且 Priya 为嘉宾的日历事件",
36
+ "check_logic": "筛选 current_state 中 id 不在 initial_state 的新事件,遍历查找 title 包含 'onboarding check-in' 且 guests 列表中任一元素匹配 PRIYA_EMAILS 或包含 'priya' 的事件",
37
+ "pass_condition": "存在新的日历事件,标题包含 'onboarding check-in',且嘉宾包含 Priya"
38
+ },
39
+ {
40
+ "name": "Component 4 — CALENDAR recurrence",
41
+ "weight": 0.1,
42
+ "description": "检查上述日历事件是否设置为每周重复且开始时间为 09:00",
43
+ "check_logic": "读取事件的 recurring 字段是否为 'weekly',并用正则匹配 start 字段中的时间部分是否为 T09:00",
44
+ "pass_condition": "recurring 字段为 'weekly',且 start 时间包含 09:00"
45
+ }
46
+ ],
47
+ "total_max_score": 1.0,
48
+ "score_aggregation": "各组件分数相加,最终用 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数",
49
+ "failure_modes": [
50
+ "读取 /tmp/task_web_sid 失败或 sid 为空时提前退出,返回 0.0",
51
+ "Gusto 服务不可达(fetch 返回 None)时该部分返回 0.0",
52
+ "Calendar 服务不可达(fetch 返回 None)时该部分返回 0.0",
53
+ "Priya 部门未变更为 Marketing 时 Component 1 不得分",
54
+ "未找到新的 onboarding checklist 时 Component 2 不得分",
55
+ "未找到新的 Onboarding Check-in 事件或 Priya 不在嘉宾列表中时 Component 3 不得分,且跳过 Component 4 检查",
56
+ "事件不是 weekly 重复或开始时间不是 09:00 时 Component 4 不得分"
57
+ ],
58
+ "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后分别向 Gusto (8167) 和 Calendar (8161) 的 /go?sid={sid} 接口拉取 initial_state 和 current_state。Gusto 部分:定位员工 Priya Sharma,若其 department 字段从非 marketing 变为 marketing 则得 0.40;若 onboardingChecklists 中存在属于 Priya 且 id 在初始状态中没有的新清单则得 0.30。Calendar 部分:找出所有新事件,若存在标题包含 'onboarding check-in' 且 guests 包含 Priya 的新事件则得 0.20;若该事件存在,进一步检查 recurring 是否为 'weekly' 且 start 时间是否为 09:00,满足则再得 0.10。各组件得分累加后,通过 min(total, 1.0) 钳制上限并四舍五入到 4 位小数作为最终分数。",
59
+ "confidence": 1.0
60
+ },
61
+ "raw_response": "用户要求我分析一个 reward.py 评分脚本,并输出一个严格的 JSON 对象,不要有任何额外文字。\n\n让我仔细阅读代码:\n\n1. **任务信息**:\n - Task ID: hr_onboarding_002(从 docstring 中明确提取)\n - Domain: mock_websites(从 docstring 中明确提取,包含 gusto[xusto=8149] + google_calendar[8141])\n\n2. **Summary**:一句话概括。这个脚本验证在 Gusto (Xusto) 和 Google Calendar 上完成 Priya Sharma 的 HR 入职流程,包括设置部门、创���入职清单、创建日历事件并设置每周重复。\n\n3. **is_placeholder**:false。这个脚本有完整的检查逻辑,不是占位脚本。\n\n4. **data_sources**:\n - `/tmp/task_web_sid`:读取 sid\n - `http://28.7.186.212:8167`:Gusto mock 服务\n - `http://28.7.186.212:8161`:Calendar mock 服务\n\n5. **scoring_components**:\n - Component 1:GUSTO department,weight 0.40。检查 Priya Sharma 的部门是否从初始状态改变为 'Marketing'。代码逻辑:`cur_dept == 'marketing' and init_dept != 'marketing'`。\n - Component 2:GUSTO onboarding,weight 0.30。检查是否存在新的入职清单(onboarding checklist)给 Priya Sharma。代码逻辑:比较 init 和 cur 中的 checklist ID,找出新的。\n - Component 3:CALENDAR event,weight 0.20。检查是否创建了新的 'Onboarding Check-in' 事件且 Priya 是嘉宾。代码逻辑:在 new_events 中查找标题包含 'onboarding check-in' 且嘉宾包含 Priya 邮箱或名字的事件。\n - Component 4:CALENDAR recurrence,weight 0.10。检查该事件是否每周重复且开始时间约为周一 09:00。代码逻辑:`recurring == 'weekly'` 且 `start` 时间匹配 `T09:00`。\n\n6. **total_max_score**:1.0(0.40+0.30+0.20+0.10=1.0)\n\n7. **score_aggregation**:相加,然后 `min(total, 1.0)` 钳制到上限 1.0,再四舍五入到 4 位小数。\n\n8. **failure_modes**:\n - 读取 `/tmp/task_web_sid` 失败(sid 为空或文件不存在)→ 提前退出,打印 REWARD: 0.0\n - Gusto 服务不可达(fetch 返回 None)→ verify_gusto 返回 0.0\n - Calendar 服务不可达(fetch 返回 None)→ verify_calendar 返回 0.0\n - 部门不是 Marketing 或未改变 → C1 失败,不得分\n - 没有新的 onboarding checklist → C2 失败,不得分\n - 没有新的 Onboarding Check-in 事件或 Priya 不是嘉宾 → C3 失败,不得分(且直接 return score,跳过后续 C4 检查)\n - 事件不是 weekly 重复或开始时间不是 09:00 → C4 失败,不得分\n\n9. **scoring_logic_explanation**:详细中文解释,按执行顺序。\n - 从 `/tmp/task_web_sid` 读取会话 ID。\n - 分别向 Gusto (8167) 和 Calendar (8161) 的 `/go?sid={sid}` 接口请求 initial_state 和 current_state。\n - Gusto 部分:查找员工 Priya Sharma,对比初始和当前部门,若当前为 Marketing 且初始不是则得 0.40;对比初始和当前的 onboarding checklist,若存在新的属于 Priya 的清单则得 0.30。\n - Calendar 部分:找出所有新事件,筛选标题包含 \"onboarding check-in\" 且嘉宾包含 Priya 的新事件,若存在则得 0.20;若该事件存在,进一步检查其 recurring 字段是否为 \"weekly\" 且 start 时间是否为 09:00,满足则再得 0.10。\n - 各组件得分相加,最终用 min(total, 1.0) 钳制到 1.0 并四舍五入到 4 位小数输出。\n\n10. **confidence**:1.0。代码逻辑清晰完整。\n\n检查 JSON 格式要求:\n- 只输出 JSON 对象\n- 不要 Markdown 代码块\n- 不要额外解释\n- 不要 thinking 标签\n- 第一个字符必须是 {,最后一个字符必须是 }\n- 所有字符串 value 使用中文;task_id、domain、字段名、代码标识符保留原样\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"hr_onboarding_002\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证在 Gusto (Xusto) 和 Google Calendar 上完成 Priya Sharma 的 HR 入职流程,包括将其部门设为 Marketing、创建入职清单、新建名为 Onboarding Check-in 的日历事件并设置为每周一 09:00 重复\",\n \"is_placeholder\": false,\n \"data_sources\": [\n \"/tmp/task_web_sid\",\n \"http://28.7.186.212:8167 (Gusto/Xusto mock)\",\n \"http://28.7.186.212:8161 (Google Calendar mock)\"\n ],\n \"scoring_components\": [\n {\n \"name\": \"Component 1 — GUSTO department\",\n \"weight\": 0.4,\n \"description\": \"检查 Priya Sharma 在 Gusto 中的部门是否从初始状态变更为 Marketing\",\n \"check_logic\": \"通过 find_priya 在 initial_state 和 current_state 中定位员工,比较 department 字段:cur_dept == 'marketing' 且 init_dept != 'marketing'\",\n \"pass_condition\": \"当前部门为 'marketing',且初始部门不是 'marketing'\"\n },\n {\n \"name\": \"Component 2 — GUSTO onboarding\",\n \"weight\": 0.3,\n \"description\": \"检查是否为 Priya Sharma 新建了入职清单(onboarding checklist)\",\n \"check_logic\": \"分别提取 initial_state 和 current_state 中属于 Priya 的 checklist(按 employeeId 或 employeeName 匹配),用 ID 集合去重,判断 current 中是否存在 init 中没有的新 checklist\",\n \"pass_condition\": \"current_state 中存在至少一个 initial_state 中没有的、属于 Priya Sharma 的 onboarding checklist\"\n },\n {\n \"name\": \"Component 3 — CALENDAR event\",\n \"weight\": 0.2,\n \"description\": \"检查是否新建了标题包含 Onboarding Check-in 且 Priya 为嘉宾的日历事件\",\n \"check_logic\": \"筛选 current_state 中 id 不在 initial_state 的新事件,遍历查找 title 包含 'onboarding check-in' 且 guests 列表中任一元素匹配 PRIYA_EMAILS 或包含 'priya' 的事件\",\n \"pass_condition\": \"存在新的日历事件,标题包含 'onboarding check-in',且嘉宾包含 Priya\"\n },\n {\n \"name\": \"Component 4 — CALENDAR recurrence\",\n \"weight\": 0.1,\n \"description\": \"检查上述日历事件是否设置为每周重复且开始时间为 09:00\",\n \"check_logic\": \"读取事件的 recurring 字段是否为 'weekly',并用正则匹配 start 字段中的时间部分是否为 T09:00\",\n \"pass_condition\": \"recurring 字段为 'weekly',且 start 时间包含 09:00\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数相加,最终用 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\",\n \"failure_modes\": [\n \"读取 /tmp/task_web_sid 失败或 sid 为空时提前退出,返回 0.0\",\n \"Gusto 服务不可达(fetch 返回 None)时该部分返回 0.0\",\n \"Calendar 服务不可达(fetch 返回 None)时该部分返回 0.0\",\n \"Priya 部门未变更为 Marketing 时 Component 1 不得分\",\n \"未找到新的 onboarding checklist 时 Component 2 不得分\",\n \"未找到新的 Onboarding Check-in 事件或 Priya 不在嘉宾列表中时 Component 3 不得分,且跳过 Component 4 检查\",\n \"事件不是 weekly 重复或开始时间不是 09:00 时 Component 4 不得分\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后分别向 Gusto (8167) 和 Calendar (8161) 的 /go?sid={sid} 接口拉取 initial_state 和 current_state。Gusto 部分:定位员工 Priya Sharma,若其 department 字段从非 marketing 变为 marketing 则得 0.40;若 onboardingChecklists 中存在属于 Priya 且 ID 在初始状态中没有的新清单则得 0.30。Calendar 部分:找出所有新事件,若存在标题包含 'onboarding check-in' 且 guests 包含 Priya 的新事件则得 0.20;若该事件存在,进一步检查 recurring 是否为 'weekly' 且 start 时间是否为 09:00,满足则再得 0.10。各组件得分累加后,通过 min(total, 1.0) 钳制上限并四舍五入到 4 位小数作为最终分数。\",\n \"confidence\": 1.0\n}\n```\n\n等等,我需要确保 JSON 中所有 value 都是中文,除了 task_id、domain、字段名、代码标识符。data_sources 里的 URL 是代码标识符/数据源名称,保留原样没问题。scoring_components 里的 check_logic 和 pass_condition 包含代码字段名,保留原样。\n\n再检查一下 weight:代码中明确给出了 0.40, 0.30, 0.20, 0.10。JSON 中应该写 0.4 还是 0.40?JSON 数字不区分 0.4 和 0.40,但我会写 0.4 或 0.40 都可以。为了准确,我写 0.4, 0.3, 0.2, 0.1 或者保持原样 0.4 等。其实 0.40 在 JSON 中就是 0.4。我会写 0.4, 0.3, 0.2, 0.1。\n\n等等,用户要求 \"weight 字段填写代码中显式给出的分值(如 0.3)\"。代码中显式给出的是 0.40, 0.30, 0.20, 0.10。JSON 数字 0.40 等价于 0.4。我可以写 0.4 或 0.40。为了和代码一致,我会在文本中写 0.4 但描述中提及原值。其实直接写 0.4 没问题。\n\n再检查 failure_modes:代码中 verify_calendar 在 C3 失败时直接 `return score`,所以 C4 会被跳过。这属于一种失败路径。\n\n再检查 summary:需要一句话概括。\n\n再检查 is_placeholder:false。\n\n再检查 confidence:1.0。\n\n确保没有 Markdown 代码块,没有额外文字,第一个字符是 {,最后一个字符是 }。\n\n让我再仔细看看代码中的 domain 提取。docstring 中写的是 \"Domain: mock_websites (gusto[xusto=8149] + google_calendar[8141])\"。所以 domain 是 \"mock_websites\"。\n\ntask_id 是 \"hr_onboarding_002\"。\n\n所有要求都满足了。输出 JSON。 </think> {\n \"task_id\": \"hr_onboarding_002\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证在 Gusto (Xusto) 和 Google Calendar 上完成 Priya Sharma 的 HR 入职流程,包括将其部门设为 Marketing、创建入职清单、新建名为 Onboarding Check-in 的日历事件并设置为每周 09:00 重复\",\n \"is_placeholder\": false,\n \"data_sources\": [\n \"/tmp/task_web_sid\",\n \"http://28.7.186.212:8167 (Gusto/Xusto mock)\",\n \"http://28.7.186.212:8161 (Google Calendar mock)\"\n ],\n \"scoring_components\": [\n {\n \"name\": \"Component 1 — GUSTO department\",\n \"weight\": 0.4,\n \"description\": \"检查 Priya Sharma 在 Gusto 中的部门是否从初始状态变更为 Marketing\",\n \"check_logic\": \"通过 find_priya 在 initial_state 和 current_state 中定位员工,比较 department 字段:cur_dept == 'marketing' 且 init_dept != 'marketing'\",\n \"pass_condition\": \"当前 department 为 'marketing',且初始 department 不是 'marketing'\"\n },\n {\n \"name\": \"Component 2 — GUSTO onboarding\",\n \"weight\": 0.3,\n \"description\": \"检查是否为 Priya Sharma 新建了入职清单(onboarding checklist)\",\n \"check_logic\": \"分别提取 initial_state 和 current_state 中属于 Priya 的 checklist(按 employeeId 或 employeeName 匹配),用 id 集合去重,判断 current_state 中是否存在 initial_state 里没有的新 checklist\",\n \"pass_condition\": \"current_state 中存在至少一个 initial_state 中没有的、属于 Priya Sharma 的 onboarding checklist\"\n },\n {\n \"name\": \"Component 3 — CALENDAR event\",\n \"weight\": 0.2,\n \"description\": \"检查是否新建了标题包含 Onboarding Check-in 且 Priya 为嘉宾的日历事件\",\n \"check_logic\": \"筛选 current_state 中 id 不在 initial_state 的新事件,遍历查找 title 包含 'onboarding check-in' 且 guests 列表中任一元素匹配 PRIYA_EMAILS 或包含 'priya' 的事件\",\n \"pass_condition\": \"存在新的日历事件,标题包含 'onboarding check-in',且嘉宾包含 Priya\"\n },\n {\n \"name\": \"Component 4 — CALENDAR recurrence\",\n \"weight\": 0.1,\n \"description\": \"检查上述日历事件是否设置为每周重复且开始时间为 09:00\",\n \"check_logic\": \"读取事件的 recurring 字段是否为 'weekly',并用正则匹配 start 字段中的时间部分是否为 T09:00\",\n \"pass_condition\": \"recurring 字段为 'weekly',且 start 时间包含 09:00\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数相加,最终用 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数\",\n \"failure_modes\": [\n \"读取 /tmp/task_web_sid 失败或 sid 为空时提前退出,返回 0.0\",\n \"Gusto 服务不可达(fetch 返回 None)时该部分返回 0.0\",\n \"Calendar 服务不可达(fetch 返回 None)时该部分返回 0.0\",\n \"Priya 部门未变更为 Marketing 时 Component 1 不得分\",\n \"未找到新的 onboarding checklist 时 Component 2 不得分\",\n \"未找到新的 Onboarding Check-in 事件或 Priya 不在嘉宾列表中时 Component 3 不得分,且跳过 Component 4 检查\",\n \"事件不是 weekly 重复或开始时间不是 09:00 时 Component 4 不得分\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后分别向 Gusto (8167) 和 Calendar (8161) 的 /go?sid={sid} 接口拉取 initial_state 和 current_state。Gusto 部分:定位员工 Priya Sharma,若其 department 字段从非 marketing 变为 marketing 则得 0.40;若 onboardingChecklists 中存在属于 Priya 且 id 在初始状态中没有的新清单则得 0.30。Calendar 部分:找出所有新事件,若存在标题包含 'onboarding check-in' 且 guests 包含 Priya 的新事件则得 0.20;若该事件存在,进一步检查 recurring 是否为 'weekly' 且 start 时间是否为 09:00,满足则再得 0.10。各组件得分累加后,通过 min(total, 1.0) 钳制上限并四舍五入到 4 位小数作为最终分数。\",\n \"confidence\": 1.0\n}"
62
+ }
ops_shift_cover_005/_cua_gym_vm_bridge.sh ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # CUA-Gym VM-side network fix (direct-IP mock access).
3
+ #
4
+ # Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by
5
+ # their real IDC address (http://28.7.184.198:81xx) instead of the old
6
+ # localhost:9000-9097 socat bridge, so the VM only needs two fixes:
7
+ #
8
+ # 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's
9
+ # cluster DNS, which is unreachable from QEMU SLIRP NAT
10
+ # ("Temporary failure in name resolution").
11
+ # 2. The mock host excluded from the woa http proxy — otherwise the VM's
12
+ # Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403
13
+ # from the proxy when hitting 28.7.184.198:81xx. (The old socat path never
14
+ # hit this because localhost is bypassed by default.)
15
+ #
16
+ # Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic
17
+ # OSWorld setup pipeline.
18
+ #
19
+ # Argv:
20
+ # $1 optional sudo password (default "password"; SetupController
21
+ # substitutes {CLIENT_PASSWORD} when uploaded as a cache file).
22
+ # $2 unused (kept for backward compat — was socat first port 9000).
23
+ # $3 unused (kept for backward compat — was socat last port 9097).
24
+ # $4 optional mock host IP (default 28.7.184.198).
25
+
26
+ set +e
27
+
28
+ PASS="${1:-password}"
29
+ MOCK_HOST="${4:-28.7.184.198}"
30
+ # Derive the /16 IDC subnet so future port/host tweaks on the same segment
31
+ # stay bypassed too (28.7.184.198 -> 28.7.0.0/16).
32
+ MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')"
33
+
34
+ run_root() {
35
+ echo "$PASS" | sudo -S -p "" bash -c "$1"
36
+ }
37
+
38
+ # Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2.
39
+ GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')"
40
+ GW="${GW:-10.0.2.2}"
41
+
42
+ # ─── CUA-Gym network fix (Taiji-specific) ─────────────────────────────
43
+ fix_vm_network() {
44
+ # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP
45
+ # DNS forwarder. Nothing hardcoded except the mock host above.
46
+ local GW_NET="${GW%.*}"
47
+ local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3
48
+ local OWN_CIDR
49
+ OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \
50
+ | awk '{print $4; exit}')"
51
+ local OWN_IP="${OWN_CIDR%/*}"
52
+ local OWN_NET=""
53
+ [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24"
54
+
55
+ # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps
56
+ # systemd-resolved/NetworkManager from clobbering it.
57
+ if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf
58
+ chattr +i /etc/resolv.conf 2>/dev/null || true"; then
59
+ echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})"
60
+ else
61
+ echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf"
62
+ fi
63
+
64
+ # 2) Build the proxy bypass list from detected values + the direct-IP
65
+ # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx
66
+ # reachable from inside the VM — without it the woa proxy 403s it.
67
+ local ignore_list="['localhost', '127.0.0.0/8', '${GW}'"
68
+ [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'"
69
+ [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'"
70
+ [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'"
71
+ [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'"
72
+ [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'"
73
+ ignore_list="${ignore_list}]"
74
+
75
+ # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these.
76
+ if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then
77
+ echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}"
78
+ else
79
+ echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)"
80
+ fi
81
+
82
+ # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl).
83
+ local NP="localhost,127.0.0.1,${GW}"
84
+ [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}"
85
+ [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}"
86
+ [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24"
87
+ [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}"
88
+ [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}"
89
+
90
+ for var in no_proxy NO_PROXY; do
91
+ if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then
92
+ echo "export ${var}=${NP}" >> /home/user/.bashrc
93
+ fi
94
+ done
95
+ run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \
96
+ && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \
97
+ || echo 'no_proxy=\"${NP}\"' >> /etc/environment
98
+ grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \
99
+ && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \
100
+ || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1
101
+ echo "[cua_gym_vm_bridge] no_proxy=${NP}"
102
+ }
103
+
104
+ fix_vm_network
105
+
106
+ echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed"
ops_shift_cover_005/initial_setup.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: Shift coverage task — Maple Grove Family Clinic
3
+ Task ID: ops_shift_cover_005
4
+ Domain: mock_websites
5
+ Mocks: google_sheets_mock (http://28.7.184.198:8145), slack_mock (http://28.7.184.198:8178)
6
+ """
7
+
8
+ import json
9
+ import os
10
+ import shlex
11
+ import subprocess
12
+ import time
13
+ import uuid
14
+
15
+ import requests
16
+
17
+ # --- Config ---
18
+ SHEETS_URL = 'http://28.7.184.198:8145'
19
+ SLACK_URL = 'http://28.7.184.198:8178'
20
+
21
+ # Generate a UNIQUE sid for THIS environment (initial_env). The mock servers are
22
+ # SHARED external backends reachable from both VMs, with state scoped per-sid.
23
+ # Each environment MUST use a distinct sid so that golden_patch.py (golden_env)
24
+ # writing its completed state to a DIFFERENT sid never collides with initial_env's
25
+ # pre-task state. We persist this sid to /tmp/task_web_sid so reward-gen on this VM
26
+ # reads the correct (pre-task) current_state.
27
+ TASK_ID = 'prof31_shift_cover_001'
28
+ sid = f'{TASK_ID}_initial_{uuid.uuid4().hex}'
29
+ with open('/tmp/task_web_sid', 'w') as f:
30
+ f.write(sid)
31
+
32
+ print(f'Using unique initial_env sid: {sid}')
33
+
34
+ # ---------------------------------------------------------------------------
35
+ # Build Google Sheets initial state
36
+ # ---------------------------------------------------------------------------
37
+ sheets_state = {
38
+ "id": "wb_staff_01",
39
+ "title": "Staffing Tracker",
40
+ "activeSheetId": "sh_staff_01",
41
+ "selectedCell": "A1",
42
+ "selectionRange": None,
43
+ "clipboard": None,
44
+ "isDragging": False,
45
+ "undoStack": [],
46
+ "redoStack": [],
47
+ "namedRanges": [],
48
+ "conditionalFormats": [],
49
+ "charts": [],
50
+ "showGridlines": True,
51
+ "showFormulas": False,
52
+ "zoom": 100,
53
+ "sheets": [
54
+ {
55
+ "id": "sh_staff_01",
56
+ "name": "Weekly Schedule",
57
+ "rowCount": 100,
58
+ "colCount": 26,
59
+ "frozenRows": 1,
60
+ "frozenCols": 0,
61
+ "tabColor": None,
62
+ "isHidden": False,
63
+ "columnWidths": {},
64
+ "data": {
65
+ "A1": {"value": "Date", "formula": "Date", "style": {"bold": True, "bg": "#E8EAED", "align": "center"}},
66
+ "B1": {"value": "Shift", "formula": "Shift", "style": {"bold": True, "bg": "#E8EAED", "align": "center"}},
67
+ "C1": {"value": "Role", "formula": "Role", "style": {"bold": True, "bg": "#E8EAED", "align": "center"}},
68
+ "D1": {"value": "Assigned", "formula": "Assigned", "style": {"bold": True, "bg": "#E8EAED", "align": "center"}},
69
+ "E1": {"value": "Coverage Status", "formula": "Coverage Status", "style": {"bold": True, "bg": "#E8EAED", "align": "center"}},
70
+ "A2": {"value": "2026-07-01", "formula": "2026-07-01"},
71
+ "B2": {"value": "Morning (08:00-13:00)", "formula": "Morning (08:00-13:00)"},
72
+ "C2": {"value": "RN", "formula": "RN"},
73
+ "D2": {"value": "Priya Nair", "formula": "Priya Nair"},
74
+ "E2": {"value": "Covered", "formula": "Covered"},
75
+ "A3": {"value": "2026-07-02", "formula": "2026-07-02"},
76
+ "B3": {"value": "Morning (08:00-13:00)", "formula": "Morning (08:00-13:00)"},
77
+ "C3": {"value": "Front Desk", "formula": "Front Desk"},
78
+ "D3": {"value": "Leo Tran", "formula": "Leo Tran"},
79
+ "E3": {"value": "Covered", "formula": "Covered"},
80
+ "A4": {"value": "2026-07-03", "formula": "2026-07-03"},
81
+ "B4": {"value": "Afternoon (13:00-21:00)", "formula": "Afternoon (13:00-21:00)"},
82
+ "C4": {"value": "Medical Assistant", "formula": "Medical Assistant"},
83
+ "D4": {"value": "", "formula": ""},
84
+ "E4": {"value": "Gap", "formula": "Gap"},
85
+ "A5": {"value": "2026-07-04", "formula": "2026-07-04"},
86
+ "B5": {"value": "Morning (08:00-13:00)", "formula": "Morning (08:00-13:00)"},
87
+ "C5": {"value": "RN", "formula": "RN"},
88
+ "D5": {"value": "Grace Liu", "formula": "Grace Liu"},
89
+ "E5": {"value": "Covered", "formula": "Covered"},
90
+ },
91
+ }
92
+ ],
93
+ }
94
+
95
+ # ---------------------------------------------------------------------------
96
+ # Build Slack initial state
97
+ # ---------------------------------------------------------------------------
98
+ slack_state = {
99
+ "currentUser": {
100
+ "userId": "user_admin",
101
+ "fullName": "Practice Admin",
102
+ "displayName": "Practice Admin",
103
+ "email": "admin@maplegrove.clinic",
104
+ "avatar": "https://picsum.photos/200/200?random=10",
105
+ "status": "active",
106
+ "statusMessage": "",
107
+ "statusEmoji": "",
108
+ "timeZone": "America/Chicago",
109
+ },
110
+ "workspace": {"workspaceId": "ws_mg", "workspaceName": "Maple Grove Family Clinic", "icon": ""},
111
+ "users": [
112
+ {"userId": "user_admin", "fullName": "Practice Admin", "displayName": "Practice Admin", "email": "admin@maplegrove.clinic", "avatar": "https://picsum.photos/200/200?random=10", "status": "active", "statusMessage": "", "statusEmoji": "", "timeZone": "America/Chicago", "title": "Practice Administrator"},
113
+ {"userId": "user_2", "fullName": "Priya Nair", "displayName": "Priya", "email": "priya.nair@maplegrove.clinic", "avatar": "https://picsum.photos/200/200?random=2", "status": "active", "statusMessage": "", "statusEmoji": "", "timeZone": "America/Chicago", "title": "RN"},
114
+ {"userId": "user_3", "fullName": "Leo Tran", "displayName": "Leo", "email": "leo.tran@maplegrove.clinic", "avatar": "https://picsum.photos/200/200?random=3", "status": "active", "statusMessage": "", "statusEmoji": "", "timeZone": "America/Chicago", "title": "Front Desk"},
115
+ {"userId": "user_4", "fullName": "Grace Liu", "displayName": "Grace", "email": "grace.liu@maplegrove.clinic", "avatar": "https://picsum.photos/200/200?random=4", "status": "active", "statusMessage": "", "statusEmoji": "", "timeZone": "America/Chicago", "title": "RN"},
116
+ ],
117
+ "channels": [
118
+ {"channelId": "staffing", "name": "staffing", "description": "Shift staffing and coverage coordination", "topic": "Staffing coverage requests", "isPrivate": False, "isStarred": False, "members": ["user_admin", "user_2", "user_3", "user_4"], "createdBy": "user_admin", "createdAt": "2026-06-01T09:00:00Z", "pinnedMessages": [], "unreadCount": 0},
119
+ {"channelId": "general", "name": "general", "description": "General clinic announcements", "topic": "", "isPrivate": False, "isStarred": False, "members": ["user_admin", "user_2", "user_3", "user_4"], "createdBy": "user_admin", "createdAt": "2026-06-01T09:00:00Z", "pinnedMessages": [], "unreadCount": 0},
120
+ ],
121
+ "messages": {
122
+ "staffing": [
123
+ {"messageId": "msg_seed_1", "senderId": "user_2", "content": "Reminder: please update your availability for next week by EOD Friday.", "timestamp": "2026-06-28T14:00:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False},
124
+ ],
125
+ "general": [
126
+ {"messageId": "msg_g_1", "senderId": "user_admin", "content": "Clinic hours are 08:00-21:00 Monday through Saturday.", "timestamp": "2026-06-20T08:00:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False},
127
+ ],
128
+ },
129
+ "threads": {},
130
+ "dms": [],
131
+ "bookmarkedMessages": [],
132
+ "callHistory": [],
133
+ "settings": {"theme": "light", "notifications": "all", "displayDensity": "comfortable", "showAvatars": True, "use24Hour": False},
134
+ "invitations": [],
135
+ "notifications": [],
136
+ }
137
+
138
+ # ---------------------------------------------------------------------------
139
+ # Inject state into each mock
140
+ # ---------------------------------------------------------------------------
141
+ for name, url, state in [
142
+ ("google_sheets_mock", SHEETS_URL, sheets_state),
143
+ ("slack_mock", SLACK_URL, slack_state),
144
+ ]:
145
+ resp = requests.post(
146
+ f'{url}/post?sid={sid}',
147
+ json={'action': 'set', 'state': state},
148
+ timeout=30,
149
+ )
150
+ assert resp.status_code == 200, f'{name} state injection failed: {resp.text}'
151
+ print(f'[{name}] state injected OK')
152
+
153
+ # Verify
154
+ for name, url in [("google_sheets_mock", SHEETS_URL), ("slack_mock", SLACK_URL)]:
155
+ go = requests.get(f'{url}/go?sid={sid}', timeout=10).json()
156
+ assert go['initial_state'] is not None, f'{name} initial_state is None'
157
+ print('Verified: both mocks have initial_state set')
158
+
159
+
160
+ # ---------------------------------------------------------------------------
161
+ # Launch Chrome for each mock
162
+ # ---------------------------------------------------------------------------
163
+ def launch_gui(command, delay_sec=1.0):
164
+ env = os.environ.copy()
165
+ env['DISPLAY'] = ':0'
166
+ subprocess.Popen(
167
+ shlex.split(command),
168
+ stdout=subprocess.DEVNULL,
169
+ stderr=subprocess.DEVNULL,
170
+ env=env,
171
+ )
172
+ time.sleep(delay_sec)
173
+
174
+
175
+ launch_gui(f'google-chrome "{SHEETS_URL}/?sid={sid}"', delay_sec=1.0)
176
+ launch_gui(f'google-chrome "{SLACK_URL}/?sid={sid}"', delay_sec=1.0)
177
+
178
+
179
+ # ---------------------------------------------------------------------------
180
+ # Wait until mocks are loaded and rendered
181
+ # ---------------------------------------------------------------------------
182
+ def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0):
183
+ import time as _t
184
+ deadline = _t.time() + timeout
185
+ pending = dict(mocks)
186
+ while pending and _t.time() < deadline:
187
+ for name in list(pending):
188
+ try:
189
+ r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5)
190
+ if r.status_code == 200 and r.json().get('initial_state') is not None:
191
+ del pending[name]
192
+ except Exception:
193
+ pass
194
+ if pending:
195
+ _t.sleep(1.0)
196
+ if pending:
197
+ raise RuntimeError(f'Mocks not ready within {timeout}s: {list(pending)}')
198
+ try:
199
+ from playwright.sync_api import sync_playwright
200
+ except ImportError:
201
+ print('WARN: playwright not installed; skipping render check, settle 5s')
202
+ _t.sleep(5.0)
203
+ return
204
+ with sync_playwright() as p:
205
+ browser = p.chromium.launch(channel='chrome', headless=True,
206
+ args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'])
207
+ try:
208
+ for name, url in mocks.items():
209
+ page = browser.new_page()
210
+ try:
211
+ page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded',
212
+ timeout=int(render_timeout * 1000))
213
+ page.wait_for_function(
214
+ "document.body && document.body.innerText.length > 100",
215
+ timeout=int(render_timeout * 1000))
216
+ html = page.content()
217
+ if len(html) < 2000:
218
+ raise RuntimeError(
219
+ f'[{name}] rendered DOM too small ({len(html)} bytes) — blank/stuck loading')
220
+ print(f'[{name}] rendered OK ({len(html)} bytes)')
221
+ finally:
222
+ page.close()
223
+ finally:
224
+ browser.close()
225
+
226
+
227
+ wait_for_mocks_loaded({'google_sheets_mock': SHEETS_URL, 'slack_mock': SLACK_URL}, sid)
228
+ print(f'GUI_READY: both mocks launched and verified (sid={sid})')
ops_shift_cover_005/reward.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: prof31_shift_cover_001 — post shift coverage request in Slack and
3
+ update Google Sheets coverage status.
4
+ Task ID: ops_shift_cover_005
5
+ Domain: mock_websites
6
+ Mocks: google_sheets_mock (http://28.7.184.198:8145), slack_mock (http://28.7.184.198:8178)
7
+ Scoring: 3 deterministic exact-match components, each anchored to a TASK-INTRODUCED
8
+ change (so every component FAILS on initial_env and PASSES on golden_env):
9
+ - Slack #staffing gained exactly one new message == required text, and nothing
10
+ else in Slack changed (0.5)
11
+ - Google Sheets 'Weekly Schedule' row 4 col E == 'Request Posted' (0.3)
12
+ - The Google Sheets edit is surgical: E4 is the ONLY cell that differs from the
13
+ initial state (rows 2/3/5 and row 4 A-D unchanged, no other sheet modified) (0.2)
14
+ No LLM judge is used: the task is fully deterministic (exact strings / exact cell values).
15
+ """
16
+ import json
17
+ import re
18
+ import sys
19
+
20
+ import requests
21
+
22
+ # --- Mock endpoints (shared external backends, per task_config.json) ---
23
+ GOOGLE_SHEETS_URL = 'http://28.7.184.198:8145'
24
+ SLACK_URL = 'http://28.7.184.198:8178'
25
+
26
+ # Task ground-truth constants parsed from context in task_config.json
27
+ REQUIRED_MESSAGE = ('@channel Shift coverage needed: Medical Assistant, Fri 2026-07-03, '
28
+ 'Afternoon 13:00-21:00. Please volunteer in reply. — Practice Admin')
29
+ SHEET_ID = 'sh_staff_01'
30
+ SHEET_NAME = 'Weekly Schedule'
31
+
32
+
33
+ def _norm_text(s):
34
+ """Normalize for tolerant comparison: treat em/en/figure-dash as whitespace
35
+ and collapse internal whitespace runs. Lets a message that substituted the
36
+ em-dash (U+2014) with regular spaces still match REQUIRED_MESSAGE.
37
+ """
38
+ s = s or ''
39
+ s = s.replace('\u2014', ' ').replace('\u2013', ' ').replace('\u2012', ' ')
40
+ return re.sub(r'\s+', ' ', s).strip()
41
+
42
+
43
+ def _comp(idx, name, weight, passed, score, detail="", description=""):
44
+ """Emit a structured COMPONENT line for per-module scoring visibility."""
45
+ print("COMPONENT: " + json.dumps({
46
+ "id": idx,
47
+ "name": name,
48
+ "weight": float(weight),
49
+ "passed": bool(passed),
50
+ "score": float(score),
51
+ "detail": detail,
52
+ "description": description,
53
+ }))
54
+
55
+
56
+ def _run_component(idx, name, weight, fn, args):
57
+ """Run one check function, emit PASS/FAIL + COMPONENT line."""
58
+ try:
59
+ passed, score, detail = fn(*args)
60
+ except Exception as e:
61
+ passed, score, detail = False, 0.0, f'error: {e}'
62
+ status = 'PASS' if passed else 'FAIL'
63
+ suffix = f' ({weight} pts)' if passed else f' — {detail}'
64
+ print(f'{status}: Component {idx} — {name}{suffix}')
65
+ _comp(idx, name, weight, passed, score, detail,
66
+ description=(fn.__doc__ or '').strip())
67
+ return passed, score, detail
68
+
69
+
70
+ # --- State fetching ---
71
+ def _fetch_state(url, sid):
72
+ """Fetch {initial_state, current_state} from a mock's /go endpoint."""
73
+ resp = requests.get(f'{url}/go?sid={sid}', timeout=15)
74
+ resp.raise_for_status()
75
+ data = resp.json()
76
+ return data.get('initial_state', {}), data.get('current_state', {})
77
+
78
+
79
+ def _get_sheet(state):
80
+ """Return the 'Weekly Schedule' sheet (id=sh_staff_01) from google sheets state."""
81
+ sheets = state.get('sheets', []) or []
82
+ for s in sheets:
83
+ if s.get('id') == SHEET_ID or s.get('name') == SHEET_NAME:
84
+ return s
85
+ return None
86
+
87
+
88
+ def _cell_value(sheet, cell):
89
+ """Return the .value of a cell from a sheet's data map, or None if absent."""
90
+ if sheet is None:
91
+ return None
92
+ return (sheet.get('data', {}).get(cell, {}) or {}).get('value')
93
+
94
+
95
+ def _sheet_diff_cells(init_sheet, curr_sheet):
96
+ """Return the set of cell ids whose .value differs between two sheets."""
97
+ if init_sheet is None or curr_sheet is None:
98
+ return None
99
+ init_data = init_sheet.get('data', {}) or {}
100
+ curr_data = curr_sheet.get('data', {}) or {}
101
+ changed = set()
102
+ all_cells = set(init_data) | set(curr_data)
103
+ for cell in all_cells:
104
+ # Normalize None/"" to '' so cells that only gained/lost an empty value
105
+ # (e.g. mock creating {"value": ""} on click) don't count as changed.
106
+ iv = (init_data.get(cell, {}) or {}).get('value') or ''
107
+ cv = (curr_data.get(cell, {}) or {}).get('value') or ''
108
+ if iv != cv:
109
+ changed.add(cell)
110
+ return changed
111
+
112
+
113
+ # --- Per-component checks ---
114
+ # Every component is anchored to a TASK-INTRODUCED change (a delta vs initial_state),
115
+ # so it FAILS on initial_env (where current == initial) and PASSES on golden_env.
116
+
117
+ def check_component_1(initial, current):
118
+ """Slack #staffing gained exactly one new message == required text, and nothing
119
+ else in Slack changed. Pass condition: current staffing msgs == initial + 1 with the
120
+ single new message == REQUIRED_MESSAGE verbatim; AND the entire Slack message state
121
+ delta is exactly that one #staffing message (no other channel/message altered).
122
+ """
123
+ init_msgs = initial.get('messages', {}) or {}
124
+ curr_msgs = current.get('messages', {}) or {}
125
+
126
+ # 1a: exactly one new #staffing message, matching verbatim
127
+ init_staff = init_msgs.get('staffing', []) or []
128
+ curr_staff = curr_msgs.get('staffing', []) or []
129
+ if len(curr_staff) != len(init_staff) + 1:
130
+ return False, 0.0, (f'staffing msg count {len(curr_staff)} != '
131
+ f'expected {len(init_staff) + 1}')
132
+ new_msgs = curr_staff[len(init_staff):]
133
+ if len(new_msgs) != 1:
134
+ return False, 0.0, f'expected exactly 1 new message, found {len(new_msgs)}'
135
+ if _norm_text(new_msgs[0].get('content')) != _norm_text(REQUIRED_MESSAGE):
136
+ return False, 0.0, f'new message content mismatch: {new_msgs[0].get("content")!r}'
137
+
138
+ # 1b: no other Slack channel/message changed (the full Slack delta is just this one msg)
139
+ if set(init_msgs.keys()) != set(curr_msgs.keys()):
140
+ return False, 0.0, (f'channel set changed: {set(curr_msgs.keys())} != '
141
+ f'{set(init_msgs.keys())}')
142
+ for ch, init_list in init_msgs.items():
143
+ if ch == 'staffing':
144
+ continue
145
+ curr_list = curr_msgs.get(ch, [])
146
+ if len(curr_list) != len(init_list):
147
+ return False, 0.0, f'channel {ch} message count changed'
148
+ for a, b in zip(init_list, curr_list):
149
+ if (a.get('content') or '') != (b.get('content') or ''):
150
+ return False, 0.0, f'channel {ch} message content changed'
151
+
152
+ return True, 0.5, 'exactly one new #staffing message (verbatim); no other Slack change'
153
+
154
+
155
+ def check_component_2(initial, current):
156
+ """Google Sheets 'Weekly Schedule' row 4 col E == 'Request Posted'. Pass condition:
157
+ current E4 value == 'Request Posted' (which differs from the initial 'Gap').
158
+ """
159
+ init_sheet = _get_sheet(initial)
160
+ curr_sheet = _get_sheet(current)
161
+ if curr_sheet is None:
162
+ return False, 0.0, 'Weekly Schedule sheet not found in current_state'
163
+ init_e4 = _cell_value(init_sheet, 'E4')
164
+ curr_e4 = _cell_value(curr_sheet, 'E4')
165
+ if curr_e4 == 'Request Posted' and curr_e4 != init_e4:
166
+ return True, 0.3, f'E4 == "Request Posted" (was {init_e4!r})'
167
+ return False, 0.0, f'E4 == {curr_e4!r} (expected "Request Posted", initial {init_e4!r})'
168
+
169
+
170
+ def check_component_3(initial, current):
171
+ """The Google Sheets edit is surgical: E4 is the ONLY cell that differs from initial.
172
+ Pass condition: the set of cells whose value changed between initial and current is
173
+ exactly {'E4'} (proving rows 2/3/5 and row 4 A-D are unchanged and no other cell /
174
+ sheet was altered). Because this requires a non-empty delta, it FAILS on initial_env.
175
+ """
176
+ init_sheet = _get_sheet(initial)
177
+ curr_sheet = _get_sheet(current)
178
+ changed = _sheet_diff_cells(init_sheet, curr_sheet)
179
+ if changed is None:
180
+ return False, 0.0, 'Weekly Schedule sheet missing in one of the states'
181
+ if changed == {'E4'}:
182
+ return True, 0.2, 'only E4 changed; rows 2/3/5 and row 4 A-D intact'
183
+ return False, 0.0, f'changed cells = {sorted(changed)} (expected exactly ["E4"])'
184
+
185
+
186
+ def verify_task():
187
+ """Verify task completion with progressive scoring against both mocks.
188
+ Returns: float between 0.0 and 1.0
189
+ """
190
+ # --- Read sid from /tmp/task_web_sid (NOT hardcoded) ---
191
+ try:
192
+ with open('/tmp/task_web_sid') as f:
193
+ sid = f.read().strip()
194
+ if not sid:
195
+ raise ValueError('sid is empty')
196
+ except Exception as e:
197
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
198
+ print('REWARD: 0.0')
199
+ return 0.0
200
+
201
+ # --- Fetch state from both mocks ---
202
+ try:
203
+ gs_init, gs_curr = _fetch_state(GOOGLE_SHEETS_URL, sid)
204
+ slack_init, slack_curr = _fetch_state(SLACK_URL, sid)
205
+ except Exception as e:
206
+ print(f'CRITICAL: Cannot fetch state for sid={sid}: {e}')
207
+ print('REWARD: 0.0')
208
+ return 0.0
209
+
210
+ total_score = 0.0
211
+
212
+ # Independent components: dispatch via a table.
213
+ for idx, name, weight, fn, args in [
214
+ (1, 'Exact required message in #staffing; no other Slack change', 0.5,
215
+ check_component_1, (slack_init, slack_curr)),
216
+ (2, "Row 4 col E == 'Request Posted'", 0.3,
217
+ check_component_2, (gs_init, gs_curr)),
218
+ (3, 'Surgical edit: only E4 changed in sheet', 0.2,
219
+ check_component_3, (gs_init, gs_curr)),
220
+ ]:
221
+ _, score, _ = _run_component(idx, name, weight, fn, args)
222
+ total_score += score
223
+
224
+ final_score = round(min(total_score, 1.0), 4)
225
+ print(f"\nScore: {total_score}/1.0")
226
+ print(f"REWARD: {final_score}")
227
+ return final_score
228
+
229
+
230
+ if __name__ == '__main__':
231
+ verify_task()
ops_shift_cover_005/reward_label.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/prof31_shift_cover_001/reward.py",
3
+ "api_url": "http://28.7.184.184:8000/v1/chat/completions",
4
+ "model": "Kimi-K2.6",
5
+ "max_code_chars": 100000,
6
+ "created_at": "2026-07-14 10:31:09",
7
+ "label": {
8
+ "task_id": "ops_shift_cover_005",
9
+ "domain": "mock_websites",
10
+ "summary": "验证在 Slack #staffing 频道发布精确的班次覆盖请求消息,并在 Google Sheets 'Weekly Schedule' 中将 E4 单元格精确修改为 'Request Posted',且仅修改该单元格",
11
+ "is_placeholder": false,
12
+ "data_sources": [
13
+ "/tmp/task_web_sid",
14
+ "google_sheets_mock (http://28.7.186.212:8165)",
15
+ "slack_mock (http://28.7.186.212:8198)"
16
+ ],
17
+ "scoring_components": [
18
+ {
19
+ "name": "Component 1",
20
+ "weight": 0.5,
21
+ "description": "Slack #staffing 频道新增一条完全匹配要求文本的消息,且 Slack 其他部分没有任何变化",
22
+ "check_logic": "比较 initial 和 current 的 messages['staffing'] 列表长度,要求 curr_len == init_len + 1;新增消息内容必须完全等于 REQUIRED_MESSAGE;检查所有其他频道的消息数量和每条消息内容均未改变",
23
+ "pass_condition": "#staffing 恰好新增 1 条消息且内容完全匹配 REQUIRED_MESSAGE;所有其他频道和消息与初始状态完全一致"
24
+ },
25
+ {
26
+ "name": "Component 2",
27
+ "weight": 0.3,
28
+ "description": "Google Sheets 'Weekly Schedule' 的 E4 单元格值为 'Request Posted'",
29
+ "check_logic": "从 current_state 中获取 sheet 'sh_staff_01'/'Weekly Schedule' 的 E4 单元格值,检查是否等于 'Request Posted' 且与 initial_state 中的 E4 值不同",
30
+ "pass_condition": "E4 == 'Request Posted' 且该值与初始值不同"
31
+ },
32
+ {
33
+ "name": "Component 3",
34
+ "weight": 0.2,
35
+ "description": "Google Sheets 的修改是精确的:只有 E4 单元格发生变化",
36
+ "check_logic": "遍历 initial 和 current sheet 的所有单元格值,收集 value 发生变化的单元格集合,检查该集合是否精确等于 {'E4'}",
37
+ "pass_condition": "发生变化的单元格集合恰好只有 {'E4'}"
38
+ }
39
+ ],
40
+ "total_max_score": 1.0,
41
+ "score_aggregation": "各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限并四舍五入到 4 位小数",
42
+ "failure_modes": [
43
+ "读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并返回 0.0",
44
+ "从任一 mock 获取状态失败:打印 CRITICAL 并返回 0.0",
45
+ "Component 1: #staffing 消息数量不等于初始+1、新增消息内容不完全匹配 REQUIRED_MESSAGE、其他频道消息数量或内容发生变化",
46
+ "Component 2: 'Weekly Schedule' 工作表未找到、E4 不等于 'Request Posted' 或与初始值相同",
47
+ "Component 3: 工作表在某个状态中缺失、发生变化的单元格集合不等于 {'E4'}"
48
+ ],
49
+ "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后分别向 google_sheets_mock 和 slack_mock 的 /go 端点请求 initial_state 和 current_state。接着依次执行三个独立组件检查:1) 检查 Slack #staffing 是否恰好新增一条完全匹配 REQUIRED_MESSAGE 的消息,且 Slack 其他部分无任何变化(0.5 分);2) 检查 Google Sheets 'Weekly Schedule' 的 E4 单元格是否被修改为 'Request Posted' 且确实发生了变更(0.3 分);3) 检查 Google Sheets 中是否仅有 E4 单元格的值发生变化,确保修改是精确的(0.2 分)。每个组件通过 _run_component 执行并输出 PASS/FAIL 和结构化 COMPONENT 日志。三个组件得分相加得到总分,经 min(..., 1.0) 钳制并四舍五入后作为最终 REWARD 返回。",
50
+ "confidence": 1.0
51
+ },
52
+ "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出分析结果。\n\n让我仔细阅读代码:\n\n1. **任务信息提取**:\n - Task ID: prof31_shift_cover_001(从 docstring 中明确提取)\n - Domain: mock_websites(从 docstring 中明确提取)\n - Mocks: google_sheets_mock, slack_mock\n\n2. **评分组件**:\n - Component 1: Slack #staffing 频道新增一条消息,内容必须完全匹配 REQUIRED_MESSAGE,且 Slack 其他频道/消息没有任何变化。权重 0.5。\n - Component 2: Google Sheets 'Weekly Schedule' 的 E4 单元格值为 'Request Posted',且与初始值不同。权重 0.3。\n - Component 3: Google Sheets 的修改是精确的:只有 E4 单元格的值发生了变化,其他所有单元格都保持不变。权重 0.2。\n\n3. **状态获取**:\n - 从 `/tmp/task_web_sid` 读取 sid\n - 从两个 mock 服务获取 initial_state 和 current_state:\n - Google Sheets: http://28.7.186.212:8165\n - Slack: http://28.7.186.212:8198\n\n4. **分数汇总**:\n - 各组件分数相加(0.5 + 0.3 + 0.2 = 1.0)\n - 最终分数 = round(min(total_score, 1.0), 4)\n\n5. **失败模式**:\n - 读取 sid 失败:返回 0.0\n - 获取 mock 状态失败:返回 0.0\n - Component 1 失败:staffing 消息数量不对、新消息内容不匹配、其他频道变化等\n - Component 2 失败:E4 不是 'Request Posted' 或与初始值相同\n - Component 3 失败:变化的单元格不是只有 E4\n\n6. **is_placeholder**:false,因为脚本有详细的检查逻辑。\n\n7. **confidence**:1.0,因为代码逻辑非常清晰完整。\n\n现在构建 JSON:\n\n```json\n{\n \"task_id\": \"prof31_shift_cover_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证在 Slack #staffing 频道发布精确的班次覆盖请求消息,并在 Google Sheets 'Weekly Schedule' 中将 E4 单元格精确修改为 'Request Posted',且仅修改该单元格。\",\n \"is_placeholder\": false,\n \"data_sources\": [\n \"/tmp/task_web_sid\",\n \"google_sheets_mock (http://28.7.186.212:8165)\",\n \"slack_mock (http://28.7.186.212:8198)\"\n ],\n \"scoring_components\": [\n {\n \"name\": \"Component 1\",\n \"weight\": 0.5,\n \"description\": \"Slack #staffing 频道新增一条完全匹配要求文本的消息,且 Slack 其他部分没有任何变化\",\n \"check_logic\": \"比较 initial 和 current 的 messages['staffing'] 列表长度,要求 curr_len == init_len + 1;新增消息内容必须完全等于 REQUIRED_MESSAGE;检查所有其他频道的消息数量和每条消息内容均未改变\",\n \"pass_condition\": \"#staffing 恰好新增 1 条消息且内容完全匹配 REQUIRED_MESSAGE;所有其他频道和消息与初始状态完全一致\"\n },\n {\n \"name\": \"Component 2\",\n \"weight\": 0.3,\n \"description\": \"Google Sheets 'Weekly Schedule' 的 E4 单元格值为 'Request Posted'\",\n \"check_logic\": \"从 current_state 中获取 sheet 'sh_staff_01'/'Weekly Schedule' 的 E4 单元格值,检查是否等于 'Request Posted' 且与 initial_state 中的 E4 值不同\",\n \"pass_condition\": \"E4 == 'Request Posted' 且该值与初始值不同\"\n },\n {\n \"name\": \"Component 3\",\n \"weight\": 0.2,\n \"description\": \"Google Sheets 的修改是精确的:只有 E4 单元格发生变化\",\n \"check_logic\": \"遍历 initial 和 current sheet 的所有单元格值,收集 value 发生变化的单元格集合,检查该集合是否精确等于 {'E4'}\",\n \"pass_condition\": \"发生变化的单元格集合恰好只有 {'E4'}\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限并四舍五入到 4 位小数\",\n \"failure_modes\": [\n \"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并返回 0.0\",\n \"从任一 mock 获取状态失败:打印 CRITICAL 并返回 0.0\",\n \"Component 1: #staffing 消息数量不等于初始+1、新增消息内容不完全匹配 REQUIRED_MESSAGE、其他频道消息数量或内容发生变化\",\n \"Component 2: 'Weekly Schedule' 工作表未找到、E4 不等于 'Request Posted' 或与初始值相同\",\n \"Component 3: 工作表在某个状态中缺失、发生变化的单元格集合不等于 {'E4'}\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后分别向 google_sheets_mock 和 slack_mock 的 /go 端点请求 initial_state 和 current_state。接着依次执行三个独立组件检查:1) 检查 Slack #staffing 是否恰好新增一条完全匹配 REQUIRED_MESSAGE 的消息,且 Slack 其他部分无任何变化(0.5 分);2) 检查 Google Sheets 'Weekly Schedule' 的 E4 单元格是否被修改为 'Request Posted' 且确实发生了变更(0.3 分);3) 检查 Google Sheets 中是否仅有 E4 单元格的值发生变化,确保修改是精确的(0.2 分)。每个组件通过 _run_component 执行并输出 PASS/FAIL 和结构化 COMPONENT 日志。三个组件得分相加得到总分,经 min(..., 1.0) 钳制并四舍五入后作为最终 REWARD 返回。\",\n \"confidence\": 1.0\n}\n```\n\n检查要求:\n- 只输出 JSON 对象,不要 Markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 字符串 value 使用中文,task_id/domain/字段名/代码标识符保留原样\n- weight 填写显式分值\n- is_placeholder 为 false\n\n看起来都符合。 </think> {\"task_id\":\"prof31_shift_cover_001\",\"domain\":\"mock_websites\",\"summary\":\"验证在 Slack #staffing 频道发布精确的班次覆盖请求消息,并在 Google Sheets 'Weekly Schedule' 中将 E4 单元格精确修改为 'Request Posted',且仅修改该单元格\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"google_sheets_mock (http://28.7.186.212:8165)\",\"slack_mock (http://28.7.186.212:8198)\"],\"scoring_components\":[{\"name\":\"Component 1\",\"weight\":0.5,\"description\":\"Slack #staffing 频道新增一条完全匹配要求文本的消息,且 Slack 其他部分没有任何��化\",\"check_logic\":\"比较 initial 和 current 的 messages['staffing'] 列表长度,要求 curr_len == init_len + 1;新增消息内容必须完全等于 REQUIRED_MESSAGE;检查所有其他频道的消息数量和每条消息内容均未改变\",\"pass_condition\":\"#staffing 恰好新增 1 条消息且内容完全匹配 REQUIRED_MESSAGE;所有其他频道和消息与初始状态完全一致\"},{\"name\":\"Component 2\",\"weight\":0.3,\"description\":\"Google Sheets 'Weekly Schedule' 的 E4 单元格值为 'Request Posted'\",\"check_logic\":\"从 current_state 中获取 sheet 'sh_staff_01'/'Weekly Schedule' 的 E4 单元格值,检查是否等于 'Request Posted' 且与 initial_state 中的 E4 值不同\",\"pass_condition\":\"E4 == 'Request Posted' 且该值与初始值不同\"},{\"name\":\"Component 3\",\"weight\":0.2,\"description\":\"Google Sheets 的修改是精确的:只有 E4 单元格发生变化\",\"check_logic\":\"遍历 initial 和 current sheet 的所有单元格值,收集 value 发生变化的单元格集合,检查该集合是否精确等于 {'E4'}\",\"pass_condition\":\"发生变化的单元格集合恰好只有 {'E4'}\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限并四舍五入到 4 位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并返回 0.0\",\"从任一 mock 获取状态失败:打印 CRITICAL 并返回 0.0\",\"Component 1: #staffing 消息数量不等于初始+1、新增消息内容不完全匹配 REQUIRED_MESSAGE、其他频道消息数量或内容发生变化\",\"Component 2: 'Weekly Schedule' 工作表未找到、E4 不等于 'Request Posted' 或与初始值相同\",\"Component 3: 工作表在某个状态中缺失、发生变化的单元格集合不等于 {'E4'}\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后分别向 google_sheets_mock 和 slack_mock 的 /go 端点请求 initial_state 和 current_state。接着依次执行三个独立组件检查:1) 检查 Slack #staffing 是否恰好新增一条完全匹配 REQUIRED_MESSAGE 的消息,且 Slack 其他部分无任何变化(0.5 分);2) 检查 Google Sheets 'Weekly Schedule' 的 E4 单元格是否被修改为 'Request Posted' 且确实发生了变更(0.3 分);3) 检查 Google Sheets 中是否仅有 E4 单元格的值发生变化,确保修改是精确的(0.2 分)。每个组件通过 _run_component 执行并输出 PASS/FAIL 和结构化 COMPONENT 日志。三个组件得分相加得到总分,经 min(..., 1.0) 钳制并四舍五入后作为最终 REWARD 返回。\",\"confidence\":1.0}"
53
+ }
sdr_lead_import_004__long/_cua_gym_vm_bridge.sh ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # CUA-Gym VM-side network fix (direct-IP mock access).
3
+ #
4
+ # Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by
5
+ # their real IDC address (http://28.7.184.198:81xx) instead of the old
6
+ # localhost:9000-9097 socat bridge, so the VM only needs two fixes:
7
+ #
8
+ # 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's
9
+ # cluster DNS, which is unreachable from QEMU SLIRP NAT
10
+ # ("Temporary failure in name resolution").
11
+ # 2. The mock host excluded from the woa http proxy — otherwise the VM's
12
+ # Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403
13
+ # from the proxy when hitting 28.7.184.198:81xx. (The old socat path never
14
+ # hit this because localhost is bypassed by default.)
15
+ #
16
+ # Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic
17
+ # OSWorld setup pipeline.
18
+ #
19
+ # Argv:
20
+ # $1 optional sudo password (default "password"; SetupController
21
+ # substitutes {CLIENT_PASSWORD} when uploaded as a cache file).
22
+ # $2 unused (kept for backward compat — was socat first port 9000).
23
+ # $3 unused (kept for backward compat — was socat last port 9097).
24
+ # $4 optional mock host IP (default 28.7.184.198).
25
+
26
+ set +e
27
+
28
+ PASS="${1:-password}"
29
+ MOCK_HOST="${4:-28.7.184.198}"
30
+ # Derive the /16 IDC subnet so future port/host tweaks on the same segment
31
+ # stay bypassed too (28.7.184.198 -> 28.7.0.0/16).
32
+ MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')"
33
+
34
+ run_root() {
35
+ echo "$PASS" | sudo -S -p "" bash -c "$1"
36
+ }
37
+
38
+ # Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2.
39
+ GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')"
40
+ GW="${GW:-10.0.2.2}"
41
+
42
+ # ─── CUA-Gym network fix (Taiji-specific) ─────────────────────────────
43
+ fix_vm_network() {
44
+ # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP
45
+ # DNS forwarder. Nothing hardcoded except the mock host above.
46
+ local GW_NET="${GW%.*}"
47
+ local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3
48
+ local OWN_CIDR
49
+ OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \
50
+ | awk '{print $4; exit}')"
51
+ local OWN_IP="${OWN_CIDR%/*}"
52
+ local OWN_NET=""
53
+ [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24"
54
+
55
+ # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps
56
+ # systemd-resolved/NetworkManager from clobbering it.
57
+ if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf
58
+ chattr +i /etc/resolv.conf 2>/dev/null || true"; then
59
+ echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})"
60
+ else
61
+ echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf"
62
+ fi
63
+
64
+ # 2) Build the proxy bypass list from detected values + the direct-IP
65
+ # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx
66
+ # reachable from inside the VM — without it the woa proxy 403s it.
67
+ local ignore_list="['localhost', '127.0.0.0/8', '${GW}'"
68
+ [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'"
69
+ [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'"
70
+ [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'"
71
+ [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'"
72
+ [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'"
73
+ ignore_list="${ignore_list}]"
74
+
75
+ # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these.
76
+ if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then
77
+ echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}"
78
+ else
79
+ echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)"
80
+ fi
81
+
82
+ # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl).
83
+ local NP="localhost,127.0.0.1,${GW}"
84
+ [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}"
85
+ [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}"
86
+ [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24"
87
+ [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}"
88
+ [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}"
89
+
90
+ for var in no_proxy NO_PROXY; do
91
+ if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then
92
+ echo "export ${var}=${NP}" >> /home/user/.bashrc
93
+ fi
94
+ done
95
+ run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \
96
+ && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \
97
+ || echo 'no_proxy=\"${NP}\"' >> /etc/environment
98
+ grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \
99
+ && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \
100
+ || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1
101
+ echo "[cua_gym_vm_bridge] no_proxy=${NP}"
102
+ }
103
+
104
+ fix_vm_network
105
+
106
+ echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed"
sdr_lead_import_004__long/initial_setup.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: lc_s2 — Bulk lead entry into CRM (review-fix v2)
3
+ Source: adapted from CUA-Gym-Hub task_benchmark/tasks/lc_s2.py
4
+ Original task: lc_s2 (eval)
5
+ Mocks: salesforce_mock,google_sheets_mock,slack_mock
6
+ """
7
+ import os
8
+ import shlex
9
+ import subprocess
10
+ import time
11
+ import uuid
12
+
13
+ import requests
14
+
15
+ sid = str(uuid.uuid4())
16
+ with open('/tmp/task_web_sid', 'w') as f:
17
+ f.write(sid)
18
+ print(f'Generated sid: {sid}')
19
+
20
+ APP_STATES = [
21
+ ('http://28.7.184.198:8175', {'leads': [{'leadId': 'lead-pref-0', 'firstName': 'Priya', 'lastName': 'Raman', 'company': 'Sequoia Health Labs', 'title': '', 'email': 'priya.raman@sequoiahealth.io', 'phone': '(408) 555-0101', 'mobile': '', 'status': 'New', 'source': '', 'rating': 'Warm', 'street': '', 'city': '', 'state': '', 'zip': '', 'country': 'United States', 'industry': '', 'employees': 0, 'revenue': 0, 'website': '', 'description': 'MQL from G2 review; mid-market, 200 employees.', 'ownerId': 'U1', 'createdDate': '2026-06-04T00:00:00Z', 'modifiedDate': '2026-06-04T00:00:00Z'}, {'leadId': 'lead-pref-1', 'firstName': 'Daniel', 'lastName': "O'Connor", 'company': 'Brightlane Logistics', 'title': '', 'email': 'daniel.oconnor@brightlane.co', 'phone': '(312) 555-0157', 'mobile': '', 'status': 'New', 'source': '', 'rating': 'Warm', 'street': '', 'city': '', 'state': '', 'zip': '', 'country': 'United States', 'industry': '', 'employees': 0, 'revenue': 0, 'website': '', 'description': 'Trade show booth scan; CFO, evaluating freight TMS.', 'ownerId': 'U1', 'createdDate': '2026-06-04T00:00:00Z', 'modifiedDate': '2026-06-04T00:00:00Z'}], 'users': [{'userId': 'U1', 'firstName': 'Sales', 'lastName': 'Rep', 'email': 'U1@company.com', 'phone': '', 'title': '', 'department': 'Sales', 'role': 'Rep', 'avatar': 'https://i.pravatar.cc/150?u=U1', 'timezone': 'America/New_York', 'locale': 'en-US', 'theme': 'lightning'}], 'user': {'userId': 'U1', 'firstName': 'Sales', 'lastName': 'Rep', 'email': 'U1@company.com', 'phone': '', 'title': '', 'department': 'Sales', 'role': 'Rep', 'avatar': 'https://i.pravatar.cc/150?u=U1', 'timezone': 'America/New_York', 'locale': 'en-US', 'theme': 'lightning'}, 'accounts': [], 'contacts': [], 'opportunities': [], 'cases': [], 'activities': [], 'chatterPosts': [], 'files': [], 'dashboards': [], 'following': [], 'recentlyViewed': [], 'dismissedNotifications': []}),
22
+ ('http://28.7.184.198:8145', {'id': 'workbook_lc_s2', 'title': 'Inbound', 'activeSheetId': 'sheet_1', 'selectedCell': 'A1', 'selectionRange': None, 'clipboard': None, 'isDragging': False, 'undoStack': [], 'redoStack': [], 'namedRanges': [], 'conditionalFormats': [], 'charts': [], 'showGridlines': True, 'showFormulas': False, 'zoom': 100, 'sheets': [{'id': 'sheet_1', 'name': 'Inbound', 'data': {'A1': {'value': 'first_name', 'formula': 'first_name', 'computed': 'first_name', 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, 'B1': {'value': 'last_name', 'formula': 'last_name', 'computed': 'last_name', 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, 'C1': {'value': 'company', 'formula': 'company', 'computed': 'company', 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, 'D1': {'value': 'phone', 'formula': 'phone', 'computed': 'phone', 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, 'E1': {'value': 'email', 'formula': 'email', 'computed': 'email', 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, 'F1': {'value': 'notes', 'formula': 'notes', 'computed': 'notes', 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, 'G1': {'value': 'status', 'formula': 'status', 'computed': 'status', 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}, 'A2': {'value': 'Priya', 'formula': 'Priya', 'computed': 'Priya'}, 'B2': {'value': 'Raman', 'formula': 'Raman', 'computed': 'Raman'}, 'C2': {'value': 'Sequoia Health Labs', 'formula': 'Sequoia Health Labs', 'computed': 'Sequoia Health Labs'}, 'D2': {'value': '(408) 555-0101', 'formula': '(408) 555-0101', 'computed': '(408) 555-0101'}, 'E2': {'value': 'priya.raman@sequoiahealth.io', 'formula': 'priya.raman@sequoiahealth.io', 'computed': 'priya.raman@sequoiahealth.io'}, 'F2': {'value': 'MQL from G2 review; mid-market, 200 employees.', 'formula': 'MQL from G2 review; mid-market, 200 employees.', 'computed': 'MQL from G2 review; mid-market, 200 employees.'}, 'G2': {'value': 'Entered', 'formula': 'Entered', 'computed': 'Entered'}, 'A3': {'value': 'Daniel', 'formula': 'Daniel', 'computed': 'Daniel'}, 'B3': {'value': "O'Connor", 'formula': "O'Connor", 'computed': "O'Connor"}, 'C3': {'value': 'Brightlane Logistics', 'formula': 'Brightlane Logistics', 'computed': 'Brightlane Logistics'}, 'D3': {'value': '(312) 555-0157', 'formula': '(312) 555-0157', 'computed': '(312) 555-0157'}, 'E3': {'value': 'daniel.oconnor@brightlane.co', 'formula': 'daniel.oconnor@brightlane.co', 'computed': 'daniel.oconnor@brightlane.co'}, 'F3': {'value': 'Trade show booth scan; CFO, evaluating freight TMS.', 'formula': 'Trade show booth scan; CFO, evaluating freight TMS.', 'computed': 'Trade show booth scan; CFO, evaluating freight TMS.'}, 'G3': {'value': 'Entered', 'formula': 'Entered', 'computed': 'Entered'}, 'A4': {'value': 'Anika', 'formula': 'Anika', 'computed': 'Anika'}, 'B4': {'value': 'Sharma', 'formula': 'Sharma', 'computed': 'Sharma'}, 'C4': {'value': 'Polaris BioSciences', 'formula': 'Polaris BioSciences', 'computed': 'Polaris BioSciences'}, 'D4': {'value': '(617) 555-0173', 'formula': '(617) 555-0173', 'computed': '(617) 555-0173'}, 'E4': {'value': 'anika.sharma@polarisbio.com', 'formula': 'anika.sharma@polarisbio.com', 'computed': 'anika.sharma@polarisbio.com'}, 'F4': {'value': 'Webinar attendee; asked for HIPAA compliance docs.', 'formula': 'Webinar attendee; asked for HIPAA compliance docs.', 'computed': 'Webinar attendee; asked for HIPAA compliance docs.'}, 'G4': {'value': '', 'formula': '', 'computed': ''}, 'A5': {'value': 'Tomasz', 'formula': 'Tomasz', 'computed': 'Tomasz'}, 'B5': {'value': 'Nowak', 'formula': 'Nowak', 'computed': 'Nowak'}, 'C5': {'value': 'Helix Game Studios', 'formula': 'Helix Game Studios', 'computed': 'Helix Game Studios'}, 'D5': {'value': '(206) 555-0119', 'formula': '(206) 555-0119', 'computed': '(206) 555-0119'}, 'E5': {'value': 'tomasz.nowak@helixgames.gg', 'formula': 'tomasz.nowak@helixgames.gg', 'computed': 'tomasz.nowak@helixgames.gg'}, 'F5': {'value': 'LinkedIn outbound reply; team of 35, evaluating SSO.', 'formula': 'LinkedIn outbound reply; team of 35, evaluating SSO.', 'computed': 'LinkedIn outbound reply; team of 35, evaluating SSO.'}, 'G5': {'value': '', 'formula': '', 'computed': ''}, 'A6': {'value': 'Gabriela', 'formula': 'Gabriela', 'computed': 'Gabriela'}, 'B6': {'value': 'Mendes', 'formula': 'Mendes', 'computed': 'Mendes'}, 'C6': {'value': 'Atlas Outdoor Co.', 'formula': 'Atlas Outdoor Co.', 'computed': 'Atlas Outdoor Co.'}, 'D6': {'value': '(720) 555-0146', 'formula': '(720) 555-0146', 'computed': '(720) 555-0146'}, 'E6': {'value': 'gabriela.mendes@atlasoutdoor.com', 'formula': 'gabriela.mendes@atlasoutdoor.com', 'computed': 'gabriela.mendes@atlasoutdoor.com'}, 'F6': {'value': 'Inbound contact form; wants invoicing in EUR.', 'formula': 'Inbound contact form; wants invoicing in EUR.', 'computed': 'Inbound contact form; wants invoicing in EUR.'}, 'G6': {'value': '', 'formula': '', 'computed': ''}, 'A7': {'value': 'Henry', 'formula': 'Henry', 'computed': 'Henry'}, 'B7': {'value': 'Wallace', 'formula': 'Wallace', 'computed': 'Wallace'}, 'C7': {'value': 'Vector Capital Partners', 'formula': 'Vector Capital Partners', 'computed': 'Vector Capital Partners'}, 'D7': {'value': '(212) 555-0190', 'formula': '(212) 555-0190', 'computed': '(212) 555-0190'}, 'E7': {'value': 'henry.wallace@vectorcap.partners', 'formula': 'henry.wallace@vectorcap.partners', 'computed': 'henry.wallace@vectorcap.partners'}, 'F7': {'value': 'Referred by Acme; PE buyer due diligence in 2 weeks.', 'formula': 'Referred by Acme; PE buyer due diligence in 2 weeks.', 'computed': 'Referred by Acme; PE buyer due diligence in 2 weeks.'}, 'G7': {'value': '', 'formula': '', 'computed': ''}, 'A8': {'value': 'Yuna', 'formula': 'Yuna', 'computed': 'Yuna'}, 'B8': {'value': 'Park', 'formula': 'Park', 'computed': 'Park'}, 'C8': {'value': 'Coral Reef Cosmetics', 'formula': 'Coral Reef Cosmetics', 'computed': 'Coral Reef Cosmetics'}, 'D8': {'value': '(310) 555-0163', 'formula': '(310) 555-0163', 'computed': '(310) 555-0163'}, 'E8': {'value': 'yuna.park@coralreefcosmetics.com', 'formula': 'yuna.park@coralreefcosmetics.com', 'computed': 'yuna.park@coralreefcosmetics.com'}, 'F8': {'value': 'Shopify install; asked about affiliate workflow.', 'formula': 'Shopify install; asked about affiliate workflow.', 'computed': 'Shopify install; asked about affiliate workflow.'}, 'G8': {'value': '', 'formula': '', 'computed': ''}, 'A9': {'value': 'Liam', 'formula': 'Liam', 'computed': 'Liam'}, 'B9': {'value': 'Foster', 'formula': 'Foster', 'computed': 'Foster'}, 'C9': {'value': 'Granite Peak Construction', 'formula': 'Granite Peak Construction', 'computed': 'Granite Peak Construction'}, 'D9': {'value': '(801) 555-0124', 'formula': '(801) 555-0124', 'computed': '(801) 555-0124'}, 'E9': {'value': 'liam.foster@granitepeak.build', 'formula': 'liam.foster@granitepeak.build', 'computed': 'liam.foster@granitepeak.build'}, 'F9': {'value': 'Cold email reply; needs mobile-friendly quoting.', 'formula': 'Cold email reply; needs mobile-friendly quoting.', 'computed': 'Cold email reply; needs mobile-friendly quoting.'}, 'G9': {'value': '', 'formula': '', 'computed': ''}, 'A10': {'value': 'Saanvi', 'formula': 'Saanvi', 'computed': 'Saanvi'}, 'B10': {'value': 'Iyer', 'formula': 'Iyer', 'computed': 'Iyer'}, 'C10': {'value': 'Halcyon EdTech', 'formula': 'Halcyon EdTech', 'computed': 'Halcyon EdTech'}, 'D10': {'value': '(857) 555-0138', 'formula': '(857) 555-0138', 'computed': '(857) 555-0138'}, 'E10': {'value': 'saanvi.iyer@halcyon-edtech.org', 'formula': 'saanvi.iyer@halcyon-edtech.org', 'computed': 'saanvi.iyer@halcyon-edtech.org'}, 'F10': {'value': 'Demo request from .edu domain; nonprofit pricing question.', 'formula': 'Demo request from .edu domain; nonprofit pricing question.', 'computed': 'Demo request from .edu domain; nonprofit pricing question.'}, 'G10': {'value': '', 'formula': '', 'computed': ''}, 'A11': {'value': 'Ethan', 'formula': 'Ethan', 'computed': 'Ethan'}, 'B11': {'value': 'Brooks', 'formula': 'Brooks', 'computed': 'Brooks'}, 'C11': {'value': 'Riverstone Wines', 'formula': 'Riverstone Wines', 'computed': 'Riverstone Wines'}, 'D11': {'value': '(707) 555-0151', 'formula': '(707) 555-0151', 'computed': '(707) 555-0151'}, 'E11': {'value': 'ethan.brooks@riverstonewines.com', 'formula': 'ethan.brooks@riverstonewines.com', 'computed': 'ethan.brooks@riverstonewines.com'}, 'F11': {'value': 'Trade show; DTC operations lead, 5 SKUs to launch Q3.', 'formula': 'Trade show; DTC operations lead, 5 SKUs to launch Q3.', 'computed': 'Trade show; DTC operations lead, 5 SKUs to launch Q3.'}, 'G11': {'value': '', 'formula': '', 'computed': ''}}, 'rowCount': 100, 'colCount': 26, 'frozenRows': 1, 'frozenCols': 0, 'tabColor': None, 'isHidden': False, 'columnWidths': {}, 'rowHeights': {}, 'filterRange': None, 'filterCriteria': {}, 'sortColumn': None, 'sortDirection': None}], '_task_adapter': {'source_schema': 'rows_dict', 'task_id': 'lc_s2', 'variant': 'eval', 'task_sheets': {'Inbound': {'headers': ['first_name', 'last_name', 'company', 'phone', 'email', 'notes', 'status'], 'rows': [{'first_name': 'Priya', 'last_name': 'Raman', 'company': 'Sequoia Health Labs', 'phone': '(408) 555-0101', 'email': 'priya.raman@sequoiahealth.io', 'notes': 'MQL from G2 review; mid-market, 200 employees.', 'status': 'Entered'}, {'first_name': 'Daniel', 'last_name': "O'Connor", 'company': 'Brightlane Logistics', 'phone': '(312) 555-0157', 'email': 'daniel.oconnor@brightlane.co', 'notes': 'Trade show booth scan; CFO, evaluating freight TMS.', 'status': 'Entered'}, {'first_name': 'Anika', 'last_name': 'Sharma', 'company': 'Polaris BioSciences', 'phone': '(617) 555-0173', 'email': 'anika.sharma@polarisbio.com', 'notes': 'Webinar attendee; asked for HIPAA compliance docs.', 'status': ''}, {'first_name': 'Tomasz', 'last_name': 'Nowak', 'company': 'Helix Game Studios', 'phone': '(206) 555-0119', 'email': 'tomasz.nowak@helixgames.gg', 'notes': 'LinkedIn outbound reply; team of 35, evaluating SSO.', 'status': ''}, {'first_name': 'Gabriela', 'last_name': 'Mendes', 'company': 'Atlas Outdoor Co.', 'phone': '(720) 555-0146', 'email': 'gabriela.mendes@atlasoutdoor.com', 'notes': 'Inbound contact form; wants invoicing in EUR.', 'status': ''}, {'first_name': 'Henry', 'last_name': 'Wallace', 'company': 'Vector Capital Partners', 'phone': '(212) 555-0190', 'email': 'henry.wallace@vectorcap.partners', 'notes': 'Referred by Acme; PE buyer due diligence in 2 weeks.', 'status': ''}, {'first_name': 'Yuna', 'last_name': 'Park', 'company': 'Coral Reef Cosmetics', 'phone': '(310) 555-0163', 'email': 'yuna.park@coralreefcosmetics.com', 'notes': 'Shopify install; asked about affiliate workflow.', 'status': ''}, {'first_name': 'Liam', 'last_name': 'Foster', 'company': 'Granite Peak Construction', 'phone': '(801) 555-0124', 'email': 'liam.foster@granitepeak.build', 'notes': 'Cold email reply; needs mobile-friendly quoting.', 'status': ''}, {'first_name': 'Saanvi', 'last_name': 'Iyer', 'company': 'Halcyon EdTech', 'phone': '(857) 555-0138', 'email': 'saanvi.iyer@halcyon-edtech.org', 'notes': 'Demo request from .edu domain; nonprofit pricing question.', 'status': ''}, {'first_name': 'Ethan', 'last_name': 'Brooks', 'company': 'Riverstone Wines', 'phone': '(707) 555-0151', 'email': 'ethan.brooks@riverstonewines.com', 'notes': 'Trade show; DTC operations lead, 5 SKUs to launch Q3.', 'status': ''}]}}, 'headers_by_sheet': {'Inbound': ['first_name', 'last_name', 'company', 'phone', 'email', 'notes', 'status']}, 'sheet_names': ['Inbound']}}),
23
+ ('http://28.7.184.198:8178', {
24
+ 'channels': [
25
+ {'channelId': 'general', 'name': 'general', 'description': 'Company-wide announcements and work-based matters', 'topic': 'Welcome to Acme Corp!', 'isPrivate': False, 'isStarred': True, 'members': ['user_1', 'user_2', 'user_3', 'user_4'], 'createdBy': 'user_2', 'createdAt': '2026-05-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0},
26
+ {'channelId': 'announcements', 'name': 'announcements', 'description': 'Important company updates', 'topic': 'Read-mostly. Big news only.', 'isPrivate': False, 'isStarred': False, 'members': ['user_1', 'user_2', 'user_3', 'user_4'], 'createdBy': 'user_2', 'createdAt': '2026-05-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0},
27
+ {'channelId': 'random', 'name': 'random', 'description': 'Non-work banter and watercooler chat', 'topic': 'Coffee, memes, weekend plans', 'isPrivate': False, 'isStarred': False, 'members': ['user_1', 'user_2', 'user_3', 'user_4'], 'createdBy': 'user_3', 'createdAt': '2026-05-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0},
28
+ {'channelId': 'sales-ops', 'name': 'sales-ops', 'description': 'Sales operations updates and bulk lead entry confirmations', 'topic': 'Drop a line whenever you finish a batch of lead entries', 'isPrivate': False, 'isStarred': False, 'members': ['user_1', 'user_2'], 'createdBy': 'user_1', 'createdAt': '2026-06-04T00:00:00Z', 'pinnedMessages': [], 'unreadCount': 0},
29
+ ],
30
+ 'currentUser': {'userId': 'user_1', 'fullName': 'John Smith', 'displayName': 'John', 'email': 'john.smith@company.com', 'avatar': 'https://picsum.photos/200/200?random=1', 'title': 'Sales Ops', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'},
31
+ 'users': [
32
+ {'userId': 'user_1', 'fullName': 'John Smith', 'displayName': 'John', 'email': 'john.smith@company.com', 'avatar': 'https://picsum.photos/200/200?random=1', 'title': 'Sales Ops', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'},
33
+ {'userId': 'user_2', 'fullName': 'Maya Lindqvist', 'displayName': 'Maya', 'email': 'maya.lindqvist@company.com', 'avatar': 'https://picsum.photos/200/200?random=2', 'title': 'People Ops', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'Europe/Stockholm'},
34
+ {'userId': 'user_3', 'fullName': 'Hiroshi Tanabe', 'displayName': 'Hiroshi', 'email': 'hiroshi.tanabe@company.com', 'avatar': 'https://picsum.photos/200/200?random=3', 'title': 'Engineering', 'status': 'away', 'statusMessage': 'In a meeting', 'statusEmoji': ':calendar:', 'timeZone': 'Asia/Tokyo'},
35
+ {'userId': 'user_4', 'fullName': 'Olivia Becker', 'displayName': 'Olivia', 'email': 'olivia.becker@company.com', 'avatar': 'https://picsum.photos/200/200?random=4', 'title': 'Marketing', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Los_Angeles'},
36
+ ],
37
+ 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Acme Corp', 'icon': ''},
38
+ 'messages': {
39
+ 'general': [
40
+ {'messageId': 'm_g_1', 'senderId': 'user_2', 'content': "Morning everyone \u2014 reminder that the office will be closed next Friday for the holiday.", 'timestamp': '2026-06-03T13:02:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []},
41
+ {'messageId': 'm_g_2', 'senderId': 'user_4', 'content': 'Thanks Maya! Long weekend incoming :tada:', 'timestamp': '2026-06-03T13:05:00Z', 'reactions': [{'emoji': '\ud83c\udf89', 'users': ['user_1', 'user_3']}], 'isEdited': False, 'threadId': None, 'attachments': []},
42
+ {'messageId': 'm_g_3', 'senderId': 'user_3', 'content': 'Quick heads-up: the staging environment is being rebuilt today, expect slowness 10:00\u201311:00 JST.', 'timestamp': '2026-06-04T01:12:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []},
43
+ {'messageId': 'm_g_4', 'senderId': 'user_1', 'content': "Got it, I'll hold off on deploys until after.", 'timestamp': '2026-06-04T01:15:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []},
44
+ {'messageId': 'm_g_5', 'senderId': 'user_2', 'content': 'New hire starts Monday \u2014 please welcome them when you see the announcement.', 'timestamp': '2026-06-04T14:40:00Z', 'reactions': [{'emoji': '\ud83d\udc4b', 'users': ['user_1', 'user_4']}], 'isEdited': False, 'threadId': None, 'attachments': []},
45
+ ],
46
+ 'announcements': [
47
+ {'messageId': 'm_a_1', 'senderId': 'user_2', 'content': 'Q2 all-hands has been scheduled for June 28 at 10:00 PT. Calendar invite goes out today.', 'timestamp': '2026-06-02T16:30:00Z', 'reactions': [{'emoji': '\u2705', 'users': ['user_1', 'user_3', 'user_4']}], 'isEdited': False, 'threadId': None, 'attachments': []},
48
+ {'messageId': 'm_a_2', 'senderId': 'user_2', 'content': 'New laptop refresh policy is live on the People Ops wiki. TL;DR: 3-year cycle, request via the IT portal.', 'timestamp': '2026-06-04T09:00:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []},
49
+ ],
50
+ 'random': [
51
+ {'messageId': 'm_r_1', 'senderId': 'user_4', 'content': 'Anyone tried the new ramen place on 3rd? Verdict?', 'timestamp': '2026-06-03T18:50:00Z', 'reactions': [{'emoji': '\ud83c\udf5c', 'users': ['user_3']}], 'isEdited': False, 'threadId': None, 'attachments': []},
52
+ {'messageId': 'm_r_2', 'senderId': 'user_3', 'content': "10/10, get the spicy miso. Bring tissues though, it's no joke.", 'timestamp': '2026-06-03T18:55:00Z', 'reactions': [{'emoji': '\ud83d\ude05', 'users': ['user_1', 'user_4']}], 'isEdited': False, 'threadId': None, 'attachments': []},
53
+ {'messageId': 'm_r_3', 'senderId': 'user_1', 'content': 'My cat has decided my keyboard is her new bed. Send help.', 'timestamp': '2026-06-04T08:20:00Z', 'reactions': [{'emoji': '\ud83d\ude3a', 'users': ['user_2', 'user_3', 'user_4']}], 'isEdited': False, 'threadId': None, 'attachments': []},
54
+ {'messageId': 'm_r_4', 'senderId': 'user_2', 'content': "Pics or it didn't happen.", 'timestamp': '2026-06-04T08:22:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []},
55
+ ],
56
+ 'sales-ops': [],
57
+ },
58
+ 'threads': {},
59
+ 'dms': [],
60
+ 'bookmarkedMessages': [],
61
+ 'callHistory': [],
62
+ 'settings': {'theme': 'light', 'notifications': 'all', 'displayDensity': 'comfortable', 'showAvatars': True, 'use24Hour': False},
63
+ 'invitations': [],
64
+ 'notifications': [],
65
+ }),
66
+ ]
67
+
68
+ for placeholder, state in APP_STATES:
69
+ resp = requests.post(
70
+ f'{placeholder}/post?sid={sid}',
71
+ json={'action': 'set', 'state': state},
72
+ timeout=30,
73
+ )
74
+ assert resp.status_code == 200, (
75
+ f'State injection failed for {placeholder}: {resp.text}'
76
+ )
77
+ print(f'State injected: {placeholder} sid={sid}')
78
+
79
+ for placeholder, _ in APP_STATES:
80
+ go = requests.get(f'{placeholder}/go?sid={sid}', timeout=15).json()
81
+ assert go.get('initial_state') is not None, (
82
+ f'initial_state is None after injection for {placeholder}'
83
+ )
84
+ print(f'Verified initial_state set: {placeholder}')
85
+
86
+
87
+ # PATCHED_BY: patch_wait_mocks_loaded.py
88
+ def launch_gui(command, delay_sec=1.0):
89
+ """Launch a GUI command, fully detached from this script.
90
+
91
+ Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that
92
+ wait_mocks_loaded's CDP phase can verify browser render below.
93
+ Idempotent: if the caller already specified a debug port, keep it.
94
+ """
95
+ env = os.environ.copy()
96
+ env['DISPLAY'] = ':0'
97
+ if isinstance(command, str):
98
+ _parts = shlex.split(command)
99
+ else:
100
+ _parts = list(command)
101
+ if (_parts and 'google-chrome' in _parts[0]
102
+ and not any(p.startswith('--remote-debugging-port') for p in _parts)):
103
+ _parts[1:1] = [
104
+ '--no-first-run',
105
+ '--no-default-browser-check',
106
+ '--remote-debugging-port=1337',
107
+ ]
108
+ subprocess.Popen(
109
+ _parts,
110
+ stdin=subprocess.DEVNULL,
111
+ stdout=subprocess.DEVNULL,
112
+ stderr=subprocess.DEVNULL,
113
+ env=env,
114
+ start_new_session=True,
115
+ )
116
+ time.sleep(delay_sec)
117
+
118
+
119
+ def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12):
120
+ """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style.
121
+
122
+ Phase 1 - Backend readiness:
123
+ Poll each mock's /state?sid=<sid> (preferred) or /go?sid=<sid>
124
+ (fallback) until it returns 200 with 'stored_state' or
125
+ 'initial_state' respectively, or until timeout.
126
+
127
+ Phase 2 - Browser render verification (via CDP + Playwright):
128
+ Connect to http://localhost:1337 (the --remote-debugging-port
129
+ injected by launch_gui above), wait for every open tab to reach
130
+ 'networkidle' AND to contain at least 20 DOM elements. This
131
+ guarantees the SPA fetched /go?sid= data AND actually painted,
132
+ not just that the mock backend is up.
133
+
134
+ Fallback:
135
+ If Playwright is missing or CDP cannot be reached, sleep for
136
+ `render_buffer` seconds as a best-effort delay so the screenshot
137
+ loop does not start on a still-blank tab.
138
+ """
139
+ import urllib.request as _urlreq
140
+ import time as _t
141
+ _urls = [p for p, _ in app_states]
142
+ _opener = _urlreq.build_opener(_urlreq.ProxyHandler({}))
143
+
144
+ # ---- Phase 1: backend readiness ----
145
+ _deadline = _t.time() + timeout
146
+ _todo = list(_urls)
147
+ while _todo and _t.time() < _deadline:
148
+ _rest = []
149
+ for _u in _todo:
150
+ _ok = False
151
+ for _path, _need in (('/state?sid=', b'stored_state'),
152
+ ('/go?sid=', b'initial_state')):
153
+ try:
154
+ _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5)
155
+ if _r.status == 200:
156
+ _body = _r.read()
157
+ if _need in _body:
158
+ _ok = True
159
+ break
160
+ except Exception:
161
+ pass
162
+ if _ok:
163
+ print(f" {_u}: backend ready")
164
+ continue
165
+ _rest.append(_u)
166
+ _todo = _rest
167
+ if _todo:
168
+ _t.sleep(2)
169
+ _done = len(_urls) - len(_todo)
170
+ _pend = f" (pending: {_todo})" if _todo else ""
171
+ print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}")
172
+
173
+ # ---- Phase 2: browser render verification via CDP ----
174
+ _cdp_ok = False
175
+ try:
176
+ from playwright.sync_api import sync_playwright
177
+ _cdp_dl = _t.time() + max(15.0, _deadline - _t.time())
178
+ with sync_playwright() as _p:
179
+ _br = None
180
+ while _t.time() < _cdp_dl:
181
+ try:
182
+ _br = _p.chromium.connect_over_cdp('http://localhost:1337')
183
+ break
184
+ except Exception:
185
+ _t.sleep(0.5)
186
+ if _br is None:
187
+ print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?")
188
+ else:
189
+ _n_expected = len(_urls)
190
+ _pages = []
191
+ _pg_dl = _t.time() + 15
192
+ _last_count = -1
193
+ _stable_since = None
194
+ while _t.time() < _pg_dl:
195
+ _pages = []
196
+ for _c in _br.contexts:
197
+ _pages.extend(_c.pages)
198
+ _cnt = len(_pages)
199
+ if _n_expected > 0 and _cnt >= _n_expected:
200
+ break
201
+ if _cnt > 0 and _cnt == _last_count:
202
+ if _stable_since is None:
203
+ _stable_since = _t.time()
204
+ elif _t.time() - _stable_since >= 1.5:
205
+ break
206
+ else:
207
+ _stable_since = None
208
+ _last_count = _cnt
209
+ _t.sleep(0.5)
210
+ _pages = []
211
+ for _c in _br.contexts:
212
+ _pages.extend(_c.pages)
213
+ if not _pages:
214
+ print(" wait_mocks_loaded: CDP connected but no open tabs found")
215
+ else:
216
+ print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render")
217
+ _MIN_ELEMS = 20
218
+ _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap
219
+ for _pg in _pages: # bring each to front once to defeat background-tab render throttling
220
+ try:
221
+ _pg.bring_to_front()
222
+ except Exception:
223
+ pass
224
+ _pending = list(_pages)
225
+ while _pending and _t.time() < _verify_dl:
226
+ _still = []
227
+ for _pg in _pending:
228
+ _ttl = ""
229
+ try:
230
+ _ttl = _pg.title()
231
+ except Exception:
232
+ pass
233
+ try:
234
+ _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0")
235
+ except Exception:
236
+ _n = 0
237
+ if _n >= _MIN_ELEMS:
238
+ print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)")
239
+ else:
240
+ _still.append(_pg)
241
+ _pending = _still
242
+ if _pending:
243
+ _t.sleep(2)
244
+ if not _pending:
245
+ _cdp_ok = True
246
+ else:
247
+ for _pg in _pending:
248
+ _ttl = ""
249
+ try:
250
+ _ttl = _pg.title()
251
+ except Exception:
252
+ pass
253
+ print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back")
254
+ except ImportError:
255
+ print(" wait_mocks_loaded: playwright not installed; skipping CDP phase")
256
+ except Exception as _e:
257
+ print(f" wait_mocks_loaded: CDP phase error ({_e!r})")
258
+
259
+ if not _cdp_ok:
260
+ print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep")
261
+ _t.sleep(render_buffer)
262
+ else:
263
+ print(" wait_mocks_loaded: browser render verified, skipping render_buffer")
264
+
265
+
266
+ def _open_mock_tabs(app_states, sid_value):
267
+ """Open the first mock as the primary Chrome window, the rest as new tabs.
268
+
269
+ Uses launch_gui once per URL so that the macOS localizer regex-extract
270
+ (which grabs the FIRST quoted URL per call) still works correctly.
271
+ """
272
+ _urls = [p for p, _ in app_states]
273
+ if not _urls:
274
+ return
275
+ launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0)
276
+ for _u in _urls[1:]:
277
+ launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0)
278
+
279
+
280
+
281
+ # PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate)
282
+ def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0):
283
+ """Block until every mock serves injected state AND (best-effort) renders."""
284
+ import time as _t
285
+ deadline = _t.time() + timeout
286
+ pending = dict(mocks)
287
+ while pending and _t.time() < deadline:
288
+ for name in list(pending):
289
+ try:
290
+ r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5)
291
+ if r.status_code == 200 and r.json().get('initial_state') is not None:
292
+ del pending[name]
293
+ except Exception:
294
+ pass
295
+ if pending:
296
+ _t.sleep(1.0)
297
+ if pending:
298
+ print(f'WARN: mocks not ready within {timeout}s: {list(pending)}')
299
+ try:
300
+ from playwright.sync_api import sync_playwright
301
+ except ImportError:
302
+ print('WARN: playwright not installed; skipping render check, settle 3s')
303
+ _t.sleep(3.0)
304
+ return
305
+ with sync_playwright() as p:
306
+ try:
307
+ browser = p.chromium.launch(channel='chrome', headless=True,
308
+ args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'])
309
+ except Exception as e:
310
+ print(f'WARN: could not launch chrome for render check: {e}; settle 3s')
311
+ _t.sleep(3.0)
312
+ return
313
+ try:
314
+ for name, url in mocks.items():
315
+ page = browser.new_page()
316
+ try:
317
+ page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000))
318
+ page.wait_for_function(
319
+ "document.body && document.body.innerText.length > 50",
320
+ timeout=int(render_timeout * 1000))
321
+ print(f'[{name}] rendered OK')
322
+ except Exception as e:
323
+ print(f'WARN: [{name}] render check issue: {e}')
324
+ finally:
325
+ page.close()
326
+ finally:
327
+ browser.close()
328
+
329
+
330
+ # ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render
331
+ _open_mock_tabs(APP_STATES, sid)
332
+ wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15)
333
+ wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12)
334
+ print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps')
sdr_lead_import_004__long/reward.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: lc_s2 — Bulk lead entry into CRM (review-fix v2)
3
+ Source: macOS CUA-Gym-Hub/task_benchmark/tasks/lc_s2.py
4
+ Original variant: eval
5
+ Mocks: salesforce_mock,google_sheets_mock,slack_mock
6
+ """
7
+ import re
8
+ import sys
9
+
10
+ import requests
11
+
12
+ try:
13
+ with open('/tmp/task_web_sid') as f:
14
+ sid = f.read().strip()
15
+ if not sid:
16
+ raise ValueError('sid is empty')
17
+ except Exception as e:
18
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
19
+ print('REWARD: 0.0')
20
+ sys.exit(0)
21
+
22
+ APP_URLS = {'salesforce': 'http://28.7.184.198:8175', 'google_sheets': 'http://28.7.184.198:8145', 'slack': 'http://28.7.184.198:8178'}
23
+ _GO_CACHE = {}
24
+
25
+
26
+ def go(app_name):
27
+ if app_name in _GO_CACHE:
28
+ return _GO_CACHE[app_name]
29
+ base = APP_URLS.get(app_name)
30
+ if not base:
31
+ print(f'CRITICAL: unknown app {app_name!r} (no URL placeholder mapped)')
32
+ print('REWARD: 0.0')
33
+ sys.exit(0)
34
+ try:
35
+ resp = requests.get(f'{base}/go?sid={sid}', timeout=15)
36
+ resp.raise_for_status()
37
+ payload = resp.json()
38
+ except Exception as e:
39
+ print(f'CRITICAL: cannot fetch {app_name} go state: {e}')
40
+ print('REWARD: 0.0')
41
+ sys.exit(0)
42
+ _GO_CACHE[app_name] = payload
43
+ return payload
44
+
45
+
46
+ def clamp01(x):
47
+ return max(0.0, min(1.0, float(x)))
48
+
49
+
50
+ def frac(num, den):
51
+ return 0.0 if den == 0 else num / den
52
+
53
+
54
+ def has_text(haystack, *needles):
55
+ s = (haystack or '').lower()
56
+ return any(n.lower() in s for n in needles)
57
+
58
+
59
+ def norm(s):
60
+ return (str(s) if s is not None else '').strip().lower()
61
+
62
+
63
+ def _msg_text(msg):
64
+ return msg.get('content') or msg.get('text') or ''
65
+
66
+
67
+ def _col_to_idx(col):
68
+ v = 0
69
+ for ch in col:
70
+ v = v * 26 + (ord(ch) - ord('A') + 1)
71
+ return v - 1
72
+
73
+
74
+ def _idx_to_col(idx):
75
+ idx += 1
76
+ out = []
77
+ while idx > 0:
78
+ idx, r = divmod(idx - 1, 26)
79
+ out.append(chr(ord('A') + r))
80
+ return ''.join(reversed(out))
81
+
82
+
83
+ def _parse_rows_from_sheet_data(sheet_data):
84
+ if not isinstance(sheet_data, dict) or not sheet_data:
85
+ return []
86
+ used_cols = set()
87
+ max_row = 1
88
+ for cell_id in sheet_data.keys():
89
+ m = re.fullmatch(r'([A-Z]+)(\d+)', str(cell_id))
90
+ if not m:
91
+ continue
92
+ used_cols.add(_col_to_idx(m.group(1)))
93
+ max_row = max(max_row, int(m.group(2)))
94
+ if not used_cols:
95
+ return []
96
+ headers = []
97
+ for cidx in sorted(used_cols):
98
+ cell = sheet_data.get(f'{_idx_to_col(cidx)}1', {})
99
+ h = (cell.get('computed') if isinstance(cell, dict) else None) or (cell.get('value') if isinstance(cell, dict) else None)
100
+ h = norm(h)
101
+ if h:
102
+ headers.append((cidx, h))
103
+ if not headers:
104
+ return []
105
+ rows = []
106
+ for r in range(2, max_row + 1):
107
+ row = {}
108
+ non_empty = False
109
+ for cidx, h in headers:
110
+ cell = sheet_data.get(f'{_idx_to_col(cidx)}{r}', {})
111
+ val = (cell.get('computed') if isinstance(cell, dict) else None)
112
+ if val is None:
113
+ val = (cell.get('value') if isinstance(cell, dict) else None)
114
+ sval = '' if val is None else str(val)
115
+ row[h] = sval
116
+ if sval.strip():
117
+ non_empty = True
118
+ if non_empty:
119
+ rows.append(row)
120
+ return rows
121
+
122
+
123
+ def _sheet_rows(go_payload, state_key, sheet_name):
124
+ state = go_payload.get(state_key, {})
125
+ sheets = state.get('sheets', {})
126
+ if isinstance(sheets, dict):
127
+ sheet = sheets.get(sheet_name, {})
128
+ rows = sheet.get('rows', [])
129
+ if isinstance(rows, list) and rows:
130
+ return rows
131
+ data_rows = _parse_rows_from_sheet_data(sheet.get('data', {}))
132
+ if data_rows:
133
+ return data_rows
134
+ if isinstance(sheets, list):
135
+ for sheet in sheets:
136
+ if norm(sheet.get('name')) != norm(sheet_name):
137
+ continue
138
+ rows = sheet.get('rows', [])
139
+ if isinstance(rows, list) and rows:
140
+ return rows
141
+ data_rows = _parse_rows_from_sheet_data(sheet.get('data', {}))
142
+ if data_rows:
143
+ return data_rows
144
+ adapter = state.get('_task_adapter', {})
145
+ rows = adapter.get('task_sheets', {}).get(sheet_name, {}).get('rows', [])
146
+ return rows if isinstance(rows, list) else []
147
+
148
+
149
+ def _slack_channel_messages(slack_state, channel_name):
150
+ channels = slack_state.get('channels', [])
151
+ target = None
152
+ for ch in channels:
153
+ if norm(ch.get('name')) == norm(channel_name):
154
+ target = ch
155
+ break
156
+ if target is None:
157
+ return []
158
+ ch_msgs = target.get('messages')
159
+ if isinstance(ch_msgs, list):
160
+ return ch_msgs
161
+ msg_map = slack_state.get('messages', {})
162
+ if isinstance(msg_map, dict):
163
+ return msg_map.get(target.get('channelId'), []) or []
164
+ return []
165
+
166
+
167
+ # =============================================================================
168
+ # Task-specific reward (v3: refined for strict 7-field per-lead match)
169
+ #
170
+ # Scoring formula:
171
+ # score = 0.70 * sf_match/N + 0.25 * sheet_match/N + 0.05 * slack_ok
172
+ #
173
+ # Where N = number of sheet rows whose initial Status is NOT 'Entered'
174
+ # (i.e. the rows the agent must process). For this task's setup, N = 8.
175
+ #
176
+ # Three independent sub-scores:
177
+ # 1. sf_match (0.70): For each target row, find a NEWLY-CREATED Salesforce
178
+ # lead that matches ALL 7 fields:
179
+ # firstName, lastName, company, phone, email,
180
+ # description (= sheet's notes), status='New'.
181
+ # All string compares are case-insensitive and trimmed.
182
+ # One newly-created lead can be consumed by at most one
183
+ # target (no double-counting).
184
+ # 2. sheet_match (0.25): For each target row index i, current_state row i has
185
+ # Status == 'Entered' (case-insensitive).
186
+ # 3. slack_ok (0.05): At least one message in #sales-ops whose text matches
187
+ # the regex /^entered\s+{n_target}\s+new\s+leads?\.?$/i
188
+ # where n_target = total number of rows the agent had to
189
+ # process (rows whose initial Status was not 'Entered').
190
+ # Aligns with instruction wording "{n} is the total number
191
+ # of rows you needed to process ... use this exact count
192
+ # even if you did not finish them all".
193
+ # =============================================================================
194
+ _SF_FIELD_KEYS = {
195
+ 'firstName': ('firstName', 'first_name', 'firstname', 'first name'),
196
+ 'lastName': ('lastName', 'last_name', 'lastname', 'last name'),
197
+ 'company': ('company',),
198
+ 'phone': ('phone',),
199
+ 'email': ('email',),
200
+ 'description': ('description', 'notes'),
201
+ 'status': ('status',),
202
+ }
203
+
204
+ _SHEET_FIELD_KEYS = {
205
+ 'firstName': ('first_name', 'firstname', 'first name'),
206
+ 'lastName': ('last_name', 'lastname', 'last name'),
207
+ 'company': ('company',),
208
+ 'phone': ('phone',),
209
+ 'email': ('email',),
210
+ 'description': ('notes', 'description'),
211
+ }
212
+
213
+
214
+ def _pick(record, aliases):
215
+ """Return record[alias] for first alias present, else ''."""
216
+ if not isinstance(record, dict):
217
+ return ''
218
+ for a in aliases:
219
+ if a in record and record[a] is not None:
220
+ return record[a]
221
+ return ''
222
+
223
+
224
+ def _lead_key(lead):
225
+ """3-tuple identity for a lead, used for diff-counting newly-created leads."""
226
+ return (
227
+ norm(_pick(lead, _SF_FIELD_KEYS['company'])),
228
+ norm(_pick(lead, _SF_FIELD_KEYS['firstName'])),
229
+ norm(_pick(lead, _SF_FIELD_KEYS['lastName'])),
230
+ )
231
+
232
+
233
+ def _row_expected_fields(row):
234
+ """Extract 6 expected field values from a sheet row, all normalized."""
235
+ return {
236
+ 'firstName': norm(_pick(row, _SHEET_FIELD_KEYS['firstName'])),
237
+ 'lastName': norm(_pick(row, _SHEET_FIELD_KEYS['lastName'])),
238
+ 'company': norm(_pick(row, _SHEET_FIELD_KEYS['company'])),
239
+ 'phone': norm(_pick(row, _SHEET_FIELD_KEYS['phone'])),
240
+ 'email': norm(_pick(row, _SHEET_FIELD_KEYS['email'])),
241
+ 'description': norm(_pick(row, _SHEET_FIELD_KEYS['description'])),
242
+ }
243
+
244
+
245
+ def _lead_full_match(lead, expected):
246
+ """7-field strict match: 6 fields + status='New'."""
247
+ if norm(_pick(lead, _SF_FIELD_KEYS['firstName'])) != expected['firstName']:
248
+ return False
249
+ if norm(_pick(lead, _SF_FIELD_KEYS['lastName'])) != expected['lastName']:
250
+ return False
251
+ if norm(_pick(lead, _SF_FIELD_KEYS['company'])) != expected['company']:
252
+ return False
253
+ if norm(_pick(lead, _SF_FIELD_KEYS['phone'])) != expected['phone']:
254
+ return False
255
+ if norm(_pick(lead, _SF_FIELD_KEYS['email'])) != expected['email']:
256
+ return False
257
+ if norm(_pick(lead, _SF_FIELD_KEYS['description'])) != expected['description']:
258
+ return False
259
+ if norm(_pick(lead, _SF_FIELD_KEYS['status'])) != 'new':
260
+ return False
261
+ return True
262
+
263
+
264
+ def reward(go):
265
+ rows_i = _sheet_rows(go('google_sheets'), 'initial_state', 'Inbound')
266
+ rows_c = _sheet_rows(go('google_sheets'), 'current_state', 'Inbound')
267
+ sf_i = go('salesforce')['initial_state'].get('leads', [])
268
+ sf_c = go('salesforce')['current_state'].get('leads', [])
269
+ slack = go('slack')['current_state']
270
+
271
+ if not rows_i:
272
+ return 0.0
273
+
274
+ # Targets = rows whose initial Status is not 'Entered'
275
+ target_idx = [i for i, r in enumerate(rows_i) if norm(r.get('status')) != 'entered']
276
+ n_target = len(target_idx)
277
+ if n_target == 0:
278
+ return 1.0
279
+
280
+ # ---- 1) Compute newly-created leads (current - initial, by 3-key) ----
281
+ init_counts = {}
282
+ for ld in sf_i:
283
+ k = _lead_key(ld)
284
+ init_counts[k] = init_counts.get(k, 0) + 1
285
+
286
+ # Track which current leads are "new" (not present in initial), preserving
287
+ # original objects so we can do full-field matching later.
288
+ initial_pool = dict(init_counts) # mutable copy: remaining initial budget per key
289
+ new_leads = []
290
+ for ld in sf_c:
291
+ k = _lead_key(ld)
292
+ if initial_pool.get(k, 0) > 0:
293
+ initial_pool[k] -= 1 # consumed by an initial lead
294
+ else:
295
+ new_leads.append(ld)
296
+ actual_new = len(new_leads)
297
+
298
+ # ---- 2) sf_match: per-target 7-field strict match against new leads ----
299
+ consumed = [False] * len(new_leads)
300
+ sf_match = 0
301
+ for i in target_idx:
302
+ expected = _row_expected_fields(rows_i[i])
303
+ for j, ld in enumerate(new_leads):
304
+ if consumed[j]:
305
+ continue
306
+ if _lead_full_match(ld, expected):
307
+ consumed[j] = True
308
+ sf_match += 1
309
+ break
310
+ sf_score = frac(sf_match, n_target)
311
+
312
+ # ---- 3) sheet_match: per-target row's current Status == 'Entered' ----
313
+ sheet_match = 0
314
+ for i in target_idx:
315
+ if i < len(rows_c) and norm(rows_c[i].get('status')) == 'entered':
316
+ sheet_match += 1
317
+ sheet_score = frac(sheet_match, n_target)
318
+
319
+ # ---- 4) slack_ok: strict regex over #sales-ops messages ----
320
+ # Per instruction, {n} = total number of rows to process = n_target,
321
+ # NOT the actual count of leads the agent created. Even if the agent
322
+ # only finished 3/8 rows, the message still has to say 'Entered 8 ...'.
323
+ chan = _slack_channel_messages(slack, 'sales-ops')
324
+ pat = re.compile(rf'^\s*entered\s+{n_target}\s+new\s+leads?\.?\s*$', re.I)
325
+ slack_ok = 1.0 if any(pat.match((_msg_text(msg) or '').strip()) for msg in chan) else 0.0
326
+
327
+ # ---- 5) Combine ----
328
+ s_sf = 0.70 * sf_score
329
+ s_sheet = 0.25 * sheet_score
330
+ s_slack = 0.05 * slack_ok
331
+ score = s_sf + s_sheet + s_slack
332
+
333
+ print(
334
+ 'DEBUG_S2 '
335
+ f'N={n_target} actual_new={actual_new} '
336
+ f'sf_match={sf_match}/{n_target} sf_score={round(sf_score, 4)} '
337
+ f'sheet_match={sheet_match}/{n_target} sheet_score={round(sheet_score, 4)} '
338
+ f'slack_ok={slack_ok} '
339
+ f'w_sf={round(s_sf, 4)} w_sheet={round(s_sheet, 4)} w_slack={round(s_slack, 4)} '
340
+ f'total={round(score, 4)}'
341
+ )
342
+
343
+ return clamp01(score)
344
+
345
+
346
+ try:
347
+ score = float(reward(go))
348
+ except Exception as exc:
349
+ print(f'ERROR: reward() raised {exc!r}')
350
+ score = 0.0
351
+
352
+ score = clamp01(score)
353
+ print(f'\nREWARD: {round(score, 4)}')
sre_change_review_002__long/_cua_gym_vm_bridge.sh ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # CUA-Gym VM-side network fix (direct-IP mock access).
3
+ #
4
+ # Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by
5
+ # their real IDC address (http://28.7.184.198:81xx) instead of the old
6
+ # localhost:9000-9097 socat bridge, so the VM only needs two fixes:
7
+ #
8
+ # 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's
9
+ # cluster DNS, which is unreachable from QEMU SLIRP NAT
10
+ # ("Temporary failure in name resolution").
11
+ # 2. The mock host excluded from the woa http proxy — otherwise the VM's
12
+ # Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403
13
+ # from the proxy when hitting 28.7.184.198:81xx. (The old socat path never
14
+ # hit this because localhost is bypassed by default.)
15
+ #
16
+ # Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic
17
+ # OSWorld setup pipeline.
18
+ #
19
+ # Argv:
20
+ # $1 optional sudo password (default "password"; SetupController
21
+ # substitutes {CLIENT_PASSWORD} when uploaded as a cache file).
22
+ # $2 unused (kept for backward compat — was socat first port 9000).
23
+ # $3 unused (kept for backward compat — was socat last port 9097).
24
+ # $4 optional mock host IP (default 28.7.184.198).
25
+
26
+ set +e
27
+
28
+ PASS="${1:-password}"
29
+ MOCK_HOST="${4:-28.7.184.198}"
30
+ # Derive the /16 IDC subnet so future port/host tweaks on the same segment
31
+ # stay bypassed too (28.7.184.198 -> 28.7.0.0/16).
32
+ MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')"
33
+
34
+ run_root() {
35
+ echo "$PASS" | sudo -S -p "" bash -c "$1"
36
+ }
37
+
38
+ # Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2.
39
+ GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')"
40
+ GW="${GW:-10.0.2.2}"
41
+
42
+ # ─── CUA-Gym network fix (Taiji-specific) ─────────────────────────────
43
+ fix_vm_network() {
44
+ # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP
45
+ # DNS forwarder. Nothing hardcoded except the mock host above.
46
+ local GW_NET="${GW%.*}"
47
+ local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3
48
+ local OWN_CIDR
49
+ OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \
50
+ | awk '{print $4; exit}')"
51
+ local OWN_IP="${OWN_CIDR%/*}"
52
+ local OWN_NET=""
53
+ [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24"
54
+
55
+ # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps
56
+ # systemd-resolved/NetworkManager from clobbering it.
57
+ if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf
58
+ chattr +i /etc/resolv.conf 2>/dev/null || true"; then
59
+ echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})"
60
+ else
61
+ echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf"
62
+ fi
63
+
64
+ # 2) Build the proxy bypass list from detected values + the direct-IP
65
+ # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx
66
+ # reachable from inside the VM — without it the woa proxy 403s it.
67
+ local ignore_list="['localhost', '127.0.0.0/8', '${GW}'"
68
+ [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'"
69
+ [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'"
70
+ [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'"
71
+ [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'"
72
+ [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'"
73
+ ignore_list="${ignore_list}]"
74
+
75
+ # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these.
76
+ if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then
77
+ echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}"
78
+ else
79
+ echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)"
80
+ fi
81
+
82
+ # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl).
83
+ local NP="localhost,127.0.0.1,${GW}"
84
+ [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}"
85
+ [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}"
86
+ [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24"
87
+ [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}"
88
+ [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}"
89
+
90
+ for var in no_proxy NO_PROXY; do
91
+ if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then
92
+ echo "export ${var}=${NP}" >> /home/user/.bashrc
93
+ fi
94
+ done
95
+ run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \
96
+ && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \
97
+ || echo 'no_proxy=\"${NP}\"' >> /etc/environment
98
+ grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \
99
+ && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \
100
+ || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1
101
+ echo "[cua_gym_vm_bridge] no_proxy=${NP}"
102
+ }
103
+
104
+ fix_vm_network
105
+
106
+ echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed"
sre_change_review_002__long/initial_setup.py ADDED
@@ -0,0 +1,692 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: W01 — SRE change review + deployment dispatch (v2)
3
+ Task ID: sre_change_review_002__long
4
+ Persona: SRE Mei
5
+ Mocks: ServiceNow_mock,gitlab_mock,slack_mock,google_sheets_mock
6
+
7
+ Ground-truth embedding (read by reward.py from initial_state):
8
+ - ServiceNow changeRequests[*]._expected_decision on every approval=='Requested'
9
+ change ('Approved' | 'Rejected'); decided by the risk/type rule.
10
+ - ServiceNow changeRequests[*]._expected_start / _expected_end on every pending
11
+ change — the fixed maintenance window the agent must set (Planned start/end).
12
+ Observable outputs kept ABSENT at injection (Rule 3):
13
+ - all 10 pending changes still have approval=='Requested' (not yet decided)
14
+ - all 10 pending changes still carry their OLD start_date/end_date (not the
15
+ fixed window) so "change the schedule" is a real edit
16
+ - GitLab has NO 'Deploy: CHG...' issue — the agent must New Issue each one
17
+ - Google Sheet 'Change Approvals' Decision column is blank on the 10 task rows
18
+ - Slack #change channel has zero messages
19
+ """
20
+ import os
21
+ import shlex
22
+ import subprocess
23
+ import time
24
+ import uuid
25
+
26
+ import requests
27
+
28
+ sid = str(uuid.uuid4())
29
+ with open('/tmp/task_web_sid', 'w') as f:
30
+ f.write(sid)
31
+ print(f'Generated sid: {sid}')
32
+
33
+
34
+ # ---------------------------------------------------------------------------
35
+ # Fixed maintenance window every pending change must be moved to (written
36
+ # dead, independent of execution time). Reward compares against these.
37
+ # ---------------------------------------------------------------------------
38
+ EXPECTED_START = '2026-06-15T02:00:00'
39
+ EXPECTED_END = '2026-06-15T04:00:00'
40
+
41
+
42
+ # ---------------------------------------------------------------------------
43
+ # Builders
44
+ # ---------------------------------------------------------------------------
45
+ def sn_change(sys_id, number, type_, short_desc, desc, state, risk, impact,
46
+ approval, assignment_group, assigned_to, requested_by,
47
+ start_date, end_date, expected_decision=None,
48
+ expected_start=None, expected_end=None,
49
+ close_code='', close_notes='', priority=3):
50
+ """ServiceNow ChangeRequest builder. expected_decision / expected_start /
51
+ expected_end are the embedded answer key for pending (approval=='Requested')
52
+ changes; ignored by the UI."""
53
+ rec = {
54
+ 'sys_id': sys_id, 'number': number, 'type': type_,
55
+ 'short_description': short_desc, 'description': desc,
56
+ 'state': state, 'priority': priority, 'impact': impact, 'risk': risk,
57
+ 'category': 'Software', 'assignment_group': assignment_group,
58
+ 'assigned_to': assigned_to, 'requested_by': requested_by,
59
+ 'opened_at': '2026-06-25T09:00:00.000Z', 'opened_by': requested_by,
60
+ 'start_date': start_date, 'end_date': end_date,
61
+ 'close_code': close_code, 'close_notes': close_notes,
62
+ 'updated_at': '2026-06-26T09:00:00.000Z', 'cmdb_ci': '',
63
+ 'approval': approval, 'conflict_status': 'No Conflicts',
64
+ }
65
+ if expected_decision is not None:
66
+ rec['_expected_decision'] = expected_decision # hidden answer key
67
+ if expected_start is not None:
68
+ rec['_expected_start'] = expected_start
69
+ if expected_end is not None:
70
+ rec['_expected_end'] = expected_end
71
+ return rec
72
+
73
+
74
+ def pending(sys_id, number, type_, short_desc, desc, risk, impact,
75
+ assignment_group, assigned_to, requested_by,
76
+ old_start, old_end, expected_decision, priority=3):
77
+ """A change awaiting approval: carries the answer key (decision + fixed
78
+ window) and an OLD schedule the agent must overwrite."""
79
+ state = -1 if type_ == 'Emergency' else -2
80
+ return sn_change(
81
+ sys_id, number, type_, short_desc, desc, state=state, risk=risk,
82
+ impact=impact, approval='Requested', assignment_group=assignment_group,
83
+ assigned_to=assigned_to, requested_by=requested_by,
84
+ start_date=old_start, end_date=old_end,
85
+ expected_decision=expected_decision,
86
+ expected_start=EXPECTED_START, expected_end=EXPECTED_END,
87
+ priority=priority)
88
+
89
+
90
+ def sn_user(sys_id, user_name, first, last, title, dept, role, avatar):
91
+ return {
92
+ 'sys_id': sys_id, 'user_name': user_name, 'first_name': first,
93
+ 'last_name': last, 'email': f'{user_name}@company.com', 'title': title,
94
+ 'department': dept, 'phone': '555-0100', 'avatar': avatar,
95
+ 'role': role, 'active': True, 'vip': False,
96
+ }
97
+
98
+
99
+ def gl_issue(issue_id, title, description, status, labels):
100
+ return {
101
+ 'id': issue_id, 'projectId': 1, 'title': title,
102
+ 'description': description, 'status': status, 'labels': labels,
103
+ 'assignee': 'Mei Tanaka',
104
+ }
105
+
106
+
107
+ def cell(v):
108
+ return {'value': str(v), 'formula': str(v), 'computed': str(v)}
109
+
110
+
111
+ def hcell(v):
112
+ return {'value': str(v), 'formula': str(v), 'computed': str(v),
113
+ 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}
114
+
115
+
116
+ # ---------------------------------------------------------------------------
117
+ # Decision rule (documented in instruction; encoded here only via the
118
+ # _expected_decision answer key, NOT re-derived in reward):
119
+ # Approve a pending change if Risk is Low or Moderate.
120
+ # Reject (with a reason) if Risk is High,
121
+ # UNLESS Type is Emergency, in which case Approve regardless of risk.
122
+ # ---------------------------------------------------------------------------
123
+ MEI = sn_user('u1', 'mei.tanaka', 'Mei', 'Tanaka', 'Site Reliability Engineer',
124
+ 'IT Operations', 'admin', 'MT')
125
+ USERS = [
126
+ MEI,
127
+ sn_user('u2', 'beth.anglin', 'Beth', 'Anglin', 'Release Manager', 'IT Operations', 'itil', 'BA'),
128
+ sn_user('u3', 'david.loo', 'David', 'Loo', 'Backend Engineer', 'Engineering', 'itil', 'DL'),
129
+ sn_user('u4', 'fred.luddy', 'Fred', 'Luddy', 'Network Engineer', 'IT Network', 'itil', 'FL'),
130
+ sn_user('u5', 'luke.wilson', 'Luke', 'Wilson', 'Database Engineer', 'IT Database', 'itil', 'LW'),
131
+ ]
132
+ GROUPS = [
133
+ {'sys_id': 'g1', 'name': 'Platform SRE', 'description': 'Site reliability', 'manager': 'u1', 'members': ['u1', 'u2'], 'type': 'itil', 'active': True},
134
+ {'sys_id': 'g2', 'name': 'Network', 'description': 'Network ops', 'manager': 'u4', 'members': ['u4'], 'type': 'itil', 'active': True},
135
+ {'sys_id': 'g3', 'name': 'Database', 'description': 'DB ops', 'manager': 'u5', 'members': ['u5'], 'type': 'itil', 'active': True},
136
+ {'sys_id': 'g5', 'name': 'Software', 'description': 'App delivery', 'manager': 'u3', 'members': ['u3', 'u5'], 'type': 'itil', 'active': True},
137
+ ]
138
+
139
+ # 10 pending changes covering every risk/type combination so the rule has
140
+ # real discrimination. Each carries an OLD (different) schedule the agent must
141
+ # move to the fixed window EXPECTED_START/EXPECTED_END.
142
+ CHANGE_REQUESTS = [
143
+ pending('chg_p1', 'CHG0030101', 'Normal',
144
+ 'Deploy payments-service v2.4.0 to production',
145
+ 'Rolling deploy of payments-service v2.4.0 (config + bugfix release). No schema changes.',
146
+ risk='Moderate', impact=2, assignment_group='g1', assigned_to='u1', requested_by='u3',
147
+ old_start='2026-05-03T22:00:00.000Z', old_end='2026-05-03T23:00:00.000Z',
148
+ expected_decision='Approved', priority=3),
149
+ pending('chg_p2', 'CHG0030102', 'Normal',
150
+ 'Migrate primary Postgres to new cluster (schema change)',
151
+ 'Cut over the primary Postgres database to a new cluster with an online schema migration. Irreversible during the window.',
152
+ risk='High', impact=1, assignment_group='g3', assigned_to='u5', requested_by='u5',
153
+ old_start='2026-05-06T02:00:00.000Z', old_end='2026-05-06T06:00:00.000Z',
154
+ expected_decision='Rejected', priority=2),
155
+ pending('chg_p3', 'CHG0030103', 'Standard',
156
+ 'Rotate TLS certificates on edge gateways',
157
+ 'Pre-approved template: rotate expiring TLS certificates on the edge gateway fleet. Zero-downtime hot reload.',
158
+ risk='Low', impact=3, assignment_group='g2', assigned_to='u4', requested_by='u4',
159
+ old_start='2026-05-09T18:00:00.000Z', old_end='2026-05-09T18:30:00.000Z',
160
+ expected_decision='Approved', priority=4),
161
+ pending('chg_p4', 'CHG0030104', 'Emergency',
162
+ 'Emergency patch for auth-service CVE-2026-1234',
163
+ 'Expedited patch of auth-service to remediate critical CVE-2026-1234 (auth bypass). High risk but urgent — Emergency override.',
164
+ risk='High', impact=1, assignment_group='g1', assigned_to='u1', requested_by='u1',
165
+ old_start='2026-05-11T20:00:00.000Z', old_end='2026-05-11T21:00:00.000Z',
166
+ expected_decision='Approved', priority=1),
167
+ pending('chg_p5', 'CHG0030105', 'Normal',
168
+ 'Bump nginx ingress to 1.25 across staging+prod',
169
+ 'Routine ingress controller upgrade. Backwards compatible config, rolling restart per node pool.',
170
+ risk='Low', impact=3, assignment_group='g1', assigned_to='u2', requested_by='u2',
171
+ old_start='2026-05-14T07:00:00.000Z', old_end='2026-05-14T08:00:00.000Z',
172
+ expected_decision='Approved', priority=4),
173
+ pending('chg_p6', 'CHG0030106', 'Normal',
174
+ 'Repartition Kafka topics for billing events',
175
+ 'Increase partition count on the billing event topics. High blast radius — consumers must be drained first.',
176
+ risk='High', impact=1, assignment_group='g3', assigned_to='u5', requested_by='u3',
177
+ old_start='2026-05-17T01:00:00.000Z', old_end='2026-05-17T04:00:00.000Z',
178
+ expected_decision='Rejected', priority=2),
179
+ pending('chg_p7', 'CHG0030107', 'Standard',
180
+ 'Quarterly OS package patching — app tier',
181
+ 'Pre-approved template: apply quarterly security package updates to the app-tier fleet, node by node.',
182
+ risk='Moderate', impact=2, assignment_group='g5', assigned_to='u3', requested_by='u3',
183
+ old_start='2026-05-20T22:00:00.000Z', old_end='2026-05-20T23:30:00.000Z',
184
+ expected_decision='Approved', priority=3),
185
+ pending('chg_p8', 'CHG0030108', 'Emergency',
186
+ 'Failover Redis cache to standby region',
187
+ 'Emergency failover of the Redis cache fleet to the standby region after primary-region degradation.',
188
+ risk='Moderate', impact=2, assignment_group='g1', assigned_to='u1', requested_by='u1',
189
+ old_start='2026-05-23T15:00:00.000Z', old_end='2026-05-23T16:00:00.000Z',
190
+ expected_decision='Approved', priority=2),
191
+ pending('chg_p9', 'CHG0030109', 'Normal',
192
+ 'Drop legacy columns from orders table',
193
+ 'Destructive schema change: drop deprecated columns from the orders table. No rollback once applied.',
194
+ risk='High', impact=1, assignment_group='g3', assigned_to='u5', requested_by='u5',
195
+ old_start='2026-05-26T03:00:00.000Z', old_end='2026-05-26T05:00:00.000Z',
196
+ expected_decision='Rejected', priority=2),
197
+ pending('chg_p10', 'CHG0030110', 'Emergency',
198
+ 'Hotfix runaway memory leak in checkout-service',
199
+ 'Emergency deploy of a hotfix for a memory leak crashing checkout-service pods. High risk, but production is bleeding — Emergency override.',
200
+ risk='High', impact=1, assignment_group='g1', assigned_to='u1', requested_by='u3',
201
+ old_start='2026-05-29T19:00:00.000Z', old_end='2026-05-29T20:00:00.000Z',
202
+ expected_decision='Approved', priority=1),
203
+ # ---- NOISE (already decided / not requested) — no Approve/Reject button,
204
+ # no answer key, not scored. ----
205
+ sn_change('chg_n1', 'CHG0030090', 'Normal',
206
+ 'Upgrade CDN edge configuration',
207
+ 'Already approved last week; scheduled. Do not touch.',
208
+ state=-2, risk='Low', impact=3, approval='Approved',
209
+ assignment_group='g2', assigned_to='u4', requested_by='u4',
210
+ start_date='2026-06-28T22:00:00.000Z', end_date='2026-06-28T23:00:00.000Z',
211
+ priority=4),
212
+ sn_change('chg_n2', 'CHG0030091', 'Normal',
213
+ 'Decommission legacy billing host',
214
+ 'Previously rejected pending capacity review. Do not touch.',
215
+ state=4, risk='Moderate', impact=2, approval='Rejected',
216
+ assignment_group='g5', assigned_to='u3', requested_by='u3',
217
+ start_date='2026-06-20T22:00:00.000Z', end_date='2026-06-20T23:00:00.000Z',
218
+ close_code='Cancelled', close_notes='Rejected: capacity review outstanding.',
219
+ priority=3),
220
+ sn_change('chg_n3', 'CHG0030092', 'Normal',
221
+ 'Draft: revamp logging pipeline',
222
+ 'Still a draft, approval not yet requested. Do not touch.',
223
+ state=-5, risk='Moderate', impact=2, approval='Not Yet Requested',
224
+ assignment_group='g1', assigned_to='u1', requested_by='u1',
225
+ start_date='', end_date='', priority=3),
226
+ ]
227
+
228
+ INCIDENTS = [
229
+ {'sys_id': 'inc1', 'number': 'INC0010001', 'caller_id': 'u3', 'category': 'Software',
230
+ 'subcategory': 'Application', 'contact_type': 'Self-service',
231
+ 'short_description': 'Elevated 5xx on payments-service', 'description': 'Error rate spiked after last deploy.',
232
+ 'state': 2, 'impact': 2, 'urgency': 2, 'priority': 3, 'assignment_group': 'g1',
233
+ 'assigned_to': 'u1', 'opened_at': '2026-06-26T08:00:00.000Z', 'opened_by': 'u3',
234
+ 'resolved_at': None, 'resolved_by': None, 'closed_at': None, 'closed_by': None,
235
+ 'close_code': '', 'close_notes': '', 'updated_at': '2026-06-26T08:00:00.000Z',
236
+ 'sla_due': '2026-06-28T08:00:00.000Z', 'cmdb_ci': 'ci1', 'knowledge': False},
237
+ {'sys_id': 'inc2', 'number': 'INC0010002', 'caller_id': 'u4', 'category': 'Network',
238
+ 'subcategory': 'VPN', 'contact_type': 'Phone',
239
+ 'short_description': 'Intermittent VPN drops', 'description': 'Users report VPN disconnects.',
240
+ 'state': 1, 'impact': 3, 'urgency': 3, 'priority': 5, 'assignment_group': 'g2',
241
+ 'assigned_to': None, 'opened_at': '2026-06-25T10:00:00.000Z', 'opened_by': 'u4',
242
+ 'resolved_at': None, 'resolved_by': None, 'closed_at': None, 'closed_by': None,
243
+ 'close_code': '', 'close_notes': '', 'updated_at': '2026-06-25T10:00:00.000Z',
244
+ 'sla_due': '2026-06-29T10:00:00.000Z', 'cmdb_ci': None, 'knowledge': False},
245
+ ]
246
+
247
+ CMDB_ITEMS = [
248
+ {'sys_id': 'ci1', 'name': 'payments-service', 'sys_class_name': 'cmdb_ci_app_server',
249
+ 'status': 'Installed', 'environment': 'Production', 'category': 'Software',
250
+ 'assigned_to': 'u1', 'department': 'IT Operations', 'location': 'us-east-1',
251
+ 'ip_address': '10.0.1.20', 'serial_number': 'SVC-PAY-01', 'manufacturer': 'Internal',
252
+ 'model': 'k8s-deployment'},
253
+ ]
254
+
255
+ SERVICENOW_STATE = {
256
+ 'currentUser': MEI,
257
+ 'users': USERS,
258
+ 'groups': GROUPS,
259
+ 'incidents': INCIDENTS,
260
+ 'problems': [],
261
+ 'changeRequests': CHANGE_REQUESTS,
262
+ 'catalog': {'sys_id': 'cat1', 'title': 'Service Catalog', 'description': 'Browse and order IT services and equipment', 'active': True},
263
+ 'catalogCategories': [],
264
+ 'catalogItems': [],
265
+ 'requests': [],
266
+ 'requestedItems': [],
267
+ 'kbCategories': [],
268
+ 'kbArticles': [],
269
+ 'cmdbItems': CMDB_ITEMS,
270
+ 'journal': [],
271
+ 'notifications': [
272
+ {'sys_id': 'notif1', 'type': 'approval', 'target_table': 'change_request',
273
+ 'target_id': 'chg_p4', 'target_number': 'CHG0030104',
274
+ 'message': 'CHG0030104 requires approval', 'created_at': '2026-06-30T19:00:00.000Z',
275
+ 'read': False, 'actor': 'u1'},
276
+ {'sys_id': 'notif2', 'type': 'approval', 'target_table': 'change_request',
277
+ 'target_id': 'chg_p1', 'target_number': 'CHG0030101',
278
+ 'message': 'CHG0030101 requires approval', 'created_at': '2026-06-26T09:00:00.000Z',
279
+ 'read': False, 'actor': 'u3'},
280
+ ],
281
+ 'shoppingCart': [],
282
+ 'navigatorFilter': '',
283
+ 'navigatorExpandedSections': ['Change'],
284
+ 'activeModule': 'change',
285
+ 'favorites': [],
286
+ 'history': [],
287
+ 'currentListFilters': {},
288
+ 'currentSortColumn': None,
289
+ 'currentSortDirection': 'asc',
290
+ }
291
+
292
+ # ---------------------------------------------------------------------------
293
+ # GitLab — platform-infra project. NO 'Deploy: CHG...' issue is pre-seeded:
294
+ # the agent must New Issue one per APPROVED change (title 'Deploy: <CHG>').
295
+ # Only a few unrelated noise issues exist. (Reducer has no DELETE_ISSUE, so the
296
+ # board cannot be cleaned — reward never penalises extra issues.)
297
+ # ---------------------------------------------------------------------------
298
+ GITLAB_STATE = {
299
+ 'currentUser': {'id': 1, 'name': 'Mei Tanaka', 'username': 'mei.tanaka', 'avatarUrl': ''},
300
+ 'projects': [
301
+ {'id': 1, 'name': 'platform-infra', 'description': 'Production platform & deployment automation',
302
+ 'visibility': 'private', 'stars': 7, 'forks': 2, 'updatedAt': '2026-06-26T00:00:00.000Z',
303
+ 'branches': ['main', 'release', 'hotfix'], 'files': []},
304
+ ],
305
+ 'pipelines': [],
306
+ 'issues': [
307
+ gl_issue(1, 'Update deployment runbook', 'Doc chore: refresh the on-call deployment runbook.', 'open', ['docs']),
308
+ gl_issue(2, 'Investigate flaky e2e test', 'Known flaky checkout e2e test in CI.', 'in_progress', ['ci']),
309
+ gl_issue(3, 'Tune Prometheus alert thresholds', 'Reduce noisy alerts on the staging cluster.', 'open', ['observability']),
310
+ ],
311
+ 'mergeRequests': [],
312
+ 'registry': [],
313
+ 'snippets': [],
314
+ 'wiki': [],
315
+ 'vulnerabilities': [],
316
+ 'milestones': [],
317
+ 'releases': [],
318
+ }
319
+
320
+ # ---------------------------------------------------------------------------
321
+ # Slack — #change channel starts empty; decoy chatter elsewhere.
322
+ # ---------------------------------------------------------------------------
323
+ SLACK_STATE = {
324
+ 'channels': [
325
+ {'channelId': 'general', 'name': 'general', 'description': 'Company-wide chatter', 'topic': 'Welcome!', 'isPrivate': False, 'isStarred': True, 'members': ['user_1', 'user_2', 'user_3', 'user_4'], 'createdBy': 'user_2', 'createdAt': '2026-05-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0},
326
+ {'channelId': 'incidents', 'name': 'incidents', 'description': 'Live incident coordination', 'topic': 'Page here', 'isPrivate': False, 'isStarred': False, 'members': ['user_1', 'user_2', 'user_3', 'user_4'], 'createdBy': 'user_1', 'createdAt': '2026-05-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0},
327
+ {'channelId': 'change', 'name': 'change', 'description': 'Change advisory board — approvals and deploy dispatch', 'topic': 'Post a summary after every change-review batch', 'isPrivate': False, 'isStarred': False, 'members': ['user_1', 'user_2', 'user_3'], 'createdBy': 'user_1', 'createdAt': '2026-06-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0},
328
+ ],
329
+ 'currentUser': {'userId': 'user_1', 'fullName': 'Mei Tanaka', 'displayName': 'Mei', 'email': 'mei.tanaka@company.com', 'avatar': 'https://picsum.photos/200/200?random=1', 'title': 'Site Reliability Engineer', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Los_Angeles'},
330
+ 'users': [
331
+ {'userId': 'user_1', 'fullName': 'Mei Tanaka', 'displayName': 'Mei', 'email': 'mei.tanaka@company.com', 'avatar': 'https://picsum.photos/200/200?random=1', 'title': 'Site Reliability Engineer', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Los_Angeles'},
332
+ {'userId': 'user_2', 'fullName': 'Beth Anglin', 'displayName': 'Beth', 'email': 'beth.anglin@company.com', 'avatar': 'https://picsum.photos/200/200?random=2', 'title': 'Release Manager', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'},
333
+ {'userId': 'user_3', 'fullName': 'David Loo', 'displayName': 'David', 'email': 'david.loo@company.com', 'avatar': 'https://picsum.photos/200/200?random=3', 'title': 'Backend Engineer', 'status': 'away', 'statusMessage': 'Heads down', 'statusEmoji': ':no_bell:', 'timeZone': 'Asia/Tokyo'},
334
+ {'userId': 'user_4', 'fullName': 'Fred Luddy', 'displayName': 'Fred', 'email': 'fred.luddy@company.com', 'avatar': 'https://picsum.photos/200/200?random=4', 'title': 'Network Engineer', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Chicago'},
335
+ ],
336
+ 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Acme Corp', 'icon': ''},
337
+ 'messages': {
338
+ 'general': [
339
+ {'messageId': 'm_g_1', 'senderId': 'user_2', 'content': 'Morning all — change freeze lifts today, so the review queue is open again.', 'timestamp': '2026-06-30T13:02:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []},
340
+ {'messageId': 'm_g_2', 'senderId': 'user_4', 'content': 'Thanks Beth! I have a couple of changes waiting on approval.', 'timestamp': '2026-06-30T13:05:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []},
341
+ ],
342
+ 'incidents': [
343
+ {'messageId': 'm_i_1', 'senderId': 'user_3', 'content': 'payments-service 5xx is back under threshold after the rollback.', 'timestamp': '2026-06-29T22:10:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []},
344
+ ],
345
+ 'change': [],
346
+ },
347
+ 'threads': {},
348
+ 'dms': [],
349
+ 'bookmarkedMessages': [],
350
+ 'callHistory': [],
351
+ 'settings': {'theme': 'light', 'notifications': 'all', 'displayDensity': 'comfortable', 'showAvatars': True, 'use24Hour': False},
352
+ 'invitations': [],
353
+ 'notifications': [],
354
+ }
355
+
356
+ # ---------------------------------------------------------------------------
357
+ # Google Sheets — 'Change Approvals' ledger.
358
+ # Row 1: header (CHG Number | Decision)
359
+ # Row 2: a worked EXAMPLE (CHG-EXAMPLE | Approved) — demonstrates format,
360
+ # NOT scored.
361
+ # Rows 3..12: the 10 pending CHG numbers in col A; Decision (col B) BLANK
362
+ # (Rule 3) — agent fills each with Approved/Rejected.
363
+ # ---------------------------------------------------------------------------
364
+ PENDING_NUMBERS = [c['number'] for c in CHANGE_REQUESTS
365
+ if c.get('approval') == 'Requested']
366
+ _sheet_data = {
367
+ 'A1': hcell('CHG Number'),
368
+ 'B1': hcell('Decision'),
369
+ 'A2': cell('CHG-EXAMPLE'),
370
+ 'B2': cell('Approved'), # example row — reward ignores it
371
+ }
372
+ for _i, _num in enumerate(PENDING_NUMBERS):
373
+ _r = _i + 3
374
+ _sheet_data[f'A{_r}'] = cell(_num)
375
+ _sheet_data[f'B{_r}'] = cell('') # blank — agent fills this
376
+
377
+ SHEETS_STATE = {
378
+ 'id': 'workbook_change_review', 'title': 'Change Approvals',
379
+ 'activeSheetId': 'sheet_1', 'selectedCell': 'A1', 'selectionRange': None,
380
+ 'clipboard': None, 'isDragging': False, 'undoStack': [], 'redoStack': [],
381
+ 'namedRanges': [], 'conditionalFormats': [], 'charts': [],
382
+ 'showGridlines': True, 'showFormulas': False, 'zoom': 100,
383
+ 'sheets': [{
384
+ 'id': 'sheet_1', 'name': 'Change Approvals', 'data': _sheet_data,
385
+ 'rowCount': 100, 'colCount': 26, 'frozenRows': 1, 'frozenCols': 0,
386
+ 'tabColor': None, 'isHidden': False, 'columnWidths': {}, 'rowHeights': {},
387
+ 'filterRange': None, 'filterCriteria': {}, 'sortColumn': None,
388
+ 'sortDirection': None,
389
+ }],
390
+ }
391
+
392
+
393
+ APP_STATES = [
394
+ ('http://28.7.184.198:8105', SERVICENOW_STATE), # ServiceNow_mock (L2 anchor)
395
+ ('http://28.7.184.198:8137', GITLAB_STATE), # gitlab_mock
396
+ ('http://28.7.184.198:8178', SLACK_STATE), # slack_mock
397
+ ('http://28.7.184.198:8145', SHEETS_STATE), # google_sheets_mock
398
+ ]
399
+
400
+ for placeholder, state in APP_STATES:
401
+ resp = requests.post(
402
+ f'{placeholder}/post?sid={sid}',
403
+ json={'action': 'set', 'state': state},
404
+ timeout=30,
405
+ )
406
+ assert resp.status_code == 200, (
407
+ f'State injection failed for {placeholder}: {resp.text}'
408
+ )
409
+ print(f'State injected: {placeholder} sid={sid}')
410
+
411
+ for placeholder, _ in APP_STATES:
412
+ go = requests.get(f'{placeholder}/go?sid={sid}', timeout=15).json()
413
+ assert go.get('initial_state') is not None, (
414
+ f'initial_state is None after injection for {placeholder}'
415
+ )
416
+ print(f'Verified initial_state set: {placeholder}')
417
+
418
+
419
+ def wait_mocks_ready(urls, sid, timeout=60, render_buffer=8):
420
+ """Pure-HTTP readiness: wait for every mock to serve its injected state.
421
+ No CDP / 9222 probing (that hangs on local review boxes)."""
422
+ import urllib.request as _urlreq
423
+ _opener = _urlreq.build_opener(_urlreq.ProxyHandler({}))
424
+ deadline = time.time() + timeout
425
+ todo = list(urls)
426
+ while todo and time.time() < deadline:
427
+ rest = []
428
+ for _u in todo:
429
+ try:
430
+ _r = _opener.open(f"{_u}/go?sid={sid}", timeout=5)
431
+ if _r.status == 200:
432
+ print(f" {_u}: ready")
433
+ continue
434
+ except Exception:
435
+ pass
436
+ rest.append(_u)
437
+ todo = rest
438
+ if todo:
439
+ time.sleep(2)
440
+ print(f" mocks ready: {len(urls) - len(todo)}/{len(urls)}"
441
+ + (f" (pending: {todo})" if todo else ""))
442
+ time.sleep(render_buffer)
443
+
444
+
445
+ # PATCHED_BY: patch_wait_mocks_loaded.py
446
+ def launch_gui(command, delay_sec=1.0):
447
+ """Launch a GUI command, fully detached from this script.
448
+
449
+ Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that
450
+ wait_mocks_loaded's CDP phase can verify browser render below.
451
+ Idempotent: if the caller already specified a debug port, keep it.
452
+ """
453
+ env = os.environ.copy()
454
+ env['DISPLAY'] = ':0'
455
+ if isinstance(command, str):
456
+ _parts = shlex.split(command)
457
+ else:
458
+ _parts = list(command)
459
+ if (_parts and 'google-chrome' in _parts[0]
460
+ and not any(p.startswith('--remote-debugging-port') for p in _parts)):
461
+ _parts[1:1] = [
462
+ '--no-first-run',
463
+ '--no-default-browser-check',
464
+ '--remote-debugging-port=1337',
465
+ ]
466
+ subprocess.Popen(
467
+ _parts,
468
+ stdin=subprocess.DEVNULL,
469
+ stdout=subprocess.DEVNULL,
470
+ stderr=subprocess.DEVNULL,
471
+ env=env,
472
+ start_new_session=True,
473
+ )
474
+ time.sleep(delay_sec)
475
+
476
+
477
+ def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12):
478
+ """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style.
479
+
480
+ Phase 1 - Backend readiness:
481
+ Poll each mock's /state?sid=<sid> (preferred) or /go?sid=<sid>
482
+ (fallback) until it returns 200 with 'stored_state' or
483
+ 'initial_state' respectively, or until timeout.
484
+
485
+ Phase 2 - Browser render verification (via CDP + Playwright):
486
+ Connect to http://localhost:1337 (the --remote-debugging-port
487
+ injected by launch_gui above), wait for every open tab to reach
488
+ 'networkidle' AND to contain at least 20 DOM elements. This
489
+ guarantees the SPA fetched /go?sid= data AND actually painted,
490
+ not just that the mock backend is up.
491
+
492
+ Fallback:
493
+ If Playwright is missing or CDP cannot be reached, sleep for
494
+ `render_buffer` seconds as a best-effort delay so the screenshot
495
+ loop does not start on a still-blank tab.
496
+ """
497
+ import urllib.request as _urlreq
498
+ import time as _t
499
+ _urls = [p for p, _ in app_states]
500
+ _opener = _urlreq.build_opener(_urlreq.ProxyHandler({}))
501
+
502
+ # ---- Phase 1: backend readiness ----
503
+ _deadline = _t.time() + timeout
504
+ _todo = list(_urls)
505
+ while _todo and _t.time() < _deadline:
506
+ _rest = []
507
+ for _u in _todo:
508
+ _ok = False
509
+ for _path, _need in (('/state?sid=', b'stored_state'),
510
+ ('/go?sid=', b'initial_state')):
511
+ try:
512
+ _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5)
513
+ if _r.status == 200:
514
+ _body = _r.read()
515
+ if _need in _body:
516
+ _ok = True
517
+ break
518
+ except Exception:
519
+ pass
520
+ if _ok:
521
+ print(f" {_u}: backend ready")
522
+ continue
523
+ _rest.append(_u)
524
+ _todo = _rest
525
+ if _todo:
526
+ _t.sleep(2)
527
+ _done = len(_urls) - len(_todo)
528
+ _pend = f" (pending: {_todo})" if _todo else ""
529
+ print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}")
530
+
531
+ # ---- Phase 2: browser render verification via CDP ----
532
+ _cdp_ok = False
533
+ try:
534
+ from playwright.sync_api import sync_playwright
535
+ _cdp_dl = _t.time() + max(15.0, _deadline - _t.time())
536
+ with sync_playwright() as _p:
537
+ _br = None
538
+ while _t.time() < _cdp_dl:
539
+ try:
540
+ _br = _p.chromium.connect_over_cdp('http://localhost:1337')
541
+ break
542
+ except Exception:
543
+ _t.sleep(0.5)
544
+ if _br is None:
545
+ print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?")
546
+ else:
547
+ _n_expected = len(_urls)
548
+ _pages = []
549
+ _pg_dl = _t.time() + 15
550
+ _last_count = -1
551
+ _stable_since = None
552
+ while _t.time() < _pg_dl:
553
+ _pages = []
554
+ for _c in _br.contexts:
555
+ _pages.extend(_c.pages)
556
+ _cnt = len(_pages)
557
+ if _n_expected > 0 and _cnt >= _n_expected:
558
+ break
559
+ if _cnt > 0 and _cnt == _last_count:
560
+ if _stable_since is None:
561
+ _stable_since = _t.time()
562
+ elif _t.time() - _stable_since >= 1.5:
563
+ break
564
+ else:
565
+ _stable_since = None
566
+ _last_count = _cnt
567
+ _t.sleep(0.5)
568
+ _pages = []
569
+ for _c in _br.contexts:
570
+ _pages.extend(_c.pages)
571
+ if not _pages:
572
+ print(" wait_mocks_loaded: CDP connected but no open tabs found")
573
+ else:
574
+ print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render")
575
+ _MIN_ELEMS = 20
576
+ _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap
577
+ for _pg in _pages: # bring each to front once to defeat background-tab render throttling
578
+ try:
579
+ _pg.bring_to_front()
580
+ except Exception:
581
+ pass
582
+ _pending = list(_pages)
583
+ while _pending and _t.time() < _verify_dl:
584
+ _still = []
585
+ for _pg in _pending:
586
+ _ttl = ""
587
+ try:
588
+ _ttl = _pg.title()
589
+ except Exception:
590
+ pass
591
+ try:
592
+ _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0")
593
+ except Exception:
594
+ _n = 0
595
+ if _n >= _MIN_ELEMS:
596
+ print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)")
597
+ else:
598
+ _still.append(_pg)
599
+ _pending = _still
600
+ if _pending:
601
+ _t.sleep(2)
602
+ if not _pending:
603
+ _cdp_ok = True
604
+ else:
605
+ for _pg in _pending:
606
+ _ttl = ""
607
+ try:
608
+ _ttl = _pg.title()
609
+ except Exception:
610
+ pass
611
+ print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back")
612
+ except ImportError:
613
+ print(" wait_mocks_loaded: playwright not installed; skipping CDP phase")
614
+ except Exception as _e:
615
+ print(f" wait_mocks_loaded: CDP phase error ({_e!r})")
616
+
617
+ if not _cdp_ok:
618
+ print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep")
619
+ _t.sleep(render_buffer)
620
+ else:
621
+ print(" wait_mocks_loaded: browser render verified, skipping render_buffer")
622
+
623
+
624
+ def _open_mock_tabs(app_states, sid_value):
625
+ """Open the first mock as the primary Chrome window, the rest as new tabs.
626
+
627
+ Uses launch_gui once per URL so that the macOS localizer regex-extract
628
+ (which grabs the FIRST quoted URL per call) still works correctly.
629
+ """
630
+ _urls = [p for p, _ in app_states]
631
+ if not _urls:
632
+ return
633
+ launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0)
634
+ for _u in _urls[1:]:
635
+ launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0)
636
+
637
+
638
+
639
+ # PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate)
640
+ def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0):
641
+ """Block until every mock serves injected state AND (best-effort) renders."""
642
+ import time as _t
643
+ deadline = _t.time() + timeout
644
+ pending = dict(mocks)
645
+ while pending and _t.time() < deadline:
646
+ for name in list(pending):
647
+ try:
648
+ r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5)
649
+ if r.status_code == 200 and r.json().get('initial_state') is not None:
650
+ del pending[name]
651
+ except Exception:
652
+ pass
653
+ if pending:
654
+ _t.sleep(1.0)
655
+ if pending:
656
+ print(f'WARN: mocks not ready within {timeout}s: {list(pending)}')
657
+ try:
658
+ from playwright.sync_api import sync_playwright
659
+ except ImportError:
660
+ print('WARN: playwright not installed; skipping render check, settle 3s')
661
+ _t.sleep(3.0)
662
+ return
663
+ with sync_playwright() as p:
664
+ try:
665
+ browser = p.chromium.launch(channel='chrome', headless=True,
666
+ args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'])
667
+ except Exception as e:
668
+ print(f'WARN: could not launch chrome for render check: {e}; settle 3s')
669
+ _t.sleep(3.0)
670
+ return
671
+ try:
672
+ for name, url in mocks.items():
673
+ page = browser.new_page()
674
+ try:
675
+ page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000))
676
+ page.wait_for_function(
677
+ "document.body && document.body.innerText.length > 50",
678
+ timeout=int(render_timeout * 1000))
679
+ print(f'[{name}] rendered OK')
680
+ except Exception as e:
681
+ print(f'WARN: [{name}] render check issue: {e}')
682
+ finally:
683
+ page.close()
684
+ finally:
685
+ browser.close()
686
+
687
+
688
+ # ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render
689
+ _open_mock_tabs(APP_STATES, sid)
690
+ wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15)
691
+ wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12)
692
+ print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps')
sre_change_review_002__long/reward.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: W01 — SRE change review + deployment dispatch (v2)
3
+ Task ID: sre_change_review_002__long
4
+ Persona: SRE Mei
5
+ Mocks: ServiceNow_mock,gitlab_mock,slack_mock,google_sheets_mock
6
+
7
+ Answer key (embedded in initial_state):
8
+ - ServiceNow changeRequests[*]._expected_decision on every approval=='Requested'
9
+ change ('Approved' | 'Rejected').
10
+ - ServiceNow changeRequests[*]._expected_start / _expected_end on every pending
11
+ change — the fixed maintenance window the schedule must be moved to.
12
+
13
+ Scoring (sub-weights sum to 1.0):
14
+ 0.45 ServiceNow decisions (L2 anchor): per pending change, current approval
15
+ == _expected_decision. Reachable only via the gated Approve/Reject
16
+ buttons (rendered only when !isNew && approval=='Requested').
17
+ 0.20 ServiceNow schedule (L2 anchor a'): per pending change, current
18
+ start_date/end_date == _expected_start/_expected_end (datetime
19
+ normalized to a 'YYYY-MM-DDTHH:MM' prefix).
20
+ 0.15 GitLab deploy issues (recall, no penalty for extras): for each APPROVED
21
+ change, an issue titled 'Deploy: <CHG number>' exists. score = hits /
22
+ should-build. Extra/wrong issues are NEVER penalised (GitLab cannot
23
+ delete issues).
24
+ 0.10 Google Sheet ledger: per pending change's row, Decision column ==
25
+ expected decision (the CHG-EXAMPLE row is ignored).
26
+ 0.10 Slack #change summary: a message whose 'X approved, Y rejected' counts
27
+ match the expected number of approvals/rejections.
28
+ """
29
+ import re
30
+ import sys
31
+
32
+ import requests
33
+
34
+ # --- Read sid (fatal if missing) ---
35
+ try:
36
+ with open('/tmp/task_web_sid') as f:
37
+ sid = f.read().strip()
38
+ if not sid:
39
+ raise ValueError('sid is empty')
40
+ except Exception as e:
41
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
42
+ print('REWARD: 0.0')
43
+ sys.exit(0)
44
+
45
+ APP_URLS = {
46
+ 'servicenow': 'http://28.7.184.198:8105',
47
+ 'gitlab': 'http://28.7.184.198:8137',
48
+ 'slack': 'http://28.7.184.198:8178',
49
+ 'google_sheets': 'http://28.7.184.198:8145',
50
+ }
51
+ _GO_CACHE = {}
52
+
53
+
54
+ def go(app_name):
55
+ if app_name in _GO_CACHE:
56
+ return _GO_CACHE[app_name]
57
+ base = APP_URLS.get(app_name)
58
+ if not base:
59
+ print(f'CRITICAL: unknown app {app_name!r} (no URL placeholder mapped)')
60
+ print('REWARD: 0.0')
61
+ sys.exit(0)
62
+ try:
63
+ resp = requests.get(f'{base}/go?sid={sid}', timeout=15)
64
+ resp.raise_for_status()
65
+ payload = resp.json()
66
+ except Exception as e:
67
+ print(f'CRITICAL: cannot fetch {app_name} go state: {e}')
68
+ print('REWARD: 0.0')
69
+ sys.exit(0)
70
+ _GO_CACHE[app_name] = payload
71
+ return payload
72
+
73
+
74
+ # --- Shared utils ---
75
+ def clamp01(x):
76
+ return max(0.0, min(1.0, float(x)))
77
+
78
+
79
+ def frac(num, den):
80
+ return 0.0 if den == 0 else num / den
81
+
82
+
83
+ def norm(s):
84
+ return (str(s) if s is not None else '').strip().lower()
85
+
86
+
87
+ def _collapse_ws(s):
88
+ return re.sub(r'\s+', ' ', norm(s))
89
+
90
+
91
+ def _dt_key(s):
92
+ """Normalize a datetime-ish string to a 'YYYY-MM-DDTHH:MM' prefix so
93
+ ISO-with-Z / milliseconds / seconds differences don't matter."""
94
+ s = (str(s) if s is not None else '').strip()
95
+ if not s:
96
+ return ''
97
+ s = s.replace(' ', 'T')
98
+ return s[:16]
99
+
100
+
101
+ def _to_epoch_min(s):
102
+ """Parse a datetime string to integer epoch-minutes (UTC). Treats a bare
103
+ (tz-less) value as UTC. Returns None on failure."""
104
+ import datetime as _dt
105
+ s = (str(s) if s is not None else '').strip()
106
+ if not s:
107
+ return None
108
+ s = s.replace(' ', 'T')
109
+ # strip milliseconds
110
+ s = re.sub(r'\.\d+', '', s)
111
+ try:
112
+ if s.endswith('Z'):
113
+ d = _dt.datetime.strptime(s[:19], '%Y-%m-%dT%H:%M:%S').replace(tzinfo=_dt.timezone.utc)
114
+ elif re.search(r'[+-]\d{2}:\d{2}$', s):
115
+ d = _dt.datetime.fromisoformat(s)
116
+ else:
117
+ # bare wall-clock — assume UTC
118
+ core = s[:19] if len(s) >= 19 else s + ':00'
119
+ d = _dt.datetime.strptime(core[:19], '%Y-%m-%dT%H:%M:%S').replace(tzinfo=_dt.timezone.utc)
120
+ return int(d.timestamp() // 60)
121
+ except Exception:
122
+ return None
123
+
124
+
125
+ def _schedule_matches(cur_val, expected_wall):
126
+ """True if the stored value equals the expected wall-clock time under SOME
127
+ whole-hour UTC offset. The ServiceNow ChangeForm stores schedule as
128
+ `new Date(<datetime-local wall clock>).toISOString()`, so the persisted
129
+ UTC instant is the expected wall-clock interpreted in the browser/VM tz.
130
+ We accept any whole-hour offset within +/-14h (covers all real tz), with
131
+ minutes matching exactly. Falls back to exact prefix match."""
132
+ if _dt_key(cur_val) == _dt_key(expected_wall):
133
+ return True
134
+ cur_m = _to_epoch_min(cur_val)
135
+ exp_m = _to_epoch_min(expected_wall)
136
+ if cur_m is None or exp_m is None:
137
+ return False
138
+ diff = abs(cur_m - exp_m)
139
+ # whole-hour offset, |offset| <= 14h
140
+ return diff % 60 == 0 and diff <= 14 * 60
141
+
142
+
143
+ def _msg_text(msg):
144
+ return msg.get('content') or msg.get('text') or ''
145
+
146
+
147
+ def _col_to_idx(col):
148
+ v = 0
149
+ for ch in col:
150
+ v = v * 26 + (ord(ch) - ord('A') + 1)
151
+ return v - 1
152
+
153
+
154
+ def _idx_to_col(idx):
155
+ idx += 1
156
+ out = []
157
+ while idx > 0:
158
+ idx, r = divmod(idx - 1, 26)
159
+ out.append(chr(ord('A') + r))
160
+ return ''.join(reversed(out))
161
+
162
+
163
+ def _parse_rows_from_sheet_data(sheet_data):
164
+ if not isinstance(sheet_data, dict) or not sheet_data:
165
+ return []
166
+ used_cols = set()
167
+ max_row = 1
168
+ for cell_id in sheet_data.keys():
169
+ m = re.fullmatch(r'([A-Z]+)(\d+)', str(cell_id))
170
+ if not m:
171
+ continue
172
+ used_cols.add(_col_to_idx(m.group(1)))
173
+ max_row = max(max_row, int(m.group(2)))
174
+ if not used_cols:
175
+ return []
176
+ headers = []
177
+ for cidx in sorted(used_cols):
178
+ cell = sheet_data.get(f'{_idx_to_col(cidx)}1', {})
179
+ h = (cell.get('computed') if isinstance(cell, dict) else None) or (cell.get('value') if isinstance(cell, dict) else None)
180
+ h = norm(h)
181
+ if h:
182
+ headers.append((cidx, h))
183
+ if not headers:
184
+ return []
185
+ rows = []
186
+ for r in range(2, max_row + 1):
187
+ row = {}
188
+ non_empty = False
189
+ for cidx, h in headers:
190
+ cell = sheet_data.get(f'{_idx_to_col(cidx)}{r}', {})
191
+ val = (cell.get('computed') if isinstance(cell, dict) else None)
192
+ if val is None:
193
+ val = (cell.get('value') if isinstance(cell, dict) else None)
194
+ sval = '' if val is None else str(val)
195
+ row[h] = sval
196
+ if sval.strip():
197
+ non_empty = True
198
+ if non_empty:
199
+ rows.append(row)
200
+ return rows
201
+
202
+
203
+ def _sheet_rows(go_payload, state_key, sheet_name):
204
+ state = go_payload.get(state_key, {})
205
+ sheets = state.get('sheets', {})
206
+ if isinstance(sheets, dict):
207
+ sheet = sheets.get(sheet_name, {})
208
+ rows = sheet.get('rows', [])
209
+ if isinstance(rows, list) and rows:
210
+ return rows
211
+ data_rows = _parse_rows_from_sheet_data(sheet.get('data', {}))
212
+ if data_rows:
213
+ return data_rows
214
+ if isinstance(sheets, list):
215
+ for sheet in sheets:
216
+ if norm(sheet.get('name')) != norm(sheet_name):
217
+ continue
218
+ rows = sheet.get('rows', [])
219
+ if isinstance(rows, list) and rows:
220
+ return rows
221
+ data_rows = _parse_rows_from_sheet_data(sheet.get('data', {}))
222
+ if data_rows:
223
+ return data_rows
224
+ # fall back to first sheet if name mismatch
225
+ for sheet in sheets:
226
+ data_rows = _parse_rows_from_sheet_data(sheet.get('data', {}))
227
+ if data_rows:
228
+ return data_rows
229
+ return []
230
+
231
+
232
+ def _slack_channel_messages(slack_state, channel_name):
233
+ channels = slack_state.get('channels', [])
234
+ target = None
235
+ for ch in channels:
236
+ if norm(ch.get('name')) == norm(channel_name):
237
+ target = ch
238
+ break
239
+ if target is None:
240
+ return []
241
+ ch_msgs = target.get('messages')
242
+ if isinstance(ch_msgs, list):
243
+ return ch_msgs
244
+ msg_map = slack_state.get('messages', {})
245
+ if isinstance(msg_map, dict):
246
+ return msg_map.get(target.get('channelId'), []) or []
247
+ return []
248
+
249
+
250
+ def _by_sys_id(records):
251
+ out = {}
252
+ for r in records or []:
253
+ if isinstance(r, dict) and r.get('sys_id') is not None:
254
+ out[r['sys_id']] = r
255
+ return out
256
+
257
+
258
+ # =============================================================================
259
+ # Task-specific reward
260
+ # =============================================================================
261
+ def reward(go):
262
+ sn_i = go('servicenow').get('initial_state', {}) or {}
263
+ sn_c = go('servicenow').get('current_state', {}) or {}
264
+ gl_c = go('gitlab').get('current_state', {}) or {}
265
+ slack_c = go('slack').get('current_state', {}) or {}
266
+
267
+ changes_i = sn_i.get('changeRequests', []) or []
268
+ changes_c_by_id = _by_sys_id(sn_c.get('changeRequests', []))
269
+
270
+ # ---- Answer key: pending changes with an embedded expected decision ----
271
+ pendings = [c for c in changes_i
272
+ if norm(c.get('approval')) == 'requested' and c.get('_expected_decision')]
273
+ n = len(pendings)
274
+ if n == 0:
275
+ print('DEBUG_W01 no pending changes with embedded decision; nothing to score')
276
+ return 0.0
277
+
278
+ expected_by_id = {c['sys_id']: norm(c['_expected_decision']) for c in pendings}
279
+ n_approved = sum(1 for d in expected_by_id.values() if d == 'approved')
280
+ n_rejected = sum(1 for d in expected_by_id.values() if d == 'rejected')
281
+
282
+ # ---- 1) ServiceNow decisions (L2 anchor) — 0.45 ----
283
+ sn_match = 0
284
+ try:
285
+ for sys_id, exp in expected_by_id.items():
286
+ cur = changes_c_by_id.get(sys_id, {})
287
+ if norm(cur.get('approval')) == exp:
288
+ sn_match += 1
289
+ except Exception as e:
290
+ print(f'DEBUG_W01 decisions component error: {e!r}')
291
+ sn_score = frac(sn_match, n)
292
+
293
+ # ---- 2) ServiceNow schedule (L2 anchor a') — 0.20 ----
294
+ # Timezone-robust: ChangeForm stores new Date(wallclock).toISOString(), so
295
+ # the persisted UTC instant depends on browser tz. _schedule_matches accepts
296
+ # any whole-hour offset (minutes must match), so entering 02:00 / 04:00 in
297
+ # any tz scores. Old (initial) May dates differ by days → no false positive.
298
+ sched_match = 0
299
+ try:
300
+ for c in pendings:
301
+ sys_id = c['sys_id']
302
+ exp_s = c.get('_expected_start')
303
+ exp_e = c.get('_expected_end')
304
+ cur = changes_c_by_id.get(sys_id, {})
305
+ if (_schedule_matches(cur.get('start_date'), exp_s)
306
+ and _schedule_matches(cur.get('end_date'), exp_e)):
307
+ sched_match += 1
308
+ except Exception as e:
309
+ print(f'DEBUG_W01 schedule component error: {e!r}')
310
+ sched_score = frac(sched_match, n)
311
+
312
+ # ---- 3) GitLab deploy issues (recall, no penalty for extras) — 0.15 ----
313
+ # For each APPROVED change, an issue titled 'Deploy: <CHG number>' must
314
+ # exist AND be moved to the 'In Progress' column (status == 'in_progress').
315
+ # A freshly created issue defaults to status 'open', so this forces the
316
+ # agent to both create and drag it. Extra/wrong issues never reduce the
317
+ # score (GitLab can't delete), so this stays pure recall.
318
+ gl_match = 0
319
+ approved_numbers = [norm(c.get('number')) for c in pendings
320
+ if norm(c['_expected_decision']) == 'approved']
321
+ try:
322
+ issues_c = gl_c.get('issues', []) or []
323
+ for num in approved_numbers:
324
+ needle = f'deploy: {num}'
325
+ if any(needle in _collapse_ws(iss.get('title'))
326
+ and norm(iss.get('status')) == 'in_progress'
327
+ for iss in issues_c):
328
+ gl_match += 1
329
+ except Exception as e:
330
+ print(f'DEBUG_W01 gitlab component error: {e!r}')
331
+ gl_score = frac(gl_match, n_approved) if n_approved else 1.0
332
+
333
+ # ---- 4) Google Sheet ledger — 0.10 ----
334
+ # 10 pending rows must have the correct Decision; CHG-EXAMPLE row ignored.
335
+ num_to_expected = {norm(c.get('number')): norm(c['_expected_decision']) for c in pendings}
336
+ sheet_match = 0
337
+ try:
338
+ rows_c = _sheet_rows(go('google_sheets'), 'current_state', 'Change Approvals')
339
+
340
+ def _row_field(row, *aliases):
341
+ for a in aliases:
342
+ if a in row:
343
+ return row[a]
344
+ return ''
345
+
346
+ for num, exp in num_to_expected.items():
347
+ for row in rows_c:
348
+ if norm(_row_field(row, 'chg number', 'chg', 'number')) == num:
349
+ if norm(_row_field(row, 'decision')) == exp:
350
+ sheet_match += 1
351
+ break
352
+ except Exception as e:
353
+ print(f'DEBUG_W01 sheet component error: {e!r}')
354
+ sheet_score = frac(sheet_match, n)
355
+
356
+ # ---- 5) Slack #change summary — 0.10 ----
357
+ slack_ok = 0.0
358
+ try:
359
+ chan = _slack_channel_messages(slack_c, 'change')
360
+ for msg in chan:
361
+ txt = (_msg_text(msg) or '').lower()
362
+ if not txt.strip():
363
+ continue
364
+ am = re.search(r'(\d+)\s*(?:changes?\s+)?approved', txt)
365
+ rm = re.search(r'(\d+)\s*(?:changes?\s+)?rejected', txt)
366
+ if am and rm and int(am.group(1)) == n_approved and int(rm.group(1)) == n_rejected:
367
+ slack_ok = 1.0
368
+ break
369
+ # Fallback partial credit: a non-empty message naming both keywords.
370
+ if slack_ok == 0.0:
371
+ for msg in chan:
372
+ txt = (_msg_text(msg) or '').lower()
373
+ if 'approv' in txt and 'reject' in txt:
374
+ slack_ok = 0.5
375
+ break
376
+ except Exception as e:
377
+ print(f'DEBUG_W01 slack component error: {e!r}')
378
+
379
+ # ---- Combine ----
380
+ s_sn = 0.45 * sn_score
381
+ s_sched = 0.20 * sched_score
382
+ s_gl = 0.15 * gl_score
383
+ s_sheet = 0.10 * sheet_score
384
+ s_slack = 0.10 * slack_ok
385
+ score = s_sn + s_sched + s_gl + s_sheet + s_slack
386
+
387
+ print(
388
+ 'DEBUG_W01 '
389
+ f'n_pending={n} n_approved={n_approved} n_rejected={n_rejected} '
390
+ f'sn_match={sn_match}/{n} sn_score={round(sn_score, 4)} '
391
+ f'sched_match={sched_match}/{n} sched_score={round(sched_score, 4)} '
392
+ f'gl_match={gl_match}/{n_approved} gl_score={round(gl_score, 4)} '
393
+ f'sheet_match={sheet_match}/{n} sheet_score={round(sheet_score, 4)} '
394
+ f'slack_ok={slack_ok} '
395
+ f'w_sn={round(s_sn, 4)} w_sched={round(s_sched, 4)} w_gl={round(s_gl, 4)} '
396
+ f'w_sheet={round(s_sheet, 4)} w_slack={round(s_slack, 4)} '
397
+ f'total={round(score, 4)}'
398
+ )
399
+
400
+ return clamp01(score)
401
+
402
+
403
+ try:
404
+ score = float(reward(go))
405
+ except Exception as exc:
406
+ print(f'ERROR: reward() raised {exc!r}')
407
+ score = 0.0
408
+
409
+ score = clamp01(score)
410
+ print(f'\nREWARD: {round(score, 4)}')