lkeab commited on
Commit
788f047
·
verified ·
1 Parent(s): e5d5706

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_contract_signature_001/_cua_gym_vm_bridge.sh +106 -0
  2. ae_contract_signature_001/initial_setup.py +609 -0
  3. ae_contract_signature_001/reward.py +467 -0
  4. ae_contract_signature_001/reward_label.json +63 -0
  5. ae_deal_handoff_002__long/_cua_gym_vm_bridge.sh +106 -0
  6. ae_deal_handoff_002__long/initial_setup.py +762 -0
  7. ae_deal_handoff_002__long/reward.py +825 -0
  8. calc_income_statement_001__long/.PLACEHOLDER +5 -0
  9. calc_income_statement_001__long/10da84b0-f0cf-58ff-b185-1c101d3b8b00_IncomeStatement2_1.xlsx +0 -0
  10. calc_income_statement_001__long/350e50bf-8624-51bc-91b7-a8dd0462e518_IncomeStatement2_2.xlsx +0 -0
  11. calc_income_statement_001__long/4429656d-69b9-58f3-af62-b51df1b7a682_IncomeStatement2_4.xlsx +0 -0
  12. calc_income_statement_001__long/5_IncomeStatement2_gt1_1.xlsx +0 -0
  13. calc_income_statement_001__long/5_IncomeStatement2_gt1_2.xlsx +0 -0
  14. calc_income_statement_001__long/5_IncomeStatement2_gt1_3.xlsx +0 -0
  15. calc_income_statement_001__long/5_IncomeStatement2_gt1_4.xlsx +0 -0
  16. calc_income_statement_001__long/5_IncomeStatement2_gt1_5.xlsx +0 -0
  17. calc_income_statement_001__long/876296d5-884d-51ad-b5dd-285374e43ac4_IncomeStatement2_5.xlsx +0 -0
  18. calc_income_statement_001__long/93be5864-b16f-5f70-8d80-1a515dedf794_IncomeStatement2_3.xlsx +0 -0
  19. calc_sales_rep_002__long/.PLACEHOLDER +5 -0
  20. calc_sales_rep_002__long/0b920aed-a86f-552f-8c4e-4230d20fb019_SalesRep_3.xlsx +0 -0
  21. calc_sales_rep_002__long/3_SalesRep_gt1_1.xlsx +0 -0
  22. calc_sales_rep_002__long/3_SalesRep_gt1_2.xlsx +0 -0
  23. calc_sales_rep_002__long/3_SalesRep_gt1_3.xlsx +0 -0
  24. calc_sales_rep_002__long/3_SalesRep_gt1_4.xlsx +0 -0
  25. calc_sales_rep_002__long/3_SalesRep_gt1_5.xlsx +0 -0
  26. calc_sales_rep_002__long/5e509850-8212-5d6a-958f-c2d16aee6ceb_SalesRep_4.xlsx +0 -0
  27. calc_sales_rep_002__long/6c32f05d-1532-5354-a3db-ac954dd7d2ca_SalesRep_1.xlsx +0 -0
  28. calc_sales_rep_002__long/dd7e65b9-bfb4-542a-adf9-13c4153016fc_SalesRep_2.xlsx +0 -0
  29. calc_sales_rep_002__long/e5d3b713-bd13-5796-83bc-ab47351ba44c_SalesRep_5.xlsx +0 -0
  30. csm_training_rate_005/_cua_gym_vm_bridge.sh +106 -0
  31. csm_training_rate_005/reward_label.json +58 -0
  32. hr_midyear_review_007__long/_cua_gym_vm_bridge.sh +106 -0
  33. hr_midyear_review_007__long/initial_setup.py +794 -0
  34. hr_midyear_review_007__long/reward.py +359 -0
  35. itops_access_approval_001/_cua_gym_vm_bridge.sh +106 -0
  36. itops_access_approval_001/initial_setup.py +307 -0
  37. itops_access_approval_001/reward.py +184 -0
  38. itops_access_approval_001/reward_label.json +52 -0
  39. ops_board_agenda_008/_cua_gym_vm_bridge.sh +106 -0
  40. ops_board_agenda_008/initial_setup.py +256 -0
  41. ops_board_agenda_008/reward.py +124 -0
  42. ops_board_agenda_008/reward_label.json +74 -0
  43. ops_catalog_update_003__long/_cua_gym_vm_bridge.sh +106 -0
  44. ops_catalog_update_003__long/initial_setup.py +634 -0
  45. ops_catalog_update_003__long/reward.py +326 -0
  46. ops_inbox_meeting_007/_cua_gym_vm_bridge.sh +106 -0
  47. ops_inbox_meeting_007/initial_setup.py +257 -0
  48. ops_inbox_meeting_007/reward.py +107 -0
  49. ops_inbox_meeting_007/reward_label.json +78 -0
  50. ops_risk_log_006/_cua_gym_vm_bridge.sh +106 -0
ae_contract_signature_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"
ae_contract_signature_001/initial_setup.py ADDED
@@ -0,0 +1,609 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: Get the Globex Platform Expansion order form out for signature.
194
+ Task ID: ae_contract_signature_001
195
+ Domain: mock_websites (multi-mock)
196
+ Mocks: salesforce, notion, docusign, slack
197
+
198
+ Persona: Alex Rivera (user-1), Account Executive at Northwind Cloud
199
+ (alex.rivera@northwindcloud.com). Today = 2026-06-24.
200
+
201
+ The deal to process:
202
+ opp-1 'Globex - Platform Expansion' | Globex Corporation | Maria Gomez
203
+ (VP of Operations, maria.gomez@globex.com) | $120,000 | Closed Won.
204
+
205
+ Pre-task state ONLY. MUST NOT contain task-completed elements:
206
+ - DocuSign: NO envelope for the Globex Platform Expansion order form.
207
+ - Notion 'Contracts' database: NO row for Globex Platform Expansion.
208
+ - Salesforce: NO activity on opp-1 recording the order form / DocuSign
209
+ envelope being sent.
210
+ - Slack #deal-desk: NO message about Globex awaiting signature.
211
+
212
+ Distractors that MUST exist and stay untouched by the golden state:
213
+ - Salesforce opp-2 (Initech - Annual Renewal, Negotiation, NOT won).
214
+ - Salesforce opp-6 (Globex - SMB Add-on, Closed Lost).
215
+ - DocuSign address-book contacts Michael Torres, Daniel Park (NOT signers).
216
+ """
217
+ import os
218
+ import shlex
219
+ import subprocess
220
+ import time
221
+ import uuid
222
+
223
+ import requests
224
+
225
+ # --- Mock registry ---
226
+ MOCKS = {
227
+ 'salesforce': 'http://28.7.184.198:8175',
228
+ 'notion': 'http://28.7.184.198:8166',
229
+ 'docusign': 'http://28.7.184.198:8130',
230
+ 'slack': 'http://28.7.184.198:8178',
231
+ }
232
+
233
+ # --- Shared session id ---
234
+ sid = str(uuid.uuid4())
235
+ with open('/tmp/task_web_sid', 'w') as f:
236
+ f.write(sid)
237
+ print(f'sid = {sid}')
238
+
239
+
240
+ # ----------------------------------------------------------------------------
241
+ # Salesforce state
242
+ # opp-1 Globex Platform Expansion Closed Won <- the deal to process
243
+ # opp-2 Initech Annual Renewal Negotiation (distractor, not won)
244
+ # opp-6 Globex SMB Add-on Closed Lost (distractor, lost)
245
+ # NO activity on opp-1 about the order form / DocuSign envelope.
246
+ # ----------------------------------------------------------------------------
247
+ def salesforce_state():
248
+ user_1 = {
249
+ "userId": "user-1", "firstName": "Alex", "lastName": "Rivera",
250
+ "email": "alex.rivera@northwindcloud.com", "phone": "(555) 240-1188",
251
+ "title": "Account Executive", "department": "Sales", "role": "Rep",
252
+ "avatar": "https://i.pravatar.cc/150?u=user-1",
253
+ "timezone": "America/Los_Angeles", "locale": "en-US",
254
+ "theme": "lightning",
255
+ }
256
+ user_2 = {
257
+ "userId": "user-2", "firstName": "Sam", "lastName": "Lee",
258
+ "email": "sam.lee@northwindcloud.com", "phone": "(555) 240-1190",
259
+ "title": "Sales Manager", "department": "Sales", "role": "Manager",
260
+ "avatar": "https://i.pravatar.cc/150?u=user-2",
261
+ "timezone": "America/Los_Angeles", "locale": "en-US",
262
+ "theme": "lightning",
263
+ }
264
+
265
+ accounts = [
266
+ {"accountId": "account-1", "name": "Globex Corporation",
267
+ "type": "Customer", "industry": "Technology", "revenue": 480000000,
268
+ "employees": 5200, "ownerId": "user-1",
269
+ "billingStreet": "500 Innovation Way", "billingCity": "San Jose",
270
+ "billingState": "CA", "billingZip": "95110", "billingCountry": "USA"},
271
+ {"accountId": "account-2", "name": "Initech LLC", "type": "Customer",
272
+ "industry": "Software", "revenue": 22000000, "employees": 320,
273
+ "ownerId": "user-1", "billingStreet": "78 Office Park Dr",
274
+ "billingCity": "Austin", "billingState": "TX",
275
+ "billingZip": "73301", "billingCountry": "USA"},
276
+ ]
277
+
278
+ contacts = [
279
+ {"contactId": "contact-1", "accountId": "account-1",
280
+ "firstName": "Maria", "lastName": "Gomez", "title": "VP of Operations",
281
+ "department": "Operations", "email": "maria.gomez@globex.com",
282
+ "phone": "(555) 101-2201", "ownerId": "user-1"},
283
+ {"contactId": "contact-2", "accountId": "account-2",
284
+ "firstName": "Daniel", "lastName": "Park", "title": "CTO",
285
+ "department": "Engineering", "email": "daniel.park@initech.com",
286
+ "phone": "(555) 330-2201", "ownerId": "user-1"},
287
+ ]
288
+
289
+ opportunities = [
290
+ {"opportunityId": "opp-1", "name": "Globex - Platform Expansion",
291
+ "accountId": "account-1", "contactId": "contact-1", "amount": 120000,
292
+ "closeDate": "2026-06-20", "stage": "Closed Won", "probability": 100,
293
+ "ownerId": "user-1"},
294
+ {"opportunityId": "opp-2", "name": "Initech - Annual Renewal",
295
+ "accountId": "account-2", "contactId": "contact-2", "amount": 60000,
296
+ "closeDate": "2026-07-15", "stage": "Negotiation", "probability": 60,
297
+ "ownerId": "user-1"},
298
+ {"opportunityId": "opp-6", "name": "Globex - SMB Add-on",
299
+ "accountId": "account-1", "contactId": "contact-1", "amount": 9000,
300
+ "closeDate": "2026-05-30", "stage": "Closed Lost", "probability": 0,
301
+ "ownerId": "user-1"},
302
+ ]
303
+
304
+ # An unrelated pre-existing activity on opp-1 (a closed-won celebration
305
+ # note). It is NOT about the order form / DocuSign envelope being sent,
306
+ # so it must not satisfy the success checkpoint by itself.
307
+ activities = [
308
+ {"activityId": "activity-1", "type": "task",
309
+ "subject": "Send thank-you note to Globex stakeholders",
310
+ "status": "Completed", "priority": "Normal",
311
+ "dueDate": "2026-06-20",
312
+ "relatedToType": "opportunity", "relatedToId": "opp-1",
313
+ "assignedToId": "user-1",
314
+ "description": "Closed-won celebration outreach to the Globex team.",
315
+ "createdDate": "2026-06-20T17:00:00.000Z",
316
+ "modifiedDate": "2026-06-20T17:00:00.000Z"},
317
+ ]
318
+
319
+ return {
320
+ "user": user_1,
321
+ "users": [user_1, user_2],
322
+ "leads": [],
323
+ "accounts": accounts,
324
+ "contacts": contacts,
325
+ "opportunities": opportunities,
326
+ "cases": [],
327
+ "activities": activities,
328
+ "chatterPosts": [],
329
+ "files": [],
330
+ "following": [],
331
+ "recentlyViewed": [],
332
+ "dismissedNotifications": [],
333
+ }
334
+
335
+
336
+ # ----------------------------------------------------------------------------
337
+ # Notion state
338
+ # workspace 'Northwind Sales' with a 'Contracts' database (table view).
339
+ # Properties: Customer (text), Deal (text), Amount (number),
340
+ # Status (select: Draft/Sent/Completed).
341
+ # Has ONE unrelated existing row (Acme Tooling) but NO Globex Platform
342
+ # Expansion row.
343
+ # ----------------------------------------------------------------------------
344
+ def notion_state():
345
+ user = {"id": "user-1", "name": "Alex Rivera",
346
+ "email": "alex.rivera@northwindcloud.com", "avatar": ""}
347
+ workspace = {"id": "ws-1", "name": "Northwind Sales", "icon": "\U0001F3E2",
348
+ "members": ["user-1"]}
349
+
350
+ db_id = "db-contracts"
351
+ properties = [
352
+ {"id": "prop_customer", "name": "Customer", "type": "text"},
353
+ {"id": "prop_deal", "name": "Deal", "type": "text"},
354
+ {"id": "prop_amount", "name": "Amount", "type": "number"},
355
+ {"id": "prop_status", "name": "Status", "type": "select",
356
+ "options": ["Draft", "Sent", "Completed"]},
357
+ ]
358
+
359
+ # One unrelated existing row so the tracker isn't empty (distractor data).
360
+ existing_row = {
361
+ "id": "row-acme",
362
+ "title": "Acme Tooling",
363
+ "icon": "", "cover": None, "parentId": db_id,
364
+ "blockIds": [], "favorite": False,
365
+ "createdDate": "2026-05-12T09:00:00.000Z",
366
+ "lastEditedDate": "2026-05-12T09:00:00.000Z",
367
+ "properties": {
368
+ "prop_customer": "Acme Tooling",
369
+ "prop_deal": "Acme - Starter Bundle",
370
+ "prop_amount": 30000,
371
+ "prop_status": "Completed",
372
+ },
373
+ }
374
+
375
+ contracts_db = {
376
+ "id": db_id,
377
+ "title": "Contracts",
378
+ "icon": "\U0001F4DD", "cover": None, "parentId": None,
379
+ "type": "database", "viewType": "table",
380
+ "properties": properties,
381
+ "views": [{
382
+ "id": "view-contracts", "name": "Table", "type": "table",
383
+ "filters": [], "sorts": [], "groupBy": None,
384
+ "visibleProperties": ["prop_customer", "prop_deal",
385
+ "prop_amount", "prop_status"],
386
+ }],
387
+ "items": ["row-acme"],
388
+ "blockIds": [], "favorite": False,
389
+ "createdDate": "2026-05-01T09:00:00.000Z",
390
+ }
391
+
392
+ return {
393
+ "user": user,
394
+ "workspace": workspace,
395
+ "pages": {db_id: contracts_db, "row-acme": existing_row},
396
+ "blocks": {},
397
+ "trash": [],
398
+ "comments": {},
399
+ "settings": {"appearance": "light", "startWeekMonday": False,
400
+ "fontSize": "default"},
401
+ "notifications": [],
402
+ "pageOrder": [db_id],
403
+ }
404
+
405
+
406
+ # ----------------------------------------------------------------------------
407
+ # DocuSign state
408
+ # user Alex Rivera. An 'Order Form' template + address-book contact for
409
+ # Maria Gomez. Distractor contacts (Michael Torres, Daniel Park) present.
410
+ # NO envelope for the Globex order form.
411
+ # ----------------------------------------------------------------------------
412
+ def docusign_state():
413
+ user = {
414
+ "id": "user-1", "name": "Alex Rivera",
415
+ "email": "alex.rivera@northwindcloud.com",
416
+ "title": "Account Executive", "company": "Northwind Cloud",
417
+ "avatar": "https://i.pravatar.cc/150?u=user-1",
418
+ "memberSince": "2024-01-15T00:00:00Z",
419
+ "settings": {"defaultReminderDays": 3, "defaultExpirationDays": 120,
420
+ "timezone": "America/Los_Angeles"},
421
+ }
422
+
423
+ # One unrelated, already-completed envelope as a distractor — nothing to
424
+ # do with the Globex Platform Expansion order form.
425
+ distractor_env = {
426
+ "id": "env_initech_old",
427
+ "subject": "Initech - NDA",
428
+ "message": "Please review and sign the mutual NDA.",
429
+ "status": "completed",
430
+ "createdAt": "2026-04-10T09:00:00Z",
431
+ "sentAt": "2026-04-10T09:30:00Z",
432
+ "completedAt": "2026-04-12T14:00:00Z",
433
+ "voidedAt": None, "declinedAt": None,
434
+ "lastActivityAt": "2026-04-12T14:00:00Z", "expiresAt": None,
435
+ "senderId": "user-1", "folderId": None, "templateId": None,
436
+ "reminderEnabled": False, "reminderDays": 3, "reminderFrequency": 2,
437
+ "documents": [{"id": "doc_initech_nda", "name": "Initech_NDA.pdf",
438
+ "pageCount": 3, "order": 1,
439
+ "fileUrl": "https://picsum.photos/seed/initechnda/800/1100",
440
+ "fileType": "pdf"}],
441
+ "recipients": [{"id": "rec_initech_nda", "name": "Daniel Park",
442
+ "email": "daniel.park@initech.com", "role": "signer",
443
+ "routingOrder": 1, "status": "signed",
444
+ "signedAt": "2026-04-12T14:00:00Z",
445
+ "viewedAt": "2026-04-11T10:00:00Z",
446
+ "deliveredAt": "2026-04-10T09:31:00Z",
447
+ "declinedAt": None, "declineReason": None}],
448
+ "fields": [],
449
+ "history": [
450
+ {"id": "evt_initech_nda_1", "timestamp": "2026-04-10T09:00:00Z",
451
+ "action": "created", "actorName": "Alex Rivera",
452
+ "actorEmail": "alex.rivera@northwindcloud.com",
453
+ "details": "Envelope created"},
454
+ {"id": "evt_initech_nda_2", "timestamp": "2026-04-12T14:00:00Z",
455
+ "action": "completed", "actorName": "Daniel Park",
456
+ "actorEmail": "daniel.park@initech.com",
457
+ "details": "All recipients signed"},
458
+ ],
459
+ }
460
+
461
+ return {
462
+ "user": user,
463
+ "envelopes": [distractor_env],
464
+ "templates": [
465
+ {"id": "tmpl_order_form", "name": "Order Form",
466
+ "description": "Standard Northwind Cloud order form template.",
467
+ "createdAt": "2025-01-10T09:00:00Z",
468
+ "lastUsedAt": "2026-05-01T10:00:00Z",
469
+ "usageCount": 22, "ownerId": "user-1", "shared": True,
470
+ "documents": [{"id": "tdoc_order_form_1", "name": "Order_Form.pdf",
471
+ "pageCount": 4, "order": 1,
472
+ "fileUrl": "https://picsum.photos/seed/orderform/800/1100",
473
+ "fileType": "pdf"}],
474
+ "roles": [{"id": "trole_signer", "name": "Customer Signer",
475
+ "role": "signer", "routingOrder": 1}],
476
+ "fields": []},
477
+ ],
478
+ "folders": [],
479
+ "contacts": [
480
+ {"id": "con_maria", "name": "Maria Gomez",
481
+ "email": "maria.gomez@globex.com",
482
+ "company": "Globex Corporation", "title": "VP of Operations"},
483
+ {"id": "con_michael", "name": "Michael Torres",
484
+ "email": "michael.torres@example.com",
485
+ "company": "Stark Holdings", "title": "Procurement Lead"},
486
+ {"id": "con_daniel", "name": "Daniel Park",
487
+ "email": "daniel.park@initech.com",
488
+ "company": "Initech LLC", "title": "CTO"},
489
+ ],
490
+ "auditLog": [
491
+ {"id": "audit_initech_nda", "timestamp": "2026-04-12T14:00:00Z",
492
+ "action": "COMPLETE_ENVELOPE",
493
+ "details": "Initech - NDA completed",
494
+ "envelopeId": "env_initech_old"},
495
+ ],
496
+ }
497
+
498
+
499
+ # ----------------------------------------------------------------------------
500
+ # Slack state — workspace 'Northwind Cloud', currentUser Alex Rivera (user_1),
501
+ # channel '#deal-desk' exists with prior chatter but NO awaiting-signature
502
+ # message for Globex.
503
+ # ----------------------------------------------------------------------------
504
+ def slack_state():
505
+ user_1 = {"userId": "user_1", "fullName": "Alex Rivera",
506
+ "displayName": "Alex", "email": "alex.rivera@northwindcloud.com",
507
+ "avatar": "https://picsum.photos/200/200?random=1",
508
+ "status": "online", "statusMessage": "", "statusEmoji": "",
509
+ "timeZone": "America/Los_Angeles", "title": "Account Executive"}
510
+ user_2 = {"userId": "user_2", "fullName": "Sam Lee",
511
+ "displayName": "Sam", "email": "sam.lee@northwindcloud.com",
512
+ "avatar": "https://picsum.photos/200/200?random=2",
513
+ "status": "online", "statusMessage": "", "statusEmoji": "",
514
+ "timeZone": "America/Los_Angeles", "title": "Sales Manager"}
515
+
516
+ deal_desk = {
517
+ "channelId": "deal-desk", "name": "deal-desk",
518
+ "description": "Deal desk coordination",
519
+ "topic": "Contracts, order forms & signatures",
520
+ "isPrivate": False, "isStarred": False,
521
+ "members": ["user_1", "user_2"], "createdBy": "user_2",
522
+ "createdAt": "2024-01-01T10:00:00Z", "pinnedMessages": [],
523
+ "unreadCount": 0}
524
+
525
+ return {
526
+ "currentUser": user_1,
527
+ "workspace": {"workspaceId": "ws_1",
528
+ "workspaceName": "Northwind Cloud", "icon": ""},
529
+ "users": [user_1, user_2],
530
+ "channels": [deal_desk],
531
+ "messages": {
532
+ "deal-desk": [
533
+ {"messageId": "msg_1", "senderId": "user_2",
534
+ "content": "Reminder: log every order form you send out here "
535
+ "so finance can track signatures.",
536
+ "timestamp": "2026-06-24T08:05:00Z", "threadId": None,
537
+ "reactions": [], "attachments": [], "isEdited": False},
538
+ ],
539
+ },
540
+ "threads": {},
541
+ "dms": [],
542
+ "bookmarkedMessages": [],
543
+ "callHistory": [],
544
+ "settings": {"theme": "light", "notifications": "all",
545
+ "displayDensity": "comfortable", "showAvatars": True,
546
+ "use24Hour": False},
547
+ "invitations": [],
548
+ "notifications": [],
549
+ }
550
+
551
+
552
+ # ----------------------------------------------------------------------------
553
+ # Inject all states
554
+ # ----------------------------------------------------------------------------
555
+ STATE_BUILDERS = {
556
+ 'salesforce': salesforce_state,
557
+ 'notion': notion_state,
558
+ 'docusign': docusign_state,
559
+ 'slack': slack_state,
560
+ }
561
+
562
+ for name, build in STATE_BUILDERS.items():
563
+ url = MOCKS[name]
564
+ state = build()
565
+ resp = requests.post(f'{url}/post?sid={sid}',
566
+ json={'action': 'set', 'state': state}, timeout=30)
567
+ assert resp.status_code == 200, \
568
+ f'{name} injection failed: {resp.status_code} {resp.text}'
569
+ go = requests.get(f'{url}/go?sid={sid}', timeout=10).json()
570
+ assert go.get('initial_state') is not None, f'{name} initial_state is None'
571
+ print(f' injected {name}: initial_state OK')
572
+
573
+ print(f'All 4 mocks injected with sid={sid}')
574
+
575
+
576
+ # ----------------------------------------------------------------------------
577
+ # GUI-ready: launch Chrome on Salesforce (where the task starts)
578
+ # ----------------------------------------------------------------------------
579
+ def launch_gui(command, delay_sec=1.0):
580
+ env = os.environ.copy()
581
+ env['DISPLAY'] = ':0'
582
+ # Accept both a command string and a pre-split arg list (some tasks
583
+ # build arg lists themselves, e.g. se_hard_008).
584
+ if isinstance(command, str):
585
+ _parts = shlex.split(command)
586
+ else:
587
+ _parts = list(command)
588
+ # Inject CDP debug port so wait_mocks_loaded can verify browser render
589
+ # via Playwright connect_over_cdp. Idempotent: skip if any arg already
590
+ # starts with --remote-debugging-port (some tasks inject their own
591
+ # dynamic port, e.g. se_hard_008).
592
+ if _parts and 'google-chrome' in _parts[0] \
593
+ and not any(p.startswith('--remote-debugging-port') for p in _parts):
594
+ _parts[1:1] = ['--no-first-run', '--no-default-browser-check',
595
+ '--remote-debugging-port=1337']
596
+ _proc = subprocess.Popen(_parts, stdin=subprocess.DEVNULL,
597
+ stdout=subprocess.DEVNULL,
598
+ stderr=subprocess.DEVNULL, env=env,
599
+ start_new_session=True)
600
+ time.sleep(delay_sec)
601
+ if _proc.poll() is not None:
602
+ print(' WARNING: launch_gui process exited early (code=%s)'
603
+ % _proc.returncode)
604
+ return _proc
605
+ _primary_mock_url = MOCKS["salesforce"]
606
+ launch_gui(f'google-chrome "{MOCKS["salesforce"]}/?sid={sid}"', delay_sec=2.0)
607
+ _open_remaining_mock_tabs(_primary_mock_url)
608
+ wait_mocks_loaded()
609
+ print(f'GUI_READY: launched browser at {MOCKS["salesforce"]}/?sid={sid}')
ae_contract_signature_001/reward.py ADDED
@@ -0,0 +1,467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: Globex Platform Expansion order form — close-won contract signature flow
13
+ Task ID: ae_contract_signature_001
14
+ Domain: mock_websites (multi-mock: docusign, notion, salesforce, slack)
15
+
16
+ Scoring (1.0 total) — every component verifies a NEW artifact present in current_state
17
+ but ABSENT from initial_state (so it is the task-introduced change, not a precondition):
18
+
19
+ Component 1 — DocuSign envelope (0.35)
20
+ - a NEW envelope referencing the Globex Platform Expansion order form (0.10)
21
+ - status == 'sent' AND sentAt populated (0.10)
22
+ - exactly one signer recipient named 'Maria Gomez' / maria.gomez@globex.com (0.15)
23
+ Component 2 — Notion 'Contracts' row (0.25)
24
+ - NEW db row: Customer 'Globex Corporation', Deal ~ 'Platform Expansion',
25
+ Amount 120000, Status 'Sent'
26
+ Component 3 — Salesforce activity on opp-1 (0.20)
27
+ - NEW activity related to opp-1 referencing order form/DocuSign + sent,
28
+ AND opp-1 stage still 'Closed Won'
29
+ Component 4 — Slack #deal-desk message (0.20)
30
+ - NEW message mentioning Globex, amount 120000 ($120,000), awaiting signature
31
+
32
+ Verification is fully deterministic (structured mock state). No LLM judge used.
33
+ """
34
+ import os
35
+ import re
36
+ import unicodedata
37
+ from datetime import datetime
38
+
39
+ import requests
40
+
41
+ # Which state to score. Default 'current_state' (post-task / agent result).
42
+ # Override to 'initial_state' only for discriminator self-testing of the 0.0 baseline.
43
+ STATE_TO_SCORE = os.environ.get('REWARD_STATE_KEY', 'current_state')
44
+
45
+ MOCKS = {
46
+ 'docusign': 'http://28.7.184.198:8130',
47
+ 'notion': 'http://28.7.184.198:8166',
48
+ 'salesforce': 'http://28.7.184.198:8175',
49
+ 'slack': 'http://28.7.184.198:8178',
50
+ }
51
+
52
+
53
+ def read_sid():
54
+ try:
55
+ with open('/tmp/task_web_sid') as f:
56
+ sid = f.read().strip()
57
+ if not sid:
58
+ raise ValueError('sid empty')
59
+ return sid
60
+ except Exception as e:
61
+ print(f'CRITICAL: cannot read /tmp/task_web_sid: {e}')
62
+ return None
63
+
64
+
65
+ def fetch_all(sid):
66
+ """Fetch /go from every mock. Returns {name: {initial, current}} or None on failure."""
67
+ out = {}
68
+ for name, base in MOCKS.items():
69
+ try:
70
+ data = requests.get(f'{base}/go?sid={sid}', timeout=15).json()
71
+ except Exception as e:
72
+ print(f'CRITICAL: cannot fetch {name} state: {e}')
73
+ return None
74
+ out[name] = {
75
+ 'initial': data.get('initial_state') or {},
76
+ 'current': data.get('current_state') or {},
77
+ }
78
+ return out
79
+
80
+
81
+ def pick(states, name):
82
+ """Return (scored_state, initial_state) for a mock per STATE_TO_SCORE."""
83
+ s = states[name]
84
+ return s.get(STATE_TO_SCORE.replace('_state', '')), s['initial']
85
+
86
+
87
+ # ---------------------------------------------------------------------------
88
+ # Component checks. Each returns (points_awarded, max_points).
89
+ # Each is anchored to artifacts NEW in scored-state vs initial_state.
90
+ # ---------------------------------------------------------------------------
91
+
92
+ def _norm_words(value):
93
+ """Lowercase text and collapse punctuation/spacing for tolerant matching."""
94
+ if value is None:
95
+ return ''
96
+ text = unicodedata.normalize('NFKC', str(value)).lower()
97
+ text = re.sub(r'[^a-z0-9]+', ' ', text)
98
+ return re.sub(r'\s+', ' ', text).strip()
99
+
100
+
101
+ def _has_all(value, terms):
102
+ text = _norm_words(value)
103
+ return all(_norm_words(term) in text for term in terms)
104
+
105
+
106
+ def _has_any(value, terms):
107
+ text = _norm_words(value)
108
+ return any(_norm_words(term) in text for term in terms)
109
+
110
+
111
+ def _email(value):
112
+ return re.sub(r'\s+', '', str(value or '')).lower()
113
+
114
+
115
+ def _name_matches(value, first, last):
116
+ tokens = set(_norm_words(value).split())
117
+ return first.lower() in tokens and last.lower() in tokens
118
+
119
+
120
+ def _parse_datetime(value):
121
+ if not value:
122
+ return None
123
+ text = str(value).strip()
124
+ try:
125
+ return datetime.fromisoformat(text.replace('Z', '+00:00'))
126
+ except Exception:
127
+ pass
128
+ for fmt in ('%Y-%m-%d %H:%M:%S', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d'):
129
+ try:
130
+ return datetime.strptime(text[:19], fmt)
131
+ except Exception:
132
+ continue
133
+ return None
134
+
135
+
136
+ def _amount_matches(value, expected):
137
+ if isinstance(value, (int, float)):
138
+ return abs(float(value) - expected) < 0.01
139
+ text = str(value or '').lower().strip()
140
+ if not text:
141
+ return False
142
+ cleaned = text.replace(',', '').replace('$', '')
143
+ compact = re.sub(r'\s+', '', cleaned)
144
+ candidates = re.findall(r'\d+(?:\.\d+)?\s*k|\d+(?:\.\d+)?', cleaned)
145
+ if re.search(r'(?<!\d)120000(?!\d)', compact):
146
+ candidates.append('120000')
147
+ for raw in candidates:
148
+ try:
149
+ raw = raw.strip()
150
+ amount = float(raw[:-1]) * 1000 if raw.endswith('k') else float(raw)
151
+ except Exception:
152
+ continue
153
+ if abs(amount - expected) < 0.01:
154
+ return True
155
+ return False
156
+
157
+
158
+ def _sent_for_signature(value):
159
+ return (_has_any(value, [
160
+ 'awaiting signature', 'awaiting signatures', 'waiting for signature',
161
+ 'waiting on signature', 'pending signature', 'signature pending',
162
+ 'sent for signature', 'out for signature', 'needs signature',
163
+ 'awaiting sign off', 'pending sign off',
164
+ ]) or (
165
+ _has_any(value, ['sent', 'awaiting', 'waiting', 'pending', 'out'])
166
+ and _has_any(value, ['signature', 'signing', 'sign off'])
167
+ ))
168
+
169
+
170
+ def check_docusign(scored, initial):
171
+ """Component 1 — new Globex order-form envelope, sent, signer Maria Gomez. (0.35)"""
172
+ pts = 0.0
173
+ try:
174
+ ini_envs = initial.get('envelopes', []) or []
175
+ cur_envs = scored.get('envelopes', []) or []
176
+ ini_ids = {e.get('id') for e in ini_envs}
177
+ new_envs = [e for e in cur_envs if e.get('id') not in ini_ids]
178
+
179
+ # Identify the Globex Platform Expansion order-form envelope among NEW ones.
180
+ def is_globex_orderform(e):
181
+ blob = ' '.join([
182
+ str(e.get('subject', '')),
183
+ str(e.get('message', '')),
184
+ ' '.join(str(d.get('name', '')) for d in (e.get('documents', []) or [])),
185
+ ])
186
+ has_customer = _has_any(blob, ['globex', 'globex corporation'])
187
+ has_deal = _has_all(blob, ['platform', 'expansion'])
188
+ has_order_form = (
189
+ _has_all(blob, ['order', 'form'])
190
+ or _has_any(blob, ['orderform'])
191
+ )
192
+ return has_customer and has_deal and has_order_form
193
+
194
+ globex_new = [e for e in new_envs if is_globex_orderform(e)]
195
+ # Distractor guard: a new envelope referencing Initech or SMB Add-on is wrong.
196
+ bad_new = [e for e in new_envs
197
+ if _has_any(e.get('subject', ''), ['initech', 'smb add on'])]
198
+ if bad_new:
199
+ print(f'WARN: distractor envelope(s) created: '
200
+ f'{[e.get("subject") for e in bad_new]}')
201
+
202
+ if not globex_new:
203
+ print('FAIL: C1 — no NEW envelope referencing the Globex Platform Expansion '
204
+ 'order form')
205
+ return pts, 0.35
206
+ env = globex_new[0]
207
+
208
+ # 1a: new envelope referencing the Globex order form exists (0.10)
209
+ print(f'PASS: C1a — new Globex order-form envelope (subject="{env.get("subject")}") '
210
+ f'(0.10)')
211
+ pts += 0.10
212
+
213
+ # 1b: status indicates it was sent AND sentAt is a parseable timestamp (0.10)
214
+ status = _norm_words(env.get('status'))
215
+ sent_at = env.get('sentAt')
216
+ if status in {'sent', 'delivered'} and _parse_datetime(sent_at):
217
+ print(f'PASS: C1b — status {status}, sentAt={sent_at} (0.10)')
218
+ pts += 0.10
219
+ else:
220
+ print(f'FAIL: C1b — expected sent/delivered status + parseable sentAt, '
221
+ f'got status={env.get("status")} sentAt={sent_at}')
222
+
223
+ # 1c: exactly one signer recipient Maria Gomez / maria.gomez@globex.com (0.15)
224
+ recips = env.get('recipients', []) or []
225
+ signers = [r for r in recips if 'signer' in _norm_words(r.get('role', ''))]
226
+ if len(signers) == 1:
227
+ r = signers[0]
228
+ nm = str(r.get('name', '')).strip()
229
+ em = _email(r.get('email'))
230
+ name_ok = _name_matches(nm, 'maria', 'gomez') or em == 'maria.gomez@globex.com'
231
+ if name_ok and em == 'maria.gomez@globex.com':
232
+ print(f'PASS: C1c — single signer Maria Gomez <{em}> (0.15)')
233
+ pts += 0.15
234
+ else:
235
+ print(f'FAIL: C1c — signer mismatch: name="{r.get("name")}" '
236
+ f'email="{r.get("email")}"')
237
+ else:
238
+ print(f'FAIL: C1c — expected exactly 1 signer, found {len(signers)}')
239
+ except Exception as e:
240
+ print(f'ERROR: C1 (docusign) — {e}')
241
+ return pts, 0.35
242
+
243
+
244
+ def check_notion(scored, initial):
245
+ """Component 2 — new Contracts row for Globex Platform Expansion. (0.25)"""
246
+ max_pts = 0.25
247
+ try:
248
+ ini_pages = initial.get('pages', {}) or {}
249
+ cur_pages = scored.get('pages', {}) or {}
250
+
251
+ # Find the Contracts database (by title) in scored state.
252
+ db = None
253
+ for pid, p in cur_pages.items():
254
+ if p.get('type') == 'database' and _norm_words(p.get('title')) == 'contracts':
255
+ db = p
256
+ break
257
+ if db is None:
258
+ print('FAIL: C2 — Contracts database not found')
259
+ return 0.0, max_pts
260
+
261
+ db_id = db.get('id')
262
+ ini_items = set((ini_pages.get(db_id, {}) or {}).get('items', []) or [])
263
+ new_item_ids = [i for i in (db.get('items', []) or []) if i not in ini_items]
264
+ for pid, page in cur_pages.items():
265
+ if pid not in ini_pages and page.get('parentId') == db_id and pid not in new_item_ids:
266
+ new_item_ids.append(pid)
267
+ if not new_item_ids:
268
+ print('FAIL: C2 — no NEW row added to Contracts database')
269
+ return 0.0, max_pts
270
+
271
+ # Evaluate each new row; require ALL four fields correct for full credit.
272
+ prop_name_to_id = {
273
+ _norm_words(p.get('name')): p.get('id')
274
+ for p in (db.get('properties', []) or [])
275
+ if p.get('id') and p.get('name')
276
+ }
277
+
278
+ def field_text(props, names, fallback_ids):
279
+ keys = list(fallback_ids)
280
+ keys.extend(prop_name_to_id.get(_norm_words(n)) for n in names)
281
+ for key in [k for k in keys if k]:
282
+ if key not in props:
283
+ continue
284
+ v = props.get(key, {})
285
+ if isinstance(v, dict):
286
+ for value_key in ('title', 'text', 'select', 'status',
287
+ 'number', 'date'):
288
+ if v.get(value_key) not in (None, ''):
289
+ return v.get(value_key)
290
+ elif v not in (None, ''):
291
+ return v
292
+ return None
293
+
294
+ best = None
295
+ for rid in new_item_ids:
296
+ row = cur_pages.get(rid, {}) or {}
297
+ props = row.get('properties', {}) or {}
298
+ customer = (
299
+ field_text(props, ['Customer'], ['prop_customer'])
300
+ or row.get('title')
301
+ or ''
302
+ )
303
+ deal = field_text(props, ['Deal'], ['prop_deal']) or ''
304
+ amount = field_text(props, ['Amount'], ['prop_amount'])
305
+ status = field_text(props, ['Status'], ['prop_status']) or ''
306
+ checks = {
307
+ 'customer': _has_any(customer, ['globex corporation', 'globex corp', 'globex']),
308
+ 'deal': _has_all(deal, ['platform', 'expansion']),
309
+ 'amount': _amount_matches(amount, 120000),
310
+ 'status': _norm_words(status) == 'sent',
311
+ }
312
+ score = sum(checks.values())
313
+ if best is None or score > best[0]:
314
+ best = (score, checks, customer, deal, amount, status)
315
+
316
+ score, checks, customer, deal, amount, status = best
317
+ if all(checks.values()):
318
+ print(f'PASS: C2 — new Contracts row Customer="{customer}" Deal="{deal}" '
319
+ f'Amount={amount} Status="{status}" (0.25)')
320
+ return max_pts, max_pts
321
+ else:
322
+ print(f'FAIL: C2 — row field mismatch {checks} '
323
+ f'(customer={customer}, deal={deal}, amount={amount}, status={status})')
324
+ return 0.0, max_pts
325
+ except Exception as e:
326
+ print(f'ERROR: C2 (notion) — {e}')
327
+ return 0.0, max_pts
328
+
329
+
330
+ def check_salesforce(scored, initial):
331
+ """Component 3 — new activity on opp-1 logging the sent order form; stage intact. (0.20)"""
332
+ max_pts = 0.20
333
+ try:
334
+ ini_acts = initial.get('activities', []) or []
335
+ cur_acts = scored.get('activities', []) or []
336
+ ini_ids = {a.get('activityId') for a in ini_acts}
337
+ new_acts = [a for a in cur_acts if a.get('activityId') not in ini_ids]
338
+
339
+ def target_opp(state):
340
+ for opp in (state.get('opportunities', []) or []):
341
+ name = opp.get('name', '')
342
+ if (_has_any(name, ['globex'])
343
+ and _has_all(name, ['platform', 'expansion'])
344
+ and _amount_matches(opp.get('amount'), 120000)):
345
+ return opp
346
+ return None
347
+
348
+ opp1 = target_opp(scored) or next(
349
+ (o for o in (scored.get('opportunities', []) or [])
350
+ if o.get('opportunityId') == 'opp-1'), None)
351
+ opp_id = (opp1 or {}).get('opportunityId', 'opp-1')
352
+
353
+ def relates_target_opp(a):
354
+ return a.get('relatedToId') == opp_id
355
+
356
+ def logs_orderform_sent(a):
357
+ blob = ' '.join([
358
+ str(a.get('subject', '')),
359
+ str(a.get('description', '')),
360
+ str(a.get('type', '')),
361
+ str(a.get('status', '')),
362
+ ])
363
+ mentions_contract = _has_any(blob, [
364
+ 'order form', 'orderform', 'docu sign', 'docusign',
365
+ 'envelope', 'signature packet',
366
+ ])
367
+ return mentions_contract and _sent_for_signature(blob)
368
+
369
+ matching = [
370
+ a for a in new_acts
371
+ if relates_target_opp(a) and logs_orderform_sent(a)
372
+ ]
373
+ # Target opportunity must remain Closed Won.
374
+ stage_ok = opp1 is not None and _norm_words(opp1.get('stage')) == 'closed won'
375
+
376
+ if matching and stage_ok:
377
+ print(f'PASS: C3 — new opp activity "{matching[0].get("subject")}" logged; '
378
+ f'stage still Closed Won (0.20)')
379
+ return max_pts, max_pts
380
+ else:
381
+ print(f'FAIL: C3 — matching_new_activity={bool(matching)} '
382
+ f'target_stage_closed_won={stage_ok}')
383
+ return 0.0, max_pts
384
+ except Exception as e:
385
+ print(f'ERROR: C3 (salesforce) — {e}')
386
+ return 0.0, max_pts
387
+
388
+
389
+ def check_slack(scored, initial):
390
+ """Component 4 — new #deal-desk message: Globex, $120,000, awaiting signature. (0.20)"""
391
+ max_pts = 0.20
392
+ try:
393
+ channel_ids = {
394
+ c.get('channelId') for c in (scored.get('channels', []) or [])
395
+ if _norm_words(c.get('name')) == 'deal desk'
396
+ or _norm_words(c.get('channelId')) == 'deal desk'
397
+ }
398
+ channel_ids.add('deal-desk')
399
+
400
+ new_msgs = []
401
+ for channel_id in [c for c in channel_ids if c]:
402
+ ini_msgs = (initial.get('messages', {}) or {}).get(channel_id, []) or []
403
+ cur_msgs = (scored.get('messages', {}) or {}).get(channel_id, []) or []
404
+ ini_ids = {m.get('messageId') for m in ini_msgs}
405
+ new_msgs.extend(m for m in cur_msgs if m.get('messageId') not in ini_ids)
406
+ if not new_msgs:
407
+ print('FAIL: C4 — no NEW message in #deal-desk')
408
+ return 0.0, max_pts
409
+
410
+ for m in new_msgs:
411
+ blob = str(m.get('content', ''))
412
+ has_customer = _has_any(blob, ['globex', 'globex corporation'])
413
+ has_amount = _amount_matches(blob, 120000)
414
+ has_await = _sent_for_signature(blob)
415
+ if has_customer and has_amount and has_await:
416
+ print(f'PASS: C4 — #deal-desk message mentions Globex, $120,000, '
417
+ f'awaiting signature (0.20)')
418
+ return max_pts, max_pts
419
+ print(f'FAIL: C4 — new message(s) present but none mention all of '
420
+ f'{{Globex, 120000, awaiting signature}}: '
421
+ f'{[m.get("content") for m in new_msgs]}')
422
+ return 0.0, max_pts
423
+ except Exception as e:
424
+ print(f'ERROR: C4 (slack) — {e}')
425
+ return 0.0, max_pts
426
+
427
+
428
+ def _num(v):
429
+ try:
430
+ text = str(v).replace(',', '').replace('$', '')
431
+ if text.lower().strip().endswith('k'):
432
+ return float(text[:-1]) * 1000
433
+ return float(text)
434
+ except Exception:
435
+ return None
436
+
437
+
438
+ def main():
439
+ sid = read_sid()
440
+ if not sid:
441
+ print('REWARD: 0.0')
442
+ return
443
+
444
+ print(f'Egress: direct; scoring state: {STATE_TO_SCORE}')
445
+
446
+ states = fetch_all(sid)
447
+ if states is None:
448
+ print('REWARD: 0.0')
449
+ return
450
+
451
+ total = 0.0
452
+ ds_s, ds_i = pick(states, 'docusign')
453
+ no_s, no_i = pick(states, 'notion')
454
+ sf_s, sf_i = pick(states, 'salesforce')
455
+ sl_s, sl_i = pick(states, 'slack')
456
+
457
+ p, _ = check_docusign(ds_s or {}, ds_i or {}); total += p
458
+ p, _ = check_notion(no_s or {}, no_i or {}); total += p
459
+ p, _ = check_salesforce(sf_s or {}, sf_i or {}); total += p
460
+ p, _ = check_slack(sl_s or {}, sl_i or {}); total += p
461
+
462
+ final = round(min(total, 1.0), 4)
463
+ print(f'\nScore: {total}/1.0')
464
+ print(f'REWARD: {final}')
465
+
466
+
467
+ main()
ae_contract_signature_001/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/ae_contract_signature_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 18:47:48",
7
+ "label": {
8
+ "task_id": "ae_contract_signature_001",
9
+ "domain": "mock_websites",
10
+ "summary": "验证在DocuSign、Notion、Salesforce和Slack四个mock服务中,是否针对Globex Platform Expansion订单成功创建了新的信封、数据库行、活动记录和频道消息,并满足指定的内容与状态要求。",
11
+ "is_placeholder": false,
12
+ "data_sources": [
13
+ "/tmp/task_web_sid",
14
+ "docusign_mock (http://28.7.186.212:8150)",
15
+ "notion_mock (http://28.7.186.212:8186)",
16
+ "salesforce_mock (http://28.7.186.212:8195)",
17
+ "slack_mock (http://28.7.186.212:8198)"
18
+ ],
19
+ "scoring_components": [
20
+ {
21
+ "name": "Component 1 — DocuSign envelope",
22
+ "weight": 0.35,
23
+ "description": "检查DocuSign中是否新增了引用Globex Platform Expansion订单的信封,且状态为已发送,并包含指定的签署人。",
24
+ "check_logic": "对比initial_state与scored_state的envelopes列表,筛选出id不在初始状态的新信封;通过subject/message/documents.name匹配是否包含globex、platform、expansion、order form等关键词;若找到则得0.10。进一步检查status归一化后是否为sent或delivered且sentAt可解析为有效时间戳,满足则再加0.10。最后检查recipients中role含signer的恰好只有一人,且其email必须为maria.gomez@globex.com,name最好匹配Maria Gomez,满足则再加0.15。",
25
+ "pass_condition": "存在新的Globex Platform Expansion订单信封(+0.10),status为sent/delivered且sentAt有效(+0.10),恰好一个signer且email为maria.gomez@globex.com(+0.15)"
26
+ },
27
+ {
28
+ "name": "Component 2 — Notion 'Contracts' row",
29
+ "weight": 0.25,
30
+ "description": "检查Notion的Contracts数据库中是否新增了符合要求的合同行。",
31
+ "check_logic": "在scored_state中查找title归一化后为contracts的数据库;对比initial_state找出该数据库下新增的item(通过items列表或parentId判断)。对新增行提取Customer、Deal、Amount、Status四个字段,要求Customer包含globex,Deal同时包含platform和expansion,Amount匹配120000,Status归一化后等于sent。四个条件全部满足得0.25,否则该组件得0.0。",
32
+ "pass_condition": "Contracts数据库中存在新增行,且Customer含Globex、Deal含Platform Expansion、Amount为120000、Status为Sent"
33
+ },
34
+ {
35
+ "name": "Component 3 — Salesforce activity on opp-1",
36
+ "weight": 0.2,
37
+ "description": "检查Salesforce中是否在opp-1上新增了记录发送订单表单的活动,且机会阶段保持Closed Won。",
38
+ "check_logic": "对比activities找出activityId不在初始状态的新活动。定位目标机会(opp-1或name匹配Globex Platform Expansion且amount为120000的机会)。检查新活动的relatedToId是否等于该机会ID,且subject/description/type/status的拼接文本中提及order form/docusign/envelope等关键词,并通过_sent_for_signature判断为待签署状态。同时要求该机会的stage归一化后仍为closed won。全部满足得0.20,否则0.0。",
39
+ "pass_condition": "存在与opp-1相关的新活动,内容表明订单表单/DocuSign已发送待签署,且对应机会阶段仍为Closed Won"
40
+ },
41
+ {
42
+ "name": "Component 4 — Slack #deal-desk message",
43
+ "weight": 0.2,
44
+ "description": "检查Slack的#deal-desk频道中是否新增了提及Globex、金额12万且等待签署的消息。",
45
+ "check_logic": "在scored_state中查找name或channelId匹配deal desk的频道(包括deal-desk)。对比initial_state的messages,筛选出messageId不在初始状态的新消息。遍历新消息,检查content是否同时包含:Globex相关关键词、金额120000、以及待签署语义(通过_sent_for_signature判断)。任一消息满足全部三个条件即得0.20,否则0.0。",
46
+ "pass_condition": "#deal-desk频道中存在新消息,同时提及Globex、金额120000和等待签署/已发送待签等语义"
47
+ }
48
+ ],
49
+ "total_max_score": 1.0,
50
+ "score_aggregation": "四个组件得分直接相加,最终结果通过min(total, 1.0)钳制到上限1.0,并四舍五入保留4位小数。",
51
+ "failure_modes": [
52
+ "读取/tmp/task_web_sid失败或sid为空时,脚本打印CRITICAL并直接返回REWARD: 0.0",
53
+ "任一mock服务(docusign/notion/salesforce/slack)的/go接口请求失败或超时,fetch_all返回None,脚本直接返回REWARD: 0.0",
54
+ "DocuSign中未找到新的Globex Platform Expansion信封,该组件得0分(后续子项不再计分)",
55
+ "Notion中未找到Contracts数据库、无新增行、或新增行四个字段任一不匹配,该组件得0分",
56
+ "Salesforce中未找到匹配的新activity、activity未关联目标机会、内容未提及订单/DocuSign/待签署、或机会stage不是Closed Won,该组件得0分",
57
+ "Slack中#deal-desk无新消息,或新消息未同时包含Globex、120000、待签署三个要素,该组件得0分"
58
+ ],
59
+ "scoring_logic_explanation": "脚本首先读取/tmp/task_web_sid获取会话ID,然后并行(顺序)向四个mock服务请求/go接口获取initial_state和current_state。根据环境变量REWARD_STATE_KEY(默认current_state)确定要评分的状态。随后依次执行四个组件检查:每个组件都将当前状态与初始状态对比,仅验证任务执行期间新增的artifact。Component 1采用增量计分(0.10+0.10+0.15),其余组件为二值判定(通过得满分,否则得0)。各组件得分累加后,用min函数确保不超过1.0上限,最后输出REWARD。",
60
+ "confidence": 1.0
61
+ },
62
+ "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出结果。\n\n让我仔细阅读代码:\n\n1. **任务信息提取**:\n - Task ID: ae_contract_signature_003(从 docstring 中明确提取)\n - Domain: mock_websites (multi-mock: docusign, notion, salesforce, slack)(从 docstring 中提取)\n\n2. **脚本性质**:\n - 这不是占位脚本,它实际检查了多个 mock 服务的状态。\n - is_placeholder: false\n\n3. **数据源**:\n - /tmp/task_web_sid(读取 sid)\n - docusign mock: http://28.7.186.212:8150\n - notion mock: http://28.7.186.212:8186\n - salesforce mock: http://28.7.186.212:8195\n - slack mock: http://28.7.186.212:8198\n\n4. **评分组件**:\n - Component 1: DocuSign envelope (0.35)\n - 检查新的 envelope 引用 Globex Platform Expansion order form (0.10)\n - status == 'sent' 或 'delivered' 且 sentAt 可解析 (0.10)\n - 恰好一个 signer recipient 名为 Maria Gomez / maria.gomez@globex.com (0.15)\n - 注意:代码中 1a、1b、1c 是累加的,但 1a 只要找到 globex_new 就加 0.10,1b 条件满足加 0.10,1c 条件满足加 0.15。如果前面失败会提前 return。\n \n - Component 2: Notion 'Contracts' row (0.25)\n - 检查 Contracts 数据库中新增的行\n - Customer 包含 Globex\n - Deal 包含 Platform Expansion\n - Amount 匹配 120000\n - Status 为 'sent'\n - 这是一个全有或全无的检查,通过得 0.25,否则 0.0\n \n - Component 3: Salesforce activity on opp-1 (0.20)\n - 检查 opp-1(或匹配的 Globex Platform Expansion 机会)上的新 activity\n - activity 内容引用 order form/DocuSign/sent\n - 且 opp-1 stage 仍为 'Closed Won'\n - 全有或全无,0.20 或 0.0\n \n - Component 4: Slack #deal-desk message (0.20)\n - 检查 #deal-desk 频道的新消息\n - 消息提及 Globex、amount 120000、awaiting signature\n - 全有或全无,0.20 或 0.0\n\n5. **分数汇总**:\n - 各组件分数相加\n - 最后 min(total, 1.0) 并四舍五入到 4 位小数\n - total_max_score: 1.0\n\n6. **失败模式**:\n - 读取 /tmp/task_web_sid 失败 → return 0.0\n - fetch_all 任一 mock 拉取失败 → return 0.0\n - DocuSign: 无新 envelope → 该组件 0 分(不会提前退出,只是该组件 0 分)\n - Notion: 找不到 Contracts 数据库 → 0 分;无新行 → 0 分;字段不匹配 → 0 分\n - Salesforce: 无匹配新 activity 或 stage 不是 Closed Won → 0 分\n - Slack: 无新消息 → 0 分;新消息但不包含所有要求 → 0 分\n\n7. **评分逻辑详细解释**:\n - 读取 sid 文件\n - 从四个 mock 服务获取 initial_state 和 current_state\n - 根据 STATE_TO_SCORE 环境变量决定评分状态(默认 current_state)\n - 分别检查四个组件,每个组件对比 scored state 和 initial state,只验证 NEW 的 artifact\n - 累加各组件得分,上限 1.0\n\n8. **Confidence**: 1.0(代码逻辑清晰完整)\n\n现在构建 JSON:\n\n- task_id: \"ae_contract_signature_003\"\n- domain: \"mock_websites\"\n- summary: \"验证在 DocuSign、Notion、Salesforce 和 Slack 四个 mock 服务中是否成功创建了与 Globex Platform Expansion 订单相关的新工件(信封、数据库行、活动记录和 Slack 消息),并确保状态正确。\"\n- is_placeholder: false\n- data_sources: [\"/tmp/task_web_sid\", \"docusign_mock\", \"notion_mock\", \"salesforce_mock\", \"slack_mock\"] 或者更具体地按照代码中的 URL。但通常写 mock 服务名即可。代码中写的是 MOCKS 字典的 key 和 /tmp/task_web_sid。\n\n让我再仔细看 Component 1 的 weight。代码中:\n- 1a: 0.10\n- 1b: 0.10\n- 1c: 0.15\n- 总计 max 0.35\n\n但 JSON 格式要求每个组件一个 weight。Component 1 的总 weight 是 0.35。在 check_logic 中说明子分数。\n\n对于 Component 2、3、4,代码中是二值判定(返回 max_pts 或 0.0),weight 应填 1.0?不,等等。用���说:\"weight 字段填写代码中显式给出的分值(如 0.3);若代码未显式分值但有通过/失败二值判定,weight 填 1.0 并在 check_logic 中说明。\"\n\n但是这里 Component 2 的 max_pts 是 0.25,Component 3 是 0.20,Component 4 是 0.20。这些分值在 docstring 和代码中都明确给出了。所以 weight 应该填这些分值。\n\n等等,用户说:\"若代码未显式分值但有通过/失败二值判定,weight 填 1.0\"。但这里代码有显式分值(0.25, 0.20, 0.20),所以填这些。\n\nComponent 1 比较特殊,它内部有子分数(0.10, 0.10, 0.15),但总体 max 是 0.35。weight 填 0.35。\n\ncheck_logic 需要描述具体判断逻辑。\n\n让我再确认一下 Component 1 的通过条件:\n- 必须存在新的 envelope 引用 Globex Platform Expansion order form(否则直接 return 0.0, 0.35)\n- 如果存在,+0.10\n- status 是 sent/delivered 且 sentAt 可解析,+0.10\n- 恰好一个 signer,名字匹配 Maria Gomez 或邮箱是 maria.gomez@globex.com,且邮箱必须等于 maria.gomez@globex.com,+0.15\n\n注意 C1c 的条件:`name_ok and em == 'maria.gomez@globex.com'`,其中 name_ok 是 `_name_matches(nm, 'maria', 'gomez') or em == 'maria.gomez@globex.com'`。所以实际上邮箱必须匹配,名字最好也匹配(或者如果名字不匹配但邮箱匹配,name_ok 为 true,然后 `name_ok and em == ...` 只要邮箱对就过)。\n\nComponent 2:\n- 找到 Contracts 数据库\n- 找到新行\n- 检查四个字段:customer 含 globex,deal 含 platform+expansion,amount 匹配 120000,status 为 sent\n- 全部满足得 0.25,否则 0.0\n\nComponent 3:\n- 找到 opp-1(或匹配的 Globex Platform Expansion 机会)\n- 检查新 activity 是否 relatedToId 匹配 opp_id\n- activity 内容 blob 包含 order form/orderform/docu sign/docusign/envelope/signature packet 之一,且 _sent_for_signature 为 true\n- opp1 stage 仍为 closed won\n- 全满足得 0.20\n\nComponent 4:\n- 在 #deal-desk 频道(channelId 或 name 匹配)\n- 找到新消息\n- 消息内容包含 Globex、120000、awaiting signature(通过 _sent_for_signature 判断)\n- 满足得 0.20\n\nScore aggregation: 相加,然后 min(total, 1.0),四舍五入到 4 位小数。\n\nFailure modes:\n- 读取 sid 失败 → REWARD: 0.0\n- fetch_all 任一 mock 失败 → REWARD: 0.0\n- DocuSign 无新 Globex envelope → 该组件 0 分\n- Notion 无 Contracts DB → 0 分;无新行 → 0 分;字段不匹配 → 0 分\n- Salesforce 无匹配 activity 或 stage 非 Closed Won → 0 分\n- Slack 无新消息或内容不匹配 → 0 分\n\n现在组织 JSON。 </think> {\"task_id\":\"ae_contract_signature_003\",\"domain\":\"mock_websites\",\"summary\":\"验证在DocuSign、Notion、Salesforce和Slack四个mock服务中,是否针对Globex Platform Expansion订单成功创建了新的信封、数据库行、活动记录和频道消息,并满足指定的内容与状态要求。\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"docusign_mock (http://28.7.186.212:8150)\",\"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 1 — DocuSign envelope\",\"weight\":0.35,\"description\":\"检查DocuSign中是否新增了引用Globex Platform Expansion订单的信封,且状态为已发送,并包含指定的签署人。\",\"check_logic\":\"对比initial_state与scored_state的envelopes列表,筛选出id不在初始状态的新信封;通过subject/message/documents.name匹配是否包含globex、platform、expansion、order form等关键词;若找到则得0.10。进一步检查status归一化后是否为sent或delivered且sentAt可解析为有效时间戳,满足则再加0.10。最后检查recipients中role含signer的恰好只有一人,且其email必须为maria.gomez@globex.com,name最好匹配Maria Gomez,满足则再加0.15。\",\"pass_condition\":\"存在新的Globex Platform Expansion订单信封(+0.10),status为sent/delivered且sentAt有效(+0.10),恰好一个signer且email为maria.gomez@globex.com(+0.15)\"},{\"name\":\"Component 2 — Notion 'Contracts' row\",\"weight\":0.25,\"description\":\"检查Notion的Contracts数据库中是否新增了符合要求的合同行。\",\"check_logic\":\"在scored_state中查找title归一化后为contracts的数据库;对比initial_state找出该数据库下新增的item(通过items列表或parentId判断)。对新增行提取Customer、Deal、Amount、Status四个字段,要求Customer包含globex,Deal同时包含platform和expansion,Amount匹配120000,Status归一化后等于sent。四个条件全部满足得0.25,否则该组件得0.0。\",\"pass_condition\":\"Contracts数据库中存在新增行,且Customer含Globex、Deal含Platform Expansion、Amount为120000、Status为Sent\"},{\"name\":\"Component 3 — Salesforce activity on opp-1\",\"weight\":0.20,\"description\":\"检查Salesforce中是否在opp-1上新增了记录发送订单表单的活动,且机会阶段保持Closed Won。\",\"check_logic\":\"对比activities找出activityId不在初始状态的新活动。定位目标机会(opp-1或name匹配Globex Platform Expansion且amount为120000的机会)。检查新活动的relatedToId是否等于该机会ID,且subject/description/type/status的拼接文本中提及order form/docusign/envelope等关键词,并通过_sent_for_signature判断为待签署状态。同时要求该机会的stage归一化后仍为closed won。全部满足得0.20,否则0.0。\",\"pass_condition\":\"存在与opp-1相关的新活动,内容表明订单表单/DocuSign已发送待签署,且对应机会阶段仍为Closed Won\"},{\"name\":\"Component 4 — Slack #deal-desk message\",\"weight\":0.20,\"description\":\"检查Slack的#deal-desk频道中是否新增了提及Globex、金额12万且等待签署的消息。\",\"check_logic\":\"在scored_state中查找name或channelId匹配deal desk的频道(包括deal-desk)。对比initial_state的messages,筛选出messageId不在初始状态的新消息。遍历新消息,检查content是否同时包含:Globex相关关键词、金额120000、以及待签署语义(通过_sent_for_signature判断)。任一消息满足全部三个条件即得0.20,否则0.0。\",\"pass_condition\":\"#deal-desk频道中存在新消息,同时提及Globex、金额120000和等待签署/已发送待签等语义\"}],\"total_max_score\":1.0,\"score_aggregation\":\"四个组件得分直接相加,最终结果通过min(total, 1.0)钳制到上限1.0,并四舍五入保留4位小数。\",\"failure_modes\":[\"读取/tmp/task_web_sid失败或sid为空时,脚本打印CRITICAL并直接返回REWARD: 0.0\",\"任一mock服务(docusign/notion/salesforce/slack)的/go接口请求失败或超时,fetch_all返回None,脚本直接返回REWARD: 0.0\",\"DocuSign中未找到新的Globex Platform Expansion信封,该组件得0分(后续子项不再计分)\",\"Notion中未找到Contracts数据库、无新增行、或新增行四个字段任一不匹配,该组件得0分\",\"Salesforce中未找到匹配的新activity、activity未关联目标机会、内容未提及订单/DocuSign/待签署、或机会stage不是Closed Won,该组件得0分\",\"Slack中#deal-desk无新消息,或新消息未同时包含Globex、120000、待签署三个要素,该组件得0分\"],\"scoring_logic_explanation\":\"脚本首先读取/tmp/task_web_sid获取会话ID,然后并行(顺序)向四个mock服务请求/go接口获取initial_state和current_state。根据环境变量REWARD_STATE_KEY(默认current_state)确定要评分的状态。随后依次执行四个组件检查:每个组件都将当前状态与初始状态对比,仅验证任务执行期间新增的artifact。Component 1采用增量计分(0.10+0.10+0.15),其余组件为二值判定(通过得满分,否则得0)。各组件得分累加后,用min函数确保不超过1.0上限,最后输出REWARD。\",\"confidence\":1.0}"
63
+ }
ae_deal_handoff_002__long/_cua_gym_vm_bridge.sh ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # CUA-Gym VM-side network fix (direct-IP mock access).
3
+ #
4
+ # Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by
5
+ # their real IDC address (http://28.7.184.198:81xx) instead of the old
6
+ # localhost:9000-9097 socat bridge, so the VM only needs two fixes:
7
+ #
8
+ # 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's
9
+ # cluster DNS, which is unreachable from QEMU SLIRP NAT
10
+ # ("Temporary failure in name resolution").
11
+ # 2. The mock host excluded from the woa http proxy — otherwise the VM's
12
+ # Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403
13
+ # from the proxy when hitting 28.7.184.198:81xx. (The old socat path never
14
+ # hit this because localhost is bypassed by default.)
15
+ #
16
+ # Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic
17
+ # OSWorld setup pipeline.
18
+ #
19
+ # Argv:
20
+ # $1 optional sudo password (default "password"; SetupController
21
+ # substitutes {CLIENT_PASSWORD} when uploaded as a cache file).
22
+ # $2 unused (kept for backward compat — was socat first port 9000).
23
+ # $3 unused (kept for backward compat — was socat last port 9097).
24
+ # $4 optional mock host IP (default 28.7.184.198).
25
+
26
+ set +e
27
+
28
+ PASS="${1:-password}"
29
+ MOCK_HOST="${4:-28.7.184.198}"
30
+ # Derive the /16 IDC subnet so future port/host tweaks on the same segment
31
+ # stay bypassed too (28.7.184.198 -> 28.7.0.0/16).
32
+ MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')"
33
+
34
+ run_root() {
35
+ echo "$PASS" | sudo -S -p "" bash -c "$1"
36
+ }
37
+
38
+ # Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2.
39
+ GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')"
40
+ GW="${GW:-10.0.2.2}"
41
+
42
+ # ─── CUA-Gym network fix (Taiji-specific) ─────────────────────────────
43
+ fix_vm_network() {
44
+ # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP
45
+ # DNS forwarder. Nothing hardcoded except the mock host above.
46
+ local GW_NET="${GW%.*}"
47
+ local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3
48
+ local OWN_CIDR
49
+ OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \
50
+ | awk '{print $4; exit}')"
51
+ local OWN_IP="${OWN_CIDR%/*}"
52
+ local OWN_NET=""
53
+ [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24"
54
+
55
+ # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps
56
+ # systemd-resolved/NetworkManager from clobbering it.
57
+ if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf
58
+ chattr +i /etc/resolv.conf 2>/dev/null || true"; then
59
+ echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})"
60
+ else
61
+ echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf"
62
+ fi
63
+
64
+ # 2) Build the proxy bypass list from detected values + the direct-IP
65
+ # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx
66
+ # reachable from inside the VM — without it the woa proxy 403s it.
67
+ local ignore_list="['localhost', '127.0.0.0/8', '${GW}'"
68
+ [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'"
69
+ [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'"
70
+ [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'"
71
+ [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'"
72
+ [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'"
73
+ ignore_list="${ignore_list}]"
74
+
75
+ # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these.
76
+ if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then
77
+ echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}"
78
+ else
79
+ echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)"
80
+ fi
81
+
82
+ # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl).
83
+ local NP="localhost,127.0.0.1,${GW}"
84
+ [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}"
85
+ [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}"
86
+ [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24"
87
+ [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}"
88
+ [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}"
89
+
90
+ for var in no_proxy NO_PROXY; do
91
+ if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then
92
+ echo "export ${var}=${NP}" >> /home/user/.bashrc
93
+ fi
94
+ done
95
+ run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \
96
+ && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \
97
+ || echo 'no_proxy=\"${NP}\"' >> /etc/environment
98
+ grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \
99
+ && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \
100
+ || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1
101
+ echo "[cua_gym_vm_bridge] no_proxy=${NP}"
102
+ }
103
+
104
+ fix_vm_network
105
+
106
+ echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed"
ae_deal_handoff_002__long/initial_setup.py ADDED
@@ -0,0 +1,762 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: Hand off qualified opportunities (H16)
3
+ Task ID: ae_deal_handoff_002__long
4
+ Mocks: salesforce_mock,trello_mock,gmail_mock,slack_mock
5
+
6
+ A sales-ops rep hands off newly-qualified Salesforce Closed-Won opportunities
7
+ to the delivery team. For each qualifying opp the rep tiers by amount, then
8
+ takes tier-appropriate actions across SF (owner + optional kickoff task),
9
+ Trello (handoff card w/ tier label + due date), Gmail (label + kickoff email
10
+ for Tier-1 only), and Slack (summary post + pin).
11
+
12
+ DEVIATION FROM DESIGN SPEC: the salesforce_mock Opportunity.stage enum has
13
+ NO 'Onboarding' value; per the design's construction note, the graded
14
+ Salesforce transition is Owner -> 'Delivery Lead' for every tier. Stage is
15
+ left unchanged.
16
+
17
+ Ground-truth (answer key) is embedded in salesforce.initial_state._task_adapter
18
+ (task_opps + expected). Every listed action is ABSENT at injection (Rule 3):
19
+ no Handoff cards, no 'Kickoff -' activities, no Handoff labels or Kickoff
20
+ emails, no #delivery messages.
21
+ """
22
+ import datetime as _dt
23
+ import os
24
+ import shlex
25
+ import subprocess
26
+ import time
27
+ import uuid
28
+
29
+ import requests
30
+
31
+ sid = str(uuid.uuid4())
32
+ with open('/tmp/task_web_sid', 'w', encoding='utf-8') as f:
33
+ f.write(sid)
34
+ print(f'Generated sid: {sid}')
35
+
36
+ TASK_ID = '9e3cf2fc-771b-44a9-8dd3-2b8b9a6f91b4'
37
+ TODAY = _dt.date(2026, 6, 29)
38
+ SUMMARY_CHANNEL = 'delivery'
39
+
40
+ TIER1_MIN = 100_000
41
+ TIER2_MIN = 25_000
42
+ TIER_DUE_DAYS = {'Tier-1': 3, 'Tier-2': 5, 'Tier-3': 7}
43
+ TIER_LABEL_NAMES = {'Tier-1': 'Tier-1', 'Tier-2': 'Tier-2', 'Tier-3': 'Tier-3'}
44
+
45
+ DELIVERY_BOARD_ID = 'board-delivery'
46
+ DELIVERY_LIST_ID = 'list-delivery-queue'
47
+
48
+ ADMIN_OWNER_ID = 'user-admin'
49
+ ADMIN_OWNER_NAME = 'Admin User'
50
+ DELIVERY_OWNER_ID = 'user-delivery'
51
+ DELIVERY_OWNER_NAME = 'Delivery Lead'
52
+ MANAGER_ID = 'user-1'
53
+
54
+
55
+ def _tier_of(amount):
56
+ if amount >= TIER1_MIN:
57
+ return 'Tier-1'
58
+ if amount >= TIER2_MIN:
59
+ return 'Tier-2'
60
+ return 'Tier-3'
61
+
62
+
63
+ def _due(days):
64
+ return (TODAY + _dt.timedelta(days=days)).isoformat()
65
+
66
+
67
+ _OPP_SPEC = [
68
+ dict(name='Northstar Platform Rollout', account='Northstar Industries',
69
+ account_email='ap@northstarind.example',
70
+ amount=185_000, stage='Closed Won', owner=ADMIN_OWNER_ID),
71
+ dict(name='Cedar Grove Expansion', account='Cedar Grove Health',
72
+ account_email='billing@cedargrove.example',
73
+ amount=140_000, stage='Closed Won', owner=ADMIN_OWNER_ID),
74
+ dict(name='Blue Harbor Renewal', account='Blue Harbor Marine',
75
+ account_email='ap@blueharbor.example',
76
+ amount=68_000, stage='Closed Won', owner=ADMIN_OWNER_ID),
77
+ dict(name='Sunridge Solar Deploy', account='Sunridge Energy',
78
+ account_email='ap@sunridge.example',
79
+ amount=42_000, stage='Closed Won', owner=ADMIN_OWNER_ID),
80
+ dict(name='Fernway Analytics Pilot', account='Fernway Analytics',
81
+ account_email='ap@fernway.example',
82
+ amount=18_500, stage='Closed Won', owner=ADMIN_OWNER_ID),
83
+ dict(name='Kinley Retail Onboard', account='Kinley Retail',
84
+ account_email='ap@kinley.example',
85
+ amount=9_800, stage='Closed Won', owner=ADMIN_OWNER_ID),
86
+ dict(name='Ember Valley Upsell', account='Ember Valley Insurance',
87
+ account_email='ap@embervalley.example',
88
+ amount=210_000, stage='Negotiation', owner=ADMIN_OWNER_ID),
89
+ dict(name='Silverline Migration', account='Silverline Networks',
90
+ account_email='ap@silverline.example',
91
+ amount=125_000, stage='Closed Won', owner=DELIVERY_OWNER_ID),
92
+ ]
93
+
94
+ opportunities = []
95
+ task_opps = {}
96
+ expected = []
97
+
98
+ for idx, spec in enumerate(_OPP_SPEC, start=1):
99
+ opp_id = f'opp-{idx}'
100
+ tier = _tier_of(spec['amount']) if spec['stage'] == 'Closed Won' else None
101
+ already_handed_off = (spec['owner'] == DELIVERY_OWNER_ID)
102
+ is_won = (spec['stage'] == 'Closed Won')
103
+ requires_action = bool(is_won and not already_handed_off)
104
+
105
+ card_title = f'Handoff: {spec["name"]}' if requires_action else None
106
+ card_label = TIER_LABEL_NAMES.get(tier) if requires_action else None
107
+ card_due = _due(TIER_DUE_DAYS[tier]) if (requires_action and tier) else None
108
+ task_subject = f'Kickoff - {spec["name"]}' if (requires_action and tier == 'Tier-1') else None
109
+ email_subject = f'Kickoff for {spec["name"]}' if (requires_action and tier == 'Tier-1') else None
110
+ label_name = 'Handoff' if (requires_action and tier == 'Tier-1') else None
111
+
112
+ opportunities.append({
113
+ 'opportunityId': opp_id,
114
+ 'name': spec['name'],
115
+ 'accountId': f'acct-{idx}',
116
+ 'contactId': f'contact-{idx}',
117
+ 'amount': spec['amount'],
118
+ 'closeDate': (TODAY - _dt.timedelta(days=1)).isoformat(),
119
+ 'stage': spec['stage'],
120
+ 'probability': 100 if is_won else 60,
121
+ 'ownerId': spec['owner'],
122
+ 'createdDate': '2026-06-01T09:00:00Z',
123
+ 'modifiedDate': '2026-06-24T09:00:00Z',
124
+ })
125
+ task_opps[opp_id] = {
126
+ 'id': opp_id,
127
+ 'name': spec['name'],
128
+ 'account': spec['account'],
129
+ 'ownerName': (ADMIN_OWNER_NAME if spec['owner'] == ADMIN_OWNER_ID
130
+ else DELIVERY_OWNER_NAME),
131
+ }
132
+ expected.append({
133
+ 'opp_id': opp_id,
134
+ 'opp_name': spec['name'],
135
+ 'account': spec['account'],
136
+ 'account_email': spec['account_email'],
137
+ 'amount': spec['amount'],
138
+ 'stage_at_injection': spec['stage'],
139
+ 'owner_id_at_injection': spec['owner'],
140
+ 'tier': tier,
141
+ 'requires_action': requires_action,
142
+ 'target_owner_name': DELIVERY_OWNER_NAME if requires_action else None,
143
+ 'card_title': card_title,
144
+ 'card_label': card_label,
145
+ 'card_due': card_due,
146
+ 'task_subject': task_subject,
147
+ 'email_subject': email_subject,
148
+ 'label_name': label_name,
149
+ })
150
+
151
+ _won_action = [e for e in expected if e['requires_action']]
152
+ _tier1 = [e for e in _won_action if e['tier'] == 'Tier-1']
153
+ _tier2 = [e for e in _won_action if e['tier'] == 'Tier-2']
154
+ _tier3 = [e for e in _won_action if e['tier'] == 'Tier-3']
155
+ _skipped = [e for e in expected if not e['requires_action']]
156
+
157
+ assert len(expected) == 8
158
+ assert len(_tier1) == 2 and len(_tier2) == 2 and len(_tier3) == 2
159
+ assert len(_skipped) == 2
160
+
161
+ expected_card_titles = [e['card_title'] for e in _won_action]
162
+
163
+ SF_USERS = [
164
+ {'userId': MANAGER_ID, 'firstName': 'Jordan', 'lastName': 'Blake',
165
+ 'email': 'jordan.blake@company.example', 'phone': '(555) 123-4567',
166
+ 'title': 'Sales Ops', 'department': 'Sales', 'role': 'Manager',
167
+ 'avatar': 'https://i.pravatar.cc/150?u=user-1',
168
+ 'timezone': 'America/New_York', 'locale': 'en-US', 'theme': 'lightning'},
169
+ {'userId': ADMIN_OWNER_ID, 'firstName': 'Admin', 'lastName': 'User',
170
+ 'email': 'admin.user@company.example', 'phone': '',
171
+ 'title': 'System Administrator', 'department': 'Operations', 'role': 'Admin',
172
+ 'avatar': 'https://i.pravatar.cc/150?u=admin',
173
+ 'timezone': 'America/New_York', 'locale': 'en-US', 'theme': 'lightning'},
174
+ {'userId': DELIVERY_OWNER_ID, 'firstName': 'Delivery', 'lastName': 'Lead',
175
+ 'email': 'delivery.lead@company.example', 'phone': '',
176
+ 'title': 'Delivery Lead', 'department': 'Delivery', 'role': 'Rep',
177
+ 'avatar': 'https://i.pravatar.cc/150?u=delivery',
178
+ 'timezone': 'America/New_York', 'locale': 'en-US', 'theme': 'lightning'},
179
+ {'userId': 'user-2', 'firstName': 'Sara', 'lastName': 'Nolan',
180
+ 'email': 'sara.nolan@company.example', 'phone': '',
181
+ 'title': 'Account Executive', 'department': 'Sales', 'role': 'Rep',
182
+ 'avatar': 'https://i.pravatar.cc/150?u=user-2',
183
+ 'timezone': 'America/Chicago', 'locale': 'en-US', 'theme': 'lightning'},
184
+ ]
185
+
186
+ SF_ACCOUNTS = []
187
+ SF_CONTACTS = []
188
+ for idx, spec in enumerate(_OPP_SPEC, start=1):
189
+ aid = f'acct-{idx}'
190
+ cid = f'contact-{idx}'
191
+ SF_ACCOUNTS.append({
192
+ 'accountId': aid, 'name': spec['account'], 'industry': 'Technology',
193
+ 'annualRevenue': spec['amount'] * 8, 'website': '',
194
+ 'phone': '(555) 010-0100', 'billingStreet': '',
195
+ 'billingCity': '', 'billingState': '', 'billingZip': '',
196
+ 'billingCountry': 'United States', 'ownerId': ADMIN_OWNER_ID,
197
+ 'createdDate': '2026-05-01T00:00:00Z',
198
+ })
199
+ SF_CONTACTS.append({
200
+ 'contactId': cid, 'accountId': aid,
201
+ 'firstName': 'Ops', 'lastName': f'Contact {idx}',
202
+ 'email': spec['account_email'], 'phone': '(555) 010-0100',
203
+ 'title': 'Head of Ops', 'ownerId': ADMIN_OWNER_ID,
204
+ 'createdDate': '2026-05-01T00:00:00Z',
205
+ })
206
+
207
+ SF_ACTIVITIES = [
208
+ {'activityId': 'activity-decoy-1', 'type': 'event', 'subject': 'Weekly deal review',
209
+ 'status': 'Completed', 'priority': 'Normal',
210
+ 'startDateTime': '2026-06-24T15:00:00Z', 'endDateTime': '2026-06-24T15:30:00Z',
211
+ 'relatedToType': 'Opportunity', 'relatedToId': 'opp-1',
212
+ 'assignedToId': 'user-2', 'description': ''},
213
+ {'activityId': 'activity-decoy-2', 'type': 'task',
214
+ 'subject': 'Send proposal to Ember Valley',
215
+ 'status': 'Completed', 'priority': 'Low',
216
+ 'dueDate': (TODAY - _dt.timedelta(days=2)).isoformat(),
217
+ 'relatedToType': 'Opportunity', 'relatedToId': 'opp-7',
218
+ 'assignedToId': 'user-2', 'description': ''},
219
+ ]
220
+
221
+ salesforce_state = {
222
+ 'user': SF_USERS[0],
223
+ 'users': SF_USERS,
224
+ 'leads': [],
225
+ 'accounts': SF_ACCOUNTS,
226
+ 'contacts': SF_CONTACTS,
227
+ 'opportunities': opportunities,
228
+ 'cases': [],
229
+ 'activities': SF_ACTIVITIES,
230
+ 'chatterPosts': [],
231
+ 'files': [],
232
+ 'dashboards': [],
233
+ 'following': [],
234
+ 'recentlyViewed': [],
235
+ 'dismissedNotifications': [],
236
+ '_task_adapter': {
237
+ 'task_id': TASK_ID,
238
+ 'variant': 'eval',
239
+ 'today': TODAY.isoformat(),
240
+ 'task_opps': task_opps,
241
+ 'expected': expected,
242
+ 'summary_channel': SUMMARY_CHANNEL,
243
+ 'delivery_owner_name': DELIVERY_OWNER_NAME,
244
+ 'delivery_board_id': DELIVERY_BOARD_ID,
245
+ 'delivery_list_id': DELIVERY_LIST_ID,
246
+ 'delivery_list_name': 'Delivery Queue',
247
+ 'delivery_board_name': 'Delivery Handoffs',
248
+ 'expected_card_titles': expected_card_titles,
249
+ 'tier_label_names': TIER_LABEL_NAMES,
250
+ },
251
+ }
252
+
253
+ _forbidden_task_subjects = {
254
+ (e['task_subject'] or '').lower() for e in _tier1 if e['task_subject']
255
+ }
256
+ assert not any(str(a.get('subject', '')).lower() in _forbidden_task_subjects
257
+ for a in SF_ACTIVITIES)
258
+ _won_action_ids = {e['opp_id'] for e in _won_action}
259
+ for opp in opportunities:
260
+ if opp['opportunityId'] in _won_action_ids:
261
+ assert opp['ownerId'] == ADMIN_OWNER_ID
262
+
263
+ LABEL_TIER1 = 'lbl-tier-1'
264
+ LABEL_TIER2 = 'lbl-tier-2'
265
+ LABEL_TIER3 = 'lbl-tier-3'
266
+
267
+ trello_boards = {
268
+ DELIVERY_BOARD_ID: {
269
+ 'id': DELIVERY_BOARD_ID,
270
+ 'title': 'Delivery Handoffs',
271
+ 'description': 'Queue of qualified opps handed off to Delivery',
272
+ 'listIds': [DELIVERY_LIST_ID],
273
+ 'starred': True,
274
+ 'visibility': 'workspace',
275
+ 'archivedListIds': [],
276
+ 'archivedCardIds': [],
277
+ 'labels': [
278
+ {'id': LABEL_TIER1, 'name': 'Tier-1', 'color': 'red'},
279
+ {'id': LABEL_TIER2, 'name': 'Tier-2', 'color': 'orange'},
280
+ {'id': LABEL_TIER3, 'name': 'Tier-3', 'color': 'green'},
281
+ ],
282
+ 'memberIds': ['u1'],
283
+ 'createdAt': '2026-05-01T09:00:00.000Z',
284
+ },
285
+ }
286
+
287
+ trello_lists = {
288
+ DELIVERY_LIST_ID: {
289
+ 'id': DELIVERY_LIST_ID,
290
+ 'title': 'Delivery Queue',
291
+ 'boardId': DELIVERY_BOARD_ID,
292
+ 'cardIds': ['card-watermark'],
293
+ 'archived': False,
294
+ 'position': 0,
295
+ 'createdAt': '2026-05-01T09:00:00.000Z',
296
+ },
297
+ }
298
+
299
+ trello_cards = {
300
+ 'card-watermark': {
301
+ 'id': 'card-watermark',
302
+ 'title': 'Delivery Queue -- add handoff cards below',
303
+ 'description': 'Watermark card. Do not touch.',
304
+ 'listId': DELIVERY_LIST_ID,
305
+ 'boardId': DELIVERY_BOARD_ID,
306
+ 'labelIds': [],
307
+ 'memberIds': [],
308
+ 'dueDate': None,
309
+ 'startDate': None,
310
+ 'completed': False,
311
+ 'cover': None,
312
+ 'checklists': [],
313
+ 'comments': [],
314
+ 'attachments': [],
315
+ 'archived': False,
316
+ 'watching': False,
317
+ 'position': 0,
318
+ 'createdAt': '2026-05-01T09:00:00.000Z',
319
+ },
320
+ }
321
+
322
+ trello_state = {
323
+ 'currentUser': {'id': 'u1', 'name': 'Jordan Blake',
324
+ 'email': 'jordan.blake@company.example',
325
+ 'avatar': 'https://picsum.photos/200/200?random=trello'},
326
+ 'members': [{'id': 'u1', 'name': 'Jordan Blake',
327
+ 'email': 'jordan.blake@company.example',
328
+ 'avatar': 'https://picsum.photos/200/200?random=trello'}],
329
+ 'boards': trello_boards,
330
+ 'lists': trello_lists,
331
+ 'cards': trello_cards,
332
+ 'workspaces': [{'id': 'ws-1', 'name': 'Sales Ops', 'boards': [DELIVERY_BOARD_ID]}],
333
+ 'activeBoard': DELIVERY_BOARD_ID,
334
+ 'ui': {'openCardId': None, 'searchQuery': ''},
335
+ }
336
+
337
+ _forbidden_card_titles = {t.lower() for t in expected_card_titles}
338
+ assert not any(str(c.get('title', '')).lower() in _forbidden_card_titles
339
+ for c in trello_cards.values())
340
+
341
+ GMAIL_USER = {
342
+ 'userId': 'u1',
343
+ 'username': 'Jordan Blake',
344
+ 'email': 'jordan.blake@company.example',
345
+ 'avatar': 'https://picsum.photos/200/200?random=gmail',
346
+ }
347
+
348
+ GMAIL_LABELS = [
349
+ {'id': 'l1', 'name': 'Work', 'color': '#ef4444'},
350
+ {'id': 'l2', 'name': 'Personal', 'color': '#3b82f6'},
351
+ {'id': 'lbl-handoff', 'name': 'Handoff', 'color': '#8b5cf6'},
352
+ {'id': 'lbl-tier1', 'name': 'Tier-1', 'color': '#f59e0b'},
353
+ ]
354
+
355
+
356
+ def _gmail_email(eid, sender_name, sender_email, subject, body, ts, folder='inbox'):
357
+ return {
358
+ 'id': eid, 'threadId': f'thread_{eid}',
359
+ 'from': {'name': sender_name, 'email': sender_email, 'avatar': ''},
360
+ 'to': [{'name': GMAIL_USER['username'], 'email': GMAIL_USER['email']}],
361
+ 'cc': [], 'bcc': [], 'folder': folder,
362
+ 'subject': subject, 'body': body, 'snippet': body[:120],
363
+ 'timestamp': ts, 'read': False, 'starred': False, 'important': False,
364
+ 'labels': [], 'category': 'primary', 'attachments': [],
365
+ }
366
+
367
+
368
+ EMAILS = []
369
+ _ts_pool = ['2026-06-29T07:12:00Z', '2026-06-29T06:40:00Z',
370
+ '2026-06-29T05:55:00Z', '2026-06-29T05:20:00Z',
371
+ '2026-06-28T18:02:00Z', '2026-06-28T16:15:00Z']
372
+ for i, e in enumerate(_won_action):
373
+ EMAILS.append(_gmail_email(
374
+ f'm-acct-{i + 1}', e['account'], e['account_email'],
375
+ f"Onboarding logistics -- {e['opp_name']}",
376
+ (f"Hi Jordan, this is {e['account']}. Now that we are signed we would like to "
377
+ f"align on the kickoff plan and delivery timeline for {e['opp_name']}. "
378
+ f"Can you loop in the delivery team?"),
379
+ _ts_pool[i % len(_ts_pool)]))
380
+ EMAILS.append(_gmail_email(
381
+ 'm-noise-1', 'Sales Weekly', 'newsletter@company.example',
382
+ 'Sales Weekly digest', 'Wins from this week + a couple of reminders.',
383
+ '2026-06-29T04:00:00Z'))
384
+
385
+ _tier1_addrs = {e['account_email'].lower() for e in _tier1}
386
+ assert all(em['labels'] == [] for em in EMAILS)
387
+ assert not any(em['folder'] == 'sent'
388
+ and any((r.get('email') or '').lower() in _tier1_addrs
389
+ for r in em.get('to', []))
390
+ for em in EMAILS)
391
+
392
+ gmail_state = {
393
+ 'user': GMAIL_USER,
394
+ 'emails': EMAILS,
395
+ 'labels': GMAIL_LABELS,
396
+ 'drafts': [],
397
+ 'settings': {'density': 'default', 'undoSend': 10},
398
+ 'today': TODAY.isoformat(),
399
+ }
400
+
401
+ SLACK_USERS = [
402
+ {'userId': 'user_1', 'fullName': 'Jordan Blake', 'displayName': 'Jordan',
403
+ 'email': 'jordan.blake@company.example',
404
+ 'avatar': 'https://picsum.photos/200/200?random=1',
405
+ 'title': 'Sales Ops', 'status': 'online', 'statusMessage': '',
406
+ 'statusEmoji': '', 'timeZone': 'America/New_York'},
407
+ {'userId': 'user_2', 'fullName': 'Sara Nolan', 'displayName': 'Sara',
408
+ 'email': 'sara.nolan@company.example',
409
+ 'avatar': 'https://picsum.photos/200/200?random=2',
410
+ 'title': 'AE', 'status': 'online', 'statusMessage': '', 'statusEmoji': '',
411
+ 'timeZone': 'America/Chicago'},
412
+ {'userId': 'user_3', 'fullName': 'Delivery Lead', 'displayName': 'Delivery',
413
+ 'email': 'delivery.lead@company.example',
414
+ 'avatar': 'https://picsum.photos/200/200?random=3',
415
+ 'title': 'Delivery Lead', 'status': 'online', 'statusMessage': '',
416
+ 'statusEmoji': '', 'timeZone': 'America/New_York'},
417
+ ]
418
+
419
+
420
+ def _slack_channel(cid, name, desc, topic, starred=False, unread=0):
421
+ return {
422
+ 'channelId': cid, 'name': name, 'description': desc, 'topic': topic,
423
+ 'isPrivate': False, 'isStarred': starred,
424
+ 'members': ['user_1', 'user_2', 'user_3'],
425
+ 'createdBy': 'user_1', 'createdAt': '2026-06-01T09:00:00Z',
426
+ 'pinnedMessages': [], 'unreadCount': unread,
427
+ }
428
+
429
+
430
+ def _slack_msg(mid, sender, content, ts):
431
+ return {
432
+ 'messageId': mid, 'senderId': sender, 'content': content,
433
+ 'timestamp': ts, 'threadId': None, 'reactions': [],
434
+ 'attachments': [], 'isEdited': False,
435
+ }
436
+
437
+
438
+ slack_state = {
439
+ 'currentUser': SLACK_USERS[0],
440
+ 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Acme Sales Ops', 'icon': ''},
441
+ 'users': SLACK_USERS,
442
+ 'channels': [
443
+ _slack_channel('delivery', 'delivery', 'Handoffs to the delivery team',
444
+ 'Post the daily handoff summary here', starred=True),
445
+ _slack_channel('general', 'general', 'Company-wide announcements',
446
+ 'Welcome!', starred=True),
447
+ _slack_channel('random', 'random', 'Non-work banter', 'Watercooler',
448
+ unread=2),
449
+ _slack_channel('deals', 'deals', 'War-room for active deals',
450
+ 'Post wins here', unread=1),
451
+ ],
452
+ 'messages': {
453
+ 'delivery': [],
454
+ 'general': [
455
+ _slack_msg('m_g_1', 'user_2', 'Morning all -- pipeline is looking good.',
456
+ '2026-06-29T07:55:00Z'),
457
+ ],
458
+ 'random': [
459
+ _slack_msg('m_r_1', 'user_3', 'Anyone up for coffee?',
460
+ '2026-06-29T07:20:00Z'),
461
+ ],
462
+ 'deals': [
463
+ _slack_msg('m_d_1', 'user_2', 'Northstar came in above quota.',
464
+ '2026-06-27T16:15:00Z'),
465
+ ],
466
+ },
467
+ 'threads': {},
468
+ 'dms': [],
469
+ 'bookmarkedMessages': [],
470
+ 'callHistory': [],
471
+ 'settings': {'theme': 'light', 'notifications': 'all',
472
+ 'displayDensity': 'comfortable', 'showAvatars': True,
473
+ 'use24Hour': False},
474
+ 'invitations': [],
475
+ 'notifications': [],
476
+ '_task_adapter': {
477
+ 'task_id': TASK_ID,
478
+ 'variant': 'eval',
479
+ 'summary_channel': SUMMARY_CHANNEL,
480
+ 'won_action_count': len(_won_action),
481
+ },
482
+ }
483
+ assert not slack_state['messages'].get('delivery')
484
+
485
+ APP_STATES = [
486
+ ('http://28.7.184.198:8175', salesforce_state),
487
+ ('http://28.7.184.198:8182', trello_state),
488
+ ('http://28.7.184.198:8138', gmail_state),
489
+ ('http://28.7.184.198:8178', slack_state),
490
+ ]
491
+
492
+ for app_url, state in APP_STATES:
493
+ resp = requests.post(
494
+ f'{app_url}/post?sid={sid}',
495
+ json={'action': 'set', 'state': state},
496
+ timeout=30,
497
+ )
498
+ assert resp.status_code == 200, (
499
+ f'State injection failed for {app_url}: {resp.text}'
500
+ )
501
+ print(f'State injected: {app_url} sid={sid}')
502
+
503
+ for app_url, _ in APP_STATES:
504
+ go_payload = requests.get(f'{app_url}/go?sid={sid}', timeout=15).json()
505
+ assert go_payload.get('initial_state') is not None, (
506
+ f'initial_state is None after injection for {app_url}'
507
+ )
508
+ print(f'Verified initial_state set: {app_url}')
509
+
510
+ print(f'Precomputed: won_action={len(_won_action)} T1={len(_tier1)} '
511
+ f'T2={len(_tier2)} T3={len(_tier3)} skipped={len(_skipped)} '
512
+ f'summary_channel=#{SUMMARY_CHANNEL}')
513
+
514
+
515
+ # PATCHED_BY: patch_wait_mocks_loaded.py
516
+ def launch_gui(command, delay_sec=1.0):
517
+ """Launch a GUI command, fully detached from this script.
518
+
519
+ Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that
520
+ wait_mocks_loaded's CDP phase can verify browser render below.
521
+ Idempotent: if the caller already specified a debug port, keep it.
522
+ """
523
+ env = os.environ.copy()
524
+ env['DISPLAY'] = ':0'
525
+ if isinstance(command, str):
526
+ _parts = shlex.split(command)
527
+ else:
528
+ _parts = list(command)
529
+ if (_parts and 'google-chrome' in _parts[0]
530
+ and not any(p.startswith('--remote-debugging-port') for p in _parts)):
531
+ _parts[1:1] = [
532
+ '--no-first-run',
533
+ '--no-default-browser-check',
534
+ '--remote-debugging-port=1337',
535
+ ]
536
+ subprocess.Popen(
537
+ _parts,
538
+ stdin=subprocess.DEVNULL,
539
+ stdout=subprocess.DEVNULL,
540
+ stderr=subprocess.DEVNULL,
541
+ env=env,
542
+ start_new_session=True,
543
+ )
544
+ time.sleep(delay_sec)
545
+
546
+
547
+ def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12):
548
+ """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style.
549
+
550
+ Phase 1 - Backend readiness:
551
+ Poll each mock's /state?sid=<sid> (preferred) or /go?sid=<sid>
552
+ (fallback) until it returns 200 with 'stored_state' or
553
+ 'initial_state' respectively, or until timeout.
554
+
555
+ Phase 2 - Browser render verification (via CDP + Playwright):
556
+ Connect to http://localhost:1337 (the --remote-debugging-port
557
+ injected by launch_gui above), wait for every open tab to reach
558
+ 'networkidle' AND to contain at least 20 DOM elements. This
559
+ guarantees the SPA fetched /go?sid= data AND actually painted,
560
+ not just that the mock backend is up.
561
+
562
+ Fallback:
563
+ If Playwright is missing or CDP cannot be reached, sleep for
564
+ `render_buffer` seconds as a best-effort delay so the screenshot
565
+ loop does not start on a still-blank tab.
566
+ """
567
+ import urllib.request as _urlreq
568
+ import time as _t
569
+ _urls = [p for p, _ in app_states]
570
+ _opener = _urlreq.build_opener(_urlreq.ProxyHandler({}))
571
+
572
+ # ---- Phase 1: backend readiness ----
573
+ _deadline = _t.time() + timeout
574
+ _todo = list(_urls)
575
+ while _todo and _t.time() < _deadline:
576
+ _rest = []
577
+ for _u in _todo:
578
+ _ok = False
579
+ for _path, _need in (('/state?sid=', b'stored_state'),
580
+ ('/go?sid=', b'initial_state')):
581
+ try:
582
+ _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5)
583
+ if _r.status == 200:
584
+ _body = _r.read()
585
+ if _need in _body:
586
+ _ok = True
587
+ break
588
+ except Exception:
589
+ pass
590
+ if _ok:
591
+ print(f" {_u}: backend ready")
592
+ continue
593
+ _rest.append(_u)
594
+ _todo = _rest
595
+ if _todo:
596
+ _t.sleep(2)
597
+ _done = len(_urls) - len(_todo)
598
+ _pend = f" (pending: {_todo})" if _todo else ""
599
+ print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}")
600
+
601
+ # ---- Phase 2: browser render verification via CDP ----
602
+ _cdp_ok = False
603
+ try:
604
+ from playwright.sync_api import sync_playwright
605
+ _cdp_dl = _t.time() + max(15.0, _deadline - _t.time())
606
+ with sync_playwright() as _p:
607
+ _br = None
608
+ while _t.time() < _cdp_dl:
609
+ try:
610
+ _br = _p.chromium.connect_over_cdp('http://localhost:1337')
611
+ break
612
+ except Exception:
613
+ _t.sleep(0.5)
614
+ if _br is None:
615
+ print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?")
616
+ else:
617
+ _n_expected = len(_urls)
618
+ _pages = []
619
+ _pg_dl = _t.time() + 15
620
+ _last_count = -1
621
+ _stable_since = None
622
+ while _t.time() < _pg_dl:
623
+ _pages = []
624
+ for _c in _br.contexts:
625
+ _pages.extend(_c.pages)
626
+ _cnt = len(_pages)
627
+ if _n_expected > 0 and _cnt >= _n_expected:
628
+ break
629
+ if _cnt > 0 and _cnt == _last_count:
630
+ if _stable_since is None:
631
+ _stable_since = _t.time()
632
+ elif _t.time() - _stable_since >= 1.5:
633
+ break
634
+ else:
635
+ _stable_since = None
636
+ _last_count = _cnt
637
+ _t.sleep(0.5)
638
+ _pages = []
639
+ for _c in _br.contexts:
640
+ _pages.extend(_c.pages)
641
+ if not _pages:
642
+ print(" wait_mocks_loaded: CDP connected but no open tabs found")
643
+ else:
644
+ print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render")
645
+ _MIN_ELEMS = 20
646
+ _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap
647
+ for _pg in _pages: # bring each to front once to defeat background-tab render throttling
648
+ try:
649
+ _pg.bring_to_front()
650
+ except Exception:
651
+ pass
652
+ _pending = list(_pages)
653
+ while _pending and _t.time() < _verify_dl:
654
+ _still = []
655
+ for _pg in _pending:
656
+ _ttl = ""
657
+ try:
658
+ _ttl = _pg.title()
659
+ except Exception:
660
+ pass
661
+ try:
662
+ _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0")
663
+ except Exception:
664
+ _n = 0
665
+ if _n >= _MIN_ELEMS:
666
+ print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)")
667
+ else:
668
+ _still.append(_pg)
669
+ _pending = _still
670
+ if _pending:
671
+ _t.sleep(2)
672
+ if not _pending:
673
+ _cdp_ok = True
674
+ else:
675
+ for _pg in _pending:
676
+ _ttl = ""
677
+ try:
678
+ _ttl = _pg.title()
679
+ except Exception:
680
+ pass
681
+ print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back")
682
+ except ImportError:
683
+ print(" wait_mocks_loaded: playwright not installed; skipping CDP phase")
684
+ except Exception as _e:
685
+ print(f" wait_mocks_loaded: CDP phase error ({_e!r})")
686
+
687
+ if not _cdp_ok:
688
+ print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep")
689
+ _t.sleep(render_buffer)
690
+ else:
691
+ print(" wait_mocks_loaded: browser render verified, skipping render_buffer")
692
+
693
+
694
+ def _open_mock_tabs(app_states, sid_value):
695
+ """Open the first mock as the primary Chrome window, the rest as new tabs.
696
+
697
+ Uses launch_gui once per URL so that the macOS localizer regex-extract
698
+ (which grabs the FIRST quoted URL per call) still works correctly.
699
+ """
700
+ _urls = [p for p, _ in app_states]
701
+ if not _urls:
702
+ return
703
+ launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0)
704
+ for _u in _urls[1:]:
705
+ launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0)
706
+
707
+
708
+
709
+ # PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate)
710
+ def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0):
711
+ """Block until every mock serves injected state AND (best-effort) renders."""
712
+ import time as _t
713
+ deadline = _t.time() + timeout
714
+ pending = dict(mocks)
715
+ while pending and _t.time() < deadline:
716
+ for name in list(pending):
717
+ try:
718
+ r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5)
719
+ if r.status_code == 200 and r.json().get('initial_state') is not None:
720
+ del pending[name]
721
+ except Exception:
722
+ pass
723
+ if pending:
724
+ _t.sleep(1.0)
725
+ if pending:
726
+ print(f'WARN: mocks not ready within {timeout}s: {list(pending)}')
727
+ try:
728
+ from playwright.sync_api import sync_playwright
729
+ except ImportError:
730
+ print('WARN: playwright not installed; skipping render check, settle 3s')
731
+ _t.sleep(3.0)
732
+ return
733
+ with sync_playwright() as p:
734
+ try:
735
+ browser = p.chromium.launch(channel='chrome', headless=True,
736
+ args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'])
737
+ except Exception as e:
738
+ print(f'WARN: could not launch chrome for render check: {e}; settle 3s')
739
+ _t.sleep(3.0)
740
+ return
741
+ try:
742
+ for name, url in mocks.items():
743
+ page = browser.new_page()
744
+ try:
745
+ page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000))
746
+ page.wait_for_function(
747
+ "document.body && document.body.innerText.length > 50",
748
+ timeout=int(render_timeout * 1000))
749
+ print(f'[{name}] rendered OK')
750
+ except Exception as e:
751
+ print(f'WARN: [{name}] render check issue: {e}')
752
+ finally:
753
+ page.close()
754
+ finally:
755
+ browser.close()
756
+
757
+
758
+ # ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render
759
+ _open_mock_tabs(APP_STATES, sid)
760
+ wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15)
761
+ wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12)
762
+ print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps')
ae_deal_handoff_002__long/reward.py ADDED
@@ -0,0 +1,825 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: T-hard — Hand off qualified opportunities (H16)
3
+ Task ID: ae_deal_handoff_002__long
4
+ Mocks: salesforce_mock,trello_mock,gmail_mock,slack_mock
5
+
6
+ A sales-ops rep hands off newly-qualified Salesforce Closed-Won opportunities
7
+ to the delivery team. For each qualifying opp the rep tiers by amount and takes
8
+ tier-appropriate actions across SF (owner change, + kickoff task on Tier-1),
9
+ Trello (Handoff card w/ tier label + due date), Gmail (label + kickoff email
10
+ on Tier-1 only) and Slack (summary post + pin).
11
+
12
+ DEVIATION FROM DESIGN SPEC: the salesforce_mock Opportunity.stage enum has NO
13
+ 'Onboarding' value; per the design's construction note, the graded Salesforce
14
+ transition is Owner -> 'Delivery Lead' for every tier. Stage is not graded.
15
+
16
+ Answer key (sole source of truth): salesforce.initial_state._task_adapter has
17
+ task_opps + expected (list of dicts w/ opp_id, tier, requires_action,
18
+ target_owner_name, card_title, card_label, card_due, task_subject, label_name,
19
+ email_subject, account_email, ...). The list is precomputed in initial_setup.
20
+
21
+ SCORING CONTRACT (HARD_TASK_PIPELINE §5): every component ∈ [0,1], weights sum
22
+ to exactly 1.0, NO subtracted penalties. Leak (re-owning an already-handed-off
23
+ opp / handing off a not-won opp / spurious Delivery-Queue card / spurious
24
+ kickoff activity) is punished by *precision* inside the F1 / decision-set
25
+ components — it lowers them toward 0 but total stays in [0,1].
26
+
27
+ Weights (sum = 1.00):
28
+ 0.24 SF owner F1 — true = {opp_id : opps requiring action}, pred =
29
+ {opp_id : opps whose ownerId != injection ownerId AND
30
+ current owner name == 'Delivery Lead'}. FP = re-owning
31
+ a not-won or already-handed-off opp.
32
+ 0.24 handoff card F1 — NEW Trello cards on 'Delivery Queue' vs the
33
+ card_title set (diff by card id; F1).
34
+ 0.14 card label+due — among MATCHED cards, frac w/ correct tier-label
35
+ (by board-label NAME) AND dueDate == card_due (day).
36
+ 0.12 Tier-1 kickoff — F1 over the Tier-1 'Kickoff - <Opp>' subject set of
37
+ task NEW activities[] entries (diff by id).
38
+ 0.10 gmail label — frac of Tier-1 accounts w/ their inbound email
39
+ carrying the 'Handoff' label (by NAME).
40
+ 0.06 Tier-1 email — frac of Tier-1 with a SENT 'Kickoff for <Opp>' email
41
+ to the account contact address.
42
+ 0.05 slack post — a non-empty #delivery message containing a digit.
43
+ 0.05 slack pin — that summary is PINNED (gated on a real posted msg).
44
+ do-nothing -> 0.0 ; perfect -> 1.0 ; leak -> < 1.0 (via precision, never < 0).
45
+ """
46
+ import copy
47
+ import re
48
+ import sys
49
+
50
+ import requests
51
+
52
+ from datetime import datetime, timezone, timedelta
53
+
54
+ TZ_PLUS_8 = timezone(timedelta(hours=8))
55
+
56
+
57
+ def parse_as_utc(s, default_tz=TZ_PLUS_8):
58
+ """
59
+ Parse an ISO datetime string and convert it to UTC.
60
+
61
+ Assumption:
62
+ - If the string has Z or +00:00, it is already timezone-aware.
63
+ - If the string has no timezone, treat it as UTC+8.
64
+ """
65
+ if not s:
66
+ return None
67
+
68
+ s = str(s).strip()
69
+
70
+ # Python's fromisoformat prefers +00:00 over Z
71
+ if s.endswith("Z"):
72
+ s = s[:-1] + "+00:00"
73
+
74
+ dt = datetime.fromisoformat(s)
75
+
76
+ # Example: "2024-03-18T09:00" has no timezone.
77
+ # Treat it as UTC+8.
78
+ if dt.tzinfo is None:
79
+ dt = dt.replace(tzinfo=default_tz)
80
+
81
+ return dt.astimezone(timezone.utc)
82
+
83
+
84
+ def norm_dt(s):
85
+ dt = parse_as_utc(s)
86
+ if dt is None:
87
+ return ""
88
+ return dt.isoformat(timespec="seconds")
89
+
90
+
91
+ def date_key(s, local_tz=TZ_PLUS_8):
92
+ """
93
+ Return the calendar date (YYYY-MM-DD) that an ISO datetime represents in
94
+ LOCAL (UTC+8) terms. Timezone-aware values are converted to local first so
95
+ that, e.g., a UTC '...T09:00:00Z' due-time round-trips to the same local day
96
+ as a naive '...T17:00:00'. Naive values are taken as-is (already local).
97
+ Bare 'YYYY-MM-DD' strings fall back to their first 10 chars.
98
+ """
99
+ if not s:
100
+ return None
101
+ s = str(s).strip()
102
+ if s.endswith("Z"):
103
+ s = s[:-1] + "+00:00"
104
+ try:
105
+ dt = datetime.fromisoformat(s)
106
+ except ValueError:
107
+ return s[:10] if len(s) >= 10 else None
108
+ if dt.tzinfo is not None:
109
+ dt = dt.astimezone(local_tz)
110
+ return dt.date().isoformat()
111
+
112
+
113
+ # --- Read sid (set by initial_setup.py) ---
114
+ try:
115
+ with open('/tmp/task_web_sid', encoding='utf-8') as f:
116
+ sid = f.read().strip()
117
+ if not sid:
118
+ raise ValueError('sid is empty')
119
+ except Exception as e:
120
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
121
+ print('REWARD: 0.0')
122
+ sys.exit(0)
123
+
124
+
125
+ APP_URLS = {'salesforce': 'http://28.7.184.198:8175', 'trello': 'http://28.7.184.198:8182',
126
+ 'gmail': 'http://28.7.184.198:8138', 'slack': 'http://28.7.184.198:8178'}
127
+ _GO_CACHE = {}
128
+
129
+
130
+ def clamp01(x):
131
+ return max(0.0, min(1.0, float(x)))
132
+
133
+
134
+ def frac(num, den):
135
+ return 0.0 if den == 0 else num / den
136
+
137
+
138
+ def f1(true_set, pred_set):
139
+ if not true_set and not pred_set:
140
+ return 1.0
141
+ tp = len(true_set & pred_set)
142
+ if tp == 0:
143
+ return 0.0
144
+ prec = tp / len(pred_set)
145
+ rec = tp / len(true_set)
146
+ return 2 * prec * rec / (prec + rec)
147
+
148
+
149
+ def by_id(items, key='id'):
150
+ return {it.get(key): it for it in (items or []) if isinstance(it, dict)}
151
+
152
+
153
+ def has_text(haystack, *needles):
154
+ s = (haystack or '').lower()
155
+ return any(n.lower() in s for n in needles)
156
+
157
+
158
+ def norm(s):
159
+ return (str(s) if s is not None else '').strip().lower()
160
+
161
+
162
+ def _msg_text(msg):
163
+ return msg.get('content') or msg.get('text') or ''
164
+
165
+
166
+ def _slack_channel_messages(slack_state, channel_name):
167
+ channels = slack_state.get('channels', [])
168
+ target = None
169
+ for ch in channels:
170
+ if norm(ch.get('name')) == norm(channel_name):
171
+ target = ch
172
+ break
173
+ if target is None:
174
+ return []
175
+
176
+ ch_msgs = target.get('messages')
177
+ if isinstance(ch_msgs, list):
178
+ return ch_msgs
179
+
180
+ msg_map = slack_state.get('messages', {})
181
+ if isinstance(msg_map, dict):
182
+ return msg_map.get(target.get('channelId'), []) or []
183
+ return []
184
+
185
+
186
+ def _normalize_app_name(app):
187
+ app = (app or '').strip().lower()
188
+ return app[:-5] if app.endswith('_mock') else app
189
+
190
+
191
+ def _parse_cell_id(cell_id):
192
+ if not isinstance(cell_id, str) or not cell_id:
193
+ return None
194
+ idx = 0
195
+ while idx < len(cell_id) and cell_id[idx].isalpha():
196
+ idx += 1
197
+ if idx == 0 or idx >= len(cell_id):
198
+ return None
199
+ col = 0
200
+ for ch in cell_id[:idx].upper():
201
+ col = col * 26 + (ord(ch) - ord('A') + 1)
202
+ try:
203
+ row = int(cell_id[idx:])
204
+ except ValueError:
205
+ return None
206
+ return row, col - 1
207
+
208
+
209
+ def _extract_rows_from_workbook(state):
210
+ if not isinstance(state, dict):
211
+ return None
212
+ sheets = state.get('sheets')
213
+ if not isinstance(sheets, list):
214
+ return None
215
+
216
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
217
+ headers_by_sheet = adapter.get('headers_by_sheet') if isinstance(adapter.get('headers_by_sheet'), dict) else {}
218
+
219
+ out = {}
220
+ for sh in sheets:
221
+ if not isinstance(sh, dict):
222
+ continue
223
+ name = sh.get('name') or sh.get('id') or 'Sheet1'
224
+ data = sh.get('data') if isinstance(sh.get('data'), dict) else {}
225
+
226
+ headers = headers_by_sheet.get(name)
227
+ if not headers:
228
+ cols = []
229
+ for cid, cell in data.items():
230
+ rc = _parse_cell_id(cid)
231
+ if not rc:
232
+ continue
233
+ row_idx, col_idx = rc
234
+ if row_idx != 1:
235
+ continue
236
+ value = ''
237
+ if isinstance(cell, dict):
238
+ value = cell.get('value', '')
239
+ elif cell is not None:
240
+ value = str(cell)
241
+ if value is not None and str(value) != '':
242
+ cols.append((col_idx, str(value)))
243
+ headers = [v for _, v in sorted(cols)]
244
+
245
+ if not headers:
246
+ continue
247
+
248
+ by_row = {}
249
+ for cid, cell in data.items():
250
+ rc = _parse_cell_id(cid)
251
+ if not rc:
252
+ continue
253
+ row_idx, col_idx = rc
254
+ if row_idx <= 1 or col_idx >= len(headers):
255
+ continue
256
+ if isinstance(cell, dict):
257
+ value = cell.get('value', '')
258
+ else:
259
+ value = cell
260
+ by_row.setdefault(row_idx, {})[headers[col_idx]] = value
261
+
262
+ rows = []
263
+ for row_idx in sorted(by_row.keys()):
264
+ row = by_row[row_idx]
265
+ if not any(str(row.get(h, '')).strip() for h in headers):
266
+ continue
267
+ rows.append({h: row.get(h, '') for h in headers})
268
+
269
+ out[name] = {'headers': headers, 'rows': rows}
270
+
271
+ if not out:
272
+ return None
273
+ return {'sheets': out}
274
+
275
+
276
+ def _sheet_rows(state, sheet_name=None):
277
+ wb = _extract_rows_from_workbook(state) or {}
278
+ sheets = wb.get('sheets', {}) if isinstance(wb, dict) else {}
279
+ if sheet_name is not None:
280
+ s = sheets.get(sheet_name)
281
+ return s.get('rows', []) if isinstance(s, dict) else []
282
+ for s in sheets.values():
283
+ if isinstance(s, dict):
284
+ return s.get('rows', [])
285
+ return []
286
+
287
+
288
+ def _materialize_google_sheets(payload):
289
+ for key in ('initial_state', 'current_state'):
290
+ state = payload.get(key)
291
+ if not isinstance(state, dict):
292
+ continue
293
+ maybe_rows = _extract_rows_from_workbook(state)
294
+ if maybe_rows is not None:
295
+ state['_ui_workbook'] = {
296
+ 'sheets': copy.deepcopy(state.get('sheets', [])),
297
+ 'title': state.get('title'),
298
+ }
299
+ state['sheets'] = maybe_rows['sheets']
300
+
301
+
302
+ def _materialize_slack(payload):
303
+ for key in ('initial_state', 'current_state'):
304
+ state = payload.get(key)
305
+ if not isinstance(state, dict):
306
+ continue
307
+ channels = state.get('channels') if isinstance(state.get('channels'), list) else []
308
+ messages_map = state.get('messages') if isinstance(state.get('messages'), dict) else {}
309
+ for ch in channels:
310
+ if not isinstance(ch, dict):
311
+ continue
312
+ cid = ch.get('channelId') or ch.get('id')
313
+ if not cid:
314
+ continue
315
+ msg_list = messages_map.get(cid) if isinstance(messages_map.get(cid), list) else []
316
+ channel_msgs = ch.get('messages') if isinstance(ch.get('messages'), list) else []
317
+ merged = {
318
+ (m.get('messageId') or m.get('id')): dict(m)
319
+ for m in channel_msgs
320
+ if isinstance(m, dict)
321
+ }
322
+ for m in msg_list:
323
+ if not isinstance(m, dict):
324
+ continue
325
+ mid = m.get('messageId') or m.get('id')
326
+ text = m.get('text') if m.get('text') is not None else m.get('content', '')
327
+ merged[mid] = {
328
+ 'id': mid,
329
+ 'messageId': mid,
330
+ 'text': text,
331
+ 'content': m.get('content', text),
332
+ 'senderId': m.get('senderId'),
333
+ 'timestamp': m.get('timestamp'),
334
+ 'reactions': m.get('reactions') if isinstance(m.get('reactions'), list) else [],
335
+ }
336
+ ch['messages'] = list(merged.values())
337
+
338
+
339
+ def _owner_name_map(state):
340
+ out = {}
341
+ users = state.get('users') if isinstance(state.get('users'), list) else []
342
+ for u in users:
343
+ if not isinstance(u, dict):
344
+ continue
345
+ uid = u.get('userId')
346
+ if not uid:
347
+ continue
348
+ name = (f"{u.get('firstName', '')} {u.get('lastName', '')}".strip() or u.get('name') or uid)
349
+ out[uid] = name
350
+ return out
351
+
352
+
353
+ def _materialize_salesforce(payload):
354
+ for key in ('initial_state', 'current_state'):
355
+ state = payload.get(key)
356
+ if not isinstance(state, dict):
357
+ continue
358
+
359
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
360
+ owner_names = _owner_name_map(state)
361
+
362
+ task_leads = adapter.get('task_leads') if isinstance(adapter.get('task_leads'), dict) else None
363
+ if task_leads and isinstance(state.get('leads'), list):
364
+ restored = []
365
+ for lead in state['leads']:
366
+ if not isinstance(lead, dict):
367
+ continue
368
+ lid = str(lead.get('leadId') or lead.get('id') or '')
369
+ meta = task_leads.get(lid, {})
370
+ restored.append({
371
+ 'id': meta.get('id') or lead.get('leadId') or lead.get('id'),
372
+ 'company': lead.get('company', meta.get('company', '')),
373
+ 'status': lead.get('status', 'New'),
374
+ 'ownerName': owner_names.get(lead.get('ownerId')) or meta.get('ownerName'),
375
+ 'annualRevenue': meta.get('annualRevenue', lead.get('revenue')),
376
+ })
377
+ state['leads'] = restored
378
+
379
+ task_accounts = adapter.get('task_accounts') if isinstance(adapter.get('task_accounts'), dict) else None
380
+ if task_accounts and isinstance(state.get('accounts'), list):
381
+ current_by_id = {}
382
+ for acc in state['accounts']:
383
+ if isinstance(acc, dict):
384
+ current_by_id[str(acc.get('accountId') or acc.get('id') or '')] = acc
385
+
386
+ restored_accounts = []
387
+ for aid, meta in task_accounts.items():
388
+ cur = current_by_id.get(str(aid), {})
389
+ restored_accounts.append({
390
+ 'id': meta.get('id') or aid,
391
+ 'name': meta.get('name') or cur.get('name', ''),
392
+ 'contact': meta.get('contact'),
393
+ 'wonWithin7d': bool(meta.get('wonWithin7d', False)),
394
+ 'onboardingStage': cur.get('onboardingStage', meta.get('onboardingStage')),
395
+ })
396
+ state['accounts'] = restored_accounts
397
+
398
+
399
+ def _materialize_google_docs(payload):
400
+ for key in ('initial_state', 'current_state'):
401
+ state = payload.get(key)
402
+ if not isinstance(state, dict):
403
+ continue
404
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
405
+ task_docs = adapter.get('task_documents') if isinstance(adapter.get('task_documents'), dict) else None
406
+ if not task_docs:
407
+ continue
408
+ docs_map = state.get('documents') if isinstance(state.get('documents'), dict) else {}
409
+ restored = []
410
+ for did, meta in task_docs.items():
411
+ cur = docs_map.get(did, {}) if isinstance(docs_map, dict) else {}
412
+ restored.append({
413
+ 'id': meta.get('id') or did,
414
+ 'title': cur.get('title', meta.get('title')),
415
+ 'vendor': meta.get('vendor'),
416
+ 'folder': meta.get('folder'),
417
+ 'content': cur.get('content', meta.get('content', '')),
418
+ })
419
+ state['documents'] = restored
420
+
421
+
422
+ def _adapt_payload_for_reward(app, payload):
423
+ app_name = _normalize_app_name(app)
424
+ if app_name == 'google_sheets':
425
+ _materialize_google_sheets(payload)
426
+ elif app_name == 'slack':
427
+ _materialize_slack(payload)
428
+ elif app_name == 'salesforce':
429
+ _materialize_salesforce(payload)
430
+ elif app_name == 'google_docs':
431
+ _materialize_google_docs(payload)
432
+ return payload
433
+
434
+
435
+ def go(app_name):
436
+ if app_name in _GO_CACHE:
437
+ return _GO_CACHE[app_name]
438
+
439
+ base = APP_URLS.get(app_name)
440
+ if not base:
441
+ print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)')
442
+ print('REWARD: 0.0')
443
+ sys.exit(0)
444
+
445
+ try:
446
+ resp = requests.get(f'{base}/go?sid={sid}', timeout=15)
447
+ resp.raise_for_status()
448
+ payload = resp.json()
449
+ except Exception as e:
450
+ print(f'CRITICAL: cannot fetch {app_name} go state: {e}')
451
+ print('REWARD: 0.0')
452
+ sys.exit(0)
453
+
454
+ payload = _adapt_payload_for_reward(app_name, payload)
455
+ _GO_CACHE[app_name] = payload
456
+ return payload
457
+
458
+
459
+ # === Task-specific helpers ===
460
+ def _gmail_sent_emails(gmail_state):
461
+ """All emails that look 'sent' (folder sent/outbox OR isSent/sentAt flags)."""
462
+ out = []
463
+ if not isinstance(gmail_state, dict):
464
+ return out
465
+ for e in (gmail_state.get('emails', []) or []):
466
+ if not isinstance(e, dict):
467
+ continue
468
+ folder = norm(e.get('folder'))
469
+ if folder in ('sent', 'sentitems', 'sent items', 'outbox'):
470
+ out.append(e)
471
+ continue
472
+ if e.get('isSent') is True or e.get('sentAt') or e.get('sentDateTime'):
473
+ out.append(e)
474
+ if out:
475
+ return out
476
+ for key in ('sent', 'sentEmails', 'outbox'):
477
+ items = gmail_state.get(key, [])
478
+ if isinstance(items, list):
479
+ out.extend(x for x in items if isinstance(x, dict))
480
+ return out
481
+
482
+
483
+ def _email_to_addrs(e):
484
+ """Normalized set of recipient email addresses on an email."""
485
+ out = set()
486
+ to = e.get('to')
487
+ if isinstance(to, list):
488
+ for x in to:
489
+ if isinstance(x, dict):
490
+ a = x.get('email') or x.get('name')
491
+ else:
492
+ a = x
493
+ if a:
494
+ out.add(norm(a))
495
+ elif isinstance(to, dict):
496
+ a = to.get('email') or to.get('name')
497
+ if a:
498
+ out.add(norm(a))
499
+ elif to:
500
+ out.add(norm(to))
501
+ return out
502
+
503
+
504
+ def _email_from_addr(e):
505
+ frm = e.get('from')
506
+ if isinstance(frm, dict):
507
+ return norm(frm.get('email') or frm.get('name'))
508
+ return norm(frm)
509
+
510
+
511
+ def _raw_date_part(s):
512
+ """Literal wall-clock date 'YYYY-MM-DD' (strip Z / tz offset, take date)."""
513
+ if not s:
514
+ return ''
515
+ t = str(s).strip()
516
+ if 'T' not in t:
517
+ return t[:10]
518
+ return t.split('T', 1)[0]
519
+
520
+
521
+ def _due_day_matches(due_val, target_day):
522
+ """True if the card dueDate falls on target_day ('YYYY-MM-DD') under EITHER the
523
+ literal wall-clock reading OR the UTC->UTC+8 conversion (robust to whatever the
524
+ trello card-modal date input serialized: naive-local, UTC midnight, or offset)."""
525
+ target = norm(target_day)
526
+ if not target or not due_val:
527
+ return False
528
+ if norm(_raw_date_part(due_val)) == target:
529
+ return True
530
+ if date_key(due_val) == target: # UTC->local (UTC+8) reading
531
+ return True
532
+ dt = parse_as_utc(due_val) # UTC-as-is reading
533
+ if dt is not None and dt.date().isoformat() == target:
534
+ return True
535
+ return False
536
+
537
+
538
+ def _label_name_set(email, label_id_to_name):
539
+ """Resolve an email's label ids/names to a set of normalized label NAMES."""
540
+ out = set()
541
+ labels = email.get('labels')
542
+ if not isinstance(labels, list):
543
+ return out
544
+ for lab in labels:
545
+ if isinstance(lab, dict):
546
+ nm = lab.get('name') or lab.get('id')
547
+ if nm:
548
+ out.add(norm(label_id_to_name.get(nm, nm)))
549
+ else:
550
+ out.add(norm(label_id_to_name.get(lab, lab)))
551
+ return out
552
+
553
+
554
+ # === Task-specific reward ===
555
+ #
556
+ # Ground truth lives in salesforce.initial_state._task_adapter.expected (a list
557
+ # of dicts, one per opportunity):
558
+ # opp_id (str) -> Salesforce Opportunity id
559
+ # opp_name (str) -> Opportunity name
560
+ # account (str) / account_email (str)
561
+ # amount (int)
562
+ # stage_at_injection (str) -> 'Closed Won' | 'Negotiation'
563
+ # owner_id_at_injection (str) -> ADMIN_OWNER_ID (change) or DELIVERY (skip)
564
+ # tier (str|None) -> 'Tier-1'|'Tier-2'|'Tier-3' (only for Won)
565
+ # requires_action (bool) -> Won AND owner != Delivery Lead
566
+ # target_owner_name (str|None) -> 'Delivery Lead' (all requires_action opps)
567
+ # card_title (str|None) -> 'Handoff: <Opp>' (all requires_action opps)
568
+ # card_label (str|None) -> 'Tier-1'|'Tier-2'|'Tier-3'
569
+ # card_due (str|None) -> 'YYYY-MM-DD' (today+3/5/7)
570
+ # task_subject (str|None) -> 'Kickoff - <Opp>' (Tier-1 only)
571
+ # label_name (str|None) -> 'Handoff' (Tier-1 only; Gmail label by NAME)
572
+ # email_subject (str|None) -> 'Kickoff for <Opp>' (Tier-1 only)
573
+
574
+ WEIGHT_OWNER = 0.24 # SF opp owner F1 (opps requiring change vs opps re-owned to Delivery Lead)
575
+ WEIGHT_CARD = 0.24 # handoff card F1 (NEW Trello cards on Delivery Queue vs card_title set)
576
+ WEIGHT_CARDMETA = 0.14 # among matched cards, correct tier-label (by NAME) + due date
577
+ WEIGHT_TASK = 0.12 # Tier-1 kickoff activity F1 (NEW activities[] w/ 'Kickoff -' subject)
578
+ WEIGHT_GLABEL = 0.10 # Tier-1 account inbound email carries 'Handoff' label (by NAME)
579
+ WEIGHT_EMAIL = 0.06 # Tier-1 SENT 'Kickoff for <Opp>' email to account contact
580
+ WEIGHT_POST = 0.05 # slack #delivery summary posted
581
+ WEIGHT_PIN = 0.05 # that summary pinned
582
+ assert abs((WEIGHT_OWNER + WEIGHT_CARD + WEIGHT_CARDMETA + WEIGHT_TASK
583
+ + WEIGHT_GLABEL + WEIGHT_EMAIL + WEIGHT_POST + WEIGHT_PIN) - 1.0) < 1e-9
584
+
585
+
586
+ def reward(go):
587
+ # === Salesforce state (owner + kickoff task) ===
588
+ sf = go('salesforce')
589
+ sf_i = sf.get('initial_state', {}) or {}
590
+ sf_c = sf.get('current_state', {}) or {}
591
+ adapter = sf_i.get('_task_adapter', {}) if isinstance(sf_i.get('_task_adapter'), dict) else {}
592
+ expected = adapter.get('expected', []) or []
593
+ delivery_owner_name = norm(adapter.get('delivery_owner_name') or 'Delivery Lead')
594
+ delivery_list_id = adapter.get('delivery_list_id')
595
+ delivery_list_name = norm(adapter.get('delivery_list_name') or 'Delivery Queue')
596
+ summary_channel = adapter.get('summary_channel') or 'delivery'
597
+
598
+ opps_i_by_id = by_id(sf_i.get('opportunities') or [], 'opportunityId')
599
+ opps_c_by_id = by_id(sf_c.get('opportunities') or [], 'opportunityId')
600
+
601
+ # After _materialize_salesforce, each opp payload carries an 'ownerName'
602
+ # convenience field derived from users[]. Fall back to the users[] map.
603
+ owner_name_map = _owner_name_map(sf_c)
604
+
605
+ def _owner_name_of(opp):
606
+ if not isinstance(opp, dict):
607
+ return ''
608
+ # Prefer materialized ownerName; else look up.
609
+ n = norm(opp.get('ownerName') or '')
610
+ if n:
611
+ return n
612
+ return norm(owner_name_map.get(opp.get('ownerId'), ''))
613
+
614
+ require_action = [e for e in expected if e.get('requires_action')]
615
+ tier1 = [e for e in require_action if norm(e.get('tier') or '') == 'tier-1']
616
+ skipped = [e for e in expected if not e.get('requires_action')]
617
+ n_action = len(require_action)
618
+ n_tier1 = len(tier1)
619
+
620
+ # --- Component 1 (0.24): SF owner F1 ---
621
+ # TRUE = { opp_id : requires_action }
622
+ # PRED = { opp_id : opp whose current owner == 'Delivery Lead' AND
623
+ # whose ownerId differs from injection ownerId }
624
+ true_owner_ids = {e['opp_id'] for e in require_action}
625
+ pred_owner_ids = set()
626
+ for oid, cur in opps_c_by_id.items():
627
+ init = opps_i_by_id.get(oid) or {}
628
+ if norm(_owner_name_of(cur)) == delivery_owner_name and cur.get('ownerId') != init.get('ownerId'):
629
+ pred_owner_ids.add(oid)
630
+ owner_f1 = f1(true_owner_ids, pred_owner_ids)
631
+ s_owner = WEIGHT_OWNER * owner_f1
632
+
633
+ # --- Component 4 (0.12): Tier-1 kickoff activity F1 (NEW activities) ---
634
+ acts_i = sf_i.get('activities') or []
635
+ acts_c = sf_c.get('activities') or []
636
+ initial_act_ids = {a.get('activityId') for a in acts_i if isinstance(a, dict)}
637
+ new_acts = [a for a in acts_c if isinstance(a, dict) and a.get('activityId') not in initial_act_ids]
638
+ true_task_subjects = {norm(e.get('task_subject') or '') for e in tier1
639
+ if e.get('task_subject')}
640
+ pred_task_subjects = set()
641
+ tier1_ids = {e['opp_id'] for e in tier1}
642
+ for a in new_acts:
643
+ subj = norm(a.get('subject') or '')
644
+ if not subj:
645
+ continue
646
+ # Only credit activities related to a Tier-1 opp (extra Kickoff cards
647
+ # attached to random opps count as false positives via the F1 pred set).
648
+ rel_id = a.get('relatedToId')
649
+ if rel_id and rel_id not in tier1_ids and rel_id in opps_i_by_id:
650
+ # Attached to a non-Tier-1 opp -> spurious.
651
+ pred_task_subjects.add(subj + f'@{rel_id}') # tag-different
652
+ continue
653
+ pred_task_subjects.add(subj)
654
+ task_f1 = f1(true_task_subjects, pred_task_subjects)
655
+ s_task = WEIGHT_TASK * task_f1
656
+
657
+ # === Trello state (handoff cards) ===
658
+ trello = go('trello')
659
+ tr_i = trello.get('initial_state', {}) or {}
660
+ tr_c = trello.get('current_state', {}) or {}
661
+ cards_i = tr_i.get('cards', {}) if isinstance(tr_i.get('cards'), dict) else {}
662
+ cards_c = tr_c.get('cards', {}) if isinstance(tr_c.get('cards'), dict) else {}
663
+ lists_c = tr_c.get('lists', {}) if isinstance(tr_c.get('lists'), dict) else {}
664
+ boards_c = tr_c.get('boards', {}) if isinstance(tr_c.get('boards'), dict) else {}
665
+
666
+ # Board label NAME -> id (union over all boards).
667
+ label_name_to_id = {}
668
+ for b in boards_c.values():
669
+ if not isinstance(b, dict):
670
+ continue
671
+ for lab in (b.get('labels') or []):
672
+ if isinstance(lab, dict) and lab.get('name') and lab.get('id'):
673
+ label_name_to_id.setdefault(norm(lab.get('name')), lab.get('id'))
674
+
675
+ # Delivery Queue list id — prefer adapter's delivery_list_id; fallback by title.
676
+ dq_list_id = None
677
+ if delivery_list_id and isinstance(lists_c.get(delivery_list_id), dict):
678
+ dq_list_id = delivery_list_id
679
+ if dq_list_id is None:
680
+ for lid, lst in lists_c.items():
681
+ if isinstance(lst, dict) and norm(lst.get('title') or lst.get('name')) == delivery_list_name:
682
+ dq_list_id = lid
683
+ break
684
+
685
+ initial_card_ids = set(cards_i.keys())
686
+ dq_card_ids = []
687
+ if dq_list_id is not None and isinstance(lists_c.get(dq_list_id), dict):
688
+ dq_card_ids = list(lists_c[dq_list_id].get('cardIds') or [])
689
+ new_dq_cards = [cards_c[cid] for cid in dq_card_ids
690
+ if cid not in initial_card_ids and isinstance(cards_c.get(cid), dict)]
691
+
692
+ # --- Component 2 (0.24): handoff card F1 ---
693
+ true_titles = {norm(e.get('card_title') or '') for e in require_action
694
+ if e.get('card_title')}
695
+ pred_titles = {norm(c.get('title') or '') for c in new_dq_cards if c.get('title')}
696
+ card_f1 = f1(true_titles, pred_titles)
697
+ s_card = WEIGHT_CARD * card_f1
698
+
699
+ # Match new cards back to expected rows by title.
700
+ matched = [] # (card, expected_row)
701
+ for e in require_action:
702
+ want_title = norm(e.get('card_title') or '')
703
+ if not want_title:
704
+ continue
705
+ for c in new_dq_cards:
706
+ if norm(c.get('title') or '') == want_title:
707
+ matched.append((c, e))
708
+ break
709
+
710
+ # --- Component 3 (0.14): matched cards carry correct tier-label + due ---
711
+ meta_ok = 0
712
+ meta_flags = []
713
+ for c, e in matched:
714
+ want_label = norm(e.get('card_label') or '')
715
+ want_label_id = label_name_to_id.get(want_label)
716
+ label_hit = bool(want_label_id) and want_label_id in (c.get('labelIds') or [])
717
+ want_due = e.get('card_due')
718
+ got_due = c.get('dueDate')
719
+ due_hit = _due_day_matches(got_due, want_due)
720
+ ok = label_hit and due_hit
721
+ meta_ok += int(ok)
722
+ meta_flags.append(f"{e.get('opp_id')}=L{int(label_hit)}D{int(due_hit)}")
723
+ s_cardmeta = WEIGHT_CARDMETA * frac(meta_ok, len(matched))
724
+
725
+ # === Gmail state (Tier-1 label + kickoff email) ===
726
+ gmail = go('gmail')
727
+ gmail_i = gmail.get('initial_state', {}) or {}
728
+ gmail_c = gmail.get('current_state', {}) or {}
729
+ emails_c = [em for em in (gmail_c.get('emails', []) or []) if isinstance(em, dict)]
730
+ gmail_id_to_name = {}
731
+ for lab in list(gmail_i.get('labels', []) or []) + list(gmail_c.get('labels', []) or []):
732
+ if isinstance(lab, dict) and lab.get('id'):
733
+ gmail_id_to_name[lab['id']] = lab.get('name') or lab['id']
734
+
735
+ # --- Component 5 (0.10): Tier-1 account inbound email carries 'Handoff' label ---
736
+ glabel_ok = 0
737
+ glabel_flags = []
738
+ for e in tier1:
739
+ cust = norm(e.get('account_email') or '')
740
+ want_label = norm(e.get('label_name') or '')
741
+ ok = bool(cust) and bool(want_label) and any(
742
+ _email_from_addr(em) == cust and norm(em.get('folder')) != 'sent'
743
+ and want_label in _label_name_set(em, gmail_id_to_name)
744
+ for em in emails_c
745
+ )
746
+ glabel_ok += int(ok)
747
+ glabel_flags.append(f"{e.get('opp_id')}={'Y' if ok else 'N'}")
748
+ s_glabel = WEIGHT_GLABEL * frac(glabel_ok, n_tier1)
749
+
750
+ # --- Component 6 (0.06): Tier-1 SENT 'Kickoff for <Opp>' email ---
751
+ sent_emails = _gmail_sent_emails(gmail_c)
752
+ email_ok = 0
753
+ email_flags = []
754
+ for e in tier1:
755
+ cust = norm(e.get('account_email') or '')
756
+ want_subj = norm(e.get('email_subject') or '')
757
+ ok = bool(cust) and any(
758
+ cust in _email_to_addrs(em) and want_subj in norm(em.get('subject') or '')
759
+ for em in sent_emails
760
+ )
761
+ email_ok += int(ok)
762
+ email_flags.append(f"{e.get('opp_id')}={'Y' if ok else 'N'}")
763
+ s_email = WEIGHT_EMAIL * frac(email_ok, n_tier1)
764
+
765
+ # === Slack state (post + pin) ===
766
+ slack = go('slack')
767
+ scur = slack.get('current_state', {}) if isinstance(slack.get('current_state'), dict) else {}
768
+ dm_msgs = _slack_channel_messages(scur, summary_channel)
769
+
770
+ def _is_summary(m):
771
+ text = (_msg_text(m) or '').strip()
772
+ return bool(text) and bool(re.search(r'\d', text))
773
+
774
+ post_ok = any(_is_summary(m) for m in dm_msgs if isinstance(m, dict))
775
+ dm_ch = None
776
+ for ch in (scur.get('channels') or []):
777
+ if isinstance(ch, dict) and norm(ch.get('name')) == norm(summary_channel):
778
+ dm_ch = ch
779
+ break
780
+ pinned = (dm_ch.get('pinnedMessages') or []) if isinstance(dm_ch, dict) else []
781
+ pinned_ids = set()
782
+ for pm in pinned:
783
+ pid = pm.get('messageId') or pm.get('id') if isinstance(pm, dict) else pm
784
+ if pid is not None:
785
+ pinned_ids.add(norm(pid))
786
+ msg_ids = {norm(m.get('messageId') or m.get('id')) for m in dm_msgs if isinstance(m, dict)}
787
+ pin_ok = bool(post_ok and (pinned_ids & msg_ids))
788
+ s_post = WEIGHT_POST * (1.0 if post_ok else 0.0)
789
+ s_pin = WEIGHT_PIN * (1.0 if pin_ok else 0.0)
790
+
791
+ score = (s_owner + s_card + s_cardmeta + s_task
792
+ + s_glabel + s_email + s_post + s_pin)
793
+
794
+ print(
795
+ 'DEBUG_9e3cf2fc '
796
+ f'expected={len(expected)} require_action={n_action} tier1={n_tier1} '
797
+ f'skipped={len(skipped)} '
798
+ f'true_owners={len(true_owner_ids)} pred_owners={len(pred_owner_ids)} '
799
+ f'owner_f1={round(owner_f1, 4)} '
800
+ f'true_cards={len(true_titles)} pred_cards={len(pred_titles)} '
801
+ f'card_f1={round(card_f1, 4)} '
802
+ f'matched={len(matched)} cardmeta={meta_ok}/{len(matched)}[{",".join(meta_flags)}] '
803
+ f'true_tasks={len(true_task_subjects)} pred_tasks={len(pred_task_subjects)} '
804
+ f'task_f1={round(task_f1, 4)} '
805
+ f'glabel={glabel_ok}/{n_tier1}[{",".join(glabel_flags)}] '
806
+ f'email={email_ok}/{n_tier1}[{",".join(email_flags)}] sent={len(sent_emails)} '
807
+ f'slack_post={post_ok} slack_pin={pin_ok} '
808
+ f's_owner={round(s_owner, 4)} s_card={round(s_card, 4)} '
809
+ f's_cardmeta={round(s_cardmeta, 4)} s_task={round(s_task, 4)} '
810
+ f's_glabel={round(s_glabel, 4)} s_email={round(s_email, 4)} '
811
+ f's_post={round(s_post, 4)} s_pin={round(s_pin, 4)} '
812
+ f'total={round(score, 4)}'
813
+ )
814
+
815
+ return clamp01(score)
816
+
817
+
818
+ try:
819
+ score = float(reward(go))
820
+ except Exception as exc:
821
+ print(f'ERROR: reward() raised {exc!r}')
822
+ score = 0.0
823
+
824
+ score = clamp01(score)
825
+ print(f'\nREWARD: {round(score, 4)}')
calc_income_statement_001__long/.PLACEHOLDER ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ This directory is intentionally empty.
2
+ It exists only to satisfy start_our_benchmark_test.sh's uniform
3
+ 'cache_dir/<tid>/ must exist' precheck. Non-mock tasks do not use
4
+ cua_gym cache; their evaluators read a vm_file tarball instead.
5
+ See docs/0716_迁移执行日志.md § S15 for details.
calc_income_statement_001__long/10da84b0-f0cf-58ff-b185-1c101d3b8b00_IncomeStatement2_1.xlsx ADDED
Binary file (9.94 kB). View file
 
calc_income_statement_001__long/350e50bf-8624-51bc-91b7-a8dd0462e518_IncomeStatement2_2.xlsx ADDED
Binary file (9.94 kB). View file
 
calc_income_statement_001__long/4429656d-69b9-58f3-af62-b51df1b7a682_IncomeStatement2_4.xlsx ADDED
Binary file (9.94 kB). View file
 
calc_income_statement_001__long/5_IncomeStatement2_gt1_1.xlsx ADDED
Binary file (10.6 kB). View file
 
calc_income_statement_001__long/5_IncomeStatement2_gt1_2.xlsx ADDED
Binary file (10.6 kB). View file
 
calc_income_statement_001__long/5_IncomeStatement2_gt1_3.xlsx ADDED
Binary file (10.6 kB). View file
 
calc_income_statement_001__long/5_IncomeStatement2_gt1_4.xlsx ADDED
Binary file (10.6 kB). View file
 
calc_income_statement_001__long/5_IncomeStatement2_gt1_5.xlsx ADDED
Binary file (10.6 kB). View file
 
calc_income_statement_001__long/876296d5-884d-51ad-b5dd-285374e43ac4_IncomeStatement2_5.xlsx ADDED
Binary file (9.94 kB). View file
 
calc_income_statement_001__long/93be5864-b16f-5f70-8d80-1a515dedf794_IncomeStatement2_3.xlsx ADDED
Binary file (9.94 kB). View file
 
calc_sales_rep_002__long/.PLACEHOLDER ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ This directory is intentionally empty.
2
+ It exists only to satisfy start_our_benchmark_test.sh's uniform
3
+ 'cache_dir/<tid>/ must exist' precheck. Non-mock tasks do not use
4
+ cua_gym cache; their evaluators read a vm_file tarball instead.
5
+ See docs/0716_迁移执行日志.md § S15 for details.
calc_sales_rep_002__long/0b920aed-a86f-552f-8c4e-4230d20fb019_SalesRep_3.xlsx ADDED
Binary file (9.5 kB). View file
 
calc_sales_rep_002__long/3_SalesRep_gt1_1.xlsx ADDED
Binary file (10.1 kB). View file
 
calc_sales_rep_002__long/3_SalesRep_gt1_2.xlsx ADDED
Binary file (10.1 kB). View file
 
calc_sales_rep_002__long/3_SalesRep_gt1_3.xlsx ADDED
Binary file (10.1 kB). View file
 
calc_sales_rep_002__long/3_SalesRep_gt1_4.xlsx ADDED
Binary file (10.1 kB). View file
 
calc_sales_rep_002__long/3_SalesRep_gt1_5.xlsx ADDED
Binary file (10.1 kB). View file
 
calc_sales_rep_002__long/5e509850-8212-5d6a-958f-c2d16aee6ceb_SalesRep_4.xlsx ADDED
Binary file (9.5 kB). View file
 
calc_sales_rep_002__long/6c32f05d-1532-5354-a3db-ac954dd7d2ca_SalesRep_1.xlsx ADDED
Binary file (9.5 kB). View file
 
calc_sales_rep_002__long/dd7e65b9-bfb4-542a-adf9-13c4153016fc_SalesRep_2.xlsx ADDED
Binary file (9.5 kB). View file
 
calc_sales_rep_002__long/e5d3b713-bd13-5796-83bc-ab47351ba44c_SalesRep_5.xlsx ADDED
Binary file (9.5 kB). View file
 
csm_training_rate_005/_cua_gym_vm_bridge.sh ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # CUA-Gym VM-side network fix (direct-IP mock access).
3
+ #
4
+ # Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by
5
+ # their real IDC address (http://28.7.184.198:81xx) instead of the old
6
+ # localhost:9000-9097 socat bridge, so the VM only needs two fixes:
7
+ #
8
+ # 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's
9
+ # cluster DNS, which is unreachable from QEMU SLIRP NAT
10
+ # ("Temporary failure in name resolution").
11
+ # 2. The mock host excluded from the woa http proxy — otherwise the VM's
12
+ # Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403
13
+ # from the proxy when hitting 28.7.184.198:81xx. (The old socat path never
14
+ # hit this because localhost is bypassed by default.)
15
+ #
16
+ # Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic
17
+ # OSWorld setup pipeline.
18
+ #
19
+ # Argv:
20
+ # $1 optional sudo password (default "password"; SetupController
21
+ # substitutes {CLIENT_PASSWORD} when uploaded as a cache file).
22
+ # $2 unused (kept for backward compat — was socat first port 9000).
23
+ # $3 unused (kept for backward compat — was socat last port 9097).
24
+ # $4 optional mock host IP (default 28.7.184.198).
25
+
26
+ set +e
27
+
28
+ PASS="${1:-password}"
29
+ MOCK_HOST="${4:-28.7.184.198}"
30
+ # Derive the /16 IDC subnet so future port/host tweaks on the same segment
31
+ # stay bypassed too (28.7.184.198 -> 28.7.0.0/16).
32
+ MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')"
33
+
34
+ run_root() {
35
+ echo "$PASS" | sudo -S -p "" bash -c "$1"
36
+ }
37
+
38
+ # Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2.
39
+ GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')"
40
+ GW="${GW:-10.0.2.2}"
41
+
42
+ # ─── CUA-Gym network fix (Taiji-specific) ─────────────────────────────
43
+ fix_vm_network() {
44
+ # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP
45
+ # DNS forwarder. Nothing hardcoded except the mock host above.
46
+ local GW_NET="${GW%.*}"
47
+ local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3
48
+ local OWN_CIDR
49
+ OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \
50
+ | awk '{print $4; exit}')"
51
+ local OWN_IP="${OWN_CIDR%/*}"
52
+ local OWN_NET=""
53
+ [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24"
54
+
55
+ # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps
56
+ # systemd-resolved/NetworkManager from clobbering it.
57
+ if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf
58
+ chattr +i /etc/resolv.conf 2>/dev/null || true"; then
59
+ echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})"
60
+ else
61
+ echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf"
62
+ fi
63
+
64
+ # 2) Build the proxy bypass list from detected values + the direct-IP
65
+ # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx
66
+ # reachable from inside the VM — without it the woa proxy 403s it.
67
+ local ignore_list="['localhost', '127.0.0.0/8', '${GW}'"
68
+ [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'"
69
+ [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'"
70
+ [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'"
71
+ [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'"
72
+ [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'"
73
+ ignore_list="${ignore_list}]"
74
+
75
+ # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these.
76
+ if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then
77
+ echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}"
78
+ else
79
+ echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)"
80
+ fi
81
+
82
+ # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl).
83
+ local NP="localhost,127.0.0.1,${GW}"
84
+ [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}"
85
+ [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}"
86
+ [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24"
87
+ [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}"
88
+ [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}"
89
+
90
+ for var in no_proxy NO_PROXY; do
91
+ if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then
92
+ echo "export ${var}=${NP}" >> /home/user/.bashrc
93
+ fi
94
+ done
95
+ run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \
96
+ && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \
97
+ || echo 'no_proxy=\"${NP}\"' >> /etc/environment
98
+ grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \
99
+ && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \
100
+ || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1
101
+ echo "[cua_gym_vm_bridge] no_proxy=${NP}"
102
+ }
103
+
104
+ fix_vm_network
105
+
106
+ echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed"
csm_training_rate_005/reward_label.json ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/f7631cb7-a5d8-58f1-89d7-3a5a8bc86a23/reward.py",
3
+ "api_url": "http://28.7.184.184:8000/v1/chat/completions",
4
+ "model": "Kimi-K2.6",
5
+ "max_code_chars": 100000,
6
+ "created_at": "2026-07-14 10:26:12",
7
+ "label": {
8
+ "task_id": "csm_training_rate_005",
9
+ "domain": "mock_websites",
10
+ "summary": "验证用户在 Google Sheets 中计算完成率为75%,在 Salesforce 中将 TechVentures 商机标记为 Closed Won,并在 Slack #general 频道发送新消息及报告75%完成率",
11
+ "is_placeholder": false,
12
+ "data_sources": [
13
+ "/tmp/task_web_sid",
14
+ "google_sheets_mock",
15
+ "salesforce_mock",
16
+ "slack_mock"
17
+ ],
18
+ "scoring_components": [
19
+ {
20
+ "name": "completion rate computed as 75%",
21
+ "weight": 0.4,
22
+ "description": "检查 Google Sheets 单元格 B8 的值或计算结果是否包含75",
23
+ "check_logic": "读取 google_sheets_mock 的 sheets[0].data.B8,检查 value 或 computed 字段的字符串表示中是否包含 '75'",
24
+ "pass_condition": "B8 单元格的 value 或 computed 包含 '75'"
25
+ },
26
+ {
27
+ "name": "TechVentures opp -> Closed Won",
28
+ "weight": 0.3,
29
+ "description": "检查 Salesforce 中 opportunityId 为 o1 的商机阶段是否为 Closed Won",
30
+ "check_logic": "在 salesforce_mock 的 opportunities 列表中查找 opportunityId == 'o1' 的对象,检查其 stage 字段是否等于 'Closed Won'",
31
+ "pass_condition": "opportunityId 为 'o1' 的商机 stage 为 'Closed Won'"
32
+ },
33
+ {
34
+ "name": "slack_new_msg",
35
+ "weight": 0.1,
36
+ "description": "检查 Slack #general 频道是否有 user_1 发送的新消息",
37
+ "check_logic": "读取 slack_mock 的 messages.general,排除 SEED 中已有的消息,筛选 senderId == 'user_1' 的消息,检查列表是否非空",
38
+ "pass_condition": "#general 中存在 messageId 不在 seed 中且 senderId 为 'user_1' 的新消息"
39
+ },
40
+ {
41
+ "name": "reports the 75% rate",
42
+ "weight": 0.2,
43
+ "description": "检查 Slack #general 频道 user_1 的新消息内容是否报告了75%的完成率",
44
+ "check_logic": "读取 slack_mock 的 messages.general 中 user_1 的新消息,拼接内容转小写,检查是否包含 '75%'、'75 percent' 或 '75'",
45
+ "pass_condition": "user_1 在 #general 发送的新消息内容(小写)包含 '75%'、'75 percent' 或 '75'"
46
+ }
47
+ ],
48
+ "total_max_score": 1.0,
49
+ "score_aggregation": "各组件分数相加,最终通过 min(total, 1.0) 钳制到上限 1.0 并四舍五入到4位小数",
50
+ "failure_modes": [
51
+ "读取 /tmp/task_web_sid 失败或 sid 为空时打印 CRITICAL 并返回 0.0",
52
+ "从任一 mock 服务(google_sheets_mock、salesforce_mock、slack_mock)拉取状态失败时打印 CRITICAL 并返回 0.0"
53
+ ],
54
+ "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 google_sheets_mock、salesforce_mock、slack_mock 发送请求获取当前状态。接着按顺序检查四个组件:1)Google Sheets 单元格 B8 是否包含75;2)Salesforce 中 o1 商机是否为 Closed Won;3)Slack #general 是否有 user_1 的新消息;4)该新消息是否提及75%完成率。每个组件通过则累加对应分数,不通过则仅打印 FAIL 不加分。最终总分经 min 钳制和 round 后输出。",
55
+ "confidence": 1.0
56
+ },
57
+ "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码:\n\n1. 文件路径和 docstring:\n - Task ID: f7631cb7-a5d8-58f1-89d7-3a5a8bc86a23(从 docstring 中提取)\n - Domain: mock_websites(从 docstring 中提取)\n - Mocks: google_sheets_mock, salesforce_mock, slack_mock\n\n2. 数据源:\n - 从 /tmp/task_web_sid 读取 sid\n - 从三个 mock 服务获取状态:google_sheets_mock, salesforce_mock, slack_mock\n - SEED 用于 slack 消息去重\n\n3. 评分组件:\n - c0: 0.4 分 - google_sheets_mock 中 sheets[0].data.B8 的 value 或 computed 包含 '75'\n - c1: 0.3 分 - salesforce_mock 中 opportunities 里 opportunityId 为 'o1' 的 stage 是 'Closed Won'\n - c2: 0.1 分 - slack_mock 中 #general 频道有 user_1 发送的新消息(不在 seed 中)\n - c3: 0.2 分 - slack_mock 中 #general 频道 user_1 发送的新消息内容包含 '75%' 或 '75 percent' 或 '75'\n\n4. 分数汇总:\n - total 累加各组件分数\n - final = round(min(total, 1.0), 4)\n - 是相加逻辑\n\n5. 失败模式:\n - 读取 sid 失败 -> 0.0 退出\n - 获取 mock 状态失败 -> 0.0 退出\n - 各组件检查失败只是不加分,不会提前退出\n\n6. 是否是占位脚本:\n - 不是,有具体的检查逻辑\n\n7. confidence:\n - 1.0,因为逻辑清晰\n\n现在构建 JSON:\n\ntask_id: \"f7631cb7-a5d8-58f1-89d7-3a5a8bc86a23\"\ndomain: \"mock_websites\"\nsummary: \"验证用户在 Google Sheets 中计算完成率为75%,在 Salesforce 中将 TechVentures 商机标记为 Closed Won,并在 Slack #general 频道发送包含75%完成率的新消息\"\nis_placeholder: false\ndata_sources: [\"/tmp/task_web_sid\", \"google_sheets_mock\", \"salesforce_mock\", \"slack_mock\"]\n\nscoring_components:\n1. name: \"completion rate computed as 75%\", weight: 0.4\n description: \"检查 Google Sheets 单元格 B8 的值或计算结果是否包含75\"\n check_logic: \"读取 google_sheets_mock 的 sheets[0].data.B8,检查 value 或 computed 字段的字符串表示中是否包含 '75'\"\n pass_condition: \"B8 单元格的 value 或 computed 包含 '75'\"\n\n2. name: \"TechVentures opp -> Closed Won\", weight: 0.3\n description: \"检查 Salesforce 中 opportunityId 为 o1 的商机阶段是否为 Closed Won\"\n check_logic: \"在 salesforce_mock 的 opportunities 列表中查找 opportunityId == 'o1' 的对象,检查其 stage 字段是否等于 'Closed Won'\"\n pass_condition: \"opportunityId 为 'o1' 的商机 stage 为 'Closed Won'\"\n\n3. name: \"slack_new_msg\", weight: 0.1\n description: \"检查 Slack #general 频道是否有 user_1 发送的新消息\"\n check_logic: \"读取 slack_mock 的 messages.general,排除 SEED 中已有的消息,筛选 senderId == 'user_1' 的消息,检查列表是否非空\"\n pass_condition: \"#general 中存在 messageId 不在 seed 中且 senderId 为 'user_1' 的新消息\"\n\n4. name: \"reports the 75% rate\", weight: 0.2\n description: \"检查 Slack #general 频道 user_1 的新消息内容是否报告了75%的完成率\"\n check_logic: \"读取 slack_mock 的 messages.general 中 user_1 的新消息,拼接内容转小写,检查是否包含 '75%'、'75 percent' 或 '75'\"\n pass_condition: \"user_1 在 #general 发送的新消息内容(小写)包含 '75%'、'75 percent' 或 '75'\"\n\ntotal_max_score: 1.0\nscore_aggregation: \"各组件分数相加,最终通过 min(total, 1.0) 钳制到上限 1.0 并四舍五入到4位小数\"\nfailure_modes: [\n \"读取 /tmp/task_web_sid 失败或 sid 为空时打印 CRITICAL 并返回 0.0\",\n \"从任一 mock 服务(google_sheets_mock、salesforce_mock、slack_mock)拉取状态失败时打印 CRITICAL 并返回 0.0\"\n]\n\nscoring_logic_explanation: \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 google_sheets_mock、salesforce_mock、slack_mock 发送请求获取当前状态。接着按顺序检查四个组件:1)Google Sheets 单元格 B8 是否包含75;2)Salesforce 中 o1 商机是否为 Closed Won;3)Slack #general 是否有 user_1 的新消息;4)该新消息是否提及75%完成率。每个组件通过则累加对应分数,不通过则仅打印 FAIL 不加分。最终总分经 min 钳制和 round 后输出。\"\n\nconfidence: 1.0\n\n确保 JSON 格式正确,没有 markdown 代码块,第一个字符是 {,最后一个字符是 }。 </think> {\"task_id\":\"f7631cb7-a5d8-58f1-89d7-3a5a8bc86a23\",\"domain\":\"mock_websites\",\"summary\":\"验证用户在 Google Sheets 中计算完成率为75%,在 Salesforce 中将 TechVentures 商机标记为 Closed Won,并在 Slack #general 频道发送新消息及报告75%完成率\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"google_sheets_mock\",\"salesforce_mock\",\"slack_mock\"],\"scoring_components\":[{\"name\":\"completion rate computed as 75%\",\"weight\":0.4,\"description\":\"检查 Google Sheets 单元格 B8 的值或计算结果是否包含75\",\"check_logic\":\"读取 google_sheets_mock 的 sheets[0].data.B8,检查 value 或 computed 字段的字符串表示中是否包含 '75'\",\"pass_condition\":\"B8 单元格的 value 或 computed 包含 '75'\"},{\"name\":\"TechVentures opp -> Closed Won\",\"weight\":0.3,\"description\":\"检查 Salesforce 中 opportunityId 为 o1 的商机阶段是否为 Closed Won\",\"check_logic\":\"在 salesforce_mock 的 opportunities 列表中查找 opportunityId == 'o1' 的对象,检查其 stage 字段是否等于 'Closed Won'\",\"pass_condition\":\"opportunityId 为 'o1' 的商机 stage 为 'Closed Won'\"},{\"name\":\"slack_new_msg\",\"weight\":0.1,\"description\":\"检查 Slack #general 频道是否有 user_1 发送的新消息\",\"check_logic\":\"读取 slack_mock 的 messages.general,排除 SEED 中已有的消息,筛选 senderId == 'user_1' 的消息,检查列表是否非空\",\"pass_condition\":\"#general 中存在 messageId 不在 seed 中且 senderId 为 'user_1' 的新消息\"},{\"name\":\"reports the 75% rate\",\"weight\":0.2,\"description\":\"检查 Slack #general 频道 user_1 的新消息内容是否报告了75%的完成率\",\"check_logic\":\"读取 slack_mock 的 messages.general 中 user_1 的新消息,拼接内容转小写,检查是否包含 '75%'、'75 percent' 或 '75'\",\"pass_condition\":\"user_1 在 #general 发送的新消息内容(小写)包含 '75%'、'75 percent' 或 '75'\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分��相加,最终通过 min(total, 1.0) 钳制到上限 1.0 并四舍五入到4位小数\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或 sid 为空时打印 CRITICAL 并返回 0.0\",\"从任一 mock 服务(google_sheets_mock、salesforce_mock、slack_mock)拉取状态失败时打印 CRITICAL 并返回 0.0\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 google_sheets_mock、salesforce_mock、slack_mock 发送请求获取当前状态。接着按顺序检查四个组件:1)Google Sheets 单元格 B8 是否包含75;2)Salesforce 中 o1 商机是否为 Closed Won;3)Slack #general 是否有 user_1 的新消息;4)该新消息是否提及75%完成率。每个组件通过则累加对应分数,不通过则仅打印 FAIL 不加分。最终总分经 min 钳制和 round 后输出。\",\"confidence\":1.0}"
58
+ }
hr_midyear_review_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"
hr_midyear_review_007__long/initial_setup.py ADDED
@@ -0,0 +1,794 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: W05 — HRBP performance review + conditional raise letters
3
+ Task ID: hr_midyear_review_007__long
4
+ Persona: HRBP Tara Singh
5
+ Mocks: workday_mock,docusign_mock,slack_mock,google_sheets_mock
6
+
7
+ Ground-truth embedding (read by reward.py from initial_state):
8
+ - Workday reviews[*]._expected_rating on every status=='Pending Manager Review'
9
+ review managed by Tara — the 1..5 score the manager-review must submit
10
+ (decided by the goal-attainment rule, encoded ONLY as this answer key).
11
+ - reviews[*]._expected_envelope (bool) — true iff _expected_rating >= 4
12
+ (Exceeds / Significantly Exceeds): those reports must get a DocuSign raise
13
+ letter. The conditional branch.
14
+ - reviews[*]._employee_name / _employee_email — the report's identity, so
15
+ reward can match the sent envelope's recipient loosely (name OR email).
16
+
17
+ Observable outputs kept ABSENT at injection:
18
+ - all 10 pending reviews still have status=='Pending Manager Review' with the
19
+ DEFAULT ratingScore (3) untouched — the agent must open each and submit a
20
+ rating + comment (ADD_REVIEW_COMMENT → status 'Completed').
21
+ - DocuSign has NO raise-letter envelope addressed to any qualifying employee
22
+ (only a reusable template + unrelated noise envelopes) — the agent must
23
+ create-from-template, set the employee as recipient, and Send.
24
+ - Google Sheet 'Performance Review Tracker' Rating column is blank on the 10
25
+ report rows (only a worked example row is filled).
26
+ - Slack #hr channel has zero messages.
27
+ """
28
+ import os
29
+ import shlex
30
+ import subprocess
31
+ import time
32
+ import uuid
33
+ import base64
34
+
35
+ import requests
36
+
37
+ sid = str(uuid.uuid4())
38
+ with open('/tmp/task_web_sid', 'w') as f:
39
+ f.write(sid)
40
+ print(f'Generated sid: {sid}')
41
+
42
+
43
+ # ---------------------------------------------------------------------------
44
+ # Builders
45
+ # ---------------------------------------------------------------------------
46
+ def employee(emp_id, name, title, dept='Engineering', dept_id='dept001',
47
+ manager_id='emp_tara', role='Employee'):
48
+ first = name.split()[0]
49
+ last = name.split()[-1]
50
+ uname = f'{first}.{last}'.lower()
51
+ return {
52
+ 'id': emp_id, 'name': name,
53
+ 'email': f'{uname}@acmecorp.com',
54
+ 'phone': '+1 (415) 555-0140', 'role': role, 'department': dept,
55
+ 'departmentId': dept_id,
56
+ 'avatar': f'https://ui-avatars.com/api/?name={first}+{last}&background=0875E1&color=fff&size=128',
57
+ 'managerId': manager_id, 'title': title, 'location': 'San Francisco, CA',
58
+ 'joinDate': '2021-05-10', 'employeeType': 'Full-Time',
59
+ 'birthday': '1990-01-01', 'workAnniversary': '2021-05-10',
60
+ }
61
+
62
+
63
+ def review(review_id, emp_id, period, status, self_comments,
64
+ manager_id='emp_tara', rating_score=None, rating='',
65
+ manager_comments='', completed_date=None,
66
+ expected_rating=None, expected_envelope=None,
67
+ employee_name=None, employee_email=None):
68
+ rec = {
69
+ 'reviewId': review_id, 'employeeId': emp_id, 'managerId': manager_id,
70
+ 'period': period, 'rating': rating, 'ratingScore': rating_score,
71
+ 'status': status, 'selfReviewComments': self_comments,
72
+ 'managerComments': manager_comments, 'comments': '',
73
+ 'completedDate': completed_date,
74
+ }
75
+ if expected_rating is not None:
76
+ rec['_expected_rating'] = expected_rating # hidden answer key
77
+ if expected_envelope is not None:
78
+ rec['_expected_envelope'] = expected_envelope
79
+ if employee_name is not None:
80
+ rec['_employee_name'] = employee_name
81
+ if employee_email is not None:
82
+ rec['_employee_email'] = employee_email
83
+ return rec
84
+
85
+
86
+ def cell(v):
87
+ return {'value': str(v), 'formula': str(v), 'computed': str(v)}
88
+
89
+
90
+ def hcell(v):
91
+ return {'value': str(v), 'formula': str(v), 'computed': str(v),
92
+ 'style': {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}}
93
+
94
+
95
+ # ---------------------------------------------------------------------------
96
+ # Rating rule (documented in instruction; encoded here ONLY as the embedded
97
+ # _expected_rating answer key, NOT re-derived in reward):
98
+ # Score each report's mid-year review on the 1..5 scale by goal attainment:
99
+ # 5 = significantly exceeded (beat every goal)
100
+ # 4 = exceeded (beat most goals)
101
+ # 3 = met expectations (delivered the agreed goals)
102
+ # 2 = partially met (missed some goals)
103
+ # 1 = did not meet (missed most goals)
104
+ # Conditional branch: send a DocuSign salary-increase letter ONLY to reports
105
+ # rated 4 or 5.
106
+ # ---------------------------------------------------------------------------
107
+ PERIOD = '2026 Mid-Year Review'
108
+
109
+ TARA = {
110
+ 'id': 'emp_tara', 'name': 'Tara Singh', 'email': 'tara.singh@acmecorp.com',
111
+ 'phone': '+1 (415) 555-0100', 'role': 'Manager', 'department': 'Engineering',
112
+ 'departmentId': 'dept001',
113
+ 'avatar': 'https://ui-avatars.com/api/?name=Tara+Singh&background=7C3AED&color=fff&size=128',
114
+ 'managerId': 'emp_dir', 'title': 'HR Business Partner',
115
+ 'location': 'San Francisco, CA', 'joinDate': '2019-02-01',
116
+ 'employeeType': 'Full-Time', 'skills': ['Coaching', 'Comp Planning'],
117
+ 'birthday': '1986-07-19', 'workAnniversary': '2019-02-01',
118
+ }
119
+ DIRECTOR = {
120
+ 'id': 'emp_dir', 'name': 'Olivia Reyes', 'email': 'olivia.reyes@acmecorp.com',
121
+ 'phone': '+1 (415) 555-0101', 'role': 'Director', 'department': 'Engineering',
122
+ 'departmentId': 'dept001',
123
+ 'avatar': 'https://ui-avatars.com/api/?name=Olivia+Reyes&background=DB2777&color=fff&size=128',
124
+ 'managerId': None, 'title': 'Director of Engineering',
125
+ 'location': 'San Francisco, CA', 'joinDate': '2017-03-01',
126
+ 'employeeType': 'Full-Time', 'birthday': '1982-02-02',
127
+ 'workAnniversary': '2017-03-01',
128
+ }
129
+
130
+ # (emp_id, name, title, expected_rating, self_assessment)
131
+ REPORTS = [
132
+ ('emp_r1', 'Daniel Okafor', 'Senior Backend Engineer', 5,
133
+ 'Beat every one of my four quarterly goals: shipped the billing rewrite a '
134
+ 'full sprint early, cut p99 latency 40%, and mentored three new hires who '
135
+ 'are all ramped. Took on the on-call redesign on top of my roadmap.'),
136
+ ('emp_r2', 'Priya Nair', 'Product Designer', 3,
137
+ 'Delivered all of my agreed goals for the half: the design-system refresh '
138
+ 'and two feature flows shipped on schedule. A solid, on-plan half with no '
139
+ 'surprises.'),
140
+ ('emp_r3', 'Marcus Bell', 'Data Engineer', 4,
141
+ 'Exceeded most of my goals — the warehouse migration landed two weeks '
142
+ 'early and I added the data-quality alerts that were not in scope. One '
143
+ 'stretch goal (self-serve dashboards) slipped to next half.'),
144
+ ('emp_r4', 'Hana Kim', 'Frontend Engineer', 2,
145
+ 'Partially met my goals. The accessibility audit shipped, but I missed the '
146
+ 'component-library deadline and the perf-budget goal carried over. A rough '
147
+ 'half with the reorg churn.'),
148
+ ('emp_r5', 'Tom Becker', 'Staff SRE', 5,
149
+ 'Significantly exceeded: led the multi-region failover project to a clean '
150
+ 'finish ahead of plan, drove incident MTTR down by half, and beat all '
151
+ 'reliability targets. Also ran the company-wide game-day.'),
152
+ ('emp_r6', 'Grace Liu', 'QA Engineer', 3,
153
+ 'Met expectations across the board — cleared the regression backlog and '
154
+ 'stood up the nightly e2e suite exactly as committed. On plan.'),
155
+ ('emp_r7', 'Samir Patel', 'Backend Engineer', 4,
156
+ 'Exceeded most goals: the payments API v2 shipped on time and I picked up '
157
+ 'the fraud-rules service when a teammate left. Documentation goal was only '
158
+ 'half done.'),
159
+ ('emp_r8', 'Elena Vasquez', 'Junior Engineer', 1,
160
+ 'Did not meet most of my goals this half. Onboarding took longer than '
161
+ 'expected and two of my three committed features slipped; the third is '
162
+ 'still in review. I need a stronger plan for next half.'),
163
+ ('emp_r9', 'Noah Schmidt', 'DevOps Engineer', 3,
164
+ 'Met my goals — migrated CI to the new runners and kept the platform '
165
+ 'green. Delivered what was agreed, nothing beyond.'),
166
+ ('emp_r10', 'Aisha Mohammed', 'Senior Frontend Engineer', 4,
167
+ 'Exceeded most goals: led the design-system adoption across four squads '
168
+ 'ahead of schedule and cut bundle size 30%. The i18n stretch goal slipped '
169
+ 'a few weeks.'),
170
+ ]
171
+
172
+ EMPLOYEES = [TARA, DIRECTOR]
173
+ REVIEWS = []
174
+ for emp_id, name, title, exp_rating, self_text in REPORTS:
175
+ emp = employee(emp_id, name, title)
176
+ EMPLOYEES.append(emp)
177
+ REVIEWS.append(review(
178
+ f'rev_{emp_id}', emp_id, PERIOD, 'Pending Manager Review', self_text,
179
+ manager_id='emp_tara', rating_score=3, # default, agent must set
180
+ expected_rating=exp_rating,
181
+ expected_envelope=(exp_rating >= 4),
182
+ employee_name=name, employee_email=emp['email'],
183
+ ))
184
+
185
+ # ---- NOISE employees + reviews (no answer key, not scored) ----
186
+ # n1: report of a DIFFERENT manager, still Pending Manager Review -> does NOT
187
+ # appear in Tara's "Reviews to give" list (managerId != Tara). Do not touch.
188
+ NOISE_EMP_1 = employee('emp_n1', 'Victor Ross', 'Marketing Analyst',
189
+ dept='Marketing', dept_id='dept003',
190
+ manager_id='emp_dir')
191
+ # n2: Tara's report but review ALREADY Completed -> no Complete-Review button.
192
+ NOISE_EMP_2 = employee('emp_n2', 'Fatima Zahra', 'Engineering Manager')
193
+ # n3: Tara's report but still Pending Self-Review -> not yet in her list.
194
+ NOISE_EMP_3 = employee('emp_n3', 'Liam Carter', 'Backend Engineer')
195
+ EMPLOYEES += [NOISE_EMP_1, NOISE_EMP_2, NOISE_EMP_3]
196
+
197
+ REVIEWS += [
198
+ review('rev_n1', 'emp_n1', PERIOD, 'Pending Manager Review',
199
+ 'Crushed the campaign analytics goals this half.',
200
+ manager_id='emp_dir'), # NOT Tara's report
201
+ review('rev_n2', 'emp_n2', PERIOD, 'Completed',
202
+ 'Led the platform team through the reorg and hit all goals.',
203
+ manager_id='emp_tara', rating_score=5, rating='Significantly Exceeds',
204
+ manager_comments='Outstanding leadership.',
205
+ completed_date='2026-06-20'), # already done
206
+ review('rev_n3', 'emp_n3', PERIOD, 'Pending Self-Review',
207
+ '', manager_id='emp_tara'), # self-review not submitted yet
208
+ ]
209
+
210
+ # Tara's own review (as an employee) — Completed, decoy in "My reviews" list.
211
+ REVIEWS.append(review('rev_tara', 'emp_tara', '2025 Annual Review', 'Completed',
212
+ 'Strong year partnering with engineering.',
213
+ manager_id='emp_dir', rating_score=4,
214
+ rating='Exceeds Expectations',
215
+ manager_comments='Great partner.',
216
+ completed_date='2026-01-15'))
217
+
218
+ QUALIFYING = [r for r in REVIEWS if r.get('_expected_envelope')]
219
+ QUALIFYING_NAMES = [r['_employee_name'] for r in QUALIFYING]
220
+ print(f'Reports pending: {len(REPORTS)}; qualifying for raise letter: '
221
+ f'{len(QUALIFYING)} -> {QUALIFYING_NAMES}')
222
+
223
+ WORKDAY_STATE = {
224
+ 'currentUser': TARA,
225
+ 'employees': EMPLOYEES,
226
+ 'departments': [
227
+ {'id': 'dept001', 'name': 'Engineering', 'headcount': 12, 'managerId': 'emp_dir'},
228
+ {'id': 'dept003', 'name': 'Marketing', 'headcount': 4, 'managerId': 'emp_dir'},
229
+ ],
230
+ 'timeEntries': [],
231
+ 'timeOffRequests': [],
232
+ 'timeOffBalance': {'vacation': 120, 'sick': 40, 'personal': 16},
233
+ 'payroll': [],
234
+ 'benefits': {'employeeId': 'emp_tara', 'enrollmentStatus': 'Complete',
235
+ 'plans': [], 'dependents': []},
236
+ 'reviews': REVIEWS,
237
+ 'goals': [],
238
+ 'tasks': [
239
+ {'taskId': 't1', 'employeeId': 'emp_tara', 'type': 'Review',
240
+ 'subType': 'Performance Review',
241
+ 'description': 'Complete mid-year manager reviews for your reports',
242
+ 'status': 'Pending', 'dueDate': '2026-07-05', 'createdDate': '2026-06-25',
243
+ 'relatedId': None, 'initiator': 'HR System',
244
+ 'businessProcess': 'Mid-Year Performance Review', 'priority': 'High',
245
+ 'comments': []},
246
+ ],
247
+ 'announcements': [
248
+ {'id': 'a1', 'title': 'Mid-Year Reviews Due July 5',
249
+ 'date': '2026-06-25', 'content': 'Managers: submit ratings for all reports.',
250
+ 'category': 'HR', 'priority': 'High'},
251
+ ],
252
+ 'notifications': [
253
+ {'id': 'n1', 'type': 'task', 'title': 'Reviews to give',
254
+ 'message': 'You have pending manager reviews.',
255
+ 'timestamp': '2026-06-25T12:00:00.000Z', 'read': False, 'link': '/performance'},
256
+ ],
257
+ 'clockStatus': {'isClockedIn': False, 'startTime': None},
258
+ }
259
+
260
+ # ---------------------------------------------------------------------------
261
+ # DocuSign — Tara is the sender. A reusable raise-letter TEMPLATE is provided
262
+ # (document + one signer role) so the agent can Use-a-Template -> set the
263
+ # employee as recipient -> Send through the 3-step /prepare flow. NO sent
264
+ # raise letter to any qualifying employee exists yet (only unrelated noise).
265
+ # ---------------------------------------------------------------------------
266
+ def _letter_data_url():
267
+ """A self-contained SVG that renders as a real salary-increase letter
268
+ (white page, Acme letterhead, body copy, signature line). Used as the
269
+ template document's fileUrl so the /prepare canvas shows an actual letter
270
+ instead of a random stock photo. No network dependency."""
271
+ svg = (
272
+ "<svg xmlns='http://www.w3.org/2000/svg' width='800' height='1100' "
273
+ "viewBox='0 0 800 1100'>"
274
+ "<rect width='800' height='1100' fill='#ffffff'/>"
275
+ "<rect x='0' y='0' width='800' height='90' fill='#0875E1'/>"
276
+ "<text x='48' y='58' font-family='Georgia, serif' font-size='30' "
277
+ "fill='#ffffff' font-weight='bold'>Acme Corporation</text>"
278
+ "<text x='48' y='150' font-family='Georgia, serif' font-size='24' "
279
+ "fill='#111827' font-weight='bold'>Salary Increase Confirmation Letter</text>"
280
+ "<text x='48' y='210' font-family='Arial, sans-serif' font-size='16' "
281
+ "fill='#374151'>Dear Employee,</text>"
282
+ "<text x='48' y='260' font-family='Arial, sans-serif' font-size='15' "
283
+ "fill='#374151'>We are pleased to confirm a merit-based increase to your "
284
+ "annual base salary,</text>"
285
+ "<text x='48' y='288' font-family='Arial, sans-serif' font-size='15' "
286
+ "fill='#374151'>in recognition of your strong performance this review "
287
+ "cycle. The adjustment</text>"
288
+ "<text x='48' y='316' font-family='Arial, sans-serif' font-size='15' "
289
+ "fill='#374151'>takes effect at the start of the next pay period.</text>"
290
+ "<text x='48' y='372' font-family='Arial, sans-serif' font-size='15' "
291
+ "fill='#374151'>Please review and sign below to acknowledge receipt of "
292
+ "this confirmation.</text>"
293
+ "<text x='48' y='430' font-family='Arial, sans-serif' font-size='15' "
294
+ "fill='#374151'>Sincerely,</text>"
295
+ "<text x='48' y='462' font-family='Arial, sans-serif' font-size='15' "
296
+ "fill='#374151'>Tara Singh — HR Business Partner</text>"
297
+ "<line x1='48' y1='900' x2='320' y2='900' stroke='#9ca3af' "
298
+ "stroke-width='2'/>"
299
+ "<text x='48' y='928' font-family='Arial, sans-serif' font-size='13' "
300
+ "fill='#6b7280'>Employee Signature</text>"
301
+ "<line x1='430' y1='900' x2='702' y2='900' stroke='#9ca3af' "
302
+ "stroke-width='2'/>"
303
+ "<text x='430' y='928' font-family='Arial, sans-serif' font-size='13' "
304
+ "fill='#6b7280'>Date Signed</text>"
305
+ "</svg>"
306
+ )
307
+ b64 = base64.b64encode(svg.encode('utf-8')).decode('ascii')
308
+ return f'data:image/svg+xml;base64,{b64}'
309
+
310
+
311
+ DS_USER = {
312
+ 'id': 'user_1', 'name': 'Tara Singh', 'email': 'tara.singh@acmecorp.com',
313
+ 'title': 'HR Business Partner', 'company': 'Acme Corporation',
314
+ 'avatar': '', 'signatureDataUrl': '', 'initialsDataUrl': '',
315
+ 'memberSince': '2019-02-01',
316
+ 'settings': {'defaultReminderDays': 3, 'defaultExpirationDays': 120,
317
+ 'timezone': 'America/Los_Angeles'},
318
+ }
319
+
320
+ RAISE_TEMPLATE = {
321
+ 'id': 'tmpl_raise', 'name': 'Salary Increase Confirmation Letter',
322
+ 'description': 'Standard merit-increase confirmation for a single employee to sign.',
323
+ 'createdAt': '2026-01-05T09:00:00Z', 'lastUsedAt': '2026-05-01T09:00:00Z',
324
+ 'usageCount': 6, 'ownerId': 'user_1', 'shared': True,
325
+ 'documents': [{'id': 'tdoc_1', 'name': 'Salary Increase Letter.pdf',
326
+ 'pageCount': 1, 'order': 1,
327
+ 'fileUrl': _letter_data_url(),
328
+ 'fileType': 'pdf'}],
329
+ 'roles': [{'id': 'role_1', 'name': 'Employee', 'role': 'signer', 'routingOrder': 1}],
330
+ 'fields': [{'id': 'tf_1', 'type': 'signature', 'roleId': 'role_1',
331
+ 'documentId': 'tdoc_1', 'pageNumber': 1, 'x': 80, 'y': 820,
332
+ 'width': 200, 'height': 50, 'value': '', 'required': True,
333
+ 'label': '', 'readOnly': False, 'fontSize': 14, 'fontColor': '#000000'}],
334
+ }
335
+
336
+
337
+ def noise_template(tid, name, desc, doc_name, last_used, usage):
338
+ """A decoy template (not scored). Its ONLY purpose is to give the Templates
339
+ table >= 2 rows: the raise-letter template must NOT be the last/only row,
340
+ or its row-action ('...') dropdown — which opens downward with `top-full` —
341
+ gets clipped by the table wrapper's `overflow-hidden` and the 'Use' item is
342
+ invisible (confirmed in Templates.jsx). With the raise template as row 1 and
343
+ decoys below it, its Use/Edit/Delete menu renders inside the container."""
344
+ return {
345
+ 'id': tid, 'name': name, 'description': desc,
346
+ 'createdAt': '2026-01-05T09:00:00Z', 'lastUsedAt': last_used,
347
+ 'usageCount': usage, 'ownerId': 'user_1', 'shared': False,
348
+ 'documents': [{'id': f'{tid}_doc', 'name': doc_name, 'pageCount': 1,
349
+ 'order': 1, 'fileUrl': _letter_data_url(), 'fileType': 'pdf'}],
350
+ 'roles': [{'id': f'{tid}_role', 'name': 'Signer', 'role': 'signer',
351
+ 'routingOrder': 1}],
352
+ 'fields': [{'id': f'{tid}_f1', 'type': 'signature', 'roleId': f'{tid}_role',
353
+ 'documentId': f'{tid}_doc', 'pageNumber': 1, 'x': 80, 'y': 820,
354
+ 'width': 200, 'height': 50, 'value': '', 'required': True,
355
+ 'label': '', 'readOnly': False, 'fontSize': 14,
356
+ 'fontColor': '#000000'}],
357
+ }
358
+
359
+
360
+ # Decoy templates (not scored) — kept AFTER the raise template so it stays row 1.
361
+ NOISE_TEMPLATE_1 = noise_template(
362
+ 'tmpl_offer', 'Offer Letter',
363
+ 'Standard full-time offer letter for a new hire.',
364
+ 'Offer Letter.pdf', '2026-04-12T09:00:00Z', 11)
365
+ NOISE_TEMPLATE_2 = noise_template(
366
+ 'tmpl_remote', 'Remote Work Agreement',
367
+ 'Acknowledgement for employees working remotely.',
368
+ 'Remote Work Agreement.pdf', '2026-02-28T09:00:00Z', 3)
369
+
370
+
371
+ def ds_envelope(eid, subject, status, recipients, created='2026-06-10T09:00:00Z',
372
+ sent_at=None):
373
+ return {
374
+ 'id': eid, 'subject': subject, 'message': '', 'status': status,
375
+ 'createdAt': created, 'sentAt': sent_at, 'completedAt': None,
376
+ 'voidedAt': None, 'declinedAt': None,
377
+ 'lastActivityAt': sent_at or created,
378
+ 'expiresAt': None, 'senderId': 'user_1', 'folderId': None,
379
+ 'templateId': None, 'reminderEnabled': False, 'reminderDays': 3,
380
+ 'reminderFrequency': 2,
381
+ 'documents': [{'id': f'{eid}_doc', 'name': 'Document.pdf', 'pageCount': 1,
382
+ 'order': 1, 'fileUrl': 'https://picsum.photos/seed/' + eid + '/800/1100',
383
+ 'fileType': 'pdf'}],
384
+ 'recipients': recipients,
385
+ 'fields': [],
386
+ 'history': [{'id': f'{eid}_h1', 'timestamp': created, 'action': 'created',
387
+ 'actorName': 'Tara Singh', 'actorEmail': 'tara.singh@acmecorp.com',
388
+ 'details': 'Envelope created'}],
389
+ }
390
+
391
+
392
+ def ds_recipient(rid, name, email, status='sent', role='signer'):
393
+ return {'id': rid, 'name': name, 'email': email, 'role': role,
394
+ 'routingOrder': 1, 'status': status, 'signedAt': None,
395
+ 'viewedAt': None, 'deliveredAt': None, 'declinedAt': None,
396
+ 'declineReason': None}
397
+
398
+
399
+ # Noise envelopes — unrelated, already sent/completed; NONE address a
400
+ # qualifying report's email, so they never satisfy the raise-letter anchor.
401
+ DOCUSIGN_STATE = {
402
+ 'user': DS_USER,
403
+ 'envelopes': [
404
+ ds_envelope('env_n1', 'Q1 Vendor NDA - Acme x Northwind', 'completed',
405
+ [ds_recipient('env_n1_r1', 'Brent Cooper', 'brent@northwind.example')],
406
+ created='2026-03-01T09:00:00Z', sent_at='2026-03-01T10:00:00Z'),
407
+ ds_envelope('env_n2', 'Office Lease Amendment 2026', 'sent',
408
+ [ds_recipient('env_n2_r1', 'Karen Diaz', 'karen.diaz@landlord.example')],
409
+ created='2026-05-20T09:00:00Z', sent_at='2026-05-20T11:00:00Z'),
410
+ ds_envelope('env_n3', 'Contractor Agreement - J. Wu', 'draft',
411
+ [ds_recipient('env_n3_r1', 'Jason Wu', 'jason.wu@contractor.example',
412
+ status='created')]),
413
+ ],
414
+ 'templates': [RAISE_TEMPLATE, NOISE_TEMPLATE_1, NOISE_TEMPLATE_2],
415
+ 'folders': [{'id': 'fold_1', 'name': 'HR Documents', 'parentFolder': None,
416
+ 'createdAt': '2026-01-01T09:00:00Z'}],
417
+ 'contacts': [
418
+ {'id': 'c1', 'name': 'Brent Cooper', 'email': 'brent@northwind.example',
419
+ 'company': 'Northwind', 'title': 'Counsel'},
420
+ ],
421
+ 'auditLog': [],
422
+ }
423
+
424
+ # ---------------------------------------------------------------------------
425
+ # Slack — #hr channel starts empty; decoy chatter elsewhere.
426
+ # ---------------------------------------------------------------------------
427
+ SLACK_STATE = {
428
+ 'channels': [
429
+ {'channelId': 'general', 'name': 'general', 'description': 'Company-wide chatter', 'topic': 'Welcome!', 'isPrivate': False, 'isStarred': True, 'members': ['user_1', 'user_2', 'user_3'], 'createdBy': 'user_2', 'createdAt': '2026-05-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0},
430
+ {'channelId': 'people-ops', 'name': 'people-ops', 'description': 'HR ops coordination', 'topic': 'Cycle logistics', 'isPrivate': False, 'isStarred': False, 'members': ['user_1', 'user_2'], 'createdBy': 'user_1', 'createdAt': '2026-05-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0},
431
+ {'channelId': 'hr', 'name': 'hr', 'description': 'HR announcements and review-cycle summaries', 'topic': 'Post a summary after each review batch', 'isPrivate': False, 'isStarred': False, 'members': ['user_1', 'user_2', 'user_3'], 'createdBy': 'user_1', 'createdAt': '2026-06-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0},
432
+ ],
433
+ 'currentUser': {'userId': 'user_1', 'fullName': 'Tara Singh', 'displayName': 'Tara', 'email': 'tara.singh@acmecorp.com', 'avatar': 'https://picsum.photos/200/200?random=1', 'title': 'HR Business Partner', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Los_Angeles'},
434
+ 'users': [
435
+ {'userId': 'user_1', 'fullName': 'Tara Singh', 'displayName': 'Tara', 'email': 'tara.singh@acmecorp.com', 'avatar': 'https://picsum.photos/200/200?random=1', 'title': 'HR Business Partner', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Los_Angeles'},
436
+ {'userId': 'user_2', 'fullName': 'Olivia Reyes', 'displayName': 'Olivia', 'email': 'olivia.reyes@acmecorp.com', 'avatar': 'https://picsum.photos/200/200?random=2', 'title': 'Director of Engineering', 'status': 'online', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/Los_Angeles'},
437
+ {'userId': 'user_3', 'fullName': 'Raj Mehta', 'displayName': 'Raj', 'email': 'raj.mehta@acmecorp.com', 'avatar': 'https://picsum.photos/200/200?random=3', 'title': 'Compensation Lead', 'status': 'away', 'statusMessage': '', 'statusEmoji': '', 'timeZone': 'America/New_York'},
438
+ ],
439
+ 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Acme Corp', 'icon': ''},
440
+ 'messages': {
441
+ 'general': [
442
+ {'messageId': 'm_g_1', 'senderId': 'user_2', 'content': 'Reminder: mid-year ratings are due July 5.', 'timestamp': '2026-06-26T13:02:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []},
443
+ ],
444
+ 'people-ops': [
445
+ {'messageId': 'm_p_1', 'senderId': 'user_3', 'content': 'Merit budget is locked; raise letters can go out as reviews close.', 'timestamp': '2026-06-26T15:00:00Z', 'reactions': [], 'isEdited': False, 'threadId': None, 'attachments': []},
446
+ ],
447
+ 'hr': [],
448
+ },
449
+ 'threads': {},
450
+ 'dms': [],
451
+ 'bookmarkedMessages': [],
452
+ 'callHistory': [],
453
+ 'settings': {'theme': 'light', 'notifications': 'all', 'displayDensity': 'comfortable', 'showAvatars': True, 'use24Hour': False},
454
+ 'invitations': [],
455
+ 'notifications': [],
456
+ }
457
+
458
+ # ---------------------------------------------------------------------------
459
+ # Google Sheets — 'Performance Review Tracker' ledger.
460
+ # Row 1: header (Employee | Rating | Raise Letter Sent)
461
+ # Row 2: a worked EXAMPLE (not scored).
462
+ # Rows 3..12: the 10 report names in col A; Rating (col B) + Raise Letter Sent
463
+ # (col C) BLANK — the agent fills them.
464
+ # ---------------------------------------------------------------------------
465
+ _sheet_data = {
466
+ 'A1': hcell('Employee'),
467
+ 'B1': hcell('Rating'),
468
+ 'C1': hcell('Raise Letter Sent'),
469
+ 'A2': cell('Sample Employee'),
470
+ 'B2': cell('3'),
471
+ 'C2': cell('No'),
472
+ }
473
+ for _i, (_emp_id, _name, _title, _exp, _self) in enumerate(REPORTS):
474
+ _r = _i + 3
475
+ _sheet_data[f'A{_r}'] = cell(_name)
476
+ _sheet_data[f'B{_r}'] = cell('') # blank — agent fills rating
477
+ _sheet_data[f'C{_r}'] = cell('') # blank — agent fills Yes/No
478
+
479
+ SHEETS_STATE = {
480
+ 'id': 'workbook_perf_review', 'title': 'Performance Review Tracker',
481
+ 'activeSheetId': 'sheet_1', 'selectedCell': 'A1', 'selectionRange': None,
482
+ 'clipboard': None, 'isDragging': False, 'undoStack': [], 'redoStack': [],
483
+ 'namedRanges': [], 'conditionalFormats': [], 'charts': [],
484
+ 'showGridlines': True, 'showFormulas': False, 'zoom': 100,
485
+ 'sheets': [{
486
+ 'id': 'sheet_1', 'name': 'Performance Review Tracker', 'data': _sheet_data,
487
+ 'rowCount': 100, 'colCount': 26, 'frozenRows': 1, 'frozenCols': 0,
488
+ 'tabColor': None, 'isHidden': False, 'columnWidths': {}, 'rowHeights': {},
489
+ 'filterRange': None, 'filterCriteria': {}, 'sortColumn': None,
490
+ 'sortDirection': None,
491
+ }],
492
+ }
493
+
494
+
495
+ APP_STATES = [
496
+ ('http://28.7.184.198:8192', WORKDAY_STATE), # workday_mock (L2 anchor 1)
497
+ ('http://28.7.184.198:8130', DOCUSIGN_STATE), # docusign_mock (L2 anchor 2)
498
+ ('http://28.7.184.198:8178', SLACK_STATE), # slack_mock
499
+ ('http://28.7.184.198:8145', SHEETS_STATE), # google_sheets_mock
500
+ ]
501
+
502
+ for placeholder, state in APP_STATES:
503
+ resp = requests.post(
504
+ f'{placeholder}/post?sid={sid}',
505
+ json={'action': 'set', 'state': state},
506
+ timeout=30,
507
+ )
508
+ assert resp.status_code == 200, (
509
+ f'State injection failed for {placeholder}: {resp.text}'
510
+ )
511
+ print(f'State injected: {placeholder} sid={sid}')
512
+
513
+ for placeholder, _ in APP_STATES:
514
+ go = requests.get(f'{placeholder}/go?sid={sid}', timeout=15).json()
515
+ assert go.get('initial_state') is not None, (
516
+ f'initial_state is None after injection for {placeholder}'
517
+ )
518
+ print(f'Verified initial_state set: {placeholder}')
519
+
520
+
521
+ def wait_mocks_ready(urls, sid, timeout=60, render_buffer=8):
522
+ """Pure-HTTP readiness: wait for every mock to serve its injected state.
523
+ No CDP / 9222 probing (that hangs on local review boxes)."""
524
+ import urllib.request as _urlreq
525
+ _opener = _urlreq.build_opener(_urlreq.ProxyHandler({}))
526
+ deadline = time.time() + timeout
527
+ todo = list(urls)
528
+ while todo and time.time() < deadline:
529
+ rest = []
530
+ for _u in todo:
531
+ try:
532
+ _r = _opener.open(f"{_u}/go?sid={sid}", timeout=5)
533
+ if _r.status == 200:
534
+ print(f" {_u}: ready")
535
+ continue
536
+ except Exception:
537
+ pass
538
+ rest.append(_u)
539
+ todo = rest
540
+ if todo:
541
+ time.sleep(2)
542
+ print(f" mocks ready: {len(urls) - len(todo)}/{len(urls)}"
543
+ + (f" (pending: {todo})" if todo else ""))
544
+ time.sleep(render_buffer)
545
+
546
+
547
+ # PATCHED_BY: patch_wait_mocks_loaded.py
548
+ def launch_gui(command, delay_sec=1.0):
549
+ """Launch a GUI command, fully detached from this script.
550
+
551
+ Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that
552
+ wait_mocks_loaded's CDP phase can verify browser render below.
553
+ Idempotent: if the caller already specified a debug port, keep it.
554
+ """
555
+ env = os.environ.copy()
556
+ env['DISPLAY'] = ':0'
557
+ if isinstance(command, str):
558
+ _parts = shlex.split(command)
559
+ else:
560
+ _parts = list(command)
561
+ if (_parts and 'google-chrome' in _parts[0]
562
+ and not any(p.startswith('--remote-debugging-port') for p in _parts)):
563
+ _parts[1:1] = [
564
+ '--no-first-run',
565
+ '--no-default-browser-check',
566
+ '--remote-debugging-port=1337',
567
+ ]
568
+ subprocess.Popen(
569
+ _parts,
570
+ stdin=subprocess.DEVNULL,
571
+ stdout=subprocess.DEVNULL,
572
+ stderr=subprocess.DEVNULL,
573
+ env=env,
574
+ start_new_session=True,
575
+ )
576
+ time.sleep(delay_sec)
577
+
578
+
579
+ def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12):
580
+ """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style.
581
+
582
+ Phase 1 - Backend readiness:
583
+ Poll each mock's /state?sid=<sid> (preferred) or /go?sid=<sid>
584
+ (fallback) until it returns 200 with 'stored_state' or
585
+ 'initial_state' respectively, or until timeout.
586
+
587
+ Phase 2 - Browser render verification (via CDP + Playwright):
588
+ Connect to http://localhost:1337 (the --remote-debugging-port
589
+ injected by launch_gui above), wait for every open tab to reach
590
+ 'networkidle' AND to contain at least 20 DOM elements. This
591
+ guarantees the SPA fetched /go?sid= data AND actually painted,
592
+ not just that the mock backend is up.
593
+
594
+ Fallback:
595
+ If Playwright is missing or CDP cannot be reached, sleep for
596
+ `render_buffer` seconds as a best-effort delay so the screenshot
597
+ loop does not start on a still-blank tab.
598
+ """
599
+ import urllib.request as _urlreq
600
+ import time as _t
601
+ _urls = [p for p, _ in app_states]
602
+ _opener = _urlreq.build_opener(_urlreq.ProxyHandler({}))
603
+
604
+ # ---- Phase 1: backend readiness ----
605
+ _deadline = _t.time() + timeout
606
+ _todo = list(_urls)
607
+ while _todo and _t.time() < _deadline:
608
+ _rest = []
609
+ for _u in _todo:
610
+ _ok = False
611
+ for _path, _need in (('/state?sid=', b'stored_state'),
612
+ ('/go?sid=', b'initial_state')):
613
+ try:
614
+ _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5)
615
+ if _r.status == 200:
616
+ _body = _r.read()
617
+ if _need in _body:
618
+ _ok = True
619
+ break
620
+ except Exception:
621
+ pass
622
+ if _ok:
623
+ print(f" {_u}: backend ready")
624
+ continue
625
+ _rest.append(_u)
626
+ _todo = _rest
627
+ if _todo:
628
+ _t.sleep(2)
629
+ _done = len(_urls) - len(_todo)
630
+ _pend = f" (pending: {_todo})" if _todo else ""
631
+ print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}")
632
+
633
+ # ---- Phase 2: browser render verification via CDP ----
634
+ _cdp_ok = False
635
+ try:
636
+ from playwright.sync_api import sync_playwright
637
+ _cdp_dl = _t.time() + max(15.0, _deadline - _t.time())
638
+ with sync_playwright() as _p:
639
+ _br = None
640
+ while _t.time() < _cdp_dl:
641
+ try:
642
+ _br = _p.chromium.connect_over_cdp('http://localhost:1337')
643
+ break
644
+ except Exception:
645
+ _t.sleep(0.5)
646
+ if _br is None:
647
+ print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?")
648
+ else:
649
+ _n_expected = len(_urls)
650
+ _pages = []
651
+ _pg_dl = _t.time() + 15
652
+ _last_count = -1
653
+ _stable_since = None
654
+ while _t.time() < _pg_dl:
655
+ _pages = []
656
+ for _c in _br.contexts:
657
+ _pages.extend(_c.pages)
658
+ _cnt = len(_pages)
659
+ if _n_expected > 0 and _cnt >= _n_expected:
660
+ break
661
+ if _cnt > 0 and _cnt == _last_count:
662
+ if _stable_since is None:
663
+ _stable_since = _t.time()
664
+ elif _t.time() - _stable_since >= 1.5:
665
+ break
666
+ else:
667
+ _stable_since = None
668
+ _last_count = _cnt
669
+ _t.sleep(0.5)
670
+ _pages = []
671
+ for _c in _br.contexts:
672
+ _pages.extend(_c.pages)
673
+ if not _pages:
674
+ print(" wait_mocks_loaded: CDP connected but no open tabs found")
675
+ else:
676
+ print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render")
677
+ _MIN_ELEMS = 20
678
+ _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap
679
+ for _pg in _pages: # bring each to front once to defeat background-tab render throttling
680
+ try:
681
+ _pg.bring_to_front()
682
+ except Exception:
683
+ pass
684
+ _pending = list(_pages)
685
+ while _pending and _t.time() < _verify_dl:
686
+ _still = []
687
+ for _pg in _pending:
688
+ _ttl = ""
689
+ try:
690
+ _ttl = _pg.title()
691
+ except Exception:
692
+ pass
693
+ try:
694
+ _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0")
695
+ except Exception:
696
+ _n = 0
697
+ if _n >= _MIN_ELEMS:
698
+ print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)")
699
+ else:
700
+ _still.append(_pg)
701
+ _pending = _still
702
+ if _pending:
703
+ _t.sleep(2)
704
+ if not _pending:
705
+ _cdp_ok = True
706
+ else:
707
+ for _pg in _pending:
708
+ _ttl = ""
709
+ try:
710
+ _ttl = _pg.title()
711
+ except Exception:
712
+ pass
713
+ print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back")
714
+ except ImportError:
715
+ print(" wait_mocks_loaded: playwright not installed; skipping CDP phase")
716
+ except Exception as _e:
717
+ print(f" wait_mocks_loaded: CDP phase error ({_e!r})")
718
+
719
+ if not _cdp_ok:
720
+ print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep")
721
+ _t.sleep(render_buffer)
722
+ else:
723
+ print(" wait_mocks_loaded: browser render verified, skipping render_buffer")
724
+
725
+
726
+ def _open_mock_tabs(app_states, sid_value):
727
+ """Open the first mock as the primary Chrome window, the rest as new tabs.
728
+
729
+ Uses launch_gui once per URL so that the macOS localizer regex-extract
730
+ (which grabs the FIRST quoted URL per call) still works correctly.
731
+ """
732
+ _urls = [p for p, _ in app_states]
733
+ if not _urls:
734
+ return
735
+ launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0)
736
+ for _u in _urls[1:]:
737
+ launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0)
738
+
739
+
740
+
741
+ # PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate)
742
+ def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0):
743
+ """Block until every mock serves injected state AND (best-effort) renders."""
744
+ import time as _t
745
+ deadline = _t.time() + timeout
746
+ pending = dict(mocks)
747
+ while pending and _t.time() < deadline:
748
+ for name in list(pending):
749
+ try:
750
+ r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5)
751
+ if r.status_code == 200 and r.json().get('initial_state') is not None:
752
+ del pending[name]
753
+ except Exception:
754
+ pass
755
+ if pending:
756
+ _t.sleep(1.0)
757
+ if pending:
758
+ print(f'WARN: mocks not ready within {timeout}s: {list(pending)}')
759
+ try:
760
+ from playwright.sync_api import sync_playwright
761
+ except ImportError:
762
+ print('WARN: playwright not installed; skipping render check, settle 3s')
763
+ _t.sleep(3.0)
764
+ return
765
+ with sync_playwright() as p:
766
+ try:
767
+ browser = p.chromium.launch(channel='chrome', headless=True,
768
+ args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'])
769
+ except Exception as e:
770
+ print(f'WARN: could not launch chrome for render check: {e}; settle 3s')
771
+ _t.sleep(3.0)
772
+ return
773
+ try:
774
+ for name, url in mocks.items():
775
+ page = browser.new_page()
776
+ try:
777
+ page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000))
778
+ page.wait_for_function(
779
+ "document.body && document.body.innerText.length > 50",
780
+ timeout=int(render_timeout * 1000))
781
+ print(f'[{name}] rendered OK')
782
+ except Exception as e:
783
+ print(f'WARN: [{name}] render check issue: {e}')
784
+ finally:
785
+ page.close()
786
+ finally:
787
+ browser.close()
788
+
789
+
790
+ # ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render
791
+ _open_mock_tabs(APP_STATES, sid)
792
+ wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15)
793
+ wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12)
794
+ print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps')
hr_midyear_review_007__long/reward.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: W05 — HRBP performance review + conditional raise letters
3
+ Task ID: hr_midyear_review_007__long
4
+ Persona: HRBP Tara Singh
5
+ Mocks: workday_mock,docusign_mock,slack_mock,google_sheets_mock
6
+
7
+ Answer key (embedded in initial_state):
8
+ - Workday reviews[*]._expected_rating on every status=='Pending Manager Review'
9
+ review managed by Tara (the 1..5 score the manager-review must submit).
10
+ - reviews[*]._expected_envelope (bool): true iff rating >= 4 -> a DocuSign
11
+ raise letter must be sent to that report.
12
+ - reviews[*]._employee_name / _employee_email: the report's identity for
13
+ loose recipient matching on the sent envelope.
14
+
15
+ Scoring (sub-weights sum to 1.0):
16
+ 0.35 Workday ratings (L2 anchor 1): per pending review, current ratingScore
17
+ == _expected_rating AND status == 'Completed'. Reachable only via the
18
+ gated Complete-Review action (rendered only for managerId==currentUser
19
+ && status=='Pending Manager Review').
20
+ 0.25 DocuSign raise letters (L2 anchor 2, recall, loose): for each
21
+ qualifying report (_expected_envelope), an envelope with status in
22
+ {sent,delivered,completed,signed} addressed to that report (recipient
23
+ name OR email match). score = hits / should-send. Extra/wrong envelopes
24
+ are NEVER penalised.
25
+ 0.20 Google Sheet tracker: per report row, Rating column == expected rating
26
+ (the example row is ignored).
27
+ 0.20 Slack #hr summary: a message naming how many reviews were completed and
28
+ how many raise letters were sent (loose number match + fallback).
29
+ """
30
+ import re
31
+ import sys
32
+
33
+ import requests
34
+
35
+ # --- Read sid (fatal if missing) ---
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
+ APP_URLS = {
47
+ 'workday': 'http://28.7.184.198:8192',
48
+ 'docusign': 'http://28.7.184.198:8130',
49
+ 'slack': 'http://28.7.184.198:8178',
50
+ 'google_sheets': 'http://28.7.184.198:8145',
51
+ }
52
+ _GO_CACHE = {}
53
+
54
+
55
+ def go(app_name):
56
+ if app_name in _GO_CACHE:
57
+ return _GO_CACHE[app_name]
58
+ base = APP_URLS.get(app_name)
59
+ if not base:
60
+ print(f'CRITICAL: unknown app {app_name!r} (no URL placeholder mapped)')
61
+ print('REWARD: 0.0')
62
+ sys.exit(0)
63
+ try:
64
+ resp = requests.get(f'{base}/go?sid={sid}', timeout=15)
65
+ resp.raise_for_status()
66
+ payload = resp.json()
67
+ except Exception as e:
68
+ print(f'CRITICAL: cannot fetch {app_name} go state: {e}')
69
+ print('REWARD: 0.0')
70
+ sys.exit(0)
71
+ _GO_CACHE[app_name] = payload
72
+ return payload
73
+
74
+
75
+ # --- Shared utils ---
76
+ def clamp01(x):
77
+ return max(0.0, min(1.0, float(x)))
78
+
79
+
80
+ def frac(num, den):
81
+ return 0.0 if den == 0 else num / den
82
+
83
+
84
+ def norm(s):
85
+ return (str(s) if s is not None else '').strip().lower()
86
+
87
+
88
+ def _msg_text(msg):
89
+ return msg.get('content') or msg.get('text') or ''
90
+
91
+
92
+ def _col_to_idx(col):
93
+ v = 0
94
+ for ch in col:
95
+ v = v * 26 + (ord(ch) - ord('A') + 1)
96
+ return v - 1
97
+
98
+
99
+ def _idx_to_col(idx):
100
+ idx += 1
101
+ out = []
102
+ while idx > 0:
103
+ idx, r = divmod(idx - 1, 26)
104
+ out.append(chr(ord('A') + r))
105
+ return ''.join(reversed(out))
106
+
107
+
108
+ def _parse_rows_from_sheet_data(sheet_data):
109
+ if not isinstance(sheet_data, dict) or not sheet_data:
110
+ return []
111
+ used_cols = set()
112
+ max_row = 1
113
+ for cell_id in sheet_data.keys():
114
+ m = re.fullmatch(r'([A-Z]+)(\d+)', str(cell_id))
115
+ if not m:
116
+ continue
117
+ used_cols.add(_col_to_idx(m.group(1)))
118
+ max_row = max(max_row, int(m.group(2)))
119
+ if not used_cols:
120
+ return []
121
+ headers = []
122
+ for cidx in sorted(used_cols):
123
+ cell = sheet_data.get(f'{_idx_to_col(cidx)}1', {})
124
+ h = (cell.get('computed') if isinstance(cell, dict) else None) or (cell.get('value') if isinstance(cell, dict) else None)
125
+ h = norm(h)
126
+ if h:
127
+ headers.append((cidx, h))
128
+ if not headers:
129
+ return []
130
+ rows = []
131
+ for r in range(2, max_row + 1):
132
+ row = {}
133
+ non_empty = False
134
+ for cidx, h in headers:
135
+ cell = sheet_data.get(f'{_idx_to_col(cidx)}{r}', {})
136
+ val = (cell.get('computed') if isinstance(cell, dict) else None)
137
+ if val is None:
138
+ val = (cell.get('value') if isinstance(cell, dict) else None)
139
+ sval = '' if val is None else str(val)
140
+ row[h] = sval
141
+ if sval.strip():
142
+ non_empty = True
143
+ if non_empty:
144
+ rows.append(row)
145
+ return rows
146
+
147
+
148
+ def _sheet_rows(go_payload, state_key, sheet_name):
149
+ state = go_payload.get(state_key, {})
150
+ sheets = state.get('sheets', {})
151
+ if isinstance(sheets, dict):
152
+ sheet = sheets.get(sheet_name, {})
153
+ rows = sheet.get('rows', [])
154
+ if isinstance(rows, list) and rows:
155
+ return rows
156
+ data_rows = _parse_rows_from_sheet_data(sheet.get('data', {}))
157
+ if data_rows:
158
+ return data_rows
159
+ if isinstance(sheets, list):
160
+ for sheet in sheets:
161
+ if norm(sheet.get('name')) != norm(sheet_name):
162
+ continue
163
+ rows = sheet.get('rows', [])
164
+ if isinstance(rows, list) and rows:
165
+ return rows
166
+ data_rows = _parse_rows_from_sheet_data(sheet.get('data', {}))
167
+ if data_rows:
168
+ return data_rows
169
+ for sheet in sheets:
170
+ data_rows = _parse_rows_from_sheet_data(sheet.get('data', {}))
171
+ if data_rows:
172
+ return data_rows
173
+ return []
174
+
175
+
176
+ def _slack_channel_messages(slack_state, channel_name):
177
+ channels = slack_state.get('channels', [])
178
+ target = None
179
+ for ch in channels:
180
+ if norm(ch.get('name')) == norm(channel_name):
181
+ target = ch
182
+ break
183
+ if target is None:
184
+ return []
185
+ ch_msgs = target.get('messages')
186
+ if isinstance(ch_msgs, list):
187
+ return ch_msgs
188
+ msg_map = slack_state.get('messages', {})
189
+ if isinstance(msg_map, dict):
190
+ return msg_map.get(target.get('channelId'), []) or []
191
+ return []
192
+
193
+
194
+ def _first_last(name):
195
+ parts = norm(name).split()
196
+ return (parts[0] if parts else '', parts[-1] if parts else '')
197
+
198
+
199
+ # =============================================================================
200
+ # Task-specific reward
201
+ # =============================================================================
202
+ def reward(go):
203
+ wd_i = go('workday').get('initial_state', {}) or {}
204
+ wd_c = go('workday').get('current_state', {}) or {}
205
+ ds_c = go('docusign').get('current_state', {}) or {}
206
+ slack_c = go('slack').get('current_state', {}) or {}
207
+
208
+ reviews_i = wd_i.get('reviews', []) or []
209
+ reviews_c = wd_c.get('reviews', []) or []
210
+ reviews_c_by_id = {r.get('reviewId'): r for r in reviews_c if isinstance(r, dict)}
211
+
212
+ # ---- Answer key: pending reviews with an embedded expected rating ----
213
+ pendings = [r for r in reviews_i
214
+ if r.get('_expected_rating') is not None
215
+ and norm(r.get('status')) == 'pending manager review']
216
+ n = len(pendings)
217
+ if n == 0:
218
+ print('DEBUG_W05 no pending reviews with embedded rating; nothing to score')
219
+ return 0.0
220
+
221
+ qualifying = [r for r in pendings if r.get('_expected_envelope')]
222
+ n_qual = len(qualifying)
223
+ n_completed_expected = n # every pending review should be completed
224
+
225
+ # ---- 1) Workday ratings (L2 anchor 1) — 0.35 ----
226
+ wd_match = 0
227
+ try:
228
+ for r in pendings:
229
+ rid = r.get('reviewId')
230
+ exp = r.get('_expected_rating')
231
+ cur = reviews_c_by_id.get(rid, {})
232
+ try:
233
+ cur_score = int(cur.get('ratingScore')) if cur.get('ratingScore') is not None else None
234
+ except (TypeError, ValueError):
235
+ cur_score = None
236
+ if cur_score == int(exp) and norm(cur.get('status')) == 'completed':
237
+ wd_match += 1
238
+ except Exception as e:
239
+ print(f'DEBUG_W05 workday ratings component error: {e!r}')
240
+ wd_score = frac(wd_match, n)
241
+
242
+ # ---- 2) DocuSign raise letters (L2 anchor 2, recall, loose) — 0.25 ----
243
+ SENT_STATES = {'sent', 'delivered', 'completed', 'signed'}
244
+ ds_match = 0
245
+ try:
246
+ envelopes = ds_c.get('envelopes', []) or []
247
+ sent_envs = [e for e in envelopes if norm(e.get('status')) in SENT_STATES]
248
+ for r in qualifying:
249
+ emp_name = norm(r.get('_employee_name'))
250
+ emp_email = norm(r.get('_employee_email'))
251
+ efirst, elast = _first_last(r.get('_employee_name'))
252
+ hit = False
253
+ for env in sent_envs:
254
+ for rec in (env.get('recipients') or []):
255
+ rname = norm(rec.get('name'))
256
+ remail = norm(rec.get('email'))
257
+ if emp_email and remail and emp_email == remail:
258
+ hit = True
259
+ break
260
+ if emp_name and rname and emp_name == rname:
261
+ hit = True
262
+ break
263
+ # loose: first+last both present in recipient name
264
+ if efirst and elast and efirst in rname and elast in rname:
265
+ hit = True
266
+ break
267
+ if hit:
268
+ break
269
+ if hit:
270
+ ds_match += 1
271
+ except Exception as e:
272
+ print(f'DEBUG_W05 docusign component error: {e!r}')
273
+ ds_score = frac(ds_match, n_qual) if n_qual else 1.0
274
+
275
+ # ---- 3) Google Sheet tracker — 0.20 ----
276
+ # Per report row: Rating column == expected rating. Example row ignored
277
+ # (its name does not match any report).
278
+ name_to_rating = {norm(r.get('_employee_name')): str(int(r.get('_expected_rating')))
279
+ for r in pendings}
280
+ sheet_match = 0
281
+ try:
282
+ rows_c = _sheet_rows(go('google_sheets'), 'current_state',
283
+ 'Performance Review Tracker')
284
+
285
+ def _row_field(row, *aliases):
286
+ for a in aliases:
287
+ if a in row:
288
+ return row[a]
289
+ return ''
290
+
291
+ for name, exp_rating in name_to_rating.items():
292
+ for row in rows_c:
293
+ if norm(_row_field(row, 'employee', 'name', 'employee name')) == name:
294
+ cur = norm(_row_field(row, 'rating', 'score'))
295
+ # accept '4', '4.0', or a digit anywhere in the cell
296
+ m = re.search(r'\d', cur)
297
+ if m and m.group(0) == exp_rating:
298
+ sheet_match += 1
299
+ break
300
+ except Exception as e:
301
+ print(f'DEBUG_W05 sheet component error: {e!r}')
302
+ sheet_score = frac(sheet_match, n)
303
+
304
+ # ---- 4) Slack #hr summary — 0.20 ----
305
+ slack_ok = 0.0
306
+ try:
307
+ chan = _slack_channel_messages(slack_c, 'hr')
308
+ for msg in chan:
309
+ txt = norm(_msg_text(msg))
310
+ if not txt.strip():
311
+ continue
312
+ # find numbers near review/letter keywords
313
+ rev_m = re.search(r'(\d+)\s*(?:manager\s+)?reviews?', txt)
314
+ let_m = re.search(r'(\d+)\s*(?:raise\s+|salary\s+|increase\s+)?(?:letters?|envelopes?)', txt)
315
+ if (rev_m and int(rev_m.group(1)) == n_completed_expected
316
+ and let_m and int(let_m.group(1)) == n_qual):
317
+ slack_ok = 1.0
318
+ break
319
+ if slack_ok == 0.0:
320
+ # fallback: any non-empty message mentioning both reviews and letters
321
+ for msg in chan:
322
+ txt = norm(_msg_text(msg))
323
+ if ('review' in txt and
324
+ ('letter' in txt or 'raise' in txt or 'increase' in txt)):
325
+ slack_ok = 0.5
326
+ break
327
+ except Exception as e:
328
+ print(f'DEBUG_W05 slack component error: {e!r}')
329
+
330
+ # ---- Combine ----
331
+ s_wd = 0.35 * wd_score
332
+ s_ds = 0.25 * ds_score
333
+ s_sheet = 0.20 * sheet_score
334
+ s_slack = 0.20 * slack_ok
335
+ score = s_wd + s_ds + s_sheet + s_slack
336
+
337
+ print(
338
+ 'DEBUG_W05 '
339
+ f'n_pending={n} n_qualifying={n_qual} '
340
+ f'wd_match={wd_match}/{n} wd_score={round(wd_score, 4)} '
341
+ f'ds_match={ds_match}/{n_qual} ds_score={round(ds_score, 4)} '
342
+ f'sheet_match={sheet_match}/{n} sheet_score={round(sheet_score, 4)} '
343
+ f'slack_ok={slack_ok} '
344
+ f'w_wd={round(s_wd, 4)} w_ds={round(s_ds, 4)} '
345
+ f'w_sheet={round(s_sheet, 4)} w_slack={round(s_slack, 4)} '
346
+ f'total={round(score, 4)}'
347
+ )
348
+
349
+ return clamp01(score)
350
+
351
+
352
+ try:
353
+ score = float(reward(go))
354
+ except Exception as exc:
355
+ print(f'ERROR: reward() raised {exc!r}')
356
+ score = 0.0
357
+
358
+ score = clamp01(score)
359
+ print(f'\nREWARD: {round(score, 4)}')
itops_access_approval_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"
itops_access_approval_001/initial_setup.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: Access Request Approval Log (prof26_access_approval_001)
3
+ Task ID: itops_access_approval_001
4
+ Domain: mock_websites
5
+ Mocks: jira_mock, workday_mock, google_sheets_mock
6
+
7
+ Resets the three mock apps to their initial pre-task state and writes a
8
+ canonical JSON snapshot of the Approvals sheet to /home/user/prof26_access_approval_001.json.
9
+ """
10
+ import json
11
+ import os
12
+ import shlex
13
+ import subprocess
14
+ import time
15
+ import uuid
16
+
17
+ import requests
18
+
19
+ # --- Config ---
20
+ JIRA_URL = "http://28.7.184.198:8153"
21
+ WORKDAY_URL = "http://28.7.184.198:8192"
22
+ SHEETS_URL = "http://28.7.184.198:8145"
23
+
24
+ WORKDIR = "/home/user"
25
+ TASK_ID = "prof26_access_approval_001"
26
+ SNAPSHOT = f"{WORKDIR}/{TASK_ID}.json"
27
+
28
+ # --- Generate and persist sid ---
29
+ sid = str(uuid.uuid4())
30
+ with open("/tmp/task_web_sid", "w") as f:
31
+ f.write(sid)
32
+
33
+ # ---------------------------------------------------------------------------
34
+ # Build initial state for each mock
35
+ # ---------------------------------------------------------------------------
36
+
37
+ HEADER_STYLE = {"bold": True, "bg": "#E8EAED"}
38
+
39
+
40
+ def cell(value, style=None):
41
+ c = {"value": value, "formula": value}
42
+ if style:
43
+ c["style"] = style
44
+ return c
45
+
46
+
47
+ def build_sheets_state():
48
+ """Access Control Register workbook with 'Approvals' sheet: header + 3 records."""
49
+ headers = ["Request ID", "Date", "Requester", "System", "Access Level",
50
+ "Department", "Manager Approval", "SysAdmin Decision", "Notes"]
51
+ data = {}
52
+ for col_idx, h in enumerate(headers):
53
+ col = chr(ord("A") + col_idx) # A..I
54
+ data[f"{col}1"] = cell(h, HEADER_STYLE)
55
+
56
+ records = [
57
+ ["IAR-309", "2026-06-27", "Nina Cole", "HubSpot", "Edit", "Marketing",
58
+ "Approved", "Approved",
59
+ "Department verified in Workday (E-10410). Edit access compliant for Marketing."],
60
+ ["IAR-310", "2026-06-29", "Omar Diaz", "Google Sheets", "Edit", "Finance",
61
+ "Approved", "Approved",
62
+ "Department verified in Workday (E-10455). Edit access compliant for Finance."],
63
+ ["IAR-311", "2026-06-30", "Priya Sen", "Salesforce", "Read-only", "Sales Operations",
64
+ "Approved", "Approved",
65
+ "Department verified in Workday (E-10477). Read-only access compliant for Sales Operations."],
66
+ ]
67
+ for r, rec in enumerate(records, start=2):
68
+ for col_idx, val in enumerate(rec):
69
+ col = chr(ord("A") + col_idx)
70
+ data[f"{col}{r}"] = cell(val)
71
+
72
+ sheet = {
73
+ "id": "sh_apr_01",
74
+ "name": "Approvals",
75
+ "rowCount": 100,
76
+ "colCount": 26,
77
+ "frozenRows": 1,
78
+ "frozenCols": 0,
79
+ "tabColor": None,
80
+ "isHidden": False,
81
+ "data": data,
82
+ }
83
+ return {
84
+ "id": "wb_acr_01",
85
+ "title": "Access Control Register",
86
+ "activeSheetId": "sh_apr_01",
87
+ "selectedCell": "A1",
88
+ "selectionRange": None,
89
+ "clipboard": None,
90
+ "isDragging": False,
91
+ "undoStack": [],
92
+ "redoStack": [],
93
+ "namedRanges": [],
94
+ "conditionalFormats": [],
95
+ "charts": [],
96
+ "showGridlines": True,
97
+ "showFormulas": False,
98
+ "zoom": 100,
99
+ "sheets": [sheet],
100
+ }
101
+
102
+
103
+ def build_jira_state():
104
+ return {
105
+ "currentUser": {"id": "u1", "name": "Business Systems Admin",
106
+ "email": "sysadmin@meridianlabs.io",
107
+ "avatar": "https://picsum.photos/100/100?random=u1"},
108
+ "users": [
109
+ {"id": "u1", "name": "Business Systems Admin", "email": "sysadmin@meridianlabs.io",
110
+ "avatar": "https://picsum.photos/100/100?random=u1"},
111
+ {"id": "u2", "name": "Linda Hess", "email": "l.hess@meridianlabs.io",
112
+ "avatar": "https://picsum.photos/100/100?random=u2"},
113
+ ],
114
+ "projects": [
115
+ {"id": "p_iar", "key": "IAR", "name": "IT Access Requests", "leadId": "u1",
116
+ "category": "IT", "icon": "https://picsum.photos/64/64?random=iar"},
117
+ ],
118
+ "sprints": [
119
+ {"id": "s1", "projectId": "p_iar", "name": "Sprint 1",
120
+ "goal": "Process access requests", "startDate": "2026-06-22T12:00:00.000Z",
121
+ "endDate": "2026-07-06T12:00:00.000Z", "state": "active"},
122
+ ],
123
+ "issues": [
124
+ {
125
+ "id": "i_iar_312", "key": "IAR-312", "projectId": "p_iar",
126
+ "summary": "Access request: Salesforce read-only for onboarding rep",
127
+ "description": ("Requester: Tom Becker (tom.becker@meridianlabs.io). "
128
+ "Requested system: Salesforce. Access level: Read-only. "
129
+ "Purpose: Support onboarding-campaign reporting. "
130
+ "Manager approval: Approved by Linda Hess (l.hess@meridianlabs.io)."),
131
+ "type": "Task", "status": "To Do", "priority": "Medium", "storyPoints": 1,
132
+ "reporterId": "u2", "assigneeId": "u1", "sprintId": "s1", "epicId": None,
133
+ "labels": ["access-request"], "subtasks": [], "linkedIssueIds": [],
134
+ "createdAt": "2026-07-01T09:00:00.000Z", "updatedAt": "2026-07-01T09:00:00.000Z",
135
+ },
136
+ ],
137
+ "comments": [],
138
+ "workflows": [{"id": "w1", "name": "IT Access Workflow",
139
+ "transitions": [{"from": "To Do", "to": ["In Progress", "Done"]},
140
+ {"from": "In Progress", "to": ["Done", "To Do"]},
141
+ {"from": "Done", "to": ["To Do"]}]}],
142
+ "notifications": [],
143
+ }
144
+
145
+
146
+ def build_workday_state():
147
+ return {
148
+ "currentUser": {
149
+ "id": "emp001", "name": "Business Systems Admin",
150
+ "email": "sysadmin@meridianlabs.io", "phone": "+1 (415) 555-0100",
151
+ "role": "Manager", "department": "IT Operations", "departmentId": "dept001",
152
+ "avatar": "https://ui-avatars.com/api/?name=Business+Systems+Admin&background=0875E1&color=fff&size=128",
153
+ "managerId": None, "title": "Business Systems Administrator",
154
+ "location": "Remote", "joinDate": "2021-03-15", "employeeType": "Full-Time",
155
+ "skills": ["Identity Management", "Access Governance"],
156
+ "birthday": "1990-04-12", "workAnniversary": "2021-03-15",
157
+ },
158
+ "employees": [
159
+ {
160
+ "id": "E-10482", "name": "Tom Becker", "email": "tom.becker@meridianlabs.io",
161
+ "phone": "+1 (415) 555-0182", "role": "Employee", "department": "Sales Operations",
162
+ "departmentId": "dept003", "avatar": "https://ui-avatars.com/api/?name=Tom+Becker&background=0875E1&color=fff&size=128",
163
+ "managerId": "emp001", "title": "Onboarding Representative",
164
+ "location": "Remote", "joinDate": "2024-01-15", "employeeType": "Full-Time",
165
+ "skills": ["Sales", "Onboarding"], "birthday": "1992-08-22",
166
+ "workAnniversary": "2024-01-15",
167
+ },
168
+ ],
169
+ "departments": [
170
+ {"id": "dept001", "name": "IT Operations", "headcount": 1, "managerId": None},
171
+ {"id": "dept003", "name": "Sales Operations", "headcount": 1, "managerId": "emp001"},
172
+ ],
173
+ "timeEntries": [],
174
+ "timeOffRequests": [],
175
+ "timeOffBalance": {"vacation": 120, "sick": 40, "personal": 16},
176
+ "payroll": [],
177
+ "benefits": {"employeeId": "E-10482", "enrollmentStatus": "Complete", "plans": [], "dependents": []},
178
+ "reviews": [],
179
+ "goals": [],
180
+ "tasks": [],
181
+ "announcements": [],
182
+ "notifications": [],
183
+ "clockStatus": {"isClockedIn": False, "startTime": None},
184
+ }
185
+
186
+
187
+ # ---------------------------------------------------------------------------
188
+ # Inject state into each mock
189
+ # ---------------------------------------------------------------------------
190
+ mocks = {
191
+ "jira_mock": JIRA_URL,
192
+ "workday_mock": WORKDAY_URL,
193
+ "google_sheets_mock": SHEETS_URL,
194
+ }
195
+
196
+ states = {
197
+ "jira_mock": build_jira_state(),
198
+ "workday_mock": build_workday_state(),
199
+ "google_sheets_mock": build_sheets_state(),
200
+ }
201
+
202
+ for name, url in mocks.items():
203
+ resp = requests.post(
204
+ f"{url}/post?sid={sid}",
205
+ json={"action": "set", "state": states[name]},
206
+ timeout=30,
207
+ )
208
+ assert resp.status_code == 200, f"{name} state injection failed: {resp.text}"
209
+ print(f"State injected: {name} (sid={sid})")
210
+
211
+ # ---------------------------------------------------------------------------
212
+ # Verify initial_state is served
213
+ # ---------------------------------------------------------------------------
214
+ for name, url in mocks.items():
215
+ go = requests.get(f"{url}/go?sid={sid}", timeout=10).json()
216
+ assert go.get("initial_state") is not None, f"{name}: initial_state is None after injection"
217
+ print("Verified: all three mocks have initial_state set")
218
+
219
+ # ---------------------------------------------------------------------------
220
+ # Write canonical JSON snapshot of the Approvals sheet (initial state)
221
+ # ---------------------------------------------------------------------------
222
+ sheets_state = build_sheets_state()
223
+ apr = next(s for s in sheets_state["sheets"] if s["id"] == "sh_apr_01")
224
+ snapshot = {
225
+ "task_id": TASK_ID,
226
+ "sid": sid,
227
+ "workbook_id": sheets_state["id"],
228
+ "workbook_title": sheets_state["title"],
229
+ "sheet_id": apr["id"],
230
+ "sheet_name": apr["name"],
231
+ "cells": apr["data"],
232
+ "row_count": apr["rowCount"],
233
+ "col_count": apr["colCount"],
234
+ }
235
+ with open(SNAPSHOT, "w") as f:
236
+ json.dump(snapshot, f, indent=2)
237
+ print(f"Initial snapshot written: {SNAPSHOT}")
238
+
239
+ # ---------------------------------------------------------------------------
240
+ # Launch Chrome for each mock (GUI-ready state)
241
+ # ---------------------------------------------------------------------------
242
+ def launch_gui(command, delay_sec=1.0):
243
+ env = os.environ.copy()
244
+ env["DISPLAY"] = ":0"
245
+ subprocess.Popen(
246
+ shlex.split(command),
247
+ stdout=subprocess.DEVNULL,
248
+ stderr=subprocess.DEVNULL,
249
+ env=env,
250
+ )
251
+ time.sleep(delay_sec)
252
+
253
+
254
+ for name, url in mocks.items():
255
+ launch_gui(f'google-chrome "{url}/?sid={sid}"', delay_sec=0.5)
256
+ print(f"Launched Chrome for {len(mocks)} mocks")
257
+
258
+
259
+ # ---------------------------------------------------------------------------
260
+ # Wait until every mock serves injected state AND renders (Phase 1 + Phase 2)
261
+ # ---------------------------------------------------------------------------
262
+ def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0):
263
+ import time as _t
264
+ deadline = _t.time() + timeout
265
+ pending = dict(mocks)
266
+ while pending and _t.time() < deadline:
267
+ for name in list(pending):
268
+ try:
269
+ r = requests.get(f"{pending[name]}/go?sid={sid}", timeout=5)
270
+ if r.status_code == 200 and r.json().get("initial_state") is not None:
271
+ del pending[name]
272
+ except Exception:
273
+ pass
274
+ if pending:
275
+ _t.sleep(1.0)
276
+ if pending:
277
+ raise RuntimeError(f"Mocks not ready within {timeout}s: {list(pending)}")
278
+ try:
279
+ from playwright.sync_api import sync_playwright
280
+ except ImportError:
281
+ print("WARN: playwright not installed; skipping render check, settle 5s")
282
+ _t.sleep(5.0)
283
+ return
284
+ with sync_playwright() as p:
285
+ browser = p.chromium.launch(channel="chrome", headless=True,
286
+ args=["--no-sandbox", "--disable-gpu", "--disable-dev-shm-usage"])
287
+ try:
288
+ for name, url in mocks.items():
289
+ page = browser.new_page()
290
+ try:
291
+ page.goto(f"{url}/?sid={sid}", wait_until="domcontentloaded",
292
+ timeout=int(render_timeout * 1000))
293
+ page.wait_for_function(
294
+ "document.body && document.body.innerText.length > 100",
295
+ timeout=int(render_timeout * 1000))
296
+ html = page.content()
297
+ if len(html) < 2000:
298
+ raise RuntimeError(f"[{name}] rendered DOM too small ({len(html)} bytes)")
299
+ print(f"[{name}] rendered OK ({len(html)} bytes)")
300
+ finally:
301
+ page.close()
302
+ finally:
303
+ browser.close()
304
+
305
+
306
+ wait_for_mocks_loaded(mocks, sid)
307
+ print(f"GUI_READY: all {len(mocks)} mocks launched and verified (sid={sid})")
itops_access_approval_001/reward.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: Access Request Approval Log — record IAR-312 in Google Sheets
3
+ Task ID: itops_access_approval_001
4
+ Domain: mock_websites
5
+ Mock: google_sheets_mock
6
+ Scoring: Verify the 'Approvals' sheet has exactly one new row (row 5) added
7
+ with the exact ground-truth values, no extra rows, and no duplicate
8
+ IAR-312 request id.
9
+
10
+ State source: The agent edits the Google Sheets mock through the browser,
11
+ which updates the mock's in-memory state keyed by the task session id. We
12
+ read the live current_state from the mock's /go endpoint (using the sid in
13
+ /tmp/task_web_sid) so the reward reflects the agent's actual changes. The
14
+ sid is task-private (initial_setup.py mints a fresh uuid.uuid4() per run),
15
+ so /go returns only this task's state.
16
+ """
17
+ import json
18
+ import sys
19
+
20
+ import requests
21
+
22
+ # Mock base URL (from task_config.json).
23
+ SHEETS_URL = "http://28.7.184.198:8145" # google_sheets_mock
24
+
25
+ # Ground-truth values for the new row 5 (from task_config.json context).
26
+ EXPECTED_ROW5 = {
27
+ 'A': 'IAR-312',
28
+ 'B': '2026-07-01',
29
+ 'C': 'Tom Becker',
30
+ 'D': 'Salesforce',
31
+ 'E': 'Read-only',
32
+ 'F': 'Sales Operations',
33
+ 'G': 'Approved',
34
+ 'H': 'Approved',
35
+ 'I': 'Department verified in Workday (E-10482). Read-only access compliant for Sales Operations.',
36
+ }
37
+
38
+ # Ground-truth values for the pre-existing rows 2-4 (must remain unchanged).
39
+ EXPECTED_ROWS_2_4 = {
40
+ 'A2': 'IAR-309', 'B2': '2026-06-27', 'C2': 'Nina Cole', 'D2': 'HubSpot',
41
+ 'E2': 'Edit', 'F2': 'Marketing', 'G2': 'Approved', 'H2': 'Approved',
42
+ 'I2': 'Department verified in Workday (E-10410). Edit access compliant for Marketing.',
43
+ 'A3': 'IAR-310', 'B3': '2026-06-29', 'C3': 'Omar Diaz', 'D3': 'Google Sheets',
44
+ 'E3': 'Edit', 'F3': 'Finance', 'G3': 'Approved', 'H3': 'Approved',
45
+ 'I3': 'Department verified in Workday (E-10455). Edit access compliant for Finance.',
46
+ 'A4': 'IAR-311', 'B4': '2026-06-30', 'C4': 'Priya Sen', 'D4': 'Salesforce',
47
+ 'E4': 'Read-only', 'F4': 'Sales Operations', 'G4': 'Approved', 'H4': 'Approved',
48
+ 'I4': 'Department verified in Workday (E-10477). Read-only access compliant for Sales Operations.',
49
+ }
50
+
51
+ # Expected Request ID column values (rows 2-5). IAR-312 must appear exactly once.
52
+ EXPECTED_REQUEST_IDS = ['IAR-309', 'IAR-310', 'IAR-311', 'IAR-312']
53
+
54
+
55
+ def _comp(idx, name, weight, passed, score, detail="", description=""):
56
+ """Emit a structured COMPONENT line for per-module scoring visibility."""
57
+ print("COMPONENT: " + json.dumps({
58
+ "id": idx, "name": name, "weight": float(weight),
59
+ "passed": bool(passed), "score": float(score),
60
+ "detail": detail, "description": description,
61
+ }))
62
+
63
+
64
+ def _run_component(idx, name, weight, fn, args):
65
+ """Run one check fn, emit PASS/FAIL + COMPONENT line, return (passed, score, detail)."""
66
+ try:
67
+ passed, score, detail = fn(*args)
68
+ except Exception as e:
69
+ passed, score, detail = False, 0.0, f'error: {e}'
70
+ status = 'PASS' if passed else 'FAIL'
71
+ suffix = f' ({weight} pts)' if passed else f' — {detail}'
72
+ print(f'{status}: Component {idx} — {name}{suffix}')
73
+ _comp(idx, name, weight, passed, score, detail,
74
+ description=(fn.__doc__ or '').strip())
75
+ return passed, score, detail
76
+
77
+
78
+ def _load_cells():
79
+ """Fetch the Approvals sheet cells from the google_sheets_mock live state.
80
+
81
+ Reads /tmp/task_web_sid for the session id, queries the mock's /go
82
+ endpoint, and returns the data dict of the 'sh_apr_01' sheet. Returns
83
+ None on any failure.
84
+ """
85
+ try:
86
+ with open('/tmp/task_web_sid') as f:
87
+ sid = f.read().strip()
88
+ except Exception as e:
89
+ print(f'CRITICAL: cannot read /tmp/task_web_sid: {e}')
90
+ return None
91
+ try:
92
+ resp = requests.get(f'{SHEETS_URL}/go?sid={sid}', timeout=15)
93
+ resp.raise_for_status()
94
+ data = resp.json()
95
+ except Exception as e:
96
+ print(f'CRITICAL: cannot fetch sheets mock state: {e}')
97
+ return None
98
+ try:
99
+ cur = data['current_state']
100
+ sheet = next(s for s in cur['sheets'] if s['id'] == 'sh_apr_01')
101
+ cells = sheet['data']
102
+ except Exception as e:
103
+ print(f'CRITICAL: cannot locate sh_apr_01 in current_state: {e}')
104
+ return None
105
+ if not isinstance(cells, dict):
106
+ print('CRITICAL: sheet data is not a dict')
107
+ return None
108
+ return cells
109
+
110
+
111
+ def check_component_1(cells):
112
+ """New row 5 fully populated with the exact 9 ground-truth values.
113
+ Pass condition: cells A5..I5 all exist and equal EXPECTED_ROW5 exactly.
114
+ """
115
+ missing = [f'{col}5' for col in 'ABCDEFGHI'
116
+ if cells.get(f'{col}5', {}).get('value') != EXPECTED_ROW5[col]]
117
+ if not missing:
118
+ return True, 0.70, 'row 5 has all 9 correct values (A5=IAR-312 ... I5=notes)'
119
+ return False, 0.0, f'row 5 missing/incorrect cells: {missing}'
120
+
121
+
122
+ def check_component_2(cells):
123
+ """Exactly one new row added, no extra rows, and rows 2-4 preserved intact.
124
+ Pass condition: snapshot has exactly 45 cells (rows 1-5 x 9 cols) AND rows
125
+ 2-4 still match EXPECTED_ROWS_2_4 in every field. Fails on initial (36 cells).
126
+ """
127
+ n = len(cells)
128
+ if n != 45:
129
+ return False, 0.0, f'expected exactly 45 cells (rows 1-5), found {n}'
130
+ wrong = []
131
+ for addr, exp in EXPECTED_ROWS_2_4.items():
132
+ got = cells.get(addr, {}).get('value')
133
+ if got != exp:
134
+ wrong.append(f'{addr}={got!r}(exp {exp!r})')
135
+ if not wrong:
136
+ return True, 0.20, 'exactly 45 cells and rows 2-4 unchanged in all 27 fields'
137
+ return False, 0.0, f'rows 2-4 mismatch: {wrong[:5]}'
138
+
139
+
140
+ def check_component_3(cells):
141
+ """No duplicate IAR-312 request id; IAR-312 appears exactly once in col A.
142
+ Pass condition: Request IDs A2..A5 equal ['IAR-309','IAR-310','IAR-311',
143
+ 'IAR-312'] and there is no A6+ request id (no extra rows).
144
+ """
145
+ actual_ids = []
146
+ for r in range(2, 6):
147
+ v = cells.get(f'A{r}', {}).get('value')
148
+ if v is None:
149
+ break
150
+ actual_ids.append(v)
151
+ if actual_ids != EXPECTED_REQUEST_IDS:
152
+ return False, 0.0, f'request-id column A = {actual_ids} (exp {EXPECTED_REQUEST_IDS})'
153
+ # Ensure no stray row 6 (would indicate an extra/duplicate row was added).
154
+ if cells.get('A6', {}).get('value') is not None:
155
+ return False, 0.0, 'extra row 6 present — A6 is not empty'
156
+ return True, 0.10, 'IAR-312 appears exactly once (at A5); no extra rows'
157
+
158
+
159
+ def verify_task():
160
+ cells = _load_cells()
161
+ if cells is None:
162
+ print('REWARD: 0.0')
163
+ return 0.0
164
+
165
+ total_score = 0.0
166
+ for idx, name, weight, fn, args in [
167
+ (1, 'Row 5 added with exact ground-truth values', 0.70,
168
+ check_component_1, (cells,)),
169
+ (2, 'Exactly one row added + rows 2-4 preserved', 0.20,
170
+ check_component_2, (cells,)),
171
+ (3, 'No duplicate IAR-312 / no extra rows', 0.10,
172
+ check_component_3, (cells,)),
173
+ ]:
174
+ _, score, _ = _run_component(idx, name, weight, fn, args)
175
+ total_score += score
176
+
177
+ final_score = round(min(total_score, 1.0), 4)
178
+ print(f'\nScore: {total_score}/1.0')
179
+ print(f'REWARD: {final_score}')
180
+ return final_score
181
+
182
+
183
+ if __name__ == '__main__':
184
+ verify_task()
itops_access_approval_001/reward_label.json ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/prof26_access_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:30:57",
7
+ "label": {
8
+ "task_id": "itops_access_approval_001",
9
+ "domain": "mock_websites",
10
+ "summary": "验证在 Google Sheets 的 Approvals 工作表中是否正确添加了 IAR-312 的新行(第5行),且现有行未被修改,无重复或额外行",
11
+ "is_placeholder": false,
12
+ "data_sources": [
13
+ "/home/user/prof26_access_approval_001.json"
14
+ ],
15
+ "scoring_components": [
16
+ {
17
+ "name": "Component 1",
18
+ "weight": 0.7,
19
+ "description": "检查新添加的第5行是否完全填充了9个预期值",
20
+ "check_logic": "遍历列 A 到 I,检查 cells.get(f'{col}5', {}).get('value') 是否等于 EXPECTED_ROW5 中对应列的值;若全部匹配则通过,否则列出缺失或不匹配的单元格",
21
+ "pass_condition": "A5 到 I5 全部存在且值与 EXPECTED_ROW5 完全一致"
22
+ },
23
+ {
24
+ "name": "Component 2",
25
+ "weight": 0.2,
26
+ "description": "检查是否只新增了一行且第2-4行保持原样",
27
+ "check_logic": "先检查 len(cells) 是否等于 45;再遍历 EXPECTED_ROWS_2_4 中每个地址和预期值,检查 cells.get(addr, {}).get('value') 是否匹配",
28
+ "pass_condition": "快照中恰好有 45 个单元格(行1-5 × 9列),且第2-4行的全部 27 个字段与 EXPECTED_ROWS_2_4 完全一致"
29
+ },
30
+ {
31
+ "name": "Component 3",
32
+ "weight": 0.1,
33
+ "description": "检查 IAR-312 在 A 列只出现一次且无额外行",
34
+ "check_logic": "遍历 A2 到 A5,提取值组成 actual_ids,检查是否等于 EXPECTED_REQUEST_IDS;再检查 A6 的值是否为 None(即无第6行)",
35
+ "pass_condition": "A2 到 A5 的请求 ID 恰好为 ['IAR-309', 'IAR-310', 'IAR-311', 'IAR-312'],且 A6 为空"
36
+ }
37
+ ],
38
+ "total_max_score": 1.0,
39
+ "score_aggregation": "各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限,并四舍五入保留4位小数",
40
+ "failure_modes": [
41
+ "快照文件 /home/user/prof26_access_approval_001.json 不存在",
42
+ "快照文件解析失败或内容不是有效的 JSON",
43
+ "快照中的 cells 字段不是字典类型",
44
+ "第5行有任何单元格缺失或与 EXPECTED_ROW5 不匹配(组件1失败,得0分)",
45
+ "单元格总数不是45,或第2-4行有任何字段被修改(组件2失败,得0分)",
46
+ "A2-A5 请求 ID 列表不匹配,或 A6 不为空(组件3失败,得0分)"
47
+ ],
48
+ "scoring_logic_explanation": "脚本首先在 VM 上加载本地快照文件 /home/user/prof26_access_approval_001.json。若加载失败(文件不存在、解析错误或 cells 不是字典),直接输出 CRITICAL 并返回 0.0。加载成功后,依次执行三个组件检查:组件1验证第5行(A5-I5)的9个单元格是否完全匹配预期的 IAR-312 记录,权重0.70;组件2验证快照中恰好有45个单元格(即只有1-5行)且第2-4行的全部27个字段保持原样,权重0.20;组件3验证A列请求ID从A2到A5依次为IAR-309到IAR-312,且A6为空以确保无重复或额外行,权重0.10。每个组件通过时获得对应权重分数,失败则得0分。三个组件得分累加后,用 min(total_score, 1.0) 钳制上限,四舍五入到4位小数作为最终 REWARD 返回。",
49
+ "confidence": 1.0
50
+ },
51
+ "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读源码:\n\n1. **Task ID**: prof26_access_approval_001(从 docstring 中明确提取)\n2. **Domain**: mock_websites(从 docstring 中明确提取)\n3. **Summary**: 验证在 Google Sheets 的 'Approvals' 工作表中是否正确添加了 IAR-312 的新行(第5行),且现有行未被修改,无重复/额外行。\n4. **is_placeholder**: false(这是一个真正的评分脚本,不是占位符)\n5. **data_sources**: 脚本从 `/home/user/prof26_access_approval_001.json`(VM 上的状态快照文件)获取状态。docstring 提到 mock 是 google_sheets_mock,但实际验证的是快照文件。\n6. **Scoring components**:\n - Component 1: weight 0.70, 检查 A5..I5 是否完全匹配 EXPECTED_ROW5\n - Component 2: weight 0.20, 检查总单元格数是否为 45(行1-5 × 9列),且行2-4完全匹配 EXPECTED_ROWS_2_4\n - Component 3: weight 0.10, 检查 A2..A5 的请求 ID 是否完全匹配 ['IAR-309', 'IAR-310', 'IAR-311', 'IAR-312'],且 A6 为空(无额外行)\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 各组件分数相加,然后取 min(total_score, 1.0) 并四舍五入到4位小数\n9. **failure_modes**:\n - 快照文件不存在\n - 快照文件无法解析\n - cells 不是 dict\n - 任何组件检查失败(返回 0.0 分)\n - 组件1:A5-I5 有任何缺失或不匹配\n - 组件2:单元格数不是 45,或行2-4有任何字段不匹配\n - 组件3:A2-A5 请求 ID 不匹配,或 A6 不为空\n10. **scoring_logic_explanation**: 按执行顺序:\n - 从 `/home/user/prof26_access_approval_001.json` 加载快照\n - 如果加载失败,打印 CRITICAL 并返回 0.0\n - 依次运行三个组件检查:\n 1. 检查第5行9个单元格是否完全匹配预期值(0.7分)\n 2. 检查总单元格数是否为45(即只有1-5行)且第2-4行27个字段完全不变(0.2分)\n 3. 检查A列请求ID是否为预期列表且A6为空,确保IAR-312只出现一次且无额外行(0.1分)\n - 各组件得分累加,最终钳制在1.0并四舍五入\n11. **confidence**: 1.0(源码完整清晰)\n\n需要确保:\n- 只输出 JSON,无 markdown 代码块\n- 第一个字符是 {,最后一个字符是 }\n- 所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样\n- 不要臆测\n\n让我构建 JSON:\n\n```json\n{\n \"task_id\": \"prof26_access_approval_001\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证在 Google Sheets 的 Approvals 工作表中是否正确添加了 IAR-312 的新行(第5行),且现有行未被修改,无重复或额外行\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/home/user/prof26_access_approval_001.json\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 1\",\n \"weight\": 0.70,\n \"description\": \"检查新添加的第5行是否完全填充了9个预期值\",\n \"check_logic\": \"遍历列 A 到 I,检查 cells.get(f'{col}5', {}).get('value') 是否等于 EXPECTED_ROW5 中对应列的值;若全部匹配则通过\",\n \"pass_condition\": \"A5 到 I5 全部存在且值与 EXPECTED_ROW5 完全一致\"\n },\n {\n \"name\": \"Component 2\",\n \"weight\": 0.20,\n \"description\": \"检查是否只新增了一行且第2-4行保持原样\",\n \"check_logic\": \"先检查 len(cells) 是否等于 45;再遍历 EXPECTED_ROWS_2_4 中每个地址和预期值,检查 cells.get(addr, {}).get('value') 是否匹配\",\n \"pass_condition\": \"快照中恰好有 45 个单元格(行1-5 × 9列),且第2-4行的全部 27 个字段与 EXPECTED_ROWS_2_4 完全一致\"\n },\n {\n \"name\": \"Component 3\",\n \"weight\": 0.10,\n \"description\": \"检查 IAR-312 在 A 列只出现一次且无额外行\",\n \"check_logic\": \"遍历 A2 到 A5,提取值组成 actual_ids,检查是否等于 EXPECTED_REQUEST_IDS;再检查 A6 的值是否为 None\",\n \"pass_condition\": \"A2 到 A5 的请求 ID 恰好为 ['IAR-309', 'IAR-310', 'IAR-311', 'IAR-312'],且 A6 为空(无第6行)\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限,并四舍五入保留4位小数\",\n \"failure_modes\": [\n \"快照文件 /home/user/prof26_access_approval_001.json 不存在\",\n \"快照文件解析失败或内容不是有效的 JSON\",\n \"快照中的 cells 字段不是字典类型\",\n \"第5行有任何单元格缺失或与 EXPECTED_ROW5 不匹配(组件1失败,得0分)\",\n \"单元格总数不是45,或第2-4行有任何字段被修改(组件2失败,得0分)\",\n \"A2-A5 请求 ID 列表不匹配,或 A6 不为空(组件3失败,得0分)\"\n ],\n \"scoring_logic_explanation\": \"脚本首先在 VM 上加载本地快照文件 /home/user/prof26_access_approval_001.json。若加载失败(文件不存在、解析错误或格式不对),直接输出 CRITICAL 并返回 0.0。加载成功后,依次执行三个组件检查:组件1验证第5行(A5-I5)的9个单元格是否完全匹配预期的 IAR-312 记录,权重0.70;组件2验证快照中恰好有45个单元格(即只有1-5行)且第2-4行的全部27个字段保持原样,权重0.20;组件3验证A列请求ID从A2到A5依次为IAR-309到IAR-312,且A6为空以确保无重复或额外行,权重0.10。每个组件通过时获得对应权重分数,失败则得0分。三个组件得分累加后,用 min(total_score, 1.0) 钳制上限,四舍五入到4位小数作为最终 REWARD 返回。\",\n \"confidence\": 1.0\n}\n```\n\n检查格式要求:\n- 只输出 JSON 对象\n- 不要输出 Markdown 代码块标记\n- 不要输出额外解释\n- 不要输出思考过程\n- 不要输出 thinking 标签\n- 第一个字符必须是 {,最后一个字符必须是 }\n- 所有字符串 value 使用中文;task_id、domain、字段名、代码标识符保留原样\n\n看起来都符合。 </think> {\"task_id\":\"prof26_access_approval_001\",\"domain\":\"mock_websites\",\"summary\":\"验证在 Google Sheets 的 Approvals 工作表中是否正确添加了 IAR-312 的新行(第5行),且现有行未被修改,无重复或额外行\",\"is_placeholder\":false,\"data_sources\":[\"/home/user/prof26_access_approval_001.json\"],\"scoring_components\":[{\"name\":\"Component 1\",\"weight\":0.7,\"description\":\"检查新添加的第5行是否完全填充了9个预期值\",\"check_logic\":\"遍历列 A 到 I,检查 cells.get(f'{col}5', {}).get('value') 是否等于 EXPECTED_ROW5 中对应列的值;若全部匹配则通过,否则列出缺失或不匹配的单元格\",\"pass_condition\":\"A5 到 I5 全部存在且值与 EXPECTED_ROW5 完全一致\"},{\"name\":\"Component 2\",\"weight\":0.2,\"description\":\"检查是否只新增了一行且第2-4行保持原样\",\"check_logic\":\"先检查 len(cells) 是否等于 45;再遍历 EXPECTED_ROWS_2_4 中每个地址和预期值,检查 cells.get(addr, {}).get('value') 是否匹配\",\"pass_condition\":\"快照中恰好有 45 个单元格(行1-5 × 9列),且第2-4行的全部 27 个字段与 EXPECTED_ROWS_2_4 完全一致\"},{\"name\":\"Component 3\",\"weight\":0.1,\"description\":\"检查 IAR-312 在 A 列只出现一次且无额外行\",\"check_logic\":\"遍历 A2 到 A5,提取值组成 actual_ids,检查是否等于 EXPECTED_REQUEST_IDS;再检查 A6 的值是否为 None(即无第6行)\",\"pass_condition\":\"A2 到 A5 的请求 ID 恰好为 ['IAR-309', 'IAR-310', 'IAR-311', 'IAR-312'],且 A6 为空\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最终用 min(total_score, 1.0) 钳制到上限,并四舍五入保留4位小数\",\"failure_modes\":[\"快照文件 /home/user/prof26_access_approval_001.json 不存在\",\"快照文件解析失败或内容不是有效的 JSON\",\"快照中的 cells 字段不是字典类型\",\"第5行有任何单元格缺失或与 EXPECTED_ROW5 不匹配(组件1失败,得0分)\",\"单元格总数不是45,或第2-4行有任何字段被修改(组件2失败,得0分)\",\"A2-A5 请求 ID 列表不匹配,或 A6 不为空(组件3失败,得0分)\"],\"scoring_logic_explanation\":\"脚本首先在 VM 上加载本地快照文件 /home/user/prof26_access_approval_001.json。若加载失败(文件不存在、解析错误或 cells 不是字典),直接输出 CRITICAL 并返回 0.0。加载成功后,依次执行三个组件检查:组件1验证第5行(A5-I5)的9个单元格是否完全匹配预期的 IAR-312 记录,权重0.70;组件2验证快照中恰好有45个单元格(即只有1-5行)且第2-4行的全部27个字段保持原样,权重0.20;组件3验证A列请求ID从A2到A5依次为IAR-309到IAR-312,且A6为空以确保无重复或额外行,权重0.10。每个组件通过时获得对应权重分数,失败则得0分。三个组件得分累加后,用 min(total_score, 1.0) 钳制上限,四舍五入到4位小数作为最终 REWARD 返回。\",\"confidence\":1.0}"
52
+ }
ops_board_agenda_008/_cua_gym_vm_bridge.sh ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # CUA-Gym VM-side network fix (direct-IP mock access).
3
+ #
4
+ # Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by
5
+ # their real IDC address (http://28.7.184.198:81xx) instead of the old
6
+ # localhost:9000-9097 socat bridge, so the VM only needs two fixes:
7
+ #
8
+ # 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's
9
+ # cluster DNS, which is unreachable from QEMU SLIRP NAT
10
+ # ("Temporary failure in name resolution").
11
+ # 2. The mock host excluded from the woa http proxy — otherwise the VM's
12
+ # Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403
13
+ # from the proxy when hitting 28.7.184.198:81xx. (The old socat path never
14
+ # hit this because localhost is bypassed by default.)
15
+ #
16
+ # Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic
17
+ # OSWorld setup pipeline.
18
+ #
19
+ # Argv:
20
+ # $1 optional sudo password (default "password"; SetupController
21
+ # substitutes {CLIENT_PASSWORD} when uploaded as a cache file).
22
+ # $2 unused (kept for backward compat — was socat first port 9000).
23
+ # $3 unused (kept for backward compat — was socat last port 9097).
24
+ # $4 optional mock host IP (default 28.7.184.198).
25
+
26
+ set +e
27
+
28
+ PASS="${1:-password}"
29
+ MOCK_HOST="${4:-28.7.184.198}"
30
+ # Derive the /16 IDC subnet so future port/host tweaks on the same segment
31
+ # stay bypassed too (28.7.184.198 -> 28.7.0.0/16).
32
+ MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')"
33
+
34
+ run_root() {
35
+ echo "$PASS" | sudo -S -p "" bash -c "$1"
36
+ }
37
+
38
+ # Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2.
39
+ GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')"
40
+ GW="${GW:-10.0.2.2}"
41
+
42
+ # ─── CUA-Gym network fix (Taiji-specific) ─────────────────────────────
43
+ fix_vm_network() {
44
+ # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP
45
+ # DNS forwarder. Nothing hardcoded except the mock host above.
46
+ local GW_NET="${GW%.*}"
47
+ local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3
48
+ local OWN_CIDR
49
+ OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \
50
+ | awk '{print $4; exit}')"
51
+ local OWN_IP="${OWN_CIDR%/*}"
52
+ local OWN_NET=""
53
+ [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24"
54
+
55
+ # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps
56
+ # systemd-resolved/NetworkManager from clobbering it.
57
+ if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf
58
+ chattr +i /etc/resolv.conf 2>/dev/null || true"; then
59
+ echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})"
60
+ else
61
+ echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf"
62
+ fi
63
+
64
+ # 2) Build the proxy bypass list from detected values + the direct-IP
65
+ # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx
66
+ # reachable from inside the VM — without it the woa proxy 403s it.
67
+ local ignore_list="['localhost', '127.0.0.0/8', '${GW}'"
68
+ [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'"
69
+ [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'"
70
+ [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'"
71
+ [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'"
72
+ [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'"
73
+ ignore_list="${ignore_list}]"
74
+
75
+ # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these.
76
+ if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then
77
+ echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}"
78
+ else
79
+ echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)"
80
+ fi
81
+
82
+ # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl).
83
+ local NP="localhost,127.0.0.1,${GW}"
84
+ [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}"
85
+ [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}"
86
+ [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24"
87
+ [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}"
88
+ [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}"
89
+
90
+ for var in no_proxy NO_PROXY; do
91
+ if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then
92
+ echo "export ${var}=${NP}" >> /home/user/.bashrc
93
+ fi
94
+ done
95
+ run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \
96
+ && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \
97
+ || echo 'no_proxy=\"${NP}\"' >> /etc/environment
98
+ grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \
99
+ && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \
100
+ || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1
101
+ echo "[cua_gym_vm_bridge] no_proxy=${NP}"
102
+ }
103
+
104
+ fix_vm_network
105
+
106
+ echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed"
ops_board_agenda_008/initial_setup.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: ea_board_prep_b101
3
+ Task ID: ops_board_agenda_008
4
+ Domain: mock_websites
5
+ Mocks: google_docs_mock, notion_mock, google_calendar_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 Notion workspace, the team calendar, 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 'Board Agenda - May'; Notion workspace with pages 'Board Brief Template'; an empty Google Calendar; Slack workspace with channels #general, #random. GROUND TRUTH — the agent earns partial credit for each checkpoint: new June board agenda doc (+0.2); agenda has the template's 3 sections (+0.3); cal_new_event (+0.1); Board Meeting event (+0.1); on June 30 (+0.2); 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
+ "notion_mock": "http://28.7.184.198:8166",
24
+ "google_calendar_mock": "http://28.7.184.198:8141",
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-prev': { 'id': 'd-prev',
52
+ 'title': 'Board Agenda - May',
53
+ 'content': '<p>old</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
+ 'notion_mock': { 'user': { 'id': 'user-1',
72
+ 'name': 'Sarah Chen',
73
+ 'email': 'sarah.chen@acme.com',
74
+ 'avatar': ''},
75
+ 'workspace': { 'id': 'ws-1',
76
+ 'name': 'Acme Product',
77
+ 'icon': '',
78
+ 'members': ['user-1']},
79
+ 'pages': { 'page-tmpl': { 'id': 'page-tmpl',
80
+ 'title': 'Board Brief Template',
81
+ 'icon': '',
82
+ 'cover': None,
83
+ 'parentId': None,
84
+ 'blockIds': ['blk-t1'],
85
+ 'favorite': False,
86
+ 'createdDate': '2026-05-20T00:00:00.000Z',
87
+ 'lastEditedDate': '2026-06-05T00:00:00.000Z',
88
+ 'properties': {}}},
89
+ 'blocks': { 'blk-t1': { 'id': 'blk-t1',
90
+ 'type': 'text',
91
+ 'content': 'Standard agenda sections: '
92
+ 'Approvals, Financials, Risks.',
93
+ 'properties': {},
94
+ 'createdDate': '2026-05-20T00:00:00.000Z',
95
+ 'lastEditedDate': '2026-05-20T00:00:00.000Z'}},
96
+ 'trash': [],
97
+ 'comments': {},
98
+ 'settings': { 'appearance': 'light',
99
+ 'startWeekMonday': False,
100
+ 'fontSize': 'default'},
101
+ 'notifications': [],
102
+ 'pageOrder': ['page-tmpl'],
103
+ 'focusBlockId': None},
104
+ 'google_calendar_mock': { 'user': { 'id': 'u1',
105
+ 'username': 'Demo User',
106
+ 'email': 'demo@example.com',
107
+ 'avatar': ''},
108
+ 'calendars': [ { 'id': 'c1',
109
+ 'name': 'Personal',
110
+ 'color': '#039BE5',
111
+ 'visible': True,
112
+ 'userId': 'u1',
113
+ 'isDefault': True},
114
+ { 'id': 'c2',
115
+ 'name': 'Work',
116
+ 'color': '#33B679',
117
+ 'visible': True,
118
+ 'userId': 'u1',
119
+ 'isDefault': False}],
120
+ 'events': [],
121
+ 'view': 'week',
122
+ 'currentDate': '2026-06-08T00:00:00.000Z',
123
+ 'sidebarOpen': True,
124
+ 'settings': { 'weekStart': 0,
125
+ 'defaultDuration': 60,
126
+ 'defaultView': 'week',
127
+ 'defaultReminder': {'type': 'popup', 'minutes': 10},
128
+ 'timeFormat': '12h',
129
+ 'showWeekNumbers': False,
130
+ 'showDeclinedEvents': False}},
131
+ 'slack_mock': { 'currentUser': { 'userId': 'user_1',
132
+ 'fullName': 'John Smith',
133
+ 'displayName': 'John',
134
+ 'email': 'john.smith@company.com',
135
+ 'avatar': 'https://picsum.photos/200/200?random=1',
136
+ 'title': '',
137
+ 'status': 'online',
138
+ 'statusMessage': '',
139
+ 'statusEmoji': '',
140
+ 'timeZone': 'America/New_York'},
141
+ 'workspace': { 'workspaceId': 'ws_1',
142
+ 'workspaceName': 'Acme Corp',
143
+ 'icon': ''},
144
+ 'users': [ { 'userId': 'user_1',
145
+ 'fullName': 'John Smith',
146
+ 'displayName': 'John',
147
+ 'email': 'john.smith@company.com',
148
+ 'avatar': 'https://picsum.photos/200/200?random=1',
149
+ 'title': '',
150
+ 'status': 'online',
151
+ 'statusMessage': '',
152
+ 'statusEmoji': '',
153
+ 'timeZone': 'America/New_York'},
154
+ { 'userId': 'user_2',
155
+ 'fullName': 'Sarah Johnson',
156
+ 'displayName': 'Sarah',
157
+ 'email': 'sarah.johnson@company.com',
158
+ 'avatar': 'https://picsum.photos/200/200?random=2',
159
+ 'title': '',
160
+ 'status': 'online',
161
+ 'statusMessage': '',
162
+ 'statusEmoji': '',
163
+ 'timeZone': 'America/New_York'},
164
+ { 'userId': 'user_3',
165
+ 'fullName': 'Mike Chen',
166
+ 'displayName': 'Mike',
167
+ 'email': 'mike.chen@company.com',
168
+ 'avatar': 'https://picsum.photos/200/200?random=3',
169
+ 'title': '',
170
+ 'status': 'online',
171
+ 'statusMessage': '',
172
+ 'statusEmoji': '',
173
+ 'timeZone': 'America/New_York'},
174
+ { 'userId': 'user_4',
175
+ 'fullName': 'Lisa Park',
176
+ 'displayName': 'Lisa',
177
+ 'email': 'lisa.park@company.com',
178
+ 'avatar': 'https://picsum.photos/200/200?random=4',
179
+ 'title': '',
180
+ 'status': 'online',
181
+ 'statusMessage': '',
182
+ 'statusEmoji': '',
183
+ 'timeZone': 'America/New_York'}],
184
+ 'channels': [ { 'channelId': 'general',
185
+ 'name': 'general',
186
+ 'description': 'general channel',
187
+ 'topic': '',
188
+ 'isPrivate': False,
189
+ 'isStarred': False,
190
+ 'members': ['user_1', 'user_2', 'user_3', 'user_4'],
191
+ 'createdBy': 'user_1',
192
+ 'createdAt': '2026-01-01T10:00:00Z',
193
+ 'pinnedMessages': [],
194
+ 'unreadCount': 0},
195
+ { 'channelId': 'random',
196
+ 'name': 'random',
197
+ 'description': 'random channel',
198
+ 'topic': '',
199
+ 'isPrivate': False,
200
+ 'isStarred': False,
201
+ 'members': ['user_1', 'user_2', 'user_3', 'user_4'],
202
+ 'createdBy': 'user_1',
203
+ 'createdAt': '2026-01-01T10:00:00Z',
204
+ 'pinnedMessages': [],
205
+ 'unreadCount': 0}],
206
+ 'messages': { 'general': [ { 'messageId': 'g1',
207
+ 'senderId': 'user_2',
208
+ 'content': 'is the board agenda ready?',
209
+ 'timestamp': '2026-06-08T08:00:00Z',
210
+ 'threadId': None,
211
+ 'reactions': [],
212
+ 'attachments': [],
213
+ 'isEdited': False}],
214
+ 'random': []},
215
+ 'threads': {},
216
+ 'dms': [],
217
+ 'bookmarkedMessages': [],
218
+ 'callHistory': [],
219
+ 'settings': { 'theme': 'light',
220
+ 'notifications': 'all',
221
+ 'displayDensity': 'comfortable',
222
+ 'showAvatars': True,
223
+ 'use24Hour': False},
224
+ 'invitations': [],
225
+ 'notifications': []}}
226
+
227
+
228
+ def launch_gui(command, delay_sec=1.0):
229
+ env = os.environ.copy()
230
+ env['DISPLAY'] = ':0'
231
+ subprocess.Popen(shlex.split(command), stdin=subprocess.DEVNULL,
232
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
233
+ env=env, start_new_session=True)
234
+ time.sleep(delay_sec)
235
+
236
+
237
+ for name, url in MOCK_URLS.items():
238
+ resp = requests.post(f'{url}/post?sid={sid}',
239
+ json={'action': 'set', 'state': STATES[name]}, timeout=30)
240
+ assert resp.status_code == 200, f'{name} injection failed: {resp.text}'
241
+ go = requests.get(f'{url}/go?sid={sid}', timeout=10).json()
242
+ assert go.get('initial_state') is not None, f'{name} initial_state is None'
243
+ print(f'State injected: {name} sid={sid}')
244
+
245
+ # Open the PRIMARY app as the main window first, then open every other
246
+ # involved mock as an additional browser tab so the agent can see/reach all
247
+ # relevant apps (e.g. read the email in the Gmail tab AND post in Slack).
248
+ # Without this, secondary-app data is injected but has no on-screen entry
249
+ # point, and the agent wastes its budget hunting for a non-existent client.
250
+ launch_gui(f'google-chrome "{PRIMARY_URL}/?sid={sid}"', delay_sec=2.0)
251
+ print(f'GUI_READY: launched browser at {PRIMARY_URL}/?sid={sid}')
252
+ for _name, _url in MOCK_URLS.items():
253
+ if _url == PRIMARY_URL:
254
+ continue
255
+ launch_gui(f'google-chrome --new-tab "{_url}/?sid={sid}"', delay_sec=1.0)
256
+ print(f'Opened tab: {_name} at {_url}/?sid={sid}')
ops_board_agenda_008/reward.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: ea_board_prep_b101
3
+ Task ID: ops_board_agenda_008
4
+ Domain: mock_websites
5
+ Mocks: google_docs_mock, notion_mock, google_calendar_mock, slack_mock
6
+ Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0):
7
+ - [0.2] new June board agenda doc
8
+ - [0.3] agenda has the template's 3 sections
9
+ - [0.1] cal_new_event
10
+ - [0.1] Board Meeting event
11
+ - [0.2] on June 30
12
+ - [0.1] slack_new_msg
13
+ """
14
+ import re
15
+ import sys
16
+
17
+ import requests
18
+
19
+ MOCK_URLS = {
20
+ "google_docs_mock": "http://28.7.184.198:8142",
21
+ "notion_mock": "http://28.7.184.198:8166",
22
+ "google_calendar_mock": "http://28.7.184.198:8141",
23
+ "slack_mock": "http://28.7.184.198:8178"
24
+ }
25
+ SEED = {
26
+ "slack_mock:general": [
27
+ "g1"
28
+ ],
29
+ "slack_mock:random": []
30
+ }
31
+
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: {e}')
39
+ print('REWARD: 0.0')
40
+ sys.exit(0)
41
+
42
+ STATES = {}
43
+ for _name, _url in MOCK_URLS.items():
44
+ try:
45
+ _r = requests.get(f'{_url}/go?sid={sid}', timeout=15)
46
+ _r.raise_for_status()
47
+ STATES[_name] = _r.json()
48
+ except Exception as e:
49
+ print(f'CRITICAL: cannot fetch {_name}: {e}')
50
+ print('REWARD: 0.0')
51
+ sys.exit(0)
52
+
53
+
54
+ def cur(mock):
55
+ return (STATES.get(mock) or {}).get('current_state') or {}
56
+
57
+
58
+ def _lc(s):
59
+ return (s or '').lower()
60
+
61
+
62
+ total = 0.0
63
+
64
+ # c0: a new google doc titled about (new June board agenda doc)
65
+ c0_init = set((STATES['google_docs_mock'].get('initial_state') or {}).get('documents', {}).keys())
66
+ c0_docs = cur('google_docs_mock').get('documents') or {}
67
+ 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 ['board meeting agenda', 'board meeting agenda - june', 'board agenda - june'])]
68
+ if c0_new:
69
+ print('PASS: new June board agenda doc (0.2)')
70
+ total += 0.2
71
+ else:
72
+ print('FAIL: new June board agenda doc')
73
+
74
+ # c1: new google doc body (agenda has the template\'s 3 sections)
75
+ c1_init = set((STATES['google_docs_mock'].get('initial_state') or {}).get('documents', {}).keys())
76
+ c1_docs = cur('google_docs_mock').get('documents') or {}
77
+ 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 ['board meeting agenda', 'board agenda - june'])]
78
+ c1_txt = _lc(' '.join(d.get('content','') for d in c1_new))
79
+ if c1_new and all(t in c1_txt for t in ['approvals', 'financials', 'risks']):
80
+ print('PASS: agenda has the template\'s 3 sections (0.3)')
81
+ total += 0.3
82
+ else:
83
+ print('FAIL: agenda has the template\'s 3 sections')
84
+
85
+ # c2: a new calendar event was created
86
+ c2_init_ids = {e.get('id') for e in ((STATES['google_calendar_mock'].get('initial_state') or {}).get('events') or [])}
87
+ c2_new = [e for e in (cur('google_calendar_mock').get('events') or []) if e.get('id') not in c2_init_ids]
88
+ globals()['cal_new_events'] = c2_new
89
+ if c2_new:
90
+ print('PASS: new calendar event (0.1)')
91
+ total += 0.1
92
+ else:
93
+ print('FAIL: no new calendar event')
94
+
95
+ # c3: new event title (Board Meeting event)
96
+ c3_new = globals().get('cal_new_events', [])
97
+ if any(any(t in _lc(e.get('title','')) for t in ['board meeting']) for e in c3_new):
98
+ print('PASS: Board Meeting event (0.1)')
99
+ total += 0.1
100
+ else:
101
+ print('FAIL: Board Meeting event')
102
+
103
+ # c4: new event date contains '2026-06-30'
104
+ c4_new = globals().get('cal_new_events', [])
105
+ if any('2026-06-30' in (e.get('start','') or '') for e in c4_new):
106
+ print('PASS: on June 30 (0.2)')
107
+ total += 0.2
108
+ else:
109
+ print('FAIL: on June 30')
110
+
111
+ # c5: new message by user_1 in #general
112
+ c5_msgs = (cur('slack_mock').get('messages') or {}).get('general', []) or []
113
+ c5_seed = set(SEED.get('slack_mock:general', []))
114
+ c5_new = [m for m in c5_msgs if m.get('messageId') not in c5_seed and m.get('senderId') == 'user_1']
115
+ c5_blob = _lc(' '.join((m.get('content') or '') for m in c5_new))
116
+ if c5_new:
117
+ print('PASS: new message by user_1 in #general (0.1)')
118
+ total += 0.1
119
+ else:
120
+ print('FAIL: no new user_1 message in #general')
121
+
122
+ final = round(min(total, 1.0), 4)
123
+ print(f'\nScore: {total}/1.0')
124
+ print(f'REWARD: {final}')
ops_board_agenda_008/reward_label.json ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/2ae6814e-a7b8-5f0e-b574-5dd99095d0bf/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:18:50",
7
+ "label": {
8
+ "task_id": "ops_board_agenda_008",
9
+ "domain": "mock_websites",
10
+ "summary": "验证用户是否创建了6月董事会会议议程文档、在日历中创建了6月30日的董事会会议事件,并在Slack #general频道发送了新消息",
11
+ "is_placeholder": false,
12
+ "data_sources": [
13
+ "/tmp/task_web_sid",
14
+ "google_docs_mock",
15
+ "notion_mock",
16
+ "google_calendar_mock",
17
+ "slack_mock"
18
+ ],
19
+ "scoring_components": [
20
+ {
21
+ "name": "c0: new June board agenda doc",
22
+ "weight": 0.2,
23
+ "description": "检查是否在 Google Docs 中创建了新的6月董事会会议议程文档",
24
+ "check_logic": "对比 google_docs_mock 的 initial_state 与 current_state 中的 documents,筛选出新增文档(id 不在初始集合中),并检查其标题(不区分大小写)是否包含 'board meeting agenda'、'board meeting agenda - june' 或 'board agenda - june'",
25
+ "pass_condition": "存在新增文档且标题匹配上述任一关键词"
26
+ },
27
+ {
28
+ "name": "c1: agenda has the template's 3 sections",
29
+ "weight": 0.3,
30
+ "description": "检查新创建的议程文档是否包含模板的三个部分",
31
+ "check_logic": "在新增文档中筛选标题(不区分大小写)包含 'board meeting agenda' 或 'board agenda - june' 的文档,将其 content 拼接并转小写,检查是否同时包含 'approvals'、'financials'、'risks'",
32
+ "pass_condition": "存在新增议程文档且其内容同时包含 approvals、financials、risks 三个关键词"
33
+ },
34
+ {
35
+ "name": "c2: cal_new_event",
36
+ "weight": 0.1,
37
+ "description": "检查是否在 Google Calendar 中创建了新事件",
38
+ "check_logic": "对比 google_calendar_mock 的 initial_state 与 current_state 中的 events,按事件 id 判断是否有新增事件,并将新事件列表存入全局变量 cal_new_events",
39
+ "pass_condition": "存在至少一个 id 不在初始状态中的新事件"
40
+ },
41
+ {
42
+ "name": "c3: Board Meeting event",
43
+ "weight": 0.1,
44
+ "description": "检查新创建的事件标题是否为董事会会议",
45
+ "check_logic": "读取 cal_new_events 中的新事件,检查任一事件的标题(不区分大小写)是否包含 'board meeting'",
46
+ "pass_condition": "至少一个新事件的标题包含 'board meeting'"
47
+ },
48
+ {
49
+ "name": "c4: on June 30",
50
+ "weight": 0.2,
51
+ "description": "检查新事件是否安排在2026年6月30日",
52
+ "check_logic": "读取 cal_new_events 中的新事件,检查任一事件的 start 字段字符串是否包含 '2026-06-30'",
53
+ "pass_condition": "至少一个新事件的 start 字段包含 '2026-06-30'"
54
+ },
55
+ {
56
+ "name": "c5: slack_new_msg",
57
+ "weight": 0.1,
58
+ "description": "检查 user_1 是否在 Slack #general 频道发送了新消息",
59
+ "check_logic": "获取 slack_mock current_state 中 general 频道的消息列表,排除 SEED 中预置的消息(messageId 不在 seed 集合中),筛选 senderId 为 'user_1' 的消息",
60
+ "pass_condition": "存在至少一条 senderId 为 'user_1' 且 messageId 不在初始 SEED 中的新消息"
61
+ }
62
+ ],
63
+ "total_max_score": 1.0,
64
+ "score_aggregation": "各组件分数相加,最后通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数作为最终 REWARD",
65
+ "failure_modes": [
66
+ "读取 /tmp/task_web_sid 失败或内容为空时,打印 CRITICAL 并输出 REWARD: 0.0 后退出",
67
+ "请求任一 mock 服务(google_docs_mock、notion_mock、google_calendar_mock、slack_mock)的 current_state 失败时,打印 CRITICAL 并输出 REWARD: 0.0 后退出",
68
+ "各评分组件检查失败仅导致该组件不得分,不会提前退出或导致总分归零"
69
+ ],
70
+ "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向四个 mock 服务请求当前状态。若 sid 读取失败或任一 mock 状态获取失败,脚本立即输出 0.0 并退出。获取状态后,脚本按顺序执行 6 项评分检查:1)检查 Google Docs 中是否新增了标题匹配董事会会议议程的文档(0.2分);2)检查该新文档内容是否同时包含 approvals、financials、risks 三个部分(0.3分);3)检查 Google Calendar 是否新增了事件(0.1分);4)检查新事件标题是否包含 Board Meeting(0.1分);5)检查新事件日期是否为 2026-06-30(0.2分);6)检查 Slack #general 频道是否有 user_1 发送的新消息(0.1分)。每项通过则累加对应分数,最终���分经 min(total, 1.0) 钳制并四舍五入到 4 位小数后作为 REWARD 输出。",
71
+ "confidence": 1.0
72
+ },
73
+ "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码:\n\n1. 文件路径和 docstring:\n - Reward Script: ea_board_prep_b101\n - Task ID: 2ae6814e-a7b8-5f0e-b574-5dd99095d0bf\n - Domain: mock_websites\n - Mocks: google_docs_mock, notion_mock, google_calendar_mock, slack_mock\n - Scoring total = 1.0\n\n2. 数据源:\n - 从 /tmp/task_web_sid 读取 sid\n - 从 MOCK_URLS 获取各个 mock 的 current_state:\n - google_docs_mock\n - notion_mock (虽然获取了状态,但评分中似乎没有用到)\n - google_calendar_mock\n - slack_mock\n\n3. 评分组件:\n - c0: 0.2 - new June board agenda doc\n - 检查 google_docs_mock 中是否有新文档(不在 initial_state 中)\n - 标题包含 'board meeting agenda', 'board meeting agenda - june', 'board agenda - june'\n - c1: 0.3 - agenda has the template's 3 sections\n - 检查新 Google Doc(标题包含 'board meeting agenda' 或 'board agenda - june')\n - 内容包含 'approvals', 'financials', 'risks'\n - c2: 0.1 - cal_new_event\n - 检查 google_calendar_mock 中是否有新事件(id 不在 initial_state 中)\n - c3: 0.1 - Board Meeting event\n - 检查新事件标题包含 'board meeting'\n - c4: 0.2 - on June 30\n - 检查新事件 start 日期包含 '2026-06-30'\n - c5: 0.1 - slack_new_msg\n - 检查 slack_mock #general 频道中 user_1 发送的新消息(不在 SEED 中)\n\n4. 分数汇总:\n - 各组件分数相加\n - 最后 min(total, 1.0) 并 round 到 4 位小数\n\n5. 失败模式:\n - 读取 sid 失败 -> 0.0 退出\n - 获取任何 mock 状态失败 -> 0.0 退出\n - 各组件检查失败只是不加分,不会提前退出\n\n6. 是否是占位脚本:\n - 不是,有详细的检查逻辑\n\n7. confidence:\n - 1.0,代码逻辑清晰\n\n现在构建 JSON:\n\ntask_id: \"2ae6814e-a7b8-5f0e-b574-5dd99095d0bf\"\ndomain: \"mock_websites\"\nsummary: \"验证用户是否创建了6月董事会会议议程文档、在日历中创建了6月30日的董事会会议事件,并在Slack #general频道发送了新消息\"\nis_placeholder: false\ndata_sources: [\"/tmp/task_web_sid\", \"google_docs_mock\", \"google_calendar_mock\", \"slack_mock\", \"notion_mock\"]\nscoring_components: [\n {\n \"name\": \"c0: new June board agenda doc\",\n \"weight\": 0.2,\n \"description\": \"检查是否在 Google Docs 中创建了新的6月董事会会议议程文档\",\n \"check_logic\": \"对比 initial_state 和 current_state 的 documents,找出新增文档,检查标题(不区分大小写)是否包含 'board meeting agenda'、'board meeting agenda - june' 或 'board agenda - june'\",\n \"pass_condition\": \"存在新增文档且标题匹配上述关键词之一\"\n },\n {\n \"name\": \"c1: agenda has the template's 3 sections\",\n \"weight\": 0.3,\n \"description\": \"检查新创建的议程文档是否包含模板的三个部分\",\n \"check_logic\": \"在新增议程文档(标题匹配 c0 条件)的内容中,不区分大小写地检查是否同时包含 'approvals'、'financials' 和 'risks'\",\n \"pass_condition\": \"存在新增议程文档且其内容同时包含 approvals、financials、risks 三个关键词\"\n },\n {\n \"name\": \"c2: cal_new_event\",\n \"weight\": 0.1,\n \"description\": \"检查是否在 Google Calendar 中创建了新事件\",\n \"check_logic\": \"对比 initial_state 和 current_state 的 events,按事件 id 判断是否新增事件\",\n \"pass_condition\": \"存在 id 不在初始状态中的新事件\"\n },\n {\n \"name\": \"c3: Board Meeting event\",\n \"weight\": 0.1,\n \"description\": \"检查新创建的事件标题是否为董事会会议\",\n \"check_logic\": \"在 c2 识别出的新事件中,检查标题(不区分大小写)是否包含 'board meeting'\",\n \"pass_condition\": \"至少一个新事件的标题包含 'board meeting'\"\n },\n {\n \"name\": \"c4: on June 30\",\n \"weight\": 0.2,\n \"description\": \"检查新事件是否安排在2026年6月30日\",\n \"check_logic\": \"在 c2 识别出的新事件中,检查 start 字段是否包含 '2026-06-30'\",\n \"pass_condition\": \"至少一个新事件的 start 字段包含 '2026-06-30'\"\n },\n {\n \"name\": \"c5: slack_new_msg\",\n \"weight\": 0.1,\n \"description\": \"检查 user_1 是否在 Slack #general 频道发送了新消息\",\n \"check_logic\": \"获取 slack_mock current_state 中 general 频道的消息,排除 SEED 中预置的消息(messageId 不在 seed 中),检查 senderId 是否为 'user_1'\",\n \"pass_condition\": \"存在至少一条 senderId 为 'user_1' 且 messageId 不在 seed 中的新消息\"\n }\n]\ntotal_max_score: 1.0\nscore_aggregation: \"各组件分数相加,最后通过 min(total, 1.0) 钳制��上限 1.0,并四舍五入到 4 位小数\"\nfailure_modes: [\n \"读取 /tmp/task_web_sid 失败或为空时,打印 CRITICAL 并返回 0.0 退出\",\n \"请求任一 mock 服务(google_docs_mock、notion_mock、google_calendar_mock、slack_mock)的 current_state 失败时,打印 CRITICAL 并返回 0.0 退出\",\n \"各评分组件检查失败仅导致该组件不得分,不会提前退出\"\n]\nscoring_logic_explanation: \"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向 google_docs_mock、notion_mock、google_calendar_mock、slack_mock 四个 mock 服务请求当前状态。若 sid 读取失败或任一 mock 状态获取失败,脚本立即输出 0.0 并退出。获取状态后,脚本按顺序执行 6 项评分检查:1)检查 Google Docs 中是否新增了标题匹配董事会会议议程的文档(0.2分);2)检查该新文档内容是否同时包含 approvals、financials、risks 三个部分(0.3分);3)检查 Google Calendar 是否新增了事件(0.1分);4)检查新事件标题是否包含 Board Meeting(0.1分);5)检查新事件日期是否为 2026-06-30(0.2分);6)检查 Slack #general 频道是否有 user_1 发送的新消息(0.1分)。每项通过则累加对应分数,最终总分经 min(total, 1.0) 钳制并四舍五入后作为 REWARD 输出。\"\nconfidence: 1.0\n\n检查 JSON 格式要求:\n- 不要输出 Markdown 代码块标记\n- 不要输出额外解释\n- 不要输出思考过程\n- 不要输出 <thinking> 标签\n- 第一个字符必须是 {,最后一个字符必须是 }\n- 所有字符串 value 使用中文;task_id、domain、字段名、代码标识符保留原样\n\n让我再检查一下 notion_mock 是否在评分中被使用。代码中确实获取了 notion_mock 的状态,但评分逻辑中没有使用它。不过 data_sources 应该列出脚本获取状态的数据源,所以应该包含 notion_mock。\n\n再检查一下 c1 的标题匹配条件:代码中是 `['board meeting agenda', 'board agenda - june']`,比 c0 少了一个 'board meeting agenda - june'。我需要准确反映这一点。\n\nc0: `['board meeting agenda', 'board meeting agenda - june', 'board agenda - june']`\nc1: `['board meeting agenda', 'board agenda - june']`\n\nc5 的 SEED 检查:代码中 `c5_seed = set(SEED.get('slack_mock:general', []))`,然后 `m.get('messageId') not in c5_seed`。\n\n最终输出应该是一个纯 JSON。 </think> {\"task_id\":\"2ae6814e-a7b8-5f0e-b574-5dd99095d0bf\",\"domain\":\"mock_websites\",\"summary\":\"验证用户是否创建了6月董事会会议议程文档、在日历中创建了6月30日的董事会会议事件,并在Slack #general频道发送了新消息\",\"is_placeholder\":false,\"data_sources\":[\"/tmp/task_web_sid\",\"google_docs_mock\",\"notion_mock\",\"google_calendar_mock\",\"slack_mock\"],\"scoring_components\":[{\"name\":\"c0: new June board agenda doc\",\"weight\":0.2,\"description\":\"检查是否在 Google Docs 中创建了新的6月董事会会议议程文档\",\"check_logic\":\"对比 google_docs_mock 的 initial_state 与 current_state 中的 documents,筛选出新增文档(id 不在初始集合中),并检查其标题(不区分大小写)是否包含 'board meeting agenda'、'board meeting agenda - june' 或 'board agenda - june'\",\"pass_condition\":\"存在新增文档且标题匹配上述任一关键词\"},{\"name\":\"c1: agenda has the template's 3 sections\",\"weight\":0.3,\"description\":\"检查新创建的议程文档是否包含模板的三个部分\",\"check_logic\":\"在新增文档中筛选标题(不区分大小写)包含 'board meeting agenda' 或 'board agenda - june' 的文档,将其 content 拼接并转小写,检查是否同时包含 'approvals'、'financials'、'risks'\",\"pass_condition\":\"存在新增议程文档且其内容同时包含 approvals、financials、risks 三个关键词\"},{\"name\":\"c2: cal_new_event\",\"weight\":0.1,\"description\":\"检查是否在 Google Calendar 中创建了新事件\",\"check_logic\":\"对比 google_calendar_mock 的 initial_state 与 current_state 中的 events,按事件 id 判断是否有新增事件,并将新事件列表存入全局变量 cal_new_events\",\"pass_condition\":\"存在至少一个 id 不在初始状态中的新事件\"},{\"name\":\"c3: Board Meeting event\",\"weight\":0.1,\"description\":\"检查新创建的事件标题是否为董事会会议\",\"check_logic\":\"读取 cal_new_events 中的新事件,检查任一事件的标题(不区分大小写)是否包含 'board meeting'\",\"pass_condition\":\"至少一个新事件的标题包含 'board meeting'\"},{\"name\":\"c4: on June 30\",\"weight\":0.2,\"description\":\"检查新事件是否安排在2026年6月30日\",\"check_logic\":\"读取 cal_new_events 中的新事件,检查任一事件的 start 字段字符串是否包含 '2026-06-30'\",\"pass_condition\":\"至少一个新事件的 start 字段包含 '2026-06-30'\"},{\"name\":\"c5: slack_new_msg\",\"weight\":0.1,\"description\":\"检查 user_1 是否在 Slack #general 频���发送了新消息\",\"check_logic\":\"获取 slack_mock current_state 中 general 频道的消息列表,排除 SEED 中预置的消息(messageId 不在 seed 集合中),筛选 senderId 为 'user_1' 的消息\",\"pass_condition\":\"存在至少一条 senderId 为 'user_1' 且 messageId 不在初始 SEED 中的新消息\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最后通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到 4 位小数作为最终 REWARD\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或内容为空时,打印 CRITICAL 并输出 REWARD: 0.0 后退出\",\"请求任一 mock 服务(google_docs_mock、notion_mock、google_calendar_mock、slack_mock)的 current_state 失败时,打印 CRITICAL 并输出 REWARD: 0.0 后退出\",\"各评分组件检查失败仅导致该组件不得分,不会提前退出或导致总分归零\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,然后依次向四个 mock 服务请求当前状态。若 sid 读取失败或任一 mock 状态获取失败,脚本立即输出 0.0 并退出。获取状态后,脚本按顺序执行 6 项评分检查:1)检查 Google Docs 中是否新增了标题匹配董事会会议议程的文档(0.2分);2)检查该新文档内容是否同时包含 approvals、financials、risks 三个部分(0.3分);3)检查 Google Calendar 是否新增了事件(0.1分);4)检查新事件标题是否包含 Board Meeting(0.1分);5)检查新事件日期是否为 2026-06-30(0.2分);6)检查 Slack #general 频道是否有 user_1 发送的新消息(0.1分)。每项通过则累加对应分数,最终总分经 min(total, 1.0) 钳制并四舍五入到 4 位小数后作为 REWARD 输出。\",\"confidence\":1.0}"
74
+ }
ops_catalog_update_003__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"
ops_catalog_update_003__long/initial_setup.py ADDED
@@ -0,0 +1,634 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: Product-listing review with a must-read listing standard & completeness bonus
3
+ Task ID: ops_catalog_update_003__long (output/0707 #25, cluster F / commerce)
4
+ Mocks: shopify_admin_mock, google_docs_mock, google_sheets_mock, slack_mock
5
+
6
+ The agent is a catalog manager reviewing draft products and publishing the ready ones in
7
+ Shopify Admin per a LISTING STANDARD -- NOT in the instruction:
8
+
9
+ * lever g/j (MUST-READ doc): the publish checklist + the product-type -> collection mapping
10
+ live in the google_docs 'Product Listing Standard' page (the Slack #catalog pin points to
11
+ it). A draft product may be published (status active) only if it has an image, a non-empty
12
+ description, at least one variant priced > 0, and a productType. When publishing, the item
13
+ is assigned to a collection by the doc's product-type -> collection mapping.
14
+ * lever i (bulk + keep-group): 12 products. 7 draft & ready-to-publish; 3 draft but FAIL the
15
+ checklist (missing image / description / price -> leave draft); 2 already active (keep).
16
+ Publishing an incomplete/keep product, or logging a wrong collection, lowers F1 / field
17
+ correctness. Denominator = the 7.
18
+ * lever j (completeness bonus): a 0.10 bonus awarded ONLY if the core review subtotal >= 0.60
19
+ (like OSW2 070), rewarding full coverage of the ready set.
20
+
21
+ Publish = set product.status 'active'. The agent logs a "Listing Log" register
22
+ (Product, ProductType, Collection) and posts a summary to #catalog.
23
+
24
+ GROUND TRUTH: google_sheets._task_adapter (expected_log, ready_ids, type_by_id, collection_by_id,
25
+ incomplete_ids, keep_ids, completeness_*) + shopify.products[*]._lst.
26
+ Observable results ship ABSENT (Rule 3): ready products status 'draft', Listing Log header-only,
27
+ no summary.
28
+
29
+ SCORING (HIDDEN_STATE_DIFFICULTY.md §3 positive form): "don't publish incomplete/keep" is an F1
30
+ PRECISION denominator; the completeness bonus is a POSITIVE add gated on a subtotal (like OSW2
31
+ 070), NOT a penalty; total stays in [0,1]. No hard gate, no LLM judge.
32
+ """
33
+ import os
34
+ import shlex
35
+ import subprocess
36
+ import time
37
+ import uuid
38
+
39
+ import requests
40
+
41
+
42
+ sid = str(uuid.uuid4())
43
+ with open('/tmp/task_web_sid', 'w', encoding='utf-8') as f:
44
+ f.write(sid)
45
+ print(f'Generated sid: {sid}')
46
+
47
+
48
+ COMPLETENESS_THRESHOLD = 0.60
49
+ COMPLETENESS_BONUS = 0.10
50
+
51
+ # product-type -> collection mapping (lives in the google_docs standard)
52
+ TYPE_TO_COLLECTION = {
53
+ 'Shirts': 'Apparel',
54
+ 'Hoodies': 'Apparel',
55
+ 'Mugs': 'Drinkware',
56
+ 'Bottles': 'Drinkware',
57
+ 'Bags': 'Accessories',
58
+ 'Hats': 'Accessories',
59
+ 'Stationery': 'Office',
60
+ }
61
+
62
+
63
+ # ---------------------------------------------------------------------------
64
+ # Product spec: (pid, title, ptype, has_image, has_desc, price, kind)
65
+ # kind: 'ready' (draft, passes checklist -> publish) /
66
+ # 'incomplete' (draft, fails checklist -> leave draft) /
67
+ # 'keep' (already active)
68
+ # ---------------------------------------------------------------------------
69
+ _PROD_SPEC = [
70
+ # --- 7 draft & ready to publish (image + desc + price>0 + type) ---
71
+ ('prod_1', 'Classic Tee - Black', 'Shirts', True, True, 24.99, 'ready'),
72
+ ('prod_2', 'Classic Tee - White', 'Shirts', True, True, 24.99, 'ready'),
73
+ ('prod_3', 'Zip Hoodie - Grey', 'Hoodies', True, True, 49.00, 'ready'),
74
+ ('prod_4', 'Ceramic Mug 12oz', 'Mugs', True, True, 14.00, 'ready'),
75
+ ('prod_5', 'Steel Bottle 24oz', 'Bottles', True, True, 28.00, 'ready'),
76
+ ('prod_6', 'Canvas Tote', 'Bags', True, True, 18.00, 'ready'),
77
+ ('prod_7', 'Dad Cap - Navy', 'Hats', True, True, 22.00, 'ready'),
78
+ # --- 3 draft but FAIL the checklist (leave draft) ---
79
+ ('prod_8', 'Beanie (no image yet)', 'Hats', False, True, 20.00, 'incomplete'), # no image
80
+ ('prod_9', 'Notebook (no desc)', 'Stationery', True, False, 9.00, 'incomplete'), # no description
81
+ ('prod_10', 'Sticker Pack (no price)', 'Stationery', True, True, 0.0, 'incomplete'), # price 0
82
+ # --- 2 already active (keep) ---
83
+ ('prod_11', 'Enamel Pin', 'Accessories-legacy', True, True, 8.00, 'keep'),
84
+ ('prod_12', 'Lanyard', 'Accessories-legacy', True, True, 6.00, 'keep'),
85
+ ]
86
+
87
+
88
+ def _collection_of(ptype):
89
+ return TYPE_TO_COLLECTION.get(ptype, '')
90
+
91
+
92
+ def _passes_checklist(has_image, has_desc, price, ptype):
93
+ return bool(has_image and has_desc and price and price > 0 and ptype)
94
+
95
+
96
+ # ---------------------------------------------------------------------------
97
+ # Precompute answer key.
98
+ # ---------------------------------------------------------------------------
99
+ EXPECTED_LOG = []
100
+ READY_IDS = []
101
+ TYPE_BY_ID = {}
102
+ COLLECTION_BY_ID = {}
103
+ for (pid, title, ptype, has_image, has_desc, price, kind) in _PROD_SPEC:
104
+ if kind != 'ready':
105
+ continue
106
+ coll = _collection_of(ptype)
107
+ READY_IDS.append(pid)
108
+ TYPE_BY_ID[pid] = ptype
109
+ COLLECTION_BY_ID[pid] = coll
110
+ EXPECTED_LOG.append({'Product': title, 'ProductType': ptype, 'Collection': coll})
111
+
112
+ INCOMPLETE_IDS = [p[0] for p in _PROD_SPEC if p[6] == 'incomplete']
113
+ KEEP_IDS = [p[0] for p in _PROD_SPEC if p[6] == 'keep']
114
+ TITLE_BY_ID = {p[0]: p[1] for p in _PROD_SPEC}
115
+
116
+ assert len(READY_IDS) == 7, READY_IDS
117
+ assert len(INCOMPLETE_IDS) == 3 and len(KEEP_IDS) == 2, (INCOMPLETE_IDS, KEEP_IDS)
118
+ # every ready product passes the checklist; every incomplete fails it
119
+ for (pid, title, ptype, hi, hd, pr, kind) in _PROD_SPEC:
120
+ passes = _passes_checklist(hi, hd, pr, ptype)
121
+ if kind == 'ready':
122
+ assert passes, (pid, 'ready but fails checklist')
123
+ elif kind == 'incomplete':
124
+ assert not passes, (pid, 'incomplete but passes checklist')
125
+ print(f'Ready: {READY_IDS}; incomplete(leave draft): {INCOMPLETE_IDS}; keep: {KEEP_IDS}')
126
+
127
+
128
+ # ---------------------------------------------------------------------------
129
+ # Shopify Admin — draft products (ready in 'draft', keep in 'active') + inventory.
130
+ # NOTE (review #4): product images previously pointed at https://placehold.co/... which needs
131
+ # network access and shows broken thumbnails offline. Image URLs do NOT affect scoring (reward
132
+ # judges only status draft->active), but for offline robustness + realism we embed a tiny inline
133
+ # SVG data: URI so a real thumbnail renders with no network.
134
+ # ---------------------------------------------------------------------------
135
+ import base64 as _b64
136
+
137
+
138
+ def _img_data_uri(label):
139
+ svg = (
140
+ "<svg xmlns='http://www.w3.org/2000/svg' width='400' height='400'>"
141
+ "<rect width='400' height='400' fill='#e8f5e9'/>"
142
+ "<text x='200' y='210' font-family='sans-serif' font-size='28' fill='#2e7d32' "
143
+ "text-anchor='middle'>" + label + "</text></svg>"
144
+ )
145
+ return 'data:image/svg+xml;base64,' + _b64.b64encode(svg.encode('utf-8')).decode('ascii')
146
+
147
+
148
+ def _build_product(pid, title, ptype, has_image, has_desc, price, kind):
149
+ status = 'active' if kind == 'keep' else 'draft'
150
+ images = ([{'id': f'img_{pid}', 'src': _img_data_uri(title), 'alt': title, 'position': 1}]
151
+ if has_image else [])
152
+ body = f'<p>{title} — premium quality.</p>' if has_desc else ''
153
+ return {
154
+ 'id': pid, 'title': title, 'bodyHtml': body, 'vendor': 'Evergreen',
155
+ 'productType': ptype, 'handle': pid, 'status': status, 'tags': [], 'images': images,
156
+ 'variants': [{'id': f'var_{pid}', 'productId': pid, 'title': 'Default',
157
+ 'price': f'{price:.2f}', 'compareAtPrice': None, 'sku': pid.upper(),
158
+ 'inventoryQuantity': 50, 'option1': 'Default', 'option2': None, 'position': 1}],
159
+ 'options': [{'id': f'opt_{pid}', 'name': 'Title', 'position': 1, 'values': ['Default']}],
160
+ 'collections': [], 'createdAt': '2026-04-20T10:00:00Z', 'updatedAt': '2026-04-29T14:30:00Z',
161
+ '_lst': {'kind': kind, 'title': title, 'ptype': ptype,
162
+ 'collection': _collection_of(ptype) if kind == 'ready' else ''},
163
+ }
164
+
165
+
166
+ _PRODUCTS = [_build_product(*spec) for spec in _PROD_SPEC]
167
+
168
+ _SHOPIFY_STATE = {
169
+ 'store': {'id': 'store_1', 'name': 'Evergreen Goods', 'email': 'admin@evergreengoods.com',
170
+ 'phone': '', 'domain': 'evergreengoods.myshopify.com', 'customDomain': '',
171
+ 'address': '', 'currency': 'USD', 'timezone': '(GMT-08:00) Pacific Time',
172
+ 'weightUnit': 'lb', 'plan': 'Basic Shopify',
173
+ 'owner': {'firstName': 'Nadia', 'lastName': 'Farouk', 'email': 'nadia@evergreengoods.com'},
174
+ 'createdAt': '2024-01-01T00:00:00Z'},
175
+ 'products': _PRODUCTS,
176
+ 'collections': [
177
+ {'id': 'col_apparel', 'title': 'Apparel', 'bodyHtml': '', 'handle': 'apparel',
178
+ 'collectionType': 'manual', 'productIds': [], 'productsCount': 0, 'sortOrder': 'manual',
179
+ 'publishedAt': '2026-01-01T00:00:00Z', 'updatedAt': '2026-01-01T00:00:00Z', 'image': None},
180
+ {'id': 'col_drinkware', 'title': 'Drinkware', 'bodyHtml': '', 'handle': 'drinkware',
181
+ 'collectionType': 'manual', 'productIds': [], 'productsCount': 0, 'sortOrder': 'manual',
182
+ 'publishedAt': '2026-01-01T00:00:00Z', 'updatedAt': '2026-01-01T00:00:00Z', 'image': None},
183
+ {'id': 'col_accessories', 'title': 'Accessories', 'bodyHtml': '', 'handle': 'accessories',
184
+ 'collectionType': 'manual', 'productIds': [], 'productsCount': 0, 'sortOrder': 'manual',
185
+ 'publishedAt': '2026-01-01T00:00:00Z', 'updatedAt': '2026-01-01T00:00:00Z', 'image': None},
186
+ {'id': 'col_office', 'title': 'Office', 'bodyHtml': '', 'handle': 'office',
187
+ 'collectionType': 'manual', 'productIds': [], 'productsCount': 0, 'sortOrder': 'manual',
188
+ 'publishedAt': '2026-01-01T00:00:00Z', 'updatedAt': '2026-01-01T00:00:00Z', 'image': None},
189
+ ],
190
+ 'orders': [], 'customers': [], 'discounts': [], 'draftOrders': [], 'giftCards': [],
191
+ 'analytics': {'dailyMetrics': [], 'totalSalesThisMonth': 0, 'totalOrdersThisMonth': 0,
192
+ 'totalSessionsThisMonth': 0},
193
+ 'pages': [], 'blogPosts': [], 'navigationMenus': [],
194
+ 'settings': {'storeName': 'Evergreen Goods', 'storeEmail': 'admin@evergreengoods.com',
195
+ 'currency': 'USD', 'timezone': '(GMT-08:00) Pacific Time', 'weightUnit': 'lb'},
196
+ '_task_adapter': {'source_schema': 'listing_review',
197
+ 'task_id': 'b8d2ef43-0c4a-4e9f-da71-0707ddee7788'},
198
+ }
199
+
200
+
201
+ # ---------------------------------------------------------------------------
202
+ # google_docs — the must-read 'Product Listing Standard' (lever j) + a decoy.
203
+ # NOTE (review #2): google_docs_mock renders each doc card via
204
+ # format(new Date(doc.updated), ...) and sorts on doc.created/doc.updated. If those fields are
205
+ # absent (we previously used createdAt/modifiedAt), date-fns throws "Invalid time value" and the
206
+ # whole document list crashes to a blank screen -> search finds nothing. So use created/updated.
207
+ # ---------------------------------------------------------------------------
208
+ def _standard_html():
209
+ rows = ''.join(f'<li>{t} &rarr; {c}</li>' for t, c in TYPE_TO_COLLECTION.items())
210
+ return (
211
+ '<h1>Product Listing Standard</h1>'
212
+ '<h2>Publish checklist</h2>'
213
+ '<p>A draft product may be published (set status Active) ONLY if it has ALL of:</p>'
214
+ '<ul><li>at least one product image</li>'
215
+ '<li>a non-empty description</li>'
216
+ '<li>at least one variant with a price greater than 0</li>'
217
+ '<li>a product type assigned</li></ul>'
218
+ '<p>If any item is missing, leave the product as a draft.</p>'
219
+ '<h2>Collection assignment (by product type)</h2>'
220
+ f'<ul>{rows}</ul>'
221
+ '<p>When you publish a product, assign it to the collection its product type maps to above.</p>'
222
+ )
223
+
224
+
225
+ _DOCS_STATE = {
226
+ 'user': {'id': 'user-1', 'name': 'Nadia Farouk', 'email': 'nadia@evergreengoods.com'},
227
+ 'documents': {
228
+ 'doc-standard': {'id': 'doc-standard', 'title': 'Product Listing Standard',
229
+ 'content': _standard_html(), 'ownerId': 'user-1', 'starred': True,
230
+ 'created': '2026-01-05T09:00:00Z', 'updated': '2026-03-01T09:00:00Z',
231
+ 'sharedWith': [], 'linkSharing': {'enabled': False}},
232
+ 'doc-decoy': {'id': 'doc-decoy', 'title': 'Brand Voice Guide',
233
+ 'content': '<h1>Brand Voice</h1><p>Friendly and concise.</p>',
234
+ 'ownerId': 'user-1', 'starred': False, 'created': '2026-02-01T09:00:00Z',
235
+ 'updated': '2026-02-01T09:00:00Z', 'sharedWith': [],
236
+ 'linkSharing': {'enabled': False}},
237
+ },
238
+ 'comments': [],
239
+ 'ui': {'currentDocId': None, 'documentListView': 'grid', 'searchQuery': ''},
240
+ }
241
+
242
+
243
+ # ---------------------------------------------------------------------------
244
+ # Google Sheet — 'Listing Log' register (header only) + answer key.
245
+ # ---------------------------------------------------------------------------
246
+ REG_HEADERS = ['Product', 'ProductType', 'Collection']
247
+ _HEADER_STYLE = {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}
248
+
249
+
250
+ def _header_cell(text):
251
+ return {'value': text, 'formula': text, 'computed': text, 'style': dict(_HEADER_STYLE)}
252
+
253
+
254
+ _reg_data = {}
255
+ for col_idx, header in enumerate(REG_HEADERS):
256
+ _reg_data[f'{chr(ord("A") + col_idx)}1'] = _header_cell(header)
257
+
258
+
259
+ _SHEET_STATE = {
260
+ 'id': 'workbook_listing', 'title': 'Catalog Workbook',
261
+ 'activeSheetId': 'sheet_reg', 'selectedCell': 'A1', 'selectionRange': None,
262
+ 'clipboard': None, 'isDragging': False, 'undoStack': [], 'redoStack': [],
263
+ 'namedRanges': [], 'conditionalFormats': [], 'charts': [], 'showGridlines': True,
264
+ 'showFormulas': False, 'zoom': 100,
265
+ 'sheets': [{
266
+ 'id': 'sheet_reg', 'name': 'Listing Log', 'data': _reg_data,
267
+ 'rowCount': 100, 'colCount': 26, 'frozenRows': 1, 'frozenCols': 0,
268
+ 'tabColor': None, 'isHidden': False, 'columnWidths': {}, 'rowHeights': {},
269
+ 'filterRange': None, 'filterCriteria': {}, 'sortColumn': None, 'sortDirection': None,
270
+ }],
271
+ '_task_adapter': {
272
+ 'source_schema': 'listing_review',
273
+ 'task_id': 'b8d2ef43-0c4a-4e9f-da71-0707ddee7788',
274
+ 'variant': 'eval',
275
+ 'target_sheet': 'Listing Log',
276
+ 'headers': REG_HEADERS,
277
+ 'headers_by_sheet': {'Listing Log': REG_HEADERS},
278
+ 'sheet_names': ['Listing Log'],
279
+ 'published_status': 'active',
280
+ # ---- ANSWER KEY ----
281
+ 'expected_log': EXPECTED_LOG,
282
+ 'ready_ids': READY_IDS,
283
+ 'type_by_id': TYPE_BY_ID,
284
+ 'collection_by_id': COLLECTION_BY_ID,
285
+ 'title_by_id': TITLE_BY_ID,
286
+ 'incomplete_ids': INCOMPLETE_IDS,
287
+ 'keep_ids': KEEP_IDS,
288
+ 'type_to_collection': TYPE_TO_COLLECTION,
289
+ 'completeness_threshold': COMPLETENESS_THRESHOLD,
290
+ 'completeness_bonus': COMPLETENESS_BONUS,
291
+ 'catalog_channel': 'catalog',
292
+ },
293
+ }
294
+
295
+
296
+ # ---------------------------------------------------------------------------
297
+ # Slack — #catalog pin pointing to the listing standard (lever j pointer).
298
+ # Review #1: give every user fullName+displayName (slack_mock renders authors via
299
+ # users[].userId -> fullName else displayName else "Unknown User"); add extra channels +
300
+ # harmless chatter so #catalog looks active and the pinned note sits above real backlog.
301
+ # ---------------------------------------------------------------------------
302
+ _PIN_TEXT = (
303
+ ':pushpin: CATALOG: before publishing draft products, follow the "Product Listing Standard" '
304
+ 'doc in Google Docs — it has the publish checklist and the product-type to collection mapping. '
305
+ 'Log every product you publish in the Listing Log sheet.'
306
+ )
307
+
308
+
309
+ def _slack_user(uid, first, last):
310
+ full = f'{first} {last}'
311
+ return {'userId': uid, 'firstName': first, 'lastName': last, 'name': full,
312
+ 'fullName': full, 'displayName': full}
313
+
314
+
315
+ _SLACK_USERS = [
316
+ _slack_user('user_1', 'Nadia', 'Farouk'), # catalog manager (current user)
317
+ _slack_user('user_2', 'Dana', 'Cole'), # ops lead (posts the pin)
318
+ _slack_user('user_3', 'Theo', 'Marsh'), # merchandiser
319
+ _slack_user('user_4', 'Priya', 'Raman'), # content
320
+ ]
321
+
322
+
323
+ def _smsg(mid, ch, sender, content, ts):
324
+ return {'messageId': mid, 'senderId': sender, 'content': content, 'timestamp': ts,
325
+ 'threadId': None, 'reactions': [], 'attachments': [], 'isEdited': False}
326
+
327
+
328
+ _CATALOG_HISTORY = [
329
+ _smsg('msg_pin', 'catalog', 'user_2', _PIN_TEXT, '2026-04-01T09:00:00Z'),
330
+ _smsg('msg_c1', 'catalog', 'user_3', 'New spring drop photos are in the shared drive — 7 products staged as drafts.', '2026-04-28T10:00:00Z'),
331
+ _smsg('msg_c2', 'catalog', 'user_4', 'Descriptions written for all but the beanie; that one still needs copy.', '2026-04-29T11:15:00Z'),
332
+ _smsg('msg_c3', 'catalog', 'user_2', '@Nadia can you review the drafts and publish the ones that pass the standard today?', '2026-04-30T08:30:00Z'),
333
+ _smsg('msg_c4', 'catalog', 'user_1', 'On it — going through Shopify drafts now and will log what I publish.', '2026-04-30T08:45:00Z'),
334
+ ]
335
+
336
+ _GENERAL_HISTORY = [
337
+ _smsg('msg_g1', 'general', 'user_2', 'Welcome to Evergreen Goods :wave:', '2026-04-15T09:00:00Z'),
338
+ _smsg('msg_g2', 'general', 'user_3', 'Reminder: warehouse inventory count this Friday.', '2026-04-27T14:00:00Z'),
339
+ _smsg('msg_g3', 'general', 'user_4', 'Q2 marketing calendar is published in Docs.', '2026-04-29T16:30:00Z'),
340
+ ]
341
+
342
+ _SLACK_STATE = {
343
+ 'currentUser': _slack_user('user_1', 'Nadia', 'Farouk'),
344
+ 'users': _SLACK_USERS,
345
+ 'channels': [
346
+ {'channelId': 'general', 'name': 'general', 'description': 'Company-wide',
347
+ 'topic': 'General', 'isPrivate': False, 'isStarred': True,
348
+ 'members': [u['userId'] for u in _SLACK_USERS], 'createdBy': 'user_2',
349
+ 'createdAt': '2026-01-01T09:00:00Z', 'pinnedMessages': [], 'unreadCount': 0},
350
+ {'channelId': 'catalog', 'name': 'catalog', 'description': 'Catalog management',
351
+ 'topic': 'Listings', 'isPrivate': False, 'isStarred': True,
352
+ 'members': [u['userId'] for u in _SLACK_USERS], 'createdBy': 'user_2',
353
+ 'createdAt': '2026-01-01T10:00:00Z', 'pinnedMessages': ['msg_pin'], 'unreadCount': 0},
354
+ ],
355
+ 'messages': {
356
+ 'general': _GENERAL_HISTORY,
357
+ 'catalog': _CATALOG_HISTORY,
358
+ },
359
+ 'threads': {}, 'dms': [], 'bookmarkedMessages': [], 'callHistory': [], 'notifications': [],
360
+ }
361
+
362
+
363
+ # ---------------------------------------------------------------------------
364
+ # Inject.
365
+ # ---------------------------------------------------------------------------
366
+ APP_STATES = [
367
+ ('http://28.7.184.198:8177', _SHOPIFY_STATE), # shopify_admin_mock
368
+ ('http://28.7.184.198:8142', _DOCS_STATE), # google_docs_mock
369
+ ('http://28.7.184.198:8145', _SHEET_STATE), # google_sheets_mock
370
+ ('http://28.7.184.198:8178', _SLACK_STATE), # slack_mock
371
+ ]
372
+
373
+
374
+ for app_url, state in APP_STATES:
375
+ resp = requests.post(f'{app_url}/post?sid={sid}',
376
+ json={'action': 'set', 'state': state}, timeout=30)
377
+ assert resp.status_code == 200, f'State injection failed for {app_url}: {resp.text}'
378
+ print(f'State injected: {app_url} sid={sid}')
379
+
380
+ for app_url, _ in APP_STATES:
381
+ go_payload = requests.get(f'{app_url}/go?sid={sid}', timeout=15).json()
382
+ assert go_payload.get('initial_state') is not None, (
383
+ f'initial_state is None after injection for {app_url}')
384
+ print(f'Verified initial_state set: {app_url}')
385
+
386
+
387
+ # PATCHED_BY: patch_wait_mocks_loaded.py
388
+ def launch_gui(command, delay_sec=1.0):
389
+ """Launch a GUI command, fully detached from this script.
390
+
391
+ Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that
392
+ wait_mocks_loaded's CDP phase can verify browser render below.
393
+ Idempotent: if the caller already specified a debug port, keep it.
394
+ """
395
+ env = os.environ.copy()
396
+ env['DISPLAY'] = ':0'
397
+ if isinstance(command, str):
398
+ _parts = shlex.split(command)
399
+ else:
400
+ _parts = list(command)
401
+ if (_parts and 'google-chrome' in _parts[0]
402
+ and not any(p.startswith('--remote-debugging-port') for p in _parts)):
403
+ _parts[1:1] = [
404
+ '--no-first-run',
405
+ '--no-default-browser-check',
406
+ '--remote-debugging-port=1337',
407
+ ]
408
+ subprocess.Popen(
409
+ _parts,
410
+ stdin=subprocess.DEVNULL,
411
+ stdout=subprocess.DEVNULL,
412
+ stderr=subprocess.DEVNULL,
413
+ env=env,
414
+ start_new_session=True,
415
+ )
416
+ time.sleep(delay_sec)
417
+
418
+
419
+ def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12):
420
+ """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style.
421
+
422
+ Phase 1 - Backend readiness:
423
+ Poll each mock's /state?sid=<sid> (preferred) or /go?sid=<sid>
424
+ (fallback) until it returns 200 with 'stored_state' or
425
+ 'initial_state' respectively, or until timeout.
426
+
427
+ Phase 2 - Browser render verification (via CDP + Playwright):
428
+ Connect to http://localhost:1337 (the --remote-debugging-port
429
+ injected by launch_gui above), wait for every open tab to reach
430
+ 'networkidle' AND to contain at least 20 DOM elements. This
431
+ guarantees the SPA fetched /go?sid= data AND actually painted,
432
+ not just that the mock backend is up.
433
+
434
+ Fallback:
435
+ If Playwright is missing or CDP cannot be reached, sleep for
436
+ `render_buffer` seconds as a best-effort delay so the screenshot
437
+ loop does not start on a still-blank tab.
438
+ """
439
+ import urllib.request as _urlreq
440
+ import time as _t
441
+ _urls = [p for p, _ in app_states]
442
+ _opener = _urlreq.build_opener(_urlreq.ProxyHandler({}))
443
+
444
+ # ---- Phase 1: backend readiness ----
445
+ _deadline = _t.time() + timeout
446
+ _todo = list(_urls)
447
+ while _todo and _t.time() < _deadline:
448
+ _rest = []
449
+ for _u in _todo:
450
+ _ok = False
451
+ for _path, _need in (('/state?sid=', b'stored_state'),
452
+ ('/go?sid=', b'initial_state')):
453
+ try:
454
+ _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5)
455
+ if _r.status == 200:
456
+ _body = _r.read()
457
+ if _need in _body:
458
+ _ok = True
459
+ break
460
+ except Exception:
461
+ pass
462
+ if _ok:
463
+ print(f" {_u}: backend ready")
464
+ continue
465
+ _rest.append(_u)
466
+ _todo = _rest
467
+ if _todo:
468
+ _t.sleep(2)
469
+ _done = len(_urls) - len(_todo)
470
+ _pend = f" (pending: {_todo})" if _todo else ""
471
+ print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}")
472
+
473
+ # ---- Phase 2: browser render verification via CDP ----
474
+ _cdp_ok = False
475
+ try:
476
+ from playwright.sync_api import sync_playwright
477
+ _cdp_dl = _t.time() + max(15.0, _deadline - _t.time())
478
+ with sync_playwright() as _p:
479
+ _br = None
480
+ while _t.time() < _cdp_dl:
481
+ try:
482
+ _br = _p.chromium.connect_over_cdp('http://localhost:1337')
483
+ break
484
+ except Exception:
485
+ _t.sleep(0.5)
486
+ if _br is None:
487
+ print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?")
488
+ else:
489
+ _n_expected = len(_urls)
490
+ _pages = []
491
+ _pg_dl = _t.time() + 15
492
+ _last_count = -1
493
+ _stable_since = None
494
+ while _t.time() < _pg_dl:
495
+ _pages = []
496
+ for _c in _br.contexts:
497
+ _pages.extend(_c.pages)
498
+ _cnt = len(_pages)
499
+ if _n_expected > 0 and _cnt >= _n_expected:
500
+ break
501
+ if _cnt > 0 and _cnt == _last_count:
502
+ if _stable_since is None:
503
+ _stable_since = _t.time()
504
+ elif _t.time() - _stable_since >= 1.5:
505
+ break
506
+ else:
507
+ _stable_since = None
508
+ _last_count = _cnt
509
+ _t.sleep(0.5)
510
+ _pages = []
511
+ for _c in _br.contexts:
512
+ _pages.extend(_c.pages)
513
+ if not _pages:
514
+ print(" wait_mocks_loaded: CDP connected but no open tabs found")
515
+ else:
516
+ print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render")
517
+ _MIN_ELEMS = 20
518
+ _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap
519
+ for _pg in _pages: # bring each to front once to defeat background-tab render throttling
520
+ try:
521
+ _pg.bring_to_front()
522
+ except Exception:
523
+ pass
524
+ _pending = list(_pages)
525
+ while _pending and _t.time() < _verify_dl:
526
+ _still = []
527
+ for _pg in _pending:
528
+ _ttl = ""
529
+ try:
530
+ _ttl = _pg.title()
531
+ except Exception:
532
+ pass
533
+ try:
534
+ _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0")
535
+ except Exception:
536
+ _n = 0
537
+ if _n >= _MIN_ELEMS:
538
+ print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)")
539
+ else:
540
+ _still.append(_pg)
541
+ _pending = _still
542
+ if _pending:
543
+ _t.sleep(2)
544
+ if not _pending:
545
+ _cdp_ok = True
546
+ else:
547
+ for _pg in _pending:
548
+ _ttl = ""
549
+ try:
550
+ _ttl = _pg.title()
551
+ except Exception:
552
+ pass
553
+ print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back")
554
+ except ImportError:
555
+ print(" wait_mocks_loaded: playwright not installed; skipping CDP phase")
556
+ except Exception as _e:
557
+ print(f" wait_mocks_loaded: CDP phase error ({_e!r})")
558
+
559
+ if not _cdp_ok:
560
+ print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep")
561
+ _t.sleep(render_buffer)
562
+ else:
563
+ print(" wait_mocks_loaded: browser render verified, skipping render_buffer")
564
+
565
+
566
+ def _open_mock_tabs(app_states, sid_value):
567
+ """Open the first mock as the primary Chrome window, the rest as new tabs.
568
+
569
+ Uses launch_gui once per URL so that the macOS localizer regex-extract
570
+ (which grabs the FIRST quoted URL per call) still works correctly.
571
+ """
572
+ _urls = [p for p, _ in app_states]
573
+ if not _urls:
574
+ return
575
+ launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0)
576
+ for _u in _urls[1:]:
577
+ launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0)
578
+
579
+
580
+
581
+ # PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate)
582
+ def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0):
583
+ """Block until every mock serves injected state AND (best-effort) renders."""
584
+ import time as _t
585
+ deadline = _t.time() + timeout
586
+ pending = dict(mocks)
587
+ while pending and _t.time() < deadline:
588
+ for name in list(pending):
589
+ try:
590
+ r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5)
591
+ if r.status_code == 200 and r.json().get('initial_state') is not None:
592
+ del pending[name]
593
+ except Exception:
594
+ pass
595
+ if pending:
596
+ _t.sleep(1.0)
597
+ if pending:
598
+ print(f'WARN: mocks not ready within {timeout}s: {list(pending)}')
599
+ try:
600
+ from playwright.sync_api import sync_playwright
601
+ except ImportError:
602
+ print('WARN: playwright not installed; skipping render check, settle 3s')
603
+ _t.sleep(3.0)
604
+ return
605
+ with sync_playwright() as p:
606
+ try:
607
+ browser = p.chromium.launch(channel='chrome', headless=True,
608
+ args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'])
609
+ except Exception as e:
610
+ print(f'WARN: could not launch chrome for render check: {e}; settle 3s')
611
+ _t.sleep(3.0)
612
+ return
613
+ try:
614
+ for name, url in mocks.items():
615
+ page = browser.new_page()
616
+ try:
617
+ page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000))
618
+ page.wait_for_function(
619
+ "document.body && document.body.innerText.length > 50",
620
+ timeout=int(render_timeout * 1000))
621
+ print(f'[{name}] rendered OK')
622
+ except Exception as e:
623
+ print(f'WARN: [{name}] render check issue: {e}')
624
+ finally:
625
+ page.close()
626
+ finally:
627
+ browser.close()
628
+
629
+
630
+ # ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render
631
+ _open_mock_tabs(APP_STATES, sid)
632
+ wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15)
633
+ wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12)
634
+ print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps')
ops_catalog_update_003__long/reward.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: Product-listing review with a must-read listing standard & completeness bonus
3
+ Task ID: ops_catalog_update_003__long (output/0707 #25, cluster F / commerce)
4
+ Mocks: shopify_admin_mock, google_docs_mock, google_sheets_mock, slack_mock
5
+
6
+ Scoring — ALL positive; every component in [0,1]; core weights sum to 0.90 and ONE
7
+ completeness bonus (0.10) gated on the core subtotal >= 0.60. NO penalties, NO hard gate.
8
+
9
+ CORE (0.90):
10
+ 0.30 publish decision-set F1: true={7 ready products}; pred={products set to status active}
11
+ (publishing an incomplete/keep product = precision FP)
12
+ 0.20 product-type correctness in the log: frac of the 7 logged with correct ProductType
13
+ 0.15 collection correctness: frac of the 7 logged with correct Collection (per doc mapping)
14
+ 0.20 listing-log F1 over (Product, ProductType, Collection) for the 7
15
+ 0.05 slack #catalog summary post
16
+ BONUS (0.10), gated:
17
+ 0.10 completeness bonus, awarded ONLY if core subtotal >= 0.60 (like OSW2 070). Positive add.
18
+
19
+ Answer key: google_sheets.initial_state._task_adapter (expected_log, ready_ids, type_by_id,
20
+ collection_by_id, title_by_id, incomplete_ids, keep_ids, completeness_*, published_status) +
21
+ shopify.products[*]._lst.
22
+ """
23
+ import sys
24
+
25
+ import requests
26
+
27
+
28
+ try:
29
+ with open('/tmp/task_web_sid', encoding='utf-8') as f:
30
+ sid = f.read().strip()
31
+ if not sid:
32
+ raise ValueError('sid is empty')
33
+ except Exception as e:
34
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
35
+ print('REWARD: 0.0')
36
+ sys.exit(0)
37
+
38
+
39
+ APP_URLS = {
40
+ 'shopify': 'http://28.7.184.198:8177',
41
+ 'google_sheets': 'http://28.7.184.198:8145',
42
+ 'slack': 'http://28.7.184.198:8178',
43
+ }
44
+ _GO_CACHE = {}
45
+
46
+
47
+ def clamp01(x):
48
+ return max(0.0, min(1.0, float(x)))
49
+
50
+
51
+ def frac(num, den):
52
+ return 0.0 if den == 0 else num / den
53
+
54
+
55
+ def f1(true_set, pred_set):
56
+ if not true_set and not pred_set:
57
+ return 1.0
58
+ tp = len(true_set & pred_set)
59
+ if tp == 0:
60
+ return 0.0
61
+ prec = tp / len(pred_set)
62
+ rec = tp / len(true_set)
63
+ return 2 * prec * rec / (prec + rec)
64
+
65
+
66
+ def norm(s):
67
+ return (str(s) if s is not None else '').strip().lower()
68
+
69
+
70
+ def _s(v):
71
+ return '' if v is None else str(v).strip()
72
+
73
+
74
+ def _msg_text(m):
75
+ return m.get('content') or m.get('text') or ''
76
+
77
+
78
+ def _slack_channel_messages(slack_state, channel_name):
79
+ if not isinstance(slack_state, dict):
80
+ return []
81
+ channels = slack_state.get('channels') if isinstance(slack_state.get('channels'), list) else []
82
+ messages_map = slack_state.get('messages') if isinstance(slack_state.get('messages'), dict) else {}
83
+ out = []
84
+ for ch in channels:
85
+ if not isinstance(ch, dict) or norm(ch.get('name')) != norm(channel_name):
86
+ continue
87
+ cid = ch.get('channelId') or ch.get('id')
88
+ for m in (ch.get('messages') if isinstance(ch.get('messages'), list) else []):
89
+ if isinstance(m, dict):
90
+ out.append(m)
91
+ if cid and isinstance(messages_map.get(cid), list):
92
+ for m in messages_map[cid]:
93
+ if isinstance(m, dict):
94
+ out.append(m)
95
+ return out
96
+
97
+
98
+ def _parse_cell_id(cell_id):
99
+ if not isinstance(cell_id, str) or not cell_id:
100
+ return None
101
+ idx = 0
102
+ while idx < len(cell_id) and cell_id[idx].isalpha():
103
+ idx += 1
104
+ if idx == 0 or idx >= len(cell_id):
105
+ return None
106
+ col = 0
107
+ for ch in cell_id[:idx].upper():
108
+ col = col * 26 + (ord(ch) - ord('A') + 1)
109
+ try:
110
+ row = int(cell_id[idx:])
111
+ except ValueError:
112
+ return None
113
+ return row, col - 1
114
+
115
+
116
+ def _adapt_payload_for_reward(app, payload):
117
+ return payload
118
+
119
+
120
+ def go(app_name):
121
+ if app_name in _GO_CACHE:
122
+ return _GO_CACHE[app_name]
123
+ base = APP_URLS.get(app_name)
124
+ if not base:
125
+ print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)')
126
+ print('REWARD: 0.0')
127
+ sys.exit(0)
128
+ try:
129
+ resp = requests.get(f'{base}/go?sid={sid}', timeout=15)
130
+ resp.raise_for_status()
131
+ payload = resp.json()
132
+ except Exception as e:
133
+ print(f'CRITICAL: cannot fetch {app_name} go state: {e}')
134
+ print('REWARD: 0.0')
135
+ sys.exit(0)
136
+ payload = _adapt_payload_for_reward(app_name, payload)
137
+ _GO_CACHE[app_name] = payload
138
+ return payload
139
+
140
+
141
+ def _cell_disp(cell):
142
+ if isinstance(cell, dict):
143
+ comp = cell.get('computed')
144
+ val = cell.get('value', '')
145
+ if isinstance(val, str) and val.strip().startswith('='):
146
+ if comp is not None and str(comp).strip() != '':
147
+ return comp
148
+ return val
149
+ if (val is None or str(val).strip() == '') and comp is not None:
150
+ return comp
151
+ return val
152
+ return cell
153
+
154
+
155
+ def _raw_sheet(state, name):
156
+ if not isinstance(state, dict):
157
+ return None
158
+ sheets = state.get('sheets')
159
+ if not isinstance(sheets, list):
160
+ return None
161
+ for sh in sheets:
162
+ if isinstance(sh, dict) and (norm(sh.get('name')) == norm(name) or norm(sh.get('id')) == norm(name)):
163
+ return sh
164
+ if len(sheets) == 1 and isinstance(sheets[0], dict):
165
+ return sheets[0]
166
+ return None
167
+
168
+
169
+ def _grid(sheet):
170
+ grid = {}
171
+ data = sheet.get('data') if isinstance(sheet, dict) else None
172
+ if not isinstance(data, dict):
173
+ return grid
174
+ for cid, cell in data.items():
175
+ rc = _parse_cell_id(cid)
176
+ if not rc:
177
+ continue
178
+ r, c = rc
179
+ grid.setdefault(r, {})[c] = _cell_disp(cell)
180
+ return grid
181
+
182
+
183
+ # ===========================================================================
184
+ def reward(go):
185
+ W_PUBF1 = 0.30
186
+ W_TYPE = 0.20
187
+ W_COLL = 0.15
188
+ W_LOGF1 = 0.20
189
+ W_POST = 0.05
190
+
191
+ # ---- 1) answer key ----
192
+ gs = go('google_sheets')
193
+ gs_init = gs.get('initial_state', {}) if isinstance(gs.get('initial_state'), dict) else {}
194
+ gs_cur = gs.get('current_state', {}) if isinstance(gs.get('current_state'), dict) else {}
195
+ adapter = gs_init.get('_task_adapter', {}) if isinstance(gs_init.get('_task_adapter'), dict) else {}
196
+
197
+ expected_log = adapter.get('expected_log') if isinstance(adapter.get('expected_log'), list) else []
198
+ ready_ids = list(adapter.get('ready_ids') or [])
199
+ type_by_id = {norm(k): norm(v) for k, v in (adapter.get('type_by_id') or {}).items()}
200
+ collection_by_id = {norm(k): norm(v) for k, v in (adapter.get('collection_by_id') or {}).items()}
201
+ title_by_id = {norm(k): norm(v) for k, v in (adapter.get('title_by_id') or {}).items()}
202
+ published_status = norm(adapter.get('published_status') or 'active')
203
+ comp_threshold = adapter.get('completeness_threshold', 0.60)
204
+ comp_bonus = adapter.get('completeness_bonus', 0.10)
205
+ channel = adapter.get('catalog_channel') or 'catalog'
206
+ target_sheet = adapter.get('target_sheet') or 'Listing Log'
207
+ n_ready = len(ready_ids)
208
+ if n_ready == 0:
209
+ print('DEBUG_SHOP_LISTING fatal=no_ready_ids total=0.0')
210
+ return 0.0
211
+
212
+ # ---- 2) shopify: diff product status; only NEWLY-published (draft->active) count ----
213
+ gh = go('shopify')
214
+ gh_init = gh.get('initial_state', {}) if isinstance(gh.get('initial_state'), dict) else {}
215
+ gh_cur = gh.get('current_state', {}) if isinstance(gh.get('current_state'), dict) else {}
216
+
217
+ def _prod_map(state):
218
+ out = {}
219
+ for p in (state.get('products') or []):
220
+ if isinstance(p, dict):
221
+ out[p.get('id')] = p
222
+ return out
223
+
224
+ init_p = _prod_map(gh_init)
225
+ cur_p = _prod_map(gh_cur)
226
+ newly_pub = {pid for pid, p in cur_p.items()
227
+ if norm(p.get('status')) == published_status
228
+ and norm(init_p.get(pid, {}).get('status')) != published_status}
229
+
230
+ true_ids = {norm(i) for i in ready_ids}
231
+ pub_ids = {norm(i) for i in newly_pub}
232
+ pub_f1 = f1(true_ids, pub_ids)
233
+ s_pubf1 = W_PUBF1 * pub_f1
234
+
235
+ # ---- 3) parse Listing Log rows; index by title ----
236
+ sheet = _raw_sheet(gs_cur, target_sheet)
237
+ grid = _grid(sheet) if sheet is not None else {}
238
+ log_rows = []
239
+ for r in sorted(grid.keys()):
240
+ if r <= 1:
241
+ continue
242
+ row = grid[r]
243
+ prod = _s(row.get(0))
244
+ ptype = _s(row.get(1))
245
+ coll = _s(row.get(2))
246
+ if not prod and not ptype and not coll:
247
+ continue
248
+ log_rows.append({'Product': prod, 'ProductType': ptype, 'Collection': coll})
249
+
250
+ # map title(lower) -> id(lower) for the ready set
251
+ id_by_title = {t: i for i, t in title_by_id.items()}
252
+ logged_by_id = {}
253
+ for r in log_rows:
254
+ pid = id_by_title.get(norm(r['Product']))
255
+ if pid and pid not in logged_by_id:
256
+ logged_by_id[pid] = r
257
+
258
+ # ---- 4) product-type correctness over the 7 ----
259
+ type_ok = 0
260
+ for pid in true_ids:
261
+ r = logged_by_id.get(pid)
262
+ if r and norm(r.get('ProductType')) == type_by_id.get(pid):
263
+ type_ok += 1
264
+ type_score = frac(type_ok, n_ready)
265
+ s_type = W_TYPE * type_score
266
+
267
+ # ---- 5) collection correctness over the 7 ----
268
+ coll_ok = 0
269
+ for pid in true_ids:
270
+ r = logged_by_id.get(pid)
271
+ if r and norm(r.get('Collection')) == collection_by_id.get(pid):
272
+ coll_ok += 1
273
+ coll_score = frac(coll_ok, n_ready)
274
+ s_coll = W_COLL * coll_score
275
+
276
+ # ---- 6) listing-log F1 over (Product, ProductType, Collection) ----
277
+ def _log_key(prod, ptype, coll):
278
+ return (norm(prod), norm(ptype), norm(coll))
279
+
280
+ true_log = {_log_key(d['Product'], d['ProductType'], d['Collection']) for d in expected_log}
281
+ pred_log = {_log_key(r['Product'], r['ProductType'], r['Collection']) for r in log_rows
282
+ if _s(r['Product'])}
283
+ log_f1 = f1(true_log, pred_log)
284
+ s_logf1 = W_LOGF1 * log_f1
285
+
286
+ # ---- 7) slack summary post ----
287
+ slack = go('slack')
288
+ scur = slack.get('current_state', {}) if isinstance(slack.get('current_state'), dict) else {}
289
+ sinit = slack.get('initial_state', {}) if isinstance(slack.get('initial_state'), dict) else {}
290
+ init_msg = {(m.get('messageId') or m.get('id'))
291
+ for m in _slack_channel_messages(sinit, channel) if isinstance(m, dict)}
292
+ _catalog_kw = ('publish', 'product', 'catalog', 'listing', 'collection')
293
+ def _is_catalog_summary(m):
294
+ t = (_msg_text(m) or '').lower()
295
+ return any(k in t for k in _catalog_kw)
296
+ new_msgs = [m for m in _slack_channel_messages(scur, channel)
297
+ if isinstance(m, dict)
298
+ and (m.get('messageId') or m.get('id')) not in init_msg
299
+ and (_msg_text(m) or '').strip()]
300
+ post_ok = any(_is_catalog_summary(m) for m in new_msgs)
301
+ s_post = W_POST * (1.0 if post_ok else 0.0)
302
+
303
+ # ---- 8) core subtotal + completeness bonus ----
304
+ core = s_pubf1 + s_type + s_coll + s_logf1 + s_post
305
+ bonus = comp_bonus if core >= comp_threshold else 0.0
306
+ score = clamp01(core + bonus)
307
+
308
+ print(
309
+ 'DEBUG_SHOP_LISTING '
310
+ f'n_ready={n_ready} published={len(pub_ids)} pub_f1={round(pub_f1, 4)} '
311
+ f'type_ok={type_ok}/{n_ready} coll_ok={coll_ok}/{n_ready} log_f1={round(log_f1, 4)} '
312
+ f'post={post_ok} core={round(core, 4)} bonus={bonus} '
313
+ f'w_pubf1={round(s_pubf1, 4)} w_type={round(s_type, 4)} w_coll={round(s_coll, 4)} '
314
+ f'w_logf1={round(s_logf1, 4)} w_post={round(s_post, 4)} total={round(score, 4)}'
315
+ )
316
+ return score
317
+
318
+
319
+ try:
320
+ score = float(reward(go))
321
+ except Exception as exc:
322
+ print(f'ERROR: reward() raised {exc!r}')
323
+ score = 0.0
324
+
325
+ score = clamp01(score)
326
+ print(f'\nREWARD: {round(score, 4)}')
ops_inbox_meeting_007/_cua_gym_vm_bridge.sh ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # CUA-Gym VM-side network fix (direct-IP mock access).
3
+ #
4
+ # Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by
5
+ # their real IDC address (http://28.7.184.198:81xx) instead of the old
6
+ # localhost:9000-9097 socat bridge, so the VM only needs two fixes:
7
+ #
8
+ # 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's
9
+ # cluster DNS, which is unreachable from QEMU SLIRP NAT
10
+ # ("Temporary failure in name resolution").
11
+ # 2. The mock host excluded from the woa http proxy — otherwise the VM's
12
+ # Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403
13
+ # from the proxy when hitting 28.7.184.198:81xx. (The old socat path never
14
+ # hit this because localhost is bypassed by default.)
15
+ #
16
+ # Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic
17
+ # OSWorld setup pipeline.
18
+ #
19
+ # Argv:
20
+ # $1 optional sudo password (default "password"; SetupController
21
+ # substitutes {CLIENT_PASSWORD} when uploaded as a cache file).
22
+ # $2 unused (kept for backward compat — was socat first port 9000).
23
+ # $3 unused (kept for backward compat — was socat last port 9097).
24
+ # $4 optional mock host IP (default 28.7.184.198).
25
+
26
+ set +e
27
+
28
+ PASS="${1:-password}"
29
+ MOCK_HOST="${4:-28.7.184.198}"
30
+ # Derive the /16 IDC subnet so future port/host tweaks on the same segment
31
+ # stay bypassed too (28.7.184.198 -> 28.7.0.0/16).
32
+ MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')"
33
+
34
+ run_root() {
35
+ echo "$PASS" | sudo -S -p "" bash -c "$1"
36
+ }
37
+
38
+ # Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2.
39
+ GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')"
40
+ GW="${GW:-10.0.2.2}"
41
+
42
+ # ─── CUA-Gym network fix (Taiji-specific) ─────────────────────────────
43
+ fix_vm_network() {
44
+ # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP
45
+ # DNS forwarder. Nothing hardcoded except the mock host above.
46
+ local GW_NET="${GW%.*}"
47
+ local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3
48
+ local OWN_CIDR
49
+ OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \
50
+ | awk '{print $4; exit}')"
51
+ local OWN_IP="${OWN_CIDR%/*}"
52
+ local OWN_NET=""
53
+ [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24"
54
+
55
+ # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps
56
+ # systemd-resolved/NetworkManager from clobbering it.
57
+ if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf
58
+ chattr +i /etc/resolv.conf 2>/dev/null || true"; then
59
+ echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})"
60
+ else
61
+ echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf"
62
+ fi
63
+
64
+ # 2) Build the proxy bypass list from detected values + the direct-IP
65
+ # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx
66
+ # reachable from inside the VM — without it the woa proxy 403s it.
67
+ local ignore_list="['localhost', '127.0.0.0/8', '${GW}'"
68
+ [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'"
69
+ [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'"
70
+ [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'"
71
+ [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'"
72
+ [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'"
73
+ ignore_list="${ignore_list}]"
74
+
75
+ # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these.
76
+ if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then
77
+ echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}"
78
+ else
79
+ echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)"
80
+ fi
81
+
82
+ # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl).
83
+ local NP="localhost,127.0.0.1,${GW}"
84
+ [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}"
85
+ [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}"
86
+ [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24"
87
+ [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}"
88
+ [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}"
89
+
90
+ for var in no_proxy NO_PROXY; do
91
+ if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then
92
+ echo "export ${var}=${NP}" >> /home/user/.bashrc
93
+ fi
94
+ done
95
+ run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \
96
+ && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \
97
+ || echo 'no_proxy=\"${NP}\"' >> /etc/environment
98
+ grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \
99
+ && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \
100
+ || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1
101
+ echo "[cua_gym_vm_bridge] no_proxy=${NP}"
102
+ }
103
+
104
+ fix_vm_network
105
+
106
+ echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed"
ops_inbox_meeting_007/initial_setup.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: ea_meeting_from_inbox_b100
3
+ Task ID: ops_inbox_meeting_007
4
+ Domain: mock_websites
5
+ Mocks: gmail_mock, google_calendar_mock, slack_mock (single shared sid)
6
+
7
+ Persona: You are an office worker acting as an operations associate. Your tools for this task are: the shared email inbox, the team calendar, 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): Gmail inbox with 3 email(s): "Your industry roundup" from news@digest.com; "Prep call before the board meeting?" from chair@board.org; "FYI: office closed July 4" from facilities@company.com; an empty Google Calendar; Slack workspace with channels #general, #random. GROUND TRUTH — the agent earns partial credit for each checkpoint: cal_new_event (+0.2); event titled Board Prep Call (+0.2); on June 26 (+0.2); gmail_new_sent (+0.1); replied to the board chair (+0.2); 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
+ "gmail_mock": "http://28.7.184.198:8138",
23
+ "google_calendar_mock": "http://28.7.184.198:8141",
24
+ "slack_mock": "http://28.7.184.198:8178"
25
+ }
26
+ PRIMARY_URL = 'http://28.7.184.198:8138'
27
+
28
+ sid = str(uuid.uuid4())
29
+ with open('/tmp/task_web_sid', 'w') as f:
30
+ f.write(sid)
31
+ print(f'Generated sid: {sid}')
32
+
33
+ # Full initial state for every mock involved (all required top-level keys present).
34
+ STATES = { 'gmail_mock': { 'user': { 'userId': 'u1',
35
+ 'username': 'John Smith',
36
+ 'email': 'john.smith@company.com',
37
+ 'avatar': ''},
38
+ 'labels': [ {'id': 'l1', 'name': 'Work', 'color': '#ef4444'},
39
+ {'id': 'l2', 'name': 'Personal', 'color': '#3b82f6'},
40
+ {'id': 'l3', 'name': 'Travel', 'color': '#22c55e'},
41
+ {'id': 'l4', 'name': 'Finance', 'color': '#eab308'}],
42
+ 'emails': [ { 'id': 'email_1',
43
+ 'threadId': 'thread_email_1',
44
+ 'from': { 'name': 'Weekly Digest',
45
+ 'email': 'news@digest.com',
46
+ 'avatar': ''},
47
+ 'to': [ { 'name': 'John Smith',
48
+ 'email': 'john.smith@company.com'}],
49
+ 'cc': [],
50
+ 'bcc': [],
51
+ 'subject': 'Your industry roundup',
52
+ 'body': '<p>Top 10 stories this week.</p>',
53
+ 'snippet': 'Top 10 stories.',
54
+ 'timestamp': '2026-06-08T08:15:00Z',
55
+ 'read': False,
56
+ 'starred': False,
57
+ 'important': False,
58
+ 'labels': [],
59
+ 'category': 'updates',
60
+ 'folder': 'inbox',
61
+ 'attachments': []},
62
+ { 'id': 'email_2',
63
+ 'threadId': 'thread_email_2',
64
+ 'from': { 'name': 'Eleanor Vance',
65
+ 'email': 'chair@board.org',
66
+ 'avatar': ''},
67
+ 'to': [ { 'name': 'John Smith',
68
+ 'email': 'john.smith@company.com'}],
69
+ 'cc': [],
70
+ 'bcc': [],
71
+ 'subject': 'Prep call before the board meeting?',
72
+ 'body': '<p>Could we do a 30-minute prep call on June 26 '
73
+ 'at 10:00 AM? Want to align on the agenda.</p>',
74
+ 'snippet': '30-min prep call June 26 10am?',
75
+ 'timestamp': '2026-06-08T08:15:00Z',
76
+ 'read': False,
77
+ 'starred': False,
78
+ 'important': False,
79
+ 'labels': [],
80
+ 'category': 'primary',
81
+ 'folder': 'inbox',
82
+ 'attachments': []},
83
+ { 'id': 'email_3',
84
+ 'threadId': 'thread_email_3',
85
+ 'from': { 'name': 'Facilities',
86
+ 'email': 'facilities@company.com',
87
+ 'avatar': ''},
88
+ 'to': [ { 'name': 'John Smith',
89
+ 'email': 'john.smith@company.com'}],
90
+ 'cc': [],
91
+ 'bcc': [],
92
+ 'subject': 'FYI: office closed July 4',
93
+ 'body': '<p>Reminder the office is closed July 4.</p>',
94
+ 'snippet': 'Office closed July 4.',
95
+ 'timestamp': '2026-06-08T08:15:00Z',
96
+ 'read': False,
97
+ 'starred': False,
98
+ 'important': False,
99
+ 'labels': [],
100
+ 'category': 'updates',
101
+ 'folder': 'inbox',
102
+ 'attachments': []}],
103
+ 'drafts': []},
104
+ 'google_calendar_mock': { 'user': { 'id': 'u1',
105
+ 'username': 'Demo User',
106
+ 'email': 'demo@example.com',
107
+ 'avatar': ''},
108
+ 'calendars': [ { 'id': 'c1',
109
+ 'name': 'Personal',
110
+ 'color': '#039BE5',
111
+ 'visible': True,
112
+ 'userId': 'u1',
113
+ 'isDefault': True},
114
+ { 'id': 'c2',
115
+ 'name': 'Work',
116
+ 'color': '#33B679',
117
+ 'visible': True,
118
+ 'userId': 'u1',
119
+ 'isDefault': False}],
120
+ 'events': [],
121
+ 'view': 'week',
122
+ 'currentDate': '2026-06-08T00:00:00.000Z',
123
+ 'sidebarOpen': True,
124
+ 'settings': { 'weekStart': 0,
125
+ 'defaultDuration': 60,
126
+ 'defaultView': 'week',
127
+ 'defaultReminder': {'type': 'popup', 'minutes': 10},
128
+ 'timeFormat': '12h',
129
+ 'showWeekNumbers': False,
130
+ 'showDeclinedEvents': False}},
131
+ 'slack_mock': { 'currentUser': { 'userId': 'user_1',
132
+ 'fullName': 'John Smith',
133
+ 'displayName': 'John',
134
+ 'email': 'john.smith@company.com',
135
+ 'avatar': 'https://picsum.photos/200/200?random=1',
136
+ 'title': '',
137
+ 'status': 'online',
138
+ 'statusMessage': '',
139
+ 'statusEmoji': '',
140
+ 'timeZone': 'America/New_York'},
141
+ 'workspace': { 'workspaceId': 'ws_1',
142
+ 'workspaceName': 'Acme Corp',
143
+ 'icon': ''},
144
+ 'users': [ { 'userId': 'user_1',
145
+ 'fullName': 'John Smith',
146
+ 'displayName': 'John',
147
+ 'email': 'john.smith@company.com',
148
+ 'avatar': 'https://picsum.photos/200/200?random=1',
149
+ 'title': '',
150
+ 'status': 'online',
151
+ 'statusMessage': '',
152
+ 'statusEmoji': '',
153
+ 'timeZone': 'America/New_York'},
154
+ { 'userId': 'user_2',
155
+ 'fullName': 'Sarah Johnson',
156
+ 'displayName': 'Sarah',
157
+ 'email': 'sarah.johnson@company.com',
158
+ 'avatar': 'https://picsum.photos/200/200?random=2',
159
+ 'title': '',
160
+ 'status': 'online',
161
+ 'statusMessage': '',
162
+ 'statusEmoji': '',
163
+ 'timeZone': 'America/New_York'},
164
+ { 'userId': 'user_3',
165
+ 'fullName': 'Mike Chen',
166
+ 'displayName': 'Mike',
167
+ 'email': 'mike.chen@company.com',
168
+ 'avatar': 'https://picsum.photos/200/200?random=3',
169
+ 'title': '',
170
+ 'status': 'online',
171
+ 'statusMessage': '',
172
+ 'statusEmoji': '',
173
+ 'timeZone': 'America/New_York'},
174
+ { 'userId': 'user_4',
175
+ 'fullName': 'Lisa Park',
176
+ 'displayName': 'Lisa',
177
+ 'email': 'lisa.park@company.com',
178
+ 'avatar': 'https://picsum.photos/200/200?random=4',
179
+ 'title': '',
180
+ 'status': 'online',
181
+ 'statusMessage': '',
182
+ 'statusEmoji': '',
183
+ 'timeZone': 'America/New_York'}],
184
+ 'channels': [ { 'channelId': 'general',
185
+ 'name': 'general',
186
+ 'description': 'general channel',
187
+ 'topic': '',
188
+ 'isPrivate': False,
189
+ 'isStarred': False,
190
+ 'members': ['user_1', 'user_2', 'user_3', 'user_4'],
191
+ 'createdBy': 'user_1',
192
+ 'createdAt': '2026-01-01T10:00:00Z',
193
+ 'pinnedMessages': [],
194
+ 'unreadCount': 0},
195
+ { 'channelId': 'random',
196
+ 'name': 'random',
197
+ 'description': 'random channel',
198
+ 'topic': '',
199
+ 'isPrivate': False,
200
+ 'isStarred': False,
201
+ 'members': ['user_1', 'user_2', 'user_3', 'user_4'],
202
+ 'createdBy': 'user_1',
203
+ 'createdAt': '2026-01-01T10:00:00Z',
204
+ 'pinnedMessages': [],
205
+ 'unreadCount': 0}],
206
+ 'messages': { 'general': [ { 'messageId': 'g1',
207
+ 'senderId': 'user_2',
208
+ 'content': 'did the board prep call get '
209
+ 'scheduled?',
210
+ 'timestamp': '2026-06-08T08:00:00Z',
211
+ 'threadId': None,
212
+ 'reactions': [],
213
+ 'attachments': [],
214
+ 'isEdited': False}],
215
+ 'random': []},
216
+ 'threads': {},
217
+ 'dms': [],
218
+ 'bookmarkedMessages': [],
219
+ 'callHistory': [],
220
+ 'settings': { 'theme': 'light',
221
+ 'notifications': 'all',
222
+ 'displayDensity': 'comfortable',
223
+ 'showAvatars': True,
224
+ 'use24Hour': False},
225
+ 'invitations': [],
226
+ 'notifications': []}}
227
+
228
+
229
+ def launch_gui(command, delay_sec=1.0):
230
+ env = os.environ.copy()
231
+ env['DISPLAY'] = ':0'
232
+ subprocess.Popen(shlex.split(command), stdin=subprocess.DEVNULL,
233
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
234
+ env=env, start_new_session=True)
235
+ time.sleep(delay_sec)
236
+
237
+
238
+ for name, url in MOCK_URLS.items():
239
+ resp = requests.post(f'{url}/post?sid={sid}',
240
+ json={'action': 'set', 'state': STATES[name]}, timeout=30)
241
+ assert resp.status_code == 200, f'{name} injection failed: {resp.text}'
242
+ go = requests.get(f'{url}/go?sid={sid}', timeout=10).json()
243
+ assert go.get('initial_state') is not None, f'{name} initial_state is None'
244
+ print(f'State injected: {name} sid={sid}')
245
+
246
+ # Open the PRIMARY app as the main window first, then open every other
247
+ # involved mock as an additional browser tab so the agent can see/reach all
248
+ # relevant apps (e.g. read the email in the Gmail tab AND post in Slack).
249
+ # Without this, secondary-app data is injected but has no on-screen entry
250
+ # point, and the agent wastes its budget hunting for a non-existent client.
251
+ launch_gui(f'google-chrome "{PRIMARY_URL}/?sid={sid}"', delay_sec=2.0)
252
+ print(f'GUI_READY: launched browser at {PRIMARY_URL}/?sid={sid}')
253
+ for _name, _url in MOCK_URLS.items():
254
+ if _url == PRIMARY_URL:
255
+ continue
256
+ launch_gui(f'google-chrome --new-tab "{_url}/?sid={sid}"', delay_sec=1.0)
257
+ print(f'Opened tab: {_name} at {_url}/?sid={sid}')
ops_inbox_meeting_007/reward.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: ea_meeting_from_inbox_b100
3
+ Task ID: ops_inbox_meeting_007
4
+ Domain: mock_websites
5
+ Mocks: gmail_mock, google_calendar_mock
6
+ Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0):
7
+ - [0.2] cal_new_event
8
+ - [0.2] event titled Board Prep Call
9
+ - [0.2] on June 26
10
+ - [0.2] gmail_new_sent
11
+ - [0.2] replied to the board chair
12
+ """
13
+ import re
14
+ import sys
15
+
16
+ import requests
17
+
18
+ MOCK_URLS = {
19
+ "gmail_mock": "http://28.7.184.198:8138",
20
+ "google_calendar_mock": "http://28.7.184.198:8141"
21
+ }
22
+
23
+ try:
24
+ with open('/tmp/task_web_sid') 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: {e}')
30
+ print('REWARD: 0.0')
31
+ sys.exit(0)
32
+
33
+ STATES = {}
34
+ for _name, _url in MOCK_URLS.items():
35
+ try:
36
+ _r = requests.get(f'{_url}/go?sid={sid}', timeout=15)
37
+ _r.raise_for_status()
38
+ STATES[_name] = _r.json()
39
+ except Exception as e:
40
+ print(f'CRITICAL: cannot fetch {_name}: {e}')
41
+ print('REWARD: 0.0')
42
+ sys.exit(0)
43
+
44
+
45
+ def cur(mock):
46
+ return (STATES.get(mock) or {}).get('current_state') or {}
47
+
48
+
49
+ def _lc(s):
50
+ return (s or '').lower()
51
+
52
+
53
+ total = 0.0
54
+
55
+ # c0: a new calendar event was created
56
+ c0_init_ids = {e.get('id') for e in ((STATES['google_calendar_mock'].get('initial_state') or {}).get('events') or [])}
57
+ c0_new = [e for e in (cur('google_calendar_mock').get('events') or []) if e.get('id') not in c0_init_ids]
58
+ globals()['cal_new_events'] = c0_new
59
+ if c0_new:
60
+ print('PASS: new calendar event (0.2)')
61
+ total += 0.2
62
+ else:
63
+ print('FAIL: no new calendar event')
64
+
65
+ # c1: new event title (event titled Board Prep Call)
66
+ c1_new = globals().get('cal_new_events', [])
67
+ if any(any(t in _lc(e.get('title','')) for t in ['board prep call', 'board prep', 'prep call']) for e in c1_new):
68
+ print('PASS: event titled Board Prep Call (0.2)')
69
+ total += 0.2
70
+ else:
71
+ print('FAIL: event titled Board Prep Call')
72
+
73
+ # c2: new event date contains '2026-06-26'
74
+ c2_new = globals().get('cal_new_events', [])
75
+ if any('2026-06-26' in (e.get('start','') or '') for e in c2_new):
76
+ print('PASS: on June 26 (0.2)')
77
+ total += 0.2
78
+ else:
79
+ print('FAIL: on June 26')
80
+
81
+ # c3: a new email was sent (folder sent) or saved as draft
82
+ c3_init = (STATES['gmail_mock'].get('initial_state') or {})
83
+ c3_cur = cur('gmail_mock')
84
+ c3_init_ids = {e.get('id') for e in (c3_init.get('emails') or [])}
85
+ c3_sent = [e for e in (c3_cur.get('emails') or []) if e.get('id') not in c3_init_ids and e.get('folder') in ('sent', 'drafts')]
86
+ c3_sent += [d for d in (c3_cur.get('drafts') or []) if d.get('id') not in {x.get('id') for x in (c3_init.get('drafts') or [])}]
87
+ if c3_sent:
88
+ print('PASS: new email sent/drafted (0.2)')
89
+ total += 0.2
90
+ else:
91
+ print('FAIL: no new sent/draft email')
92
+
93
+ # c4: sent/draft email addressed to (replied to the board chair)
94
+ c4_init = (STATES['gmail_mock'].get('initial_state') or {})
95
+ c4_cur = cur('gmail_mock')
96
+ c4_init_ids = {e.get('id') for e in (c4_init.get('emails') or [])}
97
+ c4_pool = [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')] + (c4_cur.get('drafts') or [])
98
+ c4_tos = _lc(' '.join(t.get('email','') for e in c4_pool for t in (e.get('to') or [])))
99
+ if any(t in c4_tos for t in ['chair@board.org']):
100
+ print('PASS: replied to the board chair (0.2)')
101
+ total += 0.2
102
+ else:
103
+ print('FAIL: replied to the board chair')
104
+
105
+ final = round(min(total, 1.0), 4)
106
+ print(f'\nScore: {total}/1.0')
107
+ print(f'REWARD: {final}')
ops_inbox_meeting_007/reward_label.json ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/c4ce61fa-20a5-563d-8bba-542633ab52bc/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:47",
7
+ "label": {
8
+ "task_id": "ops_inbox_meeting_007",
9
+ "domain": "mock_websites",
10
+ "summary": "验证用户是否在Google Calendar新建了6月26日的Board Prep Call会议、通过Gmail向董事会主席发送/草拟了邮件,并在Slack的#general频道以user_1身份发送了新消息",
11
+ "is_placeholder": false,
12
+ "data_sources": [
13
+ "gmail_mock",
14
+ "google_calendar_mock",
15
+ "slack_mock",
16
+ "/tmp/task_web_sid"
17
+ ],
18
+ "scoring_components": [
19
+ {
20
+ "name": "cal_new_event",
21
+ "weight": 0.2,
22
+ "description": "检查Google Calendar是否创建了新的日历事件",
23
+ "check_logic": "对比google_calendar_mock的initial_state.events与current_state.events,收集id不在初始集合中的事件存入cal_new_events;若cal_new_events非空则通过",
24
+ "pass_condition": "current_state.events中存在id不在initial_state.events中的新事件"
25
+ },
26
+ {
27
+ "name": "event titled Board Prep Call",
28
+ "weight": 0.2,
29
+ "description": "检查新建日历事件的标题是否包含Board Prep Call相关关键词",
30
+ "check_logic": "遍历cal_new_events,将title转小写后检查是否包含'board prep call'、'board prep'或'prep call'任一子串",
31
+ "pass_condition": "新事件的title字段(忽略大小写)包含上述任一关键词"
32
+ },
33
+ {
34
+ "name": "on June 26",
35
+ "weight": 0.2,
36
+ "description": "检查新建日历事件的开始日期是否为2026-06-26",
37
+ "check_logic": "遍历cal_new_events,检查start字段(字符串)中是否包含'2026-06-26'",
38
+ "pass_condition": "至少一个新事件的start字段包含'2026-06-26'"
39
+ },
40
+ {
41
+ "name": "gmail_new_sent",
42
+ "weight": 0.1,
43
+ "description": "检查Gmail是否有新发送的邮件或新保存的草稿",
44
+ "check_logic": "收集current_state.emails中id不在initial_state.emails且folder为'sent'或'drafts'的邮件,并收集current_state.drafts中id不在initial_state.drafts的草稿;若合并后列表非空则通过",
45
+ "pass_condition": "存在新的sent邮件或新的draft"
46
+ },
47
+ {
48
+ "name": "replied to the board chair",
49
+ "weight": 0.2,
50
+ "description": "检查新邮件/草稿的收件人是否包含董事会主席邮箱",
51
+ "check_logic": "构建c4_pool(新sent/drafts邮件加上current_state.drafts),提取所有to列表中的email字段拼接为小写字符串,检查是否包含'chair@board.org'",
52
+ "pass_condition": "新邮件/草稿的收件人邮箱中包含'chair@board.org'"
53
+ },
54
+ {
55
+ "name": "slack_new_msg",
56
+ "weight": 0.1,
57
+ "description": "检查Slack #general频道是否有user_1发送的新消息",
58
+ "check_logic": "获取current_state.messages.general,排除SEED中预置的messageId(如'g1'),筛选senderId为'user_1'的消息;若存在则通过",
59
+ "pass_condition": "#general频道中存在messageId不在SEED且senderId为'user_1'的新消息"
60
+ }
61
+ ],
62
+ "total_max_score": 1.0,
63
+ "score_aggregation": "各组件分数累加求和,最终通过min(total, 1.0)将总分钳制在1.0上限,并四舍五入保留4位小数",
64
+ "failure_modes": [
65
+ "读取/tmp/task_web_sid失败或内容为空时打印CRITICAL并返回0.0",
66
+ "任一mock服务(gmail_mock、google_calendar_mock、slack_mock)状态拉取失败时打印CRITICAL并返回0.0",
67
+ "未创建新日历事件导致c0失败,无法获得后续c1、c2的分数",
68
+ "新事件标题不匹配关键词导致c1失败",
69
+ "新事件start字段不含'2026-06-26'导致c2失败",
70
+ "无新sent/draft邮件导致c3失败",
71
+ "新邮件未发送给chair@board.org导致c4失败",
72
+ "user_1未在#general发送新消息导致c5失败"
73
+ ],
74
+ "scoring_logic_explanation": "脚本首先读取/tmp/task_web_sid获取会话ID,然后依次向gmail_mock、google_calendar_mock、slack_mock发送请求拉取各自的current_state和initial_state。若任何一步失败则直接退出并返回0.0。评分按顺序执行6个组件:先通过对比initial_state与current_state的events列表识别新日历事件(0.2分);再检查这些新事件的标题是否包含Board Prep Call相关关键词(0.2分)以及start字段是否包含2026-06-26(0.2分);接着检查Gmail中是否有新的sent邮件或drafts(0.1分),并进一步检查这些新邮件的收件人是否包含chair@board.org(0.2分);最后检查Slack #general频道中是否有user_1发送的新消息(0.1分)。每个组件独立判断,通过则累加对应分值,不通过则仅打印FAIL不扣分也不��断。最终总分经min(total, 1.0)钳制后四舍五入到4位小数输出。",
75
+ "confidence": 1.0
76
+ },
77
+ "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并以 JSON 格式输出结果。\n\n让我仔细阅读代码:\n\n1. 文件路径和 docstring:\n - Task ID: c4ce61fa-20a5-563d-8bba-542633ab52bc\n - Domain: mock_websites\n - Mocks: gmail_mock, google_calendar_mock, slack_mock\n - Scoring total = 1.0\n\n2. 数据源:\n - 从 /tmp/task_web_sid 读取 sid\n - 从三个 mock 服务获取状态:gmail_mock, google_calendar_mock, slack_mock\n\n3. 评分组件:\n - c0: cal_new_event (0.2) - 检查是否有新的日历事件创建\n - c1: event titled Board Prep Call (0.2) - 检查新事件标题是否包含 'board prep call', 'board prep', 或 'prep call'\n - c2: on June 26 (0.2) - 检查新事件日期是否包含 '2026-06-26'\n - c3: gmail_new_sent (0.1) - 检查是否有新邮件发送或保存为草稿\n - c4: replied to the board chair (0.2) - 检查发送/草稿邮件是否发送给 chair@board.org\n - c5: slack_new_msg (0.1) - 检查 user_1 是否在 #general 频道发送了新消息\n\n4. 失败模式:\n - 读取 sid 失败 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n - 获取 mock 状态失败 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n - 各组件检查失败只是不加分,不会提前退出\n\n5. 分数汇总:\n - total 累加各组件分数\n - final = round(min(total, 1.0), 4)\n - 是相加汇总,然后钳制到 1.0\n\n6. is_placeholder:\n - false,因为脚本有详细的检查逻辑\n\n7. confidence:\n - 1.0,因为代码逻辑清晰完整\n\n现在构建 JSON:\n\ntask_id: \"c4ce61fa-20a5-563d-8bba-542633ab52bc\"\ndomain: \"mock_websites\"\nsummary: \"验证用户是否通过Gmail回复董事会主席、在Google Calendar创建6月26日的Board Prep Call会议,并在Slack #general频道发送新消息\"\nis_placeholder: false\ndata_sources: [\"gmail_mock\", \"google_calendar_mock\", \"slack_mock\", \"/tmp/task_web_sid\"]\n\nscoring_components:\n1. cal_new_event (0.2): 对比 initial_state 和 current_state 的 events,检查是否有新事件\n2. event titled Board Prep Call (0.2): 检查新事件标题是否包含指定关键词\n3. on June 26 (0.2): 检查新事件 start 字段是否包含 '2026-06-26'\n4. gmail_new_sent (0.1): 检查 Gmail 是否有新的 sent 或 drafts 邮件\n5. replied to the board chair (0.2): 检查新邮件的 to 字段是否包含 chair@board.org\n6. slack_new_msg (0.1): 检查 Slack #general 频道是否有 user_1 的新消息\n\nscore_aggregation: \"各组件分数相加,最终通过 min(total, 1.0) 钳制到上限 1.0,并四舍五入到4位小数\"\n\nfailure_modes:\n- 读取 /tmp/task_web_sid 失败或为空\n- 任一 mock 服务状态获取失败\n- 无新日历事件(c0失败)\n- 新日历事件标题不匹配(c1失败)\n- 新日历事件日期不是2026-06-26(c2失败)\n- 无新发送/草稿邮件(c3失败)\n- 新邮件未发送给 chair@board.org(c4失败)\n- user_1 未在 #general 发送新消息(c5失败)\n\nscoring_logic_explanation: 详细按执行顺序说明...\n\n让我确保所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样。\n\n检查代码细节:\n- c0: c0_init_ids 来自 initial_state.events,c0_new 是 current_state.events 中 id 不在 c0_init_ids 的事件\n- c1: 检查 cal_new_events 中任一事件 title 包含 'board prep call', 'board prep', 或 'prep call'\n- c2: 检查 cal_new_events 中任一事件 start 包含 '2026-06-26'\n- c3: 检查 emails 中 folder 为 sent 或 drafts 且 id 不在 initial emails 中的邮件,或 drafts 中 id 不在 initial drafts 中的草稿\n- c4: 类似 c3 构建 pool,提取所有 to.email 字段,检查是否包含 'chair@board.org'\n- c5: 检查 slack_mock current_state.messages.general 中 messageId 不在 SEED 中且 senderId 为 'user_1' 的消息\n\n注意 c4 的代码有一个小问题:c4_pool 的构建中,第二部分直接加了 (c4_cur.get('drafts') or []),没有排除初始草稿。但代码确实是这样写的,我如实描述。\n\n等等,c4 代码:\nc4_pool = [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')] + (c4_cur.get('drafts') or [])\n这里确实没有过滤掉初始草稿。但 c3 中过滤了。这是代码实际逻辑,如实记录。\n\nc5: SEED 是 {\"slack_mock:general\": [\"g1\"], \"slack_mock:random\": []},所以 c5_seed = {\"g1\"},排除 messageId 为 \"g1\" 的种子消息。\n\n好,现在写 JSON。 </think> {\"task_id\":\"c4ce61fa-20a5-563d-8bba-542633ab52bc\",\"domain\":\"mock_websites\",\"summary\":\"验证用户是否在Google Calendar新建了6月26日的Board Prep Call会议、通过Gmail向董事会主席发送/草拟了邮件,并在Slack的#general频道以user_1身份发送了新消息\",\"is_placeholder\":false,\"data_sources\":[\"gmail_mock\",\"google_calendar_mock\",\"slack_mock\",\"/tmp/task_web_sid\"],\"scoring_components\":[{\"name\":\"cal_new_event\",\"weight\":0.2,\"description\":\"检查Google Calendar是否创建了新的日历事件\",\"check_logic\":\"对比google_calendar_mock的initial_state.events与current_state.events,收集id不在初始集合中的事件存入cal_new_events;若cal_new_events非空则通过\",\"pass_condition\":\"current_state.events中存在id不在initial_state.events中的新事件\"},{\"name\":\"event titled Board Prep Call\",\"weight\":0.2,\"description\":\"检查新建日历事件的标题是否包含Board Prep Call相关关键词\",\"check_logic\":\"遍历cal_new_events,将title转小写后检查是否包含'board prep call'、'board prep'或'prep call'任一子串\",\"pass_condition\":\"新事件的title字段(忽略大小写)包含上述任一关键词\"},{\"name\":\"on June 26\",\"weight\":0.2,\"description\":\"检查新建日历事件的开始日期是否为2026-06-26\",\"check_logic\":\"遍历cal_new_events,检查start字段(字符串)中是否包含'2026-06-26'\",\"pass_condition\":\"至少一个新事件的start字段包含'2026-06-26'\"},{\"name\":\"gmail_new_sent\",\"weight\":0.1,\"description\":\"检查Gmail是否有新发送的邮件或新保存的草稿\",\"check_logic\":\"收集current_state.emails中id不在initial_state.emails且folder为'sent'或'drafts'的邮件,并收集current_state.drafts中id不在initial_state.drafts的草稿;若合并后列表非空则通过\",\"pass_condition\":\"存在新的sent邮件或新的draft\"},{\"name\":\"replied to the board chair\",\"weight\":0.2,\"description\":\"检查新邮件/草稿的收件人是否包含董事会主席邮箱\",\"check_logic\":\"构建c4_pool(新sent/drafts邮件加上current_state.drafts),提取所有to列表中的email字段拼接为小写字符串,检查是否包含'chair@board.org'\",\"pass_condition\":\"新邮件/草稿的收件人邮箱中包含'chair@board.org'\"},{\"name\":\"slack_new_msg\",\"weight\":0.1,\"description\":\"检查Slack #general频道是否有user_1发送的新消息\",\"check_logic\":\"获取current_state.messages.general,排除SEED中预置的messageId(如'g1'),筛选senderId为'user_1'的消息;若存在则通过\",\"pass_condition\":\"#general频道中存在messageId不在SEED且senderId为'user_1'的新消息\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数累加求和,最终通过min(total, 1.0)将总分钳制在1.0上限,并四舍五入保留4位小数\",\"failure_modes\":[\"读取/tmp/task_web_sid失败或内容为空时打印CRITICAL并返回0.0\",\"任一mock服务(gmail_mock、google_calendar_mock、slack_mock)状态拉取失败时打印CRITICAL并返回0.0\",\"未创建新日历事件导致c0失败,无法获得后续c1、c2的分数\",\"新事件标题不匹配关键词导致c1失败\",\"新事件start字段不含'2026-06-26'导致c2失败\",\"无新sent/draft邮件导致c3失败\",\"新邮件未发送给chair@board.org导致c4失败\",\"user_1未在#general发送新消息导致c5失败\"],\"scoring_logic_explanation\":\"脚本首先读取/tmp/task_web_sid获取会话ID,然后依次向gmail_mock、google_calendar_mock、slack_mock发送请求拉取各自的current_state和initial_state。若任何一步失败则直接退出并返回0.0。评分按顺序执行6个组件:先通过对比initial_state与current_state的events列表识别新日历事件(0.2分);再检查这些新事件的标题是否包含Board Prep Call相关关键词(0.2分)以及start字段是否包含2026-06-26(0.2分);接着检查Gmail中是否有新的sent邮件或drafts(0.1分),并进一步检查这些新邮件的收件人是否包含chair@board.org(0.2分);最后检查Slack #general频道中是否有user_1发送的新消息(0.1分)。每个组件独立判断,通过则累加对应分值,不通过则仅打印FAIL不扣分也不中断。最终总分经min(total, 1.0)钳制后四舍五入到4位小数输出。\",\"confidence\":1.0}"
78
+ }
ops_risk_log_006/_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"