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

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. am_renewal_contract_001/_cua_gym_vm_bridge.sh +106 -0
  2. am_renewal_contract_001/initial_setup.py +648 -0
  3. am_renewal_contract_001/reward.py +494 -0
  4. am_renewal_contract_001/reward_label.json +88 -0
  5. ar_closeout_006/_cua_gym_vm_bridge.sh +106 -0
  6. ar_closeout_006/initial_setup.py +928 -0
  7. ar_closeout_006/reward.py +624 -0
  8. ar_closeout_006/reward_label.json +61 -0
  9. ar_remittance_008__long/_cua_gym_vm_bridge.sh +106 -0
  10. ar_remittance_008__long/initial_setup.py +644 -0
  11. ar_remittance_008__long/reward.py +664 -0
  12. calc_boomerang_sales_004__long/.PLACEHOLDER +5 -0
  13. calc_boomerang_sales_004__long/338372e2-5164-5bba-be72-3024f425418f_BoomerangSales_4.xlsx +0 -0
  14. calc_boomerang_sales_004__long/3c734b28-876f-590a-8a9b-a7dea013cdd9_BoomerangSales_5.xlsx +0 -0
  15. calc_boomerang_sales_004__long/6_BoomerangSales_gt1_1.xlsx +0 -0
  16. calc_boomerang_sales_004__long/6_BoomerangSales_gt1_2.xlsx +0 -0
  17. calc_boomerang_sales_004__long/6_BoomerangSales_gt1_3.xlsx +0 -0
  18. calc_boomerang_sales_004__long/6_BoomerangSales_gt1_4.xlsx +0 -0
  19. calc_boomerang_sales_004__long/6_BoomerangSales_gt1_5.xlsx +0 -0
  20. calc_boomerang_sales_004__long/7594f1e5-2945-5a98-9eec-5aac2e8aaf1b_BoomerangSales_3.xlsx +0 -0
  21. calc_boomerang_sales_004__long/b9ee9e4b-d3c9-5341-a797-ba31c5448117_BoomerangSales_1.xlsx +0 -0
  22. calc_boomerang_sales_004__long/e22b8fec-7bed-5cb0-a402-a977fa125750_BoomerangSales_2.xlsx +0 -0
  23. calc_student_grades_005__long/.PLACEHOLDER +5 -0
  24. calc_student_grades_005__long/0a94aee5-1a46-57a5-b453-2402af0ffede_Student_Grades_and_Remarks_4.xlsx +0 -0
  25. calc_student_grades_005__long/26aa94e9-ffcf-57a5-b2dd-e92752c4b57f_Student_Grades_and_Remarks_2.xlsx +0 -0
  26. calc_student_grades_005__long/639ca2f8-0ba9-5a67-b827-a64f4cd425b5_Student_Grades_and_Remarks_3.xlsx +0 -0
  27. calc_student_grades_005__long/914ebed1-4ae1-5a3e-b9ab-bbbfe8206f7b_Student_Grades_and_Remarks_1.xlsx +0 -0
  28. calc_student_grades_005__long/Student_Grades_and_Remarks_gold_1.xlsx +0 -0
  29. calc_student_grades_005__long/Student_Grades_and_Remarks_gold_2.xlsx +0 -0
  30. calc_student_grades_005__long/Student_Grades_and_Remarks_gold_3.xlsx +0 -0
  31. calc_student_grades_005__long/Student_Grades_and_Remarks_gold_4.xlsx +0 -0
  32. calc_student_grades_005__long/Student_Grades_and_Remarks_gold_5.xlsx +0 -0
  33. calc_student_grades_005__long/f4dfeace-a9ac-57e3-9cb7-b78690026317_Student_Grades_and_Remarks_5.xlsx +0 -0
  34. csm_training_rate_005/initial_setup.py +279 -0
  35. csm_training_rate_005/reward.py +102 -0
  36. csops_inbox_triage_006__long/_cua_gym_vm_bridge.sh +106 -0
  37. csops_inbox_triage_006__long/initial_setup.py +771 -0
  38. csops_inbox_triage_006__long/reward.py +654 -0
  39. csops_incident_command_004__long/_cua_gym_vm_bridge.sh +106 -0
  40. csops_incident_command_004__long/initial_setup.py +617 -0
  41. csops_incident_command_004__long/reward.py +218 -0
  42. hr_payroll_approval_006__long/_cua_gym_vm_bridge.sh +106 -0
  43. hr_payroll_approval_006__long/initial_setup.py +782 -0
  44. hr_payroll_approval_006__long/reward.py +341 -0
  45. hr_policy_ack_002/_cua_gym_vm_bridge.sh +106 -0
  46. hr_policy_ack_002/initial_setup.py +369 -0
  47. hr_policy_ack_002/reward.py +134 -0
  48. hr_policy_ack_002/reward_label.json +57 -0
  49. itops_access_log_003/_cua_gym_vm_bridge.sh +106 -0
  50. itops_access_log_003/initial_setup.py +238 -0
am_renewal_contract_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"
am_renewal_contract_001/initial_setup.py ADDED
@@ -0,0 +1,648 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: Contract-To-Signature renewal pipeline (Globex Corp)
194
+ Task ID: am_renewal_contract_001
195
+ Domain: mock_websites
196
+ Mocks: notion_mock, docusign_mock, slack_mock
197
+
198
+ Injects initial state into all three mocks under a single shared, DETERMINISTIC sid:
199
+ - Notion: current 'Renewal Brief - Globex Corp' page (terms) + a stale FY24 distractor page
200
+ - DocuSign: Jordan Avery user, address-book contacts (David Okafor + finance mailbox),
201
+ 'Annual Renewal Agreement' template, and several unrelated distractor envelopes.
202
+ NO Globex renewal envelope exists yet.
203
+ - Slack: Vertex Cloud workspace with a 'deal-desk' channel (Jordan + finance + legal).
204
+ NO message about the Globex renewal envelope yet.
205
+
206
+ NOTE on sid: initial_env and golden_env are SEPARATE VMs that do NOT share /tmp.
207
+ A random per-VM UUID would not match across them. We therefore use a deterministic
208
+ sid derived from the task id so initial_setup.py (initial VM) and golden_patch.py
209
+ (golden VM) reference the same server-side state. Both scripts also write the sid to
210
+ their own /tmp/task_web_sid so reward.py can read it on either VM.
211
+ """
212
+ import os
213
+ import shlex
214
+ import subprocess
215
+ import time
216
+
217
+ import requests
218
+
219
+ TASK_ID = 'am_renewal_contract_003'
220
+ # initial_env and golden_env are SEPARATE containers but hit the SAME shared mock
221
+ # server. They MUST therefore use DISTINCT sids, otherwise reward.py (run on both
222
+ # VMs against the same reward code) would read identical server state and the
223
+ # initial env could never score 0. This script owns the *_initial sid.
224
+ SID = f'cuagym-{TASK_ID}-initial' # deterministic; valid chars [a-zA-Z0-9_-]
225
+
226
+ # Persist sid for reward.py on THIS (initial) VM.
227
+ with open('/tmp/task_web_sid', 'w') as f:
228
+ f.write(SID)
229
+ print(f'sid={SID}')
230
+
231
+ MOCK_URLS = {
232
+ 'notion': 'http://28.7.184.198:8166',
233
+ 'docusign': 'http://28.7.184.198:8130',
234
+ 'slack': 'http://28.7.184.198:8178',
235
+ }
236
+ PROXY = None
237
+
238
+
239
+ # ----------------------------------------------------------------------------
240
+ # Network: the mocks may require the corporate proxy. Auto-detect once.
241
+ # ----------------------------------------------------------------------------
242
+ def pick_proxies():
243
+ for p in (None, {'http': PROXY, 'https': PROXY}):
244
+ try:
245
+ r = requests.get(f'{MOCK_URLS["docusign"]}/go?sid=probe', proxies=p, timeout=10)
246
+ if r.status_code == 200:
247
+ print(f'connectivity OK via proxies={p}')
248
+ return p
249
+ except Exception as e:
250
+ print(f'probe with proxies={p} failed: {repr(e)[:80]}')
251
+ raise RuntimeError('Cannot reach mock server directly or via proxy')
252
+
253
+
254
+ PROXIES = None
255
+
256
+
257
+ # ----------------------------------------------------------------------------
258
+ # NOTION state
259
+ # ----------------------------------------------------------------------------
260
+ def build_notion_state():
261
+ cur_page_id = 'page-globex-renewal-2026'
262
+ old_page_id = 'page-globex-renewal-fy24'
263
+ getting_started_id = 'page-getting-started'
264
+
265
+ cur_blocks = [
266
+ ('blk-cur-h1', 'heading-1', 'Renewal Brief - Globex Corp'),
267
+ ('blk-cur-intro', 'text',
268
+ 'Renewal package for Globex Corp. Use these terms to prepare the renewal agreement for e-signature.'),
269
+ ('blk-cur-h2-terms', 'heading-2', 'Key Terms'),
270
+ ('blk-cur-customer', 'bullet-list', 'Customer: Globex Corp'),
271
+ ('blk-cur-arr', 'bullet-list', 'Renewal ARR / contract value: $85,000'),
272
+ ('blk-cur-term', 'bullet-list', 'Term: 12 months'),
273
+ ('blk-cur-uplift', 'bullet-list', 'Price uplift: 5% vs. prior term'),
274
+ ('blk-cur-payment', 'bullet-list', 'Payment terms: Net-30'),
275
+ ('blk-cur-finance', 'bullet-list', 'Finance CC mailbox: finance@vertexcloud.example.com'),
276
+ ('blk-cur-autorenew', 'bullet-list',
277
+ 'Auto-renewal clause: yes (12-month auto-renew unless cancelled 60 days prior)'),
278
+ ('blk-cur-closedate', 'bullet-list', 'Renewal (close) date: 2026-08-30'),
279
+ ('blk-cur-h2-signer', 'heading-2', 'Authorized Signer (Customer)'),
280
+ ('blk-cur-signer', 'text', 'David Okafor, COO, david.okafor@globex.example.com'),
281
+ ('blk-cur-callout', 'callout',
282
+ 'Send via DocuSign using the "Annual Renewal Agreement" template. CC finance@vertexcloud.example.com.'),
283
+ ]
284
+
285
+ old_blocks = [
286
+ ('blk-old-h1', 'heading-1', 'Renewal Brief - Globex Corp (FY24)'),
287
+ ('blk-old-note', 'callout',
288
+ "ARCHIVED - last year's terms. Do not use for the current renewal."),
289
+ ('blk-old-h2', 'heading-2', 'FY24 Terms (stale)'),
290
+ ('blk-old-arr', 'bullet-list', 'Renewal ARR / contract value: $72,000'),
291
+ ('blk-old-term', 'bullet-list', 'Term: 12 months'),
292
+ ('blk-old-uplift', 'bullet-list', 'Price uplift: 3% vs. prior term'),
293
+ ('blk-old-payment', 'bullet-list', 'Payment terms: Net-30'),
294
+ ('blk-old-closedate', 'bullet-list', 'Renewal (close) date: 2025-08-30'),
295
+ ('blk-old-signer', 'text',
296
+ 'Authorized signer: David Okafor, COO, david.okafor@globex.example.com'),
297
+ ]
298
+
299
+ gs_blocks = [
300
+ ('blk-gs-h1', 'heading-1', 'Vertex Cloud - Renewals Workspace'),
301
+ ('blk-gs-text', 'text',
302
+ 'Home base for the renewals team. Open a customer renewal brief to get started.'),
303
+ ]
304
+
305
+ created = '2026-06-10T09:00:00.000Z'
306
+ blocks = {}
307
+
308
+ def add_blocks(block_list):
309
+ for bid, btype, content in block_list:
310
+ blocks[bid] = {
311
+ 'id': bid, 'type': btype, 'content': content, 'properties': {},
312
+ 'createdDate': created, 'lastEditedDate': created,
313
+ }
314
+
315
+ add_blocks(cur_blocks)
316
+ add_blocks(old_blocks)
317
+ add_blocks(gs_blocks)
318
+
319
+ pages = {
320
+ getting_started_id: {
321
+ 'id': getting_started_id, 'title': 'Vertex Cloud - Renewals Workspace',
322
+ 'icon': '\U0001F680', 'cover': None, 'parentId': None,
323
+ 'blockIds': [b[0] for b in gs_blocks], 'favorite': True,
324
+ 'createdDate': created, 'lastEditedDate': created, 'properties': {},
325
+ },
326
+ cur_page_id: {
327
+ 'id': cur_page_id, 'title': 'Renewal Brief - Globex Corp',
328
+ 'icon': '\U0001F4DD', 'cover': None, 'parentId': None,
329
+ 'blockIds': [b[0] for b in cur_blocks], 'favorite': False,
330
+ 'createdDate': '2026-06-08T10:00:00.000Z',
331
+ 'lastEditedDate': '2026-06-08T10:00:00.000Z', 'properties': {},
332
+ },
333
+ old_page_id: {
334
+ 'id': old_page_id, 'title': 'Renewal Brief - Globex Corp (FY24)',
335
+ 'icon': '\U0001F5C3', 'cover': None, 'parentId': None,
336
+ 'blockIds': [b[0] for b in old_blocks], 'favorite': False,
337
+ 'createdDate': '2024-07-01T10:00:00.000Z',
338
+ 'lastEditedDate': '2024-07-01T10:00:00.000Z', 'properties': {},
339
+ },
340
+ }
341
+
342
+ return {
343
+ 'user': {'id': 'user-1', 'name': 'Jordan Avery',
344
+ 'email': 'jordan.avery@vertexcloud.example.com',
345
+ 'avatar': 'https://picsum.photos/seed/jordan/100/100'},
346
+ 'workspace': {'id': 'ws-1', 'name': 'Vertex Cloud', 'icon': '☁️', 'members': ['user-1']},
347
+ 'pages': pages,
348
+ 'blocks': blocks,
349
+ 'trash': [],
350
+ 'comments': {},
351
+ 'settings': {'appearance': 'light', 'startWeekMonday': False, 'fontSize': 'default'},
352
+ 'notifications': [],
353
+ 'pageOrder': [getting_started_id, cur_page_id, old_page_id],
354
+ 'focusBlockId': None,
355
+ }
356
+
357
+
358
+ # ----------------------------------------------------------------------------
359
+ # DOCUSIGN state
360
+ # ----------------------------------------------------------------------------
361
+ def build_docusign_state():
362
+ user = {
363
+ 'id': 'user_1', 'name': 'Jordan Avery',
364
+ 'email': 'jordan.avery@vertexcloud.example.com',
365
+ 'title': 'Account Manager', 'company': 'Vertex Cloud',
366
+ 'avatar': 'https://picsum.photos/seed/jordan/100/100',
367
+ 'signatureDataUrl': None, 'initialsDataUrl': None, 'memberSince': '2022-04-12',
368
+ 'settings': {'defaultReminderDays': 3, 'defaultExpirationDays': 120,
369
+ 'timezone': 'America/Los_Angeles'},
370
+ }
371
+
372
+ contacts = [
373
+ {'id': 'contact_1', 'name': 'David Okafor', 'email': 'david.okafor@globex.example.com',
374
+ 'company': 'Globex Corp', 'title': 'COO'},
375
+ {'id': 'contact_2', 'name': 'Vertex Cloud Finance', 'email': 'finance@vertexcloud.example.com',
376
+ 'company': 'Vertex Cloud', 'title': 'Finance Mailbox'},
377
+ {'id': 'contact_3', 'name': 'Maria Lindqvist', 'email': 'm.lindqvist@initech.example.com',
378
+ 'company': 'Initech', 'title': 'VP Procurement'},
379
+ {'id': 'contact_4', 'name': 'Tom Becker', 'email': 't.becker@umbrella.example.com',
380
+ 'company': 'Umbrella Inc', 'title': 'Director of IT'},
381
+ {'id': 'contact_5', 'name': 'Priya Nair', 'email': 'priya.nair@hooli.example.com',
382
+ 'company': 'Hooli', 'title': 'Head of Legal'},
383
+ ]
384
+
385
+ templates = [
386
+ {
387
+ 'id': 'tmpl_renewal', 'name': 'Annual Renewal Agreement',
388
+ 'description': 'Standard 12-month SaaS subscription renewal agreement for existing customers.',
389
+ 'createdAt': '2024-01-15T12:00:00Z', 'lastUsedAt': '2026-05-20T10:00:00Z',
390
+ 'usageCount': 24, 'ownerId': 'user_1', 'shared': True,
391
+ 'documents': [{'id': 'tdoc_renewal_1', 'name': 'Annual_Renewal_Agreement.pdf',
392
+ 'pageCount': 5, 'order': 1,
393
+ 'fileUrl': 'https://picsum.photos/seed/renewaltmpl/800/1100', 'fileType': 'pdf'}],
394
+ 'roles': [
395
+ {'id': 'role_renewal_1', 'name': 'Customer Signer', 'role': 'signer', 'routingOrder': 1},
396
+ {'id': 'role_renewal_cc', 'name': 'Vertex Cloud Finance',
397
+ 'role': 'cc', 'routingOrder': 2},
398
+ ],
399
+ 'fields': [],
400
+ },
401
+ {
402
+ 'id': 'tmpl_nda', 'name': 'Standard NDA',
403
+ 'description': 'Mutual non-disclosure agreement.',
404
+ 'createdAt': '2023-09-01T12:00:00Z', 'lastUsedAt': '2026-02-11T10:00:00Z',
405
+ 'usageCount': 41, 'ownerId': 'user_1', 'shared': True,
406
+ 'documents': [{'id': 'tdoc_nda_1', 'name': 'Mutual_NDA.pdf', 'pageCount': 3, 'order': 1,
407
+ 'fileUrl': 'https://picsum.photos/seed/ndatmpl/800/1100', 'fileType': 'pdf'}],
408
+ 'roles': [{'id': 'role_nda_1', 'name': 'Party A', 'role': 'signer', 'routingOrder': 1},
409
+ {'id': 'role_nda_2', 'name': 'Party B', 'role': 'signer', 'routingOrder': 2}],
410
+ 'fields': [],
411
+ },
412
+ {
413
+ 'id': 'tmpl_order', 'name': 'New Order Form',
414
+ 'description': 'Net-new subscription order form for new logos.',
415
+ 'createdAt': '2024-03-20T12:00:00Z', 'lastUsedAt': '2026-04-30T10:00:00Z',
416
+ 'usageCount': 13, 'ownerId': 'user_1', 'shared': False,
417
+ 'documents': [{'id': 'tdoc_order_1', 'name': 'Order_Form.pdf', 'pageCount': 2, 'order': 1,
418
+ 'fileUrl': 'https://picsum.photos/seed/ordertmpl/800/1100', 'fileType': 'pdf'}],
419
+ 'roles': [{'id': 'role_order_1', 'name': 'Authorized Signer', 'role': 'signer', 'routingOrder': 1}],
420
+ 'fields': [],
421
+ },
422
+ ]
423
+
424
+ folders = [
425
+ {'id': 'folder_1', 'name': 'Renewals', 'parentFolder': None, 'createdAt': '2024-01-01T00:00:00Z'},
426
+ {'id': 'folder_2', 'name': 'New Business', 'parentFolder': None, 'createdAt': '2024-01-01T00:00:00Z'},
427
+ ]
428
+
429
+ envelopes = [
430
+ {
431
+ 'id': 'env_initech', 'subject': 'Initech - Annual Renewal Agreement',
432
+ 'message': 'Please review and sign the renewal agreement.', 'status': 'completed',
433
+ 'createdAt': '2026-03-01T09:00:00Z', 'sentAt': '2026-03-01T09:30:00Z',
434
+ 'completedAt': '2026-03-04T15:20:00Z', 'voidedAt': None, 'declinedAt': None,
435
+ 'lastActivityAt': '2026-03-04T15:20:00Z', 'expiresAt': None,
436
+ 'senderId': 'user_1', 'folderId': 'folder_1', 'templateId': 'tmpl_renewal',
437
+ 'reminderEnabled': True, 'reminderDays': 3, 'reminderFrequency': 2,
438
+ 'documents': [{'id': 'doc_in_1', 'name': 'Initech_Renewal.pdf', 'pageCount': 5,
439
+ 'order': 1, 'fileUrl': 'https://picsum.photos/seed/initech/800/1100', 'fileType': 'pdf'}],
440
+ 'recipients': [{'id': 'rec_in_1', 'name': 'Maria Lindqvist',
441
+ 'email': 'm.lindqvist@initech.example.com', 'role': 'signer', 'routingOrder': 1,
442
+ 'status': 'signed', 'signedAt': '2026-03-04T15:20:00Z',
443
+ 'viewedAt': '2026-03-02T08:00:00Z', 'deliveredAt': '2026-03-01T09:31:00Z',
444
+ 'declinedAt': None, 'declineReason': None}],
445
+ 'fields': [],
446
+ 'history': [
447
+ {'id': 'evt_in_1', 'timestamp': '2026-03-01T09:00:00Z', 'action': 'created',
448
+ 'actorName': 'Jordan Avery', 'actorEmail': 'jordan.avery@vertexcloud.example.com',
449
+ 'details': 'Envelope created'},
450
+ {'id': 'evt_in_2', 'timestamp': '2026-03-04T15:20:00Z', 'action': 'completed',
451
+ 'actorName': 'Maria Lindqvist', 'actorEmail': 'm.lindqvist@initech.example.com',
452
+ 'details': 'Signed by all recipients'},
453
+ ],
454
+ },
455
+ {
456
+ 'id': 'env_umbrella', 'subject': 'Umbrella Inc - Mutual NDA',
457
+ 'message': 'NDA for the upcoming evaluation.', 'status': 'sent',
458
+ 'createdAt': '2026-06-05T11:00:00Z', 'sentAt': '2026-06-05T11:10:00Z',
459
+ 'completedAt': None, 'voidedAt': None, 'declinedAt': None,
460
+ 'lastActivityAt': '2026-06-05T11:10:00Z', 'expiresAt': '2026-10-03T11:10:00Z',
461
+ 'senderId': 'user_1', 'folderId': 'folder_2', 'templateId': 'tmpl_nda',
462
+ 'reminderEnabled': False, 'reminderDays': 3, 'reminderFrequency': 2,
463
+ 'documents': [{'id': 'doc_um_1', 'name': 'Umbrella_NDA.pdf', 'pageCount': 3,
464
+ 'order': 1, 'fileUrl': 'https://picsum.photos/seed/umbrella/800/1100', 'fileType': 'pdf'}],
465
+ 'recipients': [{'id': 'rec_um_1', 'name': 'Tom Becker', 'email': 't.becker@umbrella.example.com',
466
+ 'role': 'signer', 'routingOrder': 1, 'status': 'delivered', 'signedAt': None,
467
+ 'viewedAt': '2026-06-06T09:00:00Z', 'deliveredAt': '2026-06-05T11:11:00Z',
468
+ 'declinedAt': None, 'declineReason': None}],
469
+ 'fields': [],
470
+ 'history': [
471
+ {'id': 'evt_um_1', 'timestamp': '2026-06-05T11:00:00Z', 'action': 'created',
472
+ 'actorName': 'Jordan Avery', 'actorEmail': 'jordan.avery@vertexcloud.example.com',
473
+ 'details': 'Envelope created'},
474
+ {'id': 'evt_um_2', 'timestamp': '2026-06-05T11:10:00Z', 'action': 'sent',
475
+ 'actorName': 'Jordan Avery', 'actorEmail': 'jordan.avery@vertexcloud.example.com',
476
+ 'details': 'Envelope sent'},
477
+ ],
478
+ },
479
+ {
480
+ 'id': 'env_hooli', 'subject': 'Hooli - New Order Form (Q3)',
481
+ 'message': 'Draft order form, not yet sent.', 'status': 'draft',
482
+ 'createdAt': '2026-06-18T14:00:00Z', 'sentAt': None,
483
+ 'completedAt': None, 'voidedAt': None, 'declinedAt': None,
484
+ 'lastActivityAt': '2026-06-18T14:00:00Z', 'expiresAt': None,
485
+ 'senderId': 'user_1', 'folderId': 'folder_2', 'templateId': 'tmpl_order',
486
+ 'reminderEnabled': False, 'reminderDays': 3, 'reminderFrequency': 2,
487
+ 'documents': [{'id': 'doc_ho_1', 'name': 'Hooli_Order.pdf', 'pageCount': 2,
488
+ 'order': 1, 'fileUrl': 'https://picsum.photos/seed/hooli/800/1100', 'fileType': 'pdf'}],
489
+ 'recipients': [{'id': 'rec_ho_1', 'name': 'Priya Nair', 'email': 'priya.nair@hooli.example.com',
490
+ 'role': 'signer', 'routingOrder': 1, 'status': 'created', 'signedAt': None,
491
+ 'viewedAt': None, 'deliveredAt': None, 'declinedAt': None, 'declineReason': None}],
492
+ 'fields': [],
493
+ 'history': [
494
+ {'id': 'evt_ho_1', 'timestamp': '2026-06-18T14:00:00Z', 'action': 'created',
495
+ 'actorName': 'Jordan Avery', 'actorEmail': 'jordan.avery@vertexcloud.example.com',
496
+ 'details': 'Envelope created'},
497
+ ],
498
+ },
499
+ ]
500
+
501
+ auditLog = [
502
+ {'id': 'audit_1', 'timestamp': '2026-03-01T09:00:00Z', 'action': 'CREATE_ENVELOPE',
503
+ 'details': 'Initech - Annual Renewal Agreement', 'envelopeId': 'env_initech'},
504
+ {'id': 'audit_2', 'timestamp': '2026-03-04T15:20:00Z', 'action': 'COMPLETE_ENVELOPE',
505
+ 'details': 'Initech - Annual Renewal Agreement', 'envelopeId': 'env_initech'},
506
+ {'id': 'audit_3', 'timestamp': '2026-06-05T11:10:00Z', 'action': 'SEND_ENVELOPE',
507
+ 'details': 'Umbrella Inc - Mutual NDA', 'envelopeId': 'env_umbrella'},
508
+ {'id': 'audit_4', 'timestamp': '2026-06-18T14:00:00Z', 'action': 'CREATE_ENVELOPE',
509
+ 'details': 'Hooli - New Order Form (Q3)', 'envelopeId': 'env_hooli'},
510
+ ]
511
+
512
+ return {'user': user, 'envelopes': envelopes, 'templates': templates,
513
+ 'folders': folders, 'contacts': contacts, 'auditLog': auditLog}
514
+
515
+
516
+ # ----------------------------------------------------------------------------
517
+ # SLACK state
518
+ # ----------------------------------------------------------------------------
519
+ def build_slack_state():
520
+ users = [
521
+ {'userId': 'user_1', 'fullName': 'Jordan Avery', 'displayName': 'Jordan',
522
+ 'email': 'jordan.avery@vertexcloud.example.com', 'avatar': 'https://picsum.photos/200/200?random=1',
523
+ 'title': 'Account Manager', 'status': 'online', 'statusMessage': '', 'statusEmoji': '',
524
+ 'timeZone': 'America/Los_Angeles'},
525
+ {'userId': 'user_2', 'fullName': 'Dana Whitfield', 'displayName': 'Dana',
526
+ 'email': 'dana.whitfield@vertexcloud.example.com', 'avatar': 'https://picsum.photos/200/200?random=2',
527
+ 'title': 'Finance Manager', 'status': 'online', 'statusMessage': '', 'statusEmoji': '',
528
+ 'timeZone': 'America/New_York'},
529
+ {'userId': 'user_3', 'fullName': 'Liam Castellano', 'displayName': 'Liam',
530
+ 'email': 'liam.castellano@vertexcloud.example.com', 'avatar': 'https://picsum.photos/200/200?random=3',
531
+ 'title': 'Legal Counsel', 'status': 'away', 'statusMessage': '', 'statusEmoji': '',
532
+ 'timeZone': 'America/New_York'},
533
+ {'userId': 'user_4', 'fullName': 'Sofia Reyes', 'displayName': 'Sofia',
534
+ 'email': 'sofia.reyes@vertexcloud.example.com', 'avatar': 'https://picsum.photos/200/200?random=4',
535
+ 'title': 'Sales Director', 'status': 'online', 'statusMessage': '', 'statusEmoji': '',
536
+ 'timeZone': 'America/Los_Angeles'},
537
+ ]
538
+
539
+ channels = [
540
+ {'channelId': 'deal-desk', 'name': 'deal-desk',
541
+ 'description': 'Deal desk: pricing approvals, contracts, and renewals coordination',
542
+ 'topic': 'Renewals & contracts', 'isPrivate': False, 'isStarred': True,
543
+ 'members': ['user_1', 'user_2', 'user_3', 'user_4'], 'createdBy': 'user_4',
544
+ 'createdAt': '2025-01-10T10:00:00Z', 'pinnedMessages': [], 'unreadCount': 0},
545
+ {'channelId': 'general', 'name': 'general',
546
+ 'description': 'Company-wide announcements and general discussion',
547
+ 'topic': 'Company-wide announcements', 'isPrivate': False, 'isStarred': False,
548
+ 'members': ['user_1', 'user_2', 'user_3', 'user_4'], 'createdBy': 'user_4',
549
+ 'createdAt': '2024-12-01T10:00:00Z', 'pinnedMessages': [], 'unreadCount': 0},
550
+ {'channelId': 'sales', 'name': 'sales',
551
+ 'description': 'Sales team coordination', 'topic': 'Pipeline & quota',
552
+ 'isPrivate': False, 'isStarred': False,
553
+ 'members': ['user_1', 'user_4'], 'createdBy': 'user_4',
554
+ 'createdAt': '2024-12-01T10:00:00Z', 'pinnedMessages': [], 'unreadCount': 0},
555
+ ]
556
+
557
+ messages = {
558
+ 'deal-desk': [
559
+ {'messageId': 'msg_dd_1', 'senderId': 'user_4',
560
+ 'content': 'Reminder: please post in here once any renewal envelope goes out so finance and legal are looped in.',
561
+ 'timestamp': '2026-06-20T16:00:00Z', 'threadId': None, 'reactions': [],
562
+ 'attachments': [], 'isEdited': False},
563
+ {'messageId': 'msg_dd_2', 'senderId': 'user_2',
564
+ 'content': 'Thanks Sofia. We are watching the Globex renewal closely this quarter.',
565
+ 'timestamp': '2026-06-20T16:05:00Z', 'threadId': None, 'reactions': [],
566
+ 'attachments': [], 'isEdited': False},
567
+ ],
568
+ 'general': [
569
+ {'messageId': 'msg_g_1', 'senderId': 'user_4',
570
+ 'content': 'Welcome to the Vertex Cloud workspace!',
571
+ 'timestamp': '2026-06-01T09:00:00Z', 'threadId': None, 'reactions': [],
572
+ 'attachments': [], 'isEdited': False},
573
+ ],
574
+ 'sales': [
575
+ {'messageId': 'msg_s_1', 'senderId': 'user_1',
576
+ 'content': 'Globex renewal brief is finalized, prepping paperwork next.',
577
+ 'timestamp': '2026-06-19T11:00:00Z', 'threadId': None, 'reactions': [],
578
+ 'attachments': [], 'isEdited': False},
579
+ ],
580
+ }
581
+
582
+ return {
583
+ 'currentUser': users[0],
584
+ 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Vertex Cloud',
585
+ 'icon': 'https://picsum.photos/64/64?random=workspace'},
586
+ 'users': users, 'channels': channels, 'messages': messages,
587
+ 'threads': {}, 'dms': [], 'bookmarkedMessages': [], 'callHistory': [],
588
+ 'settings': {'theme': 'light', 'notifications': 'all', 'displayDensity': 'comfortable',
589
+ 'showAvatars': True, 'use24Hour': False},
590
+ 'invitations': [], 'notifications': [],
591
+ }
592
+
593
+
594
+ # ----------------------------------------------------------------------------
595
+ # Inject + verify (reset first for idempotency across adversarial rounds)
596
+ # ----------------------------------------------------------------------------
597
+ def inject(name, state):
598
+ url = MOCK_URLS[name]
599
+ # Reset clears both initial and current so each round starts clean.
600
+ requests.post(f'{url}/post?sid={SID}', json={'action': 'reset'}, proxies=PROXIES, timeout=60)
601
+ resp = requests.post(f'{url}/post?sid={SID}', json={'action': 'set', 'state': state},
602
+ proxies=PROXIES, timeout=60)
603
+ assert resp.status_code == 200, f'{name} set failed: {resp.status_code} {resp.text[:300]}'
604
+ go = requests.get(f'{url}/go?sid={SID}', proxies=PROXIES, timeout=30).json()
605
+ assert go.get('initial_state') is not None, f'{name} initial_state is None'
606
+ print(f'{name}: injected and verified')
607
+
608
+
609
+ inject('notion', build_notion_state())
610
+ inject('docusign', build_docusign_state())
611
+ inject('slack', build_slack_state())
612
+
613
+
614
+ # --- Launch browser (GUI-ready). DocuSign is the primary deliverable. ---
615
+ def launch_gui(command, delay_sec=1.0):
616
+ env = os.environ.copy()
617
+ env['DISPLAY'] = ':0'
618
+ # Accept both a command string and a pre-split arg list (some tasks
619
+ # build arg lists themselves, e.g. se_hard_008).
620
+ if isinstance(command, str):
621
+ _parts = shlex.split(command)
622
+ else:
623
+ _parts = list(command)
624
+ # Inject CDP debug port so wait_mocks_loaded can verify browser render
625
+ # via Playwright connect_over_cdp. Idempotent: skip if any arg already
626
+ # starts with --remote-debugging-port (some tasks inject their own
627
+ # dynamic port, e.g. se_hard_008).
628
+ if _parts and 'google-chrome' in _parts[0] \
629
+ and not any(p.startswith('--remote-debugging-port') for p in _parts):
630
+ _parts[1:1] = ['--no-first-run', '--no-default-browser-check',
631
+ '--remote-debugging-port=1337']
632
+ _proc = subprocess.Popen(_parts, stdin=subprocess.DEVNULL,
633
+ stdout=subprocess.DEVNULL,
634
+ stderr=subprocess.DEVNULL, env=env,
635
+ start_new_session=True)
636
+ time.sleep(delay_sec)
637
+ if _proc.poll() is not None:
638
+ print(' WARNING: launch_gui process exited early (code=%s)'
639
+ % _proc.returncode)
640
+ return _proc
641
+ notion_tab = f'{MOCK_URLS["notion"]}/?sid={SID}'
642
+ docusign_tab = f'{MOCK_URLS["docusign"]}/?sid={SID}'
643
+ slack_tab = f'{MOCK_URLS["slack"]}/?sid={SID}'
644
+ proxy_flag = f'--proxy-server="{PROXY}" ' if PROXIES else ''
645
+ launch_gui(f'google-chrome {proxy_flag}"{docusign_tab}" "{notion_tab}" "{slack_tab}"', delay_sec=3.0)
646
+ wait_mocks_loaded()
647
+ print('GUI_READY: launched Chrome with DocuSign + Notion + Slack tabs')
648
+ print(f'sid={SID}')
am_renewal_contract_001/reward.py ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: Send Globex Corp renewal DocuSign envelope + post Slack notification
13
+ Task ID: am_renewal_contract_001
14
+ Domain: mock_websites (docusign_mock + slack_mock)
15
+
16
+ Scoring rubric (only scores task-introduced changes; each component FAILS on
17
+ initial_env and PASSES on golden_env):
18
+
19
+ DocuSign (0.70):
20
+ C1 NEW envelope clearly relates to Globex renewal 0.15
21
+ C2 Signer recipient = David Okafor (david.okafor@globex...) 0.15
22
+ C3 CC recipient = finance@vertexcloud.example.com (role cc) 0.10
23
+ C4 Envelope contains >= 1 document 0.05
24
+ C5 Envelope is sent/out for signature 0.15
25
+ C6 Terms match current brief ($85,000/85k), NOT FY24 ($72,000) 0.10
26
+ Slack (0.30):
27
+ C7 NEW message from Jordan (currentUser) in #deal-desk 0.15
28
+ C8 Message says Globex renewal envelope is sent 0.15
29
+
30
+ Total: 1.0
31
+ """
32
+
33
+ import os
34
+ import re
35
+ import sys
36
+
37
+ import requests
38
+
39
+ DOCUSIGN_URL = 'http://28.7.184.198:8130'
40
+ SLACK_URL = 'http://28.7.184.198:8178'
41
+
42
+ # --- Read sid ---
43
+ try:
44
+ with open('/tmp/task_web_sid') as f:
45
+ sid = f.read().strip()
46
+ if not sid:
47
+ raise ValueError('sid is empty')
48
+ except Exception as e:
49
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
50
+ print('REWARD: 0.0')
51
+ sys.exit(0)
52
+
53
+ # --- Egress proxy helper (MANDATORY) ---
54
+ PROXY_CANDIDATES = [
55
+ os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy'),
56
+ None,
57
+ ]
58
+
59
+
60
+ def resolve_proxy(probe_url):
61
+ try:
62
+ requests.get(probe_url, timeout=8)
63
+ return None
64
+ except Exception:
65
+ pass
66
+ for candidate in PROXY_CANDIDATES:
67
+ if not candidate:
68
+ continue
69
+ try:
70
+ requests.get(
71
+ probe_url,
72
+ timeout=12,
73
+ proxies={'http': candidate, 'https': candidate},
74
+ )
75
+ return candidate
76
+ except Exception:
77
+ continue
78
+ return None
79
+
80
+
81
+ PROXY = resolve_proxy(f'{DOCUSIGN_URL}/go?sid=conn-probe')
82
+ PROXIES = {'http': PROXY, 'https': PROXY} if PROXY else None
83
+ print(f'Egress proxy: {PROXY or "direct"}')
84
+
85
+
86
+ def fetch_state(base_url):
87
+ resp = requests.get(f'{base_url}/go?sid={sid}', timeout=15, proxies=PROXIES)
88
+ resp.raise_for_status()
89
+ return resp.json()
90
+
91
+
92
+ # --- Fetch both mocks ---
93
+ try:
94
+ ds = fetch_state(DOCUSIGN_URL)
95
+ sl = fetch_state(SLACK_URL)
96
+ except Exception as e:
97
+ print(f'CRITICAL: Cannot fetch mock state: {e}')
98
+ print('REWARD: 0.0')
99
+ sys.exit(0)
100
+
101
+ ds_initial = ds.get('initial_state') or {}
102
+ ds_current = ds.get('current_state') or {}
103
+ sl_initial = sl.get('initial_state') or {}
104
+ sl_current = sl.get('current_state') or {}
105
+
106
+
107
+ TARGET_SIGNER_NAME = 'David Okafor'
108
+ TARGET_SIGNER_EMAIL = 'david.okafor@globex.example.com'
109
+ TARGET_CC_EMAIL = 'finance@vertexcloud.example.com'
110
+ TARGET_AMOUNT = 85000
111
+ STALE_AMOUNT = 72000
112
+ TARGET_CLOSE_DATE = (2026, 8, 30)
113
+ TARGET_CHANNEL = 'deal-desk'
114
+
115
+
116
+ def _txt(*vals):
117
+ """Lowercased concatenation of stringy values, ignoring None."""
118
+ return ' '.join(str(v) for v in vals if v is not None).lower()
119
+
120
+
121
+ def _norm_text(value):
122
+ return re.sub(r'\s+', ' ', str(value or '').lower()).strip()
123
+
124
+
125
+ def _word_text(value):
126
+ return re.sub(r'[^a-z0-9]+', ' ', _norm_text(value)).strip()
127
+
128
+
129
+ def _norm_email(value):
130
+ return re.sub(r'\s+', '', str(value or '').lower())
131
+
132
+
133
+ def _norm_role(value):
134
+ return _word_text(value)
135
+
136
+
137
+ def _norm_channel(value):
138
+ return re.sub(r'[^a-z0-9]+', '', str(value or '').lower().lstrip('#'))
139
+
140
+
141
+ def _name_matches(value, expected):
142
+ words = re.findall(r'[a-z]+', expected.lower())
143
+ haystack = set(_word_text(value).split())
144
+ return bool(words) and all(w in haystack for w in words)
145
+
146
+
147
+ def _role_is_signer(value):
148
+ role = _norm_role(value)
149
+ return role in {'signer', 'customer signer', 'authorized signer', 'signatory'} \
150
+ or ' signer' in f' {role} ' or ' signatory' in f' {role} '
151
+
152
+
153
+ def _role_is_cc(value):
154
+ role = _norm_role(value)
155
+ return role in {
156
+ 'cc', 'carbon copy', 'copy', 'copied', 'copy recipient',
157
+ 'receives a copy', 'receive a copy',
158
+ } or role.endswith(' cc') or ' carbon copy' in f' {role}'
159
+
160
+
161
+ def _contains_customer(value):
162
+ words = _word_text(value)
163
+ return 'globex' in words.split() or 'globex corp' in words \
164
+ or 'globex corporation' in words
165
+
166
+
167
+ def _contains_renewal(value):
168
+ words = _word_text(value)
169
+ return any(term in words for term in (
170
+ 'renewal', 'renew', 'renewed', 'contract', 'agreement', 'paperwork',
171
+ ))
172
+
173
+
174
+ def _extract_amounts(value):
175
+ text = _norm_text(value).replace(',', '')
176
+ amounts = []
177
+ for match in re.finditer(
178
+ r'(?<![a-z0-9])(?:usd\s*)?\$?\s*(\d+(?:\.\d+)?)\s*(k|thousand)?(?![a-z0-9])',
179
+ text):
180
+ try:
181
+ amount = float(match.group(1))
182
+ except ValueError:
183
+ continue
184
+ if match.group(2):
185
+ amount *= 1000
186
+ amounts.append(round(amount))
187
+ return amounts
188
+
189
+
190
+ def _contains_amount(value, amount):
191
+ return any(abs(found - amount) <= 1 for found in _extract_amounts(value))
192
+
193
+
194
+ def _contains_date(value, year, month, day):
195
+ text = _norm_text(value)
196
+ if re.search(rf'\b{year}\s*[-/.年]\s*0?{month}\s*[-/.月]\s*0?{day}\b', text):
197
+ return True
198
+
199
+ month_names = (
200
+ 'jan(?:uary)?', 'feb(?:ruary)?', 'mar(?:ch)?', 'apr(?:il)?',
201
+ 'may', 'jun(?:e)?', 'jul(?:y)?', 'aug(?:ust)?',
202
+ 'sep(?:t(?:ember)?)?', 'oct(?:ober)?', 'nov(?:ember)?', 'dec(?:ember)?',
203
+ )
204
+ month_re = month_names[month - 1]
205
+ if re.search(rf'\b{month_re}\.?\s+0?{day}(?:st|nd|rd|th)?(?:,)?\s+{year}\b', text):
206
+ return True
207
+ if re.search(rf'\b0?{day}(?:st|nd|rd|th)?\s+{month_re}\.?(?:,)?\s+{year}\b', text):
208
+ return True
209
+
210
+ for match in re.finditer(r'\b(\d{1,4})[-/](\d{1,2})[-/](\d{1,4})\b', text):
211
+ a, b, c = (int(x) for x in match.groups())
212
+ if a == year and b == month and c == day:
213
+ return True
214
+ if c in {year, year % 100} and ((a, b) == (month, day) or (a, b) == (day, month)):
215
+ return True
216
+ return False
217
+
218
+
219
+ def _collect_envelope_text(env, templates_by_id=None, include_recipients=False):
220
+ parts = [env.get('subject'), env.get('message'), env.get('templateId')]
221
+ if templates_by_id:
222
+ tmpl = templates_by_id.get(env.get('templateId')) or {}
223
+ parts.extend([tmpl.get('name'), tmpl.get('description')])
224
+ for doc in env.get('documents') or []:
225
+ parts.append(doc.get('name'))
226
+ for field in env.get('fields') or []:
227
+ parts.extend([field.get('label'), field.get('value')])
228
+ if include_recipients:
229
+ for rec in env.get('recipients') or []:
230
+ parts.extend([rec.get('name'), rec.get('email'), rec.get('role')])
231
+ return _txt(*parts)
232
+
233
+
234
+ def _has_signer(recipients):
235
+ return any(
236
+ _role_is_signer(r.get('role'))
237
+ and _norm_email(r.get('email')) == TARGET_SIGNER_EMAIL
238
+ and _name_matches(r.get('name'), TARGET_SIGNER_NAME)
239
+ for r in recipients
240
+ )
241
+
242
+
243
+ def _has_finance_cc(recipients):
244
+ return any(
245
+ _role_is_cc(r.get('role'))
246
+ and _norm_email(r.get('email')) == TARGET_CC_EMAIL
247
+ for r in recipients
248
+ )
249
+
250
+
251
+ def _is_sent_envelope(env):
252
+ status = _norm_role(env.get('status'))
253
+ sent_at = bool(env.get('sentAt'))
254
+ status_ok = status in {
255
+ 'sent', 'delivered', 'out for signature', 'out for signing',
256
+ 'in progress', 'in_progress', 'waiting for others',
257
+ }
258
+ history_parts = []
259
+ for h in env.get('history') or []:
260
+ history_parts.extend([h.get('action'), h.get('details')])
261
+ history_text = _txt(*history_parts)
262
+ history_sent = any(term in history_text for term in (
263
+ 'sent', 'send envelope', 'envelope sent', 'out for signature',
264
+ ))
265
+ recipient_sent = any(
266
+ _norm_role(r.get('status')) in {'sent', 'delivered', 'viewed'}
267
+ for r in (env.get('recipients') or [])
268
+ )
269
+ return status_ok or sent_at or history_sent or recipient_sent
270
+
271
+
272
+ def _find_relevant_envelope(new_envs, templates_by_id):
273
+ best_env = None
274
+ best_score = 0.0
275
+ for env in new_envs:
276
+ recipients = env.get('recipients') or []
277
+ blob = _collect_envelope_text(env, templates_by_id, include_recipients=True)
278
+ score = 0.0
279
+ if _contains_customer(blob):
280
+ score += 2.0
281
+ if _contains_renewal(blob):
282
+ score += 1.0
283
+ if _has_signer(recipients):
284
+ score += 3.0
285
+ if _has_finance_cc(recipients):
286
+ score += 2.0
287
+ if _contains_amount(blob, TARGET_AMOUNT):
288
+ score += 1.0
289
+ if _is_sent_envelope(env):
290
+ score += 1.0
291
+ if env.get('documents'):
292
+ score += 0.5
293
+ if score > best_score:
294
+ best_env = env
295
+ best_score = score
296
+ return best_env if best_score >= 3.0 else None
297
+
298
+
299
+ def _get_channel_messages(state, target_channel):
300
+ messages = state.get('messages') or {}
301
+ target_norm = _norm_channel(target_channel)
302
+ candidate_keys = []
303
+ for channel in state.get('channels') or []:
304
+ if _norm_channel(channel.get('channelId')) == target_norm \
305
+ or _norm_channel(channel.get('name')) == target_norm:
306
+ candidate_keys.extend([channel.get('channelId'), channel.get('name')])
307
+ candidate_keys.extend(messages.keys())
308
+
309
+ seen = set()
310
+ for key in candidate_keys:
311
+ if key is None or key in seen:
312
+ continue
313
+ seen.add(key)
314
+ if _norm_channel(key) == target_norm and isinstance(messages.get(key), list):
315
+ return messages.get(key) or []
316
+ return []
317
+
318
+
319
+ def _message_fingerprint(message):
320
+ return (
321
+ message.get('senderId'),
322
+ _norm_text(message.get('content')),
323
+ message.get('timestamp'),
324
+ )
325
+
326
+
327
+ def _mentions_sent_notification(value):
328
+ words = _word_text(value)
329
+ raw = _norm_text(value)
330
+ sent_terms = (
331
+ 'sent', 'sent for signature', 'out for signature', 'out for signing',
332
+ 'went out', 'dispatched', 'issued', 'signature request', 'ready for signature',
333
+ )
334
+ has_sent = any(term in raw or term in words for term in sent_terms)
335
+ has_doc_context = any(term in words for term in (
336
+ 'renewal', 'renew', 'envelope', 'docusign', 'agreement', 'contract', 'paperwork',
337
+ ))
338
+ return _contains_customer(value) and has_doc_context and has_sent
339
+
340
+
341
+ def verify_task():
342
+ total = 0.0
343
+
344
+ # ---------- Locate the NEW Globex renewal envelope ----------
345
+ # Only envelopes that did not exist in initial_state count as task output.
346
+ globex_env = None
347
+ try:
348
+ init_ids = {e.get('id') for e in (ds_initial.get('envelopes') or [])}
349
+ new_envs = [e for e in (ds_current.get('envelopes') or [])
350
+ if e.get('id') not in init_ids]
351
+ templates_by_id = {t.get('id'): t for t in (ds_current.get('templates') or [])}
352
+ globex_env = _find_relevant_envelope(new_envs, templates_by_id)
353
+ except Exception as e:
354
+ print(f'ERROR: locating Globex envelope — {e}')
355
+
356
+ # Component 1: NEW envelope clearly relates to the Globex renewal (0.15)
357
+ try:
358
+ if globex_env is not None:
359
+ print(f"PASS: C1 new Globex renewal envelope found "
360
+ f"(subject={globex_env.get('subject')!r}) (+0.15)")
361
+ total += 0.15
362
+ else:
363
+ print('FAIL: C1 no NEW envelope clearly matching Globex renewal signals')
364
+ except Exception as e:
365
+ print(f'ERROR: C1 — {e}')
366
+
367
+ recipients = (globex_env.get('recipients') or []) if globex_env else []
368
+
369
+ # Component 2: signer recipient David Okafor (0.15)
370
+ try:
371
+ signer_ok = _has_signer(recipients)
372
+ if signer_ok:
373
+ print('PASS: C2 signer = David Okafor (david.okafor@globex.example.com) (+0.15)')
374
+ total += 0.15
375
+ else:
376
+ print('FAIL: C2 no signer recipient David Okafor with correct email')
377
+ except Exception as e:
378
+ print(f'ERROR: C2 — {e}')
379
+
380
+ # Component 3: CC recipient finance mailbox (0.10)
381
+ try:
382
+ cc_ok = _has_finance_cc(recipients)
383
+ if cc_ok:
384
+ print('PASS: C3 CC = finance@vertexcloud.example.com (role cc) (+0.10)')
385
+ total += 0.10
386
+ else:
387
+ print('FAIL: C3 no CC recipient finance@vertexcloud.example.com')
388
+ except Exception as e:
389
+ print(f'ERROR: C3 — {e}')
390
+
391
+ # Component 4: envelope contains at least one document (0.05)
392
+ try:
393
+ docs = (globex_env.get('documents') or []) if globex_env else []
394
+ if len(docs) >= 1:
395
+ print(f'PASS: C4 envelope has {len(docs)} document(s) (+0.05)')
396
+ total += 0.05
397
+ else:
398
+ print('FAIL: C4 envelope has no documents')
399
+ except Exception as e:
400
+ print(f'ERROR: C4 — {e}')
401
+
402
+ # Component 5: envelope SENT (status 'sent' + sentAt set) (0.15)
403
+ try:
404
+ status = _norm_text(globex_env.get('status')) if globex_env else ''
405
+ sent_at = globex_env.get('sentAt') if globex_env else None
406
+ if globex_env is not None and _is_sent_envelope(globex_env):
407
+ print(f"PASS: C5 envelope sent (status={status!r}, sentAt={sent_at!r}) (+0.15)")
408
+ total += 0.15
409
+ else:
410
+ print(f'FAIL: C5 envelope not sent (status={status!r}, sentAt={sent_at!r})')
411
+ except Exception as e:
412
+ print(f'ERROR: C5 — {e}')
413
+
414
+ # Component 6: terms match current brief ($85,000) and NOT FY24 ($72,000) (0.10)
415
+ # Search envelope subject, message, document names, and field values/labels.
416
+ try:
417
+ if globex_env is not None:
418
+ blob_parts = [globex_env.get('subject'), globex_env.get('message')]
419
+ for d in (globex_env.get('documents') or []):
420
+ blob_parts.append(d.get('name'))
421
+ for fld in (globex_env.get('fields') or []):
422
+ blob_parts.append(fld.get('value'))
423
+ blob_parts.append(fld.get('label'))
424
+ blob = _txt(*blob_parts)
425
+ has_current = _contains_amount(blob, TARGET_AMOUNT)
426
+ has_stale = _contains_amount(blob, STALE_AMOUNT)
427
+ if has_current and not has_stale:
428
+ print('PASS: C6 terms reference $85,000/85k (current brief), no FY24 $72,000 (+0.10)')
429
+ total += 0.10
430
+ elif has_current and has_stale:
431
+ print('FAIL: C6 both $85,000 and stale $72,000 present — ambiguous terms')
432
+ else:
433
+ print('FAIL: C6 current term $85,000 not found in envelope text')
434
+ else:
435
+ print('FAIL: C6 no Globex envelope to inspect for terms')
436
+ except Exception as e:
437
+ print(f'ERROR: C6 — {e}')
438
+
439
+ # ---------- Slack: new notification from Jordan in #deal-desk ----------
440
+ new_dd_user_msgs = []
441
+ try:
442
+ cur_user = (sl_current.get('currentUser') or {}).get('userId') or 'user_1'
443
+ init_dd = _get_channel_messages(sl_initial, TARGET_CHANNEL)
444
+ cur_dd = _get_channel_messages(sl_current, TARGET_CHANNEL)
445
+ init_msg_ids = {m.get('messageId') for m in init_dd if m.get('messageId')}
446
+ init_fingerprints = {_message_fingerprint(m) for m in init_dd}
447
+ # New messages = those not present in initial, authored by current user (Jordan)
448
+ new_dd_user_msgs = [
449
+ m for m in cur_dd
450
+ if m.get('senderId') == cur_user
451
+ and (
452
+ (m.get('messageId') and m.get('messageId') not in init_msg_ids)
453
+ or _message_fingerprint(m) not in init_fingerprints
454
+ )
455
+ ]
456
+ except Exception as e:
457
+ print(f'ERROR: locating Slack message — {e}')
458
+
459
+ # Component 7: NEW message from Jordan in #deal-desk (0.15)
460
+ try:
461
+ if new_dd_user_msgs:
462
+ print(f'PASS: C7 {len(new_dd_user_msgs)} new message(s) from Jordan in #deal-desk (+0.15)')
463
+ total += 0.15
464
+ else:
465
+ print('FAIL: C7 no new message from current user (Jordan) in #deal-desk')
466
+ except Exception as e:
467
+ print(f'ERROR: C7 — {e}')
468
+
469
+ # Component 8: that message says the Globex renewal envelope is sent/out for signature (0.15)
470
+ try:
471
+ ok_content = False
472
+ for m in new_dd_user_msgs:
473
+ c = m.get('content') or ''
474
+ has_terms = _contains_amount(c, TARGET_AMOUNT) \
475
+ or _contains_date(c, *TARGET_CLOSE_DATE)
476
+ if _mentions_sent_notification(c) or (
477
+ _contains_customer(c) and has_terms and _contains_renewal(c)):
478
+ ok_content = True
479
+ break
480
+ if ok_content:
481
+ print('PASS: C8 Slack message reports the Globex renewal envelope is sent (+0.15)')
482
+ total += 0.15
483
+ else:
484
+ print('FAIL: C8 no new Jordan message clearly reports Globex renewal sent/out for signature')
485
+ except Exception as e:
486
+ print(f'ERROR: C8 — {e}')
487
+
488
+ final = round(min(total, 1.0), 4)
489
+ print(f'\nScore: {total}/1.0')
490
+ print(f'REWARD: {final}')
491
+ return final
492
+
493
+
494
+ verify_task()
am_renewal_contract_001/reward_label.json ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/am_renewal_contract_003/reward.py",
3
+ "api_url": "http://28.7.184.184:8000/v1/chat/completions",
4
+ "model": "Kimi-K2.6",
5
+ "max_code_chars": 100000,
6
+ "created_at": "2026-07-03 20:14:37",
7
+ "label": {
8
+ "task_id": "am_renewal_contract_001",
9
+ "domain": "mock_websites",
10
+ "summary": "验证是否通过 DocuSign 向 David Okafor 发送了 Globex Corp 续约信封(含正确金额与抄送),并在 Slack #deal-desk 频道由 Jordan 发布通知。",
11
+ "is_placeholder": false,
12
+ "data_sources": [
13
+ "/tmp/task_web_sid",
14
+ "docusign_mock",
15
+ "slack_mock"
16
+ ],
17
+ "scoring_components": [
18
+ {
19
+ "name": "Component 1",
20
+ "weight": 0.15,
21
+ "description": "检查是否存在新增的、明确与 Globex 续约相关的 DocuSign 信封",
22
+ "check_logic": "对比 ds_initial 与 ds_current 的 envelopes,排除 initial 中已存在的 id,通过 _find_relevant_envelope 对候选信封按 globex 客户名、renewal 关键词、signer、CC、金额 85000、已发送状态、文档数量等维度打分,返回 best_score >= 3.0 的最佳信封。若 globex_env 不为 None 则通过。",
23
+ "pass_condition": "在 current_state 中存在一个 initial_state 中没有的、且与 Globex 续约强相关的新信封"
24
+ },
25
+ {
26
+ "name": "Component 2",
27
+ "weight": 0.15,
28
+ "description": "检查信封的 signer 收件人是否为 David Okafor",
29
+ "check_logic": "调用 _has_signer(recipients),要求收件人 role 经 _norm_role 归一化后属于 signer 类别,email 经 _norm_email 后等于 'david.okafor@globex.example.com',且 name 经 _name_matches 匹配 'David Okafor'。",
30
+ "pass_condition": "新增信封的 recipients 中存在 email 为 david.okafor@globex.example.com、name 为 David Okafor、role 为 signer 的收件人"
31
+ },
32
+ {
33
+ "name": "Component 3",
34
+ "weight": 0.1,
35
+ "description": "检查信封是否存在 finance@vertexcloud.example.com 的 CC 收件人",
36
+ "check_logic": "调用 _has_finance_cc(recipients),要求收件人 role 经 _norm_role 归一化后属于 cc 类别,且 email 经 _norm_email 后等于 'finance@vertexcloud.example.com'。",
37
+ "pass_condition": "新增信封的 recipients 中存在 email 为 finance@vertexcloud.example.com、role 为 cc 的收件人"
38
+ },
39
+ {
40
+ "name": "Component 4",
41
+ "weight": 0.05,
42
+ "description": "检查信封是否包含至少一份文档",
43
+ "check_logic": "获取 globex_env.get('documents'),判断列表长度是否 >= 1。",
44
+ "pass_condition": "新增信封的 documents 列表长度大于等于 1"
45
+ },
46
+ {
47
+ "name": "Component 5",
48
+ "weight": 0.15,
49
+ "description": "检查信封是否已发送/待签署",
50
+ "check_logic": "调用 _is_sent_envelope(globex_env),检查 status 是否为 sent/delivered/out for signature 等,或 sentAt 字段存在,或 history 文本包含 sent 相关记录,或 recipients 的 status 为 sent/delivered/viewed。",
51
+ "pass_condition": "信封状态为已发送、已投递或待签署,或在历史记录/收件人状态中体现已发送"
52
+ },
53
+ {
54
+ "name": "Component 6",
55
+ "weight": 0.1,
56
+ "description": "检查信封文本是否包含当前合同金额 $85,000/85k,且不包含旧金额 $72,000",
57
+ "check_logic": "收集信封的 subject、message、documents.name、fields.value/label 拼接为 blob,调用 _contains_amount(blob, 85000) 和 _contains_amount(blob, 72000)。仅当 has_current 为真且 has_stale 为假时通过。",
58
+ "pass_condition": "信封文本中包含 85000(或 85k)且不含 72000(或 72k)"
59
+ },
60
+ {
61
+ "name": "Component 7",
62
+ "weight": 0.15,
63
+ "description": "检查 Slack #deal-desk 频道是否有 Jordan(当前用户)发送的新消息",
64
+ "check_logic": "获取 sl_current 的 currentUser.userId 作为 cur_user,对比 initial 与 current 的 #deal-desk 消息。排除 initial 中已存在的 messageId 或 fingerprint,筛选 senderId == cur_user 的消息。若 new_dd_user_msgs 非空则通过。",
65
+ "pass_condition": "#deal-desk 频道中存在 initial_state 中没有的、由当前用户(Jordan)发送的新消息"
66
+ },
67
+ {
68
+ "name": "Component 8",
69
+ "weight": 0.15,
70
+ "description": "检查 Jordan 的新消息是否报告 Globex 续约信封已发送/待签署",
71
+ "check_logic": "遍历 new_dd_user_msgs,检查 content 是否满足 _mentions_sent_notification(c)(包含 globex、sent 相关词、文档上下文),或同时满足 _contains_customer(c)、_contains_renewal(c) 以及金额 85000 或日期 2026-08-30。",
72
+ "pass_condition": "新消息内容明确提及 Globex 续约信封已发送/已发出/待签署"
73
+ }
74
+ ],
75
+ "total_max_score": 1.0,
76
+ "score_aggregation": "各组件分数累加,最终通过 round(min(total, 1.0), 4) 钳制到上限 1.0",
77
+ "failure_modes": [
78
+ "读取 /tmp/task_web_sid 失败或为空时打印 CRITICAL 并返回 0.0",
79
+ "请求 docusign_mock 或 slack_mock 状态失败时打印 CRITICAL 并返回 0.0",
80
+ "未找到新的 Globex 续约信封导致 C1 失败,并连带使 C2-C6 无法通过",
81
+ "#deal-desk 频道没有 Jordan 的新消息导致 C7 失败,并连带使 C8 无法通过",
82
+ "C6 中同时出现 $85,000 与 $72,000 会被判定为 ambiguous terms 而失败"
83
+ ],
84
+ "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话标识,失败则直接退出并返回 0.0。接着通过 HTTP 请求拉取 docusign_mock 和 slack_mock 的 initial_state 与 current_state,拉取失败同样返回 0.0。评分分为 DocuSign(0.70)和 Slack(0.30)两大部分。DocuSign 部分通过对比信封 id 找出新增信封,再利用多维度打分函数 _find_relevant_envelope 定位最可能的 Globex 续约信封,随后依次验证 signer、CC、文档数量、发送状态及合同金额(必须含 85000 且不含 72000)。Slack 部分通过对比 #deal-desk 频道的初始消息与当前消息,找出 Jordan 发送的新消息,并验证其内容是否报告了 Globex 续约信封已发送。8 个组件的得分累加后,使用 min(total, 1.0) 钳制上限并四舍五入到 4 位小数作为最终 REWARD。",
85
+ "confidence": 1.0
86
+ },
87
+ "raw_response": "用户要求我分析一个 reward.py 评分脚本的评分逻辑,并输出一个严格的 JSON 对象。\n\n让我仔细阅读代码并提取信息:\n\n1. **task_id**: 从 docstring 中可以看到 \"Task ID: am_renewal_contract_003\"\n2. **domain**: 从 docstring 中可以看到 \"Domain: mock_websites (docusign_mock + slack_mock)\"\n3. **summary**: 一句话概括:验证是否通过 DocuSign 发送了 Globex Corp 续约信封并在 Slack #deal-desk 频道通知。\n4. **is_placeholder**: false,因为脚本有详细的检查逻辑。\n5. **data_sources**: \n - `/tmp/task_web_sid` (读取 sid)\n - `docusign_mock` (通过 http://28.7.186.212:8150 访问)\n - `slack_mock` (通过 http://28.7.186.212:8198 访问)\n\n6. **scoring_components**:\n - C1: 0.15 - NEW envelope clearly relates to Globex renewal\n - C2: 0.15 - Signer recipient = David Okafor\n - C3: 0.10 - CC recipient = finance@vertexcloud.example.com\n - C4: 0.05 - Envelope contains >= 1 document\n - C5: 0.15 - Envelope is sent/out for signature\n - C6: 0.10 - Terms match current brief ($85,000/85k), NOT FY24 ($72,000)\n - C7: 0.15 - NEW message from Jordan in #deal-desk\n - C8: 0.15 - Message says Globex renewal envelope is sent\n\n 让我详细看每个组件的检查逻辑:\n\n **C1**: \n - 检查 `globex_env is not None`\n - `globex_env` 是通过 `_find_relevant_envelope(new_envs, templates_by_id)` 找到的\n - `_find_relevant_envelope` 要求 best_score >= 3.0\n - 评分基于:包含 customer (globex) +2, 包含 renewal +1, 有 signer +3, 有 finance cc +2, 包含 amount 85000 +1, 已发送 +1, 有文档 +0.5\n - pass_condition: 找到一个新的、与 Globex 续约相关的信封(best_score >= 3.0)\n\n **C2**:\n - 检查 `_has_signer(recipients)`\n - `_has_signer` 要求:role 是 signer 相关,email 归一化后等于 'david.okafor@globex.example.com',name 匹配 'David Okafor'\n - pass_condition: 收件人中有 David Okafor 作为 signer\n\n **C3**:\n - 检查 `_has_finance_cc(recipients)`\n - 要求:role 是 cc 相关,email 归一化后等于 'finance@vertexcloud.example.com'\n - pass_condition: 收件人中有 finance@vertexcloud.example.com 作为 CC\n\n **C4**:\n - 检查 `len(docs) >= 1`\n - pass_condition: 信封包含至少 1 个文档\n\n **C5**:\n - 检查 `_is_sent_envelope(globex_env)`\n - `_is_sent_envelope` 检查 status 是否为 sent/delivered/out for signature 等,或 sentAt 存在,或 history 中有 sent 相关记录,或 recipient 状态为 sent/delivered/viewed\n - pass_condition: 信封已发送/待签署\n\n **C6**:\n - 检查信封文本(subject, message, document names, field values/labels)中是否包含 $85,000/85k 且不包含 $72,000\n - `_contains_amount(blob, TARGET_AMOUNT)` 和 `_contains_amount(blob, STALE_AMOUNT)`\n - pass_condition: 包含当前合同金额 $85,000 且不包含旧金额 $72,000\n\n **C7**:\n - 检查 `new_dd_user_msgs` 非空\n - 新消息定义为:senderId == currentUser (Jordan),且不在 initial 消息中(通过 messageId 或 fingerprint 判断)\n - pass_condition: #deal-desk 频道有 Jordan 发送的新消息\n\n **C8**:\n - 检查新消息内容是否提到 Globex 续约信封已发送\n - `_mentions_sent_notification(c)` 或 (`_contains_customer(c) and has_terms and _contains_renewal(c)`)\n - `_mentions_sent_notification` 要求:包含 customer (globex),有 sent 相关术语,有 doc 上下文(renewal/envelope/docusign 等)\n - pass_condition: 消息内容明确报告 Globex 续约信封已发送/待签署\n\n7. **total_max_score**: 1.0\n8. **score_aggregation**: 各组件分数相加,最后 `round(min(total, 1.0), 4)`,即相加后钳制到 1.0\n9. **failure_modes**:\n - 读取 `/tmp/task_web_sid` 失败或为空 -> CRITICAL, REWARD: 0.0, sys.exit(0)\n - 获取 mock 状态失败(ds 或 sl)-> CRITICAL, REWARD: 0.0, sys.exit(0)\n - 找不到新的 Globex 续约信封 -> C1 失败,后续 C2-C6 也会失败(因为依赖 globex_env)\n - 没有新消息 -> C7 失败,C8 也失败\n\n10. **scoring_logic_explanation**: \n - 首先读取 /tmp/task_web_sid 获取会话 ID,失败则返回 0.0。\n - 解析代理设置,然后分别请求 docusign_mock 和 slack_mock 的 /go?sid={sid} 获取初始状态和当前状态。\n - DocuSign 部分:对比 initial_state 和 current_state 的 envelopes,找出新增信封。通过 _find_relevant_envelope 按 Globex 相关信号打分,选出最佳匹配(>=3.0 分)。然后逐项检查:C1 存在新信封,C2 有 David Okafor 作为 signer,C3 有 finance@vertexcloud.example.com 作为 CC,C4 有至少一个文档,C5 信封已发送,C6 文本包含 $85,000 且不包含 $72,000。\n - Slack 部分:获取 #deal-desk 频道的初始和当前消息,筛选出当前用户(Jordan)发送的新消息。C7 检查是否存在这样的新消息,C8 检查消息内容是否报告 Globex 续约信封已发送。\n - 各组件分数累加,最终用 min(total, 1.0) 钳制到 1.0 并四舍五入到 4 位小数。\n\n11. **confidence**: 1.0(代码逻辑清晰完整)\n\n让我再仔细检查一下各个字段的权重和描述是否准确。\n\nC1 weight: 0.15\nC2 weight: 0.15\nC3 weight: 0.10\nC4 weight: 0.05\nC5 weight: 0.15\nC6 weight: 0.10\nC7 weight: 0.15\nC8 weight: 0.15\n\nTotal = 1.0\n\n检查 JSON 格式要求:\n- 只输出一个 JSON 对象\n- 不要输出 Markdown 代码块标记\n- 不要输出额外解释\n- 不要输出思考过程\n- 不要输出 <thinking> 标签\n- 输出的第一个字符必须是 {,最后一个字符必须是 }\n- 所有字符串 value 使用中文;task_id、domain、字段名、代码标识符保留原样\n\n我需要确保所有 value 都是中文,但代码中的字段名、函数名、标识符保留原样。\n\n让我构建 JSON:\n\n{\n \"task_id\": \"am_renewal_contract_003\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证是否通过 DocuSign 向 David Okafor 发送了 Globex Corp 续约信封(含正确金额与抄送),并在 Slack #deal-desk 频道由 Jordan 发布通知。\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"docusign_mock\", \"slack_mock\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 1\",\n \"weight\": 0.15,\n \"description\": \"检查是否存在新增的、明确与 Globex 续约相关的 DocuSign 信封\",\n \"check_logic\": \"对比 ds_initial 与 ds_current 的 envelopes,排除 initial 中已存在的 id,通过 _find_relevant_envelope 对候选信封按 globex 客户名、renewal 关键词、signer、CC、金额 85000、已发送状态、文档数量等维度打分,返回 best_score >= 3.0 的最佳信封。若 globex_env 不为 None 则通过。\",\n \"pass_condition\": \"在 current_state 中存在一个 initial_state 中没有的、且与 Globex 续约强相关的新信封\"\n },\n {\n \"name\": \"Component 2\",\n \"weight\": 0.15,\n \"description\": \"检查信封的 signer 收件人是否为 David Okafor\",\n \"check_logic\": \"调用 _has_signer(recipients),要求收件人 role 经 _norm_role 归一化后属于 signer 类别,email 经 _norm_email 后等于 'david.okafor@globex.example.com',且 name 经 _name_matches 匹配 'David Okafor'。\",\n \"pass_condition\": \"新增信封的 recipients 中存在 email 为 david.okafor@globex.example.com、name 为 David Okafor、role 为 signer 的收件人\"\n },\n {\n \"name\": \"Component 3\",\n \"weight\": 0.10,\n \"description\": \"检查信封是否存在 finance@vertexcloud.example.com 的 CC 收件人\",\n \"check_logic\": \"调用 _has_finance_cc(recipients),要求收件人 role 经 _norm_role 归一化后属于 cc 类别,且 email 经 _norm_email 后等于 'finance@vertexcloud.example.com'。\",\n \"pass_condition\": \"新增信封的 recipients 中存在 email 为 finance@vertexcloud.example.com、role 为 cc 的收件人\"\n },\n {\n \"name\": \"Component 4\",\n \"weight\": 0.05,\n \"description\": \"检查信封是否包含至少一份文档\",\n \"check_logic\": \"获取 globex_env.get('documents'),判断列表长度是否 >= 1。\",\n \"pass_condition\": \"新增信封的 documents 列表长度大于等于 1\"\n },\n {\n \"name\": \"Component 5\",\n \"weight\": 0.15,\n \"description\": \"检查信封是否已发送/待签署\",\n \"check_logic\": \"调用 _is_sent_envelope(globex_env),检查 status 是否为 sent/delivered/out for signature 等,或 sentAt 字段存在,或 history 文本包含 sent 相关记录,或 recipients 的 status 为 sent/delivered/viewed。\",\n \"pass_condition\": \"信封状态为已发送、已投递或待签署,或在历史记录/收件人状态中体现已发送\"\n },\n {\n \"name\": \"Component 6\",\n \"weight\": 0.10,\n \"description\": \"检查信封文本是否包含当前合同金额 $85,000/85k,且不包含旧金额 $72,000\",\n \"check_logic\": \"收集信封的 subject、message、documents.name、fields.value/label 拼接为 blob,调用 _contains_amount(blob, 85000) 和 _contains_amount(blob, 72000)。仅当 has_current 为真且 has_stale 为假时通过。\",\n \"pass_condition\": \"信封文本中包含 85000(或 85k)且不含 72000(或 72k)\"\n },\n {\n \"name\": \"Component 7\",\n \"weight\": 0.15,\n \"description\": \"检查 Slack #deal-desk 频道是否有 Jordan(当前用户)发送的新消息\",\n \"check_logic\": \"获取 sl_current 的 currentUser.userId 作为 cur_user,对比 initial 与 current 的 #deal-desk 消息。排除 initial 中已存在的 messageId 或 fingerprint,筛选 senderId == cur_user 的消息。若 new_dd_user_msgs 非空则通过。\",\n \"pass_condition\": \"#deal-desk 频道中存在 initial_state 中没有的、由当前用户(Jordan)发送的新消息\"\n },\n {\n \"name\": \"Component 8\",\n \"weight\": 0.15,\n \"description\": \"检查 Jordan 的新消息是否报告 Globex 续约信封已发送/待签署\",\n \"check_logic\": \"遍历 new_dd_user_msgs,检查 content 是否满足 _mentions_sent_notification(c)(包含 globex、sent 相关词、文档上下文),或同时满足 _contains_customer(c)、_contains_renewal(c) 以及金额 85000 或日期 2026-08-30。\",\n \"pass_condition\": \"新消息内容明确提及 Globex 续约信封已发送/已发出/待签署\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数累加,最终通过 round(min(total, 1.0), 4) 钳制到上限 1.0\",\n \"failure_modes\": [\n \"读取 /tmp/task_web_sid 失败或为空时打印 CRITICAL 并返回 0.0\",\n \"请求 docusign_mock 或 slack_mock 状态失败时打印 CRITICAL 并返回 0.0\",\n \"未找到新的 Globex 续约信封导致 C1 失败,并连带使 C2-C6 无法通过\",\n \"#deal-desk 频道没有 Jordan 的新消息导致 C7 失败,并连带使 C8 无法通过\",\n \"C6 中同时出现 $85,000 与 $72,000 会被判定为 ambiguous terms 而失败\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话标识,失败则直接退出并返回 0.0。接着通过 HTTP 请求拉取 docusign_mock 和 slack_mock 的 initial_state 与 current_state,拉取失败同样返回 0.0。评分分为 DocuSign(0.70)和 Slack(0.30)两大部分。DocuSign 部分通过对比信封 id 找出新增信封,再利用多维度打分函数 _find_relevant_envelope 定位最可能的 Globex 续约信封,随后依次验证 signer、CC、文档数量、发送状态及合同金额(必须含 85000 且不含 72000)。Slack 部分通过对比 #deal-desk 频道的初始消息与当前消息,找出 Jordan 发送的新消息,并验证其内容是否报告了 Globex 续约信封已发送。8 个组件的得分累加后,使用 min(total, 1.0) 钳制上限并四舍五入到 4 位小数作为最终 REWARD。\",\n \"confidence\": 1.0\n}\n\n我需要确保 JSON 是合法的,没有多余的逗号,所有字符串都正确转义。\n\n再检查一下 domain,docstring 写的是 \"mock_websites (docusign_mock + slack_mock)\",我简化为 \"mock_websites\" 是合理的,因为字段说明要求如 mock_websites / software_engineer / libreoffice_calc。\n\n再检查 summary 和 scoring_logic_explanation 是否用了中文。是的。\n\n再检查 failure_modes 中的 \"C6 中同时出现 $85,000 与 $72,000 会被判定为 ambiguous terms 而失败\" —— 代码中确实有这个分支:`elif has_current and has_stale: print('FAIL: C6 both $85,000 and stale $72,000 present — ambiguous terms')`,虽然没有提前退出,但会扣分(不加分),所以作为 failure mode 是合理的。\n\n再检查 C8 的 check_logic,代码中是:\n```python\nif _mentions_sent_notification(c) or (\n _contains_customer(c) and has_terms and _contains_renewal(c)):\n```\n其中 has_terms = `_contains_amount(c, TARGET_AMOUNT) or _contains_date(c, *TARGET_CLOSE_DATE)`\n\n我在描述中写了\"以及金额 85000 或日期 2026-08-30\",这是准确的。\n\n一切看起来都正确。 </think> {\n \"task_id\": \"am_renewal_contract_003\",\n \"domain\": \"mock_websites\",\n \"summary\": \"验证是否通过 DocuSign 向 David Okafor 发送了 Globex Corp 续约信封(含正确金额与抄送),并在 Slack #deal-desk 频道由 Jordan 发布通知。\",\n \"is_placeholder\": false,\n \"data_sources\": [\"/tmp/task_web_sid\", \"docusign_mock\", \"slack_mock\"],\n \"scoring_components\": [\n {\n \"name\": \"Component 1\",\n \"weight\": 0.15,\n \"description\": \"检查是否存在新增的、明确与 Globex 续约相关的 DocuSign 信封\",\n \"check_logic\": \"对比 ds_initial 与 ds_current 的 envelopes,排除 initial 中已存在的 id,通过 _find_relevant_envelope 对候选信封按 globex 客户名、renewal 关键词、signer、CC、金额 85000、已发送状态、文档数量等维度打分,返回 best_score >= 3.0 的最佳信封。若 globex_env 不为 None 则通过。\",\n \"pass_condition\": \"在 current_state 中存在一个 initial_state 中没有的、且与 Globex 续约强相关的新信封\"\n },\n {\n \"name\": \"Component 2\",\n \"weight\": 0.15,\n \"description\": \"检查信封的 signer 收件人是否为 David Okafor\",\n \"check_logic\": \"调用 _has_signer(recipients),要求收件人 role 经 _norm_role 归一化后属于 signer 类别,email 经 _norm_email 后等于 'david.okafor@globex.example.com',且 name 经 _name_matches 匹配 'David Okafor'。\",\n \"pass_condition\": \"新增信封的 recipients 中存在 email 为 david.okafor@globex.example.com、name 为 David Okafor、role 为 signer 的收件人\"\n },\n {\n \"name\": \"Component 3\",\n \"weight\": 0.10,\n \"description\": \"检查信封是否存在 finance@vertexcloud.example.com 的 CC 收件人\",\n \"check_logic\": \"调用 _has_finance_cc(recipients),要求收件人 role 经 _norm_role 归一化后属于 cc 类别,且 email 经 _norm_email 后等于 'finance@vertexcloud.example.com'。\",\n \"pass_condition\": \"新增信封的 recipients 中存在 email 为 finance@vertexcloud.example.com、role 为 cc 的收件人\"\n },\n {\n \"name\": \"Component 4\",\n \"weight\": 0.05,\n \"description\": \"检查信封是否包含至少一份文档\",\n \"check_logic\": \"获取 globex_env.get('documents'),判断列表长度是否 >= 1。\",\n \"pass_condition\": \"新增信封的 documents 列表长度大于等于 1\"\n },\n {\n \"name\": \"Component 5\",\n \"weight\": 0.15,\n \"description\": \"检查信封是否已发送/待签署\",\n \"check_logic\": \"调用 _is_sent_envelope(globex_env),检查 status 是否为 sent/delivered/out for signature 等,或 sentAt 字段存在,或 history 文本包含 sent 相关记录,或 recipients 的 status 为 sent/delivered/viewed。\",\n \"pass_condition\": \"信封状态为已发送、已投递或待签署,或在历史记录/收件人状态中体现已发送\"\n },\n {\n \"name\": \"Component 6\",\n \"weight\": 0.10,\n \"description\": \"检查信封文本是否包含当前合同金额 $85,000/85k,且不包含旧金额 $72,000\",\n \"check_logic\": \"收集信封的 subject、message、documents.name、fields.value/label 拼接为 blob,调用 _contains_amount(blob, 85000) 和 _contains_amount(blob, 72000)。仅当 has_current 为真且 has_stale 为假时通过。\",\n \"pass_condition\": \"信封文本中包含 85000(或 85k)且不含 72000(或 72k)\"\n },\n {\n \"name\": \"Component 7\",\n \"weight\": 0.15,\n \"description\": \"检查 Slack #deal-desk 频道是否有 Jordan(当前用户)发送的新消息\",\n \"check_logic\": \"获取 sl_current 的 currentUser.userId 作为 cur_user,对比 initial 与 current 的 #deal-desk 消息。排除 initial 中已存在的 messageId 或 fingerprint,筛选 senderId == cur_user 的消息。若 new_dd_user_msgs 非空则通过。\",\n \"pass_condition\": \"#deal-desk 频道中存在 initial_state 中没有的、由当前用户(Jordan)发送的新消息\"\n },\n {\n \"name\": \"Component 8\",\n \"weight\": 0.15,\n \"description\": \"检查 Jordan 的新消息是否报告 Globex 续约信封已发送/待签署\",\n \"check_logic\": \"遍历 new_dd_user_msgs,检查 content 是否满足 _mentions_sent_notification(c)(包含 globex、sent 相关词、文档上下文),或同时满足 _contains_customer(c)、_contains_renewal(c) 以及金额 85000 或日期 2026-08-30。\",\n \"pass_condition\": \"新消息内容明确提及 Globex 续约信封已发送/已发出/待签署\"\n }\n ],\n \"total_max_score\": 1.0,\n \"score_aggregation\": \"各组件分数累加,最终通过 round(min(total, 1.0), 4) 钳制到上限 1.0\",\n \"failure_modes\": [\n \"读取 /tmp/task_web_sid 失败或为空时打印 CRITICAL 并返回 0.0\",\n \"请求 docusign_mock 或 slack_mock 状态失败时打印 CRITICAL 并返回 0.0\",\n \"未找到新的 Globex 续约信封导致 C1 失败,并连带使 C2-C6 无法通过\",\n \"#deal-desk 频道没有 Jordan 的新消息导致 C7 失败,并连带使 C8 无法通过\",\n \"C6 中同时出现 $85,000 与 $72,000 会被判定为 ambiguous terms 而失败\"\n ],\n \"scoring_logic_explanation\": \"脚本首先读取 /tmp/task_web_sid 获取会话标识,失败则直接退出并返回 0.0。接着通过 HTTP 请求拉取 docusign_mock 和 slack_mock 的 initial_state 与 current_state,拉取失败同样返回 0.0。评分分为 DocuSign(0.70)和 Slack(0.30)两大部分。DocuSign 部分通过对比信封 id 找出新增信封,再利用多维度打分函数 _find_relevant_envelope 定位最可能的 Globex 续约信封,随后依次验证 signer、CC、文档数量、发送状态及合同金额(必须含 85000 且不含 72000)。Slack 部分通过对比 #deal-desk 频道的初始消息与当前消息,找出 Jordan 发送的新消息,并验证其内容是否报告了 Globex 续约信封已发送。8 个组件的得分累加后,使用 min(total, 1.0) 钳制上限并四舍五入到 4 位小数作为最终 REWARD。\",\n \"confidence\": 1.0\n}"
88
+ }
ar_closeout_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"
ar_closeout_006/initial_setup.py ADDED
@@ -0,0 +1,928 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: month-end AR closeout across seven live mock web apps.
3
+ Task ID: ar_closeout_006
4
+ Domain: mock_websites
5
+
6
+ The previous setup only opened a static dashboard backed by local JSON files.
7
+ This version injects the pre-task state into the shared mock services, persists
8
+ one sid for reward.py, verifies every service, and opens each app in Chrome.
9
+ """
10
+ import base64
11
+ import json
12
+ import os
13
+ import shlex
14
+ import subprocess
15
+ import time
16
+ import uuid
17
+
18
+ import requests
19
+
20
+
21
+ TASK_ID = "prof20_ar_closeout_003"
22
+ BASE = "http://28.7.184.198"
23
+ MOCKS = {
24
+ "salesforce": f"{BASE}:8175",
25
+ "hubspot": f"{BASE}:8150",
26
+ "docusign": f"{BASE}:8130",
27
+ "google_sheets": f"{BASE}:8145",
28
+ "slack": f"{BASE}:8178",
29
+ "gmail": f"{BASE}:8138",
30
+ "google_docs": f"{BASE}:8142",
31
+ }
32
+
33
+ # The VM bridge configures this globally; set it in-process as well so requests
34
+ # never sends the private mock host through the corporate HTTP proxy.
35
+ for proxy_var in ("no_proxy", "NO_PROXY"):
36
+ bypass = os.environ.get(proxy_var, "")
37
+ if "28.7.184.198" not in bypass:
38
+ os.environ[proxy_var] = ",".join(filter(None, [bypass, "28.7.184.198"]))
39
+
40
+ SID = str(uuid.uuid4())
41
+
42
+
43
+ def avatar(name):
44
+ return (
45
+ "https://ui-avatars.com/api/?name="
46
+ + name.replace(" ", "+")
47
+ + "&background=1A73E8&color=fff"
48
+ )
49
+
50
+
51
+ def build_salesforce():
52
+ users = [
53
+ {
54
+ "userId": "user-ar",
55
+ "firstName": "Dana",
56
+ "lastName": "Whitman",
57
+ "email": "ar@saas-co.com",
58
+ "phone": "(555) 100-1000",
59
+ "title": "AR Specialist",
60
+ "department": "Finance",
61
+ "role": "Finance Operations",
62
+ "avatar": avatar("Dana Whitman"),
63
+ "timezone": "America/New_York",
64
+ "locale": "en-US",
65
+ "theme": "lightning",
66
+ },
67
+ {
68
+ "userId": "user-tom",
69
+ "firstName": "Tom",
70
+ "lastName": "Reyes",
71
+ "email": "tom.reyes@saas-co.com",
72
+ "phone": "(555) 100-1001",
73
+ "title": "Account Executive",
74
+ "department": "Sales",
75
+ "role": "User",
76
+ "avatar": avatar("Tom Reyes"),
77
+ "timezone": "America/Los_Angeles",
78
+ "locale": "en-US",
79
+ "theme": "lightning",
80
+ },
81
+ ]
82
+ accounts = [
83
+ {
84
+ "accountId": "acct-cobalt",
85
+ "name": "Cobalt Freight LLC",
86
+ "phone": "(303) 555-0174",
87
+ "website": "https://cobaltfreight.example",
88
+ "type": "Customer",
89
+ "industry": "Transportation",
90
+ "revenue": 120000000,
91
+ "employees": 900,
92
+ "description": "Enterprise freight and logistics account.",
93
+ "ownerId": "user-tom",
94
+ "billingStreet": "1700 Blake St",
95
+ "billingCity": "Denver",
96
+ "billingState": "CO",
97
+ "billingZip": "80202",
98
+ "billingCountry": "United States",
99
+ "shippingStreet": "1700 Blake St",
100
+ "shippingCity": "Denver",
101
+ "shippingState": "CO",
102
+ "shippingZip": "80202",
103
+ "shippingCountry": "United States",
104
+ "createdDate": "2025-02-10T09:00:00.000Z",
105
+ "modifiedDate": "2026-07-01T09:00:00.000Z",
106
+ },
107
+ {
108
+ "accountId": "acct-sable",
109
+ "name": "Sable Robotics",
110
+ "phone": "(512) 555-0193",
111
+ "website": "https://sablerobotics.example",
112
+ "type": "Customer",
113
+ "industry": "Manufacturing",
114
+ "revenue": 28000000,
115
+ "employees": 180,
116
+ "description": "Industrial robotics customer.",
117
+ "ownerId": "user-tom",
118
+ "billingStreet": "600 Congress Ave",
119
+ "billingCity": "Austin",
120
+ "billingState": "TX",
121
+ "billingZip": "78701",
122
+ "billingCountry": "United States",
123
+ "shippingStreet": "600 Congress Ave",
124
+ "shippingCity": "Austin",
125
+ "shippingState": "TX",
126
+ "shippingZip": "78701",
127
+ "shippingCountry": "United States",
128
+ "createdDate": "2025-11-04T09:00:00.000Z",
129
+ "modifiedDate": "2026-07-01T09:00:00.000Z",
130
+ },
131
+ ]
132
+ opportunities = [
133
+ {
134
+ "opportunityId": "OPP-7740",
135
+ "name": "Cobalt Freight — Trial",
136
+ "accountId": "acct-cobalt",
137
+ "amount": 12000,
138
+ "closeDate": "2026-06-20T00:00:00.000Z",
139
+ "stage": "Closed Lost",
140
+ "probability": 0,
141
+ "ownerId": "user-tom",
142
+ "type": "New Business",
143
+ "leadSource": "Outbound",
144
+ "nextStep": "None — closed lost",
145
+ "description": "Trial opportunity. Closed Lost — do not process.",
146
+ "createdDate": "2026-05-10T09:00:00.000Z",
147
+ "modifiedDate": "2026-06-20T12:00:00.000Z",
148
+ },
149
+ {
150
+ "opportunityId": "OPP-7741",
151
+ "name": "Cobalt Freight — Enterprise",
152
+ "accountId": "acct-cobalt",
153
+ "amount": 95000,
154
+ "closeDate": "2026-07-01T00:00:00.000Z",
155
+ "stage": "Closed Won",
156
+ "probability": 100,
157
+ "ownerId": "user-tom",
158
+ "type": "New Business",
159
+ "leadSource": "Outbound",
160
+ "nextStep": "Create draft invoice; finance approval required",
161
+ "description": (
162
+ "Closed-Won enterprise deal. Payment Terms: Net 30. "
163
+ "Discount applied: 22% (approval threshold: 15%). "
164
+ "DocuSign: MSA — Cobalt Freight (OPP-7741)."
165
+ ),
166
+ "createdDate": "2026-05-20T09:00:00.000Z",
167
+ "modifiedDate": "2026-07-01T09:00:00.000Z",
168
+ },
169
+ {
170
+ "opportunityId": "OPP-7743",
171
+ "name": "Sable Robotics — Pilot+",
172
+ "accountId": "acct-sable",
173
+ "amount": 18000,
174
+ "closeDate": "2026-07-01T00:00:00.000Z",
175
+ "stage": "Closed Won",
176
+ "probability": 100,
177
+ "ownerId": "user-tom",
178
+ "type": "New Business",
179
+ "leadSource": "Referral",
180
+ "nextStep": "Create $21,000 draft invoice; finance approval required",
181
+ "description": (
182
+ "Closed-Won pilot. Payment Terms: Net 60. +$3,000 manual "
183
+ "invoice adjustment (approval threshold: $2,000; base $18,000; "
184
+ "invoice total $21,000). DocuSign: "
185
+ "MSA — Sable Robotics (OPP-7743)."
186
+ ),
187
+ "createdDate": "2026-06-02T09:00:00.000Z",
188
+ "modifiedDate": "2026-07-01T09:00:00.000Z",
189
+ },
190
+ ]
191
+ return {
192
+ "user": users[0],
193
+ "users": users,
194
+ "leads": [],
195
+ "accounts": accounts,
196
+ "contacts": [],
197
+ "opportunities": opportunities,
198
+ "cases": [],
199
+ "activities": [],
200
+ "chatterPosts": [],
201
+ "files": [],
202
+ "following": [],
203
+ "recentlyViewed": [],
204
+ "dismissedNotifications": [],
205
+ "dashboards": [],
206
+ "emailDrafts": [],
207
+ "reportSnapshots": [],
208
+ }
209
+
210
+
211
+ def build_hubspot():
212
+ stages = {
213
+ "appointment_scheduled": {
214
+ "id": "appointment_scheduled",
215
+ "label": "Appointment Scheduled",
216
+ "probability": 20,
217
+ "color": "#E5F4FF",
218
+ "order": 1,
219
+ },
220
+ "qualified_to_buy": {
221
+ "id": "qualified_to_buy",
222
+ "label": "Qualified to Buy",
223
+ "probability": 40,
224
+ "color": "#FFF0E6",
225
+ "order": 2,
226
+ },
227
+ "presentation_scheduled": {
228
+ "id": "presentation_scheduled",
229
+ "label": "Presentation Scheduled",
230
+ "probability": 60,
231
+ "color": "#FFF8E6",
232
+ "order": 3,
233
+ },
234
+ "decision_maker_bought_in": {
235
+ "id": "decision_maker_bought_in",
236
+ "label": "Decision Maker Bought-In",
237
+ "probability": 80,
238
+ "color": "#E8F5E9",
239
+ "order": 4,
240
+ },
241
+ "contract_sent": {
242
+ "id": "contract_sent",
243
+ "label": "Contract Sent",
244
+ "probability": 90,
245
+ "color": "#E6FFFA",
246
+ "order": 5,
247
+ },
248
+ "closed_won": {
249
+ "id": "closed_won",
250
+ "label": "Closed Won",
251
+ "probability": 100,
252
+ "color": "#E6FFEC",
253
+ "order": 6,
254
+ },
255
+ "closed_lost": {
256
+ "id": "closed_lost",
257
+ "label": "Closed Lost",
258
+ "probability": 0,
259
+ "color": "#FFE6E6",
260
+ "order": 7,
261
+ },
262
+ }
263
+ ticket_statuses = {
264
+ "new": {"id": "new", "label": "New", "color": "#E5F4FF", "order": 1},
265
+ "waiting_on_contact": {
266
+ "id": "waiting_on_contact",
267
+ "label": "Waiting on Contact",
268
+ "color": "#FFF8E6",
269
+ "order": 2,
270
+ },
271
+ "waiting_on_us": {
272
+ "id": "waiting_on_us",
273
+ "label": "Waiting on Us",
274
+ "color": "#FFF0E6",
275
+ "order": 3,
276
+ },
277
+ "in_progress": {
278
+ "id": "in_progress",
279
+ "label": "In Progress",
280
+ "color": "#E6FFFA",
281
+ "order": 4,
282
+ },
283
+ "closed": {
284
+ "id": "closed",
285
+ "label": "Closed",
286
+ "color": "#E6FFEC",
287
+ "order": 5,
288
+ },
289
+ }
290
+ return {
291
+ "contacts": [
292
+ {
293
+ "id": "contact-verdant",
294
+ "firstName": "Contracts",
295
+ "lastName": "Team",
296
+ "email": "contracts@verdant-health.co",
297
+ "phone": "+1 (617) 555-0142",
298
+ "jobTitle": "Contracts Operations",
299
+ "companyId": "company-verdant",
300
+ "lifecycleStage": "customer",
301
+ "leadStatus": "open_deal",
302
+ "owner": "Lena Park",
303
+ "city": "Boston",
304
+ "state": "MA",
305
+ "country": "United States",
306
+ "createDate": "2026-03-10T09:00:00Z",
307
+ "lastActivityDate": "2026-07-01T09:00:00Z",
308
+ "timeline": [],
309
+ }
310
+ ],
311
+ "companies": [
312
+ {
313
+ "id": "company-verdant",
314
+ "name": "Verdant Health Co.",
315
+ "domain": "verdant-health.co",
316
+ "industry": "Healthcare",
317
+ "phone": "+1 (617) 555-0100",
318
+ "city": "Boston",
319
+ "state": "MA",
320
+ "country": "United States",
321
+ "numberOfEmployees": 420,
322
+ "annualRevenue": 65000000,
323
+ "lifecycleStage": "customer",
324
+ "owner": "Lena Park",
325
+ "description": "Healthcare platform customer.",
326
+ "createDate": "2026-03-10T09:00:00Z",
327
+ }
328
+ ],
329
+ "deals": [
330
+ {
331
+ "id": "D-7742",
332
+ "name": "Verdant Health — Platform",
333
+ "companyId": "company-verdant",
334
+ "contactIds": ["contact-verdant"],
335
+ "amount": 41000,
336
+ "stage": "closed_won",
337
+ "closeDate": "2026-07-01",
338
+ "dealType": "new_business",
339
+ "priority": "high",
340
+ "owner": "Lena Park",
341
+ "probability": 100,
342
+ "description": (
343
+ "Closed Won. Payment Terms: Net 45. Discount: 0%. "
344
+ "DocuSign envelope "
345
+ "MSA — Verdant Health (D-7742) is still awaiting signature."
346
+ ),
347
+ "createDate": "2026-05-20T10:00:00Z",
348
+ "lastActivityDate": "2026-07-01T09:00:00Z",
349
+ }
350
+ ],
351
+ "tickets": [],
352
+ "tasks": [],
353
+ "notes": [],
354
+ "templates": [],
355
+ "meetings": [],
356
+ "forms": [],
357
+ "dealStages": stages,
358
+ "ticketStatuses": ticket_statuses,
359
+ "appState": {
360
+ "sidebarOpen": True,
361
+ "currentUser": {
362
+ "name": "Dana Whitman",
363
+ "email": "ar@saas-co.com",
364
+ "avatar": None,
365
+ },
366
+ },
367
+ }
368
+
369
+
370
+ def envelope(eid, subject, status, signer_name, signer_email, deal_id):
371
+ completed = status == "completed"
372
+ return {
373
+ "id": eid,
374
+ "subject": subject,
375
+ "message": f"Master Service Agreement for {deal_id}.",
376
+ "status": status,
377
+ "createdAt": "2026-06-25T09:00:00Z",
378
+ "sentAt": "2026-06-25T09:05:00Z",
379
+ "completedAt": "2026-06-30T15:30:00Z" if completed else None,
380
+ "voidedAt": None,
381
+ "declinedAt": None,
382
+ "lastActivityAt": (
383
+ "2026-06-30T15:30:00Z" if completed else "2026-06-25T09:05:00Z"
384
+ ),
385
+ "expiresAt": "2026-10-23T09:05:00Z",
386
+ "senderId": "user-ar",
387
+ "folderId": None,
388
+ "templateId": None,
389
+ "reminderEnabled": True,
390
+ "reminderDays": 3,
391
+ "reminderFrequency": 2,
392
+ "documents": [
393
+ {
394
+ "id": f"doc-{eid}",
395
+ "name": f"{subject}.pdf",
396
+ "pageCount": 8,
397
+ "order": 1,
398
+ "fileUrl": f"https://picsum.photos/seed/{eid}/800/1100",
399
+ "fileType": "pdf",
400
+ }
401
+ ],
402
+ "recipients": [
403
+ {
404
+ "id": f"rec-{eid}",
405
+ "name": signer_name,
406
+ "email": signer_email,
407
+ "role": "signer",
408
+ "routingOrder": 1,
409
+ "status": "signed" if completed else "sent",
410
+ "signedAt": "2026-06-30T15:30:00Z" if completed else None,
411
+ "viewedAt": "2026-06-30T15:20:00Z" if completed else None,
412
+ "deliveredAt": "2026-06-25T09:10:00Z",
413
+ "declinedAt": None,
414
+ "declineReason": None,
415
+ }
416
+ ],
417
+ "fields": [],
418
+ "history": [],
419
+ }
420
+
421
+
422
+ def build_docusign():
423
+ user = {
424
+ "id": "user-ar",
425
+ "name": "Dana Whitman",
426
+ "email": "ar@saas-co.com",
427
+ "title": "AR Specialist",
428
+ "company": "SaaS-Co",
429
+ "avatar": avatar("Dana Whitman"),
430
+ "memberSince": "2023-02-01",
431
+ "settings": {
432
+ "defaultReminderDays": 3,
433
+ "defaultExpirationDays": 120,
434
+ "timezone": "America/New_York",
435
+ },
436
+ }
437
+ return {
438
+ "user": user,
439
+ "envelopes": [
440
+ envelope(
441
+ "env-7741",
442
+ "MSA — Cobalt Freight (OPP-7741)",
443
+ "completed",
444
+ "Morgan Lee",
445
+ "contracts@cobaltfreight.com",
446
+ "OPP-7741",
447
+ ),
448
+ envelope(
449
+ "env-7742",
450
+ "MSA — Verdant Health (D-7742)",
451
+ "sent",
452
+ "Verdant Contracts",
453
+ "contracts@verdant-health.co",
454
+ "D-7742",
455
+ ),
456
+ envelope(
457
+ "env-7743",
458
+ "MSA — Sable Robotics (OPP-7743)",
459
+ "completed",
460
+ "Avery Stone",
461
+ "legal@sablerobotics.com",
462
+ "OPP-7743",
463
+ ),
464
+ ],
465
+ "templates": [],
466
+ "folders": [],
467
+ "contacts": [],
468
+ "auditLog": [],
469
+ }
470
+
471
+
472
+ def cell(value, bold=False):
473
+ result = {"value": str(value), "formula": str(value)}
474
+ if bold:
475
+ result["style"] = {"bold": True, "bg": "#E8EAED", "align": "center"}
476
+ return result
477
+
478
+
479
+ LEDGER_ROWS = [
480
+ ["INV-7701", "Northwind Traders", "$12,400", "Net 30", "Paid", "Salesforce OPP-7690", "2026-06-03"],
481
+ ["INV-7702", "Acme Logistics", "$8,900", "Net 30", "Paid", "HubSpot D-7691", "2026-06-03"],
482
+ ["INV-7703", "Helios Energy", "$33,250", "Net 45", "Draft", "Salesforce OPP-7692", "2026-06-04"],
483
+ ["INV-7704", "Brightline Media", "$4,150", "Net 15", "Paid", "HubSpot D-7693", "2026-06-05"],
484
+ ["INV-7705", "Quanta Systems", "$21,700", "Net 60", "Draft", "Salesforce OPP-7694", "2026-06-06"],
485
+ ["INV-7706", "Meridian Labs", "$15,300", "Net 30", "Paid", "HubSpot D-7695", "2026-06-08"],
486
+ ["INV-7707", "Cascade Foods", "$9,800", "Net 30", "Draft", "Salesforce OPP-7696", "2026-06-09"],
487
+ ["INV-7708", "Pioneer Steel", "$47,000", "Net 45", "Paid", "Salesforce OPP-7697", "2026-06-10"],
488
+ ["INV-7709", "Lumen Health", "$28,400", "Net 30", "Draft", "HubSpot D-7698", "2026-06-11"],
489
+ ["INV-7710", "Atlas Freight", "$11,300", "Net 30", "Paid", "Salesforce OPP-7699", "2026-06-12"],
490
+ ["INV-7711", "Vertex Pharmaceuticals", "$62,500", "Net 60", "Draft", "Salesforce OPP-7700", "2026-06-13"],
491
+ ["INV-7712", "Cedar Works", "$6,750", "Net 15", "Paid", "HubSpot D-7701", "2026-06-15"],
492
+ ["INV-7713", "Orion Analytics", "$19,200", "Net 30", "Draft", "Salesforce OPP-7702", "2026-06-16"],
493
+ ["INV-7714", "Granite Bank", "$54,900", "Net 45", "Paid", "Salesforce OPP-7703", "2026-06-17"],
494
+ ["INV-7715", "Solstice Retail", "$13,600", "Net 30", "Draft", "HubSpot D-7704", "2026-06-18"],
495
+ ["INV-7716", "Tundra Mining", "$38,300", "Net 60", "Paid", "Salesforce OPP-7705", "2026-06-19"],
496
+ ["INV-7717", "Harbor Logistics", "$7,450", "Net 30", "Draft", "HubSpot D-7706", "2026-06-20"],
497
+ ["INV-7718", "Evergreen Utilities", "$24,800", "Net 45", "Paid", "Salesforce OPP-7707", "2026-06-21"],
498
+ ]
499
+
500
+
501
+ def build_sheets():
502
+ headers = [
503
+ "Invoice ID",
504
+ "Account Name",
505
+ "Amount",
506
+ "Payment Terms",
507
+ "Status",
508
+ "Source",
509
+ "Created Date",
510
+ ]
511
+ cols = "ABCDEFG"
512
+ data = {}
513
+ for idx, value in enumerate(headers):
514
+ data[f"{cols[idx]}1"] = cell(value, bold=True)
515
+ for row_idx, row in enumerate(LEDGER_ROWS, start=2):
516
+ for col_idx, value in enumerate(row):
517
+ data[f"{cols[col_idx]}{row_idx}"] = cell(value)
518
+ return {
519
+ "id": "workbook-invoice-ledger",
520
+ "title": "Invoice Ledger",
521
+ "activeSheetId": "sheet-fy26",
522
+ "selectedCell": "A20",
523
+ "selectionRange": None,
524
+ "clipboard": None,
525
+ "isDragging": False,
526
+ "undoStack": [],
527
+ "redoStack": [],
528
+ "namedRanges": [],
529
+ "conditionalFormats": [],
530
+ "charts": [],
531
+ "showGridlines": True,
532
+ "showFormulas": False,
533
+ "zoom": 100,
534
+ "sheets": [
535
+ {
536
+ "id": "sheet-fy26",
537
+ "name": "FY26 Invoices",
538
+ "rowCount": 100,
539
+ "colCount": 26,
540
+ "frozenRows": 1,
541
+ "frozenCols": 0,
542
+ "tabColor": "#1A73E8",
543
+ "isHidden": False,
544
+ "columnWidths": {
545
+ "0": 110,
546
+ "1": 190,
547
+ "2": 100,
548
+ "3": 120,
549
+ "4": 100,
550
+ "5": 180,
551
+ "6": 120,
552
+ },
553
+ "data": data,
554
+ }
555
+ ],
556
+ }
557
+
558
+
559
+ def slack_user(uid, name, display, email, title):
560
+ return {
561
+ "userId": uid,
562
+ "fullName": name,
563
+ "displayName": display,
564
+ "email": email,
565
+ "avatar": avatar(name),
566
+ "title": title,
567
+ "status": "online",
568
+ "statusMessage": "",
569
+ "statusEmoji": "",
570
+ "timeZone": "America/New_York",
571
+ }
572
+
573
+
574
+ def build_slack():
575
+ users = [
576
+ slack_user("user-ar", "Dana Whitman", "Dana", "ar@saas-co.com", "AR Specialist"),
577
+ slack_user("user-tom", "Tom Reyes", "Tom", "tom.reyes@saas-co.com", "Account Executive"),
578
+ slack_user("user-lena", "Lena Park", "Lena", "lena.park@saas-co.com", "Account Executive"),
579
+ slack_user("user-controller", "Rebecca Liu", "Rebecca", "rebecca.liu@saas-co.com", "Controller"),
580
+ ]
581
+ members = [u["userId"] for u in users]
582
+
583
+ def channel(cid, description):
584
+ return {
585
+ "channelId": cid,
586
+ "name": cid,
587
+ "description": description,
588
+ "topic": "Month-end AR close",
589
+ "isPrivate": False,
590
+ "isStarred": True,
591
+ "members": members,
592
+ "createdBy": "user-controller",
593
+ "createdAt": "2026-01-05T09:00:00Z",
594
+ "pinnedMessages": [],
595
+ "unreadCount": 0,
596
+ }
597
+
598
+ return {
599
+ "currentUser": users[0],
600
+ "workspace": {"workspaceId": "ws-saas", "workspaceName": "SaaS-Co", "icon": ""},
601
+ "users": users,
602
+ "channels": [
603
+ channel("finance-approvals", "Discount and invoice-adjustment approvals"),
604
+ channel("finance-ar", "Accounts receivable reminders and escalations"),
605
+ ],
606
+ "messages": {
607
+ "finance-approvals": [
608
+ {
609
+ "messageId": "msg-hist-approval",
610
+ "senderId": "user-controller",
611
+ "content": "Q2 closeout approvals have all been archived.",
612
+ "timestamp": "2026-06-02T14:03:00Z",
613
+ "threadId": None,
614
+ "reactions": [],
615
+ "attachments": [],
616
+ "isEdited": False,
617
+ }
618
+ ],
619
+ "finance-ar": [
620
+ {
621
+ "messageId": "msg-hist-ar",
622
+ "senderId": "user-ar",
623
+ "content": "INV-7703 moved to the collections queue.",
624
+ "timestamp": "2026-06-05T09:15:00Z",
625
+ "threadId": None,
626
+ "reactions": [],
627
+ "attachments": [],
628
+ "isEdited": False,
629
+ }
630
+ ],
631
+ },
632
+ "threads": {},
633
+ "dms": [],
634
+ "bookmarkedMessages": [],
635
+ "callHistory": [],
636
+ "settings": {
637
+ "theme": "light",
638
+ "notifications": "all",
639
+ "displayDensity": "comfortable",
640
+ "showAvatars": True,
641
+ "use24Hour": False,
642
+ },
643
+ "invitations": [],
644
+ "notifications": [],
645
+ }
646
+
647
+
648
+ def build_gmail():
649
+ return {
650
+ "user": {
651
+ "userId": "user-ar",
652
+ "username": "Dana Whitman",
653
+ "email": "ar@saas-co.com",
654
+ "avatar": avatar("Dana Whitman"),
655
+ },
656
+ "emails": [
657
+ {
658
+ "id": "mail-historical",
659
+ "threadId": "thread-historical",
660
+ "from": {"name": "Controller", "email": "controller@saas-co.com"},
661
+ "to": [{"name": "Dana Whitman", "email": "ar@saas-co.com"}],
662
+ "cc": [],
663
+ "bcc": [],
664
+ "subject": "Month-end AR close",
665
+ "body": "<p>Please complete the July 1 AR closeout.</p>",
666
+ "timestamp": "2026-07-01T08:00:00Z",
667
+ "read": True,
668
+ "starred": True,
669
+ "important": True,
670
+ "labels": ["l1"],
671
+ "category": "primary",
672
+ "folder": "inbox",
673
+ "attachments": [],
674
+ }
675
+ ],
676
+ "labels": [
677
+ {"id": "l1", "name": "Finance", "color": "#1A73E8"},
678
+ {"id": "l2", "name": "Contracts", "color": "#22C55E"},
679
+ ],
680
+ "drafts": [],
681
+ "settings": {
682
+ "density": "default",
683
+ "undoSend": 10,
684
+ "signature": "",
685
+ "categoryTabs": {
686
+ "primary": True,
687
+ "social": True,
688
+ "promotions": True,
689
+ "updates": False,
690
+ "forums": False,
691
+ },
692
+ "replyBehavior": "Reply",
693
+ "language": "English (US)",
694
+ "sysLabelShown": {},
695
+ "userLabelShown": {},
696
+ },
697
+ }
698
+
699
+
700
+ def build_docs():
701
+ user = {
702
+ "id": "user-ar",
703
+ "name": "Dana Whitman",
704
+ "email": "ar@saas-co.com",
705
+ "avatar": avatar("Dana Whitman"),
706
+ }
707
+ return {
708
+ "currentUser": user,
709
+ "users": [user],
710
+ # Docs deep-merges its default document map. Reuse all five default IDs
711
+ # so unrelated demo documents cannot leak into this task's UI/state.
712
+ "documents": {
713
+ "doc-1": {
714
+ "id": "doc-1",
715
+ "title": "Q1 Closeout — 2026-04-01",
716
+ "content": (
717
+ "<h1>Q1 Closeout — 2026-04-01</h1>"
718
+ "<h2>1. Signed &amp; Awaiting Approval</h2>"
719
+ "<p>Prior-quarter approvals archived.</p>"
720
+ "<h2>2. Unsigned &amp; Reminded</h2>"
721
+ "<p>Prior-quarter reminders complete.</p>"
722
+ "<h2>3. Summary</h2><p>Q1 close complete.</p>"
723
+ ),
724
+ "ownerId": "user-ar",
725
+ "starred": False,
726
+ "created": "2026-04-01T10:00:00Z",
727
+ "updated": "2026-04-01T16:00:00Z",
728
+ "sharedWith": [],
729
+ "linkSharing": {"enabled": False, "permission": "viewer"},
730
+ },
731
+ "doc-2": {
732
+ "id": "doc-2",
733
+ "title": "Collections Notes — 2026-06",
734
+ "content": "<h1>Collections Notes — 2026-06</h1><p>Archived.</p>",
735
+ "ownerId": "user-ar",
736
+ "starred": False,
737
+ "created": "2026-06-01T10:00:00Z",
738
+ "updated": "2026-06-30T16:00:00Z",
739
+ "sharedWith": [],
740
+ "linkSharing": {"enabled": False, "permission": "viewer"},
741
+ },
742
+ "doc-3": {
743
+ "id": "doc-3",
744
+ "title": "Invoice Review Notes",
745
+ "content": "<h1>Invoice Review Notes</h1><p>Archived.</p>",
746
+ "ownerId": "user-ar",
747
+ "starred": False,
748
+ "created": "2026-05-01T10:00:00Z",
749
+ "updated": "2026-05-31T16:00:00Z",
750
+ "sharedWith": [],
751
+ "linkSharing": {"enabled": False, "permission": "viewer"},
752
+ },
753
+ "doc-4": {
754
+ "id": "doc-4",
755
+ "title": "Approval Archive",
756
+ "content": "<h1>Approval Archive</h1><p>Archived.</p>",
757
+ "ownerId": "user-ar",
758
+ "starred": False,
759
+ "created": "2026-04-01T10:00:00Z",
760
+ "updated": "2026-04-30T16:00:00Z",
761
+ "sharedWith": [],
762
+ "linkSharing": {"enabled": False, "permission": "viewer"},
763
+ },
764
+ "doc-5": {
765
+ "id": "doc-5",
766
+ "title": "AR Process Reference",
767
+ "content": "<h1>AR Process Reference</h1><p>Archived.</p>",
768
+ "ownerId": "user-ar",
769
+ "starred": False,
770
+ "created": "2026-01-01T10:00:00Z",
771
+ "updated": "2026-03-31T16:00:00Z",
772
+ "sharedWith": [],
773
+ "linkSharing": {"enabled": False, "permission": "viewer"},
774
+ },
775
+ },
776
+ "comments": [],
777
+ "ui": {
778
+ "currentDocId": None,
779
+ "sidebarOpen": False,
780
+ "sidebarTab": "comments",
781
+ "shareDialogOpen": False,
782
+ "findReplaceOpen": False,
783
+ "viewMode": "editing",
784
+ "zoom": 100,
785
+ "documentListView": "grid",
786
+ "searchQuery": "",
787
+ },
788
+ }
789
+
790
+
791
+ BUILDERS = {
792
+ "salesforce": build_salesforce,
793
+ "hubspot": build_hubspot,
794
+ "docusign": build_docusign,
795
+ "google_sheets": build_sheets,
796
+ "slack": build_slack,
797
+ "gmail": build_gmail,
798
+ "google_docs": build_docs,
799
+ }
800
+
801
+
802
+ def inject(name, state):
803
+ url = f"{MOCKS[name]}/post?sid={SID}"
804
+ reset = requests.post(url, json={"action": "reset"}, timeout=30)
805
+ reset.raise_for_status()
806
+ response = requests.post(
807
+ url, json={"action": "set", "state": state}, timeout=30
808
+ )
809
+ response.raise_for_status()
810
+ print(f"[initial_setup] injected {name}")
811
+
812
+
813
+ def verify(name):
814
+ response = requests.get(f"{MOCKS[name]}/go?sid={SID}", timeout=20)
815
+ response.raise_for_status()
816
+ state = response.json()
817
+ assert state.get("initial_state") is not None, f"{name}: missing initial_state"
818
+ assert state.get("current_state") is not None, f"{name}: missing current_state"
819
+
820
+
821
+ def launch_gui(command, delay_sec=3.0):
822
+ env = os.environ.copy()
823
+ env["DISPLAY"] = ":0"
824
+ subprocess.Popen(
825
+ shlex.split(command),
826
+ stdout=subprocess.DEVNULL,
827
+ stderr=subprocess.DEVNULL,
828
+ env=env,
829
+ )
830
+ time.sleep(delay_sec)
831
+
832
+
833
+ def seed_docs_browser_state(state):
834
+ """Work around Docs' first-load race by seeding its sid-scoped localStorage.
835
+
836
+ google_docs_mock currently writes default data to localStorage during its
837
+ synchronous reducer initialization. Its later custom-state effect then
838
+ mistakes that key for a refresh and skips fetching the injected state,
839
+ before posting the defaults back to /post. Seed the already-open Docs tab
840
+ with the same state and reload it so both the visible UI and server-side
841
+ current_state remain aligned with the injected initial_state.
842
+ """
843
+ import pyautogui
844
+
845
+ encoded = base64.b64encode(
846
+ json.dumps(state, separators=(",", ":")).encode("utf-8")
847
+ ).decode("ascii")
848
+ state_key = f"google_docs_mock_state_{SID}"
849
+ initial_key = f"google_docs_mock_initial_{SID}"
850
+ javascript = (
851
+ "javascript:(()=>{"
852
+ f"const s=JSON.parse(atob('{encoded}'));"
853
+ f"localStorage.setItem('{state_key}',JSON.stringify(s));"
854
+ f"localStorage.setItem('{initial_key}',JSON.stringify(s));"
855
+ "location.reload()"
856
+ "})()"
857
+ )
858
+
859
+ # Docs is launched as the final Chrome tab. Ctrl+9 selects the last tab
860
+ # even when setup is rerun in an already-open Chrome session.
861
+ pyautogui.hotkey("ctrl", "9")
862
+ time.sleep(1.0)
863
+ pyautogui.hotkey("ctrl", "l")
864
+ pyautogui.write(javascript, interval=0.0001)
865
+ pyautogui.press("enter")
866
+
867
+ expected_titles = {
868
+ document["title"] for document in state["documents"].values()
869
+ }
870
+ deadline = time.time() + 20
871
+ while time.time() < deadline:
872
+ try:
873
+ payload = requests.get(
874
+ f'{MOCKS["google_docs"]}/go?sid={SID}', timeout=5
875
+ ).json()
876
+ current = payload.get("current_state") or {}
877
+ current_titles = {
878
+ document.get("title")
879
+ for document in (current.get("documents") or {}).values()
880
+ }
881
+ if current_titles == expected_titles:
882
+ return
883
+ except Exception:
884
+ pass
885
+ time.sleep(1.0)
886
+ raise RuntimeError("google_docs: browser state did not match injected state")
887
+
888
+
889
+ def main():
890
+ with open("/tmp/task_web_sid", "w") as f:
891
+ f.write(SID)
892
+ print(f"[initial_setup] sid={SID}")
893
+
894
+ for name, builder in BUILDERS.items():
895
+ inject(name, builder())
896
+ for name in MOCKS:
897
+ verify(name)
898
+
899
+ sheets = requests.get(
900
+ f'{MOCKS["google_sheets"]}/go?sid={SID}', timeout=20
901
+ ).json()["current_state"]
902
+ sheet_data = sheets["sheets"][0]["data"]
903
+ assert sheet_data["A19"]["value"] == "INV-7718"
904
+ assert "A20" not in sheet_data
905
+
906
+ urls = [
907
+ f'{MOCKS["salesforce"]}/opportunities',
908
+ f'{MOCKS["hubspot"]}/deals',
909
+ f'{MOCKS["docusign"]}/agreements/sent',
910
+ f'{MOCKS["google_sheets"]}/spreadsheet',
911
+ f'{MOCKS["slack"]}/channel/finance-approvals',
912
+ MOCKS["gmail"],
913
+ MOCKS["google_docs"],
914
+ ]
915
+ tabs = " ".join(f'"{url}?sid={SID}"' for url in urls)
916
+ launch_gui(
917
+ "google-chrome --no-first-run --no-default-browser-check " + tabs,
918
+ delay_sec=4.0,
919
+ )
920
+ seed_docs_browser_state(build_docs())
921
+ print(
922
+ "GUI_READY: launched Salesforce, HubSpot, DocuSign, Sheets, Slack, "
923
+ f"Gmail, and Docs (sid={SID})"
924
+ )
925
+
926
+
927
+ if __name__ == "__main__":
928
+ main()
ar_closeout_006/reward.py ADDED
@@ -0,0 +1,624 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward: AR Closeout across live Google Sheets, Slack, Gmail, and Google Docs.
3
+ Task ID: ar_closeout_006
4
+ Domain: mock_websites
5
+
6
+ All checks read each CUA-Gym-Hub backend through /go?sid=... and score only
7
+ task-introduced changes relative to initial_state.
8
+ """
9
+ import html
10
+ import json
11
+ import os
12
+ import re
13
+ from datetime import date, datetime
14
+ from decimal import Decimal, InvalidOperation
15
+
16
+ import requests
17
+
18
+
19
+ BASE = "http://28.7.184.198"
20
+ MOCKS = {
21
+ "google_sheets": f"{BASE}:8145",
22
+ "slack": f"{BASE}:8178",
23
+ "gmail": f"{BASE}:8138",
24
+ "google_docs": f"{BASE}:8142",
25
+ }
26
+
27
+ for proxy_var in ("no_proxy", "NO_PROXY"):
28
+ bypass = os.environ.get(proxy_var, "")
29
+ if "28.7.184.198" not in bypass:
30
+ os.environ[proxy_var] = ",".join(filter(None, [bypass, "28.7.184.198"]))
31
+
32
+ APPROVAL_7741 = (
33
+ "APPROVAL NEEDED: OPP-7741 Cobalt Freight LLC — 22% discount on $95,000 "
34
+ "invoice INV-7741 exceeds 15% threshold. AE: Tom Reyes. Envelope signed."
35
+ )
36
+ APPROVAL_7743 = (
37
+ "APPROVAL NEEDED: OPP-7743 Sable Robotics — $3,000 invoice adjustment on "
38
+ "$18,000 base (INV-7743, total $21,000) exceeds $2,000 threshold. "
39
+ "AE: Tom Reyes. Envelope signed."
40
+ )
41
+ AR_REMINDER = (
42
+ "Reminder: MSA — Verdant Health (D-7742) unsigned; Gmail nudge sent to "
43
+ "contracts@verdant-health.co. AE: Lena Park. $41,000 Net 45."
44
+ )
45
+ SUMMARY = (
46
+ "3 deals processed; 2 approval posts to #finance-approvals; 1 Gmail reminder "
47
+ "sent; 3 invoice rows added to Invoice Ledger."
48
+ )
49
+
50
+
51
+ def read_sid():
52
+ try:
53
+ with open("/tmp/task_web_sid") as f:
54
+ sid = f.read().strip()
55
+ if not sid:
56
+ raise ValueError("empty sid")
57
+ return sid
58
+ except Exception as exc:
59
+ print(f"CRITICAL: cannot read /tmp/task_web_sid: {exc}")
60
+ return None
61
+
62
+
63
+ def fetch_states(name, sid):
64
+ response = requests.get(f"{MOCKS[name]}/go?sid={sid}", timeout=30)
65
+ response.raise_for_status()
66
+ payload = response.json()
67
+ initial = payload.get("initial_state")
68
+ current = payload.get("current_state")
69
+ if not isinstance(initial, dict) or not isinstance(current, dict):
70
+ raise ValueError(f"{name}: /go returned invalid initial/current state")
71
+ return initial, current
72
+
73
+
74
+ def norm(value):
75
+ text = html.unescape(str(value or ""))
76
+ text = text.replace("—", "-").replace("–", "-").replace("‐", "-")
77
+ text = text.replace("\u00a0", " ").replace("’", "'").replace("‘", "'")
78
+ return re.sub(r"\s+", " ", text).strip().lower()
79
+
80
+
81
+ def norm_ignoring_long_dash(value):
82
+ """Normalize text while ignoring missing or substituted long dashes."""
83
+ text = html.unescape(str(value or ""))
84
+ text = re.sub(r"[—–‐]", "", text)
85
+ text = re.sub(r"(?<!\S)-(?!\S)", "", text)
86
+ text = text.replace("\u00a0", " ").replace("’", "'").replace("‘", "'")
87
+ return re.sub(r"\s+", " ", text).strip().lower()
88
+
89
+
90
+ def plain_html(value):
91
+ markup = str(value or "")
92
+ markup = re.sub(
93
+ r"</?(?:p|div|h[1-6]|li|ul|ol|br|blockquote)[^>]*>",
94
+ "\n",
95
+ markup,
96
+ flags=re.IGNORECASE,
97
+ )
98
+ return norm(re.sub(r"<[^>]+>", " ", markup))
99
+
100
+
101
+ def parse_money(value):
102
+ """Return a Decimal amount while rejecting digit-collision false positives."""
103
+ if isinstance(value, bool) or value in (None, ""):
104
+ return None
105
+ text = str(value).strip().replace("$", "").replace(",", "")
106
+ text = re.sub(r"\s+", "", text)
107
+ if not re.fullmatch(r"[-+]?\d+(?:\.\d+)?", text):
108
+ return None
109
+ try:
110
+ return Decimal(text)
111
+ except InvalidOperation:
112
+ return None
113
+
114
+
115
+ def parse_ymd(value):
116
+ """Parse common spreadsheet date representations into (year, month, day)."""
117
+ if isinstance(value, datetime):
118
+ return value.date().timetuple()[:3]
119
+ if isinstance(value, date):
120
+ return value.timetuple()[:3]
121
+ text = str(value or "").strip()
122
+ for pattern in (
123
+ r"^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})$",
124
+ r"^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$",
125
+ ):
126
+ match = re.match(pattern, text)
127
+ if not match:
128
+ continue
129
+ parts = tuple(int(part) for part in match.groups())
130
+ year, month, day = parts if len(match.group(1)) == 4 else (parts[2], parts[0], parts[1])
131
+ try:
132
+ date(year, month, day)
133
+ return year, month, day
134
+ except ValueError:
135
+ return None
136
+ return None
137
+
138
+
139
+ def component(idx, name, weight, passed, detail, description=""):
140
+ score = weight if passed else 0.0
141
+ print(f"{'PASS' if passed else 'FAIL'}: Component {idx} — {name} — {detail}")
142
+ print(
143
+ "COMPONENT: "
144
+ + json.dumps(
145
+ {
146
+ "id": idx,
147
+ "name": name,
148
+ "weight": weight,
149
+ "passed": passed,
150
+ "score": score,
151
+ "detail": detail,
152
+ "description": description,
153
+ }
154
+ )
155
+ )
156
+ return score
157
+
158
+
159
+ def sheet_rows(state):
160
+ sheets = state.get("sheets") or []
161
+ sheet = next((s for s in sheets if s.get("name") == "FY26 Invoices"), None)
162
+ if not sheet:
163
+ return {}
164
+ data = sheet.get("data") or {}
165
+ row_numbers = sorted(
166
+ {
167
+ int(match.group(1))
168
+ for key in data
169
+ for match in [re.match(r"^[A-Z]+(\d+)$", key)]
170
+ if match
171
+ }
172
+ )
173
+ rows = {}
174
+ for row_num in row_numbers:
175
+ values = [
176
+ (data.get(f"{col}{row_num}") or {}).get("value")
177
+ for col in "ABCDEFG"
178
+ ]
179
+ if any(value not in (None, "") for value in values):
180
+ rows[row_num] = values
181
+ return rows
182
+
183
+
184
+ def invoice_map(rows):
185
+ invoices = {}
186
+ for row_num, row in rows.items():
187
+ invoice_id = str(row[0] or "").strip().upper()
188
+ if invoice_id.startswith("INV-"):
189
+ invoices.setdefault(invoice_id, []).append((row_num, row))
190
+ return invoices
191
+
192
+
193
+ def invoice_row_matches(actual, expected):
194
+ checks = [
195
+ norm(actual[0]) == norm(expected[0]),
196
+ norm(actual[1]) == norm(expected[1]),
197
+ parse_money(actual[2]) == parse_money(expected[2]),
198
+ norm(actual[3]) == norm(expected[3]),
199
+ norm(actual[4]) == norm(expected[4]),
200
+ norm(actual[5]) == norm(expected[5]),
201
+ parse_ymd(actual[6]) == parse_ymd(expected[6]),
202
+ ]
203
+ return all(checks)
204
+
205
+
206
+ def check_sheets(initial, current):
207
+ """Verify exactly three invoice rows were added and all original rows stayed intact."""
208
+ initial_rows = sheet_rows(initial)
209
+ current_rows = sheet_rows(current)
210
+ initial_map = invoice_map(initial_rows)
211
+ current_map = invoice_map(current_rows)
212
+ expected = {
213
+ "INV-7741": [
214
+ "INV-7741",
215
+ "Cobalt Freight LLC",
216
+ "$95,000",
217
+ "Net 30",
218
+ "Draft",
219
+ "Salesforce OPP-7741",
220
+ "2026-07-01",
221
+ ],
222
+ "INV-7742": [
223
+ "INV-7742",
224
+ "Verdant Health Co.",
225
+ "$41,000",
226
+ "Net 45",
227
+ "Draft",
228
+ "HubSpot D-7742",
229
+ "2026-07-01",
230
+ ],
231
+ "INV-7743": [
232
+ "INV-7743",
233
+ "Sable Robotics",
234
+ "$21,000",
235
+ "Net 60",
236
+ "Draft",
237
+ "Salesforce OPP-7743",
238
+ "2026-07-01",
239
+ ],
240
+ }
241
+
242
+ if any(invoice_id in initial_map for invoice_id in expected):
243
+ return False, "target invoice already existed in initial_state"
244
+
245
+ for row_num, initial_row in initial_rows.items():
246
+ if current_rows.get(row_num) != initial_row:
247
+ return False, f"original ledger row {row_num} was modified or removed"
248
+
249
+ if len(current_rows) != len(initial_rows) + 3:
250
+ return False, (
251
+ f"expected exactly 3 new non-empty rows, initial={len(initial_rows)}, "
252
+ f"current={len(current_rows)}"
253
+ )
254
+
255
+ new_rows = {
256
+ row_num: row
257
+ for row_num, row in current_rows.items()
258
+ if row_num not in initial_rows
259
+ }
260
+ if any(
261
+ "opp-7740" in norm(" ".join(str(value or "") for value in row))
262
+ or "inv-7740" in norm(" ".join(str(value or "") for value in row))
263
+ for row in new_rows.values()
264
+ ):
265
+ return False, "distractor OPP-7740/INV-7740 was processed in the ledger"
266
+
267
+ failures = []
268
+ for invoice_id, expected_row in expected.items():
269
+ rows = current_map.get(invoice_id, [])
270
+ if len(rows) != 1:
271
+ failures.append(f"{invoice_id}: expected one row, found {len(rows)}")
272
+ elif rows[0][0] not in new_rows:
273
+ failures.append(f"{invoice_id}: row was not task-introduced")
274
+ elif not invoice_row_matches(rows[0][1], expected_row):
275
+ failures.append(f"{invoice_id}: values={rows[0][1]!r}")
276
+ if failures:
277
+ return False, "; ".join(failures)
278
+ return True, "three exact new invoice rows added; original ledger preserved"
279
+
280
+
281
+ def item_identity(item, id_field):
282
+ item_id = item.get(id_field) if isinstance(item, dict) else None
283
+ if item_id not in (None, ""):
284
+ return ("id", str(item_id))
285
+ return (
286
+ "value",
287
+ json.dumps(item, sort_keys=True, ensure_ascii=False, default=str),
288
+ )
289
+
290
+
291
+ def initial_items_preserved(initial_items, current_items, id_field):
292
+ current_by_identity = {
293
+ item_identity(item, id_field): item for item in current_items
294
+ }
295
+ for item in initial_items:
296
+ identity = item_identity(item, id_field)
297
+ if current_by_identity.get(identity) != item:
298
+ return False, identity
299
+ return True, None
300
+
301
+
302
+ def new_slack_messages(initial, current, channel_id):
303
+ initial_messages = (initial.get("messages") or {}).get(channel_id) or []
304
+ current_messages = (current.get("messages") or {}).get(channel_id) or []
305
+ initial_ids = {
306
+ item_identity(message, "messageId") for message in initial_messages
307
+ }
308
+ return [
309
+ message
310
+ for message in current_messages
311
+ if item_identity(message, "messageId") not in initial_ids
312
+ ]
313
+
314
+
315
+ def message_matches(content, required):
316
+ text = norm(content)
317
+ return all(norm(token) in text for token in required)
318
+
319
+
320
+ def check_approval_slack(initial, current):
321
+ """Verify exactly two new, distinct approval posts with all required details."""
322
+ initial_messages = (initial.get("messages") or {}).get("finance-approvals") or []
323
+ current_messages = (current.get("messages") or {}).get("finance-approvals") or []
324
+ preserved, changed = initial_items_preserved(
325
+ initial_messages, current_messages, "messageId"
326
+ )
327
+ if not preserved:
328
+ return False, f"historical approval message changed or disappeared: {changed}"
329
+ messages = new_slack_messages(initial, current, "finance-approvals")
330
+ if len(messages) != 2:
331
+ return False, f"expected exactly 2 new approval posts, found {len(messages)}"
332
+ requirements = [
333
+ [
334
+ "approval needed",
335
+ "OPP-7741",
336
+ "Cobalt Freight LLC",
337
+ "22%",
338
+ "$95,000",
339
+ "INV-7741",
340
+ "15% threshold",
341
+ "Tom Reyes",
342
+ "Envelope signed",
343
+ ],
344
+ [
345
+ "approval needed",
346
+ "OPP-7743",
347
+ "Sable Robotics",
348
+ "$3,000",
349
+ "$18,000",
350
+ "INV-7743",
351
+ "$21,000",
352
+ "$2,000 threshold",
353
+ "Tom Reyes",
354
+ "Envelope signed",
355
+ ],
356
+ ]
357
+ matched_indices = set()
358
+ for required in requirements:
359
+ match_idx = next(
360
+ (
361
+ idx
362
+ for idx, message in enumerate(messages)
363
+ if idx not in matched_indices
364
+ and message_matches(message.get("content"), required)
365
+ ),
366
+ None,
367
+ )
368
+ if match_idx is None:
369
+ return False, (
370
+ f"only {len(matched_indices)}/2 distinct approval posts matched"
371
+ )
372
+ matched_indices.add(match_idx)
373
+ return True, "two distinct task-introduced approval posts matched"
374
+
375
+
376
+ def check_ar_slack(initial, current):
377
+ """Verify exactly one new AR reminder with all required unsigned-deal details."""
378
+ initial_messages = (initial.get("messages") or {}).get("finance-ar") or []
379
+ current_messages = (current.get("messages") or {}).get("finance-ar") or []
380
+ preserved, changed = initial_items_preserved(
381
+ initial_messages, current_messages, "messageId"
382
+ )
383
+ if not preserved:
384
+ return False, f"historical AR message changed or disappeared: {changed}"
385
+ messages = new_slack_messages(initial, current, "finance-ar")
386
+ if len(messages) != 1:
387
+ return False, f"expected exactly 1 new AR reminder, found {len(messages)}"
388
+ required = [
389
+ "Reminder",
390
+ "MSA",
391
+ "Verdant Health",
392
+ "D-7742",
393
+ "unsigned",
394
+ "Gmail nudge sent",
395
+ "contracts@verdant-health.co",
396
+ "Lena Park",
397
+ "$41,000",
398
+ "Net 45",
399
+ ]
400
+ if any(message_matches(message.get("content"), required) for message in messages):
401
+ return True, "new #finance-ar reminder contains all required details"
402
+ return False, f"no qualifying new reminder among {len(messages)} message(s)"
403
+
404
+
405
+ def recipient_emails(email_obj):
406
+ recipients = email_obj.get("to") or []
407
+ if isinstance(recipients, (str, dict)):
408
+ recipients = [recipients]
409
+ result = []
410
+ for recipient in recipients:
411
+ if isinstance(recipient, dict):
412
+ result.append(norm(recipient.get("email")))
413
+ else:
414
+ result.append(norm(recipient))
415
+ return result
416
+
417
+
418
+ def check_gmail(initial, current):
419
+ """Verify one exact task-introduced sent email from AR to the contract signer."""
420
+ preserved, changed = initial_items_preserved(
421
+ initial.get("emails") or [], current.get("emails") or [], "id"
422
+ )
423
+ if not preserved:
424
+ return False, f"historical email changed or disappeared: {changed}"
425
+ initial_ids = {
426
+ item_identity(email_obj, "id") for email_obj in initial.get("emails") or []
427
+ }
428
+ sent = [
429
+ email_obj
430
+ for email_obj in current.get("emails") or []
431
+ if item_identity(email_obj, "id") not in initial_ids
432
+ and norm(email_obj.get("folder")) == "sent"
433
+ ]
434
+ if len(sent) != 1:
435
+ return False, f"expected exactly 1 new sent email, found {len(sent)}"
436
+
437
+ target = "contracts@verdant-health.co"
438
+ expected_subject = "Action required: Please sign MSA — Verdant Health (D-7742)"
439
+ body_tokens = [
440
+ "Your MSA for the Verdant Health platform",
441
+ "D-7742",
442
+ "$41,000",
443
+ "Net 45",
444
+ "awaiting signature",
445
+ "MSA — Verdant Health (D-7742)",
446
+ ]
447
+ for email_obj in sent:
448
+ if recipient_emails(email_obj) != [norm(target)]:
449
+ continue
450
+ sender = email_obj.get("from") or {}
451
+ sender_email = sender.get("email") if isinstance(sender, dict) else sender
452
+ account = current.get("user") or {}
453
+ account_email = account.get("email") if isinstance(account, dict) else ""
454
+ effective_sender = sender_email or account_email
455
+ if norm(effective_sender) != norm("ar@saas-co.com"):
456
+ continue
457
+ if email_obj.get("cc") or email_obj.get("bcc"):
458
+ continue
459
+ if norm_ignoring_long_dash(email_obj.get("subject")) != norm_ignoring_long_dash(
460
+ expected_subject
461
+ ):
462
+ continue
463
+ body = norm_ignoring_long_dash(plain_html(email_obj.get("body")))
464
+ if "opp-7740" in body or "inv-7740" in body:
465
+ continue
466
+ if all(norm_ignoring_long_dash(token) in body for token in body_tokens):
467
+ return True, "task-introduced Gmail reminder has exact recipient/subject/details"
468
+ return False, "the new sent email has incorrect sender/recipient/subject/body"
469
+
470
+
471
+ def title_matches(value):
472
+ return norm_ignoring_long_dash(value) == norm_ignoring_long_dash(
473
+ "AR Closeout — 2026-07-01"
474
+ )
475
+
476
+
477
+ def marked_as_heading_or_bold(content, heading):
478
+ normalized_html = html.unescape(str(content or "")).replace("—", "-").replace("–", "-")
479
+ normalized_heading = heading.replace("—", "-").replace("–", "-")
480
+ escaped = re.escape(normalized_heading)
481
+ patterns = [
482
+ rf"<h[1-6][^>]*>.*?{escaped}.*?</h[1-6]>",
483
+ rf"<(?:strong|b)[^>]*>.*?{escaped}.*?</(?:strong|b)>",
484
+ ]
485
+ return any(
486
+ re.search(pattern, normalized_html, flags=re.IGNORECASE | re.DOTALL)
487
+ for pattern in patterns
488
+ )
489
+
490
+
491
+ def check_docs(initial, current):
492
+ """Verify one new closeout document with ordered bold sections and scoped content."""
493
+ initial_docs = initial.get("documents") or {}
494
+ current_docs = current.get("documents") or {}
495
+ for doc_id, initial_document in initial_docs.items():
496
+ if current_docs.get(doc_id) != initial_document:
497
+ return False, (
498
+ f"existing document {doc_id} changed or was overwritten "
499
+ "(possible first-load state race)"
500
+ )
501
+ new_docs = [
502
+ document
503
+ for doc_id, document in current_docs.items()
504
+ if doc_id not in initial_docs
505
+ ]
506
+ if len(new_docs) != 1:
507
+ return False, f"expected exactly one new document, found {len(new_docs)}"
508
+ candidates = [
509
+ document for document in new_docs if title_matches(document.get("title"))
510
+ ]
511
+ if len(candidates) != 1:
512
+ return False, "the single new document does not have the required title"
513
+
514
+ document = candidates[0]
515
+ content = str(document.get("content") or "")
516
+ text = norm_ignoring_long_dash(plain_html(content))
517
+ if "opp-7740" in text or norm_ignoring_long_dash("Cobalt Freight — Trial") in text:
518
+ return False, "distractor OPP-7740 was included in the closeout document"
519
+ headings = [
520
+ "1. Signed & Awaiting Approval",
521
+ "2. Unsigned & Reminded",
522
+ "3. Summary",
523
+ ]
524
+ missing_headings = [heading for heading in headings if norm(heading) not in text]
525
+ if missing_headings:
526
+ return False, f"missing section headings: {missing_headings}"
527
+ unformatted = [
528
+ heading
529
+ for heading in headings
530
+ if not marked_as_heading_or_bold(content, heading)
531
+ ]
532
+ if unformatted:
533
+ return False, f"section headings are not bold/heading-formatted: {unformatted}"
534
+
535
+ positions = [text.find(norm(heading)) for heading in headings]
536
+ if not (positions[0] < positions[1] < positions[2]):
537
+ return False, "section headings are not in the required order"
538
+ sections = [
539
+ text[positions[0] + len(norm(headings[0])) : positions[1]],
540
+ text[positions[1] + len(norm(headings[1])) : positions[2]],
541
+ text[positions[2] + len(norm(headings[2])) :],
542
+ ]
543
+
544
+ missing_approvals = [
545
+ block
546
+ for block in (APPROVAL_7741, APPROVAL_7743)
547
+ if norm_ignoring_long_dash(block) not in sections[0]
548
+ ]
549
+ if missing_approvals:
550
+ return False, (
551
+ "Signed & Awaiting Approval is missing exact approval text "
552
+ f"for {len(missing_approvals)} deal(s)"
553
+ )
554
+
555
+ reminder_tokens = [
556
+ "D-7742",
557
+ "unsigned",
558
+ "reminded",
559
+ ]
560
+ if not all(norm(token) in sections[1] for token in reminder_tokens):
561
+ return False, "Unsigned & Reminded section lacks D-7742 status"
562
+ if norm_ignoring_long_dash(SUMMARY) not in sections[2]:
563
+ return False, "Summary section lacks the exact required summary sentence"
564
+ return True, "new AR Closeout doc has 3 formatted sections and required content"
565
+
566
+
567
+ def main():
568
+ sid = read_sid()
569
+ if not sid:
570
+ print("REWARD: 0.0")
571
+ return 0.0
572
+
573
+ states = {}
574
+ for name in MOCKS:
575
+ try:
576
+ states[name] = fetch_states(name, sid)
577
+ except Exception as exc:
578
+ print(f"CRITICAL: cannot fetch {name}: {exc}")
579
+ print("REWARD: 0.0")
580
+ return 0.0
581
+
582
+ checks = [
583
+ (1, "Invoice Ledger — 3 new rows", 0.30, check_sheets, states["google_sheets"]),
584
+ (
585
+ 2,
586
+ "Slack #finance-approvals — 2 posts",
587
+ 0.20,
588
+ check_approval_slack,
589
+ states["slack"],
590
+ ),
591
+ (
592
+ 3,
593
+ "Slack #finance-ar — reminder",
594
+ 0.10,
595
+ check_ar_slack,
596
+ states["slack"],
597
+ ),
598
+ (4, "Gmail — signing reminder", 0.10, check_gmail, states["gmail"]),
599
+ (5, "Google Docs — AR Closeout", 0.30, check_docs, states["google_docs"]),
600
+ ]
601
+
602
+ total = 0.0
603
+ for idx, name, weight, check, args in checks:
604
+ try:
605
+ passed, detail = check(*args)
606
+ except Exception as exc:
607
+ passed, detail = False, f"error: {exc}"
608
+ total += component(
609
+ idx,
610
+ name,
611
+ weight,
612
+ passed,
613
+ detail,
614
+ description=(check.__doc__ or "").strip(),
615
+ )
616
+
617
+ final = round(min(total, 1.0), 4)
618
+ print(f"\nScore: {total}/1.0")
619
+ print(f"REWARD: {final}")
620
+ return final
621
+
622
+
623
+ if __name__ == "__main__":
624
+ main()
ar_closeout_006/reward_label.json ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "reward_file": "/apdcephfs_fsgm/share_304220499/xiangwu/workspace/mini-osworld-generalBenchmark/out_benchmark_cache/prof20_ar_closeout_003/reward.py",
3
+ "created_at": "2026-07-19",
4
+ "label": {
5
+ "task_id": "ar_closeout_006",
6
+ "domain": "mock_websites",
7
+ "summary": "通过同一 sid 的 CUA-Gym-Hub /go 状态验证 AR closeout 的五个任务变更组件,并将 initial_state 作为不可变基线。",
8
+ "is_placeholder": false,
9
+ "data_sources": [
10
+ "http://28.7.186.212:8165/go?sid=<sid>",
11
+ "http://28.7.186.212:8198/go?sid=<sid>",
12
+ "http://28.7.186.212:8158/go?sid=<sid>",
13
+ "http://28.7.186.212:8162/go?sid=<sid>"
14
+ ],
15
+ "scoring_components": [
16
+ {
17
+ "id": 1,
18
+ "name": "Invoice Ledger — 3 new rows",
19
+ "weight": 0.3,
20
+ "pass_condition": "FY26 Invoices 恰好新增三条非空行;INV-7741、INV-7742、INV-7743 的七列值正确;所有初始行保持原位置和原值;不得处理 OPP-7740/INV-7740。"
21
+ },
22
+ {
23
+ "id": 2,
24
+ "name": "Slack #finance-approvals — 2 posts",
25
+ "weight": 0.2,
26
+ "pass_condition": "历史消息保持不变,且恰好新增两条不同的审批消息,分别完整覆盖 OPP-7741 和 OPP-7743 的金额、阈值、AE、发票及签署状态。"
27
+ },
28
+ {
29
+ "id": 3,
30
+ "name": "Slack #finance-ar — reminder",
31
+ "weight": 0.1,
32
+ "pass_condition": "历史消息保持不变,且恰好新增一条 D-7742 未签署提醒,包含 Gmail、收件人、AE、金额和账期信息。"
33
+ },
34
+ {
35
+ "id": 4,
36
+ "name": "Gmail — signing reminder",
37
+ "weight": 0.1,
38
+ "pass_condition": "历史邮件保持不变,且恰好新增一封由 ar@saas-co.com 发往 contracts@verdant-health.co 的 sent 邮件;无抄送/密送;主题和正文符合 instruction。"
39
+ },
40
+ {
41
+ "id": 5,
42
+ "name": "Google Docs — AR Closeout",
43
+ "weight": 0.3,
44
+ "pass_condition": "所有初始文档保持不变,恰好新增一份指定标题文档;三个章节按顺序出现且为加粗或标题格式;各章节内容位于正确章节;不得包含 OPP-7740。"
45
+ }
46
+ ],
47
+ "score_aggregation": "五个组件分别为全有或全无得分,权重相加并限制在 0.0 到 1.0;最后一行输出 REWARD: <score>。",
48
+ "regression_targets": {
49
+ "initial_state": 0.0,
50
+ "complete_state": 1.0,
51
+ "known_partial_gui_state": 0.6
52
+ },
53
+ "notes": [
54
+ "不读取 /home/user/mock_state/*.json,不依赖静态 dashboard。",
55
+ "金额使用 Decimal 解析,避免仅拼接数字导致的误判。",
56
+ "日期按年月日比较,兼容 YYYY-MM-DD、MM/DD/YYYY 等常见 GUI 表示。",
57
+ "Google Docs 会检查初始文档是否被首次加载竞态覆盖。"
58
+ ]
59
+ },
60
+ "raw_response": "Manually refreshed after live VM, backend-state, and in-memory initial/golden regression validation."
61
+ }
ar_remittance_008__long/_cua_gym_vm_bridge.sh ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # CUA-Gym VM-side network fix (direct-IP mock access).
3
+ #
4
+ # Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by
5
+ # their real IDC address (http://28.7.184.198:81xx) instead of the old
6
+ # localhost:9000-9097 socat bridge, so the VM only needs two fixes:
7
+ #
8
+ # 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's
9
+ # cluster DNS, which is unreachable from QEMU SLIRP NAT
10
+ # ("Temporary failure in name resolution").
11
+ # 2. The mock host excluded from the woa http proxy — otherwise the VM's
12
+ # Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403
13
+ # from the proxy when hitting 28.7.184.198:81xx. (The old socat path never
14
+ # hit this because localhost is bypassed by default.)
15
+ #
16
+ # Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic
17
+ # OSWorld setup pipeline.
18
+ #
19
+ # Argv:
20
+ # $1 optional sudo password (default "password"; SetupController
21
+ # substitutes {CLIENT_PASSWORD} when uploaded as a cache file).
22
+ # $2 unused (kept for backward compat — was socat first port 9000).
23
+ # $3 unused (kept for backward compat — was socat last port 9097).
24
+ # $4 optional mock host IP (default 28.7.184.198).
25
+
26
+ set +e
27
+
28
+ PASS="${1:-password}"
29
+ MOCK_HOST="${4:-28.7.184.198}"
30
+ # Derive the /16 IDC subnet so future port/host tweaks on the same segment
31
+ # stay bypassed too (28.7.184.198 -> 28.7.0.0/16).
32
+ MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')"
33
+
34
+ run_root() {
35
+ echo "$PASS" | sudo -S -p "" bash -c "$1"
36
+ }
37
+
38
+ # Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2.
39
+ GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')"
40
+ GW="${GW:-10.0.2.2}"
41
+
42
+ # ─── CUA-Gym network fix (Taiji-specific) ─────────────────────────────
43
+ fix_vm_network() {
44
+ # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP
45
+ # DNS forwarder. Nothing hardcoded except the mock host above.
46
+ local GW_NET="${GW%.*}"
47
+ local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3
48
+ local OWN_CIDR
49
+ OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \
50
+ | awk '{print $4; exit}')"
51
+ local OWN_IP="${OWN_CIDR%/*}"
52
+ local OWN_NET=""
53
+ [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24"
54
+
55
+ # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps
56
+ # systemd-resolved/NetworkManager from clobbering it.
57
+ if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf
58
+ chattr +i /etc/resolv.conf 2>/dev/null || true"; then
59
+ echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})"
60
+ else
61
+ echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf"
62
+ fi
63
+
64
+ # 2) Build the proxy bypass list from detected values + the direct-IP
65
+ # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx
66
+ # reachable from inside the VM — without it the woa proxy 403s it.
67
+ local ignore_list="['localhost', '127.0.0.0/8', '${GW}'"
68
+ [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'"
69
+ [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'"
70
+ [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'"
71
+ [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'"
72
+ [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'"
73
+ ignore_list="${ignore_list}]"
74
+
75
+ # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these.
76
+ if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then
77
+ echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}"
78
+ else
79
+ echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)"
80
+ fi
81
+
82
+ # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl).
83
+ local NP="localhost,127.0.0.1,${GW}"
84
+ [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}"
85
+ [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}"
86
+ [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24"
87
+ [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}"
88
+ [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}"
89
+
90
+ for var in no_proxy NO_PROXY; do
91
+ if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then
92
+ echo "export ${var}=${NP}" >> /home/user/.bashrc
93
+ fi
94
+ done
95
+ run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \
96
+ && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \
97
+ || echo 'no_proxy=\"${NP}\"' >> /etc/environment
98
+ grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \
99
+ && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \
100
+ || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1
101
+ echo "[cua_gym_vm_bridge] no_proxy=${NP}"
102
+ }
103
+
104
+ fix_vm_network
105
+
106
+ echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed"
ar_remittance_008__long/initial_setup.py ADDED
@@ -0,0 +1,644 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: T06 — QuickBooks AR Aging report -> Google Sheet (+ Gmail reconcile)
3
+ Task ID: ar_remittance_008__long
4
+ Mocks: quickbooks_mock, google_sheets_mock, gmail_mock
5
+
6
+ The agent must build an Accounts Receivable aging report from QuickBooks open
7
+ invoices into the 'AR Aging' tab of the Google Sheet — but FIRST reconcile two
8
+ payments announced in Gmail.
9
+
10
+ * "Today" is fixed at 2026-04-30 (stated in the instruction).
11
+ * A Gmail remittance email lists two invoice numbers that were just wired in.
12
+ The agent must record those in QuickBooks with the status-gated 'Receive
13
+ payment' action so each becomes status 'Paid' (this control only appears on
14
+ an unpaid invoice's detail view).
15
+ * THEN: only invoices whose status is 'Sent' or 'Overdue' qualify for the aging
16
+ report (Paid/Draft skipped) — so the two just-paid invoices drop out.
17
+ * days_overdue = today - dueDate; bucket by Current(<=0)/1-30/31-60/61-90/90+.
18
+ * Detail rows: Customer, InvoiceNumber, Total, DueDate, DaysOverdue, Bucket,
19
+ one row per qualifying invoice, sorted by DaysOverdue DESC.
20
+ * Summary block: one row per bucket (col A label, col C SUM of Total) in fixed
21
+ order Current,1-30,31-60,61-90,90+, then a 'Grand Total' row.
22
+
23
+ GROUND TRUTH EMBEDDING:
24
+ * quickbooks.invoices[*]: each invoice that ends qualifying (Sent/Overdue after
25
+ reconciliation) carries a hidden `_age` = {'days_overdue': int, 'bucket': str}.
26
+ The two reconcile invoices carry `_receive_payment=True` and NO `_age` (they
27
+ must be marked Paid and excluded). Paid/Draft distractors carry neither.
28
+ * google_sheets._task_adapter holds `expected_rows` (ordered detail rows) and
29
+ `expected_summary` (per-bucket totals, fixed order) + `grand_total`.
30
+
31
+ Everything below is PRECOMPUTED with datetime so the embedded answer key is
32
+ internally consistent with the visible invoice data. The 'AR Aging' tab ships
33
+ header-row-only (Rule 3: the observable result is ABSENT at injection); the two
34
+ reconcile invoices ship UNPAID (status 'Sent', so 'Receive payment' is available).
35
+ """
36
+ import datetime as _dt
37
+ import os
38
+ import shlex
39
+ import subprocess
40
+ import time
41
+ import uuid
42
+
43
+ import requests
44
+
45
+
46
+ sid = str(uuid.uuid4())
47
+ with open('/tmp/task_web_sid', 'w', encoding='utf-8') as f:
48
+ f.write(sid)
49
+ print(f'Generated sid: {sid}')
50
+
51
+
52
+ # ---------------------------------------------------------------------------
53
+ # Fixed "today" and bucket logic (matches the instruction exactly)
54
+ # ---------------------------------------------------------------------------
55
+ TODAY = _dt.date(2026, 4, 30)
56
+
57
+
58
+ def _days_overdue(due_date_str):
59
+ """today - dueDate (positive = overdue, <=0 = not yet due)."""
60
+ due = _dt.date.fromisoformat(due_date_str)
61
+ return (TODAY - due).days
62
+
63
+
64
+ def _bucket(days):
65
+ """Aging bucket per instruction (Current<=0, then 1-30/31-60/61-90/90+)."""
66
+ if days <= 0:
67
+ return 'Current'
68
+ if days <= 30:
69
+ return '1-30'
70
+ if days <= 60:
71
+ return '31-60'
72
+ if days <= 90:
73
+ return '61-90'
74
+ return '90+'
75
+
76
+
77
+ # Fixed bucket display order for the summary block.
78
+ BUCKET_ORDER = ['Current', '1-30', '31-60', '61-90', '90+']
79
+
80
+
81
+ # ---------------------------------------------------------------------------
82
+ # Customers (seeded so qualifying invoices resolve to real display names)
83
+ # ---------------------------------------------------------------------------
84
+ _CUSTOMERS = [
85
+ {'id': 'c1', 'name': 'Acme Corporation', 'company': 'Acme Corporation', 'email': 'ap@acmecorp.com', 'phone': '(555) 100-1001'},
86
+ {'id': 'c2', 'name': 'Globex Industries', 'company': 'Globex Industries', 'email': 'billing@globexind.com', 'phone': '(555) 100-1002'},
87
+ {'id': 'c3', 'name': 'Initech LLC', 'company': 'Initech LLC', 'email': 'finance@initech.com', 'phone': '(555) 100-1003'},
88
+ {'id': 'c4', 'name': 'Umbrella Health', 'company': 'Umbrella Health', 'email': 'accounts@umbrella.com', 'phone': '(555) 100-1004'},
89
+ {'id': 'c5', 'name': 'Soylent Foods', 'company': 'Soylent Foods', 'email': 'ap@soylentfoods.com', 'phone': '(555) 100-1005'},
90
+ {'id': 'c6', 'name': 'Stark Industries', 'company': 'Stark Industries', 'email': 'billing@stark.com', 'phone': '(555) 100-1006'},
91
+ {'id': 'c7', 'name': 'Wayne Enterprises', 'company': 'Wayne Enterprises', 'email': 'ap@wayne.com', 'phone': '(555) 100-1007'},
92
+ {'id': 'c8', 'name': 'Hooli Inc.', 'company': 'Hooli Inc.', 'email': 'finance@hooli.com', 'phone': '(555) 100-1008'},
93
+ {'id': 'c9', 'name': 'Cyberdyne Systems', 'company': 'Cyberdyne Systems', 'email': 'accounts@cyberdyne.com', 'phone': '(555) 100-1009'},
94
+ {'id': 'c10', 'name': 'Vandelay Industries', 'company': 'Vandelay Industries', 'email': 'ap@vandelay.com', 'phone': '(555) 100-1010'},
95
+ ]
96
+ for _c in _CUSTOMERS:
97
+ _c.setdefault('address', '100 Market St, San Francisco, CA 94105')
98
+ _c.setdefault('balance', 0)
99
+ _c.setdefault('notes', '')
100
+ _c.setdefault('isActive', True)
101
+ _c.setdefault('createdAt', '2025-11-01')
102
+
103
+ _CUST_NAME = {c['id']: c['name'] for c in _CUSTOMERS}
104
+
105
+
106
+ # ---------------------------------------------------------------------------
107
+ # Invoice spec. qualifies=True -> Sent/Overdue (counts); False -> distractor.
108
+ # reconcile=True -> announced as paid in Gmail; agent must 'Receive payment'
109
+ # (mark Paid) FIRST, so it drops OUT of the aging report. Ships UNPAID.
110
+ # Format: (number, customerId, dueDate, total, status, qualifies, reconcile)
111
+ # ---------------------------------------------------------------------------
112
+ # 10 Sent/Overdue invoices span ALL five buckets (2 each); each has a UNIQUE
113
+ # days-overdue so the DaysOverdue-desc ordering is unambiguous. Future due
114
+ # dates (-> Current) carry status 'Sent'; past-due carry status 'Overdue'.
115
+ # Two of them (1003, 1007) are the reconcile invoices the agent must mark Paid.
116
+ _INVOICE_SPEC = [
117
+ # --- Current (not yet due, days <= 0) ---
118
+ ('1001', 'c1', '2026-05-15', 1500.00, 'Sent', True, False), # days -15
119
+ ('1002', 'c2', '2026-05-30', 2400.00, 'Sent', True, False), # days -30
120
+ # --- 1-30 ---
121
+ ('1003', 'c3', '2026-04-20', 3200.00, 'Overdue', True, True), # days 10 -> RECONCILE (mark Paid)
122
+ ('1004', 'c4', '2026-04-05', 1800.00, 'Overdue', True, False), # days 25
123
+ # --- 31-60 ---
124
+ ('1005', 'c5', '2026-03-20', 4500.00, 'Overdue', True, False), # days 41
125
+ ('1006', 'c6', '2026-03-10', 2750.00, 'Overdue', True, False), # days 51
126
+ # --- 61-90 ---
127
+ ('1007', 'c7', '2026-02-20', 5200.00, 'Overdue', True, True), # days 69 -> RECONCILE (mark Paid)
128
+ ('1008', 'c8', '2026-02-10', 3600.00, 'Overdue', True, False), # days 79
129
+ # --- 90+ ---
130
+ ('1009', 'c9', '2026-01-15', 6800.00, 'Overdue', True, False), # days 105
131
+ ('1010', 'c10', '2025-12-20', 4100.00, 'Overdue', True, False), # days 131
132
+
133
+ # --- DISTRACTORS: Paid / Draft -> NO _age, must be skipped by the agent ---
134
+ ('1011', 'c1', '2026-03-01', 2200.00, 'Paid', False, False), # paid, ignore
135
+ ('1012', 'c3', '2026-02-15', 9900.00, 'Paid', False, False), # paid, ignore
136
+ ('1013', 'c5', '2026-05-25', 1750.00, 'Draft', False, False), # draft, ignore
137
+ ('1014', 'c7', '2026-04-10', 8800.00, 'Draft', False, False), # draft, ignore
138
+ ]
139
+
140
+
141
+ def _build_invoice(idx, number, customer_id, due_date, total, status, qualifies, reconcile):
142
+ """Builder helper -> a schema-complete Invoice (cf. quickbooks_mock schema).
143
+
144
+ Invoices that END qualifying carry the hidden `_age` answer-key field.
145
+ Reconcile invoices ship UNPAID but carry `_receive_payment=True` and NO
146
+ `_age` (they must be marked Paid and excluded). Distractors carry neither.
147
+ """
148
+ inv_date = (_dt.date.fromisoformat(due_date) - _dt.timedelta(days=30)).isoformat()
149
+ paid = (status == 'Paid')
150
+ inv = {
151
+ 'id': f'inv{idx}',
152
+ 'number': number,
153
+ 'customerId': customer_id,
154
+ 'date': inv_date,
155
+ 'dueDate': due_date,
156
+ 'items': [{
157
+ 'id': f'inv{idx}_li1',
158
+ 'productId': 'p1',
159
+ 'description': 'Professional services',
160
+ 'qty': 1,
161
+ 'rate': total,
162
+ 'amount': total,
163
+ }],
164
+ 'subtotal': total,
165
+ 'tax': 0,
166
+ 'total': total,
167
+ 'status': status,
168
+ 'paidAmount': total if paid else 0,
169
+ 'paidDate': inv_date if paid else None,
170
+ 'terms': 'Net 30',
171
+ 'message': '',
172
+ 'createdAt': f'{inv_date}T09:00:00Z',
173
+ }
174
+ if reconcile:
175
+ # Announced paid in Gmail; agent must Receive payment -> Paid, then it is
176
+ # excluded from the aging report. No _age (it must not appear in rows).
177
+ inv['_receive_payment'] = True
178
+ elif qualifies:
179
+ days = _days_overdue(due_date)
180
+ inv['_age'] = {'days_overdue': days, 'bucket': _bucket(days)}
181
+ return inv
182
+
183
+
184
+ _INVOICES = [
185
+ _build_invoice(i, number, cid, due, total, status, qualifies, reconcile)
186
+ for i, (number, cid, due, total, status, qualifies, reconcile)
187
+ in enumerate(_INVOICE_SPEC, start=1)
188
+ ]
189
+
190
+
191
+ # ---------------------------------------------------------------------------
192
+ # Precompute the answer key (expected_rows + expected_summary) from the SAME
193
+ # source data so the embedded values are internally consistent.
194
+ # ---------------------------------------------------------------------------
195
+ _qualifying = []
196
+ _RECONCILE_NUMBERS = []
197
+ _RECONCILE = [] # (number, customer_name, total) for the Gmail notice + answer key
198
+ for (number, cid, due, total, status, qualifies, reconcile) in _INVOICE_SPEC:
199
+ if reconcile:
200
+ _RECONCILE_NUMBERS.append(number)
201
+ _RECONCILE.append({'number': number, 'customer': _CUST_NAME[cid], 'total': total})
202
+ continue # reconcile invoices are marked Paid -> excluded from the report
203
+ if not qualifies:
204
+ continue
205
+ days = _days_overdue(due)
206
+ _qualifying.append({
207
+ 'Customer': _CUST_NAME[cid],
208
+ 'InvoiceNumber': number,
209
+ 'Total': total,
210
+ 'DueDate': due,
211
+ 'DaysOverdue': days,
212
+ 'Bucket': _bucket(days),
213
+ })
214
+
215
+ # Detail rows sorted by DaysOverdue DESC (most overdue first). Unique day values
216
+ # guarantee a stable, unambiguous order.
217
+ EXPECTED_ROWS = sorted(_qualifying, key=lambda r: r['DaysOverdue'], reverse=True)
218
+
219
+ # Per-bucket SUM of Total in the fixed bucket order.
220
+ _bucket_totals = {b: 0.0 for b in BUCKET_ORDER}
221
+ for r in _qualifying:
222
+ _bucket_totals[r['Bucket']] += r['Total']
223
+ EXPECTED_SUMMARY = [
224
+ {'bucket': b, 'total': round(_bucket_totals[b], 2)} for b in BUCKET_ORDER
225
+ ]
226
+ GRAND_TOTAL = round(sum(r['Total'] for r in _qualifying), 2)
227
+
228
+ # Self-check: 2 reconcile invoices, 8 rows remain in the report (10 Sent/Overdue - 2).
229
+ assert len(_RECONCILE_NUMBERS) == 2, _RECONCILE_NUMBERS
230
+ assert len(EXPECTED_ROWS) == 8, len(EXPECTED_ROWS)
231
+ assert all(r['InvoiceNumber'] not in _RECONCILE_NUMBERS for r in EXPECTED_ROWS)
232
+ print(f'Reconcile-first invoices (mark Paid, exclude): {_RECONCILE_NUMBERS}; '
233
+ f'aging rows after reconcile: {len(EXPECTED_ROWS)}; grand total {GRAND_TOTAL}')
234
+
235
+
236
+ # ---------------------------------------------------------------------------
237
+ # Google Sheet — 'AR Aging' tab, header row only (observable result ABSENT).
238
+ # Headers map to columns A..F: Customer, InvoiceNumber, Total, DueDate,
239
+ # DaysOverdue, Bucket.
240
+ # ---------------------------------------------------------------------------
241
+ AR_HEADERS = ['Customer', 'InvoiceNumber', 'Total', 'DueDate', 'DaysOverdue', 'Bucket']
242
+ _HEADER_STYLE = {'bold': True, 'bg': '#F3F3F3', 'align': 'center'}
243
+
244
+
245
+ def _header_cell(text):
246
+ return {'value': text, 'formula': text, 'computed': text, 'style': dict(_HEADER_STYLE)}
247
+
248
+
249
+ _ar_data = {}
250
+ for col_idx, header in enumerate(AR_HEADERS):
251
+ col_letter = chr(ord('A') + col_idx)
252
+ _ar_data[f'{col_letter}1'] = _header_cell(header)
253
+
254
+
255
+ _SHEET_STATE = {
256
+ 'id': 'workbook_ar_aging',
257
+ 'title': 'AR Aging Workbook',
258
+ 'activeSheetId': 'sheet_ar',
259
+ 'selectedCell': 'A1',
260
+ 'selectionRange': None,
261
+ 'clipboard': None,
262
+ 'isDragging': False,
263
+ 'undoStack': [],
264
+ 'redoStack': [],
265
+ 'namedRanges': [],
266
+ 'conditionalFormats': [],
267
+ 'charts': [],
268
+ 'showGridlines': True,
269
+ 'showFormulas': False,
270
+ 'zoom': 100,
271
+ 'sheets': [{
272
+ 'id': 'sheet_ar',
273
+ 'name': 'AR Aging',
274
+ 'data': _ar_data, # header row 1 only; rows + summary ABSENT
275
+ 'rowCount': 100,
276
+ 'colCount': 26,
277
+ 'frozenRows': 1,
278
+ 'frozenCols': 0,
279
+ 'tabColor': None,
280
+ 'isHidden': False,
281
+ 'columnWidths': {},
282
+ 'rowHeights': {},
283
+ 'filterRange': None,
284
+ 'filterCriteria': {},
285
+ 'sortColumn': None,
286
+ 'sortDirection': None,
287
+ }],
288
+ '_task_adapter': {
289
+ 'source_schema': 'ar_aging',
290
+ 'task_id': '29e36334-3263-4955-9d91-a14163000860',
291
+ 'variant': 'eval',
292
+ 'today': TODAY.isoformat(),
293
+ 'target_sheet': 'AR Aging',
294
+ 'headers': AR_HEADERS,
295
+ 'bucket_order': BUCKET_ORDER,
296
+ 'sheet_names': ['AR Aging'],
297
+ 'headers_by_sheet': {'AR Aging': AR_HEADERS},
298
+ # ---- ANSWER KEY ----
299
+ 'expected_rows': EXPECTED_ROWS,
300
+ 'expected_summary': EXPECTED_SUMMARY,
301
+ 'grand_total': GRAND_TOTAL,
302
+ 'reconcile_invoice_numbers': _RECONCILE_NUMBERS,
303
+ },
304
+ }
305
+
306
+
307
+ # ---------------------------------------------------------------------------
308
+ # QuickBooks state (partial inject; deep-merged with mock defaults).
309
+ # ---------------------------------------------------------------------------
310
+ _QB_STATE = {
311
+ 'company': {
312
+ 'name': 'Acme Corp',
313
+ 'address': '123 Business Rd, San Francisco, CA 94105',
314
+ 'email': 'admin@acmecorp.com',
315
+ 'industry': 'Technology Services',
316
+ 'accountingMethod': 'Accrual',
317
+ },
318
+ 'customers': _CUSTOMERS,
319
+ 'invoices': _INVOICES,
320
+ }
321
+
322
+
323
+ # ---------------------------------------------------------------------------
324
+ # Gmail state — a remittance notice naming the two invoices that were wired in.
325
+ # The agent reads this, then uses QB 'Receive payment' to mark them Paid. NO
326
+ # aging-report artefact here; this mailbox is read-only context.
327
+ # ---------------------------------------------------------------------------
328
+ _RECON_LINES = '<br>'.join(
329
+ f"- Invoice {r['number']} ({r['customer']}): ${r['total']:.2f}" for r in _RECONCILE
330
+ )
331
+ _GMAIL_STATE = {
332
+ 'user': {'userId': 'u1', 'username': 'Dana Reyes',
333
+ 'email': 'dana.reyes@acmecorp.com',
334
+ 'avatar': 'https://picsum.photos/200/200?random=3'},
335
+ 'emails': [
336
+ {'id': 'm_remit', 'threadId': 'thread_remit',
337
+ 'from': {'name': 'Accounts Receivable', 'email': 'ar-bank@acmecorp.com', 'avatar': ''},
338
+ 'to': [{'name': 'Dana Reyes', 'email': 'dana.reyes@acmecorp.com'}],
339
+ 'cc': [], 'bcc': [],
340
+ 'subject': 'Wire payments received — please reconcile before AR aging',
341
+ 'body': ('Hi Dana,<br><br>Two customer wires cleared this morning. Please '
342
+ 'mark these invoices as paid in QuickBooks before you run the AR '
343
+ f'aging report so they are not counted as outstanding:<br><br>{_RECON_LINES}'
344
+ '<br><br>Thanks,<br>AR Bank Desk'),
345
+ 'snippet': 'Two customer wires cleared this morning. Please mark these invoices as paid...',
346
+ 'timestamp': '2026-04-30T07:30:00Z', 'read': False, 'starred': False,
347
+ 'important': True, 'labels': [], 'category': 'primary', 'folder': 'inbox',
348
+ 'attachments': []},
349
+ {'id': 'm_decoy1', 'threadId': 'thread_d1',
350
+ 'from': {'name': 'Office Newsletter', 'email': 'news@acmecorp.com', 'avatar': ''},
351
+ 'to': [{'name': 'Dana Reyes', 'email': 'dana.reyes@acmecorp.com'}],
352
+ 'cc': [], 'bcc': [],
353
+ 'subject': 'April company update', 'body': 'Highlights from the month and a few reminders.',
354
+ 'snippet': 'Highlights from the month...', 'timestamp': '2026-04-29T15:00:00Z',
355
+ 'read': True, 'starred': False, 'important': False, 'labels': [],
356
+ 'category': 'updates', 'folder': 'inbox', 'attachments': []},
357
+ ],
358
+ 'labels': [
359
+ {'id': 'l1', 'name': 'Work', 'color': '#ef4444'},
360
+ {'id': 'l2', 'name': 'Finance', 'color': '#eab308'},
361
+ ],
362
+ 'drafts': [],
363
+ 'settings': {'density': 'default', 'undoSend': 10},
364
+ 'today': '2026-04-30',
365
+ }
366
+
367
+
368
+ # ---------------------------------------------------------------------------
369
+ # State payloads to inject (ports from the shipped registry).
370
+ # ---------------------------------------------------------------------------
371
+ APP_STATES = [
372
+ ('http://28.7.184.198:8172', _QB_STATE), # quickbooks_mock
373
+ ('http://28.7.184.198:8145', _SHEET_STATE), # google_sheets_mock
374
+ ('http://28.7.184.198:8138', _GMAIL_STATE), # gmail_mock
375
+ ]
376
+
377
+
378
+ for app_url, state in APP_STATES:
379
+ resp = requests.post(
380
+ f'{app_url}/post?sid={sid}',
381
+ json={'action': 'set', 'state': state},
382
+ timeout=30,
383
+ )
384
+ assert resp.status_code == 200, (
385
+ f'State injection failed for {app_url}: {resp.text}'
386
+ )
387
+ print(f'State injected: {app_url} sid={sid}')
388
+
389
+ for app_url, _ in APP_STATES:
390
+ go_payload = requests.get(f'{app_url}/go?sid={sid}', timeout=15).json()
391
+ assert go_payload.get('initial_state') is not None, (
392
+ f'initial_state is None after injection for {app_url}'
393
+ )
394
+ print(f'Verified initial_state set: {app_url}')
395
+
396
+
397
+ # PATCHED_BY: patch_wait_mocks_loaded.py
398
+ def launch_gui(command, delay_sec=1.0):
399
+ """Launch a GUI command, fully detached from this script.
400
+
401
+ Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that
402
+ wait_mocks_loaded's CDP phase can verify browser render below.
403
+ Idempotent: if the caller already specified a debug port, keep it.
404
+ """
405
+ env = os.environ.copy()
406
+ env['DISPLAY'] = ':0'
407
+ if isinstance(command, str):
408
+ _parts = shlex.split(command)
409
+ else:
410
+ _parts = list(command)
411
+ if (_parts and 'google-chrome' in _parts[0]
412
+ and not any(p.startswith('--remote-debugging-port') for p in _parts)):
413
+ _parts[1:1] = [
414
+ '--no-first-run',
415
+ '--no-default-browser-check',
416
+ '--remote-debugging-port=1337',
417
+ ]
418
+ subprocess.Popen(
419
+ _parts,
420
+ stdin=subprocess.DEVNULL,
421
+ stdout=subprocess.DEVNULL,
422
+ stderr=subprocess.DEVNULL,
423
+ env=env,
424
+ start_new_session=True,
425
+ )
426
+ time.sleep(delay_sec)
427
+
428
+
429
+ def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12):
430
+ """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style.
431
+
432
+ Phase 1 - Backend readiness:
433
+ Poll each mock's /state?sid=<sid> (preferred) or /go?sid=<sid>
434
+ (fallback) until it returns 200 with 'stored_state' or
435
+ 'initial_state' respectively, or until timeout.
436
+
437
+ Phase 2 - Browser render verification (via CDP + Playwright):
438
+ Connect to http://localhost:1337 (the --remote-debugging-port
439
+ injected by launch_gui above), wait for every open tab to reach
440
+ 'networkidle' AND to contain at least 20 DOM elements. This
441
+ guarantees the SPA fetched /go?sid= data AND actually painted,
442
+ not just that the mock backend is up.
443
+
444
+ Fallback:
445
+ If Playwright is missing or CDP cannot be reached, sleep for
446
+ `render_buffer` seconds as a best-effort delay so the screenshot
447
+ loop does not start on a still-blank tab.
448
+ """
449
+ import urllib.request as _urlreq
450
+ import time as _t
451
+ _urls = [p for p, _ in app_states]
452
+ _opener = _urlreq.build_opener(_urlreq.ProxyHandler({}))
453
+
454
+ # ---- Phase 1: backend readiness ----
455
+ _deadline = _t.time() + timeout
456
+ _todo = list(_urls)
457
+ while _todo and _t.time() < _deadline:
458
+ _rest = []
459
+ for _u in _todo:
460
+ _ok = False
461
+ for _path, _need in (('/state?sid=', b'stored_state'),
462
+ ('/go?sid=', b'initial_state')):
463
+ try:
464
+ _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5)
465
+ if _r.status == 200:
466
+ _body = _r.read()
467
+ if _need in _body:
468
+ _ok = True
469
+ break
470
+ except Exception:
471
+ pass
472
+ if _ok:
473
+ print(f" {_u}: backend ready")
474
+ continue
475
+ _rest.append(_u)
476
+ _todo = _rest
477
+ if _todo:
478
+ _t.sleep(2)
479
+ _done = len(_urls) - len(_todo)
480
+ _pend = f" (pending: {_todo})" if _todo else ""
481
+ print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}")
482
+
483
+ # ---- Phase 2: browser render verification via CDP ----
484
+ _cdp_ok = False
485
+ try:
486
+ from playwright.sync_api import sync_playwright
487
+ _cdp_dl = _t.time() + max(15.0, _deadline - _t.time())
488
+ with sync_playwright() as _p:
489
+ _br = None
490
+ while _t.time() < _cdp_dl:
491
+ try:
492
+ _br = _p.chromium.connect_over_cdp('http://localhost:1337')
493
+ break
494
+ except Exception:
495
+ _t.sleep(0.5)
496
+ if _br is None:
497
+ print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?")
498
+ else:
499
+ _n_expected = len(_urls)
500
+ _pages = []
501
+ _pg_dl = _t.time() + 15
502
+ _last_count = -1
503
+ _stable_since = None
504
+ while _t.time() < _pg_dl:
505
+ _pages = []
506
+ for _c in _br.contexts:
507
+ _pages.extend(_c.pages)
508
+ _cnt = len(_pages)
509
+ if _n_expected > 0 and _cnt >= _n_expected:
510
+ break
511
+ if _cnt > 0 and _cnt == _last_count:
512
+ if _stable_since is None:
513
+ _stable_since = _t.time()
514
+ elif _t.time() - _stable_since >= 1.5:
515
+ break
516
+ else:
517
+ _stable_since = None
518
+ _last_count = _cnt
519
+ _t.sleep(0.5)
520
+ _pages = []
521
+ for _c in _br.contexts:
522
+ _pages.extend(_c.pages)
523
+ if not _pages:
524
+ print(" wait_mocks_loaded: CDP connected but no open tabs found")
525
+ else:
526
+ print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render")
527
+ _MIN_ELEMS = 20
528
+ _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap
529
+ for _pg in _pages: # bring each to front once to defeat background-tab render throttling
530
+ try:
531
+ _pg.bring_to_front()
532
+ except Exception:
533
+ pass
534
+ _pending = list(_pages)
535
+ while _pending and _t.time() < _verify_dl:
536
+ _still = []
537
+ for _pg in _pending:
538
+ _ttl = ""
539
+ try:
540
+ _ttl = _pg.title()
541
+ except Exception:
542
+ pass
543
+ try:
544
+ _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0")
545
+ except Exception:
546
+ _n = 0
547
+ if _n >= _MIN_ELEMS:
548
+ print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)")
549
+ else:
550
+ _still.append(_pg)
551
+ _pending = _still
552
+ if _pending:
553
+ _t.sleep(2)
554
+ if not _pending:
555
+ _cdp_ok = True
556
+ else:
557
+ for _pg in _pending:
558
+ _ttl = ""
559
+ try:
560
+ _ttl = _pg.title()
561
+ except Exception:
562
+ pass
563
+ print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back")
564
+ except ImportError:
565
+ print(" wait_mocks_loaded: playwright not installed; skipping CDP phase")
566
+ except Exception as _e:
567
+ print(f" wait_mocks_loaded: CDP phase error ({_e!r})")
568
+
569
+ if not _cdp_ok:
570
+ print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep")
571
+ _t.sleep(render_buffer)
572
+ else:
573
+ print(" wait_mocks_loaded: browser render verified, skipping render_buffer")
574
+
575
+
576
+ def _open_mock_tabs(app_states, sid_value):
577
+ """Open the first mock as the primary Chrome window, the rest as new tabs.
578
+
579
+ Uses launch_gui once per URL so that the macOS localizer regex-extract
580
+ (which grabs the FIRST quoted URL per call) still works correctly.
581
+ """
582
+ _urls = [p for p, _ in app_states]
583
+ if not _urls:
584
+ return
585
+ launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0)
586
+ for _u in _urls[1:]:
587
+ launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0)
588
+
589
+
590
+
591
+ # PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate)
592
+ def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0):
593
+ """Block until every mock serves injected state AND (best-effort) renders."""
594
+ import time as _t
595
+ deadline = _t.time() + timeout
596
+ pending = dict(mocks)
597
+ while pending and _t.time() < deadline:
598
+ for name in list(pending):
599
+ try:
600
+ r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5)
601
+ if r.status_code == 200 and r.json().get('initial_state') is not None:
602
+ del pending[name]
603
+ except Exception:
604
+ pass
605
+ if pending:
606
+ _t.sleep(1.0)
607
+ if pending:
608
+ print(f'WARN: mocks not ready within {timeout}s: {list(pending)}')
609
+ try:
610
+ from playwright.sync_api import sync_playwright
611
+ except ImportError:
612
+ print('WARN: playwright not installed; skipping render check, settle 3s')
613
+ _t.sleep(3.0)
614
+ return
615
+ with sync_playwright() as p:
616
+ try:
617
+ browser = p.chromium.launch(channel='chrome', headless=True,
618
+ args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'])
619
+ except Exception as e:
620
+ print(f'WARN: could not launch chrome for render check: {e}; settle 3s')
621
+ _t.sleep(3.0)
622
+ return
623
+ try:
624
+ for name, url in mocks.items():
625
+ page = browser.new_page()
626
+ try:
627
+ page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000))
628
+ page.wait_for_function(
629
+ "document.body && document.body.innerText.length > 50",
630
+ timeout=int(render_timeout * 1000))
631
+ print(f'[{name}] rendered OK')
632
+ except Exception as e:
633
+ print(f'WARN: [{name}] render check issue: {e}')
634
+ finally:
635
+ page.close()
636
+ finally:
637
+ browser.close()
638
+
639
+
640
+ # ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render
641
+ _open_mock_tabs(APP_STATES, sid)
642
+ wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15)
643
+ wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12)
644
+ print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps')
ar_remittance_008__long/reward.py ADDED
@@ -0,0 +1,664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: T06 — QuickBooks AR aging report into Google Sheets (+ Gmail reconcile)
3
+ Task ID: ar_remittance_008__long
4
+ Mocks: quickbooks_mock,google_sheets_mock,gmail_mock
5
+ Scoring (all components 0 at do-nothing; reconcile invoices ship unpaid):
6
+ 0.40 detail rows == expected_rows as an ORDERED list (DaysOverdue desc),
7
+ matching on (Customer, InvoiceNumber, Total, Bucket); frac of correctly-placed rows
8
+ 0.15 DaysOverdue + Bucket values correct per row (avg of two per-row sub-checks)
9
+ 0.20 per-bucket SUM rows match expected_summary (5 buckets, col A label + col C sum, exact)
10
+ 0.10 Grand Total row ('Grand Total' label + col C sum == grand_total)
11
+ 0.15 the two Gmail-announced invoices marked Paid via 'Receive payment' (status-gated)
12
+ (− modest over-inclusion penalty for Paid/Draft distractor invoice rows, capped 0.10)
13
+ Answer key: google_sheets.initial_state._task_adapter.expected_rows / expected_summary /
14
+ grand_total / reconcile_invoice_numbers (primary) + quickbooks invoices[*]._age.
15
+ """
16
+ import copy
17
+ import datetime as _dt
18
+ import re
19
+ import sys
20
+
21
+ import requests
22
+
23
+
24
+ try:
25
+ with open('/tmp/task_web_sid', encoding='utf-8') as f:
26
+ sid = f.read().strip()
27
+ if not sid:
28
+ raise ValueError('sid is empty')
29
+ except Exception as e:
30
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
31
+ print('REWARD: 0.0')
32
+ sys.exit(0)
33
+
34
+
35
+ APP_URLS = {'quickbooks': 'http://28.7.184.198:8172', 'google_sheets': 'http://28.7.184.198:8145'}
36
+ _GO_CACHE = {}
37
+
38
+
39
+ def clamp01(x):
40
+ return max(0.0, min(1.0, float(x)))
41
+
42
+
43
+ def frac(num, den):
44
+ return 0.0 if den == 0 else num / den
45
+
46
+
47
+ def f1(true_set, pred_set):
48
+ if not true_set and not pred_set:
49
+ return 1.0
50
+ tp = len(true_set & pred_set)
51
+ if tp == 0:
52
+ return 0.0
53
+ prec = tp / len(pred_set)
54
+ rec = tp / len(true_set)
55
+ return 2 * prec * rec / (prec + rec)
56
+
57
+
58
+ def by_id(items, key='id'):
59
+ return {it.get(key): it for it in (items or []) if isinstance(it, dict)}
60
+
61
+
62
+ def has_text(haystack, *needles):
63
+ s = (haystack or '').lower()
64
+ return any(n.lower() in s for n in needles)
65
+
66
+
67
+ def norm(s):
68
+ return (str(s) if s is not None else '').strip().lower()
69
+
70
+
71
+ def _to_float(v):
72
+ try:
73
+ return float(v)
74
+ except (TypeError, ValueError):
75
+ return 0.0
76
+
77
+
78
+ def _msg_text(m):
79
+ return m.get('content') or m.get('text') or ''
80
+
81
+
82
+ def _slack_channel_messages(slack_state, channel_name):
83
+ # Slack messages may live under channels[*].messages OR the top-level
84
+ # messages[channelId] map — read both.
85
+ if not isinstance(slack_state, dict):
86
+ return []
87
+ channels = slack_state.get('channels') if isinstance(slack_state.get('channels'), list) else []
88
+ messages_map = slack_state.get('messages') if isinstance(slack_state.get('messages'), dict) else {}
89
+ out = []
90
+ for ch in channels:
91
+ if not isinstance(ch, dict):
92
+ continue
93
+ if norm(ch.get('name')) != norm(channel_name):
94
+ continue
95
+ cid = ch.get('channelId') or ch.get('id')
96
+ for m in (ch.get('messages') if isinstance(ch.get('messages'), list) else []):
97
+ if isinstance(m, dict):
98
+ out.append(m)
99
+ if cid and isinstance(messages_map.get(cid), list):
100
+ for m in messages_map[cid]:
101
+ if isinstance(m, dict):
102
+ out.append(m)
103
+ return out
104
+
105
+
106
+ def _sheet_rows(sheet):
107
+ if not isinstance(sheet, dict):
108
+ return []
109
+ rows = sheet.get('rows', [])
110
+ return rows if isinstance(rows, list) else []
111
+
112
+
113
+ def _sheet_tabs(sheets):
114
+ if isinstance(sheets, dict):
115
+ return sheets
116
+ if isinstance(sheets, list):
117
+ out = {}
118
+ for sh in sheets:
119
+ if not isinstance(sh, dict):
120
+ continue
121
+ name = sh.get('name') or sh.get('id')
122
+ if name:
123
+ out[name] = sh
124
+ return out
125
+ return {}
126
+
127
+
128
+ def _normalize_app_name(app):
129
+ app = (app or '').strip().lower()
130
+ return app[:-5] if app.endswith('_mock') else app
131
+
132
+
133
+ def _parse_cell_id(cell_id):
134
+ if not isinstance(cell_id, str) or not cell_id:
135
+ return None
136
+ idx = 0
137
+ while idx < len(cell_id) and cell_id[idx].isalpha():
138
+ idx += 1
139
+ if idx == 0 or idx >= len(cell_id):
140
+ return None
141
+ col = 0
142
+ for ch in cell_id[:idx].upper():
143
+ col = col * 26 + (ord(ch) - ord('A') + 1)
144
+ try:
145
+ row = int(cell_id[idx:])
146
+ except ValueError:
147
+ return None
148
+ return row, col - 1
149
+
150
+
151
+ def _extract_rows_from_workbook(state):
152
+ if not isinstance(state, dict):
153
+ return None
154
+ sheets = state.get('sheets')
155
+ if not isinstance(sheets, list):
156
+ return None
157
+
158
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
159
+ headers_by_sheet = adapter.get('headers_by_sheet') if isinstance(adapter.get('headers_by_sheet'), dict) else {}
160
+
161
+ out = {}
162
+ for sh in sheets:
163
+ if not isinstance(sh, dict):
164
+ continue
165
+ name = sh.get('name') or sh.get('id') or 'Sheet1'
166
+ data = sh.get('data') if isinstance(sh.get('data'), dict) else {}
167
+
168
+ headers = headers_by_sheet.get(name)
169
+ if not headers:
170
+ cols = []
171
+ for cid, cell in data.items():
172
+ rc = _parse_cell_id(cid)
173
+ if not rc:
174
+ continue
175
+ row_idx, col_idx = rc
176
+ if row_idx != 1:
177
+ continue
178
+ value = ''
179
+ if isinstance(cell, dict):
180
+ value = cell.get('value', '')
181
+ elif cell is not None:
182
+ value = str(cell)
183
+ if value is not None and str(value) != '':
184
+ cols.append((col_idx, str(value)))
185
+ headers = [v for _, v in sorted(cols)]
186
+
187
+ if not headers:
188
+ continue
189
+
190
+ by_row = {}
191
+ for cid, cell in data.items():
192
+ rc = _parse_cell_id(cid)
193
+ if not rc:
194
+ continue
195
+ row_idx, col_idx = rc
196
+ if row_idx <= 1 or col_idx >= len(headers):
197
+ continue
198
+ if isinstance(cell, dict):
199
+ value = cell.get('value', '')
200
+ else:
201
+ value = cell
202
+ by_row.setdefault(row_idx, {})[headers[col_idx]] = value
203
+
204
+ rows = []
205
+ for row_idx in sorted(by_row.keys()):
206
+ row = by_row[row_idx]
207
+ if not any(str(row.get(h, '')).strip() for h in headers):
208
+ continue
209
+ rows.append({h: row.get(h, '') for h in headers})
210
+
211
+ out[name] = {'headers': headers, 'rows': rows}
212
+
213
+ if not out:
214
+ return None
215
+ return {'sheets': out}
216
+
217
+
218
+ def _materialize_google_sheets(payload):
219
+ for key in ('initial_state', 'current_state'):
220
+ state = payload.get(key)
221
+ if not isinstance(state, dict):
222
+ continue
223
+ maybe_rows = _extract_rows_from_workbook(state)
224
+ if maybe_rows is not None:
225
+ state['_ui_workbook'] = {
226
+ 'sheets': copy.deepcopy(state.get('sheets', [])),
227
+ 'title': state.get('title'),
228
+ }
229
+ state['sheets'] = maybe_rows['sheets']
230
+
231
+
232
+ def _materialize_slack(payload):
233
+ for key in ('initial_state', 'current_state'):
234
+ state = payload.get(key)
235
+ if not isinstance(state, dict):
236
+ continue
237
+ channels = state.get('channels') if isinstance(state.get('channels'), list) else []
238
+ messages_map = state.get('messages') if isinstance(state.get('messages'), dict) else {}
239
+ for ch in channels:
240
+ if not isinstance(ch, dict):
241
+ continue
242
+ cid = ch.get('channelId') or ch.get('id')
243
+ if not cid:
244
+ continue
245
+ msg_list = messages_map.get(cid) if isinstance(messages_map.get(cid), list) else []
246
+ channel_msgs = ch.get('messages') if isinstance(ch.get('messages'), list) else []
247
+ merged = {
248
+ (m.get('messageId') or m.get('id')): dict(m)
249
+ for m in channel_msgs
250
+ if isinstance(m, dict)
251
+ }
252
+ for m in msg_list:
253
+ if not isinstance(m, dict):
254
+ continue
255
+ mid = m.get('messageId') or m.get('id')
256
+ text = m.get('text') if m.get('text') is not None else m.get('content', '')
257
+ merged[mid] = {
258
+ 'id': mid,
259
+ 'messageId': mid,
260
+ 'text': text,
261
+ 'content': m.get('content', text),
262
+ 'senderId': m.get('senderId'),
263
+ 'timestamp': m.get('timestamp'),
264
+ 'reactions': m.get('reactions') if isinstance(m.get('reactions'), list) else [],
265
+ }
266
+ ch['messages'] = list(merged.values())
267
+
268
+
269
+ def _owner_name_map(state):
270
+ out = {}
271
+ users = state.get('users') if isinstance(state.get('users'), list) else []
272
+ for u in users:
273
+ if not isinstance(u, dict):
274
+ continue
275
+ uid = u.get('userId')
276
+ if not uid:
277
+ continue
278
+ name = (f"{u.get('firstName', '')} {u.get('lastName', '')}".strip() or u.get('name') or uid)
279
+ out[uid] = name
280
+ return out
281
+
282
+
283
+ def _materialize_salesforce(payload):
284
+ for key in ('initial_state', 'current_state'):
285
+ state = payload.get(key)
286
+ if not isinstance(state, dict):
287
+ continue
288
+
289
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
290
+ owner_names = _owner_name_map(state)
291
+
292
+ task_leads = adapter.get('task_leads') if isinstance(adapter.get('task_leads'), dict) else None
293
+ if task_leads and isinstance(state.get('leads'), list):
294
+ restored = []
295
+ for lead in state['leads']:
296
+ if not isinstance(lead, dict):
297
+ continue
298
+ lid = str(lead.get('leadId') or lead.get('id') or '')
299
+ meta = task_leads.get(lid, {})
300
+ restored.append({
301
+ 'id': meta.get('id') or lead.get('leadId') or lead.get('id'),
302
+ 'company': lead.get('company', meta.get('company', '')),
303
+ 'status': lead.get('status', 'New'),
304
+ 'ownerName': owner_names.get(lead.get('ownerId')) or meta.get('ownerName'),
305
+ 'annualRevenue': meta.get('annualRevenue', lead.get('revenue')),
306
+ })
307
+ state['leads'] = restored
308
+
309
+ task_accounts = adapter.get('task_accounts') if isinstance(adapter.get('task_accounts'), dict) else None
310
+ if task_accounts and isinstance(state.get('accounts'), list):
311
+ current_by_id = {}
312
+ for acc in state['accounts']:
313
+ if isinstance(acc, dict):
314
+ current_by_id[str(acc.get('accountId') or acc.get('id') or '')] = acc
315
+
316
+ restored_accounts = []
317
+ for aid, meta in task_accounts.items():
318
+ cur = current_by_id.get(str(aid), {})
319
+ restored_accounts.append({
320
+ 'id': meta.get('id') or aid,
321
+ 'name': meta.get('name') or cur.get('name', ''),
322
+ 'contact': meta.get('contact'),
323
+ 'wonWithin7d': bool(meta.get('wonWithin7d', False)),
324
+ 'onboardingStage': cur.get('onboardingStage', meta.get('onboardingStage')),
325
+ })
326
+ state['accounts'] = restored_accounts
327
+
328
+
329
+ def _materialize_google_docs(payload):
330
+ for key in ('initial_state', 'current_state'):
331
+ state = payload.get(key)
332
+ if not isinstance(state, dict):
333
+ continue
334
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
335
+ task_docs = adapter.get('task_documents') if isinstance(adapter.get('task_documents'), dict) else None
336
+ if not task_docs:
337
+ continue
338
+ docs_map = state.get('documents') if isinstance(state.get('documents'), dict) else {}
339
+ restored = []
340
+ for did, meta in task_docs.items():
341
+ cur = docs_map.get(did, {}) if isinstance(docs_map, dict) else {}
342
+ restored.append({
343
+ 'id': meta.get('id') or did,
344
+ 'title': cur.get('title', meta.get('title')),
345
+ 'vendor': meta.get('vendor'),
346
+ 'folder': meta.get('folder'),
347
+ 'content': cur.get('content', meta.get('content', '')),
348
+ })
349
+ state['documents'] = restored
350
+
351
+
352
+ def _adapt_payload_for_reward(app, payload):
353
+ app_name = _normalize_app_name(app)
354
+ if app_name == 'google_sheets':
355
+ _materialize_google_sheets(payload)
356
+ elif app_name == 'slack':
357
+ _materialize_slack(payload)
358
+ elif app_name == 'salesforce':
359
+ _materialize_salesforce(payload)
360
+ elif app_name == 'google_docs':
361
+ _materialize_google_docs(payload)
362
+ return payload
363
+
364
+
365
+ def go(app_name):
366
+ if app_name in _GO_CACHE:
367
+ return _GO_CACHE[app_name]
368
+
369
+ base = APP_URLS.get(app_name)
370
+ if not base:
371
+ print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)')
372
+ print('REWARD: 0.0')
373
+ sys.exit(0)
374
+
375
+ try:
376
+ resp = requests.get(f'{base}/go?sid={sid}', timeout=15)
377
+ resp.raise_for_status()
378
+ payload = resp.json()
379
+ except Exception as e:
380
+ print(f'CRITICAL: cannot fetch {app_name} go state: {e}')
381
+ print('REWARD: 0.0')
382
+ sys.exit(0)
383
+
384
+ payload = _adapt_payload_for_reward(app_name, payload)
385
+ _GO_CACHE[app_name] = payload
386
+ return payload
387
+
388
+
389
+ # === Task-specific reward ===
390
+ #
391
+ # The agent reads QuickBooks open invoices (Sent/Overdue only), buckets them by
392
+ # days overdue (today = 2026-04-30), and writes an AR-aging report into the
393
+ # 'AR Aging' tab of the Google Sheet:
394
+ # - one detail row per qualifying invoice (Customer, InvoiceNumber, Total,
395
+ # DueDate, DaysOverdue, Bucket), sorted by DaysOverdue DESC, and
396
+ # - a summary block: one row per bucket (label in col A, SUM of Total in col C)
397
+ # in fixed bucket order, then a 'Grand Total' row (sum in col C).
398
+ #
399
+ # Ground truth lives in google_sheets.initial_state._task_adapter (expected_rows,
400
+ # expected_summary, grand_total). QuickBooks invoices carry a hidden `_age` on the
401
+ # Sent/Overdue invoices; we read it to recover the qualifying-invoice set used for
402
+ # the distractor (Paid/Draft) over-inclusion guard.
403
+ def reward(go):
404
+ TOL = 0.01 # penny tolerance for currency / sums
405
+ W_DETAIL = 0.40
406
+ W_VALUES = 0.15
407
+ W_SUMMARY = 0.20
408
+ W_GRAND = 0.10
409
+ W_RECEIVE = 0.15 # reconcile invoices marked Paid via 'Receive payment'
410
+ PENALTY_PER_DISTRACTOR = 0.05
411
+ PENALTY_CAP = 0.10
412
+
413
+ # ---- helpers for raw cell-grid reading ----
414
+ def _cell_disp(cell):
415
+ # Resolve a cell to its displayed value: prefer `computed` when `value`
416
+ # is a formula (=SUM(...)) or empty.
417
+ if isinstance(cell, dict):
418
+ comp = cell.get('computed')
419
+ val = cell.get('value', '')
420
+ if isinstance(val, str) and val.strip().startswith('='):
421
+ if comp is not None and str(comp).strip() != '':
422
+ return comp
423
+ return val
424
+ if (val is None or str(val).strip() == '') and comp is not None:
425
+ return comp
426
+ return val
427
+ return cell
428
+
429
+ def _to_num(v):
430
+ if v is None:
431
+ return None
432
+ if isinstance(v, bool):
433
+ return None
434
+ if isinstance(v, (int, float)):
435
+ return float(v)
436
+ s = str(v).strip()
437
+ if not s:
438
+ return None
439
+ s = s.replace('$', '').replace(',', '').strip()
440
+ if s in ('', '-', '+'):
441
+ return None
442
+ try:
443
+ return float(s)
444
+ except Exception:
445
+ return None
446
+
447
+ def _s(v):
448
+ if v is None:
449
+ return ''
450
+ return str(v).strip()
451
+
452
+ def _raw_sheet(state, name):
453
+ if not isinstance(state, dict):
454
+ return None
455
+ candidates = []
456
+ ui = state.get('_ui_workbook')
457
+ if isinstance(ui, dict) and isinstance(ui.get('sheets'), list):
458
+ candidates = ui['sheets']
459
+ elif isinstance(state.get('sheets'), list):
460
+ candidates = state['sheets']
461
+ for sh in candidates:
462
+ if not isinstance(sh, dict):
463
+ continue
464
+ if norm(sh.get('name')) == norm(name) or norm(sh.get('id')) == norm(name):
465
+ return sh
466
+ if len(candidates) == 1 and isinstance(candidates[0], dict):
467
+ return candidates[0]
468
+ return None
469
+
470
+ def _grid(sheet):
471
+ grid = {}
472
+ data = sheet.get('data') if isinstance(sheet, dict) else None
473
+ if not isinstance(data, dict):
474
+ return grid
475
+ for cid, cell in data.items():
476
+ rc = _parse_cell_id(cid)
477
+ if not rc:
478
+ continue
479
+ r, c = rc # r 1-based, c 0-based
480
+ grid.setdefault(r, {})[c] = _cell_disp(cell)
481
+ return grid
482
+
483
+ # ---- 1) Pull answer key (primary) from sheets adapter ----
484
+ gs = go('google_sheets')
485
+ gs_init = gs.get('initial_state', {}) if isinstance(gs.get('initial_state'), dict) else {}
486
+ gs_cur = gs.get('current_state', {}) if isinstance(gs.get('current_state'), dict) else {}
487
+ adapter = gs_init.get('_task_adapter', {}) if isinstance(gs_init.get('_task_adapter'), dict) else {}
488
+
489
+ expected_rows = adapter.get('expected_rows') if isinstance(adapter.get('expected_rows'), list) else []
490
+ expected_summary = adapter.get('expected_summary') if isinstance(adapter.get('expected_summary'), list) else []
491
+ grand_total_truth = adapter.get('grand_total')
492
+ bucket_order = adapter.get('bucket_order') if isinstance(adapter.get('bucket_order'), list) else \
493
+ ['Current', '1-30', '31-60', '61-90', '90+']
494
+ target_sheet = adapter.get('target_sheet') or 'AR Aging'
495
+ bucket_label_set = {norm(b) for b in bucket_order}
496
+
497
+ # ---- secondary key: qualifying invoice numbers from QB `_age` ----
498
+ qb_payload = go('quickbooks')
499
+ qb_init = qb_payload.get('initial_state', {}) or {}
500
+ qb_cur = qb_payload.get('current_state', {}) or {}
501
+ qb_inv = qb_init.get('invoices', []) or []
502
+ qualifying_nums = {norm(inv.get('number')) for inv in qb_inv
503
+ if isinstance(inv, dict) and '_age' in inv}
504
+ # expected detail invoice numbers (string) — used for distractor detection
505
+ expected_nums = {norm(er.get('InvoiceNumber')) for er in expected_rows
506
+ if isinstance(er, dict)}
507
+ if not expected_nums:
508
+ expected_nums = qualifying_nums
509
+
510
+ n = len(expected_rows)
511
+ if n == 0:
512
+ print('DEBUG_T06_AR_AGING fatal=no_expected_rows total=0.0')
513
+ return 0.0
514
+
515
+ # ---- 2) Parse agent output grid for the AR Aging tab ----
516
+ sheet = _raw_sheet(gs_cur, target_sheet)
517
+ grid = _grid(sheet) if sheet is not None else {}
518
+
519
+ # Columns: A=0 Customer, B=1 InvoiceNumber, C=2 Total, D=3 DueDate,
520
+ # E=4 DaysOverdue, F=5 Bucket
521
+ detail_rows = [] # ordered list of agent detail rows (dicts)
522
+ summary_cells = {} # bucket-label-norm -> total float
523
+ grand_total_val = None
524
+ distractor_detail = 0
525
+
526
+ for r in sorted(grid.keys()):
527
+ if r <= 1:
528
+ continue # header row
529
+ row = grid[r]
530
+ a = _s(row.get(0))
531
+ b = _s(row.get(1))
532
+ a_norm = norm(a)
533
+ is_grand = ('grand' in a_norm and 'total' in a_norm)
534
+ is_bucket_label = a_norm in bucket_label_set
535
+
536
+ if is_grand:
537
+ gv = _to_num(row.get(2))
538
+ if gv is not None:
539
+ grand_total_val = gv
540
+ continue
541
+ if is_bucket_label and not b:
542
+ cv = _to_num(row.get(2))
543
+ if a_norm not in summary_cells and cv is not None:
544
+ summary_cells[a_norm] = cv
545
+ continue
546
+ if b:
547
+ # detail (invoice) row
548
+ inv_num = b
549
+ detail_rows.append({
550
+ 'Customer': a,
551
+ 'InvoiceNumber': inv_num,
552
+ 'Total': _to_num(row.get(2)),
553
+ 'DueDate': _s(row.get(3)),
554
+ 'DaysOverdue': _to_num(row.get(4)),
555
+ 'Bucket': _s(row.get(5)),
556
+ })
557
+ if norm(inv_num) not in expected_nums:
558
+ distractor_detail += 1
559
+ # else: blank / unrecognized row -> ignore
560
+
561
+ # ---- 3) Component 1 (0.45): ordered detail match on (Customer, InvoiceNumber, Total, Bucket) ----
562
+ hits_detail = 0
563
+ for i, exp in enumerate(expected_rows):
564
+ if i >= len(detail_rows):
565
+ continue
566
+ got = detail_rows[i]
567
+ exp_total = _to_num(exp.get('Total'))
568
+ got_total = got.get('Total')
569
+ total_ok = (got_total is not None and exp_total is not None
570
+ and abs(got_total - exp_total) <= TOL)
571
+ if (norm(got.get('Customer')) == norm(exp.get('Customer'))
572
+ and norm(got.get('InvoiceNumber')) == norm(exp.get('InvoiceNumber'))
573
+ and total_ok
574
+ and norm(got.get('Bucket')) == norm(exp.get('Bucket'))):
575
+ hits_detail += 1
576
+ s_detail = W_DETAIL * frac(hits_detail, n)
577
+
578
+ # ---- 4) Component 2 (0.20): DaysOverdue + Bucket correct per row (avg two sub-checks) ----
579
+ hits_days = 0
580
+ hits_bucket = 0
581
+ for i, exp in enumerate(expected_rows):
582
+ if i >= len(detail_rows):
583
+ continue
584
+ got = detail_rows[i]
585
+ exp_days = exp.get('DaysOverdue')
586
+ got_days = got.get('DaysOverdue')
587
+ try:
588
+ if got_days is not None and exp_days is not None and \
589
+ int(round(float(got_days))) == int(round(float(exp_days))):
590
+ hits_days += 1
591
+ except Exception:
592
+ pass
593
+ if norm(got.get('Bucket')) == norm(exp.get('Bucket')):
594
+ hits_bucket += 1
595
+ s_values = W_VALUES * 0.5 * (frac(hits_days, n) + frac(hits_bucket, n))
596
+
597
+ # ---- 5) Component 3 (0.25): per-bucket SUM rows == expected_summary ----
598
+ n_buckets = len(expected_summary)
599
+ hits_summary = 0
600
+ for item in expected_summary:
601
+ if not isinstance(item, dict):
602
+ continue
603
+ blabel = norm(item.get('bucket'))
604
+ btot = _to_num(item.get('total'))
605
+ got = summary_cells.get(blabel)
606
+ if got is not None and btot is not None and abs(got - btot) <= TOL:
607
+ hits_summary += 1
608
+ s_summary = W_SUMMARY * frac(hits_summary, n_buckets) if n_buckets else 0.0
609
+
610
+ # ---- 6) Component 4 (0.10): Grand Total ----
611
+ gt_truth = _to_num(grand_total_truth)
612
+ grand_ok = (grand_total_val is not None and gt_truth is not None
613
+ and abs(grand_total_val - gt_truth) <= TOL)
614
+ s_grand = W_GRAND * (1.0 if grand_ok else 0.0)
615
+
616
+ # ---- 6b) Component 5 (0.15): reconcile invoices marked Paid via 'Receive payment' ----
617
+ # The two invoices named in the Gmail notice must be status 'Paid' in QB
618
+ # current_state. They ship UNPAID (Sent), so a do-nothing agent scores 0 here.
619
+ recon_numbers = set()
620
+ adapter_recon = adapter.get('reconcile_invoice_numbers') if isinstance(adapter, dict) else None
621
+ if isinstance(adapter_recon, list):
622
+ recon_numbers = {str(x) for x in adapter_recon}
623
+ if not recon_numbers:
624
+ # fallback: invoices carrying the hidden _receive_payment flag in QB initial_state
625
+ for inv in (qb_init.get('invoices', []) or []):
626
+ if isinstance(inv, dict) and inv.get('_receive_payment'):
627
+ recon_numbers.add(str(inv.get('number')))
628
+ qb_cur_invoices = qb_cur.get('invoices', []) or []
629
+ cur_status_by_num = {}
630
+ for inv in qb_cur_invoices:
631
+ if isinstance(inv, dict):
632
+ cur_status_by_num[str(inv.get('number'))] = norm(inv.get('status'))
633
+ recv_ok = sum(1 for num in recon_numbers if cur_status_by_num.get(num) == 'paid')
634
+ s_receive = W_RECEIVE * frac(recv_ok, len(recon_numbers)) if recon_numbers else 0.0
635
+
636
+ # ---- 7) Over-inclusion guard: penalize Paid/Draft distractor rows ----
637
+ penalty = min(PENALTY_CAP, PENALTY_PER_DISTRACTOR * distractor_detail)
638
+
639
+ raw = s_detail + s_values + s_summary + s_grand + s_receive - penalty
640
+ score = clamp01(raw)
641
+
642
+ print(
643
+ 'DEBUG_T06_AR_AGING '
644
+ f'n_exp={n} n_detail={len(detail_rows)} qual_nums={len(qualifying_nums)} '
645
+ f'detail_hits={hits_detail}/{n} days_hits={hits_days}/{n} bucket_hits={hits_bucket}/{n} '
646
+ f'summary_hits={hits_summary}/{n_buckets} grand_ok={int(grand_ok)} '
647
+ f'recv_ok={recv_ok}/{len(recon_numbers)} '
648
+ f'distractors={distractor_detail} penalty={round(penalty, 4)} '
649
+ f'w_detail={round(s_detail, 4)} w_values={round(s_values, 4)} '
650
+ f'w_summary={round(s_summary, 4)} w_grand={round(s_grand, 4)} w_receive={round(s_receive, 4)} '
651
+ f'raw={round(raw, 4)} total={round(score, 4)}'
652
+ )
653
+
654
+ return score
655
+
656
+
657
+ try:
658
+ score = float(reward(go))
659
+ except Exception as exc:
660
+ print(f'ERROR: reward() raised {exc!r}')
661
+ score = 0.0
662
+
663
+ score = clamp01(score)
664
+ print(f'\nREWARD: {round(score, 4)}')
calc_boomerang_sales_004__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_boomerang_sales_004__long/338372e2-5164-5bba-be72-3024f425418f_BoomerangSales_4.xlsx ADDED
Binary file (12.4 kB). View file
 
calc_boomerang_sales_004__long/3c734b28-876f-590a-8a9b-a7dea013cdd9_BoomerangSales_5.xlsx ADDED
Binary file (12.4 kB). View file
 
calc_boomerang_sales_004__long/6_BoomerangSales_gt1_1.xlsx ADDED
Binary file (18.5 kB). View file
 
calc_boomerang_sales_004__long/6_BoomerangSales_gt1_2.xlsx ADDED
Binary file (18.5 kB). View file
 
calc_boomerang_sales_004__long/6_BoomerangSales_gt1_3.xlsx ADDED
Binary file (18.5 kB). View file
 
calc_boomerang_sales_004__long/6_BoomerangSales_gt1_4.xlsx ADDED
Binary file (18.5 kB). View file
 
calc_boomerang_sales_004__long/6_BoomerangSales_gt1_5.xlsx ADDED
Binary file (18.5 kB). View file
 
calc_boomerang_sales_004__long/7594f1e5-2945-5a98-9eec-5aac2e8aaf1b_BoomerangSales_3.xlsx ADDED
Binary file (12.4 kB). View file
 
calc_boomerang_sales_004__long/b9ee9e4b-d3c9-5341-a797-ba31c5448117_BoomerangSales_1.xlsx ADDED
Binary file (12.4 kB). View file
 
calc_boomerang_sales_004__long/e22b8fec-7bed-5cb0-a402-a977fa125750_BoomerangSales_2.xlsx ADDED
Binary file (12.4 kB). View file
 
calc_student_grades_005__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_student_grades_005__long/0a94aee5-1a46-57a5-b453-2402af0ffede_Student_Grades_and_Remarks_4.xlsx ADDED
Binary file (6.12 kB). View file
 
calc_student_grades_005__long/26aa94e9-ffcf-57a5-b2dd-e92752c4b57f_Student_Grades_and_Remarks_2.xlsx ADDED
Binary file (6.12 kB). View file
 
calc_student_grades_005__long/639ca2f8-0ba9-5a67-b827-a64f4cd425b5_Student_Grades_and_Remarks_3.xlsx ADDED
Binary file (6.12 kB). View file
 
calc_student_grades_005__long/914ebed1-4ae1-5a3e-b9ab-bbbfe8206f7b_Student_Grades_and_Remarks_1.xlsx ADDED
Binary file (6.12 kB). View file
 
calc_student_grades_005__long/Student_Grades_and_Remarks_gold_1.xlsx ADDED
Binary file (8.82 kB). View file
 
calc_student_grades_005__long/Student_Grades_and_Remarks_gold_2.xlsx ADDED
Binary file (8.82 kB). View file
 
calc_student_grades_005__long/Student_Grades_and_Remarks_gold_3.xlsx ADDED
Binary file (8.82 kB). View file
 
calc_student_grades_005__long/Student_Grades_and_Remarks_gold_4.xlsx ADDED
Binary file (8.82 kB). View file
 
calc_student_grades_005__long/Student_Grades_and_Remarks_gold_5.xlsx ADDED
Binary file (8.82 kB). View file
 
calc_student_grades_005__long/f4dfeace-a9ac-57e3-9cb7-b78690026317_Student_Grades_and_Remarks_5.xlsx ADDED
Binary file (6.12 kB). View file
 
csm_training_rate_005/initial_setup.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: ce_adoption_rate_b107
3
+ Task ID: csm_training_rate_005
4
+ Domain: mock_websites
5
+ Mocks: google_sheets_mock, salesforce_mock, slack_mock (single shared sid)
6
+
7
+ Persona: You are an office worker acting as a finance analyst. Your tools for this task are: shared spreadsheets, the Salesforce CRM, 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): a Google Sheet with seeded tabular data; Salesforce CRM with 1 opp(s), 0 case(s); Slack workspace with channels #general, #random. GROUND TRUTH — the agent earns partial credit for each checkpoint: completion rate computed as 75% (+0.4); TechVentures opp -> Closed Won (+0.3); slack_new_msg (+0.1); reports the 75% rate (+0.2). 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_sheets_mock": "http://28.7.184.198:8145",
23
+ "salesforce_mock": "http://28.7.184.198:8175",
24
+ "slack_mock": "http://28.7.184.198:8178"
25
+ }
26
+ PRIMARY_URL = 'http://28.7.184.198:8145'
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 = { 'google_sheets_mock': { 'id': 'workbook_1',
35
+ 'title': 'Q2 Adoption Tracker',
36
+ 'activeSheetId': 'sheet_1',
37
+ 'selectedCell': 'A1',
38
+ 'selectionRange': None,
39
+ 'clipboard': None,
40
+ 'isDragging': False,
41
+ 'undoStack': [],
42
+ 'redoStack': [],
43
+ 'namedRanges': [],
44
+ 'conditionalFormats': [],
45
+ 'charts': [],
46
+ 'showGridlines': True,
47
+ 'showFormulas': False,
48
+ 'zoom': 100,
49
+ 'sheets': [ { 'id': 'sheet_1',
50
+ 'name': 'Training Attendance',
51
+ 'rowCount': 100,
52
+ 'colCount': 26,
53
+ 'frozenRows': 1,
54
+ 'frozenCols': 0,
55
+ 'tabColor': None,
56
+ 'isHidden': False,
57
+ 'columnWidths': {},
58
+ 'data': { 'A1': { 'value': 'Account',
59
+ 'formula': 'Account',
60
+ 'style': {'bold': True}},
61
+ 'B1': { 'value': 'Owner',
62
+ 'formula': 'Owner',
63
+ 'style': {'bold': True}},
64
+ 'C1': { 'value': 'Sessions',
65
+ 'formula': 'Sessions',
66
+ 'style': {'bold': True}},
67
+ 'D1': { 'value': 'Completed',
68
+ 'formula': 'Completed',
69
+ 'style': {'bold': True}},
70
+ 'A2': { 'value': 'TechVentures',
71
+ 'formula': 'TechVentures'},
72
+ 'B2': { 'value': 'John',
73
+ 'formula': 'John'},
74
+ 'C2': {'value': '3', 'formula': '3'},
75
+ 'D2': { 'value': 'Yes',
76
+ 'formula': 'Yes'},
77
+ 'A3': { 'value': 'LeadCo',
78
+ 'formula': 'LeadCo'},
79
+ 'B3': { 'value': 'Amy',
80
+ 'formula': 'Amy'},
81
+ 'C3': {'value': '2', 'formula': '2'},
82
+ 'D3': { 'value': 'Yes',
83
+ 'formula': 'Yes'},
84
+ 'A4': { 'value': 'Globex',
85
+ 'formula': 'Globex'},
86
+ 'B4': { 'value': 'John',
87
+ 'formula': 'John'},
88
+ 'C4': {'value': '3', 'formula': '3'},
89
+ 'D4': { 'value': 'Yes',
90
+ 'formula': 'Yes'},
91
+ 'A5': { 'value': 'Initech',
92
+ 'formula': 'Initech'},
93
+ 'B5': { 'value': 'Amy',
94
+ 'formula': 'Amy'},
95
+ 'C5': {'value': '1', 'formula': '1'},
96
+ 'D5': {'value': 'No', 'formula': 'No'},
97
+ 'A8': { 'value': 'Completion Rate',
98
+ 'formula': 'Completion Rate',
99
+ 'style': {'bold': True}}}}]},
100
+ 'salesforce_mock': { 'user': { 'userId': 'user-1',
101
+ 'firstName': 'John',
102
+ 'lastName': 'Smith',
103
+ 'email': 'john.smith@company.com',
104
+ 'phone': '(555) 123-4567',
105
+ 'title': 'Sales Manager',
106
+ 'department': 'Sales',
107
+ 'role': 'Manager',
108
+ 'avatar': 'https://i.pravatar.cc/150?u=user-1',
109
+ 'timezone': 'America/New_York',
110
+ 'locale': 'en-US',
111
+ 'theme': 'lightning'},
112
+ 'users': [ { 'userId': 'user-1',
113
+ 'firstName': 'John',
114
+ 'lastName': 'Smith',
115
+ 'email': 'john.smith@company.com'},
116
+ { 'userId': 'user-2',
117
+ 'firstName': 'Amy',
118
+ 'lastName': 'Wong',
119
+ 'email': 'amy@company.com'}],
120
+ 'leads': [],
121
+ 'accounts': [ { 'accountId': 'account-1',
122
+ 'name': 'TechVentures Inc.',
123
+ 'type': 'Customer',
124
+ 'industry': 'Technology',
125
+ 'revenue': 15000000,
126
+ 'employees': 250,
127
+ 'ownerId': 'user-1'}],
128
+ 'contacts': [ { 'contactId': 'contact-1',
129
+ 'accountId': 'account-1',
130
+ 'firstName': 'Sarah',
131
+ 'lastName': 'Johnson',
132
+ 'title': 'VP Eng',
133
+ 'department': 'Engineering',
134
+ 'email': 'sarah.j@techventures.com',
135
+ 'phone': '(555) 111-2222',
136
+ 'ownerId': 'user-1'}],
137
+ 'opportunities': [ { 'opportunityId': 'o1',
138
+ 'name': 'TechVentures Expansion',
139
+ 'accountId': 'account-1',
140
+ 'contactId': 'contact-1',
141
+ 'amount': 50000,
142
+ 'closeDate': '2026-06-30',
143
+ 'stage': 'Proposal',
144
+ 'probability': 60,
145
+ 'ownerId': 'user-1'}],
146
+ 'cases': [],
147
+ 'activities': [],
148
+ 'chatterPosts': [],
149
+ 'files': [],
150
+ 'following': [],
151
+ 'recentlyViewed': [],
152
+ 'dismissedNotifications': []},
153
+ 'slack_mock': { 'currentUser': { 'userId': 'user_1',
154
+ 'fullName': 'John Smith',
155
+ 'displayName': 'John',
156
+ 'email': 'john.smith@company.com',
157
+ 'avatar': 'https://picsum.photos/200/200?random=1',
158
+ 'title': '',
159
+ 'status': 'online',
160
+ 'statusMessage': '',
161
+ 'statusEmoji': '',
162
+ 'timeZone': 'America/New_York'},
163
+ 'workspace': { 'workspaceId': 'ws_1',
164
+ 'workspaceName': 'Acme Corp',
165
+ 'icon': ''},
166
+ 'users': [ { 'userId': 'user_1',
167
+ 'fullName': 'John Smith',
168
+ 'displayName': 'John',
169
+ 'email': 'john.smith@company.com',
170
+ 'avatar': 'https://picsum.photos/200/200?random=1',
171
+ 'title': '',
172
+ 'status': 'online',
173
+ 'statusMessage': '',
174
+ 'statusEmoji': '',
175
+ 'timeZone': 'America/New_York'},
176
+ { 'userId': 'user_2',
177
+ 'fullName': 'Sarah Johnson',
178
+ 'displayName': 'Sarah',
179
+ 'email': 'sarah.johnson@company.com',
180
+ 'avatar': 'https://picsum.photos/200/200?random=2',
181
+ 'title': '',
182
+ 'status': 'online',
183
+ 'statusMessage': '',
184
+ 'statusEmoji': '',
185
+ 'timeZone': 'America/New_York'},
186
+ { 'userId': 'user_3',
187
+ 'fullName': 'Mike Chen',
188
+ 'displayName': 'Mike',
189
+ 'email': 'mike.chen@company.com',
190
+ 'avatar': 'https://picsum.photos/200/200?random=3',
191
+ 'title': '',
192
+ 'status': 'online',
193
+ 'statusMessage': '',
194
+ 'statusEmoji': '',
195
+ 'timeZone': 'America/New_York'},
196
+ { 'userId': 'user_4',
197
+ 'fullName': 'Lisa Park',
198
+ 'displayName': 'Lisa',
199
+ 'email': 'lisa.park@company.com',
200
+ 'avatar': 'https://picsum.photos/200/200?random=4',
201
+ 'title': '',
202
+ 'status': 'online',
203
+ 'statusMessage': '',
204
+ 'statusEmoji': '',
205
+ 'timeZone': 'America/New_York'}],
206
+ 'channels': [ { 'channelId': 'general',
207
+ 'name': 'general',
208
+ 'description': 'general channel',
209
+ 'topic': '',
210
+ 'isPrivate': False,
211
+ 'isStarred': False,
212
+ 'members': ['user_1', 'user_2', 'user_3', 'user_4'],
213
+ 'createdBy': 'user_1',
214
+ 'createdAt': '2026-01-01T10:00:00Z',
215
+ 'pinnedMessages': [],
216
+ 'unreadCount': 0},
217
+ { 'channelId': 'random',
218
+ 'name': 'random',
219
+ 'description': 'random channel',
220
+ 'topic': '',
221
+ 'isPrivate': False,
222
+ 'isStarred': False,
223
+ 'members': ['user_1', 'user_2', 'user_3', 'user_4'],
224
+ 'createdBy': 'user_1',
225
+ 'createdAt': '2026-01-01T10:00:00Z',
226
+ 'pinnedMessages': [],
227
+ 'unreadCount': 0}],
228
+ 'messages': { 'general': [ { 'messageId': 'g1',
229
+ 'senderId': 'user_2',
230
+ 'content': "what's the Q2 enablement "
231
+ 'completion rate?',
232
+ 'timestamp': '2026-06-08T08:00:00Z',
233
+ 'threadId': None,
234
+ 'reactions': [],
235
+ 'attachments': [],
236
+ 'isEdited': False}],
237
+ 'random': []},
238
+ 'threads': {},
239
+ 'dms': [],
240
+ 'bookmarkedMessages': [],
241
+ 'callHistory': [],
242
+ 'settings': { 'theme': 'light',
243
+ 'notifications': 'all',
244
+ 'displayDensity': 'comfortable',
245
+ 'showAvatars': True,
246
+ 'use24Hour': False},
247
+ 'invitations': [],
248
+ 'notifications': []}}
249
+
250
+
251
+ def launch_gui(command, delay_sec=1.0):
252
+ env = os.environ.copy()
253
+ env['DISPLAY'] = ':0'
254
+ subprocess.Popen(shlex.split(command), stdin=subprocess.DEVNULL,
255
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
256
+ env=env, start_new_session=True)
257
+ time.sleep(delay_sec)
258
+
259
+
260
+ for name, url in MOCK_URLS.items():
261
+ resp = requests.post(f'{url}/post?sid={sid}',
262
+ json={'action': 'set', 'state': STATES[name]}, timeout=30)
263
+ assert resp.status_code == 200, f'{name} injection failed: {resp.text}'
264
+ go = requests.get(f'{url}/go?sid={sid}', timeout=10).json()
265
+ assert go.get('initial_state') is not None, f'{name} initial_state is None'
266
+ print(f'State injected: {name} sid={sid}')
267
+
268
+ # Open the PRIMARY app as the main window first, then open every other
269
+ # involved mock as an additional browser tab so the agent can see/reach all
270
+ # relevant apps (e.g. read the email in the Gmail tab AND post in Slack).
271
+ # Without this, secondary-app data is injected but has no on-screen entry
272
+ # point, and the agent wastes its budget hunting for a non-existent client.
273
+ launch_gui(f'google-chrome "{PRIMARY_URL}/?sid={sid}"', delay_sec=2.0)
274
+ print(f'GUI_READY: launched browser at {PRIMARY_URL}/?sid={sid}')
275
+ for _name, _url in MOCK_URLS.items():
276
+ if _url == PRIMARY_URL:
277
+ continue
278
+ launch_gui(f'google-chrome --new-tab "{_url}/?sid={sid}"', delay_sec=1.0)
279
+ print(f'Opened tab: {_name} at {_url}/?sid={sid}')
csm_training_rate_005/reward.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: ce_adoption_rate_b107
3
+ Task ID: csm_training_rate_005
4
+ Domain: mock_websites
5
+ Mocks: google_sheets_mock, salesforce_mock, slack_mock
6
+ Scoring (all programmatic; evaluated against each mock's current_state; total = 1.0):
7
+ - [0.4] completion rate computed as 75%
8
+ - [0.3] TechVentures opp -> Closed Won
9
+ - [0.1] slack_new_msg
10
+ - [0.2] reports the 75% rate
11
+ """
12
+ import re
13
+ import sys
14
+
15
+ import requests
16
+
17
+ MOCK_URLS = {
18
+ "google_sheets_mock": "http://28.7.184.198:8145",
19
+ "salesforce_mock": "http://28.7.184.198:8175",
20
+ "slack_mock": "http://28.7.184.198:8178"
21
+ }
22
+ SEED = {
23
+ "slack_mock:general": [
24
+ "g1"
25
+ ],
26
+ "slack_mock:random": []
27
+ }
28
+
29
+ try:
30
+ with open('/tmp/task_web_sid') as f:
31
+ sid = f.read().strip()
32
+ if not sid:
33
+ raise ValueError('sid is empty')
34
+ except Exception as e:
35
+ print(f'CRITICAL: cannot read sid: {e}')
36
+ print('REWARD: 0.0')
37
+ sys.exit(0)
38
+
39
+ STATES = {}
40
+ for _name, _url in MOCK_URLS.items():
41
+ try:
42
+ _r = requests.get(f'{_url}/go?sid={sid}', timeout=15)
43
+ _r.raise_for_status()
44
+ STATES[_name] = _r.json()
45
+ except Exception as e:
46
+ print(f'CRITICAL: cannot fetch {_name}: {e}')
47
+ print('REWARD: 0.0')
48
+ sys.exit(0)
49
+
50
+
51
+ def cur(mock):
52
+ return (STATES.get(mock) or {}).get('current_state') or {}
53
+
54
+
55
+ def _lc(s):
56
+ return (s or '').lower()
57
+
58
+
59
+ total = 0.0
60
+
61
+ # c0: sheet cell B8 value contains '75'
62
+ c0_sheets = cur('google_sheets_mock').get('sheets') or []
63
+ c0_data = (c0_sheets[0].get('data') if c0_sheets else {}) or {}
64
+ c0_cd = c0_data.get('B8') or {}
65
+ if '75' in str(c0_cd.get('value','')) or '75' in str(c0_cd.get('computed','')):
66
+ print('PASS: completion rate computed as 75% (0.4)')
67
+ total += 0.4
68
+ else:
69
+ print('FAIL: completion rate computed as 75%')
70
+
71
+ # c1: salesforce opp o1 stage == 'Closed Won'
72
+ c1_o = next((o for o in (cur('salesforce_mock').get('opportunities') or []) if o.get('opportunityId') == 'o1'), None)
73
+ if c1_o and c1_o.get('stage') == 'Closed Won':
74
+ print('PASS: TechVentures opp -> Closed Won (0.3)')
75
+ total += 0.3
76
+ else:
77
+ print('FAIL: TechVentures opp -> Closed Won')
78
+
79
+ # c2: new message by user_1 in #general
80
+ c2_msgs = (cur('slack_mock').get('messages') or {}).get('general', []) or []
81
+ c2_seed = set(SEED.get('slack_mock:general', []))
82
+ c2_new = [m for m in c2_msgs if m.get('messageId') not in c2_seed and m.get('senderId') == 'user_1']
83
+ c2_blob = _lc(' '.join((m.get('content') or '') for m in c2_new))
84
+ if c2_new:
85
+ print('PASS: new message by user_1 in #general (0.1)')
86
+ total += 0.1
87
+ else:
88
+ print('FAIL: no new user_1 message in #general')
89
+
90
+ # c3: slack #general contains (reports the 75% rate)
91
+ c3_msgs = (cur('slack_mock').get('messages') or {}).get('general', []) or []
92
+ c3_seed = set(SEED.get('slack_mock:general', []))
93
+ c3_blob = _lc(' '.join((m.get('content') or '') for m in c3_msgs if m.get('messageId') not in c3_seed and m.get('senderId') == 'user_1'))
94
+ if any(t in c3_blob for t in ['75%', '75 percent', '75']):
95
+ print('PASS: reports the 75% rate (0.2)')
96
+ total += 0.2
97
+ else:
98
+ print('FAIL: reports the 75% rate')
99
+
100
+ final = round(min(total, 1.0), 4)
101
+ print(f'\nScore: {total}/1.0')
102
+ print(f'REWARD: {final}')
csops_inbox_triage_006__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"
csops_inbox_triage_006__long/initial_setup.py ADDED
@@ -0,0 +1,771 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: T02_trello_triage_sla — Triage support inbox into the 'Support' Trello board
3
+ Task ID: csops_inbox_triage_006__long
4
+ Mocks: gmail_mock,trello_mock,google_calendar_mock,slack_mock
5
+
6
+ Ground-truth embedding style: INLINE hidden field `triage` on every gmail email
7
+ triage = {"kind": "actionable|noise|resolved",
8
+ "component": "Bug|Billing|Feature Request|Account" | None,
9
+ "priority": "P1|P2|P3" | None,
10
+ "due": "<ISO date>T17:00:00" | None,
11
+ # P1 (urgent) tickets only — Google Calendar follow-up answer key:
12
+ "event_title": "Follow-up: <subject>",
13
+ "event_date": "<today+1>",
14
+ "guest_email": "<requester email>"}
15
+ Only kind == "actionable" yields a Trello card. reward.py reads `triage`
16
+ from gmail initial_state. Priority + due are PRECOMPUTED in Python from each
17
+ email body (severity keywords) and the SLA rule, so the embedded answer key is
18
+ internally consistent with the visible email text.
19
+
20
+ HIDDEN ACCESS POINTS the agent must DISCOVER (the whole point of this task):
21
+ - Gmail: the priority LABEL button is SELECTION-GATED — it only appears in the
22
+ toolbar after you tick an email's checkbox. The picker then lists the
23
+ P1/P2/P3 labels seeded below. (Analog of Salesforce "select row -> Change
24
+ Owner button appears".) reward grades the priority label on each genuine
25
+ email, matched by label NAME.
26
+ - Trello: a card's priority label + due date live ONLY inside the card-detail
27
+ modal you open by clicking the card.
28
+ - Calendar: guests are typed into the buried "Add guests" field in the event
29
+ editor; the requester email is NOT in the autocomplete list, so it must be
30
+ carried over from the Gmail message.
31
+ - Slack: the summary message posted to #support must be PINNED — pin lives
32
+ behind the per-message hover "..." (More actions) menu.
33
+
34
+ Observable result kept ABSENT at injection (Rule 3):
35
+ - The four target Trello lists (Bug / Billing / Feature Request / Account)
36
+ start with ZERO cards. Only the decoy 'Done' list carries watermark cards.
37
+ - All 12 emails start in folder 'inbox' (nothing archived yet) and carry NO
38
+ labels (labels: []).
39
+ - The calendar holds NO 'Follow-up:' events at injection (only decoys).
40
+ - The Slack #support channel starts EMPTY (no messages, no pinned messages).
41
+ Only decoy channels carry watermark chatter.
42
+ """
43
+ import datetime
44
+ import os
45
+ import shlex
46
+ import subprocess
47
+ import time
48
+ import uuid
49
+
50
+ import requests
51
+
52
+ sid = str(uuid.uuid4())
53
+ with open('/tmp/task_web_sid', 'w', encoding='utf-8') as f:
54
+ f.write(sid)
55
+ print(f'Generated sid: {sid}')
56
+
57
+ # ---------------------------------------------------------------------------
58
+ # Ground-truth derivation (PRECOMPUTED so embedded keys match the visible data)
59
+ # "Assume today is Tuesday, June 16, 2026."
60
+ # ---------------------------------------------------------------------------
61
+ TODAY = datetime.date(2026, 6, 16)
62
+ assert TODAY.strftime('%A') == 'Tuesday', 'today must be Tuesday June 16, 2026'
63
+
64
+ # SLA: P1 = today +1d, P2 = today +3d, P3 = today +7d, all due at 17:00 local.
65
+ SLA_DAYS = {'P1': 1, 'P2': 3, 'P3': 7}
66
+
67
+
68
+ def sla_due(priority):
69
+ d = TODAY + datetime.timedelta(days=SLA_DAYS[priority])
70
+ return f'{d.isoformat()}T17:00:00'
71
+
72
+
73
+ def classify_priority(body):
74
+ """Severity keyword rule, applied in precedence order (P1 > P2 > P3)."""
75
+ b = body.lower()
76
+ if 'urgent' in b or 'production down' in b:
77
+ return 'P1'
78
+ if 'broken' in b or 'error' in b or 'cannot' in b:
79
+ return 'P2'
80
+ return 'P3'
81
+
82
+
83
+ # Email specs. For actionable emails, priority/due are DERIVED from `body`;
84
+ # `expect_priority` is a sanity assertion that the authored body really yields
85
+ # the intended priority. Non-actionable emails get null component/priority/due.
86
+ EMAIL_SPECS = [
87
+ # ---- 7 ACTIONABLE support emails (one card each) ----
88
+ dict(eid='m1', thread='thread_m1', component='Bug', kind='actionable',
89
+ expect_priority='P1',
90
+ sender_name='Priya Nair', sender_email='priya.nair@northwind.example',
91
+ subject='Checkout page returns 500 for all users',
92
+ body='This is urgent -- production down since 8am, every customer hits a 500 at checkout. Please escalate.',
93
+ ts='2026-06-16T08:12:00Z'),
94
+ dict(eid='m2', thread='thread_m2', component='Bug', kind='actionable',
95
+ expect_priority='P2',
96
+ sender_name='Tomas Vidal', sender_email='tomas.vidal@harborlabs.example',
97
+ subject='Image upload broken on profile page',
98
+ body='The avatar upload is broken and throws an error whenever I pick a PNG. Was working last week.',
99
+ ts='2026-06-16T07:40:00Z'),
100
+ dict(eid='m3', thread='thread_m3', component='Billing', kind='actionable',
101
+ expect_priority='P2',
102
+ sender_name='Dana Whitfield', sender_email='dana@whitfield-cpa.example',
103
+ subject='Invoice shows wrong tax amount',
104
+ body='I cannot download my March invoice and the tax line looks wrong -- it doubled the VAT.',
105
+ ts='2026-06-15T16:05:00Z'),
106
+ dict(eid='m4', thread='thread_m4', component='Billing', kind='actionable',
107
+ expect_priority='P3',
108
+ sender_name='Leo Park', sender_email='leo.park@brightway.example',
109
+ subject='Request a copy of last year receipts',
110
+ body='Could you send the 2025 receipts for our accounting records when you get a chance? No rush at all.',
111
+ ts='2026-06-15T11:22:00Z'),
112
+ dict(eid='m5', thread='thread_m5', component='Feature Request', kind='actionable',
113
+ expect_priority='P3',
114
+ sender_name='Marisol Ferreira', sender_email='marisol@ferreira-design.example',
115
+ subject='Add dark mode to the dashboard',
116
+ body='It would be great to have a dark theme option in settings. Easier on the eyes for late shifts.',
117
+ ts='2026-06-15T09:48:00Z'),
118
+ dict(eid='m6', thread='thread_m6', component='Feature Request', kind='actionable',
119
+ expect_priority='P1',
120
+ sender_name='Greg Olsson', sender_email='greg.olsson@meridian.example',
121
+ subject='Need CSV export before the board meeting',
122
+ body='This is urgent: we need CSV export of the analytics dashboard by Friday for the board deck.',
123
+ ts='2026-06-16T06:30:00Z'),
124
+ dict(eid='m7', thread='thread_m7', component='Account', kind='actionable',
125
+ expect_priority='P2',
126
+ sender_name='Hana Sato', sender_email='hana.sato@kabuki.example',
127
+ subject='Cannot log in after password reset',
128
+ body='After resetting my password I cannot log in -- it shows an error saying the token expired.',
129
+ ts='2026-06-16T05:58:00Z'),
130
+
131
+ # ---- 5 NON-ACTIONABLE emails (must be archived, no card) ----
132
+ dict(eid='m8', thread='thread_m8', component=None, kind='noise',
133
+ expect_priority=None,
134
+ sender_name='Acme Product', sender_email='newsletter@acme-product.example',
135
+ subject='Acme Weekly: product updates and tips',
136
+ body='Here is what shipped this week, plus three tips to get more out of your dashboard. Unsubscribe anytime.',
137
+ ts='2026-06-16T04:00:00Z'),
138
+ dict(eid='m9', thread='thread_m9', component=None, kind='noise',
139
+ expect_priority=None,
140
+ sender_name='Owen Brandt', sender_email='owen.brandt@partnerco.example',
141
+ subject='Automatic reply: Out of office',
142
+ body='I am currently out of office and will return Monday June 22. For urgent matters contact my colleague.',
143
+ ts='2026-06-16T03:30:00Z'),
144
+ dict(eid='m10', thread='thread_m10', component=None, kind='noise',
145
+ expect_priority=None,
146
+ sender_name='Carla Mendez', sender_email='carla.mendez@summit.example',
147
+ subject='Thanks for the quick fix!',
148
+ body='Just wanted to say thank you -- the export works perfectly now. Really appreciate the fast turnaround.',
149
+ ts='2026-06-15T18:10:00Z'),
150
+ # Resolved THREAD: original support request + a later reply marking it done.
151
+ # Both emails are non-actionable (kind=resolved) and must be archived.
152
+ dict(eid='m11', thread='thread_resolved', component=None, kind='resolved',
153
+ expect_priority=None,
154
+ sender_name='Felix Adler', sender_email='felix.adler@coastal.example',
155
+ subject='Login button does nothing on Safari',
156
+ body='The login button appears broken on Safari and throws a console error. Can someone take a look?',
157
+ ts='2026-06-15T13:20:00Z'),
158
+ dict(eid='m12', thread='thread_resolved', component=None, kind='resolved',
159
+ expect_priority=None,
160
+ sender_name='Felix Adler', sender_email='felix.adler@coastal.example',
161
+ subject='Re: Login button does nothing on Safari',
162
+ body='Update: this is now resolved after I cleared the cache. Everything works, please close it out. Thanks!',
163
+ ts='2026-06-15T15:05:00Z'),
164
+ ]
165
+
166
+ GMAIL_USER = {
167
+ 'userId': 'u1',
168
+ 'username': 'Support Team',
169
+ 'email': 'support@acme.io',
170
+ 'avatar': 'https://picsum.photos/200/200?random=1',
171
+ }
172
+
173
+
174
+ def build_email(spec):
175
+ body = spec['body']
176
+ if spec['kind'] == 'actionable':
177
+ priority = classify_priority(body)
178
+ assert priority == spec['expect_priority'], (
179
+ f"{spec['eid']}: body classifies as {priority} but expected {spec['expect_priority']}"
180
+ )
181
+ due = sla_due(priority)
182
+ component = spec['component']
183
+ else:
184
+ priority = None
185
+ due = None
186
+ component = None
187
+ assert spec['component'] is None
188
+
189
+ triage = {
190
+ 'kind': spec['kind'],
191
+ 'component': component,
192
+ 'priority': priority,
193
+ 'due': due,
194
+ }
195
+ # P1 (urgent) tickets ALSO require a Google Calendar follow-up event whose
196
+ # GUEST is the requester's email (typed into the buried guest field). The
197
+ # event date is the P1 SLA due date (today + 1). Non-P1 emails carry no event
198
+ # answer key, so they neither require nor are penalised for a calendar event.
199
+ if spec['kind'] == 'actionable' and priority == 'P1':
200
+ triage['event_title'] = f"Follow-up: {spec['subject']}"
201
+ triage['event_date'] = due[:10] # 'YYYY-MM-DD' (P1 = today+1)
202
+ triage['guest_email'] = spec['sender_email'] # cross-app: extracted from Gmail
203
+
204
+ return {
205
+ 'id': spec['eid'],
206
+ 'threadId': spec['thread'],
207
+ 'from': {'name': spec['sender_name'], 'email': spec['sender_email'], 'avatar': ''},
208
+ 'to': [{'name': GMAIL_USER['username'], 'email': GMAIL_USER['email']}],
209
+ 'cc': [],
210
+ 'bcc': [],
211
+ 'folder': 'inbox',
212
+ 'subject': spec['subject'],
213
+ 'body': body,
214
+ 'snippet': body[:120],
215
+ 'timestamp': spec['ts'],
216
+ 'read': False,
217
+ 'starred': False,
218
+ 'important': False,
219
+ 'labels': [],
220
+ 'category': 'primary',
221
+ 'attachments': [],
222
+ # ---- inline hidden answer key (reward reads this) ----
223
+ 'triage': triage,
224
+ }
225
+
226
+
227
+ EMAILS = [build_email(s) for s in EMAIL_SPECS]
228
+
229
+ # Internal-consistency report (printed at setup time, not graded).
230
+ _actionable = [e for e in EMAILS if e['triage']['kind'] == 'actionable']
231
+ _nonactionable = [e for e in EMAILS if e['triage']['kind'] != 'actionable']
232
+ assert len(_actionable) == 7, f'expected 7 actionable, got {len(_actionable)}'
233
+ assert len(_nonactionable) == 5, f'expected 5 non-actionable, got {len(_nonactionable)}'
234
+ print('Ground truth (actionable -> component / priority / due):')
235
+ for e in _actionable:
236
+ t = e['triage']
237
+ print(f" {e['id']}: {t['component']:<16} {t['priority']} due {t['due']} | {e['subject']}")
238
+
239
+ # P1 tickets carry a calendar-event answer key; verify it is internally consistent.
240
+ _p1 = [e for e in _actionable if e['triage'].get('priority') == 'P1']
241
+ assert all('event_title' in e['triage'] and e['triage'].get('guest_email')
242
+ for e in _p1), 'every P1 email must carry the event answer key'
243
+ print(f'P1 calendar follow-ups required: {len(_p1)} '
244
+ f'-> {[e["triage"]["guest_email"] for e in _p1]}')
245
+
246
+ # Gmail priority LABELS (P1/P2/P3) are seeded so the SELECTION-GATED Label button
247
+ # has something to apply. reward matches the label by NAME -> id, so the exact id
248
+ # strings here are not load-bearing (only the names P1/P2/P3 are). Work/Personal
249
+ # are decoys. Emails start with labels:[] (Rule 3) so the gradable label is absent.
250
+ GMAIL_LABELS = [
251
+ {'id': 'l1', 'name': 'Work', 'color': '#ef4444'},
252
+ {'id': 'l2', 'name': 'Personal', 'color': '#3b82f6'},
253
+ {'id': 'lbl-p1', 'name': 'P1', 'color': '#eb5a46'}, # red
254
+ {'id': 'lbl-p2', 'name': 'P2', 'color': '#ff9f1a'}, # orange
255
+ {'id': 'lbl-p3', 'name': 'P3', 'color': '#f2d600'}, # yellow
256
+ ]
257
+
258
+ gmail_state = {
259
+ 'user': GMAIL_USER,
260
+ 'emails': EMAILS,
261
+ 'labels': GMAIL_LABELS,
262
+ 'drafts': [],
263
+ 'settings': {
264
+ 'density': 'default',
265
+ 'undoSend': 10,
266
+ 'categoryTabs': {
267
+ 'primary': True,
268
+ 'social': True,
269
+ 'promotions': True,
270
+ 'updates': False,
271
+ 'forums': False,
272
+ },
273
+ },
274
+ 'today': '2026-06-16',
275
+ }
276
+
277
+ # ---------------------------------------------------------------------------
278
+ # Trello: 'Support' board, four empty component lists + decoy 'Done', P1/P2/P3
279
+ # labels. Target lists start with NO cards (Rule 3). Done holds watermark cards.
280
+ # ---------------------------------------------------------------------------
281
+ SUPPORT_LABELS = [
282
+ {'id': 'lbl-p1', 'name': 'P1', 'color': '#eb5a46'}, # red
283
+ {'id': 'lbl-p2', 'name': 'P2', 'color': '#ff9f1a'}, # orange
284
+ {'id': 'lbl-p3', 'name': 'P3', 'color': '#f2d600'}, # yellow
285
+ ]
286
+
287
+
288
+ def trello_card(cid, title, list_id, board_id, label_ids=None, due=None,
289
+ completed=False, position=0, description=''):
290
+ return {
291
+ 'id': cid,
292
+ 'title': title,
293
+ 'description': description,
294
+ 'listId': list_id,
295
+ 'boardId': board_id,
296
+ 'labelIds': label_ids or [],
297
+ 'memberIds': ['u1'],
298
+ 'dueDate': due,
299
+ 'startDate': None,
300
+ 'completed': completed,
301
+ 'cover': None,
302
+ 'checklists': [],
303
+ 'comments': [],
304
+ 'attachments': [],
305
+ 'archived': False,
306
+ 'watching': False,
307
+ 'position': position,
308
+ 'createdAt': '2026-06-12T09:00:00.000Z',
309
+ }
310
+
311
+
312
+ # Two decoy cards in the (excluded-from-scoring) 'Done' list — watermark only.
313
+ decoy_done_cards = {
314
+ 'card-done-1': trello_card(
315
+ 'card-done-1', 'Rotate API signing keys (Q2)', 'list-done', 'board-support',
316
+ label_ids=['lbl-p3'], due='2026-06-10T17:00:00.000Z', completed=True, position=0,
317
+ description='Quarterly key rotation completed and verified in prod.'),
318
+ 'card-done-2': trello_card(
319
+ 'card-done-2', 'Publish status-page postmortem', 'list-done', 'board-support',
320
+ label_ids=['lbl-p2'], due='2026-06-09T17:00:00.000Z', completed=True, position=1,
321
+ description='Postmortem for the May latency incident shared with customers.'),
322
+ }
323
+
324
+ trello_state = {
325
+ 'currentUser': 'u1',
326
+ 'users': {
327
+ 'u1': {'id': 'u1', 'name': 'Support Team', 'username': 'support',
328
+ 'initials': 'ST', 'email': 'support@acme.io', 'avatarUrl': ''},
329
+ 'u2': {'id': 'u2', 'name': 'Maya Lindqvist', 'username': 'maya',
330
+ 'initials': 'ML', 'email': 'maya.lindqvist@acme.io', 'avatarUrl': ''},
331
+ 'u3': {'id': 'u3', 'name': 'Hiroshi Tanabe', 'username': 'hiroshi',
332
+ 'initials': 'HT', 'email': 'hiroshi.tanabe@acme.io', 'avatarUrl': ''},
333
+ },
334
+ 'boards': {
335
+ 'board-support': {
336
+ 'id': 'board-support',
337
+ 'title': 'Support',
338
+ 'description': 'Customer support triage board. One card per genuine support email.',
339
+ 'background': '#0079BF',
340
+ 'listIds': ['list-bug', 'list-billing', 'list-feature', 'list-account', 'list-done'],
341
+ 'starred': True,
342
+ 'visibility': 'workspace',
343
+ 'archivedListIds': [],
344
+ 'archivedCardIds': [],
345
+ 'labels': SUPPORT_LABELS,
346
+ 'memberIds': ['u1', 'u2', 'u3'],
347
+ 'createdAt': '2026-06-01T09:00:00.000Z',
348
+ }
349
+ },
350
+ 'lists': {
351
+ 'list-bug': {'id': 'list-bug', 'title': 'Bug', 'boardId': 'board-support',
352
+ 'cardIds': [], 'archived': False},
353
+ 'list-billing': {'id': 'list-billing', 'title': 'Billing', 'boardId': 'board-support',
354
+ 'cardIds': [], 'archived': False},
355
+ 'list-feature': {'id': 'list-feature', 'title': 'Feature Request', 'boardId': 'board-support',
356
+ 'cardIds': [], 'archived': False},
357
+ 'list-account': {'id': 'list-account', 'title': 'Account', 'boardId': 'board-support',
358
+ 'cardIds': [], 'archived': False},
359
+ 'list-done': {'id': 'list-done', 'title': 'Done', 'boardId': 'board-support',
360
+ 'cardIds': ['card-done-1', 'card-done-2'], 'archived': False},
361
+ },
362
+ 'cards': decoy_done_cards,
363
+ 'boardOrder': ['board-support'],
364
+ 'lastReadNotificationAt': None,
365
+ }
366
+
367
+ # ---------------------------------------------------------------------------
368
+ # Google Calendar: operator's calendars. NO 'Follow-up:' events at injection
369
+ # (Rule 3) — only two decoy events for realism. The agent must create a
370
+ # follow-up event per P1 ticket and TYPE the requester's email into the guest
371
+ # field (the autocomplete only lists @example.com users, so the real email
372
+ # from Gmail must be carried over).
373
+ # ---------------------------------------------------------------------------
374
+ def cal_event(eid, calendar_id, title, start_iso, end_iso, location, description, guests):
375
+ return {
376
+ 'id': eid, 'calendarId': calendar_id, 'title': title,
377
+ 'start': start_iso, 'end': end_iso,
378
+ 'allDay': False, 'location': location, 'description': description,
379
+ 'guests': guests, 'color': 'bg-green-500', 'recurring': 'none',
380
+ 'reminders': [{'type': 'popup', 'minutes': 10}],
381
+ }
382
+
383
+
384
+ google_calendar_state = {
385
+ 'user': {'id': 'u1', 'username': 'Support Team',
386
+ 'email': 'support@acme.io',
387
+ 'avatar': 'https://picsum.photos/100/100?random=u1'},
388
+ 'calendars': [
389
+ {'id': 'c1', 'name': 'Personal', 'color': 'bg-blue-500',
390
+ 'textColor': 'text-white', 'visible': True, 'userId': 'u1'},
391
+ {'id': 'c2', 'name': 'Work', 'color': 'bg-green-500',
392
+ 'textColor': 'text-white', 'visible': True, 'userId': 'u1'},
393
+ ],
394
+ 'events': [
395
+ cal_event('evt_standup', 'c2', 'Support Standup',
396
+ '2026-06-16T09:30:00.000Z', '2026-06-16T10:00:00.000Z',
397
+ 'Conference Room A', 'Daily support sync', ['support@acme.io']),
398
+ cal_event('evt_retro', 'c2', 'Sprint Retro',
399
+ '2026-06-18T15:00:00.000Z', '2026-06-18T16:00:00.000Z',
400
+ 'Zoom', 'Bi-weekly retro', []),
401
+ ],
402
+ 'view': 'week',
403
+ 'currentDate': '2026-06-16T00:00:00.000Z',
404
+ 'sidebarOpen': True,
405
+ 'settings': {'weekStart': 0, 'defaultDuration': 60},
406
+ 'today': '2026-06-16',
407
+ }
408
+
409
+ # ---------------------------------------------------------------------------
410
+ # Slack: the team workspace. The agent must post a one-line triage SUMMARY to
411
+ # #support stating how many tickets were triaged, then PIN that message (pin is
412
+ # hidden behind the per-message hover "..." menu). #support starts EMPTY
413
+ # (no messages, no pinned messages) per Rule 3; decoy channels carry watermark
414
+ # chatter so the agent must find the right channel.
415
+ # ---------------------------------------------------------------------------
416
+ SLACK_USERS = [
417
+ {'userId': 'user_1', 'fullName': 'Sam Rivera', 'displayName': 'Sam',
418
+ 'email': 'support@acme.io', 'avatar': 'https://picsum.photos/200/200?random=1',
419
+ 'title': 'Support Engineer', 'status': 'online', 'statusMessage': '',
420
+ 'statusEmoji': '', 'timeZone': 'America/New_York'},
421
+ {'userId': 'user_2', 'fullName': 'Maya Lindqvist', 'displayName': 'Maya',
422
+ 'email': 'maya.lindqvist@acme.io', 'avatar': 'https://picsum.photos/200/200?random=2',
423
+ 'title': 'Support Lead', 'status': 'online', 'statusMessage': '',
424
+ 'statusEmoji': '', 'timeZone': 'America/New_York'},
425
+ {'userId': 'user_3', 'fullName': 'Hiroshi Tanabe', 'displayName': 'Hiroshi',
426
+ 'email': 'hiroshi.tanabe@acme.io', 'avatar': 'https://picsum.photos/200/200?random=3',
427
+ 'title': 'Engineer', 'status': 'away', 'statusMessage': '',
428
+ 'statusEmoji': '', 'timeZone': 'America/Los_Angeles'},
429
+ ]
430
+
431
+
432
+ def slack_channel(cid, name, desc, topic, starred=False, unread=0):
433
+ return {
434
+ 'channelId': cid, 'name': name, 'description': desc, 'topic': topic,
435
+ 'isPrivate': False, 'isStarred': starred,
436
+ 'members': ['user_1', 'user_2', 'user_3'],
437
+ 'createdBy': 'user_1', 'createdAt': '2026-06-01T09:00:00Z',
438
+ 'pinnedMessages': [], 'unreadCount': unread,
439
+ }
440
+
441
+
442
+ def slack_msg(mid, sender, content, ts):
443
+ return {
444
+ 'messageId': mid, 'senderId': sender, 'content': content,
445
+ 'timestamp': ts, 'threadId': None, 'reactions': [],
446
+ 'attachments': [], 'isEdited': False,
447
+ }
448
+
449
+
450
+ slack_state = {
451
+ 'currentUser': SLACK_USERS[0],
452
+ 'workspace': {'workspaceId': 'ws_1', 'workspaceName': 'Acme Support', 'icon': ''},
453
+ 'users': SLACK_USERS,
454
+ 'channels': [
455
+ # TARGET channel — starts empty (Rule 3).
456
+ slack_channel('support', 'support',
457
+ 'Customer support triage coordination', 'Daily triage updates',
458
+ starred=True),
459
+ # Decoys (watermark chatter).
460
+ slack_channel('general', 'general', 'Company-wide announcements', 'Welcome!',
461
+ starred=True, unread=0),
462
+ slack_channel('random', 'random', 'Non-work banter', 'Watercooler', unread=2),
463
+ slack_channel('incidents', 'incidents', 'Live incident coordination',
464
+ 'Page on-call here', unread=1),
465
+ ],
466
+ 'messages': {
467
+ # #support intentionally EMPTY — the gradable post is absent at injection.
468
+ 'support': [],
469
+ 'general': [
470
+ slack_msg('m_g_1', 'user_2', 'Morning all — support queue looks busy today.',
471
+ '2026-06-16T07:55:00Z'),
472
+ slack_msg('m_g_2', 'user_3', 'On it after standup.',
473
+ '2026-06-16T08:01:00Z'),
474
+ ],
475
+ 'random': [
476
+ slack_msg('m_r_1', 'user_3', 'Anyone tried the new ramen place on 3rd?',
477
+ '2026-06-15T12:30:00Z'),
478
+ slack_msg('m_r_2', 'user_2', '10/10, get the spicy miso.',
479
+ '2026-06-15T12:42:00Z'),
480
+ ],
481
+ 'incidents': [
482
+ slack_msg('m_i_1', 'user_2', 'Checkout 500s reported — investigating.',
483
+ '2026-06-16T08:15:00Z'),
484
+ ],
485
+ },
486
+ 'threads': {},
487
+ 'dms': [],
488
+ 'bookmarkedMessages': [],
489
+ 'callHistory': [],
490
+ 'settings': {
491
+ 'theme': 'light', 'notifications': 'all', 'displayDensity': 'comfortable',
492
+ 'showAvatars': True, 'use24Hour': False,
493
+ },
494
+ 'invitations': [],
495
+ 'notifications': [],
496
+ }
497
+
498
+ APP_STATES = [
499
+ ('http://28.7.184.198:8138', gmail_state),
500
+ ('http://28.7.184.198:8182', trello_state),
501
+ ('http://28.7.184.198:8141', google_calendar_state),
502
+ ('http://28.7.184.198:8178', slack_state),
503
+ ]
504
+
505
+ for app_url, state in APP_STATES:
506
+ resp = requests.post(
507
+ f'{app_url}/post?sid={sid}',
508
+ json={'action': 'set', 'state': state},
509
+ timeout=30,
510
+ )
511
+ assert resp.status_code == 200, (
512
+ f'State injection failed for {app_url}: {resp.text}'
513
+ )
514
+ print(f'State injected: {app_url} sid={sid}')
515
+
516
+ for app_url, _ in APP_STATES:
517
+ go_payload = requests.get(f'{app_url}/go?sid={sid}', timeout=15).json()
518
+ assert go_payload.get('initial_state') is not None, (
519
+ f'initial_state is None after injection for {app_url}'
520
+ )
521
+ print(f'Verified initial_state set: {app_url}')
522
+
523
+
524
+ # PATCHED_BY: patch_wait_mocks_loaded.py
525
+ def launch_gui(command, delay_sec=1.0):
526
+ """Launch a GUI command, fully detached from this script.
527
+
528
+ Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that
529
+ wait_mocks_loaded's CDP phase can verify browser render below.
530
+ Idempotent: if the caller already specified a debug port, keep it.
531
+ """
532
+ env = os.environ.copy()
533
+ env['DISPLAY'] = ':0'
534
+ if isinstance(command, str):
535
+ _parts = shlex.split(command)
536
+ else:
537
+ _parts = list(command)
538
+ if (_parts and 'google-chrome' in _parts[0]
539
+ and not any(p.startswith('--remote-debugging-port') for p in _parts)):
540
+ _parts[1:1] = [
541
+ '--no-first-run',
542
+ '--no-default-browser-check',
543
+ '--remote-debugging-port=1337',
544
+ ]
545
+ subprocess.Popen(
546
+ _parts,
547
+ stdin=subprocess.DEVNULL,
548
+ stdout=subprocess.DEVNULL,
549
+ stderr=subprocess.DEVNULL,
550
+ env=env,
551
+ start_new_session=True,
552
+ )
553
+ time.sleep(delay_sec)
554
+
555
+
556
+ def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12):
557
+ """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style.
558
+
559
+ Phase 1 - Backend readiness:
560
+ Poll each mock's /state?sid=<sid> (preferred) or /go?sid=<sid>
561
+ (fallback) until it returns 200 with 'stored_state' or
562
+ 'initial_state' respectively, or until timeout.
563
+
564
+ Phase 2 - Browser render verification (via CDP + Playwright):
565
+ Connect to http://localhost:1337 (the --remote-debugging-port
566
+ injected by launch_gui above), wait for every open tab to reach
567
+ 'networkidle' AND to contain at least 20 DOM elements. This
568
+ guarantees the SPA fetched /go?sid= data AND actually painted,
569
+ not just that the mock backend is up.
570
+
571
+ Fallback:
572
+ If Playwright is missing or CDP cannot be reached, sleep for
573
+ `render_buffer` seconds as a best-effort delay so the screenshot
574
+ loop does not start on a still-blank tab.
575
+ """
576
+ import urllib.request as _urlreq
577
+ import time as _t
578
+ _urls = [p for p, _ in app_states]
579
+ _opener = _urlreq.build_opener(_urlreq.ProxyHandler({}))
580
+
581
+ # ---- Phase 1: backend readiness ----
582
+ _deadline = _t.time() + timeout
583
+ _todo = list(_urls)
584
+ while _todo and _t.time() < _deadline:
585
+ _rest = []
586
+ for _u in _todo:
587
+ _ok = False
588
+ for _path, _need in (('/state?sid=', b'stored_state'),
589
+ ('/go?sid=', b'initial_state')):
590
+ try:
591
+ _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5)
592
+ if _r.status == 200:
593
+ _body = _r.read()
594
+ if _need in _body:
595
+ _ok = True
596
+ break
597
+ except Exception:
598
+ pass
599
+ if _ok:
600
+ print(f" {_u}: backend ready")
601
+ continue
602
+ _rest.append(_u)
603
+ _todo = _rest
604
+ if _todo:
605
+ _t.sleep(2)
606
+ _done = len(_urls) - len(_todo)
607
+ _pend = f" (pending: {_todo})" if _todo else ""
608
+ print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}")
609
+
610
+ # ---- Phase 2: browser render verification via CDP ----
611
+ _cdp_ok = False
612
+ try:
613
+ from playwright.sync_api import sync_playwright
614
+ _cdp_dl = _t.time() + max(15.0, _deadline - _t.time())
615
+ with sync_playwright() as _p:
616
+ _br = None
617
+ while _t.time() < _cdp_dl:
618
+ try:
619
+ _br = _p.chromium.connect_over_cdp('http://localhost:1337')
620
+ break
621
+ except Exception:
622
+ _t.sleep(0.5)
623
+ if _br is None:
624
+ print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?")
625
+ else:
626
+ _n_expected = len(_urls)
627
+ _pages = []
628
+ _pg_dl = _t.time() + 15
629
+ _last_count = -1
630
+ _stable_since = None
631
+ while _t.time() < _pg_dl:
632
+ _pages = []
633
+ for _c in _br.contexts:
634
+ _pages.extend(_c.pages)
635
+ _cnt = len(_pages)
636
+ if _n_expected > 0 and _cnt >= _n_expected:
637
+ break
638
+ if _cnt > 0 and _cnt == _last_count:
639
+ if _stable_since is None:
640
+ _stable_since = _t.time()
641
+ elif _t.time() - _stable_since >= 1.5:
642
+ break
643
+ else:
644
+ _stable_since = None
645
+ _last_count = _cnt
646
+ _t.sleep(0.5)
647
+ _pages = []
648
+ for _c in _br.contexts:
649
+ _pages.extend(_c.pages)
650
+ if not _pages:
651
+ print(" wait_mocks_loaded: CDP connected but no open tabs found")
652
+ else:
653
+ print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render")
654
+ _MIN_ELEMS = 20
655
+ _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap
656
+ for _pg in _pages: # bring each to front once to defeat background-tab render throttling
657
+ try:
658
+ _pg.bring_to_front()
659
+ except Exception:
660
+ pass
661
+ _pending = list(_pages)
662
+ while _pending and _t.time() < _verify_dl:
663
+ _still = []
664
+ for _pg in _pending:
665
+ _ttl = ""
666
+ try:
667
+ _ttl = _pg.title()
668
+ except Exception:
669
+ pass
670
+ try:
671
+ _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0")
672
+ except Exception:
673
+ _n = 0
674
+ if _n >= _MIN_ELEMS:
675
+ print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)")
676
+ else:
677
+ _still.append(_pg)
678
+ _pending = _still
679
+ if _pending:
680
+ _t.sleep(2)
681
+ if not _pending:
682
+ _cdp_ok = True
683
+ else:
684
+ for _pg in _pending:
685
+ _ttl = ""
686
+ try:
687
+ _ttl = _pg.title()
688
+ except Exception:
689
+ pass
690
+ print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back")
691
+ except ImportError:
692
+ print(" wait_mocks_loaded: playwright not installed; skipping CDP phase")
693
+ except Exception as _e:
694
+ print(f" wait_mocks_loaded: CDP phase error ({_e!r})")
695
+
696
+ if not _cdp_ok:
697
+ print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep")
698
+ _t.sleep(render_buffer)
699
+ else:
700
+ print(" wait_mocks_loaded: browser render verified, skipping render_buffer")
701
+
702
+
703
+ def _open_mock_tabs(app_states, sid_value):
704
+ """Open the first mock as the primary Chrome window, the rest as new tabs.
705
+
706
+ Uses launch_gui once per URL so that the macOS localizer regex-extract
707
+ (which grabs the FIRST quoted URL per call) still works correctly.
708
+ """
709
+ _urls = [p for p, _ in app_states]
710
+ if not _urls:
711
+ return
712
+ launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0)
713
+ for _u in _urls[1:]:
714
+ launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0)
715
+
716
+
717
+
718
+ # PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate)
719
+ def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0):
720
+ """Block until every mock serves injected state AND (best-effort) renders."""
721
+ import time as _t
722
+ deadline = _t.time() + timeout
723
+ pending = dict(mocks)
724
+ while pending and _t.time() < deadline:
725
+ for name in list(pending):
726
+ try:
727
+ r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5)
728
+ if r.status_code == 200 and r.json().get('initial_state') is not None:
729
+ del pending[name]
730
+ except Exception:
731
+ pass
732
+ if pending:
733
+ _t.sleep(1.0)
734
+ if pending:
735
+ print(f'WARN: mocks not ready within {timeout}s: {list(pending)}')
736
+ try:
737
+ from playwright.sync_api import sync_playwright
738
+ except ImportError:
739
+ print('WARN: playwright not installed; skipping render check, settle 3s')
740
+ _t.sleep(3.0)
741
+ return
742
+ with sync_playwright() as p:
743
+ try:
744
+ browser = p.chromium.launch(channel='chrome', headless=True,
745
+ args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'])
746
+ except Exception as e:
747
+ print(f'WARN: could not launch chrome for render check: {e}; settle 3s')
748
+ _t.sleep(3.0)
749
+ return
750
+ try:
751
+ for name, url in mocks.items():
752
+ page = browser.new_page()
753
+ try:
754
+ page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000))
755
+ page.wait_for_function(
756
+ "document.body && document.body.innerText.length > 50",
757
+ timeout=int(render_timeout * 1000))
758
+ print(f'[{name}] rendered OK')
759
+ except Exception as e:
760
+ print(f'WARN: [{name}] render check issue: {e}')
761
+ finally:
762
+ page.close()
763
+ finally:
764
+ browser.close()
765
+
766
+
767
+ # ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render
768
+ _open_mock_tabs(APP_STATES, sid)
769
+ wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15)
770
+ wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12)
771
+ print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps')
csops_inbox_triage_006__long/reward.py ADDED
@@ -0,0 +1,654 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: T02_trello_triage_sla — Support inbox triage into Trello + Calendar + Slack
3
+ Task ID: csops_inbox_triage_006__long
4
+ Mocks: gmail_mock,trello_mock,google_calendar_mock,slack_mock
5
+ Scoring (all components are frac/F1 over absent-at-injection outputs -> do-nothing == 0):
6
+ 0.30 card placement F1 : true=(component,Subject) for actionable emails;
7
+ pred=(listName,title) over all NON-'Done' lists.
8
+ 0.15 gmail priority label: among actionable emails, frac whose CURRENT gmail
9
+ labels include the email's priority label (matched by
10
+ NAME P1/P2/P3). HIDDEN: the Label button only appears
11
+ in the Gmail toolbar after the email's checkbox is
12
+ ticked (selection-gated).
13
+ 0.12 trello label corr : among MATCHED cards, frac whose labelIds holds the
14
+ email's priority label id (by board label name P1/P2/P3).
15
+ HIDDEN: label lives inside the card-detail modal.
16
+ 0.08 due-date corr : among MATCHED cards, frac whose dueDate matches the
17
+ embedded `due` to the DAY (local-date comparison).
18
+ HIDDEN: due date lives inside the card-detail modal.
19
+ 0.10 archive rate : non-actionable emails moved to archive/all-mail/trash.
20
+ 0.08 P1 follow-up event : per P1 ticket, a calendar event titled 'Follow-up: <subj>'
21
+ on the P1 due date exists.
22
+ 0.07 P1 event guest : that event lists the requester's email as a guest
23
+ (HIDDEN: buried guest field; email carried from Gmail).
24
+ 0.05 slack summary post : a non-empty message exists in the #support channel
25
+ (empty at injection).
26
+ 0.05 slack pin : that #support message is PINNED (HIDDEN: pin is behind
27
+ the per-message hover "..." menu).
28
+ Answer key (sole source of truth): gmail.initial_state.emails[*].triage
29
+ """
30
+ import copy
31
+ import re
32
+ import sys
33
+
34
+ import requests
35
+
36
+ from datetime import datetime, timezone, timedelta
37
+
38
+ TZ_PLUS_8 = timezone(timedelta(hours=8))
39
+
40
+
41
+ def parse_as_utc(s, default_tz=TZ_PLUS_8):
42
+ """
43
+ Parse an ISO datetime string and convert it to UTC.
44
+
45
+ Assumption:
46
+ - If the string has Z or +00:00, it is already timezone-aware.
47
+ - If the string has no timezone, treat it as UTC+8.
48
+ """
49
+ if not s:
50
+ return None
51
+
52
+ s = str(s).strip()
53
+
54
+ # Python's fromisoformat prefers +00:00 over Z
55
+ if s.endswith("Z"):
56
+ s = s[:-1] + "+00:00"
57
+
58
+ dt = datetime.fromisoformat(s)
59
+
60
+ # Example: "2024-03-18T09:00" has no timezone.
61
+ # Treat it as UTC+8.
62
+ if dt.tzinfo is None:
63
+ dt = dt.replace(tzinfo=default_tz)
64
+
65
+ return dt.astimezone(timezone.utc)
66
+
67
+
68
+ def norm_dt(s):
69
+ dt = parse_as_utc(s)
70
+ if dt is None:
71
+ return ""
72
+ return dt.isoformat(timespec="seconds")
73
+
74
+
75
+ def date_key(s, local_tz=TZ_PLUS_8):
76
+ """
77
+ Return the calendar date (YYYY-MM-DD) that an ISO datetime represents in
78
+ LOCAL (UTC+8) terms. Timezone-aware values are converted to local first so
79
+ that, e.g., a UTC '...T09:00:00Z' due-time round-trips to the same local day
80
+ as a naive '...T17:00:00'. Naive values are taken as-is (already local).
81
+ Bare 'YYYY-MM-DD' strings fall back to their first 10 chars.
82
+ """
83
+ if not s:
84
+ return None
85
+ s = str(s).strip()
86
+ if s.endswith("Z"):
87
+ s = s[:-1] + "+00:00"
88
+ try:
89
+ dt = datetime.fromisoformat(s)
90
+ except ValueError:
91
+ return s[:10] if len(s) >= 10 else None
92
+ if dt.tzinfo is not None:
93
+ dt = dt.astimezone(local_tz)
94
+ return dt.date().isoformat()
95
+
96
+
97
+ # --- Read sid (set by initial_setup.py) ---
98
+ try:
99
+ with open('/tmp/task_web_sid', encoding='utf-8') as f:
100
+ sid = f.read().strip()
101
+ if not sid:
102
+ raise ValueError('sid is empty')
103
+ except Exception as e:
104
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
105
+ print('REWARD: 0.0')
106
+ sys.exit(0)
107
+
108
+
109
+ APP_URLS = {'gmail': 'http://28.7.184.198:8138', 'trello': 'http://28.7.184.198:8182',
110
+ 'google_calendar': 'http://28.7.184.198:8141', 'slack': 'http://28.7.184.198:8178'}
111
+ _GO_CACHE = {}
112
+
113
+
114
+ def clamp01(x):
115
+ return max(0.0, min(1.0, float(x)))
116
+
117
+
118
+ def frac(num, den):
119
+ return 0.0 if den == 0 else num / den
120
+
121
+
122
+ def f1(true_set, pred_set):
123
+ if not true_set and not pred_set:
124
+ return 1.0
125
+ tp = len(true_set & pred_set)
126
+ if tp == 0:
127
+ return 0.0
128
+ prec = tp / len(pred_set)
129
+ rec = tp / len(true_set)
130
+ return 2 * prec * rec / (prec + rec)
131
+
132
+
133
+ def by_id(items, key='id'):
134
+ return {it.get(key): it for it in (items or []) if isinstance(it, dict)}
135
+
136
+
137
+ def has_text(haystack, *needles):
138
+ s = (haystack or '').lower()
139
+ return any(n.lower() in s for n in needles)
140
+
141
+
142
+ def norm(s):
143
+ return (str(s) if s is not None else '').strip().lower()
144
+
145
+
146
+ def _msg_text(msg):
147
+ return msg.get('content') or msg.get('text') or ''
148
+
149
+
150
+ def _slack_channel_messages(slack_state, channel_name):
151
+ channels = slack_state.get('channels', [])
152
+ target = None
153
+ for ch in channels:
154
+ if norm(ch.get('name')) == norm(channel_name):
155
+ target = ch
156
+ break
157
+ if target is None:
158
+ return []
159
+
160
+ ch_msgs = target.get('messages')
161
+ if isinstance(ch_msgs, list):
162
+ return ch_msgs
163
+
164
+ msg_map = slack_state.get('messages', {})
165
+ if isinstance(msg_map, dict):
166
+ return msg_map.get(target.get('channelId'), []) or []
167
+ return []
168
+
169
+
170
+ def _normalize_app_name(app):
171
+ app = (app or '').strip().lower()
172
+ return app[:-5] if app.endswith('_mock') else app
173
+
174
+
175
+ def _parse_cell_id(cell_id):
176
+ if not isinstance(cell_id, str) or not cell_id:
177
+ return None
178
+ idx = 0
179
+ while idx < len(cell_id) and cell_id[idx].isalpha():
180
+ idx += 1
181
+ if idx == 0 or idx >= len(cell_id):
182
+ return None
183
+ col = 0
184
+ for ch in cell_id[:idx].upper():
185
+ col = col * 26 + (ord(ch) - ord('A') + 1)
186
+ try:
187
+ row = int(cell_id[idx:])
188
+ except ValueError:
189
+ return None
190
+ return row, col - 1
191
+
192
+
193
+ def _extract_rows_from_workbook(state):
194
+ if not isinstance(state, dict):
195
+ return None
196
+ sheets = state.get('sheets')
197
+ if not isinstance(sheets, list):
198
+ return None
199
+
200
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
201
+ headers_by_sheet = adapter.get('headers_by_sheet') if isinstance(adapter.get('headers_by_sheet'), dict) else {}
202
+
203
+ out = {}
204
+ for sh in sheets:
205
+ if not isinstance(sh, dict):
206
+ continue
207
+ name = sh.get('name') or sh.get('id') or 'Sheet1'
208
+ data = sh.get('data') if isinstance(sh.get('data'), dict) else {}
209
+
210
+ headers = headers_by_sheet.get(name)
211
+ if not headers:
212
+ cols = []
213
+ for cid, cell in data.items():
214
+ rc = _parse_cell_id(cid)
215
+ if not rc:
216
+ continue
217
+ row_idx, col_idx = rc
218
+ if row_idx != 1:
219
+ continue
220
+ value = ''
221
+ if isinstance(cell, dict):
222
+ value = cell.get('value', '')
223
+ elif cell is not None:
224
+ value = str(cell)
225
+ if value is not None and str(value) != '':
226
+ cols.append((col_idx, str(value)))
227
+ headers = [v for _, v in sorted(cols)]
228
+
229
+ if not headers:
230
+ continue
231
+
232
+ by_row = {}
233
+ for cid, cell in data.items():
234
+ rc = _parse_cell_id(cid)
235
+ if not rc:
236
+ continue
237
+ row_idx, col_idx = rc
238
+ if row_idx <= 1 or col_idx >= len(headers):
239
+ continue
240
+ if isinstance(cell, dict):
241
+ value = cell.get('value', '')
242
+ else:
243
+ value = cell
244
+ by_row.setdefault(row_idx, {})[headers[col_idx]] = value
245
+
246
+ rows = []
247
+ for row_idx in sorted(by_row.keys()):
248
+ row = by_row[row_idx]
249
+ if not any(str(row.get(h, '')).strip() for h in headers):
250
+ continue
251
+ rows.append({h: row.get(h, '') for h in headers})
252
+
253
+ out[name] = {'headers': headers, 'rows': rows}
254
+
255
+ if not out:
256
+ return None
257
+ return {'sheets': out}
258
+
259
+
260
+ def _sheet_rows(state, sheet_name=None):
261
+ wb = _extract_rows_from_workbook(state) or {}
262
+ sheets = wb.get('sheets', {}) if isinstance(wb, dict) else {}
263
+ if sheet_name is not None:
264
+ s = sheets.get(sheet_name)
265
+ return s.get('rows', []) if isinstance(s, dict) else []
266
+ for s in sheets.values():
267
+ if isinstance(s, dict):
268
+ return s.get('rows', [])
269
+ return []
270
+
271
+
272
+ def _materialize_google_sheets(payload):
273
+ for key in ('initial_state', 'current_state'):
274
+ state = payload.get(key)
275
+ if not isinstance(state, dict):
276
+ continue
277
+ maybe_rows = _extract_rows_from_workbook(state)
278
+ if maybe_rows is not None:
279
+ state['_ui_workbook'] = {
280
+ 'sheets': copy.deepcopy(state.get('sheets', [])),
281
+ 'title': state.get('title'),
282
+ }
283
+ state['sheets'] = maybe_rows['sheets']
284
+
285
+
286
+ def _materialize_slack(payload):
287
+ for key in ('initial_state', 'current_state'):
288
+ state = payload.get(key)
289
+ if not isinstance(state, dict):
290
+ continue
291
+ channels = state.get('channels') if isinstance(state.get('channels'), list) else []
292
+ messages_map = state.get('messages') if isinstance(state.get('messages'), dict) else {}
293
+ for ch in channels:
294
+ if not isinstance(ch, dict):
295
+ continue
296
+ cid = ch.get('channelId') or ch.get('id')
297
+ if not cid:
298
+ continue
299
+ msg_list = messages_map.get(cid) if isinstance(messages_map.get(cid), list) else []
300
+ channel_msgs = ch.get('messages') if isinstance(ch.get('messages'), list) else []
301
+ merged = {
302
+ (m.get('messageId') or m.get('id')): dict(m)
303
+ for m in channel_msgs
304
+ if isinstance(m, dict)
305
+ }
306
+ for m in msg_list:
307
+ if not isinstance(m, dict):
308
+ continue
309
+ mid = m.get('messageId') or m.get('id')
310
+ text = m.get('text') if m.get('text') is not None else m.get('content', '')
311
+ merged[mid] = {
312
+ 'id': mid,
313
+ 'messageId': mid,
314
+ 'text': text,
315
+ 'content': m.get('content', text),
316
+ 'senderId': m.get('senderId'),
317
+ 'timestamp': m.get('timestamp'),
318
+ 'reactions': m.get('reactions') if isinstance(m.get('reactions'), list) else [],
319
+ }
320
+ ch['messages'] = list(merged.values())
321
+
322
+
323
+ def _owner_name_map(state):
324
+ out = {}
325
+ users = state.get('users') if isinstance(state.get('users'), list) else []
326
+ for u in users:
327
+ if not isinstance(u, dict):
328
+ continue
329
+ uid = u.get('userId')
330
+ if not uid:
331
+ continue
332
+ name = (f"{u.get('firstName', '')} {u.get('lastName', '')}".strip() or u.get('name') or uid)
333
+ out[uid] = name
334
+ return out
335
+
336
+
337
+ def _materialize_salesforce(payload):
338
+ for key in ('initial_state', 'current_state'):
339
+ state = payload.get(key)
340
+ if not isinstance(state, dict):
341
+ continue
342
+
343
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
344
+ owner_names = _owner_name_map(state)
345
+
346
+ task_leads = adapter.get('task_leads') if isinstance(adapter.get('task_leads'), dict) else None
347
+ if task_leads and isinstance(state.get('leads'), list):
348
+ restored = []
349
+ for lead in state['leads']:
350
+ if not isinstance(lead, dict):
351
+ continue
352
+ lid = str(lead.get('leadId') or lead.get('id') or '')
353
+ meta = task_leads.get(lid, {})
354
+ restored.append({
355
+ 'id': meta.get('id') or lead.get('leadId') or lead.get('id'),
356
+ 'company': lead.get('company', meta.get('company', '')),
357
+ 'status': lead.get('status', 'New'),
358
+ 'ownerName': owner_names.get(lead.get('ownerId')) or meta.get('ownerName'),
359
+ 'annualRevenue': meta.get('annualRevenue', lead.get('revenue')),
360
+ })
361
+ state['leads'] = restored
362
+
363
+ task_accounts = adapter.get('task_accounts') if isinstance(adapter.get('task_accounts'), dict) else None
364
+ if task_accounts and isinstance(state.get('accounts'), list):
365
+ current_by_id = {}
366
+ for acc in state['accounts']:
367
+ if isinstance(acc, dict):
368
+ current_by_id[str(acc.get('accountId') or acc.get('id') or '')] = acc
369
+
370
+ restored_accounts = []
371
+ for aid, meta in task_accounts.items():
372
+ cur = current_by_id.get(str(aid), {})
373
+ restored_accounts.append({
374
+ 'id': meta.get('id') or aid,
375
+ 'name': meta.get('name') or cur.get('name', ''),
376
+ 'contact': meta.get('contact'),
377
+ 'wonWithin7d': bool(meta.get('wonWithin7d', False)),
378
+ 'onboardingStage': cur.get('onboardingStage', meta.get('onboardingStage')),
379
+ })
380
+ state['accounts'] = restored_accounts
381
+
382
+
383
+ def _materialize_google_docs(payload):
384
+ for key in ('initial_state', 'current_state'):
385
+ state = payload.get(key)
386
+ if not isinstance(state, dict):
387
+ continue
388
+ adapter = state.get('_task_adapter') if isinstance(state.get('_task_adapter'), dict) else {}
389
+ task_docs = adapter.get('task_documents') if isinstance(adapter.get('task_documents'), dict) else None
390
+ if not task_docs:
391
+ continue
392
+ docs_map = state.get('documents') if isinstance(state.get('documents'), dict) else {}
393
+ restored = []
394
+ for did, meta in task_docs.items():
395
+ cur = docs_map.get(did, {}) if isinstance(docs_map, dict) else {}
396
+ restored.append({
397
+ 'id': meta.get('id') or did,
398
+ 'title': cur.get('title', meta.get('title')),
399
+ 'vendor': meta.get('vendor'),
400
+ 'folder': meta.get('folder'),
401
+ 'content': cur.get('content', meta.get('content', '')),
402
+ })
403
+ state['documents'] = restored
404
+
405
+
406
+ def _adapt_payload_for_reward(app, payload):
407
+ app_name = _normalize_app_name(app)
408
+ if app_name == 'google_sheets':
409
+ _materialize_google_sheets(payload)
410
+ elif app_name == 'slack':
411
+ _materialize_slack(payload)
412
+ elif app_name == 'salesforce':
413
+ _materialize_salesforce(payload)
414
+ elif app_name == 'google_docs':
415
+ _materialize_google_docs(payload)
416
+ return payload
417
+
418
+
419
+ def go(app_name):
420
+ if app_name in _GO_CACHE:
421
+ return _GO_CACHE[app_name]
422
+
423
+ base = APP_URLS.get(app_name)
424
+ if not base:
425
+ print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)')
426
+ print('REWARD: 0.0')
427
+ sys.exit(0)
428
+
429
+ try:
430
+ resp = requests.get(f'{base}/go?sid={sid}', timeout=15)
431
+ resp.raise_for_status()
432
+ payload = resp.json()
433
+ except Exception as e:
434
+ print(f'CRITICAL: cannot fetch {app_name} go state: {e}')
435
+ print('REWARD: 0.0')
436
+ sys.exit(0)
437
+
438
+ payload = _adapt_payload_for_reward(app_name, payload)
439
+ _GO_CACHE[app_name] = payload
440
+ return payload
441
+
442
+
443
+ # === Task-specific reward ===
444
+ def reward(go):
445
+ gmail = go('gmail')
446
+ trello = go('trello')
447
+
448
+ emails_i = gmail.get('initial_state', {}).get('emails', []) or []
449
+ emails_c_list = gmail.get('current_state', {}).get('emails', []) or []
450
+ emails_c = {e.get('id'): e for e in emails_c_list if isinstance(e, dict)}
451
+
452
+ tcur = trello.get('current_state', {}) if isinstance(trello.get('current_state'), dict) else {}
453
+ lists_map = tcur.get('lists', {}) if isinstance(tcur.get('lists'), dict) else {}
454
+ cards_map = tcur.get('cards', {}) if isinstance(tcur.get('cards'), dict) else {}
455
+ boards_map = tcur.get('boards', {}) if isinstance(tcur.get('boards'), dict) else {}
456
+
457
+ # Board label NAME -> label id (e.g. 'p1' -> 'lbl-p1'); union over all boards.
458
+ label_name_to_id = {}
459
+ for b in boards_map.values():
460
+ if not isinstance(b, dict):
461
+ continue
462
+ for lab in (b.get('labels') or []):
463
+ if isinstance(lab, dict) and lab.get('name') and lab.get('id'):
464
+ label_name_to_id.setdefault(norm(lab.get('name')), lab.get('id'))
465
+
466
+ # --- partition emails by embedded triage.kind (sole source of truth) ---
467
+ actionable = []
468
+ nonactionable = []
469
+ for e in emails_i:
470
+ if not isinstance(e, dict):
471
+ continue
472
+ tri = e.get('triage') or {}
473
+ if norm(tri.get('kind')) == 'actionable':
474
+ actionable.append(e)
475
+ else:
476
+ nonactionable.append(e)
477
+
478
+ # true set = (component, Subject); lookup back to the source email.
479
+ true_set = set()
480
+ true_lookup = {}
481
+ for e in actionable:
482
+ tri = e.get('triage') or {}
483
+ key = (norm(tri.get('component')), norm(e.get('subject')))
484
+ true_set.add(key)
485
+ true_lookup[key] = e
486
+
487
+ # pred set + matched cards over all NON-'Done' lists (membership via cardIds).
488
+ pred_set = set()
489
+ matched = [] # (card, source_email)
490
+ for lst in lists_map.values():
491
+ if not isinstance(lst, dict):
492
+ continue
493
+ ltitle = lst.get('title') if lst.get('title') is not None else lst.get('name')
494
+ if norm(ltitle) == 'done':
495
+ continue
496
+ for cid in (lst.get('cardIds') or []):
497
+ card = cards_map.get(cid)
498
+ if not isinstance(card, dict):
499
+ continue
500
+ key = (norm(ltitle), norm(card.get('title')))
501
+ pred_set.add(key)
502
+ if key in true_lookup:
503
+ matched.append((card, true_lookup[key]))
504
+
505
+ card_f1 = f1(true_set, pred_set)
506
+
507
+ # --- Gmail priority label among ACTIONABLE emails (selection-gated control) ---
508
+ # Resolve each CURRENT gmail label id -> name so a label named P1/P2/P3 matches
509
+ # regardless of id drift; emails start with labels:[] so this is 0 at do-nothing.
510
+ gmail_labels_c = gmail.get('current_state', {}).get('labels', []) or []
511
+ gmail_labels_i = gmail.get('initial_state', {}).get('labels', []) or []
512
+ gmail_id_to_name = {}
513
+ for lab in list(gmail_labels_i) + list(gmail_labels_c):
514
+ if isinstance(lab, dict) and lab.get('id'):
515
+ gmail_id_to_name[lab.get('id')] = norm(lab.get('name'))
516
+ glabel_ok = 0
517
+ for e in actionable:
518
+ tri = e.get('triage') or {}
519
+ want = norm(tri.get('priority'))
520
+ cur = emails_c.get(e.get('id'), {})
521
+ got_names = {gmail_id_to_name.get(lid) for lid in (cur.get('labels') or [])}
522
+ if want and want in got_names:
523
+ glabel_ok += 1
524
+ glabel_score = frac(glabel_ok, len(actionable)) if actionable else 0.0
525
+
526
+ # priority-label correctness among MATCHED cards (hidden: card-detail modal)
527
+ lab_ok = 0
528
+ for card, e in matched:
529
+ tri = e.get('triage') or {}
530
+ want_id = label_name_to_id.get(norm(tri.get('priority')))
531
+ if want_id and want_id in (card.get('labelIds') or []):
532
+ lab_ok += 1
533
+ label_score = frac(lab_ok, len(matched))
534
+
535
+ # due-date correctness among MATCHED cards (compare to the day, local)
536
+ due_ok = 0
537
+ for card, e in matched:
538
+ tri = e.get('triage') or {}
539
+ want = date_key(tri.get('due'))
540
+ got = date_key(card.get('dueDate'))
541
+ if want and got and want == got:
542
+ due_ok += 1
543
+ due_score = frac(due_ok, len(matched))
544
+
545
+ # archive rate of non-actionable emails
546
+ arch = 0
547
+ for e in nonactionable:
548
+ cur = emails_c.get(e.get('id'), {})
549
+ if norm(cur.get('folder')) in ('archive', 'all-mail', 'trash'):
550
+ arch += 1
551
+ archive_score = frac(arch, len(nonactionable)) if nonactionable else 0.0
552
+
553
+ # --- Calendar follow-up for P1 tickets (event on right date + requester guest) ---
554
+ cal = go('google_calendar')
555
+ cur_events = cal.get('current_state', {}).get('events', []) or []
556
+
557
+ def _event_guests(ev):
558
+ g = ev.get('guests')
559
+ if not isinstance(g, list):
560
+ g = ev.get('attendees') if isinstance(ev.get('attendees'), list) else []
561
+ out = set()
562
+ for a in g:
563
+ if isinstance(a, dict):
564
+ a = a.get('email') or a.get('name')
565
+ if a:
566
+ out.add(norm(a))
567
+ return out
568
+
569
+ p1_emails = [e for e in actionable if (e.get('triage') or {}).get('priority') == 'P1'
570
+ and (e.get('triage') or {}).get('event_title')]
571
+ n_p1 = len(p1_emails)
572
+ event_ok = 0
573
+ guest_ok = 0
574
+ for e in p1_emails:
575
+ tri = e['triage']
576
+ want_title = norm(tri.get('event_title'))
577
+ want_date = tri.get('event_date') # 'YYYY-MM-DD'
578
+ want_guest = norm(tri.get('guest_email'))
579
+ ev_match = None
580
+ for ev in cur_events:
581
+ if not isinstance(ev, dict):
582
+ continue
583
+ if norm(ev.get('title')) == want_title and date_key(ev.get('start')) == want_date:
584
+ ev_match = ev
585
+ break
586
+ if ev_match is not None:
587
+ event_ok += 1
588
+ if want_guest and want_guest in _event_guests(ev_match):
589
+ guest_ok += 1
590
+ event_score = frac(event_ok, n_p1) if n_p1 else 0.0
591
+ guest_score = frac(guest_ok, n_p1) if n_p1 else 0.0
592
+
593
+ # --- Slack: summary posted to #support, then PINNED (hidden hover "..." menu) ---
594
+ slack = go('slack')
595
+ scur = slack.get('current_state', {}) if isinstance(slack.get('current_state'), dict) else {}
596
+ support_msgs = _slack_channel_messages(scur, 'support')
597
+ _support_kw = ('triag', 'ticket')
598
+ def _is_support_summary(m):
599
+ t = (_msg_text(m) or '').lower()
600
+ return bool(t.strip()) and any(k in t for k in _support_kw) and any(c.isdigit() for c in t)
601
+ post_ok = any(_is_support_summary(m) for m in support_msgs if isinstance(m, dict))
602
+ support_ch = None
603
+ for ch in (scur.get('channels') or []):
604
+ if isinstance(ch, dict) and norm(ch.get('name')) == 'support':
605
+ support_ch = ch
606
+ break
607
+ pinned_ids = (support_ch.get('pinnedMessages') or []) if isinstance(support_ch, dict) else []
608
+ support_msg_ids = {(m.get('messageId') or m.get('id'))
609
+ for m in support_msgs if isinstance(m, dict)}
610
+ # Pin must reference a message that actually lives in #support (so a posted
611
+ # summary, not a phantom id), and a post must exist for a pin to count.
612
+ pin_ok = bool(post_ok and any(pid in support_msg_ids for pid in pinned_ids))
613
+ post_score = 1.0 if post_ok else 0.0
614
+ pin_score = 1.0 if pin_ok else 0.0
615
+
616
+ s_card = 0.30 * card_f1
617
+ s_glabel = 0.15 * glabel_score
618
+ s_label = 0.12 * label_score
619
+ s_due = 0.08 * due_score
620
+ s_archive = 0.10 * archive_score
621
+ s_event = 0.08 * event_score
622
+ s_guest = 0.07 * guest_score
623
+ s_post = 0.05 * post_score
624
+ s_pin = 0.05 * pin_score
625
+ score = (s_card + s_glabel + s_label + s_due + s_archive
626
+ + s_event + s_guest + s_post + s_pin)
627
+
628
+ print(
629
+ 'DEBUG_T02 '
630
+ f'actionable={len(actionable)} nonactionable={len(nonactionable)} '
631
+ f'true_cards={len(true_set)} pred_cards={len(pred_set)} card_f1={round(card_f1, 4)} '
632
+ f'glabel_ok={glabel_ok}/{len(actionable)} glabel_score={round(glabel_score, 4)} '
633
+ f'matched={len(matched)} label_ok={lab_ok}/{len(matched)} label_score={round(label_score, 4)} '
634
+ f'due_ok={due_ok}/{len(matched)} due_score={round(due_score, 4)} '
635
+ f'archived={arch}/{len(nonactionable)} archive_score={round(archive_score, 4)} '
636
+ f'p1={n_p1} event_ok={event_ok}/{n_p1} guest_ok={guest_ok}/{n_p1} '
637
+ f'slack_post={post_ok} slack_pin={pin_ok} '
638
+ f'w_card={round(s_card, 4)} w_glabel={round(s_glabel, 4)} w_label={round(s_label, 4)} '
639
+ f'w_due={round(s_due, 4)} w_archive={round(s_archive, 4)} w_event={round(s_event, 4)} '
640
+ f'w_guest={round(s_guest, 4)} w_post={round(s_post, 4)} w_pin={round(s_pin, 4)} '
641
+ f'total={round(score, 4)}'
642
+ )
643
+
644
+ return clamp01(score)
645
+
646
+
647
+ try:
648
+ score = float(reward(go))
649
+ except Exception as exc:
650
+ print(f'ERROR: reward() raised {exc!r}')
651
+ score = 0.0
652
+
653
+ score = clamp01(score)
654
+ print(f'\nREWARD: {round(score, 4)}')
csops_incident_command_004__long/_cua_gym_vm_bridge.sh ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # CUA-Gym VM-side network fix (direct-IP mock access).
3
+ #
4
+ # Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by
5
+ # their real IDC address (http://28.7.184.198:81xx) instead of the old
6
+ # localhost:9000-9097 socat bridge, so the VM only needs two fixes:
7
+ #
8
+ # 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's
9
+ # cluster DNS, which is unreachable from QEMU SLIRP NAT
10
+ # ("Temporary failure in name resolution").
11
+ # 2. The mock host excluded from the woa http proxy — otherwise the VM's
12
+ # Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403
13
+ # from the proxy when hitting 28.7.184.198:81xx. (The old socat path never
14
+ # hit this because localhost is bypassed by default.)
15
+ #
16
+ # Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic
17
+ # OSWorld setup pipeline.
18
+ #
19
+ # Argv:
20
+ # $1 optional sudo password (default "password"; SetupController
21
+ # substitutes {CLIENT_PASSWORD} when uploaded as a cache file).
22
+ # $2 unused (kept for backward compat — was socat first port 9000).
23
+ # $3 unused (kept for backward compat — was socat last port 9097).
24
+ # $4 optional mock host IP (default 28.7.184.198).
25
+
26
+ set +e
27
+
28
+ PASS="${1:-password}"
29
+ MOCK_HOST="${4:-28.7.184.198}"
30
+ # Derive the /16 IDC subnet so future port/host tweaks on the same segment
31
+ # stay bypassed too (28.7.184.198 -> 28.7.0.0/16).
32
+ MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')"
33
+
34
+ run_root() {
35
+ echo "$PASS" | sudo -S -p "" bash -c "$1"
36
+ }
37
+
38
+ # Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2.
39
+ GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')"
40
+ GW="${GW:-10.0.2.2}"
41
+
42
+ # ─── CUA-Gym network fix (Taiji-specific) ─────────────────────────────
43
+ fix_vm_network() {
44
+ # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP
45
+ # DNS forwarder. Nothing hardcoded except the mock host above.
46
+ local GW_NET="${GW%.*}"
47
+ local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3
48
+ local OWN_CIDR
49
+ OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \
50
+ | awk '{print $4; exit}')"
51
+ local OWN_IP="${OWN_CIDR%/*}"
52
+ local OWN_NET=""
53
+ [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24"
54
+
55
+ # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps
56
+ # systemd-resolved/NetworkManager from clobbering it.
57
+ if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf
58
+ chattr +i /etc/resolv.conf 2>/dev/null || true"; then
59
+ echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})"
60
+ else
61
+ echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf"
62
+ fi
63
+
64
+ # 2) Build the proxy bypass list from detected values + the direct-IP
65
+ # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx
66
+ # reachable from inside the VM — without it the woa proxy 403s it.
67
+ local ignore_list="['localhost', '127.0.0.0/8', '${GW}'"
68
+ [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'"
69
+ [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'"
70
+ [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'"
71
+ [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'"
72
+ [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'"
73
+ ignore_list="${ignore_list}]"
74
+
75
+ # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these.
76
+ if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then
77
+ echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}"
78
+ else
79
+ echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)"
80
+ fi
81
+
82
+ # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl).
83
+ local NP="localhost,127.0.0.1,${GW}"
84
+ [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}"
85
+ [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}"
86
+ [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24"
87
+ [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}"
88
+ [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}"
89
+
90
+ for var in no_proxy NO_PROXY; do
91
+ if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then
92
+ echo "export ${var}=${NP}" >> /home/user/.bashrc
93
+ fi
94
+ done
95
+ run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \
96
+ && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \
97
+ || echo 'no_proxy=\"${NP}\"' >> /etc/environment
98
+ grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \
99
+ && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \
100
+ || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1
101
+ echo "[cua_gym_vm_bridge] no_proxy=${NP}"
102
+ }
103
+
104
+ fix_vm_network
105
+
106
+ echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed"
csops_incident_command_004__long/initial_setup.py ADDED
@@ -0,0 +1,617 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: Incident triage & on-call routing with cross-source availability & ask-before-guess
3
+ Task ID: csops_incident_command_004__long (output/0707 #12, cluster C / ITSM)
4
+ Mocks: ServiceNow_mock, microsoft_teams_mock, google_calendar_mock, gmail_mock
5
+
6
+ The agent is an incident commander working the overnight incident queue in ServiceNow.
7
+ Assign each new incident to the on-call engineer for its service, then act by priority.
8
+
9
+ * lever d (cross-source): the on-call rota is in a Gmail note; engineer availability
10
+ (PTO this window) is in the Calendar. Assignee = rota[service], UNLESS the primary is
11
+ on PTO -> route to their backup. No single app decides.
12
+ * read-from-history (was lever k): incident INC0007 doesn't name its service owner and the
13
+ service isn't in the rota; the answer is PRE-SEEDED in the Teams #incidents HISTORY
14
+ (a manager already replied "INC0007 = Payments, on-call Priya Patel"). The agent reads
15
+ the channel history and assigns Priya. (Review 2026-07-11: replaced the live ask/reply —
16
+ we can't preset a mid-run reply — with an already-answered exchange in history.)
17
+ * lever i (bulk + keep-group): 15 incidents. 8 New to assign (2 P1); 3 already In Progress
18
+ + 2 Resolved/Closed (keep); 2 Planning (P5) skip. Assigning a keep/skip incident, or the
19
+ wrong engineer, lowers decision-set PRECISION. Denominator = the 8.
20
+
21
+ Assign = set assigned_to + state 2 (In Progress). P1 also gets a Teams bridge post + a
22
+ Calendar "Bridge: <incident>" event (dated the incident date).
23
+
24
+ GROUND TRUTH: ServiceNow.incidents[*]._inc {branch, priority, service, assignee, is_p1,
25
+ actionable}; google_calendar._task_adapter holds the answer key + rota + PTO + bridge date.
26
+ Observable results ship ABSENT (Rule 3): New incidents assigned_to null / state 1, no bridge
27
+ posts, no bridge events.
28
+
29
+ SCORING (HIDDEN_STATE_DIFFICULTY.md §3 positive form): "don't assign keep/skip" is a PRECISION
30
+ denominator; the missing-owner (read from history) + PTO-reroute are positive, gated by data flow.
31
+ No negatives. No live simulator.
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
+ # ---------------------------------------------------------------------------
49
+ # Engineers + on-call rota (rota lives in the Gmail note; embedded to precompute key).
50
+ # rota: service -> {primary, backup}. PTO this window: user_diaz (primary for 'Search').
51
+ # ---------------------------------------------------------------------------
52
+ ENGINEERS = {
53
+ 'user_wong': 'Alice Wong', 'user_lee': 'Bob Lee', 'user_diaz': 'Carol Diaz',
54
+ 'user_kim': 'David Kim', 'user_patel': 'Priya Patel', 'user_roy': 'Fiona Roy',
55
+ }
56
+ ROTA = {
57
+ 'API': {'primary': 'user_wong', 'backup': 'user_lee'},
58
+ 'Database': {'primary': 'user_lee', 'backup': 'user_wong'},
59
+ 'Search': {'primary': 'user_diaz', 'backup': 'user_kim'}, # diaz on PTO -> backup kim
60
+ 'Auth': {'primary': 'user_kim', 'backup': 'user_diaz'},
61
+ 'Web': {'primary': 'user_roy', 'backup': 'user_wong'},
62
+ 'Payments': {'primary': 'user_patel', 'backup': 'user_lee'}, # INC0007 owner (revealed via ask)
63
+ }
64
+ PTO_USERS = {'user_diaz'} # on PTO this window (from Calendar)
65
+ MISSING_OWNER_INCIDENT = 'INC0007'
66
+ MISSING_OWNER_SERVICE = 'Payments'
67
+
68
+
69
+ def _assignee_for(service):
70
+ r = ROTA[service]
71
+ primary = r['primary']
72
+ return r['backup'] if primary in PTO_USERS else primary
73
+
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # Incident spec: (number, short_desc, service, priority, state, kind)
77
+ # kind: 'assign' (New, actionable) / 'skip' (P5 Planning) / 'keep' (In Progress/Resolved/Closed)
78
+ # priority: 1 (P1) .. 5 (Planning). state: 1 New / 2 In Progress / 6 Resolved / 7 Closed.
79
+ # INC0007 (Payments) has service unknown from the ticket -> ask; here we still tag its service
80
+ # for the key, but the injected short_description won't name the owner.
81
+ # ---------------------------------------------------------------------------
82
+ _INC_SPEC = [
83
+ # --- 8 New to assign (2 P1, 6 P2/P3) ---
84
+ ('INC0001', 'API 5xx spike', 'API', 1, 1, 'assign'), # P1
85
+ ('INC0002', 'Checkout DB timeouts', 'Database', 1, 1, 'assign'), # P1
86
+ ('INC0003', 'Search results stale', 'Search', 2, 1, 'assign'), # PTO reroute (diaz->kim)
87
+ ('INC0004', 'Auth token refresh slow', 'Auth', 2, 1, 'assign'),
88
+ ('INC0005', 'Web page load latency', 'Web', 3, 1, 'assign'),
89
+ ('INC0006', 'API rate-limit errors', 'API', 3, 1, 'assign'),
90
+ ('INC0007', 'Payments latency', 'Payments', 2, 1, 'assign'), # k: owner unknown -> ask
91
+ ('INC0008', 'Auth MFA delays', 'Auth', 3, 1, 'assign'),
92
+ # --- 2 Planning (P5) -> skip ---
93
+ ('INC0009', 'Tech-debt: log rotation', 'Web', 5, 1, 'skip'),
94
+ ('INC0010', 'Backlog: metrics cleanup', 'API', 5, 1, 'skip'),
95
+ # --- 3 already In Progress -> keep ---
96
+ ('INC0011', 'Ongoing DB migration', 'Database', 2, 2, 'keep'),
97
+ ('INC0012', 'Search index rebuild', 'Search', 3, 2, 'keep'),
98
+ ('INC0013', 'Auth cert renewal', 'Auth', 3, 2, 'keep'),
99
+ # --- 2 Resolved/Closed -> keep ---
100
+ ('INC0014', 'Resolved: web outage', 'Web', 2, 6, 'keep'),
101
+ ('INC0015', 'Closed: api hotfix', 'API', 2, 7, 'keep'),
102
+ ]
103
+
104
+
105
+ def _build_incident(idx, number, desc, service, priority, state, kind):
106
+ if kind == 'assign':
107
+ branch, actionable = 'assign', True
108
+ assignee = _assignee_for(service)
109
+ elif kind == 'skip':
110
+ branch, actionable, assignee = 'skip', False, None
111
+ else:
112
+ branch, actionable, assignee = 'keep', False, None
113
+ is_p1 = (priority == 1 and kind == 'assign')
114
+ # injected: New incidents unassigned; keep incidents pre-assigned.
115
+ inj_assigned = None if kind in ('assign', 'skip') else 'user_wong'
116
+ return {
117
+ 'sys_id': f'inc{idx}', 'number': number, 'caller_id': 'user_ext',
118
+ 'category': 'Software', 'short_description': desc, 'description': desc,
119
+ 'state': state, 'impact': 2, 'urgency': 2, 'priority': priority,
120
+ 'assignment_group': 'g1', 'assigned_to': inj_assigned,
121
+ 'opened_at': '2026-04-30T02:00:00Z', 'opened_by': 'user_ext',
122
+ 'service': service, 'updated_at': '2026-04-30T02:00:00Z',
123
+ '_inc': {'branch': branch, 'priority': priority, 'service': service,
124
+ 'assignee': assignee, 'is_p1': is_p1, 'actionable': actionable},
125
+ }
126
+
127
+
128
+ _INCIDENTS = [_build_incident(i, *spec) for i, spec in enumerate(_INC_SPEC, start=1)]
129
+
130
+
131
+ # ---------------------------------------------------------------------------
132
+ # Precompute answer key.
133
+ # ---------------------------------------------------------------------------
134
+ ASSIGN_IDS = [t['sys_id'] for t in _INCIDENTS if t['_inc']['branch'] == 'assign']
135
+ P1_IDS = [t['sys_id'] for t in _INCIDENTS if t['_inc']['is_p1']]
136
+ SKIP_IDS = [t['sys_id'] for t in _INCIDENTS if t['_inc']['branch'] == 'skip']
137
+ KEEP_IDS = [t['sys_id'] for t in _INCIDENTS if t['_inc']['branch'] == 'keep']
138
+ ASSIGNEE_BY_ID = {t['sys_id']: t['_inc']['assignee'] for t in _INCIDENTS if t['_inc']['branch'] == 'assign'}
139
+ NUMBER_BY_ID = {t['sys_id']: t['number'] for t in _INCIDENTS}
140
+ MISSING_ID = next(t['sys_id'] for t in _INCIDENTS if t['number'] == MISSING_OWNER_INCIDENT)
141
+ MISSING_ASSIGNEE = ASSIGNEE_BY_ID[MISSING_ID]
142
+ PTO_INCIDENT_ID = next(t['sys_id'] for t in _INCIDENTS if t['number'] == 'INC0003') # Search -> reroute
143
+ BRIDGE_EVENTS = [{'number': NUMBER_BY_ID[i], 'title': f'Bridge: {NUMBER_BY_ID[i]}',
144
+ 'date': '2026-04-30'} for i in P1_IDS]
145
+
146
+ assert len(ASSIGN_IDS) == 8, ASSIGN_IDS
147
+ assert len(P1_IDS) == 2, P1_IDS
148
+ assert len(SKIP_IDS) == 2 and len(KEEP_IDS) == 5, (SKIP_IDS, KEEP_IDS)
149
+ assert ASSIGNEE_BY_ID[PTO_INCIDENT_ID] == 'user_kim', ASSIGNEE_BY_ID[PTO_INCIDENT_ID] # backup, not diaz
150
+ assert MISSING_ASSIGNEE == 'user_patel', MISSING_ASSIGNEE
151
+ print(f'Assign: {ASSIGN_IDS} (P1={P1_IDS}); skip: {SKIP_IDS}; keep: {KEEP_IDS}')
152
+ print(f'PTO reroute INC0003 -> {ASSIGNEE_BY_ID[PTO_INCIDENT_ID]}; INC0007 owner -> {MISSING_ASSIGNEE}')
153
+
154
+
155
+ # ---------------------------------------------------------------------------
156
+ # ServiceNow state.
157
+ # NOTE: ServiceNow_mock frontend (see websites/ServiceNow_mock/SCHEMA.md and
158
+ # src/pages/IncidentForm.jsx `${u.first_name} ${u.last_name}`) requires users to have
159
+ # {sys_id, user_name, first_name, last_name, email, active}. Passing only {sys_id,name,email}
160
+ # makes every Caller/Assigned-to option render as "undefined undefined".
161
+ # ---------------------------------------------------------------------------
162
+ def _split_full_name(full):
163
+ parts = full.split(' ', 1)
164
+ return parts[0], (parts[1] if len(parts) > 1 else '')
165
+
166
+
167
+ def _sn_user(uid, full_name, email):
168
+ first, last = _split_full_name(full_name)
169
+ return {'sys_id': uid, 'user_name': uid, 'first_name': first, 'last_name': last,
170
+ 'email': email, 'active': True}
171
+
172
+
173
+ _SERVICENOW_STATE = {
174
+ 'users': [_sn_user(uid, name, f'{uid}@northgate.com') for uid, name in ENGINEERS.items()]
175
+ + [_sn_user('user_ext', 'External Caller', 'ext@customer.com')],
176
+ 'groups': [{'sys_id': 'g1', 'name': 'SRE On-Call', 'description': 'On-call rotation'}],
177
+ 'incidents': _INCIDENTS, 'problems': [], 'changeRequests': [],
178
+ 'requests': [], 'requestedItems': [], 'catalogItems': [], 'knowledge': [], 'cmdb': [],
179
+ '_task_adapter': {'source_schema': 'incident_oncall',
180
+ 'task_id': 'a9b5c210-7e1f-4c3d-d92a-0707aa778800'},
181
+ }
182
+
183
+
184
+ # ---------------------------------------------------------------------------
185
+ # Microsoft Teams — the incident channel + extra channels/chatter.
186
+ # Review changes:
187
+ # #2 ask-before-guess REMOVED (no live mid-run reply). Instead the INC0007 owner Q&A is
188
+ # PRE-SEEDED in the #incidents history: the manager already answered "INC0007 = Payments,
189
+ # on-call Priya Patel". The agent READS history and assigns accordingly (no asking scored).
190
+ # #5 add extra channels (general, sre-announcements) + harmless filler chatter so Teams looks
191
+ # real; every senderId resolves to a users[] entry with a displayName.
192
+ # ---------------------------------------------------------------------------
193
+ TEAMS_USERS = [
194
+ {'userId': 'user_1', 'displayName': 'Lena Ortiz', 'email': 'lena@northgate.com'},
195
+ {'userId': 'user_mgr', 'displayName': 'Sam Wren', 'email': 'sam@northgate.com'},
196
+ {'userId': 'user_patel', 'displayName': 'Priya Patel', 'email': 'priya@northgate.com'},
197
+ {'userId': 'user_kim', 'displayName': 'David Kim', 'email': 'david@northgate.com'},
198
+ {'userId': 'user_wong', 'displayName': 'Alice Wong', 'email': 'alice@northgate.com'},
199
+ ]
200
+
201
+
202
+ def _tmsg(mid, ch, sender, content, ts):
203
+ return {'messageId': mid, 'containerId': ch, 'containerType': 'channel',
204
+ 'senderId': sender, 'content': content, 'contentType': 'text',
205
+ 'messageType': 'message', 'createdDateTime': ts, 'replyToId': None,
206
+ 'reactions': [], 'mentions': [], 'attachments': [], 'isBookmarked': False}
207
+
208
+
209
+ # #incidents history: seed the INC0007 owner Q&A (already asked & answered) + normal chatter.
210
+ _INCIDENTS_HISTORY = [
211
+ _tmsg('msg_seed', 'ch_incidents', 'user_mgr',
212
+ 'Overnight queue is up — please triage and assign per the on-call rota.', '2026-04-30T02:00:00Z'),
213
+ _tmsg('msg_q_inc7', 'ch_incidents', 'user_1',
214
+ 'Quick one: INC0007 (payments latency) does not name a service owner and Payments is '
215
+ 'not in the rota email — who is on-call for it?', '2026-04-30T02:05:00Z'),
216
+ _tmsg('msg_a_inc7', 'ch_incidents', 'user_mgr',
217
+ 'INC0007 is the Payments service — on-call is Priya Patel (user_patel). Assign it to her.',
218
+ '2026-04-30T02:07:00Z'),
219
+ ]
220
+
221
+ _GENERAL_HISTORY = [
222
+ _tmsg('msg_g1', 'ch_general', 'user_mgr', 'Welcome to the SRE workspace :wave:', '2026-04-20T09:00:00Z'),
223
+ _tmsg('msg_g2', 'ch_general', 'user_kim', 'Reminder: incident retro moved to Friday 3pm.', '2026-04-28T14:00:00Z'),
224
+ _tmsg('msg_g3', 'ch_general', 'user_wong', 'Coffee machine on 4th floor is fixed 🎉', '2026-04-29T10:30:00Z'),
225
+ ]
226
+
227
+ _ANNOUNCE_HISTORY = [
228
+ _tmsg('msg_an1', 'ch_announcements', 'user_mgr',
229
+ 'Q2 on-call rotation published — check the pinned rota email.', '2026-04-27T08:00:00Z'),
230
+ _tmsg('msg_an2', 'ch_announcements', 'user_mgr',
231
+ 'New sev-1 escalation policy takes effect May 1.', '2026-04-29T16:00:00Z'),
232
+ ]
233
+
234
+ _TEAMS_STATE = {
235
+ 'currentUser': {'userId': 'user_1', 'displayName': 'Lena Ortiz', 'email': 'lena@northgate.com'},
236
+ 'users': TEAMS_USERS,
237
+ 'teams': [{'teamId': 'team_1', 'displayName': 'SRE', 'description': 'Site reliability',
238
+ 'avatar': '', 'channels': ['ch_general', 'ch_announcements', 'ch_incidents'],
239
+ 'members': [u['userId'] for u in TEAMS_USERS],
240
+ 'owners': ['user_mgr'], 'settings': {}}],
241
+ 'channels': [
242
+ {'channelId': 'ch_general', 'teamId': 'team_1', 'displayName': 'general',
243
+ 'description': 'Team-wide chatter', 'isPinned': False,
244
+ 'members': [u['userId'] for u in TEAMS_USERS], 'pinnedMessages': [], 'tabs': []},
245
+ {'channelId': 'ch_announcements', 'teamId': 'team_1', 'displayName': 'sre-announcements',
246
+ 'description': 'Announcements', 'isPinned': False,
247
+ 'members': [u['userId'] for u in TEAMS_USERS], 'pinnedMessages': [], 'tabs': []},
248
+ {'channelId': 'ch_incidents', 'teamId': 'team_1', 'displayName': 'incidents',
249
+ 'description': 'Incident bridge', 'isPinned': False,
250
+ 'members': [u['userId'] for u in TEAMS_USERS], 'pinnedMessages': [], 'tabs': []},
251
+ ],
252
+ 'chats': [],
253
+ 'messages': {
254
+ 'ch_general': _GENERAL_HISTORY,
255
+ 'ch_announcements': _ANNOUNCE_HISTORY,
256
+ 'ch_incidents': _INCIDENTS_HISTORY,
257
+ },
258
+ 'meetings': [], 'calls': [], 'files': [], 'notifications': [],
259
+ 'settings': {}, 'ui': {},
260
+ }
261
+
262
+
263
+ # ---------------------------------------------------------------------------
264
+ # Google Calendar — engineer PTO (Carol Diaz) + no Bridge events yet. Answer key on adapter.
265
+ # NOTE (review #1): google_calendar_mock only renders events whose calendarId is one of its
266
+ # hardcoded ids {c1,c2,c3,c4} AND whose calendar entry is visible. An injected calendar with
267
+ # id='primary' is replaced-in (wiping the c1..c4 defaults) so events (normalized to 'c1') have
268
+ # no visible calendar -> nothing shows. So we inject a calendar with id='c1', visible=True, and
269
+ # reference calendarId='c1' on every event.
270
+ # ---------------------------------------------------------------------------
271
+ CAL_ID = 'c1'
272
+
273
+
274
+ def cal_event(eid, title, start_iso, end_iso, guests):
275
+ return {'id': eid, 'calendarId': CAL_ID, 'title': title, 'start': start_iso,
276
+ 'end': end_iso, 'location': '', 'description': '', 'guests': guests,
277
+ 'color': 'bg-blue-500', 'recurring': 'none'}
278
+
279
+
280
+ _CAL_STATE = {
281
+ 'user': {'userId': 'u1', 'email': 'lena@northgate.com'},
282
+ 'calendars': [{'id': CAL_ID, 'name': 'On-Call', 'color': 'bg-blue-500',
283
+ 'textColor': 'text-white', 'visible': True, 'userId': 'u1'}],
284
+ 'events': [
285
+ cal_event('ev_pto', 'PTO - Carol Diaz', '2026-04-29T00:00:00Z', '2026-05-02T00:00:00Z', []),
286
+ cal_event('ev_decoy', 'Weekly SRE sync', '2026-05-01T15:00:00Z', '2026-05-01T15:30:00Z', []),
287
+ ],
288
+ 'today': '2026-04-30',
289
+ '_task_adapter': {
290
+ 'source_schema': 'incident_oncall',
291
+ 'task_id': 'a9b5c210-7e1f-4c3d-d92a-0707aa778800',
292
+ 'variant': 'eval',
293
+ # ---- ANSWER KEY ----
294
+ 'assign_ids': ASSIGN_IDS,
295
+ 'p1_ids': P1_IDS,
296
+ 'skip_ids': SKIP_IDS,
297
+ 'keep_ids': KEEP_IDS,
298
+ 'assignee_by_id': ASSIGNEE_BY_ID,
299
+ 'number_by_id': NUMBER_BY_ID,
300
+ 'bridge_events': BRIDGE_EVENTS,
301
+ 'missing_owner_id': MISSING_ID,
302
+ 'missing_owner_assignee': MISSING_ASSIGNEE,
303
+ 'pto_incident_id': PTO_INCIDENT_ID,
304
+ 'in_progress_state': 2,
305
+ # review #2: no live user-simulator anymore. INC0007's owner is revealed in the
306
+ # #incidents Teams HISTORY (msg_a_inc7); the agent reads it and assigns Priya Patel.
307
+ # review #3: bridge events must match title AND date (the incident date) on the calendar.
308
+ 'bridge_event_date': '2026-04-30',
309
+ },
310
+ }
311
+
312
+
313
+ # ---------------------------------------------------------------------------
314
+ # Gmail — the on-call rota note + a decoy.
315
+ # ---------------------------------------------------------------------------
316
+ _rota_lines = '<br>'.join(
317
+ f"- {svc}: primary {ENGINEERS[r['primary']]}, backup {ENGINEERS[r['backup']]}"
318
+ for svc, r in ROTA.items() if svc != MISSING_OWNER_SERVICE # Payments owner not in the note (ask)
319
+ )
320
+ _GMAIL_STATE = {
321
+ 'user': {'userId': 'u1', 'username': 'Lena Ortiz', 'email': 'lena@northgate.com',
322
+ 'avatar': 'https://picsum.photos/200/200?random=23'},
323
+ 'emails': [
324
+ {'id': 'm_rota', 'threadId': 'thread_r',
325
+ 'from': {'name': 'On-Call Bot', 'email': 'oncall@northgate.com', 'avatar': ''},
326
+ 'to': [{'name': 'Lena Ortiz', 'email': 'lena@northgate.com'}], 'cc': [], 'bcc': [],
327
+ 'subject': 'This week on-call rota',
328
+ 'body': ('Hi Lena,<br><br>On-call rota for this week:<br>' + _rota_lines +
329
+ '<br><br>Remember to check calendars for PTO before assigning.<br>— On-Call Bot'),
330
+ 'snippet': 'On-call rota for this week...', 'timestamp': '2026-04-28T08:00:00Z',
331
+ 'read': False, 'starred': False, 'important': True, 'labels': [],
332
+ 'category': 'primary', 'folder': 'inbox', 'attachments': []},
333
+ {'id': 'm_decoy1', 'threadId': 'thread_d1',
334
+ 'from': {'name': 'IT Newsletter', 'email': 'news@northgate.com', 'avatar': ''},
335
+ 'to': [{'name': 'Lena Ortiz', 'email': 'lena@northgate.com'}], 'cc': [], 'bcc': [],
336
+ 'subject': 'April reliability review', 'body': 'Reminders.', 'snippet': 'Reminders...',
337
+ 'timestamp': '2026-04-27T15:00:00Z', 'read': True, 'starred': False,
338
+ 'important': False, 'labels': [], 'category': 'updates', 'folder': 'inbox',
339
+ 'attachments': []},
340
+ ],
341
+ 'labels': [{'id': 'l1', 'name': 'Work', 'color': '#ef4444'}],
342
+ 'drafts': [], 'settings': {'density': 'default', 'undoSend': 10}, 'today': '2026-04-30',
343
+ }
344
+
345
+
346
+ # ---------------------------------------------------------------------------
347
+ # Inject.
348
+ # ---------------------------------------------------------------------------
349
+ APP_STATES = [
350
+ ('http://28.7.184.198:8105', _SERVICENOW_STATE), # ServiceNow_mock
351
+ ('http://28.7.184.198:8162', _TEAMS_STATE), # microsoft_teams_mock
352
+ ('http://28.7.184.198:8141', _CAL_STATE), # google_calendar_mock
353
+ ('http://28.7.184.198:8138', _GMAIL_STATE), # gmail_mock
354
+ ]
355
+
356
+
357
+ for app_url, state in APP_STATES:
358
+ resp = requests.post(f'{app_url}/post?sid={sid}',
359
+ json={'action': 'set', 'state': state}, timeout=30)
360
+ assert resp.status_code == 200, f'State injection failed for {app_url}: {resp.text}'
361
+ print(f'State injected: {app_url} sid={sid}')
362
+
363
+ for app_url, _ in APP_STATES:
364
+ go_payload = requests.get(f'{app_url}/go?sid={sid}', timeout=15).json()
365
+ assert go_payload.get('initial_state') is not None, (
366
+ f'initial_state is None after injection for {app_url}')
367
+ print(f'Verified initial_state set: {app_url}')
368
+
369
+
370
+ # PATCHED_BY: patch_wait_mocks_loaded.py
371
+ def launch_gui(command, delay_sec=1.0):
372
+ """Launch a GUI command, fully detached from this script.
373
+
374
+ Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that
375
+ wait_mocks_loaded's CDP phase can verify browser render below.
376
+ Idempotent: if the caller already specified a debug port, keep it.
377
+ """
378
+ env = os.environ.copy()
379
+ env['DISPLAY'] = ':0'
380
+ if isinstance(command, str):
381
+ _parts = shlex.split(command)
382
+ else:
383
+ _parts = list(command)
384
+ if (_parts and 'google-chrome' in _parts[0]
385
+ and not any(p.startswith('--remote-debugging-port') for p in _parts)):
386
+ _parts[1:1] = [
387
+ '--no-first-run',
388
+ '--no-default-browser-check',
389
+ '--remote-debugging-port=1337',
390
+ ]
391
+ subprocess.Popen(
392
+ _parts,
393
+ stdin=subprocess.DEVNULL,
394
+ stdout=subprocess.DEVNULL,
395
+ stderr=subprocess.DEVNULL,
396
+ env=env,
397
+ start_new_session=True,
398
+ )
399
+ time.sleep(delay_sec)
400
+
401
+
402
+ def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12):
403
+ """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style.
404
+
405
+ Phase 1 - Backend readiness:
406
+ Poll each mock's /state?sid=<sid> (preferred) or /go?sid=<sid>
407
+ (fallback) until it returns 200 with 'stored_state' or
408
+ 'initial_state' respectively, or until timeout.
409
+
410
+ Phase 2 - Browser render verification (via CDP + Playwright):
411
+ Connect to http://localhost:1337 (the --remote-debugging-port
412
+ injected by launch_gui above), wait for every open tab to reach
413
+ 'networkidle' AND to contain at least 20 DOM elements. This
414
+ guarantees the SPA fetched /go?sid= data AND actually painted,
415
+ not just that the mock backend is up.
416
+
417
+ Fallback:
418
+ If Playwright is missing or CDP cannot be reached, sleep for
419
+ `render_buffer` seconds as a best-effort delay so the screenshot
420
+ loop does not start on a still-blank tab.
421
+ """
422
+ import urllib.request as _urlreq
423
+ import time as _t
424
+ _urls = [p for p, _ in app_states]
425
+ _opener = _urlreq.build_opener(_urlreq.ProxyHandler({}))
426
+
427
+ # ---- Phase 1: backend readiness ----
428
+ _deadline = _t.time() + timeout
429
+ _todo = list(_urls)
430
+ while _todo and _t.time() < _deadline:
431
+ _rest = []
432
+ for _u in _todo:
433
+ _ok = False
434
+ for _path, _need in (('/state?sid=', b'stored_state'),
435
+ ('/go?sid=', b'initial_state')):
436
+ try:
437
+ _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5)
438
+ if _r.status == 200:
439
+ _body = _r.read()
440
+ if _need in _body:
441
+ _ok = True
442
+ break
443
+ except Exception:
444
+ pass
445
+ if _ok:
446
+ print(f" {_u}: backend ready")
447
+ continue
448
+ _rest.append(_u)
449
+ _todo = _rest
450
+ if _todo:
451
+ _t.sleep(2)
452
+ _done = len(_urls) - len(_todo)
453
+ _pend = f" (pending: {_todo})" if _todo else ""
454
+ print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}")
455
+
456
+ # ---- Phase 2: browser render verification via CDP ----
457
+ _cdp_ok = False
458
+ try:
459
+ from playwright.sync_api import sync_playwright
460
+ _cdp_dl = _t.time() + max(15.0, _deadline - _t.time())
461
+ with sync_playwright() as _p:
462
+ _br = None
463
+ while _t.time() < _cdp_dl:
464
+ try:
465
+ _br = _p.chromium.connect_over_cdp('http://localhost:1337')
466
+ break
467
+ except Exception:
468
+ _t.sleep(0.5)
469
+ if _br is None:
470
+ print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?")
471
+ else:
472
+ _n_expected = len(_urls)
473
+ _pages = []
474
+ _pg_dl = _t.time() + 15
475
+ _last_count = -1
476
+ _stable_since = None
477
+ while _t.time() < _pg_dl:
478
+ _pages = []
479
+ for _c in _br.contexts:
480
+ _pages.extend(_c.pages)
481
+ _cnt = len(_pages)
482
+ if _n_expected > 0 and _cnt >= _n_expected:
483
+ break
484
+ if _cnt > 0 and _cnt == _last_count:
485
+ if _stable_since is None:
486
+ _stable_since = _t.time()
487
+ elif _t.time() - _stable_since >= 1.5:
488
+ break
489
+ else:
490
+ _stable_since = None
491
+ _last_count = _cnt
492
+ _t.sleep(0.5)
493
+ _pages = []
494
+ for _c in _br.contexts:
495
+ _pages.extend(_c.pages)
496
+ if not _pages:
497
+ print(" wait_mocks_loaded: CDP connected but no open tabs found")
498
+ else:
499
+ print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render")
500
+ _MIN_ELEMS = 20
501
+ _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap
502
+ for _pg in _pages: # bring each to front once to defeat background-tab render throttling
503
+ try:
504
+ _pg.bring_to_front()
505
+ except Exception:
506
+ pass
507
+ _pending = list(_pages)
508
+ while _pending and _t.time() < _verify_dl:
509
+ _still = []
510
+ for _pg in _pending:
511
+ _ttl = ""
512
+ try:
513
+ _ttl = _pg.title()
514
+ except Exception:
515
+ pass
516
+ try:
517
+ _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0")
518
+ except Exception:
519
+ _n = 0
520
+ if _n >= _MIN_ELEMS:
521
+ print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)")
522
+ else:
523
+ _still.append(_pg)
524
+ _pending = _still
525
+ if _pending:
526
+ _t.sleep(2)
527
+ if not _pending:
528
+ _cdp_ok = True
529
+ else:
530
+ for _pg in _pending:
531
+ _ttl = ""
532
+ try:
533
+ _ttl = _pg.title()
534
+ except Exception:
535
+ pass
536
+ print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back")
537
+ except ImportError:
538
+ print(" wait_mocks_loaded: playwright not installed; skipping CDP phase")
539
+ except Exception as _e:
540
+ print(f" wait_mocks_loaded: CDP phase error ({_e!r})")
541
+
542
+ if not _cdp_ok:
543
+ print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep")
544
+ _t.sleep(render_buffer)
545
+ else:
546
+ print(" wait_mocks_loaded: browser render verified, skipping render_buffer")
547
+
548
+
549
+ def _open_mock_tabs(app_states, sid_value):
550
+ """Open the first mock as the primary Chrome window, the rest as new tabs.
551
+
552
+ Uses launch_gui once per URL so that the macOS localizer regex-extract
553
+ (which grabs the FIRST quoted URL per call) still works correctly.
554
+ """
555
+ _urls = [p for p, _ in app_states]
556
+ if not _urls:
557
+ return
558
+ launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0)
559
+ for _u in _urls[1:]:
560
+ launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0)
561
+
562
+
563
+
564
+ # PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate)
565
+ def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0):
566
+ """Block until every mock serves injected state AND (best-effort) renders."""
567
+ import time as _t
568
+ deadline = _t.time() + timeout
569
+ pending = dict(mocks)
570
+ while pending and _t.time() < deadline:
571
+ for name in list(pending):
572
+ try:
573
+ r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5)
574
+ if r.status_code == 200 and r.json().get('initial_state') is not None:
575
+ del pending[name]
576
+ except Exception:
577
+ pass
578
+ if pending:
579
+ _t.sleep(1.0)
580
+ if pending:
581
+ print(f'WARN: mocks not ready within {timeout}s: {list(pending)}')
582
+ try:
583
+ from playwright.sync_api import sync_playwright
584
+ except ImportError:
585
+ print('WARN: playwright not installed; skipping render check, settle 3s')
586
+ _t.sleep(3.0)
587
+ return
588
+ with sync_playwright() as p:
589
+ try:
590
+ browser = p.chromium.launch(channel='chrome', headless=True,
591
+ args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'])
592
+ except Exception as e:
593
+ print(f'WARN: could not launch chrome for render check: {e}; settle 3s')
594
+ _t.sleep(3.0)
595
+ return
596
+ try:
597
+ for name, url in mocks.items():
598
+ page = browser.new_page()
599
+ try:
600
+ page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000))
601
+ page.wait_for_function(
602
+ "document.body && document.body.innerText.length > 50",
603
+ timeout=int(render_timeout * 1000))
604
+ print(f'[{name}] rendered OK')
605
+ except Exception as e:
606
+ print(f'WARN: [{name}] render check issue: {e}')
607
+ finally:
608
+ page.close()
609
+ finally:
610
+ browser.close()
611
+
612
+
613
+ # ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render
614
+ _open_mock_tabs(APP_STATES, sid)
615
+ wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15)
616
+ wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12)
617
+ print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps')
csops_incident_command_004__long/reward.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: Incident triage & on-call routing with cross-source availability & ask-before-guess
3
+ Task ID: csops_incident_command_004__long (output/0707 #12, cluster C / ITSM)
4
+ Mocks: ServiceNow_mock, microsoft_teams_mock, google_calendar_mock, gmail_mock
5
+
6
+ Scoring — ALL positive. Every component in [0,1]; weights sum to 1.0. NO penalties, NO gate.
7
+
8
+ 0.35 assignment decision-set precision:
9
+ frac(#New incidents assigned to CORRECT engineer, 8 + #wrongly_assigned)
10
+ (assigning a keep/skip incident, or the wrong engineer, = false positive)
11
+ 0.15 state correctness: frac of the 8 moved to In Progress (state 2)
12
+ 0.15 P1 bridge: frac of P1 incidents with BOTH a Teams bridge post + a Calendar bridge event
13
+ whose title is 'Bridge: <INC>' AND whose date is the incident date
14
+ 0.25 missing-owner correctness: INC0007 assigned to the engineer named in the Teams #incidents
15
+ history (review 2026-07-11: the owner Q&A is pre-seeded in history; no live ask is scored)
16
+ 0.10 PTO-reroute correctness: the PTO-affected incident assigned to the BACKUP
17
+
18
+ Answer key: google_calendar.initial_state._task_adapter (assign_ids, p1_ids, assignee_by_id,
19
+ bridge_events, bridge_event_date, missing_owner_*, pto_incident_id) + ServiceNow.incidents[*]._inc.
20
+ """
21
+ import sys
22
+
23
+ import requests
24
+
25
+
26
+ try:
27
+ with open('/tmp/task_web_sid', encoding='utf-8') as f:
28
+ sid = f.read().strip()
29
+ if not sid:
30
+ raise ValueError('sid is empty')
31
+ except Exception as e:
32
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
33
+ print('REWARD: 0.0')
34
+ sys.exit(0)
35
+
36
+
37
+ APP_URLS = {
38
+ 'servicenow': 'http://28.7.184.198:8105',
39
+ 'microsoft_teams': 'http://28.7.184.198:8162',
40
+ 'google_calendar': 'http://28.7.184.198:8141',
41
+ }
42
+ _GO_CACHE = {}
43
+
44
+
45
+ def clamp01(x):
46
+ return max(0.0, min(1.0, float(x)))
47
+
48
+
49
+ def frac(num, den):
50
+ return 0.0 if den == 0 else num / den
51
+
52
+
53
+ def norm(s):
54
+ return (str(s) if s is not None else '').strip().lower()
55
+
56
+
57
+ def _date_key(s):
58
+ if not s:
59
+ return ''
60
+ import datetime as dt
61
+ txt = str(s).replace('Z', '+00:00')
62
+ try:
63
+ d = dt.datetime.fromisoformat(txt) + dt.timedelta(hours=8)
64
+ return d.date().isoformat()
65
+ except Exception:
66
+ return str(s)[:10]
67
+
68
+
69
+ def _adapt_payload_for_reward(app, payload):
70
+ return payload
71
+
72
+
73
+ def go(app_name):
74
+ if app_name in _GO_CACHE:
75
+ return _GO_CACHE[app_name]
76
+ base = APP_URLS.get(app_name)
77
+ if not base:
78
+ print(f'CRITICAL: unknown app {app_name!r} (no URL mapped)')
79
+ print('REWARD: 0.0')
80
+ sys.exit(0)
81
+ try:
82
+ resp = requests.get(f'{base}/go?sid={sid}', timeout=15)
83
+ resp.raise_for_status()
84
+ payload = resp.json()
85
+ except Exception as e:
86
+ print(f'CRITICAL: cannot fetch {app_name} go state: {e}')
87
+ print('REWARD: 0.0')
88
+ sys.exit(0)
89
+ payload = _adapt_payload_for_reward(app_name, payload)
90
+ _GO_CACHE[app_name] = payload
91
+ return payload
92
+
93
+
94
+ def _inc_map(state):
95
+ out = {}
96
+ for t in (state.get('incidents') or []):
97
+ if isinstance(t, dict):
98
+ out[t.get('sys_id')] = t
99
+ return out
100
+
101
+
102
+ def _teams_channel_messages(state, channel_id):
103
+ msgs = state.get('messages')
104
+ if isinstance(msgs, dict) and isinstance(msgs.get(channel_id), list):
105
+ return [m for m in msgs[channel_id] if isinstance(m, dict)]
106
+ return []
107
+
108
+
109
+ # ===========================================================================
110
+ def reward(go):
111
+ W_ASSIGN = 0.35
112
+ W_STATE = 0.15
113
+ W_BRIDGE = 0.15
114
+ W_MISS = 0.25
115
+ W_PTO = 0.10
116
+
117
+ # ---- 1) answer key (on the calendar adapter) ----
118
+ cal = go('google_calendar')
119
+ cal_init = cal.get('initial_state', {}) if isinstance(cal.get('initial_state'), dict) else {}
120
+ cal_cur = cal.get('current_state', {}) if isinstance(cal.get('current_state'), dict) else {}
121
+ adapter = cal_init.get('_task_adapter', {}) if isinstance(cal_init.get('_task_adapter'), dict) else {}
122
+
123
+ assign_ids = set(adapter.get('assign_ids') or [])
124
+ p1_ids = list(adapter.get('p1_ids') or [])
125
+ assignee_by_id = adapter.get('assignee_by_id') if isinstance(adapter.get('assignee_by_id'), dict) else {}
126
+ bridge_events = adapter.get('bridge_events') if isinstance(adapter.get('bridge_events'), list) else []
127
+ bridge_date = adapter.get('bridge_event_date')
128
+ missing_id = adapter.get('missing_owner_id')
129
+ missing_assignee = norm(adapter.get('missing_owner_assignee'))
130
+ pto_id = adapter.get('pto_incident_id')
131
+ in_progress_state = adapter.get('in_progress_state', 2)
132
+ n_assign = len(assign_ids)
133
+ if n_assign == 0:
134
+ print('DEBUG_SN_ONCALL fatal=no_assign_ids total=0.0')
135
+ return 0.0
136
+
137
+ # ---- 2) ServiceNow: assignment diff (only newly-assigned New incidents count) ----
138
+ sn = go('servicenow')
139
+ sn_init = sn.get('initial_state', {}) if isinstance(sn.get('initial_state'), dict) else {}
140
+ sn_cur = sn.get('current_state', {}) if isinstance(sn.get('current_state'), dict) else {}
141
+ init_i = _inc_map(sn_init)
142
+ cur_i = _inc_map(sn_cur)
143
+
144
+ correct_assign = 0
145
+ wrongly_assign = 0
146
+ for iid, inc in cur_i.items():
147
+ cur_a = norm(inc.get('assigned_to'))
148
+ init_a = norm(init_i.get(iid, {}).get('assigned_to'))
149
+ if not cur_a or cur_a == init_a:
150
+ continue # no new assignment
151
+ if iid in assign_ids and cur_a == norm(assignee_by_id.get(iid)):
152
+ correct_assign += 1
153
+ else:
154
+ wrongly_assign += 1
155
+ assign_score = frac(correct_assign, n_assign + wrongly_assign)
156
+ s_assign = W_ASSIGN * assign_score
157
+
158
+ # ---- 3) state correctness: the 8 -> In Progress ----
159
+ state_ok = sum(1 for iid in assign_ids
160
+ if int(cur_i.get(iid, {}).get('state', -1)) == int(in_progress_state))
161
+ state_score = frac(state_ok, n_assign)
162
+ s_state = W_STATE * state_score
163
+
164
+ # ---- 4) P1 bridge: Teams post + Calendar bridge event (title AND date) ----
165
+ # review #3: the bridge event must match its title ('Bridge: <INC>') AND be dated the
166
+ # incident date, matching the instruction — not just any event with that title.
167
+ teams = go('microsoft_teams')
168
+ tcur = teams.get('current_state', {}) if isinstance(teams.get('current_state'), dict) else {}
169
+ tinit = teams.get('initial_state', {}) if isinstance(teams.get('initial_state'), dict) else {}
170
+ init_msg_ids = {m.get('messageId') for m in _teams_channel_messages(tinit, 'ch_incidents')}
171
+ new_msgs = [m for m in _teams_channel_messages(tcur, 'ch_incidents')
172
+ if m.get('messageId') not in init_msg_ids and norm(m.get('content'))]
173
+ cur_events = cal_cur.get('events', []) or []
174
+
175
+ bridge_ok = 0
176
+ for be in bridge_events:
177
+ num = norm(be.get('number'))
178
+ title = norm(be.get('title'))
179
+ want_date = be.get('date') or bridge_date
180
+ posted = any(num in norm(m.get('content')) for m in new_msgs)
181
+ evented = any(norm(ev.get('title')) == title and _date_key(ev.get('start')) == want_date
182
+ for ev in cur_events)
183
+ if posted and evented:
184
+ bridge_ok += 1
185
+ bridge_score = frac(bridge_ok, len(bridge_events)) if bridge_events else 0.0
186
+ s_bridge = W_BRIDGE * bridge_score
187
+
188
+ # ---- 5) missing-owner correctness: INC0007 assigned to the engineer named in Teams history ----
189
+ # review #2: the answer is pre-seeded in the #incidents history (no live ask scored).
190
+ miss_ok = (norm(cur_i.get(missing_id, {}).get('assigned_to')) == missing_assignee)
191
+ s_miss = W_MISS * (1.0 if miss_ok else 0.0)
192
+
193
+ # ---- 6) PTO-reroute correctness: PTO incident assigned to the BACKUP ----
194
+ pto_ok = (norm(cur_i.get(pto_id, {}).get('assigned_to')) == norm(assignee_by_id.get(pto_id)))
195
+ s_pto = W_PTO * (1.0 if pto_ok else 0.0)
196
+
197
+ score = clamp01(s_assign + s_state + s_bridge + s_miss + s_pto)
198
+
199
+ print(
200
+ 'DEBUG_SN_ONCALL '
201
+ f'n_assign={n_assign} correct={correct_assign} wrongly={wrongly_assign} '
202
+ f'assign={round(assign_score, 4)} state_ok={state_ok}/{n_assign} '
203
+ f'bridge_ok={bridge_ok}/{len(bridge_events)} miss_ok={miss_ok} pto_ok={pto_ok} '
204
+ f'w_assign={round(s_assign, 4)} w_state={round(s_state, 4)} w_bridge={round(s_bridge, 4)} '
205
+ f'w_miss={round(s_miss, 4)} w_pto={round(s_pto, 4)} '
206
+ f'total={round(score, 4)}'
207
+ )
208
+ return score
209
+
210
+
211
+ try:
212
+ score = float(reward(go))
213
+ except Exception as exc:
214
+ print(f'ERROR: reward() raised {exc!r}')
215
+ score = 0.0
216
+
217
+ score = clamp01(score)
218
+ print(f'\nREWARD: {round(score, 4)}')
hr_payroll_approval_006__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_payroll_approval_006__long/initial_setup.py ADDED
@@ -0,0 +1,782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: W06 — Payroll specialist batch approval + chase dispatch
3
+ Task ID: hr_payroll_approval_006__long
4
+ Persona: Payroll Specialist Niko
5
+ Mocks: workday_mock (L2 anchor) , asana_mock (L1) , microsoft_teams_mock , gmail_mock
6
+
7
+ Ground-truth embedding (read by reward.py from initial_state):
8
+ - Workday tasks[*]._expected_approve on every Pending inbox task
9
+ (True -> agent should approve it via the bulk-approve bar;
10
+ False -> agent must LEAVE it pending and open a follow-up instead).
11
+ - On every _expected_approve==False task: tasks[*]._chase_title (the Asana
12
+ follow-up task title the agent should create) and tasks[*]._expected_priority
13
+ ('High' for over-cap timesheets, 'Medium' for non-compliant leave).
14
+ Observable outputs kept ABSENT at injection (Rule 3):
15
+ - all 10 pending inbox tasks still have status=='Pending' (none decided)
16
+ - Asana has NO 'Follow up: <name>' task — agent must create each one and set
17
+ its Priority custom field
18
+ - microsoft_teams 'Payroll' channel has zero messages
19
+ - gmail has no SENT notification email
20
+ """
21
+ import os
22
+ import shlex
23
+ import subprocess
24
+ import time
25
+ import uuid
26
+
27
+ import requests
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
+
35
+ # ===========================================================================
36
+ # WORKDAY (L2 anchor: Inbox bulk-approve bar — renders only when >=1 pending
37
+ # task is checked; handleBulkApprove COMPLETE_TASKs the selected subset).
38
+ #
39
+ # Approval rule (documented in instruction; encoded here only via the
40
+ # _expected_approve answer key, NOT re-derived in reward):
41
+ # APPROVE a pending request if it is in-policy:
42
+ # - a weekly timesheet of 40 hours or fewer, OR
43
+ # - a leave request that is within the employee's balance AND does not
44
+ # overlap the month-end payroll blackout.
45
+ # DO NOT APPROVE (leave pending + open a follow-up) if it breaks policy:
46
+ # - a timesheet logging more than 40 hours (unauthorised overtime), OR
47
+ # - leave that exceeds the remaining balance or overlaps the blackout.
48
+ # ===========================================================================
49
+ def wd_employee(eid, name, title, dept, dept_id, mgr='emp_niko'):
50
+ first = name.split()[0]
51
+ return {
52
+ 'id': eid, 'name': name,
53
+ 'email': f'{name.lower().replace(" ", ".")}@acmecorp.com',
54
+ 'phone': '+1 (415) 555-0100', 'role': 'Employee', 'department': dept,
55
+ 'departmentId': dept_id,
56
+ 'avatar': f'https://ui-avatars.com/api/?name={first}&background=0875E1&color=fff&size=128',
57
+ 'managerId': mgr, 'title': title, 'location': 'San Francisco, CA',
58
+ 'joinDate': '2021-05-01', 'employeeType': 'Full-Time',
59
+ 'birthday': '1990-01-01', 'workAnniversary': '2021-05-01',
60
+ }
61
+
62
+
63
+ def wd_task(task_id, sub_type, description, initiator, business_process,
64
+ due_date, priority, expected_approve,
65
+ chase_title=None, expected_priority=None):
66
+ """A Pending inbox approval. Carries the hidden answer key."""
67
+ rec = {
68
+ 'taskId': task_id, 'employeeId': 'emp_niko', 'type': 'Approval',
69
+ 'subType': sub_type, 'description': description, 'status': 'Pending',
70
+ 'dueDate': due_date, 'createdDate': '2026-06-26',
71
+ 'relatedId': None, 'initiator': initiator,
72
+ 'businessProcess': business_process, 'priority': priority,
73
+ 'comments': [],
74
+ '_expected_approve': expected_approve, # hidden answer key
75
+ }
76
+ if chase_title is not None:
77
+ rec['_chase_title'] = chase_title
78
+ if expected_priority is not None:
79
+ rec['_expected_priority'] = expected_priority
80
+ return rec
81
+
82
+
83
+ NIKO = {
84
+ 'id': 'emp_niko', 'name': 'Niko Bellic',
85
+ 'email': 'niko.bellic@acmecorp.com', 'phone': '+1 (415) 555-0188',
86
+ 'role': 'Manager', 'department': 'Finance', 'departmentId': 'dept004',
87
+ 'avatar': 'https://ui-avatars.com/api/?name=Niko+Bellic&background=0875E1&color=fff&size=128',
88
+ 'managerId': 'emp_dir', 'title': 'Payroll Specialist',
89
+ 'location': 'San Francisco, CA', 'joinDate': '2019-02-11',
90
+ 'employeeType': 'Full-Time', 'skills': ['Payroll', 'Compliance'],
91
+ 'birthday': '1986-09-12', 'workAnniversary': '2019-02-11',
92
+ }
93
+ WD_DIRECTOR = {
94
+ 'id': 'emp_dir', 'name': 'Sandra Voss', 'email': 'sandra.voss@acmecorp.com',
95
+ 'phone': '+1 (415) 555-0101', 'role': 'Director', 'department': 'Finance',
96
+ 'departmentId': 'dept004',
97
+ 'avatar': 'https://ui-avatars.com/api/?name=Sandra+Voss&background=7C3AED&color=fff&size=128',
98
+ 'managerId': None, 'title': 'Director of Finance',
99
+ 'location': 'San Francisco, CA', 'joinDate': '2016-01-04',
100
+ 'employeeType': 'Full-Time', 'birthday': '1980-03-03',
101
+ 'workAnniversary': '2016-01-04',
102
+ }
103
+
104
+ WD_EMPLOYEES = [
105
+ NIKO, WD_DIRECTOR,
106
+ # Tom Reed — payroll analyst on Niko's team; the exception-handoff email
107
+ # recipient. Present in the Workday Directory so his address is discoverable
108
+ # (the instruction names him but does not give his email).
109
+ wd_employee('emp110', 'Tom Reed', 'Payroll Analyst', 'Finance', 'dept004'),
110
+ wd_employee('emp101', 'Marcus Johnson', 'Backend Engineer', 'Engineering', 'dept001'),
111
+ wd_employee('emp102', 'Rachel Green', 'Data Analyst', 'Engineering', 'dept001'),
112
+ wd_employee('emp103', 'David Kim', 'Network Engineer', 'Engineering', 'dept001'),
113
+ wd_employee('emp104', 'Nina Patel', 'QA Engineer', 'Engineering', 'dept001'),
114
+ wd_employee('emp105', 'John Smith', 'Frontend Engineer', 'Engineering', 'dept001'),
115
+ wd_employee('emp106', 'Emily Chen', 'Product Designer', 'Design', 'dept002'),
116
+ wd_employee('emp107', 'Lisa Park', 'Marketing Lead', 'Marketing', 'dept003'),
117
+ wd_employee('emp108', 'James Wilson', 'Sales Rep', 'Marketing', 'dept003'),
118
+ wd_employee('emp109', 'Priya Nair', 'Recruiter', 'Human Resources', 'dept005'),
119
+ ]
120
+
121
+ WD_DEPARTMENTS = [
122
+ {'id': 'dept001', 'name': 'Engineering', 'headcount': 5, 'managerId': 'emp_dir'},
123
+ {'id': 'dept002', 'name': 'Design', 'headcount': 1, 'managerId': 'emp_dir'},
124
+ {'id': 'dept003', 'name': 'Marketing', 'headcount': 2, 'managerId': 'emp_dir'},
125
+ {'id': 'dept004', 'name': 'Finance', 'headcount': 3, 'managerId': 'emp_dir'},
126
+ {'id': 'dept005', 'name': 'Human Resources', 'headcount': 1, 'managerId': 'emp_dir'},
127
+ ]
128
+
129
+ # --- 12 PENDING approval tasks (the batch to triage) -----------------------
130
+ # 7 in-policy -> approve; 5 out-of-policy -> leave pending + chase.
131
+ #
132
+ # DESIGN (v2): descriptions give ONLY the raw facts — never the verdict. The
133
+ # agent must APPLY the policy itself:
134
+ # - timesheets list per-day hours; the agent sums them and compares to 40.
135
+ # - leave requests give only the raw date range; the agent must read the
136
+ # blackout window (Jun 29 - Jul 3) from the Workday announcement / the HR
137
+ # email — it is NOT repeated in the task — and compute the overlap.
138
+ # - over-balance leave states the request hours AND the employee's remaining
139
+ # balance for that leave type; the agent compares the two.
140
+ # Boundary traps: a timesheet of EXACTLY 40.0h is in-policy; 40.5h is not. A
141
+ # leave ending the day BEFORE the blackout is fine; one ending on its first day
142
+ # is not. So a "looks like a lot" heuristic fails — real arithmetic is required.
143
+ WD_PENDING = [
144
+ # ---- APPROVE: standard timesheets (sum <= 40h) ----
145
+ wd_task('wd_t1', 'Timesheet Approval',
146
+ 'Weekly timesheet for John Smith, week of Jun 22. Hours logged: Mon 8.0, Tue 8.0, Wed 8.0, Thu 8.0, Fri 8.0.',
147
+ 'John Smith', 'Submit Timesheet', '2026-07-01', 'Normal',
148
+ expected_approve=True),
149
+ wd_task('wd_t2', 'Timesheet Approval',
150
+ 'Weekly timesheet for Emily Chen, week of Jun 22. Hours logged: Mon 7.5, Tue 8.0, Wed 8.0, Thu 7.5, Fri 7.5.',
151
+ 'Emily Chen', 'Submit Timesheet', '2026-07-01', 'Normal',
152
+ expected_approve=True),
153
+ # boundary: exactly 40.0h across 6 days -> still in policy (approve)
154
+ wd_task('wd_t3', 'Timesheet Approval',
155
+ 'Weekly timesheet for Lisa Park, week of Jun 22. Hours logged: Mon 7.0, Tue 7.0, Wed 7.0, Thu 7.0, Fri 6.0, Sat 6.0.',
156
+ 'Lisa Park', 'Submit Timesheet', '2026-07-01', 'Normal',
157
+ expected_approve=True),
158
+ # ---- APPROVE: in-policy leave (no blackout overlap, within balance) ----
159
+ wd_task('wd_t4', 'Time Off Request',
160
+ 'Vacation request — James Wilson, Jul 13-15 (24 hours requested). Remaining vacation balance: 80 hours.',
161
+ 'James Wilson', 'Request Time Off', '2026-07-08', 'Normal',
162
+ expected_approve=True),
163
+ wd_task('wd_t5', 'Time Off Request',
164
+ 'Sick leave — Sandra Voss, Jul 6 (8 hours requested). Remaining sick balance: 40 hours.',
165
+ 'Sandra Voss', 'Request Time Off', '2026-07-06', 'Normal',
166
+ expected_approve=True),
167
+ wd_task('wd_t6', 'Time Off Request',
168
+ 'Personal day — Priya Nair, Jul 8 (8 hours requested). Remaining personal balance: 16 hours.',
169
+ 'Priya Nair', 'Request Time Off', '2026-07-07', 'Low',
170
+ expected_approve=True),
171
+ # boundary: leave ending the day BEFORE the blackout starts -> approve
172
+ wd_task('wd_t11', 'Time Off Request',
173
+ 'Vacation request — Emily Chen, Jun 26-28 (24 hours requested). Remaining vacation balance: 64 hours.',
174
+ 'Emily Chen', 'Request Time Off', '2026-06-25', 'Normal',
175
+ expected_approve=True),
176
+ # ---- DO NOT APPROVE: over-cap timesheets (sum > 40h) -> chase High ----
177
+ wd_task('wd_t7', 'Timesheet Approval',
178
+ 'Weekly timesheet for Marcus Johnson, week of Jun 22. Hours logged: Mon 10.0, Tue 10.0, Wed 9.0, Thu 9.0, Fri 8.0, Sat 6.0.',
179
+ 'Marcus Johnson', 'Submit Timesheet', '2026-07-01', 'High',
180
+ expected_approve=False,
181
+ chase_title='Follow up: Marcus Johnson', expected_priority='High'),
182
+ # boundary: 40.5h (just over) -> NOT in policy, chase High
183
+ wd_task('wd_t8', 'Timesheet Approval',
184
+ 'Weekly timesheet for Rachel Green, week of Jun 22. Hours logged: Mon 8.5, Tue 8.0, Wed 8.0, Thu 8.0, Fri 8.0.',
185
+ 'Rachel Green', 'Submit Timesheet', '2026-07-01', 'High',
186
+ expected_approve=False,
187
+ chase_title='Follow up: Rachel Green', expected_priority='High'),
188
+ # ---- DO NOT APPROVE: non-compliant leave -> chase Medium ----
189
+ # overlaps blackout (Jun 29 - Jul 3): agent must read blackout elsewhere
190
+ wd_task('wd_t9', 'Time Off Request',
191
+ 'Vacation request — David Kim, Jun 29 - Jul 2 (32 hours requested). Remaining vacation balance: 96 hours.',
192
+ 'David Kim', 'Request Time Off', '2026-06-26', 'High',
193
+ expected_approve=False,
194
+ chase_title='Follow up: David Kim', expected_priority='Medium'),
195
+ # boundary: ends ON the blackout's first day -> overlaps -> chase Medium
196
+ wd_task('wd_t12', 'Time Off Request',
197
+ 'Vacation request — John Smith, Jun 27-29 (24 hours requested). Remaining vacation balance: 72 hours.',
198
+ 'John Smith', 'Request Time Off', '2026-06-26', 'Normal',
199
+ expected_approve=False,
200
+ chase_title='Follow up: John Smith', expected_priority='Medium'),
201
+ # over balance: 48h requested vs 16h remaining -> chase Medium
202
+ wd_task('wd_t10', 'Time Off Request',
203
+ 'Vacation request — Nina Patel, Jul 6-13 (48 hours requested). Remaining vacation balance: 16 hours.',
204
+ 'Nina Patel', 'Request Time Off', '2026-07-02', 'High',
205
+ expected_approve=False,
206
+ chase_title='Follow up: Nina Patel', expected_priority='Medium'),
207
+ ]
208
+
209
+ # --- NOISE: already-processed tasks (Archive tab, no checkbox, not scored) --
210
+ WD_NOISE = [
211
+ {'taskId': 'wd_n1', 'employeeId': 'emp_niko', 'type': 'Approval',
212
+ 'subType': 'Timesheet Approval',
213
+ 'description': 'Approve weekly timesheet — John Smith, week of Jun 15. Already approved.',
214
+ 'status': 'Completed', 'dueDate': '2026-06-22', 'createdDate': '2026-06-19',
215
+ 'relatedId': None, 'initiator': 'John Smith', 'businessProcess': 'Submit Timesheet',
216
+ 'priority': 'Normal', 'comments': []},
217
+ {'taskId': 'wd_n2', 'employeeId': 'emp_niko', 'type': 'Approval',
218
+ 'subType': 'Time Off Request',
219
+ 'description': 'Approve vacation — Marcus Johnson, May 5-7. Previously denied (blackout).',
220
+ 'status': 'Denied', 'dueDate': '2026-05-04', 'createdDate': '2026-05-01',
221
+ 'relatedId': None, 'initiator': 'Marcus Johnson', 'businessProcess': 'Request Time Off',
222
+ 'priority': 'Normal', 'comments': []},
223
+ ]
224
+
225
+ WD_TASKS = WD_PENDING + WD_NOISE
226
+
227
+ WORKDAY_STATE = {
228
+ 'currentUser': NIKO,
229
+ 'employees': WD_EMPLOYEES,
230
+ 'departments': WD_DEPARTMENTS,
231
+ 'timeEntries': [
232
+ {'entryId': 'te1', 'employeeId': 'emp_niko', 'date': '2026-06-24', 'hours': 8,
233
+ 'project': 'General', 'status': 'Approved', 'notes': ''},
234
+ ],
235
+ 'timeOffRequests': [
236
+ {'requestId': 'tr1', 'employeeId': 'emp108', 'type': 'Vacation',
237
+ 'startDate': '2026-07-13', 'endDate': '2026-07-15', 'status': 'Pending',
238
+ 'reason': 'Family trip', 'totalHours': 24, 'reviewedBy': None, 'reviewedDate': None},
239
+ ],
240
+ 'timeOffBalance': {'vacation': 120, 'sick': 40, 'personal': 16},
241
+ 'payroll': [
242
+ {'paystubId': 'ps1', 'employeeId': 'emp_niko', 'period': 'Jun 1 - Jun 15, 2026',
243
+ 'payDate': '2026-06-15', 'date': '2026-06-15', 'grossPay': 5576.92,
244
+ 'federalTax': 892.31, 'stateTax': 445.35, 'socialSecurity': 345.77,
245
+ 'medicare': 80.87, 'healthInsurance': 120.00, 'retirement401k': 278.85,
246
+ 'otherDeductions': 15.00, 'totalDeductions': 2178.15, 'netPay': 3398.77,
247
+ 'deductions': 2178.15},
248
+ ],
249
+ 'benefits': {
250
+ 'employeeId': 'emp_niko', 'enrollmentStatus': 'Complete',
251
+ 'plans': [
252
+ {'id': 'b1', 'type': 'Medical', 'name': 'Medical - PPO Plus',
253
+ 'provider': 'BlueCross BlueShield', 'coverageLevel': 'Employee Only',
254
+ 'employeeCost': 180.00, 'employerCost': 600.00, 'cost': 180.00,
255
+ 'status': 'Active', 'effectiveDate': '2024-01-01',
256
+ 'details': {'deductible': 1500, 'outOfPocketMax': 5000, 'copay': 25, 'coinsurance': 20}},
257
+ ],
258
+ 'dependents': [],
259
+ },
260
+ 'reviews': [],
261
+ 'goals': [],
262
+ 'tasks': WD_TASKS,
263
+ 'announcements': [
264
+ {'id': 'a1', 'title': 'Month-End Payroll Blackout', 'date': '2026-06-25',
265
+ 'content': 'Payroll blackout runs Jun 29 - Jul 3. No leave should be approved that overlaps these dates.',
266
+ 'category': 'HR', 'priority': 'High'},
267
+ ],
268
+ 'notifications': [
269
+ {'id': 'n1', 'type': 'task', 'title': 'Approvals waiting',
270
+ 'message': 'You have timesheet and leave approvals waiting in your inbox.',
271
+ 'timestamp': '2026-06-26T09:00:00.000Z', 'read': False, 'link': '/inbox'},
272
+ ],
273
+ 'clockStatus': {'isClockedIn': False, 'startTime': None},
274
+ }
275
+
276
+
277
+ # ===========================================================================
278
+ # ASANA (L1: per chase item, create a 'Follow up: <name>' task and set its
279
+ # Priority custom field — customFieldValues['field-1']). No follow-up task is
280
+ # pre-seeded; only unrelated noise tasks exist.
281
+ # ===========================================================================
282
+ def asana_user(uid, name, title, dept):
283
+ return {
284
+ 'userId': uid, 'name': name,
285
+ 'email': f'{name.lower().replace(" ", ".")}@company.com',
286
+ 'avatar': f'https://i.pravatar.cc/150?u={uid}', 'title': title,
287
+ 'department': dept, 'location': 'San Francisco, CA',
288
+ 'timezone': 'PST', 'theme': 'light',
289
+ }
290
+
291
+
292
+ ASANA_NIKO = asana_user('user-0', 'Niko Bellic', 'Payroll Specialist', 'Finance')
293
+ ASANA_USERS = [
294
+ ASANA_NIKO,
295
+ asana_user('user-1', 'Sandra Voss', 'Director of Finance', 'Finance'),
296
+ asana_user('user-2', 'Tom Reed', 'Payroll Analyst', 'Finance'),
297
+ ]
298
+
299
+ ASANA_PROJECT = {
300
+ 'projectId': 'project-payroll', 'name': 'Payroll Operations', 'teamId': 'team-1',
301
+ 'description': 'Payroll cycle tasks, exceptions, and follow-ups.',
302
+ 'color': '#4186E0', 'icon': 'https://i.pravatar.cc/40?u=payroll',
303
+ 'ownerId': 'user-0', 'memberIds': ['user-0', 'user-1', 'user-2'],
304
+ 'sections': [
305
+ {'sectionId': 'section-p-1', 'name': 'Follow-ups', 'collapsed': False},
306
+ {'sectionId': 'section-p-2', 'name': 'In Progress', 'collapsed': False},
307
+ {'sectionId': 'section-p-3', 'name': 'Done', 'collapsed': False},
308
+ ],
309
+ 'customFields': [
310
+ {'id': 'field-1', 'name': 'Priority', 'type': 'dropdown',
311
+ 'options': ['High', 'Medium', 'Low']},
312
+ ],
313
+ 'privacy': 'public', 'startDate': '2026-06-01', 'dueDate': '2026-07-31',
314
+ 'archived': False, 'starred': True,
315
+ 'createdDate': '2026-06-01T00:00:00Z', 'modifiedDate': '2026-06-25T00:00:00Z',
316
+ }
317
+
318
+
319
+ def asana_task(task_id, name, section_id, priority=None):
320
+ rec = {
321
+ 'taskId': task_id, 'name': name, 'projectId': 'project-payroll',
322
+ 'sectionId': section_id, 'description': '', 'assigneeId': 'user-0',
323
+ 'creatorId': 'user-0', 'completed': False, 'dependencies': [],
324
+ 'tags': [], 'attachmentIds': [], 'customFieldValues': {},
325
+ 'likeCount': 0, 'createdDate': '2026-06-20T00:00:00Z',
326
+ 'modifiedDate': '2026-06-20T00:00:00Z',
327
+ }
328
+ if priority is not None:
329
+ rec['customFieldValues']['field-1'] = priority
330
+ return rec
331
+
332
+
333
+ # Noise tasks only — NOT the 'Follow up: <name>' chase tasks.
334
+ ASANA_TASKS = [
335
+ asana_task('task-noise-1', 'Reconcile June payroll register', 'section-p-2', 'Medium'),
336
+ asana_task('task-noise-2', 'File Q2 941 tax deposit', 'section-p-1', 'High'),
337
+ asana_task('task-noise-3', 'Update direct-deposit forms batch', 'section-p-3'),
338
+ ]
339
+
340
+ ASANA_STATE = {
341
+ 'currentUser': ASANA_NIKO,
342
+ 'users': ASANA_USERS,
343
+ 'teams': [
344
+ {'teamId': 'team-1', 'name': 'Finance', 'description': 'Finance & payroll',
345
+ 'memberIds': ['user-0', 'user-1', 'user-2'], 'ownerId': 'user-1',
346
+ 'privacy': 'public', 'createdDate': '2026-01-01T00:00:00Z'},
347
+ ],
348
+ 'projects': [ASANA_PROJECT],
349
+ 'tasks': ASANA_TASKS,
350
+ 'comments': [],
351
+ 'portfolios': [],
352
+ 'goals': [],
353
+ 'notifications': [],
354
+ 'attachments': [],
355
+ }
356
+
357
+
358
+ # ===========================================================================
359
+ # MICROSOFT TEAMS (post a summary to the 'Payroll' channel — Posts only;
360
+ # Calendar/Files untouched to avoid the known crash). Channel starts empty.
361
+ # ===========================================================================
362
+ def teams_user(uid, name, title, dept):
363
+ first, last = (name.split() + [''])[:2]
364
+ return {
365
+ 'userId': uid, 'displayName': name, 'firstName': first, 'lastName': last,
366
+ 'email': f'{name.lower().replace(" ", ".")}@contoso.com',
367
+ 'avatar': f'https://i.pravatar.cc/150?u={uid}', 'jobTitle': title,
368
+ 'department': dept, 'location': 'Seattle, WA', 'phone': '+1 (206) 555-0110',
369
+ 'presence': 'available', 'statusMessage': '', 'statusEmoji': '',
370
+ 'outOfOffice': False, 'timezone': 'America/Los_Angeles',
371
+ }
372
+
373
+
374
+ TEAMS_NIKO = teams_user('user_1', 'Niko Bellic', 'Payroll Specialist', 'Finance')
375
+ TEAMS_USERS = [
376
+ TEAMS_NIKO,
377
+ teams_user('user_2', 'Sandra Voss', 'Director of Finance', 'Finance'),
378
+ teams_user('user_3', 'Tom Reed', 'Payroll Analyst', 'Finance'),
379
+ ]
380
+
381
+ TEAMS_STATE = {
382
+ 'currentUser': TEAMS_NIKO,
383
+ 'users': TEAMS_USERS,
384
+ 'teams': [
385
+ {'teamId': 'team_fin', 'displayName': 'Finance Ops', 'description': 'Finance & payroll collaboration',
386
+ 'avatar': '', 'avatarColor': '#4A90D9', 'avatarInitials': 'FO',
387
+ 'visibility': 'private', 'isArchived': False, 'isFavorite': True,
388
+ 'createdDateTime': '2024-06-15T10:00:00Z',
389
+ 'members': ['user_1', 'user_2', 'user_3'], 'owners': ['user_2'],
390
+ 'channels': ['ch_general', 'ch_payroll'],
391
+ 'settings': {'allowMemberCreateChannels': True, 'allowMemberDeleteMessages': True,
392
+ 'allowGiphy': True, 'allowStickers': True, 'allowMemes': True}},
393
+ ],
394
+ 'channels': [
395
+ {'channelId': 'ch_general', 'teamId': 'team_fin', 'displayName': 'General',
396
+ 'description': 'General finance discussion', 'membershipType': 'standard',
397
+ 'isFavoriteByDefault': True, 'isPinned': False, 'isMuted': False, 'unreadCount': 0,
398
+ 'lastMessagePreview': 'Reminder: month-end blackout starts Jun 29.',
399
+ 'lastMessageTimestamp': '2026-06-25T15:00:00.000Z',
400
+ 'createdDateTime': '2024-06-15T10:00:00Z', 'members': [],
401
+ 'tabs': [{'tabId': 'tab_posts_g', 'displayName': 'Posts', 'type': 'posts', 'isDefault': True}],
402
+ 'pinnedMessages': []},
403
+ {'channelId': 'ch_payroll', 'teamId': 'team_fin', 'displayName': 'Payroll',
404
+ 'description': 'Payroll approvals and exceptions', 'membershipType': 'standard',
405
+ 'isFavoriteByDefault': False, 'isPinned': False, 'isMuted': False, 'unreadCount': 0,
406
+ 'lastMessagePreview': '', 'lastMessageTimestamp': '2026-06-25T09:00:00.000Z',
407
+ 'createdDateTime': '2026-06-01T10:00:00Z', 'members': [],
408
+ 'tabs': [{'tabId': 'tab_posts_p', 'displayName': 'Posts', 'type': 'posts', 'isDefault': True}],
409
+ 'pinnedMessages': []},
410
+ ],
411
+ 'chats': [],
412
+ 'messages': {
413
+ 'ch_general': [
414
+ {'messageId': 'msg_g1', 'containerId': 'ch_general', 'containerType': 'channel',
415
+ 'senderId': 'user_2', 'content': 'Reminder: month-end blackout starts Jun 29.',
416
+ 'contentType': 'text', 'messageType': 'message',
417
+ 'createdDateTime': '2026-06-25T15:00:00.000Z', 'lastEditedDateTime': None,
418
+ 'deletedDateTime': None, 'importance': 'normal', 'subject': '',
419
+ 'replyToId': None, 'reactions': [], 'mentions': [], 'attachments': [],
420
+ 'isBookmarked': False},
421
+ ],
422
+ 'ch_payroll': [],
423
+ },
424
+ 'meetings': [],
425
+ 'calls': [],
426
+ 'files': [],
427
+ 'notifications': [],
428
+ 'settings': {
429
+ 'theme': 'light', 'language': 'en-US',
430
+ 'notifications': {'showMessagePreviews': True, 'playSound': True, 'showBadgeCount': True,
431
+ 'muteAll': False, 'quietHoursEnabled': False,
432
+ 'quietHoursStart': '22:00', 'quietHoursEnd': '07:00'},
433
+ 'privacy': {'readReceipts': True, 'showPresence': True},
434
+ 'display': {'density': 'comfortable', 'showChannelPreview': True},
435
+ },
436
+ 'ui': {'activeView': 'chat', 'activeTeamId': None, 'activeChannelId': None,
437
+ 'activeChatId': None, 'activeThreadMessageId': None, 'isThreadPanelOpen': False,
438
+ 'isDetailsPanelOpen': False, 'searchQuery': '', 'searchResults': None},
439
+ }
440
+
441
+
442
+ # ===========================================================================
443
+ # GMAIL (record hub: send a notification email; no SENT email pre-seeded).
444
+ # ===========================================================================
445
+ GMAIL_STATE = {
446
+ 'user': {'userId': 'u1', 'username': 'Niko Bellic', 'email': 'niko.bellic@acmecorp.com',
447
+ 'avatar': 'https://i.pravatar.cc/150?u=niko'},
448
+ 'emails': [
449
+ {'id': 'email_1', 'threadId': 'thread_1',
450
+ 'from': {'name': 'Sandra Voss', 'email': 'sandra.voss@acmecorp.com'},
451
+ 'to': [{'name': 'Niko Bellic', 'email': 'niko.bellic@acmecorp.com'}],
452
+ 'cc': [], 'bcc': [],
453
+ 'subject': 'This week’s timesheet & leave approvals',
454
+ 'body': '<p>Niko, please clear the approval queue in Workday today and flag anything that breaks policy. Thanks!</p>',
455
+ 'snippet': 'Please clear the approval queue in Workday today.',
456
+ 'timestamp': '2026-06-26T08:30:00Z', 'read': False, 'starred': False,
457
+ 'important': True, 'labels': ['l1'], 'category': 'primary', 'folder': 'inbox',
458
+ 'attachments': []},
459
+ {'id': 'email_2', 'threadId': 'thread_2',
460
+ 'from': {'name': 'Acme HR', 'email': 'hr@acmecorp.com'},
461
+ 'to': [{'name': 'Niko Bellic', 'email': 'niko.bellic@acmecorp.com'}],
462
+ 'cc': [], 'bcc': [],
463
+ 'subject': 'Payroll blackout: Jun 29 – Jul 3',
464
+ 'body': '<p>The month-end payroll blackout runs Jun 29 through Jul 3. Do not approve leave overlapping these dates.</p>',
465
+ 'snippet': 'The month-end payroll blackout runs Jun 29 through Jul 3.',
466
+ 'timestamp': '2026-06-25T12:00:00Z', 'read': True, 'starred': False,
467
+ 'important': False, 'labels': ['l1'], 'category': 'primary', 'folder': 'inbox',
468
+ 'attachments': []},
469
+ ],
470
+ 'labels': [
471
+ {'id': 'l1', 'name': 'Work', 'color': '#ef4444'},
472
+ {'id': 'l2', 'name': 'Personal', 'color': '#3b82f6'},
473
+ {'id': 'l3', 'name': 'Travel', 'color': '#22c55e'},
474
+ {'id': 'l4', 'name': 'Finance', 'color': '#eab308'},
475
+ ],
476
+ 'drafts': [],
477
+ }
478
+
479
+
480
+ # ===========================================================================
481
+ # Inject (each mock gets its FULL top-level schema; missing keys -> blank page)
482
+ # ===========================================================================
483
+ APP_STATES = [
484
+ ('http://28.7.184.198:8192', WORKDAY_STATE), # workday_mock (L2 anchor)
485
+ ('http://28.7.184.198:8114', ASANA_STATE), # asana_mock (L1)
486
+ ('http://28.7.184.198:8162', TEAMS_STATE), # microsoft_teams_mock
487
+ ('http://28.7.184.198:8138', GMAIL_STATE), # gmail_mock
488
+ ]
489
+
490
+ for placeholder, state in APP_STATES:
491
+ resp = requests.post(
492
+ f'{placeholder}/post?sid={sid}',
493
+ json={'action': 'set', 'state': state},
494
+ timeout=30,
495
+ )
496
+ assert resp.status_code == 200, (
497
+ f'State injection failed for {placeholder}: {resp.text}'
498
+ )
499
+ print(f'State injected: {placeholder} sid={sid}')
500
+
501
+ for placeholder, _ in APP_STATES:
502
+ go = requests.get(f'{placeholder}/go?sid={sid}', timeout=15).json()
503
+ assert go.get('initial_state') is not None, (
504
+ f'initial_state is None after injection for {placeholder}'
505
+ )
506
+ print(f'Verified initial_state set: {placeholder}')
507
+
508
+
509
+ def wait_mocks_ready(urls, sid, timeout=60, render_buffer=8):
510
+ """Pure-HTTP readiness: wait for every mock to serve its injected state.
511
+ No CDP / 9222 probing (that hangs on local review boxes)."""
512
+ import urllib.request as _urlreq
513
+ _opener = _urlreq.build_opener(_urlreq.ProxyHandler({}))
514
+ deadline = time.time() + timeout
515
+ todo = list(urls)
516
+ while todo and time.time() < deadline:
517
+ rest = []
518
+ for _u in todo:
519
+ try:
520
+ _r = _opener.open(f"{_u}/go?sid={sid}", timeout=5)
521
+ if _r.status == 200:
522
+ print(f" {_u}: ready")
523
+ continue
524
+ except Exception:
525
+ pass
526
+ rest.append(_u)
527
+ todo = rest
528
+ if todo:
529
+ time.sleep(2)
530
+ print(f" mocks ready: {len(urls) - len(todo)}/{len(urls)}"
531
+ + (f" (pending: {todo})" if todo else ""))
532
+ time.sleep(render_buffer)
533
+
534
+
535
+ # PATCHED_BY: patch_wait_mocks_loaded.py
536
+ def launch_gui(command, delay_sec=1.0):
537
+ """Launch a GUI command, fully detached from this script.
538
+
539
+ Inject --remote-debugging-port=1337 (and Chrome quiet flags) so that
540
+ wait_mocks_loaded's CDP phase can verify browser render below.
541
+ Idempotent: if the caller already specified a debug port, keep it.
542
+ """
543
+ env = os.environ.copy()
544
+ env['DISPLAY'] = ':0'
545
+ if isinstance(command, str):
546
+ _parts = shlex.split(command)
547
+ else:
548
+ _parts = list(command)
549
+ if (_parts and 'google-chrome' in _parts[0]
550
+ and not any(p.startswith('--remote-debugging-port') for p in _parts)):
551
+ _parts[1:1] = [
552
+ '--no-first-run',
553
+ '--no-default-browser-check',
554
+ '--remote-debugging-port=1337',
555
+ ]
556
+ subprocess.Popen(
557
+ _parts,
558
+ stdin=subprocess.DEVNULL,
559
+ stdout=subprocess.DEVNULL,
560
+ stderr=subprocess.DEVNULL,
561
+ env=env,
562
+ start_new_session=True,
563
+ )
564
+ time.sleep(delay_sec)
565
+
566
+
567
+ def wait_mocks_loaded(app_states, sid_value, timeout=90, render_buffer=12):
568
+ """2-phase readiness wait, mirrors cache/ae_pipeline_hygiene_004 style.
569
+
570
+ Phase 1 - Backend readiness:
571
+ Poll each mock's /state?sid=<sid> (preferred) or /go?sid=<sid>
572
+ (fallback) until it returns 200 with 'stored_state' or
573
+ 'initial_state' respectively, or until timeout.
574
+
575
+ Phase 2 - Browser render verification (via CDP + Playwright):
576
+ Connect to http://localhost:1337 (the --remote-debugging-port
577
+ injected by launch_gui above), wait for every open tab to reach
578
+ 'networkidle' AND to contain at least 20 DOM elements. This
579
+ guarantees the SPA fetched /go?sid= data AND actually painted,
580
+ not just that the mock backend is up.
581
+
582
+ Fallback:
583
+ If Playwright is missing or CDP cannot be reached, sleep for
584
+ `render_buffer` seconds as a best-effort delay so the screenshot
585
+ loop does not start on a still-blank tab.
586
+ """
587
+ import urllib.request as _urlreq
588
+ import time as _t
589
+ _urls = [p for p, _ in app_states]
590
+ _opener = _urlreq.build_opener(_urlreq.ProxyHandler({}))
591
+
592
+ # ---- Phase 1: backend readiness ----
593
+ _deadline = _t.time() + timeout
594
+ _todo = list(_urls)
595
+ while _todo and _t.time() < _deadline:
596
+ _rest = []
597
+ for _u in _todo:
598
+ _ok = False
599
+ for _path, _need in (('/state?sid=', b'stored_state'),
600
+ ('/go?sid=', b'initial_state')):
601
+ try:
602
+ _r = _opener.open(f"{_u}{_path}{sid_value}", timeout=5)
603
+ if _r.status == 200:
604
+ _body = _r.read()
605
+ if _need in _body:
606
+ _ok = True
607
+ break
608
+ except Exception:
609
+ pass
610
+ if _ok:
611
+ print(f" {_u}: backend ready")
612
+ continue
613
+ _rest.append(_u)
614
+ _todo = _rest
615
+ if _todo:
616
+ _t.sleep(2)
617
+ _done = len(_urls) - len(_todo)
618
+ _pend = f" (pending: {_todo})" if _todo else ""
619
+ print(f" mocks backend ready: {_done}/{len(_urls)}{_pend}")
620
+
621
+ # ---- Phase 2: browser render verification via CDP ----
622
+ _cdp_ok = False
623
+ try:
624
+ from playwright.sync_api import sync_playwright
625
+ _cdp_dl = _t.time() + max(15.0, _deadline - _t.time())
626
+ with sync_playwright() as _p:
627
+ _br = None
628
+ while _t.time() < _cdp_dl:
629
+ try:
630
+ _br = _p.chromium.connect_over_cdp('http://localhost:1337')
631
+ break
632
+ except Exception:
633
+ _t.sleep(0.5)
634
+ if _br is None:
635
+ print(" wait_mocks_loaded: CDP connect to :1337 failed; is Chrome up with --remote-debugging-port?")
636
+ else:
637
+ _n_expected = len(_urls)
638
+ _pages = []
639
+ _pg_dl = _t.time() + 15
640
+ _last_count = -1
641
+ _stable_since = None
642
+ while _t.time() < _pg_dl:
643
+ _pages = []
644
+ for _c in _br.contexts:
645
+ _pages.extend(_c.pages)
646
+ _cnt = len(_pages)
647
+ if _n_expected > 0 and _cnt >= _n_expected:
648
+ break
649
+ if _cnt > 0 and _cnt == _last_count:
650
+ if _stable_since is None:
651
+ _stable_since = _t.time()
652
+ elif _t.time() - _stable_since >= 1.5:
653
+ break
654
+ else:
655
+ _stable_since = None
656
+ _last_count = _cnt
657
+ _t.sleep(0.5)
658
+ _pages = []
659
+ for _c in _br.contexts:
660
+ _pages.extend(_c.pages)
661
+ if not _pages:
662
+ print(" wait_mocks_loaded: CDP connected but no open tabs found")
663
+ else:
664
+ print(f" wait_mocks_loaded: {len(_pages)} tab(s) open (expected {_n_expected}); polling render")
665
+ _MIN_ELEMS = 20
666
+ _verify_dl = _t.time() + 40.0 # bounded so total setup stays < VM 120s cap
667
+ for _pg in _pages: # bring each to front once to defeat background-tab render throttling
668
+ try:
669
+ _pg.bring_to_front()
670
+ except Exception:
671
+ pass
672
+ _pending = list(_pages)
673
+ while _pending and _t.time() < _verify_dl:
674
+ _still = []
675
+ for _pg in _pending:
676
+ _ttl = ""
677
+ try:
678
+ _ttl = _pg.title()
679
+ except Exception:
680
+ pass
681
+ try:
682
+ _n = _pg.evaluate("document.body ? document.querySelectorAll('*').length : 0")
683
+ except Exception:
684
+ _n = 0
685
+ if _n >= _MIN_ELEMS:
686
+ print(f" wait_mocks_loaded: tab {_ttl!r} rendered ({_n} elements)")
687
+ else:
688
+ _still.append(_pg)
689
+ _pending = _still
690
+ if _pending:
691
+ _t.sleep(2)
692
+ if not _pending:
693
+ _cdp_ok = True
694
+ else:
695
+ for _pg in _pending:
696
+ _ttl = ""
697
+ try:
698
+ _ttl = _pg.title()
699
+ except Exception:
700
+ pass
701
+ print(f" wait_mocks_loaded: WARNING tab {_ttl!r} still not rendered after poll, will fall back")
702
+ except ImportError:
703
+ print(" wait_mocks_loaded: playwright not installed; skipping CDP phase")
704
+ except Exception as _e:
705
+ print(f" wait_mocks_loaded: CDP phase error ({_e!r})")
706
+
707
+ if not _cdp_ok:
708
+ print(f" wait_mocks_loaded: falling back to render_buffer={render_buffer}s sleep")
709
+ _t.sleep(render_buffer)
710
+ else:
711
+ print(" wait_mocks_loaded: browser render verified, skipping render_buffer")
712
+
713
+
714
+ def _open_mock_tabs(app_states, sid_value):
715
+ """Open the first mock as the primary Chrome window, the rest as new tabs.
716
+
717
+ Uses launch_gui once per URL so that the macOS localizer regex-extract
718
+ (which grabs the FIRST quoted URL per call) still works correctly.
719
+ """
720
+ _urls = [p for p, _ in app_states]
721
+ if not _urls:
722
+ return
723
+ launch_gui(f'google-chrome "{_urls[0]}/?sid={sid_value}"', delay_sec=2.0)
724
+ for _u in _urls[1:]:
725
+ launch_gui(f'google-chrome --new-tab "{_u}/?sid={sid_value}"', delay_sec=1.0)
726
+
727
+
728
+
729
+ # PATCHED_BY: add_wait_for_mocks_loaded (colleague headless+playwright render gate)
730
+ def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0):
731
+ """Block until every mock serves injected state AND (best-effort) renders."""
732
+ import time as _t
733
+ deadline = _t.time() + timeout
734
+ pending = dict(mocks)
735
+ while pending and _t.time() < deadline:
736
+ for name in list(pending):
737
+ try:
738
+ r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5)
739
+ if r.status_code == 200 and r.json().get('initial_state') is not None:
740
+ del pending[name]
741
+ except Exception:
742
+ pass
743
+ if pending:
744
+ _t.sleep(1.0)
745
+ if pending:
746
+ print(f'WARN: mocks not ready within {timeout}s: {list(pending)}')
747
+ try:
748
+ from playwright.sync_api import sync_playwright
749
+ except ImportError:
750
+ print('WARN: playwright not installed; skipping render check, settle 3s')
751
+ _t.sleep(3.0)
752
+ return
753
+ with sync_playwright() as p:
754
+ try:
755
+ browser = p.chromium.launch(channel='chrome', headless=True,
756
+ args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'])
757
+ except Exception as e:
758
+ print(f'WARN: could not launch chrome for render check: {e}; settle 3s')
759
+ _t.sleep(3.0)
760
+ return
761
+ try:
762
+ for name, url in mocks.items():
763
+ page = browser.new_page()
764
+ try:
765
+ page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded', timeout=int(render_timeout * 1000))
766
+ page.wait_for_function(
767
+ "document.body && document.body.innerText.length > 50",
768
+ timeout=int(render_timeout * 1000))
769
+ print(f'[{name}] rendered OK')
770
+ except Exception as e:
771
+ print(f'WARN: [{name}] render check issue: {e}')
772
+ finally:
773
+ page.close()
774
+ finally:
775
+ browser.close()
776
+
777
+
778
+ # ref pattern (out_benchmark_cache): open visible tabs FIRST, then block until mocks render
779
+ _open_mock_tabs(APP_STATES, sid)
780
+ wait_for_mocks_loaded({u.rsplit(':', 1)[-1]: u for u, _ in APP_STATES}, sid, timeout=60, render_timeout=15)
781
+ wait_mocks_loaded(APP_STATES, sid, timeout=90, render_buffer=12)
782
+ print(f'GUI_READY: launched browser tabs for {len(APP_STATES)} apps')
hr_payroll_approval_006__long/reward.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: W06 — Payroll specialist batch approval + chase dispatch
3
+ Task ID: hr_payroll_approval_006__long
4
+ Persona: Payroll Specialist Niko
5
+ Mocks: workday_mock (L2 anchor) , asana_mock (L1) , microsoft_teams_mock , gmail_mock
6
+
7
+ Answer key (embedded in initial_state):
8
+ - workday tasks[*]._expected_approve on every Pending task (True/False).
9
+ - on each _expected_approve==False task: _chase_title (Asana follow-up title)
10
+ and _expected_priority ('High' over-cap timesheet | 'Medium' bad leave).
11
+
12
+ Scoring (sub-weights sum to 1.0):
13
+ 0.45 Workday bulk approval (L2 anchor): penalty-based recall over the
14
+ should-approve set. +1 for each in-policy task the agent actively
15
+ Completed; -1 for each out-of-policy (chase) task the agent wrongly
16
+ Completed; score = max(0, +sum) / n_approve. Untouched state scores 0
17
+ (so "approve nothing" earns nothing) and "approve everything" is
18
+ penalised (W04 lesson). Reachable only via the gated bulk-approve bar
19
+ (renders only when >=1 task is checked). NOTE (v2): task descriptions
20
+ give only raw facts (per-day hours / raw leave dates / balance); the
21
+ agent must APPLY the policy — sum hours vs 40, read the blackout window
22
+ from the announcement/email and compute date overlap, compare requested
23
+ hours vs balance — rather than read a pre-computed verdict.
24
+ 0.25 Asana follow-ups (recall, no penalty for extras): per chase item, an
25
+ Asana task titled 'Follow up: <name>' exists (half) with its Priority
26
+ custom field == _expected_priority (other half).
27
+ 0.15 Teams 'Payroll' channel (TWO posts, strict): 0.075 a summary post with
28
+ the EXACT approved/follow-up counts + 0.075 an exception-list post
29
+ naming every flagged employee (partial = fraction of names). No
30
+ non-empty fallback.
31
+ 0.15 Gmail (TWO sent emails, strict): 0.075 a summary to Sandra Voss
32
+ (sandra.voss@acmecorp.com) with the EXACT counts + 0.075 an exception
33
+ handoff to Tom Reed (tom.reed@acmecorp.com) naming every flagged
34
+ employee (partial = fraction of names). No "any sent email" fallback.
35
+ """
36
+ import re
37
+ import sys
38
+
39
+ import requests
40
+
41
+ # --- Read sid (fatal if missing) ---
42
+ try:
43
+ with open('/tmp/task_web_sid') as f:
44
+ sid = f.read().strip()
45
+ if not sid:
46
+ raise ValueError('sid is empty')
47
+ except Exception as e:
48
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
49
+ print('REWARD: 0.0')
50
+ sys.exit(0)
51
+
52
+ APP_URLS = {
53
+ 'workday': 'http://28.7.184.198:8192',
54
+ 'asana': 'http://28.7.184.198:8114',
55
+ 'teams': 'http://28.7.184.198:8162',
56
+ 'gmail': 'http://28.7.184.198:8138',
57
+ }
58
+ _GO_CACHE = {}
59
+
60
+
61
+ def go(app_name):
62
+ if app_name in _GO_CACHE:
63
+ return _GO_CACHE[app_name]
64
+ base = APP_URLS.get(app_name)
65
+ if not base:
66
+ print(f'CRITICAL: unknown app {app_name!r} (no URL placeholder mapped)')
67
+ print('REWARD: 0.0')
68
+ sys.exit(0)
69
+ try:
70
+ resp = requests.get(f'{base}/go?sid={sid}', timeout=15)
71
+ resp.raise_for_status()
72
+ payload = resp.json()
73
+ except Exception as e:
74
+ print(f'CRITICAL: cannot fetch {app_name} go state: {e}')
75
+ print('REWARD: 0.0')
76
+ sys.exit(0)
77
+ _GO_CACHE[app_name] = payload
78
+ return payload
79
+
80
+
81
+ # --- Shared utils ---
82
+ def clamp01(x):
83
+ return max(0.0, min(1.0, float(x)))
84
+
85
+
86
+ def frac(num, den):
87
+ return 0.0 if den == 0 else num / den
88
+
89
+
90
+ def norm(s):
91
+ return (str(s) if s is not None else '').strip().lower()
92
+
93
+
94
+ def _collapse_ws(s):
95
+ return re.sub(r'\s+', ' ', norm(s))
96
+
97
+
98
+ def _by_id(records, key):
99
+ out = {}
100
+ for r in records or []:
101
+ if isinstance(r, dict) and r.get(key) is not None:
102
+ out[r[key]] = r
103
+ return out
104
+
105
+
106
+ def _msg_text(msg):
107
+ return msg.get('content') or msg.get('text') or ''
108
+
109
+
110
+ def _teams_channel_messages(teams_state, channel_name):
111
+ channels = teams_state.get('channels', []) or []
112
+ target = None
113
+ for ch in channels:
114
+ if norm(ch.get('displayName')) == norm(channel_name) or norm(ch.get('name')) == norm(channel_name):
115
+ target = ch
116
+ break
117
+ if target is None:
118
+ return []
119
+ msg_map = teams_state.get('messages', {}) or {}
120
+ if isinstance(msg_map, dict):
121
+ return msg_map.get(target.get('channelId'), []) or []
122
+ return []
123
+
124
+
125
+ def _asana_priority(task):
126
+ cfv = task.get('customFieldValues', {}) or {}
127
+ return norm(cfv.get('field-1'))
128
+
129
+
130
+ def _names_present(text, names):
131
+ """How many of `names` appear in `text` (full name, case-insensitive)."""
132
+ t = norm(text)
133
+ return sum(1 for nm in names if norm(nm) in t)
134
+
135
+
136
+ def _counts_match(text, n_approve, n_chase):
137
+ """True iff the text states BOTH the approved count and the follow-up count
138
+ correctly, accepting either word order ('7 approved' or 'approved 7', etc.).
139
+ Strict on the numbers, lenient on phrasing."""
140
+ low = norm(text)
141
+ approve_kw = r'(?:approv\w*)'
142
+ chase_kw = r'(?:follow[- ]?ups?|flagged|exceptions?|pending|on hold|held)'
143
+
144
+ def _has(n, kw):
145
+ return bool(
146
+ re.search(rf'\b{n}\b[^.\n]{{0,30}}?{kw}', low) or
147
+ re.search(rf'{kw}[^.\n0-9]{{0,30}}?\b{n}\b', low)
148
+ )
149
+ return _has(n_approve, approve_kw) and _has(n_chase, chase_kw)
150
+
151
+
152
+ # =============================================================================
153
+ # Task-specific reward
154
+ # =============================================================================
155
+ def reward(go):
156
+ wd_i = go('workday').get('initial_state', {}) or {}
157
+ wd_c = go('workday').get('current_state', {}) or {}
158
+ asana_c = go('asana').get('current_state', {}) or {}
159
+ teams_c = go('teams').get('current_state', {}) or {}
160
+ gmail_c = go('gmail').get('current_state', {}) or {}
161
+
162
+ tasks_i = wd_i.get('tasks', []) or []
163
+ tasks_c_by_id = _by_id(wd_c.get('tasks', []), 'taskId')
164
+
165
+ # ---- Answer key: pending tasks carrying _expected_approve ----
166
+ pendings = [t for t in tasks_i
167
+ if norm(t.get('status')) == 'pending' and '_expected_approve' in t]
168
+ n = len(pendings)
169
+ if n == 0:
170
+ print('DEBUG_W06 no pending tasks with embedded answer key; nothing to score')
171
+ return 0.0
172
+
173
+ should_approve = [t for t in pendings if t.get('_expected_approve') is True]
174
+ should_chase = [t for t in pendings if t.get('_expected_approve') is False]
175
+ n_approve = len(should_approve)
176
+ n_chase = len(should_chase)
177
+
178
+ # Flagged employee names (from the chase answer key) — the exception list /
179
+ # handoff must name every one of these. Derive from _chase_title
180
+ # ('Follow up: <name>') so it stays correct across variants.
181
+ flagged_names = []
182
+ for t in should_chase:
183
+ ct = t.get('_chase_title') or ''
184
+ nm = ct.split(':', 1)[1].strip() if ':' in ct else ct.strip()
185
+ if nm:
186
+ flagged_names.append(nm)
187
+
188
+ # ---- 1) Workday bulk approval (L2 anchor) — 0.45 ----
189
+ # Penalty-based recall: reward actively approving the in-policy set, punish
190
+ # approving any out-of-policy (chase) task. Untouched inbox -> 0 (no free
191
+ # credit); blanket "approve all" -> heavily penalised (W04 lesson).
192
+ wd_correct = 0 # in-policy tasks correctly Completed
193
+ wd_wrong = 0 # out-of-policy tasks wrongly Completed
194
+ try:
195
+ for t in pendings:
196
+ cur = tasks_c_by_id.get(t['taskId'], {})
197
+ completed = norm(cur.get('status')) == 'completed'
198
+ if t.get('_expected_approve') is True and completed:
199
+ wd_correct += 1
200
+ elif t.get('_expected_approve') is False and completed:
201
+ wd_wrong += 1
202
+ except Exception as e:
203
+ print(f'DEBUG_W06 workday component error: {e!r}')
204
+ wd_score = clamp01(frac(wd_correct - wd_wrong, n_approve))
205
+
206
+ # ---- 2) Asana follow-ups (recall, no penalty for extras) — 0.25 ----
207
+ # Per chase item: title 'Follow up: <name>' exists (0.5) + Priority custom
208
+ # field == _expected_priority (0.5). Extra/wrong tasks never penalised.
209
+ asana_points = 0.0
210
+ try:
211
+ asana_tasks = asana_c.get('tasks', []) or []
212
+ for t in should_chase:
213
+ title = norm(t.get('_chase_title'))
214
+ exp_pri = norm(t.get('_expected_priority'))
215
+ if not title:
216
+ continue
217
+ hit = None
218
+ for at in asana_tasks:
219
+ if _collapse_ws(at.get('name')) == _collapse_ws(title):
220
+ hit = at
221
+ break
222
+ if hit is None:
223
+ # looser: any task whose name contains the chase title
224
+ for at in asana_tasks:
225
+ if title in _collapse_ws(at.get('name')):
226
+ hit = at
227
+ break
228
+ if hit is not None:
229
+ asana_points += 0.5
230
+ if exp_pri and _asana_priority(hit) == exp_pri:
231
+ asana_points += 0.5
232
+ except Exception as e:
233
+ print(f'DEBUG_W06 asana component error: {e!r}')
234
+ asana_score = frac(asana_points, n_chase) if n_chase else 1.0
235
+
236
+ # ---- 3) Teams 'Payroll' channel — 0.15 (two posts, strict) ----
237
+ # Requires TWO separate posts:
238
+ # 0.075 a summary post with the EXACT approved (n_approve) and follow-up
239
+ # (n_chase) counts.
240
+ # 0.075 an exception-list post naming EVERY flagged employee (all
241
+ # n_chase names present). Partial credit = fraction of names found.
242
+ # No non-empty-message fallback (v2: strict).
243
+ teams_summary_ok = 0.0
244
+ teams_list_frac = 0.0
245
+ try:
246
+ msgs = _teams_channel_messages(teams_c, 'Payroll')
247
+ texts = [(_msg_text(m) or '') for m in msgs if (_msg_text(m) or '').strip()]
248
+ for txt in texts:
249
+ if _counts_match(txt, n_approve, n_chase):
250
+ teams_summary_ok = 1.0
251
+ break
252
+ # exception-list post: the message naming the most flagged employees
253
+ if flagged_names:
254
+ best = max((_names_present(txt, flagged_names) for txt in texts), default=0)
255
+ teams_list_frac = frac(best, len(flagged_names))
256
+ else:
257
+ teams_list_frac = 1.0
258
+ except Exception as e:
259
+ print(f'DEBUG_W06 teams component error: {e!r}')
260
+ teams_ok = 0.5 * teams_summary_ok + 0.5 * teams_list_frac
261
+
262
+ # ---- 4) Gmail — 0.15 (two emails, strict) ----
263
+ # Requires TWO sent emails:
264
+ # 0.075 summary to Sandra Voss (sandra.voss@acmecorp.com) whose body
265
+ # carries the EXACT approved + follow-up counts.
266
+ # 0.075 exception handoff to Tom Reed (tom.reed@acmecorp.com) naming
267
+ # EVERY flagged employee (partial = fraction of names found).
268
+ # No "any sent email" fallback (v2: strict).
269
+ SANDRA = 'sandra.voss@acmecorp.com'
270
+ TOM = 'tom.reed@acmecorp.com'
271
+ gmail_summary_ok = 0.0
272
+ gmail_handoff_frac = 0.0
273
+ try:
274
+ emails = gmail_c.get('emails', []) or []
275
+ sent = [e for e in emails if norm(e.get('folder')) == 'sent']
276
+
277
+ def _recips(e):
278
+ out = []
279
+ for fld in ('to', 'cc', 'bcc'):
280
+ v = e.get(fld)
281
+ if isinstance(v, list):
282
+ for r in v:
283
+ if isinstance(r, dict):
284
+ out.append(norm(r.get('email')))
285
+ else:
286
+ out.append(norm(r))
287
+ elif v:
288
+ out.append(norm(v))
289
+ return out
290
+
291
+ def _blob(e):
292
+ return (norm(e.get('subject')) + ' ' + norm(e.get('snippet')) + ' '
293
+ + norm(e.get('body')))
294
+
295
+ for e in sent:
296
+ if SANDRA in _recips(e):
297
+ if _counts_match(_blob(e), n_approve, n_chase):
298
+ gmail_summary_ok = 1.0
299
+ break
300
+ if flagged_names:
301
+ best = 0
302
+ for e in sent:
303
+ if TOM in _recips(e):
304
+ best = max(best, _names_present(_blob(e), flagged_names))
305
+ gmail_handoff_frac = frac(best, len(flagged_names))
306
+ else:
307
+ gmail_handoff_frac = 1.0
308
+ except Exception as e:
309
+ print(f'DEBUG_W06 gmail component error: {e!r}')
310
+ gmail_ok = 0.5 * gmail_summary_ok + 0.5 * gmail_handoff_frac
311
+
312
+ # ---- Combine ----
313
+ s_wd = 0.45 * wd_score
314
+ s_asana = 0.25 * asana_score
315
+ s_teams = 0.15 * teams_ok
316
+ s_gmail = 0.15 * gmail_ok
317
+ score = s_wd + s_asana + s_teams + s_gmail
318
+
319
+ print(
320
+ 'DEBUG_W06 '
321
+ f'n_pending={n} n_approve={n_approve} n_chase={n_chase} '
322
+ f'wd_correct={wd_correct}/{n_approve} wd_wrong={wd_wrong} wd_score={round(wd_score, 4)} '
323
+ f'asana_points={round(asana_points, 4)}/{n_chase} asana_score={round(asana_score, 4)} '
324
+ f'teams_summary={teams_summary_ok} teams_list={round(teams_list_frac, 3)} teams_ok={round(teams_ok, 3)} '
325
+ f'gmail_summary={gmail_summary_ok} gmail_handoff={round(gmail_handoff_frac, 3)} gmail_ok={round(gmail_ok, 3)} '
326
+ f'w_wd={round(s_wd, 4)} w_asana={round(s_asana, 4)} '
327
+ f'w_teams={round(s_teams, 4)} w_gmail={round(s_gmail, 4)} '
328
+ f'total={round(score, 4)}'
329
+ )
330
+
331
+ return clamp01(score)
332
+
333
+
334
+ try:
335
+ score = float(reward(go))
336
+ except Exception as exc:
337
+ print(f'ERROR: reward() raised {exc!r}')
338
+ score = 0.0
339
+
340
+ score = clamp01(score)
341
+ print(f'\nREWARD: {round(score, 4)}')
hr_policy_ack_002/_cua_gym_vm_bridge.sh ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # CUA-Gym VM-side network fix (direct-IP mock access).
3
+ #
4
+ # Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by
5
+ # their real IDC address (http://28.7.184.198:81xx) instead of the old
6
+ # localhost:9000-9097 socat bridge, so the VM only needs two fixes:
7
+ #
8
+ # 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's
9
+ # cluster DNS, which is unreachable from QEMU SLIRP NAT
10
+ # ("Temporary failure in name resolution").
11
+ # 2. The mock host excluded from the woa http proxy — otherwise the VM's
12
+ # Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403
13
+ # from the proxy when hitting 28.7.184.198:81xx. (The old socat path never
14
+ # hit this because localhost is bypassed by default.)
15
+ #
16
+ # Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic
17
+ # OSWorld setup pipeline.
18
+ #
19
+ # Argv:
20
+ # $1 optional sudo password (default "password"; SetupController
21
+ # substitutes {CLIENT_PASSWORD} when uploaded as a cache file).
22
+ # $2 unused (kept for backward compat — was socat first port 9000).
23
+ # $3 unused (kept for backward compat — was socat last port 9097).
24
+ # $4 optional mock host IP (default 28.7.184.198).
25
+
26
+ set +e
27
+
28
+ PASS="${1:-password}"
29
+ MOCK_HOST="${4:-28.7.184.198}"
30
+ # Derive the /16 IDC subnet so future port/host tweaks on the same segment
31
+ # stay bypassed too (28.7.184.198 -> 28.7.0.0/16).
32
+ MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')"
33
+
34
+ run_root() {
35
+ echo "$PASS" | sudo -S -p "" bash -c "$1"
36
+ }
37
+
38
+ # Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2.
39
+ GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')"
40
+ GW="${GW:-10.0.2.2}"
41
+
42
+ # ─── CUA-Gym network fix (Taiji-specific) ─────────────────────────────
43
+ fix_vm_network() {
44
+ # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP
45
+ # DNS forwarder. Nothing hardcoded except the mock host above.
46
+ local GW_NET="${GW%.*}"
47
+ local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3
48
+ local OWN_CIDR
49
+ OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \
50
+ | awk '{print $4; exit}')"
51
+ local OWN_IP="${OWN_CIDR%/*}"
52
+ local OWN_NET=""
53
+ [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24"
54
+
55
+ # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps
56
+ # systemd-resolved/NetworkManager from clobbering it.
57
+ if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf
58
+ chattr +i /etc/resolv.conf 2>/dev/null || true"; then
59
+ echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})"
60
+ else
61
+ echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf"
62
+ fi
63
+
64
+ # 2) Build the proxy bypass list from detected values + the direct-IP
65
+ # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx
66
+ # reachable from inside the VM — without it the woa proxy 403s it.
67
+ local ignore_list="['localhost', '127.0.0.0/8', '${GW}'"
68
+ [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'"
69
+ [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'"
70
+ [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'"
71
+ [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'"
72
+ [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'"
73
+ ignore_list="${ignore_list}]"
74
+
75
+ # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these.
76
+ if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then
77
+ echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}"
78
+ else
79
+ echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)"
80
+ fi
81
+
82
+ # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl).
83
+ local NP="localhost,127.0.0.1,${GW}"
84
+ [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}"
85
+ [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}"
86
+ [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24"
87
+ [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}"
88
+ [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}"
89
+
90
+ for var in no_proxy NO_PROXY; do
91
+ if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then
92
+ echo "export ${var}=${NP}" >> /home/user/.bashrc
93
+ fi
94
+ done
95
+ run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \
96
+ && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \
97
+ || echo 'no_proxy=\"${NP}\"' >> /etc/environment
98
+ grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \
99
+ && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \
100
+ || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1
101
+ echo "[cua_gym_vm_bridge] no_proxy=${NP}"
102
+ }
103
+
104
+ fix_vm_network
105
+
106
+ echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed"
hr_policy_ack_002/initial_setup.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: Carlos Mendez completed signing the Remote Work Policy in DocuSign
3
+ Task ID: hr_policy_ack_002
4
+ Domain: mock_websites
5
+ Mocks: docusign_mock, workday_mock, slack_mock
6
+ """
7
+
8
+ import json
9
+ import os
10
+ import shlex
11
+ import subprocess
12
+ import time
13
+ import uuid
14
+
15
+ import requests
16
+
17
+ # --- Config ---
18
+ TASK_ID = "hr_policy_ack_002"
19
+
20
+ # Generate and persist sid for golden_patch.py and reward.py
21
+ sid = str(uuid.uuid4())
22
+ with open('/tmp/task_web_sid', 'w') as f:
23
+ f.write(sid)
24
+
25
+ print(f"Session ID generated: {sid}")
26
+
27
+ # Mock URLs (using public URLs from skill documentation)
28
+ MOCKS = {
29
+ "docusign_mock": "http://28.7.184.198:8130",
30
+ "workday_mock": "http://28.7.184.198:8192",
31
+ "slack_mock": "http://28.7.184.198:8178"
32
+ }
33
+
34
+ # --- Build DocuSign initial state ---
35
+ # Carlos Mendez's Remote Work Policy envelope is in "Completed" state (signed)
36
+ docusign_state = {
37
+ "user": {
38
+ "id": "user_hr_admin",
39
+ "name": "HR Administrator",
40
+ "email": "hr.admin@company.com",
41
+ "title": "HR Administrator",
42
+ "company": "TechCorp Inc",
43
+ "settings": {"defaultReminderDays": 3, "defaultExpirationDays": 30, "timezone": "America/New_York"}
44
+ },
45
+ "envelopes": [
46
+ {
47
+ "id": "env_remote_work_policy_carlos",
48
+ "subject": "Remote Work Policy 2026",
49
+ "message": "Please review and sign the updated Remote Work Policy for 2026.",
50
+ "status": "completed", # Already signed/completed as per task context
51
+ "createdAt": "2026-06-20T10:00:00Z",
52
+ "sentAt": "2026-06-20T10:15:00Z",
53
+ "completedAt": "2026-06-24T09:30:00Z", # Recently completed
54
+ "voidedAt": None,
55
+ "declinedAt": None,
56
+ "lastActivityAt": "2026-06-24T09:30:00Z",
57
+ "expiresAt": None,
58
+ "senderId": "user_hr_admin",
59
+ "folderId": None,
60
+ "templateId": None,
61
+ "reminderEnabled": False,
62
+ "reminderDays": 3,
63
+ "reminderFrequency": 2,
64
+ "documents": [
65
+ {
66
+ "id": "doc_remote_policy",
67
+ "name": "Remote Work Policy 2026.pdf",
68
+ "pageCount": 8,
69
+ "order": 1,
70
+ "fileUrl": "https://picsum.photos/seed/remote_policy/800/1100",
71
+ "fileType": "pdf"
72
+ }
73
+ ],
74
+ "recipients": [
75
+ {
76
+ "id": "rec_carlos_mendez",
77
+ "name": "Carlos Mendez",
78
+ "email": "carlos.mendez@company.com",
79
+ "role": "signer",
80
+ "routingOrder": 1,
81
+ "status": "signed", # Signed status
82
+ "signedAt": "2026-06-24T09:30:00Z",
83
+ "viewedAt": "2026-06-24T09:25:00Z",
84
+ "deliveredAt": "2026-06-20T10:20:00Z",
85
+ "declinedAt": None,
86
+ "declineReason": None
87
+ }
88
+ ],
89
+ "fields": [],
90
+ "history": [
91
+ {
92
+ "id": "evt_created",
93
+ "timestamp": "2026-06-20T10:00:00Z",
94
+ "action": "created",
95
+ "actorName": "HR Administrator",
96
+ "actorEmail": "hr.admin@company.com",
97
+ "details": "Envelope created"
98
+ },
99
+ {
100
+ "id": "evt_sent",
101
+ "timestamp": "2026-06-20T10:15:00Z",
102
+ "action": "sent",
103
+ "actorName": "HR Administrator",
104
+ "actorEmail": "hr.admin@company.com",
105
+ "details": "Envelope sent to Carlos Mendez"
106
+ },
107
+ {
108
+ "id": "evt_completed",
109
+ "timestamp": "2026-06-24T09:30:00Z",
110
+ "action": "completed",
111
+ "actorName": "Carlos Mendez",
112
+ "actorEmail": "carlos.mendez@company.com",
113
+ "details": "Envelope completed and signed"
114
+ }
115
+ ]
116
+ }
117
+ ],
118
+ "templates": [],
119
+ "folders": [],
120
+ "contacts": [],
121
+ "auditLog": []
122
+ }
123
+
124
+ # --- Build Workday initial state ---
125
+ # Carlos's onboarding checklist has "Policy Acknowledgement" item marked "Not Started"
126
+ workday_state = {
127
+ "currentUser": {
128
+ "id": "emp_hr_admin",
129
+ "name": "HR Administrator",
130
+ "email": "hr.admin@company.com",
131
+ "phone": "+1 (555) 123-4567",
132
+ "role": "Manager",
133
+ "department": "Human Resources",
134
+ "departmentId": "dept_hr",
135
+ "avatar": "https://ui-avatars.com/api/?name=HR+Admin&background=0875E1&color=fff&size=128",
136
+ "managerId": None,
137
+ "title": "HR Administrator",
138
+ "location": "New York, NY",
139
+ "joinDate": "2022-01-15",
140
+ "employeeType": "Full-Time",
141
+ "skills": ["HR Management", "Employee Relations", "Compliance"],
142
+ "birthday": "1985-03-20",
143
+ "workAnniversary": "2022-01-15"
144
+ },
145
+ "employees": [
146
+ {
147
+ "id": "emp_hr_admin",
148
+ "name": "HR Administrator",
149
+ "email": "hr.admin@company.com",
150
+ "role": "Manager",
151
+ "department": "Human Resources",
152
+ "departmentId": "dept_hr",
153
+ "avatar": "https://ui-avatars.com/api/?name=HR+Admin&background=0875E1&color=fff&size=128",
154
+ "managerId": None,
155
+ "title": "HR Administrator",
156
+ "location": "New York, NY",
157
+ "joinDate": "2022-01-15",
158
+ "employeeType": "Full-Time",
159
+ "birthday": "1985-03-20",
160
+ "workAnniversary": "2022-01-15"
161
+ },
162
+ {
163
+ "id": "emp_carlos_mendez",
164
+ "name": "Carlos Mendez",
165
+ "email": "carlos.mendez@company.com",
166
+ "role": "Employee",
167
+ "department": "Engineering",
168
+ "departmentId": "dept_eng",
169
+ "avatar": "https://ui-avatars.com/api/?name=Carlos+Mendez&background=7C3AED&color=fff&size=128",
170
+ "managerId": "emp_eng_manager",
171
+ "title": "Software Engineer",
172
+ "location": "San Francisco, CA",
173
+ "joinDate": "2026-06-01",
174
+ "employeeType": "Full-Time",
175
+ "birthday": "1992-08-15",
176
+ "workAnniversary": "2026-06-01"
177
+ },
178
+ {
179
+ "id": "emp_eng_manager",
180
+ "name": "Sarah Chen",
181
+ "email": "sarah.chen@company.com",
182
+ "role": "Manager",
183
+ "department": "Engineering",
184
+ "departmentId": "dept_eng",
185
+ "avatar": "https://ui-avatars.com/api/?name=Sarah+Chen&background=DC2626&color=fff&size=128",
186
+ "managerId": None,
187
+ "title": "Engineering Manager",
188
+ "location": "San Francisco, CA",
189
+ "joinDate": "2020-03-10",
190
+ "employeeType": "Full-Time",
191
+ "birthday": "1988-11-30",
192
+ "workAnniversary": "2020-03-10"
193
+ }
194
+ ],
195
+ "departments": [
196
+ {"id": "dept_hr", "name": "Human Resources", "headcount": 1, "managerId": "emp_hr_admin"},
197
+ {"id": "dept_eng", "name": "Engineering", "headcount": 2, "managerId": "emp_eng_manager"}
198
+ ],
199
+ "timeEntries": [],
200
+ "timeOffRequests": [],
201
+ "timeOffBalance": {"vacation": 120, "sick": 40, "personal": 16},
202
+ "payroll": [],
203
+ "benefits": {
204
+ "employeeId": "emp_hr_admin",
205
+ "enrollmentStatus": "Complete",
206
+ "plans": [],
207
+ "dependents": []
208
+ },
209
+ "reviews": [],
210
+ "goals": [],
211
+ "tasks": [
212
+ {
213
+ "taskId": "task_policy_ack",
214
+ "employeeId": "emp_hr_admin",
215
+ "type": "To-Do",
216
+ "subType": "Onboarding",
217
+ "description": "Policy Acknowledgement for Carlos Mendez",
218
+ "status": "Pending", # Not Started - will be marked Completed during the task
219
+ "dueDate": "2026-06-30",
220
+ "createdDate": "2026-06-20",
221
+ "relatedId": "emp_carlos_mendez",
222
+ "initiator": "System",
223
+ "businessProcess": "Employee Onboarding",
224
+ "priority": "Normal",
225
+ "comments": []
226
+ }
227
+ ],
228
+ "announcements": [],
229
+ "notifications": [],
230
+ "clockStatus": {"isClockedIn": False, "startTime": None}
231
+ }
232
+
233
+ # --- Build Slack initial state ---
234
+ # #hr-ops channel has existing message announcing policy was sent to Carlos for signing
235
+ slack_state = {
236
+ "currentUser": {
237
+ "userId": "user_hr_admin",
238
+ "fullName": "HR Administrator",
239
+ "displayName": "HR Admin",
240
+ "email": "hr.admin@company.com",
241
+ "avatar": "https://ui-avatars.com/api/?name=HR+Admin&background=0875E1&color=fff&size=128",
242
+ "status": "online",
243
+ "statusMessage": "",
244
+ "statusEmoji": "",
245
+ "timeZone": "America/New_York"
246
+ },
247
+ "workspace": {"workspaceId": "ws_techcorp", "workspaceName": "TechCorp", "icon": ""},
248
+ "users": [
249
+ {
250
+ "userId": "user_hr_admin",
251
+ "fullName": "HR Administrator",
252
+ "displayName": "HR Admin",
253
+ "email": "hr.admin@company.com",
254
+ "avatar": "https://ui-avatars.com/api/?name=HR+Admin&background=0875E1&color=fff&size=128",
255
+ "status": "online"
256
+ },
257
+ {
258
+ "userId": "user_sarah_chen",
259
+ "fullName": "Sarah Chen",
260
+ "displayName": "Sarah",
261
+ "email": "sarah.chen@company.com",
262
+ "avatar": "https://ui-avatars.com/api/?name=Sarah+Chen&background=DC2626&color=fff&size=128",
263
+ "status": "online"
264
+ }
265
+ ],
266
+ "channels": [
267
+ {
268
+ "channelId": "hr-ops",
269
+ "name": "hr-ops",
270
+ "description": "HR Operations and Announcements",
271
+ "topic": "Employee onboarding and policy management",
272
+ "isPrivate": False,
273
+ "isStarred": False,
274
+ "members": ["user_hr_admin", "user_sarah_chen"],
275
+ "createdBy": "user_hr_admin",
276
+ "createdAt": "2024-01-01T10:00:00Z",
277
+ "pinnedMessages": [],
278
+ "unreadCount": 0
279
+ }
280
+ ],
281
+ "messages": {
282
+ "hr-ops": [
283
+ {
284
+ "messageId": "msg_policy_sent",
285
+ "senderId": "user_hr_admin",
286
+ "content": "Sent Remote Work Policy 2026 to Carlos Mendez (carlos.mendez@company.com) for signature via DocuSign.",
287
+ "timestamp": "2026-06-20T10:30:00Z",
288
+ "threadId": None, # This will be the parent message for the threaded reply
289
+ "reactions": [],
290
+ "attachments": [],
291
+ "isEdited": False
292
+ }
293
+ ]
294
+ },
295
+ "threads": {},
296
+ "dms": [],
297
+ "bookmarkedMessages": [],
298
+ "callHistory": [],
299
+ "settings": {
300
+ "theme": "light",
301
+ "notifications": "all",
302
+ "displayDensity": "comfortable",
303
+ "showAvatars": True,
304
+ "use24Hour": False
305
+ },
306
+ "invitations": [],
307
+ "notifications": []
308
+ }
309
+
310
+ # --- Inject state into all mocks ---
311
+ print("Injecting initial state into all mocks...")
312
+
313
+ for mock_name, base_url in MOCKS.items():
314
+ print(f" Injecting into {mock_name} at {base_url}")
315
+
316
+ if mock_name == "docusign_mock":
317
+ state = docusign_state
318
+ elif mock_name == "workday_mock":
319
+ state = workday_state
320
+ elif mock_name == "slack_mock":
321
+ state = slack_state
322
+
323
+ try:
324
+ resp = requests.post(
325
+ f'{base_url}/post?sid={sid}',
326
+ json={'action': 'set', 'state': state},
327
+ timeout=30
328
+ )
329
+ assert resp.status_code == 200, f'State injection failed for {mock_name}: {resp.text}'
330
+ print(f" ✓ State injected successfully")
331
+
332
+ # Verify state was set
333
+ go = requests.get(f'{base_url}/go?sid={sid}', timeout=10).json()
334
+ assert go['initial_state'] is not None, f'initial_state is None after injection for {mock_name}'
335
+ print(f" ✓ State verified")
336
+
337
+ except Exception as e:
338
+ print(f" ✗ Error injecting state into {mock_name}: {e}")
339
+ raise
340
+
341
+ print("All states injected successfully!")
342
+
343
+ # --- Launch browser with primary mock (DocuSign as per task_config) ---
344
+ def launch_gui(command, delay_sec=1.0):
345
+ env = os.environ.copy()
346
+ env['DISPLAY'] = ':0'
347
+ subprocess.Popen(
348
+ shlex.split(command),
349
+ stdout=subprocess.DEVNULL,
350
+ stderr=subprocess.DEVNULL,
351
+ env=env,
352
+ )
353
+ time.sleep(delay_sec)
354
+
355
+ # Launch browser with DocuSign (primary mock)
356
+ primary_url = f"{MOCKS['docusign_mock']}/?sid={sid}"
357
+ launch_gui(f'google-chrome "{primary_url}"', delay_sec=2.0)
358
+ print(f'GUI_READY: launched browser at {primary_url}')
359
+
360
+ # Also launch Workday and Slack in separate tabs after a delay
361
+ time.sleep(1.0)
362
+ workday_url = f"{MOCKS['workday_mock']}/?sid={sid}"
363
+ launch_gui(f'google-chrome "{workday_url}"', delay_sec=0.5)
364
+
365
+ time.sleep(0.5)
366
+ slack_url = f"{MOCKS['slack_mock']}/?sid={sid}"
367
+ launch_gui(f'google-chrome "{slack_url}"', delay_sec=0.5)
368
+
369
+ print("All browsers launched successfully!")
hr_policy_ack_002/reward.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Reward Script: Carlos Mendez Remote Work Policy Acknowledgement
3
+ Task ID: hr_policy_ack_002
4
+ Domain: mock_websites
5
+ Mocks: docusign_mock, workday_mock, slack_mock
6
+ Scoring:
7
+ - DocuSign envelope completed (0.3 pts)
8
+ - Workday checklist item completed (0.4 pts)
9
+ - Slack threaded reply confirming completion (0.3 pts)
10
+ """
11
+
12
+ import json
13
+ import sys
14
+ import requests
15
+
16
+ # Mock URLs based on the schema documentation
17
+ MOCKS = {
18
+ 'docusign_mock': 'http://28.7.184.198:8130',
19
+ 'workday_mock': 'http://28.7.184.198:8192',
20
+ 'slack_mock': 'http://28.7.184.198:8178'
21
+ }
22
+
23
+ def verify_task():
24
+ total_score = 0.0
25
+
26
+ # Read session ID
27
+ try:
28
+ with open('/tmp/task_web_sid') as f:
29
+ sid = f.read().strip()
30
+ if not sid:
31
+ raise ValueError('sid is empty')
32
+ except Exception as e:
33
+ print(f'CRITICAL: Cannot read sid from /tmp/task_web_sid: {e}')
34
+ print('REWARD: 0.0')
35
+ return 0.0
36
+
37
+ # Fetch state from all mocks
38
+ states = {}
39
+ for name, url in MOCKS.items():
40
+ try:
41
+ resp = requests.get(f'{url}/go?sid={sid}', timeout=15)
42
+ resp.raise_for_status()
43
+ data = resp.json()
44
+ states[name] = data
45
+ except Exception as e:
46
+ print(f'ERROR: Cannot fetch state from {name}: {e}')
47
+ print('REWARD: 0.0')
48
+ return 0.0
49
+
50
+ # Component 1: DocuSign envelope status is 'completed' (0.3 points)
51
+ try:
52
+ docusign_current = states['docusign_mock'].get('current_state', {})
53
+ envelopes = docusign_current.get('envelopes', [])
54
+
55
+ # Find Carlos Mendez's Remote Work Policy envelope
56
+ carlos_envelope_found = False
57
+ for envelope in envelopes:
58
+ # Check if this is the Remote Work Policy for Carlos Mendez
59
+ recipients = envelope.get('recipients', [])
60
+ carlos_recipient = None
61
+ for recipient in recipients:
62
+ if recipient.get('email') == 'carlos.mendez@company.com':
63
+ carlos_recipient = recipient
64
+ break
65
+
66
+ if carlos_recipient and envelope.get('subject', '').lower().find('remote work policy') != -1:
67
+ carlos_envelope_found = True
68
+ if envelope.get('status') == 'completed' and carlos_recipient.get('status') == 'signed':
69
+ print(f'PASS: DocuSign envelope for Carlos Mendez is completed (0.3 pts)')
70
+ total_score += 0.3
71
+ else:
72
+ print(f'FAIL: DocuSign envelope status: {envelope.get("status")}, recipient status: {carlos_recipient.get("status")}')
73
+ break
74
+
75
+ if not carlos_envelope_found:
76
+ print('FAIL: Could not find Carlos Mendez Remote Work Policy envelope in DocuSign')
77
+ except Exception as e:
78
+ print(f'ERROR: Component 1 — {e}')
79
+
80
+ # Component 2: Workday onboarding checklist item marked 'Completed' (0.4 points)
81
+ try:
82
+ workday_current = states['workday_mock'].get('current_state', {})
83
+ tasks = workday_current.get('tasks', [])
84
+
85
+ # Find the Policy Acknowledgement task for Carlos Mendez
86
+ policy_task_found = False
87
+ for task in tasks:
88
+ if (task.get('description', '').lower().find('policy acknowledgement') != -1 and
89
+ task.get('subType', '').lower().find('onboarding') != -1):
90
+ policy_task_found = True
91
+ if task.get('status') == 'Completed':
92
+ print(f'PASS: Workday Policy Acknowledgement task is completed (0.4 pts)')
93
+ total_score += 0.4
94
+ else:
95
+ print(f'FAIL: Workday task status: {task.get("status")}')
96
+ break
97
+
98
+ if not policy_task_found:
99
+ print('FAIL: Could not find Policy Acknowledgement onboarding task in Workday')
100
+ except Exception as e:
101
+ print(f'ERROR: Component 2 — {e}')
102
+
103
+ # Component 3: Slack threaded reply confirms policy signed and recorded (0.3 points)
104
+ try:
105
+ slack_current = states['slack_mock'].get('current_state', {})
106
+ messages = slack_current.get('messages', {})
107
+ hr_ops_messages = messages.get('hr-ops', [])
108
+
109
+ # Check for threaded replies that mention policy completion
110
+ policy_reply_found = False
111
+ for message in hr_ops_messages:
112
+ thread_id = message.get('threadId')
113
+ if thread_id:
114
+ # This is a threaded reply, check content
115
+ content = message.get('content', '').lower()
116
+ if ('signed' in content and 'recorded' in content and
117
+ ('policy' in content or 'remote work' in content)):
118
+ policy_reply_found = True
119
+ print(f'PASS: Slack threaded reply confirms policy signed and recorded (0.3 pts)')
120
+ total_score += 0.3
121
+ break
122
+
123
+ if not policy_reply_found:
124
+ print('FAIL: No threaded reply confirming policy signed and recorded found in Slack #hr-ops')
125
+ except Exception as e:
126
+ print(f'ERROR: Component 3 — {e}')
127
+
128
+ final_score = min(total_score, 1.0)
129
+ print(f'\nScore: {total_score}/1.0')
130
+ print(f'REWARD: {final_score}')
131
+ return final_score
132
+
133
+ if __name__ == '__main__':
134
+ verify_task()
hr_policy_ack_002/reward_label.json ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "reward_file": "/apdcephfs_sh2/share_300000800/user/jackwkwang/long-horizon-tasks/mini_osworld_xiangwu/cache/hr_policy_ack_002/reward.py",
3
+ "api_url": "http://28.7.184.184:8000/v1/chat/completions",
4
+ "model": "Kimi-K2.6",
5
+ "max_code_chars": 100000,
6
+ "created_at": "2026-07-14 10:27:05",
7
+ "label": {
8
+ "task_id": "hr_policy_ack_002",
9
+ "domain": "mock_websites",
10
+ "summary": "验证 Carlos Mendez 是否完成远程工作政策确认,包括 DocuSign 信封签署、Workday 入职任务完成以及 Slack 线程回复确认",
11
+ "is_placeholder": false,
12
+ "data_sources": [
13
+ "docusign_mock",
14
+ "workday_mock",
15
+ "slack_mock",
16
+ "/tmp/task_web_sid"
17
+ ],
18
+ "scoring_components": [
19
+ {
20
+ "name": "Component 1",
21
+ "weight": 0.3,
22
+ "description": "检查 DocuSign 中 Carlos Mendez 的 Remote Work Policy 信封是否已完成签署",
23
+ "check_logic": "遍历 docusign_mock.current_state.envelopes,查找收件人 email 为 'carlos.mendez@company.com' 且 subject 包含 'remote work policy' 的信封;判断 envelope['status'] == 'completed' 且 recipient['status'] == 'signed'",
24
+ "pass_condition": "找到 Carlos Mendez 的 Remote Work Policy 信封,且信封状态为 'completed'、收件人状态为 'signed'"
25
+ },
26
+ {
27
+ "name": "Component 2",
28
+ "weight": 0.4,
29
+ "description": "检查 Workday 中 Policy Acknowledgement 入职任务是否标记为已完成",
30
+ "check_logic": "遍历 workday_mock.current_state.tasks,查找 description 包含 'policy acknowledgement' 且 subType 包含 'onboarding' 的任务;判断 task['status'] == 'Completed'",
31
+ "pass_condition": "找到 Policy Acknowledgement 入职任务,且其 status 为 'Completed'"
32
+ },
33
+ {
34
+ "name": "Component 3",
35
+ "weight": 0.3,
36
+ "description": "检查 Slack #hr-ops 频道中是否有线程回复确认政策已签署并记录",
37
+ "check_logic": "遍历 slack_mock.current_state.messages['hr-ops'],查找存在 threadId 的消息(即线程回复);判断 content.lower() 同时包含 'signed' 和 'recorded',且包含 'policy' 或 'remote work'",
38
+ "pass_condition": "在 #hr-ops 中找到线程回复,且内容同时包含 'signed'、'recorded' 以及 'policy' 或 'remote work'"
39
+ }
40
+ ],
41
+ "total_max_score": 1.0,
42
+ "score_aggregation": "各组件分数相加,最终通过 min(total_score, 1.0) 钳制到上限 1.0",
43
+ "failure_modes": [
44
+ "读取 /tmp/task_web_sid 失败或内容为空:打印 CRITICAL 并提前返回 0.0",
45
+ "从 docusign_mock、workday_mock 或 slack_mock 任意一个获取状态失败:打印 ERROR 并提前返回 0.0",
46
+ "未找到 Carlos Mendez 的 Remote Work Policy 信封:Component 1 不得分",
47
+ "DocuSign 信封状态非 'completed' 或收件人状态非 'signed':Component 1 不得分",
48
+ "未找到 Policy Acknowledgement 入职任务:Component 2 不得分",
49
+ "Workday 任务状态非 'Completed':Component 2 不得分",
50
+ "在 Slack #hr-ops 中未找到符合条件的线程回复:Component 3 不得分",
51
+ "各组件检查过程中发生异常:捕获后打印 ERROR,该组件不得分,但不影响其他组件评分"
52
+ ],
53
+ "scoring_logic_explanation": "脚本首先读取 /tmp/task_web_sid 获取会话 ID,失败则直接返回 0.0。随后依次向 docusign_mock、workday_mock、slack_mock 发送请求获取当前状态,任一请求失败也直接返回 0.0。接着分三个组件评分:Component 1 在 DocuSign 中查找 Carlos Mendez 的 Remote Work Policy 信封,验证信封和收件人状态均为完成/已签署,通过加 0.3 分;Component 2 在 Workday 中查找 Policy Acknowledgement 入职任务,验证状态为 Completed,通过加 0.4 分;Component 3 在 Slack #hr-ops 中查找包含特定关键词的线程回复,通过加 0.3 分。各组件异常仅导致该组件失分,不会中断后续评分。最终总分通过 min(total_score, 1.0) 计算并输出。",
54
+ "confidence": 1.0
55
+ },
56
+ "raw_response": "用户要求我分析一个 reward.py 评分脚本,并输出一个严格的 JSON 对象,不包含任何额外文本、Markdown 代码块标记或思考过程。\n\n让我仔细阅读源码:\n\n1. **Docstring 信息提取**:\n - Task ID: hr_policy_ack_002\n - Domain: mock_websites\n - Mocks: docusign_mock, workday_mock, slack_mock\n - Scoring:\n - DocuSign envelope completed (0.3 pts)\n - Workday checklist item completed (0.4 pts)\n - Slack threaded reply confirming completion (0.3 pts)\n\n2. **脚本行为分析**:\n - 不是占位脚本,它实际检查了三个 mock 服务的状态。\n - 读取 `/tmp/task_web_sid` 获取 session ID,失败则返回 0.0。\n - 从三个 mock 服务获取状态,失败则返回 0.0。\n - Component 1: 检查 docusign_mock 中 Carlos Mendez (carlos.mendez@company.com) 的 Remote Work Policy envelope 状态为 'completed' 且 recipient 状态为 'signed',通��得 0.3。\n - Component 2: 检查 workday_mock 中 description 包含 'policy acknowledgement' 且 subType 包含 'onboarding' 的任务状态为 'Completed',通过得 0.4。\n - Component 3: 检查 slack_mock 的 hr-ops 频道中,是否有 threaded reply(有 threadId)且内容包含 'signed' 和 'recorded' 以及 'policy' 或 'remote work',通过得 0.3。\n - 最终分数 = min(total_score, 1.0),即相加后钳制到 1.0。\n\n3. **失败模式**:\n - 读取 sid 失败(返回 0.0)\n - 从任意 mock 拉取状态失败(返回 0.0)\n - 各组件检查中的异常(打印 ERROR,该组件不得分,但不提前退出)\n - 未找到对应 envelope/task/message(该组件不得分)\n\n4. **JSON 字段填充**:\n - task_id: \"hr_policy_ack_002\"\n - domain: \"mock_websites\"\n - summary: \"验证 Carlos Mendez 是否完成远程工作政策确认,包括 DocuSign 签署、Workday 任务完成以及 Slack 确认回复\"\n - is_placeholder: false\n - data_sources: [\"docusign_mock\", \"workday_mock\", \"slack_mock\", \"/tmp/task_web_sid\"]\n - scoring_components: 三个组件,按代码中的分值和逻辑描述\n - total_max_score: 1.0\n - score_aggregation: \"各组件分数相加,最终通过 min(total_score, 1.0) 钳制到上限 1.0\"\n - failure_modes: [\"读取 /tmp/task_web_sid 失败或为空\", \"从 docusign_mock、workday_mock 或 slack_mock 获取状态失败\", \"未找到 Carlos Mendez 的 Remote Work Policy 信封\", \"DocuSign 信封或收件人状态非 completed/signed\", \"未找到 Policy Acknowledgement 入职任务\", \"Workday 任务状态非 Completed\", \"在 Slack #hr-ops 中未找到符合条件的线程回复\", \"各组件检查中的异常导致该组件不得分\"]\n - scoring_logic_explanation: 详细按执行顺序说明\n - confidence: 1.0\n\n让我确保所有字符串 value 使用中文,但 task_id、domain、字段名、代码标识符保留原样。\n\n检查 scoring_components 的 pass_condition:\n- Component 1: envelope.get('status') == 'completed' 且 carlos_recipient.get('status') == 'signed'\n- Component 2: task.get('status') == 'Completed'\n- Component 3: message 有 threadId,且 content.lower() 同时包含 'signed' 和 'recorded',且包含 'policy' 或 'remote work'\n\nweight 字段:\n- 代码中显式给出 0.3, 0.4, 0.3\n\nscore_aggregation:\n- 相加后钳制到上限\n\nfailure_modes 需要列出会导致提前退出或返回 0.0 或扣分的情况:\n- 读取 sid 失败:提前退出,返回 0.0\n- mock 状态拉取失败:提前退出,返回 0.0\n- 各组件未找到或状态不匹配:该组件不得分(不提前退出)\n- 组件异常:该组件不得分(不提前退出)\n\n现在构建 JSON。 </think> {\"task_id\":\"hr_policy_ack_002\",\"domain\":\"mock_websites\",\"summary\":\"验证 Carlos Mendez 是否完成远程工作政策确认,包括 DocuSign 信封签署、Workday 入职任务完成以及 Slack 线程回复确认\",\"is_placeholder\":false,\"data_sources\":[\"docusign_mock\",\"workday_mock\",\"slack_mock\",\"/tmp/task_web_sid\"],\"scoring_components\":[{\"name\":\"Component 1\",\"weight\":0.3,\"description\":\"检查 DocuSign 中 Carlos Mendez 的 Remote Work Policy 信封是否已完成签署\",\"check_logic\":\"遍历 docusign_mock.current_state.envelopes,查找收件人 email 为 'carlos.mendez@company.com' 且 subject 包含 'remote work policy' 的信封;判断 envelope['status'] == 'completed' 且 recipient['status'] == 'signed'\",\"pass_condition\":\"找到 Carlos Mendez 的 Remote Work Policy 信封,且信封状态为 'completed'、收件人状态为 'signed'\"},{\"name\":\"Component 2\",\"weight\":0.4,\"description\":\"检查 Workday 中 Policy Acknowledgement 入职任务是否标记为已完成\",\"check_logic\":\"遍历 workday_mock.current_state.tasks,查找 description 包含 'policy acknowledgement' 且 subType 包含 'onboarding' 的任务;判断 task['status'] == 'Completed'\",\"pass_condition\":\"找到 Policy Acknowledgement 入职任务,且其 status 为 'Completed'\"},{\"name\":\"Component 3\",\"weight\":0.3,\"description\":\"检查 Slack #hr-ops 频道中是否有线程回复确认政策已签署并记录\",\"check_logic\":\"遍历 slack_mock.current_state.messages['hr-ops'],查找存在 threadId 的消息(即线程回复);判断 content.lower() 同时包含 'signed' 和 'recorded',且包含 'policy' 或 'remote work'\",\"pass_condition\":\"在 #hr-ops 中找到线程回复,且内容同时包含 'signed'、'recorded' 以及 'policy' 或 'remote work'\"}],\"total_max_score\":1.0,\"score_aggregation\":\"各组件分数相加,最终通过 min(total_score, 1.0) 钳制到上限 1.0\",\"failure_modes\":[\"读取 /tmp/task_web_sid 失败或内容为空:打印 CRITICAL 并提前返回 0.0\",\"从 docusign_mock、workday_mock 或 slack_mock 任意一个获取状态失败:打印 ERROR 并提前返回 0.0\",\"未找到 Carlos Mendez 的 Remote Work Policy 信封:Component 1 不得分\",\"DocuSign 信封状态非 'completed' 或收件人状态非 'signed':Component 1 不得分\",\"未找到 Policy Acknowledgement 入职任务:Component 2 不得分\",\"Workday 任务状态非 'Completed':Component 2 不得分\",\"在 Slack #hr-ops 中未找到符合条件的线程回复:Component 3 不得分\",\"各组件检查过程中发生异常:捕获后打印 ERROR,该组件不得分,但不影响其他组件评分\"],\"scoring_logic_explanation\":\"脚本首先读取 /tmp/task_web_sid 获取会话 ID,失败则直接返回 0.0。随后依次向 docusign_mock、workday_mock、slack_mock 发送请求获取当前状态,任一请求失败也直接返回 0.0。接着分三个组件评分:Component 1 在 DocuSign 中查找 Carlos Mendez 的 Remote Work Policy 信封,验证信封和收件人状态均为完成/已签署,通过加 0.3 分;Component 2 在 Workday 中查找 Policy Acknowledgement 入职任务,验证状态为 Completed,通过加 0.4 分;Component 3 在 Slack #hr-ops 中查找包含特定关键词的线程回复,通过加 0.3 分。各组件异常仅导致该组件失分,不会中断后续评分。最终总分通过 min(total_score, 1.0) 计算并输出。\",\"confidence\":1.0}"
57
+ }
itops_access_log_003/_cua_gym_vm_bridge.sh ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # CUA-Gym VM-side network fix (direct-IP mock access).
3
+ #
4
+ # Runs INSIDE the QEMU guest. The CUA-Gym mock services are now reached by
5
+ # their real IDC address (http://28.7.184.198:81xx) instead of the old
6
+ # localhost:9000-9097 socat bridge, so the VM only needs two fixes:
7
+ #
8
+ # 1. Working DNS — the qcow2-baked /etc/resolv.conf points at the Pod's
9
+ # cluster DNS, which is unreachable from QEMU SLIRP NAT
10
+ # ("Temporary failure in name resolution").
11
+ # 2. The mock host excluded from the woa http proxy — otherwise the VM's
12
+ # Chrome (gsettings proxy) and initial_setup.py's `requests` get a 403
13
+ # from the proxy when hitting 28.7.184.198:81xx. (The old socat path never
14
+ # hit this because localhost is bypassed by default.)
15
+ #
16
+ # Idempotent. Scoped to the CUA-Gym bridge step; does not touch the generic
17
+ # OSWorld setup pipeline.
18
+ #
19
+ # Argv:
20
+ # $1 optional sudo password (default "password"; SetupController
21
+ # substitutes {CLIENT_PASSWORD} when uploaded as a cache file).
22
+ # $2 unused (kept for backward compat — was socat first port 9000).
23
+ # $3 unused (kept for backward compat — was socat last port 9097).
24
+ # $4 optional mock host IP (default 28.7.184.198).
25
+
26
+ set +e
27
+
28
+ PASS="${1:-password}"
29
+ MOCK_HOST="${4:-28.7.184.198}"
30
+ # Derive the /16 IDC subnet so future port/host tweaks on the same segment
31
+ # stay bypassed too (28.7.184.198 -> 28.7.0.0/16).
32
+ MOCK_NET="$(echo "${MOCK_HOST}" | awk -F. 'NF==4{print $1"."$2".0.0/16"}')"
33
+
34
+ run_root() {
35
+ echo "$PASS" | sudo -S -p "" bash -c "$1"
36
+ }
37
+
38
+ # Detect SLIRP gateway from VM's routing table; fall back to 10.0.2.2.
39
+ GW="$(ip route 2>/dev/null | awk '/default/ {print $3; exit}')"
40
+ GW="${GW:-10.0.2.2}"
41
+
42
+ # ─── CUA-Gym network fix (Taiji-specific) ─────────────────────────────
43
+ fix_vm_network() {
44
+ # 0) Discover VM network state at runtime — gateway, own IP/CIDR, SLIRP
45
+ # DNS forwarder. Nothing hardcoded except the mock host above.
46
+ local GW_NET="${GW%.*}"
47
+ local SLIRP_DNS="${GW_NET}.3" # QEMU SLIRP DNS proxy is always .3
48
+ local OWN_CIDR
49
+ OWN_CIDR="$(ip -4 -o addr show scope global 2>/dev/null \
50
+ | awk '{print $4; exit}')"
51
+ local OWN_IP="${OWN_CIDR%/*}"
52
+ local OWN_NET=""
53
+ [ -n "${OWN_IP}" ] && OWN_NET="${OWN_IP%.*}.0/24"
54
+
55
+ # 1) DNS — point at SLIRP DNS proxy + public fallbacks. chattr +i keeps
56
+ # systemd-resolved/NetworkManager from clobbering it.
57
+ if run_root "printf 'nameserver ${SLIRP_DNS}\\nnameserver 114.114.114.114\\nnameserver 8.8.8.8\\n' > /etc/resolv.conf
58
+ chattr +i /etc/resolv.conf 2>/dev/null || true"; then
59
+ echo "[cua_gym_vm_bridge] DNS set: ${SLIRP_DNS}, 114.114.114.114, 8.8.8.8 (gw=${GW})"
60
+ else
61
+ echo "[cua_gym_vm_bridge] WARN: failed to write /etc/resolv.conf"
62
+ fi
63
+
64
+ # 2) Build the proxy bypass list from detected values + the direct-IP
65
+ # mock host (and its /16 subnet). THIS is what makes 28.7.184.198:81xx
66
+ # reachable from inside the VM — without it the woa proxy 403s it.
67
+ local ignore_list="['localhost', '127.0.0.0/8', '${GW}'"
68
+ [ -n "${OWN_IP}" ] && ignore_list="${ignore_list}, '${OWN_IP}'"
69
+ [ -n "${OWN_NET}" ] && ignore_list="${ignore_list}, '${OWN_NET}'"
70
+ [ -n "${GW_NET}" ] && ignore_list="${ignore_list}, '${GW_NET}.0/24'"
71
+ [ -n "${MOCK_HOST}" ] && ignore_list="${ignore_list}, '${MOCK_HOST}'"
72
+ [ -n "${MOCK_NET}" ] && ignore_list="${ignore_list}, '${MOCK_NET}'"
73
+ ignore_list="${ignore_list}]"
74
+
75
+ # 3) GNOME proxy ignore-hosts — Chrome bypasses the woa proxy for these.
76
+ if gsettings set org.gnome.system.proxy ignore-hosts "${ignore_list}" 2>/tmp/gsettings_err; then
77
+ echo "[cua_gym_vm_bridge] gsettings ignore-hosts = ${ignore_list}"
78
+ else
79
+ echo "[cua_gym_vm_bridge] WARN: gsettings ignore-hosts failed: $(cat /tmp/gsettings_err 2>/dev/null)"
80
+ fi
81
+
82
+ # 4) Shell env — comma-separated form for no_proxy/NO_PROXY (requests/curl).
83
+ local NP="localhost,127.0.0.1,${GW}"
84
+ [ -n "${OWN_IP}" ] && NP="${NP},${OWN_IP}"
85
+ [ -n "${OWN_NET}" ] && NP="${NP},${OWN_NET}"
86
+ [ -n "${GW_NET}" ] && NP="${NP},${GW_NET}.0/24"
87
+ [ -n "${MOCK_HOST}" ] && NP="${NP},${MOCK_HOST}"
88
+ [ -n "${MOCK_NET}" ] && NP="${NP},${MOCK_NET}"
89
+
90
+ for var in no_proxy NO_PROXY; do
91
+ if ! grep -q "export ${var}=${NP}" /home/user/.bashrc 2>/dev/null; then
92
+ echo "export ${var}=${NP}" >> /home/user/.bashrc
93
+ fi
94
+ done
95
+ run_root "grep -q '^no_proxy=' /etc/environment 2>/dev/null \
96
+ && sed -i 's|^no_proxy=.*|no_proxy=\"${NP}\"|' /etc/environment \
97
+ || echo 'no_proxy=\"${NP}\"' >> /etc/environment
98
+ grep -q '^NO_PROXY=' /etc/environment 2>/dev/null \
99
+ && sed -i 's|^NO_PROXY=.*|NO_PROXY=\"${NP}\"|' /etc/environment \
100
+ || echo 'NO_PROXY=\"${NP}\"' >> /etc/environment" >/dev/null 2>&1
101
+ echo "[cua_gym_vm_bridge] no_proxy=${NP}"
102
+ }
103
+
104
+ fix_vm_network
105
+
106
+ echo "[cua_gym_vm_bridge] direct-IP mode: ${MOCK_HOST} (+${MOCK_NET}) bypassed from woa proxy; no socat forwarding needed"
itops_access_log_003/initial_setup.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Initial Setup: Access-Request-To-Log pipeline (Slack -> Google Sheets)
3
+ Task ID: itops_access_log_003
4
+ Domain: mock_websites
5
+ Mocks: slack_mock (http://28.7.184.198:8178), google_sheets_mock (http://28.7.184.198:8145)
6
+ """
7
+
8
+ import json
9
+ import os
10
+ import shlex
11
+ import subprocess
12
+ import time
13
+ import uuid
14
+
15
+ import requests
16
+
17
+ # --- Config (task-config URLs) ---
18
+ SLACK_URL = 'http://28.7.184.198:8178'
19
+ SHEETS_URL = 'http://28.7.184.198:8145'
20
+
21
+ # Use a deterministic sid derived from task_id so initial_env, golden_env, and
22
+ # reward.py all agree on the same session. The mock apps are remote HTTP servers
23
+ # (state keyed by sid), so a stable sid lets golden_patch.py (running on a separate
24
+ # VM with its own filesystem) locate the shared state without a local file dependency.
25
+ # We still persist it to /tmp/task_web_sid for reward.py's convenience.
26
+ sid = 'prof34_access_log_001'
27
+ with open('/tmp/task_web_sid', 'w') as f:
28
+ f.write(sid)
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # Slack initial state
32
+ # ---------------------------------------------------------------------------
33
+ slack_state = {
34
+ "currentUser": {
35
+ "userId": "user_1",
36
+ "fullName": "Jordan Blake",
37
+ "displayName": "Jordan",
38
+ "email": "jordan.blake@northwind.io",
39
+ "avatar": "https://picsum.photos/200/200?random=1",
40
+ "title": "Access Request Manager",
41
+ "status": "active",
42
+ "statusMessage": "On the IT help desk",
43
+ "statusEmoji": "",
44
+ "timeZone": "America/New_York"
45
+ },
46
+ "workspace": {"workspaceId": "ws_nw", "workspaceName": "Northwind Corp", "icon": ""},
47
+ "users": [
48
+ {"userId": "user_1", "fullName": "Jordan Blake", "displayName": "Jordan", "email": "jordan.blake@northwind.io", "avatar": "https://picsum.photos/200/200?random=1", "title": "Access Request Manager", "status": "active", "statusMessage": "On the IT help desk", "statusEmoji": "", "timeZone": "America/New_York"},
49
+ {"userId": "user_2", "fullName": "Maya Chen", "displayName": "Maya", "email": "maya.chen@northwind.io", "avatar": "https://picsum.photos/200/200?random=2", "title": "Sales Operations Analyst", "status": "active", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"},
50
+ {"userId": "user_3", "fullName": "Daniel Okafor", "displayName": "Daniel", "email": "d.okafor@northwind.io", "avatar": "https://picsum.photos/200/200?random=3", "title": "Engineering Manager", "status": "active", "statusMessage": "", "statusEmoji": "", "timeZone": "America/New_York"}
51
+ ],
52
+ "channels": [
53
+ {"channelId": "it-access-requests", "name": "it-access-requests", "description": "Channel for IT access requests", "topic": "Request app access here", "isPrivate": False, "isStarred": False, "members": ["user_1", "user_2", "user_3"], "createdBy": "user_1", "createdAt": "2026-06-01T09:00:00Z", "pinnedMessages": [], "unreadCount": 1}
54
+ ],
55
+ "messages": {
56
+ "it-access-requests": [
57
+ {"messageId": "msg-req-001", "senderId": "user_2", "content": "@it-helpdesk Access request: App=Salesforce, Requester=Maya Chen (maya.chen@northwind.io), Manager Approval=Approved by Daniel Okafor (d.okafor@northwind.io). Need read-only CRM access for Q3 sales support.", "timestamp": "2026-07-01T08:15:00Z", "threadId": None, "reactions": [], "attachments": [], "isEdited": False}
58
+ ]
59
+ },
60
+ "threads": {},
61
+ "dms": [],
62
+ "bookmarkedMessages": [],
63
+ "callHistory": [],
64
+ "settings": {"theme": "light", "notifications": "all", "displayDensity": "comfortable", "showAvatars": True, "use24Hour": False},
65
+ "invitations": [],
66
+ "notifications": []
67
+ }
68
+
69
+ # ---------------------------------------------------------------------------
70
+ # Google Sheets initial state
71
+ # ---------------------------------------------------------------------------
72
+ def header_cell(value):
73
+ return {"value": value, "formula": value, "style": {"bold": True, "bg": "#E8EAED"}}
74
+
75
+ def data_cell(value):
76
+ return {"value": value, "formula": value}
77
+
78
+ access_log_data = {
79
+ "A1": header_cell("Request ID"),
80
+ "B1": header_cell("Date"),
81
+ "C1": header_cell("Requester"),
82
+ "D1": header_cell("Email"),
83
+ "E1": header_cell("App"),
84
+ "F1": header_cell("Access Level"),
85
+ "G1": header_cell("Manager"),
86
+ "H1": header_cell("Approval"),
87
+ "I1": header_cell("Status"),
88
+ "A2": data_cell("ACC-2026-0628-001"),
89
+ "B2": data_cell("2026-06-28"),
90
+ "C2": data_cell("Liam Wong"),
91
+ "D2": data_cell("liam.wong@northwind.io"),
92
+ "E2": data_cell("Asana"),
93
+ "F2": data_cell("Read-only"),
94
+ "G2": data_cell("Sara Kim"),
95
+ "H2": data_cell("Approved"),
96
+ "I2": data_cell("Provisioned"),
97
+ "A3": data_cell("ACC-2026-0629-002"),
98
+ "B3": data_cell("2026-06-29"),
99
+ "C3": data_cell("Nina Patel"),
100
+ "D3": data_cell("nina.patel@northwind.io"),
101
+ "E3": data_cell("Google Sheets"),
102
+ "F3": data_cell("Edit"),
103
+ "G3": data_cell("Daniel Okafor"),
104
+ "H3": data_cell("Approved"),
105
+ "I3": data_cell("Provisioned"),
106
+ "A4": data_cell("ACC-2026-0630-003"),
107
+ "B4": data_cell("2026-06-30"),
108
+ "C4": data_cell("Omar Said"),
109
+ "D4": data_cell("omar.said@northwind.io"),
110
+ "E4": data_cell("GitHub"),
111
+ "F4": data_cell("Read-only"),
112
+ "G4": data_cell("Sara Kim"),
113
+ "H4": data_cell("Pending"),
114
+ "I4": data_cell("Awaiting"),
115
+ }
116
+
117
+ sheets_state = {
118
+ "id": "wb_acc_01",
119
+ "title": "Access Audit Log",
120
+ "activeSheetId": "sh_acc_01",
121
+ "selectedCell": "A1",
122
+ "selectionRange": None,
123
+ "clipboard": None,
124
+ "isDragging": False,
125
+ "undoStack": [],
126
+ "redoStack": [],
127
+ "namedRanges": [],
128
+ "conditionalFormats": [],
129
+ "charts": [],
130
+ "showGridlines": True,
131
+ "showFormulas": False,
132
+ "zoom": 100,
133
+ "sheets": [
134
+ {
135
+ "id": "sh_acc_01",
136
+ "name": "Access Log",
137
+ "rowCount": 100,
138
+ "colCount": 26,
139
+ "frozenRows": 1,
140
+ "frozenCols": 0,
141
+ "tabColor": None,
142
+ "isHidden": False,
143
+ "columnWidths": {},
144
+ "rowHeights": {},
145
+ "filterRange": None,
146
+ "filterCriteria": {},
147
+ "sortColumn": None,
148
+ "sortDirection": None,
149
+ "data": access_log_data
150
+ }
151
+ ]
152
+ }
153
+
154
+ # ---------------------------------------------------------------------------
155
+ # Inject state into BOTH mocks with the same sid
156
+ # ---------------------------------------------------------------------------
157
+ resp = requests.post(f'{SLACK_URL}/post?sid={sid}', json={'action': 'set', 'state': slack_state}, timeout=30)
158
+ assert resp.status_code == 200, f'Slack state injection failed: {resp.text}'
159
+ print('Slack initial state injected')
160
+
161
+ resp = requests.post(f'{SHEETS_URL}/post?sid={sid}', json={'action': 'set', 'state': sheets_state}, timeout=30)
162
+ assert resp.status_code == 200, f'Sheets state injection failed: {resp.text}'
163
+ print('Google Sheets initial state injected')
164
+
165
+ # Verify
166
+ go_slack = requests.get(f'{SLACK_URL}/go?sid={sid}', timeout=10).json()
167
+ go_sheets = requests.get(f'{SHEETS_URL}/go?sid={sid}', timeout=10).json()
168
+ assert go_slack['initial_state'] is not None, 'Slack initial_state is None'
169
+ assert go_sheets['initial_state'] is not None, 'Sheets initial_state is None'
170
+ print('Verified: both mocks have initial_state + current_state set')
171
+
172
+ # ---------------------------------------------------------------------------
173
+ # Launch a Chrome window for EACH mock
174
+ # ---------------------------------------------------------------------------
175
+ def launch_gui(command, delay_sec=1.0):
176
+ env = os.environ.copy()
177
+ env['DISPLAY'] = ':0'
178
+ subprocess.Popen(
179
+ shlex.split(command),
180
+ stdout=subprocess.DEVNULL,
181
+ stderr=subprocess.DEVNULL,
182
+ env=env,
183
+ )
184
+ time.sleep(delay_sec)
185
+
186
+ launch_gui(f'google-chrome "{SLACK_URL}/?sid={sid}"', delay_sec=1.0)
187
+ launch_gui(f'google-chrome "{SHEETS_URL}/?sid={sid}"', delay_sec=1.0)
188
+
189
+ # ---------------------------------------------------------------------------
190
+ # Wait until both mocks serve injected state AND fully render
191
+ # ---------------------------------------------------------------------------
192
+ def wait_for_mocks_loaded(mocks, sid, timeout=60.0, render_timeout=15.0):
193
+ import time as _t
194
+ deadline = _t.time() + timeout
195
+ pending = dict(mocks)
196
+ while pending and _t.time() < deadline:
197
+ for name in list(pending):
198
+ try:
199
+ r = requests.get(f'{pending[name]}/go?sid={sid}', timeout=5)
200
+ if r.status_code == 200 and r.json().get('initial_state') is not None:
201
+ del pending[name]
202
+ except Exception:
203
+ pass
204
+ if pending:
205
+ _t.sleep(1.0)
206
+ if pending:
207
+ raise RuntimeError(f'Mocks not ready within {timeout}s: {list(pending)}')
208
+ try:
209
+ from playwright.sync_api import sync_playwright
210
+ except ImportError:
211
+ print('WARN: playwright not installed; skipping render check, settle 5s')
212
+ _t.sleep(5.0)
213
+ return
214
+ with sync_playwright() as p:
215
+ browser = p.chromium.launch(channel='chrome', headless=True,
216
+ args=['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'])
217
+ try:
218
+ for name, url in mocks.items():
219
+ page = browser.new_page()
220
+ try:
221
+ page.goto(f'{url}/?sid={sid}', wait_until='domcontentloaded',
222
+ timeout=int(render_timeout * 1000))
223
+ page.wait_for_function(
224
+ "document.body && document.body.innerText.length > 100",
225
+ timeout=int(render_timeout * 1000))
226
+ html = page.content()
227
+ if len(html) < 2000:
228
+ raise RuntimeError(
229
+ f'[{name}] rendered DOM too small ({len(html)} bytes) — blank/stuck loading')
230
+ print(f'[{name}] rendered OK ({len(html)} bytes)')
231
+ finally:
232
+ page.close()
233
+ finally:
234
+ browser.close()
235
+
236
+ mocks = {'slack_mock': SLACK_URL, 'google_sheets_mock': SHEETS_URL}
237
+ wait_for_mocks_loaded(mocks, sid)
238
+ print(f'GUI_READY: all {len(mocks)} mocks launched and verified (sid={sid})')