lkeab commited on
Commit
d45a493
·
verified ·
1 Parent(s): 5c16527

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ae_pipeline_review_004__long/_cua_gym_vm_bridge.sh +106 -0
  2. ae_pipeline_review_004__long/initial_setup.py +799 -0
  3. ae_pipeline_review_004__long/reward.py +586 -0
  4. am_renewal_hubspot_004__long/_cua_gym_vm_bridge.sh +106 -0
  5. am_renewal_hubspot_004__long/initial_setup.py +688 -0
  6. am_renewal_hubspot_004__long/reward.py +727 -0
  7. am_renewal_outreach_002/_cua_gym_vm_bridge.sh +106 -0
  8. am_renewal_outreach_002/initial_setup.py +583 -0
  9. am_renewal_outreach_002/reward.py +427 -0
  10. am_renewal_outreach_002/reward_label.json +85 -0
  11. am_renewal_tracker_003/_cua_gym_vm_bridge.sh +106 -0
  12. am_renewal_tracker_003/initial_setup.py +486 -0
  13. am_renewal_tracker_003/reward.py +427 -0
  14. am_renewal_tracker_003/reward_label.json +61 -0
  15. ar_approval_002/_cua_gym_vm_bridge.sh +106 -0
  16. ar_approval_002/initial_setup.py +240 -0
  17. ar_approval_002/reward.py +213 -0
  18. ar_approval_002/reward_label.json +82 -0
  19. ar_billing_exception_012__long/_cua_gym_vm_bridge.sh +106 -0
  20. ar_billing_exception_012__long/initial_setup.py +934 -0
  21. ar_billing_exception_012__long/reward.py +649 -0
  22. ar_deal_to_invoice_007__long/_cua_gym_vm_bridge.sh +106 -0
  23. ar_deal_to_invoice_007__long/initial_setup.py +431 -0
  24. ar_deal_to_invoice_007__long/reward.py +826 -0
  25. ar_invoice_003/initial_setup.py +279 -0
  26. ar_invoice_003/reward.py +263 -0
  27. ar_payment_004/_cua_gym_vm_bridge.sh +106 -0
  28. ar_payment_004/initial_setup.py +253 -0
  29. ar_payment_004/reward.py +227 -0
  30. ar_payment_004/reward_label.json +63 -0
  31. ar_payment_alert_010__long/_cua_gym_vm_bridge.sh +106 -0
  32. ar_payment_alert_010__long/initial_setup.py +969 -0
  33. ar_payment_alert_010__long/reward.py +689 -0
  34. csm_escalation_001/_cua_gym_vm_bridge.sh +106 -0
  35. csm_escalation_001/initial_setup.py +528 -0
  36. csm_escalation_001/reward.py +466 -0
  37. csm_escalation_001/reward_label.json +71 -0
  38. csm_health_risk_002/_cua_gym_vm_bridge.sh +106 -0
  39. csm_health_risk_002/initial_setup.py +593 -0
  40. csm_health_risk_002/reward.py +399 -0
  41. csm_health_risk_002/reward_label.json +76 -0
  42. csm_onboarding_checklist_004/_cua_gym_vm_bridge.sh +106 -0
  43. csm_onboarding_checklist_004/initial_setup.py +254 -0
  44. csm_onboarding_checklist_004/reward.py +154 -0
  45. csm_onboarding_checklist_004/reward_label.json +88 -0
  46. csm_qbr_renewal_003/_cua_gym_vm_bridge.sh +106 -0
  47. csm_qbr_renewal_003/initial_setup.py +760 -0
  48. csm_qbr_renewal_003/reward.py +339 -0
  49. csm_qbr_renewal_003/reward_label.json +87 -0
  50. csops_p1_incident_002/_cua_gym_vm_bridge.sh +106 -0
ae_pipeline_review_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"
ae_pipeline_review_004__long/initial_setup.py ADDED
@@ -0,0 +1,799 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: T05_salesforce_oppty_followups — Pipeline Review sync into Salesforce
3
+ Task ID: ae_pipeline_review_004__long
4
+ Mocks: salesforce_mock,google_sheets_mock,slack_mock
5
+
6
+ The 'Pipeline Review' Google Sheet lists opportunities (rows 2+:
7
+ OppName, Account, Amount, Stage, CloseDate). For each row the agent must find
8
+ the matching Salesforce Opportunity by NAME and apply the decision rules:
9
+ - Stage 'Closed Won' -> SF stage 'Closed Won' + Task 'Kickoff: <Account>' (Status 'Not Started')
10
+ + reassign the opportunity Owner to 'Morgan Avery' (onboarding lead)
11
+ - Stage 'Closed Lost' -> SF stage 'Closed Lost' (no task, owner unchanged)
12
+ - Stage 'Negotiation' AND Amount >= 50000 -> SF stage 'Negotiation' + Task 'Exec review: <Account>' (owner unchanged)
13
+ - all other rows -> leave the SF opportunity UNCHANGED
14
+ - rows whose OppName has NO matching SF opportunity are SKIPPED
15
+ Then create a new Slack channel named 'backup', export the Salesforce
16
+ Opportunities report and the 'Pipeline Review' sheet to CSV, and upload BOTH
17
+ CSV files into the 'backup' channel.
18
+
19
+ The opportunity STAGE is changed from the opportunity's own page (the stage path),
20
+ the follow-up TASK is created from the opportunity's Activity timeline, and the
21
+ OWNER reassignment is a bulk action that only appears once an opportunity row is
22
+ selected in the list -- all three are controls the agent has to discover.
23
+
24
+ After syncing, the agent must create a new Slack channel named 'backup', export the
25
+ Salesforce Opportunities report to CSV and the 'Pipeline Review' sheet to CSV, and
26
+ upload BOTH CSV files into the 'backup' channel as a pipeline backup.
27
+
28
+ Ground-truth (answer key) is PRECOMPUTED below and embedded into initial_state
29
+ so reward.py is the sole source of truth:
30
+ - google_sheets._task_adapter.task_sheets['Pipeline Review'] (source rows)
31
+ - google_sheets._task_adapter.expected (per-row decision: matched/final_stage/task_subject)
32
+ - google_sheets._task_adapter.matched_count == n
33
+ - salesforce._task_adapter.expected / .expected_by_name / .matched_count (mirror, co-located with the SF live state reward reads)
34
+ - slack._task_adapter.backup_channel == 'backup' and .required_csv_count == 2
35
+ """
36
+ import datetime
37
+ import os
38
+ import shlex
39
+ import subprocess
40
+ import time
41
+ import uuid
42
+
43
+ import requests
44
+
45
+ # ---------------------------------------------------------------------------
46
+ # sid
47
+ # ---------------------------------------------------------------------------
48
+ sid = str(uuid.uuid4())
49
+ with open('/tmp/task_web_sid', 'w', encoding='utf-8') as f:
50
+ f.write(sid)
51
+ print(f'Generated sid: {sid}')
52
+
53
+ TASK_ID = '60c91d2c-31b7-490f-bc00-1317ca378c29'
54
+ SHEET_NAME = 'Pipeline Review'
55
+ HEADERS = ['OppName', 'Account', 'Amount', 'Stage', 'CloseDate']
56
+
57
+ # Owner reassignment target for Closed-Won opps (the "onboarding lead").
58
+ # Opportunities are seeded owned by 'U1'; Closed-Won rows must end owned by U4.
59
+ SEEDED_OWNER_ID = 'U1'
60
+ ONBOARDING_OWNER_ID = 'U4'
61
+ ONBOARDING_OWNER_NAME = 'Morgan Avery'
62
+
63
+ # ---------------------------------------------------------------------------
64
+ # Date helpers (relative to "today" so CloseDate values are realistic)
65
+ # ---------------------------------------------------------------------------
66
+ TODAY = datetime.date(2026, 6, 23)
67
+
68
+
69
+ def fdate(days_ahead):
70
+ return (TODAY + datetime.timedelta(days=days_ahead)).isoformat()
71
+
72
+
73
+ # Stage -> default probability for a Salesforce opportunity.
74
+ STAGE_PROB = {
75
+ 'Prospecting': 10,
76
+ 'Qualification': 25,
77
+ 'Needs Analysis': 35,
78
+ 'Value Proposition': 50,
79
+ 'Proposal': 65,
80
+ 'Negotiation': 80,
81
+ 'Closed Won': 100,
82
+ 'Closed Lost': 0,
83
+ }
84
+
85
+ # ---------------------------------------------------------------------------
86
+ # Single source of truth for the scenario. Everything else (sheet cells,
87
+ # SF opportunities, the expected answer key, n) is DERIVED from this list, so
88
+ # the visible data and the embedded key can never drift apart.
89
+ #
90
+ # Each spec:
91
+ # opp_name : OppName in the sheet (== SF Opportunity.name when matched)
92
+ # account : Account in the sheet (drives the Task subject)
93
+ # amount : Amount in the sheet
94
+ # sheet_stage : Stage in the sheet (the DESIRED decision input)
95
+ # close_off : CloseDate = today + close_off days
96
+ # matched : True -> a SF opportunity with this name is pre-seeded
97
+ # False -> NO SF opportunity (agent must skip this row)
98
+ # sf_initial : the SF opportunity's stage AT INJECTION (only if matched).
99
+ # Chosen != the final stage for rows that require a change so
100
+ # the change is observable; == final stage for unchanged rows.
101
+ # ---------------------------------------------------------------------------
102
+ ROW_SPECS = [
103
+ # --- Branch: Closed Won (set stage + create Kickoff task) ---------------
104
+ dict(opp_name='Acme Renewal', account='Acme Corp', amount=120000,
105
+ sheet_stage='Closed Won', close_off=7, matched=True, sf_initial='Proposal'),
106
+ # --- Branch: Closed Lost (set stage, no task) ----------------------------
107
+ dict(opp_name='Globex Expansion', account='Globex Inc', amount=85000,
108
+ sheet_stage='Closed Lost', close_off=12, matched=True, sf_initial='Negotiation'),
109
+ # --- Branch: Negotiation & Amount >= 50000 (set stage + Exec review) -----
110
+ dict(opp_name='Initech Platform', account='Initech LLC', amount=75000,
111
+ sheet_stage='Negotiation', close_off=18, matched=True, sf_initial='Qualification'),
112
+ # --- Branch: Negotiation & Amount < 50000 (unchanged; the 30000 case) ----
113
+ dict(opp_name='Umbrella Rollout', account='Umbrella Corp', amount=30000,
114
+ sheet_stage='Negotiation', close_off=24, matched=True, sf_initial='Value Proposition'),
115
+ # --- Branch: Closed Won (second one, observe Negotiation -> Closed Won) ---
116
+ dict(opp_name='Soylent Upsell', account='Soylent Co', amount=60000,
117
+ sheet_stage='Closed Won', close_off=9, matched=True, sf_initial='Negotiation'),
118
+ # --- Branch: Closed Lost (second one) ------------------------------------
119
+ dict(opp_name='Stark Integration', account='Stark Industries', amount=95000,
120
+ sheet_stage='Closed Lost', close_off=15, matched=True, sf_initial='Proposal'),
121
+ # --- Branch: other stage 'Proposal' (unchanged) --------------------------
122
+ dict(opp_name='Wayne Migration', account='Wayne Enterprises', amount=40000,
123
+ sheet_stage='Proposal', close_off=30, matched=True, sf_initial='Proposal'),
124
+ # --- Branch: other stage 'Prospecting' (unchanged) -----------------------
125
+ dict(opp_name='Hooli Renewal', account='Hooli Inc', amount=150000,
126
+ sheet_stage='Prospecting', close_off=40, matched=True, sf_initial='Prospecting'),
127
+ # --- No matching SF opportunity (must be SKIPPED) ------------------------
128
+ dict(opp_name='Pied Piper Deal', account='Pied Piper', amount=50000,
129
+ sheet_stage='Closed Won', close_off=20, matched=False, sf_initial=None),
130
+ dict(opp_name='Vehement Capital', account='Vehement Partners', amount=70000,
131
+ sheet_stage='Negotiation', close_off=22, matched=False, sf_initial=None),
132
+ ]
133
+
134
+
135
+ def decide(spec):
136
+ """Apply the task's decision rules -> (final_stage, task_subject, task_status,
137
+ task_status_required, requires_change, requires_task).
138
+
139
+ final_stage is the stage the SF opp must END at; for matched rows that do
140
+ NOT require a change this equals sf_initial (so reward checks 'no drift').
141
+ task_status_required encodes that the instruction only mandates a Status
142
+ ('Not Started') for the Kickoff task; the Exec review task's subject is the
143
+ binding requirement (status defaults to the natural 'Not Started').
144
+ """
145
+ stage = spec['sheet_stage']
146
+ amount = spec['amount']
147
+ initial = spec['sf_initial']
148
+ account = spec['account']
149
+
150
+ if stage == 'Closed Won':
151
+ final_stage = 'Closed Won'
152
+ task_subject = f'Kickoff: {account}'
153
+ task_status = 'Not Started'
154
+ task_status_required = True
155
+ requires_task = True
156
+ final_owner = ONBOARDING_OWNER_ID # Closed Won -> reassign owner
157
+ elif stage == 'Closed Lost':
158
+ final_stage = 'Closed Lost'
159
+ task_subject = None
160
+ task_status = None
161
+ task_status_required = False
162
+ requires_task = False
163
+ final_owner = SEEDED_OWNER_ID # owner unchanged
164
+ elif stage == 'Negotiation' and amount >= 50000:
165
+ final_stage = 'Negotiation'
166
+ task_subject = f'Exec review: {account}'
167
+ task_status = 'Not Started'
168
+ task_status_required = False
169
+ requires_task = True
170
+ final_owner = SEEDED_OWNER_ID # owner unchanged
171
+ else:
172
+ # all other rows -> leave the SF opportunity unchanged
173
+ final_stage = initial
174
+ task_subject = None
175
+ task_status = None
176
+ task_status_required = False
177
+ requires_task = False
178
+ final_owner = SEEDED_OWNER_ID # owner unchanged
179
+
180
+ requires_change = bool(initial is not None and final_stage != initial)
181
+ requires_owner_change = bool(final_owner != SEEDED_OWNER_ID)
182
+ return (final_stage, task_subject, task_status,
183
+ task_status_required, requires_change, requires_task,
184
+ final_owner, requires_owner_change)
185
+
186
+
187
+ # ---------------------------------------------------------------------------
188
+ # PRECOMPUTE: expected answer key + matched count (n) + SF opportunities
189
+ # ---------------------------------------------------------------------------
190
+ expected = [] # full per-row key (incl. unmatched rows)
191
+ sf_opportunities = [] # matched rows -> a seeded SF opportunity
192
+ sf_accounts = [] # one account per matched opp + decoys
193
+ sheet_rows_dict = [] # for _task_adapter.task_sheets
194
+
195
+ acc_counter = 0
196
+ opp_counter = 0
197
+ for spec in ROW_SPECS:
198
+ (final_stage, task_subject, task_status, task_status_required,
199
+ requires_change, requires_task, final_owner, requires_owner_change) = decide(spec)
200
+
201
+ opportunity_id = None
202
+ account_id = None
203
+ if spec['matched']:
204
+ opp_counter += 1
205
+ acc_counter += 1
206
+ opportunity_id = f'opp-{opp_counter}'
207
+ account_id = f'acc-{acc_counter}'
208
+ sf_accounts.append({
209
+ 'accountId': account_id,
210
+ 'name': spec['account'],
211
+ 'type': 'Customer',
212
+ 'industry': 'Technology',
213
+ 'revenue': spec['amount'] * 10,
214
+ 'employees': 200 + opp_counter * 25,
215
+ 'ownerId': 'U1',
216
+ 'billingStreet': '', 'billingCity': '', 'billingState': '',
217
+ 'billingZip': '', 'billingCountry': 'United States',
218
+ 'shippingStreet': '', 'shippingCity': '', 'shippingState': '',
219
+ 'shippingZip': '', 'shippingCountry': 'United States',
220
+ 'phone': '', 'website': '', 'description': '',
221
+ 'createdDate': '2026-05-01T00:00:00Z',
222
+ 'modifiedDate': '2026-05-01T00:00:00Z',
223
+ })
224
+ sf_opportunities.append({
225
+ 'opportunityId': opportunity_id,
226
+ 'name': spec['opp_name'],
227
+ 'accountId': account_id,
228
+ 'contactId': '',
229
+ 'amount': spec['amount'],
230
+ 'closeDate': fdate(spec['close_off']),
231
+ 'stage': spec['sf_initial'],
232
+ 'probability': STAGE_PROB.get(spec['sf_initial'], 10),
233
+ 'ownerId': 'U1',
234
+ 'type': 'Existing Customer - Upgrade',
235
+ 'leadSource': 'Partner',
236
+ 'description': '',
237
+ 'createdDate': '2026-05-05T00:00:00Z',
238
+ 'modifiedDate': '2026-05-05T00:00:00Z',
239
+ })
240
+
241
+ expected.append({
242
+ 'oppName': spec['opp_name'],
243
+ 'account': spec['account'],
244
+ 'amount': spec['amount'],
245
+ 'sheet_stage': spec['sheet_stage'],
246
+ 'matched': spec['matched'],
247
+ 'opportunityId': opportunity_id,
248
+ 'initial_stage': spec['sf_initial'],
249
+ 'final_stage': final_stage,
250
+ 'task_subject': task_subject,
251
+ 'task_status': task_status,
252
+ 'task_status_required': task_status_required,
253
+ 'requires_change': requires_change,
254
+ 'requires_task': requires_task,
255
+ 'initial_owner': SEEDED_OWNER_ID if spec['matched'] else None,
256
+ 'final_owner': final_owner if spec['matched'] else None,
257
+ 'requires_owner_change': requires_owner_change if spec['matched'] else False,
258
+ })
259
+
260
+ sheet_rows_dict.append({
261
+ 'OppName': spec['opp_name'],
262
+ 'Account': spec['account'],
263
+ 'Amount': spec['amount'],
264
+ 'Stage': spec['sheet_stage'],
265
+ 'CloseDate': fdate(spec['close_off']),
266
+ })
267
+
268
+ matched_count = sum(1 for e in expected if e['matched']) # n
269
+ expected_message = f'Synced {matched_count} opportunities'
270
+ expected_by_name = {
271
+ e['oppName']: {
272
+ 'final_stage': e['final_stage'],
273
+ 'task_subject': e['task_subject'],
274
+ 'task_status': e['task_status'],
275
+ 'task_status_required': e['task_status_required'],
276
+ 'requires_change': e['requires_change'],
277
+ 'requires_task': e['requires_task'],
278
+ 'initial_owner': e['initial_owner'],
279
+ 'final_owner': e['final_owner'],
280
+ 'requires_owner_change': e['requires_owner_change'],
281
+ }
282
+ for e in expected if e['matched']
283
+ }
284
+
285
+ # Decoy SF opportunities NOT present in the sheet (watermark; never graded).
286
+ sf_accounts.append({
287
+ 'accountId': 'acc-d1', 'name': 'Cyberdyne Systems', 'type': 'Prospect',
288
+ 'industry': 'Robotics', 'revenue': 9000000, 'employees': 800, 'ownerId': 'U2',
289
+ 'billingStreet': '', 'billingCity': '', 'billingState': '', 'billingZip': '',
290
+ 'billingCountry': 'United States', 'shippingStreet': '', 'shippingCity': '',
291
+ 'shippingState': '', 'shippingZip': '', 'shippingCountry': 'United States',
292
+ 'phone': '', 'website': '', 'description': '',
293
+ 'createdDate': '2026-05-01T00:00:00Z', 'modifiedDate': '2026-05-01T00:00:00Z',
294
+ })
295
+ sf_accounts.append({
296
+ 'accountId': 'acc-d2', 'name': 'Tyrell Corporation', 'type': 'Customer',
297
+ 'industry': 'Biotech', 'revenue': 25000000, 'employees': 1200, 'ownerId': 'U3',
298
+ 'billingStreet': '', 'billingCity': '', 'billingState': '', 'billingZip': '',
299
+ 'billingCountry': 'United States', 'shippingStreet': '', 'shippingCity': '',
300
+ 'shippingState': '', 'shippingZip': '', 'shippingCountry': 'United States',
301
+ 'phone': '', 'website': '', 'description': '',
302
+ 'createdDate': '2026-05-01T00:00:00Z', 'modifiedDate': '2026-05-01T00:00:00Z',
303
+ })
304
+ sf_opportunities.append({
305
+ 'opportunityId': 'opp-d1', 'name': 'Cyberdyne Support Renewal', 'accountId': 'acc-d1',
306
+ 'contactId': '', 'amount': 22000, 'closeDate': fdate(55), 'stage': 'Qualification',
307
+ 'probability': 25, 'ownerId': 'U2', 'type': 'Existing Customer - Renewal',
308
+ 'leadSource': 'Web', 'description': '', 'createdDate': '2026-05-05T00:00:00Z',
309
+ 'modifiedDate': '2026-05-05T00:00:00Z',
310
+ })
311
+ sf_opportunities.append({
312
+ 'opportunityId': 'opp-d2', 'name': 'Tyrell New Business', 'accountId': 'acc-d2',
313
+ 'contactId': '', 'amount': 310000, 'closeDate': fdate(70), 'stage': 'Proposal',
314
+ 'probability': 65, 'ownerId': 'U3', 'type': 'New Business',
315
+ 'leadSource': 'Referral', 'description': '', 'createdDate': '2026-05-05T00:00:00Z',
316
+ 'modifiedDate': '2026-05-05T00:00:00Z',
317
+ })
318
+
319
+ # Decoy activities — present (Rule: "activities array present") but NONE has a
320
+ # subject equal to any expected Kickoff/Exec-review subject, and none is tied to
321
+ # a graded opportunity, so they cannot create false positives at injection.
322
+ sf_activities = [
323
+ {'activityId': 'activity-1', 'type': 'event', 'subject': 'Discovery call — Cyberdyne Systems',
324
+ 'status': 'Completed', 'priority': 'Normal',
325
+ 'startDateTime': '2026-06-18T15:00:00Z', 'endDateTime': '2026-06-18T15:30:00Z',
326
+ 'relatedToType': 'opportunity', 'relatedToId': 'opp-d1', 'assignedToId': 'U2',
327
+ 'description': ''},
328
+ {'activityId': 'activity-2', 'type': 'task', 'subject': 'Send NDA to Tyrell Corporation',
329
+ 'status': 'Completed', 'priority': 'High', 'dueDate': fdate(-2),
330
+ 'relatedToType': 'opportunity', 'relatedToId': 'opp-d2', 'assignedToId': 'U3',
331
+ 'description': ''},
332
+ ]
333
+
334
+ # ---------------------------------------------------------------------------
335
+ # Salesforce users
336
+ # ---------------------------------------------------------------------------
337
+ sf_users = [
338
+ {'userId': 'U1', 'firstName': 'John', 'lastName': 'Smith', 'email': 'john.smith@company.com',
339
+ 'phone': '(555) 123-4567', 'title': 'RevOps Manager', 'department': 'Sales', 'role': 'Manager',
340
+ 'avatar': 'https://i.pravatar.cc/150?u=U1', 'timezone': 'America/New_York',
341
+ 'locale': 'en-US', 'theme': 'lightning'},
342
+ {'userId': 'U2', 'firstName': 'Sarah', 'lastName': 'Chen', 'email': 'sarah.chen@company.com',
343
+ 'phone': '', 'title': 'Account Executive', 'department': 'Sales', 'role': 'Rep',
344
+ 'avatar': 'https://i.pravatar.cc/150?u=U2', 'timezone': 'America/New_York',
345
+ 'locale': 'en-US', 'theme': 'lightning'},
346
+ {'userId': 'U3', 'firstName': 'Diego', 'lastName': 'Ruiz', 'email': 'diego.ruiz@company.com',
347
+ 'phone': '', 'title': 'Account Executive', 'department': 'Sales', 'role': 'Rep',
348
+ 'avatar': 'https://i.pravatar.cc/150?u=U3', 'timezone': 'America/Chicago',
349
+ 'locale': 'en-US', 'theme': 'lightning'},
350
+ {'userId': 'U4', 'firstName': 'Morgan', 'lastName': 'Avery', 'email': 'morgan.avery@company.com',
351
+ 'phone': '', 'title': 'Customer Onboarding Lead', 'department': 'Customer Success', 'role': 'Manager',
352
+ 'avatar': 'https://i.pravatar.cc/150?u=U4', 'timezone': 'America/New_York',
353
+ 'locale': 'en-US', 'theme': 'lightning'},
354
+ ]
355
+
356
+ salesforce_state = {
357
+ 'user': sf_users[0],
358
+ 'users': sf_users,
359
+ 'leads': [],
360
+ 'accounts': sf_accounts,
361
+ 'contacts': [],
362
+ 'opportunities': sf_opportunities,
363
+ 'cases': [],
364
+ 'activities': sf_activities,
365
+ 'chatterPosts': [],
366
+ 'files': [],
367
+ 'dashboards': [],
368
+ 'following': [],
369
+ 'recentlyViewed': [],
370
+ 'dismissedNotifications': [],
371
+ '_task_adapter': {
372
+ 'task_id': TASK_ID,
373
+ 'variant': 'eval',
374
+ 'matched_count': matched_count,
375
+ 'expected': expected,
376
+ 'expected_by_name': expected_by_name,
377
+ 'onboarding_owner_id': ONBOARDING_OWNER_ID,
378
+ 'onboarding_owner_name': ONBOARDING_OWNER_NAME,
379
+ 'seeded_owner_id': SEEDED_OWNER_ID,
380
+ },
381
+ }
382
+
383
+ # ---------------------------------------------------------------------------
384
+ # Google Sheets — 'Pipeline Review' workbook
385
+ # ---------------------------------------------------------------------------
386
+ COL_LETTERS = ['A', 'B', 'C', 'D', 'E']
387
+
388
+
389
+ def header_cell(text):
390
+ return {'value': text, 'formula': text, 'computed': text,
391
+ 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}
392
+
393
+
394
+ def text_cell(text):
395
+ return {'value': text, 'formula': text, 'computed': text}
396
+
397
+
398
+ def num_cell(n):
399
+ return {'value': str(n), 'formula': str(n), 'computed': n}
400
+
401
+
402
+ sheet_data = {}
403
+ # Header row (row 1)
404
+ for col, head in zip(COL_LETTERS, HEADERS):
405
+ sheet_data[f'{col}1'] = header_cell(head)
406
+ # Data rows (rows 2..N)
407
+ for idx, row in enumerate(sheet_rows_dict):
408
+ r = idx + 2
409
+ sheet_data[f'A{r}'] = text_cell(row['OppName'])
410
+ sheet_data[f'B{r}'] = text_cell(row['Account'])
411
+ sheet_data[f'C{r}'] = num_cell(row['Amount'])
412
+ sheet_data[f'D{r}'] = text_cell(row['Stage'])
413
+ sheet_data[f'E{r}'] = text_cell(row['CloseDate'])
414
+
415
+ google_sheets_state = {
416
+ 'id': 'workbook_t05_pipeline_review',
417
+ 'title': 'Pipeline Review',
418
+ 'activeSheetId': 'sheet_1',
419
+ 'selectedCell': 'A1',
420
+ 'selectionRange': None,
421
+ 'clipboard': None,
422
+ 'isDragging': False,
423
+ 'undoStack': [],
424
+ 'redoStack': [],
425
+ 'namedRanges': [],
426
+ 'conditionalFormats': [],
427
+ 'charts': [],
428
+ 'showGridlines': True,
429
+ 'showFormulas': False,
430
+ 'zoom': 100,
431
+ 'sheets': [{
432
+ 'id': 'sheet_1',
433
+ 'name': SHEET_NAME,
434
+ 'data': sheet_data,
435
+ 'rowCount': 100,
436
+ 'colCount': 26,
437
+ 'frozenRows': 1,
438
+ 'frozenCols': 0,
439
+ 'tabColor': None,
440
+ 'isHidden': False,
441
+ 'columnWidths': {},
442
+ 'rowHeights': {},
443
+ 'filterRange': None,
444
+ 'filterCriteria': {},
445
+ 'sortColumn': None,
446
+ 'sortDirection': None,
447
+ }],
448
+ '_task_adapter': {
449
+ 'source_schema': 'rows_dict',
450
+ 'task_id': TASK_ID,
451
+ 'variant': 'eval',
452
+ 'task_sheets': {SHEET_NAME: {'headers': HEADERS, 'rows': sheet_rows_dict}},
453
+ 'headers_by_sheet': {SHEET_NAME: HEADERS},
454
+ 'sheet_names': [SHEET_NAME],
455
+ 'expected': expected,
456
+ 'expected_by_name': expected_by_name,
457
+ 'matched_count': matched_count,
458
+ 'expected_message': expected_message,
459
+ },
460
+ }
461
+
462
+ # ---------------------------------------------------------------------------
463
+ # Slack — the 'backup' channel must NOT exist yet (Rule 3); the agent creates
464
+ # it and uploads the two CSVs. Pre-existing channels are decoy chatter only.
465
+ # ---------------------------------------------------------------------------
466
+ slack_state = {
467
+ 'channels': [
468
+ {'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},
469
+ {'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},
470
+ {'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},
471
+ {'channelId': 'revops', 'name': 'revops', 'description': 'Revenue operations — pipeline hygiene and sync confirmations', 'topic': 'Drop a note when you finish a pipeline sync', 'isPrivate': False, 'isStarred': False, 'members': ['user_1'], 'createdBy': 'user_1', 'createdAt': '2026-06-04T00:00:00Z', 'pinnedMessages': [], 'unreadCount': 0},
472
+ ],
473
+ 'currentUser': {'userId': 'user_1', 'fullName': 'John Smith', 'displayName': 'John', 'email': 'john.smith@company.com', 'avatar': 'https://picsum.photos/200/200?random=1', 'title': 'RevOps Manager', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'},
474
+ 'users': [
475
+ {'userId': 'user_1', 'fullName': 'John Smith', 'displayName': 'John', 'email': 'john.smith@company.com', 'avatar': 'https://picsum.photos/200/200?random=1', 'title': 'RevOps Manager', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'},
476
+ {'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'},
477
+ {'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'},
478
+ {'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'},
479
+ ],
480
+ 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Acme Corp', 'icon': ''},
481
+ 'messages': {
482
+ 'general': [
483
+ {'messageId': 'm_g_1', 'senderId': 'user_2', 'content': 'Morning everyone — reminder that the office will be closed next Friday for the holiday.', 'timestamp': '2026-06-18T13:02:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []},
484
+ {'messageId': 'm_g_2', 'senderId': 'user_4', 'content': 'Thanks Maya! Long weekend incoming :tada:', 'timestamp': '2026-06-18T13:05:00Z', 'reactions': [{'emoji': '\U0001F389', 'users': ['user_1', 'user_3']}], 'isEdited': False, 'threadId': None, 'attachments': []},
485
+ {'messageId': 'm_g_3', 'senderId': 'user_3', 'content': 'Quick heads-up: the staging environment is being rebuilt today, expect slowness 10:00–11:00 JST.', 'timestamp': '2026-06-19T01:12:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []},
486
+ {'messageId': 'm_g_4', 'senderId': 'user_1', 'content': "Got it, I'll hold off on the pipeline review until after.", 'timestamp': '2026-06-19T01:15:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []},
487
+ ],
488
+ 'announcements': [
489
+ {'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-17T16:30:00Z', 'reactions': [{'emoji': '✅', 'users': ['user_1', 'user_3', 'user_4']}], 'isEdited': False, 'threadId': None, 'attachments': []},
490
+ {'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-19T09:00:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []},
491
+ ],
492
+ 'random': [
493
+ {'messageId': 'm_r_1', 'senderId': 'user_4', 'content': 'Anyone tried the new ramen place on 3rd? Verdict?', 'timestamp': '2026-06-18T18:50:00Z', 'reactions': [{'emoji': '\U0001F35C', 'users': ['user_3']}], 'isEdited': False, 'threadId': None, 'attachments': []},
494
+ {'messageId': 'm_r_2', 'senderId': 'user_3', 'content': "10/10, get the spicy miso. Bring tissues though, it's no joke.", 'timestamp': '2026-06-18T18:55:00Z', 'reactions': [{'emoji': '\U0001F605', 'users': ['user_1', 'user_4']}], 'isEdited': False, 'threadId': None, 'attachments': []},
495
+ {'messageId': 'm_r_3', 'senderId': 'user_1', 'content': 'My cat has decided my keyboard is her new bed. Send help.', 'timestamp': '2026-06-19T08:20:00Z', 'reactions': [{'emoji': '\U0001F63A', 'users': ['user_2', 'user_3', 'user_4']}], 'isEdited': False, 'threadId': None, 'attachments': []},
496
+ ],
497
+ # Decoy channel — not graded. The gradable artefact is the NEW 'backup'
498
+ # channel (created by the agent), which must be ABSENT at injection.
499
+ 'revops': [],
500
+ },
501
+ 'threads': {},
502
+ 'dms': [],
503
+ 'bookmarkedMessages': [],
504
+ 'callHistory': [],
505
+ 'settings': {'theme': 'light', 'notifications': 'all', 'displayDensity': 'comfortable', 'showAvatars': True, 'use24Hour': False},
506
+ 'invitations': [],
507
+ 'notifications': [],
508
+ '_task_adapter': {
509
+ 'task_id': TASK_ID,
510
+ 'variant': 'eval',
511
+ 'backup_channel': 'backup', # agent must CREATE this channel (absent at injection)
512
+ 'required_csv_count': 2, # SF opportunities CSV + Pipeline Review sheet CSV
513
+ 'matched_count': matched_count,
514
+ },
515
+ }
516
+
517
+ # Rule 3 guard: the 'backup' channel must NOT exist at injection (gradable output absent).
518
+ assert not any(str(c.get('name', '')).strip().lower() == 'backup' for c in slack_state['channels']), \
519
+ "'backup' channel must be absent at injection"
520
+
521
+ # ---------------------------------------------------------------------------
522
+ # (url, state) — EXACT app_urls from task_config.json
523
+ # ---------------------------------------------------------------------------
524
+ APP_STATES = [
525
+ ('http://28.7.184.198:8175', salesforce_state), # salesforce_mock
526
+ ('http://28.7.184.198:8145', google_sheets_state), # google_sheets_mock
527
+ ('http://28.7.184.198:8178', slack_state), # slack_mock
528
+ ]
529
+
530
+ for app_url, state in APP_STATES:
531
+ resp = requests.post(
532
+ f'{app_url}/post?sid={sid}',
533
+ json={'action': 'set', 'state': state},
534
+ timeout=30,
535
+ )
536
+ assert resp.status_code == 200, (
537
+ f'State injection failed for {app_url}: {resp.text}'
538
+ )
539
+ print(f'State injected: {app_url} sid={sid}')
540
+
541
+ for app_url, _ in APP_STATES:
542
+ go_payload = requests.get(f'{app_url}/go?sid={sid}', timeout=15).json()
543
+ assert go_payload.get('initial_state') is not None, (
544
+ f'initial_state is None after injection for {app_url}'
545
+ )
546
+ print(f'Verified initial_state set: {app_url}')
547
+
548
+ print(f'Precomputed matched_count (n) = {matched_count}; '
549
+ f'backup_channel = backup; required_csv_count = 2')
550
+
551
+
552
+ # PATCHED_BY: patch_wait_mocks_loaded.py
553
+ def launch_gui(command, delay_sec=1.0):
554
+ """Launch a GUI command, fully detached from this script.
555
+
556
+ Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that
557
+ wait_mocks_loaded's CDP phase can verify browser render below.
558
+ Idempotent: if the caller already specified a debug port, keep it.
559
+ """
560
+ env = os.environ.copy()
561
+ env['DISPLAY'] = ':0'
562
+ if isinstance(command, str):
563
+ _parts = shlex.split(command)
564
+ else:
565
+ _parts = list(command)
566
+ if (_parts and 'google-chrome' in _parts[0]
567
+ and not any(p.startswith('--remote-debugging-port') for p in _parts)):
568
+ _parts[1:1] = [
569
+ '--no-first-run',
570
+ '--no-default-browser-check',
571
+ '--remote-debugging-port=1337',
572
+ ]
573
+ subprocess.Popen(
574
+ _parts,
575
+ stdin=subprocess.DEVNULL,
576
+ stdout=subprocess.DEVNULL,
577
+ stderr=subprocess.DEVNULL,
578
+ env=env,
579
+ start_new_session=True,
580
+ )
581
+ time.sleep(delay_sec)
582
+
583
+
584
+ def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12):
585
+ """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style.
586
+
587
+ Phase 1 - Backend readiness:
588
+ Poll each mock's /state?sid=<sid> (preferred) or /go?sid=<sid>
589
+ (fallback) until it returns 200 with 'stored_state' or
590
+ 'initial_state' respectively, or until timeout.
591
+
592
+ Phase 2 - Browser render verification (via CDP + Playwright):
593
+ Connect to http://localhost:1337 (the --remote-debugging-port
594
+ injected by launch_gui above), wait for every open tab to reach
595
+ 'networkidle' AND to contain at least 20 DOM elements. This
596
+ guarantees the SPA fetched /go?sid= data AND actually painted,
597
+ not just that the mock backend is up.
598
+
599
+ Fallback:
600
+ If Playwright is missing or CDP cannot be reached, sleep for
601
+ `render_buffer` seconds as a best-effort delay so the screenshot
602
+ loop does not start on a still-blank tab.
603
+ """
604
+ import urllib.request as _urlreq
605
+ import time as _t
606
+ _urls = [p for p, _ in app_states]
607
+ _opener = _urlreq.build_opener(_urlreq.ProxyHandler({}))
608
+
609
+ # ---- Phase 1: backend readiness ----
610
+ _deadline = _t.time() + timeout
611
+ _todo = list(_urls)
612
+ while _todo and _t.time() < _deadline:
613
+ _rest = []
614
+ for _u in _todo:
615
+ _ok = False
616
+ for _path, _need in (('/state?sid=', b'stored_state'),
617
+ ('/go?sid=', b'initial_state')):
618
+ try:
619
+ _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5)
620
+ if _r.status == 200:
621
+ _body = _r.read()
622
+ if _need in _body:
623
+ _ok = True
624
+ break
625
+ except Exception:
626
+ pass
627
+ if _ok:
628
+ print(f" {_u}: backend ready")
629
+ continue
630
+ _rest.append(_u)
631
+ _todo = _rest
632
+ if _todo:
633
+ _t.sleep(2)
634
+ _done = len(_urls) - len(_todo)
635
+ _pend = f" (pending: {_todo})" if _todo else ""
636
+ print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}")
637
+
638
+ # ---- Phase 2: browser render verification via CDP ----
639
+ _cdp_ok = False
640
+ try:
641
+ from playwright.sync_api import sync_playwright
642
+ _cdp_dl = _t.time() + max(15.0, _deadline - _t.time())
643
+ with sync_playwright() as _p:
644
+ _br = None
645
+ while _t.time() < _cdp_dl:
646
+ try:
647
+ _br = _p.chromium.connect_over_cdp('http://localhost:1337')
648
+ break
649
+ except Exception:
650
+ _t.sleep(0.5)
651
+ if _br is None:
652
+ print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?")
653
+ else:
654
+ _n_expected = len(_urls)
655
+ _pages = []
656
+ _pg_dl = _t.time() + 15
657
+ _last_count = -1
658
+ _stable_since = None
659
+ while _t.time() < _pg_dl:
660
+ _pages = []
661
+ for _c in _br.contexts:
662
+ _pages.extend(_c.pages)
663
+ _cnt = len(_pages)
664
+ if _n_expected > 0 and _cnt >= _n_expected:
665
+ break
666
+ if _cnt > 0 and _cnt == _last_count:
667
+ if _stable_since is None:
668
+ _stable_since = _t.time()
669
+ elif _t.time() - _stable_since >= 1.5:
670
+ break
671
+ else:
672
+ _stable_since = None
673
+ _last_count = _cnt
674
+ _t.sleep(0.5)
675
+ _pages = []
676
+ for _c in _br.contexts:
677
+ _pages.extend(_c.pages)
678
+ if not _pages:
679
+ print(" wait_mocks_loaded: CDP connected but no open tabs found")
680
+ else:
681
+ print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render")
682
+ _MIN_ELEMS = 20
683
+ _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap
684
+ for _pg in _pages: # bring each to front once to defeat background-tab render throttling
685
+ try:
686
+ _pg.bring_to_front()
687
+ except Exception:
688
+ pass
689
+ _pending = list(_pages)
690
+ while _pending and _t.time() < _verify_dl:
691
+ _still = []
692
+ for _pg in _pending:
693
+ _ttl = ""
694
+ try:
695
+ _ttl = _pg.title()
696
+ except Exception:
697
+ pass
698
+ try:
699
+ _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0")
700
+ except Exception:
701
+ _n = 0
702
+ if _n >= _MIN_ELEMS:
703
+ print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)")
704
+ else:
705
+ _still.append(_pg)
706
+ _pending = _still
707
+ if _pending:
708
+ _t.sleep(2)
709
+ if not _pending:
710
+ _cdp_ok = True
711
+ else:
712
+ for _pg in _pending:
713
+ _ttl = ""
714
+ try:
715
+ _ttl = _pg.title()
716
+ except Exception:
717
+ pass
718
+ print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back")
719
+ except ImportError:
720
+ print(" wait_mocks_loaded: playwright not installed; skipping CDP phase")
721
+ except Exception as _e:
722
+ print(f" wait_mocks_loaded: CDP phase error ({_e!r})")
723
+
724
+ if not _cdp_ok:
725
+ print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep")
726
+ _t.sleep(render_buffer)
727
+ else:
728
+ print(" wait_mocks_loaded: browser render verified, skipping render_buffer")
729
+
730
+
731
+ def _open_mock_tabs(app_states, sid_value):
732
+ """Open the first mock as the primary Chrome window, the rest as new tabs.
733
+
734
+ Uses launch_gui once per URL so that the macOS localizer regex-extract
735
+ (which grabs the FIRST quoted URL per call) still works correctly.
736
+ """
737
+ _urls = [p for p, _ in app_states]
738
+ if not _urls:
739
+ return
740
+ launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0)
741
+ for _u in _urls[1:]:
742
+ launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0)
743
+
744
+
745
+
746
+ # PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate)
747
+ def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0):
748
+ """Block until every mock serves injected state AND (best-effort) renders."""
749
+ import time as _t
750
+ deadline = _t.time() + timeout
751
+ pending = dict(mocks)
752
+ while pending and _t.time() < deadline:
753
+ for name in list(pending):
754
+ try:
755
+ r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5)
756
+ if r.status_code == 200 and r.json().get('initial_state') is not None:
757
+ del pending[name]
758
+ except Exception:
759
+ pass
760
+ if pending:
761
+ _t.sleep(1.0)
762
+ if pending:
763
+ print(f'WARN: mocks not ready within {timeout}s: {list(pending)}')
764
+ try:
765
+ from playwright.sync_api import sync_playwright
766
+ except ImportError:
767
+ print('WARN: playwright not installed; skipping render check, settle 3s')
768
+ _t.sleep(3.0)
769
+ return
770
+ with sync_playwright() as p:
771
+ try:
772
+ browser = p.chromium.launch(channel='chrome', headless=True,
773
+ args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'])
774
+ except Exception as e:
775
+ print(f'WARN: could not launch chrome for render check: {e}; settle 3s')
776
+ _t.sleep(3.0)
777
+ return
778
+ try:
779
+ for name, url in mocks.items():
780
+ page = browser.new_page()
781
+ try:
782
+ page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000))
783
+ page.wait_for_function(
784
+ "document.body && document.body.innerText.length > 50",
785
+ timeout=int(render_timeout * 1000))
786
+ print(f'[{name}] rendered OK')
787
+ except Exception as e:
788
+ print(f'WARN: [{name}] render check issue: {e}')
789
+ finally:
790
+ page.close()
791
+ finally:
792
+ browser.close()
793
+
794
+
795
+ # ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render
796
+ _open_mock_tabs(APP_STATES, sid)
797
+ wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15)
798
+ wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12)
799
+ print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps')
ae_pipeline_review_004__long/reward.py ADDED
@@ -0,0 +1,586 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: T05 — Pipeline Review sync into Salesforce opportunities
3
+ Task ID: ae_pipeline_review_004__long
4
+ Mocks: salesforce_mock,google_sheets_mock,slack_mock
5
+ Scoring (positives sum to 1.0; leak penalties subtracted):
6
+ 0.40 stage set correctly over the rows that require a stage change.
7
+ 0.25 follow-up Task with exact Subject (+ Status 'Not Started' where required)
8
+ created for the requires_task rows (and absent on the others).
9
+ 0.20 owner reassigned to 'Morgan Avery' on the Closed-Won rows.
10
+ 0.15 Slack: a NEW 'backup' channel exists (absent at injection) and holds the
11
+ two exported CSV files as attachments (0.4 create + 0.6 for 2 CSVs).
12
+ penalties: stage-drift 0.15, forbidden-task 0.10, owner-drift 0.10 (each frac).
13
+ Answer key: read from salesforce.initial_state._task_adapter (.expected / .matched_count)
14
+ and slack.initial_state._task_adapter (.backup_channel / .required_csv_count).
15
+ """
16
+ import copy
17
+ import re
18
+ import sys
19
+
20
+ import requests
21
+
22
+
23
+ try:
24
+ with open('/tmp/task_web_sid', encoding='utf-8') as f:
25
+ sid = f.read().strip()
26
+ if not sid:
27
+ raise ValueError('sid is empty')
28
+ except Exception as e:
29
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
30
+ print('REWARD: 0.0')
31
+ sys.exit(0)
32
+
33
+
34
+ APP_URLS = {'salesforce': 'http://28.7.184.198:8175', 'google_sheets': 'http://28.7.184.198:8145', 'slack': 'http://28.7.184.198:8178'}
35
+ _GO_CACHE = {}
36
+
37
+
38
+ def clamp01(x):
39
+ return max(0.0, min(1.0, float(x)))
40
+
41
+
42
+ def frac(num, den):
43
+ return 0.0 if den == 0 else num / den
44
+
45
+
46
+ def f1(true_set, pred_set):
47
+ if not true_set and not pred_set:
48
+ return 1.0
49
+ tp = len(true_set & pred_set)
50
+ if tp == 0:
51
+ return 0.0
52
+ prec = tp / len(pred_set)
53
+ rec = tp / len(true_set)
54
+ return 2 * prec * rec / (prec + rec)
55
+
56
+
57
+ def by_id(items, key='id'):
58
+ return {it.get(key): it for it in (items or []) if isinstance(it, dict)}
59
+
60
+
61
+ def has_text(haystack, *needles):
62
+ s = (haystack or '').lower()
63
+ return any(n.lower() in s for n in needles)
64
+
65
+
66
+ def norm(s):
67
+ return (str(s) if s is not None else '').strip().lower()
68
+
69
+
70
+ def _msg_text(msg):
71
+ if not isinstance(msg, dict):
72
+ return ''
73
+ return msg.get('content') or msg.get('text') or ''
74
+
75
+
76
+ def _slack_channel_messages(slack_state, channel_name):
77
+ channels = slack_state.get('channels', []) if isinstance(slack_state, dict) else []
78
+ target = None
79
+ for ch in channels:
80
+ if isinstance(ch, dict) and norm(ch.get('name')) == norm(channel_name):
81
+ target = ch
82
+ break
83
+ if target is None:
84
+ return []
85
+ ch_msgs = target.get('messages')
86
+ if isinstance(ch_msgs, list):
87
+ return ch_msgs
88
+ msg_map = slack_state.get('messages', {})
89
+ if isinstance(msg_map, dict):
90
+ return msg_map.get(target.get('channelId') or target.get('id'), []) or []
91
+ return []
92
+
93
+
94
+ def _to_float(v):
95
+ try:
96
+ return float(v)
97
+ except (TypeError, ValueError):
98
+ return 0.0
99
+
100
+
101
+ def _sheet_rows(sheet):
102
+ if not isinstance(sheet, dict):
103
+ return []
104
+ rows = sheet.get('rows', [])
105
+ return rows if isinstance(rows, list) else []
106
+
107
+
108
+ def _sheet_tabs(sheets):
109
+ if isinstance(sheets, dict):
110
+ return sheets
111
+ if isinstance(sheets, list):
112
+ out = {}
113
+ for sh in sheets:
114
+ if not isinstance(sh, dict):
115
+ continue
116
+ name = sh.get('name') or sh.get('id')
117
+ if name:
118
+ out[name] = sh
119
+ return out
120
+ return {}
121
+
122
+
123
+ def _jaccard(a, b):
124
+ if not a and not b:
125
+ return 1.0
126
+ u = a | b
127
+ return (len(a & b) / len(u)) if u else 1.0
128
+
129
+
130
+ def _normalize_app_name(app):
131
+ app = (app or '').strip().lower()
132
+ return app[:-5] if app.endswith('_mock') else app
133
+
134
+
135
+ def _parse_cell_id(cell_id):
136
+ if not isinstance(cell_id, str) or not cell_id:
137
+ return None
138
+ idx = 0
139
+ while idx < len(cell_id) and cell_id[idx].isalpha():
140
+ idx += 1
141
+ if idx == 0 or idx >= len(cell_id):
142
+ return None
143
+ col = 0
144
+ for ch in cell_id[:idx].upper():
145
+ col = col * 26 + (ord(ch) - ord('A') + 1)
146
+ try:
147
+ row = int(cell_id[idx:])
148
+ except ValueError:
149
+ return None
150
+ return row, col - 1
151
+
152
+
153
+ def _extract_rows_from_workbook(state):
154
+ if not isinstance(state, dict):
155
+ return None
156
+ sheets = state.get('sheets')
157
+ if not isinstance(sheets, list):
158
+ return None
159
+
160
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
161
+ headers_by_sheet = adapter.get('headers_by_sheet') if isinstance(adapter.get('headers_by_sheet'), dict) else {}
162
+
163
+ out = {}
164
+ for sh in sheets:
165
+ if not isinstance(sh, dict):
166
+ continue
167
+ name = sh.get('name') or sh.get('id') or 'Sheet1'
168
+ data = sh.get('data') if isinstance(sh.get('data'), dict) else {}
169
+
170
+ headers = headers_by_sheet.get(name)
171
+ if not headers:
172
+ cols = []
173
+ for cid, cell in data.items():
174
+ rc = _parse_cell_id(cid)
175
+ if not rc:
176
+ continue
177
+ row_idx, col_idx = rc
178
+ if row_idx != 1:
179
+ continue
180
+ value = ''
181
+ if isinstance(cell, dict):
182
+ value = cell.get('value', '')
183
+ elif cell is not None:
184
+ value = str(cell)
185
+ if value is not None and str(value) != '':
186
+ cols.append((col_idx, str(value)))
187
+ headers = [v for _, v in sorted(cols)]
188
+
189
+ if not headers:
190
+ continue
191
+
192
+ by_row = {}
193
+ for cid, cell in data.items():
194
+ rc = _parse_cell_id(cid)
195
+ if not rc:
196
+ continue
197
+ row_idx, col_idx = rc
198
+ if row_idx <= 1 or col_idx >= len(headers):
199
+ continue
200
+ if isinstance(cell, dict):
201
+ value = cell.get('value', '')
202
+ else:
203
+ value = cell
204
+ by_row.setdefault(row_idx, {})[headers[col_idx]] = value
205
+
206
+ rows = []
207
+ for row_idx in sorted(by_row.keys()):
208
+ row = by_row[row_idx]
209
+ if not any(str(row.get(h, '')).strip() for h in headers):
210
+ continue
211
+ rows.append({h: row.get(h, '') for h in headers})
212
+
213
+ out[name] = {'headers': headers, 'rows': rows}
214
+
215
+ if not out:
216
+ return None
217
+ return {'sheets': out}
218
+
219
+
220
+ def _materialize_google_sheets(payload):
221
+ for key in ('initial_state', 'current_state'):
222
+ state = payload.get(key)
223
+ if not isinstance(state, dict):
224
+ continue
225
+ maybe_rows = _extract_rows_from_workbook(state)
226
+ if maybe_rows is not None:
227
+ state['_ui_workbook'] = {
228
+ 'sheets': copy.deepcopy(state.get('sheets', [])),
229
+ 'title': state.get('title'),
230
+ }
231
+ state['sheets'] = maybe_rows['sheets']
232
+
233
+
234
+ def _materialize_slack(payload):
235
+ for key in ('initial_state', 'current_state'):
236
+ state = payload.get(key)
237
+ if not isinstance(state, dict):
238
+ continue
239
+ channels = state.get('channels') if isinstance(state.get('channels'), list) else []
240
+ messages_map = state.get('messages') if isinstance(state.get('messages'), dict) else {}
241
+ for ch in channels:
242
+ if not isinstance(ch, dict):
243
+ continue
244
+ cid = ch.get('channelId') or ch.get('id')
245
+ if not cid:
246
+ continue
247
+ msg_list = messages_map.get(cid) if isinstance(messages_map.get(cid), list) else []
248
+ channel_msgs = ch.get('messages') if isinstance(ch.get('messages'), list) else []
249
+ merged = {
250
+ (m.get('messageId') or m.get('id')): dict(m)
251
+ for m in channel_msgs
252
+ if isinstance(m, dict)
253
+ }
254
+ for m in msg_list:
255
+ if not isinstance(m, dict):
256
+ continue
257
+ mid = m.get('messageId') or m.get('id')
258
+ text = m.get('text') if m.get('text') is not None else m.get('content', '')
259
+ merged[mid] = {
260
+ 'id': mid,
261
+ 'messageId': mid,
262
+ 'text': text,
263
+ 'content': m.get('content', text),
264
+ 'senderId': m.get('senderId'),
265
+ 'timestamp': m.get('timestamp'),
266
+ 'reactions': m.get('reactions') if isinstance(m.get('reactions'), list) else [],
267
+ # Preserve uploaded-file attachments (the 'backup' CSV uploads
268
+ # land here when a message is sent into messages[channelId]).
269
+ 'attachments': m.get('attachments') if isinstance(m.get('attachments'), list) else [],
270
+ }
271
+ ch['messages'] = list(merged.values())
272
+
273
+
274
+ def _owner_name_map(state):
275
+ out = {}
276
+ users = state.get('users') if isinstance(state.get('users'), list) else []
277
+ for u in users:
278
+ if not isinstance(u, dict):
279
+ continue
280
+ uid = u.get('userId')
281
+ if not uid:
282
+ continue
283
+ name = (f"{u.get('firstName', '')} {u.get('lastName', '')}".strip() or u.get('name') or uid)
284
+ out[uid] = name
285
+ return out
286
+
287
+
288
+ def _materialize_salesforce(payload):
289
+ for key in ('initial_state', 'current_state'):
290
+ state = payload.get(key)
291
+ if not isinstance(state, dict):
292
+ continue
293
+
294
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
295
+ owner_names = _owner_name_map(state)
296
+
297
+ task_leads = adapter.get('task_leads') if isinstance(adapter.get('task_leads'), dict) else None
298
+ if task_leads and isinstance(state.get('leads'), list):
299
+ restored = []
300
+ for lead in state['leads']:
301
+ if not isinstance(lead, dict):
302
+ continue
303
+ lid = str(lead.get('leadId') or lead.get('id') or '')
304
+ meta = task_leads.get(lid, {})
305
+ restored.append({
306
+ 'id': meta.get('id') or lead.get('leadId') or lead.get('id'),
307
+ 'company': lead.get('company', meta.get('company', '')),
308
+ 'status': lead.get('status', 'New'),
309
+ 'ownerName': owner_names.get(lead.get('ownerId')) or meta.get('ownerName'),
310
+ 'annualRevenue': meta.get('annualRevenue', lead.get('revenue')),
311
+ })
312
+ state['leads'] = restored
313
+
314
+ task_accounts = adapter.get('task_accounts') if isinstance(adapter.get('task_accounts'), dict) else None
315
+ if task_accounts and isinstance(state.get('accounts'), list):
316
+ current_by_id = {}
317
+ for acc in state['accounts']:
318
+ if isinstance(acc, dict):
319
+ current_by_id[str(acc.get('accountId') or acc.get('id') or '')] = acc
320
+
321
+ restored_accounts = []
322
+ for aid, meta in task_accounts.items():
323
+ cur = current_by_id.get(str(aid), {})
324
+ restored_accounts.append({
325
+ 'id': meta.get('id') or aid,
326
+ 'name': meta.get('name') or cur.get('name', ''),
327
+ 'contact': meta.get('contact'),
328
+ 'wonWithin7d': bool(meta.get('wonWithin7d', False)),
329
+ 'onboardingStage': cur.get('onboardingStage', meta.get('onboardingStage')),
330
+ })
331
+ state['accounts'] = restored_accounts
332
+
333
+
334
+ def _materialize_google_docs(payload):
335
+ for key in ('initial_state', 'current_state'):
336
+ state = payload.get(key)
337
+ if not isinstance(state, dict):
338
+ continue
339
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
340
+ task_docs = adapter.get('task_documents') if isinstance(adapter.get('task_documents'), dict) else None
341
+ if not task_docs:
342
+ continue
343
+ docs_map = state.get('documents') if isinstance(state.get('documents'), dict) else {}
344
+ restored = []
345
+ for did, meta in task_docs.items():
346
+ cur = docs_map.get(did, {}) if isinstance(docs_map, dict) else {}
347
+ restored.append({
348
+ 'id': meta.get('id') or did,
349
+ 'title': cur.get('title', meta.get('title')),
350
+ 'vendor': meta.get('vendor'),
351
+ 'folder': meta.get('folder'),
352
+ 'content': cur.get('content', meta.get('content', '')),
353
+ })
354
+ state['documents'] = restored
355
+
356
+
357
+ def _adapt_payload_for_reward(app, payload):
358
+ app_name = _normalize_app_name(app)
359
+ if app_name == 'google_sheets':
360
+ _materialize_google_sheets(payload)
361
+ elif app_name == 'slack':
362
+ _materialize_slack(payload)
363
+ elif app_name == 'salesforce':
364
+ _materialize_salesforce(payload)
365
+ elif app_name == 'google_docs':
366
+ _materialize_google_docs(payload)
367
+ return payload
368
+
369
+
370
+ def go(app_name):
371
+ if app_name in _GO_CACHE:
372
+ return _GO_CACHE[app_name]
373
+
374
+ base = APP_URLS.get(app_name)
375
+ if not base:
376
+ print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)')
377
+ print('REWARD: 0.0')
378
+ sys.exit(0)
379
+
380
+ try:
381
+ resp = requests.get(f'{base}/go?sid={sid}', timeout=15)
382
+ resp.raise_for_status()
383
+ payload = resp.json()
384
+ except Exception as e:
385
+ print(f'CRITICAL: cannot fetch {app_name} go state: {e}')
386
+ print('REWARD: 0.0')
387
+ sys.exit(0)
388
+
389
+ payload = _adapt_payload_for_reward(app_name, payload)
390
+ _GO_CACHE[app_name] = payload
391
+ return payload
392
+
393
+
394
+ # =============================================================================
395
+ # Task-specific reward
396
+ #
397
+ # Answer key (precomputed at setup) lives in salesforce.initial_state._task_adapter:
398
+ # .expected -> list of 10 row dicts (8 matched + 2 unmatched). Each matched
399
+ # dict carries oppName, account, opportunityId, initial_stage,
400
+ # final_stage, task_subject, task_status, task_status_required,
401
+ # requires_change, requires_task.
402
+ # .matched_count -> n = 8.
403
+ # slack.initial_state._task_adapter:
404
+ # .backup_channel -> 'backup'; .required_csv_count -> 2.
405
+ #
406
+ # We score CURRENT state of each mock against this key. The salesforce materializer
407
+ # leaves opportunities/activities/_task_adapter untouched (no task_leads/task_accounts
408
+ # keys present), so we read them in their native shape.
409
+ # =============================================================================
410
+ def reward(go):
411
+ sf = go('salesforce')
412
+ sf_init = sf.get('initial_state', {}) if isinstance(sf.get('initial_state'), dict) else {}
413
+ sf_cur = sf.get('current_state', {}) if isinstance(sf.get('current_state'), dict) else {}
414
+ adapter = sf_init.get('_task_adapter', {}) if isinstance(sf_init.get('_task_adapter'), dict) else {}
415
+
416
+ expected = adapter.get('expected') if isinstance(adapter.get('expected'), list) else []
417
+ matched = [e for e in expected if isinstance(e, dict) and e.get('matched')]
418
+
419
+ n = adapter.get('matched_count')
420
+ if not isinstance(n, int) or n <= 0:
421
+ n = len(matched)
422
+ if n == 0 or not matched:
423
+ print('DEBUG_T05 no matched rows in answer key — cannot grade')
424
+ return 0.0
425
+
426
+ # --- current SF opportunities indexed by name ---
427
+ opp_by_name = {}
428
+ for o in (sf_cur.get('opportunities') or []):
429
+ if isinstance(o, dict):
430
+ opp_by_name[norm(o.get('name'))] = o
431
+
432
+ # --- current SF activities: normalized subject -> list of normalized statuses ---
433
+ act_subjects = set()
434
+ subj_statuses = {}
435
+ for a in (sf_cur.get('activities') or []):
436
+ if not isinstance(a, dict):
437
+ continue
438
+ s = norm(a.get('subject'))
439
+ if not s:
440
+ continue
441
+ act_subjects.add(s)
442
+ subj_statuses.setdefault(s, []).append(norm(a.get('status')))
443
+
444
+ # Partition matched rows by what the answer key says each REQUIRES.
445
+ change_rows = [e for e in matched if e.get('requires_change')]
446
+ keep_stage_rows = [e for e in matched if not e.get('requires_change')]
447
+ task_rows = [e for e in matched if e.get('requires_task')]
448
+ notask_rows = [e for e in matched if not e.get('requires_task')]
449
+ owner_rows = [e for e in matched if e.get('requires_owner_change')]
450
+ keep_owner_rows = [e for e in matched if not e.get('requires_owner_change')]
451
+
452
+ # ---- Component 1 (0.40): stage set correctly, scored ONLY over rows that
453
+ # require a stage change. Rows already at their target earn NO credit. ----
454
+ stage_ok = 0
455
+ for e in change_rows:
456
+ opp = opp_by_name.get(norm(e.get('oppName')))
457
+ if opp is not None and norm(opp.get('stage')) == norm(e.get('final_stage')):
458
+ stage_ok += 1
459
+ stage_frac = frac(stage_ok, len(change_rows)) if change_rows else 1.0
460
+
461
+ # stage-leak penalty: a must-keep-stage row whose stage drifted from injection.
462
+ stage_leak = 0
463
+ for e in keep_stage_rows:
464
+ opp = opp_by_name.get(norm(e.get('oppName')))
465
+ baseline = e.get('initial_stage')
466
+ if baseline is None:
467
+ baseline = e.get('final_stage')
468
+ if opp is not None and norm(opp.get('stage')) != norm(baseline):
469
+ stage_leak += 1
470
+ stage_leak_frac = frac(stage_leak, len(keep_stage_rows)) if keep_stage_rows else 0.0
471
+
472
+ # ---- Component 2 (0.25): follow-up Task created, scored ONLY over rows that
473
+ # require a task. Creating a forbidden task on other rows is penalized. ----
474
+ task_ok = 0
475
+ for e in task_rows:
476
+ want_subj = norm(e.get('task_subject'))
477
+ present = bool(want_subj) and want_subj in act_subjects
478
+ if present and e.get('task_status_required'):
479
+ present = any(st == norm('Not Started') for st in subj_statuses.get(want_subj, []))
480
+ if present:
481
+ task_ok += 1
482
+ task_frac = frac(task_ok, len(task_rows)) if task_rows else 1.0
483
+
484
+ # task-leak penalty: a no-task matched row that nonetheless gained a
485
+ # 'Kickoff: <Account>' / 'Exec review: <Account>' task.
486
+ task_leak = 0
487
+ for e in notask_rows:
488
+ account = e.get('account')
489
+ forbidden = {norm(f'Kickoff: {account}'), norm(f'Exec review: {account}')}
490
+ if forbidden & act_subjects:
491
+ task_leak += 1
492
+ task_leak_frac = frac(task_leak, len(notask_rows)) if notask_rows else 0.0
493
+
494
+ # ---- Component 3 (0.20): owner reassigned, scored ONLY over rows that
495
+ # require an owner change (Closed Won). Other rows must keep their owner. ----
496
+ owner_ok = 0
497
+ for e in owner_rows:
498
+ opp = opp_by_name.get(norm(e.get('oppName')))
499
+ want_owner = norm(e.get('final_owner'))
500
+ if opp is not None and want_owner and norm(opp.get('ownerId')) == want_owner:
501
+ owner_ok += 1
502
+ owner_frac = frac(owner_ok, len(owner_rows)) if owner_rows else 1.0
503
+
504
+ # owner-leak penalty: a must-keep-owner row whose owner drifted from seeded.
505
+ owner_leak = 0
506
+ for e in keep_owner_rows:
507
+ opp = opp_by_name.get(norm(e.get('oppName')))
508
+ baseline = norm(e.get('initial_owner'))
509
+ if opp is not None and baseline and norm(opp.get('ownerId')) != baseline:
510
+ owner_leak += 1
511
+ owner_leak_frac = frac(owner_leak, len(keep_owner_rows)) if keep_owner_rows else 0.0
512
+
513
+ # ---- Component 4 (0.15): Slack 'backup' channel created + 2 CSV files uploaded ----
514
+ slack_payload = go('slack')
515
+ slack_cur = slack_payload.get('current_state', {}) if isinstance(slack_payload.get('current_state'), dict) else {}
516
+ slack_init = slack_payload.get('initial_state', {}) if isinstance(slack_payload.get('initial_state'), dict) else {}
517
+ s_adapter = slack_init.get('_task_adapter', {}) if isinstance(slack_init.get('_task_adapter'), dict) else {}
518
+ backup_channel = s_adapter.get('backup_channel') or 'backup'
519
+ required_csv = s_adapter.get('required_csv_count')
520
+ if not isinstance(required_csv, int) or required_csv <= 0:
521
+ required_csv = 2
522
+
523
+ def _channel_exists(state, name):
524
+ chans = state.get('channels', []) if isinstance(state, dict) else []
525
+ return any(isinstance(c, dict) and norm(c.get('name')) == norm(name) for c in chans)
526
+
527
+ def _is_csv_attachment(att):
528
+ if not isinstance(att, dict):
529
+ return False
530
+ nm = norm(att.get('name') or att.get('fileName') or att.get('filename'))
531
+ mt = norm(att.get('mimeType') or att.get('mime') or att.get('type'))
532
+ url = norm(att.get('url'))
533
+ return nm.endswith('.csv') or 'csv' in mt or url.endswith('.csv')
534
+
535
+ # Channel must be NEWLY created (absent at injection, present now).
536
+ backup_exists_now = _channel_exists(slack_cur, backup_channel)
537
+ backup_existed_init = _channel_exists(slack_init, backup_channel)
538
+ channel_ok = bool(backup_exists_now and not backup_existed_init)
539
+
540
+ # Count distinct CSV files uploaded into the backup channel.
541
+ csv_count = 0
542
+ if backup_exists_now:
543
+ for m in _slack_channel_messages(slack_cur, backup_channel):
544
+ for att in (m.get('attachments') or []) if isinstance(m, dict) else []:
545
+ if _is_csv_attachment(att):
546
+ csv_count += 1
547
+
548
+ # Sub-score: 0.4 for creating the channel, 0.6 for uploading >= required CSVs
549
+ # (proportional credit for 1 of 2). Only counts CSVs inside the new channel.
550
+ slack_ok = 0.0
551
+ if channel_ok:
552
+ slack_ok = 0.4 + 0.6 * min(csv_count, required_csv) / required_csv
553
+
554
+ # ---- Combine: positives (0 in do-nothing) minus leak penalties (0 in do-nothing) ----
555
+ # Weights: stage 0.40 + task 0.25 + owner 0.20 + slack 0.15 = 1.0. The Slack
556
+ # backup step was raised 0.05 -> 0.15 (it now requires creating a channel AND
557
+ # uploading two exported CSVs), so the SF-core components were trimmed 0.10 total.
558
+ s_stage = 0.40 * stage_frac
559
+ s_task = 0.25 * task_frac
560
+ s_owner = 0.20 * owner_frac
561
+ s_slack = 0.15 * slack_ok
562
+ positive = s_stage + s_task + s_owner + s_slack
563
+ penalty = 0.15 * stage_leak_frac + 0.10 * task_leak_frac + 0.10 * owner_leak_frac
564
+ score = clamp01(positive - penalty)
565
+
566
+ print(
567
+ 'DEBUG_T05 '
568
+ f'n={n} stage_ok={stage_ok}/{len(change_rows)} stage_leak={stage_leak}/{len(keep_stage_rows)} '
569
+ f'task_ok={task_ok}/{len(task_rows)} task_leak={task_leak}/{len(notask_rows)} '
570
+ f'owner_ok={owner_ok}/{len(owner_rows)} owner_leak={owner_leak}/{len(keep_owner_rows)} '
571
+ f'backup_channel_ok={int(channel_ok)} csv_count={csv_count}/{required_csv} slack_ok={round(slack_ok, 3)} '
572
+ f'w_stage={round(s_stage, 4)} w_task={round(s_task, 4)} w_owner={round(s_owner, 4)} '
573
+ f'w_slack={round(s_slack, 4)} penalty={round(penalty, 4)} total={round(score, 4)}'
574
+ )
575
+
576
+ return clamp01(score)
577
+
578
+
579
+ try:
580
+ score = float(reward(go))
581
+ except Exception as exc:
582
+ print(f'ERROR: reward() raised {exc!r}')
583
+ score = 0.0
584
+
585
+ score = clamp01(score)
586
+ print(f'\nREWARD: {round(score, 4)}')
am_renewal_hubspot_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"
am_renewal_hubspot_004__long/initial_setup.py ADDED
@@ -0,0 +1,688 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: T04 — HubSpot renewal outreach across HubSpot + Gmail + Google Calendar
3
+ (hidden-access-point edition)
4
+ Task ID: am_renewal_hubspot_004__long
5
+ Mocks: hubspot_mock, gmail_mock, google_calendar_mock
6
+
7
+ Assume today is 2026-05-04 (a Monday). A deal QUALIFIES for renewal outreach iff
8
+ ALL hold:
9
+ - stage == 'closed_won' (label "Closed Won")
10
+ - dealType == 'existing_business'
11
+ - 2025-05-01 <= closeDate <= 2025-07-31 (inclusive)
12
+ - amount >= 10000
13
+
14
+ For every QUALIFYING deal the agent must perform SIX sub-actions across the three
15
+ apps, several of which are reachable only through HARD-TO-FIND ("hidden") controls:
16
+
17
+ HubSpot (both edits live in the slide-in panel opened by clicking the deal NAME):
18
+ (H1) append the line 'Renewal outreach sent 2026-05-04.' to the deal Description
19
+ (keeping the existing text).
20
+ (H2) reassign the deal owner — the free-text "Assigned To" field — from
21
+ 'Admin User' to 'Renewals Team'.
22
+ Gmail:
23
+ (G1) send an email to the deal's primary contact with Subject 'Renewal: <Company>'
24
+ and a body containing the company name, the original amount formatted as
25
+ $#,##0, and the original closeDate. (Obstacle: the email has to be found in HubSpot's contacts list. The contact is in the deal)
26
+ (G2) apply the 'Renewals' label to that sent email. The Label button only appears
27
+ in the toolbar AFTER an email row is selected (selection-gated control).
28
+ Google Calendar:
29
+ (C1) create a 'Renewal call: <Company>' event one week out (2026-05-11).
30
+ (C2) add the contact's email as a GUEST. The guest field is buried inside the
31
+ event editor and the contact is NOT in the autocomplete list, so the email
32
+ must be typed in.
33
+
34
+ Distractors (5 near-miss deals) each miss exactly ONE qualifying condition and must
35
+ be left untouched (no description edit, no owner change, no email, no label, no event).
36
+
37
+ Ground truth is PRECOMPUTED below in Python so the embedded answer key (hidden `_*`
38
+ fields on hubspot deals) is internally consistent with the visible deal/company/
39
+ contact data. reward.py reads `deals[*]._qualifies` (+ helper `_*` fields) from
40
+ initial_state as the sole source of truth.
41
+ """
42
+ import os
43
+ import shlex
44
+ import subprocess
45
+ import time
46
+ import uuid
47
+ from datetime import date
48
+
49
+ import requests
50
+
51
+
52
+ sid = str(uuid.uuid4())
53
+ with open('/tmp/task_web_sid', 'w', encoding='utf-8') as f:
54
+ f.write(sid)
55
+ print(f'Generated sid: {sid}')
56
+
57
+
58
+ # --------------------------------------------------------------------------- #
59
+ # Task constants
60
+ # --------------------------------------------------------------------------- #
61
+ TODAY = date(2026, 5, 4)
62
+ TODAY_STR = TODAY.isoformat() # '2026-05-04'
63
+ RENEWAL_LINE = f'Renewal outreach sent {TODAY_STR}.'
64
+ WINDOW_START = date(2025, 5, 1)
65
+ WINDOW_END = date(2025, 7, 31)
66
+ MIN_AMOUNT = 10000
67
+
68
+ NEW_OWNER = 'Renewals Team' # H2: owner reassignment target
69
+ ORIG_OWNER = 'Admin User' # owner at injection
70
+ RENEWALS_LABEL_ID = 'l3' # G2: label to apply (seeded below)
71
+ RENEWALS_LABEL_NAME = 'Renewals'
72
+ EVENT_DATE_STR = '2026-05-11' # C1: one week from today (a Monday)
73
+
74
+
75
+ # --------------------------------------------------------------------------- #
76
+ # Builder helpers (keep many similar records terse)
77
+ # --------------------------------------------------------------------------- #
78
+ def company(cid, name, domain, industry, city, st, employees, revenue):
79
+ return {
80
+ 'id': cid, 'name': name, 'domain': domain, 'industry': industry,
81
+ 'phone': f'+1 (555) 1{cid[-1]}0-00{cid[-1]}0',
82
+ 'city': city, 'state': st, 'country': 'United States',
83
+ 'numberOfEmployees': employees, 'annualRevenue': revenue,
84
+ 'lifecycleStage': 'customer', 'owner': ORIG_OWNER,
85
+ 'description': f'{name} — {industry} customer account',
86
+ 'createDate': '2023-08-10T09:00:00Z',
87
+ }
88
+
89
+
90
+ def contact(cid, first, last, email, title, company_id, city, st):
91
+ return {
92
+ 'id': cid, 'firstName': first, 'lastName': last, 'email': email,
93
+ 'phone': '+1 (555) 010-0000', 'jobTitle': title, 'companyId': company_id,
94
+ 'lifecycleStage': 'customer', 'leadStatus': 'connected',
95
+ 'owner': ORIG_OWNER, 'city': city, 'state': st, 'country': 'United States',
96
+ 'createDate': '2023-08-15T10:30:00Z', 'lastActivityDate': '2026-04-20T14:00:00Z',
97
+ 'timeline': [],
98
+ }
99
+
100
+
101
+ def deal(did, name, stage, amount, close_date, deal_type, company_id, contact_ids,
102
+ description, priority='medium'):
103
+ return {
104
+ 'id': did, 'name': name, 'stage': stage, 'amount': amount,
105
+ 'closeDate': close_date, 'dealType': deal_type, 'priority': priority,
106
+ 'owner': ORIG_OWNER, 'companyId': company_id, 'contactIds': contact_ids,
107
+ 'probability': 100 if stage == 'closed_won' else (0 if stage == 'closed_lost' else 60),
108
+ 'description': description,
109
+ 'createDate': '2024-04-01T10:00:00Z', 'lastActivityDate': '2025-07-15T14:00:00Z',
110
+ }
111
+
112
+
113
+ def gmail_email(eid, frm, to, subject, body, folder='inbox', timestamp='2026-04-30T09:00:00Z'):
114
+ return {
115
+ 'id': eid, 'threadId': f'thread_{eid}',
116
+ 'from': frm, 'to': to, 'cc': [], 'bcc': [],
117
+ 'subject': subject, 'body': body, 'snippet': body[:120],
118
+ 'timestamp': timestamp, 'read': True, 'starred': False, 'important': False,
119
+ 'labels': [], 'category': 'primary', 'folder': folder, 'attachments': [],
120
+ }
121
+
122
+
123
+ def cal_event(eid, calendar_id, title, start_iso, end_iso, location, description, guests):
124
+ """A calendar event in the shape google_calendar_mock stores them."""
125
+ return {
126
+ 'id': eid, 'calendarId': calendar_id, 'title': title,
127
+ 'start': start_iso, 'end': end_iso,
128
+ 'allDay': False, 'location': location, 'description': description,
129
+ 'guests': guests, 'color': '#33B679', 'recurring': 'none',
130
+ 'reminders': [{'type': 'popup', 'minutes': 10}],
131
+ }
132
+
133
+
134
+ # --------------------------------------------------------------------------- #
135
+ # Companies (one per deal; comp1..comp4 are the qualifying accounts)
136
+ # --------------------------------------------------------------------------- #
137
+ companies = [
138
+ company('comp1', 'Acme', 'acme.com', 'Technology', 'San Francisco', 'CA', 250, 15000000),
139
+ company('comp2', 'Globex', 'globex.com', 'Manufacturing', 'New York', 'NY', 500, 32000000),
140
+ company('comp3', 'Initech', 'initech.com', 'Technology', 'Austin', 'TX', 120, 8000000),
141
+ company('comp4', 'Umbrella', 'umbrella.com', 'Healthcare', 'Boston', 'MA', 800, 55000000),
142
+ company('comp5', 'Wayne', 'wayne.com', 'Finance', 'Chicago', 'IL', 1200, 90000000),
143
+ company('comp6', 'Hooli', 'hooli.com', 'Technology', 'Palo Alto', 'CA', 900, 60000000),
144
+ company('comp7', 'Stark', 'stark.com', 'Manufacturing', 'Los Angeles', 'CA', 1500, 120000000),
145
+ company('comp8', 'Cyberdyne', 'cyberdyne.com', 'Technology', 'Sunnyvale', 'CA', 700, 40000000),
146
+ company('comp9', 'Wonka', 'wonka.com', 'Other', 'Chicago', 'IL', 300, 18000000),
147
+ ]
148
+
149
+ # Contacts. Each QUALIFYING company (comp1..comp4) has exactly ONE contact, so
150
+ # "first contact whose companyId matches" is unambiguous on the graded slice.
151
+ # Non-qualifying companies carry a couple of extra decoy contacts (realism).
152
+ contacts = [
153
+ contact('c1', 'Alice', 'Chen', 'alice.chen@acme.com', 'VP Operations', 'comp1', 'San Francisco', 'CA'),
154
+ contact('c2', 'Bob', 'Martin', 'bob.martin@globex.com', 'Procurement Lead', 'comp2', 'New York', 'NY'),
155
+ contact('c3', 'Carol', 'Diaz', 'carol.diaz@initech.com', 'IT Director', 'comp3', 'Austin', 'TX'),
156
+ contact('c4', 'Dan', 'Wong', 'dan.wong@umbrella.com', 'Head of Research', 'comp4', 'Boston', 'MA'),
157
+ contact('c5', 'Eve', 'Parker', 'eve.parker@wayne.com', 'CFO', 'comp5', 'Chicago', 'IL'),
158
+ contact('c6', 'Frank', 'Lee', 'frank.lee@hooli.com', 'Eng Manager', 'comp6', 'Palo Alto', 'CA'),
159
+ contact('c7', 'Grace', 'Kim', 'grace.kim@stark.com', 'Plant Director', 'comp7', 'Los Angeles', 'CA'),
160
+ contact('c8', 'Henry', 'Cole', 'henry.cole@cyberdyne.com', 'CTO', 'comp8', 'Sunnyvale', 'CA'),
161
+ contact('c9', 'Iris', 'Shah', 'iris.shah@wonka.com', 'COO', 'comp9', 'Chicago', 'IL'),
162
+ # decoy second contacts on NON-qualifying accounts only
163
+ contact('c10', 'Mia', 'Stone', 'mia.stone@wayne.com', 'Controller', 'comp5', 'Chicago', 'IL'),
164
+ contact('c11', 'Leo', 'Burns', 'leo.burns@stark.com', 'Ops Analyst', 'comp7', 'Los Angeles', 'CA'),
165
+ ]
166
+
167
+
168
+ # --------------------------------------------------------------------------- #
169
+ # Deals — 4 qualifying + 5 near-miss distractors
170
+ # d1 Acme QUALIFIES (existing, 2025-05-15, $24,000)
171
+ # d2 Globex QUALIFIES (existing, 2025-06-30, $15,000)
172
+ # d3 Initech QUALIFIES (existing, 2025-07-31 high boundary, $50,000)
173
+ # d4 Umbrella QUALIFIES (existing, 2025-05-01 low boundary, $12,000)
174
+ # d5 Wayne NO -> new_business (right window+stage, $30,000)
175
+ # d6 Hooli NO -> amount 8000 < 10000 (existing, in window)
176
+ # d7 Stark NO -> closeDate 2025-04-15 just BEFORE window
177
+ # d8 Cyberdyne NO -> stage closed_lost (existing, in window, $35,000)
178
+ # d9 Wonka NO -> closeDate 2025-08-15 just AFTER window
179
+ # --------------------------------------------------------------------------- #
180
+ deals = [
181
+ deal('d1', 'Acme - Platform Subscription', 'closed_won', 24000, '2025-05-15',
182
+ 'existing_business', 'comp1', ['c1'],
183
+ 'Annual platform subscription, 250 seats. Renewed last cycle without issues.', 'high'),
184
+ deal('d2', 'Globex - Support Contract', 'closed_won', 15000, '2025-06-30',
185
+ 'existing_business', 'comp2', ['c2'],
186
+ 'Gold support contract covering all manufacturing sites.', 'medium'),
187
+ deal('d3', 'Initech - Enterprise Plan', 'closed_won', 50000, '2025-07-31',
188
+ 'existing_business', 'comp3', ['c3'],
189
+ 'Enterprise plan with premium SLA and onboarding.', 'high'),
190
+ deal('d4', 'Umbrella - Compliance Module', 'closed_won', 12000, '2025-05-01',
191
+ 'existing_business', 'comp4', ['c4'],
192
+ 'Compliance reporting module add-on for research division.', 'medium'),
193
+ # ---- distractors ----
194
+ deal('d5', 'Wayne - New Analytics Suite', 'closed_won', 30000, '2025-06-10',
195
+ 'new_business', 'comp5', ['c5'],
196
+ 'First-time purchase of the analytics suite for finance ops.', 'high'),
197
+ deal('d6', 'Hooli - Small Add-on', 'closed_won', 8000, '2025-06-20',
198
+ 'existing_business', 'comp6', ['c6'],
199
+ 'Minor seat expansion add-on, below renewal threshold.', 'low'),
200
+ deal('d7', 'Stark - Spring Renewal', 'closed_won', 40000, '2025-04-15',
201
+ 'existing_business', 'comp7', ['c7'],
202
+ 'Renewal that closed in April, outside the summer window.', 'high'),
203
+ deal('d8', 'Cyberdyne - Lost Renewal', 'closed_lost', 35000, '2025-06-05',
204
+ 'existing_business', 'comp8', ['c8'],
205
+ 'Renewal that lapsed; customer churned to a competitor.', 'medium'),
206
+ deal('d9', 'Wonka - Late Summer Renewal', 'closed_won', 22000, '2025-08-15',
207
+ 'existing_business', 'comp9', ['c9'],
208
+ 'Renewal closing in late August, just after the window.', 'medium'),
209
+ ]
210
+
211
+
212
+ # --------------------------------------------------------------------------- #
213
+ # PRECOMPUTE the ground truth and embed hidden `_*` answer-key fields.
214
+ # --------------------------------------------------------------------------- #
215
+ def parse_date(s):
216
+ y, m, d = (int(x) for x in s.split('-'))
217
+ return date(y, m, d)
218
+
219
+
220
+ def primary_contact_email(company_id):
221
+ """companies[].name -> contacts where companyId matches, first such email."""
222
+ for c in contacts:
223
+ if c['companyId'] == company_id:
224
+ return c['email']
225
+ return None
226
+
227
+
228
+ def fmt_amount(amount):
229
+ """Original amount formatted as $#,##0 (e.g. 24000 -> '$24,000')."""
230
+ return f'${amount:,}'
231
+
232
+
233
+ n_qualifying = 0
234
+ for d in deals:
235
+ cd = parse_date(d['closeDate'])
236
+ qualifies = (
237
+ d['stage'] == 'closed_won'
238
+ and d['dealType'] == 'existing_business'
239
+ and WINDOW_START <= cd <= WINDOW_END
240
+ and d['amount'] >= MIN_AMOUNT
241
+ )
242
+ company_name = next(c['name'] for c in companies if c['id'] == d['companyId'])
243
+ contact_email = primary_contact_email(d['companyId'])
244
+ d['_qualifies'] = qualifies
245
+ d['_company_name'] = company_name
246
+ d['_primary_contact_email'] = contact_email
247
+ d['_orig_owner'] = ORIG_OWNER
248
+ d['_email_subject'] = f'Renewal: {company_name}' # ALL deals (leak shape)
249
+ d['_event_title'] = f'Renewal call: {company_name}' # ALL deals (leak shape)
250
+ if qualifies:
251
+ n_qualifying += 1
252
+ # --- HubSpot answer key ---
253
+ d['_renewal_line'] = RENEWAL_LINE
254
+ d['_expected_description'] = d['description'] + '\n' + RENEWAL_LINE
255
+ d['_new_owner'] = NEW_OWNER
256
+ # --- Gmail answer key ---
257
+ d['_amount_fmt'] = fmt_amount(d['amount'])
258
+ d['_close_date'] = d['closeDate']
259
+ # Body must contain ALL of these substrings.
260
+ d['_email_body_must_contain'] = [company_name, fmt_amount(d['amount']), d['closeDate']]
261
+ d['_renewals_label_id'] = RENEWALS_LABEL_ID
262
+ d['_renewals_label_name'] = RENEWALS_LABEL_NAME
263
+ # --- Calendar answer key ---
264
+ d['_event_date'] = EVENT_DATE_STR
265
+ d['_event_guest_email'] = contact_email
266
+ else:
267
+ # Distractors must receive NO edits, NO email, NO label, NO event.
268
+ d['_renewal_line'] = None
269
+
270
+ assert n_qualifying == 4, f'expected 4 qualifying deals, got {n_qualifying}'
271
+ print(f'Precomputed ground truth: {n_qualifying} qualifying deals '
272
+ f'({[d["id"] for d in deals if d["_qualifies"]]})')
273
+
274
+
275
+ # Standard 7-stage pipeline configuration (default labels; "Closed Won" column).
276
+ DEAL_STAGES = {
277
+ 'appointment_scheduled': {'id': 'appointment_scheduled', 'label': 'Appointment Scheduled', 'probability': 20, 'color': '#E5F4FF', 'order': 1},
278
+ 'qualified_to_buy': {'id': 'qualified_to_buy', 'label': 'Qualified to Buy', 'probability': 40, 'color': '#FFF0E6', 'order': 2},
279
+ 'presentation_scheduled': {'id': 'presentation_scheduled', 'label': 'Presentation Scheduled', 'probability': 60, 'color': '#FFF8E6', 'order': 3},
280
+ 'decision_maker_bought_in': {'id': 'decision_maker_bought_in', 'label': 'Decision Maker Bought-In', 'probability': 80, 'color': '#E8F5E9', 'order': 4},
281
+ 'contract_sent': {'id': 'contract_sent', 'label': 'Contract Sent', 'probability': 90, 'color': '#E6FFFA', 'order': 5},
282
+ 'closed_won': {'id': 'closed_won', 'label': 'Closed Won', 'probability': 100, 'color': '#E6FFEC', 'order': 6},
283
+ 'closed_lost': {'id': 'closed_lost', 'label': 'Closed Lost', 'probability': 0, 'color': '#FFE6E6', 'order': 7},
284
+ }
285
+ TICKET_STATUSES = {
286
+ 'new': {'id': 'new', 'label': 'New', 'color': '#E5F4FF', 'order': 1},
287
+ 'waiting_on_contact': {'id': 'waiting_on_contact', 'label': 'Waiting on Contact', 'color': '#FFF8E6', 'order': 2},
288
+ 'waiting_on_us': {'id': 'waiting_on_us', 'label': 'Waiting on Us', 'color': '#FFF0E6', 'order': 3},
289
+ 'in_progress': {'id': 'in_progress', 'label': 'In Progress', 'color': '#E6FFFA', 'order': 4},
290
+ 'closed': {'id': 'closed', 'label': 'Closed', 'color': '#E6FFEC', 'order': 5},
291
+ }
292
+
293
+
294
+ # --------------------------------------------------------------------------- #
295
+ # Gmail account (sales rep doing the outreach). NO renewal mail pre-seeded:
296
+ # the 'sent' folder contains no 'Renewal: <Company>' subjects (Rule 3). A few
297
+ # read inbox emails act as watermark / realism only. A 'Renewals' label is
298
+ # pre-created (l3) so the agent can APPLY it; no email carries it at injection.
299
+ # --------------------------------------------------------------------------- #
300
+ gmail_user = {
301
+ 'userId': 'u1', 'username': 'Jordan Avery',
302
+ 'email': 'jordan.avery@ourcompany.com',
303
+ 'avatar': 'https://picsum.photos/200/200?random=7',
304
+ }
305
+ gmail_emails = [
306
+ gmail_email('m1',
307
+ {'name': 'Alice Chen', 'email': 'alice.chen@acme.com', 'avatar': ''},
308
+ [{'name': 'Jordan Avery', 'email': 'jordan.avery@ourcompany.com'}],
309
+ 'Re: Q1 usage report',
310
+ 'Thanks for the usage report — numbers look healthy on our end.',
311
+ folder='inbox', timestamp='2026-04-28T09:15:00Z'),
312
+ gmail_email('m2',
313
+ {'name': 'Billing', 'email': 'billing@globex.com', 'avatar': ''},
314
+ [{'name': 'Jordan Avery', 'email': 'jordan.avery@ourcompany.com'}],
315
+ 'Invoice received',
316
+ 'Confirming we received the latest support invoice. No action needed.',
317
+ folder='inbox', timestamp='2026-04-29T11:00:00Z'),
318
+ gmail_email('m3',
319
+ {'name': 'Jordan Avery', 'email': 'jordan.avery@ourcompany.com', 'avatar': ''},
320
+ [{'name': 'Carol Diaz', 'email': 'carol.diaz@initech.com'}],
321
+ 'Onboarding follow-up',
322
+ 'Glad onboarding went smoothly. Reach out anytime with questions.',
323
+ folder='sent', timestamp='2026-04-22T16:30:00Z'),
324
+ ]
325
+ gmail_labels = [
326
+ {'id': 'l1', 'name': 'Work', 'color': '#ef4444'},
327
+ {'id': 'l2', 'name': 'Personal', 'color': '#3b82f6'},
328
+ {'id': RENEWALS_LABEL_ID, 'name': RENEWALS_LABEL_NAME, 'color': '#16a34a'},
329
+ ]
330
+
331
+
332
+ # --------------------------------------------------------------------------- #
333
+ # Google Calendar account. today = 2026-05-04. A couple of decoy events for
334
+ # realism on the Work calendar; NONE titled 'Renewal call:' (Rule 3 — the
335
+ # gradable output must be absent at injection).
336
+ # --------------------------------------------------------------------------- #
337
+ # NOTE: use timezone-NAIVE local ISO (no trailing 'Z') to match the shape the
338
+ # calendar mock stores when the user creates events through the UI. Mixing
339
+ # UTC-suffixed injected events with naive-local user-created events makes the
340
+ # newly created event appear on a different day/time-slot in the week grid
341
+ # (or vanish entirely from the visible viewport). See the working reference
342
+ # in demo_tasks/.../975bd1cb-.../initial_setup.py.
343
+ calendar_events = [
344
+ cal_event('evt_standup', 'c2', 'Team Standup',
345
+ '2026-05-04T09:30:00', '2026-05-04T10:00:00',
346
+ 'Conference Room A', 'Daily sync', ['teammate@ourcompany.com']),
347
+ cal_event('evt_pipeline', 'c2', 'Pipeline Review',
348
+ '2026-05-06T14:00:00', '2026-05-06T15:00:00',
349
+ 'Zoom', 'Weekly pipeline review', []),
350
+ cal_event('evt_lunch', 'c1', 'Lunch with Sarah',
351
+ '2026-05-05T12:00:00', '2026-05-05T13:00:00',
352
+ 'Downtown Cafe', '', []),
353
+ ]
354
+
355
+
356
+ # --------------------------------------------------------------------------- #
357
+ # APP_STATES — full key set per mock; answer key embedded in hubspot.deals[*].
358
+ # --------------------------------------------------------------------------- #
359
+ APP_STATES = [
360
+ ('http://28.7.184.198:8150', { # hubspot_mock
361
+ 'contacts': contacts,
362
+ 'companies': companies,
363
+ 'deals': deals,
364
+ 'tickets': [],
365
+ 'tasks': [],
366
+ 'notes': [],
367
+ 'templates': [],
368
+ 'meetings': [],
369
+ 'forms': [],
370
+ 'dealStages': DEAL_STAGES,
371
+ 'ticketStatuses': TICKET_STATUSES,
372
+ 'appState': {
373
+ 'sidebarOpen': True,
374
+ 'currentUser': {'name': 'Admin User', 'email': 'admin@example.com', 'avatar': None},
375
+ },
376
+ '_task_adapter': {'task_id': 'T04_hubspot_renewal_outreach_3app', 'variant': 'eval'},
377
+ }),
378
+ ('http://28.7.184.198:8138', { # gmail_mock — sent folder has NO renewal mail
379
+ 'user': gmail_user,
380
+ 'emails': gmail_emails,
381
+ 'labels': gmail_labels,
382
+ 'drafts': [],
383
+ 'settings': {
384
+ 'density': 'default', 'undoSend': 10,
385
+ 'categoryTabs': {'primary': True, 'social': True, 'promotions': True,
386
+ 'updates': False, 'forums': False},
387
+ },
388
+ 'today': TODAY_STR,
389
+ }),
390
+ ('http://28.7.184.198:8141', { # google_calendar_mock — no 'Renewal call:' events
391
+ 'user': {'id': 'u1', 'username': 'Jordan Avery',
392
+ 'email': 'jordan.avery@ourcompany.com',
393
+ 'avatar': 'https://picsum.photos/100/100?random=u1'},
394
+ # WeekView renders event chips with backgroundColor=<event.color OR
395
+ # calendar.color>. The React component only accepts hex strings ('#RRGGBB');
396
+ # tailwind class names like 'bg-green-500' are invalid CSS colors, so the
397
+ # event blocks render but are invisible on the grid (though the click
398
+ # popup still shows the correct data). Use hex to match the working
399
+ # setup in demo_tasks/.../975bd1cb-.../initial_setup.py.
400
+ 'calendars': [
401
+ {'id': 'c1', 'name': 'Personal', 'color': '#039BE5',
402
+ 'textColor': 'text-white', 'visible': True, 'userId': 'u1',
403
+ 'isDefault': True},
404
+ {'id': 'c2', 'name': 'Work', 'color': '#33B679',
405
+ 'textColor': 'text-white', 'visible': True, 'userId': 'u1',
406
+ 'isDefault': False},
407
+ ],
408
+ 'events': calendar_events,
409
+ 'view': 'week',
410
+ # naive local ISO (no trailing Z), matches events[*].start above
411
+ 'currentDate': '2026-05-04T00:00:00',
412
+ 'sidebarOpen': True,
413
+ 'settings': {
414
+ 'weekStart': 0, 'defaultDuration': 60, 'defaultView': 'week',
415
+ 'defaultReminder': {'type': 'popup', 'minutes': 10},
416
+ },
417
+ 'today': TODAY_STR,
418
+ }),
419
+ ]
420
+
421
+
422
+ for app_url, state in APP_STATES:
423
+ resp = requests.post(
424
+ f'{app_url}/post?sid={sid}',
425
+ json={'action': 'set', 'state': state},
426
+ timeout=30,
427
+ )
428
+ assert resp.status_code == 200, (
429
+ f'State injection failed for {app_url}: {resp.text}'
430
+ )
431
+ print(f'State injected: {app_url} sid={sid}')
432
+
433
+ for app_url, _ in APP_STATES:
434
+ go_payload = requests.get(f'{app_url}/go?sid={sid}', timeout=15).json()
435
+ assert go_payload.get('initial_state') is not None, (
436
+ f'initial_state is None after injection for {app_url}'
437
+ )
438
+ print(f'Verified initial_state set: {app_url}')
439
+
440
+
441
+ # PATCHED_BY: patch_wait_mocks_loaded.py
442
+ def launch_gui(command, delay_sec=1.0):
443
+ """Launch a GUI command, fully detached from this script.
444
+
445
+ Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that
446
+ wait_mocks_loaded's CDP phase can verify browser render below.
447
+ Idempotent: if the caller already specified a debug port, keep it.
448
+ """
449
+ env = os.environ.copy()
450
+ env['DISPLAY'] = ':0'
451
+ if isinstance(command, str):
452
+ _parts = shlex.split(command)
453
+ else:
454
+ _parts = list(command)
455
+ if (_parts and 'google-chrome' in _parts[0]
456
+ and not any(p.startswith('--remote-debugging-port') for p in _parts)):
457
+ _parts[1:1] = [
458
+ '--no-first-run',
459
+ '--no-default-browser-check',
460
+ '--remote-debugging-port=1337',
461
+ ]
462
+ subprocess.Popen(
463
+ _parts,
464
+ stdin=subprocess.DEVNULL,
465
+ stdout=subprocess.DEVNULL,
466
+ stderr=subprocess.DEVNULL,
467
+ env=env,
468
+ start_new_session=True,
469
+ )
470
+ time.sleep(delay_sec)
471
+
472
+
473
+ def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12):
474
+ """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style.
475
+
476
+ Phase 1 - Backend readiness:
477
+ Poll each mock's /state?sid=<sid> (preferred) or /go?sid=<sid>
478
+ (fallback) until it returns 200 with 'stored_state' or
479
+ 'initial_state' respectively, or until timeout.
480
+
481
+ Phase 2 - Browser render verification (via CDP + Playwright):
482
+ Connect to http://localhost:1337 (the --remote-debugging-port
483
+ injected by launch_gui above), wait for every open tab to reach
484
+ 'networkidle' AND to contain at least 20 DOM elements. This
485
+ guarantees the SPA fetched /go?sid= data AND actually painted,
486
+ not just that the mock backend is up.
487
+
488
+ Fallback:
489
+ If Playwright is missing or CDP cannot be reached, sleep for
490
+ `render_buffer` seconds as a best-effort delay so the screenshot
491
+ loop does not start on a still-blank tab.
492
+ """
493
+ import urllib.request as _urlreq
494
+ import time as _t
495
+ _urls = [p for p, _ in app_states]
496
+ _opener = _urlreq.build_opener(_urlreq.ProxyHandler({}))
497
+
498
+ # ---- Phase 1: backend readiness ----
499
+ _deadline = _t.time() + timeout
500
+ _todo = list(_urls)
501
+ while _todo and _t.time() < _deadline:
502
+ _rest = []
503
+ for _u in _todo:
504
+ _ok = False
505
+ for _path, _need in (('/state?sid=', b'stored_state'),
506
+ ('/go?sid=', b'initial_state')):
507
+ try:
508
+ _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5)
509
+ if _r.status == 200:
510
+ _body = _r.read()
511
+ if _need in _body:
512
+ _ok = True
513
+ break
514
+ except Exception:
515
+ pass
516
+ if _ok:
517
+ print(f" {_u}: backend ready")
518
+ continue
519
+ _rest.append(_u)
520
+ _todo = _rest
521
+ if _todo:
522
+ _t.sleep(2)
523
+ _done = len(_urls) - len(_todo)
524
+ _pend = f" (pending: {_todo})" if _todo else ""
525
+ print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}")
526
+
527
+ # ---- Phase 2: browser render verification via CDP ----
528
+ _cdp_ok = False
529
+ try:
530
+ from playwright.sync_api import sync_playwright
531
+ _cdp_dl = _t.time() + max(15.0, _deadline - _t.time())
532
+ with sync_playwright() as _p:
533
+ _br = None
534
+ while _t.time() < _cdp_dl:
535
+ try:
536
+ _br = _p.chromium.connect_over_cdp('http://localhost:1337')
537
+ break
538
+ except Exception:
539
+ _t.sleep(0.5)
540
+ if _br is None:
541
+ print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?")
542
+ else:
543
+ _n_expected = len(_urls)
544
+ _pages = []
545
+ _pg_dl = _t.time() + 15
546
+ _last_count = -1
547
+ _stable_since = None
548
+ while _t.time() < _pg_dl:
549
+ _pages = []
550
+ for _c in _br.contexts:
551
+ _pages.extend(_c.pages)
552
+ _cnt = len(_pages)
553
+ if _n_expected > 0 and _cnt >= _n_expected:
554
+ break
555
+ if _cnt > 0 and _cnt == _last_count:
556
+ if _stable_since is None:
557
+ _stable_since = _t.time()
558
+ elif _t.time() - _stable_since >= 1.5:
559
+ break
560
+ else:
561
+ _stable_since = None
562
+ _last_count = _cnt
563
+ _t.sleep(0.5)
564
+ _pages = []
565
+ for _c in _br.contexts:
566
+ _pages.extend(_c.pages)
567
+ if not _pages:
568
+ print(" wait_mocks_loaded: CDP connected but no open tabs found")
569
+ else:
570
+ print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render")
571
+ _MIN_ELEMS = 20
572
+ _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap
573
+ for _pg in _pages: # bring each to front once to defeat background-tab render throttling
574
+ try:
575
+ _pg.bring_to_front()
576
+ except Exception:
577
+ pass
578
+ _pending = list(_pages)
579
+ while _pending and _t.time() < _verify_dl:
580
+ _still = []
581
+ for _pg in _pending:
582
+ _ttl = ""
583
+ try:
584
+ _ttl = _pg.title()
585
+ except Exception:
586
+ pass
587
+ try:
588
+ _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0")
589
+ except Exception:
590
+ _n = 0
591
+ if _n >= _MIN_ELEMS:
592
+ print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)")
593
+ else:
594
+ _still.append(_pg)
595
+ _pending = _still
596
+ if _pending:
597
+ _t.sleep(2)
598
+ if not _pending:
599
+ _cdp_ok = True
600
+ else:
601
+ for _pg in _pending:
602
+ _ttl = ""
603
+ try:
604
+ _ttl = _pg.title()
605
+ except Exception:
606
+ pass
607
+ print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back")
608
+ except ImportError:
609
+ print(" wait_mocks_loaded: playwright not installed; skipping CDP phase")
610
+ except Exception as _e:
611
+ print(f" wait_mocks_loaded: CDP phase error ({_e!r})")
612
+
613
+ if not _cdp_ok:
614
+ print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep")
615
+ _t.sleep(render_buffer)
616
+ else:
617
+ print(" wait_mocks_loaded: browser render verified, skipping render_buffer")
618
+
619
+
620
+ def _open_mock_tabs(app_states, sid_value):
621
+ """Open the first mock as the primary Chrome window, the rest as new tabs.
622
+
623
+ Uses launch_gui once per URL so that the macOS localizer regex-extract
624
+ (which grabs the FIRST quoted URL per call) still works correctly.
625
+ """
626
+ _urls = [p for p, _ in app_states]
627
+ if not _urls:
628
+ return
629
+ launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0)
630
+ for _u in _urls[1:]:
631
+ launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0)
632
+
633
+
634
+
635
+ # PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate)
636
+ def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0):
637
+ """Block until every mock serves injected state AND (best-effort) renders."""
638
+ import time as _t
639
+ deadline = _t.time() + timeout
640
+ pending = dict(mocks)
641
+ while pending and _t.time() < deadline:
642
+ for name in list(pending):
643
+ try:
644
+ r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5)
645
+ if r.status_code == 200 and r.json().get('initial_state') is not None:
646
+ del pending[name]
647
+ except Exception:
648
+ pass
649
+ if pending:
650
+ _t.sleep(1.0)
651
+ if pending:
652
+ print(f'WARN: mocks not ready within {timeout}s: {list(pending)}')
653
+ try:
654
+ from playwright.sync_api import sync_playwright
655
+ except ImportError:
656
+ print('WARN: playwright not installed; skipping render check, settle 3s')
657
+ _t.sleep(3.0)
658
+ return
659
+ with sync_playwright() as p:
660
+ try:
661
+ browser = p.chromium.launch(channel='chrome', headless=True,
662
+ args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'])
663
+ except Exception as e:
664
+ print(f'WARN: could not launch chrome for render check: {e}; settle 3s')
665
+ _t.sleep(3.0)
666
+ return
667
+ try:
668
+ for name, url in mocks.items():
669
+ page = browser.new_page()
670
+ try:
671
+ page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000))
672
+ page.wait_for_function(
673
+ "document.body && document.body.innerText.length > 50",
674
+ timeout=int(render_timeout * 1000))
675
+ print(f'[{name}] rendered OK')
676
+ except Exception as e:
677
+ print(f'WARN: [{name}] render check issue: {e}')
678
+ finally:
679
+ page.close()
680
+ finally:
681
+ browser.close()
682
+
683
+
684
+ # ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render
685
+ _open_mock_tabs(APP_STATES, sid)
686
+ wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15)
687
+ wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12)
688
+ print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps')
am_renewal_hubspot_004__long/reward.py ADDED
@@ -0,0 +1,727 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: T04 — HubSpot renewal outreach across HubSpot + Gmail + Google Calendar
3
+ (hidden-access-point edition)
4
+ Task ID: am_renewal_hubspot_004__long
5
+ Mocks: hubspot_mock,gmail_mock,google_calendar_mock
6
+ Scoring (per qualifying deal unless noted; frac over the qualifying set).
7
+ Positive components sum to 1.0 and are each 0 in a do-nothing run; leakage is a
8
+ PENALTY (subtracted), so a do-nothing agent scores exactly 0.0:
9
+ 0.22 HubSpot: current description endswith _renewal_line AND still contains the
10
+ original text (hidden: slide-in panel)
11
+ 0.17 HubSpot: deal owner reassigned from 'Admin User' to 'Renewals Team'
12
+ (hidden: "Assigned To" field)
13
+ 0.22 Gmail: a sent email exists with subject == 'Renewal: <Company>' and body
14
+ contains company + $amount + closeDate
15
+ 0.17 Gmail: that renewal email carries the 'Renewals' label (hidden: selection-gated
16
+ Label button; matched by label NAME so an agent-created label also counts)
17
+ 0.11 Calendar: a 'Renewal call: <Company>' event exists on 2026-05-11
18
+ (hidden: must create event; TZ-robust date match)
19
+ 0.11 Calendar: that renewal-call event lists the contact's email as a guest
20
+ (hidden: guest field buried in the event editor; contact not in the picker)
21
+ -0.15 PENALTY (max): scaled by the fraction of non-qualifying deals that were
22
+ wrongly touched (description/owner edit, 'Renewal:' email, or 'Renewal call:' event).
23
+ Answer key: hubspot_mock initial_state deals[*] hidden `_*` fields (sole source of truth).
24
+ """
25
+ import copy
26
+ import re
27
+ import sys
28
+
29
+ import requests
30
+
31
+ from datetime import datetime, timezone, timedelta
32
+
33
+ TZ_PLUS_8 = timezone(timedelta(hours=8))
34
+
35
+
36
+ try:
37
+ with open('/tmp/task_web_sid', encoding='utf-8') as f:
38
+ sid = f.read().strip()
39
+ if not sid:
40
+ raise ValueError('sid is empty')
41
+ except Exception as e:
42
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
43
+ print('REWARD: 0.0')
44
+ sys.exit(0)
45
+
46
+
47
+ APP_URLS = {
48
+ 'hubspot': 'http://28.7.184.198:8150',
49
+ 'gmail': 'http://28.7.184.198:8138',
50
+ 'google_calendar': 'http://28.7.184.198:8141',
51
+ }
52
+ _GO_CACHE = {}
53
+
54
+
55
+ def clamp01(x):
56
+ return max(0.0, min(1.0, float(x)))
57
+
58
+
59
+ def frac(num, den):
60
+ return 0.0 if den == 0 else num / den
61
+
62
+
63
+ def f1(true_set, pred_set):
64
+ if not true_set and not pred_set:
65
+ return 1.0
66
+ tp = len(true_set & pred_set)
67
+ if tp == 0:
68
+ return 0.0
69
+ prec = tp / len(pred_set)
70
+ rec = tp / len(true_set)
71
+ return 2 * prec * rec / (prec + rec)
72
+
73
+
74
+ def by_id(items, key='id'):
75
+ return {it.get(key): it for it in (items or []) if isinstance(it, dict)}
76
+
77
+
78
+ def has_text(haystack, *needles):
79
+ s = (haystack or '').lower()
80
+ return any(n.lower() in s for n in needles)
81
+
82
+
83
+ def norm(s):
84
+ return (str(s) if s is not None else '').strip().lower()
85
+
86
+
87
+ def _msg_text(m):
88
+ if not isinstance(m, dict):
89
+ return ''
90
+ return m.get('content') or m.get('text') or ''
91
+
92
+
93
+ def _slack_channel_messages(slack_state, channel_name):
94
+ """Return messages for a channel, handling channels[*].messages AND the
95
+ top-level messages[channelId] map."""
96
+ if not isinstance(slack_state, dict):
97
+ return []
98
+ target = norm(channel_name).lstrip('#')
99
+ out = []
100
+ messages_map = slack_state.get('messages') if isinstance(slack_state.get('messages'), dict) else {}
101
+ for ch in slack_state.get('channels', []) or []:
102
+ if not isinstance(ch, dict):
103
+ continue
104
+ nm = norm(ch.get('name')).lstrip('#')
105
+ if nm != target:
106
+ continue
107
+ msgs = ch.get('messages')
108
+ if isinstance(msgs, list):
109
+ out.extend(m for m in msgs if isinstance(m, dict))
110
+ cid = ch.get('channelId') or ch.get('id')
111
+ if cid and isinstance(messages_map.get(cid), list):
112
+ out.extend(m for m in messages_map[cid] if isinstance(m, dict))
113
+ return out
114
+
115
+
116
+ def _sheet_rows(sheets_state, sheet_name=None):
117
+ """Rows from a materialized sheets dict {name: {headers, rows}}."""
118
+ if isinstance(sheets_state, dict):
119
+ if sheet_name and isinstance(sheets_state.get(sheet_name), dict):
120
+ return sheets_state[sheet_name].get('rows', []) or []
121
+ for v in sheets_state.values():
122
+ if isinstance(v, dict) and 'rows' in v:
123
+ return v.get('rows', []) or []
124
+ return []
125
+
126
+
127
+ def _email_text(email):
128
+ if not isinstance(email, dict):
129
+ return str(email)
130
+
131
+ to = email.get('to', '')
132
+ if isinstance(to, list):
133
+ to = ' '.join(
134
+ (x.get('name') or x.get('email') or str(x)) if isinstance(x, dict) else str(x)
135
+ for x in to
136
+ )
137
+ elif isinstance(to, dict):
138
+ to = to.get('name') or to.get('email') or str(to)
139
+
140
+ return f"{to} {email.get('subject', '')} {email.get('body', '')}"
141
+
142
+
143
+ def _gmail_sent_emails(gmail_state):
144
+ out = []
145
+ if not isinstance(gmail_state, dict):
146
+ return out
147
+
148
+ for e in gmail_state.get('emails', []):
149
+ if not isinstance(e, dict):
150
+ continue
151
+ folder = norm(e.get('folder'))
152
+ if folder in ('sent', 'sentitems', 'sent items'):
153
+ out.append(e)
154
+ continue
155
+ if e.get('isSent') is True or e.get('sentAt') or e.get('sentDateTime'):
156
+ out.append(e)
157
+
158
+ if out:
159
+ return out
160
+
161
+ for key in ('sent', 'sentEmails', 'outbox'):
162
+ items = gmail_state.get(key, [])
163
+ if isinstance(items, list):
164
+ out.extend(x for x in items if isinstance(x, dict))
165
+ return out
166
+
167
+
168
+ def _normalize_app_name(app):
169
+ app = (app or '').strip().lower()
170
+ return app[:-5] if app.endswith('_mock') else app
171
+
172
+
173
+ def _parse_cell_id(cell_id):
174
+ if not isinstance(cell_id, str) or not cell_id:
175
+ return None
176
+ idx = 0
177
+ while idx < len(cell_id) and cell_id[idx].isalpha():
178
+ idx += 1
179
+ if idx == 0 or idx >= len(cell_id):
180
+ return None
181
+ col = 0
182
+ for ch in cell_id[:idx].upper():
183
+ col = col * 26 + (ord(ch) - ord('A') + 1)
184
+ try:
185
+ row = int(cell_id[idx:])
186
+ except ValueError:
187
+ return None
188
+ return row, col - 1
189
+
190
+
191
+ def _extract_rows_from_workbook(state):
192
+ if not isinstance(state, dict):
193
+ return None
194
+ sheets = state.get('sheets')
195
+ if not isinstance(sheets, list):
196
+ return None
197
+
198
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
199
+ headers_by_sheet = adapter.get('headers_by_sheet') if isinstance(adapter.get('headers_by_sheet'), dict) else {}
200
+
201
+ out = {}
202
+ for sh in sheets:
203
+ if not isinstance(sh, dict):
204
+ continue
205
+ name = sh.get('name') or sh.get('id') or 'Sheet1'
206
+ data = sh.get('data') if isinstance(sh.get('data'), dict) else {}
207
+
208
+ headers = headers_by_sheet.get(name)
209
+ if not headers:
210
+ cols = []
211
+ for cid, cell in data.items():
212
+ rc = _parse_cell_id(cid)
213
+ if not rc:
214
+ continue
215
+ row_idx, col_idx = rc
216
+ if row_idx != 1:
217
+ continue
218
+ value = ''
219
+ if isinstance(cell, dict):
220
+ value = cell.get('value', '')
221
+ elif cell is not None:
222
+ value = str(cell)
223
+ if value is not None and str(value) != '':
224
+ cols.append((col_idx, str(value)))
225
+ headers = [v for _, v in sorted(cols)]
226
+
227
+ if not headers:
228
+ continue
229
+
230
+ by_row = {}
231
+ for cid, cell in data.items():
232
+ rc = _parse_cell_id(cid)
233
+ if not rc:
234
+ continue
235
+ row_idx, col_idx = rc
236
+ if row_idx <= 1 or col_idx >= len(headers):
237
+ continue
238
+ if isinstance(cell, dict):
239
+ value = cell.get('value', '')
240
+ else:
241
+ value = cell
242
+ by_row.setdefault(row_idx, {})[headers[col_idx]] = value
243
+
244
+ rows = []
245
+ for row_idx in sorted(by_row.keys()):
246
+ row = by_row[row_idx]
247
+ if not any(str(row.get(h, '')).strip() for h in headers):
248
+ continue
249
+ rows.append({h: row.get(h, '') for h in headers})
250
+
251
+ out[name] = {'headers': headers, 'rows': rows}
252
+
253
+ if not out:
254
+ return None
255
+ return {'sheets': out}
256
+
257
+
258
+ def _materialize_google_sheets(payload):
259
+ for key in ('initial_state', 'current_state'):
260
+ state = payload.get(key)
261
+ if not isinstance(state, dict):
262
+ continue
263
+ maybe_rows = _extract_rows_from_workbook(state)
264
+ if maybe_rows is not None:
265
+ state['_ui_workbook'] = {
266
+ 'sheets': copy.deepcopy(state.get('sheets', [])),
267
+ 'title': state.get('title'),
268
+ }
269
+ state['sheets'] = maybe_rows['sheets']
270
+
271
+
272
+ def _materialize_slack(payload):
273
+ for key in ('initial_state', 'current_state'):
274
+ state = payload.get(key)
275
+ if not isinstance(state, dict):
276
+ continue
277
+ channels = state.get('channels') if isinstance(state.get('channels'), list) else []
278
+ messages_map = state.get('messages') if isinstance(state.get('messages'), dict) else {}
279
+ for ch in channels:
280
+ if not isinstance(ch, dict):
281
+ continue
282
+ cid = ch.get('channelId') or ch.get('id')
283
+ if not cid:
284
+ continue
285
+ msg_list = messages_map.get(cid) if isinstance(messages_map.get(cid), list) else []
286
+ channel_msgs = ch.get('messages') if isinstance(ch.get('messages'), list) else []
287
+ merged = {
288
+ (m.get('messageId') or m.get('id')): dict(m)
289
+ for m in channel_msgs
290
+ if isinstance(m, dict)
291
+ }
292
+ for m in msg_list:
293
+ if not isinstance(m, dict):
294
+ continue
295
+ mid = m.get('messageId') or m.get('id')
296
+ text = m.get('text') if m.get('text') is not None else m.get('content', '')
297
+ merged[mid] = {
298
+ 'id': mid,
299
+ 'messageId': mid,
300
+ 'text': text,
301
+ 'content': m.get('content', text),
302
+ 'senderId': m.get('senderId'),
303
+ 'timestamp': m.get('timestamp'),
304
+ 'reactions': m.get('reactions') if isinstance(m.get('reactions'), list) else [],
305
+ }
306
+ ch['messages'] = list(merged.values())
307
+
308
+
309
+ def _owner_name_map(state):
310
+ out = {}
311
+ users = state.get('users') if isinstance(state.get('users'), list) else []
312
+ for u in users:
313
+ if not isinstance(u, dict):
314
+ continue
315
+ uid = u.get('userId')
316
+ if not uid:
317
+ continue
318
+ name = (f"{u.get('firstName', '')} {u.get('lastName', '')}".strip() or u.get('name') or uid)
319
+ out[uid] = name
320
+ return out
321
+
322
+
323
+ def _materialize_salesforce(payload):
324
+ for key in ('initial_state', 'current_state'):
325
+ state = payload.get(key)
326
+ if not isinstance(state, dict):
327
+ continue
328
+
329
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
330
+ owner_names = _owner_name_map(state)
331
+
332
+ task_leads = adapter.get('task_leads') if isinstance(adapter.get('task_leads'), dict) else None
333
+ if task_leads and isinstance(state.get('leads'), list):
334
+ restored = []
335
+ for lead in state['leads']:
336
+ if not isinstance(lead, dict):
337
+ continue
338
+ lid = str(lead.get('leadId') or lead.get('id') or '')
339
+ meta = task_leads.get(lid, {})
340
+ restored.append({
341
+ 'id': meta.get('id') or lead.get('leadId') or lead.get('id'),
342
+ 'company': lead.get('company', meta.get('company', '')),
343
+ 'status': lead.get('status', 'New'),
344
+ 'ownerName': owner_names.get(lead.get('ownerId')) or meta.get('ownerName'),
345
+ 'annualRevenue': meta.get('annualRevenue', lead.get('revenue')),
346
+ })
347
+ state['leads'] = restored
348
+
349
+ task_accounts = adapter.get('task_accounts') if isinstance(adapter.get('task_accounts'), dict) else None
350
+ if task_accounts and isinstance(state.get('accounts'), list):
351
+ current_by_id = {}
352
+ for acc in state['accounts']:
353
+ if isinstance(acc, dict):
354
+ current_by_id[str(acc.get('accountId') or acc.get('id') or '')] = acc
355
+
356
+ restored_accounts = []
357
+ for aid, meta in task_accounts.items():
358
+ cur = current_by_id.get(str(aid), {})
359
+ restored_accounts.append({
360
+ 'id': meta.get('id') or aid,
361
+ 'name': meta.get('name') or cur.get('name', ''),
362
+ 'contact': meta.get('contact'),
363
+ 'wonWithin7d': bool(meta.get('wonWithin7d', False)),
364
+ 'onboardingStage': cur.get('onboardingStage', meta.get('onboardingStage')),
365
+ })
366
+ state['accounts'] = restored_accounts
367
+
368
+
369
+ def _materialize_google_docs(payload):
370
+ for key in ('initial_state', 'current_state'):
371
+ state = payload.get(key)
372
+ if not isinstance(state, dict):
373
+ continue
374
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
375
+ task_docs = adapter.get('task_documents') if isinstance(adapter.get('task_documents'), dict) else None
376
+ if not task_docs:
377
+ continue
378
+ docs_map = state.get('documents') if isinstance(state.get('documents'), dict) else {}
379
+ restored = []
380
+ for did, meta in task_docs.items():
381
+ cur = docs_map.get(did, {}) if isinstance(docs_map, dict) else {}
382
+ restored.append({
383
+ 'id': meta.get('id') or did,
384
+ 'title': cur.get('title', meta.get('title')),
385
+ 'vendor': meta.get('vendor'),
386
+ 'folder': meta.get('folder'),
387
+ 'content': cur.get('content', meta.get('content', '')),
388
+ })
389
+ state['documents'] = restored
390
+
391
+
392
+ def _adapt_payload_for_reward(app, payload):
393
+ app_name = _normalize_app_name(app)
394
+ if app_name == 'google_sheets':
395
+ _materialize_google_sheets(payload)
396
+ elif app_name == 'slack':
397
+ _materialize_slack(payload)
398
+ elif app_name == 'salesforce':
399
+ _materialize_salesforce(payload)
400
+ elif app_name == 'google_docs':
401
+ _materialize_google_docs(payload)
402
+ return payload
403
+
404
+
405
+ def go(app_name):
406
+ if app_name in _GO_CACHE:
407
+ return _GO_CACHE[app_name]
408
+
409
+ base = APP_URLS.get(app_name)
410
+ if not base:
411
+ print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)')
412
+ print('REWARD: 0.0')
413
+ sys.exit(0)
414
+
415
+ try:
416
+ resp = requests.get(f'{base}/go?sid={sid}', timeout=15)
417
+ resp.raise_for_status()
418
+ payload = resp.json()
419
+ except Exception as e:
420
+ print(f'CRITICAL: cannot fetch {app_name} go state: {e}')
421
+ print('REWARD: 0.0')
422
+ sys.exit(0)
423
+
424
+ payload = _adapt_payload_for_reward(app_name, payload)
425
+ _GO_CACHE[app_name] = payload
426
+ return payload
427
+
428
+
429
+ # === Task-specific reward ===
430
+ #
431
+ # Ground truth lives in hubspot_mock initial_state deals[*] hidden `_*` fields:
432
+ # _qualifies (bool) -> THE qualifying set (d1-d4 True; d5-d9 False)
433
+ # _renewal_line (str) -> exact line to append (qualifying only)
434
+ # _expected_description (str) -> original + "\n" + _renewal_line (qualifying)
435
+ # _orig_owner (str) -> 'Admin User' (owner at injection, ALL deals)
436
+ # _new_owner (str) -> 'Renewals Team' (qualifying only)
437
+ # _email_subject (str) -> "Renewal: <Company>" (ALL deals; leak shape)
438
+ # _email_body_must_contain -> [company, $amount, closeDate] (qualifying only)
439
+ # _renewals_label_name (str) -> 'Renewals' (qualifying only)
440
+ # _event_title (str) -> "Renewal call: <Company>" (ALL deals; leak shape)
441
+ # _event_date (str) -> '2026-05-11' (qualifying only)
442
+ # _event_guest_email (str) -> contact email to add as guest (qualifying only)
443
+ # Original description = initial_state deals[i].description (pre-edit visible field).
444
+
445
+ # Positive components (each requires an agent action -> all 0 in do-nothing).
446
+ # Weights sum to exactly 1.0. Leakage onto non-qualifying deals is a PENALTY
447
+ # (subtracted, 0 in do-nothing) rather than positive credit, so a do-nothing
448
+ # agent scores exactly 0.
449
+ WEIGHT_DESC = 0.22
450
+ WEIGHT_OWNER = 0.17
451
+ WEIGHT_EMAIL = 0.22
452
+ WEIGHT_LABEL = 0.17
453
+ WEIGHT_EVENT = 0.11
454
+ WEIGHT_GUEST = 0.11
455
+ WEIGHT_LEAK_PENALTY = 0.15 # max penalty if EVERY non-qualifying deal is touched
456
+
457
+
458
+ def _email_full_text(e):
459
+ """subject + HTML-stripped body + snippet, for substring search."""
460
+ if not isinstance(e, dict):
461
+ return ''
462
+ subj = e.get('subject') or ''
463
+ body = e.get('body') or ''
464
+ body_text = re.sub(r'<[^>]+>', ' ', body)
465
+ snippet = e.get('snippet') or ''
466
+ return f'{subj}\n{body_text}\n{snippet}'
467
+
468
+
469
+ def _desc_match(cur_desc, orig_desc, renewal_line, expected_desc):
470
+ """current description endswith renewal_line AND still contains original text."""
471
+ cur = cur_desc or ''
472
+ rl = (renewal_line or '').strip()
473
+ if not rl:
474
+ return False
475
+ cur_stripped = cur.rstrip()
476
+ ends = cur_stripped.endswith(rl) or norm(cur_stripped).endswith(norm(rl))
477
+ orig = (orig_desc or '').strip()
478
+ contains_orig = (norm(orig) in norm(cur)) if orig else True
479
+ if ends and contains_orig:
480
+ return True
481
+ # fallback: exact match to the embedded expected description
482
+ if expected_desc and norm(cur) == norm(expected_desc):
483
+ return True
484
+ return False
485
+
486
+
487
+ def _renewal_emails_by_subject(sent_emails, subject):
488
+ """All sent emails whose subject == subject (case-insensitive)."""
489
+ want_subj = norm(subject)
490
+ if not want_subj:
491
+ return []
492
+ return [e for e in (sent_emails or [])
493
+ if isinstance(e, dict) and norm(e.get('subject')) == want_subj]
494
+
495
+
496
+ def _email_body_ok(e, needles):
497
+ text = norm(_email_full_text(e))
498
+ return all(norm(nd) in text for nd in (needles or []) if nd)
499
+
500
+
501
+ def _label_name_set(email, label_id_to_name):
502
+ """Resolve an email's label ids/names to a set of normalized label NAMES."""
503
+ out = set()
504
+ labels = email.get('labels')
505
+ if not isinstance(labels, list):
506
+ return out
507
+ for lab in labels:
508
+ if isinstance(lab, dict):
509
+ nm = lab.get('name') or lab.get('id')
510
+ if nm:
511
+ out.add(norm(label_id_to_name.get(nm, nm)))
512
+ else:
513
+ out.add(norm(label_id_to_name.get(lab, lab)))
514
+ return out
515
+
516
+
517
+ # ---- Calendar helpers (TZ-robust date matching, guest subset) ----
518
+ def _parse_as_utc(s, default_tz=TZ_PLUS_8):
519
+ if not s:
520
+ return None
521
+ s = str(s).strip()
522
+ if s.endswith('Z'):
523
+ s = s[:-1] + '+00:00'
524
+ try:
525
+ dt = datetime.fromisoformat(s)
526
+ except Exception:
527
+ return None
528
+ if dt.tzinfo is None:
529
+ dt = dt.replace(tzinfo=default_tz)
530
+ return dt
531
+
532
+
533
+ def _raw_date_part(s):
534
+ """Literal wall-clock date 'YYYY-MM-DD' (strip Z / tz offset, take date)."""
535
+ if not s:
536
+ return ''
537
+ t = str(s).strip()
538
+ if 'T' not in t:
539
+ return t[:10]
540
+ return t.split('T', 1)[0]
541
+
542
+
543
+ def _event_on_date(ev, target_date):
544
+ """True if the event's start matches target_date under EITHER the literal
545
+ wall-clock reading OR the UTC->UTC+8 conversion (robust to datetime-local
546
+ -> toISOString() tz shifts the calendar mock performs)."""
547
+ start = ev.get('start')
548
+ target = norm(target_date)
549
+ if not target:
550
+ return True
551
+ if norm(_raw_date_part(start)) == target:
552
+ return True
553
+ dt = _parse_as_utc(start)
554
+ if dt is not None:
555
+ if dt.astimezone(TZ_PLUS_8).date().isoformat() == target:
556
+ return True
557
+ if dt.astimezone(timezone.utc).date().isoformat() == target:
558
+ return True
559
+ return False
560
+
561
+
562
+ def _event_guests(ev):
563
+ g = ev.get('guests')
564
+ if not isinstance(g, list):
565
+ g = ev.get('attendees') if isinstance(ev.get('attendees'), list) else []
566
+ out = set()
567
+ for a in g:
568
+ if isinstance(a, dict):
569
+ a = a.get('email') or a.get('name')
570
+ if a:
571
+ out.add(norm(a))
572
+ return out
573
+
574
+
575
+ def reward(go):
576
+ hub = go('hubspot')
577
+ hub_i = hub.get('initial_state', {}) or {}
578
+ hub_c = hub.get('current_state', {}) or {}
579
+ gmail_c = go('gmail').get('current_state', {}) or {}
580
+ cal_c = go('google_calendar').get('current_state', {}) or {}
581
+
582
+ deals_i = [d for d in (hub_i.get('deals', []) or []) if isinstance(d, dict)]
583
+ deals_c_by_id = by_id([d for d in (hub_c.get('deals', []) or []) if isinstance(d, dict)])
584
+ sent_emails = _gmail_sent_emails(gmail_c)
585
+ cur_events = [e for e in (cal_c.get('events', []) or []) if isinstance(e, dict)]
586
+
587
+ # label id -> name map (current gmail labels), for robust label-name matching
588
+ label_id_to_name = {}
589
+ for lab in (gmail_c.get('labels', []) or []):
590
+ if isinstance(lab, dict) and lab.get('id'):
591
+ label_id_to_name[lab['id']] = lab.get('name') or lab['id']
592
+
593
+ qualifying = [d for d in deals_i if d.get('_qualifies') is True]
594
+ nonqual = [d for d in deals_i if d.get('_qualifies') is not True]
595
+ n_q = len(qualifying)
596
+ n_nq = len(nonqual)
597
+
598
+ # --- Component 1: HubSpot description appended (0.20) ---
599
+ desc_ok = 0
600
+ desc_flags = []
601
+ for d in qualifying:
602
+ did = d.get('id')
603
+ cur = deals_c_by_id.get(did, {}) or {}
604
+ ok = _desc_match(
605
+ cur.get('description') or '',
606
+ d.get('description') or '',
607
+ d.get('_renewal_line') or '',
608
+ d.get('_expected_description') or '',
609
+ )
610
+ desc_ok += 1 if ok else 0
611
+ desc_flags.append(f"{did}={'Y' if ok else 'N'}")
612
+ s_desc = WEIGHT_DESC * frac(desc_ok, n_q)
613
+
614
+ # --- Component 2: HubSpot owner reassigned (0.15) ---
615
+ owner_ok = 0
616
+ owner_flags = []
617
+ for d in qualifying:
618
+ did = d.get('id')
619
+ cur = deals_c_by_id.get(did, {}) or {}
620
+ want = norm(d.get('_new_owner') or '')
621
+ ok = bool(want) and norm(cur.get('owner')) == want
622
+ owner_ok += 1 if ok else 0
623
+ owner_flags.append(f"{did}={'Y' if ok else 'N'}")
624
+ s_owner = WEIGHT_OWNER * frac(owner_ok, n_q)
625
+
626
+ # --- Component 3: Gmail renewal email sent (0.20) ---
627
+ email_ok = 0
628
+ email_flags = []
629
+ for d in qualifying:
630
+ did = d.get('id')
631
+ matches = _renewal_emails_by_subject(sent_emails, d.get('_email_subject') or '')
632
+ ok = any(_email_body_ok(e, d.get('_email_body_must_contain') or []) for e in matches)
633
+ email_ok += 1 if ok else 0
634
+ email_flags.append(f"{did}={'Y' if ok else 'N'}")
635
+ s_email = WEIGHT_EMAIL * frac(email_ok, n_q)
636
+
637
+ # --- Component 4: Gmail 'Renewals' label applied to the renewal email (0.15) ---
638
+ label_ok = 0
639
+ label_flags = []
640
+ for d in qualifying:
641
+ did = d.get('id')
642
+ want_label = norm(d.get('_renewals_label_name') or '')
643
+ matches = _renewal_emails_by_subject(sent_emails, d.get('_email_subject') or '')
644
+ ok = bool(want_label) and any(
645
+ want_label in _label_name_set(e, label_id_to_name) for e in matches
646
+ )
647
+ label_ok += 1 if ok else 0
648
+ label_flags.append(f"{did}={'Y' if ok else 'N'}")
649
+ s_label = WEIGHT_LABEL * frac(label_ok, n_q)
650
+
651
+ # --- Component 5: Calendar 'Renewal call: <Company>' event on the right date (0.10) ---
652
+ event_ok = 0
653
+ event_flags = []
654
+ for d in qualifying:
655
+ did = d.get('id')
656
+ title = norm(d.get('_event_title') or '')
657
+ date_str = d.get('_event_date') or ''
658
+ ok = bool(title) and any(
659
+ norm(ev.get('title')) == title and _event_on_date(ev, date_str)
660
+ for ev in cur_events
661
+ )
662
+ event_ok += 1 if ok else 0
663
+ event_flags.append(f"{did}={'Y' if ok else 'N'}")
664
+ s_event = WEIGHT_EVENT * frac(event_ok, n_q)
665
+
666
+ # --- Component 6: Calendar contact added as guest on the renewal-call event (0.10) ---
667
+ guest_ok = 0
668
+ guest_flags = []
669
+ for d in qualifying:
670
+ did = d.get('id')
671
+ title = norm(d.get('_event_title') or '')
672
+ want_guest = norm(d.get('_event_guest_email') or '')
673
+ ok = bool(title) and bool(want_guest) and any(
674
+ norm(ev.get('title')) == title and want_guest in _event_guests(ev)
675
+ for ev in cur_events
676
+ )
677
+ guest_ok += 1 if ok else 0
678
+ guest_flags.append(f"{did}={'Y' if ok else 'N'}")
679
+ s_guest = WEIGHT_GUEST * frac(guest_ok, n_q)
680
+
681
+ # --- Penalty: leakage onto non-qualifying deals (0 in do-nothing) ---
682
+ # A non-qualifying deal is "leaked" if the agent edited its description, changed
683
+ # its owner, sent it a 'Renewal:' email, or created its 'Renewal call:' event.
684
+ leaked = 0
685
+ leak_flags = []
686
+ for d in nonqual:
687
+ did = d.get('id')
688
+ cur = deals_c_by_id.get(did, {}) or {}
689
+ desc_leak = norm(cur.get('description') or '') != norm(d.get('description') or '')
690
+ owner_leak = norm(cur.get('owner')) != norm(d.get('_orig_owner') or '')
691
+ email_leak = len(_renewal_emails_by_subject(sent_emails, d.get('_email_subject') or '')) > 0
692
+ evt_title = norm(d.get('_event_title') or '')
693
+ event_leak = bool(evt_title) and any(norm(ev.get('title')) == evt_title for ev in cur_events)
694
+ if desc_leak or owner_leak or email_leak or event_leak:
695
+ leaked += 1
696
+ leak_flags.append(f"{did}=d{int(desc_leak)}o{int(owner_leak)}e{int(email_leak)}c{int(event_leak)}")
697
+ leak_penalty = WEIGHT_LEAK_PENALTY * (0.0 if n_nq == 0 else frac(leaked, n_nq))
698
+
699
+ positive = s_desc + s_owner + s_email + s_label + s_event + s_guest
700
+ score = clamp01(positive - leak_penalty)
701
+
702
+ print(
703
+ 'DEBUG_T04_hubspot_renewal_outreach_3app '
704
+ f'n_qual={n_q} n_nonqual={n_nq} sent_emails={len(sent_emails)} cal_events={len(cur_events)} '
705
+ f'desc={desc_ok}/{n_q}[{",".join(desc_flags)}] '
706
+ f'owner={owner_ok}/{n_q}[{",".join(owner_flags)}] '
707
+ f'email={email_ok}/{n_q}[{",".join(email_flags)}] '
708
+ f'label={label_ok}/{n_q}[{",".join(label_flags)}] '
709
+ f'event={event_ok}/{n_q}[{",".join(event_flags)}] '
710
+ f'guest={guest_ok}/{n_q}[{",".join(guest_flags)}] '
711
+ f'leaked={leaked}/{n_nq}[{",".join(leak_flags)}] '
712
+ f'w_desc={round(s_desc, 4)} w_owner={round(s_owner, 4)} w_email={round(s_email, 4)} '
713
+ f'w_label={round(s_label, 4)} w_event={round(s_event, 4)} w_guest={round(s_guest, 4)} '
714
+ f'leak_penalty={round(leak_penalty, 4)} total={round(score, 4)}'
715
+ )
716
+
717
+ return clamp01(score)
718
+
719
+
720
+ try:
721
+ score = float(reward(go))
722
+ except Exception as exc:
723
+ print(f'ERROR: reward() raised {exc!r}')
724
+ score = 0.0
725
+
726
+ score = clamp01(score)
727
+ print(f'\nREWARD: {round(score, 4)}')
am_renewal_outreach_002/_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"
am_renewal_outreach_002/initial_setup.py ADDED
@@ -0,0 +1,583 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: Renewal check-in for Northwind Traders (Salesforce task + Gmail outreach + Slack closure)
194
+ Task ID: am_renewal_outreach_002
195
+ Domain: mock_websites
196
+ Mocks: salesforce_mock, gmail_mock, slack_mock
197
+ """
198
+ import os
199
+ import shlex
200
+ import subprocess
201
+ import time
202
+ import uuid
203
+
204
+ import requests
205
+
206
+ # --- Network egress: this VM has no direct internet; web egress to the mocks
207
+ # is routed through the cluster proxy. Probe once (fast) to decide whether a
208
+ # proxy is needed, then reuse the decision. Override the proxy with WEB_PROXY. ---
209
+ PROXY = os.environ.get('WEB_PROXY') or None
210
+ PROXIES = None
211
+
212
+ _PROBE_URL = 'http://28.7.184.198:8138/go?sid=__probe__'
213
+
214
+
215
+ def _decide_proxy():
216
+ try:
217
+ requests.get(_PROBE_URL, timeout=4)
218
+ return None # direct works
219
+ except requests.exceptions.RequestException:
220
+ return PROXIES # fall back to proxy
221
+
222
+
223
+ _ACTIVE_PROXIES = _decide_proxy()
224
+ print(f'Network mode: {"proxy " + PROXY if _ACTIVE_PROXIES else "direct"}')
225
+
226
+
227
+ def http_post(url, payload):
228
+ return requests.post(url, json=payload, timeout=30, proxies=_ACTIVE_PROXIES)
229
+
230
+
231
+ def http_get(url):
232
+ return requests.get(url, timeout=30, proxies=_ACTIVE_PROXIES)
233
+
234
+
235
+ # --- Config ---
236
+ SALESFORCE_URL = 'http://28.7.184.198:8175'
237
+ GMAIL_URL = 'http://28.7.184.198:8138'
238
+ SLACK_URL = 'http://28.7.184.198:8178'
239
+
240
+ sid = str(uuid.uuid4())
241
+ with open('/tmp/task_web_sid', 'w') as f:
242
+ f.write(sid)
243
+ print(f'Generated sid={sid}')
244
+
245
+ # Use a fresh Chrome profile per task session. This avoids stale Salesforce
246
+ # modal/localStorage state (for example a lingering "New Task" dialog) from a
247
+ # previous run blocking the task flow or making state detection flaky.
248
+ CHROME_PROFILE_DIR = f'/tmp/cua_chrome_profile_{sid}'
249
+ os.makedirs(CHROME_PROFILE_DIR, exist_ok=True)
250
+
251
+
252
+ # ---------------------------------------------------------------------------
253
+ # SALESFORCE STATE
254
+ # ---------------------------------------------------------------------------
255
+ def build_salesforce_state():
256
+ jordan = {
257
+ "userId": "user-1",
258
+ "firstName": "Jordan",
259
+ "lastName": "Avery",
260
+ "email": "jordan.avery@vertexcloud.example.com",
261
+ "phone": "(555) 204-1180",
262
+ "title": "Account Manager",
263
+ "department": "Sales",
264
+ "role": "Account Manager",
265
+ "avatar": "https://i.pravatar.cc/150?u=user-1",
266
+ "timezone": "America/New_York",
267
+ "locale": "en-US",
268
+ "theme": "lightning",
269
+ }
270
+ users = [
271
+ jordan,
272
+ {
273
+ "userId": "user-2", "firstName": "Priya", "lastName": "Nair",
274
+ "email": "priya.nair@vertexcloud.example.com", "phone": "(555) 204-1181",
275
+ "title": "Sales Director", "department": "Sales", "role": "Director",
276
+ "avatar": "https://i.pravatar.cc/150?u=user-2",
277
+ "timezone": "America/New_York", "locale": "en-US", "theme": "lightning",
278
+ },
279
+ {
280
+ "userId": "user-3", "firstName": "Diego", "lastName": "Morales",
281
+ "email": "diego.morales@vertexcloud.example.com", "phone": "(555) 204-1182",
282
+ "title": "Customer Success Manager", "department": "Customer Success", "role": "CSM",
283
+ "avatar": "https://i.pravatar.cc/150?u=user-3",
284
+ "timezone": "America/Chicago", "locale": "en-US", "theme": "lightning",
285
+ },
286
+ ]
287
+
288
+ accounts = [
289
+ {
290
+ "accountId": "account-1", "name": "Northwind Traders", "type": "Customer",
291
+ "industry": "Logistics", "revenue": 48000000, "employees": 320, "ownerId": "user-1",
292
+ "phone": "(206) 555-0142", "website": "https://www.northwind-traders.example.com",
293
+ "billingStreet": "401 Harbor Way", "billingCity": "Seattle", "billingState": "WA",
294
+ "billingZip": "98101", "billingCountry": "USA",
295
+ "shippingStreet": "401 Harbor Way", "shippingCity": "Seattle", "shippingState": "WA",
296
+ "shippingZip": "98101", "shippingCountry": "USA",
297
+ "createdDate": "2024-02-10T00:00:00.000Z", "modifiedDate": "2026-05-20T00:00:00.000Z",
298
+ },
299
+ {
300
+ "accountId": "account-2", "name": "Globex Corporation", "type": "Customer",
301
+ "industry": "Manufacturing", "revenue": 92000000, "employees": 540, "ownerId": "user-1",
302
+ "phone": "(312) 555-0177", "website": "https://www.globex.example.com",
303
+ "billingStreet": "88 Industrial Blvd", "billingCity": "Chicago", "billingState": "IL",
304
+ "billingZip": "60601", "billingCountry": "USA",
305
+ "shippingStreet": "88 Industrial Blvd", "shippingCity": "Chicago", "shippingState": "IL",
306
+ "shippingZip": "60601", "shippingCountry": "USA",
307
+ "createdDate": "2023-11-04T00:00:00.000Z", "modifiedDate": "2026-04-18T00:00:00.000Z",
308
+ },
309
+ {
310
+ "accountId": "account-3", "name": "Initech", "type": "Customer",
311
+ "industry": "Technology", "revenue": 27000000, "employees": 180, "ownerId": "user-1",
312
+ "phone": "(512) 555-0190", "website": "https://www.initech.example.com",
313
+ "billingStreet": "1200 Congress Ave", "billingCity": "Austin", "billingState": "TX",
314
+ "billingZip": "78701", "billingCountry": "USA",
315
+ "shippingStreet": "1200 Congress Ave", "shippingCity": "Austin", "shippingState": "TX",
316
+ "shippingZip": "78701", "shippingCountry": "USA",
317
+ "createdDate": "2024-06-22T00:00:00.000Z", "modifiedDate": "2026-03-30T00:00:00.000Z",
318
+ },
319
+ ]
320
+
321
+ contacts = [
322
+ {
323
+ "contactId": "contact-1", "accountId": "account-1", "firstName": "Karen",
324
+ "lastName": "Walsh", "title": "VP Operations", "department": "Operations",
325
+ "email": "karen.walsh@northwind-traders.example.com", "phone": "(206) 555-0148",
326
+ "ownerId": "user-1",
327
+ },
328
+ {
329
+ "contactId": "contact-2", "accountId": "account-2", "firstName": "Hank",
330
+ "lastName": "Scorpio", "title": "COO", "department": "Executive",
331
+ "email": "hank.scorpio@globex.example.com", "phone": "(312) 555-0178",
332
+ "ownerId": "user-1",
333
+ },
334
+ {
335
+ "contactId": "contact-3", "accountId": "account-3", "firstName": "Bill",
336
+ "lastName": "Lumbergh", "title": "Director of IT", "department": "IT",
337
+ "email": "bill.lumbergh@initech.example.com", "phone": "(512) 555-0191",
338
+ "ownerId": "user-1",
339
+ },
340
+ ]
341
+
342
+ opportunities = [
343
+ {
344
+ "opportunityId": "opp-1", "name": "Northwind Traders – Annual Renewal",
345
+ "accountId": "account-1", "contactId": "contact-1", "amount": 120000,
346
+ "closeDate": "2026-07-15", "stage": "Negotiation", "probability": 75,
347
+ "ownerId": "user-1", "type": "Renewal",
348
+ "createdDate": "2026-04-01T00:00:00.000Z", "modifiedDate": "2026-05-28T00:00:00.000Z",
349
+ },
350
+ {
351
+ "opportunityId": "opp-2", "name": "Globex Corp – Platform Renewal",
352
+ "accountId": "account-2", "contactId": "contact-2", "amount": 210000,
353
+ "closeDate": "2026-09-30", "stage": "Qualification", "probability": 40,
354
+ "ownerId": "user-1", "type": "Renewal",
355
+ "createdDate": "2026-05-02T00:00:00.000Z", "modifiedDate": "2026-05-30T00:00:00.000Z",
356
+ },
357
+ {
358
+ "opportunityId": "opp-3", "name": "Initech – Renewal & Upsell",
359
+ "accountId": "account-3", "contactId": "contact-3", "amount": 85000,
360
+ "closeDate": "2026-08-20", "stage": "Value Proposition", "probability": 55,
361
+ "ownerId": "user-1", "type": "Renewal",
362
+ "createdDate": "2026-05-10T00:00:00.000Z", "modifiedDate": "2026-06-01T00:00:00.000Z",
363
+ },
364
+ ]
365
+
366
+ # Distractor activities — old COMPLETED tasks unrelated to the renewal.
367
+ activities = [
368
+ {
369
+ "activityId": "activity-1", "type": "task", "subject": "Send onboarding deck to Globex",
370
+ "status": "Completed", "priority": "Normal", "dueDate": "2026-04-12",
371
+ "relatedToType": "opportunity", "relatedToId": "opp-2", "assignedToId": "user-1",
372
+ },
373
+ {
374
+ "activityId": "activity-2", "type": "task", "subject": "Update Initech billing contact",
375
+ "status": "Completed", "priority": "Low", "dueDate": "2026-05-05",
376
+ "relatedToType": "account", "relatedToId": "account-3", "assignedToId": "user-1",
377
+ },
378
+ {
379
+ "activityId": "activity-3", "type": "event", "subject": "Quarterly business review (internal)",
380
+ "status": "Completed", "priority": "Normal",
381
+ "startDateTime": "2026-05-18T15:00:00.000Z", "endDateTime": "2026-05-18T16:00:00.000Z",
382
+ "relatedToType": "account", "relatedToId": "account-1", "assignedToId": "user-1",
383
+ },
384
+ ]
385
+
386
+ return {
387
+ "user": jordan,
388
+ "users": users,
389
+ "leads": [],
390
+ "accounts": accounts,
391
+ "contacts": contacts,
392
+ "opportunities": opportunities,
393
+ "cases": [],
394
+ "activities": activities,
395
+ "chatterPosts": [],
396
+ "files": [],
397
+ "following": ["user-2", "user-3"],
398
+ "recentlyViewed": [],
399
+ "dismissedNotifications": [],
400
+ }
401
+
402
+
403
+ # ---------------------------------------------------------------------------
404
+ # GMAIL STATE
405
+ # ---------------------------------------------------------------------------
406
+ def build_gmail_state():
407
+ jordan_user = {
408
+ "userId": "u1",
409
+ "username": "Jordan Avery",
410
+ "email": "jordan.avery@vertexcloud.example.com",
411
+ "avatar": "https://i.pravatar.cc/150?u=jordan-avery",
412
+ }
413
+ # Distractor prior thread from Karen Walsh about general account questions.
414
+ emails = [
415
+ {
416
+ "id": "email_1", "threadId": "thread_1",
417
+ "from": {"name": "Karen Walsh", "email": "karen.walsh@northwind-traders.example.com"},
418
+ "to": [{"name": "Jordan Avery", "email": "jordan.avery@vertexcloud.example.com"}],
419
+ "cc": [], "bcc": [],
420
+ "subject": "Question about our account users",
421
+ "body": "<p>Hi Jordan,</p><p>Quick question — a couple of our new ops analysts need "
422
+ "access to the reporting dashboards. Can you point me to where I add seats?</p>"
423
+ "<p>Thanks,<br/>Karen</p>",
424
+ "timestamp": "2026-06-10T14:05:00Z",
425
+ "read": True, "starred": False, "important": False,
426
+ "labels": ["l1"], "category": "primary", "folder": "inbox", "attachments": [],
427
+ },
428
+ {
429
+ "id": "email_2", "threadId": "thread_1",
430
+ "from": {"name": "Jordan Avery", "email": "jordan.avery@vertexcloud.example.com"},
431
+ "to": [{"name": "Karen Walsh", "email": "karen.walsh@northwind-traders.example.com"}],
432
+ "cc": [], "bcc": [],
433
+ "subject": "Re: Question about our account users",
434
+ "body": "<p>Hi Karen,</p><p>Happy to help — you can add seats under Settings → "
435
+ "Users → Invite. Let me know if you hit any snags.</p><p>Best,<br/>Jordan</p>",
436
+ "timestamp": "2026-06-10T16:20:00Z",
437
+ "read": True, "starred": False, "important": False,
438
+ "labels": ["l1"], "category": "primary", "folder": "sent", "attachments": [],
439
+ },
440
+ {
441
+ "id": "email_3", "threadId": "thread_2",
442
+ "from": {"name": "Vertex Cloud Billing", "email": "billing@vertexcloud.example.com"},
443
+ "to": [{"name": "Jordan Avery", "email": "jordan.avery@vertexcloud.example.com"}],
444
+ "cc": [], "bcc": [],
445
+ "subject": "June invoice summary",
446
+ "body": "<p>Your June account summary is now available in the billing portal.</p>",
447
+ "timestamp": "2026-06-15T09:00:00Z",
448
+ "read": False, "starred": False, "important": False,
449
+ "labels": ["l4"], "category": "primary", "folder": "inbox", "attachments": [],
450
+ },
451
+ ]
452
+ labels = [
453
+ {"id": "l1", "name": "Work", "color": "#ef4444"},
454
+ {"id": "l2", "name": "Personal", "color": "#3b82f6"},
455
+ {"id": "l3", "name": "Travel", "color": "#22c55e"},
456
+ {"id": "l4", "name": "Finance", "color": "#eab308"},
457
+ ]
458
+ return {"user": jordan_user, "emails": emails, "labels": labels, "drafts": []}
459
+
460
+
461
+ # ---------------------------------------------------------------------------
462
+ # SLACK STATE
463
+ # ---------------------------------------------------------------------------
464
+ def build_slack_state():
465
+ jordan = {
466
+ "userId": "user_1", "fullName": "Jordan Avery", "displayName": "Jordan",
467
+ "email": "jordan.avery@vertexcloud.example.com",
468
+ "avatar": "https://picsum.photos/200/200?random=1", "status": "online",
469
+ "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York",
470
+ }
471
+ users = [
472
+ jordan,
473
+ {"userId": "user_2", "fullName": "Priya Nair", "displayName": "Priya",
474
+ "email": "priya.nair@vertexcloud.example.com",
475
+ "avatar": "https://picsum.photos/200/200?random=2", "status": "online",
476
+ "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"},
477
+ {"userId": "user_3", "fullName": "Diego Morales", "displayName": "Diego",
478
+ "email": "diego.morales@vertexcloud.example.com",
479
+ "avatar": "https://picsum.photos/200/200?random=3", "status": "online",
480
+ "statusMessage": "", "statusEmoji": "", "timeZone": "America/Chicago"},
481
+ {"userId": "user_4", "fullName": "Mei Lin", "displayName": "Mei",
482
+ "email": "mei.lin@vertexcloud.example.com",
483
+ "avatar": "https://picsum.photos/200/200?random=4", "status": "away",
484
+ "statusMessage": "", "statusEmoji": "", "timeZone": "America/Los_Angeles"},
485
+ ]
486
+ channels = [
487
+ {"channelId": "general", "name": "general", "description": "Company-wide announcements",
488
+ "topic": "", "isPrivate": False, "isStarred": False,
489
+ "members": ["user_1", "user_2", "user_3", "user_4"], "createdBy": "user_2",
490
+ "createdAt": "2025-01-05T10:00:00Z", "pinnedMessages": [], "unreadCount": 0},
491
+ {"channelId": "random", "name": "random", "description": "Non-work banter",
492
+ "topic": "", "isPrivate": False, "isStarred": False,
493
+ "members": ["user_1", "user_2", "user_3", "user_4"], "createdBy": "user_2",
494
+ "createdAt": "2025-01-05T10:00:00Z", "pinnedMessages": [], "unreadCount": 0},
495
+ {"channelId": "customer-success", "name": "customer-success",
496
+ "description": "Customer Success team — renewals, onboarding, escalations",
497
+ "topic": "Keeping customers happy and renewing", "isPrivate": False, "isStarred": True,
498
+ "members": ["user_1", "user_2", "user_3"], "createdBy": "user_3",
499
+ "createdAt": "2025-02-01T09:00:00Z", "pinnedMessages": [], "unreadCount": 0},
500
+ ]
501
+ messages = {
502
+ "general": [
503
+ {"messageId": "msg_1", "senderId": "user_2", "content": "Morning team! Don't forget the all-hands at 11.",
504
+ "timestamp": "2026-06-22T13:30:00Z", "threadId": None, "reactions": [],
505
+ "attachments": [], "isEdited": False},
506
+ ],
507
+ "random": [
508
+ {"messageId": "msg_2", "senderId": "user_4", "content": "Anyone tried the new coffee place on 3rd?",
509
+ "timestamp": "2026-06-21T18:10:00Z", "threadId": None, "reactions": [],
510
+ "attachments": [], "isEdited": False},
511
+ ],
512
+ "customer-success": [
513
+ {"messageId": "msg_3", "senderId": "user_3",
514
+ "content": "Reminder: please keep renewal notes updated in Salesforce as you work accounts.",
515
+ "timestamp": "2026-06-19T15:45:00Z", "threadId": None, "reactions": [],
516
+ "attachments": [], "isEdited": False},
517
+ ],
518
+ }
519
+ return {
520
+ "currentUser": jordan,
521
+ "workspace": {"workspaceId": "ws_1", "workspaceName": "Vertex Cloud", "icon": ""},
522
+ "users": users,
523
+ "channels": channels,
524
+ "messages": messages,
525
+ "threads": {},
526
+ "dms": [],
527
+ "bookmarkedMessages": [],
528
+ "callHistory": [],
529
+ "settings": {"theme": "light", "notifications": "all", "displayDensity": "comfortable",
530
+ "showAvatars": True, "use24Hour": False},
531
+ "invitations": [],
532
+ "notifications": [],
533
+ }
534
+
535
+
536
+ def inject(url, state, label):
537
+ resp = http_post(f'{url}/post?sid={sid}', {'action': 'set', 'state': state})
538
+ assert resp.status_code == 200, f'{label} injection failed: {resp.status_code} {resp.text}'
539
+ go = http_get(f'{url}/go?sid={sid}').json()
540
+ assert go.get('initial_state') is not None, f'{label} initial_state is None after injection'
541
+ print(f'{label} state injected and verified.')
542
+
543
+
544
+ inject(SALESFORCE_URL, build_salesforce_state(), 'Salesforce')
545
+ inject(GMAIL_URL, build_gmail_state(), 'Gmail')
546
+ inject(SLACK_URL, build_slack_state(), 'Slack')
547
+
548
+
549
+ # --- Launch browser (primary mock = Salesforce) ---
550
+ def launch_gui(command, delay_sec=1.0):
551
+ env = os.environ.copy()
552
+ env['DISPLAY'] = ':0'
553
+ # Accept both a command string and a pre-split arg list (some tasks
554
+ # build arg lists themselves, e.g. se_hard_008).
555
+ if isinstance(command, str):
556
+ _parts = shlex.split(command)
557
+ else:
558
+ _parts = list(command)
559
+ # Inject CDP debug port so wait_mocks_loaded can verify browser render
560
+ # via Playwright connect_over_cdp. Idempotent: skip if any arg already
561
+ # starts with --remote-debugging-port (some tasks inject their own
562
+ # dynamic port, e.g. se_hard_008).
563
+ if _parts and 'google-chrome' in _parts[0] \
564
+ and not any(p.startswith('--remote-debugging-port') for p in _parts):
565
+ _parts[1:1] = ['--no-first-run', '--no-default-browser-check',
566
+ '--remote-debugging-port=1337']
567
+ if _parts and 'google-chrome' in _parts[0] \
568
+ and not any(p.startswith('--user-data-dir') for p in _parts):
569
+ _parts[1:1] = [f'--user-data-dir={CHROME_PROFILE_DIR}']
570
+ _proc = subprocess.Popen(_parts, stdin=subprocess.DEVNULL,
571
+ stdout=subprocess.DEVNULL,
572
+ stderr=subprocess.DEVNULL, env=env,
573
+ start_new_session=True)
574
+ time.sleep(delay_sec)
575
+ if _proc.poll() is not None:
576
+ print(' WARNING: launch_gui process exited early (code=%s)'
577
+ % _proc.returncode)
578
+ return _proc
579
+ _primary_mock_url = SALESFORCE_URL
580
+ launch_gui(f'google-chrome "{SALESFORCE_URL}/?sid={sid}"', delay_sec=2.0)
581
+ _open_remaining_mock_tabs(_primary_mock_url)
582
+ wait_mocks_loaded()
583
+ print(f'GUI_READY: launched browser at {SALESFORCE_URL}/?sid={sid}')
am_renewal_outreach_002/reward.py ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: AM Renewal Outreach — Northwind Traders renewal check-in
13
+ Task ID: am_renewal_outreach_002
14
+ Domain: mock_websites (salesforce_mock + gmail_mock + slack_mock)
15
+
16
+ Scoring (1.0 total), all programmatic / deterministic — verifies only the
17
+ NEW artifacts the agent must create (identified by id-set diff vs initial_state,
18
+ so pre-existing distractor records — incl. the old sent email to Karen Walsh and
19
+ the old customer-success message — never earn points):
20
+
21
+ SALESFORCE task (0.34):
22
+ - 0.18 NEW 'task' activity related to the Northwind renewal (opp-1 / account-1),
23
+ with renewal/check-in intent and assigned to Jordan (user-1 when present)
24
+ - 0.16 that task has dueDate 2026-07-01 AND status 'Open' (not completed)
25
+ GMAIL email (0.33):
26
+ - 0.13 NEW email in 'sent' folder addressed to karen.walsh@northwind-traders.example.com
27
+ - 0.10 its subject matches the explicitly required subject, allowing case/spacing/punctuation variants
28
+ - 0.10 its body proposes a renewal call before the renewal timing/date
29
+ SLACK message (0.33):
30
+ - 0.16 NEW message posted by Jordan (user_1) in the 'customer-success' channel
31
+ - 0.17 that message says Northwind/Karen renewal outreach is underway/sent
32
+ """
33
+ import html
34
+ import os
35
+ import re
36
+ import sys
37
+ from datetime import date
38
+
39
+ import requests
40
+
41
+ # ---------------------------------------------------------------------------
42
+ # sid
43
+ # ---------------------------------------------------------------------------
44
+ try:
45
+ with open('/tmp/task_web_sid') as f:
46
+ sid = f.read().strip()
47
+ if not sid:
48
+ raise ValueError('sid is empty')
49
+ except Exception as e:
50
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
51
+ print('REWARD: 0.0')
52
+ sys.exit(0)
53
+
54
+ MOCKS = {
55
+ 'salesforce': 'http://28.7.184.198:8175',
56
+ 'gmail': 'http://28.7.184.198:8138',
57
+ 'slack': 'http://28.7.184.198:8178',
58
+ }
59
+
60
+ # ---------------------------------------------------------------------------
61
+ # Egress proxy helper (mandatory)
62
+ # ---------------------------------------------------------------------------
63
+ PROXY_CANDIDATES = [
64
+ os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy'),
65
+ None,
66
+ ]
67
+
68
+
69
+ def resolve_proxy(probe_url):
70
+ try:
71
+ requests.get(probe_url, timeout=8)
72
+ return None
73
+ except Exception:
74
+ pass
75
+ for candidate in PROXY_CANDIDATES:
76
+ if not candidate:
77
+ continue
78
+ try:
79
+ requests.get(probe_url, timeout=12,
80
+ proxies={'http': candidate, 'https': candidate})
81
+ return candidate
82
+ except Exception:
83
+ continue
84
+ return None
85
+
86
+
87
+ PROXY = resolve_proxy(f"{MOCKS['salesforce']}/go?sid=conn-probe")
88
+ PROXIES = {'http': PROXY, 'https': PROXY} if PROXY else None
89
+
90
+
91
+ def fetch(name):
92
+ url = MOCKS[name]
93
+ data = requests.get(f'{url}/go?sid={sid}', timeout=20, proxies=PROXIES).json()
94
+ return data.get('initial_state') or {}, data.get('current_state') or {}
95
+
96
+
97
+ # ---------------------------------------------------------------------------
98
+ # Fetch all three mock states up front (precondition gate)
99
+ # ---------------------------------------------------------------------------
100
+ try:
101
+ sf_init, sf_cur = fetch('salesforce')
102
+ gm_init, gm_cur = fetch('gmail')
103
+ sl_init, sl_cur = fetch('slack')
104
+ except Exception as e:
105
+ print(f'CRITICAL: Cannot fetch mock state: {e}')
106
+ print('REWARD: 0.0')
107
+ sys.exit(0)
108
+
109
+
110
+ def strip_html(s):
111
+ return re.sub(r'<[^>]+>', ' ', str(s or ''))
112
+
113
+
114
+ TARGET_EMAIL_SUBJECT = 'Northwind Traders renewal call before July 15'
115
+ EXPECTED_TASK_DUE_DATE = date(2026, 7, 1)
116
+ EXPECTED_RENEWAL_DATE = date(2026, 7, 15)
117
+
118
+
119
+ def norm(s):
120
+ text = html.unescape(strip_html(s))
121
+ text = re.sub(r'[\u2010-\u2015]', '-', text)
122
+ return re.sub(r'\s+', ' ', text).strip().casefold()
123
+
124
+
125
+ def loose(s):
126
+ """Normalize user-entered prose for case/whitespace/punctuation-tolerant matching."""
127
+ return re.sub(r'\s+', ' ', re.sub(r'[^a-z0-9]+', ' ', norm(s))).strip()
128
+
129
+
130
+ def contains_any(text, phrases):
131
+ haystack = f" {loose(text)} "
132
+ return any(f" {loose(phrase)} " in haystack for phrase in phrases)
133
+
134
+
135
+ def text_blob(*values):
136
+ return ' '.join(str(v or '') for v in values)
137
+
138
+
139
+ def canonical_subject(s):
140
+ return loose(s)
141
+
142
+
143
+ def subject_matches_target(subject):
144
+ return canonical_subject(subject) == canonical_subject(TARGET_EMAIL_SUBJECT)
145
+
146
+
147
+ def norm_channel_name(s):
148
+ return norm(s).lstrip('#').strip()
149
+
150
+
151
+ MONTH_NAMES = {
152
+ 1: ('january', 'jan'), 2: ('february', 'feb'), 3: ('march', 'mar'),
153
+ 4: ('april', 'apr'), 5: ('may', 'may'), 6: ('june', 'jun'),
154
+ 7: ('july', 'jul'), 8: ('august', 'aug'), 9: ('september', 'sep'),
155
+ 10: ('october', 'oct'), 11: ('november', 'nov'), 12: ('december', 'dec'),
156
+ }
157
+
158
+
159
+ def ordinal(n):
160
+ if 10 <= n % 100 <= 20:
161
+ suffix = 'th'
162
+ else:
163
+ suffix = {1: 'st', 2: 'nd', 3: 'rd'}.get(n % 10, 'th')
164
+ return f'{n}{suffix}'
165
+
166
+
167
+ def mentions_date(text, expected):
168
+ t = norm(text)
169
+ month_full, month_short = MONTH_NAMES[expected.month]
170
+ day = expected.day
171
+ year = expected.year
172
+ variants = {
173
+ f'{month_full} {day}', f'{month_full} {ordinal(day)}',
174
+ f'{month_full} {day}, {year}', f'{month_full} {ordinal(day)}, {year}',
175
+ f'{month_full} {day} {year}', f'{month_full} {ordinal(day)} {year}',
176
+ f'{month_short} {day}', f'{month_short} {ordinal(day)}',
177
+ f'{month_short} {day}, {year}', f'{month_short} {ordinal(day)}, {year}',
178
+ f'{month_short} {day} {year}', f'{month_short} {ordinal(day)} {year}',
179
+ f'{day} {month_full}', f'{ordinal(day)} {month_full}',
180
+ f'{day} {month_short}', f'{ordinal(day)} {month_short}',
181
+ f'{day} {month_full} {year}', f'{ordinal(day)} {month_full} {year}',
182
+ f'{day} {month_short} {year}', f'{ordinal(day)} {month_short} {year}',
183
+ expected.isoformat(),
184
+ }
185
+ if any(v in t for v in variants):
186
+ return True
187
+
188
+ m = expected.month
189
+ numeric_patterns = [
190
+ rf'\b0?{m}[/.-]0?{day}(?:[/.-]{year})?\b',
191
+ rf'\b{year}[/.-]0?{m}[/.-]0?{day}\b',
192
+ rf'\b0?{day}[/.-]0?{m}(?:[/.-]{year})?\b',
193
+ ]
194
+ return any(re.search(p, t) for p in numeric_patterns)
195
+
196
+
197
+ def mentions_renewal_timing(text):
198
+ return mentions_date(text, EXPECTED_RENEWAL_DATE) or contains_any(text, [
199
+ 'renewal date', 'renewal deadline', 'renewal close date', 'close date',
200
+ 'before renewal', 'before the renewal', 'before your renewal',
201
+ 'ahead of renewal', 'ahead of the renewal', 'prior to renewal',
202
+ 'prior to the renewal', 'before it renews', 'before the contract renews',
203
+ ])
204
+
205
+
206
+ def proposes_call(text):
207
+ call_intent = contains_any(text, [
208
+ 'call', 'meeting', 'meet', 'chat', 'connect', 'sync', 'discussion',
209
+ 'discuss', 'conversation', 'touch base', 'talk', 'speak',
210
+ 'schedule time', 'set up time',
211
+ ])
212
+ renewal_context = contains_any(text, ['renewal', 'renew', 'account']) \
213
+ or mentions_renewal_timing(text)
214
+ return call_intent and renewal_context
215
+
216
+
217
+ def date_field_matches(value, expected):
218
+ if not value:
219
+ return False
220
+ text = norm(value)
221
+ if text[:10] == expected.isoformat():
222
+ return True
223
+ return mentions_date(text, expected)
224
+
225
+
226
+ total_score = 0.0
227
+
228
+ # ===========================================================================
229
+ # SALESFORCE — new renewal check-in task (0.34)
230
+ # ===========================================================================
231
+ try:
232
+ init_ids = {a.get('activityId') for a in sf_init.get('activities', [])}
233
+ new_acts = [a for a in sf_cur.get('activities', [])
234
+ if a.get('activityId') not in init_ids]
235
+
236
+ # Candidate = NEW task related to the Northwind renewal (opp-1 or account-1)
237
+ # with renewal/check-in intent. The relation preserves the customer/opportunity
238
+ # signal, so the subject can use natural wording like "call Karen" or
239
+ # "renewal follow-up" without requiring exact tokens.
240
+ sf_task = None
241
+ for a in new_acts:
242
+ if norm(a.get('type')) != 'task':
243
+ continue
244
+ task_text = text_blob(a.get('subject'), a.get('description'), a.get('comments'), a.get('notes'))
245
+ related_type = norm(a.get('relatedToType'))
246
+ related_ok = (related_type == 'opportunity' and a.get('relatedToId') == 'opp-1') \
247
+ or (related_type == 'account' and a.get('relatedToId') == 'account-1')
248
+ assigned_ok = not a.get('assignedToId') or a.get('assignedToId') == 'user-1'
249
+ intent_ok = contains_any(task_text, [
250
+ 'renewal', 'renew', 'check in', 'check-in', 'follow up',
251
+ 'follow-up', 'outreach', 'call', 'meeting', 'touch base',
252
+ 'karen', 'walsh',
253
+ ])
254
+ if related_ok and assigned_ok and intent_ok:
255
+ sf_task = a
256
+ break
257
+
258
+ # Component SF-1 (0.18): correct new task exists, right relation/owner/intent
259
+ if sf_task is not None:
260
+ print(f"PASS: SF new renewal task on Northwind (id={sf_task.get('activityId')}, "
261
+ f"subject={sf_task.get('subject')!r}, related={sf_task.get('relatedToId')}) (0.18)")
262
+ total_score += 0.18
263
+
264
+ # Component SF-2 (0.16): dueDate 2026-07-01 AND status Open
265
+ due_ok = date_field_matches(sf_task.get('dueDate'), EXPECTED_TASK_DUE_DATE)
266
+ status_ok = norm(sf_task.get('status')) in ('open', 'not started', 'in progress', 'pending')
267
+ if due_ok and status_ok:
268
+ print(f"PASS: SF task dueDate=2026-07-01 and status Open "
269
+ f"(status={sf_task.get('status')!r}) (0.16)")
270
+ total_score += 0.16
271
+ else:
272
+ print(f"FAIL: SF task date/status — dueDate={sf_task.get('dueDate')!r} "
273
+ f"(want 2026-07-01), status={sf_task.get('status')!r} (want Open)")
274
+ else:
275
+ print(f"FAIL: SF — no NEW task related to opp-1/account-1 with "
276
+ f"renewal/check-in intent assigned to user-1 when present "
277
+ f"(new activities: {[a.get('activityId') for a in new_acts]})")
278
+ except Exception as e:
279
+ print(f'ERROR: Salesforce component — {e}')
280
+
281
+ # ===========================================================================
282
+ # GMAIL — new renewal outreach email to Karen Walsh (0.33)
283
+ # ===========================================================================
284
+ KAREN = 'karen.walsh@northwind-traders.example.com'
285
+ try:
286
+ init_ids = {e.get('id') for e in gm_init.get('emails', [])}
287
+ new_emails = [e for e in gm_cur.get('emails', [])
288
+ if e.get('id') not in init_ids]
289
+
290
+ # NEW sent email addressed to Karen Walsh; prefer the explicitly named
291
+ # outreach email but keep body scoring independent so one subject typo
292
+ # does not erase otherwise correct outreach content.
293
+ sent_to_karen = None
294
+ sent_to_karen_emails = []
295
+ exact_subject_email = None
296
+ for e in new_emails:
297
+ if norm(e.get('folder')) != 'sent':
298
+ continue
299
+ recips = [norm(t.get('email')) for t in e.get('to', [])]
300
+ if KAREN in recips:
301
+ sent_to_karen_emails.append(e)
302
+ if sent_to_karen is None:
303
+ sent_to_karen = e
304
+ if subject_matches_target(e.get('subject')):
305
+ exact_subject_email = e
306
+
307
+ # Component GM-1 (0.13): new sent email to Karen Walsh exists
308
+ if sent_to_karen is not None:
309
+ print(f"PASS: Gmail NEW sent email to Karen Walsh "
310
+ f"(id={sent_to_karen.get('id')}, subject={sent_to_karen.get('subject')!r}) (0.13)")
311
+ total_score += 0.13
312
+
313
+ # Component GM-2 (0.10): subject matches the explicitly required instruction.
314
+ if exact_subject_email is not None:
315
+ print(f"PASS: Gmail subject matches required subject {TARGET_EMAIL_SUBJECT!r} (0.10)")
316
+ total_score += 0.10
317
+ else:
318
+ print(f"FAIL: Gmail subject — expected required subject {TARGET_EMAIL_SUBJECT!r}; "
319
+ f"got {[e.get('subject') for e in sent_to_karen_emails]}")
320
+
321
+ # Component GM-3 (0.10): body proposes a renewal call before the renewal timing.
322
+ # The fixed July-15 signal may appear in the required subject, while the body
323
+ # can naturally say "before your renewal date".
324
+ def email_body_ok(e):
325
+ body = strip_html(e.get('body'))
326
+ timing_ok = mentions_renewal_timing(body) or subject_matches_target(e.get('subject'))
327
+ return proposes_call(body) and timing_ok
328
+
329
+ body_email = next((e for e in ([exact_subject_email] if exact_subject_email else [])
330
+ if e and email_body_ok(e)), None)
331
+ if body_email is None:
332
+ body_email = next((e for e in sent_to_karen_emails if email_body_ok(e)), None)
333
+
334
+ if body_email is not None:
335
+ print("PASS: Gmail body proposes a renewal call before the renewal timing/date (0.10)")
336
+ total_score += 0.10
337
+ else:
338
+ print("FAIL: Gmail body — need a sent-to-Karen email body proposing a renewal "
339
+ "call/meeting before the renewal timing/date")
340
+ else:
341
+ print(f"FAIL: Gmail — no NEW sent email addressed to {KAREN} "
342
+ f"(new emails: {[e.get('id') for e in new_emails]})")
343
+ except Exception as e:
344
+ print(f'ERROR: Gmail component — {e}')
345
+
346
+ # ===========================================================================
347
+ # SLACK — new message in #customer-success (0.33)
348
+ # ===========================================================================
349
+ try:
350
+ # Resolve the customer-success channel id/name; the UI may expose the
351
+ # channel as either "customer-success" or "#customer-success".
352
+ def customer_success_keys(state):
353
+ keys = set()
354
+ for c in state.get('channels', []):
355
+ name = c.get('name')
356
+ channel_id = c.get('channelId')
357
+ if norm_channel_name(name) == 'customer-success' \
358
+ or norm_channel_name(channel_id) == 'customer-success':
359
+ for value in (channel_id, name, norm_channel_name(name),
360
+ f"#{norm_channel_name(name)}"):
361
+ if value:
362
+ keys.add(value)
363
+ return keys
364
+
365
+ cs_keys = customer_success_keys(sl_cur) or customer_success_keys(sl_init)
366
+
367
+ if not cs_keys:
368
+ print("FAIL: Slack — 'customer-success' channel not found")
369
+ else:
370
+ def messages_for_channel(state, keys):
371
+ allowed = {norm_channel_name(k) for k in keys if k}
372
+ messages = []
373
+ seen = set()
374
+ for key, vals in (state.get('messages') or {}).items():
375
+ if key in keys or norm_channel_name(key) in allowed:
376
+ for m in vals or []:
377
+ msg_id = m.get('messageId') or id(m)
378
+ if msg_id not in seen:
379
+ seen.add(msg_id)
380
+ messages.append(m)
381
+ return messages
382
+
383
+ init_msgs = messages_for_channel(sl_init, cs_keys)
384
+ cur_msgs = messages_for_channel(sl_cur, cs_keys)
385
+ init_msg_ids = {m.get('messageId') for m in init_msgs}
386
+ new_msgs = [m for m in cur_msgs if m.get('messageId') not in init_msg_ids]
387
+
388
+ # Component SL-1 (0.16): NEW message by Jordan (user_1) in customer-success
389
+ my_new = [m for m in new_msgs if m.get('senderId') == 'user_1']
390
+ if my_new:
391
+ print(f"PASS: Slack NEW message by user_1 in #customer-success "
392
+ f"({len(my_new)} new) (0.16)")
393
+ total_score += 0.16
394
+
395
+ # Component SL-2 (0.17): content says renewal outreach to
396
+ # Northwind/Karen is underway/sent. The instruction does not require
397
+ # the Slack note to repeat the fixed July-15 date.
398
+ def content_ok(m):
399
+ t = m.get('content')
400
+ customer = contains_any(t, ['northwind', 'karen walsh', 'karen', 'walsh'])
401
+ renewal = contains_any(t, ['renewal', 'renew', 'renewing', 'outreach',
402
+ 'check in', 'check-in', 'call', 'meeting'])
403
+ underway = contains_any(t, [
404
+ 'underway', 'kicked off', 'kicked-off', 'reached out', 'reach out',
405
+ 'emailed', 'email sent', 'sent email', 'contacted', 'check-in',
406
+ 'check in', 'sent', 'outreach', 'started', 'initiated',
407
+ 'in progress', 'following up', 'followed up', 'handled', 'done',
408
+ ])
409
+ return customer and renewal and underway
410
+
411
+ good = next((m for m in my_new if content_ok(m)), None)
412
+ if good is not None:
413
+ print("PASS: Slack message reports Northwind/Karen renewal outreach underway (0.17)")
414
+ total_score += 0.17
415
+ else:
416
+ print(f"FAIL: Slack message content — need Northwind/Karen + renewal/check-in "
417
+ f"+ outreach-underway/sent. Contents: {[norm(m.get('content'))[:80] for m in my_new]}")
418
+ else:
419
+ print(f"FAIL: Slack — no NEW message by user_1 in #customer-success "
420
+ f"(new msgs: {[m.get('messageId') for m in new_msgs]})")
421
+ except Exception as e:
422
+ print(f'ERROR: Slack component — {e}')
423
+
424
+ # ===========================================================================
425
+ final_score = round(min(total_score, 1.0), 4)
426
+ print(f'\nScore: {total_score}/1.0')
427
+ print(f'REWARD: {final_score}')
am_renewal_outreach_002/reward_label.json ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/am_renewal_outreach_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:16:52",
7
+ "label": {
8
+ "task_id": "am_renewal_outreach_002",
9
+ "domain": "mock_websites",
10
+ "summary": "验证代理是否在Salesforce中创建Northwind续签任务、在Gmail中发送给Karen Walsh的续签邮件、并在Slack customer-success频道发布续签外展消息",
11
+ "is_placeholder": false,
12
+ "data_sources": [
13
+ "/tmp/task_web_sid",
14
+ "salesforce_mock",
15
+ "gmail_mock",
16
+ "slack_mock"
17
+ ],
18
+ "scoring_components": [
19
+ {
20
+ "name": "SF-1: 新建Salesforce续签任务",
21
+ "weight": 0.18,
22
+ "description": "检查是否存在新增的Task活动,与Northwind续签相关,分配给Jordan,且意图匹配",
23
+ "check_logic": "通过id-set diff找出sf_cur中新增的activities;筛选type为task、relatedToId为opp-1或account-1、assignedToId为空或user-1、且subject/description/comments/notes中包含renewal/renew/check in/check-in/follow up/follow-up/outreach/call/meeting/touch base/karen/walsh等关键词的记录",
24
+ "pass_condition": "存在至少一条满足上述全部条件的新增task记录"
25
+ },
26
+ {
27
+ "name": "SF-2: 任务截止日期与状态",
28
+ "weight": 0.16,
29
+ "description": "检查上述新建任务的dueDate为2026-07-01且状态为未完成",
30
+ "check_logic": "对SF-1中找到的task,检查dueDate字段是否匹配2026-07-01(支持ISO格式或自然语言变体),且status归一化后为open/not started/in progress/pending之一",
31
+ "pass_condition": "dueDate匹配2026-07-01且status为Open(或其同义词)"
32
+ },
33
+ {
34
+ "name": "GM-1: 新建发送给Karen的邮件",
35
+ "weight": 0.13,
36
+ "description": "检查Gmail sent文件夹中是否存在新增的发送给Karen Walsh的邮件",
37
+ "check_logic": "通过id-set diff找出gm_cur中新增的emails;筛选folder为sent且to列表中包含karen.walsh@northwind-traders.example.com的邮件",
38
+ "pass_condition": "存在至少一封新增的发送给指定Karen邮箱的sent邮件"
39
+ },
40
+ {
41
+ "name": "GM-2: 邮件主题匹配",
42
+ "weight": 0.1,
43
+ "description": "检查邮件主题是否与要求的主题匹配(忽略大小写、空格、标点)",
44
+ "check_logic": "对发送给Karen的邮件,使用canonical_subject(loose归一化)比较是否等于'Northwind Traders renewal call before July 15'的loose归一化结果",
45
+ "pass_condition": "至少一封邮件的主题经loose归一化后与目标主题完全一致"
46
+ },
47
+ {
48
+ "name": "GM-3: 邮件正文提议续签通话",
49
+ "weight": 0.1,
50
+ "description": "检查邮件正文是否提议在续签日期前进行通话/会议",
51
+ "check_logic": "对候选邮件(优先主题完全匹配的邮件,否则所有发给Karen的邮件),检查body经strip_html后:proposes_call(包含call/meeting等意图词且包含renewal/account或提及续签时间)且timing_ok(正文提及renewal timing或主题已完全匹配目标主题)",
52
+ "pass_condition": "至少一封邮件正文表达通话/会议意图,并关联续签上下文或提及续签日期"
53
+ },
54
+ {
55
+ "name": "SL-1: Slack新建消息",
56
+ "weight": 0.16,
57
+ "description": "检查在customer-success频道中是否有user_1(Jordan)发布的新消息",
58
+ "check_logic": "通过channel名称或ID定位customer-success频道;通过id-set diff找出该频道下新增的消息;筛选senderId为user_1的消息",
59
+ "pass_condition": "存在至少一条user_1在customer-success频道的新增消息"
60
+ },
61
+ {
62
+ "name": "SL-2: 消息内容报告续签外展状态",
63
+ "weight": 0.17,
64
+ "description": "检查消息内容是否表明Northwind/Karen的续签外展正在进行或已发送",
65
+ "check_logic": "对SL-1中user_1的新消息,检查content是否同时满足:customer(包含northwind/karen walsh/karen/walsh)、renewal(包含renewal/renew/renewing/outreach/check in/check-in/call/meeting)、underway(包含underway/kicked off/reached out/emailed/sent email/contacted/sent/started/initiated/in progress/following up/handled/done等)",
66
+ "pass_condition": "至少一条消息内容同时包含客户标识、续签意图和外展已进行/已发送的表述"
67
+ }
68
+ ],
69
+ "total_max_score": 1.0,
70
+ "score_aggregation": "各组件分数累加,最终用min(total_score, 1.0)钳制到上限1.0,并四舍五入到4位小数",
71
+ "failure_modes": [
72
+ "无法从/tmp/task_web_sid读取sid时打印CRITICAL并返回0.0",
73
+ "无法从任一mock服务拉取状态时打印CRITICAL并返回0.0",
74
+ "Salesforce中未找到符合条件的新增task时SF���件不得分",
75
+ "Gmail中未找到新增sent邮件或收件人不是Karen时GM组件不得分",
76
+ "Slack中未找到customer-success频道时Slack组件不得分",
77
+ "Slack中未找到user_1的新消息时SL组件不得分",
78
+ "各子组件字段检查失败(如日期、状态、主题、正文、内容不匹配)时对应子组件不得分",
79
+ "各模块异常被捕获后打印ERROR,该模块不得分但不影响其他模块"
80
+ ],
81
+ "scoring_logic_explanation": "脚本首先读取/tmp/task_web_sid获取会话ID,失败则直接退出并返回0.0。接着通过HTTP GET拉取salesforce_mock、gmail_mock、slack_mock的initial_state和current_state,拉取失败同样返回0.0。评分采用id-set差分策略:将current_state中的记录ID与initial_state对比,仅对新增的artifacts进行评分,排除预存干扰项。Salesforce模块(0.34分)先检查新增task是否关联opp-1/account-1、分配给user-1且意图匹配续签/检查(0.18分),再检查该task的dueDate为2026-07-01且status为Open(0.16分)。Gmail模块(0.33分)检查新增sent邮件是否发给karen.walsh@northwind-traders.example.com(0.13分),主题是否匹配'Northwind Traders renewal call before July 15'(0.10分),正文是否提议续签通话并关联续签时间(0.10分)。Slack模块(0.33分)先定位customer-success频道,检查user_1的新消息(0.16分),再验证消息内容同时提及Northwind/Karen、续签以及外展正在进行/已发送(0.17分)。各组件独立评分,累加后通过min(total_score, 1.0)钳制上限并四舍五入输出最终REWARD。",
82
+ "confidence": 1.0
83
+ },
84
+ "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码并提取所需信息:\n\n1. **task_id**: 从 docstring 中可以看到 \"Task ID: am_renewal_outreach_002\"\n2. **domain**: 从 docstring 中可以看到 \"Domain: mock_websites (salesforce_mock + gmail_mock + slack_mock)\",所以 domain 是 mock_websites\n3. **summary**: 一句话概括。这个脚本验证代理是否在 Salesforce 中创建了新的 Northwind 续签任务、在 Gmail 中发送了给 Karen Walsh 的续签邮件、在 Slack 的 customer-success 频道发布了续签外展消息。\n4. **is_placeholder**: false,因为脚本有详细的评分逻辑,不是占位脚本。\n5. **data_sources**: 脚本从 /tmp/task_web_sid 读取 sid,从 salesforce_mock (http://28.7.186.212:8195)、gmail_mock (http://28.7.186.212:8158)、slack_mock (http://28.7.186.212:8198) 获取状态。\n6. **scoring_components**: \n - Salesforce 任务 (0.34 total):\n - Component SF-1 (0.18): 新的 task 活动,与 Northwind 续签相关 (opp-1/account-1),有续签/检查意图,分配给 Jordan (user-1)\n - Component SF-2 (0.16): 该任务的 dueDate 是 2026-07-01 且状态为 Open (或 not started/in progress/pending)\n - Gmail 邮件 (0.33 total):\n - Component GM-1 (0.13): 新的 sent 邮件发送给 karen.walsh@northwind-traders.example.com\n - Component GM-2 (0.10): 主题匹配 'Northwind Traders renewal call before July 15'(允许大小写/空格/标点变化)\n - Component GM-3 (0.10): 正文提议在续签日期前进行续签通话\n - Slack 消息 (0.33 total):\n - Component SL-1 (0.16): user_1 (Jordan) 在 customer-success 频道发布的新消息\n - Component SL-2 (0.17): 消息内容表明 Northwind/Karen 的续签外展正在进行/已发送\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 → CRITICAL,REWARD: 0.0,sys.exit(0)\n - 无法获取 mock 状态 → CRITICAL,REWARD: 0.0,sys.exit(0)\n - 找不到 customer-success 频道 → 打印 FAIL,该组件不得分\n - 各组件检查失败会打印 FAIL 并跳过加分\n - 异常会被捕获打印 ERROR 但不退出\n\n10. **scoring_logic_explanation**: 详细解释执行顺序:\n - 首先读取 /tmp/task_web_sid 获取会话 ID,失败则返回 0.0。\n - 解析代理设置,尝试直连或经代理访问三个 mock 服务。\n - 并行(顺序)拉取 salesforce、gmail、slack 的 initial_state 和 current_state,失败则返回 0.0。\n - 通过 id-set diff 识别每个 mock 中新增的 artifacts,排除预存在的干扰记录。\n - Salesforce: 检查新增 task 是否关联 opp-1/account-1、分配给 user-1、意图匹配续签/检查;再检查 dueDate 和状态。\n - Gmail: 检查新增 sent 邮件是否发给 Karen Walsh;主题是否匹配目标;正文是否提议续签通话并提及续签时间。\n - Slack: 定位 customer-success 频道,检查 user_1 的新消息;内容是否包含 Northwind/Karen、续签、外展进行中/已发送。\n - 累加各通过组件分值,最终用 min(total_score, 1.0) 钳制并四舍五入到 4 位小数。\n\n11. **confidence**: 1.0,因为代码非常清晰完整。\n\n让我再仔细检查一下各个组件的权重和逻辑:\n\nSalesforce:\n- SF-1: 0.18 (new task, related to opp-1/account-1, assigned to user-1 when present, intent matches)\n- SF-2: 0.16 (dueDate 2026-07-01 AND status Open)\n- Total: 0.34\n\nGmail:\n- GM-1: 0.13 (new sent email to KAREN)\n- GM-2: 0.10 (subject matches target)\n- GM-3: 0.10 (body proposes renewal call before renewal timing)\n- Total: 0.33\n\nSlack:\n- SL-1: 0.16 (new message by user_1 in customer-success)\n- SL-2: 0.17 (content says Northwind/Karen renewal outreach underway/sent)\n- Total: 0.33\n\nGrand total: 0.34 + 0.33 + 0.33 = 1.0\n\nFailure modes:\n- sid read failure\n- mock fetch failure\n- slack channel not found (causes fail for slack components)\n- missing new artifacts\n- incorrect fields/dates/status/subject/body/content\n\n我需要确保 JSON 格式完全符合要求,没有 markdown 代码块,第一个字符是 {,最后一个字符是 }。\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"am_renewal_outreach_002\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证代理是否在Salesforce中创建Northwind续签任务、在Gmail中发送给Karen Walsh的续签邮件、并在Slack customer-success频道发布续格外展消息\",\n \"is_placeholder\": false,\n \"data_sources\": [\n \"/tmp/task_web_sid\",\n \"salesforce_mock\",\n \"gmail_mock\",\n \"slack_mock\"\n ],\n \"scoring_components\": [\n {\n \"name\": \"SF-1: 新建Salesforce续签任务\",\n \"weight\": 0.18,\n \"description\": \"检查是否存在新增的Task活动,与Northwind续签相关,分配给Jordan,且意图匹配\",\n \"check_logic\": \"通过id-set diff找出sf_cur中新增的activities;筛选type为task、relatedToId为opp-1或account-1、assignedToId为空或user-1、且subject/description/comments/notes中包含renewal/renew/check in/check-in/follow up/follow-up/outreach/call/meeting/touch base/karen/walsh等关键词的记录\",\n \"pass_condition\": \"存在至少一条满足上述全部条件的新增task记录\"\n },\n {\n \"name\": \"SF-2: 任务截止日期与状态\",\n \"weight\": 0.16,\n \"description\": \"检查上述新建任务的dueDate为2026-07-01且状态为未完成\",\n \"check_logic\": \"对SF-1中找到的task,检查dueDate字段是否匹配2026-07-01(支持ISO格式或自然语言变体),且status归一化后为open/not started/in progress/pending之一\",\n \"pass_condition\": \"dueDate匹配2026-07-01且status为Open(或其同义词)\"\n },\n {\n \"name\": \"GM-1: 新建发送给Karen的邮件\",\n \"weight\": 0.13,\n \"description\": \"检查Gmail sent文件夹中是否存在新增的发送给Karen Walsh的邮件\",\n \"check_logic\": \"通过id-set diff找出gm_cur中新增的emails;筛选folder为sent且to列表中包含karen.walsh@northwind-traders.example.com的邮件\",\n \"pass_condition\": \"存在至少一封新增的发送给指定Karen邮箱的sent邮件\"\n },\n {\n \"name\": \"GM-2: 邮件主题匹配\",\n \"weight\": 0.10,\n \"description\": \"检查邮件主题是否与要求的主题匹配(忽略大小写、空格、标点)\",\n \"check_logic\": \"对发送给Karen的邮件,使用canonical_subject(loose归一化)比较是否等于'Northwind Traders renewal call before July 15'的loose归一化结果\",\n \"pass_condition\": \"至少一封邮件的主题经loose归一化后与目标主题完全一致\"\n },\n {\n \"name\": \"GM-3: 邮件正文提议续签通话\",\n \"weight\": 0.10,\n \"description\": \"检查邮件正文是否提议在续签日期前进行通话/会议\",\n \"check_logic\": \"对候选邮件(优先主题完全匹配的邮件,否则所有发给Karen的邮件),检查body经strip_html后:proposes_call(包含call/meeting等意图词且包含renewal/account或提及续签时间)且timing_ok(正文提及renewal timing或主题已完全匹配目标主题)\",\n \"pass_condition\": \"至少一封邮件正文表达通话/会议意图,并关联续签上下文或提及续签日期\"\n },\n {\n \"name\": \"SL-1: Slack新建消息\",\n \"weight\": 0.16,\n \"description\": \"检查在customer-success频道中是否有user_1(Jordan)发布的新消息\",\n \"check_logic\": \"通过channel名称或ID定位customer-success频道;通过id-set diff找出该频道下新增的消息;筛选senderId为user_1的消息\",\n \"pass_condition\": \"存在至少一条user_1在customer-success频道的新增消息\"\n },\n {\n \"name\": \"SL-2: 消息内容报告续签外展状态\",\n \"weight\": 0.17,\n \"description\": \"检查消息内容是否表明Northwind/Karen的续签外展正在进行或已发送\",\n \"check_logic\": \"对SL-1中user_1的新消息,检查content是否同时满足:customer(包含northwind/karen walsh/karen/walsh)、renewal(包含renewal/renew/renewing/outreach/check in/check-in/call/meeting)、underway(包含underway/kicked off/reached out/emailed/sent email/contacted/sent/started/initiated/in progress/following up/handled/done等)\",\n \"pass_condition\": \"至少一条消息内容同时包含客户标识、续签意图和外展已进行/已发送的表述\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数累加,最终用min(total_score, 1.0)钳制到上限1.0,并四舍五入到4位小数\",\n \"failure_modes\": [\n \"无法从/tmp/task_web_sid读取sid时打印CRITICAL并返回0.0\",\n \"无法从任一mock服务拉取状态时打印CRITICAL并返回0.0\",\n \"Salesforce中未找到符合条件的新增task时SF组件不得分\",\n \"Gmail中未找到新增sent邮件或收件人不是Karen时GM组件不得分\",\n \"Slack中未找到customer-success频道时Slack组件不得分\",\n \"Slack中未找到user_1的新消息时SL组件不得分\",\n \"各子组件字段检查失败(如日期、状态、主题、正文、内容不匹配)时对应子组件不得分\",\n \"各模块异常被捕获后打印ERROR,该模块不得分但不影响其他模块\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取/tmp/task_web_sid获取会话ID,失败则直接退出并返回0.0。接着通过HTTP GET拉取salesforce_mock、gmail_mock、slack_mock的initial_state和current_state,拉取失败同样返回0.0。评分采用id-set差分策略:将current_state中的记录ID与initial_state对比,仅对新增的artifacts进行评分,排除预存干扰项。Salesforce模块(0.34分)先检查新增task是否关联opp-1/account-1、分配给user-1且意图匹配续签/检查(0.18分),再检查该task的dueDate为2026-07-01且status为Open(0.16分)。Gmail模块(0.33分)检查新增sent邮件是否发给karen.walsh@northwind-traders.example.com(0.13分),主题是否匹配'Northwind Traders renewal call before July 15'(0.10分),正文是否提议续签通话并关联续签时间(0.10分)。Slack模块(0.33分)先定位customer-success频道,检查user_1的新消息(0.16分),再验证消息内容同时提及Northwind/Karen、续签以及外展正在进行/已发送(0.17分)。各组件独立评分,累加后通过min(total_score, 1.0)钳制上限并四舍五入输出最终REWARD。\",\n \"confidence\": 1.0\n}\n```\n\n我需要确保:\n- 没有 markdown 代码块标记\n- 第一个字符是 {\n- 最后一个字符是 }\n- 所有字符串 value 使用中文(task_id、domain、字段名、代码标识符保留原样)\n- JSON 格式正确\n\n让我再检查一下 `data_sources` 字段。代码中 MOCKS 定义了三个服务的 URL,但通常我们称它们为 salesforce_mock、gmail_mock、slack_mock。文件路径也提到了这些。还有 `/tmp/task_web_sid`。\n\n`scoring_components` 中的 `check_logic` 和 `pass_condition` 需要准确反映代码逻辑。\n\n对于 SF-1:\n- `related_ok`: relatedToType 为 opportunity 且 relatedToId 为 opp-1,或 relatedToType 为 account 且 relatedToId 为 account-1\n- `assigned_ok`: assignedToId 为空或为 user-1\n- `intent_ok`: task_text 包含特定关键词\n- 代码中 `if related_ok and assigned_ok and intent_ok`\n\n对于 SF-2:\n- `due_ok`: date_field_matches 检查 dueDate\n- `status_ok`: norm(status) in ('open', 'not started', 'in progress', 'pending')\n- 注意:代码中 `if due_ok and status_ok` 才加分\n\n对于 GM-1:\n- `sent_to_karen`: folder 为 sent,to 列表包含 KAREN\n\n对于 GM-2:\n- `exact_subject_email`: subject_matches_target\n- `subject_matches_target`: canonical_subject(subject) == canonical_subject(TARGET_EMAIL_SUBJECT)\n\n对于 GM-3:\n- `email_body_ok`: body 的 timing_ok 和 proposes_call\n- `timing_ok`: mentions_renewal_timing(body) or subject_matches_target(e.get('subject'))\n- `proposes_call`: call_intent and renewal_context\n- 注意:代码优先检查 exact_subject_email,然后检查 sent_to_karen_emails\n\n对于 SL-1:\n- `my_new`: new_msgs 中 senderId == 'user_1'\n\n对于 SL-2:\n- `content_ok`: customer and renewal and underway\n\n一切看起来都正确。\n\n关于 `failure_modes`:\n- 代码中 Slack 频道未找到时打印 \"FAIL: Slack — 'customer-success' channel not found\",然后进入 else 分支?不,代码是:\n```python\n if not cs_keys:\n print(\"FAIL: Slack — 'customer-success' channel not found\")\n else:\n ...\n```\n所以如果没有 cs_keys,Slack 组件不得分,但不会崩溃。\n\n关于 `score_aggregation`: 代码是 `final_score = round(min(total_score, 1.0), 4)`,所以是累加后钳制。\n\n关于 `is_placeholder`: false,因为脚本有完整的评分逻辑。\n\n关于 `confidence`: 1.0,因为代码非常清晰。\n\n让我再确认一下 domain。docstring 中写的是 \"Domain: mock_websites (salesforce_mock + gmail_mock + slack_mock)\"。按照要求,domain 应该是 mock_websites。\n\ntask_id: am_renewal_outreach_002\n\nsummary 需要一句话概括。\n\n好的,我认为 JSON 已经准备好了�� </think> {\"task_id\":\"am_renewal_outreach_002\",\"domain\":\"mock_websites\",\"summary\":\"验证代理是否在Salesforce中创建Northwind续签任务、在Gmail中发送给Karen Walsh的续签邮件、并在Slack customer-success频道发布续签外展消息\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"salesforce_mock\",\"gmail_mock\",\"slack_mock\"],\"scoring_components\":[{\"name\":\"SF-1: 新建Salesforce续签任务\",\"weight\":0.18,\"description\":\"检查是否存在新增的Task活动,与Northwind续签相关,分配给Jordan,且意图匹配\",\"check_logic\":\"通过id-set diff找出sf_cur中新增的activities;筛选type为task、relatedToId为opp-1或account-1、assignedToId为空或user-1、且subject/description/comments/notes中包含renewal/renew/check in/check-in/follow up/follow-up/outreach/call/meeting/touch base/karen/walsh等关键词的记录\",\"pass_condition\":\"存在至少一条满足上述全部条件的新增task记录\"},{\"name\":\"SF-2: 任务截止日期与状态\",\"weight\":0.16,\"description\":\"检查上述新建任务的dueDate为2026-07-01且状态为未完成\",\"check_logic\":\"对SF-1中找到的task,检查dueDate字段是否匹配2026-07-01(支持ISO格式或自然语言变体),且status归一化后为open/not started/in progress/pending之一\",\"pass_condition\":\"dueDate匹配2026-07-01且status为Open(或其同义词)\"},{\"name\":\"GM-1: 新建发送给Karen的邮件\",\"weight\":0.13,\"description\":\"检查Gmail sent文件夹中是否存在新增的发送给Karen Walsh的邮件\",\"check_logic\":\"通过id-set diff找出gm_cur中新增的emails;筛选folder为sent且to列表中包含karen.walsh@northwind-traders.example.com的邮件\",\"pass_condition\":\"存在至少一封新增的发送给指定Karen邮箱的sent邮件\"},{\"name\":\"GM-2: 邮件主题匹配\",\"weight\":0.10,\"description\":\"检查邮件主题是否与要求的主题匹配(忽略大小写、空格、标点)\",\"check_logic\":\"对发送给Karen的邮件,使用canonical_subject(loose归一化)比较是否等于'Northwind Traders renewal call before July 15'的loose归一化结果\",\"pass_condition\":\"至少一封邮件的主题经loose归一化后与目标主题完全一致\"},{\"name\":\"GM-3: 邮件正文提议续签通话\",\"weight\":0.10,\"description\":\"检查邮件正文是否提议在续签日期前进行通话/会议\",\"check_logic\":\"对候选邮件(优先主题完全匹配的邮件,否则所有发给Karen的邮件),检查body经strip_html后:proposes_call(包含call/meeting等意图词且包含renewal/account或提及续签时间)且timing_ok(正文提及renewal timing或主题已完全匹配目标主题)\",\"pass_condition\":\"至少一封邮件正文表达通话/会议意图,并关联续签上下文或提及续签日期\"},{\"name\":\"SL-1: Slack新建消息\",\"weight\":0.16,\"description\":\"检查在customer-success频道中是否有user_1(Jordan)发布的新消息\",\"check_logic\":\"通过channel名称或ID定位customer-success频道;通过id-set diff找出该频道下新增的消息;筛选senderId为user_1的消息\",\"pass_condition\":\"存在至少一条user_1在customer-success频道的新增消息\"},{\"name\":\"SL-2: 消息内容报告续签外展状态\",\"weight\":0.17,\"description\":\"检查消息内容是否表明Northwind/Karen的续签外展正在进行或已发送\",\"check_logic\":\"对SL-1中user_1的新消息,检查content是否同时满足:customer(包含northwind/karen walsh/karen/walsh)、renewal(包含renewal/renew/renewing/outreach/check in/check-in/call/meeting)、underway(包含underway/kicked off/reached out/emailed/sent email/contacted/sent/started/initiated/in progress/following up/handled/done等)\",\"pass_condition\":\"至少一条消息内容同时包含客户标识、续签意图和外展已进行/已发送的表述\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数累加,最终用min(total_score, 1.0)钳制到上限1.0,并四舍五入到4位小数\",\"failure_modes\":[\"无法从/tmp/task_web_sid读取sid时打印CRITICAL并返回0.0\",\"无法从任一mock服务拉取状态时打印CRITICAL并返回0.0\",\"Salesforce中未找到符合条件的新增task时SF组件不得分\",\"Gmail中未找到新增sent邮件或收件人不是Karen时GM组件不得分\",\"Slack中未找到customer-success频道时Slack组件不得分\",\"Slack中未找到user_1的新消息时SL组件不得分\",\"各子组件字段检查失败(如日期、状态、主题、正文、内容不匹配)时对应子组件不得分\",\"各模块异常被捕获后打印ERROR,该模块不得分但不影响其他模块\"],\"scoring_logic_explanation\":\"脚本首先读取/tmp/task_web_sid获取会话ID,失败则直接退出并返回0.0。接着通过HTTP GET拉取salesforce_mock、gmail_mock、slack_mock的initial_state和current_state,拉取失败同样返回0.0。评分采用id-set差分策略:将current_state中的记录ID与initial_state对比,仅对新���的artifacts进行评分,排除预存干扰项。Salesforce模块(0.34分)先检查新增task是否关联opp-1/account-1、分配给user-1且意图匹配续签/检查(0.18分),再检查该task的dueDate为2026-07-01且status为Open(0.16分)。Gmail模块(0.33分)检查新增sent邮件是否发给karen.walsh@northwind-traders.example.com(0.13分),主题是否匹配'Northwind Traders renewal call before July 15'(0.10分),正文是否提议续签通话并关联续签时间(0.10分)。Slack模块(0.33分)先定位customer-success频道,检查user_1的新消息(0.16分),再验证消息内容同时提及Northwind/Karen、续签以及外展正在进行/已发送(0.17分)。各组件独立评分,累加后通过min(total_score, 1.0)钳制上限并四舍五入输出最终REWARD。\",\"confidence\":1.0}"
85
+ }
am_renewal_tracker_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"
am_renewal_tracker_003/initial_setup.py ADDED
@@ -0,0 +1,486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: Quarterly renewal review — Salesforce open renewals -> Notion tracker.
194
+ Task ID: am_renewal_tracker_003
195
+ Domain: mock_websites (multi-mock: salesforce_mock + notion_mock)
196
+
197
+ Persona: Jordan Avery (user-1), Account Manager / Renewals Manager at Vertex Cloud.
198
+ jordan.avery@vertexcloud.example.com. Today = 2026-06-24.
199
+
200
+ PRE-TASK state ONLY. The Notion 'Renewal Tracker 2026' database MUST contain
201
+ ZERO rows (the agent's job is to add exactly three). Salesforce is read-only.
202
+
203
+ DUAL-VM NOTE: /tmp is NOT shared between the initial_env and golden_env containers,
204
+ and the orchestrator does not sync the sid. This script therefore generates its OWN
205
+ sid, persists it on THIS VM, and injects the initial (pre-task) state under it.
206
+ golden_patch.py does the symmetric thing on the golden VM with its own sid.
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
+ 'notion': 'http://28.7.184.198:8166',
220
+ }
221
+
222
+ # --- Egress proxy ---------------------------------------------------------
223
+ # The mocks are only reachable via the cluster HTTPS proxy on this VM (no direct
224
+ # route to the public xlang.ai hosts). Auto-detect: try direct first, then the
225
+ # known cluster proxy. Chrome is launched through the same proxy.
226
+ PROXY_CANDIDATES = [
227
+ os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy'),
228
+ None,
229
+ ]
230
+
231
+
232
+ def _resolve_proxy():
233
+ probe = f"{MOCKS['salesforce']}/go?sid=conn-probe"
234
+ try:
235
+ requests.get(probe, timeout=8)
236
+ return None
237
+ except Exception:
238
+ pass
239
+ for cand in PROXY_CANDIDATES:
240
+ if not cand:
241
+ continue
242
+ try:
243
+ requests.get(probe, timeout=12, proxies={'http': cand, 'https': cand})
244
+ return cand
245
+ except Exception:
246
+ continue
247
+ raise RuntimeError('No working route to mock servers (direct and proxies all failed)')
248
+
249
+
250
+ PROXY = _resolve_proxy()
251
+ PROXIES = None
252
+ print(f'Egress proxy: {PROXY or "direct"}')
253
+
254
+ # --- Session id (this VM only) -------------------------------------------
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
+ # ---------------------------------------------------------------------------
262
+ # SALESFORCE initial state (read-only system of record for renewals)
263
+ # ---------------------------------------------------------------------------
264
+ def salesforce_state():
265
+ user_1 = {
266
+ "userId": "user-1", "firstName": "Jordan", "lastName": "Avery",
267
+ "email": "jordan.avery@vertexcloud.example.com", "phone": "(555) 310-7742",
268
+ "title": "Account Manager", "department": "Renewals", "role": "Manager",
269
+ "avatar": "https://i.pravatar.cc/150?u=user-1",
270
+ "timezone": "America/New_York", "locale": "en-US", "theme": "lightning",
271
+ }
272
+
273
+ accounts = [
274
+ {"accountId": "account-1", "name": "Northwind Traders", "type": "Customer",
275
+ "industry": "Logistics", "revenue": 58000000, "employees": 640, "ownerId": "user-1",
276
+ "billingStreet": "210 Commerce Blvd", "billingCity": "Columbus", "billingState": "OH",
277
+ "billingZip": "43004", "billingCountry": "USA"},
278
+ {"accountId": "account-2", "name": "Globex Corp", "type": "Customer",
279
+ "industry": "Manufacturing", "revenue": 142000000, "employees": 2100, "ownerId": "user-1",
280
+ "billingStreet": "1 Globex Center", "billingCity": "San Jose", "billingState": "CA",
281
+ "billingZip": "95110", "billingCountry": "USA"},
282
+ {"accountId": "account-3", "name": "Initech", "type": "Customer",
283
+ "industry": "Fintech", "revenue": 96000000, "employees": 880, "ownerId": "user-1",
284
+ "billingStreet": "4120 Office Park Dr", "billingCity": "Austin", "billingState": "TX",
285
+ "billingZip": "73301", "billingCountry": "USA"},
286
+ {"accountId": "account-4", "name": "Soylent Industries", "type": "Customer",
287
+ "industry": "Food Tech", "revenue": 47000000, "employees": 410, "ownerId": "user-1",
288
+ "billingStreet": "88 Green Way", "billingCity": "Sacramento", "billingState": "CA",
289
+ "billingZip": "95814", "billingCountry": "USA"},
290
+ {"accountId": "account-5", "name": "Umbrella Health", "type": "Customer",
291
+ "industry": "Healthcare", "revenue": 210000000, "employees": 3400, "ownerId": "user-1",
292
+ "billingStreet": "1200 Medical Pkwy", "billingCity": "Raleigh", "billingState": "NC",
293
+ "billingZip": "27601", "billingCountry": "USA"},
294
+ {"accountId": "account-6", "name": "Hooli", "type": "Customer",
295
+ "industry": "Technology", "revenue": 320000000, "employees": 5200, "ownerId": "user-1",
296
+ "billingStreet": "500 Innovation Dr", "billingCity": "Palo Alto", "billingState": "CA",
297
+ "billingZip": "94301", "billingCountry": "USA"},
298
+ ]
299
+
300
+ contacts = [
301
+ {"contactId": "contact-1", "accountId": "account-1", "firstName": "Karen",
302
+ "lastName": "Walsh", "title": "VP Operations", "department": "Operations",
303
+ "email": "karen.walsh@northwind-traders.example.com", "phone": "(555) 221-3380",
304
+ "ownerId": "user-1"},
305
+ {"contactId": "contact-2", "accountId": "account-2", "firstName": "David",
306
+ "lastName": "Okafor", "title": "COO", "department": "Executive",
307
+ "email": "david.okafor@globex.example.com", "phone": "(555) 552-1140",
308
+ "ownerId": "user-1"},
309
+ {"contactId": "contact-3", "accountId": "account-3", "firstName": "Priya",
310
+ "lastName": "Nair", "title": "VP Finance", "department": "Finance",
311
+ "email": "priya.nair@initech.example.com", "phone": "(555) 884-2201",
312
+ "ownerId": "user-1"},
313
+ ]
314
+
315
+ opportunities = [
316
+ # QUALIFIES — closes 2026-07-15 (<= 2026-09-22), open (Negotiation), prob 75 -> Low
317
+ {"opportunityId": "opp-1", "name": "Northwind Traders – Annual Renewal",
318
+ "accountId": "account-1", "contactId": "contact-1", "amount": 120000,
319
+ "closeDate": "2026-07-15", "stage": "Negotiation", "probability": 75,
320
+ "ownerId": "user-1"},
321
+ # QUALIFIES — closes 2026-08-30, open (Proposal), prob 55 -> Medium
322
+ {"opportunityId": "opp-2", "name": "Globex Corp – Platform Renewal",
323
+ "accountId": "account-2", "contactId": "contact-2", "amount": 85000,
324
+ "closeDate": "2026-08-30", "stage": "Proposal", "probability": 55,
325
+ "ownerId": "user-1"},
326
+ # QUALIFIES — closes 2026-09-10, open (Qualification), prob 35 -> High
327
+ {"opportunityId": "opp-3", "name": "Initech – Renewal & Upsell",
328
+ "accountId": "account-3", "contactId": "contact-3", "amount": 240000,
329
+ "closeDate": "2026-09-10", "stage": "Qualification", "probability": 35,
330
+ "ownerId": "user-1"},
331
+ # DISTRACTOR — closes 2026-11-20 (AFTER 90-day window)
332
+ {"opportunityId": "opp-4", "name": "Soylent Industries – Renewal",
333
+ "accountId": "account-4", "contactId": None, "amount": 54000,
334
+ "closeDate": "2026-11-20", "stage": "Negotiation", "probability": 60,
335
+ "ownerId": "user-1"},
336
+ # DISTRACTOR — closes 2026-12-31 (AFTER 90-day window)
337
+ {"opportunityId": "opp-5", "name": "Umbrella Health – Renewal",
338
+ "accountId": "account-5", "contactId": None, "amount": 300000,
339
+ "closeDate": "2026-12-31", "stage": "Value Proposition", "probability": 50,
340
+ "ownerId": "user-1"},
341
+ # DISTRACTOR — already Closed Won (renewed in the past, 2026-05-30)
342
+ {"opportunityId": "opp-6", "name": "Hooli – Renewal",
343
+ "accountId": "account-6", "contactId": None, "amount": 95000,
344
+ "closeDate": "2026-05-30", "stage": "Closed Won", "probability": 100,
345
+ "ownerId": "user-1"},
346
+ ]
347
+
348
+ return {
349
+ "user": user_1,
350
+ "users": [user_1],
351
+ "leads": [],
352
+ "accounts": accounts,
353
+ "contacts": contacts,
354
+ "opportunities": opportunities,
355
+ "cases": [],
356
+ "activities": [],
357
+ "chatterPosts": [],
358
+ "files": [],
359
+ "following": [],
360
+ "recentlyViewed": [],
361
+ "dismissedNotifications": [],
362
+ }
363
+
364
+
365
+ # ---------------------------------------------------------------------------
366
+ # NOTION initial state — 'Renewal Tracker 2026' database with ZERO rows
367
+ # ---------------------------------------------------------------------------
368
+ DB_ID = "db-renewal-tracker-2026"
369
+
370
+ NOTION_DB_PROPERTIES = [
371
+ {"id": "prop-account", "name": "Account", "type": "text"},
372
+ {"id": "prop-arr", "name": "ARR", "type": "number"},
373
+ {"id": "prop-date", "name": "Renewal Date", "type": "date"},
374
+ {"id": "prop-risk", "name": "Risk", "type": "select",
375
+ "options": ["Low", "Medium", "High"]},
376
+ {"id": "prop-stage", "name": "Renewal Stage", "type": "select",
377
+ "options": ["Prospecting", "Qualification", "Needs Analysis",
378
+ "Value Proposition", "Proposal", "Negotiation"]},
379
+ ]
380
+
381
+ NOTION_VISIBLE_PROPS = ["prop-account", "prop-arr", "prop-date", "prop-risk", "prop-stage"]
382
+
383
+
384
+ def notion_db_page(items):
385
+ return {
386
+ "id": DB_ID,
387
+ "title": "Renewal Tracker 2026",
388
+ "icon": "\U0001F4CA",
389
+ "cover": None,
390
+ "parentId": None,
391
+ "type": "database",
392
+ "viewType": "table",
393
+ "properties": NOTION_DB_PROPERTIES,
394
+ "views": [{
395
+ "id": "view-table", "name": "Table View", "type": "table",
396
+ "filters": [], "sorts": [], "groupBy": None,
397
+ "visibleProperties": NOTION_VISIBLE_PROPS,
398
+ }],
399
+ "items": list(items),
400
+ "blockIds": [],
401
+ "favorite": False,
402
+ "createdDate": "2026-06-01T09:00:00.000Z",
403
+ }
404
+
405
+
406
+ def notion_state():
407
+ return {
408
+ "user": {"id": "user-1", "name": "Jordan Avery",
409
+ "email": "jordan.avery@vertexcloud.example.com", "avatar": ""},
410
+ "workspace": {"id": "ws-1", "name": "Vertex Cloud Renewals", "icon": "\U0001F3E2",
411
+ "members": ["user-1"]},
412
+ "pages": {
413
+ DB_ID: notion_db_page([]), # ZERO rows pre-task
414
+ },
415
+ "blocks": {},
416
+ "trash": [],
417
+ "comments": {},
418
+ "settings": {"appearance": "light", "startWeekMonday": False, "fontSize": "default"},
419
+ "notifications": [],
420
+ "pageOrder": [DB_ID],
421
+ }
422
+
423
+
424
+ # ---------------------------------------------------------------------------
425
+ # Inject initial state into BOTH mocks (action: "set")
426
+ # ---------------------------------------------------------------------------
427
+ STATE_BUILDERS = {
428
+ 'salesforce': salesforce_state,
429
+ 'notion': notion_state,
430
+ }
431
+
432
+ for name, build in STATE_BUILDERS.items():
433
+ url = MOCKS[name]
434
+ state = build()
435
+ resp = requests.post(f'{url}/post?sid={sid}',
436
+ json={'action': 'set', 'state': state},
437
+ timeout=30, proxies=PROXIES)
438
+ assert resp.status_code == 200, f'{name} injection failed: {resp.status_code} {resp.text}'
439
+ go = requests.get(f'{url}/go?sid={sid}', timeout=15, proxies=PROXIES).json()
440
+ assert go.get('initial_state') is not None, f'{name} initial_state is None after set'
441
+ print(f' injected {name}: initial_state OK')
442
+
443
+ # Sanity: Notion tracker has zero rows pre-task
444
+ ng = requests.get(f'{MOCKS["notion"]}/go?sid={sid}', timeout=15, proxies=PROXIES).json()
445
+ rows = ng['current_state']['pages'][DB_ID]['items']
446
+ assert rows == [], f'Expected 0 rows pre-task, found {len(rows)}'
447
+ print(f' notion tracker rows pre-task: {len(rows)} (correct)')
448
+
449
+ print(f'Both mocks injected with sid={sid}')
450
+
451
+
452
+ # ---------------------------------------------------------------------------
453
+ # GUI-ready: launch Chrome on Salesforce (primary app) through the proxy
454
+ # ---------------------------------------------------------------------------
455
+ def launch_gui(command, delay_sec=1.0):
456
+ env = os.environ.copy()
457
+ env['DISPLAY'] = ':0'
458
+ # Accept both a command string and a pre-split arg list (some tasks
459
+ # build arg lists themselves, e.g. se_hard_008).
460
+ if isinstance(command, str):
461
+ _parts = shlex.split(command)
462
+ else:
463
+ _parts = list(command)
464
+ # Inject CDP debug port so wait_mocks_loaded can verify browser render
465
+ # via Playwright connect_over_cdp. Idempotent: skip if any arg already
466
+ # starts with --remote-debugging-port (some tasks inject their own
467
+ # dynamic port, e.g. se_hard_008).
468
+ if _parts and 'google-chrome' in _parts[0] \
469
+ and not any(p.startswith('--remote-debugging-port') for p in _parts):
470
+ _parts[1:1] = ['--no-first-run', '--no-default-browser-check',
471
+ '--remote-debugging-port=1337']
472
+ _proc = subprocess.Popen(_parts, stdin=subprocess.DEVNULL,
473
+ stdout=subprocess.DEVNULL,
474
+ stderr=subprocess.DEVNULL, env=env,
475
+ start_new_session=True)
476
+ time.sleep(delay_sec)
477
+ if _proc.poll() is not None:
478
+ print(' WARNING: launch_gui process exited early (code=%s)'
479
+ % _proc.returncode)
480
+ return _proc
481
+ _chrome_proxy = f'--proxy-server={PROXY}' if PROXY else ''
482
+ _primary_mock_url = MOCKS["salesforce"]
483
+ launch_gui(f'google-chrome "{MOCKS["salesforce"]}/?sid={sid}"', delay_sec=2.0)
484
+ _open_remaining_mock_tabs(_primary_mock_url)
485
+ wait_mocks_loaded()
486
+ print(f'GUI_READY: launched browser at {MOCKS["salesforce"]}/?sid={sid}')
am_renewal_tracker_003/reward.py ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: Renewals tracker hygiene (Salesforce -> Notion 'Renewal Tracker 2026')
13
+ Task ID: am_renewal_tracker_003
14
+ Domain: mock_websites (notion_mock)
15
+
16
+ This task is FULLY DETERMINISTIC. The agent must add EXACTLY 3 rows to the
17
+ 'Renewal Tracker 2026' Notion database, one per qualifying open renewal that
18
+ closes within 90 days of 2026-06-24 (i.e. closeDate <= 2026-09-22) and is still
19
+ open. Risk is derived from the opportunity's win probability.
20
+
21
+ Expected rows (ground truth):
22
+ 1. Northwind Traders | ARR 120000 | 2026-07-15 | Risk Low | Stage Negotiation
23
+ 2. Globex Corp | ARR 85000 | 2026-08-30 | Risk Medium | Stage Proposal
24
+ 3. Initech | ARR 240000 | 2026-09-10 | Risk High | Stage Qualification
25
+
26
+ Distractors that MUST NOT appear: Soylent Industries (renews 2026-11-20, outside
27
+ window), Umbrella Health (2026-12-31, outside window), Hooli (Closed Won, past).
28
+
29
+ Scoring (programmatic only — NO LLM judge; the judge is unavailable here):
30
+ - 0.30 per correctly-populated expected row (ARR, Renewal Date, Risk,
31
+ Renewal Stage are parsed/normalized), keyed by Account name -> max 0.90
32
+ - 0.10 cleanliness bonus: the database contains EXACTLY 3 rows AND none of the
33
+ distractor accounts are present.
34
+ Total = 1.0
35
+
36
+ Initial state has 0 rows -> every component fails -> 0.0.
37
+ """
38
+
39
+ import os
40
+ import re
41
+ import sys
42
+ from datetime import date, datetime, timedelta
43
+
44
+ import requests
45
+
46
+ NOTION_URL = 'http://28.7.184.198:8166'
47
+ DB_TITLE = 'Renewal Tracker 2026'
48
+ TODAY_TEXT = 'June 24, 2026'
49
+ WINDOW_DAYS = 90
50
+
51
+ # Ground-truth expected rows (derived from task_config business rules, not from peeking).
52
+ EXPECTED_ROWS = [
53
+ {'Account': 'Northwind Traders', 'ARR': 120000, 'Renewal Date': '2026-07-15', 'Risk': 'Low', 'Renewal Stage': 'Negotiation'},
54
+ {'Account': 'Globex Corp', 'ARR': 85000, 'Renewal Date': '2026-08-30', 'Risk': 'Medium', 'Renewal Stage': 'Proposal'},
55
+ {'Account': 'Initech', 'ARR': 240000, 'Renewal Date': '2026-09-10', 'Risk': 'High', 'Renewal Stage': 'Qualification'},
56
+ ]
57
+ DISTRACTOR_ACCOUNTS = {'soylent industries', 'umbrella health', 'hooli'}
58
+
59
+ # ----------------------------------------------------------------------------
60
+ # Read sid
61
+ # ----------------------------------------------------------------------------
62
+ try:
63
+ with open('/tmp/task_web_sid') as f:
64
+ sid = f.read().strip()
65
+ if not sid:
66
+ raise ValueError('sid is empty')
67
+ except Exception as e:
68
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
69
+ print('REWARD: 0.0')
70
+ sys.exit(0)
71
+
72
+ # ----------------------------------------------------------------------------
73
+ # Egress proxy helper (MANDATORY)
74
+ # ----------------------------------------------------------------------------
75
+ PROXY_CANDIDATES = [
76
+ os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy'),
77
+ None,
78
+ ]
79
+
80
+
81
+ def resolve_proxy(probe_url):
82
+ try:
83
+ requests.get(probe_url, timeout=8)
84
+ return None
85
+ except Exception:
86
+ pass
87
+ for candidate in PROXY_CANDIDATES:
88
+ if not candidate:
89
+ continue
90
+ try:
91
+ requests.get(probe_url, timeout=12, proxies={'http': candidate, 'https': candidate})
92
+ return candidate
93
+ except Exception:
94
+ continue
95
+ return None
96
+
97
+
98
+ PROXY = resolve_proxy(f'{NOTION_URL}/go?sid=conn-probe')
99
+ PROXIES = None
100
+ print(f'Egress proxy: {PROXY or "direct"}')
101
+
102
+ # ----------------------------------------------------------------------------
103
+ # Fetch notion state
104
+ # ----------------------------------------------------------------------------
105
+ try:
106
+ data = requests.get(f'{NOTION_URL}/go?sid={sid}', timeout=15, proxies=PROXIES).json()
107
+ except Exception as e:
108
+ print(f'CRITICAL: Cannot fetch notion state: {e}')
109
+ print('REWARD: 0.0')
110
+ sys.exit(0)
111
+
112
+ current = data.get('current_state') or {}
113
+ if not current:
114
+ print('CRITICAL: current_state is None/empty')
115
+ print('REWARD: 0.0')
116
+ sys.exit(0)
117
+
118
+ pages = current.get('pages') or {}
119
+
120
+
121
+ # ----------------------------------------------------------------------------
122
+ # Helpers
123
+ # ----------------------------------------------------------------------------
124
+ MONTHS = {
125
+ 'jan': 1, 'january': 1, 'feb': 2, 'february': 2,
126
+ 'mar': 3, 'march': 3, 'apr': 4, 'april': 4, 'may': 5,
127
+ 'jun': 6, 'june': 6, 'jul': 7, 'july': 7,
128
+ 'aug': 8, 'august': 8, 'sep': 9, 'sept': 9, 'september': 9,
129
+ 'oct': 10, 'october': 10, 'nov': 11, 'november': 11,
130
+ 'dec': 12, 'december': 12,
131
+ }
132
+
133
+ PROPERTY_ALIASES = {
134
+ 'Account': ('Account', 'Account Name', 'Customer', 'Customer Name', 'Company'),
135
+ 'ARR': ('ARR', 'Annual Contract Value', 'Annual Recurring Revenue', 'Amount', 'Contract Value'),
136
+ 'Renewal Date': ('Renewal Date', 'Close Date', 'Closing Date', 'Renewal Close Date', 'Date'),
137
+ 'Risk': ('Risk', 'Risk Level', 'Renewal Risk'),
138
+ 'Renewal Stage': ('Renewal Stage', 'Current Sales Stage', 'Sales Stage', 'Stage'),
139
+ }
140
+
141
+ RISK_ALIASES = {
142
+ 'Low': ('low', 'low risk', 'green', 'healthy'),
143
+ 'Medium': ('medium', 'medium risk', 'med', 'moderate', 'yellow'),
144
+ 'High': ('high', 'high risk', 'at risk', 'red'),
145
+ }
146
+
147
+ STAGE_ALIASES = {
148
+ 'Negotiation': ('negotiation', 'negotiating', 'negotiate'),
149
+ 'Proposal': ('proposal', 'proposal sent', 'proposed'),
150
+ 'Qualification': ('qualification', 'qualified', 'qualifying'),
151
+ }
152
+
153
+
154
+ def text_from_value(v):
155
+ """Extract a display value from common Notion primitive/object shapes."""
156
+ if v is None:
157
+ return ''
158
+ if isinstance(v, (int, float, bool, date, datetime)):
159
+ return str(v)
160
+ if isinstance(v, list):
161
+ parts = [text_from_value(x) for x in v]
162
+ return ' '.join(p for p in parts if p)
163
+ if isinstance(v, dict):
164
+ for key in (
165
+ 'name', 'label', 'plain_text', 'text', 'content', 'title', 'start',
166
+ 'date', 'number', 'value', 'email', 'url',
167
+ ):
168
+ if key in v and v.get(key) not in (None, ''):
169
+ return text_from_value(v.get(key))
170
+ for key in ('rich_text', 'select', 'status'):
171
+ if key in v and v.get(key) not in (None, ''):
172
+ return text_from_value(v.get(key))
173
+ parts = [text_from_value(x) for x in v.values()]
174
+ return ' '.join(p for p in parts if p)
175
+ return str(v)
176
+
177
+
178
+ def norm_str(v):
179
+ return re.sub(r'\s+', ' ', text_from_value(v)).strip()
180
+
181
+
182
+ def canon_text(v):
183
+ return re.sub(r'[^a-z0-9]+', ' ', norm_str(v).lower()).strip()
184
+
185
+
186
+ def norm_num(v):
187
+ """Parse int/float or display strings like '$120,000', '120k', or 'USD 120000'."""
188
+ if v is None:
189
+ return None
190
+ if isinstance(v, (int, float)):
191
+ return float(v)
192
+ s = norm_str(v).lower().replace(',', '')
193
+ s = s.replace('$', '').replace('usd', '').replace('arr', '')
194
+ match = re.search(r'-?\d+(?:\.\d+)?\s*([km])?', s)
195
+ if not match:
196
+ return None
197
+ try:
198
+ number = float(re.match(r'-?\d+(?:\.\d+)?', match.group(0)).group(0))
199
+ except ValueError:
200
+ return None
201
+ suffix = match.group(1)
202
+ if suffix == 'k':
203
+ number *= 1000
204
+ elif suffix == 'm':
205
+ number *= 1000000
206
+ return number
207
+
208
+
209
+ def norm_date(v):
210
+ """Return a date object from common date/datetime strings and Notion date objects."""
211
+ if v is None:
212
+ return None
213
+ if isinstance(v, datetime):
214
+ return v.date()
215
+ if isinstance(v, date):
216
+ return v
217
+ if isinstance(v, dict):
218
+ v = v.get('start') or v.get('date') or ''
219
+ s = norm_str(v)
220
+ if not s:
221
+ return None
222
+ s = re.sub(r'(\d)(st|nd|rd|th)\b', r'\1', s, flags=re.IGNORECASE)
223
+ iso = s.replace('Z', '+00:00')
224
+ try:
225
+ return datetime.fromisoformat(iso).date()
226
+ except ValueError:
227
+ pass
228
+
229
+ numeric = re.search(r'\b(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})\b', s)
230
+ if numeric:
231
+ return build_date(numeric.group(1), numeric.group(2), numeric.group(3))
232
+
233
+ slash = re.search(r'\b(\d{1,2})[-/.](\d{1,2})[-/.](\d{2,4})\b', s)
234
+ if slash:
235
+ first, second, year = slash.groups()
236
+ if int(first) > 12:
237
+ day, month = first, second
238
+ else:
239
+ month, day = first, second
240
+ return build_date(year, month, day)
241
+
242
+ month_first = re.search(r'\b([A-Za-z]+)\s+(\d{1,2})(?:,)?\s+(\d{4})\b', s)
243
+ if month_first and month_first.group(1).lower() in MONTHS:
244
+ month = MONTHS[month_first.group(1).lower()]
245
+ return build_date(month_first.group(3), month, month_first.group(2))
246
+
247
+ day_first = re.search(r'\b(\d{1,2})\s+([A-Za-z]+)(?:,)?\s+(\d{4})\b', s)
248
+ if day_first and day_first.group(2).lower() in MONTHS:
249
+ month = MONTHS[day_first.group(2).lower()]
250
+ return build_date(day_first.group(3), month, day_first.group(1))
251
+
252
+ return None
253
+
254
+
255
+ def build_date(year, month, day):
256
+ try:
257
+ year = int(year)
258
+ if year < 100:
259
+ year += 2000
260
+ return date(year, int(month), int(day))
261
+ except (TypeError, ValueError):
262
+ return None
263
+
264
+
265
+ def find_database(pages_map, title):
266
+ target = canon_text(title)
267
+ for pid, p in pages_map.items():
268
+ if not isinstance(p, dict):
269
+ continue
270
+ if p.get('type') == 'database' and canon_text(p.get('title')) == target:
271
+ return pid, p
272
+ return None, None
273
+
274
+
275
+ def prop_id_by_alias(db, aliases):
276
+ """Resolve a property id from likely display names (case/punctuation-insensitive)."""
277
+ alias_keys = {canon_text(alias) for alias in aliases}
278
+ for prop in db.get('properties', []) or []:
279
+ if canon_text(prop.get('name')) in alias_keys:
280
+ return prop.get('id')
281
+ return None
282
+
283
+
284
+ def prop_value(row, prop_id, aliases=()):
285
+ props = row.get('properties', {}) or {}
286
+ if prop_id and prop_id in props:
287
+ return props.get(prop_id)
288
+
289
+ alias_keys = {canon_text(alias) for alias in aliases}
290
+ for key, value in props.items():
291
+ if canon_text(key) in alias_keys:
292
+ return value
293
+ for alias in aliases:
294
+ if alias in row:
295
+ return row.get(alias)
296
+ return None
297
+
298
+
299
+ def row_account_name(row, account_pid):
300
+ """Account may live in the Account property OR in the page title."""
301
+ value = prop_value(row, account_pid, PROPERTY_ALIASES['Account'])
302
+ if value not in (None, ''):
303
+ return norm_str(value)
304
+ return norm_str(row.get('title'))
305
+
306
+
307
+ def account_matches(candidate, expected):
308
+ candidate_key = company_key(candidate)
309
+ expected_key = company_key(expected)
310
+ return (
311
+ candidate_key == expected_key
312
+ or expected_key in candidate_key
313
+ or candidate_key in expected_key
314
+ )
315
+
316
+
317
+ def company_key(value):
318
+ tokens = ['corp' if token == 'corporation' else token
319
+ for token in canon_text(value).split()]
320
+ return ' '.join(tokens)
321
+
322
+
323
+ def select_matches(value, expected, aliases):
324
+ value_key = canon_text(value)
325
+ expected_key = canon_text(expected)
326
+ if value_key == expected_key or expected_key in value_key:
327
+ return True
328
+ return any(canon_text(alias) == value_key or canon_text(alias) in value_key
329
+ for alias in aliases.get(expected, ()))
330
+
331
+
332
+ def verify_task():
333
+ total_score = 0.0
334
+ today = norm_date(TODAY_TEXT)
335
+ cutoff = today + timedelta(days=WINDOW_DAYS) if today else None
336
+
337
+ # Precondition gate: the database must exist.
338
+ db_id, db = find_database(pages, DB_TITLE)
339
+ if db is None:
340
+ print(f"CRITICAL: database titled '{DB_TITLE}' not found")
341
+ print('REWARD: 0.0')
342
+ return 0.0
343
+
344
+ # Resolve property ids by name/alias (robust to differing prop-id schemes).
345
+ pid_account = prop_id_by_alias(db, PROPERTY_ALIASES['Account'])
346
+ pid_arr = prop_id_by_alias(db, PROPERTY_ALIASES['ARR'])
347
+ pid_date = prop_id_by_alias(db, PROPERTY_ALIASES['Renewal Date'])
348
+ pid_risk = prop_id_by_alias(db, PROPERTY_ALIASES['Risk'])
349
+ pid_stage = prop_id_by_alias(db, PROPERTY_ALIASES['Renewal Stage'])
350
+
351
+ # Collect rows: prefer the database's ordered items list, fall back to
352
+ # any page whose parentId points at this database.
353
+ item_ids = db.get('items') or []
354
+ rows = [pages[i] for i in item_ids if i in pages and isinstance(pages[i], dict)]
355
+ if not rows:
356
+ rows = [p for pid, p in pages.items()
357
+ if isinstance(p, dict) and p.get('parentId') == db_id and p.get('type') != 'database']
358
+
359
+ print(f'Found {len(rows)} row(s) in database "{DB_TITLE}"')
360
+
361
+ # --- Components 1-3: each expected row, all required fields correct (0.30 each) ---
362
+ for idx, exp in enumerate(EXPECTED_ROWS, start=1):
363
+ try:
364
+ row = next(
365
+ (r for r in rows
366
+ if account_matches(row_account_name(r, pid_account), exp['Account'])),
367
+ None,
368
+ )
369
+ if row is None:
370
+ print(f"FAIL: Component {idx} — row for account '{exp['Account']}' not found")
371
+ continue
372
+
373
+ arr_value = prop_value(row, pid_arr, PROPERTY_ALIASES['ARR'])
374
+ date_value = prop_value(row, pid_date, PROPERTY_ALIASES['Renewal Date'])
375
+ risk_value = prop_value(row, pid_risk, PROPERTY_ALIASES['Risk'])
376
+ stage_value = prop_value(row, pid_stage, PROPERTY_ALIASES['Renewal Stage'])
377
+
378
+ expected_date = norm_date(exp['Renewal Date'])
379
+ actual_date = norm_date(date_value)
380
+ arr_ok = norm_num(arr_value) == float(exp['ARR'])
381
+ date_ok = (
382
+ actual_date == expected_date
383
+ and today is not None
384
+ and cutoff is not None
385
+ and today <= actual_date <= cutoff
386
+ )
387
+ risk_ok = select_matches(risk_value, exp['Risk'], RISK_ALIASES)
388
+ stage_ok = select_matches(stage_value, exp['Renewal Stage'], STAGE_ALIASES)
389
+
390
+ if arr_ok and date_ok and risk_ok and stage_ok:
391
+ print(f"PASS: Component {idx} — '{exp['Account']}' fully correct "
392
+ f"(ARR={exp['ARR']}, Date={exp['Renewal Date']}, Risk={exp['Risk']}, Stage={exp['Renewal Stage']}) (0.30 pts)")
393
+ total_score += 0.30
394
+ else:
395
+ print(f"FAIL: Component {idx} — '{exp['Account']}' field mismatch: "
396
+ f"ARR_ok={arr_ok}(got {arr_value!r}), "
397
+ f"Date_ok={date_ok}(got {actual_date!r}), "
398
+ f"Risk_ok={risk_ok}(got {risk_value!r}), "
399
+ f"Stage_ok={stage_ok}(got {stage_value!r})")
400
+ except Exception as e:
401
+ print(f'ERROR: Component {idx} — {e}')
402
+
403
+ # --- Component 4: cleanliness — exactly 3 rows AND no distractors (0.10) ---
404
+ try:
405
+ present_accounts = [row_account_name(r, pid_account) for r in rows]
406
+ distractors_present = {
407
+ distractor
408
+ for distractor in DISTRACTOR_ACCOUNTS
409
+ if any(account_matches(account, distractor) for account in present_accounts)
410
+ }
411
+ exact_count = (len(rows) == 3)
412
+ if exact_count and not distractors_present:
413
+ print('PASS: Component 4 — exactly 3 rows, no distractor accounts (0.10 pts)')
414
+ total_score += 0.10
415
+ else:
416
+ print(f'FAIL: Component 4 — row_count={len(rows)} (expected 3), '
417
+ f'distractors_present={sorted(distractors_present)}')
418
+ except Exception as e:
419
+ print(f'ERROR: Component 4 — {e}')
420
+
421
+ final_score = round(min(total_score, 1.0), 4)
422
+ print(f'\nScore: {total_score}/1.0')
423
+ print(f'REWARD: {final_score}')
424
+ return final_score
425
+
426
+
427
+ verify_task()
am_renewal_tracker_003/reward_label.json ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/am_renewal_tracker_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-03 19:42:48",
7
+ "label": {
8
+ "task_id": "am_renewal_tracker_003",
9
+ "domain": "mock_websites",
10
+ "summary": "验证 agent 是否向 Notion 数据库 'Renewal Tracker 2026' 正确添加了恰好 3 条符合条件的续约跟踪记录,且未包含干扰项",
11
+ "is_placeholder": false,
12
+ "data_sources": [
13
+ "/tmp/task_web_sid",
14
+ "notion_mock (http://28.7.186.212:8186)"
15
+ ],
16
+ "scoring_components": [
17
+ {
18
+ "name": "Component 1 (Northwind Traders)",
19
+ "weight": 0.3,
20
+ "description": "检查是否存在 Northwind Traders 账户对应的记录,且 ARR、Renewal Date、Risk、Renewal Stage 四个字段与预期值完全匹配",
21
+ "check_logic": "在数据库行中通过 account_matches 查找账户名匹配的行,提取 ARR、Renewal Date、Risk、Renewal Stage 字段值,分别使用 norm_num、norm_date、select_matches 与预期值比较;其中日期还需满足 today(2026-06-24) <= actual_date <= cutoff(2026-09-22)",
22
+ "pass_condition": "找到该行且 arr_ok=True、date_ok=True、risk_ok=True、stage_ok=True"
23
+ },
24
+ {
25
+ "name": "Component 2 (Globex Corp)",
26
+ "weight": 0.3,
27
+ "description": "检查是否存在 Globex Corp 账户对应的记录,且四个字段与预期值完全匹配",
28
+ "check_logic": "同 Component 1,预期 ARR=85000、Date=2026-08-30、Risk=Medium、Stage=Proposal",
29
+ "pass_condition": "找到该行且四个字段全部匹配"
30
+ },
31
+ {
32
+ "name": "Component 3 (Initech)",
33
+ "weight": 0.3,
34
+ "description": "检查是否存在 Initech 账户对应的记录,且四个字段与预期值完全匹配",
35
+ "check_logic": "同 Component 1,预期 ARR=240000、Date=2026-09-10、Risk=High、Stage=Qualification",
36
+ "pass_condition": "找到该行且四个字段全部匹配"
37
+ },
38
+ {
39
+ "name": "Component 4 (Cleanliness)",
40
+ "weight": 0.1,
41
+ "description": "检查数据库总行数是否恰好为 3,且不存在任何干扰账户",
42
+ "check_logic": "检查 len(rows)==3;遍历所有行的账户名,与 DISTRACTOR_ACCOUNTS ('soylent industries', 'umbrella health', 'hooli') 进行 account_matches 比对,确认无匹配项",
43
+ "pass_condition": "总行数等于 3 且 distractors_present 为空集合"
44
+ }
45
+ ],
46
+ "total_max_score": 1.0,
47
+ "score_aggregation": "各组件分数累加,最终通过 round(min(total_score, 1.0), 4) 计算,上限钳制在 1.0",
48
+ "failure_modes": [
49
+ "无法从 /tmp/task_web_sid 读取 sid 或 sid 为空 -> 打印 CRITICAL 并返回 0.0",
50
+ "无法通过 HTTP GET 获取 notion_mock 状态 -> 打印 CRITICAL 并返回 0.0",
51
+ "current_state 为空或不存在 -> 打印 CRITICAL 并返回 0.0",
52
+ "未找到标题为 'Renewal Tracker 2026' 的数据库 -> 打印 CRITICAL 并返回 0.0",
53
+ "某预期账户对应的行未找到 -> 该 Component 不得分",
54
+ "某预期账户字段解析或匹配失败 -> 该 Component 不得分",
55
+ "数据库行数不等于 3 或存在干扰账户 -> Component 4 不得分"
56
+ ],
57
+ "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后通过 HTTP 请求拉取 notion_mock 的当前状态。在返回的 JSON 中找到名为 'Renewal Tracker 2026' 的数据库,并收集其所有行记录(优先使用 db.items,否则回退到 parentId 匹配)。接着逐项检查 3 个预期账户(Northwind Traders、Globex Corp、Initech)是否存在,且 ARR、Renewal Date、Risk、Renewal Stage 四个字段与预期一致(日期还需落在 2026-06-24 至 2026-09-22 的 90 天窗口内),每通过一项加 0.30 分。最后检查清洁度:数据库必须恰好有 3 行且不含任何干扰账户(Soylent Industries、Umbrella Health、Hooli),通过则加 0.10 分。总分累加后通过 min 钳制在 1.0,再四舍五入到 4 位小数作为最终 REWARD 输出。",
58
+ "confidence": 1.0
59
+ },
60
+ "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码:\n\n1. **Task ID**: 从 docstring 中可以看到 `Task ID: am_renewal_tracker_001`\n2. **Domain**: 从 docstring 中可以看到 `Domain: mock_websites (notion_mock)`\n3. **Summary**: 这个任务要求 agent 向 Notion 数据库 \"Renewal Tracker 2026\" 添加恰好 3 行数据,对应特定的 Salesforce 续约机会。\n4. **is_placeholder**: false,因为脚本有详细的评分逻辑。\n5. **data_sources**: 脚本从 `/tmp/task_web_sid` 读取 sid,然后向 `http://28.7.186.212:8166/go?sid={sid}` 发送请求获取 Notion mock 状态。\n6. **scoring_components**:\n - Component 1-3: 每���预期行(Northwind Traders, Globex Corp, Initech)正确填充所有字段(ARR, Renewal Date, Risk, Renewal Stage),每个 0.30 分。\n - Component 4: 清洁度奖励,数据库恰好有 3 行且没有干扰账户,0.10 分。\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 累加,然后 `min(total_score, 1.0)` 并四舍五入到 4 位小数。\n9. **failure_modes**:\n - 无法读取 sid -> 0.0\n - 无法获取 Notion 状态 -> 0.0\n - current_state 为空 -> 0.0\n - 找不到数据库 -> 0.0\n - 行数不对或有干扰账户 -> Component 4 失败\n - 字段不匹配 -> 对应 Component 失败\n10. **scoring_logic_explanation**: 按执行顺序说明。\n11. **confidence**: 1.0,因为代码逻辑清晰。\n\n让我详细检查每个组件:\n\n**Component 1-3**:\n- 遍历 EXPECTED_ROWS(3个账户)\n- 在数据库行中查找匹配账户名的行\n- 检查 ARR: `norm_num(arr_value) == float(exp['ARR'])`\n- 检查 Date: `actual_date == expected_date` 且 `today <= actual_date <= cutoff`(2026-06-24 到 2026-09-22)\n- 检查 Risk: `select_matches` 使用 RISK_ALIASES\n- 检查 Stage: `select_matches` 使用 STAGE_ALIASES\n- 全部通过得 0.30\n\n**Component 4**:\n- `exact_count = (len(rows) == 3)`\n- 检查是否有 DISTRACTOR_ACCOUNTS 中的账户存在\n- 如果恰好3行且无干扰账户,得 0.10\n\n**数据获取**:\n- 从 `/tmp/task_web_sid` 读取 sid\n- 通过 `requests.get(f'{NOTION_URL}/go?sid={sid}')` 获取状态\n- 解析 `current_state.pages`\n- 查找数据库 `Renewal Tracker 2026`\n- 收集行:优先使用 `db.get('items')`,否则查找 `parentId == db_id` 的页面\n\n**字段解析**:\n- 支持多种属性名别名(PROPERTY_ALIASES)\n- 支持多种风险/阶段别名\n- 支持多种日期格式和数字格式\n\n现在构建 JSON:\n\n```json\n{\n \"task_id\": \"am_renewal_tracker_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证 agent 是否向 Notion 数据库 'Renewal Tracker 2026' 正确添加了恰好 3 条符合条件的续约跟踪记录,且未包含干扰项\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"notion_mock (http://28.7.186.212:8186)\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 1 (Northwind Traders)\",\n \"weight\": 0.3,\n \"description\": \"检查是否存在 Northwind Traders 账户对应的记录,且 ARR、Renewal Date、Risk、Renewal Stage 四个字段与预期值完全匹配\",\n \"check_logic\": \"在数据库行中查找 account_matches 的行,提取 ARR、Renewal Date、Risk、Renewal Stage 字段值,分别用 norm_num、norm_date、select_matches 与预期值比较;日期还需满足 today(2026-06-24) <= actual_date <= cutoff(2026-09-22)\",\n \"pass_condition\": \"找到该行且 arr_ok=True, date_ok=True, risk_ok=True, stage_ok=True\"\n },\n {\n \"name\": \"Component 2 (Globex Corp)\",\n \"weight\": 0.3,\n \"description\": \"检查是否存在 Globex Corp 账户对应的记录,且四个字段与预期值完全匹配\",\n \"check_logic\": \"同 Component 1,预期 ARR=85000, Date=2026-08-30, Risk=Medium, Stage=Proposal\",\n \"pass_condition\": \"找到该行且四个字段全部匹配\"\n },\n {\n \"name\": \"Component 3 (Initech)\",\n \"weight\": 0.3,\n \"description\": \"检查是否存在 Initech 账户对应的记录,且四个字段与预期值完全匹配\",\n \"check_logic\": \"同 Component 1,预期 ARR=240000, Date=2026-09-10, Risk=High, Stage=Qualification\",\n \"pass_condition\": \"找到该行且四个字段全部匹配\"\n },\n {\n \"name\": \"Component 4 (Cleanliness)\",\n \"weight\": 0.1,\n \"description\": \"检查数据库总行数是否恰好为 3,且不存在任何干扰账户\",\n \"check_logic\": \"检查 len(rows)==3;遍历所有行的账户名,与 DISTRACTOR_ACCOUNTS ('soylent industries', 'umbrella health', 'hooli') 进行 account_matches 比对,确认无匹配\",\n \"pass_condition\": \"总行数等于 3 且 distractors_present 为空集合\"\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 读取 sid 或 sid 为空 -> 打印 CRITICAL 并返回 0.0\",\n \"无法通过 HTTP GET 获取 notion mock 状态 -> 打印 CRITICAL 并返回 0.0\",\n \"current_state 为空或不存在 -> 打印 CRITICAL 并返回 0.0\",\n \"未找到标题为 'Renewal Tracker 2026' 的数据库 -> 打印 CRITICAL 并返回 0.0\",\n \"某预期账户对应的行未找到 -> 该 Component 不得分\",\n \"某预期账户字段解析或匹配失败 -> 该 Component 不得分\",\n \"数据库行数不等于 3 或存在干扰账户 -> Component 4 不得分\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后通过 HTTP 请求拉取 notion_mock 的当前状态。在状态中��到名为 'Renewal Tracker 2026' 的数据库,收集其所有行记录。接着逐项检查 3 个预期账户(Northwind Traders、Globex Corp、Initech)是否存在且 ARR、Renewal Date、Risk、Renewal Stage 四个字段与预期一致(日期还需落在 2026-06-24 至 2026-09-22 窗口内),每通过一项加 0.30 分。最后检查清洁度:数据库必须恰好有 3 行且不含任何干扰账户(Soylent Industries、Umbrella Health、Hooli),通过则加 0.10 分。总分累加后钳制在 1.0 并四舍五入到 4 位小数作为最终 REWARD。\",\n \"confidence\": 1.0\n}\n```\n\n检查要求:\n- 只输出 JSON,没有 markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 字符串 value 使用中文,task_id、domain、字段名保留原样\n- weight 填写显式分值:0.30 和 0.10\n- is_placeholder: false\n\n确认 domain:docstring 写的是 `Domain: mock_websites (notion_mock)`,所以 domain 应该是 `mock_websites`。\n\n确认 task_id:`am_renewal_tracker_001`。\n\n确认 data_sources:`/tmp/task_web_sid` 和 `http://28.7.186.212:8166`(notion_mock)。\n\n确认评分逻辑中的日期检查:`today <= actual_date <= cutoff`,其中 today 是 2026-06-24,cutoff 是 today + 90 天 = 2026-09-22。这在代码中通过 `norm_date(TODAY_TEXT)` 和 `timedelta(days=WINDOW_DAYS)` 计算。\n\n确认数字解析:`norm_num` 会处理 `$120,000`、`120k` 等格式。\n\n确认属性别名:PROPERTY_ALIASES 中定义了多种可能的列名。\n\n一切看起来都正确。 </think> {\"task_id\":\"am_renewal_tracker_001\",\"domain\":\"mock_websites\",\"summary\":\"验证 agent 是否向 Notion 数据库 'Renewal Tracker 2026' 正确添加了恰好 3 条符合条件的续约跟踪记录,且未包含干扰项\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"notion_mock (http://28.7.186.212:8186)\"],\"scoring_components\":[{\"name\":\"Component 1 (Northwind Traders)\",\"weight\":0.3,\"description\":\"检查是否存在 Northwind Traders 账户对应的记录,且 ARR、Renewal Date、Risk、Renewal Stage 四个字段与预期值完全匹配\",\"check_logic\":\"在数据库行中通过 account_matches 查找账户名匹配的行,提取 ARR、Renewal Date、Risk、Renewal Stage 字段值,分别使用 norm_num、norm_date、select_matches 与预期值比较;其中日期还需满足 today(2026-06-24) <= actual_date <= cutoff(2026-09-22)\",\"pass_condition\":\"找到该行且 arr_ok=True、date_ok=True、risk_ok=True、stage_ok=True\"},{\"name\":\"Component 2 (Globex Corp)\",\"weight\":0.3,\"description\":\"检查是否存在 Globex Corp 账户对应的记录,且四个字段与预期值完全匹配\",\"check_logic\":\"同 Component 1,预期 ARR=85000、Date=2026-08-30、Risk=Medium、Stage=Proposal\",\"pass_condition\":\"找到该行且四个字段全部匹配\"},{\"name\":\"Component 3 (Initech)\",\"weight\":0.3,\"description\":\"检查是否存在 Initech 账户对应的记录,且四个字段与预期值完全匹配\",\"check_logic\":\"同 Component 1,预期 ARR=240000、Date=2026-09-10、Risk=High、Stage=Qualification\",\"pass_condition\":\"找到该行且四个字段全部匹配\"},{\"name\":\"Component 4 (Cleanliness)\",\"weight\":0.1,\"description\":\"检查数据库总行数是否恰好为 3,且不存在任何干扰账户\",\"check_logic\":\"检查 len(rows)==3;遍历所有行的账户名,与 DISTRACTOR_ACCOUNTS ('soylent industries', 'umbrella health', 'hooli') 进行 account_matches 比对,确认无匹配项\",\"pass_condition\":\"总行数等于 3 且 distractors_present 为空集合\"}],\"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 并返回 0.0\",\"无法通过 HTTP GET 获取 notion_mock 状态 -> 打印 CRITICAL 并返回 0.0\",\"current_state 为空或不存在 -> 打印 CRITICAL 并返回 0.0\",\"未找到标题为 'Renewal Tracker 2026' 的数据库 -> 打印 CRITICAL 并返回 0.0\",\"某预期账户对应的行未找到 -> 该 Component 不得分\",\"某预期账户字段解析或匹配失败 -> 该 Component 不得分\",\"数据库行数不等于 3 或存在干扰账户 -> Component 4 不得分\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后通过 HTTP 请求拉取 notion_mock 的当前状态。在返回的 JSON 中找到名为 'Renewal Tracker 2026' 的数据库,并收集其所有行记录(优先使用 db.items,否则回退到 parentId 匹配)。接着逐项检查 3 个预期账户(Northwind Traders、Globex Corp、Initech)是否存在,且 ARR、Renewal Date、Risk、Renewal Stage 四个字段与预期一致(日期还需落在 2026-06-24 至 2026-09-22 的 90 天窗口内),每通过一项加 0.30 分。最后检查清洁度:数据库必须恰好有 3 行且不含任何干扰账户(Soylent Industries、Umbrella Health、Hooli),通过则�� 0.10 分。总分累加后通过 min 钳制在 1.0,再四舍五入到 4 位小数作为最终 REWARD 输出。\",\"confidence\":1.0}"
61
+ }
ar_approval_002/_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_approval_002/initial_setup.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: Salesforce -> Slack discount-approval chain (Hooli Data Migration)
3
+ Task ID: ar_approval_002
4
+ Domain: mock_websites (multi-mock: salesforce_mock + slack_mock)
5
+
6
+ Initial state:
7
+ - Salesforce: opportunity 'Hooli Data Migration' (list price $90,000,
8
+ proposed/discounted amount $72,000, owner Jian Wu, account Hooli).
9
+ - Slack: #finance-approvals channel exists but contains NO approval message.
10
+ """
11
+ import os
12
+ import shlex
13
+ import subprocess
14
+ import time
15
+ import uuid
16
+
17
+ import requests
18
+
19
+ SF_URL = 'http://28.7.184.198:8175'
20
+ SLACK_URL = 'http://28.7.184.198:8178'
21
+
22
+ # --- Session id (shared across both mocks) ---
23
+ sid = str(uuid.uuid4())
24
+ with open('/tmp/task_web_sid', 'w') as f:
25
+ f.write(sid)
26
+
27
+
28
+ def launch_gui(command, delay_sec=1.0):
29
+ env = os.environ.copy()
30
+ env['DISPLAY'] = ':0'
31
+ subprocess.Popen(
32
+ shlex.split(command),
33
+ stdout=subprocess.DEVNULL,
34
+ stderr=subprocess.DEVNULL,
35
+ env=env,
36
+ )
37
+ time.sleep(delay_sec)
38
+
39
+
40
+ # =====================================================================
41
+ # Salesforce state
42
+ # =====================================================================
43
+ sf_user = {
44
+ "userId": "user-1", "firstName": "John", "lastName": "Smith",
45
+ "email": "john.smith@company.com", "phone": "(555) 123-4567",
46
+ "title": "Sales Manager", "department": "Sales", "role": "Manager",
47
+ "avatar": "https://i.pravatar.cc/150?u=user-1",
48
+ "timezone": "America/New_York", "locale": "en-US", "theme": "lightning",
49
+ }
50
+ sf_users = [
51
+ sf_user,
52
+ {
53
+ "userId": "user-2", "firstName": "Jian", "lastName": "Wu",
54
+ "email": "jian.wu@company.com", "phone": "(555) 234-5678",
55
+ "title": "Account Executive", "department": "Sales", "role": "User",
56
+ "avatar": "https://i.pravatar.cc/150?u=user-2",
57
+ "timezone": "America/Los_Angeles", "locale": "en-US", "theme": "lightning",
58
+ },
59
+ {
60
+ "userId": "user-3", "firstName": "Priya", "lastName": "Natarajan",
61
+ "email": "priya.natarajan@company.com", "phone": "(555) 345-6789",
62
+ "title": "Account Executive", "department": "Sales", "role": "User",
63
+ "avatar": "https://i.pravatar.cc/150?u=user-3",
64
+ "timezone": "America/Chicago", "locale": "en-US", "theme": "lightning",
65
+ },
66
+ ]
67
+
68
+ sf_accounts = [
69
+ {
70
+ "accountId": "account-1", "name": "Hooli", "phone": "(650) 555-0142",
71
+ "website": "https://hooli.com", "type": "Customer", "industry": "Technology",
72
+ "revenue": 120000000, "employees": 1200,
73
+ "description": "Large technology company; active enterprise account.",
74
+ "ownerId": "user-2",
75
+ "billingStreet": "1100 Bridgepointe Pkwy", "billingCity": "San Mateo",
76
+ "billingState": "CA", "billingZip": "94404", "billingCountry": "United States",
77
+ "shippingStreet": "1100 Bridgepointe Pkwy", "shippingCity": "San Mateo",
78
+ "shippingState": "CA", "shippingZip": "94404", "shippingCountry": "United States",
79
+ "createdDate": "2025-02-11T09:00:00.000Z", "modifiedDate": "2026-06-01T09:00:00.000Z",
80
+ },
81
+ {
82
+ "accountId": "account-2", "name": "Initech", "phone": "(512) 555-0199",
83
+ "website": "https://initech.com", "type": "Customer", "industry": "Finance",
84
+ "revenue": 40000000, "employees": 300,
85
+ "description": "Mid-market financial software firm.",
86
+ "ownerId": "user-3",
87
+ "billingStreet": "4120 Freidrich Ln", "billingCity": "Austin",
88
+ "billingState": "TX", "billingZip": "78744", "billingCountry": "United States",
89
+ "shippingStreet": "4120 Freidrich Ln", "shippingCity": "Austin",
90
+ "shippingState": "TX", "shippingZip": "78744", "shippingCountry": "United States",
91
+ "createdDate": "2025-08-20T09:00:00.000Z", "modifiedDate": "2026-05-15T09:00:00.000Z",
92
+ },
93
+ ]
94
+
95
+ sf_contacts = [
96
+ {
97
+ "contactId": "contact-1", "accountId": "account-1", "firstName": "Gavin",
98
+ "lastName": "Belson", "title": "CEO", "department": "Executive",
99
+ "email": "gavin.belson@hooli.com", "phone": "(650) 555-0143", "ownerId": "user-2",
100
+ },
101
+ {
102
+ "contactId": "contact-2", "accountId": "account-2", "firstName": "Bill",
103
+ "lastName": "Lumbergh", "title": "VP Operations", "department": "Operations",
104
+ "email": "bill.lumbergh@initech.com", "phone": "(512) 555-0188", "ownerId": "user-3",
105
+ },
106
+ ]
107
+
108
+ sf_opportunities = [
109
+ {
110
+ "opportunityId": "opp-1", "name": "Hooli Data Migration",
111
+ "accountId": "account-1", "contactId": "contact-1",
112
+ "amount": 72000,
113
+ "closeDate": "2026-09-30T00:00:00.000Z",
114
+ "stage": "Negotiation", "probability": 75, "type": "New Business",
115
+ "leadSource": "Partner Referral",
116
+ "nextStep": "Finalize pricing and obtain discount approval",
117
+ "description": (
118
+ "Enterprise data migration engagement for Hooli. Standard list price is "
119
+ "$90,000. Customer has requested a proposed (discounted) price of $72,000."
120
+ ),
121
+ "ownerId": "user-2",
122
+ "createdDate": "2026-05-05T09:00:00.000Z", "modifiedDate": "2026-06-28T09:00:00.000Z",
123
+ },
124
+ {
125
+ "opportunityId": "opp-2", "name": "Initech Cloud Upgrade",
126
+ "accountId": "account-2", "contactId": "contact-2",
127
+ "amount": 35000,
128
+ "closeDate": "2026-08-15T00:00:00.000Z",
129
+ "stage": "Qualification", "probability": 40, "type": "Existing Business",
130
+ "leadSource": "Website",
131
+ "nextStep": "Schedule technical scoping call",
132
+ "description": "Cloud infrastructure upgrade for Initech.",
133
+ "ownerId": "user-3",
134
+ "createdDate": "2026-06-01T09:00:00.000Z", "modifiedDate": "2026-06-20T09:00:00.000Z",
135
+ },
136
+ ]
137
+
138
+ sf_state = {
139
+ "user": sf_user,
140
+ "users": sf_users,
141
+ "leads": [],
142
+ "accounts": sf_accounts,
143
+ "contacts": sf_contacts,
144
+ "opportunities": sf_opportunities,
145
+ "cases": [],
146
+ "activities": [],
147
+ "chatterPosts": [],
148
+ "files": [],
149
+ "following": [],
150
+ "recentlyViewed": [],
151
+ "dismissedNotifications": [],
152
+ "dashboards": [],
153
+ "emailDrafts": [],
154
+ "reportSnapshots": [],
155
+ }
156
+
157
+ # =====================================================================
158
+ # Slack state
159
+ # =====================================================================
160
+ slack_current_user = {
161
+ "userId": "user_1", "fullName": "John Smith", "displayName": "John",
162
+ "email": "john.smith@company.com",
163
+ "avatar": "https://picsum.photos/200/200?random=1",
164
+ "title": "Sales Manager", "status": "online",
165
+ "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York",
166
+ }
167
+ slack_users = [
168
+ slack_current_user,
169
+ {"userId": "user_2", "fullName": "Sarah Johnson", "displayName": "Sarah",
170
+ "email": "sarah.johnson@company.com", "avatar": "https://picsum.photos/200/200?random=2",
171
+ "title": "Finance Manager", "status": "online", "statusMessage": "", "statusEmoji": "",
172
+ "timeZone": "America/New_York"},
173
+ {"userId": "user_3", "fullName": "Mike Chen", "displayName": "Mike",
174
+ "email": "mike.chen@company.com", "avatar": "https://picsum.photos/200/200?random=3",
175
+ "title": "Controller", "status": "away", "statusMessage": "", "statusEmoji": "",
176
+ "timeZone": "America/Los_Angeles"},
177
+ ]
178
+
179
+ slack_channels = [
180
+ {"channelId": "general", "name": "general",
181
+ "description": "Company-wide announcements and general discussion",
182
+ "topic": "Company-wide announcements", "isPrivate": False, "isStarred": True,
183
+ "members": ["user_1", "user_2", "user_3"], "createdBy": "user_1",
184
+ "createdAt": "2024-01-01T10:00:00Z", "pinnedMessages": [], "unreadCount": 0},
185
+ {"channelId": "finance-approvals", "name": "finance-approvals",
186
+ "description": "Discount and pricing approval requests for finance sign-off",
187
+ "topic": "Pricing / discount approvals", "isPrivate": False, "isStarred": False,
188
+ "members": ["user_1", "user_2", "user_3"], "createdBy": "user_2",
189
+ "createdAt": "2025-11-03T08:00:00Z", "pinnedMessages": [], "unreadCount": 0},
190
+ ]
191
+
192
+ slack_messages = {
193
+ "general": [
194
+ {"messageId": "msg_g1", "senderId": "user_2",
195
+ "content": "Reminder: Q3 pricing review is this Friday.",
196
+ "timestamp": "2026-06-29T15:00:00Z", "threadId": None,
197
+ "reactions": [], "attachments": [], "isEdited": False},
198
+ ],
199
+ "finance-approvals": [],
200
+ }
201
+
202
+ slack_state = {
203
+ "currentUser": slack_current_user,
204
+ "workspace": {"workspaceId": "ws_1", "workspaceName": "Acme Corp",
205
+ "icon": "https://picsum.photos/64/64?random=workspace"},
206
+ "users": slack_users,
207
+ "channels": slack_channels,
208
+ "messages": slack_messages,
209
+ "threads": {},
210
+ "dms": [],
211
+ "bookmarkedMessages": [],
212
+ "callHistory": [],
213
+ "settings": {"theme": "light", "notifications": "all",
214
+ "displayDensity": "comfortable", "showAvatars": True, "use24Hour": False},
215
+ "invitations": [],
216
+ "notifications": [],
217
+ }
218
+
219
+ # =====================================================================
220
+ # Inject state into both mocks (action: set -> writes initial + current)
221
+ # =====================================================================
222
+ for name, url, state in [
223
+ ("salesforce", SF_URL, sf_state),
224
+ ("slack", SLACK_URL, slack_state),
225
+ ]:
226
+ resp = requests.post(f'{url}/post?sid={sid}',
227
+ json={'action': 'set', 'state': state}, timeout=30)
228
+ assert resp.status_code == 200, f'{name} state injection failed: {resp.text}'
229
+ go = requests.get(f'{url}/go?sid={sid}', timeout=10).json()
230
+ assert go['initial_state'] is not None, f'{name} initial_state is None after injection'
231
+ print(f'State injected: {name} sid={sid}')
232
+
233
+ # =====================================================================
234
+ # Launch browser with both mocks (Salesforce first, then Slack tab)
235
+ # =====================================================================
236
+ launch_gui(
237
+ f'google-chrome "{SF_URL}/?sid={sid}" "{SLACK_URL}/?sid={sid}"',
238
+ delay_sec=3.0,
239
+ )
240
+ print(f'GUI_READY: launched browser with salesforce + slack (sid={sid})')
ar_approval_002/reward.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: Post a structured discount-approval request in Slack #finance-approvals
3
+ Task ID: ar_approval_002
4
+ Domain: mock_websites (Salesforce -> Slack chaining; observable state in Slack)
5
+
6
+ Task outcome (from task_config.json):
7
+ A single structured message in Slack #finance-approvals containing ALL of:
8
+ - Customer = Hooli
9
+ - Original (list) Amount = $90,000
10
+ - Adjusted (proposed) Amount = $72,000
11
+ - Discount = 20%
12
+ - Requester = Jian Wu
13
+ - A note that it exceeds the 15% threshold and needs approval / sign-off
14
+ Salesforce must remain read-only / unchanged.
15
+
16
+ Scoring (all components anchored to the NEW message in #finance-approvals, which is
17
+ absent in initial_env -> every component FAILS on initial_env -> reward(initial)=0.0):
18
+ C1 new message present in #finance-approvals .......... 0.15
19
+ C2 Customer = Hooli ................................... 0.15
20
+ C3 Original amount $90,000 ............................ 0.15
21
+ C4 Adjusted amount $72,000 ........................... 0.15
22
+ C5 Discount 20% ...................................... 0.15
23
+ C6 Requester Jian Wu ................................. 0.15
24
+ C7 Note: exceeds 15% threshold / needs approval ...... 0.10
25
+ Total = 1.0
26
+
27
+ Salesforce-unchanged is a PRECONDITION (true in both initial and golden), so it is
28
+ used only as a non-scoring integrity gate: if the Hooli opportunity's figures were
29
+ mutated, the score is zeroed (anti-cheat). It never affects golden(1.0)/initial(0.0).
30
+
31
+ All checks are deterministic. No LLM judge is used (OPENAI_API_KEY is EMPTY on the VM).
32
+ """
33
+
34
+ import os
35
+ import re
36
+ import sys
37
+
38
+ # The VM can only reach the mocks via the corporate proxy. Set it explicitly so
39
+ # `requests` uses it regardless of how the script's environment was spawned.
40
+ PROXY = 'http://star-proxy.oa.com:3128'
41
+ os.environ['http_proxy'] = PROXY
42
+ os.environ['https_proxy'] = PROXY
43
+ os.environ['HTTP_PROXY'] = PROXY
44
+ os.environ['HTTPS_PROXY'] = PROXY
45
+ os.environ['no_proxy'] = 'localhost,127.0.0.1'
46
+
47
+ import requests
48
+
49
+ SLACK_URL = 'http://28.7.184.198:8178'
50
+ SALESFORCE_URL = 'http://28.7.184.198:8175'
51
+ APPROVAL_CHANNEL = 'finance-approvals'
52
+
53
+
54
+ def fail(msg):
55
+ print(f'CRITICAL: {msg}')
56
+ print('REWARD: 0.0')
57
+ sys.exit(0)
58
+
59
+
60
+ # --- Read sid ---
61
+ try:
62
+ with open('/tmp/task_web_sid') as f:
63
+ sid = f.read().strip()
64
+ if not sid:
65
+ raise ValueError('sid is empty')
66
+ except Exception as e:
67
+ fail(f'Cannot read sid from /tmp/task_web_sid: {e}')
68
+
69
+ # --- Fetch Slack state ---
70
+ try:
71
+ slack = requests.get(f'{SLACK_URL}/go?sid={sid}', timeout=20).json()
72
+ except Exception as e:
73
+ fail(f'Cannot fetch Slack state: {e}')
74
+
75
+ slack_initial = slack.get('initial_state') or {}
76
+ slack_current = slack.get('current_state') or {}
77
+ if not slack_current:
78
+ fail('Slack current_state is empty/None')
79
+
80
+ init_msgs = (slack_initial.get('messages') or {}).get(APPROVAL_CHANNEL, []) or []
81
+ cur_msgs = (slack_current.get('messages') or {}).get(APPROVAL_CHANNEL, []) or []
82
+
83
+ # Anchor scoring to messages that are NEW relative to the initial snapshot.
84
+ new_msgs = cur_msgs[len(init_msgs):] if len(cur_msgs) > len(init_msgs) else []
85
+
86
+ # Combined raw + normalized text of the new approval message(s).
87
+ raw_text = '\n'.join(str(m.get('content', '')) for m in new_msgs)
88
+ text_lower = raw_text.lower()
89
+ # Normalized: drop commas/spaces so "$90,000" and "$90000" both match "90000".
90
+ norm = re.sub(r'[,\s]', '', text_lower)
91
+
92
+
93
+ def verify_task():
94
+ total_score = 0.0
95
+
96
+ # --- Integrity gate: Salesforce must be unchanged (read-only). ---
97
+ # Precondition (true in both initial and golden) -> awards NO points.
98
+ # Only used to zero-out the score if the agent mutated the Hooli opportunity.
99
+ try:
100
+ sf = requests.get(f'{SALESFORCE_URL}/go?sid={sid}', timeout=20).json()
101
+ sf_init = sf.get('initial_state') or {}
102
+ sf_cur = sf.get('current_state') or {}
103
+
104
+ def hooli_opp(state):
105
+ for o in (state.get('opportunities') or []):
106
+ if str(o.get('name', '')).strip().lower() == 'hooli data migration':
107
+ return o
108
+ return None
109
+
110
+ opp_i = hooli_opp(sf_init)
111
+ opp_c = hooli_opp(sf_cur)
112
+ if opp_i is not None and opp_c is not None:
113
+ # Compare the figures that the task says must stay read-only.
114
+ if (opp_i.get('amount') != opp_c.get('amount')
115
+ or opp_i.get('stage') != opp_c.get('stage')):
116
+ print('GATE FAIL: Salesforce Hooli opportunity was modified '
117
+ f'(initial amount={opp_i.get("amount")}/stage={opp_i.get("stage")} '
118
+ f'-> current amount={opp_c.get("amount")}/stage={opp_c.get("stage")}). '
119
+ 'Salesforce must be read-only.')
120
+ print('\nScore: 0.0/1.0')
121
+ print('REWARD: 0.0')
122
+ return 0.0
123
+ print('GATE PASS: Salesforce Hooli opportunity unchanged (read-only).')
124
+ else:
125
+ print('GATE INFO: Hooli opportunity not found in SF state; skipping integrity gate.')
126
+ except Exception as e:
127
+ # Do not crash scoring if SF is unreachable; just note it.
128
+ print(f'GATE WARN: could not verify Salesforce integrity: {e}')
129
+
130
+ # --- Component 1: a NEW message exists in #finance-approvals (0.15) ---
131
+ try:
132
+ if new_msgs:
133
+ print(f'PASS: C1 — {len(new_msgs)} new message(s) in #{APPROVAL_CHANNEL} (0.15)')
134
+ total_score += 0.15
135
+ else:
136
+ print(f'FAIL: C1 — no new message in #{APPROVAL_CHANNEL} '
137
+ f'(initial={len(init_msgs)}, current={len(cur_msgs)})')
138
+ except Exception as e:
139
+ print(f'ERROR: C1 — {e}')
140
+
141
+ # --- Component 2: Customer = Hooli (0.15) ---
142
+ try:
143
+ if 'hooli' in text_lower:
144
+ print('PASS: C2 — Customer "Hooli" present (0.15)')
145
+ total_score += 0.15
146
+ else:
147
+ print('FAIL: C2 — Customer "Hooli" not found')
148
+ except Exception as e:
149
+ print(f'ERROR: C2 — {e}')
150
+
151
+ # --- Component 3: Original/list amount $90,000 (0.15) ---
152
+ try:
153
+ if '90000' in norm:
154
+ print('PASS: C3 — Original amount $90,000 present (0.15)')
155
+ total_score += 0.15
156
+ else:
157
+ print('FAIL: C3 — Original amount 90,000 not found')
158
+ except Exception as e:
159
+ print(f'ERROR: C3 — {e}')
160
+
161
+ # --- Component 4: Adjusted/proposed amount $72,000 (0.15) ---
162
+ try:
163
+ if '72000' in norm:
164
+ print('PASS: C4 — Adjusted amount $72,000 present (0.15)')
165
+ total_score += 0.15
166
+ else:
167
+ print('FAIL: C4 — Adjusted amount 72,000 not found')
168
+ except Exception as e:
169
+ print(f'ERROR: C4 — {e}')
170
+
171
+ # --- Component 5: Discount 20% (0.15) ---
172
+ try:
173
+ # Require the 20% figure (allow "20 %" / "20percent" via normalization).
174
+ if '20%' in norm or '20percent' in norm:
175
+ print('PASS: C5 — Discount 20% present (0.15)')
176
+ total_score += 0.15
177
+ else:
178
+ print('FAIL: C5 — Discount 20% not found')
179
+ except Exception as e:
180
+ print(f'ERROR: C5 — {e}')
181
+
182
+ # --- Component 6: Requester Jian Wu (0.15) ---
183
+ try:
184
+ # Tolerate extra spacing; normalized form removes the space -> "jianwu".
185
+ if 'jianwu' in norm:
186
+ print('PASS: C6 — Requester "Jian Wu" present (0.15)')
187
+ total_score += 0.15
188
+ else:
189
+ print('FAIL: C6 — Requester "Jian Wu" not found')
190
+ except Exception as e:
191
+ print(f'ERROR: C6 — {e}')
192
+
193
+ # --- Component 7: note that it exceeds the 15% threshold / needs approval (0.10) ---
194
+ try:
195
+ mentions_15 = '15%' in norm or '15percent' in norm
196
+ mentions_approval = any(k in text_lower for k in
197
+ ('approval', 'sign-off', 'sign off', 'signoff', 'threshold', 'exceed'))
198
+ if mentions_15 and mentions_approval:
199
+ print('PASS: C7 — Note references 15% threshold and approval/sign-off (0.10)')
200
+ total_score += 0.10
201
+ else:
202
+ print(f'FAIL: C7 — threshold note incomplete (mentions_15={mentions_15}, '
203
+ f'mentions_approval={mentions_approval})')
204
+ except Exception as e:
205
+ print(f'ERROR: C7 — {e}')
206
+
207
+ final_score = round(min(total_score, 1.0), 4)
208
+ print(f'\nScore: {final_score}/1.0')
209
+ print(f'REWARD: {final_score}')
210
+ return final_score
211
+
212
+
213
+ verify_task()
ar_approval_002/reward_label.json ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/ar_approval_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:22:12",
7
+ "label": {
8
+ "task_id": "ar_approval_002",
9
+ "domain": "mock_websites",
10
+ "summary": "验证代理是否在 Slack #finance-approvals 频道发布了包含特定客户、金额、折扣、请求人及审批说明的结构化折扣审批请求消息,并确保 Salesforce 只读未被修改。",
11
+ "is_placeholder": false,
12
+ "data_sources": [
13
+ "/tmp/task_web_sid",
14
+ "slack_mock (http://28.7.186.212:8198)",
15
+ "salesforce_mock (http://28.7.186.212:8195)"
16
+ ],
17
+ "scoring_components": [
18
+ {
19
+ "name": "C1 new message present in #finance-approvals",
20
+ "weight": 0.15,
21
+ "description": "检查在 #finance-approvals 频道是否有相对于初始状态的新消息",
22
+ "check_logic": "比较 slack_current 与 slack_initial 中 finance-approvals 频道的消息列表,若 cur_msgs 长度大于 init_msgs,则取 new_msgs = cur_msgs[len(init_msgs):],判断 new_msgs 是否非空",
23
+ "pass_condition": "new_msgs 非空(即至少有一条新消息)"
24
+ },
25
+ {
26
+ "name": "C2 Customer = Hooli",
27
+ "weight": 0.15,
28
+ "description": "检查新消息文本中是否包含客户名称 Hooli",
29
+ "check_logic": "将新消息的 raw_text 转为小写得到 text_lower,检查 'hooli' 是否在 text_lower 中",
30
+ "pass_condition": "text_lower 中包含子串 'hooli'"
31
+ },
32
+ {
33
+ "name": "C3 Original amount $90,000",
34
+ "weight": 0.15,
35
+ "description": "检查新消息中是否包含原始金额 90,000",
36
+ "check_logic": "对 text_lower 使用 re.sub(r'[,\\s]', '', ...) 得到 norm(移除逗号和空格),检查 '90000' 是否在 norm 中",
37
+ "pass_condition": "norm 中包含子串 '90000'"
38
+ },
39
+ {
40
+ "name": "C4 Adjusted amount $72,000",
41
+ "weight": 0.15,
42
+ "description": "检查新消息中是否包含调整后金额 72,000",
43
+ "check_logic": "检查 norm 中是否包含 '72000'",
44
+ "pass_condition": "norm 中包含子串 '72000'"
45
+ },
46
+ {
47
+ "name": "C5 Discount 20%",
48
+ "weight": 0.15,
49
+ "description": "检查新消息中是否包含 20% 折扣信息",
50
+ "check_logic": "检查 norm 中是否包含 '20%' 或 '20percent'",
51
+ "pass_condition": "norm 中包含 '20%' 或 '20percent'"
52
+ },
53
+ {
54
+ "name": "C6 Requester Jian Wu",
55
+ "weight": 0.15,
56
+ "description": "检查新消息中是否包含请求人 Jian Wu",
57
+ "check_logic": "检查 norm(已移除空格)中是否包含 'jianwu'",
58
+ "pass_condition": "norm 中包含子串 'jianwu'"
59
+ },
60
+ {
61
+ "name": "C7 Note: exceeds 15% threshold / needs approval",
62
+ "weight": 0.1,
63
+ "description": "检查新消息中是否包含超过 15% 阈值并需要审批的说明",
64
+ "check_logic": "mentions_15 = '15%' in norm or '15percent' in norm;mentions_approval = any(k in text_lower for k in ('approval', 'sign-off', 'sign off', 'signoff', 'threshold', 'exceed'));要求两者同时为真",
65
+ "pass_condition": "同时满足:norm 中包含 '15%' 或 '15percent',且 text_lower 中包含 'approval'、'sign-off'、'sign off'、'signoff'、'threshold' 或 'exceed' 之一"
66
+ }
67
+ ],
68
+ "total_max_score": 1.0,
69
+ "score_aggregation": "各组件分数相加,最后通过 round(min(total_score, 1.0), 4) 汇总并钳制到上限 1.0",
70
+ "failure_modes": [
71
+ "读取 /tmp/task_web_sid 失败或为空:调用 fail() 打印 CRITICAL 并 sys.exit(0) 返回 0.0",
72
+ "无法获取 Slack 状态:调用 fail() 退出并返回 0.0",
73
+ "Slack current_state 为空/None:调用 fail() 退出并返回 0.0",
74
+ "Salesforce 中 Hooli Data Migration opportunity 的 amount 或 stage 被修改:直接打印 GATE FAIL 并返回 0.0(反作弊完整性门控)",
75
+ "无新消息(new_msgs 为空):C1 失败,不加分",
76
+ "各组件文本匹配失败:对应组件不加分,但脚本继续执行"
77
+ ],
78
+ "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后分别拉取 Slack 和 Salesforce 的 mock 状态。对于 Slack,通过比较 initial_state 和 current_state 中 #finance-approvals 频道的消息列表,提取初始状态之后的新消息(new_msgs),并将所有新消息内容拼接为 raw_text,同时生成小写和规范化(移除逗号、空格)的文本。接着执行完整性门控:检查 Salesforce 中名为 'Hooli Data Migration' 的 opportunity 在初始状态和当前状态的 amount 与 stage 是否一致,若被修改则直接返回 0.0。随后逐项检查 7 个评分组件:C1 验证新消息存在性;C2-C6 通过在 text_lower 或 norm 中搜索特定���键词验证客户、原始金额、调整后金额、折扣、请求人;C7 要求同时包含 15% 相关字样和审批/阈值/超出相关字样。每个通过组件累加对应分数,最终分数经 min(..., 1.0) 钳制并四舍五入到 4 位小数输出。",
79
+ "confidence": 1.0
80
+ },
81
+ "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码:\n\n1. **任务信息提取**:\n - Task ID: ar_approval_001(从 docstring 中明确提取)\n - Domain: mock_websites(从 docstring 中明确提取)\n\n2. **任务概述**:\n - 在 Slack #finance-approvals 频道发布一个结构化的折扣审批请求消息,包含特定字段。Salesforce 必须保持只读/不变。\n\n3. **数据源**:\n - `/tmp/task_web_sid`:读取 session ID\n - Slack mock:`http://28.7.186.212:8198`(通过 `/go?sid={sid}` 获取状态)\n - Salesforce mock:`http://28.7.186.212:8195`(通过 `/go?sid={sid}` 获取状态)\n\n4. **评分组件**:\n - C1 (0.15):#finance-approvals 中有新消息\n - C2 (0.15):包含 \"Hooli\"\n - C3 (0.15):包含原始金额 $90,000(规范化后匹配 \"90000\")\n - C4 (0.15):包含调整后金额 $72,000(规范化后匹配 \"72000\")\n - C5 (0.15):包含折扣 20%(规范化后匹配 \"20%\" 或 \"20percent\")\n - C6 (0.15):包含请求人 Jian Wu(规范化后匹配 \"jianwu\")\n - C7 (0.10):包含超过 15% 阈值/需要审批的说明(需要同时满足:包含 \"15%\" 或 \"15percent\",以及包含 \"approval\"、\"sign-off\"、\"sign off\"、\"signoff\"、\"threshold\"、\"exceed\" 之一)\n\n5. **完整性门控(Integrity gate)**:\n - 检查 Salesforce 中 Hooli Data Migration opportunity 的 amount 和 stage 是否被修改\n - 如果被修改,直接返回 0.0\n - 不贡献分数,只是反作弊\n\n6. **分数聚合**:\n - 各组件分数相加\n - 最后 `round(min(total_score, 1.0), 4)`\n\n7. **失败模式**:\n - 读取 sid 失败:调用 fail(),输出 REWARD: 0.0 并 sys.exit(0)\n - 获取 Slack 状态失败:同上\n - Slack current_state 为空:同上\n - Salesforce Hooli opportunity 被修改:返回 0.0\n - 各组件检查失败:只是不加分,不会提前退出(除了 integrity gate)\n\n8. **is_placeholder**:\n - false,因为这是一个真正的评分脚本,有详细的检查逻辑\n\n9. **confidence**:\n - 1.0,因为代码非常清晰完整\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"ar_approval_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证代理是否在 Slack #finance-approvals 频道发布了包含特定客户、金额、折扣、请求人及审批说明的结构化折扣审批请求消息,并确保 Salesforce 只读未被修改。\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"slack_mock (http://28.7.186.212:8198)\", \"salesforce_mock (http://28.7.186.212:8195)\"],\n \"scoring_components\": [\n {\n \"name\": \"C1 new message present in #finance-approvals\",\n \"weight\": 0.15,\n \"description\": \"检查在 #finance-approvals 频道是否有相对于初始状态的新消息\",\n \"check_logic\": \"比较 slack_current 与 slack_initial 中 finance-approvals 频道的消息列表,若 cur_msgs 长度大于 init_msgs,则取 new_msgs = cur_msgs[len(init_msgs):],判断 new_msgs 是否非空\",\n \"pass_condition\": \"new_msgs 非空(即至少有一条新消息)\"\n },\n {\n \"name\": \"C2 Customer = Hooli\",\n \"weight\": 0.15,\n \"description\": \"检查新消息文本中是否包含客户名称 Hooli\",\n \"check_logic\": \"将新消息的 raw_text 转为小写得到 text_lower,检查 'hooli' 是否在 text_lower 中\",\n \"pass_condition\": \"text_lower 中包含子串 'hooli'\"\n },\n {\n \"name\": \"C3 Original amount $90,000\",\n \"weight\": 0.15,\n \"description\": \"检查新消息中是否包含原始金额 90,000\",\n \"check_logic\": \"对 text_lower 使用 re.sub(r'[,\\\\s]', '', ...) 得到 norm(移除逗号和空格),检查 '90000' 是否在 norm 中\",\n \"pass_condition\": \"norm 中包含子串 '90000'\"\n },\n {\n \"name\": \"C4 Adjusted amount $72,000\",\n \"weight\": 0.15,\n \"description\": \"检查新消息中是否包含调整后金额 72,000\",\n \"check_logic\": \"检查 norm 中是否包含 '72000'\",\n \"pass_condition\": \"norm 中包含子串 '72000'\"\n },\n {\n \"name\": \"C5 Discount 20%\",\n \"weight\": 0.15,\n \"description\": \"检查新消息中是否包含 20% 折扣信息\",\n \"check_logic\": \"检查 norm 中是否包含 '20%' 或 '20percent'\",\n \"pass_condition\": \"norm 中包含 '20%' 或 '20percent'\"\n },\n {\n \"name\": \"C6 Requester Jian Wu\",\n \"weight\": 0.15,\n \"description\": \"检查新消息中是否包含请求人 Jian Wu\",\n \"check_logic\": \"检查 norm(已移除空格)中是否包含 'jianwu'\",\n \"pass_condition\": \"norm 中包含子串 'jianwu'\"\n },\n {\n \"name\": \"C7 Note: exceeds 15% threshold / needs approval\",\n \"weight\": 0.10,\n \"description\": \"检查新消息中是否包含超过 15% 阈值并需要审批的说明\",\n \"check_logic\": \"mentions_15 = '15%' in norm or '15percent' in norm;mentions_approval = any(k in text_lower for k in ('approval', 'sign-off', 'sign off', 'signoff', 'threshold', 'exceed'));要求两者同时为真\",\n \"pass_condition\": \"同时满足:norm 中包含 '15%' 或 '15percent',且 text_lower 中包含 'approval'、'sign-off'、'sign off'、'signoff'、'threshold' 或 'exceed' 之一\"\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 失败或为空:调用 fail() 打印 CRITICAL 并 sys.exit(0) 返回 0.0\",\n \"无法获取 Slack 状态:调用 fail() 退出并返回 0.0\",\n \"Slack current_state 为空/None:调用 fail() 退出并返回 0.0\",\n \"Salesforce 中 Hooli Data Migration opportunity 的 amount 或 stage 被修改:直接打印 GATE FAIL 并返回 0.0(反作弊完整性门控)\",\n \"无新消息(new_msgs 为空):C1 失败,不加分\",\n \"各组件文本匹配失败:对应组件不加分,但脚本继续执行\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后分别拉取 Slack 和 Salesforce 的 mock 状态。对于 Slack,通过比较 initial_state 和 current_state 中 #finance-approvals 频道的消息列表,提取初始状态之后的新消息(new_msgs),并将所有新消息内容拼接为 raw_text,同时生成小写和规范化(移除逗号、空格)的文本。接着执行完整性门控:检查 Salesforce 中名为 'Hooli Data Migration' 的 opportunity 在初始状态和当前状态的 amount 与 stage 是否一致,若被修改则直接返回 0.0。随后逐项检查 7 个评分组件:C1 验证新消息存在性;C2-C6 通过在 text_lower 或 norm 中搜索特定关键词验证客户、原始金额、调整后金额、折扣、请求人;C7 要求同时包含 15% 相关字样和审批/阈值/超出相关字样。每个通过组件累加对应分数,最终分数经 min(..., 1.0) 钳制并四舍五入到 4 位小数输出。\",\n \"confidence\": 1.0\n}\n```\n\n检查要求:\n- 只输出 JSON,不要 Markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 字符串 value 使用中文,task_id、domain、字段名、代码标识符保留原样\n- is_placeholder: false\n- weight 填写代码中显式给出的分值\n\n确认所有字段都已包含且格式正确。 </think> {\"task_id\":\"ar_approval_001\",\"domain\":\"mock_websites\",\"summary\":\"验证代理是否在 Slack #finance-approvals 频道发布了包含特定客户、金额、折扣、请求人及审批说明的结构化折扣审批请求消息,并确保 Salesforce 只读未被修改。\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"slack_mock (http://28.7.186.212:8198)\",\"salesforce_mock (http://28.7.186.212:8195)\"],\"scoring_components\":[{\"name\":\"C1 new message present in #finance-approvals\",\"weight\":0.15,\"description\":\"检查在 #finance-approvals 频道是否有相对于初始状态的新消息\",\"check_logic\":\"比较 slack_current 与 slack_initial 中 finance-approvals 频道的消息列表,若 cur_msgs 长度大于 init_msgs,则取 new_msgs = cur_msgs[len(init_msgs):],判断 new_msgs 是否非空\",\"pass_condition\":\"new_msgs 非空(即至少有一条新消息)\"},{\"name\":\"C2 Customer = Hooli\",\"weight\":0.15,\"description\":\"检查新消息文本中是否包含客户名称 Hooli\",\"check_logic\":\"将新消息的 raw_text 转为小写得到 text_lower,检查 'hooli' 是否在 text_lower 中\",\"pass_condition\":\"text_lower 中包含子串 'hooli'\"},{\"name\":\"C3 Original amount $90,000\",\"weight\":0.15,\"description\":\"检查新消息中是否包含原始金额 90,000\",\"check_logic\":\"对 text_lower 使用 re.sub(r'[,\\\\s]', '', ...) 得到 norm(移除逗号和空格),检查 '90000' 是否在 norm 中\",\"pass_condition\":\"norm 中包含子串 '90000'\"},{\"name\":\"C4 Adjusted amount $72,000\",\"weight\":0.15,\"description\":\"检查新消息中是否包含调整后金额 72,000\",\"check_logic\":\"检查 norm 中是否包含 '72000'\",\"pass_condition\":\"norm 中包含子串 '72000'\"},{\"name\":\"C5 Discount 20%\",\"weight\":0.15,\"description\":\"检查新消息中是否包含 20% 折扣信息\",\"check_logic\":\"检查 norm 中是否包含 '20%' 或 '20percent'\",\"pass_condition\":\"norm 中包含 '20%' 或 '20percent'\"},{\"name\":\"C6 Requester Jian Wu\",\"weight\":0.15,\"description\":\"检查新消息中是否包含请求人 Jian Wu\",\"check_logic\":\"检查 norm(已移��空格)中是否包含 'jianwu'\",\"pass_condition\":\"norm 中包含子串 'jianwu'\"},{\"name\":\"C7 Note: exceeds 15% threshold / needs approval\",\"weight\":0.10,\"description\":\"检查新消息中是否包含超过 15% 阈值并需要审批的说明\",\"check_logic\":\"mentions_15 = '15%' in norm or '15percent' in norm;mentions_approval = any(k in text_lower for k in ('approval', 'sign-off', 'sign off', 'signoff', 'threshold', 'exceed'));要求两者同时为真\",\"pass_condition\":\"同时满足:norm 中包含 '15%' 或 '15percent',且 text_lower 中包含 'approval'、'sign-off'、'sign off'、'signoff'、'threshold' 或 'exceed' 之一\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最后通过 round(min(total_score, 1.0), 4) 汇总并钳制到上限 1.0\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空:调用 fail() 打印 CRITICAL 并 sys.exit(0) 返回 0.0\",\"无法获取 Slack 状态:调用 fail() 退出并返回 0.0\",\"Slack current_state 为空/None:调用 fail() 退出并返回 0.0\",\"Salesforce 中 Hooli Data Migration opportunity 的 amount 或 stage 被修改:直接打印 GATE FAIL 并返回 0.0(反作弊完整性门控)\",\"无新消息(new_msgs 为空):C1 失败,不加分\",\"各组件文本匹配失败:对应组件不加分,但脚本继续执行\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后分别拉取 Slack 和 Salesforce 的 mock 状态。对于 Slack,通过比较 initial_state 和 current_state 中 #finance-approvals 频道的消息列表,提取初始状态之后的新消息(new_msgs),并将所有新消息内容拼接为 raw_text,同时生成小写和规范化(移除逗号、空格)的文本。接着执行完整性门控:检查 Salesforce 中名为 'Hooli Data Migration' 的 opportunity 在初始状态和当前状态的 amount 与 stage 是否一致,若被修改则直接返回 0.0。随后逐项检查 7 个评分组件:C1 验证新消息存在性;C2-C6 通过在 text_lower 或 norm 中搜索特定关键词验证客户、原始金额、调整后金额、折扣、请求人;C7 要求同时包含 15% 相关字样和审批/阈值/超出相关字样。每个通过组件累加对应分数,最终分数经 min(..., 1.0) 钳制并四舍五入到 4 位小数输出。\",\"confidence\":1.0}"
82
+ }
ar_billing_exception_012__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"
ar_billing_exception_012__long/initial_setup.py ADDED
@@ -0,0 +1,934 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: Weekly billing-exceptions reconciliation
3
+ Task ID: ar_billing_exception_012__long
4
+ Mocks: stripe_dashboard_mock (8179), quickbooks_mock (8172),
5
+ google_sheets_mock (8145), slack_mock (8178)
6
+
7
+ Scenario (multi-branch finance-ops reconciliation, "today" = 2026-06-29)
8
+ ------------------------------------------------------------------------
9
+ A finance-ops analyst clears the week's billing exceptions. The Google Sheet
10
+ "Billing Exceptions" (tab `Exceptions`, cols: Customer | Exception Type | Amount
11
+ | Invoice #) lists customers the billing system flagged, one row each. For every
12
+ row the analyst derives the corrective action from the `Exception Type`, carries
13
+ the identifier into Stripe or QuickBooks, performs the (hidden) control there,
14
+ then adds a "Reconciliation Summary" tab to the sheet and posts + pins a one-line
15
+ summary to Slack #finance.
16
+
17
+ Branch rule (stated in the instruction; VERIFIED against current app state):
18
+ * Duplicate charge -> REFUND the matching Stripe payment
19
+ (skip if that payment is already refunded).
20
+ * Churn - downgrade -> CANCEL the matching Stripe subscription at PERIOD END
21
+ (skip if already cancel_at_period_end / canceled).
22
+ * Payment received -> RECEIVE PAYMENT on the matching QuickBooks invoice
23
+ (skip if the invoice is already Paid).
24
+ * On hold / Under review -> LEAVE (must NOT act — tempting distractor).
25
+ * Customer with no matching Stripe/QB record -> SKIP (unresolvable).
26
+
27
+ Row plan (10 rows) => 6 require action, 4 must be skipped:
28
+ 2 REFUND, 2 CANCEL_EOP, 2 RECEIVE_PAYMENT, 2 LEAVE (On hold / Under review),
29
+ 1 already-refunded 'Duplicate charge' (arms the refund leak guard),
30
+ 1 no-match 'Payment received' (unresolvable distractor).
31
+
32
+ Cross-app data flow (H3):
33
+ Customer + Amount read in the Sheets worklist -> locate the matching Stripe
34
+ payment (customer_name + amount in cents) to refund, and the matching Stripe
35
+ subscription (customer) to cancel-at-period-end; Invoice # -> matching
36
+ QuickBooks invoice number to receive payment on.
37
+
38
+ Ground-truth embedding (Rule 2), PRECOMPUTED in Python from the visible sheet
39
+ rows + the injected Stripe/QB records so visible <=> key can never disagree:
40
+ * google_sheets.initial_state._task_adapter.expected -> per-row worklist
41
+ * google_sheets.initial_state._task_adapter.summary_tab_name = 'Reconciliation Summary'
42
+ * slack.initial_state._task_adapter.summary_channel = 'finance'
43
+
44
+ Observable result kept ABSENT at injection (Rule 3):
45
+ * the 2 REFUND-target payments: amount_refunded=0, refunded=False; refunds[]
46
+ holds only a decoy that does NOT reference any target.
47
+ * the 2 CANCEL_EOP-target subscriptions: cancel_at_period_end=False, status='active'.
48
+ * the 2 RECEIVE_PAYMENT-target QB invoices: status Sent/Overdue, paidAmount=0,
49
+ paidDate=None.
50
+ * the Sheets workbook has NO 'Reconciliation Summary' tab (only 'Exceptions').
51
+ * Slack #finance starts EMPTY (no messages, no pinned).
52
+ * the 'already-done' distractor payment IS already refunded (must be left alone).
53
+
54
+ NOTE: Stripe amounts are in CENTS, QuickBooks amounts are in DOLLARS.
55
+ """
56
+ import datetime as _dt
57
+ import os
58
+ import shlex
59
+ import subprocess
60
+ import time
61
+ import uuid
62
+
63
+ import requests
64
+
65
+
66
+ sid = str(uuid.uuid4())
67
+ with open('/tmp/task_web_sid', 'w', encoding='utf-8') as f:
68
+ f.write(sid)
69
+ print(f'Generated sid: {sid}')
70
+
71
+
72
+ TASK_ID = 'cc91abcd-23c1-4845-afde-3bfed691bbe4'
73
+ TODAY = _dt.date(2026, 6, 29)
74
+ SUMMARY_TAB_NAME = 'Reconciliation Summary'
75
+ SUMMARY_CHANNEL = 'finance'
76
+
77
+
78
+ # ---------------------------------------------------------------------------
79
+ # Helpers
80
+ # ---------------------------------------------------------------------------
81
+ def _ts(date_str):
82
+ """Unix seconds for date_str at 12:00 UTC (stable displayed date across TZs)."""
83
+ d = _dt.datetime.strptime(date_str, '%Y-%m-%d').replace(
84
+ hour=12, minute=0, second=0, microsecond=0, tzinfo=_dt.timezone.utc
85
+ )
86
+ return int(d.timestamp())
87
+
88
+
89
+ _CREATED = _ts('2026-01-08')
90
+ _NOW_TS = _ts('2026-06-29')
91
+
92
+
93
+ # ===========================================================================
94
+ # 1) STRIPE — payments + subscriptions (+ customers, payment methods)
95
+ # ===========================================================================
96
+ # Shared customer registry: name -> (stripe_customer_id, email, card)
97
+ _STRIPE_CUSTS = {
98
+ 'Acme Corporation': ('cus_acme00000001', 'billing@acmecorp.com', {'brand': 'visa', 'last4': '4242', 'exp_month': 12, 'exp_year': 2027}),
99
+ 'Globex Industries': ('cus_globex0000012', 'ap@globexind.com', {'brand': 'mastercard', 'last4': '5555', 'exp_month': 8, 'exp_year': 2028}),
100
+ 'TechStart Inc.': ('cus_techstart0001', 'finance@techstart.io', {'brand': 'visa', 'last4': '1234', 'exp_month': 3, 'exp_year': 2027}),
101
+ 'Riverside Medical Group': ('cus_riverside0001', 'it@riversidemedical.org', {'brand': 'visa', 'last4': '8888', 'exp_month': 1, 'exp_year': 2028}),
102
+ 'CloudSync Pro': ('cus_cloudsync0001', 'billing@cloudsyncpro.com', {'brand': 'visa', 'last4': '6543', 'exp_month': 10, 'exp_year': 2028}),
103
+ 'DataVault Systems': ('cus_datavault0001', 'procurement@datavault.io', {'brand': 'amex', 'last4': '0001', 'exp_month': 6, 'exp_year': 2028}),
104
+ 'Pioneer Labs': ('cus_pioneer000001', 'admin@pioneerlabs.io', {'brand': 'visa', 'last4': '7777', 'exp_month': 12, 'exp_year': 2027}),
105
+ 'Northwind Traders': ('cus_northwind0001', 'ap@northwindtraders.com', {'brand': 'mastercard', 'last4': '2323', 'exp_month': 5, 'exp_year': 2027}),
106
+ 'Summit Retail': ('cus_summit0000001', 'billing@summitretail.com', {'brand': 'visa', 'last4': '9090', 'exp_month': 9, 'exp_year': 2028}),
107
+ }
108
+
109
+
110
+ def _stripe_customer(name):
111
+ cid, email, _card = _STRIPE_CUSTS[name]
112
+ return {
113
+ 'id': cid, 'name': name, 'email': email, 'phone': None, 'description': None,
114
+ 'address': {'line1': '200 Market St', 'line2': None, 'city': 'San Francisco',
115
+ 'state': 'CA', 'postal_code': '94105', 'country': 'US'},
116
+ 'balance': 0, 'currency': 'usd', 'default_payment_method': None,
117
+ 'metadata': {}, 'created': _CREATED, 'livemode': True, 'delinquent': False,
118
+ 'total_spent': 0, 'payments_count': 1,
119
+ }
120
+
121
+
122
+ def _payment(pid, cust_name, amount_cents, date_str, description,
123
+ refunded=False, status='succeeded'):
124
+ cid, email, card = _STRIPE_CUSTS[cust_name]
125
+ captured = (status == 'succeeded')
126
+ return {
127
+ 'id': pid,
128
+ 'amount': amount_cents,
129
+ 'currency': 'usd',
130
+ 'status': status,
131
+ 'description': description,
132
+ 'customer': cid,
133
+ 'customer_email': email,
134
+ 'customer_name': cust_name,
135
+ 'payment_method': {'type': 'card', 'card': dict(card, funding='credit')},
136
+ 'amount_received': amount_cents if captured else 0,
137
+ 'amount_refunded': amount_cents if refunded else 0,
138
+ 'refunded': bool(refunded),
139
+ 'disputed': False,
140
+ 'captured': captured,
141
+ 'receipt_email': email,
142
+ 'receipt_url': None,
143
+ 'metadata': {},
144
+ 'created': _ts(date_str),
145
+ 'livemode': True,
146
+ 'risk_score': 12,
147
+ 'risk_level': 'normal',
148
+ 'outcome': {'type': 'authorized' if captured else 'pending',
149
+ 'risk_level': 'normal', 'risk_score': 12, 'reason': None},
150
+ 'invoice': None,
151
+ }
152
+
153
+
154
+ # Payments: 2 refund targets + 1 already-refunded distractor + 1 LEAVE bait
155
+ # (DataVault, refunding it = FALSE POSITIVE) + 2 watermark decoys not in the sheet.
156
+ _STRIPE_PAYMENTS = [
157
+ # --- REFUND targets (Duplicate charge) — ABSENT result: refunded=False ---
158
+ _payment('pi_refund_acme_0001', 'Acme Corporation', 25000, '2026-06-16',
159
+ 'Pro Plan - Monthly (duplicate charge)', refunded=False), # $250.00
160
+ _payment('pi_refund_globex_0002', 'Globex Industries', 9999, '2026-06-18',
161
+ 'Starter Plan - Monthly (duplicate charge)', refunded=False), # $99.99
162
+
163
+ # --- already-refunded distractor (Pioneer): must be LEFT alone ---
164
+ _payment('pi_already_pioneer_09', 'Pioneer Labs', 4999, '2026-06-10',
165
+ 'API Access Add-on (already refunded)', refunded=True), # $49.99
166
+
167
+ # --- LEAVE-row bait (DataVault 'Under review'): refunding this = leak/FP ---
168
+ _payment('pi_leave_datavault_08', 'DataVault Systems', 18000, '2026-06-20',
169
+ 'Team Plan - Monthly', refunded=False), # $180.00
170
+
171
+ # --- watermark decoys (customers NOT in the exceptions sheet) ---
172
+ _payment('pi_decoy_north_0011', 'Northwind Traders', 12000, '2026-06-12',
173
+ 'Pro Plan Upgrade - Monthly', refunded=False),
174
+ _payment('pi_decoy_summit_0012', 'Summit Retail', 30000, '2026-06-14',
175
+ 'Enterprise Annual - Prepaid', refunded=False),
176
+ ]
177
+
178
+
179
+ def _subscription(sub_id, cust_name, status, interval, price_id, product_name,
180
+ unit_amount_cents, quantity, cancel_at_period_end=False):
181
+ cid, email, _card = _STRIPE_CUSTS[cust_name]
182
+ if interval == 'year':
183
+ cps, cpe = _ts('2026-01-01'), _ts('2027-01-01')
184
+ else:
185
+ cps, cpe = _ts('2026-06-01'), _ts('2026-07-01')
186
+ sub = {
187
+ 'id': sub_id,
188
+ 'customer': cid,
189
+ 'customer_name': cust_name,
190
+ 'customer_email': email,
191
+ 'status': status,
192
+ 'items': [{
193
+ 'id': f'si_{sub_id[4:]}_1', 'price': price_id, 'product': f'prod_{price_id}',
194
+ 'product_name': product_name, 'quantity': quantity,
195
+ 'unit_amount': unit_amount_cents, 'currency': 'usd', 'interval': interval,
196
+ }],
197
+ 'current_period_start': cps,
198
+ 'current_period_end': cpe,
199
+ 'cancel_at_period_end': bool(cancel_at_period_end),
200
+ 'canceled_at': _ts('2026-05-20') if status == 'canceled' else None,
201
+ 'ended_at': _ts('2026-05-20') if status == 'canceled' else None,
202
+ 'trial_start': None,
203
+ 'trial_end': None,
204
+ 'collection_method': 'charge_automatically',
205
+ 'default_payment_method': None,
206
+ 'latest_invoice': None,
207
+ 'pause_collection': None,
208
+ 'metadata': {},
209
+ 'created': _CREATED,
210
+ }
211
+ return sub
212
+
213
+
214
+ # Subscriptions: 2 cancel-eop targets + 1 LEAVE bait (CloudSync active sub;
215
+ # cancelling it = FALSE POSITIVE) + 2 watermark decoys (1 already-canceled).
216
+ _STRIPE_SUBS = [
217
+ # --- CANCEL_EOP targets (Churn - downgrade) — ABSENT: cap=False, active ---
218
+ _subscription('sub_techstart00001', 'TechStart Inc.', 'active', 'month',
219
+ 'price_team_month', 'Team Plan', 4999, 3, cancel_at_period_end=False),
220
+ _subscription('sub_riverside00001', 'Riverside Medical Group', 'active', 'year',
221
+ 'price_clinic_annual', 'Clinic Suite', 359988, 1, cancel_at_period_end=False),
222
+
223
+ # --- LEAVE-row bait (CloudSync 'On hold'): cancelling this = leak/FP ---
224
+ _subscription('sub_cloudsync00001', 'CloudSync Pro', 'active', 'month',
225
+ 'price_platform_month', 'CloudSync Platform', 48000, 1, cancel_at_period_end=False),
226
+
227
+ # --- watermark decoys ---
228
+ _subscription('sub_decoy_north0001', 'Northwind Traders', 'active', 'month',
229
+ 'price_pro_month', 'Pro Plan', 9900, 2, cancel_at_period_end=False),
230
+ _subscription('sub_decoy_summit001', 'Summit Retail', 'canceled', 'month',
231
+ 'price_starter_month', 'Starter Plan', 2999, 1, cancel_at_period_end=False),
232
+ ]
233
+
234
+ _STRIPE_CUSTOMERS = [_stripe_customer(nm) for nm in _STRIPE_CUSTS]
235
+
236
+ # Decoy refund that references a NON-target payment (watermark; not the targets).
237
+ _STRIPE_REFUNDS = [
238
+ {'id': 're_decoy_pioneer_01', 'amount': 4999, 'currency': 'usd',
239
+ 'charge': 'pi_already_pioneer_09', 'reason': 'duplicate', 'status': 'succeeded',
240
+ 'created': _ts('2026-06-11'), 'metadata': {}},
241
+ ]
242
+
243
+ _STRIPE_STATE = {
244
+ 'business': {
245
+ 'name': 'Northwind SaaS', 'email': 'admin@northwind-saas.com',
246
+ 'url': 'https://northwind-saas.com', 'support_email': 'support@northwind-saas.com',
247
+ 'country': 'US', 'currency': 'usd', 'timezone': 'America/Los_Angeles',
248
+ },
249
+ 'currentUser': {'id': 'user_admin', 'name': 'Finance Admin',
250
+ 'email': 'admin@northwind-saas.com', 'role': 'administrator', 'avatar': None},
251
+ 'balance': {'available': 8421500, 'pending': 1530000, 'reserved': 0, 'currency': 'usd'},
252
+ 'customers': _STRIPE_CUSTOMERS,
253
+ 'payments': _STRIPE_PAYMENTS,
254
+ 'products': [],
255
+ 'prices': [],
256
+ 'invoices': [],
257
+ 'subscriptions': _STRIPE_SUBS,
258
+ 'payouts': [],
259
+ 'disputes': [],
260
+ 'refunds': _STRIPE_REFUNDS, # decoy only; NONE references a refund target (Rule 3)
261
+ 'balanceTransactions': [],
262
+ 'events': [],
263
+ 'paymentMethods': [],
264
+ 'testMode': False,
265
+ 'searchQuery': '',
266
+ 'selectedDateRange': '30d',
267
+ 'metrics': {
268
+ 'today': {'grossVolume': 0, 'grossVolumeChart': []},
269
+ 'summary': {
270
+ 'grossVolume': {'amount': 100097, 'change': 0, 'previousAmount': 0},
271
+ 'netVolume': {'amount': 97000, 'change': 0, 'previousAmount': 0},
272
+ 'disputeActivity': {'rate': 0, 'change': 0, 'previousRate': 0},
273
+ },
274
+ 'chartData': {'grossVolume': [], 'netVolume': [], 'disputeRate': []},
275
+ },
276
+ }
277
+
278
+
279
+ # ===========================================================================
280
+ # 2) QUICKBOOKS — invoices (+ customers). Amounts in DOLLARS.
281
+ # ===========================================================================
282
+ _QB_CUSTOMERS = [
283
+ {'id': 'c1', 'name': 'Dev Solutions LLC', 'company': 'Dev Solutions LLC', 'email': 'accounts@devsolutions.co', 'phone': '(555) 100-2001'},
284
+ {'id': 'c2', 'name': 'BrightPath Education', 'company': 'BrightPath Education', 'email': 'admin@brightpath.edu', 'phone': '(555) 100-2002'},
285
+ {'id': 'c3', 'name': 'Summit Retail', 'company': 'Summit Retail', 'email': 'billing@summitretail.com', 'phone': '(555) 100-2003'},
286
+ {'id': 'c4', 'name': 'Harbor Logistics', 'company': 'Harbor Logistics', 'email': 'ap@harborlogistics.com', 'phone': '(555) 100-2004'},
287
+ ]
288
+ for _c in _QB_CUSTOMERS:
289
+ _c.setdefault('address', '100 Market St, San Francisco, CA 94105')
290
+ _c.setdefault('balance', 0)
291
+ _c.setdefault('notes', '')
292
+ _c.setdefault('isActive', True)
293
+ _c.setdefault('createdAt', '2026-01-08')
294
+
295
+
296
+ def _qb_invoice(inv_id, number, customer_id, due_date, total, status):
297
+ inv_date = (_dt.date.fromisoformat(due_date) - _dt.timedelta(days=30)).isoformat()
298
+ paid = (status == 'Paid')
299
+ return {
300
+ 'id': inv_id,
301
+ 'number': number,
302
+ 'customerId': customer_id,
303
+ 'date': inv_date,
304
+ 'dueDate': due_date,
305
+ 'items': [{'id': f'{inv_id}_li1', 'productId': 'p1',
306
+ 'description': 'Professional services', 'qty': 1,
307
+ 'rate': total, 'amount': total}],
308
+ 'subtotal': total,
309
+ 'tax': 0,
310
+ 'total': total,
311
+ 'status': status,
312
+ 'paidAmount': total if paid else 0,
313
+ 'paidDate': inv_date if paid else None,
314
+ 'terms': 'Net 30',
315
+ 'message': '',
316
+ 'createdAt': f'{inv_date}T09:00:00Z',
317
+ }
318
+
319
+
320
+ # Invoices: 2 receive-payment targets (Sent/Overdue) + 1 unpaid decoy (receiving
321
+ # payment on it = FALSE POSITIVE) + 2 already-Paid decoys + 1 Draft decoy.
322
+ _QB_INVOICES = [
323
+ # --- RECEIVE_PAYMENT targets — ABSENT: not Paid, paidAmount=0 ---
324
+ _qb_invoice('inv_dev_1042', '1042', 'c1', '2026-06-10', 1800.00, 'Sent'), # target
325
+ _qb_invoice('inv_bright_1057', '1057', 'c2', '2026-05-20', 3200.00, 'Overdue'), # target
326
+
327
+ # --- LEAVE / leak bait: an unpaid invoice NOT referenced by any sheet row ---
328
+ _qb_invoice('inv_summit_1099', '1099', 'c3', '2026-06-15', 500.00, 'Sent'), # receiving = FP
329
+
330
+ # --- watermark decoys (already Paid / Draft) ---
331
+ _qb_invoice('inv_paid_1001', '1001', 'c4', '2026-05-01', 2200.00, 'Paid'),
332
+ _qb_invoice('inv_paid_1002', '1002', 'c1', '2026-04-25', 9900.00, 'Paid'),
333
+ _qb_invoice('inv_draft_1100', '1100', 'c4', '2026-06-25', 1750.00, 'Draft'),
334
+ ]
335
+
336
+ _QB_STATE = {
337
+ 'company': {
338
+ 'name': 'Northwind SaaS', 'address': '123 Business Rd, San Francisco, CA 94105',
339
+ 'email': 'admin@northwind-saas.com', 'industry': 'Technology Services',
340
+ 'accountingMethod': 'Accrual',
341
+ },
342
+ 'customers': _QB_CUSTOMERS,
343
+ 'invoices': _QB_INVOICES,
344
+ }
345
+
346
+
347
+ # ===========================================================================
348
+ # 3) THE WORKLIST + PRECOMPUTED ANSWER KEY (single source of truth)
349
+ # ===========================================================================
350
+ # Index injected records so the key can point at real ids + verify pre-state.
351
+ _PAY_BY_ID = {p['id']: p for p in _STRIPE_PAYMENTS}
352
+ _SUB_BY_ID = {s['id']: s for s in _STRIPE_SUBS}
353
+ _INV_BY_ID = {i['id']: i for i in _QB_INVOICES}
354
+
355
+ HEADERS = ['Customer', 'Exception Type', 'Amount', 'Invoice #']
356
+
357
+ # Each row references the target record id (or None for the no-match row).
358
+ # (customer, exception_type, amount_dollars, invoice_num,
359
+ # stripe_payment_id, stripe_subscription_id, qb_invoice_id)
360
+ _ROW_SPECS = [
361
+ # --- REFUND (Duplicate charge) ---
362
+ dict(customer='Acme Corporation', exception_type='Duplicate charge', amount=250.00, invoice_num='',
363
+ stripe_payment_id='pi_refund_acme_0001', stripe_subscription_id=None, qb_invoice_id=None),
364
+ dict(customer='Globex Industries', exception_type='Duplicate charge', amount=99.99, invoice_num='',
365
+ stripe_payment_id='pi_refund_globex_0002', stripe_subscription_id=None, qb_invoice_id=None),
366
+ # --- CANCEL_EOP (Churn - downgrade) ---
367
+ dict(customer='TechStart Inc.', exception_type='Churn - downgrade', amount=149.97, invoice_num='',
368
+ stripe_payment_id=None, stripe_subscription_id='sub_techstart00001', qb_invoice_id=None),
369
+ dict(customer='Riverside Medical Group', exception_type='Churn - downgrade', amount=299.99, invoice_num='',
370
+ stripe_payment_id=None, stripe_subscription_id='sub_riverside00001', qb_invoice_id=None),
371
+ # --- RECEIVE_PAYMENT (Payment received) ---
372
+ dict(customer='Dev Solutions LLC', exception_type='Payment received', amount=1800.00, invoice_num='1042',
373
+ stripe_payment_id=None, stripe_subscription_id=None, qb_invoice_id='inv_dev_1042'),
374
+ dict(customer='BrightPath Education', exception_type='Payment received', amount=3200.00, invoice_num='1057',
375
+ stripe_payment_id=None, stripe_subscription_id=None, qb_invoice_id='inv_bright_1057'),
376
+ # --- LEAVE (On hold / Under review) — tempting distractors ---
377
+ dict(customer='CloudSync Pro', exception_type='On hold', amount=480.00, invoice_num='',
378
+ stripe_payment_id=None, stripe_subscription_id='sub_cloudsync00001', qb_invoice_id=None),
379
+ dict(customer='DataVault Systems', exception_type='Under review', amount=180.00, invoice_num='',
380
+ stripe_payment_id='pi_leave_datavault_08', stripe_subscription_id=None, qb_invoice_id=None),
381
+ # --- already-refunded 'Duplicate charge' -> must be SKIPPED ---
382
+ dict(customer='Pioneer Labs', exception_type='Duplicate charge', amount=49.99, invoice_num='',
383
+ stripe_payment_id='pi_already_pioneer_09', stripe_subscription_id=None, qb_invoice_id=None),
384
+ # --- no matching Stripe/QB record -> SKIP ---
385
+ dict(customer='Zenith Partners', exception_type='Payment received', amount=750.00, invoice_num='9999',
386
+ stripe_payment_id=None, stripe_subscription_id=None, qb_invoice_id=None),
387
+ ]
388
+
389
+
390
+ def _decide(spec):
391
+ """Derive (action, requires_action) from Exception Type VERIFIED against the
392
+ current injected state. Precomputed so the visible row <=> key can't drift."""
393
+ et = spec['exception_type'].strip().lower()
394
+
395
+ if et == 'duplicate charge':
396
+ pid = spec['stripe_payment_id']
397
+ pay = _PAY_BY_ID.get(pid) if pid else None
398
+ if pay is None:
399
+ return 'skip', False
400
+ already = bool(pay.get('refunded')) or (
401
+ pay.get('amount', 0) > 0 and pay.get('amount_refunded', 0) >= pay.get('amount', 0))
402
+ return 'refund', (not already)
403
+
404
+ if et == 'churn - downgrade':
405
+ sid_ = spec['stripe_subscription_id']
406
+ sub = _SUB_BY_ID.get(sid_) if sid_ else None
407
+ if sub is None:
408
+ return 'skip', False
409
+ already = bool(sub.get('cancel_at_period_end')) or (
410
+ str(sub.get('status', '')).lower() == 'canceled')
411
+ return 'cancel_eop', (not already)
412
+
413
+ if et == 'payment received':
414
+ iid = spec['qb_invoice_id']
415
+ inv = _INV_BY_ID.get(iid) if iid else None
416
+ if inv is None:
417
+ return 'skip', False
418
+ already = (str(inv.get('status', '')).lower() == 'paid')
419
+ return 'receive_payment', (not already)
420
+
421
+ # 'On hold' / 'Under review' (and anything else) -> LEAVE
422
+ return 'leave', False
423
+
424
+
425
+ expected = []
426
+ sheet_rows_dict = []
427
+ for idx, spec in enumerate(_ROW_SPECS):
428
+ action, requires_action = _decide(spec)
429
+ row_index = idx + 2 # sheet row (row 1 = header)
430
+
431
+ pid = spec['stripe_payment_id']
432
+ refund_amount_cents = None
433
+ if action == 'refund' and pid:
434
+ refund_amount_cents = _PAY_BY_ID[pid].get('amount')
435
+
436
+ inv_id = spec['qb_invoice_id']
437
+ qb_invoice_number = None
438
+ if inv_id and inv_id in _INV_BY_ID:
439
+ qb_invoice_number = _INV_BY_ID[inv_id].get('number')
440
+
441
+ expected.append({
442
+ 'row_index': row_index,
443
+ 'customer': spec['customer'],
444
+ 'exception_type': spec['exception_type'],
445
+ 'action': action,
446
+ 'requires_action': bool(requires_action),
447
+ 'stripe_payment_id': pid if action == 'refund' else None,
448
+ 'refund_amount_cents': refund_amount_cents,
449
+ 'stripe_subscription_id': spec['stripe_subscription_id'] if action == 'cancel_eop' else None,
450
+ 'qb_invoice_id': inv_id if action == 'receive_payment' else None,
451
+ 'qb_invoice_number': qb_invoice_number if action == 'receive_payment' else None,
452
+ })
453
+
454
+ sheet_rows_dict.append({
455
+ 'Customer': spec['customer'],
456
+ 'Exception Type': spec['exception_type'],
457
+ 'Amount': f"{spec['amount']:.2f}",
458
+ 'Invoice #': spec['invoice_num'],
459
+ })
460
+
461
+
462
+ # ---- resolved counts (for the DEBUG line / believable data) ----
463
+ refund_rows = [e for e in expected if e['action'] == 'refund' and e['requires_action']]
464
+ cancel_rows = [e for e in expected if e['action'] == 'cancel_eop' and e['requires_action']]
465
+ receive_rows = [e for e in expected if e['action'] == 'receive_payment' and e['requires_action']]
466
+ leave_rows = [e for e in expected if e['action'] == 'leave']
467
+ refund_done = [e for e in expected if e['action'] == 'refund' and not e['requires_action']]
468
+ skip_rows = [e for e in expected if e['action'] == 'skip']
469
+ requires_rows = [e for e in expected if e['requires_action']]
470
+ resolved_count = len(requires_rows)
471
+
472
+ # ---------------------------------------------------------------------------
473
+ # Build-time asserts — pin the partition sizes + Rule-3 absences.
474
+ # ---------------------------------------------------------------------------
475
+ assert len(_ROW_SPECS) == 10, len(_ROW_SPECS)
476
+ assert len(refund_rows) == 2, refund_rows # 2 REFUND require action
477
+ assert len(cancel_rows) == 2, cancel_rows # 2 CANCEL_EOP require action
478
+ assert len(receive_rows) == 2, receive_rows # 2 RECEIVE_PAYMENT require action
479
+ assert len(leave_rows) == 2, leave_rows # 2 LEAVE (On hold / Under review)
480
+ assert len(refund_done) == 1, refund_done # 1 already-refunded distractor
481
+ assert len(skip_rows) == 1, skip_rows # 1 no-match
482
+ assert resolved_count == 6, resolved_count # 6 require action
483
+ assert (len(leave_rows) + len(refund_done) + len(skip_rows)) == 4 # 4 must be skipped
484
+
485
+ # Rule 3: refund targets NOT yet refunded.
486
+ for e in refund_rows:
487
+ p = _PAY_BY_ID[e['stripe_payment_id']]
488
+ assert p['refunded'] is False and p['amount_refunded'] == 0, p['id']
489
+ # Rule 3: the already-done distractor IS refunded (must be left alone).
490
+ _pioneer = _PAY_BY_ID['pi_already_pioneer_09']
491
+ assert _pioneer['refunded'] is True and _pioneer['amount_refunded'] == _pioneer['amount']
492
+ # Rule 3: cancel targets NOT yet cancel_at_period_end and still active.
493
+ for e in cancel_rows:
494
+ s = _SUB_BY_ID[e['stripe_subscription_id']]
495
+ assert s['cancel_at_period_end'] is False and s['status'] == 'active', s['id']
496
+ # Rule 3: receive targets NOT yet Paid.
497
+ for e in receive_rows:
498
+ inv = _INV_BY_ID[e['qb_invoice_id']]
499
+ assert str(inv['status']).lower() in ('sent', 'overdue'), inv['status']
500
+ assert inv['paidAmount'] == 0 and inv['paidDate'] is None, inv['id']
501
+ # Rule 3: NO refund references any refund target.
502
+ _target_pay_ids = {e['stripe_payment_id'] for e in refund_rows}
503
+ assert all(r['charge'] not in _target_pay_ids for r in _STRIPE_REFUNDS)
504
+
505
+ print(f'Precomputed worklist: refund={len(refund_rows)} cancel_eop={len(cancel_rows)} '
506
+ f'receive_payment={len(receive_rows)} leave={len(leave_rows)} '
507
+ f'already_refunded={len(refund_done)} no_match={len(skip_rows)} '
508
+ f'-> requires_action={resolved_count}, skipped={10 - resolved_count}')
509
+
510
+
511
+ # ===========================================================================
512
+ # 4) GOOGLE SHEETS — 'Billing Exceptions' workbook, tab 'Exceptions'
513
+ # (NO 'Reconciliation Summary' tab at injection — Rule 3)
514
+ # ===========================================================================
515
+ COL_LETTERS = ['A', 'B', 'C', 'D']
516
+
517
+
518
+ def _header_cell(text):
519
+ return {'value': text, 'formula': text, 'computed': text,
520
+ 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}
521
+
522
+
523
+ def _text_cell(text):
524
+ return {'value': text, 'formula': text, 'computed': text}
525
+
526
+
527
+ def _money_cell(text):
528
+ return {'value': text, 'formula': text, 'computed': text, 'format': 'currency'}
529
+
530
+
531
+ _sheet_data = {}
532
+ for col, head in zip(COL_LETTERS, HEADERS):
533
+ _sheet_data[f'{col}1'] = _header_cell(head)
534
+ for i, row in enumerate(sheet_rows_dict):
535
+ r = i + 2
536
+ _sheet_data[f'A{r}'] = _text_cell(row['Customer'])
537
+ _sheet_data[f'B{r}'] = _text_cell(row['Exception Type'])
538
+ _sheet_data[f'C{r}'] = _money_cell(row['Amount'])
539
+ _sheet_data[f'D{r}'] = _text_cell(row['Invoice #'])
540
+
541
+ _SHEETS_STATE = {
542
+ 'id': 'workbook_cc91abcd_billing_exceptions',
543
+ 'title': 'Billing Exceptions',
544
+ 'activeSheetId': 'sheet_exceptions',
545
+ 'selectedCell': 'A1',
546
+ 'selectionRange': None,
547
+ 'clipboard': None,
548
+ 'isDragging': False,
549
+ 'undoStack': [],
550
+ 'redoStack': [],
551
+ 'namedRanges': [],
552
+ 'conditionalFormats': [],
553
+ 'charts': [],
554
+ 'showGridlines': True,
555
+ 'showFormulas': False,
556
+ 'zoom': 100,
557
+ 'sheets': [{
558
+ 'id': 'sheet_exceptions',
559
+ 'name': 'Exceptions',
560
+ 'data': _sheet_data,
561
+ 'rowCount': 100,
562
+ 'colCount': 26,
563
+ 'frozenRows': 1,
564
+ 'frozenCols': 0,
565
+ 'tabColor': None,
566
+ 'isHidden': False,
567
+ 'columnWidths': {},
568
+ 'rowHeights': {},
569
+ 'filterRange': None,
570
+ 'filterCriteria': {},
571
+ 'sortColumn': None,
572
+ 'sortDirection': None,
573
+ }],
574
+ '_task_adapter': {
575
+ 'source_schema': 'rows_dict',
576
+ 'task_id': TASK_ID,
577
+ 'variant': 'eval',
578
+ 'sheet_names': ['Exceptions'],
579
+ 'headers_by_sheet': {'Exceptions': HEADERS},
580
+ 'task_sheets': {'Exceptions': {'headers': HEADERS, 'rows': sheet_rows_dict}},
581
+ # ---- ANSWER KEY ----
582
+ 'expected': expected,
583
+ 'summary_tab_name': SUMMARY_TAB_NAME,
584
+ 'resolved_count': resolved_count,
585
+ 'n_refund': len(refund_rows),
586
+ 'n_cancel_eop': len(cancel_rows),
587
+ 'n_receive_payment': len(receive_rows),
588
+ },
589
+ }
590
+
591
+ # Rule 3 guard: the 'Reconciliation Summary' tab must be ABSENT at injection.
592
+ assert all(str(sh.get('name', '')).strip().lower() != SUMMARY_TAB_NAME.lower()
593
+ for sh in _SHEETS_STATE['sheets']), 'Reconciliation Summary tab must be absent'
594
+
595
+
596
+ # ===========================================================================
597
+ # 5) SLACK — #finance starts EMPTY (Rule 3); decoy chatter elsewhere.
598
+ # ===========================================================================
599
+ _SLACK_STATE = {
600
+ 'channels': [
601
+ {'channelId': 'general', 'name': 'general', 'description': 'Company-wide announcements',
602
+ 'topic': 'Welcome to Northwind SaaS!', 'isPrivate': False, 'isStarred': True,
603
+ 'members': ['user_1', 'user_2'], 'createdBy': 'user_2', 'createdAt': '2026-05-01T09:00:00Z',
604
+ 'pinnedMessages': [], 'unreadCount': 0},
605
+ {'channelId': 'finance', 'name': 'finance', 'description': 'Finance ops — billing exceptions and reconciliation',
606
+ 'topic': 'Post a summary when you finish the weekly reconciliation', 'isPrivate': False,
607
+ 'isStarred': False, 'members': ['user_1'], 'createdBy': 'user_1',
608
+ 'createdAt': '2026-06-01T00:00:00Z', 'pinnedMessages': [], 'unreadCount': 0},
609
+ ],
610
+ 'currentUser': {'userId': 'user_1', 'fullName': 'Dana Reyes', 'displayName': 'Dana',
611
+ 'email': 'dana.reyes@northwind-saas.com', 'avatar': 'https://picsum.photos/200/200?random=1',
612
+ 'title': 'Finance Ops Analyst', 'status': 'online', 'statusMessage': '',
613
+ 'statusEmoji': '', 'timeZone': 'America/New_York'},
614
+ 'users': [
615
+ {'userId': 'user_1', 'fullName': 'Dana Reyes', 'displayName': 'Dana',
616
+ 'email': 'dana.reyes@northwind-saas.com', 'avatar': 'https://picsum.photos/200/200?random=1',
617
+ 'title': 'Finance Ops Analyst', 'status': 'online', 'statusMessage': '', 'statusEmoji': '',
618
+ 'timeZone': 'America/New_York'},
619
+ {'userId': 'user_2', 'fullName': 'Maya Lindqvist', 'displayName': 'Maya',
620
+ 'email': 'maya.lindqvist@northwind-saas.com', 'avatar': 'https://picsum.photos/200/200?random=2',
621
+ 'title': 'Controller', 'status': 'online', 'statusMessage': '', 'statusEmoji': '',
622
+ 'timeZone': 'Europe/Stockholm'},
623
+ ],
624
+ 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Northwind SaaS', 'icon': ''},
625
+ 'messages': {
626
+ 'general': [
627
+ {'messageId': 'm_g_1', 'senderId': 'user_2',
628
+ 'content': 'Morning all — reminder that Q2 books close on Friday.',
629
+ 'timestamp': '2026-06-29T13:02:00Z', 'reactions': [], 'isEdited': False,
630
+ 'threadId': None, 'attachments': []},
631
+ ],
632
+ # #finance starts EMPTY — the gradable post + pin are the agent's work.
633
+ 'finance': [],
634
+ },
635
+ 'threads': {},
636
+ 'dms': [],
637
+ 'bookmarkedMessages': [],
638
+ 'callHistory': [],
639
+ 'settings': {'theme': 'light', 'notifications': 'all', 'displayDensity': 'comfortable',
640
+ 'showAvatars': True, 'use24Hour': False},
641
+ 'invitations': [],
642
+ 'notifications': [],
643
+ '_task_adapter': {
644
+ 'task_id': TASK_ID,
645
+ 'variant': 'eval',
646
+ 'summary_channel': SUMMARY_CHANNEL, # agent posts + pins here (empty at injection)
647
+ 'resolved_count': resolved_count,
648
+ },
649
+ }
650
+
651
+ # Rule 3 guard: #finance has no messages and nothing pinned at injection.
652
+ _fin = next(c for c in _SLACK_STATE['channels'] if c['name'] == SUMMARY_CHANNEL)
653
+ assert _fin['pinnedMessages'] == [], 'finance must have no pinned messages at injection'
654
+ assert _SLACK_STATE['messages'].get(SUMMARY_CHANNEL) == [], 'finance must be empty at injection'
655
+
656
+
657
+ # ===========================================================================
658
+ # 6) INJECT + VERIFY + LAUNCH (domain order: stripe, quickbooks, sheets, slack)
659
+ # ===========================================================================
660
+ APP_STATES = [
661
+ ('http://28.7.184.198:8179', _STRIPE_STATE), # stripe_dashboard_mock
662
+ ('http://28.7.184.198:8172', _QB_STATE), # quickbooks_mock
663
+ ('http://28.7.184.198:8145', _SHEETS_STATE), # google_sheets_mock
664
+ ('http://28.7.184.198:8178', _SLACK_STATE), # slack_mock
665
+ ]
666
+
667
+
668
+ for app_url, state in APP_STATES:
669
+ resp = requests.post(
670
+ f'{app_url}/post?sid={sid}',
671
+ json={'action': 'set', 'state': state},
672
+ timeout=30,
673
+ )
674
+ assert resp.status_code == 200, (
675
+ f'State injection failed for {app_url}: {resp.text}'
676
+ )
677
+ print(f'State injected: {app_url} sid={sid}')
678
+
679
+ for app_url, _ in APP_STATES:
680
+ go_payload = requests.get(f'{app_url}/go?sid={sid}', timeout=15).json()
681
+ assert go_payload.get('initial_state') is not None, (
682
+ f'initial_state is None after injection for {app_url}'
683
+ )
684
+ print(f'Verified initial_state set: {app_url}')
685
+
686
+
687
+ # PATCHED_BY: patch_wait_mocks_loaded.py
688
+ def launch_gui(command, delay_sec=1.0):
689
+ """Launch a GUI command, fully detached from this script.
690
+
691
+ Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that
692
+ wait_mocks_loaded's CDP phase can verify browser render below.
693
+ Idempotent: if the caller already specified a debug port, keep it.
694
+ """
695
+ env = os.environ.copy()
696
+ env['DISPLAY'] = ':0'
697
+ if isinstance(command, str):
698
+ _parts = shlex.split(command)
699
+ else:
700
+ _parts = list(command)
701
+ if (_parts and 'google-chrome' in _parts[0]
702
+ and not any(p.startswith('--remote-debugging-port') for p in _parts)):
703
+ _parts[1:1] = [
704
+ '--no-first-run',
705
+ '--no-default-browser-check',
706
+ '--remote-debugging-port=1337',
707
+ ]
708
+ subprocess.Popen(
709
+ _parts,
710
+ stdin=subprocess.DEVNULL,
711
+ stdout=subprocess.DEVNULL,
712
+ stderr=subprocess.DEVNULL,
713
+ env=env,
714
+ start_new_session=True,
715
+ )
716
+ time.sleep(delay_sec)
717
+
718
+
719
+ def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12):
720
+ """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style.
721
+
722
+ Phase 1 - Backend readiness:
723
+ Poll each mock's /state?sid=<sid> (preferred) or /go?sid=<sid>
724
+ (fallback) until it returns 200 with 'stored_state' or
725
+ 'initial_state' respectively, or until timeout.
726
+
727
+ Phase 2 - Browser render verification (via CDP + Playwright):
728
+ Connect to http://localhost:1337 (the --remote-debugging-port
729
+ injected by launch_gui above), wait for every open tab to reach
730
+ 'networkidle' AND to contain at least 20 DOM elements. This
731
+ guarantees the SPA fetched /go?sid= data AND actually painted,
732
+ not just that the mock backend is up.
733
+
734
+ Fallback:
735
+ If Playwright is missing or CDP cannot be reached, sleep for
736
+ `render_buffer` seconds as a best-effort delay so the screenshot
737
+ loop does not start on a still-blank tab.
738
+ """
739
+ import urllib.request as _urlreq
740
+ import time as _t
741
+ _urls = [p for p, _ in app_states]
742
+ _opener = _urlreq.build_opener(_urlreq.ProxyHandler({}))
743
+
744
+ # ---- Phase 1: backend readiness ----
745
+ _deadline = _t.time() + timeout
746
+ _todo = list(_urls)
747
+ while _todo and _t.time() < _deadline:
748
+ _rest = []
749
+ for _u in _todo:
750
+ _ok = False
751
+ for _path, _need in (('/state?sid=', b'stored_state'),
752
+ ('/go?sid=', b'initial_state')):
753
+ try:
754
+ _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5)
755
+ if _r.status == 200:
756
+ _body = _r.read()
757
+ if _need in _body:
758
+ _ok = True
759
+ break
760
+ except Exception:
761
+ pass
762
+ if _ok:
763
+ print(f" {_u}: backend ready")
764
+ continue
765
+ _rest.append(_u)
766
+ _todo = _rest
767
+ if _todo:
768
+ _t.sleep(2)
769
+ _done = len(_urls) - len(_todo)
770
+ _pend = f" (pending: {_todo})" if _todo else ""
771
+ print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}")
772
+
773
+ # ---- Phase 2: browser render verification via CDP ----
774
+ _cdp_ok = False
775
+ try:
776
+ from playwright.sync_api import sync_playwright
777
+ _cdp_dl = _t.time() + max(15.0, _deadline - _t.time())
778
+ with sync_playwright() as _p:
779
+ _br = None
780
+ while _t.time() < _cdp_dl:
781
+ try:
782
+ _br = _p.chromium.connect_over_cdp('http://localhost:1337')
783
+ break
784
+ except Exception:
785
+ _t.sleep(0.5)
786
+ if _br is None:
787
+ print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?")
788
+ else:
789
+ _n_expected = len(_urls)
790
+ _pages = []
791
+ _pg_dl = _t.time() + 15
792
+ _last_count = -1
793
+ _stable_since = None
794
+ while _t.time() < _pg_dl:
795
+ _pages = []
796
+ for _c in _br.contexts:
797
+ _pages.extend(_c.pages)
798
+ _cnt = len(_pages)
799
+ if _n_expected > 0 and _cnt >= _n_expected:
800
+ break
801
+ if _cnt > 0 and _cnt == _last_count:
802
+ if _stable_since is None:
803
+ _stable_since = _t.time()
804
+ elif _t.time() - _stable_since >= 1.5:
805
+ break
806
+ else:
807
+ _stable_since = None
808
+ _last_count = _cnt
809
+ _t.sleep(0.5)
810
+ _pages = []
811
+ for _c in _br.contexts:
812
+ _pages.extend(_c.pages)
813
+ if not _pages:
814
+ print(" wait_mocks_loaded: CDP connected but no open tabs found")
815
+ else:
816
+ print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render")
817
+ _MIN_ELEMS = 20
818
+ _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap
819
+ for _pg in _pages: # bring each to front once to defeat background-tab render throttling
820
+ try:
821
+ _pg.bring_to_front()
822
+ except Exception:
823
+ pass
824
+ _pending = list(_pages)
825
+ while _pending and _t.time() < _verify_dl:
826
+ _still = []
827
+ for _pg in _pending:
828
+ _ttl = ""
829
+ try:
830
+ _ttl = _pg.title()
831
+ except Exception:
832
+ pass
833
+ try:
834
+ _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0")
835
+ except Exception:
836
+ _n = 0
837
+ if _n >= _MIN_ELEMS:
838
+ print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)")
839
+ else:
840
+ _still.append(_pg)
841
+ _pending = _still
842
+ if _pending:
843
+ _t.sleep(2)
844
+ if not _pending:
845
+ _cdp_ok = True
846
+ else:
847
+ for _pg in _pending:
848
+ _ttl = ""
849
+ try:
850
+ _ttl = _pg.title()
851
+ except Exception:
852
+ pass
853
+ print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back")
854
+ except ImportError:
855
+ print(" wait_mocks_loaded: playwright not installed; skipping CDP phase")
856
+ except Exception as _e:
857
+ print(f" wait_mocks_loaded: CDP phase error ({_e!r})")
858
+
859
+ if not _cdp_ok:
860
+ print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep")
861
+ _t.sleep(render_buffer)
862
+ else:
863
+ print(" wait_mocks_loaded: browser render verified, skipping render_buffer")
864
+
865
+
866
+ def _open_mock_tabs(app_states, sid_value):
867
+ """Open the first mock as the primary Chrome window, the rest as new tabs.
868
+
869
+ Uses launch_gui once per URL so that the macOS localizer regex-extract
870
+ (which grabs the FIRST quoted URL per call) still works correctly.
871
+ """
872
+ _urls = [p for p, _ in app_states]
873
+ if not _urls:
874
+ return
875
+ launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0)
876
+ for _u in _urls[1:]:
877
+ launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0)
878
+
879
+
880
+
881
+ # PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate)
882
+ def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0):
883
+ """Block until every mock serves injected state AND (best-effort) renders."""
884
+ import time as _t
885
+ deadline = _t.time() + timeout
886
+ pending = dict(mocks)
887
+ while pending and _t.time() < deadline:
888
+ for name in list(pending):
889
+ try:
890
+ r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5)
891
+ if r.status_code == 200 and r.json().get('initial_state') is not None:
892
+ del pending[name]
893
+ except Exception:
894
+ pass
895
+ if pending:
896
+ _t.sleep(1.0)
897
+ if pending:
898
+ print(f'WARN: mocks not ready within {timeout}s: {list(pending)}')
899
+ try:
900
+ from playwright.sync_api import sync_playwright
901
+ except ImportError:
902
+ print('WARN: playwright not installed; skipping render check, settle 3s')
903
+ _t.sleep(3.0)
904
+ return
905
+ with sync_playwright() as p:
906
+ try:
907
+ browser = p.chromium.launch(channel='chrome', headless=True,
908
+ args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'])
909
+ except Exception as e:
910
+ print(f'WARN: could not launch chrome for render check: {e}; settle 3s')
911
+ _t.sleep(3.0)
912
+ return
913
+ try:
914
+ for name, url in mocks.items():
915
+ page = browser.new_page()
916
+ try:
917
+ page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000))
918
+ page.wait_for_function(
919
+ "document.body && document.body.innerText.length > 50",
920
+ timeout=int(render_timeout * 1000))
921
+ print(f'[{name}] rendered OK')
922
+ except Exception as e:
923
+ print(f'WARN: [{name}] render check issue: {e}')
924
+ finally:
925
+ page.close()
926
+ finally:
927
+ browser.close()
928
+
929
+
930
+ # ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render
931
+ _open_mock_tabs(APP_STATES, sid)
932
+ wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15)
933
+ wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12)
934
+ print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps')
ar_billing_exception_012__long/reward.py ADDED
@@ -0,0 +1,649 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: Weekly billing-exceptions reconciliation
3
+ Task ID: ar_billing_exception_012__long
4
+ Mocks: stripe_dashboard_mock,quickbooks_mock,google_sheets_mock,slack_mock
5
+
6
+ Scoring (all components in [0,1]; weights sum to 1.0; NO subtracted penalties —
7
+ leak is punished ONLY by precision inside the three F1 set-membership components):
8
+ 0.30 refund set correctness — F1(true, pred):
9
+ true = {stripe_payment_id of REFUND rows that require action}
10
+ pred = {payment ids REFUNDED now AND NOT refunded at injection} (a diff).
11
+ Refunding the already-refunded distractor cannot enter pred (no diff);
12
+ refunding a LEAVE-row / non-target payment IS a false positive -> precision down.
13
+ 0.25 cancel-at-period-end set correctness — F1(true, pred):
14
+ true = {subscription_id of CANCEL_EOP rows}
15
+ pred = {sub ids with cancel_at_period_end==True now AND False at injection}.
16
+ Cancelling IMMEDIATELY (status->'canceled') does NOT set cancel_at_period_end,
17
+ so it is NOT a true positive (wrong control). Cancelling a LEAVE sub = FP.
18
+ 0.25 receive-payment set correctness — F1(true, pred):
19
+ true = {qb_invoice_id of RECEIVE_PAYMENT rows}
20
+ pred = {invoice ids 'Paid' now AND not 'Paid' at injection}.
21
+ 0.10 Reconciliation Summary tab: 1.0 iff a sheet named 'Reconciliation Summary'
22
+ exists now, did NOT at injection (diff name-set), AND has >=1 numeric cell.
23
+ 0.05 Slack #finance post: a non-empty message exists in #finance.
24
+ 0.05 Slack #finance pin: a pinned #finance message referencing a real posted
25
+ message (gated on a post existing).
26
+
27
+ Answer key: read from google_sheets.initial_state._task_adapter
28
+ .expected -> per-row worklist (action / requires_action / target ids)
29
+ .summary_tab_name -> 'Reconciliation Summary'
30
+ and slack.initial_state._task_adapter.summary_channel -> 'finance'.
31
+
32
+ Stripe amounts are CENTS, QuickBooks amounts are DOLLARS.
33
+ """
34
+ import copy
35
+ import re
36
+ import sys
37
+
38
+ import requests
39
+
40
+
41
+ try:
42
+ with open('/tmp/task_web_sid', encoding='utf-8') as f:
43
+ sid = f.read().strip()
44
+ if not sid:
45
+ raise ValueError('sid is empty')
46
+ except Exception as e:
47
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
48
+ print('REWARD: 0.0')
49
+ sys.exit(0)
50
+
51
+
52
+ APP_URLS = {'stripe_dashboard': 'http://28.7.184.198:8179', 'quickbooks': 'http://28.7.184.198:8172',
53
+ 'google_sheets': 'http://28.7.184.198:8145', 'slack': 'http://28.7.184.198:8178'}
54
+ _GO_CACHE = {}
55
+
56
+
57
+ def clamp01(x):
58
+ return max(0.0, min(1.0, float(x)))
59
+
60
+
61
+ def frac(num, den):
62
+ return 0.0 if den == 0 else num / den
63
+
64
+
65
+ def f1(true_set, pred_set):
66
+ if not true_set and not pred_set:
67
+ return 1.0
68
+ tp = len(true_set & pred_set)
69
+ if tp == 0:
70
+ return 0.0
71
+ prec = tp / len(pred_set)
72
+ rec = tp / len(true_set)
73
+ return 2 * prec * rec / (prec + rec)
74
+
75
+
76
+ def by_id(items, key='id'):
77
+ return {it.get(key): it for it in (items or []) if isinstance(it, dict)}
78
+
79
+
80
+ def has_text(haystack, *needles):
81
+ s = (haystack or '').lower()
82
+ return any(n.lower() in s for n in needles)
83
+
84
+
85
+ def norm(s):
86
+ return (str(s) if s is not None else '').strip().lower()
87
+
88
+
89
+ def _msg_text(msg):
90
+ if not isinstance(msg, dict):
91
+ return ''
92
+ return msg.get('content') or msg.get('text') or ''
93
+
94
+
95
+ def _slack_channel_messages(slack_state, channel_name):
96
+ channels = slack_state.get('channels', []) if isinstance(slack_state, dict) else []
97
+ target = None
98
+ for ch in channels:
99
+ if isinstance(ch, dict) and norm(ch.get('name')) == norm(channel_name):
100
+ target = ch
101
+ break
102
+ if target is None:
103
+ return []
104
+ ch_msgs = target.get('messages')
105
+ if isinstance(ch_msgs, list):
106
+ return ch_msgs
107
+ msg_map = slack_state.get('messages', {})
108
+ if isinstance(msg_map, dict):
109
+ return msg_map.get(target.get('channelId') or target.get('id'), []) or []
110
+ return []
111
+
112
+
113
+ def _to_float(v):
114
+ try:
115
+ return float(v)
116
+ except (TypeError, ValueError):
117
+ return 0.0
118
+
119
+
120
+ def _sheet_rows(sheet):
121
+ if not isinstance(sheet, dict):
122
+ return []
123
+ rows = sheet.get('rows', [])
124
+ return rows if isinstance(rows, list) else []
125
+
126
+
127
+ def _sheet_tabs(sheets):
128
+ if isinstance(sheets, dict):
129
+ return sheets
130
+ if isinstance(sheets, list):
131
+ out = {}
132
+ for sh in sheets:
133
+ if not isinstance(sh, dict):
134
+ continue
135
+ name = sh.get('name') or sh.get('id')
136
+ if name:
137
+ out[name] = sh
138
+ return out
139
+ return {}
140
+
141
+
142
+ def _jaccard(a, b):
143
+ if not a and not b:
144
+ return 1.0
145
+ u = a | b
146
+ return (len(a & b) / len(u)) if u else 1.0
147
+
148
+
149
+ def _normalize_app_name(app):
150
+ app = (app or '').strip().lower()
151
+ return app[:-5] if app.endswith('_mock') else app
152
+
153
+
154
+ def _parse_cell_id(cell_id):
155
+ if not isinstance(cell_id, str) or not cell_id:
156
+ return None
157
+ idx = 0
158
+ while idx < len(cell_id) and cell_id[idx].isalpha():
159
+ idx += 1
160
+ if idx == 0 or idx >= len(cell_id):
161
+ return None
162
+ col = 0
163
+ for ch in cell_id[:idx].upper():
164
+ col = col * 26 + (ord(ch) - ord('A') + 1)
165
+ try:
166
+ row = int(cell_id[idx:])
167
+ except ValueError:
168
+ return None
169
+ return row, col - 1
170
+
171
+
172
+ def _extract_rows_from_workbook(state):
173
+ if not isinstance(state, dict):
174
+ return None
175
+ sheets = state.get('sheets')
176
+ if not isinstance(sheets, list):
177
+ return None
178
+
179
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
180
+ headers_by_sheet = adapter.get('headers_by_sheet') if isinstance(adapter.get('headers_by_sheet'), dict) else {}
181
+
182
+ out = {}
183
+ for sh in sheets:
184
+ if not isinstance(sh, dict):
185
+ continue
186
+ name = sh.get('name') or sh.get('id') or 'Sheet1'
187
+ data = sh.get('data') if isinstance(sh.get('data'), dict) else {}
188
+
189
+ headers = headers_by_sheet.get(name)
190
+ if not headers:
191
+ cols = []
192
+ for cid, cell in data.items():
193
+ rc = _parse_cell_id(cid)
194
+ if not rc:
195
+ continue
196
+ row_idx, col_idx = rc
197
+ if row_idx != 1:
198
+ continue
199
+ value = ''
200
+ if isinstance(cell, dict):
201
+ value = cell.get('value', '')
202
+ elif cell is not None:
203
+ value = str(cell)
204
+ if value is not None and str(value) != '':
205
+ cols.append((col_idx, str(value)))
206
+ headers = [v for _, v in sorted(cols)]
207
+
208
+ if not headers:
209
+ continue
210
+
211
+ by_row = {}
212
+ for cid, cell in data.items():
213
+ rc = _parse_cell_id(cid)
214
+ if not rc:
215
+ continue
216
+ row_idx, col_idx = rc
217
+ if row_idx <= 1 or col_idx >= len(headers):
218
+ continue
219
+ if isinstance(cell, dict):
220
+ value = cell.get('value', '')
221
+ else:
222
+ value = cell
223
+ by_row.setdefault(row_idx, {})[headers[col_idx]] = value
224
+
225
+ rows = []
226
+ for row_idx in sorted(by_row.keys()):
227
+ row = by_row[row_idx]
228
+ if not any(str(row.get(h, '')).strip() for h in headers):
229
+ continue
230
+ rows.append({h: row.get(h, '') for h in headers})
231
+
232
+ out[name] = {'headers': headers, 'rows': rows}
233
+
234
+ if not out:
235
+ return None
236
+ return {'sheets': out}
237
+
238
+
239
+ def _materialize_google_sheets(payload):
240
+ for key in ('initial_state', 'current_state'):
241
+ state = payload.get(key)
242
+ if not isinstance(state, dict):
243
+ continue
244
+ maybe_rows = _extract_rows_from_workbook(state)
245
+ if maybe_rows is not None:
246
+ state['_ui_workbook'] = {
247
+ 'sheets': copy.deepcopy(state.get('sheets', [])),
248
+ 'title': state.get('title'),
249
+ }
250
+ state['sheets'] = maybe_rows['sheets']
251
+
252
+
253
+ def _materialize_slack(payload):
254
+ for key in ('initial_state', 'current_state'):
255
+ state = payload.get(key)
256
+ if not isinstance(state, dict):
257
+ continue
258
+ channels = state.get('channels') if isinstance(state.get('channels'), list) else []
259
+ messages_map = state.get('messages') if isinstance(state.get('messages'), dict) else {}
260
+ for ch in channels:
261
+ if not isinstance(ch, dict):
262
+ continue
263
+ cid = ch.get('channelId') or ch.get('id')
264
+ if not cid:
265
+ continue
266
+ msg_list = messages_map.get(cid) if isinstance(messages_map.get(cid), list) else []
267
+ channel_msgs = ch.get('messages') if isinstance(ch.get('messages'), list) else []
268
+ merged = {
269
+ (m.get('messageId') or m.get('id')): dict(m)
270
+ for m in channel_msgs
271
+ if isinstance(m, dict)
272
+ }
273
+ for m in msg_list:
274
+ if not isinstance(m, dict):
275
+ continue
276
+ mid = m.get('messageId') or m.get('id')
277
+ text = m.get('text') if m.get('text') is not None else m.get('content', '')
278
+ merged[mid] = {
279
+ 'id': mid,
280
+ 'messageId': mid,
281
+ 'text': text,
282
+ 'content': m.get('content', text),
283
+ 'senderId': m.get('senderId'),
284
+ 'timestamp': m.get('timestamp'),
285
+ 'reactions': m.get('reactions') if isinstance(m.get('reactions'), list) else [],
286
+ 'attachments': m.get('attachments') if isinstance(m.get('attachments'), list) else [],
287
+ }
288
+ ch['messages'] = list(merged.values())
289
+
290
+
291
+ def _owner_name_map(state):
292
+ out = {}
293
+ users = state.get('users') if isinstance(state.get('users'), list) else []
294
+ for u in users:
295
+ if not isinstance(u, dict):
296
+ continue
297
+ uid = u.get('userId')
298
+ if not uid:
299
+ continue
300
+ name = (f"{u.get('firstName', '')} {u.get('lastName', '')}".strip() or u.get('name') or uid)
301
+ out[uid] = name
302
+ return out
303
+
304
+
305
+ def _materialize_salesforce(payload):
306
+ for key in ('initial_state', 'current_state'):
307
+ state = payload.get(key)
308
+ if not isinstance(state, dict):
309
+ continue
310
+
311
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
312
+ owner_names = _owner_name_map(state)
313
+
314
+ task_leads = adapter.get('task_leads') if isinstance(adapter.get('task_leads'), dict) else None
315
+ if task_leads and isinstance(state.get('leads'), list):
316
+ restored = []
317
+ for lead in state['leads']:
318
+ if not isinstance(lead, dict):
319
+ continue
320
+ lid = str(lead.get('leadId') or lead.get('id') or '')
321
+ meta = task_leads.get(lid, {})
322
+ restored.append({
323
+ 'id': meta.get('id') or lead.get('leadId') or lead.get('id'),
324
+ 'company': lead.get('company', meta.get('company', '')),
325
+ 'status': lead.get('status', 'New'),
326
+ 'ownerName': owner_names.get(lead.get('ownerId')) or meta.get('ownerName'),
327
+ 'annualRevenue': meta.get('annualRevenue', lead.get('revenue')),
328
+ })
329
+ state['leads'] = restored
330
+
331
+ task_accounts = adapter.get('task_accounts') if isinstance(adapter.get('task_accounts'), dict) else None
332
+ if task_accounts and isinstance(state.get('accounts'), list):
333
+ current_by_id = {}
334
+ for acc in state['accounts']:
335
+ if isinstance(acc, dict):
336
+ current_by_id[str(acc.get('accountId') or acc.get('id') or '')] = acc
337
+
338
+ restored_accounts = []
339
+ for aid, meta in task_accounts.items():
340
+ cur = current_by_id.get(str(aid), {})
341
+ restored_accounts.append({
342
+ 'id': meta.get('id') or aid,
343
+ 'name': meta.get('name') or cur.get('name', ''),
344
+ 'contact': meta.get('contact'),
345
+ 'wonWithin7d': bool(meta.get('wonWithin7d', False)),
346
+ 'onboardingStage': cur.get('onboardingStage', meta.get('onboardingStage')),
347
+ })
348
+ state['accounts'] = restored_accounts
349
+
350
+
351
+ def _materialize_google_docs(payload):
352
+ for key in ('initial_state', 'current_state'):
353
+ state = payload.get(key)
354
+ if not isinstance(state, dict):
355
+ continue
356
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
357
+ task_docs = adapter.get('task_documents') if isinstance(adapter.get('task_documents'), dict) else None
358
+ if not task_docs:
359
+ continue
360
+ docs_map = state.get('documents') if isinstance(state.get('documents'), dict) else {}
361
+ restored = []
362
+ for did, meta in task_docs.items():
363
+ cur = docs_map.get(did, {}) if isinstance(docs_map, dict) else {}
364
+ restored.append({
365
+ 'id': meta.get('id') or did,
366
+ 'title': cur.get('title', meta.get('title')),
367
+ 'vendor': meta.get('vendor'),
368
+ 'folder': meta.get('folder'),
369
+ 'content': cur.get('content', meta.get('content', '')),
370
+ })
371
+ state['documents'] = restored
372
+
373
+
374
+ def _adapt_payload_for_reward(app, payload):
375
+ app_name = _normalize_app_name(app)
376
+ if app_name == 'google_sheets':
377
+ _materialize_google_sheets(payload)
378
+ elif app_name == 'slack':
379
+ _materialize_slack(payload)
380
+ elif app_name == 'salesforce':
381
+ _materialize_salesforce(payload)
382
+ elif app_name == 'google_docs':
383
+ _materialize_google_docs(payload)
384
+ return payload
385
+
386
+
387
+ def go(app_name):
388
+ if app_name in _GO_CACHE:
389
+ return _GO_CACHE[app_name]
390
+
391
+ base = APP_URLS.get(app_name)
392
+ if not base:
393
+ print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)')
394
+ print('REWARD: 0.0')
395
+ sys.exit(0)
396
+
397
+ try:
398
+ resp = requests.get(f'{base}/go?sid={sid}', timeout=15)
399
+ resp.raise_for_status()
400
+ payload = resp.json()
401
+ except Exception as e:
402
+ print(f'CRITICAL: cannot fetch {app_name} go state: {e}')
403
+ print('REWARD: 0.0')
404
+ sys.exit(0)
405
+
406
+ payload = _adapt_payload_for_reward(app_name, payload)
407
+ _GO_CACHE[app_name] = payload
408
+ return payload
409
+
410
+
411
+ # =============================================================================
412
+ # Task-specific reward
413
+ #
414
+ # Answer key lives in google_sheets.initial_state._task_adapter.expected — a list
415
+ # of per-row dicts with:
416
+ # action ∈ {refund, cancel_eop, receive_payment, leave, skip}
417
+ # requires_action: bool
418
+ # stripe_payment_id | refund_amount_cents (refund target)
419
+ # stripe_subscription_id (cancel_eop target)
420
+ # qb_invoice_id | qb_invoice_number (receive_payment target)
421
+ # summary_tab_name (sheets adapter) and summary_channel (slack adapter) name the
422
+ # aux artefacts. We score CURRENT state against this key using precision-aware F1
423
+ # set-membership for the three action sets — leak (acting on a distractor / LEAVE
424
+ # item / wrong control) lowers precision but never drives the score below 0.
425
+ # =============================================================================
426
+ def _refunded_id_set(stripe_state):
427
+ """Payment ids that are (fully) refunded in this Stripe state — union of the
428
+ payments[].refunded/amount_refunded flags and any refunds[].charge id."""
429
+ ids = set()
430
+ for p in (stripe_state.get('payments') or []):
431
+ if not isinstance(p, dict):
432
+ continue
433
+ pid = norm(p.get('id'))
434
+ if not pid:
435
+ continue
436
+ amt = p.get('amount') or 0
437
+ ar = p.get('amount_refunded') or 0
438
+ try:
439
+ fully = (float(amt) > 0 and float(ar) >= float(amt))
440
+ except (TypeError, ValueError):
441
+ fully = False
442
+ if p.get('refunded') is True or fully:
443
+ ids.add(pid)
444
+ for r in (stripe_state.get('refunds') or []):
445
+ if isinstance(r, dict) and r.get('charge'):
446
+ ids.add(norm(r.get('charge')))
447
+ return ids
448
+
449
+
450
+ def _cap_id_set(stripe_state):
451
+ """Subscription ids flagged cancel_at_period_end (an EOP cancel specifically;
452
+ an immediate cancel sets status='canceled' and leaves this flag False)."""
453
+ ids = set()
454
+ for s in (stripe_state.get('subscriptions') or []):
455
+ if not isinstance(s, dict):
456
+ continue
457
+ if s.get('cancel_at_period_end') is True and norm(s.get('status')) != 'canceled':
458
+ ids.add(norm(s.get('id')))
459
+ return ids
460
+
461
+
462
+ def _paid_invoice_id_set(qb_state):
463
+ ids = set()
464
+ for inv in (qb_state.get('invoices') or []):
465
+ if isinstance(inv, dict) and norm(inv.get('status')) == 'paid':
466
+ ids.add(norm(inv.get('id')))
467
+ return ids
468
+
469
+
470
+ def _raw_sheets(state):
471
+ """Raw sheet dicts (list) — prefer the pre-materialization _ui_workbook copy."""
472
+ if not isinstance(state, dict):
473
+ return []
474
+ ui = state.get('_ui_workbook')
475
+ if isinstance(ui, dict) and isinstance(ui.get('sheets'), list):
476
+ return ui['sheets']
477
+ sheets = state.get('sheets')
478
+ if isinstance(sheets, list):
479
+ return sheets
480
+ return []
481
+
482
+
483
+ def _sheet_name_set(state):
484
+ out = set()
485
+ for sh in _raw_sheets(state):
486
+ if isinstance(sh, dict) and sh.get('name'):
487
+ out.add(norm(sh.get('name')))
488
+ # also fold in materialized-dict keys (belt & suspenders)
489
+ sheets = state.get('sheets') if isinstance(state, dict) else None
490
+ if isinstance(sheets, dict):
491
+ for k in sheets:
492
+ out.add(norm(k))
493
+ return out
494
+
495
+
496
+ def _sheet_has_numeric_cell(state, tab_name):
497
+ for sh in _raw_sheets(state):
498
+ if not isinstance(sh, dict) or norm(sh.get('name')) != norm(tab_name):
499
+ continue
500
+ data = sh.get('data') if isinstance(sh.get('data'), dict) else {}
501
+ for cell in data.values():
502
+ if isinstance(cell, dict):
503
+ for k in ('computed', 'value', 'formula'):
504
+ v = cell.get(k)
505
+ if isinstance(v, bool):
506
+ continue
507
+ if isinstance(v, (int, float)):
508
+ return True
509
+ if isinstance(v, str):
510
+ s = v.replace('$', '').replace(',', '').strip()
511
+ if s and re.fullmatch(r'-?\d+(\.\d+)?', s):
512
+ return True
513
+ elif isinstance(cell, (int, float)) and not isinstance(cell, bool):
514
+ return True
515
+ return False
516
+
517
+
518
+ def reward(go):
519
+ W_REFUND = 0.30
520
+ W_CANCEL = 0.25
521
+ W_RECEIVE = 0.25
522
+ W_TAB = 0.10
523
+ W_POST = 0.05
524
+ W_PIN = 0.05
525
+
526
+ # ---- 1) Answer key from google_sheets initial_state._task_adapter ----
527
+ gs = go('google_sheets')
528
+ gs_init = gs.get('initial_state', {}) if isinstance(gs.get('initial_state'), dict) else {}
529
+ gs_cur = gs.get('current_state', {}) if isinstance(gs.get('current_state'), dict) else {}
530
+ adapter = gs_init.get('_task_adapter', {}) if isinstance(gs_init.get('_task_adapter'), dict) else {}
531
+
532
+ expected = adapter.get('expected') if isinstance(adapter.get('expected'), list) else []
533
+ summary_tab_name = adapter.get('summary_tab_name') or 'Reconciliation Summary'
534
+
535
+ if not expected:
536
+ print('DEBUG_cc91abcd fatal=no_expected_worklist total=0.0')
537
+ return 0.0
538
+
539
+ refund_true = {norm(e.get('stripe_payment_id')) for e in expected
540
+ if isinstance(e, dict) and e.get('action') == 'refund'
541
+ and e.get('requires_action') and e.get('stripe_payment_id')}
542
+ cancel_true = {norm(e.get('stripe_subscription_id')) for e in expected
543
+ if isinstance(e, dict) and e.get('action') == 'cancel_eop'
544
+ and e.get('requires_action') and e.get('stripe_subscription_id')}
545
+ receive_true = {norm(e.get('qb_invoice_id')) for e in expected
546
+ if isinstance(e, dict) and e.get('action') == 'receive_payment'
547
+ and e.get('requires_action') and e.get('qb_invoice_id')}
548
+
549
+ # ---- 2) Stripe: refund set + cancel-at-period-end set (diff vs injection) ----
550
+ stripe = go('stripe_dashboard')
551
+ st_init = stripe.get('initial_state', {}) if isinstance(stripe.get('initial_state'), dict) else {}
552
+ st_cur = stripe.get('current_state', {}) if isinstance(stripe.get('current_state'), dict) else {}
553
+
554
+ refunded_init = _refunded_id_set(st_init)
555
+ refunded_now = _refunded_id_set(st_cur)
556
+ refund_pred = refunded_now - refunded_init # newly-refunded (diff)
557
+
558
+ cap_init = _cap_id_set(st_init)
559
+ cap_now = _cap_id_set(st_cur)
560
+ cancel_pred = cap_now - cap_init # newly flagged EOP-cancel
561
+
562
+ # ---- 3) QuickBooks: receive-payment set (diff vs injection) ----
563
+ qb = go('quickbooks')
564
+ qb_init = qb.get('initial_state', {}) if isinstance(qb.get('initial_state'), dict) else {}
565
+ qb_cur = qb.get('current_state', {}) if isinstance(qb.get('current_state'), dict) else {}
566
+ paid_init = _paid_invoice_id_set(qb_init)
567
+ paid_now = _paid_invoice_id_set(qb_cur)
568
+ receive_pred = paid_now - paid_init # newly-paid invoices
569
+
570
+ # F1 components (precision punishes leak; gate on a non-empty true set so a
571
+ # malformed/empty key can never hand out free credit at do-nothing).
572
+ s_refund = W_REFUND * (f1(refund_true, refund_pred) if refund_true else 0.0)
573
+ s_cancel = W_CANCEL * (f1(cancel_true, cancel_pred) if cancel_true else 0.0)
574
+ s_receive = W_RECEIVE * (f1(receive_true, receive_pred) if receive_true else 0.0)
575
+
576
+ # ---- 4) Reconciliation Summary tab: NEW named tab with >=1 numeric cell ----
577
+ names_init = _sheet_name_set(gs_init)
578
+ names_now = _sheet_name_set(gs_cur)
579
+ tab_is_new = norm(summary_tab_name) in names_now and norm(summary_tab_name) not in names_init
580
+ tab_has_numeric = _sheet_has_numeric_cell(gs_cur, summary_tab_name)
581
+ tab_ok = bool(tab_is_new and tab_has_numeric)
582
+ s_tab = W_TAB * (1.0 if tab_ok else 0.0)
583
+
584
+ # ---- 5) Slack #finance: post (non-empty) + pin (references a real message) ----
585
+ slack = go('slack')
586
+ sl_init = slack.get('initial_state', {}) if isinstance(slack.get('initial_state'), dict) else {}
587
+ sl_cur = slack.get('current_state', {}) if isinstance(slack.get('current_state'), dict) else {}
588
+ s_adapter = sl_init.get('_task_adapter', {}) if isinstance(sl_init.get('_task_adapter'), dict) else {}
589
+ summary_channel = s_adapter.get('summary_channel') or 'finance'
590
+
591
+ fin_msgs = _slack_channel_messages(sl_cur, summary_channel)
592
+ _fin_kw = ('reconcil', 'resolved', 'payment', 'invoice', 'exception', 'refund')
593
+ def _is_fin_summary(m):
594
+ t = (_msg_text(m) or '').lower()
595
+ return bool(t.strip()) and any(k in t for k in _fin_kw) and any(c.isdigit() for c in t)
596
+ post_ok = any(_is_fin_summary(m) for m in fin_msgs if isinstance(m, dict))
597
+ s_post = W_POST * (1.0 if post_ok else 0.0)
598
+
599
+ # Pin: at least one pinned id in #finance that matches a real posted message.
600
+ msg_ids = set()
601
+ for m in fin_msgs:
602
+ if isinstance(m, dict):
603
+ mid = m.get('messageId') or m.get('id')
604
+ if mid is not None:
605
+ msg_ids.add(norm(mid))
606
+ pinned = []
607
+ for ch in (sl_cur.get('channels') or []):
608
+ if isinstance(ch, dict) and norm(ch.get('name')) == norm(summary_channel):
609
+ pinned = ch.get('pinnedMessages') or []
610
+ break
611
+ pinned_ids = set()
612
+ for pm in pinned:
613
+ if isinstance(pm, dict):
614
+ pid = pm.get('messageId') or pm.get('id')
615
+ else:
616
+ pid = pm
617
+ if pid is not None:
618
+ pinned_ids.add(norm(pid))
619
+ pin_ok = bool(post_ok and (pinned_ids & msg_ids))
620
+ s_pin = W_PIN * (1.0 if pin_ok else 0.0)
621
+
622
+ score = s_refund + s_cancel + s_receive + s_tab + s_post + s_pin
623
+
624
+ print(
625
+ 'DEBUG_cc91abcd '
626
+ f'refund_true={len(refund_true)} refund_pred={len(refund_pred)} '
627
+ f'refund_f1={round(f1(refund_true, refund_pred) if refund_true else 0.0, 4)} '
628
+ f'cancel_true={len(cancel_true)} cancel_pred={len(cancel_pred)} '
629
+ f'cancel_f1={round(f1(cancel_true, cancel_pred) if cancel_true else 0.0, 4)} '
630
+ f'receive_true={len(receive_true)} receive_pred={len(receive_pred)} '
631
+ f'receive_f1={round(f1(receive_true, receive_pred) if receive_true else 0.0, 4)} '
632
+ f'tab_new={int(tab_is_new)} tab_numeric={int(tab_has_numeric)} '
633
+ f'post_ok={int(post_ok)} pin_ok={int(pin_ok)} '
634
+ f'w_refund={round(s_refund, 4)} w_cancel={round(s_cancel, 4)} w_receive={round(s_receive, 4)} '
635
+ f'w_tab={round(s_tab, 4)} w_post={round(s_post, 4)} w_pin={round(s_pin, 4)} '
636
+ f'total={round(score, 4)}'
637
+ )
638
+
639
+ return clamp01(score)
640
+
641
+
642
+ try:
643
+ score = float(reward(go))
644
+ except Exception as exc:
645
+ print(f'ERROR: reward() raised {exc!r}')
646
+ score = 0.0
647
+
648
+ score = clamp01(score)
649
+ print(f'\nREWARD: {round(score, 4)}')
ar_deal_to_invoice_007__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"
ar_deal_to_invoice_007__long/initial_setup.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: X2 — Won deal to invoice to notification
3
+ Source: generated from CUA-Gym-Hub/task_benchmark/tasks/lc_x2.py
4
+ Variant: eval
5
+ Mocks: hubspot_mock,quickbooks_mock,gmail_mock
6
+ """
7
+ import os
8
+ import shlex
9
+ import subprocess
10
+ import time
11
+ import uuid
12
+
13
+ import requests
14
+
15
+
16
+ sid = str(uuid.uuid4())
17
+ with open('/tmp/task_web_sid', 'w', encoding='utf-8') as f:
18
+ f.write(sid)
19
+ print(f'Generated sid: {sid}')
20
+
21
+ APP_STATES = [('http://28.7.184.198:8150',
22
+ {'companies': [{'id': 'comp1', 'name': 'Acme', 'domain': 'acme.com', 'industry': 'Technology', 'phone': '+1 (555) 100-0001', 'city': 'San Francisco', 'state': 'CA', 'country': 'United States', 'numberOfEmployees': 250, 'annualRevenue': 15000000, 'lifecycleStage': 'customer', 'owner': 'Admin User', 'description': 'Enterprise SaaS platform', 'createDate': '2024-01-10T09:00:00Z'},
23
+ {'id': 'comp2', 'name': 'Globex', 'domain': 'globex.com', 'industry': 'Manufacturing', 'phone': '+1 (555) 100-0002', 'city': 'New York', 'state': 'NY', 'country': 'United States', 'numberOfEmployees': 500, 'annualRevenue': 32000000, 'lifecycleStage': 'customer', 'owner': 'Admin User', 'description': 'Industrial parts supplier', 'createDate': '2024-01-12T09:00:00Z'},
24
+ {'id': 'comp3', 'name': 'Initech', 'domain': 'initech.com', 'industry': 'Technology', 'phone': '+1 (555) 100-0003', 'city': 'Austin', 'state': 'TX', 'country': 'United States', 'numberOfEmployees': 120, 'annualRevenue': 8000000, 'lifecycleStage': 'customer', 'owner': 'Admin User', 'description': 'Office software vendor', 'createDate': '2024-01-14T09:00:00Z'},
25
+ {'id': 'comp4', 'name': 'Umbrella', 'domain': 'umbrella.com', 'industry': 'Healthcare', 'phone': '+1 (555) 100-0004', 'city': 'Boston', 'state': 'MA', 'country': 'United States', 'numberOfEmployees': 800, 'annualRevenue': 55000000, 'lifecycleStage': 'customer', 'owner': 'Admin User', 'description': 'Healthcare research', 'createDate': '2024-01-16T09:00:00Z'},
26
+ {'id': 'comp5', 'name': 'Wayne', 'domain': 'wayne.com', 'industry': 'Finance', 'phone': '+1 (555) 100-0005', 'city': 'Chicago', 'state': 'IL', 'country': 'United States', 'numberOfEmployees': 1200, 'annualRevenue': 90000000, 'lifecycleStage': 'customer', 'owner': 'Admin User', 'description': 'Financial holding group', 'createDate': '2024-01-18T09:00:00Z'},
27
+ {'id': 'comp6', 'name': 'Stale Co', 'domain': 'stale.com', 'industry': 'Other', 'phone': '+1 (555) 100-0006', 'city': 'Seattle', 'state': 'WA', 'country': 'United States', 'numberOfEmployees': 90, 'annualRevenue': 5000000, 'lifecycleStage': 'customer', 'owner': 'Admin User', 'description': 'Legacy customer (last quarter)', 'createDate': '2024-01-22T09:00:00Z'},
28
+ {'id': 'comp7', 'name': 'Future Inc', 'domain': 'future.com', 'industry': 'Technology', 'phone': '+1 (555) 100-0007', 'city': 'Denver', 'state': 'CO', 'country': 'United States', 'numberOfEmployees': 60, 'annualRevenue': 3000000, 'lifecycleStage': 'opportunity', 'owner': 'Admin User', 'description': 'Q2 prospect', 'createDate': '2024-01-24T09:00:00Z'},
29
+ {'id': 'comp8', 'name': 'LostCorp', 'domain': 'lostcorp.com', 'industry': 'Other', 'phone': '+1 (555) 100-0008', 'city': 'Miami', 'state': 'FL', 'country': 'United States', 'numberOfEmployees': 40, 'annualRevenue': 2000000, 'lifecycleStage': 'lead', 'owner': 'Admin User', 'description': 'Lost competitive bid', 'createDate': '2024-01-26T09:00:00Z'}],
30
+ 'contacts': [{'id': 'c1', 'firstName': '', 'lastName': 'Acme', 'email': 'ap@acme.com', 'phone': '+1 (555) 100-0001', 'jobTitle': 'AP Manager', 'companyId': 'comp1', 'lifecycleStage': 'customer', 'leadStatus': 'connected', 'owner': 'Admin User', 'city': 'San Francisco', 'state': 'CA', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-04-05T10:00:00Z', 'timeline': []},
31
+ {'id': 'c2', 'firstName': '', 'lastName': 'Globex', 'email': 'ap@globex.com', 'phone': '+1 (555) 100-0002', 'jobTitle': 'AP Manager', 'companyId': 'comp2', 'lifecycleStage': 'customer', 'leadStatus': 'connected', 'owner': 'Admin User', 'city': 'New York', 'state': 'NY', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-04-08T10:00:00Z', 'timeline': []},
32
+ {'id': 'c3', 'firstName': '', 'lastName': 'Initech', 'email': 'ap@initech.com', 'phone': '+1 (555) 100-0003', 'jobTitle': 'AP Manager', 'companyId': 'comp3', 'lifecycleStage': 'customer', 'leadStatus': 'connected', 'owner': 'Admin User', 'city': 'Austin', 'state': 'TX', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-04-12T10:00:00Z', 'timeline': []},
33
+ {'id': 'c4', 'firstName': '', 'lastName': 'Umbrella', 'email': 'ap@umbrella.com', 'phone': '+1 (555) 100-0004', 'jobTitle': 'AP Manager', 'companyId': 'comp4', 'lifecycleStage': 'customer', 'leadStatus': 'connected', 'owner': 'Admin User', 'city': 'Boston', 'state': 'MA', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-04-18T10:00:00Z', 'timeline': []},
34
+ {'id': 'c5', 'firstName': '', 'lastName': 'Wayne', 'email': 'ap@wayne.com', 'phone': '+1 (555) 100-0005', 'jobTitle': 'AP Manager', 'companyId': 'comp5', 'lifecycleStage': 'customer', 'leadStatus': 'connected', 'owner': 'Admin User', 'city': 'Chicago', 'state': 'IL', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-04-22T10:00:00Z', 'timeline': []},
35
+ {'id': 'c6', 'firstName': '', 'lastName': 'Stale Co', 'email': 'ap@stale.com', 'phone': '+1 (555) 100-0006', 'jobTitle': 'AP Manager', 'companyId': 'comp6', 'lifecycleStage': 'customer', 'leadStatus': 'connected', 'owner': 'Admin User', 'city': 'Seattle', 'state': 'WA', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-03-25T10:00:00Z', 'timeline': []},
36
+ {'id': 'c7', 'firstName': '', 'lastName': 'Future Inc', 'email': 'ap@future.com', 'phone': '+1 (555) 100-0007', 'jobTitle': 'AP Manager', 'companyId': 'comp7', 'lifecycleStage': 'opportunity', 'leadStatus': 'connected', 'owner': 'Admin User', 'city': 'Denver', 'state': 'CO', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-05-03T10:00:00Z', 'timeline': []},
37
+ {'id': 'c8', 'firstName': '', 'lastName': 'LostCorp', 'email': 'ap@lostcorp.com', 'phone': '+1 (555) 100-0008', 'jobTitle': 'AP Manager', 'companyId': 'comp8', 'lifecycleStage': 'lead', 'leadStatus': 'unqualified', 'owner': 'Admin User', 'city': 'Miami', 'state': 'FL', 'country': 'United States', 'createDate': '2024-01-15T10:30:00Z', 'lastActivityDate': '2026-04-15T10:00:00Z', 'timeline': []}],
38
+ # Each deal carries the schema fields the hubspot_mock front-end reads
39
+ # (name/stage/amount/closeDate/dealType/priority/owner/companyId/
40
+ # contactIds/probability/description). The rewritten reward.py reads the
41
+ # same schema (companies[id==deal.companyId].name, contacts[id==
42
+ # contactIds[0]].email, deal.description) -- there are NO legacy
43
+ # tag-along fields any more.
44
+ #
45
+ # Single-line-only design: every April Closed Won deal is invoiced with
46
+ # exactly one line item. The deal name follows the pattern
47
+ # "<Company> - <Product>" so the agent can derive the QuickBooks
48
+ # Product/Service name (the part after " - ") and the QB product catalog
49
+ # below seeds a matching product whose price equals deals[].amount.
50
+ #
51
+ # IMPORTANT: stage value is 'closedwon' (no underscore) because reward.py
52
+ # filters won deals via norm(d['stage']) == 'closedwon'. We add a matching
53
+ # 'closedwon' entry to dealStages below so the front-end pipeline shows
54
+ # those deals in their own labelled column.
55
+ 'deals': [{'id': 'd1', 'name': 'Acme - Enterprise License', 'stage': 'closedwon', 'amount': 12000, 'closeDate': '2026-04-05', 'dealType': 'new_business', 'priority': 'high', 'owner': 'Admin User', 'companyId': 'comp1', 'contactIds': ['c1'], 'probability': 100, 'description': 'Annual enterprise license, 250 seats', 'createDate': '2026-03-01T10:00:00Z', 'lastActivityDate': '2026-04-05T14:00:00Z'},
56
+ {'id': 'd2', 'name': 'Globex - Onboarding Package', 'stage': 'closedwon', 'amount': 7000, 'closeDate': '2026-04-08', 'dealType': 'new_business', 'priority': 'high', 'owner': 'Admin User', 'companyId': 'comp2', 'contactIds': ['c2'], 'probability': 100, 'description': 'Onboarding bundle (setup + license)', 'createDate': '2026-03-01T10:00:00Z', 'lastActivityDate': '2026-04-08T14:00:00Z'},
57
+ {'id': 'd3', 'name': 'Initech - Annual Subscription', 'stage': 'closedwon', 'amount': 8000, 'closeDate': '2026-04-12', 'dealType': 'existing_business', 'priority': 'medium', 'owner': 'Admin User', 'companyId': 'comp3', 'contactIds': ['c3'], 'probability': 100, 'description': 'Standard annual plan', 'createDate': '2026-03-05T10:00:00Z', 'lastActivityDate': '2026-04-12T14:00:00Z'},
58
+ {'id': 'd4', 'name': 'Umbrella - Hybrid Plan', 'stage': 'closedwon', 'amount': 8000, 'closeDate': '2026-04-18', 'dealType': 'new_business', 'priority': 'high', 'owner': 'Admin User', 'companyId': 'comp4', 'contactIds': ['c4'], 'probability': 100, 'description': 'Hybrid plan (seats + support bundled)', 'createDate': '2026-03-08T10:00:00Z', 'lastActivityDate': '2026-04-18T14:00:00Z'},
59
+ {'id': 'd5', 'name': 'Wayne - Renewal', 'stage': 'closedwon', 'amount': 15000, 'closeDate': '2026-04-22', 'dealType': 'existing_business', 'priority': 'high', 'owner': 'Admin User', 'companyId': 'comp5', 'contactIds': ['c5'], 'probability': 100, 'description': 'Renewal of existing master contract', 'createDate': '2026-03-12T10:00:00Z', 'lastActivityDate': '2026-04-22T14:00:00Z'},
60
+ {'id': 'd6', 'name': 'Stale Co - Last Quarter', 'stage': 'closedwon', 'amount': 9000, 'closeDate': '2026-03-25', 'dealType': 'existing_business', 'priority': 'medium', 'owner': 'Admin User', 'companyId': 'comp6', 'contactIds': ['c6'], 'probability': 100, 'description': 'Q1 deal, closed in March 2026', 'createDate': '2026-02-20T10:00:00Z', 'lastActivityDate': '2026-03-25T14:00:00Z'},
61
+ {'id': 'd7', 'name': 'Future Inc - Q2 Pipeline', 'stage': 'contract_sent', 'amount': 11000, 'closeDate': '2026-05-03', 'dealType': 'new_business', 'priority': 'medium', 'owner': 'Admin User', 'companyId': 'comp7', 'contactIds': ['c7'], 'probability': 90, 'description': 'Q2 deal, awaiting signature', 'createDate': '2026-04-10T10:00:00Z', 'lastActivityDate': '2026-05-03T14:00:00Z'},
62
+ {'id': 'd8', 'name': 'LostCorp - Lost Bid', 'stage': 'closed_lost', 'amount': 7000, 'closeDate': '2026-04-15', 'dealType': 'new_business', 'priority': 'low', 'owner': 'Admin User', 'companyId': 'comp8', 'contactIds': ['c8'], 'probability': 0, 'description': 'Lost to competitor', 'createDate': '2026-02-25T10:00:00Z', 'lastActivityDate': '2026-04-15T14:00:00Z', 'closedLostReason': 'Lost to competitor pricing'}],
63
+ 'tickets': [],
64
+ 'tasks': [],
65
+ # Single-line-only design: no per-deal line-item notes are needed.
66
+ 'notes': [],
67
+ 'templates': [],
68
+ 'meetings': [],
69
+ 'forms': [],
70
+ # NOTE: 'closedwon' (no underscore) is intentional and matches the literal
71
+ # value used in reward.py (norm(d['stage']) == 'closedwon'). The default
72
+ # mockData.js dealStages uses 'closed_won' (with underscore); we override
73
+ # with this dict so the pipeline view actually has a column whose id ===
74
+ # 'closedwon' to render our deals into.
75
+ 'dealStages': {'appointment_scheduled': {'id': 'appointment_scheduled', 'label': 'Appointment Scheduled', 'probability': 20, 'color': '#E5F4FF', 'order': 1},
76
+ 'qualified_to_buy': {'id': 'qualified_to_buy', 'label': 'Qualified to Buy', 'probability': 40, 'color': '#FFF0E6', 'order': 2},
77
+ 'presentation_scheduled': {'id': 'presentation_scheduled', 'label': 'Presentation Scheduled', 'probability': 60, 'color': '#FFF8E6', 'order': 3},
78
+ 'decision_maker_bought_in': {'id': 'decision_maker_bought_in', 'label': 'Decision Maker Bought-In', 'probability': 80, 'color': '#E8F5E9', 'order': 4},
79
+ 'contract_sent': {'id': 'contract_sent', 'label': 'Contract Sent', 'probability': 90, 'color': '#E6FFFA', 'order': 5},
80
+ 'closedwon': {'id': 'closedwon', 'label': 'Closed Won', 'probability': 100, 'color': '#E6FFEC', 'order': 6},
81
+ 'closed_lost': {'id': 'closed_lost', 'label': 'Closed Lost', 'probability': 0, 'color': '#FFE6E6', 'order': 7}},
82
+ 'ticketStatuses': {'new': {'id': 'new', 'label': 'New', 'color': '#E5F4FF', 'order': 1},
83
+ 'waiting_on_contact': {'id': 'waiting_on_contact', 'label': 'Waiting on Contact', 'color': '#FFF8E6', 'order': 2},
84
+ 'waiting_on_us': {'id': 'waiting_on_us', 'label': 'Waiting on Us', 'color': '#FFF0E6', 'order': 3},
85
+ 'in_progress': {'id': 'in_progress', 'label': 'In Progress', 'color': '#E6FFFA', 'order': 4},
86
+ 'closed': {'id': 'closed', 'label': 'Closed', 'color': '#E6FFEC', 'order': 5}},
87
+ 'appState': {'sidebarOpen': True, 'currentUser': {'name': 'Admin User', 'email': 'admin@example.com', 'avatar': None}}}),
88
+ # ---- QuickBooks ----
89
+ # Customer naming convention: B2B mapping. Each pre-seeded customer's `name`
90
+ # equals the corresponding HubSpot company's `name`, and `company` is set to
91
+ # the same value so the agent can satisfy the instruction's "use that name
92
+ # as both Name and Company" rule by selecting an existing record.
93
+ #
94
+ # Coverage of April 2026 Closed Won deals (d1..d5):
95
+ # d1 Acme -> qb_c1 (pre-seeded)
96
+ # d2 Globex -> qb_c2 (pre-seeded)
97
+ # d3 Initech -> qb_c3 (pre-seeded)
98
+ # d4 Umbrella -> qb_c4 (pre-seeded)
99
+ # d5 Wayne -> NOT pre-seeded -> agent MUST create it first.
100
+ #
101
+ # Plus distractors (qb_c5 Hooli, qb_c6 Pied Piper) that are unrelated to any
102
+ # HubSpot deal -- they verify the agent picks customers by deal mapping
103
+ # rather than blindly choosing the first row. qb_c7 (Stale Co) is the
104
+ # historical customer for d6 (March 25 won deal, NOT to be invoiced this run);
105
+ # keeping it makes the seed look like a realistic ongoing books.
106
+ #
107
+ # `products` is pre-seeded with one Service per April Closed Won deal: each
108
+ # product's `name` equals the part of the corresponding deal's name after
109
+ # " - " (e.g. d1 "Acme - Enterprise License" -> product "Enterprise
110
+ # License"), and its `price` equals deals[].amount. This way, when the
111
+ # agent picks the product on the invoice line the form auto-fills the Rate
112
+ # to the correct amount with no manual override needed. Every product is
113
+ # `isTaxable: false` so the form's auto-tax stays at $0.
114
+ ('http://28.7.184.198:8172',
115
+ {'customers': [{'id': 'qb_c1', 'name': 'Acme', 'company': 'Acme',
116
+ 'email': 'ap@acme.com', 'phone': '+1 (555) 100-0001',
117
+ 'address': 'San Francisco, CA, United States',
118
+ 'balance': 0, 'isActive': True, 'createdAt': '2024-02-01',
119
+ 'notes': ''},
120
+ # NOTE: qb_c2 (Globex) / qb_c3 (Initech) / qb_c4 (Umbrella)
121
+ # are intentionally NOT pre-seeded. The agent must create
122
+ # these customers via Sales -> Customers -> "New customer"
123
+ # before invoicing d2/d3/d4 (same as d5 Wayne). Only d1
124
+ # (Acme) starts with a pre-seeded customer in QB.
125
+ # Distractors: legitimate-looking customers unrelated to any
126
+ # HubSpot deal in this task. These should NOT receive any
127
+ # invoice in this run.
128
+ {'id': 'qb_c5', 'name': 'Hooli', 'company': 'Hooli',
129
+ 'email': 'billing@hooli.com', 'phone': '+1 (555) 200-0001',
130
+ 'address': 'Palo Alto, CA, United States',
131
+ 'balance': 1500, 'isActive': True, 'createdAt': '2023-09-15',
132
+ 'notes': 'Legacy account'},
133
+ {'id': 'qb_c6', 'name': 'Pied Piper', 'company': 'Pied Piper',
134
+ 'email': 'ap@piedpiper.com', 'phone': '+1 (555) 200-0002',
135
+ 'address': 'San Francisco, CA, United States',
136
+ 'balance': 0, 'isActive': True, 'createdAt': '2023-11-02',
137
+ 'notes': ''},
138
+ # Historical customer for d6 (March 25 won, OUT of April scope).
139
+ {'id': 'qb_c7', 'name': 'Stale Co', 'company': 'Stale Co',
140
+ 'email': 'ap@stale.com', 'phone': '+1 (555) 100-0006',
141
+ 'address': 'Seattle, WA, United States',
142
+ 'balance': 0, 'isActive': True, 'createdAt': '2024-02-01',
143
+ 'notes': 'Q1 customer; already invoiced in March.'}],
144
+ # One Service per April Closed Won deal. price == deals[].amount so that
145
+ # selecting the product on the invoice line auto-fills the Rate correctly.
146
+ 'products': [{'id': 'qb_p1', 'name': 'Enterprise License', 'description': 'Annual enterprise license', 'type': 'Service',
147
+ 'price': 12000, 'cost': 0, 'category': 'Services', 'sku': '',
148
+ 'isActive': True, 'isTaxable': False, 'quantityOnHand': None},
149
+ {'id': 'qb_p2', 'name': 'Onboarding Package', 'description': 'Onboarding bundle (setup + license)', 'type': 'Service',
150
+ 'price': 7000, 'cost': 0, 'category': 'Services', 'sku': '',
151
+ 'isActive': True, 'isTaxable': False, 'quantityOnHand': None},
152
+ {'id': 'qb_p3', 'name': 'Annual Subscription', 'description': 'Standard annual plan', 'type': 'Service',
153
+ 'price': 8000, 'cost': 0, 'category': 'Services', 'sku': '',
154
+ 'isActive': True, 'isTaxable': False, 'quantityOnHand': None},
155
+ {'id': 'qb_p4', 'name': 'Hybrid Plan', 'description': 'Hybrid plan (seats + support bundled)', 'type': 'Service',
156
+ 'price': 8000, 'cost': 0, 'category': 'Services', 'sku': '',
157
+ 'isActive': True, 'isTaxable': False, 'quantityOnHand': None},
158
+ {'id': 'qb_p5', 'name': 'Renewal', 'description': 'Renewal of existing master contract', 'type': 'Service',
159
+ 'price': 15000, 'cost': 0, 'category': 'Services', 'sku': '',
160
+ 'isActive': True, 'isTaxable': False, 'quantityOnHand': None}],
161
+ 'invoices': []}),
162
+ ('http://28.7.184.198:8138', {'emails': []})]
163
+
164
+
165
+ for app_url, state in APP_STATES:
166
+ resp = requests.post(
167
+ f'{app_url}/post?sid={sid}',
168
+ json={'action': 'set', 'state': state},
169
+ timeout=30,
170
+ )
171
+ assert resp.status_code == 200, (
172
+ f'State injection failed for {app_url}: {resp.text}'
173
+ )
174
+ print(f'State injected: {app_url} sid={sid}')
175
+
176
+ for app_url, _ in APP_STATES:
177
+ go_payload = requests.get(f'{app_url}/go?sid={sid}', timeout=15).json()
178
+ assert go_payload.get('initial_state') is not None, (
179
+ f'initial_state is None after injection for {app_url}'
180
+ )
181
+ print(f'Verified initial_state set: {app_url}')
182
+
183
+
184
+ # PATCHED_BY: patch_wait_mocks_loaded.py
185
+ def launch_gui(command, delay_sec=1.0):
186
+ """Launch a GUI command, fully detached from this script.
187
+
188
+ Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that
189
+ wait_mocks_loaded's CDP phase can verify browser render below.
190
+ Idempotent: if the caller already specified a debug port, keep it.
191
+ """
192
+ env = os.environ.copy()
193
+ env['DISPLAY'] = ':0'
194
+ if isinstance(command, str):
195
+ _parts = shlex.split(command)
196
+ else:
197
+ _parts = list(command)
198
+ if (_parts and 'google-chrome' in _parts[0]
199
+ and not any(p.startswith('--remote-debugging-port') for p in _parts)):
200
+ _parts[1:1] = [
201
+ '--no-first-run',
202
+ '--no-default-browser-check',
203
+ '--remote-debugging-port=1337',
204
+ ]
205
+ subprocess.Popen(
206
+ _parts,
207
+ stdin=subprocess.DEVNULL,
208
+ stdout=subprocess.DEVNULL,
209
+ stderr=subprocess.DEVNULL,
210
+ env=env,
211
+ start_new_session=True,
212
+ )
213
+ time.sleep(delay_sec)
214
+
215
+
216
+ def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12):
217
+ """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style.
218
+
219
+ Phase 1 - Backend readiness:
220
+ Poll each mock's /state?sid=<sid> (preferred) or /go?sid=<sid>
221
+ (fallback) until it returns 200 with 'stored_state' or
222
+ 'initial_state' respectively, or until timeout.
223
+
224
+ Phase 2 - Browser render verification (via CDP + Playwright):
225
+ Connect to http://localhost:1337 (the --remote-debugging-port
226
+ injected by launch_gui above), wait for every open tab to reach
227
+ 'networkidle' AND to contain at least 20 DOM elements. This
228
+ guarantees the SPA fetched /go?sid= data AND actually painted,
229
+ not just that the mock backend is up.
230
+
231
+ Fallback:
232
+ If Playwright is missing or CDP cannot be reached, sleep for
233
+ `render_buffer` seconds as a best-effort delay so the screenshot
234
+ loop does not start on a still-blank tab.
235
+ """
236
+ import urllib.request as _urlreq
237
+ import time as _t
238
+ _urls = [p for p, _ in app_states]
239
+ _opener = _urlreq.build_opener(_urlreq.ProxyHandler({}))
240
+
241
+ # ---- Phase 1: backend readiness ----
242
+ _deadline = _t.time() + timeout
243
+ _todo = list(_urls)
244
+ while _todo and _t.time() < _deadline:
245
+ _rest = []
246
+ for _u in _todo:
247
+ _ok = False
248
+ for _path, _need in (('/state?sid=', b'stored_state'),
249
+ ('/go?sid=', b'initial_state')):
250
+ try:
251
+ _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5)
252
+ if _r.status == 200:
253
+ _body = _r.read()
254
+ if _need in _body:
255
+ _ok = True
256
+ break
257
+ except Exception:
258
+ pass
259
+ if _ok:
260
+ print(f" {_u}: backend ready")
261
+ continue
262
+ _rest.append(_u)
263
+ _todo = _rest
264
+ if _todo:
265
+ _t.sleep(2)
266
+ _done = len(_urls) - len(_todo)
267
+ _pend = f" (pending: {_todo})" if _todo else ""
268
+ print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}")
269
+
270
+ # ---- Phase 2: browser render verification via CDP ----
271
+ _cdp_ok = False
272
+ try:
273
+ from playwright.sync_api import sync_playwright
274
+ _cdp_dl = _t.time() + max(15.0, _deadline - _t.time())
275
+ with sync_playwright() as _p:
276
+ _br = None
277
+ while _t.time() < _cdp_dl:
278
+ try:
279
+ _br = _p.chromium.connect_over_cdp('http://localhost:1337')
280
+ break
281
+ except Exception:
282
+ _t.sleep(0.5)
283
+ if _br is None:
284
+ print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?")
285
+ else:
286
+ _n_expected = len(_urls)
287
+ _pages = []
288
+ _pg_dl = _t.time() + 15
289
+ _last_count = -1
290
+ _stable_since = None
291
+ while _t.time() < _pg_dl:
292
+ _pages = []
293
+ for _c in _br.contexts:
294
+ _pages.extend(_c.pages)
295
+ _cnt = len(_pages)
296
+ if _n_expected > 0 and _cnt >= _n_expected:
297
+ break
298
+ if _cnt > 0 and _cnt == _last_count:
299
+ if _stable_since is None:
300
+ _stable_since = _t.time()
301
+ elif _t.time() - _stable_since >= 1.5:
302
+ break
303
+ else:
304
+ _stable_since = None
305
+ _last_count = _cnt
306
+ _t.sleep(0.5)
307
+ _pages = []
308
+ for _c in _br.contexts:
309
+ _pages.extend(_c.pages)
310
+ if not _pages:
311
+ print(" wait_mocks_loaded: CDP connected but no open tabs found")
312
+ else:
313
+ print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render")
314
+ _MIN_ELEMS = 20
315
+ _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap
316
+ for _pg in _pages: # bring each to front once to defeat background-tab render throttling
317
+ try:
318
+ _pg.bring_to_front()
319
+ except Exception:
320
+ pass
321
+ _pending = list(_pages)
322
+ while _pending and _t.time() < _verify_dl:
323
+ _still = []
324
+ for _pg in _pending:
325
+ _ttl = ""
326
+ try:
327
+ _ttl = _pg.title()
328
+ except Exception:
329
+ pass
330
+ try:
331
+ _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0")
332
+ except Exception:
333
+ _n = 0
334
+ if _n >= _MIN_ELEMS:
335
+ print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)")
336
+ else:
337
+ _still.append(_pg)
338
+ _pending = _still
339
+ if _pending:
340
+ _t.sleep(2)
341
+ if not _pending:
342
+ _cdp_ok = True
343
+ else:
344
+ for _pg in _pending:
345
+ _ttl = ""
346
+ try:
347
+ _ttl = _pg.title()
348
+ except Exception:
349
+ pass
350
+ print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back")
351
+ except ImportError:
352
+ print(" wait_mocks_loaded: playwright not installed; skipping CDP phase")
353
+ except Exception as _e:
354
+ print(f" wait_mocks_loaded: CDP phase error ({_e!r})")
355
+
356
+ if not _cdp_ok:
357
+ print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep")
358
+ _t.sleep(render_buffer)
359
+ else:
360
+ print(" wait_mocks_loaded: browser render verified, skipping render_buffer")
361
+
362
+
363
+ def _open_mock_tabs(app_states, sid_value):
364
+ """Open the first mock as the primary Chrome window, the rest as new tabs.
365
+
366
+ Uses launch_gui once per URL so that the macOS localizer regex-extract
367
+ (which grabs the FIRST quoted URL per call) still works correctly.
368
+ """
369
+ _urls = [p for p, _ in app_states]
370
+ if not _urls:
371
+ return
372
+ launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0)
373
+ for _u in _urls[1:]:
374
+ launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0)
375
+
376
+
377
+
378
+ # PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate)
379
+ def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0):
380
+ """Block until every mock serves injected state AND (best-effort) renders."""
381
+ import time as _t
382
+ deadline = _t.time() + timeout
383
+ pending = dict(mocks)
384
+ while pending and _t.time() < deadline:
385
+ for name in list(pending):
386
+ try:
387
+ r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5)
388
+ if r.status_code == 200 and r.json().get('initial_state') is not None:
389
+ del pending[name]
390
+ except Exception:
391
+ pass
392
+ if pending:
393
+ _t.sleep(1.0)
394
+ if pending:
395
+ print(f'WARN: mocks not ready within {timeout}s: {list(pending)}')
396
+ try:
397
+ from playwright.sync_api import sync_playwright
398
+ except ImportError:
399
+ print('WARN: playwright not installed; skipping render check, settle 3s')
400
+ _t.sleep(3.0)
401
+ return
402
+ with sync_playwright() as p:
403
+ try:
404
+ browser = p.chromium.launch(channel='chrome', headless=True,
405
+ args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'])
406
+ except Exception as e:
407
+ print(f'WARN: could not launch chrome for render check: {e}; settle 3s')
408
+ _t.sleep(3.0)
409
+ return
410
+ try:
411
+ for name, url in mocks.items():
412
+ page = browser.new_page()
413
+ try:
414
+ page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000))
415
+ page.wait_for_function(
416
+ "document.body && document.body.innerText.length > 50",
417
+ timeout=int(render_timeout * 1000))
418
+ print(f'[{name}] rendered OK')
419
+ except Exception as e:
420
+ print(f'WARN: [{name}] render check issue: {e}')
421
+ finally:
422
+ page.close()
423
+ finally:
424
+ browser.close()
425
+
426
+
427
+ # ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render
428
+ _open_mock_tabs(APP_STATES, sid)
429
+ wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15)
430
+ wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12)
431
+ print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps')
ar_deal_to_invoice_007__long/reward.py ADDED
@@ -0,0 +1,826 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: X2 — Won deal to invoice to notification
3
+ Source: generated from CUA-Gym-Hub/task_benchmark/tasks/lc_x2.py
4
+ Variant: eval
5
+ Mocks: hubspot_mock,quickbooks_mock,gmail_mock
6
+ """
7
+ import copy
8
+ import re
9
+ import sys
10
+
11
+ import requests
12
+
13
+
14
+ try:
15
+ with open('/tmp/task_web_sid', encoding='utf-8') as f:
16
+ sid = f.read().strip()
17
+ if not sid:
18
+ raise ValueError('sid is empty')
19
+ except Exception as e:
20
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
21
+ print('REWARD: 0.0')
22
+ sys.exit(0)
23
+
24
+
25
+ APP_URLS = {'hubspot': 'http://28.7.184.198:8150', 'quickbooks': 'http://28.7.184.198:8172', 'gmail': 'http://28.7.184.198:8138'}
26
+ _GO_CACHE = {}
27
+
28
+
29
+ def clamp01(x):
30
+ return max(0.0, min(1.0, float(x)))
31
+
32
+
33
+ def frac(num, den):
34
+ return 0.0 if den == 0 else num / den
35
+
36
+
37
+ def f1(true_set, pred_set):
38
+ if not true_set and not pred_set:
39
+ return 1.0
40
+ tp = len(true_set & pred_set)
41
+ if tp == 0:
42
+ return 0.0
43
+ prec = tp / len(pred_set)
44
+ rec = tp / len(true_set)
45
+ return 2 * prec * rec / (prec + rec)
46
+
47
+
48
+ def by_id(items, key='id'):
49
+ return {it.get(key): it for it in (items or []) if isinstance(it, dict)}
50
+
51
+
52
+ def has_text(haystack, *needles):
53
+ s = (haystack or '').lower()
54
+ return any(n.lower() in s for n in needles)
55
+
56
+
57
+ def norm(s):
58
+ return (str(s) if s is not None else '').strip().lower()
59
+
60
+
61
+ def _deal_amount(deal):
62
+ if not isinstance(deal, dict):
63
+ return 0.0
64
+ line_items = deal.get('lineItems') or []
65
+ if isinstance(line_items, list) and line_items:
66
+ total = 0.0
67
+ for item in line_items:
68
+ if isinstance(item, dict):
69
+ try:
70
+ total += float(item.get('amount', 0) or 0)
71
+ except (TypeError, ValueError):
72
+ continue
73
+ return total
74
+ try:
75
+ return float(deal.get('amount', 0) or 0)
76
+ except (TypeError, ValueError):
77
+ return 0.0
78
+
79
+ def _invoice_customer_name(iv):
80
+ if not isinstance(iv, dict):
81
+ return ''
82
+
83
+ customer = iv.get('customer')
84
+ if isinstance(customer, dict):
85
+ return customer.get('name') or customer.get('displayName') or customer.get('customerName') or customer.get('fullName') or ''
86
+
87
+ if isinstance(customer, list):
88
+ for c in customer:
89
+ if isinstance(c, dict):
90
+ name = c.get('name') or c.get('displayName') or c.get('customerName') or c.get('fullName')
91
+ if name:
92
+ return name
93
+ elif c:
94
+ return str(c)
95
+
96
+ return customer or iv.get('customerName') or iv.get('name') or iv.get('displayName') or iv.get('customerDisplayName') or ''
97
+
98
+
99
+ def _invoice_total(iv):
100
+ if not isinstance(iv, dict):
101
+ return 0.0
102
+
103
+ for key in ('total', 'amount', 'invoiceTotal', 'balance', 'totalAmount', 'amountDue', 'amount_total'):
104
+ value = iv.get(key)
105
+ if isinstance(value, dict):
106
+ value = value.get('amount') or value.get('value')
107
+ try:
108
+ return float(value or 0)
109
+ except (TypeError, ValueError):
110
+ continue
111
+
112
+ line_items = iv.get('lineItems') or iv.get('items') or iv.get('lines')
113
+ if isinstance(line_items, list) and line_items:
114
+ total = 0.0
115
+ for item in line_items:
116
+ if not isinstance(item, dict):
117
+ continue
118
+ raw = item.get('amount')
119
+ if raw is None:
120
+ qty = item.get('quantity', 1)
121
+ unit = item.get('unitPrice') or item.get('rate') or item.get('price')
122
+ try:
123
+ raw = float(qty or 0) * float(unit or 0)
124
+ except (TypeError, ValueError):
125
+ raw = 0
126
+ try:
127
+ total += float(raw or 0)
128
+ except (TypeError, ValueError):
129
+ continue
130
+ return total
131
+
132
+ return 0.0
133
+
134
+
135
+ def _notes_text(deal):
136
+ if not isinstance(deal, dict):
137
+ return ''
138
+
139
+ chunks = []
140
+ notes = deal.get('notes', [])
141
+ if isinstance(notes, list):
142
+ for x in notes:
143
+ if isinstance(x, dict):
144
+ chunks.append(str(x.get('body') or x.get('content') or x.get('text') or x.get('note') or x))
145
+ else:
146
+ chunks.append(str(x))
147
+ elif notes:
148
+ chunks.append(str(notes))
149
+
150
+ for key in ('activity', 'activities', 'timeline', 'comments'):
151
+ value = deal.get(key)
152
+ if isinstance(value, list):
153
+ for v in value:
154
+ if isinstance(v, dict):
155
+ chunks.append(str(v.get('body') or v.get('content') or v.get('text') or v.get('note') or v))
156
+ else:
157
+ chunks.append(str(v))
158
+ elif value:
159
+ chunks.append(str(value))
160
+
161
+ return ' '.join(chunks)
162
+
163
+
164
+ def _email_text(email):
165
+ if not isinstance(email, dict):
166
+ return str(email)
167
+
168
+ to = email.get('to', '')
169
+ if isinstance(to, list):
170
+ to = ' '.join(
171
+ (x.get('name') or x.get('email') or str(x)) if isinstance(x, dict) else str(x)
172
+ for x in to
173
+ )
174
+ elif isinstance(to, dict):
175
+ to = to.get('name') or to.get('email') or str(to)
176
+
177
+ to_recips = email.get('toRecipients', [])
178
+ if isinstance(to_recips, list):
179
+ to_recips = ' '.join(
180
+ (x.get('name') or x.get('email') or str(x)) if isinstance(x, dict) else str(x)
181
+ for x in to_recips
182
+ )
183
+ else:
184
+ to_recips = ''
185
+
186
+ return f"{to} {to_recips} {email.get('subject', '')} {email.get('body', '')}"
187
+
188
+
189
+ def _gmail_sent_emails(gmail_state):
190
+ out = []
191
+ if not isinstance(gmail_state, dict):
192
+ return out
193
+
194
+ for e in gmail_state.get('emails', []):
195
+ if not isinstance(e, dict):
196
+ continue
197
+ folder = norm(e.get('folder'))
198
+ if folder in ('sent', 'sentitems', 'sent items'):
199
+ out.append(e)
200
+ continue
201
+ if e.get('isSent') is True or e.get('sentAt') or e.get('sentDateTime'):
202
+ out.append(e)
203
+
204
+ if out:
205
+ return out
206
+
207
+ for key in ('sent', 'sentEmails', 'outbox'):
208
+ items = gmail_state.get(key, [])
209
+ if isinstance(items, list):
210
+ out.extend(x for x in items if isinstance(x, dict))
211
+ return out
212
+
213
+
214
+ def _normalize_app_name(app):
215
+ app = (app or '').strip().lower()
216
+ return app[:-5] if app.endswith('_mock') else app
217
+
218
+
219
+ def _parse_cell_id(cell_id):
220
+ if not isinstance(cell_id, str) or not cell_id:
221
+ return None
222
+ idx = 0
223
+ while idx < len(cell_id) and cell_id[idx].isalpha():
224
+ idx += 1
225
+ if idx == 0 or idx >= len(cell_id):
226
+ return None
227
+ col = 0
228
+ for ch in cell_id[:idx].upper():
229
+ col = col * 26 + (ord(ch) - ord('A') + 1)
230
+ try:
231
+ row = int(cell_id[idx:])
232
+ except ValueError:
233
+ return None
234
+ return row, col - 1
235
+
236
+
237
+ def _extract_rows_from_workbook(state):
238
+ if not isinstance(state, dict):
239
+ return None
240
+ sheets = state.get('sheets')
241
+ if not isinstance(sheets, list):
242
+ return None
243
+
244
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
245
+ headers_by_sheet = adapter.get('headers_by_sheet') if isinstance(adapter.get('headers_by_sheet'), dict) else {}
246
+
247
+ out = {}
248
+ for sh in sheets:
249
+ if not isinstance(sh, dict):
250
+ continue
251
+ name = sh.get('name') or sh.get('id') or 'Sheet1'
252
+ data = sh.get('data') if isinstance(sh.get('data'), dict) else {}
253
+
254
+ headers = headers_by_sheet.get(name)
255
+ if not headers:
256
+ cols = []
257
+ for cid, cell in data.items():
258
+ rc = _parse_cell_id(cid)
259
+ if not rc:
260
+ continue
261
+ row_idx, col_idx = rc
262
+ if row_idx != 1:
263
+ continue
264
+ value = ''
265
+ if isinstance(cell, dict):
266
+ value = cell.get('value', '')
267
+ elif cell is not None:
268
+ value = str(cell)
269
+ if value is not None and str(value) != '':
270
+ cols.append((col_idx, str(value)))
271
+ headers = [v for _, v in sorted(cols)]
272
+
273
+ if not headers:
274
+ continue
275
+
276
+ by_row = {}
277
+ for cid, cell in data.items():
278
+ rc = _parse_cell_id(cid)
279
+ if not rc:
280
+ continue
281
+ row_idx, col_idx = rc
282
+ if row_idx <= 1 or col_idx >= len(headers):
283
+ continue
284
+ if isinstance(cell, dict):
285
+ value = cell.get('value', '')
286
+ else:
287
+ value = cell
288
+ by_row.setdefault(row_idx, {})[headers[col_idx]] = value
289
+
290
+ rows = []
291
+ for row_idx in sorted(by_row.keys()):
292
+ row = by_row[row_idx]
293
+ if not any(str(row.get(h, '')).strip() for h in headers):
294
+ continue
295
+ rows.append({h: row.get(h, '') for h in headers})
296
+
297
+ out[name] = {'headers': headers, 'rows': rows}
298
+
299
+ if not out:
300
+ return None
301
+ return {'sheets': out}
302
+
303
+
304
+ def _materialize_google_sheets(payload):
305
+ for key in ('initial_state', 'current_state'):
306
+ state = payload.get(key)
307
+ if not isinstance(state, dict):
308
+ continue
309
+ maybe_rows = _extract_rows_from_workbook(state)
310
+ if maybe_rows is not None:
311
+ state['_ui_workbook'] = {
312
+ 'sheets': copy.deepcopy(state.get('sheets', [])),
313
+ 'title': state.get('title'),
314
+ }
315
+ state['sheets'] = maybe_rows['sheets']
316
+
317
+
318
+ def _materialize_slack(payload):
319
+ for key in ('initial_state', 'current_state'):
320
+ state = payload.get(key)
321
+ if not isinstance(state, dict):
322
+ continue
323
+ channels = state.get('channels') if isinstance(state.get('channels'), list) else []
324
+ messages_map = state.get('messages') if isinstance(state.get('messages'), dict) else {}
325
+ for ch in channels:
326
+ if not isinstance(ch, dict):
327
+ continue
328
+ cid = ch.get('channelId') or ch.get('id')
329
+ if not cid:
330
+ continue
331
+ msg_list = messages_map.get(cid) if isinstance(messages_map.get(cid), list) else []
332
+ channel_msgs = ch.get('messages') if isinstance(ch.get('messages'), list) else []
333
+ merged = {
334
+ (m.get('messageId') or m.get('id')): dict(m)
335
+ for m in channel_msgs
336
+ if isinstance(m, dict)
337
+ }
338
+ for m in msg_list:
339
+ if not isinstance(m, dict):
340
+ continue
341
+ mid = m.get('messageId') or m.get('id')
342
+ text = m.get('text') if m.get('text') is not None else m.get('content', '')
343
+ merged[mid] = {
344
+ 'id': mid,
345
+ 'messageId': mid,
346
+ 'text': text,
347
+ 'content': m.get('content', text),
348
+ 'senderId': m.get('senderId'),
349
+ 'timestamp': m.get('timestamp'),
350
+ 'reactions': m.get('reactions') if isinstance(m.get('reactions'), list) else [],
351
+ }
352
+ ch['messages'] = list(merged.values())
353
+
354
+
355
+ def _owner_name_map(state):
356
+ out = {}
357
+ users = state.get('users') if isinstance(state.get('users'), list) else []
358
+ for u in users:
359
+ if not isinstance(u, dict):
360
+ continue
361
+ uid = u.get('userId')
362
+ if not uid:
363
+ continue
364
+ name = (f"{u.get('firstName', '')} {u.get('lastName', '')}".strip() or u.get('name') or uid)
365
+ out[uid] = name
366
+ return out
367
+
368
+
369
+ def _materialize_salesforce(payload):
370
+ for key in ('initial_state', 'current_state'):
371
+ state = payload.get(key)
372
+ if not isinstance(state, dict):
373
+ continue
374
+
375
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
376
+ owner_names = _owner_name_map(state)
377
+
378
+ task_leads = adapter.get('task_leads') if isinstance(adapter.get('task_leads'), dict) else None
379
+ if task_leads and isinstance(state.get('leads'), list):
380
+ restored = []
381
+ for lead in state['leads']:
382
+ if not isinstance(lead, dict):
383
+ continue
384
+ lid = str(lead.get('leadId') or lead.get('id') or '')
385
+ meta = task_leads.get(lid, {})
386
+ restored.append({
387
+ 'id': meta.get('id') or lead.get('leadId') or lead.get('id'),
388
+ 'company': lead.get('company', meta.get('company', '')),
389
+ 'status': lead.get('status', 'New'),
390
+ 'ownerName': owner_names.get(lead.get('ownerId')) or meta.get('ownerName'),
391
+ 'annualRevenue': meta.get('annualRevenue', lead.get('revenue')),
392
+ })
393
+ state['leads'] = restored
394
+
395
+ task_accounts = adapter.get('task_accounts') if isinstance(adapter.get('task_accounts'), dict) else None
396
+ if task_accounts and isinstance(state.get('accounts'), list):
397
+ current_by_id = {}
398
+ for acc in state['accounts']:
399
+ if isinstance(acc, dict):
400
+ current_by_id[str(acc.get('accountId') or acc.get('id') or '')] = acc
401
+
402
+ restored_accounts = []
403
+ for aid, meta in task_accounts.items():
404
+ cur = current_by_id.get(str(aid), {})
405
+ restored_accounts.append({
406
+ 'id': meta.get('id') or aid,
407
+ 'name': meta.get('name') or cur.get('name', ''),
408
+ 'contact': meta.get('contact'),
409
+ 'wonWithin7d': bool(meta.get('wonWithin7d', False)),
410
+ 'onboardingStage': cur.get('onboardingStage', meta.get('onboardingStage')),
411
+ })
412
+ state['accounts'] = restored_accounts
413
+
414
+
415
+ def _materialize_google_docs(payload):
416
+ for key in ('initial_state', 'current_state'):
417
+ state = payload.get(key)
418
+ if not isinstance(state, dict):
419
+ continue
420
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
421
+ task_docs = adapter.get('task_documents') if isinstance(adapter.get('task_documents'), dict) else None
422
+ if not task_docs:
423
+ continue
424
+ docs_map = state.get('documents') if isinstance(state.get('documents'), dict) else {}
425
+ restored = []
426
+ for did, meta in task_docs.items():
427
+ cur = docs_map.get(did, {}) if isinstance(docs_map, dict) else {}
428
+ restored.append({
429
+ 'id': meta.get('id') or did,
430
+ 'title': cur.get('title', meta.get('title')),
431
+ 'vendor': meta.get('vendor'),
432
+ 'folder': meta.get('folder'),
433
+ 'content': cur.get('content', meta.get('content', '')),
434
+ })
435
+ state['documents'] = restored
436
+
437
+
438
+ def _adapt_payload_for_reward(app, payload):
439
+ app_name = _normalize_app_name(app)
440
+ if app_name == 'google_sheets':
441
+ _materialize_google_sheets(payload)
442
+ elif app_name == 'slack':
443
+ _materialize_slack(payload)
444
+ elif app_name == 'salesforce':
445
+ _materialize_salesforce(payload)
446
+ elif app_name == 'google_docs':
447
+ _materialize_google_docs(payload)
448
+ return payload
449
+
450
+
451
+ def go(app_name):
452
+ if app_name in _GO_CACHE:
453
+ return _GO_CACHE[app_name]
454
+
455
+ base = APP_URLS.get(app_name)
456
+ if not base:
457
+ print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)')
458
+ print('REWARD: 0.0')
459
+ sys.exit(0)
460
+
461
+ try:
462
+ resp = requests.get(f'{base}/go?sid={sid}', timeout=15)
463
+ resp.raise_for_status()
464
+ payload = resp.json()
465
+ except Exception as e:
466
+ print(f'CRITICAL: cannot fetch {app_name} go state: {e}')
467
+ print('REWARD: 0.0')
468
+ sys.exit(0)
469
+
470
+ payload = _adapt_payload_for_reward(app_name, payload)
471
+ _GO_CACHE[app_name] = payload
472
+ return payload
473
+
474
+
475
+ # === Task-specific reward (rewritten for new schema, per-deal weighted) ===
476
+ #
477
+ # Scoring model (B-mixed, decided 2026-06-15):
478
+ # - Each April-Closed-Won deal contributes up to 1.0 to its own score.
479
+ # - 6 sub-checks per deal, weights sum to 1.0:
480
+ # A1 customer 0.15 invoice exists for this deal's company
481
+ # A2 line item 0.20 exactly 1 item with the right product/qty/rate/amount
482
+ # (must also match customer name; A2 is self-contained
483
+ # and re-checks customer to prevent cross-deal mix-up)
484
+ # A3 header 0.15 same invoice has terms/date/dueDate/tax/status correct
485
+ # (must also match customer name; self-contained)
486
+ # B1 recipient 0.10 a sent gmail email addressed to the right contact
487
+ # B2 email body 0.15 email's subject + body match the template anchors,
488
+ # with subject/body invoice number self-consistent.
489
+ # Independent of A* (does NOT require a real invoice).
490
+ # C description 0.25 deal.description contains "Invoiced INV-<digits>.".
491
+ # Independent of A* (does NOT require a real invoice).
492
+ # - total_score = sum(deal_score(d) for d in won) / n
493
+ # - n is the count of April-Closed-Won deals in the initial state.
494
+ #
495
+ # Dependency chain (B-mixed):
496
+ # A1 -> A2 (re-checks customer) and A3 (re-checks customer): A group is integrated.
497
+ # B1 -> B2 (re-checks recipient): B group is internally chained.
498
+ # C is fully standalone (matches the literal pattern in description).
499
+ # A and B and C are independent of each other.
500
+
501
+ import datetime as _dt
502
+ import re as _re
503
+
504
+ _INV_NUMBER_RE = _re.compile(r'Invoiced\s+INV-(\d+)\.', _re.IGNORECASE)
505
+
506
+
507
+ def _april_won_deals(deals_initial):
508
+ out = []
509
+ for d in deals_initial or []:
510
+ if not isinstance(d, dict):
511
+ continue
512
+ if norm(d.get('stage')) != 'closedwon':
513
+ continue
514
+ close_date = (d.get('closeDate') or '').strip()
515
+ if close_date.startswith('2026-04-'):
516
+ out.append(d)
517
+ return out
518
+
519
+
520
+ def _company_name_for_deal(deal, hubspot_initial):
521
+ company_id = deal.get('companyId')
522
+ for c in hubspot_initial.get('companies', []) or []:
523
+ if isinstance(c, dict) and c.get('id') == company_id:
524
+ return (c.get('name') or '').strip()
525
+ return (deal.get('customer') or '').strip()
526
+
527
+
528
+ def _primary_contact_for_deal(deal, hubspot_initial):
529
+ contact_ids = deal.get('contactIds') or []
530
+ if not contact_ids:
531
+ return None
532
+ cid0 = contact_ids[0]
533
+ for c in hubspot_initial.get('contacts', []) or []:
534
+ if isinstance(c, dict) and c.get('id') == cid0:
535
+ return c
536
+ return None
537
+
538
+
539
+ def _qb_customer_name_by_id(qb_state):
540
+ return {
541
+ c.get('id'): (c.get('name') or '').strip()
542
+ for c in (qb_state.get('customers') or [])
543
+ if isinstance(c, dict) and c.get('id')
544
+ }
545
+
546
+
547
+ def _qb_product_by_id(qb_state):
548
+ return {
549
+ p.get('id'): p
550
+ for p in (qb_state.get('products') or [])
551
+ if isinstance(p, dict) and p.get('id')
552
+ }
553
+
554
+
555
+ def _add_days(date_str, days):
556
+ try:
557
+ d = _dt.datetime.strptime(date_str, '%Y-%m-%d').date()
558
+ except (TypeError, ValueError):
559
+ return ''
560
+ return (d + _dt.timedelta(days=days)).isoformat()
561
+
562
+
563
+ def _invoice_items(iv):
564
+ items = iv.get('items')
565
+ if isinstance(items, list):
566
+ return items
567
+ items = iv.get('lineItems')
568
+ if isinstance(items, list):
569
+ return items
570
+ return []
571
+
572
+
573
+ def _check_a1_customer(deal, hubspot_initial, invoices, qb_cust_by_id):
574
+ target_name = norm(_company_name_for_deal(deal, hubspot_initial))
575
+ if not target_name:
576
+ return None
577
+ for iv in invoices or []:
578
+ if not isinstance(iv, dict):
579
+ continue
580
+ cust_name = norm(qb_cust_by_id.get(iv.get('customerId'), ''))
581
+ if not cust_name:
582
+ cust_name = norm(_invoice_customer_name(iv))
583
+ if cust_name and cust_name == target_name:
584
+ return iv
585
+ return None
586
+
587
+
588
+ def _check_a2_line_item(deal, hubspot_initial, invoices, qb_cust_by_id, qb_prod_by_id):
589
+ """Self-contained: find ANY invoice for the deal's company that has the right
590
+ single line item. Independent of A1's pick (but typically returns same one)."""
591
+ target_name = norm(_company_name_for_deal(deal, hubspot_initial))
592
+ if not target_name:
593
+ return False
594
+ deal_name = deal.get('name') or ''
595
+ if ' - ' not in deal_name:
596
+ return False
597
+ expected_product = deal_name.split(' - ', 1)[1].strip()
598
+ deal_amt = _deal_amount(deal)
599
+
600
+ for invoice in invoices or []:
601
+ if not isinstance(invoice, dict):
602
+ continue
603
+ cust_name = norm(qb_cust_by_id.get(invoice.get('customerId'), ''))
604
+ if not cust_name:
605
+ cust_name = norm(_invoice_customer_name(invoice))
606
+ if cust_name != target_name:
607
+ continue
608
+ items = _invoice_items(invoice)
609
+ if len(items) != 1:
610
+ continue
611
+ item = items[0]
612
+ if not isinstance(item, dict):
613
+ continue
614
+ product = qb_prod_by_id.get(item.get('productId')) or {}
615
+ if norm(product.get('name', '')) != norm(expected_product):
616
+ continue
617
+ try:
618
+ qty = float(item.get('qty', 0) or 0)
619
+ except (TypeError, ValueError):
620
+ qty = 0
621
+ if abs(qty - 1.0) > 1e-6:
622
+ continue
623
+ try:
624
+ rate = float(item.get('rate', 0) or 0)
625
+ amt = float(item.get('amount', 0) or 0)
626
+ except (TypeError, ValueError):
627
+ continue
628
+ if abs(rate - deal_amt) > 0.5 or abs(amt - deal_amt) > 0.5:
629
+ continue
630
+ return True
631
+ return False
632
+
633
+
634
+ def _check_a3_header(deal, hubspot_initial, invoices, qb_cust_by_id):
635
+ """Self-contained: find ANY invoice for the deal's company with correct header."""
636
+ target_name = norm(_company_name_for_deal(deal, hubspot_initial))
637
+ if not target_name:
638
+ return False
639
+ close_date = (deal.get('closeDate') or '').strip()
640
+ expected_due = _add_days(close_date, 30)
641
+
642
+ for invoice in invoices or []:
643
+ if not isinstance(invoice, dict):
644
+ continue
645
+ cust_name = norm(qb_cust_by_id.get(invoice.get('customerId'), ''))
646
+ if not cust_name:
647
+ cust_name = norm(_invoice_customer_name(invoice))
648
+ if cust_name != target_name:
649
+ continue
650
+ if norm(invoice.get('terms')) != 'net 30':
651
+ continue
652
+ if (invoice.get('date') or '').strip() != close_date:
653
+ continue
654
+ if (invoice.get('dueDate') or '').strip() != expected_due:
655
+ continue
656
+ try:
657
+ tax = float(invoice.get('tax', 0) or 0)
658
+ except (TypeError, ValueError):
659
+ tax = 0
660
+ if abs(tax) > 0.01:
661
+ continue
662
+ if norm(invoice.get('status')) != 'sent':
663
+ continue
664
+ return True
665
+ return False
666
+
667
+
668
+ def _check_b1_recipient(deal, hubspot_initial, sent_emails):
669
+ contact = _primary_contact_for_deal(deal, hubspot_initial)
670
+ if not contact:
671
+ return None
672
+ target_email = norm(contact.get('email'))
673
+ if not target_email:
674
+ return None
675
+ for e in sent_emails or []:
676
+ if not isinstance(e, dict):
677
+ continue
678
+ if target_email in norm(_email_text(e)):
679
+ return e
680
+ return None
681
+
682
+
683
+ def _check_b2_email_body(deal, hubspot_initial, sent_emails):
684
+ """Self-contained: find ANY sent email to the deal's primary contact whose
685
+ subject contains 'Invoice #<n>', body contains 'INVOICE #<n>' (same <n>),
686
+ 'Total: $<deal.amount>', and 'Status: Sent'. Independent of any QB invoice."""
687
+ contact = _primary_contact_for_deal(deal, hubspot_initial)
688
+ if not contact:
689
+ return False
690
+ target_email = norm(contact.get('email'))
691
+ if not target_email:
692
+ return False
693
+ deal_amt = _deal_amount(deal)
694
+ amt_int = 'total: ${}'.format(int(round(deal_amt)))
695
+ amt_dec = 'total: ${:.2f}'.format(deal_amt)
696
+ subject_re = _re.compile(r'invoice\s*#\s*(\d+)')
697
+
698
+ for e in sent_emails or []:
699
+ if not isinstance(e, dict):
700
+ continue
701
+ if target_email not in norm(_email_text(e)):
702
+ continue
703
+ subject = norm(e.get('subject') or '')
704
+ body = e.get('body') or ''
705
+ body_text = _re.sub(r'<[^>]+>', ' ', body)
706
+ nb = norm(body_text)
707
+
708
+ m_sub = subject_re.search(subject)
709
+ if not m_sub:
710
+ continue
711
+ n = m_sub.group(1)
712
+ # Body must reference the SAME number (self-consistent).
713
+ if 'invoice #{}'.format(n) not in nb:
714
+ continue
715
+ if amt_int not in nb and amt_dec not in nb:
716
+ continue
717
+ if 'status: sent' not in nb:
718
+ continue
719
+ return True
720
+ return False
721
+
722
+
723
+ def _check_c_description(deal_current):
724
+ """Self-contained: deal.description contains 'Invoiced INV-<digits>.'.
725
+ Independent of any QB invoice. (Falls back to deal.notes for legacy agents.)"""
726
+ if not deal_current:
727
+ return False
728
+ desc = deal_current.get('description') or ''
729
+ if _INV_NUMBER_RE.search(desc):
730
+ return True
731
+ notes_text = _notes_text(deal_current)
732
+ if _INV_NUMBER_RE.search(notes_text):
733
+ return True
734
+ return False
735
+
736
+
737
+ WEIGHTS = {
738
+ 'A1_customer': 0.15,
739
+ 'A2_line_item': 0.20,
740
+ 'A3_header': 0.15,
741
+ 'B1_recipient': 0.10,
742
+ 'B2_email': 0.15,
743
+ 'C_description': 0.25,
744
+ }
745
+
746
+
747
+ def reward(go):
748
+ hubspot_i = go('hubspot').get('initial_state', {}) or {}
749
+ hubspot_c = go('hubspot').get('current_state', {}) or {}
750
+ qb_c = go('quickbooks').get('current_state', {}) or {}
751
+ gmail_c = go('gmail').get('current_state', {}) or {}
752
+
753
+ deals_i = hubspot_i.get('deals', []) or []
754
+ deals_c_by_id = {
755
+ d.get('id'): d
756
+ for d in (hubspot_c.get('deals', []) or [])
757
+ if isinstance(d, dict)
758
+ }
759
+ invoices = qb_c.get('invoices', []) or []
760
+ qb_cust_by_id = _qb_customer_name_by_id(qb_c)
761
+ qb_prod_by_id = _qb_product_by_id(qb_c)
762
+ sent_emails = _gmail_sent_emails(gmail_c)
763
+
764
+ won = _april_won_deals(deals_i)
765
+ n = len(won)
766
+ if n == 0:
767
+ print('DEBUG_054e615f n=0 -> vacuous REWARD=1.0')
768
+ return 1.0
769
+
770
+ per_deal_lines = []
771
+ pass_counts = {k: 0 for k in WEIGHTS}
772
+ total = 0.0
773
+
774
+ for d in won:
775
+ deal_id = d.get('id')
776
+ deal_current = deals_c_by_id.get(deal_id, {})
777
+
778
+ # A1 picks an invoice for debug logging; A2/A3 are self-contained
779
+ # but conceptually still belong to the same A group.
780
+ invoice = _check_a1_customer(d, hubspot_i, invoices, qb_cust_by_id)
781
+
782
+ checks = {
783
+ 'A1_customer': invoice is not None,
784
+ 'A2_line_item': _check_a2_line_item(d, hubspot_i, invoices, qb_cust_by_id, qb_prod_by_id),
785
+ 'A3_header': _check_a3_header(d, hubspot_i, invoices, qb_cust_by_id),
786
+ 'B1_recipient': _check_b1_recipient(d, hubspot_i, sent_emails) is not None,
787
+ 'B2_email': _check_b2_email_body(d, hubspot_i, sent_emails),
788
+ 'C_description': _check_c_description(deal_current),
789
+ }
790
+
791
+ deal_score = 0.0
792
+ for k, ok in checks.items():
793
+ if ok:
794
+ deal_score += WEIGHTS[k]
795
+ pass_counts[k] += 1
796
+ total += deal_score
797
+
798
+ flags = ' '.join(
799
+ '{}={}'.format(k.split('_', 1)[0], 'Y' if v else 'N')
800
+ for k, v in checks.items()
801
+ )
802
+ company = _company_name_for_deal(d, hubspot_i) or '?'
803
+ per_deal_lines.append(
804
+ ' {} {:<12s}: score={:.3f} {}'.format(deal_id, company, deal_score, flags)
805
+ )
806
+
807
+ score = total / n
808
+
809
+ print('DEBUG_054e615f n={}'.format(n))
810
+ for line in per_deal_lines:
811
+ print(line)
812
+ rates = ' '.join('{}={}/{}'.format(k.split('_', 1)[0], pass_counts[k], n) for k in WEIGHTS)
813
+ print('sub-check pass rates: {}'.format(rates))
814
+ print('total = sum / n = {:.4f} / {} = {:.4f}'.format(total, n, score))
815
+
816
+ return clamp01(score)
817
+
818
+
819
+ try:
820
+ score = float(reward(go))
821
+ except Exception as exc:
822
+ print(f'ERROR: reward() raised {exc!r}')
823
+ score = 0.0
824
+
825
+ score = clamp01(score)
826
+ print(f'\nREWARD: {round(score, 4)}')
ar_invoice_003/initial_setup.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: AR invoice issuance chain (Salesforce -> Google Sheets -> Slack)
3
+ Task ID: ar_invoice_003
4
+ Domain: mock_websites (salesforce_mock + google_sheets_mock + slack_mock)
5
+
6
+ Injects the PRE-TASK baseline into all three mocks under the INITIAL sid.
7
+ - Salesforce: read-only source of truth, contains the Closed-Won opportunity.
8
+ - Google Sheets 'AR Invoice Ledger': invoices through row 14 (INV-1042), NO INV-1043.
9
+ - Slack #finance: prior finance chatter, NO INV-1043 issuance message.
10
+ """
11
+ import copy
12
+ import hashlib
13
+ import json
14
+ import os
15
+ import shlex
16
+ import subprocess
17
+ import time
18
+ import uuid
19
+
20
+ import requests
21
+
22
+ TASK_ID = 'ar_invoice_001'
23
+ SID = 'cua-' + hashlib.md5(TASK_ID.encode()).hexdigest()[:16]
24
+
25
+ SF_URL = 'http://28.7.184.198:8175'
26
+ GS_URL = 'http://28.7.184.198:8145'
27
+ SL_URL = 'http://28.7.184.198:8178'
28
+ PROXY = {'http': 'http://star-proxy.oa.com:3128', 'https': 'http://star-proxy.oa.com:3128'}
29
+
30
+
31
+ # ---------------------------------------------------------------- HTTP helpers
32
+ def http_get(url):
33
+ last = None
34
+ for attempt in range(4):
35
+ for proxies in (None, PROXY):
36
+ try:
37
+ r = requests.get(url, timeout=25, proxies=proxies)
38
+ if r.status_code == 200:
39
+ return r
40
+ last = Exception(f'HTTP {r.status_code}: {r.text[:200]}')
41
+ except Exception as e:
42
+ last = e
43
+ time.sleep(1.0)
44
+ raise last
45
+
46
+
47
+ def http_post(url, payload):
48
+ last = None
49
+ for attempt in range(4):
50
+ for proxies in (None, PROXY):
51
+ try:
52
+ r = requests.post(url, json=payload, timeout=30, proxies=proxies)
53
+ if r.status_code == 200:
54
+ return r
55
+ last = Exception(f'HTTP {r.status_code}: {r.text[:200]}')
56
+ except Exception as e:
57
+ last = e
58
+ time.sleep(1.0)
59
+ raise last
60
+
61
+
62
+ # ----------------------------------------------------------- state builders
63
+ def build_salesforce_state():
64
+ """Fetch the rich default Salesforce org and patch the target opportunity."""
65
+ probe = 'cua-probe-' + uuid.uuid4().hex[:8]
66
+ d = http_get(f'{SF_URL}/go?sid={probe}').json()
67
+ state = copy.deepcopy(d.get('initial_state') or d.get('current_state'))
68
+
69
+ # Make user-4 the AE "Sarah Chen" (opportunity owner / Slack recipient).
70
+ for u in state.get('users', []):
71
+ if u.get('userId') == 'user-4':
72
+ u['firstName'] = 'Sarah'
73
+ u['lastName'] = 'Chen'
74
+ u['email'] = 'sarah.chen@company.com'
75
+ u['title'] = 'Account Executive'
76
+
77
+ # Patch opp-1 into the Closed-Won target opportunity (source of truth).
78
+ for opp in state.get('opportunities', []):
79
+ if opp.get('opportunityId') == 'opp-1':
80
+ opp['name'] = 'Acme Corp - Platform License'
81
+ opp['accountId'] = 'account-1'
82
+ opp['amount'] = 48000
83
+ opp['stage'] = 'Closed Won'
84
+ opp['probability'] = 100
85
+ opp['closeDate'] = '2026-06-24T00:00:00.000Z'
86
+ opp['paymentTerms'] = 'Net 30'
87
+ opp['type'] = 'New Business'
88
+ opp['ownerId'] = 'user-4'
89
+ opp['nextStep'] = 'Issue AR invoice'
90
+ opp['description'] = 'Platform license deal, closed won. Net 30 payment terms.'
91
+ break
92
+ return state
93
+
94
+
95
+ def _cell(value, fmt=None, bold=False):
96
+ c = {'value': str(value), 'formula': str(value)}
97
+ style = {}
98
+ if bold:
99
+ style = {'bold': True, 'bg': '#E8EAED', 'align': 'center'}
100
+ if style:
101
+ c['style'] = style
102
+ if fmt:
103
+ c['format'] = fmt
104
+ return c
105
+
106
+
107
+ # Ledger baseline rows: A=Invoice#, B=Customer, C=Deal/Contract, D=Amount,
108
+ # E=Issue Date, F=Due Date, G=Status, H=AE/Owner. Rows 2..14 (INV-1030..INV-1042).
109
+ LEDGER_ROWS = [
110
+ ['INV-1030', 'Globex Inc', 'Globex - Annual Support', 12000, '2026-04-02', '2026-05-02', 'Paid', 'Marcus Johnson'],
111
+ ['INV-1031', 'Initech', 'Initech - SaaS Subscription', 8500, '2026-04-10', '2026-05-10', 'Paid', 'Sarah Chen'],
112
+ ['INV-1032', 'Umbrella LLC', 'Umbrella - Platform License', 30000, '2026-04-15', '2026-05-15', 'Paid', 'Priya Patel'],
113
+ ['INV-1033', 'Soylent Corp', 'Soylent - Data Add-on', 5400, '2026-04-22', '2026-05-22', 'Paid', 'Marcus Johnson'],
114
+ ['INV-1034', 'Hooli', 'Hooli - Enterprise License', 64000, '2026-05-01', '2026-05-31', 'Paid', 'Sarah Chen'],
115
+ ['INV-1035', 'Vandelay Industries', 'Vandelay - Consulting', 15000, '2026-05-06', '2026-06-05', 'Sent', 'Priya Patel'],
116
+ ['INV-1036', 'Stark Industries', 'Stark - Platform License', 52000, '2026-05-12', '2026-06-11', 'Sent', 'Marcus Johnson'],
117
+ ['INV-1037', 'Wonka Co', 'Wonka - Annual Support', 9800, '2026-05-18', '2026-06-17', 'Sent', 'Sarah Chen'],
118
+ ['INV-1038', 'Cyberdyne', 'Cyberdyne - SaaS Subscription', 22000, '2026-05-24', '2026-06-23', 'Sent', 'Priya Patel'],
119
+ ['INV-1039', 'Wayne Enterprises', 'Wayne - Data Add-on', 7600, '2026-05-29', '2026-06-28', 'Sent', 'Marcus Johnson'],
120
+ ['INV-1040', 'Tyrell Corp', 'Tyrell - Platform License', 41000, '2026-06-03', '2026-07-03', 'Sent', 'Sarah Chen'],
121
+ ['INV-1041', 'Gekko & Co', 'Gekko - Consulting', 18500, '2026-06-09', '2026-07-09', 'Draft', 'Priya Patel'],
122
+ ['INV-1042', 'Massive Dynamic', 'Massive Dynamic - Enterprise License', 73000, '2026-06-15', '2026-07-15', 'Draft', 'Marcus Johnson'],
123
+ ]
124
+ HEADERS = ['Invoice #', 'Customer', 'Deal/Contract', 'Amount', 'Issue Date', 'Due Date', 'Status', 'AE/Owner']
125
+ COL_FMT = [None, None, None, 'currency', 'date', 'date', None, None]
126
+
127
+
128
+ def build_ledger_data(rows):
129
+ cols = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
130
+ data = {}
131
+ for i, h in enumerate(HEADERS):
132
+ data[f'{cols[i]}1'] = _cell(h, bold=True)
133
+ for r, row in enumerate(rows, start=2):
134
+ for i, val in enumerate(row):
135
+ data[f'{cols[i]}{r}'] = _cell(val, fmt=COL_FMT[i])
136
+ return data
137
+
138
+
139
+ def build_sheets_state(rows):
140
+ return {
141
+ 'id': 'workbook_1',
142
+ 'title': 'AR Invoice Ledger',
143
+ 'activeSheetId': 'sheet_1',
144
+ 'selectedCell': 'A1',
145
+ 'selectionRange': None,
146
+ 'clipboard': None,
147
+ 'isDragging': False,
148
+ 'undoStack': [],
149
+ 'redoStack': [],
150
+ 'namedRanges': [],
151
+ 'conditionalFormats': [],
152
+ 'charts': [],
153
+ 'showGridlines': True,
154
+ 'showFormulas': False,
155
+ 'zoom': 100,
156
+ 'sheets': [{
157
+ 'id': 'sheet_1',
158
+ 'name': 'Ledger',
159
+ 'rowCount': 100,
160
+ 'colCount': 26,
161
+ 'frozenRows': 1,
162
+ 'frozenCols': 0,
163
+ 'tabColor': '#1A73E8',
164
+ 'isHidden': False,
165
+ 'columnWidths': {'0': 100, '1': 150, '2': 230, '3': 100, '4': 110, '5': 110, '6': 90, '7': 140},
166
+ 'data': build_ledger_data(rows),
167
+ }],
168
+ }
169
+
170
+
171
+ def build_slack_state(include_issuance=False):
172
+ users = [
173
+ {'userId': 'user_1', 'fullName': 'John Smith', 'displayName': 'John', 'email': 'john.smith@company.com',
174
+ 'avatar': 'https://picsum.photos/200/200?random=1', 'title': 'AR Analyst', 'status': 'online',
175
+ 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'},
176
+ {'userId': 'user_2', 'fullName': 'Sarah Chen', 'displayName': 'Sarah', 'email': 'sarah.chen@company.com',
177
+ 'avatar': 'https://picsum.photos/200/200?random=2', 'title': 'Account Executive', 'status': 'online',
178
+ 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Los_Angeles'},
179
+ {'userId': 'user_3', 'fullName': 'Marcus Johnson', 'displayName': 'Marcus', 'email': 'marcus.johnson@company.com',
180
+ 'avatar': 'https://picsum.photos/200/200?random=3', 'title': 'Finance Manager', 'status': 'away',
181
+ 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'},
182
+ {'userId': 'user_4', 'fullName': 'Priya Patel', 'displayName': 'Priya', 'email': 'priya.patel@company.com',
183
+ 'avatar': 'https://picsum.photos/200/200?random=4', 'title': 'Account Executive', 'status': 'online',
184
+ 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Chicago'},
185
+ ]
186
+ current_user = copy.deepcopy(users[0])
187
+ channels = [
188
+ {'channelId': 'general', 'name': 'general', 'description': 'Company-wide announcements', 'topic': '',
189
+ 'isPrivate': False, 'isStarred': False, 'members': ['user_1', 'user_2', 'user_3', 'user_4'],
190
+ 'createdBy': 'user_1', 'createdAt': '2026-01-01T10:00:00Z', 'pinnedMessages': [], 'unreadCount': 0},
191
+ {'channelId': 'finance', 'name': 'finance', 'description': 'Accounts receivable & billing',
192
+ 'topic': 'Invoicing, AR, collections', 'isPrivate': False, 'isStarred': True,
193
+ 'members': ['user_1', 'user_2', 'user_3', 'user_4'], 'createdBy': 'user_3',
194
+ 'createdAt': '2026-01-05T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0},
195
+ ]
196
+ finance_msgs = [
197
+ {'messageId': 'msg_f1', 'senderId': 'user_3', 'content': 'Reminder: month-end AR close is this Friday.',
198
+ 'timestamp': '2026-06-22T14:00:00Z', 'threadId': None, 'reactions': [], 'attachments': [], 'isEdited': False},
199
+ {'messageId': 'msg_f2', 'senderId': 'user_2', 'content': 'Can someone confirm the Tyrell invoice went out?',
200
+ 'timestamp': '2026-06-22T15:10:00Z', 'threadId': None, 'reactions': [], 'attachments': [], 'isEdited': False},
201
+ {'messageId': 'msg_f3', 'senderId': 'user_1', 'content': 'Yes, INV-1040 was sent on the 3rd.',
202
+ 'timestamp': '2026-06-22T15:18:00Z', 'threadId': None, 'reactions': [], 'attachments': [], 'isEdited': False},
203
+ ]
204
+ if include_issuance:
205
+ finance_msgs.append({
206
+ 'messageId': 'msg_f_inv1043', 'senderId': 'user_1',
207
+ 'content': ('@Sarah Chen Invoice INV-1043 for Acme Corp ($48,000, due 2026-07-24) '
208
+ 'has been issued for the Acme Corp - Platform License deal.'),
209
+ 'timestamp': '2026-06-24T15:30:00Z', 'threadId': None,
210
+ 'reactions': [], 'attachments': [], 'isEdited': False,
211
+ })
212
+ return {
213
+ 'currentUser': current_user,
214
+ 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Acme Corp', 'icon': ''},
215
+ 'users': users,
216
+ 'channels': channels,
217
+ 'messages': {
218
+ 'general': [
219
+ {'messageId': 'msg_g1', 'senderId': 'user_2', 'content': 'Morning team!',
220
+ 'timestamp': '2026-06-22T09:00:00Z', 'threadId': None, 'reactions': [], 'attachments': [], 'isEdited': False},
221
+ ],
222
+ 'finance': finance_msgs,
223
+ },
224
+ 'threads': {},
225
+ 'dms': [],
226
+ 'bookmarkedMessages': [],
227
+ 'callHistory': [],
228
+ 'settings': {'theme': 'light', 'notifications': 'all', 'displayDensity': 'comfortable',
229
+ 'showAvatars': True, 'use24Hour': False},
230
+ 'invitations': [],
231
+ 'notifications': [],
232
+ }
233
+
234
+
235
+ # ------------------------------------------------------------------- GUI launch
236
+ def launch_gui(command, delay_sec=1.0):
237
+ env = os.environ.copy()
238
+ env['DISPLAY'] = ':0'
239
+ subprocess.Popen(shlex.split(command), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env)
240
+ time.sleep(delay_sec)
241
+
242
+
243
+ # --------------------------------------------------------------------- main
244
+ def main():
245
+ with open('/tmp/task_web_sid', 'w') as f:
246
+ f.write(SID)
247
+ print(f'INITIAL sid = {SID}')
248
+
249
+ # Inject baseline (action:set) into all three mocks.
250
+ http_post(f'{SF_URL}/post?sid={SID}', {'action': 'set', 'state': build_salesforce_state()})
251
+ print('Salesforce baseline injected.')
252
+ http_post(f'{GS_URL}/post?sid={SID}', {'action': 'set', 'state': build_sheets_state(LEDGER_ROWS)})
253
+ print('Google Sheets baseline injected (last row INV-1042).')
254
+ http_post(f'{SL_URL}/post?sid={SID}', {'action': 'set', 'state': build_slack_state(include_issuance=False)})
255
+ print('Slack baseline injected (no INV-1043 issuance message).')
256
+
257
+ # Verify each baseline.
258
+ sf = http_get(f'{SF_URL}/go?sid={SID}').json()
259
+ opp = next(o for o in sf['current_state']['opportunities'] if o['opportunityId'] == 'opp-1')
260
+ assert opp['name'] == 'Acme Corp - Platform License' and opp['stage'] == 'Closed Won' and opp['amount'] == 48000
261
+ gs = http_get(f'{GS_URL}/go?sid={SID}').json()
262
+ data = gs['current_state']['sheets'][0]['data']
263
+ assert data['A14']['value'] == 'INV-1042', f"A14={data['A14']['value']}"
264
+ assert 'A15' not in data, 'baseline must NOT contain INV-1043 row'
265
+ sl = http_get(f'{SL_URL}/go?sid={SID}').json()
266
+ fin = sl['current_state']['messages']['finance']
267
+ assert not any('INV-1043' in m['content'] for m in fin), 'baseline Slack must NOT mention INV-1043'
268
+ print('Verified baseline: SF opp Closed Won, sheet ends at INV-1042, no INV-1043 anywhere.')
269
+
270
+ # GUI-ready: open all three tabs in Chrome on the VM display.
271
+ launch_gui(
272
+ f'google-chrome --no-first-run --no-default-browser-check '
273
+ f'"{SF_URL}/?sid={SID}" "{GS_URL}/?sid={SID}" "{SL_URL}/?sid={SID}"',
274
+ delay_sec=3.0,
275
+ )
276
+ print(f'GUI_READY: launched Chrome with salesforce/sheets/slack tabs (sid={SID})')
277
+
278
+
279
+ main()
ar_invoice_003/reward.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: AR invoice chained task (Salesforce -> Google Sheets -> Slack)
3
+ Task ID: ar_invoice_003
4
+ Domain: mock_websites (google_sheets + slack)
5
+
6
+ Scoring (1.0 total) — ONLY Google Sheet + Slack are scored; Salesforce is READ-ONLY:
7
+ - Sheet (0.5): a genuinely NEW ledger row (INV-1043) is appended below the existing
8
+ data with all 8 columns A..H matching the expected values, AND existing rows are
9
+ left unchanged. Per-cell graded (0.5 * matched_cells/8), gated on the row being new
10
+ and existing rows being untouched.
11
+ - Slack (0.5): a NEW message in #finance addressed to Sarah Chen announcing that
12
+ invoice INV-1043 for Acme Corp ($48,000, due 2026-07-24) has been issued.
13
+ Graded over 5 keyword criteria (0.1 each).
14
+
15
+ Both components are anchored to task-introduced changes: they FAIL on initial_env
16
+ (no new row, no new message) and PASS on golden_env.
17
+ """
18
+ # --- injected by remap_cua_gym_ip.py: resolve dynamic mock host -> self-hosted IP ---
19
+ _CUA_GYM_REMAP_INJECTED = True
20
+ _CUA_GYM_SLUG_MAP = {'12306': 'http://28.7.184.198:8100', 'canvas-lms': 'http://28.7.184.198:8101', 'expensify': 'http://28.7.184.198:8102', 'pacs-viewer': 'http://28.7.184.198:8103', 'sap': 'http://28.7.184.198:8104', 'servicenow': 'http://28.7.184.198:8105', 'tradingview': 'http://28.7.184.198:8106', 'zendesk': 'http://28.7.184.198:8107', 'adp': 'http://28.7.184.198:8108', 'airtable': 'http://28.7.184.198:8109', 'aliyun': 'http://28.7.184.198:8110', 'amazon': 'http://28.7.184.198:8111', 'amazon-seller': 'http://28.7.184.198:8112', 'amplitude': 'http://28.7.184.198:8113', 'asana': 'http://28.7.184.198:8114', 'aws-console': 'http://28.7.184.198:8115', 'azure': 'http://28.7.184.198:8116', 'bamboohr': 'http://28.7.184.198:8117', 'booking-com': 'http://28.7.184.198:8118', 'canva': 'http://28.7.184.198:8119', 'canvas': 'http://28.7.184.198:8120', 'circleci': 'http://28.7.184.198:8121', 'clio': 'http://28.7.184.198:8122', 'cloudflare': 'http://28.7.184.198:8123', 'coinbase': 'http://28.7.184.198:8124', 'confluence': 'http://28.7.184.198:8125', 'contractbook': 'http://28.7.184.198:8126', 'datadog': 'http://28.7.184.198:8127', 'dingtalk': 'http://28.7.184.198:8128', 'discord': 'http://28.7.184.198:8129', 'docusign': 'http://28.7.184.198:8130', 'ebay': 'http://28.7.184.198:8131', 'epic-health': 'http://28.7.184.198:8132', 'expedia': 'http://28.7.184.198:8133', 'facebook': 'http://28.7.184.198:8134', 'feishu': 'http://28.7.184.198:8135', 'github': 'http://28.7.184.198:8136', 'gitlab': 'http://28.7.184.198:8137', 'gmail': 'http://28.7.184.198:8138', 'google-ads': 'http://28.7.184.198:8139', 'google-analytics': 'http://28.7.184.198:8140', 'google-calendar': 'http://28.7.184.198:8141', 'google-docs': 'http://28.7.184.198:8142', 'google-drive': 'http://28.7.184.198:8143', 'google-flights': 'http://28.7.184.198:8144', 'google-sheets': 'http://28.7.184.198:8145', 'greenhouse': 'http://28.7.184.198:8146', 'gusto': 'http://28.7.184.198:8147', 'hotjar': 'http://28.7.184.198:8148', 'hubspot-marketing': 'http://28.7.184.198:8149', 'hubspot': 'http://28.7.184.198:8150', 'instacart': 'http://28.7.184.198:8151', 'instagram': 'http://28.7.184.198:8152', 'jira': 'http://28.7.184.198:8153', 'klaviyo': 'http://28.7.184.198:8154', 'lattice': 'http://28.7.184.198:8155', 'linear': 'http://28.7.184.198:8156', 'linkedin': 'http://28.7.184.198:8157', 'looker-studio': 'http://28.7.184.198:8158', 'lucidchart': 'http://28.7.184.198:8159', 'mailchimp': 'http://28.7.184.198:8160', 'meta-ads': 'http://28.7.184.198:8161', 'microsoft-teams': 'http://28.7.184.198:8162', 'miro': 'http://28.7.184.198:8163', 'mixpanel': 'http://28.7.184.198:8164', 'monday': 'http://28.7.184.198:8165', 'notion': 'http://28.7.184.198:8166', 'openreview': 'http://28.7.184.198:8167', 'outlook-web': 'http://28.7.184.198:8168', 'paypal': 'http://28.7.184.198:8169', 'pinterest': 'http://28.7.184.198:8170', 'postman': 'http://28.7.184.198:8171', 'quickbooks': 'http://28.7.184.198:8172', 'reddit': 'http://28.7.184.198:8173', 'robinhood': 'http://28.7.184.198:8174', 'salesforce': 'http://28.7.184.198:8175', 'sentry': 'http://28.7.184.198:8176', 'shopify-admin': 'http://28.7.184.198:8177', 'slack': 'http://28.7.184.198:8178', 'stripe-dashboard': 'http://28.7.184.198:8179', 'tableau': 'http://28.7.184.198:8180', 'taobao-seller': 'http://28.7.184.198:8181', 'trello': 'http://28.7.184.198:8182', 'tripadvisor': 'http://28.7.184.198:8183', 'twitter': 'http://28.7.184.198:8184', 'uber-eats': 'http://28.7.184.198:8185', 'vercel': 'http://28.7.184.198:8186', 'wandb': 'http://28.7.184.198:8187', 'wechat': 'http://28.7.184.198:8188', 'weibo': 'http://28.7.184.198:8189', 'westlaw': 'http://28.7.184.198:8190', 'woocommerce': 'http://28.7.184.198:8191', 'workday': 'http://28.7.184.198:8192', 'xiaohongshu': 'http://28.7.184.198:8193', 'youtube': 'http://28.7.184.198:8194', 'zhihu': 'http://28.7.184.198:8195', 'zillow': 'http://28.7.184.198:8196', 'zoom-web': 'http://28.7.184.198:8197'}
21
+ def _cua_gym_base(_slug):
22
+ return _CUA_GYM_SLUG_MAP.get(_slug, 'https://cua-gym-%s.xlang.ai' % _slug)
23
+ # --- end injected ---
24
+ import json
25
+ import re
26
+ import sys
27
+ import time
28
+
29
+ import requests
30
+
31
+ # --- Read sid (written by initial_setup.py) ---
32
+ try:
33
+ with open('/tmp/task_web_sid') as f:
34
+ SID = f.read().strip()
35
+ if not SID:
36
+ raise ValueError('sid is empty')
37
+ except Exception as e:
38
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
39
+ print('REWARD: 0.0')
40
+ sys.exit(0)
41
+
42
+ PROXY = 'http://star-proxy.oa.com:3128'
43
+
44
+
45
+ def fetch_state(app):
46
+ """Fetch /go for a mock app. Proxy-first, direct fallback, with retries.
47
+ Returns parsed JSON dict or None."""
48
+ url = f'{_cua_gym_base(app)}/go?sid={SID}'
49
+ attempts = [
50
+ {'proxies': {'http': PROXY, 'https': PROXY}},
51
+ {'proxies': {'http': PROXY, 'https': PROXY}},
52
+ {'proxies': None},
53
+ {'proxies': None},
54
+ ]
55
+ for i, kw in enumerate(attempts):
56
+ try:
57
+ r = requests.get(url, timeout=30, **kw)
58
+ r.raise_for_status()
59
+ return r.json()
60
+ except Exception as e:
61
+ print(f'WARN: fetch {app} attempt {i + 1} failed: {e}')
62
+ time.sleep(2)
63
+ return None
64
+
65
+
66
+ def norm(s):
67
+ """Lowercase + collapse whitespace for robust text compare."""
68
+ return re.sub(r'\s+', ' ', str(s).strip().lower())
69
+
70
+
71
+ def norm_amount(s):
72
+ """Strip currency symbols / commas / spaces. Drop a trailing '.0'/'.00' decimal."""
73
+ if s is None:
74
+ return ''
75
+ x = re.sub(r'[^0-9.]', '', str(s))
76
+ if '.' in x:
77
+ x = x.rstrip('0').rstrip('.')
78
+ return x
79
+
80
+
81
+ def date_matches(value, expected):
82
+ """Match the expected year/month/day regardless of separators or component order."""
83
+ if value is None:
84
+ return False
85
+ year, month, day = int(expected[:4]), int(expected[4:6]), int(expected[6:8])
86
+ parts = [int(x) for x in re.findall(r'\d+', str(value))]
87
+ if year in parts and month in parts and day in parts:
88
+ return True
89
+ compact = re.sub(r'[^0-9]', '', str(value))
90
+ return compact in {
91
+ f'{year:04d}{month:02d}{day:02d}',
92
+ f'{month:02d}{day:02d}{year:04d}',
93
+ f'{day:02d}{month:02d}{year:04d}',
94
+ }
95
+
96
+
97
+ def sheet_rows(state):
98
+ """Return {row_index: [A..H values or None]} for non-empty rows of sheet 0."""
99
+ sheets = state.get('sheets') or []
100
+ if not sheets:
101
+ return {}
102
+ data = sheets[0].get('data', {})
103
+ # determine max row referenced
104
+ max_r = 0
105
+ for cid in data:
106
+ m = re.match(r'^[A-Z]+(\d+)$', cid)
107
+ if m:
108
+ max_r = max(max_r, int(m.group(1)))
109
+ out = {}
110
+ for r in range(1, max_r + 1):
111
+ vals = []
112
+ for c in 'ABCDEFGH':
113
+ cell = data.get(f'{c}{r}')
114
+ vals.append(cell.get('value') if cell else None)
115
+ if any(v is not None and str(v) != '' for v in vals):
116
+ out[r] = vals
117
+ return out
118
+
119
+
120
+ def verify_sheet():
121
+ """0.5 max. Graded per-cell, gated on row-is-new AND existing-rows-unchanged."""
122
+ data = fetch_state('google-sheets')
123
+ if not data:
124
+ print('FAIL: Sheet — could not fetch google-sheets state')
125
+ return 0.0
126
+ initial = data.get('initial_state') or {}
127
+ current = data.get('current_state') or {}
128
+ if not current:
129
+ print('FAIL: Sheet — current_state empty')
130
+ return 0.0
131
+
132
+ init_rows = sheet_rows(initial)
133
+ cur_rows = sheet_rows(current)
134
+
135
+ # invoice number -> full row, for existing (initial) rows
136
+ def inv_map(rows):
137
+ m = {}
138
+ for _, vals in rows.items():
139
+ a = (vals[0] or '').strip() if vals[0] else ''
140
+ if a.upper().startswith('INV-'):
141
+ m[a.upper()] = vals
142
+ return m
143
+
144
+ init_inv = inv_map(init_rows)
145
+ cur_inv = inv_map(cur_rows)
146
+
147
+ # Gate A: existing rows unchanged (every initial invoice row identical in current)
148
+ unchanged = True
149
+ for inv, ivals in init_inv.items():
150
+ cvals = cur_inv.get(inv)
151
+ if cvals is None or [norm(x) for x in cvals] != [norm(x) for x in ivals]:
152
+ print(f'FAIL: Sheet — existing row {inv} was modified or removed')
153
+ unchanged = False
154
+ if not unchanged:
155
+ return 0.0
156
+
157
+ # Gate B: the target row must be genuinely NEW (absent from initial)
158
+ if 'INV-1043' in init_inv:
159
+ print('FAIL: Sheet — INV-1043 already present in initial_state (not a new row)')
160
+ return 0.0
161
+ new_row = cur_inv.get('INV-1043')
162
+ if new_row is None:
163
+ print('FAIL: Sheet — no new INV-1043 row found in current_state')
164
+ return 0.0
165
+
166
+ # Per-cell match against expected (A..H)
167
+ expected = {
168
+ 'A': ('INV-1043', 'text'),
169
+ 'B': ('Acme Corp', 'text'),
170
+ 'C': ('Acme Corp - Platform License', 'text'),
171
+ 'D': ('48000', 'amount'),
172
+ 'E': ('20260624', 'date'),
173
+ 'F': ('20260724', 'date'),
174
+ 'G': ('Sent', 'text'),
175
+ 'H': ('Sarah Chen', 'text'),
176
+ }
177
+ cols = 'ABCDEFGH'
178
+ matched = 0
179
+ for i, c in enumerate(cols):
180
+ exp, kind = expected[c]
181
+ actual = new_row[i]
182
+ ok = False
183
+ if kind == 'text':
184
+ ok = norm(actual) == norm(exp)
185
+ elif kind == 'amount':
186
+ ok = norm_amount(actual) == exp
187
+ elif kind == 'date':
188
+ ok = date_matches(actual, exp)
189
+ if ok:
190
+ matched += 1
191
+ print(f'PASS: Sheet cell {c}15 = {actual!r}')
192
+ else:
193
+ print(f'FAIL: Sheet cell {c}15 — expected {exp!r} ({kind}), got {actual!r}')
194
+
195
+ score = 0.5 * (matched / len(cols))
196
+ print(f'Sheet score: {score:.4f} ({matched}/{len(cols)} cells)')
197
+ return score
198
+
199
+
200
+ def verify_slack():
201
+ """0.5 max. Graded over 5 criteria on a NEW #finance message addressed to Sarah Chen."""
202
+ data = fetch_state('slack')
203
+ if not data:
204
+ print('FAIL: Slack — could not fetch slack state')
205
+ return 0.0
206
+ initial = data.get('initial_state') or {}
207
+ current = data.get('current_state') or {}
208
+ if not current:
209
+ print('FAIL: Slack — current_state empty')
210
+ return 0.0
211
+
212
+ init_msgs = (initial.get('messages') or {}).get('finance', [])
213
+ cur_msgs = (current.get('messages') or {}).get('finance', [])
214
+
215
+ if len(cur_msgs) <= len(init_msgs):
216
+ print(f'FAIL: Slack — no new #finance message (init={len(init_msgs)}, cur={len(cur_msgs)})')
217
+ return 0.0
218
+
219
+ new_msgs = cur_msgs[len(init_msgs):]
220
+ # criteria evaluated over the new messages (best match)
221
+ criteria = [
222
+ ('addressed to Sarah Chen', lambda t: 'sarah chen' in t or '@sarah' in t),
223
+ ('invoice INV-1043', lambda t: 'inv-1043' in t),
224
+ ('customer Acme', lambda t: 'acme' in t),
225
+ ('amount 48000', lambda t: '48000' in re.sub(r'[$,\s]', '', t)),
226
+ ('due date 2026-07-24', lambda t: date_matches(t, '20260724')),
227
+ ]
228
+ best = 0
229
+ best_content = ''
230
+ for m in new_msgs:
231
+ t = norm(m.get('content', ''))
232
+ hits = sum(1 for _, fn in criteria if fn(t))
233
+ if hits > best:
234
+ best = hits
235
+ best_content = m.get('content', '')
236
+ # report against best message
237
+ if best_content:
238
+ tb = norm(best_content)
239
+ for name, fn in criteria:
240
+ print(f"{'PASS' if fn(tb) else 'FAIL'}: Slack — {name}")
241
+ score = 0.5 * (best / len(criteria))
242
+ print(f'Slack score: {score:.4f} ({best}/{len(criteria)} criteria) — msg: {best_content!r}')
243
+ return score
244
+
245
+
246
+ def main():
247
+ total = 0.0
248
+ try:
249
+ total += verify_sheet()
250
+ except Exception as e:
251
+ print(f'ERROR: Sheet component — {e}')
252
+ try:
253
+ total += verify_slack()
254
+ except Exception as e:
255
+ print(f'ERROR: Slack component — {e}')
256
+
257
+ final = round(min(total, 1.0), 4)
258
+ print(f'\nScore: {total}/1.0')
259
+ print(f'REWARD: {final}')
260
+ return final
261
+
262
+
263
+ main()
ar_payment_004/_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_payment_004/initial_setup.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: AR payment INV-1045 (Initech) — PRE-task state.
3
+ Task ID: ar_payment_004
4
+ Domain: libreoffice_calc (HYBRID: local Calc ledger + salesforce_mock + slack_mock)
5
+
6
+ Pre-task state:
7
+ - Ledger /home/user/ar_payment_002.xlsx, sheet 'AR Invoice Ledger', INV-1045 Status='Sent'.
8
+ - Salesforce: Closed-Won opp 'Initech CRM Rollout' owned by Priya Nair, NO payment-received activity.
9
+ - Slack #finance: prior chatter only, no settlement notification to Priya Nair.
10
+ GUI: libreoffice --calc ledger + google-chrome for salesforce & slack mocks (DISPLAY=:0).
11
+ """
12
+
13
+ import os
14
+ import shlex
15
+ import subprocess
16
+ import time
17
+ import uuid
18
+
19
+ import openpyxl
20
+ import requests
21
+
22
+ WORKDIR = '/home/user'
23
+ TASK_ID = 'ar_payment_002'
24
+ OUTPUT = f'{WORKDIR}/{TASK_ID}.xlsx'
25
+
26
+ SF_URL = 'http://28.7.184.198:8175'
27
+ SLACK_URL = 'http://28.7.184.198:8178'
28
+
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # Shared baseline builders (identical in initial_setup.py and golden_patch.py)
32
+ # ---------------------------------------------------------------------------
33
+ def ledger_rows():
34
+ """Fixed columns A=Invoice #,B=Customer,C=Deal/Contract,D=Amount,
35
+ E=Issue Date,F=Due Date,G=Status,H=AE/Owner. 10 data rows."""
36
+ return [
37
+ ['INV-1042', 'Acme Corp', 'Acme Enterprise License', 25000, '2026-05-10', '2026-06-09', 'Paid', 'John Smith'],
38
+ ['INV-1043', 'Globex', 'Globex Analytics Suite', 48000, '2026-05-15', '2026-06-14', 'Paid', 'Sarah Johnson'],
39
+ ['INV-1044', 'Soylent', 'Soylent Data Platform', 31500, '2026-05-20', '2026-06-19', 'Sent', 'Mike Chen'],
40
+ ['INV-1045', 'Initech', 'Initech CRM Rollout', 72000, '2026-05-25', '2026-06-24', 'Sent', 'Priya Nair'],
41
+ ['INV-1046', 'Umbrella', 'Umbrella Security Audit', 15800, '2026-06-01', '2026-07-01', 'Sent', 'Emily Davis'],
42
+ ['INV-1047', 'Hooli', 'Hooli Cloud Migration', 96000, '2026-06-03', '2026-07-03', 'Paid', 'Priya Nair'],
43
+ ['INV-1048', 'Stark Industries', 'Stark IoT Integration', 54000, '2026-06-05', '2026-07-05', 'Sent', 'Alex Kim'],
44
+ ['INV-1049', 'Wayne Enterprises', 'Wayne Security Platform', 120000, '2026-06-08', '2026-07-08', 'Paid', 'Sarah Johnson'],
45
+ ['INV-1050', 'Pied Piper', 'Pied Piper Compression API', 22500, '2026-06-12', '2026-07-12', 'Sent', 'Mike Chen'],
46
+ ['INV-1051', 'Wonka', 'Wonka Supply Chain', 38000, '2026-06-15', '2026-07-15', 'Overdue', 'Emily Davis'],
47
+ ]
48
+
49
+
50
+ def build_ledger(paid_inv1045: bool):
51
+ wb = openpyxl.Workbook()
52
+ ws = wb.active
53
+ ws.title = 'AR Invoice Ledger'
54
+ headers = ['Invoice #', 'Customer', 'Deal/Contract', 'Amount',
55
+ 'Issue Date', 'Due Date', 'Status', 'AE/Owner']
56
+ for col, h in enumerate(headers, 1):
57
+ ws.cell(row=1, column=col, value=h)
58
+ for r, row in enumerate(ledger_rows(), 2):
59
+ vals = list(row)
60
+ if paid_inv1045 and vals[0] == 'INV-1045':
61
+ vals[6] = 'Paid' # column G = Status
62
+ for c, val in enumerate(vals, 1):
63
+ ws.cell(row=r, column=c, value=val)
64
+ wb.save(OUTPUT)
65
+
66
+
67
+ def salesforce_state():
68
+ """Full baseline Salesforce org with Initech Closed-Won opp owned by Priya Nair,
69
+ NO payment-received activity on it."""
70
+ user = {
71
+ "userId": "user-1", "firstName": "John", "lastName": "Smith",
72
+ "email": "john.smith@company.com", "phone": "(555) 123-4567",
73
+ "title": "AR Specialist", "department": "Finance", "role": "Manager",
74
+ "avatar": "https://i.pravatar.cc/150?u=user-1",
75
+ "timezone": "America/New_York", "locale": "en-US", "theme": "lightning",
76
+ }
77
+ users = [
78
+ user,
79
+ {"userId": "user-2", "firstName": "Sarah", "lastName": "Johnson",
80
+ "email": "sarah.johnson@company.com", "phone": "(555) 222-3333",
81
+ "title": "Account Executive", "department": "Sales", "role": "Rep",
82
+ "avatar": "https://i.pravatar.cc/150?u=user-2", "timezone": "America/New_York",
83
+ "locale": "en-US", "theme": "lightning"},
84
+ {"userId": "user-3", "firstName": "Mike", "lastName": "Chen",
85
+ "email": "mike.chen@company.com", "phone": "(555) 333-4444",
86
+ "title": "Account Executive", "department": "Sales", "role": "Rep",
87
+ "avatar": "https://i.pravatar.cc/150?u=user-3", "timezone": "America/Los_Angeles",
88
+ "locale": "en-US", "theme": "lightning"},
89
+ {"userId": "user-6", "firstName": "Priya", "lastName": "Nair",
90
+ "email": "priya.nair@company.com", "phone": "(555) 666-7788",
91
+ "title": "Senior Account Executive", "department": "Sales", "role": "Rep",
92
+ "avatar": "https://i.pravatar.cc/150?u=user-6", "timezone": "America/New_York",
93
+ "locale": "en-US", "theme": "lightning"},
94
+ ]
95
+ accounts = [
96
+ {"accountId": "account-10", "name": "Initech", "type": "Customer",
97
+ "industry": "Technology", "revenue": 48000000, "employees": 320,
98
+ "ownerId": "user-6", "phone": "(555) 010-2030", "website": "www.initech.com",
99
+ "billingStreet": "4120 Freidrich Lane", "billingCity": "Austin",
100
+ "billingState": "TX", "billingZip": "78744", "billingCountry": "USA",
101
+ "createdDate": "2025-11-02T10:00:00.000Z", "modifiedDate": "2026-06-01T10:00:00.000Z"},
102
+ {"accountId": "account-11", "name": "Globex", "type": "Customer",
103
+ "industry": "Manufacturing", "revenue": 92000000, "employees": 540,
104
+ "ownerId": "user-2", "phone": "(555) 040-5060", "website": "www.globex.com",
105
+ "billingStreet": "200 Market St", "billingCity": "San Francisco",
106
+ "billingState": "CA", "billingZip": "94105", "billingCountry": "USA",
107
+ "createdDate": "2025-09-15T10:00:00.000Z", "modifiedDate": "2026-05-20T10:00:00.000Z"},
108
+ ]
109
+ contacts = [
110
+ {"contactId": "contact-10", "accountId": "account-10", "firstName": "Bill",
111
+ "lastName": "Lumbergh", "title": "VP of Operations", "department": "Operations",
112
+ "email": "bill.lumbergh@initech.com", "phone": "(555) 010-2031", "ownerId": "user-6"},
113
+ {"contactId": "contact-11", "accountId": "account-11", "firstName": "Hank",
114
+ "lastName": "Scorpio", "title": "CEO", "department": "Executive",
115
+ "email": "hank.scorpio@globex.com", "phone": "(555) 040-5061", "ownerId": "user-2"},
116
+ ]
117
+ opportunities = [
118
+ {"opportunityId": "opp-10", "name": "Initech CRM Rollout", "accountId": "account-10",
119
+ "contactId": "contact-10", "amount": 72000, "closeDate": "2026-06-20T00:00:00.000Z",
120
+ "stage": "Closed Won", "probability": 100, "type": "New Business",
121
+ "leadSource": "Referral", "nextStep": "Kickoff implementation",
122
+ "description": "Company-wide CRM rollout for Initech, 320 seats.",
123
+ "ownerId": "user-6", "createdDate": "2026-02-10T10:00:00.000Z",
124
+ "modifiedDate": "2026-06-20T10:00:00.000Z"},
125
+ {"opportunityId": "opp-11", "name": "Globex Analytics Suite", "accountId": "account-11",
126
+ "contactId": "contact-11", "amount": 48000, "closeDate": "2026-07-30T00:00:00.000Z",
127
+ "stage": "Negotiation", "probability": 70, "type": "New Business",
128
+ "leadSource": "Website", "nextStep": "Send revised proposal",
129
+ "description": "Analytics suite expansion for Globex.",
130
+ "ownerId": "user-2", "createdDate": "2026-04-01T10:00:00.000Z",
131
+ "modifiedDate": "2026-06-18T10:00:00.000Z"},
132
+ ]
133
+ activities = [
134
+ {"activityId": "activity-10", "type": "task", "subject": "Send kickoff agenda to Initech",
135
+ "status": "Not Started", "priority": "Normal", "dueDate": "2026-06-26T00:00:00.000Z",
136
+ "relatedToType": "Opportunity", "relatedToId": "opp-10", "assignedToId": "user-6",
137
+ "description": "Prepare and send implementation kickoff agenda to Bill Lumbergh.",
138
+ "createdDate": "2026-06-21T10:00:00.000Z"},
139
+ {"activityId": "activity-11", "type": "event", "subject": "Globex proposal review call",
140
+ "status": "Scheduled", "priority": "High",
141
+ "startDateTime": "2026-07-02T15:00:00.000Z", "endDateTime": "2026-07-02T15:30:00.000Z",
142
+ "relatedToType": "Opportunity", "relatedToId": "opp-11", "assignedToId": "user-2",
143
+ "description": "Walk through revised analytics suite proposal.",
144
+ "createdDate": "2026-06-19T10:00:00.000Z"},
145
+ ]
146
+ return {
147
+ "user": user, "users": users, "leads": [], "accounts": accounts,
148
+ "contacts": contacts, "opportunities": opportunities, "cases": [],
149
+ "activities": activities, "chatterPosts": [], "files": [], "following": [],
150
+ "recentlyViewed": [], "dismissedNotifications": [],
151
+ }
152
+
153
+
154
+ def slack_state():
155
+ """Slack workspace with a #finance channel pre-seeded with prior chatter,
156
+ NO settlement notification to Priya Nair. Priya Nair present as a user."""
157
+ current_user = {
158
+ "userId": "user_1", "fullName": "John Smith", "displayName": "John",
159
+ "email": "john.smith@company.com", "avatar": "https://picsum.photos/200/200?random=1",
160
+ "title": "AR Specialist", "status": "online", "statusMessage": "", "statusEmoji": "",
161
+ "timeZone": "America/New_York",
162
+ }
163
+ users = [
164
+ current_user,
165
+ {"userId": "user_2", "fullName": "Sarah Johnson", "displayName": "Sarah",
166
+ "email": "sarah.johnson@company.com", "avatar": "https://picsum.photos/200/200?random=2",
167
+ "title": "Account Executive", "status": "online", "statusMessage": "", "statusEmoji": "",
168
+ "timeZone": "America/New_York"},
169
+ {"userId": "user_3", "fullName": "Mike Chen", "displayName": "Mike",
170
+ "email": "mike.chen@company.com", "avatar": "https://picsum.photos/200/200?random=3",
171
+ "title": "Account Executive", "status": "away", "statusMessage": "", "statusEmoji": "",
172
+ "timeZone": "America/Los_Angeles"},
173
+ {"userId": "user_9", "fullName": "Priya Nair", "displayName": "Priya",
174
+ "email": "priya.nair@company.com", "avatar": "https://picsum.photos/200/200?random=9",
175
+ "title": "Senior Account Executive", "status": "online", "statusMessage": "", "statusEmoji": "",
176
+ "timeZone": "America/New_York"},
177
+ ]
178
+ channels = [
179
+ {"channelId": "general", "name": "general", "description": "Company-wide announcements",
180
+ "topic": "Welcome!", "isPrivate": False, "isStarred": False,
181
+ "members": ["user_1", "user_2", "user_3", "user_9"], "createdBy": "user_1",
182
+ "createdAt": "2026-01-01T10:00:00Z", "pinnedMessages": [], "unreadCount": 0},
183
+ {"channelId": "finance", "name": "finance", "description": "Accounts receivable, billing, and collections",
184
+ "topic": "AR / billing coordination", "isPrivate": False, "isStarred": True,
185
+ "members": ["user_1", "user_2", "user_3", "user_9"], "createdBy": "user_1",
186
+ "createdAt": "2026-01-05T10:00:00Z", "pinnedMessages": [], "unreadCount": 0},
187
+ ]
188
+ messages = {
189
+ "general": [
190
+ {"messageId": "msg_g1", "senderId": "user_3", "content": "Morning all, quarterly close is next week.",
191
+ "timestamp": "2026-06-29T09:00:00Z", "threadId": None, "reactions": [],
192
+ "attachments": [], "isEdited": False},
193
+ ],
194
+ "finance": [
195
+ {"messageId": "msg_f1", "senderId": "user_2", "content": "Reminder: please log payments in Salesforce as they land so AR stays clean.",
196
+ "timestamp": "2026-06-26T13:10:00Z", "threadId": None, "reactions": [],
197
+ "attachments": [], "isEdited": False},
198
+ {"messageId": "msg_f2", "senderId": "user_9", "content": "Still waiting on Initech's wire for the CRM Rollout, will confirm once it clears.",
199
+ "timestamp": "2026-06-27T16:45:00Z", "threadId": None, "reactions": [],
200
+ "attachments": [], "isEdited": False},
201
+ {"messageId": "msg_f3", "senderId": "user_1", "content": "Thanks Priya — I'll mark the invoice paid the moment treasury confirms receipt.",
202
+ "timestamp": "2026-06-27T17:02:00Z", "threadId": None, "reactions": [],
203
+ "attachments": [], "isEdited": False},
204
+ ],
205
+ }
206
+ return {
207
+ "currentUser": current_user,
208
+ "workspace": {"workspaceId": "ws_1", "workspaceName": "Acme Corp", "icon": ""},
209
+ "users": users, "channels": channels, "messages": messages, "threads": {},
210
+ "dms": [], "bookmarkedMessages": [], "callHistory": [],
211
+ "settings": {"theme": "light", "notifications": "all", "displayDensity": "comfortable",
212
+ "showAvatars": True, "use24Hour": False},
213
+ "invitations": [], "notifications": [],
214
+ }
215
+
216
+
217
+ def launch_gui(command, delay_sec=1.0):
218
+ env = os.environ.copy()
219
+ env['DISPLAY'] = ':0'
220
+ subprocess.Popen(shlex.split(command), stdout=subprocess.DEVNULL,
221
+ stderr=subprocess.DEVNULL, env=env)
222
+ time.sleep(delay_sec)
223
+
224
+
225
+ def main():
226
+ # --- 1. Local ledger (INV-1045 Status='Sent') ---
227
+ build_ledger(paid_inv1045=False)
228
+ print(f'Initial ledger created: {OUTPUT}')
229
+
230
+ # --- 2. Shared sid for both mocks ---
231
+ sid = str(uuid.uuid4())
232
+ with open('/tmp/task_web_sid', 'w') as f:
233
+ f.write(sid)
234
+
235
+ # --- 3. Inject Salesforce + Slack initial state (action 'set') ---
236
+ for name, url, state in [
237
+ ('salesforce', SF_URL, salesforce_state()),
238
+ ('slack', SLACK_URL, slack_state()),
239
+ ]:
240
+ r = requests.post(f'{url}/post?sid={sid}', json={'action': 'set', 'state': state}, timeout=30)
241
+ assert r.status_code == 200, f'{name} set failed: {r.text}'
242
+ go = requests.get(f'{url}/go?sid={sid}', timeout=15).json()
243
+ assert go['initial_state'] is not None, f'{name} initial_state is None'
244
+ print(f'{name} initial state injected: sid={sid}')
245
+
246
+ # --- 4. GUI-ready startup ---
247
+ launch_gui(f'libreoffice --calc "{OUTPUT}"', delay_sec=3.0)
248
+ launch_gui(f'google-chrome "{SF_URL}/?sid={sid}"', delay_sec=2.0)
249
+ launch_gui(f'google-chrome "{SLACK_URL}/?sid={sid}"', delay_sec=2.0)
250
+ print('GUI_READY: launched libreoffice calc + chrome (salesforce, slack) with DISPLAY=:0')
251
+
252
+
253
+ main()
ar_payment_004/reward.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: AR payment chain — mark INV-1045 Paid in local ledger,
3
+ log a payment-received activity on the Salesforce opportunity 'Initech CRM Rollout',
4
+ and notify AE Priya Nair in Slack #finance that it's settled.
5
+ Task ID: ar_payment_004
6
+ Domain: libreoffice_calc + mock_websites (HYBRID: local xlsx -> Salesforce -> Slack)
7
+
8
+ Scoring (each component scores ONLY the task-introduced delta):
9
+ Component 1 — LOCAL LEDGER (0.34): INV-1045 Status -> 'Paid' AND no other row's
10
+ Status changed from its known baseline.
11
+ Component 2 — SALESFORCE (0.33): NEW activity (delta vs initial) on opp 'Initech
12
+ CRM Rollout' recording payment of $72,000 / INV-1045.
13
+ Component 3 — SLACK (0.33): NEW message (delta vs initial) in #finance addressed
14
+ to Priya Nair confirming $72,000 / INV-1045 settled.
15
+
16
+ Total: 1.0. Fully deterministic; no LLM judge (no OpenAI creds in this env).
17
+ Runs on the VM: openpyxl for the local file, requests for the mock /go state.
18
+ """
19
+ import sys
20
+ import re
21
+
22
+ LEDGER_PATH = '/home/user/ar_payment_002.xlsx'
23
+ SHEET_NAME = 'AR Invoice Ledger'
24
+
25
+ # Known baseline (initial) Status per invoice, from the task context.
26
+ # INV-1045 is the ONLY row that should change (Sent -> Paid).
27
+ BASELINE_STATUS = {
28
+ 'INV-1042': 'Paid',
29
+ 'INV-1043': 'Paid',
30
+ 'INV-1044': 'Sent',
31
+ 'INV-1045': 'Sent', # <- the row the agent must change to 'Paid'
32
+ 'INV-1046': 'Sent',
33
+ 'INV-1047': 'Paid',
34
+ 'INV-1048': 'Sent',
35
+ 'INV-1049': 'Paid',
36
+ 'INV-1050': 'Sent',
37
+ 'INV-1051': 'Overdue',
38
+ }
39
+
40
+
41
+ def norm(s):
42
+ """Lowercase, strip, drop commas/$/spaces around numbers for robust matching."""
43
+ return str(s or '').lower()
44
+
45
+
46
+ def amount_present(text):
47
+ """True if text mentions 72000 / 72,000 / $72,000."""
48
+ t = re.sub(r'[,\s$]', '', str(text or ''))
49
+ return '72000' in t
50
+
51
+
52
+ def verify_ledger():
53
+ """Component 1 (0.34): INV-1045 -> Paid, identity intact, no other status changed."""
54
+ try:
55
+ import openpyxl
56
+ except Exception as e:
57
+ print(f"ERROR: Component 1 — openpyxl import failed: {e}")
58
+ return 0.0
59
+ try:
60
+ wb = openpyxl.load_workbook(LEDGER_PATH, data_only=True)
61
+ except Exception as e:
62
+ print(f"ERROR: Component 1 — cannot load ledger {LEDGER_PATH}: {e}")
63
+ return 0.0
64
+ try:
65
+ if SHEET_NAME not in wb.sheetnames:
66
+ print(f"FAIL: Component 1 — sheet '{SHEET_NAME}' not found; sheets={wb.sheetnames}")
67
+ return 0.0
68
+ ws = wb[SHEET_NAME]
69
+
70
+ rows_by_inv = {}
71
+ for r in ws.iter_rows(min_row=2, values_only=True):
72
+ if r and r[0]:
73
+ rows_by_inv[str(r[0]).strip()] = r # A=Invoice#, B=Cust, C=Deal, D=Amt, ... G=Status, H=Owner
74
+
75
+ # 1a: INV-1045 identity + Status == 'Paid' (the core change)
76
+ target = rows_by_inv.get('INV-1045')
77
+ if not target:
78
+ print("FAIL: Component 1 — INV-1045 row not found")
79
+ return 0.0
80
+ cust = str(target[1]).strip() if target[1] else ''
81
+ deal = str(target[2]).strip() if target[2] else ''
82
+ amt = target[3]
83
+ status = str(target[6]).strip() if target[6] else ''
84
+ owner = str(target[7]).strip() if target[7] else ''
85
+
86
+ identity_ok = (cust == 'Initech' and deal == 'Initech CRM Rollout'
87
+ and amt == 72000 and owner == 'Priya Nair')
88
+ if not identity_ok:
89
+ print(f"FAIL: Component 1 — INV-1045 identity mismatch "
90
+ f"(Customer={cust!r}, Deal={deal!r}, Amount={amt!r}, Owner={owner!r})")
91
+ return 0.0
92
+ if status != 'Paid':
93
+ print(f"FAIL: Component 1 — INV-1045 Status is {status!r}, expected 'Paid'")
94
+ return 0.0
95
+
96
+ # 1b: no OTHER row's Status changed from its baseline
97
+ for inv, expected in BASELINE_STATUS.items():
98
+ if inv == 'INV-1045':
99
+ continue
100
+ row = rows_by_inv.get(inv)
101
+ if not row:
102
+ print(f"FAIL: Component 1 — expected row {inv} missing")
103
+ return 0.0
104
+ actual = str(row[6]).strip() if row[6] else ''
105
+ if actual != expected:
106
+ print(f"FAIL: Component 1 — {inv} Status changed to {actual!r}, "
107
+ f"expected unchanged {expected!r}")
108
+ return 0.0
109
+
110
+ print("PASS: Component 1 — INV-1045 marked 'Paid', identity intact, "
111
+ "no other row's status changed (0.34 pts)")
112
+ return 0.34
113
+ except Exception as e:
114
+ print(f"ERROR: Component 1 — {e}")
115
+ return 0.0
116
+
117
+
118
+ def verify_salesforce(sid):
119
+ """Component 2 (0.33): NEW payment activity on 'Initech CRM Rollout' opportunity."""
120
+ import requests
121
+ try:
122
+ data = requests.get(f'http://28.7.184.198:8175/go?sid={sid}', timeout=20).json()
123
+ except Exception as e:
124
+ print(f"ERROR: Component 2 — cannot fetch salesforce state: {e}")
125
+ return 0.0
126
+ try:
127
+ initial = data.get('initial_state') or {}
128
+ current = data.get('current_state') or {}
129
+
130
+ # Resolve the Initech opportunity id from current state.
131
+ opp_id = None
132
+ for o in (current.get('opportunities') or []):
133
+ if str(o.get('name', '')).strip() == 'Initech CRM Rollout':
134
+ opp_id = o.get('opportunityId')
135
+ break
136
+ if not opp_id:
137
+ print("FAIL: Component 2 — opportunity 'Initech CRM Rollout' not found")
138
+ return 0.0
139
+
140
+ # DELTA: activities present now but not in initial.
141
+ init_ids = {a.get('activityId') for a in (initial.get('activities') or [])}
142
+ new_acts = [a for a in (current.get('activities') or [])
143
+ if a.get('activityId') not in init_ids]
144
+ if not new_acts:
145
+ print("FAIL: Component 2 — no new activity logged (delta empty)")
146
+ return 0.0
147
+
148
+ # A new activity must relate to the Initech opp AND record the payment.
149
+ for a in new_acts:
150
+ if a.get('relatedToId') != opp_id:
151
+ continue
152
+ blob = norm(a.get('subject', '')) + ' ' + norm(a.get('description', ''))
153
+ if 'inv-1045' in blob and amount_present(blob):
154
+ print(f"PASS: Component 2 — new payment activity {a.get('activityId')} on "
155
+ f"'Initech CRM Rollout' records INV-1045 / $72,000 (0.33 pts)")
156
+ return 0.33
157
+
158
+ print("FAIL: Component 2 — new activity exists but none on the Initech opp "
159
+ "mentions both INV-1045 and $72,000")
160
+ return 0.0
161
+ except Exception as e:
162
+ print(f"ERROR: Component 2 — {e}")
163
+ return 0.0
164
+
165
+
166
+ def verify_slack(sid):
167
+ """Component 3 (0.33): NEW #finance message to Priya Nair confirming settlement."""
168
+ import requests
169
+ try:
170
+ data = requests.get(f'http://28.7.184.198:8178/go?sid={sid}', timeout=20).json()
171
+ except Exception as e:
172
+ print(f"ERROR: Component 3 — cannot fetch slack state: {e}")
173
+ return 0.0
174
+ try:
175
+ initial = data.get('initial_state') or {}
176
+ current = data.get('current_state') or {}
177
+
178
+ init_fin = (initial.get('messages') or {}).get('finance', [])
179
+ cur_fin = (current.get('messages') or {}).get('finance', [])
180
+
181
+ # DELTA: messages beyond the initial #finance snapshot.
182
+ new_msgs = cur_fin[len(init_fin):] if len(cur_fin) > len(init_fin) else []
183
+ if not new_msgs:
184
+ print("FAIL: Component 3 — no new message in #finance (delta empty)")
185
+ return 0.0
186
+
187
+ for m in new_msgs:
188
+ c = norm(m.get('content', ''))
189
+ addresses_priya = ('priya' in c) # @Priya Nair / Priya
190
+ confirms = ('inv-1045' in c and amount_present(c)
191
+ and ('settl' in c or 'paid' in c or 'received' in c))
192
+ if addresses_priya and confirms:
193
+ print(f"PASS: Component 3 — new #finance message {m.get('messageId')} addresses "
194
+ f"Priya Nair and confirms INV-1045 / $72,000 settled (0.33 pts)")
195
+ return 0.33
196
+
197
+ print("FAIL: Component 3 — new #finance message(s) do not address Priya Nair "
198
+ "AND confirm INV-1045 / $72,000 settled")
199
+ return 0.0
200
+ except Exception as e:
201
+ print(f"ERROR: Component 3 — {e}")
202
+ return 0.0
203
+
204
+
205
+ def main():
206
+ # sid for the mock surfaces (per-env)
207
+ try:
208
+ with open('/tmp/task_web_sid') as f:
209
+ sid = f.read().strip()
210
+ if not sid:
211
+ raise ValueError('sid empty')
212
+ except Exception as e:
213
+ print(f"CRITICAL: cannot read /tmp/task_web_sid: {e}")
214
+ print("REWARD: 0.0")
215
+ return
216
+
217
+ total = 0.0
218
+ total += verify_ledger()
219
+ total += verify_salesforce(sid)
220
+ total += verify_slack(sid)
221
+
222
+ final = round(min(total, 1.0), 4)
223
+ print(f"\nScore: {total}/1.0")
224
+ print(f"REWARD: {final}")
225
+
226
+
227
+ main()
ar_payment_004/reward_label.json ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/ar_payment_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:47",
7
+ "label": {
8
+ "task_id": "ar_payment_004",
9
+ "domain": "libreoffice_calc + mock_websites (HYBRID: local xlsx -> Salesforce -> Slack)",
10
+ "summary": "验证代理是否将本地 Excel 账本中 INV-1045 标记为 Paid、在 Salesforce 的 'Initech CRM Rollout' 机会上新增 $72,000 付款活动,并在 Slack #finance 频道向 Priya Nair 发送确认结清的消息。",
11
+ "is_placeholder": false,
12
+ "data_sources": [
13
+ "/home/user/ar_payment_002.xlsx",
14
+ "/tmp/task_web_sid",
15
+ "salesforce_mock (http://28.7.186.212:8195/go)",
16
+ "slack_mock (http://28.7.186.212:8198/go)"
17
+ ],
18
+ "scoring_components": [
19
+ {
20
+ "name": "Component 1 — LOCAL LEDGER",
21
+ "weight": 0.34,
22
+ "description": "检查本地 Excel 账本中 INV-1045 是否被正确标记为 Paid,且其他行状态未被篡改。",
23
+ "check_logic": "使用 openpyxl 加载 LEDGER_PATH 的 SHEET_NAME 工作表,遍历所有行建立 Invoice# 到行的映射。对 INV-1045 检查:Customer='Initech'、Deal='Initech CRM Rollout'、Amount=72000、Owner='Priya Nair'、Status='Paid'。对 BASELINE_STATUS 中其余发票检查:行必须存在且 Status 与基准值完全一致。",
24
+ "pass_condition": "INV-1045 的身份字段完全匹配且 Status 为 'Paid',其他所有发票行的 Status 与 BASELINE_STATUS 基准一致且无缺失。"
25
+ },
26
+ {
27
+ "name": "Component 2 — SALESFORCE",
28
+ "weight": 0.33,
29
+ "description": "检查 Salesforce 中 'Initech CRM Rollout' 机会上是否新增了记录 INV-1045 / $72,000 付款的活动。",
30
+ "check_logic": "通过 requests GET 请求 salesforce_mock /go 端点,获取 initial_state 与 current_state。从 current_state.opportunities 中解析 name 为 'Initech CRM Rollout' 的 opportunityId。计算 activities 的 delta(current 中存在但 initial 中 activityId 不存在的记录)。在新增活动中查找 relatedToId 等于该 opp_id,且 subject 与 description 的归一化文本同时包含 'inv-1045' 和金额 72000 的记录。",
31
+ "pass_condition": "存在一条新增 activity,关联到 'Initech CRM Rollout' 机会,且其内容同时提及 INV-1045 和 $72,000。"
32
+ },
33
+ {
34
+ "name": "Component 3 — SLACK",
35
+ "weight": 0.33,
36
+ "description": "检查 Slack #finance 频道是否新增了向 Priya Nair 确认 INV-1045 / $72,000 已结清的消息。",
37
+ "check_logic": "通过 requests GET 请求 slack_mock /go 端点,获取 initial_state 与 current_state。提取 #finance 频道的消息列表,取 delta(current 中超出 initial 长度的尾部消息)。在新增消息中查找归一化内容同时满足:包含 'priya'、包含 'inv-1045'、包含金额 72000、包含 'settl'/'paid'/'received' 之一。",
38
+ "pass_condition": "#finance 频道存在一条新增消息,内容同时提及 Priya Nair、INV-1045、$72,000 并使用确认结清的关键词。"
39
+ }
40
+ ],
41
+ "total_max_score": 1.0,
42
+ "score_aggregation": "三个组件得分直接相加,随后使用 min(total, 1.0) 钳制到上限 1.0,最后 round(..., 4) 得到最终 REWARD。",
43
+ "failure_modes": [
44
+ "读取 /tmp/task_web_sid 失败或为空:CRITICAL 提前退出,输出 REWARD: 0.0",
45
+ "openpyxl 导入失败:Component 1 返回 0.0",
46
+ "Excel 文件加载失败或工作表 'AR Invoice Ledger' 不存在:Component 1 返回 0.0",
47
+ "INV-1045 行缺失或身份字段(Customer/Deal/Amount/Owner)不匹配:Component 1 返回 0.0",
48
+ "INV-1045 Status 不是 'Paid':Component 1 返回 0.0",
49
+ "其他发票行缺失或 Status 偏离 BASELINE_STATUS:Component 1 返回 0.0",
50
+ "Salesforce mock 请求失败:Component 2 返回 0.0",
51
+ "未找到 'Initech CRM Rollout' 机会:Component 2 返回 0.0",
52
+ "activities delta 为空:Component 2 返回 0.0",
53
+ "新增 activity 未同时包含 INV-1045 和 $72,000:Component 2 返回 0.0",
54
+ "Slack mock 请求失败:Component 3 返回 0.0",
55
+ "#finance 无新增消息:Component 3 返回 0.0",
56
+ "新增消息未同时满足 Priya + INV-1045 + 金额 + 确认词:Component 3 返回 0.0",
57
+ "任何未捕获异常导致对应 Component 返回 0.0"
58
+ ],
59
+ "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID。随后按顺序执行三个验证:1) verify_ledger() 使用 openpyxl 打开本地 Excel,确认 INV-1045 被改为 Paid 且身份正确,同时确保其他行状态与基准一致,通过得 0.34;2) verify_salesforce(sid) 请求 salesforce_mock,对比 initial 与 current state,在 'Initech CRM Rollout' 机会上查找新增且同时提及 INV-1045 和 $72,000 的 activity,��过得 0.33;3) verify_slack(sid) 请求 slack_mock,对比 #finance 消息增量,查找同时提及 Priya Nair、INV-1045、$72,000 及确认结清关键词的新消息,通过得 0.33。三个组件分数累加后,经 min(total, 1.0) 钳制并四舍五入到 4 位小数输出最终分数。",
60
+ "confidence": 1.0
61
+ },
62
+ "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出结果。\n\n让我仔细阅读代码:\n\n1. **任务信息提取**:\n - Task ID: ar_payment_002(从 docstring 中明确提取)\n - Domain: libreoffice_calc + mock_websites (HYBRID)(从 docstring 中提取)\n\n2. **脚本功能概述**:\n 验证三个组件:\n - 本地账本(Excel):将 INV-1045 标记为 Paid,且不改变其他行\n - Salesforce:在 \"Initech CRM Rollout\" 机会上新增记录 $72,000 / INV-1045 的活动\n - Slack:在 #finance 频道向 Priya Nair 发送新消息确认 $72,000 / INV-1045 已结清\n\n3. **is_placeholder**:false,因为脚本有详细的验证逻辑。\n\n4. **data_sources**:\n - 本地文件:`/home/user/ar_payment_002.xlsx`(openpyxl 读取)\n - Salesforce mock:`http://28.7.186.212:8195/go?sid={sid}`(requests 获取)\n - Slack mock:`http://28.7.186.212:8198/go?sid={sid}`(requests 获取)\n - `/tmp/task_web_sid`(读取 sid)\n\n5. **scoring_components**:\n - Component 1:weight 0.34,验证本地账本\n - Component 2:weight 0.33,验证 Salesforce\n - Component 3:weight 0.33,验证 Slack\n\n6. **score_aggregation**:相加,然后 `min(total, 1.0)` 钳制到上限,再 round 到 4 位小数。\n\n7. **failure_modes**:\n - 读取 /tmp/task_web_sid 失败会提前退出(CRITICAL)\n - openpyxl 导入失败\n - Excel 文件加载失败\n - 工作表未找到\n - INV-1045 行未找到\n - INV-1045 身份不匹配(Customer, Deal, Amount, Owner)\n - INV-1045 Status 不是 'Paid'\n - 其他行 Status 被改变或缺失\n - Salesforce mock 拉取失败\n - 未找到 \"Initech CRM Rollout\" 机会\n - 没有新活动(delta 为空)\n - 新活动未关联到正确机会或未提及 INV-1045 和金额\n - Slack mock 拉取失败\n - #finance 没有新消息\n - 新消息未同时满足:提及 Priya、包含 INV-1045、金额、确认词(settl/paid/received)\n\n8. **scoring_logic_explanation**:按执行顺序:\n - 从 /tmp/task_web_sid 读取 sid\n - Component 1:用 openpyxl 打开 Excel,检查 INV-1045 行身份(Customer=Initech, Deal=Initech CRM Rollout, Amount=72000, Owner=Priya Nair)且 Status='Paid';检查其他所有发票状态与 BASELINE_STATUS 一致未改变。通过得 0.34。\n - Component 2:用 sid 请求 Salesforce mock,对比 initial/current state,找到 \"Initech CRM Rollout\" 机会 ID,检查新增活动中是否有 relatedToId 匹配且 subject/description 同时包含 inv-1045 和 $72,000。通过得 0.33。\n - Component 3:用 sid 请求 Slack mock,对比 initial/current 的 #finance 消息,取增量消息,检查是否有消息同时满足:内容包含 \"priya\"、包含 \"inv-1045\"、包含金额 72000、包含 \"settl\"/\"paid\"/\"received\" 之一。通过得 0.33。\n - 汇总:三个组件分数相加,min(total, 1.0) 钳制,round(..., 4)。\n\n9. **confidence**:1.0,因为代码清晰完整。\n\n现在构建 JSON,确保:\n- 只输出 JSON,无 Markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 所有字符串 value 使用中文(task_id、domain、字段名、代码标识符保留原样)\n- 不要臆测\n\n让我再检查一下 weight 字段。代码中显式给出:\n- Component 1: 0.34\n- Component 2: 0.33\n- Component 3: 0.33\n\ntotal_max_score: 1.0\n\n检查 pass_condition 和 check_logic 要准确:\n\nComponent 1:\n- check_logic: 使用 openpyxl 加载 /home/user/ar_payment_002.xlsx 的 'AR Invoice Ledger' 工作表,遍历所有行。检查 INV-1045 行的 Customer='Initech'、Deal='Initech CRM Rollout'、Amount=72000、Owner='Priya Nair' 且 Status='Paid';同时遍历 BASELINE_STATUS 中除 INV-1045 外的所有发票,确认其 Status 与基准值一致且行存在。\n- pass_condition: INV-1045 的身份字段完全匹配且 Status 为 'Paid',且其他所有发票行的 Status 与 BASELINE_STATUS 基准一致、无缺失。\n\nComponent 2:\n- check_logic: 通过 HTTP GET 请求 salesforce_mock 的 /go 端点获取 initial_state 和 current_state。从 current_state.opportunities 中找到 name 为 'Initech CRM Rollout' 的 opportunityId。计算 activities 的 delta(current 中存在但 initial 中 activityId 不存在的记录)。在新增活动中查找 relatedToId 等于该 opp_id 且 subject 与 description 的归一化文本同时包含 'inv-1045' 和金额 72000 的活动。\n- pass_condition: 存在一条新增 activity,其关联到 'Initech CRM Rollout' 机会,且内容同时提及 INV-1045 和 $72,000。\n\nComponent 3:\n- check_logic: 通过 HTTP GET 请求 slack_mock 的 /go 端点获��� initial_state 和 current_state。提取 #finance 频道的消息列表,计算 delta(current 中超出 initial 长度的尾部消息)。在新增消息中查找归一化内容同时满足:包含 'priya'、包含 'inv-1045'、包含金额 72000、包含 'settl'/'paid'/'received' 之一。\n- pass_condition: #finance 频道存在一条新增消息,内容同时提及 Priya Nair、INV-1045、$72,000 并使用确认结清的关键词。\n\nfailure_modes:\n- /tmp/task_web_sid 读取失败或为空:CRITICAL 提前退出,REWARD 0.0\n- openpyxl 导入失败:Component 1 返回 0.0\n- Excel 文件加载失败:Component 1 返回 0.0\n- 工作表 'AR Invoice Ledger' 不存在:Component 1 返回 0.0\n- INV-1045 行缺失:Component 1 返回 0.0\n- INV-1045 身份字段不匹配:Component 1 返回 0.0\n- INV-1045 Status 不是 'Paid':Component 1 返回 0.0\n- 其他发票行缺失或 Status 偏离基准:Component 1 返回 0.0\n- Salesforce mock 请求失败:Component 2 返回 0.0\n- 未找到 'Initech CRM Rollout' 机会:Component 2 返回 0.0\n- activities delta 为空:Component 2 返回 0.0\n- 新增 activity 未同时包含 INV-1045 和 $72,000:Component 2 返回 0.0\n- Slack mock 请求失败:Component 3 返回 0.0\n- #finance 无新增消息:Component 3 返回 0.0\n- 新增消息未同时满足 Priya + INV-1045 + 金额 + 确认词:Component 3 返回 0.0\n- 任何未捕获异常:对应 Component 返回 0.0\n\nscore_aggregation: 三个组件得分相加,使用 min(total, 1.0) 钳制上限,再 round(..., 4) 得到最终 REWARD。\n\nsummary: 验证代理是否将本地 Excel 账本中 INV-1045 标记为 Paid、在 Salesforce 机会上记录付款活动、并在 Slack #finance 通知 Priya Nair。\n\ndomain 应该是 \"libreoffice_calc + mock_websites\" 还是只取一个?docstring 中写的是 \"libreoffice_calc + mock_websites (HYBRID: local xlsx -> Salesforce -> Slack)\"。按照要求,从 docstring 中提取的领域。我保留原样 \"libreoffice_calc + mock_websites (HYBRID: local xlsx -> Salesforce -> Slack)\" 或者简化为 \"libreoffice_calc + mock_websites\"。看要求说 \"如 mock_websites / software_engineer / libreoffice_calc\"。这里 hybrid 比较特殊,我保留原文中的描述。\n\n等等,用户要求 \"domain\": \"从 docstring 中提取的领域\"。docstring 中明确写了 \"Domain: libreoffice_calc + mock_websites (HYBRID: local xlsx -> Salesforce -> Slack)\"。我就用这个。\n\n现在确保 JSON 格式正确,没有多余内容。 </think> {\"task_id\":\"ar_payment_002\",\"domain\":\"libreoffice_calc + mock_websites (HYBRID: local xlsx -> Salesforce -> Slack)\",\"summary\":\"验证代理是否将本地 Excel 账本中 INV-1045 标记为 Paid、在 Salesforce 的 'Initech CRM Rollout' 机会上新增 $72,000 付款活动,并在 Slack #finance 频道向 Priya Nair 发送确认结清的消息。\",\"is_placeholder\":false,\"data_sources\":[\"/home/user/ar_payment_002.xlsx\",\"/tmp/task_web_sid\",\"salesforce_mock (http://28.7.186.212:8195/go)\",\"slack_mock (http://28.7.186.212:8198/go)\"],\"scoring_components\":[{\"name\":\"Component 1 — LOCAL LEDGER\",\"weight\":0.34,\"description\":\"检查本地 Excel 账本中 INV-1045 是否被正确标记为 Paid,且其他行状态未被篡改。\",\"check_logic\":\"使用 openpyxl 加载 LEDGER_PATH 的 SHEET_NAME 工作表,遍历所有行建立 Invoice# 到行的映射。对 INV-1045 检查:Customer='Initech'、Deal='Initech CRM Rollout'、Amount=72000、Owner='Priya Nair'、Status='Paid'。对 BASELINE_STATUS 中其余发票检查:行必须存在且 Status 与基准值完全一致。\",\"pass_condition\":\"INV-1045 的身份字段完全匹配且 Status 为 'Paid',其他所有发票行的 Status 与 BASELINE_STATUS 基准一致且无缺失。\"},{\"name\":\"Component 2 — SALESFORCE\",\"weight\":0.33,\"description\":\"检查 Salesforce 中 'Initech CRM Rollout' 机会上是否新增了记录 INV-1045 / $72,000 付款的活动。\",\"check_logic\":\"通过 requests GET 请求 salesforce_mock /go 端点,获取 initial_state 与 current_state。从 current_state.opportunities 中解析 name 为 'Initech CRM Rollout' 的 opportunityId。计算 activities 的 delta(current 中存在但 initial 中 activityId 不存在的记录)。在新增活动中查找 relatedToId 等于该 opp_id,且 subject 与 description 的归一化文本同时包含 'inv-1045' 和金额 72000 的记录。\",\"pass_condition\":\"存在一条新增 activity,关联到 'Initech CRM Rollout' 机会,且其内容同时提及 INV-1045 和 $72,000。\"},{\"name\":\"Component 3 — SLACK\",\"weight\":0.33,\"description\":\"检查 Slack #finance 频道是否新增了向 Priya Nair 确认 INV-1045 / $72,000 已结清的消息。\",\"check_logic\":\"通过 requests GET 请求 slack_mock /go 端点,获取 initial_state 与 current_state。提取 #finance 频道的消息列表,取 delta(current 中超出 initial 长度的尾部消息)。在新增消息中查找归一化内容同时满足:包含 'priya'、包含 'inv-1045'、包含金额 72000、包含 'settl'/'paid'/'received' 之一。\",\"pass_condition\":\"#finance 频道存在一条新增消息,内容同时提及 Priya Nair、INV-1045、$72,000 并使用确认结清的关键词。\"}],\"total_max_score\":1.0,\"score_aggregation\":\"三个组件得分直接相加,随后使用 min(total, 1.0) 钳制到上限 1.0,最后 round(..., 4) 得到最终 REWARD。\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空:CRITICAL 提前退出,输出 REWARD: 0.0\",\"openpyxl 导入失败:Component 1 返回 0.0\",\"Excel 文件加载失败或工作表 'AR Invoice Ledger' 不存在:Component 1 返回 0.0\",\"INV-1045 行缺失或身份字段(Customer/Deal/Amount/Owner)不匹配:Component 1 返回 0.0\",\"INV-1045 Status 不是 'Paid':Component 1 返回 0.0\",\"其他发票行缺失或 Status 偏离 BASELINE_STATUS:Component 1 返回 0.0\",\"Salesforce mock 请求失败:Component 2 返回 0.0\",\"未找到 'Initech CRM Rollout' 机会:Component 2 返回 0.0\",\"activities delta 为空:Component 2 返回 0.0\",\"新增 activity 未同时包含 INV-1045 和 $72,000:Component 2 返回 0.0\",\"Slack mock 请求失败:Component 3 返回 0.0\",\"#finance 无新增消息:Component 3 返回 0.0\",\"新增消息未同时满足 Priya + INV-1045 + 金额 + 确认词:Component 3 返回 0.0\",\"任何未捕获异常导致对应 Component 返回 0.0\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID。随后按顺序执行三个验证:1) verify_ledger() 使用 openpyxl 打开本地 Excel,确认 INV-1045 被改为 Paid 且身份正确,同时确保其他行状态与基准一致,通过得 0.34;2) verify_salesforce(sid) 请求 salesforce_mock,对比 initial 与 current state,在 'Initech CRM Rollout' 机会上查找新增且同时提及 INV-1045 和 $72,000 的 activity,通过得 0.33;3) verify_slack(sid) 请求 slack_mock,对比 #finance 消息增量,查找同时提及 Priya Nair、INV-1045、$72,000 及确认结清关键词的新消息,通过得 0.33。三个组件分数累加后,经 min(total, 1.0) 钳制并四舍五入到 4 位小数输出最终分数。\",\"confidence\":1.0}"
63
+ }
ar_payment_alert_010__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"
ar_payment_alert_010__long/initial_setup.py ADDED
@@ -0,0 +1,969 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: Clear the overnight payment-alert inbox
3
+ Task ID: ar_payment_alert_010__long
4
+ Mocks: stripe_dashboard_mock (8179), quickbooks_mock (8172),
5
+ gmail_mock (8138), slack_mock (8178)
6
+
7
+ Scenario (multi-branch finance-ops, "today" = 2026-06-29)
8
+ ---------------------------------------------------------
9
+ A finance-ops analyst clears the overnight PAYMENT-ALERT inbox in Gmail. Each
10
+ alert email (from the billing system) flags one payment event and names the
11
+ customer + amount (+ invoice # where relevant). For every alert the analyst
12
+ derives the corrective action from the alert TYPE, carries the customer / amount
13
+ / invoice into Stripe or QuickBooks, performs the (hidden) control there, labels
14
+ the alert with a status label, replies to the customer, then posts + pins a
15
+ one-line summary to Slack #billing-ops.
16
+
17
+ Branch rule (stated in the instruction; VERIFIED against current app state):
18
+ * Duplicate charge -> REFUND the matching Stripe payment
19
+ (skip if that payment is already refunded).
20
+ * Chargeback opened -> SUBMIT EVIDENCE on the matching Stripe dispute
21
+ (skip if its status is not 'needs_response').
22
+ * Payment received -> RECEIVE PAYMENT on the matching QuickBooks invoice
23
+ (skip if the invoice is already Paid).
24
+ * Under investigation -> LEAVE (pending — must NOT act; tempting distractor).
25
+ * Alert whose customer/invoice has no matching Stripe/QB record -> SKIP.
26
+
27
+ Alert plan (10 emails) => 6 require action, 4 must be skipped:
28
+ 2 REFUND (Duplicate charge), 2 SUBMIT_EVIDENCE (Chargeback opened),
29
+ 2 RECEIVE_PAYMENT (Payment received), 2 LEAVE (Under investigation),
30
+ 1 already-refunded 'Duplicate charge' (arms the refund skip guard),
31
+ 1 no-match 'Payment received' (unresolvable distractor).
32
+
33
+ Cross-app data flow (H3):
34
+ Customer + Amount read in the Gmail alert -> locate the matching Stripe payment
35
+ (customer_name + amount in cents) to refund, and the matching Stripe dispute
36
+ (by customer / charge) to submit evidence on. Invoice # in the alert -> matching
37
+ QuickBooks invoice number to receive payment on. Customer email (from the
38
+ matched Stripe payment / QB customer) -> the To of the Gmail reply.
39
+
40
+ Ground-truth embedding (Rule 2), PRECOMPUTED in Python from the visible alert
41
+ type + VERIFIED against the injected Stripe/QB records so visible <=> key can
42
+ never disagree:
43
+ * gmail.initial_state.emails[*]._alert -> per-alert worklist (inline hidden key)
44
+ * slack.initial_state._task_adapter.summary_channel = 'billing-ops'
45
+
46
+ Observable result kept ABSENT at injection (Rule 3):
47
+ * the 2 REFUND-target payments: amount_refunded=0, refunded=False; refunds[]
48
+ holds only a decoy that does NOT reference any target.
49
+ * the 2 SUBMIT_EVIDENCE-target disputes: status='needs_response'.
50
+ * the 2 RECEIVE_PAYMENT-target QB invoices: status Sent/Overdue, paidAmount=0,
51
+ paidDate=None.
52
+ * every Gmail alert email: labels=[]; no 'sent'-folder reply to a target customer.
53
+ * Slack #billing-ops starts EMPTY (no messages, nothing pinned).
54
+ * the already-done distractor payment IS already refunded (must be left alone);
55
+ the LEAVE-row dispute IS 'needs_response' (must be left alone).
56
+
57
+ NOTE: Stripe amounts are in CENTS, QuickBooks amounts are in DOLLARS.
58
+ """
59
+ import datetime as _dt
60
+ import os
61
+ import shlex
62
+ import subprocess
63
+ import time
64
+ import uuid
65
+
66
+ import requests
67
+
68
+
69
+ sid = str(uuid.uuid4())
70
+ with open('/tmp/task_web_sid', 'w', encoding='utf-8') as f:
71
+ f.write(sid)
72
+ print(f'Generated sid: {sid}')
73
+
74
+
75
+ TASK_ID = 'c4b39a92-99cd-45d5-9e0c-a08817d82cb8'
76
+ TODAY = _dt.date(2026, 6, 29)
77
+ SUMMARY_CHANNEL = 'billing-ops'
78
+
79
+
80
+ def norm(s):
81
+ return (str(s) if s is not None else '').strip().lower()
82
+
83
+
84
+ # ---------------------------------------------------------------------------
85
+ # Helpers
86
+ # ---------------------------------------------------------------------------
87
+ def _ts(date_str):
88
+ """Unix seconds for date_str at 12:00 UTC (stable displayed date across TZs)."""
89
+ d = _dt.datetime.strptime(date_str, '%Y-%m-%d').replace(
90
+ hour=12, minute=0, second=0, microsecond=0, tzinfo=_dt.timezone.utc
91
+ )
92
+ return int(d.timestamp())
93
+
94
+
95
+ _CREATED = _ts('2026-01-08')
96
+ _NOW_TS = _ts('2026-06-29')
97
+
98
+
99
+ # ===========================================================================
100
+ # 1) STRIPE — payments + disputes (+ customers, refunds)
101
+ # ===========================================================================
102
+ # Shared customer registry: name -> (stripe_customer_id, email, card)
103
+ _STRIPE_CUSTS = {
104
+ 'Acme Corporation': ('cus_acme00000001', 'billing@acmecorp.com', {'brand': 'visa', 'last4': '4242', 'exp_month': 12, 'exp_year': 2027}),
105
+ 'Globex Industries': ('cus_globex0000012', 'ap@globexind.com', {'brand': 'mastercard', 'last4': '5555', 'exp_month': 8, 'exp_year': 2028}),
106
+ 'TechStart Inc.': ('cus_techstart0001', 'finance@techstart.io', {'brand': 'visa', 'last4': '1234', 'exp_month': 3, 'exp_year': 2027}),
107
+ 'Riverside Medical Group': ('cus_riverside0001', 'it@riversidemedical.org', {'brand': 'visa', 'last4': '8888', 'exp_month': 1, 'exp_year': 2028}),
108
+ 'CloudSync Pro': ('cus_cloudsync0001', 'billing@cloudsyncpro.com', {'brand': 'visa', 'last4': '6543', 'exp_month': 10, 'exp_year': 2028}),
109
+ 'DataVault Systems': ('cus_datavault0001', 'procurement@datavault.io', {'brand': 'amex', 'last4': '0001', 'exp_month': 6, 'exp_year': 2028}),
110
+ 'Pioneer Labs': ('cus_pioneer000001', 'admin@pioneerlabs.io', {'brand': 'visa', 'last4': '7777', 'exp_month': 12, 'exp_year': 2027}),
111
+ 'Northwind Traders': ('cus_northwind0001', 'ap@northwindtraders.com', {'brand': 'mastercard', 'last4': '2323', 'exp_month': 5, 'exp_year': 2027}),
112
+ 'Summit Retail': ('cus_summit0000001', 'billing@summitretail.com', {'brand': 'visa', 'last4': '9090', 'exp_month': 9, 'exp_year': 2028}),
113
+ }
114
+
115
+
116
+ def _stripe_customer(name):
117
+ cid, email, _card = _STRIPE_CUSTS[name]
118
+ return {
119
+ 'id': cid, 'name': name, 'email': email, 'phone': None, 'description': None,
120
+ 'address': {'line1': '200 Market St', 'line2': None, 'city': 'San Francisco',
121
+ 'state': 'CA', 'postal_code': '94105', 'country': 'US'},
122
+ 'balance': 0, 'currency': 'usd', 'default_payment_method': None,
123
+ 'metadata': {}, 'created': _CREATED, 'livemode': True, 'delinquent': False,
124
+ 'total_spent': 0, 'payments_count': 1,
125
+ }
126
+
127
+
128
+ def _payment(pid, cust_name, amount_cents, date_str, description,
129
+ refunded=False, disputed=False, status='succeeded'):
130
+ cid, email, card = _STRIPE_CUSTS[cust_name]
131
+ captured = (status == 'succeeded')
132
+ return {
133
+ 'id': pid,
134
+ 'amount': amount_cents,
135
+ 'currency': 'usd',
136
+ 'status': status,
137
+ 'description': description,
138
+ 'customer': cid,
139
+ 'customer_email': email,
140
+ 'customer_name': cust_name,
141
+ 'payment_method': {'type': 'card', 'card': dict(card, funding='credit')},
142
+ 'amount_received': amount_cents if captured else 0,
143
+ 'amount_refunded': amount_cents if refunded else 0,
144
+ 'refunded': bool(refunded),
145
+ 'disputed': bool(disputed),
146
+ 'captured': captured,
147
+ 'receipt_email': email,
148
+ 'receipt_url': None,
149
+ 'metadata': {},
150
+ 'created': _ts(date_str),
151
+ 'livemode': True,
152
+ 'risk_score': 12,
153
+ 'risk_level': 'normal',
154
+ 'outcome': {'type': 'authorized' if captured else 'pending',
155
+ 'risk_level': 'normal', 'risk_score': 12, 'reason': None},
156
+ 'invoice': None,
157
+ }
158
+
159
+
160
+ # Payments: 2 refund targets + 1 already-refunded distractor + 1 LEAVE bait
161
+ # (DataVault, refunding it = FALSE POSITIVE) + 3 disputed charges (backing the
162
+ # disputes) + 2 watermark decoys (backing the decoy disputes).
163
+ _STRIPE_PAYMENTS = [
164
+ # --- REFUND targets (Duplicate charge) — ABSENT result: refunded=False ---
165
+ _payment('pi_refund_acme_0001', 'Acme Corporation', 25000, '2026-06-27',
166
+ 'Pro Plan - Monthly (duplicate charge)', refunded=False), # $250.00
167
+ _payment('pi_refund_globex_0002', 'Globex Industries', 9999, '2026-06-28',
168
+ 'Starter Plan - Monthly (duplicate charge)', refunded=False), # $99.99
169
+
170
+ # --- already-refunded distractor (Pioneer): must be LEFT alone ---
171
+ _payment('pi_already_pioneer_09', 'Pioneer Labs', 4999, '2026-06-20',
172
+ 'API Access Add-on (already refunded)', refunded=True), # $49.99
173
+
174
+ # --- LEAVE-row bait (DataVault 'Under investigation'): refunding = leak/FP ---
175
+ _payment('pi_leave_datavault_08', 'DataVault Systems', 18000, '2026-06-26',
176
+ 'Team Plan - Monthly', refunded=False), # $180.00
177
+
178
+ # --- disputed charges backing the SUBMIT_EVIDENCE targets + LEAVE dispute ---
179
+ _payment('pi_disp_techstart_01', 'TechStart Inc.', 12000, '2026-06-10',
180
+ 'Team Plan - Monthly', disputed=True), # $120.00
181
+ _payment('pi_disp_riverside_01', 'Riverside Medical Group', 45000, '2026-06-08',
182
+ 'Clinic Suite - Monthly', disputed=True), # $450.00
183
+ _payment('pi_disp_cloudsync_01', 'CloudSync Pro', 48000, '2026-06-12',
184
+ 'CloudSync Platform - Monthly', disputed=True), # $480.00
185
+
186
+ # --- watermark decoys (backing the decoy disputes; NOT named by any alert) ---
187
+ _payment('pi_decoy_north_0011', 'Northwind Traders', 12000, '2026-06-12',
188
+ 'Pro Plan Upgrade - Monthly', disputed=True),
189
+ _payment('pi_decoy_summit_0012', 'Summit Retail', 30000, '2026-06-14',
190
+ 'Enterprise Annual - Prepaid', disputed=True),
191
+ ]
192
+
193
+
194
+ def _dispute(dispute_id, cust_name, charge_id, amount_cents, reason, status,
195
+ due_date='2026-07-06'):
196
+ cid, _email, _card = _STRIPE_CUSTS[cust_name]
197
+ return {
198
+ 'id': dispute_id,
199
+ 'amount': amount_cents,
200
+ 'currency': 'usd',
201
+ 'charge': charge_id,
202
+ 'customer': cid,
203
+ 'customer_name': cust_name,
204
+ 'reason': reason,
205
+ 'status': status,
206
+ 'evidence_due_by': _ts(due_date),
207
+ 'created': _ts('2026-06-15'),
208
+ 'metadata': {},
209
+ }
210
+
211
+
212
+ # Disputes: 2 SUBMIT_EVIDENCE targets (needs_response) + 1 LEAVE bait
213
+ # (CloudSync needs_response; responding = FALSE POSITIVE) + 2 decoys already
214
+ # past needs_response (under_review / won — excluded from the diff).
215
+ _STRIPE_DISPUTES = [
216
+ # --- SUBMIT_EVIDENCE targets — ABSENT result: status stays 'needs_response' ---
217
+ _dispute('dp_techstart_0001', 'TechStart Inc.', 'pi_disp_techstart_01',
218
+ 12000, 'fraudulent', 'needs_response'),
219
+ _dispute('dp_riverside_0001', 'Riverside Medical Group', 'pi_disp_riverside_01',
220
+ 45000, 'product_not_received', 'needs_response'),
221
+
222
+ # --- LEAVE-row bait (CloudSync 'Under investigation'): responding = leak/FP ---
223
+ _dispute('dp_cloudsync_0001', 'CloudSync Pro', 'pi_disp_cloudsync_01',
224
+ 48000, 'unrecognized', 'needs_response'),
225
+
226
+ # --- watermark decoys (already past needs_response; never enter the diff) ---
227
+ _dispute('dp_decoy_north_001', 'Northwind Traders', 'pi_decoy_north_0011',
228
+ 12000, 'duplicate', 'under_review'),
229
+ _dispute('dp_decoy_summit_01', 'Summit Retail', 'pi_decoy_summit_0012',
230
+ 30000, 'fraudulent', 'won'),
231
+ ]
232
+
233
+ _STRIPE_CUSTOMERS = [_stripe_customer(nm) for nm in _STRIPE_CUSTS]
234
+
235
+ # Decoy refund that references a NON-target payment (watermark; not the targets).
236
+ _STRIPE_REFUNDS = [
237
+ {'id': 're_decoy_pioneer_01', 'amount': 4999, 'currency': 'usd',
238
+ 'charge': 'pi_already_pioneer_09', 'reason': 'duplicate', 'status': 'succeeded',
239
+ 'created': _ts('2026-06-21'), 'metadata': {}},
240
+ ]
241
+
242
+ _STRIPE_STATE = {
243
+ 'business': {
244
+ 'name': 'Northwind SaaS', 'email': 'admin@northwind-saas.com',
245
+ 'url': 'https://northwind-saas.com', 'support_email': 'support@northwind-saas.com',
246
+ 'country': 'US', 'currency': 'usd', 'timezone': 'America/Los_Angeles',
247
+ },
248
+ 'currentUser': {'id': 'user_admin', 'name': 'Finance Admin',
249
+ 'email': 'admin@northwind-saas.com', 'role': 'administrator', 'avatar': None},
250
+ 'balance': {'available': 8421500, 'pending': 1530000, 'reserved': 0, 'currency': 'usd'},
251
+ 'customers': _STRIPE_CUSTOMERS,
252
+ 'payments': _STRIPE_PAYMENTS,
253
+ 'products': [],
254
+ 'prices': [],
255
+ 'invoices': [],
256
+ 'subscriptions': [],
257
+ 'payouts': [],
258
+ 'disputes': _STRIPE_DISPUTES,
259
+ 'refunds': _STRIPE_REFUNDS, # decoy only; NONE references a refund target (Rule 3)
260
+ 'balanceTransactions': [],
261
+ 'events': [],
262
+ 'paymentMethods': [],
263
+ 'testMode': False,
264
+ 'searchQuery': '',
265
+ 'selectedDateRange': '30d',
266
+ 'metrics': {
267
+ 'today': {'grossVolume': 0, 'grossVolumeChart': []},
268
+ 'summary': {
269
+ 'grossVolume': {'amount': 100097, 'change': 0, 'previousAmount': 0},
270
+ 'netVolume': {'amount': 97000, 'change': 0, 'previousAmount': 0},
271
+ 'disputeActivity': {'rate': 0, 'change': 0, 'previousRate': 0},
272
+ },
273
+ 'chartData': {'grossVolume': [], 'netVolume': [], 'disputeRate': []},
274
+ },
275
+ }
276
+
277
+
278
+ # ===========================================================================
279
+ # 2) QUICKBOOKS — invoices (+ customers). Amounts in DOLLARS.
280
+ # ===========================================================================
281
+ _QB_CUSTOMERS = [
282
+ {'id': 'c1', 'name': 'Dev Solutions LLC', 'company': 'Dev Solutions LLC', 'email': 'accounts@devsolutions.co', 'phone': '(555) 100-2001'},
283
+ {'id': 'c2', 'name': 'BrightPath Education', 'company': 'BrightPath Education', 'email': 'admin@brightpath.edu', 'phone': '(555) 100-2002'},
284
+ {'id': 'c3', 'name': 'Summit Retail', 'company': 'Summit Retail', 'email': 'billing@summitretail.com', 'phone': '(555) 100-2003'},
285
+ {'id': 'c4', 'name': 'Harbor Logistics', 'company': 'Harbor Logistics', 'email': 'ap@harborlogistics.com', 'phone': '(555) 100-2004'},
286
+ ]
287
+ for _c in _QB_CUSTOMERS:
288
+ _c.setdefault('address', '100 Market St, San Francisco, CA 94105')
289
+ _c.setdefault('balance', 0)
290
+ _c.setdefault('notes', '')
291
+ _c.setdefault('isActive', True)
292
+ _c.setdefault('createdAt', '2026-01-08')
293
+
294
+
295
+ def _qb_invoice(inv_id, number, customer_id, due_date, total, status):
296
+ inv_date = (_dt.date.fromisoformat(due_date) - _dt.timedelta(days=30)).isoformat()
297
+ paid = (status == 'Paid')
298
+ return {
299
+ 'id': inv_id,
300
+ 'number': number,
301
+ 'customerId': customer_id,
302
+ 'date': inv_date,
303
+ 'dueDate': due_date,
304
+ 'items': [{'id': f'{inv_id}_li1', 'productId': 'p1',
305
+ 'description': 'Professional services', 'qty': 1,
306
+ 'rate': total, 'amount': total}],
307
+ 'subtotal': total,
308
+ 'tax': 0,
309
+ 'total': total,
310
+ 'status': status,
311
+ 'paidAmount': total if paid else 0,
312
+ 'paidDate': inv_date if paid else None,
313
+ 'terms': 'Net 30',
314
+ 'message': '',
315
+ 'createdAt': f'{inv_date}T09:00:00Z',
316
+ }
317
+
318
+
319
+ # Invoices: 2 receive-payment targets (Sent/Overdue) + 1 unpaid decoy (receiving
320
+ # payment on it = FALSE POSITIVE) + 2 already-Paid decoys + 1 Draft decoy.
321
+ _QB_INVOICES = [
322
+ # --- RECEIVE_PAYMENT targets — ABSENT: not Paid, paidAmount=0 ---
323
+ _qb_invoice('inv_dev_1042', '1042', 'c1', '2026-06-10', 1800.00, 'Sent'), # target
324
+ _qb_invoice('inv_bright_1057', '1057', 'c2', '2026-05-20', 3200.00, 'Overdue'), # target
325
+
326
+ # --- leak bait: an unpaid invoice NOT referenced by any alert ---
327
+ _qb_invoice('inv_summit_1099', '1099', 'c3', '2026-06-15', 500.00, 'Sent'), # receiving = FP
328
+
329
+ # --- watermark decoys (already Paid / Draft) ---
330
+ _qb_invoice('inv_paid_1001', '1001', 'c4', '2026-05-01', 2200.00, 'Paid'),
331
+ _qb_invoice('inv_paid_1002', '1002', 'c1', '2026-04-25', 9900.00, 'Paid'),
332
+ _qb_invoice('inv_draft_1100', '1100', 'c4', '2026-06-25', 1750.00, 'Draft'),
333
+ ]
334
+
335
+ _QB_STATE = {
336
+ 'company': {
337
+ 'name': 'Northwind SaaS', 'address': '123 Business Rd, San Francisco, CA 94105',
338
+ 'email': 'admin@northwind-saas.com', 'industry': 'Technology Services',
339
+ 'accountingMethod': 'Accrual',
340
+ },
341
+ 'customers': _QB_CUSTOMERS,
342
+ 'invoices': _QB_INVOICES,
343
+ }
344
+
345
+
346
+ # ===========================================================================
347
+ # 3) THE ALERT WORKLIST + PRECOMPUTED ANSWER KEY (single source of truth)
348
+ # ===========================================================================
349
+ # Index injected records so the key can point at real ids + verify pre-state.
350
+ _PAY_BY_ID = {p['id']: p for p in _STRIPE_PAYMENTS}
351
+ _DISP_BY_ID = {d['id']: d for d in _STRIPE_DISPUTES}
352
+ _INV_BY_ID = {i['id']: i for i in _QB_INVOICES}
353
+ _QB_CUST_BY_ID = {c['id']: c for c in _QB_CUSTOMERS}
354
+
355
+ # Status label per action, matched by NAME.
356
+ _LABEL_FOR_ACTION = {
357
+ 'refund': 'Refunded',
358
+ 'submit_evidence': 'Disputed',
359
+ 'receive_payment': 'Reconciled',
360
+ }
361
+
362
+ # Each alert references its target record id (or None for the no-match row).
363
+ _ALERT_SPECS = [
364
+ # --- REFUND (Duplicate charge) ---
365
+ dict(eid='m01', customer='Acme Corporation', alert_type='Duplicate charge',
366
+ amount_display='$250.00', invoice_num='',
367
+ stripe_payment_id='pi_refund_acme_0001', stripe_dispute_id=None, qb_invoice_id=None),
368
+ dict(eid='m02', customer='Globex Industries', alert_type='Duplicate charge',
369
+ amount_display='$99.99', invoice_num='',
370
+ stripe_payment_id='pi_refund_globex_0002', stripe_dispute_id=None, qb_invoice_id=None),
371
+ # --- SUBMIT_EVIDENCE (Chargeback opened) ---
372
+ dict(eid='m03', customer='TechStart Inc.', alert_type='Chargeback opened',
373
+ amount_display='$120.00', invoice_num='',
374
+ stripe_payment_id=None, stripe_dispute_id='dp_techstart_0001', qb_invoice_id=None),
375
+ dict(eid='m04', customer='Riverside Medical Group', alert_type='Chargeback opened',
376
+ amount_display='$450.00', invoice_num='',
377
+ stripe_payment_id=None, stripe_dispute_id='dp_riverside_0001', qb_invoice_id=None),
378
+ # --- RECEIVE_PAYMENT (Payment received) ---
379
+ dict(eid='m05', customer='Dev Solutions LLC', alert_type='Payment received',
380
+ amount_display='$1,800.00', invoice_num='1042',
381
+ stripe_payment_id=None, stripe_dispute_id=None, qb_invoice_id='inv_dev_1042'),
382
+ dict(eid='m06', customer='BrightPath Education', alert_type='Payment received',
383
+ amount_display='$3,200.00', invoice_num='1057',
384
+ stripe_payment_id=None, stripe_dispute_id=None, qb_invoice_id='inv_bright_1057'),
385
+ # --- LEAVE (Under investigation) — tempting distractors ---
386
+ dict(eid='m07', customer='DataVault Systems', alert_type='Under investigation',
387
+ amount_display='$180.00', invoice_num='',
388
+ stripe_payment_id='pi_leave_datavault_08', stripe_dispute_id=None, qb_invoice_id=None),
389
+ dict(eid='m08', customer='CloudSync Pro', alert_type='Under investigation',
390
+ amount_display='$480.00', invoice_num='',
391
+ stripe_payment_id=None, stripe_dispute_id='dp_cloudsync_0001', qb_invoice_id=None),
392
+ # --- already-refunded 'Duplicate charge' -> must be SKIPPED ---
393
+ dict(eid='m09', customer='Pioneer Labs', alert_type='Duplicate charge',
394
+ amount_display='$49.99', invoice_num='',
395
+ stripe_payment_id='pi_already_pioneer_09', stripe_dispute_id=None, qb_invoice_id=None),
396
+ # --- no matching Stripe/QB record -> SKIP ---
397
+ dict(eid='m10', customer='Zenith Partners', alert_type='Payment received',
398
+ amount_display='$750.00', invoice_num='9999',
399
+ stripe_payment_id=None, stripe_dispute_id=None, qb_invoice_id=None),
400
+ ]
401
+
402
+
403
+ def _decide(spec):
404
+ """Derive (action, requires_action) from the alert TYPE, VERIFIED against the
405
+ current injected state. Precomputed so the visible alert <=> key can't drift."""
406
+ t = norm(spec['alert_type'])
407
+
408
+ if t == 'duplicate charge':
409
+ pid = spec['stripe_payment_id']
410
+ pay = _PAY_BY_ID.get(pid) if pid else None
411
+ if pay is None:
412
+ return 'skip', False
413
+ already = bool(pay.get('refunded')) or (
414
+ pay.get('amount', 0) > 0 and pay.get('amount_refunded', 0) >= pay.get('amount', 0))
415
+ return 'refund', (not already)
416
+
417
+ if t == 'chargeback opened':
418
+ did = spec['stripe_dispute_id']
419
+ disp = _DISP_BY_ID.get(did) if did else None
420
+ if disp is None:
421
+ return 'skip', False
422
+ already = norm(disp.get('status')) != 'needs_response'
423
+ return 'submit_evidence', (not already)
424
+
425
+ if t == 'payment received':
426
+ iid = spec['qb_invoice_id']
427
+ inv = _INV_BY_ID.get(iid) if iid else None
428
+ if inv is None:
429
+ return 'skip', False
430
+ already = (norm(inv.get('status')) == 'paid')
431
+ return 'receive_payment', (not already)
432
+
433
+ # 'Under investigation' (and anything else) -> LEAVE
434
+ return 'leave', False
435
+
436
+
437
+ def _customer_email(spec, action):
438
+ """Cross-app carry: the reply-To is read from the matched Stripe payment /
439
+ dispute customer (refund / submit_evidence) or the QB customer (receive)."""
440
+ if action == 'refund':
441
+ pay = _PAY_BY_ID.get(spec['stripe_payment_id'])
442
+ return pay.get('customer_email') if pay else None
443
+ if action == 'submit_evidence':
444
+ disp = _DISP_BY_ID.get(spec['stripe_dispute_id'])
445
+ if disp:
446
+ _cid, email, _card = _STRIPE_CUSTS.get(disp.get('customer_name'), (None, None, None))
447
+ return email
448
+ return None
449
+ if action == 'receive_payment':
450
+ inv = _INV_BY_ID.get(spec['qb_invoice_id'])
451
+ cust = _QB_CUST_BY_ID.get(inv.get('customerId')) if inv else None
452
+ return cust.get('email') if cust else None
453
+ return None
454
+
455
+
456
+ ALERT_SUBJECTS = {
457
+ 'Duplicate charge': lambda s: f"Payment alert: Duplicate charge flagged for {s['customer']} ({s['amount_display']})",
458
+ 'Chargeback opened': lambda s: f"Payment alert: Chargeback opened by {s['customer']} ({s['amount_display']})",
459
+ 'Payment received': lambda s: f"Payment alert: Payment received from {s['customer']} — invoice #{s['invoice_num']} ({s['amount_display']})",
460
+ 'Under investigation': lambda s: f"Payment alert: {s['customer']} account under investigation ({s['amount_display']})",
461
+ }
462
+
463
+
464
+ def _alert_body(spec, action, customer_email):
465
+ lines = [
466
+ f"Automated billing alert ({spec['alert_type']}).",
467
+ f"Customer: {spec['customer']}",
468
+ f"Amount: {spec['amount_display']}",
469
+ ]
470
+ if spec['invoice_num']:
471
+ lines.append(f"Invoice #: {spec['invoice_num']}")
472
+ if customer_email:
473
+ lines.append(f"Customer contact: {customer_email}")
474
+ lines.append("Review this event and take the corrective action its type calls for.")
475
+ return '\n'.join(lines)
476
+
477
+
478
+ GMAIL_USER = {
479
+ 'userId': 'u1',
480
+ 'username': 'Finance Ops',
481
+ 'email': 'billing-ops@northwind-saas.com',
482
+ 'avatar': 'https://picsum.photos/200/200?random=1',
483
+ }
484
+ BILLING_BOT = {'name': 'Billing System', 'email': 'billing-bot@northwind-saas.com', 'avatar': ''}
485
+
486
+
487
+ emails = []
488
+ expected = []
489
+ for idx, spec in enumerate(_ALERT_SPECS):
490
+ action, requires_action = _decide(spec)
491
+ customer_email = _customer_email(spec, action)
492
+ subject = ALERT_SUBJECTS[spec['alert_type']](spec)
493
+
494
+ refund_amount_cents = None
495
+ if action == 'refund' and spec['stripe_payment_id']:
496
+ refund_amount_cents = _PAY_BY_ID[spec['stripe_payment_id']].get('amount')
497
+ qb_invoice_number = None
498
+ if action == 'receive_payment' and spec['qb_invoice_id'] in _INV_BY_ID:
499
+ qb_invoice_number = _INV_BY_ID[spec['qb_invoice_id']].get('number')
500
+ label_name = _LABEL_FOR_ACTION.get(action) if requires_action else None
501
+
502
+ # ---- inline hidden answer key (reward reads emails[*]._alert) ----
503
+ _alert = {
504
+ 'type': spec['alert_type'],
505
+ 'action': action,
506
+ 'requires_action': bool(requires_action),
507
+ 'customer': spec['customer'],
508
+ 'customer_email': customer_email if requires_action else None,
509
+ 'stripe_payment_id': spec['stripe_payment_id'] if action == 'refund' else None,
510
+ 'refund_amount_cents': refund_amount_cents,
511
+ 'stripe_dispute_id': spec['stripe_dispute_id'] if action == 'submit_evidence' else None,
512
+ 'qb_invoice_id': spec['qb_invoice_id'] if action == 'receive_payment' else None,
513
+ 'qb_invoice_number': qb_invoice_number,
514
+ 'label_name': label_name,
515
+ 'reply_subject': f'Re: {subject}' if requires_action else None,
516
+ }
517
+
518
+ minutes_ago = 60 * (len(_ALERT_SPECS) - idx) # spread overnight, all before today
519
+ ts_dt = _dt.datetime(2026, 6, 29, 6, 0, tzinfo=_dt.timezone.utc) - _dt.timedelta(minutes=minutes_ago)
520
+ body = _alert_body(spec, action, customer_email)
521
+ emails.append({
522
+ 'id': spec['eid'],
523
+ 'threadId': f"thread_{spec['eid']}",
524
+ 'from': dict(BILLING_BOT),
525
+ 'to': [{'name': GMAIL_USER['username'], 'email': GMAIL_USER['email']}],
526
+ 'cc': [], 'bcc': [],
527
+ 'folder': 'inbox',
528
+ 'subject': subject,
529
+ 'body': body,
530
+ 'snippet': body[:120],
531
+ 'timestamp': ts_dt.strftime('%Y-%m-%dT%H:%M:%SZ'),
532
+ 'read': False, 'starred': False, 'important': False,
533
+ 'labels': [], # Rule 3: no status label yet
534
+ 'category': 'primary',
535
+ 'attachments': [],
536
+ '_alert': _alert, # inline hidden answer key
537
+ })
538
+
539
+ expected.append({'eid': spec['eid'], **_alert})
540
+
541
+
542
+ # ---- resolved partitions (for asserts + the DEBUG line) ----
543
+ refund_rows = [e for e in expected if e['action'] == 'refund' and e['requires_action']]
544
+ dispute_rows = [e for e in expected if e['action'] == 'submit_evidence' and e['requires_action']]
545
+ receive_rows = [e for e in expected if e['action'] == 'receive_payment' and e['requires_action']]
546
+ leave_rows = [e for e in expected if e['action'] == 'leave']
547
+ refund_done = [e for e in expected if e['action'] == 'refund' and not e['requires_action']]
548
+ skip_rows = [e for e in expected if e['action'] == 'skip']
549
+ requires_rows = [e for e in expected if e['requires_action']]
550
+ resolved_count = len(requires_rows)
551
+
552
+
553
+ # ---------------------------------------------------------------------------
554
+ # Build-time asserts — pin the partition sizes + Rule-3 absences.
555
+ # ---------------------------------------------------------------------------
556
+ assert len(_ALERT_SPECS) == 10, len(_ALERT_SPECS)
557
+ assert len(refund_rows) == 2, refund_rows # 2 REFUND require action
558
+ assert len(dispute_rows) == 2, dispute_rows # 2 SUBMIT_EVIDENCE require action
559
+ assert len(receive_rows) == 2, receive_rows # 2 RECEIVE_PAYMENT require action
560
+ assert len(leave_rows) == 2, leave_rows # 2 LEAVE (Under investigation)
561
+ assert len(refund_done) == 1, refund_done # 1 already-refunded distractor
562
+ assert len(skip_rows) == 1, skip_rows # 1 no-match
563
+ assert resolved_count == 6, resolved_count # 6 require action
564
+ assert (len(leave_rows) + len(refund_done) + len(skip_rows)) == 4 # 4 must be skipped
565
+
566
+ # every require-action alert carries a status label + reply target + customer email
567
+ for e in requires_rows:
568
+ assert e['label_name'] in ('Refunded', 'Disputed', 'Reconciled'), e
569
+ assert e['customer_email'], e
570
+ assert e['reply_subject'] and e['reply_subject'].startswith('Re: '), e
571
+
572
+ # Rule 3: refund targets NOT yet refunded.
573
+ for e in refund_rows:
574
+ p = _PAY_BY_ID[e['stripe_payment_id']]
575
+ assert p['refunded'] is False and p['amount_refunded'] == 0, p['id']
576
+ # Rule 3: the already-done distractor IS refunded (must be left alone).
577
+ _pioneer = _PAY_BY_ID['pi_already_pioneer_09']
578
+ assert _pioneer['refunded'] is True and _pioneer['amount_refunded'] == _pioneer['amount']
579
+ # Rule 3: submit-evidence targets are 'needs_response' at injection.
580
+ for e in dispute_rows:
581
+ d = _DISP_BY_ID[e['stripe_dispute_id']]
582
+ assert norm(d['status']) == 'needs_response', d['id']
583
+ # Rule 3: the LEAVE-row dispute IS 'needs_response' (bait — must be left alone).
584
+ assert norm(_DISP_BY_ID['dp_cloudsync_0001']['status']) == 'needs_response'
585
+ # Rule 3: receive targets NOT yet Paid.
586
+ for e in receive_rows:
587
+ inv = _INV_BY_ID[e['qb_invoice_id']]
588
+ assert norm(inv['status']) in ('sent', 'overdue'), inv['status']
589
+ assert inv['paidAmount'] == 0 and inv['paidDate'] is None, inv['id']
590
+ # Rule 3: NO refund references any refund target.
591
+ _target_pay_ids = {e['stripe_payment_id'] for e in refund_rows}
592
+ assert all(r['charge'] not in _target_pay_ids for r in _STRIPE_REFUNDS)
593
+ # Rule 3: every alert email ships with no status label.
594
+ assert all(em['labels'] == [] for em in emails)
595
+
596
+ print(f'Precomputed worklist: refund={len(refund_rows)} submit_evidence={len(dispute_rows)} '
597
+ f'receive_payment={len(receive_rows)} leave={len(leave_rows)} '
598
+ f'already_refunded={len(refund_done)} no_match={len(skip_rows)} '
599
+ f'-> requires_action={resolved_count}, skipped={10 - resolved_count}')
600
+
601
+
602
+ # ===========================================================================
603
+ # 4) GMAIL — the alert inbox. Status labels seeded by NAME (Rule 3: unused).
604
+ # ===========================================================================
605
+ GMAIL_LABELS = [
606
+ {'id': 'l1', 'name': 'Work', 'color': '#ef4444'},
607
+ {'id': 'l2', 'name': 'Personal', 'color': '#3b82f6'},
608
+ {'id': 'l4', 'name': 'Finance', 'color': '#eab308'},
609
+ # status labels the SELECTION-GATED Label button applies (matched by NAME) ---
610
+ {'id': 'lbl-refunded', 'name': 'Refunded', 'color': '#22c55e'},
611
+ {'id': 'lbl-disputed', 'name': 'Disputed', 'color': '#eb5a46'},
612
+ {'id': 'lbl-reconciled', 'name': 'Reconciled', 'color': '#0ea5e9'},
613
+ ]
614
+
615
+ _GMAIL_STATE = {
616
+ 'user': GMAIL_USER,
617
+ 'emails': emails,
618
+ 'labels': GMAIL_LABELS,
619
+ 'drafts': [],
620
+ 'settings': {'density': 'default', 'undoSend': 10},
621
+ 'today': '2026-06-29',
622
+ '_task_adapter': {
623
+ 'task_id': TASK_ID,
624
+ 'variant': 'eval',
625
+ 'resolved_count': resolved_count,
626
+ },
627
+ }
628
+
629
+
630
+ # ===========================================================================
631
+ # 5) SLACK — #billing-ops starts EMPTY (Rule 3); decoy chatter elsewhere.
632
+ # ===========================================================================
633
+ _SLACK_STATE = {
634
+ 'channels': [
635
+ {'channelId': 'general', 'name': 'general', 'description': 'Company-wide announcements',
636
+ 'topic': 'Welcome to Northwind SaaS!', 'isPrivate': False, 'isStarred': True,
637
+ 'members': ['user_1', 'user_2'], 'createdBy': 'user_2', 'createdAt': '2026-05-01T09:00:00Z',
638
+ 'pinnedMessages': [], 'unreadCount': 0},
639
+ {'channelId': 'billing-ops', 'name': 'billing-ops',
640
+ 'description': 'Billing operations — payment alerts and reconciliation',
641
+ 'topic': 'Post a summary when you finish clearing the payment-alert inbox', 'isPrivate': False,
642
+ 'isStarred': False, 'members': ['user_1'], 'createdBy': 'user_1',
643
+ 'createdAt': '2026-06-01T00:00:00Z', 'pinnedMessages': [], 'unreadCount': 0},
644
+ ],
645
+ 'currentUser': {'userId': 'user_1', 'fullName': 'Dana Reyes', 'displayName': 'Dana',
646
+ 'email': 'dana.reyes@northwind-saas.com', 'avatar': 'https://picsum.photos/200/200?random=1',
647
+ 'title': 'Finance Ops Analyst', 'status': 'online', 'statusMessage': '',
648
+ 'statusEmoji': '', 'timeZone': 'America/New_York'},
649
+ 'users': [
650
+ {'userId': 'user_1', 'fullName': 'Dana Reyes', 'displayName': 'Dana',
651
+ 'email': 'dana.reyes@northwind-saas.com', 'avatar': 'https://picsum.photos/200/200?random=1',
652
+ 'title': 'Finance Ops Analyst', 'status': 'online', 'statusMessage': '', 'statusEmoji': '',
653
+ 'timeZone': 'America/New_York'},
654
+ {'userId': 'user_2', 'fullName': 'Maya Lindqvist', 'displayName': 'Maya',
655
+ 'email': 'maya.lindqvist@northwind-saas.com', 'avatar': 'https://picsum.photos/200/200?random=2',
656
+ 'title': 'Controller', 'status': 'online', 'statusMessage': '', 'statusEmoji': '',
657
+ 'timeZone': 'Europe/Stockholm'},
658
+ ],
659
+ 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Northwind SaaS', 'icon': ''},
660
+ 'messages': {
661
+ 'general': [
662
+ {'messageId': 'm_g_1', 'senderId': 'user_2',
663
+ 'content': 'Morning all — overnight payment alerts are in the finance inbox.',
664
+ 'timestamp': '2026-06-29T13:02:00Z', 'reactions': [], 'isEdited': False,
665
+ 'threadId': None, 'attachments': []},
666
+ ],
667
+ # #billing-ops starts EMPTY — the gradable post + pin are the agent's work.
668
+ 'billing-ops': [],
669
+ },
670
+ 'threads': {},
671
+ 'dms': [],
672
+ 'bookmarkedMessages': [],
673
+ 'callHistory': [],
674
+ 'settings': {'theme': 'light', 'notifications': 'all', 'displayDensity': 'comfortable',
675
+ 'showAvatars': True, 'use24Hour': False},
676
+ 'invitations': [],
677
+ 'notifications': [],
678
+ '_task_adapter': {
679
+ 'task_id': TASK_ID,
680
+ 'variant': 'eval',
681
+ 'summary_channel': SUMMARY_CHANNEL, # agent posts + pins here (empty at injection)
682
+ 'resolved_count': resolved_count,
683
+ },
684
+ }
685
+
686
+ # Rule 3 guard: #billing-ops has no messages and nothing pinned at injection.
687
+ _bo = next(c for c in _SLACK_STATE['channels'] if c['name'] == SUMMARY_CHANNEL)
688
+ assert _bo['pinnedMessages'] == [], 'billing-ops must have no pinned messages at injection'
689
+ assert _SLACK_STATE['messages'].get(SUMMARY_CHANNEL) == [], 'billing-ops must be empty at injection'
690
+
691
+
692
+ # ===========================================================================
693
+ # 6) INJECT + VERIFY + LAUNCH (domain order: stripe, quickbooks, gmail, slack)
694
+ # ===========================================================================
695
+ APP_STATES = [
696
+ ('http://28.7.184.198:8179', _STRIPE_STATE), # stripe_dashboard_mock
697
+ ('http://28.7.184.198:8172', _QB_STATE), # quickbooks_mock
698
+ ('http://28.7.184.198:8138', _GMAIL_STATE), # gmail_mock
699
+ ('http://28.7.184.198:8178', _SLACK_STATE), # slack_mock
700
+ ]
701
+
702
+
703
+ for app_url, state in APP_STATES:
704
+ resp = requests.post(
705
+ f'{app_url}/post?sid={sid}',
706
+ json={'action': 'set', 'state': state},
707
+ timeout=30,
708
+ )
709
+ assert resp.status_code == 200, (
710
+ f'State injection failed for {app_url}: {resp.text}'
711
+ )
712
+ print(f'State injected: {app_url} sid={sid}')
713
+
714
+ for app_url, _ in APP_STATES:
715
+ go_payload = requests.get(f'{app_url}/go?sid={sid}', timeout=15).json()
716
+ assert go_payload.get('initial_state') is not None, (
717
+ f'initial_state is None after injection for {app_url}'
718
+ )
719
+ print(f'Verified initial_state set: {app_url}')
720
+
721
+
722
+ # PATCHED_BY: patch_wait_mocks_loaded.py
723
+ def launch_gui(command, delay_sec=1.0):
724
+ """Launch a GUI command, fully detached from this script.
725
+
726
+ Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that
727
+ wait_mocks_loaded's CDP phase can verify browser render below.
728
+ Idempotent: if the caller already specified a debug port, keep it.
729
+ """
730
+ env = os.environ.copy()
731
+ env['DISPLAY'] = ':0'
732
+ if isinstance(command, str):
733
+ _parts = shlex.split(command)
734
+ else:
735
+ _parts = list(command)
736
+ if (_parts and 'google-chrome' in _parts[0]
737
+ and not any(p.startswith('--remote-debugging-port') for p in _parts)):
738
+ _parts[1:1] = [
739
+ '--no-first-run',
740
+ '--no-default-browser-check',
741
+ '--remote-debugging-port=1337',
742
+ ]
743
+ subprocess.Popen(
744
+ _parts,
745
+ stdin=subprocess.DEVNULL,
746
+ stdout=subprocess.DEVNULL,
747
+ stderr=subprocess.DEVNULL,
748
+ env=env,
749
+ start_new_session=True,
750
+ )
751
+ time.sleep(delay_sec)
752
+
753
+
754
+ def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12):
755
+ """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style.
756
+
757
+ Phase 1 - Backend readiness:
758
+ Poll each mock's /state?sid=<sid> (preferred) or /go?sid=<sid>
759
+ (fallback) until it returns 200 with 'stored_state' or
760
+ 'initial_state' respectively, or until timeout.
761
+
762
+ Phase 2 - Browser render verification (via CDP + Playwright):
763
+ Connect to http://localhost:1337 (the --remote-debugging-port
764
+ injected by launch_gui above), wait for every open tab to reach
765
+ 'networkidle' AND to contain at least 20 DOM elements. This
766
+ guarantees the SPA fetched /go?sid= data AND actually painted,
767
+ not just that the mock backend is up.
768
+
769
+ Fallback:
770
+ If Playwright is missing or CDP cannot be reached, sleep for
771
+ `render_buffer` seconds as a best-effort delay so the screenshot
772
+ loop does not start on a still-blank tab.
773
+ """
774
+ import urllib.request as _urlreq
775
+ import time as _t
776
+ _urls = [p for p, _ in app_states]
777
+ _opener = _urlreq.build_opener(_urlreq.ProxyHandler({}))
778
+
779
+ # ---- Phase 1: backend readiness ----
780
+ _deadline = _t.time() + timeout
781
+ _todo = list(_urls)
782
+ while _todo and _t.time() < _deadline:
783
+ _rest = []
784
+ for _u in _todo:
785
+ _ok = False
786
+ for _path, _need in (('/state?sid=', b'stored_state'),
787
+ ('/go?sid=', b'initial_state')):
788
+ try:
789
+ _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5)
790
+ if _r.status == 200:
791
+ _body = _r.read()
792
+ if _need in _body:
793
+ _ok = True
794
+ break
795
+ except Exception:
796
+ pass
797
+ if _ok:
798
+ print(f" {_u}: backend ready")
799
+ continue
800
+ _rest.append(_u)
801
+ _todo = _rest
802
+ if _todo:
803
+ _t.sleep(2)
804
+ _done = len(_urls) - len(_todo)
805
+ _pend = f" (pending: {_todo})" if _todo else ""
806
+ print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}")
807
+
808
+ # ---- Phase 2: browser render verification via CDP ----
809
+ _cdp_ok = False
810
+ try:
811
+ from playwright.sync_api import sync_playwright
812
+ _cdp_dl = _t.time() + max(15.0, _deadline - _t.time())
813
+ with sync_playwright() as _p:
814
+ _br = None
815
+ while _t.time() < _cdp_dl:
816
+ try:
817
+ _br = _p.chromium.connect_over_cdp('http://localhost:1337')
818
+ break
819
+ except Exception:
820
+ _t.sleep(0.5)
821
+ if _br is None:
822
+ print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?")
823
+ else:
824
+ _n_expected = len(_urls)
825
+ _pages = []
826
+ _pg_dl = _t.time() + 15
827
+ _last_count = -1
828
+ _stable_since = None
829
+ while _t.time() < _pg_dl:
830
+ _pages = []
831
+ for _c in _br.contexts:
832
+ _pages.extend(_c.pages)
833
+ _cnt = len(_pages)
834
+ if _n_expected > 0 and _cnt >= _n_expected:
835
+ break
836
+ if _cnt > 0 and _cnt == _last_count:
837
+ if _stable_since is None:
838
+ _stable_since = _t.time()
839
+ elif _t.time() - _stable_since >= 1.5:
840
+ break
841
+ else:
842
+ _stable_since = None
843
+ _last_count = _cnt
844
+ _t.sleep(0.5)
845
+ _pages = []
846
+ for _c in _br.contexts:
847
+ _pages.extend(_c.pages)
848
+ if not _pages:
849
+ print(" wait_mocks_loaded: CDP connected but no open tabs found")
850
+ else:
851
+ print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render")
852
+ _MIN_ELEMS = 20
853
+ _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap
854
+ for _pg in _pages: # bring each to front once to defeat background-tab render throttling
855
+ try:
856
+ _pg.bring_to_front()
857
+ except Exception:
858
+ pass
859
+ _pending = list(_pages)
860
+ while _pending and _t.time() < _verify_dl:
861
+ _still = []
862
+ for _pg in _pending:
863
+ _ttl = ""
864
+ try:
865
+ _ttl = _pg.title()
866
+ except Exception:
867
+ pass
868
+ try:
869
+ _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0")
870
+ except Exception:
871
+ _n = 0
872
+ if _n >= _MIN_ELEMS:
873
+ print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)")
874
+ else:
875
+ _still.append(_pg)
876
+ _pending = _still
877
+ if _pending:
878
+ _t.sleep(2)
879
+ if not _pending:
880
+ _cdp_ok = True
881
+ else:
882
+ for _pg in _pending:
883
+ _ttl = ""
884
+ try:
885
+ _ttl = _pg.title()
886
+ except Exception:
887
+ pass
888
+ print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back")
889
+ except ImportError:
890
+ print(" wait_mocks_loaded: playwright not installed; skipping CDP phase")
891
+ except Exception as _e:
892
+ print(f" wait_mocks_loaded: CDP phase error ({_e!r})")
893
+
894
+ if not _cdp_ok:
895
+ print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep")
896
+ _t.sleep(render_buffer)
897
+ else:
898
+ print(" wait_mocks_loaded: browser render verified, skipping render_buffer")
899
+
900
+
901
+ def _open_mock_tabs(app_states, sid_value):
902
+ """Open the first mock as the primary Chrome window, the rest as new tabs.
903
+
904
+ Uses launch_gui once per URL so that the macOS localizer regex-extract
905
+ (which grabs the FIRST quoted URL per call) still works correctly.
906
+ """
907
+ _urls = [p for p, _ in app_states]
908
+ if not _urls:
909
+ return
910
+ launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0)
911
+ for _u in _urls[1:]:
912
+ launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0)
913
+
914
+
915
+
916
+ # PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate)
917
+ def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0):
918
+ """Block until every mock serves injected state AND (best-effort) renders."""
919
+ import time as _t
920
+ deadline = _t.time() + timeout
921
+ pending = dict(mocks)
922
+ while pending and _t.time() < deadline:
923
+ for name in list(pending):
924
+ try:
925
+ r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5)
926
+ if r.status_code == 200 and r.json().get('initial_state') is not None:
927
+ del pending[name]
928
+ except Exception:
929
+ pass
930
+ if pending:
931
+ _t.sleep(1.0)
932
+ if pending:
933
+ print(f'WARN: mocks not ready within {timeout}s: {list(pending)}')
934
+ try:
935
+ from playwright.sync_api import sync_playwright
936
+ except ImportError:
937
+ print('WARN: playwright not installed; skipping render check, settle 3s')
938
+ _t.sleep(3.0)
939
+ return
940
+ with sync_playwright() as p:
941
+ try:
942
+ browser = p.chromium.launch(channel='chrome', headless=True,
943
+ args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'])
944
+ except Exception as e:
945
+ print(f'WARN: could not launch chrome for render check: {e}; settle 3s')
946
+ _t.sleep(3.0)
947
+ return
948
+ try:
949
+ for name, url in mocks.items():
950
+ page = browser.new_page()
951
+ try:
952
+ page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000))
953
+ page.wait_for_function(
954
+ "document.body && document.body.innerText.length > 50",
955
+ timeout=int(render_timeout * 1000))
956
+ print(f'[{name}] rendered OK')
957
+ except Exception as e:
958
+ print(f'WARN: [{name}] render check issue: {e}')
959
+ finally:
960
+ page.close()
961
+ finally:
962
+ browser.close()
963
+
964
+
965
+ # ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render
966
+ _open_mock_tabs(APP_STATES, sid)
967
+ wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15)
968
+ wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12)
969
+ print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps')
ar_payment_alert_010__long/reward.py ADDED
@@ -0,0 +1,689 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: Clear the overnight payment-alert inbox
3
+ Task ID: ar_payment_alert_010__long
4
+ Mocks: stripe_dashboard_mock,quickbooks_mock,gmail_mock,slack_mock
5
+
6
+ Scoring (all components in [0,1]; weights sum to EXACTLY 1.0; NO subtracted
7
+ penalties — leak is punished ONLY by precision inside the three F1
8
+ set-membership components):
9
+ 0.24 refund set correctness — F1(true, pred):
10
+ true = {stripe_payment_id of REFUND alerts that require action}
11
+ pred = {payment ids REFUNDED now AND NOT refunded at injection} (a diff).
12
+ Refunding the already-refunded distractor cannot enter pred (no diff);
13
+ refunding the LEAVE-row / a non-target payment IS a false positive.
14
+ 0.22 dispute-evidence set correctness — F1(true, pred):
15
+ true = {stripe_dispute_id of SUBMIT_EVIDENCE alerts that require action}
16
+ pred = {dispute ids 'under_review' (evidence submitted) now AND NOT
17
+ 'under_review' at injection}. Submitting evidence sets a dispute's
18
+ status to 'under_review' (source-verified: Disputes.jsx handleSubmitEvidence
19
+ dispatches UPDATE_DISPUTE -> status='under_review'). The already-under_review
20
+ decoys cannot enter pred (no diff); responding to the LEAVE dispute = FP.
21
+ 0.22 receive-payment set correctness — F1(true, pred):
22
+ true = {qb_invoice_id of RECEIVE_PAYMENT alerts that require action}
23
+ pred = {invoice ids 'Paid' now AND NOT 'Paid' at injection}.
24
+ 0.12 gmail status label — frac of require-action alerts whose CURRENT gmail
25
+ labels include _alert.label_name (Refunded/Disputed/Reconciled), matched
26
+ by NAME (id-agnostic). Emails ship labels=[] so this is 0 at do-nothing.
27
+ 0.10 customer reply — frac of require-action alerts with a 'sent' email either
28
+ addressed to _alert.customer_email OR whose subject == _alert.reply_subject.
29
+ 0.05 slack #billing-ops post: a non-empty message containing a digit.
30
+ 0.05 slack #billing-ops pin: a pinned real #billing-ops message (gated on post).
31
+
32
+ Answer key: read from gmail.initial_state.emails[*]._alert
33
+ .action ∈ {refund, submit_evidence, receive_payment, leave, skip}
34
+ .requires_action: bool
35
+ .stripe_payment_id | .refund_amount_cents (refund target)
36
+ .stripe_dispute_id (submit_evidence target)
37
+ .qb_invoice_id | .qb_invoice_number (receive_payment target)
38
+ .label_name | .customer_email | .reply_subject
39
+ and slack.initial_state._task_adapter.summary_channel -> 'billing-ops'.
40
+
41
+ Stripe amounts are CENTS, QuickBooks amounts are DOLLARS.
42
+ """
43
+ import copy
44
+ import re
45
+ import sys
46
+
47
+ import requests
48
+
49
+
50
+ try:
51
+ with open('/tmp/task_web_sid', encoding='utf-8') as f:
52
+ sid = f.read().strip()
53
+ if not sid:
54
+ raise ValueError('sid is empty')
55
+ except Exception as e:
56
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
57
+ print('REWARD: 0.0')
58
+ sys.exit(0)
59
+
60
+
61
+ APP_URLS = {'stripe_dashboard': 'http://28.7.184.198:8179', 'quickbooks': 'http://28.7.184.198:8172',
62
+ 'gmail': 'http://28.7.184.198:8138', 'slack': 'http://28.7.184.198:8178'}
63
+ _GO_CACHE = {}
64
+
65
+
66
+ def clamp01(x):
67
+ return max(0.0, min(1.0, float(x)))
68
+
69
+
70
+ def frac(num, den):
71
+ return 0.0 if den == 0 else num / den
72
+
73
+
74
+ def f1(true_set, pred_set):
75
+ if not true_set and not pred_set:
76
+ return 1.0
77
+ tp = len(true_set & pred_set)
78
+ if tp == 0:
79
+ return 0.0
80
+ prec = tp / len(pred_set)
81
+ rec = tp / len(true_set)
82
+ return 2 * prec * rec / (prec + rec)
83
+
84
+
85
+ def by_id(items, key='id'):
86
+ return {it.get(key): it for it in (items or []) if isinstance(it, dict)}
87
+
88
+
89
+ def has_text(haystack, *needles):
90
+ s = (haystack or '').lower()
91
+ return any(n.lower() in s for n in needles)
92
+
93
+
94
+ def norm(s):
95
+ return (str(s) if s is not None else '').strip().lower()
96
+
97
+
98
+ def _msg_text(msg):
99
+ if not isinstance(msg, dict):
100
+ return ''
101
+ return msg.get('content') or msg.get('text') or ''
102
+
103
+
104
+ def _slack_channel_messages(slack_state, channel_name):
105
+ channels = slack_state.get('channels', []) if isinstance(slack_state, dict) else []
106
+ target = None
107
+ for ch in channels:
108
+ if isinstance(ch, dict) and norm(ch.get('name')) == norm(channel_name):
109
+ target = ch
110
+ break
111
+ if target is None:
112
+ return []
113
+ ch_msgs = target.get('messages')
114
+ if isinstance(ch_msgs, list):
115
+ return ch_msgs
116
+ msg_map = slack_state.get('messages', {})
117
+ if isinstance(msg_map, dict):
118
+ return msg_map.get(target.get('channelId') or target.get('id'), []) or []
119
+ return []
120
+
121
+
122
+ def _to_float(v):
123
+ try:
124
+ return float(v)
125
+ except (TypeError, ValueError):
126
+ return 0.0
127
+
128
+
129
+ def _sheet_rows(sheet):
130
+ if not isinstance(sheet, dict):
131
+ return []
132
+ rows = sheet.get('rows', [])
133
+ return rows if isinstance(rows, list) else []
134
+
135
+
136
+ def _sheet_tabs(sheets):
137
+ if isinstance(sheets, dict):
138
+ return sheets
139
+ if isinstance(sheets, list):
140
+ out = {}
141
+ for sh in sheets:
142
+ if not isinstance(sh, dict):
143
+ continue
144
+ name = sh.get('name') or sh.get('id')
145
+ if name:
146
+ out[name] = sh
147
+ return out
148
+ return {}
149
+
150
+
151
+ def _jaccard(a, b):
152
+ if not a and not b:
153
+ return 1.0
154
+ u = a | b
155
+ return (len(a & b) / len(u)) if u else 1.0
156
+
157
+
158
+ def _normalize_app_name(app):
159
+ app = (app or '').strip().lower()
160
+ return app[:-5] if app.endswith('_mock') else app
161
+
162
+
163
+ def _parse_cell_id(cell_id):
164
+ if not isinstance(cell_id, str) or not cell_id:
165
+ return None
166
+ idx = 0
167
+ while idx < len(cell_id) and cell_id[idx].isalpha():
168
+ idx += 1
169
+ if idx == 0 or idx >= len(cell_id):
170
+ return None
171
+ col = 0
172
+ for ch in cell_id[:idx].upper():
173
+ col = col * 26 + (ord(ch) - ord('A') + 1)
174
+ try:
175
+ row = int(cell_id[idx:])
176
+ except ValueError:
177
+ return None
178
+ return row, col - 1
179
+
180
+
181
+ def _extract_rows_from_workbook(state):
182
+ if not isinstance(state, dict):
183
+ return None
184
+ sheets = state.get('sheets')
185
+ if not isinstance(sheets, list):
186
+ return None
187
+
188
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
189
+ headers_by_sheet = adapter.get('headers_by_sheet') if isinstance(adapter.get('headers_by_sheet'), dict) else {}
190
+
191
+ out = {}
192
+ for sh in sheets:
193
+ if not isinstance(sh, dict):
194
+ continue
195
+ name = sh.get('name') or sh.get('id') or 'Sheet1'
196
+ data = sh.get('data') if isinstance(sh.get('data'), dict) else {}
197
+
198
+ headers = headers_by_sheet.get(name)
199
+ if not headers:
200
+ cols = []
201
+ for cid, cell in data.items():
202
+ rc = _parse_cell_id(cid)
203
+ if not rc:
204
+ continue
205
+ row_idx, col_idx = rc
206
+ if row_idx != 1:
207
+ continue
208
+ value = ''
209
+ if isinstance(cell, dict):
210
+ value = cell.get('value', '')
211
+ elif cell is not None:
212
+ value = str(cell)
213
+ if value is not None and str(value) != '':
214
+ cols.append((col_idx, str(value)))
215
+ headers = [v for _, v in sorted(cols)]
216
+
217
+ if not headers:
218
+ continue
219
+
220
+ by_row = {}
221
+ for cid, cell in data.items():
222
+ rc = _parse_cell_id(cid)
223
+ if not rc:
224
+ continue
225
+ row_idx, col_idx = rc
226
+ if row_idx <= 1 or col_idx >= len(headers):
227
+ continue
228
+ if isinstance(cell, dict):
229
+ value = cell.get('value', '')
230
+ else:
231
+ value = cell
232
+ by_row.setdefault(row_idx, {})[headers[col_idx]] = value
233
+
234
+ rows = []
235
+ for row_idx in sorted(by_row.keys()):
236
+ row = by_row[row_idx]
237
+ if not any(str(row.get(h, '')).strip() for h in headers):
238
+ continue
239
+ rows.append({h: row.get(h, '') for h in headers})
240
+
241
+ out[name] = {'headers': headers, 'rows': rows}
242
+
243
+ if not out:
244
+ return None
245
+ return {'sheets': out}
246
+
247
+
248
+ def _materialize_google_sheets(payload):
249
+ for key in ('initial_state', 'current_state'):
250
+ state = payload.get(key)
251
+ if not isinstance(state, dict):
252
+ continue
253
+ maybe_rows = _extract_rows_from_workbook(state)
254
+ if maybe_rows is not None:
255
+ state['_ui_workbook'] = {
256
+ 'sheets': copy.deepcopy(state.get('sheets', [])),
257
+ 'title': state.get('title'),
258
+ }
259
+ state['sheets'] = maybe_rows['sheets']
260
+
261
+
262
+ def _materialize_slack(payload):
263
+ for key in ('initial_state', 'current_state'):
264
+ state = payload.get(key)
265
+ if not isinstance(state, dict):
266
+ continue
267
+ channels = state.get('channels') if isinstance(state.get('channels'), list) else []
268
+ messages_map = state.get('messages') if isinstance(state.get('messages'), dict) else {}
269
+ for ch in channels:
270
+ if not isinstance(ch, dict):
271
+ continue
272
+ cid = ch.get('channelId') or ch.get('id')
273
+ if not cid:
274
+ continue
275
+ msg_list = messages_map.get(cid) if isinstance(messages_map.get(cid), list) else []
276
+ channel_msgs = ch.get('messages') if isinstance(ch.get('messages'), list) else []
277
+ merged = {
278
+ (m.get('messageId') or m.get('id')): dict(m)
279
+ for m in channel_msgs
280
+ if isinstance(m, dict)
281
+ }
282
+ for m in msg_list:
283
+ if not isinstance(m, dict):
284
+ continue
285
+ mid = m.get('messageId') or m.get('id')
286
+ text = m.get('text') if m.get('text') is not None else m.get('content', '')
287
+ merged[mid] = {
288
+ 'id': mid,
289
+ 'messageId': mid,
290
+ 'text': text,
291
+ 'content': m.get('content', text),
292
+ 'senderId': m.get('senderId'),
293
+ 'timestamp': m.get('timestamp'),
294
+ 'reactions': m.get('reactions') if isinstance(m.get('reactions'), list) else [],
295
+ 'attachments': m.get('attachments') if isinstance(m.get('attachments'), list) else [],
296
+ }
297
+ ch['messages'] = list(merged.values())
298
+
299
+
300
+ def _owner_name_map(state):
301
+ out = {}
302
+ users = state.get('users') if isinstance(state.get('users'), list) else []
303
+ for u in users:
304
+ if not isinstance(u, dict):
305
+ continue
306
+ uid = u.get('userId')
307
+ if not uid:
308
+ continue
309
+ name = (f"{u.get('firstName', '')} {u.get('lastName', '')}".strip() or u.get('name') or uid)
310
+ out[uid] = name
311
+ return out
312
+
313
+
314
+ def _materialize_salesforce(payload):
315
+ for key in ('initial_state', 'current_state'):
316
+ state = payload.get(key)
317
+ if not isinstance(state, dict):
318
+ continue
319
+
320
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
321
+ owner_names = _owner_name_map(state)
322
+
323
+ task_leads = adapter.get('task_leads') if isinstance(adapter.get('task_leads'), dict) else None
324
+ if task_leads and isinstance(state.get('leads'), list):
325
+ restored = []
326
+ for lead in state['leads']:
327
+ if not isinstance(lead, dict):
328
+ continue
329
+ lid = str(lead.get('leadId') or lead.get('id') or '')
330
+ meta = task_leads.get(lid, {})
331
+ restored.append({
332
+ 'id': meta.get('id') or lead.get('leadId') or lead.get('id'),
333
+ 'company': lead.get('company', meta.get('company', '')),
334
+ 'status': lead.get('status', 'New'),
335
+ 'ownerName': owner_names.get(lead.get('ownerId')) or meta.get('ownerName'),
336
+ 'annualRevenue': meta.get('annualRevenue', lead.get('revenue')),
337
+ })
338
+ state['leads'] = restored
339
+
340
+ task_accounts = adapter.get('task_accounts') if isinstance(adapter.get('task_accounts'), dict) else None
341
+ if task_accounts and isinstance(state.get('accounts'), list):
342
+ current_by_id = {}
343
+ for acc in state['accounts']:
344
+ if isinstance(acc, dict):
345
+ current_by_id[str(acc.get('accountId') or acc.get('id') or '')] = acc
346
+
347
+ restored_accounts = []
348
+ for aid, meta in task_accounts.items():
349
+ cur = current_by_id.get(str(aid), {})
350
+ restored_accounts.append({
351
+ 'id': meta.get('id') or aid,
352
+ 'name': meta.get('name') or cur.get('name', ''),
353
+ 'contact': meta.get('contact'),
354
+ 'wonWithin7d': bool(meta.get('wonWithin7d', False)),
355
+ 'onboardingStage': cur.get('onboardingStage', meta.get('onboardingStage')),
356
+ })
357
+ state['accounts'] = restored_accounts
358
+
359
+
360
+ def _materialize_google_docs(payload):
361
+ for key in ('initial_state', 'current_state'):
362
+ state = payload.get(key)
363
+ if not isinstance(state, dict):
364
+ continue
365
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
366
+ task_docs = adapter.get('task_documents') if isinstance(adapter.get('task_documents'), dict) else None
367
+ if not task_docs:
368
+ continue
369
+ docs_map = state.get('documents') if isinstance(state.get('documents'), dict) else {}
370
+ restored = []
371
+ for did, meta in task_docs.items():
372
+ cur = docs_map.get(did, {}) if isinstance(docs_map, dict) else {}
373
+ restored.append({
374
+ 'id': meta.get('id') or did,
375
+ 'title': cur.get('title', meta.get('title')),
376
+ 'vendor': meta.get('vendor'),
377
+ 'folder': meta.get('folder'),
378
+ 'content': cur.get('content', meta.get('content', '')),
379
+ })
380
+ state['documents'] = restored
381
+
382
+
383
+ def _adapt_payload_for_reward(app, payload):
384
+ app_name = _normalize_app_name(app)
385
+ if app_name == 'google_sheets':
386
+ _materialize_google_sheets(payload)
387
+ elif app_name == 'slack':
388
+ _materialize_slack(payload)
389
+ elif app_name == 'salesforce':
390
+ _materialize_salesforce(payload)
391
+ elif app_name == 'google_docs':
392
+ _materialize_google_docs(payload)
393
+ return payload
394
+
395
+
396
+ def go(app_name):
397
+ if app_name in _GO_CACHE:
398
+ return _GO_CACHE[app_name]
399
+
400
+ base = APP_URLS.get(app_name)
401
+ if not base:
402
+ print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)')
403
+ print('REWARD: 0.0')
404
+ sys.exit(0)
405
+
406
+ try:
407
+ resp = requests.get(f'{base}/go?sid={sid}', timeout=15)
408
+ resp.raise_for_status()
409
+ payload = resp.json()
410
+ except Exception as e:
411
+ print(f'CRITICAL: cannot fetch {app_name} go state: {e}')
412
+ print('REWARD: 0.0')
413
+ sys.exit(0)
414
+
415
+ payload = _adapt_payload_for_reward(app_name, payload)
416
+ _GO_CACHE[app_name] = payload
417
+ return payload
418
+
419
+
420
+ # =============================================================================
421
+ # Task-specific reward
422
+ #
423
+ # Answer key lives in gmail.initial_state.emails[*]._alert — one dict per alert:
424
+ # action ∈ {refund, submit_evidence, receive_payment, leave, skip}
425
+ # requires_action: bool
426
+ # stripe_payment_id | refund_amount_cents (refund target)
427
+ # stripe_dispute_id (submit_evidence target)
428
+ # qb_invoice_id | qb_invoice_number (receive_payment target)
429
+ # label_name | customer_email | reply_subject
430
+ # slack.initial_state._task_adapter.summary_channel names the aux channel.
431
+ # We score CURRENT state against this key using precision-aware F1 set-membership
432
+ # for the three action sets (computed as a diff vs the injected state) — acting on
433
+ # a distractor / LEAVE item / wrong record lowers precision but never drives the
434
+ # score below 0.
435
+ # =============================================================================
436
+ def _refunded_id_set(stripe_state):
437
+ """Payment ids that are (fully) refunded in this Stripe state — union of the
438
+ payments[].refunded/amount_refunded flags and any refunds[].charge id."""
439
+ ids = set()
440
+ for p in (stripe_state.get('payments') or []):
441
+ if not isinstance(p, dict):
442
+ continue
443
+ pid = norm(p.get('id'))
444
+ if not pid:
445
+ continue
446
+ amt = p.get('amount') or 0
447
+ ar = p.get('amount_refunded') or 0
448
+ try:
449
+ fully = (float(amt) > 0 and float(ar) >= float(amt))
450
+ except (TypeError, ValueError):
451
+ fully = False
452
+ if p.get('refunded') is True or fully:
453
+ ids.add(pid)
454
+ for r in (stripe_state.get('refunds') or []):
455
+ if isinstance(r, dict) and r.get('charge'):
456
+ ids.add(norm(r.get('charge')))
457
+ return ids
458
+
459
+
460
+ def _evidenced_dispute_id_set(stripe_state):
461
+ """Dispute ids that have had evidence submitted — status flipped to
462
+ 'under_review' (the only status the mock's Submit-Evidence flow sets) or an
463
+ explicit evidence_submitted_at timestamp present."""
464
+ ids = set()
465
+ for d in (stripe_state.get('disputes') or []):
466
+ if not isinstance(d, dict):
467
+ continue
468
+ did = norm(d.get('id'))
469
+ if not did:
470
+ continue
471
+ if norm(d.get('status')) == 'under_review' or d.get('evidence_submitted_at'):
472
+ ids.add(did)
473
+ return ids
474
+
475
+
476
+ def _paid_invoice_id_set(qb_state):
477
+ ids = set()
478
+ for inv in (qb_state.get('invoices') or []):
479
+ if isinstance(inv, dict) and norm(inv.get('status')) == 'paid':
480
+ ids.add(norm(inv.get('id')))
481
+ return ids
482
+
483
+
484
+ def _recipient_emails(email):
485
+ """All recipient emails on a gmail email (To), normalized."""
486
+ out = set()
487
+ to = email.get('to') if isinstance(email, dict) else None
488
+ if isinstance(to, list):
489
+ for x in to:
490
+ if isinstance(x, dict):
491
+ if x.get('email'):
492
+ out.add(norm(x.get('email')))
493
+ elif x:
494
+ out.add(norm(x))
495
+ elif isinstance(to, dict):
496
+ if to.get('email'):
497
+ out.add(norm(to.get('email')))
498
+ elif to:
499
+ out.add(norm(to))
500
+ return out
501
+
502
+
503
+ def _gmail_sent_emails(gmail_state):
504
+ """Sent-folder emails (plus isSent/sentAt fallbacks, then sent/outbox lists)."""
505
+ out = []
506
+ if not isinstance(gmail_state, dict):
507
+ return out
508
+ for e in (gmail_state.get('emails') or []):
509
+ if not isinstance(e, dict):
510
+ continue
511
+ if norm(e.get('folder')) in ('sent', 'sentitems', 'sent items'):
512
+ out.append(e)
513
+ continue
514
+ if e.get('isSent') is True or e.get('sentAt') or e.get('sentDateTime'):
515
+ out.append(e)
516
+ if out:
517
+ return out
518
+ for key in ('sent', 'sentEmails', 'outbox'):
519
+ items = gmail_state.get(key, [])
520
+ if isinstance(items, list):
521
+ out.extend(x for x in items if isinstance(x, dict))
522
+ return out
523
+
524
+
525
+ def reward(go):
526
+ W_REFUND = 0.24
527
+ W_DISPUTE = 0.22
528
+ W_RECEIVE = 0.22
529
+ W_LABEL = 0.12
530
+ W_REPLY = 0.10
531
+ W_POST = 0.05
532
+ W_PIN = 0.05
533
+
534
+ # ---- 1) Answer key from gmail initial_state.emails[*]._alert ----
535
+ gmail = go('gmail')
536
+ gm_init = gmail.get('initial_state', {}) if isinstance(gmail.get('initial_state'), dict) else {}
537
+ gm_cur = gmail.get('current_state', {}) if isinstance(gmail.get('current_state'), dict) else {}
538
+
539
+ emails_i = gm_init.get('emails', []) or []
540
+ alerts = [e for e in emails_i if isinstance(e, dict) and isinstance(e.get('_alert'), dict)]
541
+ if not alerts:
542
+ print('DEBUG_c4b39a92 fatal=no_alert_worklist total=0.0')
543
+ return 0.0
544
+
545
+ def _key(e):
546
+ return e.get('_alert', {})
547
+
548
+ require_alerts = [e for e in alerts if _key(e).get('requires_action')]
549
+
550
+ refund_true = {norm(_key(e).get('stripe_payment_id')) for e in alerts
551
+ if _key(e).get('action') == 'refund' and _key(e).get('requires_action')
552
+ and _key(e).get('stripe_payment_id')}
553
+ dispute_true = {norm(_key(e).get('stripe_dispute_id')) for e in alerts
554
+ if _key(e).get('action') == 'submit_evidence' and _key(e).get('requires_action')
555
+ and _key(e).get('stripe_dispute_id')}
556
+ receive_true = {norm(_key(e).get('qb_invoice_id')) for e in alerts
557
+ if _key(e).get('action') == 'receive_payment' and _key(e).get('requires_action')
558
+ and _key(e).get('qb_invoice_id')}
559
+
560
+ # ---- 2) Stripe: refund set + dispute-evidence set (diff vs injection) ----
561
+ stripe = go('stripe_dashboard')
562
+ st_init = stripe.get('initial_state', {}) if isinstance(stripe.get('initial_state'), dict) else {}
563
+ st_cur = stripe.get('current_state', {}) if isinstance(stripe.get('current_state'), dict) else {}
564
+
565
+ refunded_init = _refunded_id_set(st_init)
566
+ refunded_now = _refunded_id_set(st_cur)
567
+ refund_pred = refunded_now - refunded_init # newly-refunded (diff)
568
+
569
+ evidenced_init = _evidenced_dispute_id_set(st_init)
570
+ evidenced_now = _evidenced_dispute_id_set(st_cur)
571
+ dispute_pred = evidenced_now - evidenced_init # newly-evidenced (diff)
572
+
573
+ # ---- 3) QuickBooks: receive-payment set (diff vs injection) ----
574
+ qb = go('quickbooks')
575
+ qb_init = qb.get('initial_state', {}) if isinstance(qb.get('initial_state'), dict) else {}
576
+ qb_cur = qb.get('current_state', {}) if isinstance(qb.get('current_state'), dict) else {}
577
+ paid_init = _paid_invoice_id_set(qb_init)
578
+ paid_now = _paid_invoice_id_set(qb_cur)
579
+ receive_pred = paid_now - paid_init # newly-paid invoices
580
+
581
+ # F1 components (precision punishes leak; gate on a non-empty true set so a
582
+ # malformed/empty key can never hand out free credit at do-nothing).
583
+ refund_f1 = f1(refund_true, refund_pred) if refund_true else 0.0
584
+ dispute_f1 = f1(dispute_true, dispute_pred) if dispute_true else 0.0
585
+ receive_f1 = f1(receive_true, receive_pred) if receive_true else 0.0
586
+ s_refund = W_REFUND * refund_f1
587
+ s_dispute = W_DISPUTE * dispute_f1
588
+ s_receive = W_RECEIVE * receive_f1
589
+
590
+ # ---- 4) Gmail status label among require-action alerts (matched by NAME) ----
591
+ emails_c = {e.get('id'): e for e in (gm_cur.get('emails', []) or []) if isinstance(e, dict)}
592
+ labels_i = gm_init.get('labels', []) or []
593
+ labels_c = gm_cur.get('labels', []) or []
594
+ gmail_id_to_name = {}
595
+ for lab in list(labels_i) + list(labels_c):
596
+ if isinstance(lab, dict) and lab.get('id') is not None:
597
+ gmail_id_to_name[lab.get('id')] = norm(lab.get('name'))
598
+ label_ok = 0
599
+ for e in require_alerts:
600
+ want = norm(_key(e).get('label_name'))
601
+ cur = emails_c.get(e.get('id'), {})
602
+ got_names = {gmail_id_to_name.get(lid) for lid in (cur.get('labels') or [])}
603
+ # tolerate a label carried as a raw name too
604
+ got_names |= {norm(lid) for lid in (cur.get('labels') or [])}
605
+ if want and want in got_names:
606
+ label_ok += 1
607
+ label_score = frac(label_ok, len(require_alerts)) if require_alerts else 0.0
608
+ s_label = W_LABEL * label_score
609
+
610
+ # ---- 5) Customer reply among require-action alerts ----
611
+ sent = _gmail_sent_emails(gm_cur)
612
+ reply_ok = 0
613
+ for e in require_alerts:
614
+ want_email = norm(_key(e).get('customer_email'))
615
+ want_subj = norm(_key(e).get('reply_subject'))
616
+ matched = False
617
+ for s in sent:
618
+ if want_email and want_email in _recipient_emails(s):
619
+ matched = True
620
+ break
621
+ subj = norm(s.get('subject'))
622
+ if want_subj and subj == want_subj:
623
+ matched = True
624
+ break
625
+ if matched:
626
+ reply_ok += 1
627
+ reply_score = frac(reply_ok, len(require_alerts)) if require_alerts else 0.0
628
+ s_reply = W_REPLY * reply_score
629
+
630
+ # ---- 6) Slack #billing-ops: post (non-empty w/ a digit) + pin ----
631
+ slack = go('slack')
632
+ sl_init = slack.get('initial_state', {}) if isinstance(slack.get('initial_state'), dict) else {}
633
+ sl_cur = slack.get('current_state', {}) if isinstance(slack.get('current_state'), dict) else {}
634
+ s_adapter = sl_init.get('_task_adapter', {}) if isinstance(sl_init.get('_task_adapter'), dict) else {}
635
+ summary_channel = s_adapter.get('summary_channel') or 'billing-ops'
636
+
637
+ bo_msgs = _slack_channel_messages(sl_cur, summary_channel)
638
+ post_ok = any(re.search(r'\d', _msg_text(m)) for m in bo_msgs if isinstance(m, dict))
639
+ s_post = W_POST * (1.0 if post_ok else 0.0)
640
+
641
+ # Pin: at least one pinned id in #billing-ops that matches a real posted message.
642
+ msg_ids = set()
643
+ for m in bo_msgs:
644
+ if isinstance(m, dict):
645
+ mid = m.get('messageId') or m.get('id')
646
+ if mid is not None:
647
+ msg_ids.add(norm(mid))
648
+ pinned = []
649
+ for ch in (sl_cur.get('channels') or []):
650
+ if isinstance(ch, dict) and norm(ch.get('name')) == norm(summary_channel):
651
+ pinned = ch.get('pinnedMessages') or []
652
+ break
653
+ pinned_ids = set()
654
+ for pm in pinned:
655
+ if isinstance(pm, dict):
656
+ pid = pm.get('messageId') or pm.get('id')
657
+ else:
658
+ pid = pm
659
+ if pid is not None:
660
+ pinned_ids.add(norm(pid))
661
+ pin_ok = bool(post_ok and (pinned_ids & msg_ids))
662
+ s_pin = W_PIN * (1.0 if pin_ok else 0.0)
663
+
664
+ score = s_refund + s_dispute + s_receive + s_label + s_reply + s_post + s_pin
665
+
666
+ print(
667
+ 'DEBUG_c4b39a92 '
668
+ f'refund_true={len(refund_true)} refund_pred={len(refund_pred)} refund_f1={round(refund_f1, 4)} '
669
+ f'dispute_true={len(dispute_true)} dispute_pred={len(dispute_pred)} dispute_f1={round(dispute_f1, 4)} '
670
+ f'receive_true={len(receive_true)} receive_pred={len(receive_pred)} receive_f1={round(receive_f1, 4)} '
671
+ f'require={len(require_alerts)} label_ok={label_ok} label_score={round(label_score, 4)} '
672
+ f'reply_ok={reply_ok} reply_score={round(reply_score, 4)} '
673
+ f'post_ok={int(post_ok)} pin_ok={int(pin_ok)} '
674
+ f'w_refund={round(s_refund, 4)} w_dispute={round(s_dispute, 4)} w_receive={round(s_receive, 4)} '
675
+ f'w_label={round(s_label, 4)} w_reply={round(s_reply, 4)} w_post={round(s_post, 4)} w_pin={round(s_pin, 4)} '
676
+ f'total={round(score, 4)}'
677
+ )
678
+
679
+ return clamp01(score)
680
+
681
+
682
+ try:
683
+ score = float(reward(go))
684
+ except Exception as exc:
685
+ print(f'ERROR: reward() raised {exc!r}')
686
+ score = 0.0
687
+
688
+ score = clamp01(score)
689
+ print(f'\nREWARD: {round(score, 4)}')
csm_escalation_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"
csm_escalation_001/initial_setup.py ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: CSM escalation -> tracked bug across Slack/Jira/Salesforce/Notion
194
+ Task ID: csm_escalation_001
195
+ Domain: mock_websites
196
+ Mocks: slack_mock, jira_mock, salesforce_mock, notion_mock
197
+
198
+ NOTE on sid: initial_env and golden_env are SEPARATE VMs that do NOT share /tmp.
199
+ We therefore use a DETERMINISTIC sid derived from the task id. This script owns the
200
+ *_initial sid; golden_patch.py owns the *_golden sid. Both also write their sid to
201
+ /tmp/task_web_sid so reward.py can read it on whichever VM it runs on.
202
+ """
203
+ import os
204
+ import shlex
205
+ import subprocess
206
+ import time
207
+
208
+ import requests
209
+
210
+ TASK_ID = 'csm_escalation_004'
211
+ SID = f'cuagym-{TASK_ID}-initial'
212
+
213
+ MOCKS = {
214
+ 'slack_mock': 'http://28.7.184.198:8178',
215
+ 'jira_mock': 'http://28.7.184.198:8153',
216
+ 'salesforce_mock': 'http://28.7.184.198:8175',
217
+ 'notion_mock': 'http://28.7.184.198:8166',
218
+ }
219
+ PRIMARY_URL = MOCKS['slack_mock']
220
+
221
+ with open('/tmp/task_web_sid', 'w') as f:
222
+ f.write(SID)
223
+ print(f'sid={SID}')
224
+
225
+ # --- Egress proxy helper (MANDATORY) ---
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, proxies={'http': candidate, 'https': candidate})
243
+ return candidate
244
+ except Exception:
245
+ continue
246
+ raise RuntimeError('No working route to mock servers; direct and proxy attempts failed')
247
+
248
+
249
+ PROXY = resolve_proxy(f'{PRIMARY_URL}/go?sid=conn-probe')
250
+ PROXIES = None
251
+ print(f'Egress proxy: {PROXY or "direct"}')
252
+
253
+
254
+ # ===========================================================================
255
+ # BASELINE BUILDERS (shared, conceptually, with golden_patch.py)
256
+ # ===========================================================================
257
+ def build_slack_state():
258
+ users = [
259
+ {"userId": "user_1", "fullName": "Jordan Rivera", "displayName": "Jordan", "email": "jordan.rivera@northwindcloud.com", "avatar": "https://picsum.photos/200/200?random=1", "title": "Customer Success Manager", "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"},
260
+ {"userId": "user_2", "fullName": "Alex Park", "displayName": "Alex", "email": "alex.park@northwindcloud.com", "avatar": "https://picsum.photos/200/200?random=2", "title": "Engineering Lead", "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"},
261
+ {"userId": "user_3", "fullName": "Priya Anand", "displayName": "Priya", "email": "priya.anand@northwindcloud.com", "avatar": "https://picsum.photos/200/200?random=3", "title": "Support Lead", "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/Chicago"},
262
+ {"userId": "user_4", "fullName": "Diego Morales", "displayName": "Diego", "email": "diego.morales@northwindcloud.com", "avatar": "https://picsum.photos/200/200?random=4", "title": "Solutions Engineer", "status": "away", "statusMessage": "", "statusEmoji": "", "timeZone": "America/Los_Angeles"},
263
+ {"userId": "user_5", "fullName": "Hannah Brooks", "displayName": "Hannah", "email": "hannah.brooks@northwindcloud.com", "avatar": "https://picsum.photos/200/200?random=5", "title": "Product Manager", "status": "online", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"},
264
+ {"userId": "user_6", "fullName": "Tom Becker", "displayName": "Tom", "email": "tom.becker@cedarworks.example.com", "avatar": "https://picsum.photos/200/200?random=6", "title": "Ops Manager (Cedar Works)", "status": "online", "statusMessage": "Guest", "statusEmoji": "", "timeZone": "America/Chicago"},
265
+ {"userId": "user_7", "fullName": "Maria Vance", "displayName": "Maria", "email": "maria.vance@vertexmfg.example.com", "avatar": "https://picsum.photos/200/200?random=7", "title": "Admin (Vertex Manufacturing)", "status": "online", "statusMessage": "Guest", "statusEmoji": "", "timeZone": "America/New_York"},
266
+ ]
267
+ current = next(u for u in users if u['userId'] == 'user_1')
268
+
269
+ def channel(cid, name, desc, members, topic=""):
270
+ return {"channelId": cid, "name": name, "description": desc, "topic": topic, "isPrivate": False,
271
+ "isStarred": False, "members": members, "createdBy": "user_1",
272
+ "createdAt": "2026-01-04T09:00:00Z", "pinnedMessages": [], "unreadCount": 0}
273
+
274
+ am = ["user_1", "user_2", "user_3", "user_4", "user_5"]
275
+ channels = [
276
+ channel("general", "general", "Company-wide announcements", am),
277
+ channel("random", "random", "Non-work banter", am),
278
+ channel("engineering", "engineering", "Engineering team", ["user_1", "user_2", "user_4"]),
279
+ channel("design", "design", "Design team", ["user_1", "user_5"]),
280
+ channel("marketing", "marketing", "Marketing team", ["user_1", "user_5"]),
281
+ channel("project-alpha", "project-alpha", "Project Alpha workstream", ["user_1", "user_2"]),
282
+ channel("acct-vertex", "acct-vertex", "Shared channel with customer Vertex Manufacturing",
283
+ ["user_1", "user_3", "user_7"], topic="Vertex Manufacturing <> Northwind Cloud"),
284
+ channel("acct-cedar", "acct-cedar", "Shared channel with customer Cedar Works",
285
+ ["user_1", "user_3", "user_6"], topic="Cedar Works <> Northwind Cloud"),
286
+ ]
287
+ messages = {
288
+ "general": [
289
+ {"messageId": "msg_g1", "senderId": "user_5", "content": "Reminder: quarterly customer reviews are due Friday.", "timestamp": "2026-06-22T13:00:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False},
290
+ {"messageId": "msg_g2", "senderId": "user_2", "content": "Deploy window for v4.2 is tomorrow 6pm ET.", "timestamp": "2026-06-23T15:30:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False},
291
+ ],
292
+ "random": [
293
+ {"messageId": "msg_r1", "senderId": "user_4", "content": "Coffee machine on 3rd floor is fixed.", "timestamp": "2026-06-23T10:00:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False},
294
+ ],
295
+ "engineering": [
296
+ {"messageId": "msg_e1", "senderId": "user_2", "content": "Staging integration latency is being investigated, low impact.", "timestamp": "2026-06-23T11:00:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False},
297
+ ],
298
+ "design": [
299
+ {"messageId": "msg_d1", "senderId": "user_5", "content": "New dashboard mockups in Figma.", "timestamp": "2026-06-22T16:00:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False},
300
+ ],
301
+ "marketing": [
302
+ {"messageId": "msg_m1", "senderId": "user_5", "content": "Case study draft ready for review.", "timestamp": "2026-06-21T14:00:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False},
303
+ ],
304
+ "project-alpha": [
305
+ {"messageId": "msg_pa1", "senderId": "user_2", "content": "Alpha milestone 2 on track.", "timestamp": "2026-06-20T09:00:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False},
306
+ ],
307
+ "acct-vertex": [
308
+ {"messageId": "msg_v1", "senderId": "user_1", "content": "Hi Maria, welcome to our shared channel! Reach out here any time.", "timestamp": "2026-06-18T09:15:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False},
309
+ {"messageId": "msg_v2", "senderId": "user_7", "content": "Thanks Jordan, this is great. Things have been running smoothly so far.", "timestamp": "2026-06-18T09:20:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False},
310
+ {"messageId": "msg_v3", "senderId": "user_7", "content": "Our Salesforce↔Northwind integration has been DOWN since this morning — every sync fails with a 500 error and it's blocking our ops team from pushing orders. Steps to reproduce: (1) open Integrations, (2) click Sync Now, (3) it errors out with a 500. This is urgent, can someone help?", "timestamp": "2026-06-24T13:05:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False},
311
+ ],
312
+ "acct-cedar": [
313
+ {"messageId": "msg_c1", "senderId": "user_6", "content": "Hi team — not urgent at all, but it would be nice to have a dark mode option in the reporting view someday. Just a feature idea for the backlog.", "timestamp": "2026-06-24T10:30:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False},
314
+ ],
315
+ }
316
+ return {
317
+ "currentUser": current,
318
+ "workspace": {"workspaceId": "ws_northwind", "workspaceName": "Northwind Cloud", "icon": ""},
319
+ "users": users,
320
+ "channels": channels,
321
+ "messages": messages,
322
+ "threads": {},
323
+ "dms": [],
324
+ "bookmarkedMessages": [],
325
+ "callHistory": [],
326
+ "settings": {"theme": "light", "notifications": "all", "displayDensity": "comfortable", "showAvatars": True, "use24Hour": False},
327
+ "invitations": [],
328
+ "notifications": [],
329
+ }
330
+
331
+
332
+ def build_jira_state():
333
+ users = [
334
+ {"id": "u1", "name": "Jordan Rivera", "email": "jordan.rivera@northwindcloud.com", "avatar": "https://picsum.photos/100/100?random=u1"},
335
+ {"id": "u2", "name": "Alex Park", "email": "alex.park@northwindcloud.com", "avatar": "https://picsum.photos/100/100?random=u2"},
336
+ {"id": "u3", "name": "Priya Anand", "email": "priya.anand@northwindcloud.com", "avatar": "https://picsum.photos/100/100?random=u3"},
337
+ {"id": "u4", "name": "Diego Morales", "email": "diego.morales@northwindcloud.com", "avatar": "https://picsum.photos/100/100?random=u4"},
338
+ ]
339
+ projects = [
340
+ {"id": "p1", "key": "KAN", "name": "Kanban Project", "leadId": "u1", "category": "Software", "icon": "https://picsum.photos/64/64?random=p1"},
341
+ {"id": "p2", "key": "SCRUM", "name": "Scrum Alpha", "leadId": "u2", "category": "Software", "icon": "https://picsum.photos/64/64?random=p2"},
342
+ ]
343
+ sprints = [
344
+ {"id": "s1", "projectId": "p2", "name": "Sprint 7", "goal": "Stabilize integrations", "startDate": "2026-06-16T12:00:00.000Z", "endDate": "2026-06-30T12:00:00.000Z", "state": "active"},
345
+ {"id": "s2", "projectId": "p2", "name": "Sprint 8", "goal": "Reporting improvements", "startDate": "2026-07-01T12:00:00.000Z", "endDate": "2026-07-14T12:00:00.000Z", "state": "future"},
346
+ ]
347
+
348
+ def issue(iid, key, pid, summary, desc, itype, status, priority, sp, reporter, assignee, sprint=None, labels=None):
349
+ return {"id": iid, "key": key, "projectId": pid, "summary": summary, "description": desc,
350
+ "type": itype, "status": status, "priority": priority, "storyPoints": sp,
351
+ "reporterId": reporter, "assigneeId": assignee, "sprintId": sprint, "epicId": None,
352
+ "labels": labels or [], "subtasks": [], "linkedIssueIds": [],
353
+ "createdAt": "2026-06-15T12:00:00.000Z", "updatedAt": "2026-06-20T12:00:00.000Z"}
354
+
355
+ issues = [
356
+ issue("i1", "KAN-1", "p1", "Set up CI/CD pipeline", "Configure build and deploy automation.", "Story", "In Progress", "High", 5, "u1", "u2"),
357
+ issue("i2", "KAN-2", "p1", "Add SSO login support", "Support SAML-based single sign-on.", "Story", "To Do", "Medium", 8, "u1", "u4"),
358
+ issue("i3", "KAN-3", "p1", "Improve onboarding docs", "Rewrite the getting-started guide.", "Task", "To Do", "Low", 3, "u3", None),
359
+ issue("i4", "SCRUM-1", "p2", "Integration latency on staging", "Sync jobs on the STAGING environment are slower than expected (around 2-3s added latency). Low customer impact; investigate query plan. This is NOT a production outage.", "Bug", "In Progress", "Low", 2, "u2", "u4", sprint="s1", labels=["staging", "performance"]),
360
+ issue("i5", "SCRUM-2", "p2", "Export to CSV button missing", "The CSV export button disappeared on the reports page.", "Bug", "To Do", "Medium", 3, "u3", "u2", sprint="s1"),
361
+ issue("i6", "SCRUM-3", "p2", "Dark mode for reports", "Add a dark theme to the reporting view.", "Story", "To Do", "Low", 5, "u3", None, sprint="s2"),
362
+ ]
363
+ return {
364
+ "currentUser": users[0],
365
+ "users": users,
366
+ "projects": projects,
367
+ "sprints": sprints,
368
+ "issues": issues,
369
+ "comments": [],
370
+ "workflows": [{"id": "w1", "name": "Software Workflow", "transitions": [
371
+ {"from": "To Do", "to": ["In Progress"]},
372
+ {"from": "In Progress", "to": ["In Review", "To Do", "Done"]},
373
+ {"from": "In Review", "to": ["Done", "In Progress"]},
374
+ {"from": "Done", "to": ["In Progress", "To Do"]}]}],
375
+ "notifications": [],
376
+ }
377
+
378
+
379
+ def build_salesforce_state():
380
+ users = [
381
+ {"userId": "user-1", "firstName": "Jordan", "lastName": "Rivera", "email": "jordan.rivera@northwindcloud.com", "phone": "(555) 123-4567", "title": "Customer Success Manager", "department": "Customer Success", "role": "CSM", "avatar": "https://i.pravatar.cc/150?u=user-1", "timezone": "America/New_York", "locale": "en-US", "theme": "lightning"},
382
+ {"userId": "user-2", "firstName": "Emma", "lastName": "Wilson", "email": "emma.wilson@northwindcloud.com", "phone": "(555) 234-5678", "title": "Account Executive", "department": "Sales", "role": "Rep", "avatar": "https://i.pravatar.cc/150?u=user-2", "timezone": "America/New_York", "locale": "en-US", "theme": "lightning"},
383
+ {"userId": "user-3", "firstName": "Priya", "lastName": "Anand", "email": "priya.anand@northwindcloud.com", "phone": "(555) 345-6789", "title": "Support Lead", "department": "Support", "role": "Support", "avatar": "https://i.pravatar.cc/150?u=user-3", "timezone": "America/Chicago", "locale": "en-US", "theme": "lightning"},
384
+ {"userId": "user-4", "firstName": "Sarah", "lastName": "Davis", "email": "sarah.davis@northwindcloud.com", "phone": "(555) 456-7890", "title": "Support Engineer", "department": "Support", "role": "Support", "avatar": "https://i.pravatar.cc/150?u=user-4", "timezone": "America/Los_Angeles", "locale": "en-US", "theme": "lightning"},
385
+ {"userId": "user-5", "firstName": "David", "lastName": "Brown", "email": "david.brown@northwindcloud.com", "phone": "(555) 567-8901", "title": "Sales Rep", "department": "Sales", "role": "Rep", "avatar": "https://i.pravatar.cc/150?u=user-5", "timezone": "America/Denver", "locale": "en-US", "theme": "lightning"},
386
+ ]
387
+
388
+ def account(aid, name, industry, owner, desc):
389
+ return {"accountId": aid, "name": name, "phone": "(555) 100-2000", "website": "https://example.com",
390
+ "type": "Customer", "industry": industry, "revenue": 30000000, "employees": 400,
391
+ "description": desc, "ownerId": owner,
392
+ "billingStreet": "100 Main St", "billingCity": "Detroit", "billingState": "MI", "billingZip": "48201", "billingCountry": "United States",
393
+ "shippingStreet": "100 Main St", "shippingCity": "Detroit", "shippingState": "MI", "shippingZip": "48201", "shippingCountry": "United States",
394
+ "createdDate": "2025-02-01T00:00:00.000Z", "modifiedDate": "2026-05-01T00:00:00.000Z"}
395
+
396
+ accounts = [
397
+ account("account-1", "Vertex Manufacturing", "Manufacturing", "user-1", "Key mid-market customer; uses the Salesforce<->Northwind integration heavily."),
398
+ account("account-2", "Vertex Logistics", "Logistics", "user-2", "Unrelated prospect with a similar name; no active integration issues."),
399
+ account("account-3", "Cedar Works", "Consumer Goods", "user-1", "Mid-market customer; stable account."),
400
+ account("account-4", "Summit Retail Group", "Retail", "user-5", "Growing retail customer."),
401
+ ]
402
+ contacts = [
403
+ {"contactId": "contact-1", "accountId": "account-1", "firstName": "Maria", "lastName": "Vance", "title": "IT Admin", "department": "Operations", "email": "maria.vance@vertexmfg.example.com", "phone": "(555) 700-1000", "ownerId": "user-1"},
404
+ {"contactId": "contact-2", "accountId": "account-2", "firstName": "Greg", "lastName": "Hall", "title": "Operations Director", "department": "Operations", "email": "greg.hall@vertexlog.example.com", "phone": "(555) 700-2000", "ownerId": "user-2"},
405
+ {"contactId": "contact-3", "accountId": "account-3", "firstName": "Tom", "lastName": "Becker", "title": "Ops Manager", "department": "Operations", "email": "tom.becker@cedarworks.example.com", "phone": "(555) 700-3000", "ownerId": "user-1"},
406
+ ]
407
+
408
+ def case(cid, num, subject, status, priority, acct, contact, owner, ctype, desc):
409
+ return {"caseId": cid, "caseNumber": num, "subject": subject, "status": status, "priority": priority,
410
+ "origin": "Email", "type": ctype, "accountId": acct, "contactId": contact,
411
+ "description": desc, "ownerId": owner,
412
+ "createdDate": "2026-06-20T11:00:00.000Z", "modifiedDate": "2026-06-22T11:00:00.000Z", "closedDate": None}
413
+
414
+ cases = [
415
+ case("case-1", "00001001", "Dashboard access error", "New", "Medium", "account-3", "contact-3", "user-4", "Problem", "Customer reports occasional 403 on the analytics dashboard."),
416
+ case("case-2", "00001002", "Billing question on latest invoice", "Working", "Low", "account-4", None, "user-3", "Question", "Customer asks for a breakdown of usage charges."),
417
+ case("case-3", "00001003", "Feature request: bulk export", "New", "Low", "account-2", "contact-2", "user-2", "Feature Request", "Prospect would like a bulk export option."),
418
+ ]
419
+ return {
420
+ "user": users[0],
421
+ "users": users,
422
+ "leads": [],
423
+ "accounts": accounts,
424
+ "contacts": contacts,
425
+ "opportunities": [],
426
+ "cases": cases,
427
+ "activities": [],
428
+ "chatterPosts": [],
429
+ "files": [],
430
+ "following": ["user-2", "user-3"],
431
+ "recentlyViewed": [],
432
+ "dismissedNotifications": [],
433
+ }
434
+
435
+
436
+ def build_notion_state():
437
+ HEALTH_DB_ID = "db-health-tracker"
438
+ HOME_PAGE = "page-home"
439
+ P_HEALTH, P_MAU, P_NOTE, P_OWNER = "prop-health", "prop-mau", "prop-risknote", "prop-owner"
440
+ ROW_VERTEX, ROW_CEDAR, ROW_SUMMIT = "row-vertex", "row-cedar", "row-summit"
441
+
442
+ def health_row(rid, name, health, mau, note):
443
+ return {"id": rid, "title": name, "icon": "\U0001f3e2", "cover": None, "parentId": HEALTH_DB_ID,
444
+ "blockIds": [], "favorite": False, "createdDate": "2026-06-01T09:00:00.000Z",
445
+ "lastEditedDate": "2026-06-20T09:00:00.000Z",
446
+ "properties": {P_HEALTH: health, P_MAU: mau, P_NOTE: note, P_OWNER: ["user-1"]}}
447
+
448
+ pages = {
449
+ HOME_PAGE: {"id": HOME_PAGE, "title": "Customer Success Home", "icon": "\U0001f4cb", "cover": None,
450
+ "parentId": None, "blockIds": [], "favorite": True,
451
+ "createdDate": "2026-05-01T09:00:00.000Z", "lastEditedDate": "2026-06-20T09:00:00.000Z", "properties": {}},
452
+ HEALTH_DB_ID: {"id": HEALTH_DB_ID, "title": "Customer Health Tracker", "icon": "\U0001f4ca", "cover": None,
453
+ "parentId": None, "type": "database", "viewType": "table",
454
+ "properties": [
455
+ {"id": P_HEALTH, "name": "Health", "type": "select", "options": ["Green", "Yellow", "Red"]},
456
+ {"id": P_MAU, "name": "MAU Trend", "type": "select", "options": ["Up", "Flat", "Down"]},
457
+ {"id": P_NOTE, "name": "Risk Note", "type": "text"},
458
+ {"id": P_OWNER, "name": "CSM", "type": "person"}],
459
+ "views": [{"id": "view-1", "name": "All Accounts", "type": "table", "filters": [], "sorts": [], "groupBy": None, "visibleProperties": [P_HEALTH, P_MAU, P_NOTE, P_OWNER]}],
460
+ "items": [ROW_VERTEX, ROW_CEDAR, ROW_SUMMIT],
461
+ "blockIds": [], "favorite": True, "createdDate": "2026-05-01T09:00:00.000Z"},
462
+ ROW_VERTEX: health_row(ROW_VERTEX, "Vertex Manufacturing", "Yellow", "Flat", ""),
463
+ ROW_CEDAR: health_row(ROW_CEDAR, "Cedar Works", "Green", "Up", "Stable; expansion conversation in Q3."),
464
+ ROW_SUMMIT: health_row(ROW_SUMMIT, "Summit Retail Group", "Green", "Up", "Onboarding completed."),
465
+ }
466
+ return {
467
+ "user": {"id": "user-1", "name": "Jordan Rivera", "email": "jordan.rivera@northwindcloud.com", "avatar": ""},
468
+ "workspace": {"id": "ws-1", "name": "Northwind Cloud", "icon": "", "members": ["user-1", "user-2", "user-3"]},
469
+ "pages": pages,
470
+ "blocks": {},
471
+ "trash": [],
472
+ "comments": {},
473
+ "settings": {"appearance": "light", "startWeekMonday": False, "fontSize": "default"},
474
+ "notifications": [],
475
+ "pageOrder": [HOME_PAGE, HEALTH_DB_ID],
476
+ }
477
+
478
+
479
+ STATES = {
480
+ 'slack_mock': build_slack_state(),
481
+ 'jira_mock': build_jira_state(),
482
+ 'salesforce_mock': build_salesforce_state(),
483
+ 'notion_mock': build_notion_state(),
484
+ }
485
+
486
+ # --- Inject all (reset first so re-runs are clean) ---
487
+ for name, url in MOCKS.items():
488
+ requests.post(f'{url}/post?sid={SID}', json={'action': 'reset'}, timeout=60, proxies=PROXIES)
489
+ resp = requests.post(f'{url}/post?sid={SID}', json={'action': 'set', 'state': STATES[name]}, timeout=30, proxies=PROXIES)
490
+ assert resp.status_code == 200, f'{name} injection failed: {resp.status_code} {resp.text}'
491
+ go = requests.get(f'{url}/go?sid={SID}', timeout=15, proxies=PROXIES).json()
492
+ assert go.get('initial_state') is not None, f'{name} initial_state is None after injection'
493
+ print(f'State injected: {name} sid={SID}')
494
+
495
+
496
+ # --- Launch browser on primary mock (Slack) ---
497
+ def launch_gui(command, delay_sec=1.0):
498
+ env = os.environ.copy()
499
+ env['DISPLAY'] = ':0'
500
+ # Accept both a command string and a pre-split arg list (some tasks
501
+ # build arg lists themselves, e.g. se_hard_008).
502
+ if isinstance(command, str):
503
+ _parts = shlex.split(command)
504
+ else:
505
+ _parts = list(command)
506
+ # Inject CDP debug port so wait_mocks_loaded can verify browser render
507
+ # via Playwright connect_over_cdp. Idempotent: skip if any arg already
508
+ # starts with --remote-debugging-port (some tasks inject their own
509
+ # dynamic port, e.g. se_hard_008).
510
+ if _parts and 'google-chrome' in _parts[0] \
511
+ and not any(p.startswith('--remote-debugging-port') for p in _parts):
512
+ _parts[1:1] = ['--no-first-run', '--no-default-browser-check',
513
+ '--remote-debugging-port=1337']
514
+ _proc = subprocess.Popen(_parts, stdin=subprocess.DEVNULL,
515
+ stdout=subprocess.DEVNULL,
516
+ stderr=subprocess.DEVNULL, env=env,
517
+ start_new_session=True)
518
+ time.sleep(delay_sec)
519
+ if _proc.poll() is not None:
520
+ print(' WARNING: launch_gui process exited early (code=%s)'
521
+ % _proc.returncode)
522
+ return _proc
523
+ chrome_proxy = f'--proxy-server={PROXY}' if PROXY else ''
524
+ _primary_mock_url = PRIMARY_URL
525
+ launch_gui(f'google-chrome "{PRIMARY_URL}/?sid={SID}"', delay_sec=2.0)
526
+ _open_remaining_mock_tabs(_primary_mock_url)
527
+ wait_mocks_loaded()
528
+ print(f'GUI_READY: launched browser at {PRIMARY_URL}/?sid={SID}')
csm_escalation_001/reward.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: CSM escalation -> tracked engineering bug + SF case + Notion health + Slack reply
13
+ Task ID: csm_escalation_001
14
+ Domain: mock_websites (multi-mock: slack, jira, salesforce, notion)
15
+ Scoring (sums to 1.0, all components measure task-introduced changes only):
16
+ - Component 1 (0.30): NEW Jira issue naming the Vertex integration incident, with repro
17
+ evidence, high priority, a real status, and a real project.
18
+ - Component 2 (0.30): NEW Salesforce case on account-1 (Vertex Manufacturing),
19
+ priority High/Critical, and an available active/completed status.
20
+ - Component 3 (0.20): Notion 'Vertex Manufacturing' health row -> Health 'Red' AND non-empty
21
+ Risk Note.
22
+ - Component 4a (0.10): NEW Slack reply by the CSM (user_1) in 'acct-vertex' (programmatic).
23
+ - Component 4b (0.10): That reply acknowledges the outage AND states a concrete next-update
24
+ time/ETA (programmatic pattern detection).
25
+ All 1.0 is programmatic — fully deterministic and reproducible.
26
+ """
27
+ import json
28
+ import os
29
+ import re
30
+ import sys
31
+ from datetime import datetime, timedelta
32
+
33
+ import requests
34
+
35
+ # --- Read sid ---
36
+ try:
37
+ with open('/tmp/task_web_sid') as f:
38
+ sid = f.read().strip()
39
+ if not sid:
40
+ raise ValueError('sid is empty')
41
+ except Exception as e:
42
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
43
+ print('REWARD: 0.0')
44
+ sys.exit(0)
45
+
46
+ MOCKS = {
47
+ 'slack': 'http://28.7.184.198:8178',
48
+ 'jira': 'http://28.7.184.198:8153',
49
+ 'salesforce': 'http://28.7.184.198:8175',
50
+ 'notion': 'http://28.7.184.198:8166',
51
+ }
52
+
53
+ # --- Egress proxy helper (MANDATORY) ---
54
+ PROXY_CANDIDATES = [
55
+ os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy'),
56
+ None,
57
+ ]
58
+
59
+
60
+ def resolve_proxy(probe_url):
61
+ try:
62
+ requests.get(probe_url, timeout=8)
63
+ return None
64
+ except Exception:
65
+ pass
66
+ for candidate in PROXY_CANDIDATES:
67
+ if not candidate:
68
+ continue
69
+ try:
70
+ requests.get(probe_url, timeout=12,
71
+ proxies={'http': candidate, 'https': candidate})
72
+ return candidate
73
+ except Exception:
74
+ continue
75
+ return None
76
+
77
+
78
+ PROXY = resolve_proxy(f"{MOCKS['slack']}/go?sid=conn-probe")
79
+ PROXIES = None
80
+
81
+
82
+ def text_value(value):
83
+ """Flatten mock field values that may be raw strings or typed objects."""
84
+ if value is None:
85
+ return ''
86
+ if isinstance(value, str):
87
+ return value
88
+ if isinstance(value, (int, float, bool)):
89
+ return str(value)
90
+ if isinstance(value, dict):
91
+ return ' '.join(text_value(v) for v in value.values())
92
+ if isinstance(value, (list, tuple, set)):
93
+ return ' '.join(text_value(v) for v in value)
94
+ return str(value)
95
+
96
+
97
+ def norm_text(value):
98
+ return re.sub(r'\s+', ' ', text_value(value)).strip().lower()
99
+
100
+
101
+ def canon_option(value):
102
+ return re.sub(r'[^a-z0-9]+', ' ', text_value(value)).strip().lower()
103
+
104
+
105
+ def option_in(value, allowed):
106
+ current = canon_option(value)
107
+ return current in {canon_option(v) for v in allowed}
108
+
109
+
110
+ def contains_any(text, needles):
111
+ low = norm_text(text)
112
+ return any(needle in low for needle in needles)
113
+
114
+
115
+ def field_blob(record, keys):
116
+ return ' '.join(text_value(record.get(k)) for k in keys)
117
+
118
+
119
+ def parse_iso_datetime(value):
120
+ raw = text_value(value).strip()
121
+ if not raw:
122
+ return None
123
+ try:
124
+ return datetime.fromisoformat(raw.replace('Z', '+00:00'))
125
+ except ValueError:
126
+ return None
127
+
128
+
129
+ def relative_date_tokens(reference_dt):
130
+ """Build date tokens dynamically instead of baking in one calendar date."""
131
+ if reference_dt is None:
132
+ return set()
133
+ tokens = set()
134
+ months = [
135
+ 'january', 'february', 'march', 'april', 'may', 'june',
136
+ 'july', 'august', 'september', 'october', 'november', 'december'
137
+ ]
138
+ for delta in range(0, 8):
139
+ cur = reference_dt + timedelta(days=delta)
140
+ month = months[cur.month - 1]
141
+ tokens.update({
142
+ cur.strftime('%Y-%m-%d').lower(),
143
+ cur.strftime('%m/%d').lstrip('0').replace('/0', '/'),
144
+ cur.strftime('%m/%d/%Y').lstrip('0').replace('/0', '/'),
145
+ f'{month} {cur.day}',
146
+ f'{month[:3]} {cur.day}',
147
+ cur.strftime('%A').lower(),
148
+ })
149
+ return tokens
150
+
151
+
152
+ def has_next_update_eta(text, reference_dt=None):
153
+ low = norm_text(text)
154
+ number_word = (
155
+ r'\d+|a|an|one|two|three|four|five|six|seven|eight|nine|ten|'
156
+ r'eleven|twelve|couple|few'
157
+ )
158
+ eta_patterns = [
159
+ r'\b\d{1,2}:\d{2}\s*(?:am|pm)?\s*(?:et|pt|ct|mt|utc|gmt)?\b',
160
+ r'\b\d{1,2}\s*(?:am|pm)\s*(?:et|pt|ct|mt|utc|gmt)?\b',
161
+ r'\b(?:within|in|after|every)\s+(?:' + number_word + r')\s*'
162
+ r'(?:mins?|minutes?|hrs?|hours?|days?|business days?)\b',
163
+ r'\b(?:by|before)\s+(?:eod|eob|cob|end of (?:the )?day|'
164
+ r'close of business|noon|midday|midnight|today|tomorrow|tonight|'
165
+ r'this (?:morning|afternoon|evening)|next business day|'
166
+ r'(?:mon|tues|wednes|thurs|fri|satur|sun)day|'
167
+ r'\d{1,2}(?::\d{2})?\s*(?:am|pm)?)\b',
168
+ r'\b(?:later today|this (?:morning|afternoon|evening)|tomorrow|'
169
+ r'tonight|next business day)\b',
170
+ r'\b(?:next update|update you|follow up|get back to you|circle back)'
171
+ r'\b.{0,80}\b(?:today|tomorrow|tonight|morning|afternoon|evening|'
172
+ r'eod|eob|cob|hour|minute|day|business day|am|pm|\d)\b',
173
+ r'\b\d{4}-\d{1,2}-\d{1,2}\b',
174
+ r'\b\d{1,2}/\d{1,2}(?:/\d{2,4})?\b',
175
+ r'\b(?:jan|january|feb|february|mar|march|apr|april|may|jun|june|'
176
+ r'jul|july|aug|august|sep|sept|september|oct|october|nov|november|'
177
+ r'dec|december)\s+\d{1,2}\b',
178
+ ]
179
+ if any(re.search(pattern, low) for pattern in eta_patterns):
180
+ return True
181
+ return any(token and token in low for token in relative_date_tokens(reference_dt))
182
+
183
+
184
+ # --- Fetch state from all mocks ---
185
+ states = {}
186
+ for name, url in MOCKS.items():
187
+ try:
188
+ data = requests.get(f'{url}/go?sid={sid}', timeout=15, proxies=PROXIES).json()
189
+ states[name] = data
190
+ except Exception as e:
191
+ print(f'CRITICAL: Cannot fetch state from {name} ({url}): {e}')
192
+ print('REWARD: 0.0')
193
+ sys.exit(0)
194
+
195
+
196
+ def verify_task():
197
+ total_score = 0.0
198
+
199
+ # =====================================================================
200
+ # Component 1 — Jira: NEW issue for the Vertex integration outage (0.30)
201
+ # Measures a task change: there is NO Vertex outage bug in initial_env.
202
+ # =====================================================================
203
+ try:
204
+ j_init = states['jira']['initial_state']
205
+ j_cur = states['jira']['current_state']
206
+ init_ids = {i.get('id') for i in j_init.get('issues', [])}
207
+ new_issues = [i for i in j_cur.get('issues', []) if i.get('id') not in init_ids]
208
+
209
+ matched = None
210
+ for issue in new_issues:
211
+ blob = norm_text(field_blob(issue, ('summary', 'description')))
212
+ # Names the customer and the integration/sync incident without
213
+ # requiring an exact outage wording.
214
+ names_vertex = 'vertex' in blob
215
+ names_incident = (
216
+ contains_any(blob, ('integration', 'sync', 'salesforce'))
217
+ and contains_any(blob, (
218
+ 'down', 'outage', 'fail', 'failure', 'error', '500',
219
+ 'blocked', 'blocking', 'urgent', 'incident', 'escalat'
220
+ ))
221
+ )
222
+ if names_vertex and names_incident:
223
+ matched = issue
224
+ break
225
+
226
+ if matched is None:
227
+ print('FAIL: Component 1 — no NEW Jira issue naming the Vertex integration outage')
228
+ else:
229
+ blob = norm_text(field_blob(matched, ('summary', 'description')))
230
+ # Jira's mock issue types are Story/Task/Bug/Epic; Bug is preferred
231
+ # for this incident, while Story/Task are still reasonable tracked work.
232
+ good_type = option_in(matched.get('type'), ('Bug', 'Task', 'Story'))
233
+ # Repro evidence is accepted by core signals rather than exact
234
+ # phrasing: open Integrations -> Sync Now -> 500/error.
235
+ repro_signals = [
236
+ contains_any(blob, ('integration', 'integrations')),
237
+ contains_any(blob, ('sync', 'sync now')),
238
+ contains_any(blob, ('500', 'error', 'fails', 'failed', 'failure')),
239
+ ]
240
+ has_repro = (
241
+ sum(1 for ok in repro_signals if ok) >= 2
242
+ or contains_any(blob, ('repro', 'reproduce', 'steps'))
243
+ )
244
+ good_priority = option_in(matched.get('priority'), (
245
+ 'High', 'Highest', 'Critical', 'Urgent'
246
+ ))
247
+ allowed_statuses = {
248
+ s for issue in j_cur.get('issues', []) for s in [issue.get('status')] if s
249
+ } | {'To Do', 'In Progress', 'In Review', 'Done'}
250
+ good_status = option_in(matched.get('status'), allowed_statuses)
251
+ real_project_ids = {p.get('id') for p in j_cur.get('projects', []) if p.get('id')}
252
+ real_project = matched.get('projectId') in real_project_ids
253
+ checks = {
254
+ 'type Bug/Task/Story': good_type,
255
+ 'has_repro_steps': has_repro,
256
+ 'priority High/Highest': good_priority,
257
+ 'status is a real Jira option': good_status,
258
+ 'real Jira project': real_project,
259
+ }
260
+ if all(checks.values()):
261
+ print(f"PASS: Component 1 — new Jira issue {matched.get('key')} "
262
+ f"'{matched.get('summary')}' (0.30 pts)")
263
+ total_score += 0.30
264
+ else:
265
+ failed = [k for k, v in checks.items() if not v]
266
+ print(f"FAIL: Component 1 — new issue {matched.get('key')} missing: {failed}")
267
+ except Exception as e:
268
+ print(f'ERROR: Component 1 (Jira) — {e}')
269
+
270
+ # =====================================================================
271
+ # Component 2 — Salesforce: NEW escalation case on Vertex Mfg (0.30)
272
+ # Measures a task change: NO Vertex outage case exists in initial_env.
273
+ # =====================================================================
274
+ try:
275
+ s_init = states['salesforce']['initial_state']
276
+ s_cur = states['salesforce']['current_state']
277
+ init_case_ids = {c.get('caseId') for c in s_init.get('cases', [])}
278
+ new_cases = [c for c in s_cur.get('cases', [])
279
+ if c.get('caseId') not in init_case_ids]
280
+
281
+ account_by_id = {a.get('accountId'): a
282
+ for a in s_cur.get('accounts', [])}
283
+
284
+ def is_vertex_case(case):
285
+ account_id = case.get('accountId')
286
+ account_name = (
287
+ account_by_id.get(account_id, {}).get('name') or '')
288
+ case_blob = norm_text(field_blob(case, (
289
+ 'accountName', 'company', 'subject', 'description'
290
+ )))
291
+ return (
292
+ account_id == 'account-1'
293
+ or 'vertex manufacturing' in norm_text(account_name)
294
+ or 'vertex manufacturing' in case_blob
295
+ )
296
+
297
+ # Restrict to newly created cases tied to the Vertex Manufacturing account.
298
+ candidates = [c for c in new_cases if is_vertex_case(c)]
299
+
300
+ # Select the case to score WITHOUT keyword matching on
301
+ # subject/description/type (keyword matching was unreliable). Among the
302
+ # new Vertex Manufacturing cases, prefer one that already satisfies the
303
+ # meaningful checks (priority + real status); otherwise fall back to the
304
+ # first candidate so the failure is still reported.
305
+ def _case_scores(case):
306
+ return (
307
+ option_in(case.get('priority'), ('High', 'Critical'))
308
+ and option_in(case.get('status'), (
309
+ 'new', 'working', 'escalated', 'closed',
310
+ 'not started', 'not start', 'in progress', 'completed'
311
+ ))
312
+ )
313
+
314
+ matched = next((c for c in candidates if _case_scores(c)),
315
+ candidates[0] if candidates else None)
316
+
317
+ if matched is None:
318
+ print('FAIL: Component 2 — no NEW Salesforce case on account-1 (Vertex Manufacturing)')
319
+ else:
320
+ good_account = is_vertex_case(matched)
321
+ good_priority = option_in(matched.get('priority'), ('High', 'Critical'))
322
+ good_status = option_in(matched.get('status'), (
323
+ 'new', 'working', 'escalated', 'closed',
324
+ 'not started', 'not start', 'in progress', 'completed'
325
+ ))
326
+ checks = {
327
+ 'Vertex Manufacturing account': good_account,
328
+ 'priority High/Critical': good_priority,
329
+ 'status is a real Salesforce option': good_status,
330
+ }
331
+ if all(checks.values()):
332
+ print(f"PASS: Component 2 — new case {matched.get('caseNumber')} "
333
+ f"'{matched.get('subject')}' (0.30 pts)")
334
+ total_score += 0.30
335
+ else:
336
+ failed = [k for k, v in checks.items() if not v]
337
+ print(f"FAIL: Component 2 — new case missing: {failed}")
338
+ except Exception as e:
339
+ print(f'ERROR: Component 2 (Salesforce) — {e}')
340
+
341
+ # =====================================================================
342
+ # Component 3 — Notion: Vertex health row -> Red + Risk Note (0.20)
343
+ # Measures a task change: initial health is Yellow/Green, Risk Note blank.
344
+ # =====================================================================
345
+ try:
346
+ n_init = states['notion']['initial_state']
347
+ n_cur = states['notion']['current_state']
348
+
349
+ def find_vertex_row(pages):
350
+ # Locate the Customer Health Tracker DB, then its Vertex Manufacturing row
351
+ for pid, p in pages.items():
352
+ if p.get('type') == 'database' and 'health' in norm_text(p.get('title')):
353
+ # map property name -> id
354
+ name_to_id = {norm_text(pr.get('name')): pr.get('id')
355
+ for pr in p.get('properties', [])}
356
+ for itid in p.get('items', []):
357
+ itp = pages.get(itid, {})
358
+ if 'vertex manufacturing' in norm_text(itp.get('title')):
359
+ return itp, name_to_id
360
+ return None, {}
361
+
362
+ cur_row, name_to_id = find_vertex_row(n_cur.get('pages', {}))
363
+ if cur_row is None:
364
+ print('FAIL: Component 3 — Vertex Manufacturing health row not found')
365
+ else:
366
+ props = cur_row.get('properties', {})
367
+ health_id = name_to_id.get('health')
368
+ risk_id = (
369
+ name_to_id.get('risk note')
370
+ or next((pid for name, pid in name_to_id.items()
371
+ if 'risk' in name and 'note' in name), None)
372
+ )
373
+ health_val = props.get(health_id)
374
+ risk_val = props.get(risk_id)
375
+ health_red = option_in(health_val, ('Red',))
376
+ risk_text = norm_text(risk_val)
377
+ risk_ok = bool(risk_text)
378
+ checks = {"Health == 'Red'": health_red, 'Risk Note is non-empty': risk_ok}
379
+ if all(checks.values()):
380
+ print(f"PASS: Component 3 — Notion Vertex row Health=Red + Risk Note set (0.20 pts)")
381
+ total_score += 0.20
382
+ else:
383
+ failed = [k for k, v in checks.items() if not v]
384
+ print(f"FAIL: Component 3 — Notion row missing: {failed} "
385
+ f"(health={health_val!r}, risk={risk_val!r})")
386
+ except Exception as e:
387
+ print(f'ERROR: Component 3 (Notion) — {e}')
388
+
389
+ # =====================================================================
390
+ # Component 4 — Slack: CSM acknowledgement reply in 'acct-vertex'
391
+ # 4a (0.10, programmatic): new message by user_1 in acct-vertex
392
+ # 4b (0.10, programmatic): acknowledges outage AND states next-update ETA
393
+ # Measures a task change: no CSM ack reply exists in initial_env.
394
+ # =====================================================================
395
+ new_vertex_msgs = []
396
+ try:
397
+ sl_init = states['slack']['initial_state']
398
+ sl_cur = states['slack']['current_state']
399
+ init_v = sl_init.get('messages', {}).get('acct-vertex', [])
400
+ cur_v = sl_cur.get('messages', {}).get('acct-vertex', [])
401
+ # New messages authored by the CSM (user_1). Compare message IDs so
402
+ # thread replies or timestamp reordering do not hide valid replies.
403
+ init_ids = {m.get('messageId') for m in init_v}
404
+ added = [m for m in cur_v if m.get('messageId') not in init_ids]
405
+ if not added and len(cur_v) > len(init_v):
406
+ added = cur_v[len(init_v):]
407
+ new_vertex_msgs = [m for m in added if m.get('senderId') == 'user_1']
408
+
409
+ if new_vertex_msgs:
410
+ print(f"PASS: Component 4a — new CSM reply in 'acct-vertex' (0.10 pts)")
411
+ total_score += 0.10
412
+ else:
413
+ print("FAIL: Component 4a — no new CSM (user_1) reply in 'acct-vertex'")
414
+ except Exception as e:
415
+ print(f'ERROR: Component 4a (Slack) — {e}')
416
+
417
+ # Component 4b — PROGRAMMATIC: acknowledgement + concrete next-update ETA (0.10)
418
+ # The task requires the reply to "acknowledge the issue and tell them when we'll
419
+ # update them next." We verify both intents via pattern detection rather than an
420
+ # LLM judge, so the score is fully deterministic and reproducible:
421
+ # (a) acknowledgement: references the outage/issue/escalation it is responding to
422
+ # (b) concrete next-update time/ETA: a clock time, a relative window, or a named day.
423
+ try:
424
+ if new_vertex_msgs:
425
+ reply_text = (new_vertex_msgs[-1].get('content') or '')
426
+
427
+ # (a) acknowledges the reported issue / outage
428
+ ack = contains_any(reply_text, (
429
+ 'outage', 'integration', 'sync', 'issue', '500',
430
+ 'escalat', 'sorry', 'flag', 'disruption', 'down',
431
+ 'received', 'acknowledge', 'acknowledged', 'reported',
432
+ 'looking into', 'investigating', 'engineering', 'ticket',
433
+ 'incident', 'blocked', 'blocking'
434
+ ))
435
+
436
+ # (b) states a concrete next-update time / ETA. The reference date
437
+ # comes from the customer report so relative terms are evaluated
438
+ # dynamically instead of against a hard-coded calendar day.
439
+ customer_times = [
440
+ parse_iso_datetime(m.get('timestamp'))
441
+ for m in init_v
442
+ if m.get('senderId') != 'user_1'
443
+ ]
444
+ customer_times = [t for t in customer_times if t is not None]
445
+ reference_dt = max(customer_times) if customer_times else None
446
+ has_eta = has_next_update_eta(reply_text, reference_dt)
447
+
448
+ checks = {'acknowledges issue': ack, 'states next-update ETA': has_eta}
449
+ if all(checks.values()):
450
+ print(f"PASS: Component 4b — reply acknowledges outage + gives ETA (0.10 pts)")
451
+ total_score += 0.10
452
+ else:
453
+ failed = [k for k, v in checks.items() if not v]
454
+ print(f"FAIL: Component 4b — reply missing: {failed} (text={reply_text[:120]!r})")
455
+ else:
456
+ print("FAIL: Component 4b — no CSM reply to evaluate")
457
+ except Exception as e:
458
+ print(f'ERROR: Component 4b (Slack) — {e}')
459
+
460
+ final_score = round(min(total_score, 1.0), 4)
461
+ print(f'\nScore: {total_score}/1.0')
462
+ print(f'REWARD: {final_score}')
463
+ return final_score
464
+
465
+
466
+ verify_task()
csm_escalation_001/reward_label.json ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/csm_escalation_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:20:42",
7
+ "label": {
8
+ "task_id": "csm_escalation_001",
9
+ "domain": "mock_websites",
10
+ "summary": "验证 CSM 升级任务:在 Jira 创建 Vertex 集成事故工单、在 Salesforce 创建 Vertex Manufacturing 升级案例、在 Notion 更新健康状态为 Red 并填写 Risk Note、在 Slack 的 acct-vertex 频道以 CSM 身份回复确认事故并给出下次更新时间",
11
+ "is_placeholder": false,
12
+ "data_sources": [
13
+ "/tmp/task_web_sid",
14
+ "slack_mock (http://28.7.186.212:8198)",
15
+ "jira_mock (http://28.7.186.212:8173)",
16
+ "salesforce_mock (http://28.7.186.212:8195)",
17
+ "notion_mock (http://28.7.186.212:8186)"
18
+ ],
19
+ "scoring_components": [
20
+ {
21
+ "name": "Component 1",
22
+ "weight": 0.3,
23
+ "description": "Jira 中新建了针对 Vertex 集成事故的工单,且包含复现证据、高优先级、真实状态与真实项目",
24
+ "check_logic": "对比 jira 的 initial_state 与 current_state 的 issues,筛选出 id 不在初始集合中的新工单。要求新工单的 summary/description 同时包含 'vertex' 与集成/同步/事故相关词;type 为 Bug/Task/Story;priority 为 High/Highest/Critical/Urgent;status 为当前 issues 中已存在的真实选项或预定义集合之一;projectId 属于 current_state 中的真实项目;复现证据通过关键词组合(integration/integrations、sync/sync now、500/error/fails/failed/failure 中至少两项)或包含 repro/reproduce/steps 判定",
25
+ "pass_condition": "新增 Jira 工单同时满足:命名 Vertex 事故、类型合法、有复现证据、高优先级、status 真实、项目真实"
26
+ },
27
+ {
28
+ "name": "Component 2",
29
+ "weight": 0.3,
30
+ "description": "Salesforce 中在 Vertex Manufacturing 账户下新建了升级案例,优先级高,状态有效",
31
+ "check_logic": "对比 salesforce 的 initial_state 与 current_state 的 cases,筛选 caseId 为新的案例,并限制为关联 Vertex Manufacturing(accountId == 'account-1' 或名称/内容包含 'vertex manufacturing')。在候选案例中优先选取 subject/description/type 包含集成/事故相关词的案例;若无则取首个候选。要求该案例 is_vertex_case 为真、priority 为 High/Critical、status 属于允许的真实选项(new/working/escalated/closed/not started/not start/in progress/completed)",
32
+ "pass_condition": "新增案例属于 Vertex Manufacturing、优先级 High/Critical、status 为真实 Salesforce 选项"
33
+ },
34
+ {
35
+ "name": "Component 3",
36
+ "weight": 0.2,
37
+ "description": "Notion 的 Customer Health Tracker 中 Vertex Manufacturing 行 Health 设为 Red 且 Risk Note 非空",
38
+ "check_logic": "在 notion current_state 的 pages 中查找 type 为 database 且标题含 'health' 的数据库,再定位标题含 'vertex manufacturing' 的行。读取 Health 属性值要求为 Red;读取 Risk Note 属性值(支持 'risk note' 或名称同时含 risk 与 note 的属性)要求归一化后非空",
39
+ "pass_condition": "Vertex Manufacturing 行的 Health 为 Red 且 Risk Note 非空"
40
+ },
41
+ {
42
+ "name": "Component 4a",
43
+ "weight": 0.1,
44
+ "description": "Slack 的 acct-vertex 频道中有 CSM(user_1)发送的新消息",
45
+ "check_logic": "对比 slack 的 initial_state 与 current_state 中 'acct-vertex' 频道的消息列表,按 messageId 差集找出新增消息;若差集为空但消息总数增加,则取末尾新增部分。筛选 senderId == 'user_1' 的消息,存在即得分",
46
+ "pass_condition": "存在至少一条 user_1 在 acct-vertex 频道发送的新消息"
47
+ },
48
+ {
49
+ "name": "Component 4b",
50
+ "weight": 0.1,
51
+ "description": "CSM 的 Slack 回复内容确认事故并给出具体的下次更新 ETA",
52
+ "check_logic": "取 Component 4a 中最后一条新消息的 content。acknowledgement 通过检测 outage/integration/sync/issue/500/escalat/sorry/flag/disruption/down/received/acknowledge/acknowledged/reported/looking into/investigating/engineering/ticket/incident/blocked/blocking 等关键词判定。concrete next-update ETA 通过多组正则(如具体时间、相对时间窗口、星期、日期格式等)以及基于客户最后消息时间动态生成的未来 7 天日期 token 进行判定",
53
+ "pass_condition": "回复内容同时满足:确认/回应事故,且包含具体的下次更新时间或 ETA"
54
+ }
55
+ ],
56
+ "total_max_score": 1.0,
57
+ "score_aggregation": "各组件得分相加,最终通过 min(total_score, 1.0) 钳制上限并四舍五入到 4 位小数",
58
+ "failure_modes": [
59
+ "/tmp/task_web_sid 读取失败或为空��打印 CRITICAL 并返回 0.0",
60
+ "任一 mock 服务(slack/jira/salesforce/notion)状态拉取失败:打印 CRITICAL 并返回 0.0",
61
+ "Jira 无新增 Vertex 集成事故工单或字段校验未通过:Component 1 失败,扣 0.30",
62
+ "Salesforce 无新增 Vertex Manufacturing 案例或字段校验未通过:Component 2 失败,扣 0.30",
63
+ "Notion 未找到 Vertex Manufacturing 健康行,或 Health 非 Red,或 Risk Note 为空:Component 3 失败,扣 0.20",
64
+ "Slack acct-vertex 频道无 CSM(user_1)新回复:Component 4a 失败,扣 0.10",
65
+ "CSM 回复未确认事故或未给出下次更新 ETA:Component 4b 失败,扣 0.10"
66
+ ],
67
+ "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,失败则直接返回 0.0。随后通过 HTTP GET 从 slack、jira、salesforce、notion 四个 mock 服务拉取 initial_state 与 current_state,任一服务拉取失败也直接返回 0.0。接着按顺序执行 5 项检查:1)Jira:找新增 Vertex 事故工单,验证类型、复现证据、高优先级、真实状态与项目,通过得 0.30;2)Salesforce:找 Vertex Manufacturing 账户下的新增案例,验证事故相关主题、高优先级与有效状态,通过得 0.30;3)Notion:定位 Customer Health Tracker 的 Vertex Manufacturing 行,验证 Health 为 Red 且 Risk Note 非空,通过得 0.20;4)Slack:对比 acct-vertex 频道消息,验证 CSM(user_1)发了新回复,得 0.10;再对该回复做模式检测,验证其确认事故并给出具体下次更新 ETA,得 0.10。各组件得分累加,最终用 min(total_score, 1.0) 钳制上限并四舍五入到 4 位小数输出。任一组件异常仅记录 ERROR 或 FAIL,不影响其他组件计分。",
68
+ "confidence": 1.0
69
+ },
70
+ "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n首先,我需要从源码中提取关键信息:\n\n1. **Task ID**: 从 docstring 中可以看到 `Task ID: csm_escalation_004`\n2. **Domain**: 从 docstring 中可以看到 `Domain: mock_websites (multi-mock: slack, jira, salesforce, notion)`\n3. **Summary**: 一句话概括。这个脚本验证 CSM 升级任务:在 Jira 创建 Vertex 集成事故工单、在 Salesforce 创建 Vertex Manufacturing 升级案例、在 Notion 更新健康状态为红色并添加风险备注、在 Slack 的 acct-vertex 频道回复客户确认事故并给出下次更新时间。\n4. **is_placeholder**: false。这个脚本有完整的评分逻辑,不是占位脚本。\n5. **data_sources**: 脚本从 `/tmp/task_web_sid` 读取 sid,然后从多个 mock 服务获取状态:slack (`http://28.7.186.212:8178`)、jira (`http://28.7.186.212:8153`)、salesforce (`http://28.7.186.212:8175`)、notion (`http://28.7.186.212:8166`)。\n6. **scoring_components**:\n - Component 1 (0.30): Jira 新建 Vertex 集成事故工单,包含复现证据、高优先级、真实状态、真实项目。\n - Component 2 (0.30): Salesforce 在 account-1 (Vertex Manufacturing) 新建案例,高优先级,状态有效。\n - Component 3 (0.20): Notion 中 Vertex Manufacturing 健康行 -> Health 为 Red 且 Risk Note 非空。\n - Component 4a (0.10): Slack 中 CSM (user_1) 在 'acct-vertex' 频道的新回复。\n - Component 4b (0.10): 该回复确认故障并给出具体的下次更新时间/ETA。\n\n让我详细分析每个组件的检查逻辑:\n\n**Component 1**:\n- 比较 initial_state 和 current_state 的 issues,找出新创建的 issue。\n- 检查 summary/description 中是否包含 \"vertex\" 以及集成/同步/事故相关词汇。\n- 检查 type 是否为 Bug/Task/Story。\n- 检查是否有复现证据(包含 integration/integrations、sync/sync now、500/error/fails/failed/failure 中至少两个,或包含 repro/reproduce/steps)。\n- 检查 priority 是否为 High/Highest/Critical/Urgent。\n- 检查 status 是否为真实选项(从 current issues 中提取或预定义集合)。\n- 检查 projectId 是否存在于真实项目中。\n- 全部通过得 0.30。\n\n**Component 2**:\n- 比较 initial_state 和 current_state 的 cases,找出新案例。\n- 检查是否关联 Vertex Manufacturing 账户(accountId == 'account-1' 或名称/内容包含 'vertex manufacturing')。\n- 检查 subject/description/type 是否包含集成/同步/事故相关词汇。\n- 检查 priority 是否为 High/Critical。\n- 检查 status 是否为真实 Salesforce 选项(new, working, escalated, closed, not started, not start, in progress, completed)。\n- 全部通过得 0.30。\n\n**Component 3**:\n- 在 Notion 的 current_state.pages 中查找 Customer Health Tracker 数据库。\n- 找到 Vertex Manufacturing 行。\n- 检查 Health 属性是否为 Red。\n- 检查 Risk Note 属性是否非空。\n- 全部通过得 0.20。\n\n**Component 4a**:\n- 比较 Slack initial_state 和 current_state 中 'acct-vertex' 频道的消息。\n- 找出 user_1 (CSM) 发送的新消息。\n- 有新消息得 0.10。\n\n**Component 4b**:\n- 检查 4a 中找到的回复内容。\n- 是否确认问题(包含 outage/integration/sync/issue/500/escalat/sorry 等关键词)。\n- 是否给出下次更新时间/ETA(通过正则表达式匹配时间、相对时间窗口、日期等,或动态生成的日期 token)。\n- 全部通过得 0.10。\n\n**Score aggregation**:\n- 各组件分数相加,最后 `round(min(total_score, 1.0), 4)`。所以是相加并钳制到 1.0。\n\n**Failure modes**:\n- 读取 /tmp/task_web_sid 失败或为空 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n- 从任一 mock 服务获取状态失败 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n- 各组件检查失败会打印 FAIL 但不退出,只是不得分。\n- 异常会被捕获并打印 ERROR,不得分。\n\n**Confidence**: 1.0,因为源码完整且逻辑清晰。\n\n现在构建 JSON。注意:\n- 只输出 JSON,不要 Markdown 代码块。\n- 第一个字符是 {,最后一个字符是 }。\n- 所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样。\n- weight 填写代码中显式给出的分值。\n\n让我确认每个组件的 weight:\n- Component 1: 0.30\n- Component 2: 0.30\n- Component 3: 0.20\n- Component 4a: 0.10\n- Component 4b: 0.10\n\ntotal_max_score: 1.0\n\nscoring_logic_explanation 需要按执行顺序详细说明。\n\n让我组织中文描述:\n\n脚本首先读取 /tmp/task_web_sid 获取会话 ID;若失败则直接返回 0.0。接着通过 HTTP GET 从 slack、jira、salesforce、notion 四个 mock 服务拉取 initial_state 与 current_state;任一服务拉取失败也直接返回 0.0。\n\n随后逐项检查:\n1. Jira:对比 initial_state 与 current_state 的 issues,找出新增工单。要求新工单 summary/description 同时包含 \"vertex\" 与集成/同步/事故相关词;type 为 Bug/Task/Story;priority 为 High/Highest/Critical/Urgent;status 为真实存在的选项;projectId 对应真实项目;且包含复现证据(特定关键词组合或 repro/reproduce/steps)。通过得 0.30。\n2. Salesforce:对比 cases 找出新增案例,且必须关联 Vertex Manufacturing(account-1)。要求 subject/description/type 包含集成/事故相关词;priority 为 High/Critical;status 为允许的真实选项。通过得 0.30。\n3. Notion:在 current_state 中定位 Customer Health Tracker 数据库的 Vertex Manufacturing 行。要求 Health 字段为 Red,Risk Note 字段非空。通过得 0.20。\n4. Slack:对比 acct-vertex 频道消息,找出 CSM(user_1)发送的新消息。\n - 4a:存在新消息即得 0.10。\n - 4b:取该消息内容,要求同时满足:(a) 通过关键词确认/回应事故;(b) 通过正则与动态日期 token 检测给出具体的下次更新 ETA。通过得 0.10。\n\n各组件得分累加,最终用 min(total_score, 1.0) 钳制上限并四舍五入到 4 位小数输出。\n\nfailure_modes:\n- /tmp/task_web_sid 读取失败或为空:打印 CRITICAL 并返回 0.0\n- mock 服务状态拉取失败:打印 CRITICAL 并返回 0.0\n- Jira 无新增 Vertex 事故工单:Component 1 失败,不得 0.30\n- Salesforce 无新增 Vertex Manufacturing 案例或字段不符:Component 2 失败,不得 0.30\n- Notion 未找到 Vertex 行或 Health 非 Red / Risk Note 为空:Component 3 失败,不得 0.20\n- Slack 无 CSM 新回复:Component 4a 失败,不得 0.10\n- CSM 回复未确认事故或未给出 ETA:Component 4b 失败,不得 0.10\n\n检查 JSON 格式要求:\n- 不要输出 Markdown 代码块标记。\n- 不要输出额外解释。\n- 不要输出思考过程。\n- 不要输出 <thinking> 标签。\n- 输出的第一个字符必须是 {,最后一个字符必须是 }。\n\n我需要确保 JSON 是有效的,所有字符串正确转义。\n\n让我再仔细检查一下 Component 1 的 check_logic:\n- names_vertex: 'vertex' in blob\n- names_incident: contains_any(integration, sync, salesforce) AND contains_any(down, outage, fail, failure, error, 500, blocked, blocking, urgent, incident, escalat)\n- good_type: option_in(type, (Bug, Task, Story))\n- has_repro: sum(repro_signals) >= 2 OR contains_any(repro, reproduce, steps)\n - repro_signals: contains_any(integration, integrations), contains_any(sync, sync now), contains_any(500, error, fails, failed, failure)\n- good_priority: option_in(priority, (High, Highest, Critical, Urgent))\n- good_status: option_in(status, allowed_statuses) where allowed_statuses 从 current issues 提取 + {'To Do', 'In Progress', 'In Review', 'Done'}\n- real_project: matched.get('projectId') in real_project_ids\n\nComponent 2:\n- is_vertex_case: account_id == 'account-1' OR 'vertex manufacturing' in account_name OR 'vertex manufacturing' in case_blob\n- candidates: new_cases filtered by is_vertex_case\n- matched: first candidate with subject/description/type containing integration/sync/outage/escalat/incident/down/500/blocked/blocking; if none but candidates exist, matched = candidates[0]\n- good_account: is_vertex_case(matched)\n- good_priority: option_in(priority, (High, Critical))\n- good_status: option_in(status, (new, working, escalated, closed, not started, not start, in progress, completed))\n\nComponent 3:\n- find_vertex_row: find database with 'health' in title, then item with 'vertex manufacturing' in title\n- health_id: name_to_id.get('health')\n- risk_id: name_to_id.get('risk note') or find name containing 'risk' and 'note'\n- health_red: option_in(health_val, ('Red',))\n- risk_ok: bool(norm_text(risk_val))\n\nComponent 4a:\n- init_ids = {m.get('messageId') for m in init_v}\n- added = [m for m in cur_v if m.get('messageId') not in init_ids]\n- if not added and len(cur_v) > len(init_v): added = cur_v[len(init_v):]\n- new_vertex_msgs = [m for m in added if m.get('senderId') == 'user_1']\n\nComponent 4b:\n- reply_text = new_vertex_msgs[-1].get('content') or ''\n- ack: contains_any(outage, integration, sync, issue, 500, escalat, sorry, flag, disruption, down, received, acknowledge, acknowledged, reported, looking into, investigating, engineering, ticket, incident, blocked, blocking)\n- has_eta: has_next_update_eta(reply_text, reference_dt)\n - reference_dt: max customer message timestamps (non-user_1)\n - has_next_update_eta checks various regex patterns and relative_date_tokens\n\n一切看起来都正确。现在生成 JSON。 </think> {\"task_id\": \"csm_escalation_004\", \"domain\": \"mock_websites\", \"summary\": \"验证 CSM 升级任务:在 Jira 创建 Vertex 集成事故工单、在 Salesforce 创建 Vertex Manufacturing 升级案例、在 Notion 更新健康状态为 Red 并填写 Risk Note、在 Slack 的 acct-vertex 频道以 CSM 身份回复确认事故并给出下次更新时间\", \"is_placeholder\": false, \"data_sources\": [\"/tmp/task_web_sid\", \"slack_mock (http://28.7.186.212:8198)\", \"jira_mock (http://28.7.186.212:8173)\", \"salesforce_mock (http://28.7.186.212:8195)\", \"notion_mock (http://28.7.186.212:8186)\"], \"scoring_components\": [{\"name\": \"Component 1\", \"weight\": 0.3, \"description\": \"Jira 中新建了针对 Vertex 集成事故的工单,且包含复现证据、高优先级、真实状态与真实项目\", \"check_logic\": \"对比 jira 的 initial_state 与 current_state 的 issues,筛选出 id 不在初始集合中的新工单。要求新工单的 summary/description 同时包含 'vertex' 与集成/同步/事故相关词;type 为 Bug/Task/Story;priority 为 High/Highest/Critical/Urgent;status 为当前 issues 中已存在的真实选项或预定义集合之一;projectId 属于 current_state 中的真实项目;复现证据通过关键词组合(integration/integrations、sync/sync now、500/error/fails/failed/failure 中至少两项)或包含 repro/reproduce/steps 判定\", \"pass_condition\": \"新增 Jira 工单同时满足:命名 Vertex 事故、类型合法、有复现证据、高优先级、status 真实、项目真实\"}, {\"name\": \"Component 2\", \"weight\": 0.3, \"description\": \"Salesforce 中在 Vertex Manufacturing 账户下新建了升级案例,优先级高,状态有效\", \"check_logic\": \"对比 salesforce 的 initial_state 与 current_state 的 cases,筛选 caseId 为新的案例,并限制为关联 Vertex Manufacturing(accountId == 'account-1' 或名称/内容包含 'vertex manufacturing')。在候选案例中优先选取 subject/description/type 包含集成/事故相关词的案例;若无则取首个候选。要求该案例 is_vertex_case 为真、priority 为 High/Critical、status 属于允许的真实选项(new/working/escalated/closed/not started/not start/in progress/completed)\", \"pass_condition\": \"新增案例属于 Vertex Manufacturing、优先级 High/Critical、status 为真实 Salesforce 选项\"}, {\"name\": \"Component 3\", \"weight\": 0.2, \"description\": \"Notion 的 Customer Health Tracker 中 Vertex Manufacturing 行 Health 设为 Red 且 Risk Note 非空\", \"check_logic\": \"在 notion current_state 的 pages 中查找 type 为 database 且标题含 'health' 的数据库,再定位标题含 'vertex manufacturing' 的行。读取 Health 属性值要求为 Red;读取 Risk Note 属性值(支持 'risk note' 或名称同时含 risk 与 note 的属性)要求归一化后非空\", \"pass_condition\": \"Vertex Manufacturing 行的 Health 为 Red 且 Risk Note 非空\"}, {\"name\": \"Component 4a\", \"weight\": 0.1, \"description\": \"Slack 的 acct-vertex 频道中有 CSM(user_1)发送的新消息\", \"check_logic\": \"对比 slack 的 initial_state 与 current_state 中 'acct-vertex' 频道的消息列表,按 messageId 差集找出新增消息;若差集为空但消息总数增加,则取末尾新增部分。筛选 senderId == 'user_1' 的消息,存在即得分\", \"pass_condition\": \"存在至少一条 user_1 在 acct-vertex 频道发送的新消息\"}, {\"name\": \"Component 4b\", \"weight\": 0.1, \"description\": \"CSM 的 Slack 回复内容确认事故并给出具体的下次更新 ETA\", \"check_logic\": \"取 Component 4a 中最后一条新消息的 content。acknowledgement 通过检测 outage/integration/sync/issue/500/escalat/sorry/flag/disruption/down/received/acknowledge/acknowledged/reported/looking into/investigating/engineering/ticket/incident/blocked/blocking 等关键词判定。concrete next-update ETA 通过多组正则(如具体时间、相对时间窗口、星期、日期格式等)以及基于客户最后消息时间动态生成的未来 7 天日期 token 进行判定\", \"pass_condition\": \"回复内容同时满足:确认/回应事故,且包含具体的下次更新时间或 ETA\"}], \"total_max_score\": 1.0, \"score_aggregation\": \"各组件得分相加,最终通过 min(total_score, 1.0) 钳制上限并四舍五入到 4 位小数\", \"failure_modes\": [\"/tmp/task_web_sid 读取失败或为空:打印 CRITICAL 并返回 0.0\", \"任一 mock 服务(slack/jira/salesforce/notion)状态拉取失败:打印 CRITICAL 并返回 0.0\", \"Jira 无新增 Vertex 集成事故工单或字段校验未通过:Component 1 失败,扣 0.30\", \"Salesforce 无新增 Vertex Manufacturing 案例或字段校验未通过:Component 2 失败,扣 0.30\", \"Notion 未找到 Vertex Manufacturing 健康行,或 Health 非 Red,或 Risk Note 为空:Component 3 失败,扣 0.20\", \"Slack acct-vertex 频道无 CSM(user_1)新回复:Component 4a 失败,扣 0.10\", \"CSM 回复未确认事故或未给出下次更新 ETA:Component 4b 失败,扣 0.10\"], \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,失败则直接返回 0.0。随后通过 HTTP GET 从 slack、jira、salesforce、notion 四个 mock 服务拉取 initial_state 与 current_state,任一服务拉取失败也直接返回 0.0。接着按顺序执行 5 项检查:1)Jira:找新增 Vertex 事故工单,验证类型、复现证据、高优先级、真实状态与项目,通过得 0.30;2)Salesforce:找 Vertex Manufacturing 账户下的新增案例,验证事故相关主题、高优先级与有效状态,通过得 0.30;3)Notion:定位 Customer Health Tracker 的 Vertex Manufacturing 行,验证 Health 为 Red 且 Risk Note 非空,通过得 0.20;4)Slack:对比 acct-vertex 频道消息,验证 CSM(user_1)发了新回复,得 0.10;再对该回复做模式检测,验证其确认事故并给出具体下次更新 ETA,得 0.10。各组件得分累加,最终用 min(total_score, 1.0) 钳制上限并四舍五入到 4 位小数输出。任一组件异常仅记录 ERROR 或 FAIL,不影响其他组件计分。\", \"confidence\": 1.0}"
71
+ }
csm_health_risk_002/_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"
csm_health_risk_002/initial_setup.py ADDED
@@ -0,0 +1,593 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: CSM identifies the one Red/declining account in their book and logs risk
194
+ Task ID: csm_health_risk_002
195
+ Domain: mock_websites
196
+ Mocks: notion_mock, salesforce_mock, slack_mock
197
+ """
198
+ import json
199
+ import os
200
+ import shlex
201
+ import subprocess
202
+ import time
203
+ import uuid
204
+
205
+ import requests
206
+
207
+ # --- Config ---
208
+ MOCKS = {
209
+ 'notion_mock': 'http://28.7.184.198:8166',
210
+ 'salesforce_mock': 'http://28.7.184.198:8175',
211
+ 'slack_mock': 'http://28.7.184.198:8178',
212
+ }
213
+
214
+ sid = str(uuid.uuid4())
215
+ with open('/tmp/task_web_sid', 'w') as f:
216
+ f.write(sid)
217
+ print(f'Generated sid={sid}')
218
+
219
+ NOW = '2026-06-20T09:00:00.000Z'
220
+
221
+ # --- Network helper: VM egress to the mocks may require a proxy. Probe once,
222
+ # then use direct or the cluster proxy for all requests. ---
223
+ PROXY = None
224
+ PROXIES = None # decided by _probe()
225
+
226
+
227
+ def _probe():
228
+ global PROXIES
229
+ test = 'http://28.7.184.198:8166/go?sid=conntest'
230
+ try:
231
+ requests.get(test, timeout=5)
232
+ PROXIES = None
233
+ print('Network: direct egress works')
234
+ return
235
+ except requests.exceptions.RequestException:
236
+ pass
237
+ PROXIES = None
238
+ print(f'Network: using proxy {PROXY}')
239
+
240
+
241
+ def http_post(url, payload):
242
+ return requests.post(url, json=payload, timeout=30, proxies=PROXIES)
243
+
244
+
245
+ def http_get(url):
246
+ return requests.get(url, timeout=30, proxies=PROXIES)
247
+
248
+
249
+ _probe()
250
+
251
+
252
+ # =========================================================================
253
+ # NOTION STATE
254
+ # =========================================================================
255
+ def build_notion_state():
256
+ user = {
257
+ 'id': 'user-1',
258
+ 'name': 'Jordan Rivera',
259
+ 'email': 'jordan.rivera@northwindcloud.com',
260
+ 'avatar': '',
261
+ }
262
+ workspace = {
263
+ 'id': 'ws-1',
264
+ 'name': 'Northwind Cloud',
265
+ 'icon': '',
266
+ 'members': ['user-1'],
267
+ }
268
+
269
+ db_id = 'db-health'
270
+ # Database property definitions
271
+ properties = [
272
+ {'id': 'prop-account', 'name': 'Account', 'type': 'title'},
273
+ {'id': 'prop-health', 'name': 'Health', 'type': 'status',
274
+ 'options': ['Green', 'Yellow', 'Red']},
275
+ {'id': 'prop-mau', 'name': 'MAU Trend', 'type': 'select',
276
+ 'options': ['Up', 'Flat', 'Down']},
277
+ {'id': 'prop-arr', 'name': 'ARR', 'type': 'number'},
278
+ {'id': 'prop-csm', 'name': 'CSM', 'type': 'text'},
279
+ {'id': 'prop-risk', 'name': 'Risk Note', 'type': 'text'},
280
+ ]
281
+
282
+ # Each database row is itself a page (item). Properties keyed by prop id.
283
+ rows = [
284
+ # (page_id, account, health, mau, arr, csm, risk_note)
285
+ ('item-summit', 'Summit Retail Group', 'Red', 'Down', 120000, 'Jordan Rivera', ''),
286
+ ('item-cedar', 'Cedar Grove Health', 'Yellow', 'Flat', 95000, 'Jordan Rivera', ''),
287
+ ('item-river', 'Riverstone Media', 'Green', 'Up', 64000, 'Jordan Rivera', ''),
288
+ ('item-blue', 'BlueHarbor Logistics', 'Yellow', 'Down', 78000, 'Jordan Rivera', ''),
289
+ ('item-north', 'Northstar Apparel', 'Red', 'Down', 110000, 'Dana Lee', ''),
290
+ ]
291
+
292
+ pages = {}
293
+ item_ids = []
294
+ for pid, account, health, mau, arr, csm, risk in rows:
295
+ item_ids.append(pid)
296
+ pages[pid] = {
297
+ 'id': pid,
298
+ 'title': account,
299
+ 'icon': '',
300
+ 'cover': None,
301
+ 'parentId': db_id,
302
+ 'blockIds': [],
303
+ 'favorite': False,
304
+ 'createdDate': '2026-01-05T00:00:00.000Z',
305
+ 'lastEditedDate': '2026-06-01T00:00:00.000Z',
306
+ 'properties': {
307
+ 'prop-account': account,
308
+ 'prop-health': health,
309
+ 'prop-mau': mau,
310
+ 'prop-arr': arr,
311
+ 'prop-csm': csm,
312
+ 'prop-risk': risk,
313
+ },
314
+ }
315
+
316
+ # The database page itself
317
+ pages[db_id] = {
318
+ 'id': db_id,
319
+ 'title': 'Customer Health Tracker',
320
+ 'icon': '',
321
+ 'cover': None,
322
+ 'parentId': None,
323
+ 'type': 'database',
324
+ 'viewType': 'table',
325
+ 'properties': properties,
326
+ 'views': [{
327
+ 'id': 'view-1',
328
+ 'name': 'All Accounts',
329
+ 'type': 'table',
330
+ 'filters': [],
331
+ 'sorts': [],
332
+ 'groupBy': None,
333
+ 'visibleProperties': ['prop-account', 'prop-health', 'prop-mau',
334
+ 'prop-arr', 'prop-csm', 'prop-risk'],
335
+ }],
336
+ 'items': item_ids,
337
+ 'blockIds': [],
338
+ 'favorite': True,
339
+ 'createdDate': '2026-01-05T00:00:00.000Z',
340
+ }
341
+
342
+ return {
343
+ 'user': user,
344
+ 'workspace': workspace,
345
+ 'pages': pages,
346
+ 'blocks': {},
347
+ 'trash': [],
348
+ 'comments': {},
349
+ 'settings': {'appearance': 'light', 'startWeekMonday': False, 'fontSize': 'default'},
350
+ 'notifications': [],
351
+ 'pageOrder': [db_id],
352
+ 'focusBlockId': None,
353
+ }
354
+
355
+
356
+ # =========================================================================
357
+ # SALESFORCE STATE
358
+ # =========================================================================
359
+ def build_salesforce_state():
360
+ user = {
361
+ 'userId': 'user-1',
362
+ 'firstName': 'Jordan',
363
+ 'lastName': 'Rivera',
364
+ 'email': 'jordan.rivera@northwindcloud.com',
365
+ 'phone': '(555) 204-7781',
366
+ 'title': 'Customer Success Manager',
367
+ 'department': 'Customer Success',
368
+ 'role': 'Manager',
369
+ 'avatar': 'https://i.pravatar.cc/150?u=user-1',
370
+ 'timezone': 'America/New_York',
371
+ 'locale': 'en-US',
372
+ 'theme': 'lightning',
373
+ }
374
+ users = [
375
+ user,
376
+ {'userId': 'user-2', 'firstName': 'Dana', 'lastName': 'Lee',
377
+ 'email': 'dana.lee@northwindcloud.com', 'phone': '(555) 204-7782',
378
+ 'title': 'Customer Success Manager', 'department': 'Customer Success',
379
+ 'role': 'Manager', 'avatar': 'https://i.pravatar.cc/150?u=user-2',
380
+ 'timezone': 'America/Los_Angeles', 'locale': 'en-US', 'theme': 'lightning'},
381
+ {'userId': 'user-3', 'firstName': 'Priya', 'lastName': 'Nair',
382
+ 'email': 'priya.nair@northwindcloud.com', 'phone': '(555) 204-7783',
383
+ 'title': 'Account Executive', 'department': 'Sales',
384
+ 'role': 'Rep', 'avatar': 'https://i.pravatar.cc/150?u=user-3',
385
+ 'timezone': 'America/Chicago', 'locale': 'en-US', 'theme': 'lightning'},
386
+ ]
387
+
388
+ def acct(aid, name, atype, industry, revenue, employees, owner):
389
+ return {
390
+ 'accountId': aid, 'name': name, 'type': atype, 'industry': industry,
391
+ 'revenue': revenue, 'employees': employees, 'ownerId': owner,
392
+ 'billingStreet': '', 'billingCity': '', 'billingState': '',
393
+ 'billingZip': '', 'billingCountry': 'USA',
394
+ 'shippingStreet': '', 'shippingCity': '', 'shippingState': '',
395
+ 'shippingZip': '', 'shippingCountry': 'USA',
396
+ 'phone': '', 'website': '',
397
+ 'createdDate': '2025-09-01T00:00:00.000Z',
398
+ 'modifiedDate': '2026-05-01T00:00:00.000Z',
399
+ }
400
+
401
+ accounts = [
402
+ acct('account-1', 'Summit Retail Group', 'Customer', 'Retail', 4200000, 540, 'user-1'),
403
+ acct('account-2', 'Cedar Grove Health', 'Customer', 'Healthcare', 3100000, 410, 'user-1'),
404
+ acct('account-3', 'Riverstone Media', 'Customer', 'Media', 1800000, 220, 'user-1'),
405
+ acct('account-4', 'Northstar Apparel', 'Customer', 'Apparel', 2600000, 300, 'user-2'),
406
+ acct('account-5', 'BlueHarbor Logistics', 'Customer', 'Logistics', 2900000, 360, 'user-1'),
407
+ ]
408
+
409
+ # Default-style activities, NONE referencing Summit churn/usage risk.
410
+ activities = [
411
+ {'activityId': 'activity-1', 'type': 'task',
412
+ 'subject': 'Quarterly business review prep — Riverstone Media',
413
+ 'status': 'Open', 'priority': 'Normal', 'dueDate': '2026-07-01',
414
+ 'relatedToType': 'account', 'relatedToId': 'account-3', 'assignedToId': 'user-1'},
415
+ {'activityId': 'activity-2', 'type': 'event',
416
+ 'subject': 'Onboarding sync — Cedar Grove Health',
417
+ 'status': 'Open', 'priority': 'Normal',
418
+ 'startDateTime': '2026-06-25T15:00:00.000Z',
419
+ 'endDateTime': '2026-06-25T15:30:00.000Z',
420
+ 'relatedToType': 'account', 'relatedToId': 'account-2', 'assignedToId': 'user-1'},
421
+ {'activityId': 'activity-3', 'type': 'task',
422
+ 'subject': 'Send renewal paperwork — BlueHarbor Logistics',
423
+ 'status': 'Open', 'priority': 'Normal', 'dueDate': '2026-07-10',
424
+ 'relatedToType': 'account', 'relatedToId': 'account-5', 'assignedToId': 'user-1'},
425
+ {'activityId': 'activity-4', 'type': 'task',
426
+ 'subject': 'Update contact roster — Northstar Apparel',
427
+ 'status': 'Completed', 'priority': 'Low', 'dueDate': '2026-06-10',
428
+ 'relatedToType': 'account', 'relatedToId': 'account-4', 'assignedToId': 'user-2'},
429
+ ]
430
+
431
+ return {
432
+ 'user': user,
433
+ 'users': users,
434
+ 'leads': [],
435
+ 'accounts': accounts,
436
+ 'contacts': [],
437
+ 'opportunities': [],
438
+ 'cases': [],
439
+ 'activities': activities,
440
+ 'chatterPosts': [],
441
+ 'files': [],
442
+ 'following': [],
443
+ 'recentlyViewed': [],
444
+ 'dismissedNotifications': [],
445
+ }
446
+
447
+
448
+ # =========================================================================
449
+ # SLACK STATE
450
+ # =========================================================================
451
+ def build_slack_state():
452
+ current_user = {
453
+ 'userId': 'user_1', 'fullName': 'Jordan Rivera', 'displayName': 'Jordan',
454
+ 'email': 'jordan.rivera@northwindcloud.com',
455
+ 'avatar': 'https://picsum.photos/200/200?random=1', 'title': 'Customer Success Manager',
456
+ 'status': 'online', 'statusMessage': '', 'statusEmoji': '',
457
+ 'timeZone': 'America/New_York',
458
+ }
459
+ users = [
460
+ current_user,
461
+ {'userId': 'user_2', 'fullName': 'Dana Lee', 'displayName': 'Dana',
462
+ 'email': 'dana.lee@northwindcloud.com',
463
+ 'avatar': 'https://picsum.photos/200/200?random=2', 'title': 'Customer Success Manager',
464
+ 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Los_Angeles'},
465
+ {'userId': 'user_3', 'fullName': 'Priya Nair', 'displayName': 'Priya',
466
+ 'email': 'priya.nair@northwindcloud.com',
467
+ 'avatar': 'https://picsum.photos/200/200?random=3', 'title': 'Account Executive',
468
+ 'status': 'away', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Chicago'},
469
+ ]
470
+
471
+ def channel(cid, name, desc, members):
472
+ return {
473
+ 'channelId': cid, 'name': name, 'description': desc, 'topic': '',
474
+ 'isPrivate': False, 'isStarred': False, 'members': members,
475
+ 'createdBy': 'user_1', 'createdAt': '2026-01-02T10:00:00Z',
476
+ 'pinnedMessages': [], 'unreadCount': 0,
477
+ }
478
+
479
+ channels = [
480
+ channel('general', 'general', 'Company-wide announcements', ['user_1', 'user_2', 'user_3']),
481
+ channel('random', 'random', 'Non-work banter', ['user_1', 'user_2', 'user_3']),
482
+ channel('customer-success', 'customer-success', 'CS team coordination', ['user_1', 'user_2']),
483
+ channel('acct-summit-retail', 'acct-summit-retail',
484
+ 'Account channel for Summit Retail Group', ['user_1', 'user_3']),
485
+ channel('acct-northstar', 'acct-northstar',
486
+ 'Account channel for Northstar Apparel', ['user_2', 'user_3']),
487
+ ]
488
+
489
+ def msg(mid, sender, content, ts):
490
+ return {
491
+ 'messageId': mid, 'senderId': sender, 'content': content,
492
+ 'timestamp': ts, 'threadId': None, 'reactions': [],
493
+ 'attachments': [], 'isEdited': False,
494
+ }
495
+
496
+ messages = {
497
+ 'general': [
498
+ msg('msg_g1', 'user_2', 'Morning all — reminder that QBR season kicks off next week.',
499
+ '2026-06-18T13:02:00Z'),
500
+ msg('msg_g2', 'user_3', 'Thanks Dana, calendars are going out today.',
501
+ '2026-06-18T13:05:00Z'),
502
+ ],
503
+ 'random': [
504
+ msg('msg_r1', 'user_3', 'Coffee machine on 4th floor is fixed.',
505
+ '2026-06-17T16:20:00Z'),
506
+ ],
507
+ 'customer-success': [
508
+ msg('msg_cs1', 'user_2', 'Let me know if anyone needs help with renewals this quarter.',
509
+ '2026-06-19T14:00:00Z'),
510
+ ],
511
+ 'acct-summit-retail': [
512
+ msg('msg_sr1', 'user_3', 'Welcome to the Summit Retail Group account channel.',
513
+ '2026-01-02T10:30:00Z'),
514
+ msg('msg_sr2', 'user_1', 'Adding our latest usage dashboard link to the bookmarks.',
515
+ '2026-05-12T11:15:00Z'),
516
+ ],
517
+ 'acct-northstar': [
518
+ msg('msg_ns1', 'user_2', 'Northstar Apparel account channel — main contact is Alex Moreno.',
519
+ '2026-01-03T09:00:00Z'),
520
+ ],
521
+ }
522
+
523
+ return {
524
+ 'currentUser': current_user,
525
+ 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Northwind Cloud', 'icon': ''},
526
+ 'users': users,
527
+ 'channels': channels,
528
+ 'messages': messages,
529
+ 'threads': {},
530
+ 'dms': [],
531
+ 'bookmarkedMessages': [],
532
+ 'callHistory': [],
533
+ 'settings': {'theme': 'light', 'notifications': 'all', 'displayDensity': 'comfortable',
534
+ 'showAvatars': True, 'use24Hour': False},
535
+ 'invitations': [],
536
+ 'notifications': [],
537
+ }
538
+
539
+
540
+ # =========================================================================
541
+ # INJECT
542
+ # =========================================================================
543
+ builders = {
544
+ 'notion_mock': build_notion_state,
545
+ 'salesforce_mock': build_salesforce_state,
546
+ 'slack_mock': build_slack_state,
547
+ }
548
+
549
+ for name, url in MOCKS.items():
550
+ state = builders[name]()
551
+ resp = http_post(f'{url}/post?sid={sid}', {'action': 'set', 'state': state})
552
+ assert resp.status_code == 200, f'{name} injection failed: {resp.status_code} {resp.text}'
553
+ go = http_get(f'{url}/go?sid={sid}').json()
554
+ assert go.get('initial_state') is not None, f'{name}: initial_state is None after injection'
555
+ print(f'Injected {name}: sid={sid}')
556
+
557
+ print('All mock states injected successfully.')
558
+
559
+
560
+ # =========================================================================
561
+ # GUI-READY: launch browser tabs for all three mocks
562
+ # =========================================================================
563
+ def launch_gui(command, delay_sec=1.0):
564
+ env = os.environ.copy()
565
+ env['DISPLAY'] = ':0'
566
+ # Accept both a command string and a pre-split arg list (some tasks
567
+ # build arg lists themselves, e.g. se_hard_008).
568
+ if isinstance(command, str):
569
+ _parts = shlex.split(command)
570
+ else:
571
+ _parts = list(command)
572
+ # Inject CDP debug port so wait_mocks_loaded can verify browser render
573
+ # via Playwright connect_over_cdp. Idempotent: skip if any arg already
574
+ # starts with --remote-debugging-port (some tasks inject their own
575
+ # dynamic port, e.g. se_hard_008).
576
+ if _parts and 'google-chrome' in _parts[0] \
577
+ and not any(p.startswith('--remote-debugging-port') for p in _parts):
578
+ _parts[1:1] = ['--no-first-run', '--no-default-browser-check',
579
+ '--remote-debugging-port=1337']
580
+ _proc = subprocess.Popen(_parts, stdin=subprocess.DEVNULL,
581
+ stdout=subprocess.DEVNULL,
582
+ stderr=subprocess.DEVNULL, env=env,
583
+ start_new_session=True)
584
+ time.sleep(delay_sec)
585
+ if _proc.poll() is not None:
586
+ print(' WARNING: launch_gui process exited early (code=%s)'
587
+ % _proc.returncode)
588
+ return _proc
589
+ launch_gui(f'google-chrome "{MOCKS["notion_mock"]}/?sid={sid}"', delay_sec=2.5)
590
+ launch_gui(f'google-chrome "{MOCKS["salesforce_mock"]}/?sid={sid}"', delay_sec=2.0)
591
+ launch_gui(f'google-chrome "{MOCKS["slack_mock"]}/?sid={sid}"', delay_sec=2.0)
592
+ wait_mocks_loaded()
593
+ print('GUI_READY: launched Chrome tabs for notion, salesforce, slack with DISPLAY=:0')
csm_health_risk_002/reward.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: CSM logs churn risk for the one Red+declining account in their book
13
+ (Summit Retail Group) across Notion, Salesforce, and Slack.
14
+ Task ID: csm_health_risk_002
15
+ Domain: mock_websites (multi-mock: notion_mock, salesforce_mock, slack_mock)
16
+
17
+ Scoring (1.0 total, 100% PROGRAMMATIC — LLM judge intentionally NOT used):
18
+ Component 1 — Notion Risk Note on Jordan Rivera's Summit Retail Group row (0.34)
19
+ 0.17 item-summit 'Risk Note' went blank -> non-empty, AND every OTHER
20
+ account row's Risk Note remains blank, with the row owned by Jordan Rivera
21
+ 0.17 the note content explains the risk (declining/Down usage + Red/churn)
22
+ Component 2 — Salesforce risk task on Jordan Rivera's account-1 (0.33)
23
+ 0.13 at least one new task (type 'task') added to activities
24
+ 0.20 the new task: relatedToType 'account', relatedToId 'account-1',
25
+ account owner/assignedToId 'user-1' (Jordan Rivera),
26
+ status != 'Completed', and text indicates health/risk or usage decline
27
+ Component 3 — Slack heads-up from Jordan Rivera in acct-summit-retail (0.33)
28
+ 0.13 a new message in 'acct-summit-retail', AND 'acct-northstar'
29
+ and 'general' untouched, sent by 'user_1' Jordan Rivera
30
+ 0.20 the message names Summit, states Red/at-risk + declining usage,
31
+ and gives a next step or owner
32
+
33
+ All checks are anchored to the initial->current delta so reward(initial_env)==0.0.
34
+ """
35
+ import os
36
+ import re
37
+ import sys
38
+
39
+ import requests
40
+
41
+ CURRENT_USER_NAME = 'Jordan Rivera'
42
+ NOTION_USER_ID = 'user-1'
43
+ SALESFORCE_USER_ID = 'user-1'
44
+ SLACK_USER_ID = 'user_1'
45
+ TARGET_NOTION_ITEM_ID = 'item-summit'
46
+ TARGET_ACCOUNT_ID = 'account-1'
47
+ TARGET_SLACK_CHANNEL_ID = 'acct-summit-retail'
48
+
49
+ # ---------------------------------------------------------------------------
50
+ # Read sid
51
+ # ---------------------------------------------------------------------------
52
+ try:
53
+ with open('/tmp/task_web_sid') as f:
54
+ sid = f.read().strip()
55
+ if not sid:
56
+ raise ValueError('sid is empty')
57
+ except Exception as e:
58
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
59
+ print('REWARD: 0.0')
60
+ sys.exit(0)
61
+
62
+ MOCKS = {
63
+ 'notion': 'http://28.7.184.198:8166',
64
+ 'salesforce': 'http://28.7.184.198:8175',
65
+ 'slack': 'http://28.7.184.198:8178',
66
+ }
67
+
68
+ # ---------------------------------------------------------------------------
69
+ # Egress proxy helper (MANDATORY in this cluster — direct egress to
70
+ # *.xlang.ai fails from inside the Docker VMs)
71
+ # ---------------------------------------------------------------------------
72
+ PROXY_CANDIDATES = [
73
+ os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy'),
74
+ None,
75
+ ]
76
+
77
+
78
+ def resolve_proxy(probe_url):
79
+ try:
80
+ requests.get(probe_url, timeout=8)
81
+ return None
82
+ except Exception:
83
+ pass
84
+ for candidate in PROXY_CANDIDATES:
85
+ if not candidate:
86
+ continue
87
+ try:
88
+ requests.get(
89
+ probe_url,
90
+ timeout=12,
91
+ proxies={'http': candidate, 'https': candidate},
92
+ )
93
+ return candidate
94
+ except Exception:
95
+ continue
96
+ return None
97
+
98
+
99
+ def fetch_state(name, url):
100
+ """Return (initial_state, current_state) dicts for a mock, or (None, None)."""
101
+ proxy = resolve_proxy(f'{url}/go?sid=conn-probe')
102
+ proxies = {'http': proxy, 'https': proxy} if proxy else None
103
+ resp = requests.get(f'{url}/go?sid={sid}', timeout=15, proxies=proxies)
104
+ resp.raise_for_status()
105
+ data = resp.json()
106
+ return data.get('initial_state') or {}, data.get('current_state') or {}
107
+
108
+
109
+ # ---------------------------------------------------------------------------
110
+ # Fetch all three mocks up front; any failure -> 0.0
111
+ # ---------------------------------------------------------------------------
112
+ states = {}
113
+ try:
114
+ for name, url in MOCKS.items():
115
+ init, curr = fetch_state(name, url)
116
+ if not curr:
117
+ print(f'CRITICAL: current_state empty for {name}')
118
+ print('REWARD: 0.0')
119
+ sys.exit(0)
120
+ states[name] = (init, curr)
121
+ except Exception as e:
122
+ print(f'CRITICAL: Cannot fetch combined mock state: {e}')
123
+ print('REWARD: 0.0')
124
+ sys.exit(0)
125
+
126
+
127
+ def value_text(value):
128
+ """Return a comparable text value for raw or lightly typed mock fields."""
129
+ if value is None:
130
+ return ''
131
+ if isinstance(value, str):
132
+ return value
133
+ if isinstance(value, (int, float, bool)):
134
+ return str(value)
135
+ if isinstance(value, dict):
136
+ parts = []
137
+ for key in ('name', 'label', 'title', 'text', 'content', 'value', 'id'):
138
+ if key in value:
139
+ parts.append(value_text(value.get(key)))
140
+ if not parts:
141
+ parts = [value_text(v) for v in value.values()]
142
+ return ' '.join(p for p in parts if p)
143
+ if isinstance(value, list):
144
+ return ' '.join(value_text(v) for v in value)
145
+ return str(value)
146
+
147
+
148
+ def normalize(text):
149
+ text = value_text(text).lower()
150
+ text = text.replace('&', ' and ')
151
+ text = re.sub(r'[_\-/]+', ' ', text)
152
+ text = re.sub(r'\s+', ' ', text)
153
+ return text.strip()
154
+
155
+
156
+ def has_any(text, keywords):
157
+ low = normalize(text)
158
+ return any(k in low for k in keywords)
159
+
160
+
161
+ # Keyword groups. These intentionally allow common UI/text variations while
162
+ # still anchoring on the requested customer, health/risk, and next action.
163
+ JORDAN_KW = ['jordan rivera', 'jordan']
164
+ ACCOUNT_KW = ['summit retail group', 'summit', 'srg']
165
+ USAGE_DECLINE_KW = [
166
+ 'declin', 'down', 'drop', 'decreas', 'fall', 'low', 'lower', 'slip',
167
+ 'slipped', 'usage', 'mau', 'adoption', 'engagement', 'activity',
168
+ 'utilization',
169
+ ]
170
+ RED_RISK_KW = [
171
+ 'red', 'at risk', 'atrisk', 'risk', 'churn', 'retention', 'health',
172
+ 'unhealthy', 'critical', 'escalat', 'renewal concern',
173
+ ]
174
+ NEXTSTEP_KW = [
175
+ 'next step', 'check in', 'checkin', 'recovery', 'recover', 'plan',
176
+ 'schedul', 'owner', 'will', 'follow up', 'followup', 'escalat',
177
+ 'meeting', 'reach out', 'contact', 'action', 'mitigat', 'sync',
178
+ ]
179
+
180
+
181
+ def is_jordan_name(text):
182
+ return has_any(text, JORDAN_KW)
183
+
184
+
185
+ def mentions_account(text):
186
+ return has_any(text, ACCOUNT_KW)
187
+
188
+
189
+ def mentions_usage_decline(text):
190
+ return has_any(text, USAGE_DECLINE_KW)
191
+
192
+
193
+ def mentions_red_or_risk(text):
194
+ return has_any(text, RED_RISK_KW)
195
+
196
+
197
+ def new_records(initial, current, id_key):
198
+ init_ids = {item.get(id_key) for item in (initial or []) if item.get(id_key)}
199
+ added = [item for item in (current or []) if item.get(id_key) not in init_ids]
200
+ if added or init_ids:
201
+ return added
202
+ return (current or [])[len(initial or []):]
203
+
204
+
205
+ def verify_task():
206
+ total_score = 0.0
207
+
208
+ # =====================================================================
209
+ # Component 1 — Notion Risk Note on Summit Retail Group (0.34)
210
+ # =====================================================================
211
+ try:
212
+ n_init, n_curr = states['notion']
213
+ init_pages = n_init.get('pages', {})
214
+ curr_pages = n_curr.get('pages', {})
215
+
216
+ notion_user = n_curr.get('user', {})
217
+ current_user_is_jordan = (
218
+ notion_user.get('id') == NOTION_USER_ID
219
+ and is_jordan_name(notion_user.get('name'))
220
+ )
221
+
222
+ summit = curr_pages.get(TARGET_NOTION_ITEM_ID, {})
223
+ summit_props = summit.get('properties', {})
224
+ summit_risk = value_text(summit_props.get('prop-risk')).strip()
225
+ summit_owner = value_text(summit_props.get('prop-csm')).strip()
226
+ summit_init_risk = (
227
+ value_text(
228
+ init_pages.get(TARGET_NOTION_ITEM_ID, {})
229
+ .get('properties', {})
230
+ .get('prop-risk')
231
+ )
232
+ ).strip()
233
+ summit_owned_by_jordan = is_jordan_name(summit_owner)
234
+
235
+ # Other rows that MUST stay blank (negative constraint)
236
+ other_ids = ['item-cedar', 'item-river', 'item-blue', 'item-north']
237
+ others_blank = all(
238
+ value_text(
239
+ curr_pages.get(pid, {}).get('properties', {}).get('prop-risk')
240
+ ).strip() == ''
241
+ for pid in other_ids
242
+ )
243
+ other_csm_unchanged = all(
244
+ normalize(curr_pages.get(pid, {}).get('properties', {}).get('prop-csm')) ==
245
+ normalize(init_pages.get(pid, {}).get('properties', {}).get('prop-csm'))
246
+ for pid in other_ids
247
+ )
248
+
249
+ # 1a (0.17): Jordan's summit note newly non-empty AND others untouched
250
+ if (current_user_is_jordan and summit_owned_by_jordan and summit_init_risk == ''
251
+ and summit_risk != '' and others_blank and other_csm_unchanged):
252
+ print('PASS: Notion Jordan-owned Summit Risk Note filled, other rows untouched (0.17)')
253
+ total_score += 0.17
254
+ else:
255
+ print(f'FAIL: Notion 1a — summit_init={summit_init_risk!r} '
256
+ f'summit_now={summit_risk!r} current_user_is_jordan={current_user_is_jordan} '
257
+ f'summit_owner={summit_owner!r} others_blank={others_blank} '
258
+ f'other_csm_unchanged={other_csm_unchanged}')
259
+
260
+ # 1b (0.17): note content explains the risk
261
+ if summit_risk != '' and mentions_usage_decline(summit_risk) and mentions_red_or_risk(summit_risk):
262
+ print('PASS: Notion Risk Note explains declining usage + red/churn risk (0.17)')
263
+ total_score += 0.17
264
+ else:
265
+ print(f'FAIL: Notion 1b — content does not name decline+red/churn: {summit_risk!r}')
266
+ except Exception as e:
267
+ print(f'ERROR: Component 1 (Notion) — {e}')
268
+
269
+ # =====================================================================
270
+ # Component 2 — Salesforce risk task on account-1 (0.33)
271
+ # =====================================================================
272
+ try:
273
+ s_init, s_curr = states['salesforce']
274
+ sf_user = s_curr.get('user', {})
275
+ current_user_is_jordan = (
276
+ sf_user.get('userId') == SALESFORCE_USER_ID
277
+ and is_jordan_name(f'{sf_user.get("firstName", "")} {sf_user.get("lastName", "")}')
278
+ )
279
+ accounts_by_id = {a.get('accountId'): a for a in (s_curr.get('accounts', []) or [])}
280
+ target_account = accounts_by_id.get(TARGET_ACCOUNT_ID, {})
281
+ target_account_owned_by_jordan = target_account.get('ownerId') == SALESFORCE_USER_ID
282
+
283
+ init_acts = s_init.get('activities', []) or []
284
+ curr_acts = s_curr.get('activities', []) or []
285
+ new_acts = new_records(init_acts, curr_acts, 'activityId')
286
+ new_tasks = [a for a in new_acts if normalize(a.get('type')) == 'task']
287
+
288
+ # 2a (0.13): at least one new task added
289
+ if len(new_tasks) >= 1:
290
+ print('PASS: Salesforce — at least one new task added (0.13)')
291
+ total_score += 0.13
292
+ else:
293
+ print(f'FAIL: Salesforce 2a — expected a new task, found {len(new_tasks)} '
294
+ f'(new activities: {[a.get("activityId") for a in new_acts]})')
295
+
296
+ # 2b (0.20): the new task is the Summit churn-risk task with correct fields
297
+ risk_task = None
298
+ for t in new_tasks:
299
+ task_text = ' '.join(
300
+ value_text(t.get(k))
301
+ for k in ('subject', 'description', 'comments', 'body')
302
+ )
303
+ related_to_target = t.get('relatedToId') == TARGET_ACCOUNT_ID
304
+ if related_to_target and (
305
+ mentions_red_or_risk(task_text)
306
+ or mentions_usage_decline(task_text)):
307
+ risk_task = t
308
+ break
309
+ if risk_task is not None:
310
+ status = normalize(risk_task.get('status'))
311
+ checks = {
312
+ 'current user=Jordan Rivera': current_user_is_jordan,
313
+ 'account.ownerId=user-1 (Jordan Rivera)': target_account_owned_by_jordan,
314
+ 'relatedToType=account': normalize(risk_task.get('relatedToType')) == 'account',
315
+ 'relatedToId=account-1': risk_task.get('relatedToId') == TARGET_ACCOUNT_ID,
316
+ 'assignedToId=user-1 (Jordan Rivera)': risk_task.get('assignedToId') == SALESFORCE_USER_ID,
317
+ 'status!=Completed': status != 'completed',
318
+ }
319
+ if all(checks.values()):
320
+ print('PASS: Salesforce risk task fields correct '
321
+ f'(subject={risk_task.get("subject")!r}) (0.20)')
322
+ total_score += 0.20
323
+ else:
324
+ failed = [k for k, v in checks.items() if not v]
325
+ print(f'FAIL: Salesforce 2b — task field mismatch: {failed} '
326
+ f'(task={risk_task})')
327
+ else:
328
+ print('FAIL: Salesforce 2b — no new account-1 task with risk/usage context found')
329
+ except Exception as e:
330
+ print(f'ERROR: Component 2 (Salesforce) — {e}')
331
+
332
+ # =====================================================================
333
+ # Component 3 — Slack heads-up in acct-summit-retail (0.33)
334
+ # =====================================================================
335
+ try:
336
+ sl_init, sl_curr = states['slack']
337
+ slack_user = sl_curr.get('currentUser', {})
338
+ current_user_is_jordan = (
339
+ slack_user.get('userId') == SLACK_USER_ID
340
+ and is_jordan_name(slack_user.get('fullName'))
341
+ )
342
+ init_msgs = sl_init.get('messages', {}) or {}
343
+ curr_msgs = sl_curr.get('messages', {}) or {}
344
+
345
+ summit_init = init_msgs.get(TARGET_SLACK_CHANNEL_ID, []) or []
346
+ summit_curr = curr_msgs.get(TARGET_SLACK_CHANNEL_ID, []) or []
347
+ new_summit = new_records(summit_init, summit_curr, 'messageId')
348
+ jordan_messages = [m for m in new_summit if m.get('senderId') == SLACK_USER_ID]
349
+ sent_by_jordan = len(jordan_messages) >= 1
350
+
351
+ # negative constraints: acct-northstar and general unchanged
352
+ north_unchanged = not new_records(
353
+ init_msgs.get('acct-northstar', []) or [],
354
+ curr_msgs.get('acct-northstar', []) or [],
355
+ 'messageId',
356
+ )
357
+ general_unchanged = not new_records(
358
+ init_msgs.get('general', []) or [],
359
+ curr_msgs.get('general', []) or [],
360
+ 'messageId',
361
+ )
362
+
363
+ # 3a (0.13): new message in summit channel from Jordan + others untouched
364
+ if (current_user_is_jordan and len(new_summit) >= 1
365
+ and sent_by_jordan and north_unchanged and general_unchanged):
366
+ print('PASS: Slack — Jordan message in acct-summit-retail, '
367
+ 'northstar+general untouched (0.13)')
368
+ total_score += 0.13
369
+ else:
370
+ print(f'FAIL: Slack 3a — summit init={len(summit_init)} curr={len(summit_curr)} '
371
+ f'current_user_is_jordan={current_user_is_jordan} sent_by_jordan={sent_by_jordan} '
372
+ f'north_unchanged={north_unchanged} general_unchanged={general_unchanged}')
373
+
374
+ # 3b (0.20): the new message names Summit + Red/at-risk + declining usage + next step
375
+ matched = None
376
+ for m in jordan_messages:
377
+ txt = m.get('content')
378
+ if (mentions_account(txt)
379
+ and mentions_red_or_risk(txt)
380
+ and mentions_usage_decline(txt)
381
+ and has_any(txt, NEXTSTEP_KW)):
382
+ matched = m
383
+ break
384
+ if matched is not None:
385
+ print('PASS: Slack message names Summit, Red/at-risk, declining usage, next step (0.20)')
386
+ total_score += 0.20
387
+ else:
388
+ print(f'FAIL: Slack 3b — new message(s) do not cover Summit+red+declining+nextstep: '
389
+ f'{[m.get("content") for m in new_summit]}')
390
+ except Exception as e:
391
+ print(f'ERROR: Component 3 (Slack) — {e}')
392
+
393
+ final_score = round(min(total_score, 1.0), 4)
394
+ print(f'\nScore: {total_score}/1.0')
395
+ print(f'REWARD: {final_score}')
396
+ return final_score
397
+
398
+
399
+ verify_task()
csm_health_risk_002/reward_label.json ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/csm_health_risk_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-03 20:20:27",
7
+ "label": {
8
+ "task_id": "csm_health_risk_002",
9
+ "domain": "mock_websites",
10
+ "summary": "验证 CSM Jordan Rivera 是否在 Notion、Salesforce 和 Slack 三个系统中正确记录了 Summit Retail Group 账户的流失风险(Red 状态且使用衰退)。",
11
+ "is_placeholder": false,
12
+ "data_sources": [
13
+ "/tmp/task_web_sid",
14
+ "notion_mock (http://28.7.186.212:8186)",
15
+ "salesforce_mock (http://28.7.186.212:8195)",
16
+ "slack_mock (http://28.7.186.212:8198)"
17
+ ],
18
+ "scoring_components": [
19
+ {
20
+ "name": "Component 1a — Notion Summit 风险笔记创建",
21
+ "weight": 0.17,
22
+ "description": "检查 Notion 中 Jordan Rivera 拥有的 Summit Retail Group 行(item-summit)的 Risk Note 从空白变为非空,且其他账户行的 Risk Note 保持空白、CSM 未改动",
23
+ "check_logic": "current_user_is_jordan 为真;summit_owned_by_jordan 为真;summit_init_risk == '' 且 summit_risk != '';others_blank 为真(item-cedar/river/blue/north 的 prop-risk 均为空);other_csm_unchanged 为真",
24
+ "pass_condition": "当前用户是 Jordan Rivera;item-summit 的 prop-risk 初始为空且当前非空;该行 CSM 属于 Jordan;其余四行账户的 prop-risk 仍为空且 CSM 与初始状态一致"
25
+ },
26
+ {
27
+ "name": "Component 1b — Notion 风险笔记内容",
28
+ "weight": 0.17,
29
+ "description": "检查 Summit Retail Group 的 Risk Note 内容是否解释了使用衰退和 Red/流失风险",
30
+ "check_logic": "summit_risk != '' 且 mentions_usage_decline(summit_risk) 返回真且 mentions_red_or_risk(summit_risk) 返回真",
31
+ "pass_condition": "笔记非空,且文本经 normalize 后同时包含 decline/down/drop 等使用衰退关键词和 red/at risk/churn 等风险关键词"
32
+ },
33
+ {
34
+ "name": "Component 2a — Salesforce 新增任务",
35
+ "weight": 0.13,
36
+ "description": "检查 Salesforce 的 activities 中是否至少新增了一条 type 为 'task' 的记录",
37
+ "check_logic": "对比 initial 和 current 的 activities 列表(按 activityId 去重),new_tasks = [a for a in new_acts if normalize(a.get('type')) == 'task'],要求 len(new_tasks) >= 1",
38
+ "pass_condition": "至少存在一条新增 activity,其 type 字段归一化后为 'task'"
39
+ },
40
+ {
41
+ "name": "Component 2b — Salesforce 风险任务字段",
42
+ "weight": 0.2,
43
+ "description": "检查新增任务是否针对 account-1、字段正确且文本体现健康风险或使用衰退",
44
+ "check_logic": "遍历 new_tasks,拼接 subject/description/comments/body 为 task_text;找到 relatedToId == 'account-1' 且 (mentions_red_or_risk(task_text) 或 mentions_usage_decline(task_text)) 的任务;再校验 current_user_is_jordan、target_account_owned_by_jordan、relatedToType 归一化后为 'account'、assignedToId == 'user-1'、status 归一化后 != 'completed'",
45
+ "pass_condition": "新增任务关联 account-1、类型为 account、分配给 user-1、状态非 Completed、当前用户为 Jordan、账户所有者为 Jordan,且任务文本包含风险或使用衰退关键词"
46
+ },
47
+ {
48
+ "name": "Component 3a — Slack 频道消息",
49
+ "weight": 0.13,
50
+ "description": "检查 Jordan Rivera 是否在 acct-summit-retail 频道发送了新消息,且 acct-northstar 和 general 频道未被改动",
51
+ "check_logic": "current_user_is_jordan 为真;new_records(summit_init, summit_curr, 'messageId') 非空且其中至少一条 senderId == 'user_1';new_records 对 acct-northstar 和 general 返回空列表(north_unchanged 和 general_unchanged 为真)",
52
+ "pass_condition": "当前 Slack 用户为 Jordan;acct-summit-retail 频道有新增消息且由 user_1 发送;acct-northstar 和 general 频道无新增消息"
53
+ },
54
+ {
55
+ "name": "Component 3b — Slack 消息内容",
56
+ "weight": 0.2,
57
+ "description": "检查新消息是否提到 Summit、Red/风险、使用衰退,并给出下一步或负责人",
58
+ "check_logic": "遍历 jordan_messages,检查 m.get('content') 同时满足 mentions_account(txt)、mentions_red_or_risk(txt)、mentions_usage_decline(txt)、has_any(txt, NEXTSTEP_KW)",
59
+ "pass_condition": "消息内容经 normalize 后同时包含 Summit 相关关键词、Red/风险关键词、使用衰退关键词以及 next step/owner/action 等下一步关键词"
60
+ }
61
+ ],
62
+ "total_max_score": 1.0,
63
+ "score_aggregation": "各子组件分数直接相加,最终通过 min(total_score, 1.0) 钳制上限为 1.0,再四舍五入保留 4 位小数",
64
+ "failure_modes": [
65
+ "读取 /tmp/task_web_sid ���败或为空:打印 CRITICAL 并返回 0.0",
66
+ "从任一 mock 服务获取状态失败或 current_state 为空:打印 CRITICAL 并返回 0.0",
67
+ "Notion 检查中当前用户非 Jordan、Summit 行未新建 Risk Note、其他行被改动:Component 1 不得分",
68
+ "Salesforce 中未新增 task 类型活动,或新增任务字段不匹配 account-1/非 Completed/未分配 Jordan:Component 2 不得分",
69
+ "Slack 中 acct-summit-retail 无 Jordan 的新消息,或其他频道被发送消息:Component 3 不得分",
70
+ "各组件内部异常被捕获为 ERROR,仅影响该组件得分,不会导致整体提前退出"
71
+ ],
72
+ "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话标识,失败则直接返回 0.0。随后通过 HTTP 请求向 notion_mock、salesforce_mock、slack_mock 三个服务的 /go?sid={sid} 端点拉取 initial_state 与 current_state,任一拉取失败或 current_state 为空即返回 0.0。接着进入 verify_task():Component 1 针对 Notion,检查 item-summit 的 prop-risk 是否由 Jordan 从空白填为有效内容(0.17),并验证内容包含使用衰退与 Red/流失风险语义(0.17),同时要求其余四行账户的 Risk Note 仍为空白且 CSM 未变;Component 2 针对 Salesforce,对比 activities 列表找出新增 task,至少一条新增 task 得 0.13,再验证该任务关联 account-1、类型为 account、分配给 user-1、状态非 Completed 且文本含风险/衰退语义得 0.20;Component 3 针对 Slack,检查 acct-summit-retail 频道有 Jordan 发送的新消息且 acct-northstar 与 general 频道无变动得 0.13,再验证消息内容同时提及 Summit、Red/风险、使用衰退及下一步行动得 0.20。所有子项得分累加后,以 min(total_score, 1.0) 限制上限并四舍五入到 4 位小数作为最终 REWARD。",
73
+ "confidence": 1.0
74
+ },
75
+ "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码并提取所需信息:\n\n1. **task_id**: 从 docstring 中可以看到 \"Task ID: csm_health_risk_001\"\n2. **domain**: 从 docstring 中可以看到 \"Domain: mock_websites (multi-mock: notion_mock, salesforce_mock, slack_mock)\",所以 domain 是 mock_websites\n3. **summary**: 一句话概括。这个脚本是验证 CSM (Customer Success Manager) Jordan Rivera 是否在 Notion、Salesforce 和 Slack 中正确记录了 Summit Retail Group 这个红标/衰退客户的风险信息。\n4. **is_placeholder**: false,因为脚本有详细的检查逻辑,不是占位脚本。\n5. **data_sources**: 脚本从以下数据源获取状态:\n - `/tmp/task_web_sid` (读取 sid)\n - `http://28.7.186.212:8166` (notion mock)\n - `http://28.7.186.212:8175` (salesforce mock)\n - `http://28.7.186.212:8178` (slack mock)\n 通过 `/go?sid={sid}` 端点获取 initial_state 和 current_state。\n\n6. **scoring_components**:\n - Component 1: Notion Risk Note (0.34 total)\n - 1a (0.17): 检查当前用户是 Jordan Rivera,Summit Retail Group 行 (item-summit) 的 Risk Note (prop-risk) 从空变为非空,且其他行 (item-cedar, item-river, item-blue, item-north) 的 Risk Note 保持空白,且其他行的 CSM 未改变。\n - 1b (0.17): Risk Note 内容提到 usage decline 和 red/churn risk。\n - Component 2: Salesforce risk task (0.33 total)\n - 2a (0.13): 至少添加了一个新的 task 类型活动。\n - 2b (0.20): 新任务关联到 account-1,relatedToType 是 account,assignedToId 是 user-1 (Jordan),状态不是 Completed,且文本提到 health/risk 或 usage decline。\n - Component 3: Slack heads-up (0.33 total)\n - 3a (0.13): 在 acct-summit-retail 频道有 Jordan 发送的新消息,且 acct-northstar 和 general 频道未改变。\n - 3b (0.20): 消息提到 Summit、Red/at-risk、declining usage,并给出 next step/owner。\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 失败或为空 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n - 获取 mock 状态失败或 current_state 为空 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n - 各组件内部异常会被捕获并打印 ERROR,但不会导致提前退出,只是该组件不得分。\n - 注意:如果检查条件不满足,只是不加分,不会提前退出。\n\n10. **scoring_logic_explanation**: 需要详细解释执行顺序:\n - 首先读取 /tmp/task_web_sid 获取会话 ID,失败则返回 0.0。\n - 然后依次从 notion、salesforce、slack 三个 mock 服务获取 initial_state 和 current_state,通过 /go?sid={sid} 端点,任何失败或 current_state 为空则返回 0.0。\n - 接着计算总分:\n - Component 1 (Notion): 检查 item-summit 的 prop-risk 从空变非空且由 Jordan 拥有,其他行未动 (0.17);再检查内容包含 decline 和 red/risk 关键词 (0.17)。\n - Component 2 (Salesforce): 检查 activities 中新增至少一个 task 类型记录 (0.13);再检查该任务关联 account-1、类型为 account、分配给 user-1、状态非 Completed、文本包含 risk/usage decline (0.20)。\n - Component 3 (Slack): 检查 acct-summit-retail 频道有 Jordan 发送的新消息且其他频道未变 (0.13);再检查消息内容提到 Summit、Red/at-risk、declining usage 和 next step (0.20)。\n - 最后将各组件得分累加,用 min(total_score, 1.0) 钳制上限,四舍五入到 4 位小数输出。\n\n11. **confidence**: 1.0,因为代码逻辑非常清晰完整。\n\n现在构建 JSON。注意:\n- 所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样。\n- 不要输出 Markdown 代码块标记。\n- 不要输出额外解释。\n- 不要输出思考过程。\n- 第一个字符必须是 {,最后一个字符必须是 }。\n\n让我仔细构造每个字段:\n\ntask_id: \"csm_health_risk_001\"\ndomain: \"mock_websites\"\nsummary: \"验证 CSM Jordan Rivera 是否在 Notion、Salesforce 和 Slack 三个系统中正确记录了 Summit Retail Group 账户的流失风险(Red 状态且使用衰退)。\"\nis_placeholder: false\ndata_sources: [\"/tmp/task_web_sid\", \"notion_mock (http://28.7.186.212:8186)\", \"salesforce_mock (http://28.7.186.212:8195)\", \"slack_mock (http://28.7.186.212:8198)\"]\n\nscoring_components:\n- name: \"Component 1a — Notion Summit 风险笔记创建\"\n weight: 0.17\n description: \"检查 Notion 中 Jordan Rivera 拥有的 Summit Retail Group 行(item-summit)的 Risk Note 从空白变为非空,且其他账户行的 Risk Note 保持空白、CSM 未改动\"\n check_logic: \"current_user_is_jordan 为真;summit_owned_by_jordan 为真;summit_init_risk == '' 且 summit_risk != '';others_blank 为真(item-cedar/river/blue/north 的 prop-risk 均为空);other_csm_unchanged 为真\"\n pass_condition: \"当前用户是 Jordan Rivera;item-summit 的 prop-risk 初始为空且当前非空;该行 CSM 属于 Jordan;其余四行 prop-risk 仍为空且 CSM 与初始状态一致\"\n\n- name: \"Component 1b — Notion 风险笔记内容\"\n weight: 0.17\n description: \"检查 Summit Retail Group 的 Risk Note 内容是否解释了使用衰退和 Red/流失风险\"\n check_logic: \"summit_risk != '' 且 mentions_usage_decline(summit_risk) 返回真且 mentions_red_or_risk(summit_risk) 返回真\"\n pass_condition: \"笔记非空,且文本经 normalize 后同时包含 decline/down/drop 等使用衰退关键词和 red/at risk/churn 等风险关键词\"\n\n- name: \"Component 2a — Salesforce 新增任务\"\n weight: 0.13\n description: \"检查 Salesforce 的 activities 中是否至少新增了一条 type 为 'task' 的记录\"\n check_logic: \"对比 initial 和 current 的 activities 列表(按 activityId 去重),new_tasks = [a for a in new_acts if normalize(a.get('type')) == 'task'],要求 len(new_tasks) >= 1\"\n pass_condition: \"至少存在一条新增 activity,其 type 字段归一化后为 'task'\"\n\n- name: \"Component 2b — Salesforce 风险任务字段\"\n weight: 0.20\n description: \"检查新增任务是否针对 account-1、字段正确且文本体现健康风险或使用衰退\"\n check_logic: \"遍历 new_tasks,拼接 subject/description/comments/body 为 task_text;找到 relatedToId == 'account-1' 且 (mentions_red_or_risk(task_text) 或 mentions_usage_decline(task_text)) 的任务;再校验 current_user_is_jordan、target_account_owned_by_jordan、relatedToType 归一化后为 'account'、assignedToId == 'user-1'、status 归一化后 != 'completed'\"\n pass_condition: \"新增任务关联 account-1、类型为 account、分配给 user-1、状态非 Completed、当前用户为 Jordan、账户所有者为 Jordan,且任务文本包含风险或使用衰退关键词\"\n\n- name: \"Component 3a — Slack 频道消息\"\n weight: 0.13\n description: \"检查 Jordan Rivera 是否在 acct-summit-retail 频道发送了新消息,且 acct-northstar 和 general 频道未被改动\"\n check_logic: \"current_user_is_jordan 为真;new_records(summit_init, summit_curr, 'messageId') 非空且其中至少一条 senderId == 'user_1';new_records 对 acct-northstar 和 general 返回空列表(north_unchanged 和 general_unchanged 为真)\"\n pass_condition: \"当前 Slack 用户为 Jordan;acct-summit-retail 频道有新增消息且由 user_1 发送;acct-northstar 和 general 频道无新增消息\"\n\n- name: \"Component 3b — Slack 消息内容\"\n weight: 0.20\n description: \"检查新消息是否提到 Summit、Red/风险、使用衰退,并给出下一步或负责人\"\n check_logic: \"遍历 jordan_messages,检查 m.get('content') 同时满足 mentions_account(txt)、mentions_red_or_risk(txt)、mentions_usage_decline(txt)、has_any(txt, NEXTSTEP_KW)\"\n pass_condition: \"消息内容经 normalize 后同时包含 Summit 相关关键词、Red/风险关键词、使用衰退关键词以及 next step/owner/action 等下一步关键词\"\n\ntotal_max_score: 1.0\nscore_aggregation: \"各子组件分数直接相加,最终通过 min(total_score, 1.0) 钳制上限为 1.0,再四舍五入保留 4 位小数\"\nfailure_modes: [\n \"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并返回 0.0\",\n \"从任一 mock 服务获取状态失败或 current_state 为空:打印 CRITICAL 并返回 0.0\",\n \"Notion 检查中当前用户非 Jordan、Summit 行未新建 Risk Note、其他行被改动:Component 1 不得分\",\n \"Salesforce 中未新增 task 类型活动,或新增任务字段不匹配 account-1/非 Completed/未分配 Jordan:Component 2 不得分\",\n \"Slack 中 acct-summit-retail 无 Jordan 的新消息,或其他频道被发送消息:Component 3 不得分\",\n \"各组件内部异常被捕获为 ERROR,仅影响该组件得分,不会导致整体提前退出\"\n]\n\nscoring_logic_explanation: \"脚本首先读取 /tmp/task_web_sid 获取会话标识,失败则直接返回 0.0。随后通过 HTTP 请求向 notion_mock、salesforce_mock、slack_mock 三个服务的 /go?sid={sid} 端点拉取 initial_state 与 current_state,任一拉取失败或 current_state 为空即返回 0.0。接着进入 verify_task():Component 1 针对 Notion,检查 item-summit 的 prop-risk 是否由 Jordan 从空白填为有效内容(0.17),并验证内容包含使用衰退与 Red/流失风险语义(0.17),同时要求其余四行账户的 Risk Note 仍为空白且 CSM 未变;Component 2 针对 Salesforce,对比 activities 列表找出新增 task,至少一条新增 task 得 0.13,再验证该任务关联 account-1、类型为 account、分配给 user-1、状态非 Completed 且文本含风险/衰退语义得 0.20;Component 3 针对 Slack,检查 acct-summit-retail 频道有 Jordan 发送的新消息且 acct-northstar 与 general 频道无变动得 0.13,再验证消息内容同时提及 Summit、Red/风险、使用衰退及下一步行动得 0.20。所有子项得分累加后,以 min(total_score, 1.0) 限制上限并四舍五入到 4 位小数作为最终 REWARD。\"\n\nconfidence: 1.0\n\n检查 JSON 格式要求:\n- 只输出一个 JSON 对象\n- 不要输出 Markdown 代码块标记\n- 不要输出额外解释\n- 不要输出思考过程\n- 不要输出 <thinking> 标签\n- 输出的第一个字符必须是 {,最后一个字符必须是 }\n\n确保所有字符串值都是中文(除了代码标识符和特定名称)。\n\n再检查一下 weight 字段。代码中显式给出了分值:0.17, 0.17, 0.13, 0.20, 0.13, 0.20。总和正好是 1.0。\n\n确认 data_sources 的写法。代码中是通过 MOCKS 字典定义的,端点是 http://28.7.186.212:8166 等。可以写为 notion_mock、salesforce_mock、slack_mock,并注明端点。\n\n确认 failure_modes 是否包含提前退出路径:\n- sid 读取失败:是,sys.exit(0)\n- mock 拉取失败:是,sys.exit(0)\n- 其他是不得分,不是提前退出,但也属于失败路径。\n\n确认 score_aggregation:\"相加后钳制到上限\" 是准确的。\n\n好,我现在可以输出最终的 JSON 了。 </think> {\"task_id\":\"csm_health_risk_001\",\"domain\":\"mock_websites\",\"summary\":\"验证 CSM Jordan Rivera 是否在 Notion、Salesforce 和 Slack 三个系统中正确记录了 Summit Retail Group 账户的流失风险(Red 状态且使用衰退)。\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"notion_mock (http://28.7.186.212:8186)\",\"salesforce_mock (http://28.7.186.212:8195)\",\"slack_mock (http://28.7.186.212:8198)\"],\"scoring_components\":[{\"name\":\"Component 1a — Notion Summit 风险笔记创建\",\"weight\":0.17,\"description\":\"检查 Notion 中 Jordan Rivera 拥有的 Summit Retail Group 行(item-summit)的 Risk Note 从空白变为非空,且其他账户行的 Risk Note 保持空白、CSM 未改动\",\"check_logic\":\"current_user_is_jordan 为真;summit_owned_by_jordan 为真;summit_init_risk == '' 且 summit_risk != '';others_blank 为真(item-cedar/river/blue/north 的 prop-risk 均为空);other_csm_unchanged 为真\",\"pass_condition\":\"当前用户是 Jordan Rivera;item-summit 的 prop-risk 初始为空且当前非空;该行 CSM 属于 Jordan;其余四行账户的 prop-risk 仍为空且 CSM 与初始状态一致\"},{\"name\":\"Component 1b — Notion 风险笔记内容\",\"weight\":0.17,\"description\":\"检查 Summit Retail Group 的 Risk Note 内容是否解释了使用衰退和 Red/流失风险\",\"check_logic\":\"summit_risk != '' 且 mentions_usage_decline(summit_risk) 返回真且 mentions_red_or_risk(summit_risk) 返回真\",\"pass_condition\":\"笔记非空,且文本经 normalize 后同时包含 decline/down/drop 等使用衰退关键词和 red/at risk/churn 等风险关键词\"},{\"name\":\"Component 2a — Salesforce 新增任务\",\"weight\":0.13,\"description\":\"检查 Salesforce 的 activities 中是否至少新增了一条 type 为 'task' 的记录\",\"check_logic\":\"对比 initial 和 current 的 activities 列表(按 activityId 去重),new_tasks = [a for a in new_acts if normalize(a.get('type')) == 'task'],要求 len(new_tasks) >= 1\",\"pass_condition\":\"至少存在一条新增 activity,其 type 字段归一化后为 'task'\"},{\"name\":\"Component 2b — Salesforce 风险任务字段\",\"weight\":0.2,\"description\":\"检查新增任务是否针对 account-1、字段正确且文本体现健康风险或使用衰退\",\"check_logic\":\"遍历 new_tasks,拼接 subject/description/comments/body 为 task_text;找到 relatedToId == 'account-1' 且 (mentions_red_or_risk(task_text) 或 mentions_usage_decline(task_text)) 的任务;再校验 current_user_is_jordan、target_account_owned_by_jordan、relatedToType 归一化后为 'account'、assignedToId == 'user-1'、status 归一化后 != 'completed'\",\"pass_condition\":\"新增任务关联 account-1、类型为 account、分配给 user-1、状态非 Completed、当前用户为 Jordan、账户所有者为 Jordan,且任务文本包含风险或使用衰退关键词\"},{\"name\":\"Component 3a — Slack 频道消息\",\"weight\":0.13,\"description\":\"检查 Jordan Rivera 是否在 acct-summit-retail 频道发送了新消息,且 acct-northstar 和 general 频道未被改动\",\"check_logic\":\"current_user_is_jordan 为真;new_records(summit_init, summit_curr, 'messageId') 非空且其中至少一条 senderId == 'user_1';new_records 对 acct-northstar 和 general 返回空列表(north_unchanged 和 general_unchanged 为真)\",\"pass_condition\":\"当前 Slack 用户为 Jordan;acct-summit-retail 频道有新增消息且由 user_1 发送;acct-northstar 和 general 频道无新增消息\"},{\"name\":\"Component 3b — Slack 消息内容\",\"weight\":0.2,\"description\":\"检查新消息是否提到 Summit、Red/风险、使用衰退,并给出下一步或负责人\",\"check_logic\":\"遍历 jordan_messages,检查 m.get('content') 同时满足 mentions_account(txt)、mentions_red_or_risk(txt)、mentions_usage_decline(txt)、has_any(txt, NEXTSTEP_KW)\",\"pass_condition\":\"消息内容经 normalize 后同时包含 Summit 相关关键词、Red/风险关键词、使用衰退关键词以及 next step/owner/action 等下一步关键词\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各子组件分数直接相加,最终通过 min(total_score, 1.0) 钳制上限为 1.0,再四舍五入保留 4 位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或为空:打印 CRITICAL 并返回 0.0\",\"从任一 mock 服务获取状态失败或 current_state 为空:打印 CRITICAL 并返回 0.0\",\"Notion 检查中当前用户非 Jordan、Summit 行未新建 Risk Note、其他行被改动:Component 1 不得分\",\"Salesforce 中未新增 task 类型活动,或新增任务字段不匹配 account-1/非 Completed/未分配 Jordan:Component 2 不得分\",\"Slack 中 acct-summit-retail 无 Jordan 的新消息,或其他频道被发送消息:Component 3 不得分\",\"各组件内部异常被捕获为 ERROR,仅影响该组件得分,不会导致整体提前退出\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话标识,失败则直接返回 0.0。随后通过 HTTP 请求向 notion_mock、salesforce_mock、slack_mock 三个服务的 /go?sid={sid} 端点拉取 initial_state 与 current_state,任一拉取失败或 current_state 为空即返回 0.0。接着进入 verify_task():Component 1 针对 Notion,检查 item-summit 的 prop-risk 是否由 Jordan 从空白填为有效内容(0.17),并验证内容包含使用衰退与 Red/流失风险语义(0.17),同时要求其余四行账户的 Risk Note 仍为空白且 CSM 未变;Component 2 针对 Salesforce,对比 activities 列表找出新增 task,至少一条新增 task 得 0.13,再验证该任务关联 account-1、类型为 account、分配给 user-1、状态非 Completed 且文本含风险/衰退语义得 0.20;Component 3 针对 Slack,检查 acct-summit-retail 频道有 Jordan 发送的新消息且 acct-northstar 与 general 频道无变动得 0.13,再验证消息内容同时提及 Summit、Red/风险、使用衰退及下一步行动得 0.20。所有子项得分累加后,以 min(total_score, 1.0) 限制上限并四舍五入到 4 位小数作为最终 REWARD。\",\"confidence\":1.0}"
76
+ }
csm_onboarding_checklist_004/_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"
csm_onboarding_checklist_004/initial_setup.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: ce_onboarding_b106
3
+ Task ID: csm_onboarding_checklist_004
4
+ Domain: mock_websites
5
+ Mocks: google_docs_mock, google_calendar_mock, gmail_mock, slack_mock (single shared sid)
6
+
7
+ Persona: You are an office worker acting as a project lead. Your tools for this task are: shared documents, the team calendar, the shared email inbox, team communications.
8
+
9
+ Environment / context (initial state + ground truth this setup establishes):
10
+ Initial environment (seeded via a single shared session id across all mocks): Google Docs with documents 'Onboarding Template'; an empty Google Calendar; Gmail inbox with 1 email(s): "Excited to get started" from sarah.j@techventures.com; Slack workspace with channels #general, #random. GROUND TRUTH — the agent earns partial credit for each checkpoint: onboarding checklist doc created (+0.15); checklist has all five steps (+0.3); cal_new_event (+0.1); training on July 1 (+0.1); gmail_new_sent (+0.05); invite emailed to champion (+0.15); invite names the date (+0.05); slack_new_msg (+0.1). Scoring is absolute over each mock's current_state; new objects exclude the seeded IDs, so an untouched environment scores 0.0 and fully completing every checkpoint scores 1.0.
11
+ """
12
+ import json
13
+ import os
14
+ import shlex
15
+ import subprocess
16
+ import time
17
+ import uuid
18
+
19
+ import requests
20
+
21
+ MOCK_URLS = {
22
+ "google_docs_mock": "http://28.7.184.198:8142",
23
+ "google_calendar_mock": "http://28.7.184.198:8141",
24
+ "gmail_mock": "http://28.7.184.198:8138",
25
+ "slack_mock": "http://28.7.184.198:8178"
26
+ }
27
+ PRIMARY_URL = 'http://28.7.184.198:8142'
28
+
29
+ sid = str(uuid.uuid4())
30
+ with open('/tmp/task_web_sid', 'w') as f:
31
+ f.write(sid)
32
+ print(f'Generated sid: {sid}')
33
+
34
+ # Full initial state for every mock involved (all required top-level keys present).
35
+ STATES = { 'google_docs_mock': { 'currentUser': { 'id': 'user-1',
36
+ 'name': 'Demo User',
37
+ 'email': 'demo@example.com',
38
+ 'avatar': ''},
39
+ 'users': [ { 'id': 'user-1',
40
+ 'name': 'Demo User',
41
+ 'email': 'demo@example.com',
42
+ 'avatar': ''},
43
+ { 'id': 'user-2',
44
+ 'name': 'Alice Chen',
45
+ 'email': 'alice@example.com',
46
+ 'avatar': ''},
47
+ { 'id': 'user-3',
48
+ 'name': 'Bob Smith',
49
+ 'email': 'bob@example.com',
50
+ 'avatar': ''}],
51
+ 'documents': { 'd-tmpl': { 'id': 'd-tmpl',
52
+ 'title': 'Onboarding Template',
53
+ 'content': '<p>tmpl</p>',
54
+ 'ownerId': 'user-1',
55
+ 'starred': False,
56
+ 'created': '2026-05-01T10:00:00Z',
57
+ 'updated': '2026-06-01T10:00:00Z',
58
+ 'sharedWith': [],
59
+ 'linkSharing': { 'enabled': False,
60
+ 'permission': 'viewer'}}},
61
+ 'comments': [],
62
+ 'ui': { 'currentDocId': None,
63
+ 'sidebarOpen': False,
64
+ 'sidebarTab': 'comments',
65
+ 'shareDialogOpen': False,
66
+ 'findReplaceOpen': False,
67
+ 'viewMode': 'editing',
68
+ 'zoom': 100,
69
+ 'documentListView': 'grid',
70
+ 'searchQuery': ''}},
71
+ 'google_calendar_mock': { 'user': { 'id': 'u1',
72
+ 'username': 'Demo User',
73
+ 'email': 'demo@example.com',
74
+ 'avatar': ''},
75
+ 'calendars': [ { 'id': 'c1',
76
+ 'name': 'Personal',
77
+ 'color': '#039BE5',
78
+ 'visible': True,
79
+ 'userId': 'u1',
80
+ 'isDefault': True},
81
+ { 'id': 'c2',
82
+ 'name': 'Work',
83
+ 'color': '#33B679',
84
+ 'visible': True,
85
+ 'userId': 'u1',
86
+ 'isDefault': False}],
87
+ 'events': [],
88
+ 'view': 'week',
89
+ 'currentDate': '2026-06-08T00:00:00.000Z',
90
+ 'sidebarOpen': True,
91
+ 'settings': { 'weekStart': 0,
92
+ 'defaultDuration': 60,
93
+ 'defaultView': 'week',
94
+ 'defaultReminder': {'type': 'popup', 'minutes': 10},
95
+ 'timeFormat': '12h',
96
+ 'showWeekNumbers': False,
97
+ 'showDeclinedEvents': False}},
98
+ 'gmail_mock': { 'user': { 'userId': 'u1',
99
+ 'username': 'John Smith',
100
+ 'email': 'john.smith@company.com',
101
+ 'avatar': ''},
102
+ 'labels': [ {'id': 'l1', 'name': 'Work', 'color': '#ef4444'},
103
+ {'id': 'l2', 'name': 'Personal', 'color': '#3b82f6'},
104
+ {'id': 'l3', 'name': 'Travel', 'color': '#22c55e'},
105
+ {'id': 'l4', 'name': 'Finance', 'color': '#eab308'}],
106
+ 'emails': [ { 'id': 'email_1',
107
+ 'threadId': 'thread_email_1',
108
+ 'from': { 'name': 'Sarah Johnson',
109
+ 'email': 'sarah.j@techventures.com',
110
+ 'avatar': ''},
111
+ 'to': [ { 'name': 'John Smith',
112
+ 'email': 'john.smith@company.com'}],
113
+ 'cc': [],
114
+ 'bcc': [],
115
+ 'subject': 'Excited to get started',
116
+ 'body': "<p>Looking forward to onboarding — when's our "
117
+ 'training?</p>',
118
+ 'snippet': "When's training?",
119
+ 'timestamp': '2026-06-08T08:15:00Z',
120
+ 'read': False,
121
+ 'starred': False,
122
+ 'important': False,
123
+ 'labels': [],
124
+ 'category': 'primary',
125
+ 'folder': 'inbox',
126
+ 'attachments': []}],
127
+ 'drafts': []},
128
+ 'slack_mock': { 'currentUser': { 'userId': 'user_1',
129
+ 'fullName': 'John Smith',
130
+ 'displayName': 'John',
131
+ 'email': 'john.smith@company.com',
132
+ 'avatar': 'https://picsum.photos/200/200?random=1',
133
+ 'title': '',
134
+ 'status': 'online',
135
+ 'statusMessage': '',
136
+ 'statusEmoji': '',
137
+ 'timeZone': 'America/New_York'},
138
+ 'workspace': { 'workspaceId': 'ws_1',
139
+ 'workspaceName': 'Acme Corp',
140
+ 'icon': ''},
141
+ 'users': [ { 'userId': 'user_1',
142
+ 'fullName': 'John Smith',
143
+ 'displayName': 'John',
144
+ 'email': 'john.smith@company.com',
145
+ 'avatar': 'https://picsum.photos/200/200?random=1',
146
+ 'title': '',
147
+ 'status': 'online',
148
+ 'statusMessage': '',
149
+ 'statusEmoji': '',
150
+ 'timeZone': 'America/New_York'},
151
+ { 'userId': 'user_2',
152
+ 'fullName': 'Sarah Johnson',
153
+ 'displayName': 'Sarah',
154
+ 'email': 'sarah.johnson@company.com',
155
+ 'avatar': 'https://picsum.photos/200/200?random=2',
156
+ 'title': '',
157
+ 'status': 'online',
158
+ 'statusMessage': '',
159
+ 'statusEmoji': '',
160
+ 'timeZone': 'America/New_York'},
161
+ { 'userId': 'user_3',
162
+ 'fullName': 'Mike Chen',
163
+ 'displayName': 'Mike',
164
+ 'email': 'mike.chen@company.com',
165
+ 'avatar': 'https://picsum.photos/200/200?random=3',
166
+ 'title': '',
167
+ 'status': 'online',
168
+ 'statusMessage': '',
169
+ 'statusEmoji': '',
170
+ 'timeZone': 'America/New_York'},
171
+ { 'userId': 'user_4',
172
+ 'fullName': 'Lisa Park',
173
+ 'displayName': 'Lisa',
174
+ 'email': 'lisa.park@company.com',
175
+ 'avatar': 'https://picsum.photos/200/200?random=4',
176
+ 'title': '',
177
+ 'status': 'online',
178
+ 'statusMessage': '',
179
+ 'statusEmoji': '',
180
+ 'timeZone': 'America/New_York'}],
181
+ 'channels': [ { 'channelId': 'general',
182
+ 'name': 'general',
183
+ 'description': 'general channel',
184
+ 'topic': '',
185
+ 'isPrivate': False,
186
+ 'isStarred': False,
187
+ 'members': ['user_1', 'user_2', 'user_3', 'user_4'],
188
+ 'createdBy': 'user_1',
189
+ 'createdAt': '2026-01-01T10:00:00Z',
190
+ 'pinnedMessages': [],
191
+ 'unreadCount': 0},
192
+ { 'channelId': 'random',
193
+ 'name': 'random',
194
+ 'description': 'random channel',
195
+ 'topic': '',
196
+ 'isPrivate': False,
197
+ 'isStarred': False,
198
+ 'members': ['user_1', 'user_2', 'user_3', 'user_4'],
199
+ 'createdBy': 'user_1',
200
+ 'createdAt': '2026-01-01T10:00:00Z',
201
+ 'pinnedMessages': [],
202
+ 'unreadCount': 0}],
203
+ 'messages': { 'general': [ { 'messageId': 'g1',
204
+ 'senderId': 'user_2',
205
+ 'content': 'did TechVentures onboarding '
206
+ 'start?',
207
+ 'timestamp': '2026-06-08T08:00:00Z',
208
+ 'threadId': None,
209
+ 'reactions': [],
210
+ 'attachments': [],
211
+ 'isEdited': False}],
212
+ 'random': []},
213
+ 'threads': {},
214
+ 'dms': [],
215
+ 'bookmarkedMessages': [],
216
+ 'callHistory': [],
217
+ 'settings': { 'theme': 'light',
218
+ 'notifications': 'all',
219
+ 'displayDensity': 'comfortable',
220
+ 'showAvatars': True,
221
+ 'use24Hour': False},
222
+ 'invitations': [],
223
+ 'notifications': []}}
224
+
225
+
226
+ def launch_gui(command, delay_sec=1.0):
227
+ env = os.environ.copy()
228
+ env['DISPLAY'] = ':0'
229
+ subprocess.Popen(shlex.split(command), stdin=subprocess.DEVNULL,
230
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
231
+ env=env, start_new_session=True)
232
+ time.sleep(delay_sec)
233
+
234
+
235
+ for name, url in MOCK_URLS.items():
236
+ resp = requests.post(f'{url}/post?sid={sid}',
237
+ json={'action': 'set', 'state': STATES[name]}, timeout=30)
238
+ assert resp.status_code == 200, f'{name} injection failed: {resp.text}'
239
+ go = requests.get(f'{url}/go?sid={sid}', timeout=10).json()
240
+ assert go.get('initial_state') is not None, f'{name} initial_state is None'
241
+ print(f'State injected: {name} sid={sid}')
242
+
243
+ # Open the PRIMARY app as the main window first, then open every other
244
+ # involved mock as an additional browser tab so the agent can see/reach all
245
+ # relevant apps (e.g. read the email in the Gmail tab AND post in Slack).
246
+ # Without this, secondary-app data is injected but has no on-screen entry
247
+ # point, and the agent wastes its budget hunting for a non-existent client.
248
+ launch_gui(f'google-chrome "{PRIMARY_URL}/?sid={sid}"', delay_sec=2.0)
249
+ print(f'GUI_READY: launched browser at {PRIMARY_URL}/?sid={sid}')
250
+ for _name, _url in MOCK_URLS.items():
251
+ if _url == PRIMARY_URL:
252
+ continue
253
+ launch_gui(f'google-chrome --new-tab "{_url}/?sid={sid}"', delay_sec=1.0)
254
+ print(f'Opened tab: {_name} at {_url}/?sid={sid}')
csm_onboarding_checklist_004/reward.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: ce_onboarding_b106
3
+ Task ID: csm_onboarding_checklist_004
4
+ Domain: mock_websites
5
+ Mocks: google_docs_mock, google_calendar_mock, gmail_mock, slack_mock
6
+ Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0):
7
+ - [0.15] onboarding checklist doc created
8
+ - [0.3] checklist has all five steps
9
+ - [0.1] cal_new_event
10
+ - [0.1] training on July 1
11
+ - [0.05] gmail_new_sent
12
+ - [0.15] invite emailed to champion
13
+ - [0.05] invite names the date
14
+ - [0.1] slack_new_msg
15
+ """
16
+ import re
17
+ import sys
18
+
19
+ import requests
20
+
21
+ MOCK_URLS = {
22
+ "google_docs_mock": "http://28.7.184.198:8142",
23
+ "google_calendar_mock": "http://28.7.184.198:8141",
24
+ "gmail_mock": "http://28.7.184.198:8138",
25
+ "slack_mock": "http://28.7.184.198:8178"
26
+ }
27
+ SEED = {
28
+ "slack_mock:general": [
29
+ "g1"
30
+ ],
31
+ "slack_mock:random": []
32
+ }
33
+
34
+ try:
35
+ with open('/tmp/task_web_sid') as f:
36
+ sid = f.read().strip()
37
+ if not sid:
38
+ raise ValueError('sid is empty')
39
+ except Exception as e:
40
+ print(f'CRITICAL: cannot read sid: {e}')
41
+ print('REWARD: 0.0')
42
+ sys.exit(0)
43
+
44
+ STATES = {}
45
+ for _name, _url in MOCK_URLS.items():
46
+ try:
47
+ _r = requests.get(f'{_url}/go?sid={sid}', timeout=15)
48
+ _r.raise_for_status()
49
+ STATES[_name] = _r.json()
50
+ except Exception as e:
51
+ print(f'CRITICAL: cannot fetch {_name}: {e}')
52
+ print('REWARD: 0.0')
53
+ sys.exit(0)
54
+
55
+
56
+ def cur(mock):
57
+ return (STATES.get(mock) or {}).get('current_state') or {}
58
+
59
+
60
+ def _lc(s):
61
+ return (s or '').lower()
62
+
63
+
64
+ total = 0.0
65
+
66
+ # c0: a new google doc titled about (onboarding checklist doc created)
67
+ c0_init = set((STATES['google_docs_mock'].get('initial_state') or {}).get('documents', {}).keys())
68
+ c0_docs = cur('google_docs_mock').get('documents') or {}
69
+ c0_new = [d for did, d in c0_docs.items() if did not in c0_init and any(t in _lc(d.get('title','')) for t in ['techventures onboarding', 'onboarding checklist'])]
70
+ if c0_new:
71
+ print('PASS: onboarding checklist doc created (0.15)')
72
+ total += 0.15
73
+ else:
74
+ print('FAIL: onboarding checklist doc created')
75
+
76
+ # c1: new google doc body (checklist has all five steps)
77
+ c1_init = set((STATES['google_docs_mock'].get('initial_state') or {}).get('documents', {}).keys())
78
+ c1_docs = cur('google_docs_mock').get('documents') or {}
79
+ c1_new = [d for did, d in c1_docs.items() if did not in c1_init and any(t in _lc(d.get('title','')) for t in ['techventures onboarding', 'onboarding checklist'])]
80
+ c1_txt = _lc(' '.join(d.get('content','') for d in c1_new))
81
+ if c1_new and all(t in c1_txt for t in ['kickoff', 'account setup', 'admin training', 'data import', 'go-live']):
82
+ print('PASS: checklist has all five steps (0.3)')
83
+ total += 0.3
84
+ else:
85
+ print('FAIL: checklist has all five steps')
86
+
87
+ # c2: a new calendar event was created
88
+ c2_init_ids = {e.get('id') for e in ((STATES['google_calendar_mock'].get('initial_state') or {}).get('events') or [])}
89
+ c2_new = [e for e in (cur('google_calendar_mock').get('events') or []) if e.get('id') not in c2_init_ids]
90
+ globals()['cal_new_events'] = c2_new
91
+ if c2_new:
92
+ print('PASS: new calendar event (0.1)')
93
+ total += 0.1
94
+ else:
95
+ print('FAIL: no new calendar event')
96
+
97
+ # c3: new event date contains '2026-07-01'
98
+ c3_new = globals().get('cal_new_events', [])
99
+ if any('2026-07-01' in (e.get('start','') or '') for e in c3_new):
100
+ print('PASS: training on July 1 (0.1)')
101
+ total += 0.1
102
+ else:
103
+ print('FAIL: training on July 1')
104
+
105
+ # c4: a new email was sent (folder sent) or saved as draft
106
+ c4_init = (STATES['gmail_mock'].get('initial_state') or {})
107
+ c4_cur = cur('gmail_mock')
108
+ c4_init_ids = {e.get('id') for e in (c4_init.get('emails') or [])}
109
+ c4_sent = [e for e in (c4_cur.get('emails') or []) if e.get('id') not in c4_init_ids and e.get('folder') in ('sent', 'drafts')]
110
+ c4_sent += [d for d in (c4_cur.get('drafts') or []) if d.get('id') not in {x.get('id') for x in (c4_init.get('drafts') or [])}]
111
+ if c4_sent:
112
+ print('PASS: new email sent/drafted (0.05)')
113
+ total += 0.05
114
+ else:
115
+ print('FAIL: no new sent/draft email')
116
+
117
+ # c5: sent/draft email addressed to (invite emailed to champion)
118
+ c5_init = (STATES['gmail_mock'].get('initial_state') or {})
119
+ c5_cur = cur('gmail_mock')
120
+ c5_init_ids = {e.get('id') for e in (c5_init.get('emails') or [])}
121
+ c5_pool = [e for e in (c5_cur.get('emails') or []) if e.get('id') not in c5_init_ids and e.get('folder') in ('sent','drafts')] + (c5_cur.get('drafts') or [])
122
+ c5_tos = _lc(' '.join(t.get('email','') for e in c5_pool for t in (e.get('to') or [])))
123
+ if any(t in c5_tos for t in ['sarah.j@techventures.com']):
124
+ print('PASS: invite emailed to champion (0.15)')
125
+ total += 0.15
126
+ else:
127
+ print('FAIL: invite emailed to champion')
128
+
129
+ # c6: sent/draft email text contains (invite names the date)
130
+ c6_init = (STATES['gmail_mock'].get('initial_state') or {})
131
+ c6_cur = cur('gmail_mock')
132
+ c6_init_ids = {e.get('id') for e in (c6_init.get('emails') or [])}
133
+ c6_pool = [e for e in (c6_cur.get('emails') or []) if e.get('id') not in c6_init_ids and e.get('folder') in ('sent','drafts')] + (c6_cur.get('drafts') or [])
134
+ c6_txt = _lc(' '.join((e.get('subject','') + ' ' + e.get('body','') + ' ' + e.get('snippet','')) for e in c6_pool))
135
+ if any(t in c6_txt for t in ['july 1', 'training']):
136
+ print('PASS: invite names the date (0.05)')
137
+ total += 0.05
138
+ else:
139
+ print('FAIL: invite names the date')
140
+
141
+ # c7: new message by user_1 in #general
142
+ c7_msgs = (cur('slack_mock').get('messages') or {}).get('general', []) or []
143
+ c7_seed = set(SEED.get('slack_mock:general', []))
144
+ c7_new = [m for m in c7_msgs if m.get('messageId') not in c7_seed and m.get('senderId') == 'user_1']
145
+ c7_blob = _lc(' '.join((m.get('content') or '') for m in c7_new))
146
+ if c7_new:
147
+ print('PASS: new message by user_1 in #general (0.1)')
148
+ total += 0.1
149
+ else:
150
+ print('FAIL: no new user_1 message in #general')
151
+
152
+ final = round(min(total, 1.0), 4)
153
+ print(f'\nScore: {total}/1.0')
154
+ print(f'REWARD: {final}')
csm_onboarding_checklist_004/reward_label.json ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/bda2b533-4396-584b-ae98-d4198dd74783/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:23:29",
7
+ "label": {
8
+ "task_id": "csm_onboarding_checklist_004",
9
+ "domain": "mock_websites",
10
+ "summary": "验证新员工入职流程是否完成,包括创建入职清单文档、安排7月1日培训日历事件、发送邀请邮件给负责人以及在Slack发布通知",
11
+ "is_placeholder": false,
12
+ "data_sources": [
13
+ "/tmp/task_web_sid",
14
+ "google_docs_mock",
15
+ "google_calendar_mock",
16
+ "gmail_mock",
17
+ "slack_mock"
18
+ ],
19
+ "scoring_components": [
20
+ {
21
+ "name": "Component 0",
22
+ "weight": 0.15,
23
+ "description": "创建入职清单文档",
24
+ "check_logic": "对比 google_docs_mock 的 initial_state 与 current_state 中的 documents,找出新增文档,检查其 title(转小写后)是否包含 'techventures onboarding' 或 'onboarding checklist'",
25
+ "pass_condition": "存在新增的 Google Doc,且标题包含指定关键词"
26
+ },
27
+ {
28
+ "name": "Component 1",
29
+ "weight": 0.3,
30
+ "description": "清单包含全部五个步骤",
31
+ "check_logic": "在 Component 0 筛选出的新文档中,提取 content 转小写后的文本,检查是否同时包含 'kickoff'、'account setup'、'admin training'、'data import'、'go-live'",
32
+ "pass_condition": "新文档内容同时包含五个指定关键词"
33
+ },
34
+ {
35
+ "name": "Component 2",
36
+ "weight": 0.1,
37
+ "description": "创建新的日历事件",
38
+ "check_logic": "对比 google_calendar_mock 的 initial_state 与 current_state 中的 events,通过 event id 判断是否有新增事件",
39
+ "pass_condition": "存在新增的日历事件"
40
+ },
41
+ {
42
+ "name": "Component 3",
43
+ "weight": 0.1,
44
+ "description": "培训安排在7月1日",
45
+ "check_logic": "在 Component 2 识别出的新事件中,检查任意事件的 start 字段是否包含 '2026-07-01'",
46
+ "pass_condition": "新增事件的 start 字段包含 '2026-07-01'"
47
+ },
48
+ {
49
+ "name": "Component 4",
50
+ "weight": 0.05,
51
+ "description": "发送或起草新邮件",
52
+ "check_logic": "对比 gmail_mock 的 initial_state 与 current_state,找出 id 不在初始集合中且 folder 为 'sent' 或 'drafts' 的邮件,或 current_state drafts 中新增的草稿",
53
+ "pass_condition": "存在新增的已发送或草稿邮件"
54
+ },
55
+ {
56
+ "name": "Component 5",
57
+ "weight": 0.15,
58
+ "description": "向负责人发送邀请邮件",
59
+ "check_logic": "在 Component 4 的邮件池(sent/drafts 新增邮件 + 所有 current drafts)中,提取所有 to 字段中的 email 地址转小写后,检查是否包含 'sarah.j@techventures.com'",
60
+ "pass_condition": "邮件收件人包含 'sarah.j@techventures.com'"
61
+ },
62
+ {
63
+ "name": "Component 6",
64
+ "weight": 0.05,
65
+ "description": "邮件中注明日期",
66
+ "check_logic": "在 Component 4 的邮件池中,将 subject、body、snippet 拼接转小写,检查是否包含 'july 1' 或 'training'",
67
+ "pass_condition": "邮件文本包含 'july 1' 或 'training'"
68
+ },
69
+ {
70
+ "name": "Component 7",
71
+ "weight": 0.1,
72
+ "description": "在 Slack #general 频道发送新消息",
73
+ "check_logic": "检查 slack_mock current_state 中 messages.general 列表,排除 SEED 中预置的 messageId,筛选 senderId 为 'user_1' 的新消息",
74
+ "pass_condition": "存在 senderId 为 'user_1' 且不在初始种子中的新消息"
75
+ }
76
+ ],
77
+ "total_max_score": 1.0,
78
+ "score_aggregation": "各组件分数相加,最后通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数",
79
+ "failure_modes": [
80
+ "无法读取 /tmp/task_web_sid 或 sid 为空时,打印 CRITICAL 并返回 0.0 退出",
81
+ "任一模 mock 服务(google_docs_mock、google_calendar_mock、gmail_mock、slack_mock)状态拉取失败时,打印 CRITICAL 并返回 0.0 退出",
82
+ "各评分组件检查失败仅导致该组件不得分,不会提前退出"
83
+ ],
84
+ "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向四个 mock 服务(google_docs_mock、google_calendar_mock、gmail_mock、slack_mock)拉取 current_state。接着按顺序执行 8 个评分组件:1)检查是否新建了标题含 onboarding 关键词的 Google Doc;2)检查该文档内容是否包含五个指定步骤关键词;3)检查 Google Calendar 是否有新增事件;4)检查新增事件是否安排在 2026-07-01;5)检查 Gmail 是否有新增的 sent/drafts 邮件;6)检查邮件是否发送给 sarah.j@techventures.com;7)���查邮件主题或正文是否提到 july 1 或 training;8)检查 Slack #general 频道是否有 user_1 发送的新消息。每个组件独立判断,通过则累加对应分值,最终总分经 min(total, 1.0) 钳制并四舍五入后输出。",
85
+ "confidence": 1.0
86
+ },
87
+ "raw_response": "用户要求我分析一个 reward.py 评分脚本,并输出一个严格的 JSON 对象,不要有任何额外文字。\n\n让我仔细阅读代码:\n\n1. 任务 ID: 从 docstring 中提取 `ce_onboarding_b106`,但文件路径中的 UUID 是 `bda2b533-4396-584b-ae98-d4198dd74783`。docstring 中明确写了 `Task ID: bda2b533-4396-584b-ae98-d4198dd74783`,所以 task_id 应该是这个 UUID。等等,docstring 第一行是 `Reward Script: ce_onboarding_b106`,但后面有 `Task ID: bda2b533-4396-584b-ae98-d4198dd74783`。根据要求\"从文件 docstring 中提取的任务 ID\",应该提取 `bda2b533-4396-584b-ae98-d4198dd74783`。\n\n2. Domain: `mock_websites`\n\n3. 数据源: `google_docs_mock`, `google_calendar_mock`, `gmail_mock`, `slack_mock`,以及 `/tmp/task_web_sid`\n\n4. 评分组件:\n - c0: 0.15 - onboarding checklist doc created - 检查新创建的 google doc 标题包含 'techventures onboarding' 或 'onboarding checklist'\n - c1: 0.3 - checklist has all five steps - 检查新 doc 内容包含 'kickoff', 'account setup', 'admin training', 'data import', 'go-live'\n - c2: 0.1 - cal_new_event - 检查 google calendar 有新事件\n - c3: 0.1 - training on July 1 - 检查新事件 start 包含 '2026-07-01'\n - c4: 0.05 - gmail_new_sent - 检查 gmail 有新 sent 或 draft 邮件\n - c5: 0.15 - invite emailed to champion - 检查邮件 to 包含 'sarah.j@techventures.com'\n - c6: 0.05 - invite names the date - 检查邮件 subject/body/snippet 包含 'july 1' 或 'training'\n - c7: 0.1 - slack_new_msg - 检查 slack #general 有新消息,senderId 为 'user_1'\n\n5. 总分计算: 各项相加,最后 `round(min(total, 1.0), 4)`\n\n6. 失败模式:\n - 读取 sid 失败 -> 0.0 退出\n - 获取 mock 状态失败 -> 0.0 退出\n - 各组件检查失败只是不加分,不会提前退出\n\n7. is_placeholder: false,因为脚本有实际检查逻辑。\n\n8. confidence: 1.0,因为逻辑清晰。\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"bda2b533-4396-584b-ae98-d4198dd74783\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证新员工入职流程是否完成,包括创建入职清单文档、安排培训日历事件、发送邀请邮件给负责人以及在Slack发布通知\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"google_docs_mock\", \"google_calendar_mock\", \"gmail_mock\", \"slack_mock\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 0\",\n \"weight\": 0.15,\n \"description\": \"创建入职清单文档\",\n \"check_logic\": \"对比 initial_state 与 current_state 中的 documents,找出新增文档,检查其 title(转小写后)是否包含 'techventures onboarding' 或 'onboarding checklist'\",\n \"pass_condition\": \"存在新增的 Google Doc,且标题包含指定关键词\"\n },\n {\n \"name\": \"Component 1\",\n \"weight\": 0.3,\n \"description\": \"清单包含全部五个步骤\",\n \"check_logic\": \"在 Component 0 筛选出的新文档中,提取 content 转小写后的文本,检查是否同时包含 'kickoff'、'account setup'、'admin training'、'data import'、'go-live'\",\n \"pass_condition\": \"新文档内容同时包含五个指定关键词\"\n },\n {\n \"name\": \"Component 2\",\n \"weight\": 0.1,\n \"description\": \"创建新的日历事件\",\n \"check_logic\": \"对比 google_calendar_mock 的 initial_state 与 current_state 中的 events,通过 event id 判断是否有新增事件\",\n \"pass_condition\": \"存在新增的日历事件\"\n },\n {\n \"name\": \"Component 3\",\n \"weight\": 0.1,\n \"description\": \"培训安排在7月1日\",\n \"check_logic\": \"在 Component 2 识别出的新事件中,检查任意事件的 start 字段是否包含 '2026-07-01'\",\n \"pass_condition\": \"新增事件的 start 字段包含 '2026-07-01'\"\n },\n {\n \"name\": \"Component 4\",\n \"weight\": 0.05,\n \"description\": \"发送或起草新邮件\",\n \"check_logic\": \"对比 gmail_mock 的 initial_state 与 current_state,找出 id 不在初始集合中且 folder 为 'sent' 或 'drafts' 的邮件,或 current_state drafts 中新增的草稿\",\n \"pass_condition\": \"存在新增的已发送或草稿邮件\"\n },\n {\n \"name\": \"Component 5\",\n \"weight\": 0.15,\n \"description\": \"向负责人发送邀请邮件\",\n \"check_logic\": \"在 Component 4 的邮件池(sent/drafts 新增邮件 + 所有 current drafts)中,提取所有 to 字段中的 email 地址转小写后,检查是否包含 'sarah.j@techventures.com'\",\n \"pass_condition\": \"邮件收件人包含 'sarah.j@techventures.com'\"\n },\n {\n \"name\": \"Component 6\",\n \"weight\": 0.05,\n \"description\": \"邮件中注明日期\",\n \"check_logic\": \"在 Component 4 的邮件池中,将 subject、body、snippet 拼接转小写,检查是否包含 'july 1' 或 'training'\",\n \"pass_condition\": \"邮件文本包含 'july 1' 或 'training'\"\n },\n {\n \"name\": \"Component 7\",\n \"weight\": 0.1,\n \"description\": \"在 Slack #general 频道发送新消息\",\n \"check_logic\": \"检查 slack_mock current_state 中 messages.general 列表,排除 SEED 中预置的 messageId,筛选 senderId 为 'user_1' 的新消息\",\n \"pass_condition\": \"存在 senderId 为 'user_1' 且不在初始种子中的新消息\"\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 为空时,打印 CRITICAL 并返回 0.0 退出\",\n \"任一模 mock 服务(google_docs_mock、google_calendar_mock、gmail_mock、slack_mock)状态拉取失败时,打印 CRITICAL 并返回 0.0 退出\",\n \"各评分组件检查失败仅导致该组件不得分,不会提前退出\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向四个 mock 服务(google_docs_mock、google_calendar_mock、gmail_mock、slack_mock)拉取 current_state。接着按顺序执行 8 个评分组件:1)检查是否新建了标题含 onboarding 关键词的 Google Doc;2)检查该文档内容是否包含五个指定步骤关键词;3)检查 Google Calendar 是否有新增事件;4)检查新增事件是否安排在 2026-07-01;5)检查 Gmail 是否有新增的 sent/drafts 邮件;6)检查邮件是否发送给 sarah.j@techventures.com;7)检查邮件主题或正文是否提到 july 1 或 training;8)检查 Slack #general 频道是否有 user_1 发送的新消息。每个组件独立判断,通过则累加对应分值,最终总分经 min(total, 1.0) 钳制并四舍五入后输出。\",\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确认 task_id:docstring 中明确写了 `Task ID: bda2b533-4396-584b-ae98-d4198dd74783`,所以用这个。\n\n确认 domain:`mock_websites`。\n\n确认 data_sources:包含 `/tmp/task_web_sid` 和四个 mock。\n\n确认 total_max_score:1.0。\n\n确认 score_aggregation:代码中是 `round(min(total, 1.0), 4)`,所以是相加后钳制到上限。\n\n确认 failure_modes:sid 读取失败、mock 拉取失败都会 sys.exit(0) 并打印 REWARD: 0.0。\n\n一切看起来正确。 </think> {\n \"task_id\": \"bda2b533-4396-584b-ae98-d4198dd74783\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证新员工入职流程是否完成,包括创建入职清单文档、安排7月1日培训日历事件、发送邀请邮件给负责人以及在Slack发布通知\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"google_docs_mock\", \"google_calendar_mock\", \"gmail_mock\", \"slack_mock\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 0\",\n \"weight\": 0.15,\n \"description\": \"创建入职清单文档\",\n \"check_logic\": \"对比 google_docs_mock 的 initial_state 与 current_state 中的 documents,找出新增文档,检查其 title(转小写后)是否包含 'techventures onboarding' 或 'onboarding checklist'\",\n \"pass_condition\": \"存在新增的 Google Doc,且标题包含指定关键词\"\n },\n {\n \"name\": \"Component 1\",\n \"weight\": 0.3,\n \"description\": \"清单包含全部五个步骤\",\n \"check_logic\": \"在 Component 0 筛选出的新文档中,提取 content 转小写后的文本,检查是否同时包含 'kickoff'、'account setup'、'admin training'、'data import'、'go-live'\",\n \"pass_condition\": \"新文档内容同时包含五个指定关键词\"\n },\n {\n \"name\": \"Component 2\",\n \"weight\": 0.1,\n \"description\": \"创建新的日历事件\",\n \"check_logic\": \"对比 google_calendar_mock 的 initial_state 与 current_state 中的 events,通过 event id 判断是否有新增事件\",\n \"pass_condition\": \"存在新增的日历事件\"\n },\n {\n \"name\": \"Component 3\",\n \"weight\": 0.1,\n \"description\": \"培训安排在7月1日\",\n \"check_logic\": \"在 Component 2 识别出的新事件中,检查任意事件的 start 字段是否包含 '2026-07-01'\",\n \"pass_condition\": \"新增事件的 start 字段包含 '2026-07-01'\"\n },\n {\n \"name\": \"Component 4\",\n \"weight\": 0.05,\n \"description\": \"发送或起草新邮件\",\n \"check_logic\": \"对比 gmail_mock 的 initial_state 与 current_state,找出 id 不在初始集合中且 folder 为 'sent' 或 'drafts' 的邮件,或 current_state drafts 中新增的草稿\",\n \"pass_condition\": \"存在新增的已发送或草稿邮件\"\n },\n {\n \"name\": \"Component 5\",\n \"weight\": 0.15,\n \"description\": \"向负责人发送邀请邮件\",\n \"check_logic\": \"在 Component 4 的邮件池(sent/drafts 新增邮件 + 所有 current drafts)中,提取所有 to 字段中的 email 地址转小写后,检查是否包含 'sarah.j@techventures.com'\",\n \"pass_condition\": \"邮件收件人包含 'sarah.j@techventures.com'\"\n },\n {\n \"name\": \"Component 6\",\n \"weight\": 0.05,\n \"description\": \"邮件中注明日期\",\n \"check_logic\": \"在 Component 4 的邮件池中,将 subject、body、snippet 拼接转小写,检查是否包含 'july 1' 或 'training'\",\n \"pass_condition\": \"邮件文本包含 'july 1' 或 'training'\"\n },\n {\n \"name\": \"Component 7\",\n \"weight\": 0.1,\n \"description\": \"在 Slack #general 频道发送新消息\",\n \"check_logic\": \"检查 slack_mock current_state 中 messages.general 列表,排除 SEED 中预置的 messageId,筛选 senderId 为 'user_1' 的新消息\",\n \"pass_condition\": \"存在 senderId 为 'user_1' 且不在初始种子中的新消息\"\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 为空时,打印 CRITICAL 并返回 0.0 退出\",\n \"任一模 mock 服务(google_docs_mock、google_calendar_mock、gmail_mock、slack_mock)状态拉取失败时,打印 CRITICAL 并返回 0.0 退出\",\n \"各评分组件检查失败仅导致该组件不得分,不会提前退出\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向四个 mock 服务(google_docs_mock、google_calendar_mock、gmail_mock、slack_mock)拉取 current_state。接着按顺序执行 8 个评分组件:1)检查是否新建了标题含 onboarding 关键词的 Google Doc;2)检查该文档内容是否包含五个指定步骤关键词;3)检查 Google Calendar 是否有新增事件;4)检查新增事件是否安排在 2026-07-01;5)检查 Gmail 是否有新增的 sent/drafts 邮件;6)检查邮件是否发送给 sarah.j@techventures.com;7)检查邮件主题或正文是否提到 july 1 或 training;8)检查 Slack #general 频道是否有 user_1 发送的新消息。每个组件独立判断,通过则累加对应分值,最终总分经 min(total, 1.0) 钳制并四舍五入后输出。\",\n \"confidence\": 1.0\n}"
88
+ }
csm_qbr_renewal_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"
csm_qbr_renewal_003/initial_setup.py ADDED
@@ -0,0 +1,760 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: CSM renewal QBR prep for Aspen Dynamics
194
+ Task ID: csm_qbr_renewal_003
195
+ Domain: mock_websites
196
+ Mocks: notion_mock, salesforce_mock, docusign_mock, gmail_mock
197
+
198
+ INITIAL STATE (pre-task):
199
+ - Notion: Jordan Rivera workspace with a 'Customer Health Tracker' database that
200
+ holds an 'Aspen Dynamics' row (Health Yellow, MAU Trend Flat, ARR 90000, usage
201
+ notes). NO QBR agenda page exists yet.
202
+ - Salesforce: CSM Jordan Rivera (user-1, Customer Success). account-1 'Aspen
203
+ Dynamics' (Customer), contact-1 'Daniel Brooks' primary contact, opp-1
204
+ 'Aspen Dynamics - FY27 Renewal' at stage 'Qualification'. Default activities
205
+ exist but NO QBR event for Aspen; the runtime "this Friday" 14:00-14:45
206
+ slot is free.
207
+ - DocuSign: CSM Jordan Rivera (Northwind Cloud). env_1 DRAFT 'Aspen Dynamics -
208
+ FY27 Renewal Agreement' with signer Daniel Brooks (status created). Distractor
209
+ env_2 DRAFT for a different customer.
210
+ - Gmail: Jordan Rivera (u1). Inbox has unrelated mail; drafts empty; NO sent
211
+ email to daniel.brooks@aspendynamics.com.
212
+ """
213
+ import os
214
+ import shlex
215
+ import subprocess
216
+ import time
217
+ import uuid
218
+ from datetime import date, timedelta
219
+
220
+ import requests
221
+
222
+ # Current mock deployments are reachable directly from the VM.
223
+ print('Network mode: direct')
224
+
225
+
226
+ def http_post(url, payload):
227
+ return requests.post(url, json=payload, timeout=30)
228
+
229
+
230
+ def http_get(url):
231
+ return requests.get(url, timeout=30)
232
+
233
+
234
+ # --- Config ---
235
+ NOTION_URL = 'http://28.7.184.198:8166'
236
+ SALESFORCE_URL = 'http://28.7.184.198:8175'
237
+ DOCUSIGN_URL = 'http://28.7.184.198:8130'
238
+ GMAIL_URL = 'http://28.7.184.198:8138'
239
+
240
+
241
+ def this_friday(today):
242
+ days_until_friday = (4 - today.weekday()) % 7
243
+ return today + timedelta(days=days_until_friday)
244
+
245
+
246
+ def fmt_month_day_year(d):
247
+ return f'{d.strftime("%b")} {d.day}, {d.year}'
248
+
249
+
250
+ TODAY = date.today()
251
+ TARGET_QBR_DATE = this_friday(TODAY)
252
+ TARGET_QBR_START = f'{TARGET_QBR_DATE.isoformat()}T14:00'
253
+ TARGET_QBR_END = f'{TARGET_QBR_DATE.isoformat()}T14:45'
254
+ RENEWAL_DATE = TODAY + timedelta(days=45)
255
+
256
+ sid = str(uuid.uuid4())
257
+ with open('/tmp/task_web_sid', 'w') as f:
258
+ f.write(sid)
259
+ with open('/tmp/task_qbr_date', 'w') as f:
260
+ f.write(TARGET_QBR_DATE.isoformat())
261
+ print(f'Generated sid={sid}')
262
+ print(f'Target QBR date={TARGET_QBR_DATE.isoformat()}')
263
+
264
+
265
+ # ---------------------------------------------------------------------------
266
+ # NOTION STATE — Customer Health Tracker database with Aspen Dynamics row.
267
+ # NO QBR agenda page yet.
268
+ # ---------------------------------------------------------------------------
269
+ def build_notion_state():
270
+ user = {
271
+ "id": "user-1",
272
+ "name": "Jordan Rivera",
273
+ "email": "jordan.rivera@northwindcloud.com",
274
+ "avatar": "",
275
+ }
276
+ workspace = {
277
+ "id": "ws-1",
278
+ "name": "Northwind Cloud — Customer Success",
279
+ "icon": "",
280
+ "members": ["user-1"],
281
+ }
282
+
283
+ # Database properties (column definitions)
284
+ db_props = [
285
+ {"id": "prop-name", "name": "Account", "type": "text"},
286
+ {"id": "prop-health", "name": "Health", "type": "select",
287
+ "options": ["Green", "Yellow", "Red"]},
288
+ {"id": "prop-mau", "name": "MAU Trend", "type": "select",
289
+ "options": ["Up", "Flat", "Down"]},
290
+ {"id": "prop-arr", "name": "ARR", "type": "text"},
291
+ {"id": "prop-notes", "name": "Usage Notes", "type": "text"},
292
+ ]
293
+
294
+ # Database rows (each is its own page referenced from items[])
295
+ row_aspen = {
296
+ "id": "row-aspen",
297
+ "title": "Aspen Dynamics",
298
+ "icon": "",
299
+ "cover": None,
300
+ "parentId": "db-health",
301
+ "blockIds": [],
302
+ "favorite": False,
303
+ "createdDate": "2026-04-02T00:00:00.000Z",
304
+ "lastEditedDate": "2026-06-18T00:00:00.000Z",
305
+ "properties": {
306
+ "prop-name": "Aspen Dynamics",
307
+ "prop-health": "Yellow",
308
+ "prop-mau": "Flat",
309
+ "prop-arr": "90000",
310
+ "prop-notes": "Adoption of reporting module up; admin seats underused; "
311
+ "one open escalation last quarter (since resolved). Renewal "
312
+ f"FY27 due {fmt_month_day_year(RENEWAL_DATE)}; champion is Daniel Brooks "
313
+ "(VP Customer Operations).",
314
+ },
315
+ }
316
+ row_orion = {
317
+ "id": "row-orion",
318
+ "title": "Orion Retail Group",
319
+ "icon": "",
320
+ "cover": None,
321
+ "parentId": "db-health",
322
+ "blockIds": [],
323
+ "favorite": False,
324
+ "createdDate": "2026-03-11T00:00:00.000Z",
325
+ "lastEditedDate": "2026-06-10T00:00:00.000Z",
326
+ "properties": {
327
+ "prop-name": "Orion Retail Group",
328
+ "prop-health": "Green",
329
+ "prop-mau": "Up",
330
+ "prop-arr": "145000",
331
+ "prop-notes": "Strong expansion last quarter; two new teams onboarded.",
332
+ },
333
+ }
334
+ row_meridian = {
335
+ "id": "row-meridian",
336
+ "title": "Meridian Logistics",
337
+ "icon": "",
338
+ "cover": None,
339
+ "parentId": "db-health",
340
+ "blockIds": [],
341
+ "favorite": False,
342
+ "createdDate": "2026-02-20T00:00:00.000Z",
343
+ "lastEditedDate": "2026-05-29T00:00:00.000Z",
344
+ "properties": {
345
+ "prop-name": "Meridian Logistics",
346
+ "prop-health": "Red",
347
+ "prop-mau": "Down",
348
+ "prop-arr": "60000",
349
+ "prop-notes": "Usage declining; sponsor left in April. At-risk renewal.",
350
+ },
351
+ }
352
+
353
+ db_health = {
354
+ "id": "db-health",
355
+ "title": "Customer Health Tracker",
356
+ "icon": "",
357
+ "cover": None,
358
+ "parentId": None,
359
+ "type": "database",
360
+ "viewType": "table",
361
+ "properties": db_props,
362
+ "views": [
363
+ {"id": "view-1", "name": "All Accounts", "type": "table",
364
+ "filters": [], "sorts": [], "groupBy": None,
365
+ "visibleProperties": ["prop-name", "prop-health", "prop-mau",
366
+ "prop-arr", "prop-notes"]},
367
+ ],
368
+ "items": ["row-aspen", "row-orion", "row-meridian"],
369
+ "blockIds": [],
370
+ "favorite": True,
371
+ "createdDate": "2026-02-01T00:00:00.000Z",
372
+ }
373
+
374
+ # A plain notes page (distractor / realism) — not a QBR agenda.
375
+ block_team_1 = {
376
+ "id": "blk-team-1", "type": "heading-2",
377
+ "content": "Standing Items",
378
+ "properties": {}, "createdDate": "2026-06-01T00:00:00.000Z",
379
+ "lastEditedDate": "2026-06-01T00:00:00.000Z",
380
+ }
381
+ block_team_2 = {
382
+ "id": "blk-team-2", "type": "bullet-list",
383
+ "content": "Review at-risk accounts weekly; keep ARR figures in sync with Salesforce.",
384
+ "properties": {}, "createdDate": "2026-06-01T00:00:00.000Z",
385
+ "lastEditedDate": "2026-06-01T00:00:00.000Z",
386
+ }
387
+ page_team = {
388
+ "id": "page-team-notes",
389
+ "title": "CS Team Notes",
390
+ "icon": "",
391
+ "cover": None,
392
+ "parentId": None,
393
+ "blockIds": ["blk-team-1", "blk-team-2"],
394
+ "favorite": False,
395
+ "createdDate": "2026-06-01T00:00:00.000Z",
396
+ "lastEditedDate": "2026-06-01T00:00:00.000Z",
397
+ "properties": {},
398
+ }
399
+
400
+ return {
401
+ "user": user,
402
+ "workspace": workspace,
403
+ "pages": {
404
+ "db-health": db_health,
405
+ "row-aspen": row_aspen,
406
+ "row-orion": row_orion,
407
+ "row-meridian": row_meridian,
408
+ "page-team-notes": page_team,
409
+ },
410
+ "blocks": {
411
+ "blk-team-1": block_team_1,
412
+ "blk-team-2": block_team_2,
413
+ },
414
+ "trash": [],
415
+ "comments": {},
416
+ "settings": {"appearance": "light", "startWeekMonday": False, "fontSize": "default"},
417
+ "notifications": [],
418
+ "pageOrder": ["db-health", "page-team-notes"],
419
+ "focusBlockId": None,
420
+ }
421
+
422
+
423
+ # ---------------------------------------------------------------------------
424
+ # SALESFORCE STATE — Aspen Dynamics renewal opportunity at Qualification.
425
+ # ---------------------------------------------------------------------------
426
+ def build_salesforce_state():
427
+ jordan = {
428
+ "userId": "user-1",
429
+ "firstName": "Jordan",
430
+ "lastName": "Rivera",
431
+ "email": "jordan.rivera@northwindcloud.com",
432
+ "phone": "(555) 410-2200",
433
+ "title": "Customer Success Manager",
434
+ "department": "Customer Success",
435
+ "role": "CSM",
436
+ "avatar": "https://i.pravatar.cc/150?u=user-1",
437
+ "timezone": "America/New_York",
438
+ "locale": "en-US",
439
+ "theme": "lightning",
440
+ }
441
+ users = [
442
+ jordan,
443
+ {"userId": "user-2", "firstName": "Priya", "lastName": "Nair",
444
+ "email": "priya.nair@northwindcloud.com", "phone": "(555) 410-2201",
445
+ "title": "Director, Customer Success", "department": "Customer Success",
446
+ "role": "Director", "avatar": "https://i.pravatar.cc/150?u=user-2",
447
+ "timezone": "America/New_York", "locale": "en-US", "theme": "lightning"},
448
+ {"userId": "user-3", "firstName": "Marcus", "lastName": "Webb",
449
+ "email": "marcus.webb@northwindcloud.com", "phone": "(555) 410-2202",
450
+ "title": "Account Executive", "department": "Sales",
451
+ "role": "AE", "avatar": "https://i.pravatar.cc/150?u=user-3",
452
+ "timezone": "America/Chicago", "locale": "en-US", "theme": "lightning"},
453
+ ]
454
+
455
+ accounts = [
456
+ {"accountId": "account-1", "name": "Aspen Dynamics", "type": "Customer",
457
+ "industry": "Technology", "revenue": 38000000, "employees": 260, "ownerId": "user-1",
458
+ "phone": "(720) 555-0133", "website": "https://www.aspendynamics.example.com",
459
+ "billingStreet": "1450 Market St", "billingCity": "Denver", "billingState": "CO",
460
+ "billingZip": "80202", "billingCountry": "USA",
461
+ "shippingStreet": "1450 Market St", "shippingCity": "Denver", "shippingState": "CO",
462
+ "shippingZip": "80202", "shippingCountry": "USA",
463
+ "createdDate": "2024-03-15T00:00:00.000Z", "modifiedDate": "2026-06-10T00:00:00.000Z"},
464
+ {"accountId": "account-2", "name": "Orion Retail Group", "type": "Customer",
465
+ "industry": "Retail", "revenue": 82000000, "employees": 610, "ownerId": "user-1",
466
+ "phone": "(415) 555-0188", "website": "https://www.orionretail.example.com",
467
+ "billingStreet": "55 Mission St", "billingCity": "San Francisco", "billingState": "CA",
468
+ "billingZip": "94105", "billingCountry": "USA",
469
+ "shippingStreet": "55 Mission St", "shippingCity": "San Francisco", "shippingState": "CA",
470
+ "shippingZip": "94105", "shippingCountry": "USA",
471
+ "createdDate": "2023-09-01T00:00:00.000Z", "modifiedDate": "2026-05-22T00:00:00.000Z"},
472
+ {"accountId": "account-3", "name": "Meridian Logistics", "type": "Customer",
473
+ "industry": "Logistics", "revenue": 41000000, "employees": 300, "ownerId": "user-1",
474
+ "phone": "(312) 555-0144", "website": "https://www.meridianlogistics.example.com",
475
+ "billingStreet": "200 Wacker Dr", "billingCity": "Chicago", "billingState": "IL",
476
+ "billingZip": "60606", "billingCountry": "USA",
477
+ "shippingStreet": "200 Wacker Dr", "shippingCity": "Chicago", "shippingState": "IL",
478
+ "shippingZip": "60606", "shippingCountry": "USA",
479
+ "createdDate": "2024-01-12T00:00:00.000Z", "modifiedDate": "2026-04-30T00:00:00.000Z"},
480
+ ]
481
+
482
+ contacts = [
483
+ {"contactId": "contact-1", "accountId": "account-1", "firstName": "Daniel",
484
+ "lastName": "Brooks", "title": "VP Customer Operations", "department": "Operations",
485
+ "email": "daniel.brooks@aspendynamics.com", "phone": "(720) 555-0134",
486
+ "ownerId": "user-1"},
487
+ {"contactId": "contact-2", "accountId": "account-2", "firstName": "Lena",
488
+ "lastName": "Ortiz", "title": "Director of IT", "department": "IT",
489
+ "email": "lena.ortiz@orionretail.example.com", "phone": "(415) 555-0189",
490
+ "ownerId": "user-1"},
491
+ {"contactId": "contact-3", "accountId": "account-3", "firstName": "Greg",
492
+ "lastName": "Halloran", "title": "Operations Manager", "department": "Operations",
493
+ "email": "greg.halloran@meridianlogistics.example.com", "phone": "(312) 555-0145",
494
+ "ownerId": "user-1"},
495
+ ]
496
+
497
+ opportunities = [
498
+ {"opportunityId": "opp-1", "name": "Aspen Dynamics — FY27 Renewal",
499
+ "accountId": "account-1", "contactId": "contact-1", "amount": 90000,
500
+ "closeDate": RENEWAL_DATE.isoformat(), "stage": "Qualification", "probability": 30,
501
+ "ownerId": "user-1", "type": "Renewal",
502
+ "createdDate": "2026-05-15T00:00:00.000Z", "modifiedDate": "2026-06-12T00:00:00.000Z"},
503
+ {"opportunityId": "opp-2", "name": "Orion Retail Group — Expansion",
504
+ "accountId": "account-2", "contactId": "contact-2", "amount": 60000,
505
+ "closeDate": "2026-09-30", "stage": "Proposal", "probability": 60,
506
+ "ownerId": "user-1", "type": "Upsell",
507
+ "createdDate": "2026-04-20T00:00:00.000Z", "modifiedDate": "2026-06-05T00:00:00.000Z"},
508
+ {"opportunityId": "opp-3", "name": "Meridian Logistics — FY27 Renewal",
509
+ "accountId": "account-3", "contactId": "contact-3", "amount": 60000,
510
+ "closeDate": "2026-07-31", "stage": "Negotiation", "probability": 50,
511
+ "ownerId": "user-1", "type": "Renewal",
512
+ "createdDate": "2026-03-10T00:00:00.000Z", "modifiedDate": "2026-06-08T00:00:00.000Z"},
513
+ ]
514
+
515
+ # Default activities for the CSM: none is an Aspen QBR event, and none
516
+ # occupies the runtime "this Friday" 14:00-14:45 slot.
517
+ activities = [
518
+ {"activityId": "activity-1", "type": "task",
519
+ "subject": "Follow up on Orion expansion proposal",
520
+ "status": "Open", "priority": "Normal", "dueDate": "2026-06-25",
521
+ "relatedToType": "opportunity", "relatedToId": "opp-2", "assignedToId": "user-1"},
522
+ {"activityId": "activity-2", "type": "task",
523
+ "subject": "Prepare Meridian recovery plan",
524
+ "status": "Open", "priority": "High", "dueDate": "2026-06-29",
525
+ "relatedToType": "account", "relatedToId": "account-3", "assignedToId": "user-1"},
526
+ {"activityId": "activity-3", "type": "event",
527
+ "subject": "Weekly CS team sync",
528
+ "status": "Open", "priority": "Normal",
529
+ "startDateTime": f"{TARGET_QBR_DATE.isoformat()}T10:00",
530
+ "endDateTime": f"{TARGET_QBR_DATE.isoformat()}T10:30",
531
+ "relatedToType": "account", "relatedToId": "account-2", "assignedToId": "user-1"},
532
+ {"activityId": "activity-4", "type": "event",
533
+ "subject": "Orion quarterly check-in",
534
+ "status": "Open", "priority": "Normal",
535
+ "startDateTime": f"{(TARGET_QBR_DATE - timedelta(days=1)).isoformat()}T16:00",
536
+ "endDateTime": f"{(TARGET_QBR_DATE - timedelta(days=1)).isoformat()}T16:30",
537
+ "relatedToType": "account", "relatedToId": "account-2", "assignedToId": "user-1"},
538
+ ]
539
+
540
+ return {
541
+ "user": jordan,
542
+ "users": users,
543
+ "leads": [],
544
+ "accounts": accounts,
545
+ "contacts": contacts,
546
+ "opportunities": opportunities,
547
+ "cases": [],
548
+ "activities": activities,
549
+ "chatterPosts": [],
550
+ "files": [],
551
+ "following": ["user-2", "user-3"],
552
+ "recentlyViewed": [],
553
+ "dismissedNotifications": [],
554
+ }
555
+
556
+
557
+ # ---------------------------------------------------------------------------
558
+ # DOCUSIGN STATE — draft renewal agreement (env_1) + distractor draft (env_2).
559
+ # ---------------------------------------------------------------------------
560
+ def build_docusign_state():
561
+ user = {
562
+ "id": "user_1",
563
+ "name": "Jordan Rivera",
564
+ "email": "jordan.rivera@northwindcloud.com",
565
+ "title": "Customer Success Manager",
566
+ "company": "Northwind Cloud",
567
+ "avatar": "",
568
+ "memberSince": "2024-01-10",
569
+ "settings": {"defaultReminderDays": 3, "defaultExpirationDays": 120,
570
+ "timezone": "America/New_York"},
571
+ }
572
+
573
+ env_1 = {
574
+ "id": "env_1",
575
+ "subject": "Aspen Dynamics — FY27 Renewal Agreement",
576
+ "message": "Please review and sign the FY27 renewal agreement for Aspen Dynamics.",
577
+ "status": "draft",
578
+ "createdAt": "2026-06-20T15:30:00Z",
579
+ "sentAt": None, "completedAt": None, "voidedAt": None, "declinedAt": None,
580
+ "lastActivityAt": "2026-06-20T15:30:00Z", "expiresAt": None,
581
+ "senderId": "user_1", "folderId": None, "templateId": None,
582
+ "reminderEnabled": False, "reminderDays": 3, "reminderFrequency": 2,
583
+ "documents": [
584
+ {"id": "doc_1_1", "name": "Aspen Dynamics FY27 Renewal Agreement.pdf",
585
+ "pageCount": 6, "order": 1,
586
+ "fileUrl": "https://picsum.photos/seed/aspenfy27/800/1100", "fileType": "pdf"},
587
+ ],
588
+ "recipients": [
589
+ {"id": "rec_1_1", "name": "Daniel Brooks", "email": "daniel.brooks@aspendynamics.com",
590
+ "role": "signer", "routingOrder": 1, "status": "created",
591
+ "signedAt": None, "viewedAt": None, "deliveredAt": None,
592
+ "declinedAt": None, "declineReason": None},
593
+ ],
594
+ "fields": [
595
+ {"id": "fld_1_1", "type": "signature", "recipientId": "rec_1_1",
596
+ "documentId": "doc_1_1", "pageNumber": 6, "x": 120, "y": 640,
597
+ "width": 200, "height": 44, "value": None, "required": True,
598
+ "label": "Signature", "readOnly": False, "fontSize": 12, "fontColor": "#000000"},
599
+ {"id": "fld_1_2", "type": "dateSigned", "recipientId": "rec_1_1",
600
+ "documentId": "doc_1_1", "pageNumber": 6, "x": 360, "y": 640,
601
+ "width": 120, "height": 24, "value": None, "required": True,
602
+ "label": "Date", "readOnly": True, "fontSize": 12, "fontColor": "#000000"},
603
+ ],
604
+ "history": [
605
+ {"id": "evt_1_1", "timestamp": "2026-06-20T15:30:00Z", "action": "created",
606
+ "actorName": "Jordan Rivera", "actorEmail": "jordan.rivera@northwindcloud.com",
607
+ "details": "Envelope created"},
608
+ ],
609
+ }
610
+
611
+ # Distractor draft for a DIFFERENT customer — must NOT be sent.
612
+ env_2 = {
613
+ "id": "env_2",
614
+ "subject": "Meridian Logistics — FY27 Renewal Agreement",
615
+ "message": "Draft renewal agreement for Meridian Logistics (not ready to send).",
616
+ "status": "draft",
617
+ "createdAt": "2026-06-18T11:05:00Z",
618
+ "sentAt": None, "completedAt": None, "voidedAt": None, "declinedAt": None,
619
+ "lastActivityAt": "2026-06-18T11:05:00Z", "expiresAt": None,
620
+ "senderId": "user_1", "folderId": None, "templateId": None,
621
+ "reminderEnabled": False, "reminderDays": 3, "reminderFrequency": 2,
622
+ "documents": [
623
+ {"id": "doc_2_1", "name": "Meridian Logistics FY27 Renewal Agreement.pdf",
624
+ "pageCount": 5, "order": 1,
625
+ "fileUrl": "https://picsum.photos/seed/meridianfy27/800/1100", "fileType": "pdf"},
626
+ ],
627
+ "recipients": [
628
+ {"id": "rec_2_1", "name": "Greg Halloran",
629
+ "email": "greg.halloran@meridianlogistics.example.com",
630
+ "role": "signer", "routingOrder": 1, "status": "created",
631
+ "signedAt": None, "viewedAt": None, "deliveredAt": None,
632
+ "declinedAt": None, "declineReason": None},
633
+ ],
634
+ "fields": [],
635
+ "history": [
636
+ {"id": "evt_2_1", "timestamp": "2026-06-18T11:05:00Z", "action": "created",
637
+ "actorName": "Jordan Rivera", "actorEmail": "jordan.rivera@northwindcloud.com",
638
+ "details": "Envelope created"},
639
+ ],
640
+ }
641
+
642
+ return {
643
+ "user": user,
644
+ "envelopes": [env_1, env_2],
645
+ "templates": [],
646
+ "folders": [],
647
+ "contacts": [
648
+ {"id": "c_1", "name": "Daniel Brooks", "email": "daniel.brooks@aspendynamics.com",
649
+ "company": "Aspen Dynamics", "title": "VP Customer Operations"},
650
+ {"id": "c_2", "name": "Greg Halloran",
651
+ "email": "greg.halloran@meridianlogistics.example.com",
652
+ "company": "Meridian Logistics", "title": "Operations Manager"},
653
+ ],
654
+ "auditLog": [
655
+ {"id": "audit_1", "timestamp": "2026-06-20T15:30:00Z", "action": "CREATE_ENVELOPE",
656
+ "details": "Created envelope 'Aspen Dynamics — FY27 Renewal Agreement'",
657
+ "envelopeId": "env_1"},
658
+ {"id": "audit_2", "timestamp": "2026-06-18T11:05:00Z", "action": "CREATE_ENVELOPE",
659
+ "details": "Created envelope 'Meridian Logistics — FY27 Renewal Agreement'",
660
+ "envelopeId": "env_2"},
661
+ ],
662
+ }
663
+
664
+
665
+ # ---------------------------------------------------------------------------
666
+ # GMAIL STATE — Jordan Rivera; inbox has unrelated mail; no sent email to Daniel.
667
+ # ---------------------------------------------------------------------------
668
+ def build_gmail_state():
669
+ user = {
670
+ "userId": "u1",
671
+ "username": "Jordan Rivera",
672
+ "email": "jordan.rivera@northwindcloud.com",
673
+ "avatar": "https://i.pravatar.cc/150?u=jordan-rivera",
674
+ }
675
+ emails = [
676
+ {"id": "email_1", "threadId": "thread_1",
677
+ "from": {"name": "Priya Nair", "email": "priya.nair@northwindcloud.com"},
678
+ "to": [{"name": "Jordan Rivera", "email": "jordan.rivera@northwindcloud.com"}],
679
+ "cc": [], "bcc": [],
680
+ "subject": "Renewals pipeline review — Friday",
681
+ "body": "<p>Hi Jordan,</p><p>Let's go through the Q3 renewals on our Friday sync. "
682
+ "Please have the at-risk accounts ready.</p><p>Thanks,<br/>Priya</p>",
683
+ "timestamp": "2026-06-22T13:15:00Z",
684
+ "read": True, "starred": False, "important": True,
685
+ "labels": ["l1"], "category": "primary", "folder": "inbox", "attachments": []},
686
+ {"id": "email_2", "threadId": "thread_2",
687
+ "from": {"name": "Northwind Cloud Billing", "email": "billing@northwindcloud.com"},
688
+ "to": [{"name": "Jordan Rivera", "email": "jordan.rivera@northwindcloud.com"}],
689
+ "cc": [], "bcc": [],
690
+ "subject": "June statement available",
691
+ "body": "<p>Your June account statement is now available in the billing portal.</p>",
692
+ "timestamp": "2026-06-20T09:00:00Z",
693
+ "read": False, "starred": False, "important": False,
694
+ "labels": ["l4"], "category": "primary", "folder": "inbox", "attachments": []},
695
+ {"id": "email_3", "threadId": "thread_3",
696
+ "from": {"name": "Lena Ortiz", "email": "lena.ortiz@orionretail.example.com"},
697
+ "to": [{"name": "Jordan Rivera", "email": "jordan.rivera@northwindcloud.com"}],
698
+ "cc": [], "bcc": [],
699
+ "subject": "Re: Orion expansion timeline",
700
+ "body": "<p>Hi Jordan, thanks for the proposal — reviewing internally and will "
701
+ "circle back next week.</p><p>Best,<br/>Lena</p>",
702
+ "timestamp": "2026-06-19T17:40:00Z",
703
+ "read": True, "starred": False, "important": False,
704
+ "labels": ["l1"], "category": "primary", "folder": "inbox", "attachments": []},
705
+ ]
706
+ labels = [
707
+ {"id": "l1", "name": "Work", "color": "#ef4444"},
708
+ {"id": "l2", "name": "Personal", "color": "#3b82f6"},
709
+ {"id": "l3", "name": "Travel", "color": "#22c55e"},
710
+ {"id": "l4", "name": "Finance", "color": "#eab308"},
711
+ ]
712
+ return {"user": user, "emails": emails, "labels": labels, "drafts": []}
713
+
714
+
715
+ def inject(url, state, label):
716
+ resp = http_post(f'{url}/post?sid={sid}', {'action': 'set', 'state': state})
717
+ assert resp.status_code == 200, f'{label} injection failed: {resp.status_code} {resp.text}'
718
+ go = http_get(f'{url}/go?sid={sid}').json()
719
+ assert go.get('initial_state') is not None, f'{label} initial_state is None after injection'
720
+ print(f'{label} state injected and verified.')
721
+
722
+
723
+ inject(NOTION_URL, build_notion_state(), 'Notion')
724
+ inject(SALESFORCE_URL, build_salesforce_state(), 'Salesforce')
725
+ inject(DOCUSIGN_URL, build_docusign_state(), 'DocuSign')
726
+ inject(GMAIL_URL, build_gmail_state(), 'Gmail')
727
+
728
+
729
+ # --- Launch browser (primary mock = Salesforce) ---
730
+ def launch_gui(command, delay_sec=1.0):
731
+ env = os.environ.copy()
732
+ env['DISPLAY'] = ':0'
733
+ # Accept both a command string and a pre-split arg list (some tasks
734
+ # build arg lists themselves, e.g. se_hard_008).
735
+ if isinstance(command, str):
736
+ _parts = shlex.split(command)
737
+ else:
738
+ _parts = list(command)
739
+ # Inject CDP debug port so wait_mocks_loaded can verify browser render
740
+ # via Playwright connect_over_cdp. Idempotent: skip if any arg already
741
+ # starts with --remote-debugging-port (some tasks inject their own
742
+ # dynamic port, e.g. se_hard_008).
743
+ if _parts and 'google-chrome' in _parts[0] \
744
+ and not any(p.startswith('--remote-debugging-port') for p in _parts):
745
+ _parts[1:1] = ['--no-first-run', '--no-default-browser-check',
746
+ '--remote-debugging-port=1337']
747
+ _proc = subprocess.Popen(_parts, stdin=subprocess.DEVNULL,
748
+ stdout=subprocess.DEVNULL,
749
+ stderr=subprocess.DEVNULL, env=env,
750
+ start_new_session=True)
751
+ time.sleep(delay_sec)
752
+ if _proc.poll() is not None:
753
+ print(' WARNING: launch_gui process exited early (code=%s)'
754
+ % _proc.returncode)
755
+ return _proc
756
+ _primary_mock_url = SALESFORCE_URL
757
+ launch_gui(f'google-chrome "{SALESFORCE_URL}/?sid={sid}"', delay_sec=2.0)
758
+ _open_remaining_mock_tabs(_primary_mock_url)
759
+ wait_mocks_loaded()
760
+ print(f'GUI_READY: launched browser at {SALESFORCE_URL}/?sid={sid}')
csm_qbr_renewal_003/reward.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: CSM Renewal QBR prep across Notion, Salesforce, DocuSign, Gmail
13
+ Task ID: csm_qbr_renewal_003
14
+ Domain: mock_websites (multi-mock)
15
+ Scoring (sums to 1.0):
16
+ - Notion (0.25): new Aspen QBR agenda page (0.07) + 4 sections each w/ non-empty content (0.18)
17
+ - Salesforce (0.30): new QBR event w/ runtime this-Friday time/relation/assignee (0.20) + opp-1 advanced forward, not closed (0.10)
18
+ - DocuSign (0.20): env_1 draft->sent w/ recipient sent + distractor env_2 stays draft (compound)
19
+ - Gmail (0.25): new sent email to Daniel (0.12) + body walks agenda & references the QBR time (0.13)
20
+ All scoring components are anchored to task-introduced changes: each FAILS on initial_env, PASSES on golden_env.
21
+ """
22
+ import re
23
+ import sys
24
+ from datetime import date, timedelta
25
+
26
+ import requests
27
+
28
+ # --- Read sid ---
29
+ try:
30
+ with open('/tmp/task_web_sid') as f:
31
+ sid = f.read().strip()
32
+ if not sid:
33
+ raise ValueError('sid empty')
34
+ except Exception as e:
35
+ print(f'CRITICAL: cannot read /tmp/task_web_sid: {e}')
36
+ print('REWARD: 0.0')
37
+ sys.exit(0)
38
+
39
+ MOCKS = {
40
+ 'notion': 'http://28.7.184.198:8166',
41
+ 'salesforce': 'http://28.7.184.198:8175',
42
+ 'docusign': 'http://28.7.184.198:8130',
43
+ 'gmail': 'http://28.7.184.198:8138',
44
+ }
45
+
46
+ # --- Fetch state from all mocks ---
47
+ S = {}
48
+ for name, url in MOCKS.items():
49
+ try:
50
+ data = requests.get(f'{url}/go?sid={sid}', timeout=15).json()
51
+ except Exception as e:
52
+ print(f'CRITICAL: cannot fetch {name} state: {e}')
53
+ print('REWARD: 0.0')
54
+ sys.exit(0)
55
+ if data.get('current_state') is None:
56
+ print(f'CRITICAL: {name} current_state is None')
57
+ print('REWARD: 0.0')
58
+ sys.exit(0)
59
+ S[name] = data
60
+
61
+
62
+ def norm(s):
63
+ return re.sub(r'[^a-z0-9 ]', '', (s or '').lower()).strip()
64
+
65
+
66
+ SECTIONS = ['business goals', 'usage highlights', 'risks', 'next actions']
67
+ MONTH_NAMES = {
68
+ 1: ('january', 'jan'),
69
+ 2: ('february', 'feb'),
70
+ 3: ('march', 'mar'),
71
+ 4: ('april', 'apr'),
72
+ 5: ('may', 'may'),
73
+ 6: ('june', 'jun'),
74
+ 7: ('july', 'jul'),
75
+ 8: ('august', 'aug'),
76
+ 9: ('september', 'sep'),
77
+ 10: ('october', 'oct'),
78
+ 11: ('november', 'nov'),
79
+ 12: ('december', 'dec'),
80
+ }
81
+
82
+
83
+ def this_friday(today=None):
84
+ today = today or date.today()
85
+ days_until_friday = (4 - today.weekday()) % 7
86
+ return today + timedelta(days=days_until_friday)
87
+
88
+
89
+ def load_target_qbr_date():
90
+ try:
91
+ with open('/tmp/task_qbr_date') as f:
92
+ return date.fromisoformat(f.read().strip())
93
+ except Exception:
94
+ return this_friday()
95
+
96
+
97
+ TARGET_QBR_DATE = load_target_qbr_date()
98
+ TARGET_QBR_START = (TARGET_QBR_DATE.year, TARGET_QBR_DATE.month, TARGET_QBR_DATE.day, 14, 0)
99
+ TARGET_QBR_END = (TARGET_QBR_DATE.year, TARGET_QBR_DATE.month, TARGET_QBR_DATE.day, 14, 45)
100
+
101
+
102
+ def parse_datetime_minute(value):
103
+ m = re.search(r'(\d{4})-(\d{1,2})-(\d{1,2})[T ](\d{1,2}):(\d{2})', str(value or ''))
104
+ if not m:
105
+ return None
106
+ return tuple(int(x) for x in m.groups())
107
+
108
+
109
+ def datetime_matches(value, target):
110
+ return parse_datetime_minute(value) == target
111
+
112
+
113
+ def text_mentions_target_date(text):
114
+ ntext = norm(text)
115
+ year, month, day = TARGET_QBR_DATE.year, TARGET_QBR_DATE.month, TARGET_QBR_DATE.day
116
+ full_month, short_month = MONTH_NAMES[month]
117
+ date_phrases = {
118
+ 'friday',
119
+ f'{year} {month:02d} {day:02d}',
120
+ f'{year} {month} {day}',
121
+ f'{full_month} {day}',
122
+ f'{short_month} {day}',
123
+ }
124
+ return any(phrase in ntext for phrase in date_phrases)
125
+
126
+
127
+ def text_mentions_2pm(text):
128
+ ntext = norm(text)
129
+ return bool(re.search(r'\b2\s*pm\b', ntext) or '200 pm' in ntext or '1400' in ntext)
130
+
131
+
132
+ def verify_task():
133
+ total = 0.0
134
+
135
+ # ===================== NOTION (0.25) =====================
136
+ notion_init = S['notion']['initial_state']
137
+ notion_cur = S['notion']['current_state']
138
+ init_page_ids = set(notion_init.get('pages', {}).keys())
139
+ cur_pages = notion_cur.get('pages', {})
140
+ cur_blocks = notion_cur.get('blocks', {})
141
+
142
+ # Find NEW pages whose title references the Aspen QBR agenda
143
+ qbr_page = None
144
+ for pid, page in cur_pages.items():
145
+ if pid in init_page_ids:
146
+ continue
147
+ t = norm(page.get('title'))
148
+ if 'aspen' in t and ('qbr' in t or 'quarterly business review' in t):
149
+ qbr_page = page
150
+ break
151
+
152
+ # Component N1: new Aspen QBR agenda page exists (0.07)
153
+ try:
154
+ if qbr_page is not None:
155
+ print(f"PASS: Notion new QBR page '{qbr_page.get('title')}' (0.07)")
156
+ total += 0.07
157
+ else:
158
+ print('FAIL: No NEW Notion page referencing Aspen + QBR found')
159
+ except Exception as e:
160
+ print(f'ERROR: Notion N1 — {e}')
161
+
162
+ # Component N2: four sections, each a heading with >=1 non-empty content block (0.18, 0.045 each)
163
+ try:
164
+ section_has_content = {s: False for s in SECTIONS}
165
+ section_heading_seen = {s: False for s in SECTIONS}
166
+ if qbr_page is not None:
167
+ block_ids = qbr_page.get('blockIds', []) or []
168
+ current_section = None
169
+ for bid in block_ids:
170
+ blk = cur_blocks.get(bid)
171
+ if not blk:
172
+ continue
173
+ btype = (blk.get('type') or '')
174
+ content = blk.get('content') or ''
175
+ ncontent = norm(content)
176
+ if btype.startswith('heading'):
177
+ # does this heading start a tracked section?
178
+ matched = None
179
+ for s in SECTIONS:
180
+ if ncontent == s or s in ncontent:
181
+ matched = s
182
+ break
183
+ if matched:
184
+ current_section = matched
185
+ section_heading_seen[matched] = True
186
+ else:
187
+ current_section = None
188
+ else:
189
+ # non-heading content block under the current section
190
+ if current_section and content.strip():
191
+ section_has_content[current_section] = True
192
+ for s in SECTIONS:
193
+ if section_heading_seen[s] and section_has_content[s]:
194
+ print(f"PASS: Notion section '{s}' has heading + non-empty content (0.045)")
195
+ total += 0.045
196
+ else:
197
+ print(f"FAIL: Notion section '{s}' heading_seen={section_heading_seen[s]} has_content={section_has_content[s]}")
198
+ except Exception as e:
199
+ print(f'ERROR: Notion N2 — {e}')
200
+
201
+ # ===================== SALESFORCE (0.30) =====================
202
+ sf_init = S['salesforce']['initial_state']
203
+ sf_cur = S['salesforce']['current_state']
204
+ init_act_ids = {a.get('activityId') for a in sf_init.get('activities', [])}
205
+ cur_acts = sf_cur.get('activities', [])
206
+
207
+ # Component S1: NEW QBR event w/ correct runtime date/time, type, relation, assignee (0.20)
208
+ try:
209
+ match = None
210
+ for a in cur_acts:
211
+ if a.get('activityId') in init_act_ids:
212
+ continue
213
+ if a.get('type') != 'event':
214
+ continue
215
+ subj = norm(a.get('subject'))
216
+ is_qbr = 'qbr' in subj or 'quarterly business review' in subj
217
+ is_aspen = 'aspen' in subj
218
+ if (is_qbr and is_aspen
219
+ and datetime_matches(a.get('startDateTime'), TARGET_QBR_START)
220
+ and datetime_matches(a.get('endDateTime'), TARGET_QBR_END)
221
+ and a.get('relatedToType') == 'account'
222
+ and a.get('relatedToId') == 'account-1'
223
+ and a.get('assignedToId') == 'user-1'):
224
+ match = a
225
+ break
226
+ if match:
227
+ print(f"PASS: Salesforce new QBR event correct ({TARGET_QBR_DATE.isoformat()} 14:00-14:45, account-1, user-1) (0.20)")
228
+ total += 0.20
229
+ else:
230
+ print(f'FAIL: No NEW Salesforce QBR event matching {TARGET_QBR_DATE.isoformat()} 14:00-14:45/relation/assignee')
231
+ except Exception as e:
232
+ print(f'ERROR: Salesforce S1 — {e}')
233
+
234
+ # Component S2: opp-1 advanced FORWARD from Qualification, still open (0.10)
235
+ try:
236
+ FORWARD_OPEN = {'needs analysis', 'value proposition', 'proposal', 'negotiation'}
237
+ opp1 = next((o for o in sf_cur.get('opportunities', []) if o.get('opportunityId') == 'opp-1'), None)
238
+ stage = norm(opp1.get('stage')) if opp1 else None
239
+ if opp1 and stage in FORWARD_OPEN:
240
+ print(f"PASS: opp-1 advanced to '{opp1.get('stage')}' (forward, open) (0.10)")
241
+ total += 0.10
242
+ else:
243
+ print(f"FAIL: opp-1 stage='{opp1.get('stage') if opp1 else None}' not a forward open stage")
244
+ except Exception as e:
245
+ print(f'ERROR: Salesforce S2 — {e}')
246
+
247
+ # ===================== DOCUSIGN (0.20) =====================
248
+ # Compound: env_1 draft->sent w/ recipient sent/delivered AND distractor env_2 stays draft.
249
+ # Anchored to the env_1 change so it FAILS on initial (env_1 still draft).
250
+ try:
251
+ ds_cur = S['docusign']['current_state']
252
+ envs = {e.get('id'): e for e in ds_cur.get('envelopes', [])}
253
+ env1 = envs.get('env_1')
254
+ env2 = envs.get('env_2')
255
+ env1_is_aspen = bool(env1) and 'aspen' in norm(env1.get('subject'))
256
+ env1_recips = env1.get('recipients', []) if env1 else []
257
+ daniel = next((r for r in env1_recips if 'daniel.brooks@aspendynamics.com' in (r.get('email') or '').lower()), None)
258
+ env1_ok = (
259
+ env1_is_aspen
260
+ and env1.get('status') == 'sent'
261
+ and bool(env1.get('sentAt'))
262
+ and daniel is not None
263
+ and daniel.get('status') in ('sent', 'delivered')
264
+ )
265
+ env2_still_draft = bool(env2) and env2.get('status') == 'draft'
266
+ if env1_ok and env2_still_draft:
267
+ print('PASS: DocuSign env_1 sent w/ Daniel sent/delivered AND env_2 stays draft (0.20)')
268
+ total += 0.20
269
+ else:
270
+ print(f'FAIL: DocuSign env1_ok={env1_ok} env2_still_draft={env2_still_draft}')
271
+ except Exception as e:
272
+ print(f'ERROR: DocuSign — {e}')
273
+
274
+ # ===================== GMAIL (0.25) =====================
275
+ gm_init = S['gmail']['initial_state']
276
+ gm_cur = S['gmail']['current_state']
277
+ init_email_ids = {m.get('id') for m in gm_init.get('emails', [])}
278
+ cur_emails = gm_cur.get('emails', [])
279
+
280
+ # Find new sent email addressed to Daniel
281
+ new_sent = None
282
+ for m in cur_emails:
283
+ if m.get('id') in init_email_ids:
284
+ continue
285
+ if m.get('folder') != 'sent':
286
+ continue
287
+ tos = m.get('to') or []
288
+ if any('daniel.brooks@aspendynamics.com' in (t.get('email') or '').lower() for t in tos):
289
+ new_sent = m
290
+ break
291
+
292
+ # Component G1: new sent email to Daniel w/ non-empty subject (0.12)
293
+ try:
294
+ if new_sent and (new_sent.get('subject') or '').strip():
295
+ print(f"PASS: Gmail new sent email to Daniel, subject='{new_sent.get('subject')}' (0.12)")
296
+ total += 0.12
297
+ else:
298
+ print('FAIL: No new sent email to daniel.brooks@aspendynamics.com with non-empty subject')
299
+ except Exception as e:
300
+ print(f'ERROR: Gmail G1 — {e}')
301
+
302
+ # Component G2: body walks agenda (>=3 of 4 sections) + references runtime QBR date/time (0.13)
303
+ try:
304
+ if new_sent:
305
+ body = (new_sent.get('body') or '')
306
+ nbody = norm(body)
307
+ sections_hit = sum(1 for s in SECTIONS if s in nbody)
308
+ mentions_qbr_date = text_mentions_target_date(body)
309
+ mentions_qbr_time = text_mentions_2pm(body)
310
+ # award proportionally: agenda walk-through 0.07, date 0.03, 2PM 0.03
311
+ sub = 0.0
312
+ if sections_hit >= 3:
313
+ sub += 0.07
314
+ print(f'PASS: Gmail body walks agenda ({sections_hit}/4 sections) (0.07)')
315
+ else:
316
+ print(f'FAIL: Gmail body mentions only {sections_hit}/4 agenda sections')
317
+ if mentions_qbr_date:
318
+ sub += 0.03
319
+ print(f'PASS: Gmail body references QBR date {TARGET_QBR_DATE.isoformat()} (0.03)')
320
+ else:
321
+ print(f'FAIL: Gmail body does not reference QBR date {TARGET_QBR_DATE.isoformat()}')
322
+ if mentions_qbr_time:
323
+ sub += 0.03
324
+ print('PASS: Gmail body names 2 PM time (0.03)')
325
+ else:
326
+ print('FAIL: Gmail body does not name 2 PM time')
327
+ total += sub
328
+ else:
329
+ print('FAIL: Gmail G2 — no sent email to evaluate body')
330
+ except Exception as e:
331
+ print(f'ERROR: Gmail G2 — {e}')
332
+
333
+ final = round(min(total, 1.0), 4)
334
+ print(f'\nScore: {total}/1.0')
335
+ print(f'REWARD: {final}')
336
+ return final
337
+
338
+
339
+ verify_task()
csm_qbr_renewal_003/reward_label.json ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/csm_qbr_renewal_003/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:22:31",
7
+ "label": {
8
+ "task_id": "csm_qbr_renewal_003",
9
+ "domain": "mock_websites",
10
+ "summary": "验证在 Notion、Salesforce、DocuSign、Gmail 上完成 CSM Renewal QBR 准备任务的行为,包括创建 QBR 议程页面、安排会议事件、推进销售机会、发送 DocuSign 信封以及发送包含议程和会议时间的邮件。",
11
+ "is_placeholder": false,
12
+ "data_sources": [
13
+ "/tmp/task_web_sid",
14
+ "/tmp/task_qbr_date",
15
+ "http://28.7.186.212:8186 (notion)",
16
+ "http://28.7.186.212:8195 (salesforce)",
17
+ "http://28.7.186.212:8150 (docusign)",
18
+ "http://28.7.186.212:8158 (gmail)"
19
+ ],
20
+ "scoring_components": [
21
+ {
22
+ "name": "Notion N1",
23
+ "weight": 0.07,
24
+ "description": "新建 Aspen QBR 议程页面",
25
+ "check_logic": "遍历 current_state.pages,排除 initial_state 中已存在的 pageId,检查是否有页面标题经 norm 处理后同时包含 'aspen' 和 'qbr'(或 'quarterly business review')",
26
+ "pass_condition": "存在一个新的 Notion 页面,其标题同时提及 Aspen 和 QBR"
27
+ },
28
+ {
29
+ "name": "Notion N2",
30
+ "weight": 0.18,
31
+ "description": "四个指定 section 均包含 heading 和非空内容",
32
+ "check_logic": "在 qbr_page 的 blockIds 中顺序遍历 block,识别 heading 类型块是否匹配 SECTIONS(business goals、usage highlights、risks、next actions)之一;匹配后,后续非 heading 块若 content.strip() 非空,则标记该 section 有内容。每个 section 独立计分 0.045。",
33
+ "pass_condition": "四个 section 每个都必须出现对应的 heading 且在该 heading 下至少有一个非空的非 heading 内容块"
34
+ },
35
+ {
36
+ "name": "Salesforce S1",
37
+ "weight": 0.2,
38
+ "description": "新建 QBR 事件,时间、关联对象和负责人正确",
39
+ "check_logic": "遍历 current_state.activities,排除 initial_state 中已有的 activityId,筛选 type='event' 且 subject 经 norm 后包含 'qbr' 和 'aspen' 的新活动;检查 startDateTime 匹配 TARGET_QBR_START(目标日期 14:00)、endDateTime 匹配 TARGET_QBR_END(目标日期 14:45)、relatedToType='account'、relatedToId='account-1'、assignedToId='user-1'。",
40
+ "pass_condition": "存在一个新的 Event,主题为 Aspen QBR,开始时间为目标日期 14:00,结束时间为 14:45,关联 account-1,负责人为 user-1"
41
+ },
42
+ {
43
+ "name": "Salesforce S2",
44
+ "weight": 0.1,
45
+ "description": "机会 opp-1 向前推进且仍处于开放阶段",
46
+ "check_logic": "在 current_state.opportunities 中查找 opportunityId='opp-1',将其 stage 经 norm 后与集合 {'needs analysis', 'value proposition', 'proposal', 'negotiation'} 比对。",
47
+ "pass_condition": "opp-1 的阶段为 Needs Analysis、Value Proposition、Proposal 或 Negotiation(即向前推进且未关闭)"
48
+ },
49
+ {
50
+ "name": "DocuSign",
51
+ "weight": 0.2,
52
+ "description": "env_1 发送给 Daniel 且 distractor env_2 保持草稿",
53
+ "check_logic": "检查 current_state.envelopes 中 id='env_1' 的 envelope:subject 经 norm 后包含 'aspen',status='sent',sentAt 非空,收件人列表中存在 email 包含 'daniel.brooks@aspendynamics.com' 且其 status 为 'sent' 或 'delivered';同时 id='env_2' 的 envelope status 必须为 'draft'。两者同时满足才得分。",
54
+ "pass_condition": "env_1 状态为 sent、主题含 Aspen、Daniel 的收件人状态为 sent/delivered,且 env_2 状态仍为 draft"
55
+ },
56
+ {
57
+ "name": "Gmail G1",
58
+ "weight": 0.12,
59
+ "description": "新建发送给 Daniel 的邮件且主题非空",
60
+ "check_logic": "遍历 current_state.emails,排除 initial_state 中已有的 id,筛选 folder='sent' 且 to 列表中任一收件人 email 包含 'daniel.brooks@aspendynamics.com' 的新邮件,并检查 subject 经 strip 后非空。",
61
+ "pass_condition": "存在一封新的 sent 邮件发送给 daniel.brooks@aspendynamics.com,且主题非空"
62
+ },
63
+ {
64
+ "name": "Gmail G2",
65
+ "weight": 0.13,
66
+ "description": "邮件正文包含议程、QBR 日期和 2PM 时间",
67
+ "check_logic": "对 new_sent.body 进行 norm 处理,统计包含 SECTIONS 中至少 3 个 section 名称(得 0.07);检查正文是否通过 text_mentions_target_date 提及目标 QBR 日期(得 0.03);检查是否通过 text_mentions_2pm 提及 2 PM(得 0.03)。三个子条件分数累加为 sub 后加入 total。",
68
+ "pass_condition": "正文至少提及 4 个议程 section 中的 3 个、提及目标 QBR 日期、并提及 2 PM 时间"
69
+ }
70
+ ],
71
+ "total_max_score": 1.0,
72
+ "score_aggregation": "各组件分数累加求和,最终用 min(total, 1.0) 钳制到上限后四舍五入到 4 位小数",
73
+ "failure_modes": [
74
+ "读取 /tmp/task_web_sid 失败或内容为空:打印 CRITICAL 并返回 REWARD: 0.0 后 sys.exit(0)",
75
+ "从任一 mock 服务(notion/salesforce/docusign/gmail)拉取状态失败:打印 CRITICAL 并返回 REWARD: 0.0 后 sys.exit(0)",
76
+ "任一 mock 返回的 current_state 为 None:打印 CRITICAL 并返回 REWARD: 0.0 后 sys.exit(0)",
77
+ "Notion 未找到新的 Aspen QBR 页面:N1 和 N2 均不得分",
78
+ "Salesforce 未找到符合条件的新 QBR Event:S1 不得分",
79
+ "opp-1 阶段未前进或已关闭:S2 不得分",
80
+ "DocuSign env_1 未发送或 Daniel 状态不对,或 env_2 不再是 draft:DocuSign 组件 0.20 分全部丢失",
81
+ "Gmail 未找到发给 Daniel 的新 sent 邮件:G1 和 G2 均不得分"
82
+ ],
83
+ "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,并依次从 notion、salesforce、docusign、gmail 四个 mock 服务拉取 initial_state 与 current_state;同时从 /tmp/task_qbr_date 加载目标日期(或默认取本周五)。随后按顺序执行验证:1) Notion 部分查找标题同时包含 Aspen 和 QBR 的新页面(0.07),并检查该页面是否包含 business goals、usage highlights、risks、next actions 四个 section 的 heading 及非空内容(每个 0.045);2) Salesforce 部分查找新的 Event,验证其主题、目标日期 14:00-14:45 的时间、关联 account-1 及负责人 user-1(0.20),并检查 opp-1 的阶段是否推进到开放的前进阶段(0.10);3) DocuSign 部分验证 env_1 变为 sent 且收件人 Daniel 状态为 sent/delivered,同时 distractor env_2 必须保持 draft(0.20);4) Gmail 部分查找发给 Daniel 的新 sent 邮件,验证主题非空(0.12),并检查正文是否至少提及 3 个议程 section(0.07)、目标 QBR 日期(0.03)和 2 PM 时间(0.03)。所有子项分数累加,最终通过 min(total, 1.0) 限制上限并四舍五入输出。",
84
+ "confidence": 1.0
85
+ },
86
+ "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码并提取所需信息:\n\n1. **task_id**: 从 docstring 中可以看到 \"Task ID: csm_qbr_renewal_003\"\n2. **domain**: 从 docstring 中可以看到 \"Domain: mock_websites (multi-mock)\"\n3. **summary**: 一句话概括。这个脚本验证在 Notion、Salesforce、DocuSign、Gmail 上完成 CSM Renewal QBR 准备任务的行为。\n4. **is_placeholder**: false,因为脚本有详细的检查逻辑,不是占位脚本。\n5. **data_sources**: 脚本从以下 mock 服务获取状态:\n - notion: http://28.7.186.212:8186\n - salesforce: http://28.7.186.212:8195\n - docusign: http://28.7.186.212:8150\n - gmail: http://28.7.186.212:8158\n - /tmp/task_web_sid (读取 sid)\n - /tmp/task_qbr_date (读取目标 QBR 日期)\n\n6. **scoring_components**: 需要详细列出各个组件:\n - Notion N1: 0.07 - 新建 Aspen QBR agenda 页面\n - Notion N2: 0.18 (4 * 0.045) - 四个 section 每个都有 heading 和非空内容\n - Salesforce S1: 0.20 - 新建 QBR event,正确时间/关系/负责人\n - Salesforce S2: 0.10 - opp-1 推进到前进阶段且未关闭\n - DocuSign: 0.20 - env_1 从 draft 变为 sent 且 Daniel 状态为 sent/delivered,env_2 保持 draft\n - Gmail G1: 0.12 - 新建发送给 Daniel 的邮件,主题非空\n - Gmail G2: 0.13 (0.07 + 0.03 + 0.03) - 邮件正文包含至少3个 agenda section、提及 QBR 日期、提及 2PM 时间\n\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 各组件分数相加,最后用 min(total, 1.0) 钳制到上限,并四舍五入到4位小数。\n9. **failure_modes**: \n - 读取 /tmp/task_web_sid 失败或为空 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n - 无法从任一 mock 服务获取状态 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n - 任一 mock 返回 current_state 为 None -> CRITICAL, REWARD: 0.0, sys.exit(0)\n - 各组件检查失败只是不加分,不会提前退出(除了 DocuSign 是复合检查,必须同时满足两个条件)\n\n10. **scoring_logic_explanation**: 详细解释执行顺序:\n - 首先读取 /tmp/task_web_sid 获取会话 ID\n - 从四个 mock 服务(Notion、Salesforce、DocuSign、Gmail)拉取 initial_state 和 current_state\n - 加载目标 QBR 日期(从 /tmp/task_qbr_date 或计算本周五)\n - Notion 检查:查找标题包含 Aspen 和 QBR 的新页面;检查四个指定 section 是否有 heading 和非空内容块\n - Salesforce 检查:查找新的 QBR event,验证时间、关联账户、负责人;检查 opp-1 阶段是否向前推进且未关闭\n - DocuSign 检查:验证 env_1 变为 sent 且收件人 Daniel 状态为 sent/delivered,同时 env_2 保持 draft\n - Gmail 检查:查找发给 Daniel 的新 sent 邮件,验证主题非空;验证正文包含至少3个 agenda section、提及 QBR 日期和 2PM 时间\n - 汇总所有得分,上限 1.0,输出 REWARD\n\n11. **confidence**: 1.0,因为代码逻辑清晰完整。\n\n让我再仔细检查一下各个组件的权重和逻辑:\n\nNotion:\n- N1: 0.07 (代码中 total += 0.07)\n- N2: 每个 section 0.045,共 4 个,总计 0.18 (代码中 total += 0.045 在循环里)\n\nSalesforce:\n- S1: 0.20 (代码中 total += 0.20)\n- S2: 0.10 (代码中 total += 0.10)\n\nDocuSign:\n- 0.20 (代码中 total += 0.20) - 这是一个复合条件,必须同时满足 env1_ok 和 env2_still_draft\n\nGmail:\n- G1: 0.12 (代码中 total += 0.12)\n- G2: 0.13,但内部是细分的:\n - sections_hit >= 3: 0.07\n - mentions_qbr_date: 0.03\n - mentions_qbr_time: 0.03\n 总计 0.13,代码中是 sub += ... 然后 total += sub\n\nTotal: 0.07 + 0.18 + 0.20 + 0.10 + 0.20 + 0.12 + 0.13 = 1.00\n\nScore aggregation: 各组件分数累加,最终 `round(min(total, 1.0), 4)`\n\nFailure modes:\n- /tmp/task_web_sid 读取失败\n- mock 状态拉取失败\n- current_state 为 None\n- 各检查项不满足(不加分)\n\n我需要确保 JSON 格式完全符合要求:\n- 不要 Markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 所有字符串 value 使用中文(task_id、domain、字段名、代码标识符保留原样)\n- 不要额外解释\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"csm_qbr_renewal_003\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证在 Notion、Salesforce、DocuSign、Gmail 上完成 CSM Renewal QBR 准备任务的行为,包括创建 QBR 议程页面、安排会议事件、推进销售机会、发送 DocuSign 信封以及发送包含议程和会议时间的邮件。\",\n \"is_placeholder\": false,\n \"data_sources\": [\n \"/tmp/task_web_sid\",\n \"/tmp/task_qbr_date\",\n \"http://28.7.186.212:8186 (notion)\",\n \"http://28.7.186.212:8195 (salesforce)\",\n \"http://28.7.186.212:8150 (docusign)\",\n \"http://28.7.186.212:8158 (gmail)\"\n ],\n \"scoring_components\": [\n {\n \"name\": \"Notion N1\",\n \"weight\": 0.07,\n \"description\": \"新建 Aspen QBR 议程页面\",\n \"check_logic\": \"遍历 current_state.pages,排除 initial_state 中已存在的 pageId,检查是否有页面标题经 norm 处理后同时包含 'aspen' 和 'qbr'(或 'quarterly business review')\",\n \"pass_condition\": \"存在一个新的 Notion 页面,其标题同时提及 Aspen 和 QBR\"\n },\n {\n \"name\": \"Notion N2\",\n \"weight\": 0.18,\n \"description\": \"四个指定 section 均包含 heading 和非空内容\",\n \"check_logic\": \"在 qbr_page 的 blockIds 中顺序遍历 block,识别 heading 类型块是否匹配 SECTIONS(business goals、usage highlights、risks、next actions)之一;匹配后,后续非 heading 块若 content.strip() 非空,则标记该 section 有内容。每个 section 独立计分 0.045。\",\n \"pass_condition\": \"四个 section 每个都必须出现对应的 heading 且在该 heading 下至少有一个非空的非 heading 内容块\"\n },\n {\n \"name\": \"Salesforce S1\",\n \"weight\": 0.20,\n \"description\": \"新建 QBR 事件,时间、关联对象和负责人正确\",\n \"check_logic\": \"遍历 current_state.activities,排除 initial_state 中已有的 activityId,筛选 type='event' 且 subject 经 norm 后包含 'qbr' 和 'aspen' 的新活动;检查 startDateTime 匹配 TARGET_QBR_START(目标日期 14:00)、endDateTime 匹配 TARGET_QBR_END(目标日期 14:45)、relatedToType='account'、relatedToId='account-1'、assignedToId='user-1'。\",\n \"pass_condition\": \"存在一个新的 Event,主题为 Aspen QBR,开始时间为目标日期 14:00,结束时间为 14:45,关联 account-1,负责人为 user-1\"\n },\n {\n \"name\": \"Salesforce S2\",\n \"weight\": 0.10,\n \"description\": \"机会 opp-1 向前推进且仍处于开放阶段\",\n \"check_logic\": \"在 current_state.opportunities 中查找 opportunityId='opp-1',将其 stage 经 norm 后与集合 {'needs analysis', 'value proposition', 'proposal', 'negotiation'} 比对。\",\n \"pass_condition\": \"opp-1 的阶段为 Needs Analysis、Value Proposition、Proposal 或 Negotiation(即向前推进且未关闭)\"\n },\n {\n \"name\": \"DocuSign\",\n \"weight\": 0.20,\n \"description\": \"env_1 发送给 Daniel 且 distractor env_2 保持草稿\",\n \"check_logic\": \"检查 current_state.envelopes 中 id='env_1' 的 envelope:subject 经 norm 后包含 'aspen',status='sent',sentAt 非空,收件人列表中存在 email 包含 'daniel.brooks@aspendynamics.com' 且其 status 为 'sent' 或 'delivered';同时 id='env_2' 的 envelope status 必须为 'draft'。两者同时满足才得分。\",\n \"pass_condition\": \"env_1 状态为 sent、主题含 Aspen、Daniel 的收件人状态为 sent/delivered,且 env_2 状态仍��� draft\"\n },\n {\n \"name\": \"Gmail G1\",\n \"weight\": 0.12,\n \"description\": \"新建发送给 Daniel 的邮件且主题非空\",\n \"check_logic\": \"遍历 current_state.emails,排除 initial_state 中已有的 id,筛选 folder='sent' 且 to 列表中任一收件人 email 包含 'daniel.brooks@aspendynamics.com' 的新邮件,并检查 subject 经 strip 后非空。\",\n \"pass_condition\": \"存在一封新的 sent 邮件发送给 daniel.brooks@aspendynamics.com,且主题非空\"\n },\n {\n \"name\": \"Gmail G2\",\n \"weight\": 0.13,\n \"description\": \"邮件正文包含议程、QBR 日期和 2PM 时间\",\n \"check_logic\": \"对 new_sent.body 进行 norm 处理,统计包含 SECTIONS 中至少 3 个 section 名称(得 0.07);检查正文是否通过 text_mentions_target_date 提及目标 QBR 日期(得 0.03);检查是否通过 text_mentions_2pm 提及 2 PM(得 0.03)。三个子条件分数累加为 sub 后加入 total。\",\n \"pass_condition\": \"正文至少提及 4 个议程 section 中的 3 个、提及目标 QBR 日期、并提及 2 PM 时间\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数累加求和,最终用 min(total, 1.0) 钳制到上限后四舍五入到 4 位小数\",\n \"failure_modes\": [\n \"读取 /tmp/task_web_sid 失败或内容为空:打印 CRITICAL 并返回 REWARD: 0.0 后 sys.exit(0)\",\n \"从任一 mock 服务(notion/salesforce/docusign/gmail)拉取状态失败:打印 CRITICAL 并返回 REWARD: 0.0 后 sys.exit(0)\",\n \"任一 mock 返回的 current_state 为 None:打印 CRITICAL 并返回 REWARD: 0.0 后 sys.exit(0)\",\n \"Notion 未找到新的 Aspen QBR 页面:N1 和 N2 均不得分\",\n \"Salesforce 未找到符合条件的新 QBR Event:S1 不得分\",\n \"opp-1 阶段未前进或已关闭:S2 不得分\",\n \"DocuSign env_1 未发送或 Daniel 状态不对,或 env_2 不再是 draft:DocuSign 组件 0.20 分全部丢失\",\n \"Gmail 未找到发给 Daniel 的新 sent 邮件:G1 和 G2 均不得分\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,并依次从 notion、salesforce、docusign、gmail 四个 mock 服务拉取 initial_state 与 current_state;同时从 /tmp/task_qbr_date 加载目标日期(或默认取本周五)。随后按顺序执行验证:1) Notion 部分查找标题同时包含 Aspen 和 QBR 的新页面(0.07),并检查该页面是否包含 business goals、usage highlights、risks、next actions 四个 section 的 heading 及非空内容(每个 0.045);2) Salesforce 部分查找新的 Event,验证其主题、目标日期 14:00-14:45 的时间、关联 account-1 及负责人 user-1(0.20),并检查 opp-1 的阶段是否推进到开放的前进阶段(0.10);3) DocuSign 部分验证 env_1 变为 sent 且收件人 Daniel 状态为 sent/delivered,同时 distractor env_2 必须保持 draft(0.20);4) Gmail 部分查找发给 Daniel 的新 sent 邮件,验证主题非空(0.12),并检查正文是否至少提及 3 个议程 section(0.07)、目标 QBR 日期(0.03)和 2 PM 时间(0.03)。所有子项分数累加,最终通过 min(total, 1.0) 限制上限并四舍五入输出。\",\n \"confidence\": 1.0\n}\n```\n\n我需要确保没有使用 Markdown 代码块,且输出严格是 JSON。让我再检查一下 domain,docstring 写的是 \"mock_websites (multi-mock)\",我应该保留为 \"mock_websites\" 还是原样?用户说 \"如 mock_websites / software_engineer / libreoffice_calc\",所以 \"mock_websites\" 应该可以。或者我可以写 \"mock_websites (multi-mock)\"?用户说 \"从 docstring 中提取的领域\",docstring 中明确写了 \"Domain: mock_websites (multi-mock)\"。为了准确,我应该保留原样或至少保留核心。看示例是保留主要标识,我会用 \"mock_websites\" 因为示例里就是这样用的。\n\n再检查 data_sources,用户示例里有 \"slack_mock、github_mock、salesforce_mock、/tmp/task_web_sid\"。我应该列出具体的 URL 或服务名。我会用 \"notion_mock\"、\"salesforce_mock\"、\"docusign_mock\"、\"gmail_mock\" 还是具体 URL?代码里用的是 MOCKS 字典,URL 是具体的 IP:端口。我会写 URL 并标注名称,这样更准确。\n\n再检查 weight 字段。Gmail G2 的 weight 应该是 0.13,虽然内部是 0.07+0.03+0.03,但作为一个组件整体是 0.13。或者我应该拆成三个子组件?用户要求列出组件,我可以把 G2 作为一个组件,weight 0.13,在 check_logic 中说明内部分数。这样比较合理,因为代码里它们是放在一个 try 块里并累加到 sub 再 total += sub。\n\nDocuSign 也是一个整体 0.20 的复合组件。\n\nNotion N2 是 0.18 整体,内部 4 个 0.045。我可以作为一个组件 weight 0.18。\n\n这样组件列表就是:\n- Notion N1: 0.07\n- Notion N2: 0.18\n- Salesforce S1: 0.20\n- Salesforce S2: 0.10\n- DocuSign: 0.20\n- Gmail G1: 0.12\n- Gmail G2: 0.13\n\n总和正好是 1.0。\n\n最后确认 JSON 格式正确,没有 trailing comma,所有字符串正确转义。 </think> {\"task_id\":\"csm_qbr_renewal_003\",\"domain\":\"mock_websites\",\"summary\":\"验证在 Notion、Salesforce、DocuSign、Gmail 上完成 CSM Renewal QBR 准备任务的行为,包括创建 QBR 议程页面、安排会议事件、推进销售机会、发送 DocuSign 信封以及发送包含议程和会议时间的邮件。\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"/tmp/task_qbr_date\",\"http://28.7.186.212:8186 (notion)\",\"http://28.7.186.212:8195 (salesforce)\",\"http://28.7.186.212:8150 (docusign)\",\"http://28.7.186.212:8158 (gmail)\"],\"scoring_components\":[{\"name\":\"Notion N1\",\"weight\":0.07,\"description\":\"新建 Aspen QBR 议程页面\",\"check_logic\":\"遍历 current_state.pages,排除 initial_state 中已存在的 pageId,检查是否有页面标题经 norm 处理后同时包含 'aspen' 和 'qbr'(或 'quarterly business review')\",\"pass_condition\":\"存在一个新的 Notion 页面,其标题同时提及 Aspen 和 QBR\"},{\"name\":\"Notion N2\",\"weight\":0.18,\"description\":\"四个指定 section 均包含 heading 和非空内容\",\"check_logic\":\"在 qbr_page 的 blockIds 中顺序遍历 block,识别 heading 类型块是否匹配 SECTIONS(business goals、usage highlights、risks、next actions)之一;匹配后,后续非 heading 块若 content.strip() 非空,则标记该 section 有内容。每个 section 独立计分 0.045。\",\"pass_condition\":\"四个 section 每个都必须出现对应的 heading 且在该 heading 下至少有一个非空的非 heading 内容块\"},{\"name\":\"Salesforce S1\",\"weight\":0.20,\"description\":\"新建 QBR 事件,时间、关联对象和负责人正确\",\"check_logic\":\"遍历 current_state.activities,排除 initial_state 中已有的 activityId,筛选 type='event' 且 subject 经 norm 后包含 'qbr' 和 'aspen' 的新活动;检查 startDateTime 匹配 TARGET_QBR_START(目标日期 14:00)、endDateTime 匹配 TARGET_QBR_END(目标日期 14:45)、relatedToType='account'、relatedToId='account-1'、assignedToId='user-1'。\",\"pass_condition\":\"存在一个新的 Event,主题为 Aspen QBR,开始时间为目标日期 14:00,结束时间为 14:45,关联 account-1,负责人为 user-1\"},{\"name\":\"Salesforce S2\",\"weight\":0.10,\"description\":\"机会 opp-1 向前推进且仍处于开放阶段\",\"check_logic\":\"在 current_state.opportunities 中查找 opportunityId='opp-1',将其 stage 经 norm 后与集合 {'needs analysis', 'value proposition', 'proposal', 'negotiation'} 比对。\",\"pass_condition\":\"opp-1 的阶段为 Needs Analysis、Value Proposition、Proposal 或 Negotiation(即向前推进且未关闭)\"},{\"name\":\"DocuSign\",\"weight\":0.20,\"description\":\"env_1 发送给 Daniel 且 distractor env_2 保持草稿\",\"check_logic\":\"检查 current_state.envelopes 中 id='env_1' 的 envelope:subject 经 norm 后包含 'aspen',status='sent',sentAt 非空,收件人列表中存在 email 包含 'daniel.brooks@aspendynamics.com' 且其 status 为 'sent' 或 'delivered';同时 id='env_2' 的 envelope status 必须为 'draft'。两者同时满足才得分。\",\"pass_condition\":\"env_1 状态为 sent、主题含 Aspen、Daniel 的收件人状态为 sent/delivered,且 env_2 状态仍为 draft\"},{\"name\":\"Gmail G1\",\"weight\":0.12,\"description\":\"新建发送给 Daniel 的邮件且主题非空\",\"check_logic\":\"遍历 current_state.emails,排除 initial_state 中已有的 id,筛选 folder='sent' 且 to 列表中任一收件人 email 包含 'daniel.brooks@aspendynamics.com' 的新邮件,并检查 subject 经 strip 后非空。\",\"pass_condition\":\"存在一封新的 sent 邮件发送给 daniel.brooks@aspendynamics.com,且主题非空\"},{\"name\":\"Gmail G2\",\"weight\":0.13,\"description\":\"邮件正文包含议程、QBR 日期和 2PM 时间\",\"check_logic\":\"对 new_sent.body 进行 norm 处理,统计包含 SECTIONS 中至少 3 个 section 名称(得 0.07);检查正文是否通过 text_mentions_target_date 提及目标 QBR 日期(得 0.03);检查是否通过 text_mentions_2pm 提及 2 PM(得 0.03)。三个子条件分数累加为 sub 后加入 total。\",\"pass_condition\":\"正文至少提及 4 个议程 section 中的 3 个、提及目标 QBR 日期、并提及 2 PM 时间\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数累加求和,最终用 min(total, 1.0) 钳制到上限后四舍五入到 4 位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或内容为空:打印 CRITICAL 并返回 REWARD: 0.0 后 sys.exit(0)\",\"从任一 mock 服务(notion/salesforce/docusign/gmail)拉取状态失败:打印 CRITICAL 并返回 REWARD: 0.0 后 sys.exit(0)\",\"任一 mock 返回的 current_state 为 None:打印 CRITICAL 并返回 REWARD: 0.0 后 sys.exit(0)\",\"Notion 未找到新的 Aspen QBR 页面:N1 和 N2 均不得分\",\"Salesforce 未找��符合条件的新 QBR Event:S1 不得分\",\"opp-1 阶段未前进或已关闭:S2 不得分\",\"DocuSign env_1 未发送或 Daniel 状态不对,或 env_2 不再是 draft:DocuSign 组件 0.20 分全部丢失\",\"Gmail 未找到发给 Daniel 的新 sent 邮件:G1 和 G2 均不得分\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,并依次从 notion、salesforce、docusign、gmail 四个 mock 服务拉取 initial_state 与 current_state;同时从 /tmp/task_qbr_date 加载目标日期(或默认取本周五)。随后按顺序执行验证:1) Notion 部分查找标题同时包含 Aspen 和 QBR 的新页面(0.07),并检查该页面是否包含 business goals、usage highlights、risks、next actions 四个 section 的 heading 及非空内容(每个 0.045);2) Salesforce 部分查找新的 Event,验证其主题、目标日期 14:00-14:45 的时间、关联 account-1 及负责人 user-1(0.20),并检查 opp-1 的阶段是否推进到开放的前进阶段(0.10);3) DocuSign 部分验证 env_1 变为 sent 且收件人 Daniel 状态为 sent/delivered,同时 distractor env_2 必须保持 draft(0.20);4) Gmail 部分查找发给 Daniel 的新 sent 邮件,验证主题非空(0.12),并检查正文是否至少提及 3 个议程 section(0.07)、目标 QBR 日期(0.03)和 2 PM 时间(0.03)。所有子项分数累加,最终通过 min(total, 1.0) 限制上限并四舍五入输出。\",\"confidence\":1.0}"
87
+ }
csops_p1_incident_002/_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"